modeling_zamba2.py 83 KB

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