modeling_zamba2.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/zamba2/modular_zamba2.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_zamba2.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
  8. #
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. import math
  22. from collections.abc import Callable
  23. from itertools import cycle
  24. from typing import Optional
  25. import torch
  26. from torch import nn
  27. from ... import initialization as init
  28. from ...activations import ACT2FN
  29. from ...cache_utils import Cache, DynamicCache
  30. from ...generation import GenerationMixin
  31. from ...integrations import use_kernel_func_from_hub
  32. from ...integrations.hub_kernels import lazy_load_kernel
  33. from ...masking_utils import create_causal_mask
  34. from ...modeling_layers import GradientCheckpointingLayer
  35. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
  36. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  37. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  38. from ...processing_utils import Unpack
  39. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
  40. from ...utils.generic import maybe_autocast, merge_with_config_defaults
  41. from ...utils.import_utils import resolve_internal_import
  42. from ...utils.output_capturing import capture_outputs
  43. from .configuration_zamba2 import Zamba2Config
  44. logger = logging.get_logger(__name__)
  45. class Zamba2RMSNormGated(torch.nn.Module):
  46. def __init__(self, hidden_size, group_size, eps=1e-6):
  47. super().__init__()
  48. self.weight = nn.Parameter(torch.ones(hidden_size))
  49. self.variance_epsilon = eps
  50. self.group_size = group_size
  51. def forward(self, hidden_states, gate=None):
  52. input_dtype = hidden_states.dtype
  53. hidden_states = hidden_states.to(torch.float32)
  54. if gate is not None:
  55. hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
  56. *prefix_dims, last_dim = hidden_states.shape
  57. group_count = last_dim // self.group_size
  58. hidden_states_group = hidden_states.view(*prefix_dims, group_count, self.group_size)
  59. variance = hidden_states_group.pow(2).mean(-1, keepdim=True)
  60. hidden_states_group = hidden_states_group * torch.rsqrt(variance + self.variance_epsilon)
  61. hidden_states = hidden_states_group.view(*prefix_dims, group_count * self.group_size)
  62. return self.weight * hidden_states.to(input_dtype)
  63. class Zamba2RMSNorm(nn.Module):
  64. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  65. """
  66. Zamba2RMSNorm is equivalent to T5LayerNorm
  67. """
  68. super().__init__()
  69. self.weight = nn.Parameter(torch.ones(hidden_size))
  70. self.variance_epsilon = eps
  71. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  72. input_dtype = hidden_states.dtype
  73. hidden_states = hidden_states.to(torch.float32)
  74. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  75. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  76. return self.weight * hidden_states.to(input_dtype)
  77. def extra_repr(self):
  78. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  79. class Zamba2RotaryEmbedding(nn.Module):
  80. inv_freq: torch.Tensor # fix linting for `register_buffer`
  81. def __init__(self, config: Zamba2Config, device=None):
  82. super().__init__()
  83. self.max_seq_len_cached = config.max_position_embeddings
  84. self.original_max_seq_len = config.max_position_embeddings
  85. self.config = config
  86. self.rope_type = self.config.rope_parameters["rope_type"]
  87. rope_init_fn: Callable = self.compute_default_rope_parameters
  88. if self.rope_type != "default":
  89. rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  90. inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
  91. self.register_buffer("inv_freq", inv_freq, persistent=False)
  92. self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
  93. @staticmethod
  94. def compute_default_rope_parameters(
  95. config: Zamba2Config | None = None,
  96. device: Optional["torch.device"] = None,
  97. seq_len: int | None = None,
  98. ) -> tuple["torch.Tensor", float]:
  99. """
  100. Computes the inverse frequencies according to the original RoPE implementation
  101. Args:
  102. config ([`~transformers.PreTrainedConfig`]):
  103. The model configuration.
  104. device (`torch.device`):
  105. The device to use for initialization of the inverse frequencies.
  106. seq_len (`int`, *optional*):
  107. The current sequence length. Unused for this type of RoPE.
  108. Returns:
  109. Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  110. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  111. """
  112. base = config.rope_parameters["rope_theta"]
  113. dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  114. attention_factor = 1.0 # Unused in this type of RoPE
  115. # Compute the inverse frequencies
  116. inv_freq = 1.0 / (
  117. base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
  118. )
  119. return inv_freq, attention_factor
  120. @torch.no_grad()
  121. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  122. def forward(self, x, position_ids):
  123. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  124. position_ids_expanded = position_ids[:, None, :].float()
  125. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  126. with maybe_autocast(device_type=device_type, enabled=False): # Force float32
  127. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  128. emb = torch.cat((freqs, freqs), dim=-1)
  129. cos = emb.cos() * self.attention_scaling
  130. sin = emb.sin() * self.attention_scaling
  131. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  132. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  133. """
  134. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  135. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  136. """
  137. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  138. if n_rep == 1:
  139. return hidden_states
  140. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  141. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  142. def eager_attention_forward(
  143. module: nn.Module,
  144. query: torch.Tensor,
  145. key: torch.Tensor,
  146. value: torch.Tensor,
  147. attention_mask: torch.Tensor | None,
  148. scaling: float,
  149. dropout: float = 0.0,
  150. **kwargs,
  151. ):
  152. key_states = repeat_kv(key, module.num_key_value_groups)
  153. value_states = repeat_kv(value, module.num_key_value_groups)
  154. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  155. if attention_mask is not None:
  156. attn_weights = attn_weights + attention_mask
  157. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  158. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  159. attn_output = torch.matmul(attn_weights, value_states)
  160. attn_output = attn_output.transpose(1, 2).contiguous()
  161. return attn_output, attn_weights
  162. def rotate_half(x):
  163. """Rotates half the hidden dims of the input."""
  164. x1 = x[..., : x.shape[-1] // 2]
  165. x2 = x[..., x.shape[-1] // 2 :]
  166. return torch.cat((-x2, x1), dim=-1)
  167. @use_kernel_func_from_hub("rotary_pos_emb")
  168. def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
  169. """Applies Rotary Position Embedding to the query and key tensors.
  170. Args:
  171. q (`torch.Tensor`): The query tensor.
  172. k (`torch.Tensor`): The key tensor.
  173. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  174. sin (`torch.Tensor`): The sine part of the rotary embedding.
  175. unsqueeze_dim (`int`, *optional*, defaults to 1):
  176. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  177. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  178. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  179. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  180. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  181. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  182. Returns:
  183. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  184. """
  185. cos = cos.unsqueeze(unsqueeze_dim)
  186. sin = sin.unsqueeze(unsqueeze_dim)
  187. q_embed = (q * cos) + (rotate_half(q) * sin)
  188. k_embed = (k * cos) + (rotate_half(k) * sin)
  189. return q_embed, k_embed
  190. class Zamba2Attention(nn.Module):
  191. """
  192. Multi-headed attention from 'Attention Is All You Need' paper.
  193. Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
  194. The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
  195. The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
  196. (see fig. 2 in https://huggingface.co/papers/2405.16712).
  197. Additionally, replaced
  198. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
  199. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
  200. Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
  201. layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
  202. expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
  203. """
  204. def __init__(
  205. self,
  206. config: Zamba2Config,
  207. layer_idx: int | None = None,
  208. num_fwd_mem_blocks: int | None = None,
  209. block_id: int | None = None,
  210. ):
  211. super().__init__()
  212. self.config = config
  213. self.layer_idx = layer_idx
  214. self.attention_hidden_size = config.attention_hidden_size
  215. self.head_dim = config.attention_head_dim
  216. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  217. self.max_position_embeddings = config.max_position_embeddings
  218. self.scaling = (self.head_dim / 2) ** -0.5
  219. self.is_causal = True
  220. self.attention_dropout = config.attention_dropout
  221. self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
  222. self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
  223. self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
  224. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  225. self.num_fwd_mem_blocks = num_fwd_mem_blocks
  226. self.layer_block_map = config.hybrid_layer_ids
  227. self.block_id = block_id
  228. if config.use_shared_attention_adapter:
  229. self.linear_q_adapter_list = nn.ModuleList([])
  230. self.linear_k_adapter_list = nn.ModuleList([])
  231. self.linear_v_adapter_list = nn.ModuleList([])
  232. for i in range(self.num_fwd_mem_blocks):
  233. if i % config.num_mem_blocks == block_id:
  234. linear_q_adapter = nn.Sequential(
  235. nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
  236. nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
  237. )
  238. linear_k_adapter = nn.Sequential(
  239. nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
  240. nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
  241. )
  242. linear_v_adapter = nn.Sequential(
  243. nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
  244. nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
  245. )
  246. else:
  247. linear_q_adapter = nn.Identity()
  248. linear_k_adapter = nn.Identity()
  249. linear_v_adapter = nn.Identity()
  250. self.linear_q_adapter_list.append(linear_q_adapter)
  251. self.linear_k_adapter_list.append(linear_k_adapter)
  252. self.linear_v_adapter_list.append(linear_v_adapter)
  253. self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)}
  254. def forward(
  255. self,
  256. hidden_states: torch.Tensor,
  257. layer_idx: int,
  258. attention_mask: torch.Tensor | None = None,
  259. past_key_values: Cache | None = None,
  260. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  261. **kwargs: Unpack[TransformersKwargs],
  262. ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
  263. input_shape = hidden_states.shape[:-1]
  264. hidden_shape = (*input_shape, -1, self.head_dim)
  265. query_states = self.q_proj(hidden_states)
  266. key_states = self.k_proj(hidden_states)
  267. value_states = self.v_proj(hidden_states)
  268. if self.config.use_shared_attention_adapter:
  269. adapter_layer_idx = self.layer_dic[layer_idx]
  270. query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states)
  271. key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states)
  272. value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states)
  273. query_states = query_states.view(hidden_shape).transpose(1, 2)
  274. key_states = key_states.view(hidden_shape).transpose(1, 2)
  275. value_states = value_states.view(hidden_shape).transpose(1, 2)
  276. if self.config.use_mem_rope:
  277. cos, sin = position_embeddings
  278. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  279. if past_key_values is not None:
  280. key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
  281. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  282. self.config._attn_implementation, eager_attention_forward
  283. )
  284. attn_output, attn_weights = attention_interface(
  285. self,
  286. query_states,
  287. key_states,
  288. value_states,
  289. attention_mask,
  290. dropout=0.0 if not self.training else self.attention_dropout,
  291. scaling=self.scaling,
  292. **kwargs,
  293. )
  294. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  295. attn_output = self.o_proj(attn_output)
  296. return attn_output, attn_weights
  297. # Helper methods for segment sum computation
  298. def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
  299. """
  300. Padding x tensor with `pad_size` on the seq_len dim (dim=1)
  301. Assumes that we only have tensors of either size 4 or 3
  302. """
  303. pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
  304. return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
  305. def reshape_into_chunks(input_tensor, pad_size, chunk_size):
  306. """
  307. Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
  308. simultaneously splitting it into chunk sequences.
  309. Assumes that we only have tensors of either size 4 or 3
  310. """
  311. # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
  312. input_tensor = pad_tensor_by_size(input_tensor, pad_size)
  313. if len(input_tensor.shape) == 3:
  314. # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
  315. return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
  316. else:
  317. # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
  318. return input_tensor.reshape(
  319. input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
  320. )
  321. def segment_sum(input_tensor):
  322. """
  323. More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
  324. """
  325. chunk_size = input_tensor.size(-1)
  326. # 1. expand input tensor to have an additional dimension and repeat along that dimension
  327. # [..., chunk_size] -> [..., chunk_size, chunk_size]
  328. input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
  329. # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
  330. mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
  331. input_tensor = input_tensor.masked_fill(~mask, 0)
  332. # 3. compute actual cumsum
  333. tensor_segsum = torch.cumsum(input_tensor, dim=-2)
  334. # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
  335. mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
  336. tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
  337. return tensor_segsum
  338. class Zamba2MambaMixer(nn.Module):
  339. """
  340. Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
  341. A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
  342. ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
  343. and is why Mamba is called **selective** state spaces)
  344. """
  345. def __init__(self, config: Zamba2Config, layer_idx: int | None = None):
  346. super().__init__()
  347. self.config = config
  348. self.hidden_size = config.hidden_size
  349. self.ssm_state_size = config.mamba_d_state
  350. self.conv_kernel_size = config.mamba_d_conv
  351. self.intermediate_size = int(config.mamba_expand * self.hidden_size)
  352. self.layer_idx = layer_idx
  353. self.use_conv_bias = config.use_conv_bias
  354. self.activation = "silu"
  355. self.act = nn.SiLU()
  356. self.use_mem_eff_path = config.use_mem_eff_path
  357. self.n_groups = config.mamba_ngroups
  358. self.head_dim = config.mamba_headdim
  359. self.num_heads = self.config.n_mamba_heads
  360. self.chunk_size = config.chunk_size
  361. self.time_step_limit = config.time_step_limit
  362. self.time_step_min = config.time_step_min
  363. self.time_step_max = config.time_step_max
  364. self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
  365. self.conv1d = nn.Conv1d(
  366. in_channels=self.conv_dim,
  367. out_channels=self.conv_dim,
  368. bias=True,
  369. kernel_size=config.mamba_d_conv,
  370. groups=self.conv_dim,
  371. padding=config.mamba_d_conv - 1,
  372. )
  373. # projection of the input hidden states
  374. projection_size = self.intermediate_size + self.conv_dim + self.num_heads
  375. self.in_proj = nn.Linear(
  376. self.hidden_size,
  377. projection_size,
  378. bias=config.add_bias_linear,
  379. )
  380. # selective projection used to make dt, B and C input dependent
  381. # time step projection (discretization)
  382. # instantiate once and copy inv_dt in init_weights of PretrainedModel
  383. self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
  384. # S4D real initialization. These are not discretized!
  385. # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
  386. A = torch.arange(1, self.num_heads + 1)
  387. self.A_log = nn.Parameter(torch.log(A))
  388. self.norm = Zamba2RMSNormGated(
  389. self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=1e-5
  390. )
  391. self.D = nn.Parameter(torch.ones(self.num_heads))
  392. self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
  393. global causal_conv1d_update, causal_conv1d_fn
  394. causal_conv1d = lazy_load_kernel("causal-conv1d")
  395. causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
  396. causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
  397. global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
  398. mamba_ssm = lazy_load_kernel("mamba-ssm")
  399. selective_state_update = resolve_internal_import(
  400. mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
  401. )
  402. mamba_chunk_scan_combined = resolve_internal_import(
  403. mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
  404. )
  405. mamba_split_conv1d_scan_combined = resolve_internal_import(
  406. mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
  407. )
  408. global is_fast_path_available
  409. is_fast_path_available = all(
  410. (
  411. selective_state_update,
  412. mamba_chunk_scan_combined,
  413. mamba_split_conv1d_scan_combined,
  414. causal_conv1d_fn,
  415. causal_conv1d_update,
  416. )
  417. )
  418. if not is_fast_path_available:
  419. logger.warning_once(
  420. "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
  421. " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
  422. " https://github.com/Dao-AILab/causal-conv1d"
  423. )
  424. def cuda_kernels_forward(
  425. self,
  426. hidden_states: torch.Tensor,
  427. cache_params: Cache | None = None,
  428. attention_mask: torch.Tensor | None = None,
  429. ):
  430. # set up dimensions for reshapes later
  431. batch_size, seq_len, _ = hidden_states.shape
  432. groups_time_state_size = self.n_groups * self.ssm_state_size
  433. d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
  434. # getting projected states from cache if it exists
  435. if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
  436. in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
  437. d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
  438. split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
  439. _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
  440. hidden_states_B_C = causal_conv1d_update(
  441. hidden_states_B_C,
  442. cache_params.layers[self.layer_idx].conv_states,
  443. self.conv1d.weight.squeeze(1),
  444. self.conv1d.bias,
  445. self.activation,
  446. )
  447. hidden_states, B, C = torch.split(
  448. hidden_states_B_C,
  449. [self.intermediate_size, groups_time_state_size, groups_time_state_size],
  450. dim=-1,
  451. )
  452. A = -torch.exp(self.A_log.float()) # (nheads,)
  453. A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
  454. dt = dt[:, :, None].expand(-1, -1, self.head_dim)
  455. dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
  456. D = self.D[:, None, ...].expand(-1, self.head_dim)
  457. B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
  458. C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
  459. hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
  460. hidden_states = selective_state_update(
  461. cache_params.layers[self.layer_idx].recurrent_states,
  462. hidden_states_reshaped,
  463. dt,
  464. A,
  465. B,
  466. C,
  467. D,
  468. z=None,
  469. dt_bias=dt_bias,
  470. dt_softplus=True,
  471. )
  472. hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
  473. hidden_states = self.norm(hidden_states, gate)
  474. out = self.out_proj(hidden_states)[:, None, ...]
  475. # if no cache is found, calling the kernel
  476. else:
  477. if attention_mask is not None and not torch.all(attention_mask == 1):
  478. # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
  479. dtype = hidden_states.dtype
  480. hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
  481. # 1. Gated MLP's linear projection
  482. projected_states = self.in_proj(hidden_states)
  483. A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
  484. dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
  485. if attention_mask is not None:
  486. input_not_masked = torch.all(attention_mask == 1)
  487. else:
  488. input_not_masked = True
  489. if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
  490. out, ssm_state = mamba_split_conv1d_scan_combined(
  491. projected_states,
  492. self.conv1d.weight.squeeze(1),
  493. self.conv1d.bias,
  494. self.dt_bias,
  495. A,
  496. D=self.D,
  497. chunk_size=self.chunk_size,
  498. seq_idx=None,
  499. activation=self.activation,
  500. rmsnorm_weight=self.norm.weight,
  501. rmsnorm_eps=self.norm.variance_epsilon,
  502. outproj_weight=self.out_proj.weight,
  503. outproj_bias=self.out_proj.bias,
  504. headdim=self.head_dim,
  505. ngroups=self.n_groups,
  506. norm_before_gate=False,
  507. return_final_states=True,
  508. **dt_limit_kwargs,
  509. )
  510. else:
  511. gate, hidden_states_B_C, time_step = torch.split(
  512. projected_states,
  513. [self.intermediate_size, self.conv_dim, self.num_heads],
  514. dim=-1,
  515. )
  516. # 1D Convolution
  517. if cache_params is not None:
  518. hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
  519. conv_state = nn.functional.pad(
  520. hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
  521. )
  522. conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
  523. if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
  524. hidden_states_B_C = self.act(
  525. self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
  526. ) # (B, L, self.d_inner + 2 * ngroups * d_state)
  527. else:
  528. hidden_states_B_C = causal_conv1d_fn(
  529. x=hidden_states_B_C.transpose(1, 2),
  530. weight=self.conv1d.weight.squeeze(1),
  531. bias=self.conv1d.bias,
  532. activation=self.activation,
  533. ).transpose(1, 2)[:, :seq_len]
  534. hidden_states, B, C = torch.split(
  535. hidden_states_B_C,
  536. [self.intermediate_size, groups_time_state_size, groups_time_state_size],
  537. dim=-1,
  538. )
  539. if attention_mask is not None and not torch.all(attention_mask == 1):
  540. # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
  541. dtype = hidden_states.dtype
  542. hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
  543. scan_output, ssm_state = mamba_chunk_scan_combined(
  544. hidden_states.view(batch_size, seq_len, -1, self.head_dim),
  545. time_step,
  546. A,
  547. B.view(batch_size, seq_len, self.n_groups, -1),
  548. C.view(batch_size, seq_len, self.n_groups, -1),
  549. chunk_size=self.chunk_size,
  550. D=self.D,
  551. z=None,
  552. seq_idx=None,
  553. return_final_states=True,
  554. dt_bias=self.dt_bias,
  555. dt_softplus=True,
  556. **dt_limit_kwargs,
  557. )
  558. if ssm_state is not None and cache_params is not None:
  559. cache_params.update_recurrent_state(ssm_state, self.layer_idx)
  560. scan_output = scan_output.view(batch_size, seq_len, -1)
  561. # Multiply "gate" branch and apply extra normalization layer
  562. scan_output = self.norm(scan_output, gate)
  563. out = self.out_proj(scan_output)
  564. return out
  565. # fmt: off
  566. def torch_forward(self, input_states, cache_params: Cache | None=None, attention_mask: torch.Tensor | None = None):
  567. batch_size, seq_len, _ = input_states.shape
  568. dtype = input_states.dtype
  569. # Gated MLP's linear projection
  570. if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
  571. projected_states = self.in_proj(input_states)
  572. else:
  573. if attention_mask is not None:
  574. # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
  575. input_states = (input_states * attention_mask[:, :, None]).to(dtype)
  576. projected_states = self.in_proj(input_states)
  577. d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
  578. _, _, gate, hidden_states, dt = projected_states.split(
  579. [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
  580. )
  581. hidden_states = hidden_states.transpose(1, 2)
  582. use_precomputed_state = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
  583. # Convolution sequence transformation
  584. if use_precomputed_state:
  585. conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
  586. hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
  587. if self.use_conv_bias:
  588. hidden_states += self.conv1d.bias
  589. hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
  590. else:
  591. if cache_params is not None:
  592. conv_state = nn.functional.pad(
  593. hidden_states,
  594. (self.conv_kernel_size - hidden_states.shape[-1], 0)
  595. )
  596. conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
  597. hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len].transpose(1, 2))
  598. if attention_mask is not None:
  599. dtype = hidden_states.dtype
  600. # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
  601. hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
  602. hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
  603. A = -torch.exp(self.A_log.float()) # [num_heads]
  604. if use_precomputed_state:
  605. # Note: there is no need to pad parameter matrices here, as there is just one new token
  606. # for batched generation
  607. dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
  608. dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
  609. # [num_heads] -> [num_heads, head_dim]
  610. dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
  611. dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
  612. dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
  613. A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
  614. # [bsz, num_heads, head_dim, state_size]
  615. dA = torch.exp(dt[..., None] * A)
  616. # Discretize B
  617. # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
  618. # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
  619. B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
  620. B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
  621. B = B.reshape(batch_size, -1, B.shape[-1])
  622. # [bsz, num_heads, head_dim, state_size]
  623. dB = dt[..., None] * B[..., None, :]
  624. # Discretize x into dB
  625. # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
  626. hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
  627. dBx = dB * hidden_states[..., None]
  628. # State calculation
  629. ssm_states = cache_params.layers[self.layer_idx].recurrent_states.clone()
  630. ssm_states = ssm_states * dA + dBx
  631. ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
  632. # Subsequent output
  633. # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
  634. C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
  635. C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
  636. C = C.reshape(batch_size, -1, C.shape[-1])
  637. # [bsz, num_heads, head_dim]
  638. ssm_states = ssm_states.to(C.dtype) # Shape: [b, h, d, n]
  639. # Reshape ssm_states to merge the first two dimensions
  640. ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
  641. C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
  642. y = torch.bmm(ssm_states_reshaped, C_reshaped)
  643. y = y.view(batch_size, self.num_heads, self.head_dim)
  644. # D skip connection
  645. # [num_heads] -> [num_heads, head_dim]
  646. D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
  647. y = (y + hidden_states * D).to(y.dtype)
  648. # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
  649. y = y.reshape(batch_size, -1)[:, None, ...]
  650. else:
  651. # begin ssd naive implementation without einsums
  652. dt = nn.functional.softplus(dt + self.dt_bias)
  653. dt = torch.clamp(dt, self.time_step_min)
  654. hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
  655. B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
  656. C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
  657. B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
  658. C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
  659. pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
  660. D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
  661. # Discretize x and A
  662. hidden_states = hidden_states * dt[..., None]
  663. A = A.to(hidden_states.dtype) * dt
  664. # Rearrange into blocks/chunks
  665. hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
  666. # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
  667. A = A.permute(0, 3, 1, 2)
  668. A_cumsum = torch.cumsum(A, dim=-1)
  669. # 1. Compute the output for each intra-chunk (diagonal blocks)
  670. # This is the analog of a causal mask
  671. L = torch.exp(segment_sum(A))
  672. # First, contraction of C and B to get G (attention-weights like)
  673. G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
  674. G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
  675. # Step 2: Compute M, equivalent to applying attention mask to weights
  676. M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
  677. M = M_intermediate.sum(dim=-1)
  678. # Step 3: Compute Y_diag (apply to values)
  679. Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
  680. # (right term of low-rank factorization of off-diagonal blocks; B terms)
  681. decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
  682. B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
  683. # permute back B * decay states
  684. states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
  685. previous_states = torch.zeros_like(states[:, :1])
  686. states = torch.cat([previous_states, states], dim=1)
  687. decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
  688. states_permuted = states.permute(0, 2, 1, 3, 4)
  689. result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
  690. new_states = result.permute(0, 2, 1, 3, 4)
  691. states, ssm_state = new_states[:, :-1], new_states[:, -1]
  692. # Compute state -> output conversion per chunk
  693. # (left term of low-rank factorization of off-diagonal blocks; C terms)
  694. state_decay_out = torch.exp(A_cumsum)
  695. # compute Yoff
  696. C_times_states = (C[..., None, :] * states[:, :, None, ...])
  697. state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
  698. Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
  699. # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
  700. y = Y_diag + Y_off
  701. # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
  702. y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
  703. y = y + D_residual
  704. # Cutting off padded chunks
  705. if pad_size > 0:
  706. y = y[:, :seq_len, :, :]
  707. y = y.reshape(batch_size, seq_len, -1)
  708. if ssm_state is not None and cache_params is not None:
  709. cache_params.update_recurrent_state(ssm_state, self.layer_idx)
  710. scan_output = self.norm(y, gate)
  711. # end ssd naive
  712. # 4. Final linear projection
  713. contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
  714. return contextualized_states
  715. # fmt: on
  716. def forward(
  717. self,
  718. hidden_states,
  719. cache_params: Cache | None = None,
  720. attention_mask: torch.Tensor | None = None,
  721. **kwargs,
  722. ):
  723. if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
  724. return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
  725. return self.torch_forward(hidden_states, cache_params, attention_mask)
  726. class Zamba2MLP(nn.Module):
  727. def __init__(self, config: Zamba2Config, num_fwd_mem_blocks=None, block_id: int | None = None):
  728. """
  729. This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
  730. is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
  731. """
  732. super().__init__()
  733. self.config = config
  734. self.hidden_size = config.hidden_size
  735. self.intermediate_size = config.intermediate_size
  736. self.num_fwd_mem_blocks = num_fwd_mem_blocks
  737. self.block_id = block_id
  738. self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.add_bias_linear)
  739. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
  740. self.act_fn = ACT2FN[config.hidden_act]
  741. self.gate_up_proj_adapter_list = nn.ModuleList([])
  742. for i in range(self.num_fwd_mem_blocks):
  743. if i % config.num_mem_blocks == block_id:
  744. gate_up_proj_adapter = nn.Sequential(
  745. nn.Linear(self.config.hidden_size, self.config.adapter_rank, bias=False),
  746. nn.Linear(self.config.adapter_rank, 2 * self.intermediate_size, bias=False),
  747. )
  748. else:
  749. gate_up_proj_adapter = nn.Identity()
  750. self.gate_up_proj_adapter_list.append(gate_up_proj_adapter)
  751. layer_block_map = config.hybrid_layer_ids
  752. self.layer_dic = {value: index for index, value in enumerate(layer_block_map)}
  753. def forward(self, hidden_state, layer_idx=None):
  754. gate_up_state = self.gate_up_proj(hidden_state)
  755. layer_idx = self.layer_dic[layer_idx]
  756. gate_up_state = gate_up_state + self.gate_up_proj_adapter_list[layer_idx](hidden_state)
  757. gate_up_state = torch.chunk(gate_up_state, 2, dim=-1)
  758. hidden_state = self.act_fn(gate_up_state[0]) * gate_up_state[1]
  759. output = self.down_proj(hidden_state)
  760. return output
  761. class Zamba2AttentionDecoderLayer(nn.Module):
  762. def __init__(self, config: Zamba2Config, block_id: int | None = None, layer_idx: int | None = None):
  763. super().__init__()
  764. self.block_id = block_id
  765. num_gs = len(config.hybrid_layer_ids)
  766. self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
  767. self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
  768. self.input_layernorm = Zamba2RMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
  769. self.pre_ff_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  770. def forward(
  771. self,
  772. hidden_states: torch.Tensor,
  773. original_hidden_states: torch.Tensor,
  774. layer_idx: int,
  775. attention_mask: torch.Tensor | None = None,
  776. past_key_values: Cache | None = None,
  777. position_embeddings: torch.LongTensor | None = None,
  778. **kwargs: Unpack[TransformersKwargs],
  779. ) -> tuple[torch.FloatTensor]:
  780. """
  781. Args:
  782. hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
  783. original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
  784. This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
  785. concatenated tensor is then used as input of the pre-attention RMSNorm
  786. (see fig. 2 in https://huggingface.co/papers/2405.16712).
  787. attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
  788. `(batch, sequence_length)` where padding elements are indicated by 0.
  789. past_key_values (`Cache`, *optional*): cached past key and value projection states
  790. use_cache (`bool`, *optional*):
  791. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  792. (see `past_key_values`).
  793. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  794. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  795. with `head_dim` being the embedding dimension of each attention head.
  796. """
  797. hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
  798. hidden_states = self.input_layernorm(hidden_states)
  799. hidden_states, _ = self.self_attn(
  800. hidden_states=hidden_states,
  801. layer_idx=layer_idx,
  802. attention_mask=attention_mask,
  803. past_key_values=past_key_values,
  804. position_embeddings=position_embeddings,
  805. **kwargs,
  806. )
  807. hidden_states = self.pre_ff_layernorm(hidden_states)
  808. hidden_states = self.feed_forward(hidden_states, layer_idx)
  809. return hidden_states
  810. class Zamba2MambaDecoderLayer(GradientCheckpointingLayer):
  811. def __init__(self, config: Zamba2Config, layer_idx: int):
  812. super().__init__()
  813. self.mamba = Zamba2MambaMixer(config=config, layer_idx=layer_idx)
  814. self.input_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  815. self.layer_idx = layer_idx
  816. def forward(
  817. self,
  818. hidden_states: torch.Tensor,
  819. original_hidden_states: torch.Tensor | None = None,
  820. layer_idx: int | None = None,
  821. attention_mask: torch.Tensor | None = None,
  822. causal_mask: torch.Tensor | None = None,
  823. past_key_values: Cache | None = None,
  824. use_cache: bool | None = False,
  825. position_ids: torch.LongTensor | None = None,
  826. transformer_hidden_states: torch.Tensor | None = None,
  827. **kwargs: Unpack[TransformersKwargs],
  828. ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
  829. """
  830. Args:
  831. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  832. attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
  833. `(batch, sequence_length)` where padding elements are indicated by 0.
  834. past_key_values (`Cache`, *optional*): cached past key and value projection states
  835. use_cache (`bool`, *optional*):
  836. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  837. (see `past_key_values`).
  838. """
  839. residual = hidden_states
  840. # `transformer_hidden_states` is the output from shared transformer + linear layer (see fig. 2 in https://huggingface.co/papers/2405.16712).
  841. # `transformer_hidden_states` is then added to the input to the mamba layer below (as described in eq. (6) of https://huggingface.co/papers/2405.16712).
  842. hidden_states = (
  843. hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states
  844. )
  845. hidden_states = self.input_layernorm(hidden_states)
  846. hidden_states = self.mamba(
  847. hidden_states=hidden_states,
  848. cache_params=past_key_values,
  849. attention_mask=attention_mask,
  850. **kwargs,
  851. )
  852. # residual connection after mamba
  853. hidden_states = residual + hidden_states
  854. return hidden_states
  855. class Zamba2HybridLayer(GradientCheckpointingLayer):
  856. def __init__(
  857. self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
  858. ):
  859. super().__init__()
  860. self.linear = linear
  861. self.mamba_decoder = mamba
  862. self.shared_transformer = shared_transformer
  863. def forward(
  864. self,
  865. hidden_states: torch.Tensor,
  866. original_hidden_states: torch.Tensor | None = None,
  867. layer_idx: int | None = None,
  868. attention_mask: torch.Tensor | None = None,
  869. causal_mask: torch.Tensor | None = None,
  870. past_key_values: Cache | None = None,
  871. use_cache: bool | None = False,
  872. position_embeddings: torch.LongTensor | None = None,
  873. position_ids: torch.LongTensor | None = None,
  874. **kwargs: Unpack[TransformersKwargs],
  875. ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
  876. """
  877. Args:
  878. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  879. original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
  880. hidden activations to form the input of the shared transformer layer.
  881. layer_idx (`int`): layer number.
  882. attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
  883. `(batch, sequence_length)` where padding elements are indicated by 0.
  884. past_key_values (`Cache`, *optional*): cached past key and value projection states
  885. use_cache (`bool`, *optional*):
  886. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  887. (see `past_key_values`).
  888. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  889. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  890. with `head_dim` being the embedding dimension of each attention head.
  891. """
  892. transformer_hidden_states = self.shared_transformer(
  893. hidden_states,
  894. original_hidden_states=original_hidden_states,
  895. layer_idx=layer_idx,
  896. attention_mask=causal_mask,
  897. past_key_values=past_key_values,
  898. position_embeddings=position_embeddings,
  899. position_ids=position_ids,
  900. **kwargs,
  901. )
  902. transformer_hidden_states = self.linear(transformer_hidden_states)
  903. hidden_states = self.mamba_decoder(
  904. hidden_states,
  905. transformer_hidden_states=transformer_hidden_states,
  906. attention_mask=attention_mask,
  907. past_key_values=past_key_values,
  908. use_cache=use_cache,
  909. position_embeddings=position_embeddings,
  910. **kwargs,
  911. )
  912. return hidden_states
  913. @auto_docstring
  914. class Zamba2PreTrainedModel(PreTrainedModel):
  915. config: Zamba2Config
  916. base_model_prefix = "model"
  917. supports_gradient_checkpointing = True
  918. _no_split_modules = ["Zamba2HybridLayer", "Zamba2MambaDecoderLayer"]
  919. _skip_keys_device_placement = "past_key_values"
  920. _supports_flash_attn = True
  921. _supports_flex_attn = True
  922. _supports_sdpa = True
  923. _is_stateful = True
  924. _can_record_outputs = {
  925. "hidden_states": Zamba2MambaDecoderLayer,
  926. "attentions": Zamba2Attention,
  927. }
  928. @torch.no_grad()
  929. def _init_weights(self, module):
  930. super()._init_weights(module)
  931. if isinstance(module, Zamba2MambaMixer):
  932. dt = torch.exp(
  933. torch.rand(self.config.n_mamba_heads)
  934. * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
  935. + math.log(self.config.time_step_min)
  936. ).clamp(min=self.config.time_step_floor)
  937. # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
  938. inv_dt = dt + torch.log(-torch.expm1(-dt))
  939. init.copy_(module.dt_bias, inv_dt)
  940. A = torch.arange(1, module.num_heads + 1)
  941. init.copy_(module.A_log, torch.log(A))
  942. init.ones_(module.D)
  943. @auto_docstring
  944. class Zamba2Model(Zamba2PreTrainedModel):
  945. """
  946. Model consisting of *config.num_hidden_layers* layers.
  947. Args:
  948. config: Zamba2Config
  949. """
  950. def __init__(self, config: Zamba2Config):
  951. super().__init__(config)
  952. self.config = config
  953. self.padding_idx = config.pad_token_id
  954. self.vocab_size = config.vocab_size
  955. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  956. self.layers_block_type = config.layers_block_type
  957. self.layers = self.get_layers()
  958. self._attn_implementation = config._attn_implementation
  959. self.final_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  960. if config.use_mem_rope:
  961. if config.use_long_context:
  962. logger.warning_once(
  963. "`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`."
  964. )
  965. self.rotary_emb = Zamba2RotaryEmbedding(config)
  966. self.gradient_checkpointing = False
  967. # Initialize weights and apply final processing
  968. self.post_init()
  969. @merge_with_config_defaults
  970. @capture_outputs
  971. @auto_docstring
  972. def forward(
  973. self,
  974. input_ids: torch.LongTensor | None = None,
  975. attention_mask: torch.Tensor | None = None,
  976. position_ids: torch.LongTensor | None = None,
  977. past_key_values: Cache | None = None,
  978. inputs_embeds: torch.FloatTensor | None = None,
  979. use_cache: bool | None = None,
  980. **kwargs: Unpack[TransformersKwargs],
  981. ) -> tuple | BaseModelOutputWithPast:
  982. if (input_ids is None) ^ (inputs_embeds is not None):
  983. raise ValueError(
  984. "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
  985. )
  986. if inputs_embeds is None:
  987. inputs_embeds = self.embed_tokens(input_ids)
  988. hidden_states = inputs_embeds
  989. original_hidden_states = torch.clone(inputs_embeds)
  990. # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
  991. if use_cache and past_key_values is None:
  992. past_key_values = DynamicCache(config=self.config)
  993. if position_ids is None:
  994. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  995. position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
  996. position_ids = position_ids.unsqueeze(0)
  997. causal_mask = create_causal_mask(
  998. config=self.config,
  999. inputs_embeds=inputs_embeds,
  1000. attention_mask=attention_mask,
  1001. past_key_values=past_key_values,
  1002. position_ids=position_ids,
  1003. )
  1004. # create position embeddings to be shared across the decoder layers
  1005. if self.config.use_mem_rope:
  1006. position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
  1007. else:
  1008. position_embeddings = None
  1009. for layer_idx, layer in enumerate(self.layers):
  1010. hidden_states = layer(
  1011. hidden_states,
  1012. original_hidden_states,
  1013. layer_idx,
  1014. attention_mask,
  1015. causal_mask,
  1016. past_key_values=past_key_values,
  1017. use_cache=use_cache,
  1018. position_embeddings=position_embeddings,
  1019. position_ids=position_ids,
  1020. **kwargs,
  1021. )
  1022. hidden_states = self.final_layernorm(hidden_states)
  1023. return BaseModelOutputWithPast(
  1024. last_hidden_state=hidden_states,
  1025. past_key_values=past_key_values if use_cache else None,
  1026. )
  1027. def get_layers(self):
  1028. layers = []
  1029. self._tied_weights_keys = {}
  1030. self.first_transformer_layer_id = 0
  1031. unique_hybrid_blocks = []
  1032. for layer_id, layer_type in enumerate(self.layers_block_type):
  1033. mamba_layer = Zamba2MambaDecoderLayer(self.config, layer_idx=layer_id)
  1034. if layer_type == "hybrid":
  1035. prefix_pattern = f"layers.{layer_id}.shared_transformer"
  1036. # Zamba ties Hybrid module weights by repeating blocks after every
  1037. # `num_mem_blocks`. So if `num_mem_blocks=2`, the blocks looks like
  1038. # [1, 2, 1, 2, 1, 2] where all "ones" share the same set of weights.
  1039. if (
  1040. not isinstance(unique_hybrid_blocks, list)
  1041. or len(unique_hybrid_blocks) >= self.config.num_mem_blocks
  1042. ):
  1043. if isinstance(unique_hybrid_blocks, list):
  1044. unique_hybrid_blocks = cycle(unique_hybrid_blocks)
  1045. target_pattern = next(unique_hybrid_blocks)
  1046. self._tied_weights_keys.update({prefix_pattern: target_pattern})
  1047. else:
  1048. # Store source patterns to which the subsequent modules will be tied
  1049. unique_hybrid_blocks.append(prefix_pattern)
  1050. block_id = layer_id % self.config.num_mem_blocks
  1051. attn_block = Zamba2AttentionDecoderLayer(self.config, block_id=block_id)
  1052. linear_layer = nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False)
  1053. layers.append(Zamba2HybridLayer(attn_block, linear_layer, mamba_layer))
  1054. else:
  1055. layers.append(mamba_layer)
  1056. return nn.ModuleList(layers)
  1057. # Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->Zamba2, JAMBA->ZAMBA2
  1058. class Zamba2ForCausalLM(Zamba2PreTrainedModel, GenerationMixin):
  1059. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  1060. def __init__(self, config: Zamba2Config):
  1061. super().__init__(config)
  1062. self.model = Zamba2Model(config)
  1063. self.vocab_size = config.vocab_size
  1064. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  1065. # Initialize weights and apply final processing
  1066. self.post_init()
  1067. @can_return_tuple
  1068. @auto_docstring
  1069. def forward(
  1070. self,
  1071. input_ids: torch.LongTensor | None = None,
  1072. attention_mask: torch.Tensor | None = None,
  1073. position_ids: torch.LongTensor | None = None,
  1074. past_key_values: Cache | None = None,
  1075. inputs_embeds: torch.FloatTensor | None = None,
  1076. labels: torch.LongTensor | None = None,
  1077. use_cache: bool | None = None,
  1078. logits_to_keep: int | torch.Tensor = 0,
  1079. **kwargs: Unpack[TransformersKwargs],
  1080. ) -> tuple | CausalLMOutputWithPast:
  1081. r"""
  1082. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1083. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1084. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1085. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1086. Example:
  1087. ```python
  1088. >>> from transformers import AutoTokenizer, Zamba2ForCausalLM
  1089. >>> model = Zamba2ForCausalLM.from_pretrained("Zyphra/Zamba2-7B-v1")
  1090. >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba2-7B-v1")
  1091. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  1092. >>> inputs = tokenizer(prompt, return_tensors="pt")
  1093. >>> # Generate
  1094. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  1095. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1096. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  1097. ```"""
  1098. outputs: BaseModelOutputWithPast = self.model(
  1099. input_ids=input_ids,
  1100. attention_mask=attention_mask,
  1101. position_ids=position_ids,
  1102. past_key_values=past_key_values,
  1103. inputs_embeds=inputs_embeds,
  1104. use_cache=use_cache,
  1105. **kwargs,
  1106. )
  1107. hidden_states = outputs.last_hidden_state
  1108. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1109. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1110. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1111. loss = None
  1112. if labels is not None:
  1113. loss = self.loss_function(
  1114. logits,
  1115. labels,
  1116. self.vocab_size,
  1117. **kwargs,
  1118. )
  1119. return CausalLMOutputWithPast(
  1120. loss=loss,
  1121. logits=logits,
  1122. past_key_values=outputs.past_key_values,
  1123. hidden_states=outputs.hidden_states,
  1124. attentions=outputs.attentions,
  1125. )
  1126. def prepare_inputs_for_generation(
  1127. self,
  1128. input_ids,
  1129. past_key_values=None,
  1130. attention_mask=None,
  1131. inputs_embeds=None,
  1132. position_ids=None,
  1133. use_cache=True,
  1134. is_first_iteration=False,
  1135. **kwargs,
  1136. ):
  1137. kwargs["logits_to_keep"] = self.config.num_logits_to_keep
  1138. model_inputs = super().prepare_inputs_for_generation(
  1139. input_ids,
  1140. past_key_values=past_key_values,
  1141. attention_mask=attention_mask,
  1142. inputs_embeds=inputs_embeds,
  1143. position_ids=position_ids,
  1144. use_cache=use_cache,
  1145. is_first_iteration=is_first_iteration,
  1146. **kwargs,
  1147. )
  1148. return model_inputs
  1149. @auto_docstring(
  1150. custom_intro="""
  1151. The Zamba2 Model with a sequence classification head on top (linear layer).
  1152. [`Zamba2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  1153. (e.g. GPT-2) do.
  1154. Since it does classification on the last token, it requires to know the position of the last token. If a
  1155. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  1156. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  1157. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  1158. each row of the batch).
  1159. """
  1160. )
  1161. class Zamba2ForSequenceClassification(Zamba2PreTrainedModel):
  1162. def __init__(self, config: Zamba2Config):
  1163. super().__init__(config)
  1164. self.num_labels = config.num_labels
  1165. self.model = Zamba2Model(config)
  1166. self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
  1167. # Initialize weights and apply final processing
  1168. self.post_init()
  1169. @can_return_tuple
  1170. @auto_docstring
  1171. def forward(
  1172. self,
  1173. input_ids: torch.LongTensor | None = None,
  1174. attention_mask: torch.Tensor | None = None,
  1175. position_ids: torch.LongTensor | None = None,
  1176. past_key_values: Cache | None = None,
  1177. inputs_embeds: torch.FloatTensor | None = None,
  1178. labels: torch.LongTensor | None = None,
  1179. use_cache: bool | None = None,
  1180. logits_to_keep: int | torch.Tensor = 0,
  1181. **kwargs: Unpack[TransformersKwargs],
  1182. ) -> tuple | SequenceClassifierOutputWithPast:
  1183. r"""
  1184. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1185. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1186. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1187. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1188. """
  1189. transformer_outputs: BaseModelOutputWithPast = self.model(
  1190. input_ids,
  1191. attention_mask=attention_mask,
  1192. position_ids=position_ids,
  1193. past_key_values=past_key_values,
  1194. inputs_embeds=inputs_embeds,
  1195. use_cache=use_cache,
  1196. **kwargs,
  1197. )
  1198. hidden_states = transformer_outputs[0]
  1199. logits = self.score(hidden_states)
  1200. if input_ids is not None:
  1201. batch_size = input_ids.shape[0]
  1202. else:
  1203. batch_size = inputs_embeds.shape[0]
  1204. if self.config.pad_token_id is None and batch_size != 1:
  1205. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  1206. if self.config.pad_token_id is None:
  1207. last_non_pad_token = -1
  1208. elif input_ids is not None:
  1209. non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
  1210. token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
  1211. last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
  1212. else:
  1213. last_non_pad_token = -1
  1214. logger.warning_once(
  1215. f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
  1216. "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
  1217. )
  1218. pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
  1219. loss = None
  1220. if labels is not None:
  1221. loss = self.loss_function(
  1222. logits=pooled_logits, labels=labels, pooled_logits=pooled_logits, config=self.config, **kwargs
  1223. )
  1224. return SequenceClassifierOutputWithPast(
  1225. loss=loss,
  1226. logits=pooled_logits,
  1227. past_key_values=transformer_outputs.past_key_values,
  1228. hidden_states=transformer_outputs.hidden_states,
  1229. attentions=transformer_outputs.attentions,
  1230. )
  1231. __all__ = ["Zamba2ForCausalLM", "Zamba2ForSequenceClassification", "Zamba2Model", "Zamba2PreTrainedModel"]