modeling_blt.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/blt/modular_blt.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_blt.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 HuggingFace Inc. team. All rights reserved.
  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. from typing import Callable, Optional, Union
  22. import torch
  23. import torch.distributions
  24. import torch.nn as nn
  25. import torch.nn.functional as F
  26. from ...activations import ACT2FN
  27. from ...cache_utils import Cache, DynamicCache
  28. from ...generation import GenerationMixin
  29. from ...masking_utils import create_causal_mask
  30. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  31. from ...modeling_layers import GradientCheckpointingLayer
  32. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
  33. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  34. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  35. from ...processing_utils import Unpack
  36. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  37. from ...utils.deprecation import deprecate_kwarg
  38. from ...utils.generic import OutputRecorder, check_model_inputs
  39. from .configuration_blt import (
  40. BltConfig,
  41. BltGlobalTransformerConfig,
  42. BltLocalDecoderConfig,
  43. BltLocalEncoderConfig,
  44. BltPatcherConfig,
  45. )
  46. class BltMLP(nn.Module):
  47. def __init__(self, config):
  48. super().__init__()
  49. self.config = config
  50. self.hidden_size = config.hidden_size
  51. self.intermediate_size = config.intermediate_size
  52. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  53. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  54. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  55. # Ignore copy
  56. self.act_fn = ACT2FN[config.hidden_act]
  57. def forward(self, x):
  58. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  59. return down_proj
  60. class BltRMSNorm(nn.Module):
  61. def __init__(self, hidden_size, eps=1e-6):
  62. """
  63. BltRMSNorm is equivalent to T5LayerNorm
  64. """
  65. super().__init__()
  66. self.weight = nn.Parameter(torch.ones(hidden_size))
  67. self.variance_epsilon = eps
  68. def forward(self, hidden_states):
  69. input_dtype = hidden_states.dtype
  70. hidden_states = hidden_states.to(torch.float32)
  71. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  72. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  73. return self.weight * hidden_states.to(input_dtype)
  74. def extra_repr(self):
  75. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  76. class BltRotaryEmbedding(nn.Module):
  77. inv_freq: torch.Tensor # fix linting for `register_buffer`
  78. def __init__(self, config: BltConfig, device=None):
  79. super().__init__()
  80. # BC: "rope_type" was originally "type"
  81. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  82. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  83. else:
  84. self.rope_type = "default"
  85. self.max_seq_len_cached = config.max_position_embeddings
  86. self.original_max_seq_len = config.max_position_embeddings
  87. self.config = config
  88. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  89. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  90. self.register_buffer("inv_freq", inv_freq, persistent=False)
  91. self.original_inv_freq = self.inv_freq
  92. @torch.no_grad()
  93. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  94. def forward(self, x, position_ids):
  95. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  96. position_ids_expanded = position_ids[:, None, :].float()
  97. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  98. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  99. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  100. emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
  101. cos = emb.cos() * self.attention_scaling
  102. sin = emb.sin() * self.attention_scaling
  103. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  104. # Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer
  105. class BltTransformerLayer(GradientCheckpointingLayer):
  106. def __init__(self, config, layer_idx: int):
  107. super().__init__()
  108. self.hidden_size = config.hidden_size
  109. self.self_attn = BltSelfAttention(config=config, layer_idx=layer_idx)
  110. self.mlp = BltMLP(config)
  111. self.input_layernorm = BltRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  112. self.post_attention_layernorm = BltRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  113. self.layer_idx = layer_idx
  114. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  115. def forward(
  116. self,
  117. hidden_states: torch.Tensor,
  118. cross_attention_states: Optional[torch.Tensor] = None,
  119. cross_attention_mask: Optional[torch.Tensor] = None,
  120. attention_mask: Optional[torch.Tensor] = None,
  121. full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  122. position_ids: Optional[torch.LongTensor] = None,
  123. past_key_values: Optional[Cache] = None,
  124. use_cache: Optional[bool] = False,
  125. cache_position: Optional[torch.LongTensor] = None,
  126. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  127. **kwargs: Unpack[FlashAttentionKwargs],
  128. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  129. """
  130. Args:
  131. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  132. attention_mask (`torch.FloatTensor`, *optional*):
  133. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  134. query_sequence_length, key_sequence_length)` if default attention is used.
  135. use_cache (`bool`, *optional*):
  136. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  137. (see `past_key_values`).
  138. past_key_values (`Cache`, *optional*): cached past key and value projection states
  139. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  140. Indices depicting the position of the input sequence tokens in the sequence
  141. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  142. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  143. with `head_dim` being the embedding dimension of each attention head.
  144. kwargs (`dict`, *optional*):
  145. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  146. into the model
  147. """
  148. residual = hidden_states
  149. hidden_states = self.input_layernorm(hidden_states)
  150. # Self Attention
  151. hidden_states, self_attn_weights = self.self_attn(
  152. hidden_states=hidden_states,
  153. attention_mask=attention_mask,
  154. position_ids=position_ids,
  155. past_key_values=past_key_values,
  156. use_cache=use_cache,
  157. cache_position=cache_position,
  158. position_embeddings=position_embeddings,
  159. **kwargs,
  160. )
  161. hidden_states = residual + hidden_states
  162. # Fully Connected
  163. residual = hidden_states
  164. hidden_states = self.post_attention_layernorm(hidden_states)
  165. hidden_states = self.mlp(hidden_states)
  166. hidden_states = residual + hidden_states
  167. return hidden_states
  168. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  169. """
  170. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  171. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  172. """
  173. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  174. if n_rep == 1:
  175. return hidden_states
  176. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  177. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  178. def eager_attention_forward(
  179. module: nn.Module,
  180. query: torch.Tensor,
  181. key: torch.Tensor,
  182. value: torch.Tensor,
  183. attention_mask: Optional[torch.Tensor],
  184. scaling: float,
  185. dropout: float = 0.0,
  186. **kwargs: Unpack[TransformersKwargs],
  187. ):
  188. key_states = repeat_kv(key, module.num_key_value_groups)
  189. value_states = repeat_kv(value, module.num_key_value_groups)
  190. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  191. if attention_mask is not None:
  192. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  193. attn_weights = attn_weights + causal_mask
  194. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  195. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  196. attn_output = torch.matmul(attn_weights, value_states)
  197. attn_output = attn_output.transpose(1, 2).contiguous()
  198. return attn_output, attn_weights
  199. def rotate_half(x):
  200. # Split and rotate. Note that this function is different from e.g. Llama.
  201. x1 = x[..., ::2]
  202. x2 = x[..., 1::2]
  203. rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
  204. return rot_x
  205. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  206. """Applies Rotary Position Embedding to the query and key tensors.
  207. Args:
  208. q (`torch.Tensor`): The query tensor.
  209. k (`torch.Tensor`): The key tensor.
  210. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  211. sin (`torch.Tensor`): The sine part of the rotary embedding.
  212. position_ids (`torch.Tensor`, *optional*):
  213. Deprecated and unused.
  214. unsqueeze_dim (`int`, *optional*, defaults to 1):
  215. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  216. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  217. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  218. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  219. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  220. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  221. Returns:
  222. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  223. """
  224. cos = cos.unsqueeze(unsqueeze_dim)
  225. sin = sin.unsqueeze(unsqueeze_dim)
  226. q_embed = (q * cos) + (rotate_half(q) * sin)
  227. k_embed = (k * cos) + (rotate_half(k) * sin)
  228. return q_embed, k_embed
  229. class BltSelfAttention(nn.Module):
  230. def __init__(self, config: BltConfig, layer_idx: int):
  231. super().__init__()
  232. self.config = config
  233. self.num_heads = config.num_attention_heads
  234. self.dropout = config.dropout
  235. self.hidden_size = config.hidden_size
  236. self.num_key_value_heads = config.num_key_value_heads
  237. self.head_dim = config.hidden_size // self.num_heads
  238. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  239. self.scaling = self.head_dim**-0.5
  240. self.rope_theta = config.rope_theta
  241. self.layer_idx = layer_idx
  242. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  243. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  244. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  245. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  246. self.is_causal = True
  247. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  248. def forward(
  249. self,
  250. hidden_states: torch.Tensor,
  251. attention_mask: torch.Tensor,
  252. position_embeddings: torch.Tensor,
  253. use_cache: bool = False,
  254. past_key_values=None,
  255. cache_position=None,
  256. **kwargs,
  257. ):
  258. bsz, q_len, _ = hidden_states.size()
  259. query_states = self.q_proj(hidden_states)
  260. key_states = self.k_proj(hidden_states)
  261. value_states = self.v_proj(hidden_states)
  262. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  263. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  264. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  265. cos, sin = position_embeddings
  266. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  267. if past_key_values is not None:
  268. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  269. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  270. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  271. attention_interface: Callable = eager_attention_forward
  272. if self.config._attn_implementation != "eager":
  273. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  274. attn_output, attn_weights = attention_interface(
  275. self,
  276. query_states,
  277. key_states,
  278. value_states,
  279. attention_mask,
  280. dropout=0.0 if not self.training else self.dropout,
  281. scaling=self.scaling,
  282. **kwargs,
  283. )
  284. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  285. attn_output = self.o_proj(attn_output)
  286. return attn_output, attn_weights
  287. class BltCrossAttention(nn.Module):
  288. """Cross-attention module for Blt, following transformers style"""
  289. def __init__(self, config: BltConfig, layer_idx: int, hidden_size: Optional[int] = None):
  290. super().__init__()
  291. self.config = config
  292. self.num_heads = self.config.num_attention_heads
  293. self.num_key_value_heads = self.config.num_key_value_heads
  294. self.dropout = config.dropout
  295. self.hidden_size = config.hidden_size
  296. self.head_dim = config.hidden_size // self.num_heads
  297. self.layer_idx = layer_idx
  298. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  299. self.scaling = self.head_dim**-0.5
  300. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  301. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  302. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  303. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  304. self.q_norm = BltRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
  305. self.k_norm = BltRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
  306. self.is_causal = False
  307. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  308. def forward(
  309. self,
  310. hidden_states: torch.Tensor,
  311. cross_attention_states: Optional[torch.Tensor] = None,
  312. past_key_values: Optional[Cache] = None,
  313. attention_mask: Optional[torch.Tensor] = None,
  314. cache_position: Optional[torch.LongTensor] = None,
  315. **kwargs: Unpack[TransformersKwargs],
  316. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  317. """Input shape: Batch x Time x Channel"""
  318. bsz, q_len, _ = hidden_states.size()
  319. query_states = self.q_norm(hidden_states)
  320. query_states = self.q_proj(query_states)
  321. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  322. if cross_attention_states is not None:
  323. cross_attention_states = self.k_norm(cross_attention_states)
  324. key_states = self.k_proj(cross_attention_states)
  325. value_states = self.v_proj(cross_attention_states)
  326. key_states = key_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  327. value_states = value_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  328. if past_key_values is not None:
  329. key_states, value_states = past_key_values.update(
  330. key_states, value_states, self.layer_idx, {"cache_position": cache_position}
  331. )
  332. elif cache_position[0] != 0:
  333. key_states, value_states = (
  334. past_key_values.layers[self.layer_idx].keys,
  335. past_key_values.layers[self.layer_idx].values,
  336. )
  337. else:
  338. raise ValueError(
  339. "Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!"
  340. )
  341. attention_interface: Callable = eager_attention_forward
  342. if self.config._attn_implementation != "eager":
  343. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  344. attn_output, attn_weights = attention_interface(
  345. self,
  346. query_states,
  347. key_states,
  348. value_states,
  349. attention_mask,
  350. dropout=0.0 if not self.training else self.dropout,
  351. scaling=self.scaling,
  352. **kwargs,
  353. )
  354. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  355. attn_output = self.o_proj(attn_output)
  356. attn_output = attn_output + hidden_states
  357. return attn_output, attn_weights
  358. @auto_docstring
  359. class BltPreTrainedModel(PreTrainedModel):
  360. config: BltConfig
  361. base_model_prefix = ""
  362. supports_gradient_checkpointing = True
  363. _no_split_modules = ["BltTransformerLayer"]
  364. _can_compile_fullgraph = False # static cache cannot have different shapes for each layer
  365. _supports_sdpa = True
  366. _supports_flash_attn = False
  367. _supports_flex_attn = False
  368. _supports_attention_backend = False
  369. _can_record_outputs = {
  370. "hidden_states": OutputRecorder(BltTransformerLayer, index=0, layer_name="local_decoder"),
  371. "attentions": OutputRecorder(BltSelfAttention, index=1, layer_name="local_decoder"),
  372. }
  373. class BltLocalEncoder(BltPreTrainedModel):
  374. config: BltLocalEncoderConfig
  375. _can_record_outputs = {
  376. "encoder_attentions": OutputRecorder(BltSelfAttention, index=1, layer_name="local_encoder"),
  377. }
  378. def __init__(self, config: BltLocalEncoderConfig):
  379. super().__init__(config)
  380. self.gradient_checkpointing = False
  381. self.config = config
  382. self.layers = nn.ModuleList(
  383. [BltTransformerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  384. )
  385. self.rotary_emb = BltRotaryEmbedding(config=config)
  386. self.patch_embedding_projection = nn.Linear(
  387. in_features=config.hidden_size,
  388. out_features=config.hidden_size * config.cross_attn_k,
  389. bias=False,
  390. )
  391. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
  392. self.cross_attn_layers = nn.ModuleList()
  393. layers_to_add = config.num_hidden_layers if config.cross_attn_all_layers else 1
  394. for layer_idx in range(layers_to_add):
  395. self.cross_attn_layers.append(
  396. BltCrossAttention(config=config, layer_idx=layer_idx, hidden_size=config.hidden_size)
  397. )
  398. self.post_init()
  399. def forward(
  400. self,
  401. input_ids: Optional[torch.LongTensor] = None,
  402. inputs_embeds: Optional[torch.Tensor] = None,
  403. patch_embeds: Optional[torch.Tensor] = None,
  404. attention_mask: Optional[torch.Tensor] = None,
  405. position_ids: Optional[torch.LongTensor] = None,
  406. past_key_values: Optional[Cache] = None,
  407. cache_position: Optional[torch.LongTensor] = None,
  408. encoder_attention_mask: Optional[torch.Tensor] = None,
  409. num_patches: Optional[int] = None,
  410. patch_ids: Optional[torch.Tensor] = None,
  411. **kwargs: Unpack[TransformersKwargs],
  412. ):
  413. if inputs_embeds is None:
  414. inputs_embeds = self.embed_tokens(input_ids)
  415. batch_size = inputs_embeds.shape[0]
  416. hidden_states = F.dropout(inputs_embeds, p=self.config.dropout, training=self.training)
  417. if position_ids is None:
  418. position_ids = (
  419. torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0).expand(batch_size, -1)
  420. )
  421. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  422. hidden_states = F.dropout(hidden_states, p=self.config.dropout, training=self.training)
  423. for idx, layer in enumerate(self.layers):
  424. hidden_states = layer(
  425. hidden_states,
  426. position_embeddings=position_embeddings,
  427. attention_mask=attention_mask,
  428. past_key_values=past_key_values,
  429. cache_position=cache_position,
  430. **kwargs,
  431. )
  432. if idx == len(self.layers) - 1 or self.config.cross_attn_all_layers:
  433. patch_embeds = self.patch_reduce(hidden_states, num_patches, patch_ids)
  434. patch_embeds = self.patch_embedding_projection(patch_embeds)
  435. patch_embeds = patch_embeds.reshape(
  436. batch_size, patch_embeds.shape[1] * self.config.cross_attn_k, self.config.hidden_size
  437. )
  438. layer_idx = idx if self.config.cross_attn_all_layers else 0
  439. cross_attention_output, _ = self.cross_attn_layers[layer_idx](
  440. hidden_states=patch_embeds,
  441. cross_attention_states=hidden_states,
  442. attention_mask=encoder_attention_mask,
  443. **kwargs,
  444. )
  445. patch_embeds = patch_embeds + cross_attention_output
  446. encoder_cross_states = patch_embeds
  447. return hidden_states, encoder_cross_states
  448. def patch_reduce(self, hidden_states, max_num_patches, patch_ids):
  449. """
  450. Reduce variable length patches to single embedding per patch
  451. Note: this works with variable number of patches for different sequences in the batch
  452. It handles variable length patches by assuming that patch_lengths will be 0 for any
  453. extra patches on the *right*. Since there can be a variable number of patches
  454. this function also return the number of patches for each sequence in the batch.
  455. Any embeddings on the right that are not allocated to a patch
  456. (i.e. if the sum(patch_lengths[i]) < seq_len for any i)
  457. will be sent to a dummy patch, which is trimmed before returning.
  458. """
  459. batch_size = hidden_states.shape[0]
  460. embedding_dim = hidden_states.shape[-1]
  461. patch_ids = patch_ids.unsqueeze(-1).expand(-1, -1, hidden_states.shape[-1])
  462. reduced_embeddings = torch.zeros(
  463. (batch_size, max_num_patches, embedding_dim), dtype=hidden_states.dtype, device=hidden_states.device
  464. )
  465. reduced_embeddings = reduced_embeddings.scatter_reduce(
  466. src=hidden_states,
  467. dim=1,
  468. index=patch_ids,
  469. reduce="amax",
  470. include_self=False,
  471. )
  472. reduced_embeddings = reduced_embeddings[:, :max_num_patches, :]
  473. return reduced_embeddings
  474. class BltLocalDecoder(BltPreTrainedModel):
  475. config: BltLocalDecoderConfig
  476. def __init__(self, config: BltLocalDecoderConfig):
  477. super().__init__(config)
  478. self.gradient_checkpointing = False
  479. self.config = config
  480. self.cross_attn_decoder = True
  481. self.layers = nn.ModuleList(
  482. [BltTransformerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  483. )
  484. self.rotary_emb = BltRotaryEmbedding(config=config)
  485. self.patch_embedding_projection = nn.Linear(
  486. in_features=config.hidden_size_global,
  487. out_features=config.hidden_size * config.cross_attn_k,
  488. bias=False,
  489. )
  490. self.norm = BltRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  491. self.cross_attn_layers = nn.ModuleList()
  492. layers_to_add = config.num_hidden_layers if config.cross_attn_all_layers else 1
  493. for layer_idx in range(layers_to_add):
  494. self.cross_attn_layers.append(
  495. BltCrossAttention(config=config, layer_idx=layer_idx, hidden_size=config.hidden_size)
  496. )
  497. self.post_init()
  498. @check_model_inputs()
  499. def forward(
  500. self,
  501. input_ids: Optional[torch.LongTensor] = None,
  502. inputs_embeds: Optional[torch.Tensor] = None,
  503. patch_embeds: Optional[torch.Tensor] = None,
  504. attention_mask: Optional[torch.Tensor] = None,
  505. position_ids: Optional[torch.LongTensor] = None,
  506. past_key_values: Optional[Cache] = None,
  507. cache_position: Optional[torch.LongTensor] = None,
  508. encoder_attention_mask: Optional[torch.Tensor] = None,
  509. **kwargs: Unpack[TransformersKwargs],
  510. ):
  511. batch_size = inputs_embeds.shape[0]
  512. hidden_states = inputs_embeds
  513. patch_embeds = self.patch_embedding_projection(patch_embeds)
  514. patch_embeds = patch_embeds.reshape(
  515. batch_size, patch_embeds.shape[1] * self.config.cross_attn_k, self.config.hidden_size
  516. )
  517. if patch_embeds is not None and not self.cross_attn_decoder:
  518. hidden_states = hidden_states + patch_embeds
  519. if position_ids is None:
  520. position_ids = (
  521. torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0).expand(batch_size, -1)
  522. )
  523. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  524. hidden_states = F.dropout(hidden_states, p=self.config.dropout, training=self.training)
  525. for i, layer in enumerate(self.layers):
  526. if i == 0 or self.config.cross_attn_all_layers:
  527. cross_attention_output, _ = self.cross_attn_layers[i](
  528. hidden_states=hidden_states,
  529. cross_attention_states=patch_embeds,
  530. attention_mask=encoder_attention_mask,
  531. **kwargs,
  532. )
  533. hidden_states = hidden_states + cross_attention_output
  534. hidden_states = layer(
  535. hidden_states,
  536. position_embeddings=position_embeddings,
  537. attention_mask=attention_mask,
  538. past_key_values=past_key_values,
  539. cache_position=cache_position,
  540. **kwargs,
  541. )
  542. logits = self.norm(hidden_states)
  543. return logits
  544. class BltGlobalTransformer(BltPreTrainedModel):
  545. config: BltGlobalTransformerConfig
  546. _can_record_outputs = {
  547. "global_attentions": OutputRecorder(BltSelfAttention, index=1, layer_name="global_transformer"),
  548. }
  549. def __init__(self, config: BltGlobalTransformerConfig):
  550. super().__init__(config)
  551. self.config = config
  552. self.layers = nn.ModuleList()
  553. for layer_idx in range(config.num_hidden_layers):
  554. self.layers.append(BltTransformerLayer(config, layer_idx))
  555. self.rotary_emb = BltRotaryEmbedding(config=config)
  556. # Create token embedding projection (use nn.Identity() when no projection needed)
  557. if getattr(config, "encoder_cross_output_size", None) is not None:
  558. self.token_embedding_projection = nn.Linear(
  559. config.encoder_cross_output_size, config.hidden_size, bias=False
  560. )
  561. else:
  562. self.token_embedding_projection = nn.Identity()
  563. self.post_init()
  564. def forward(
  565. self,
  566. input_embeds: torch.Tensor,
  567. attention_mask: Optional[torch.Tensor] = None,
  568. position_ids: Optional[torch.LongTensor] = None,
  569. past_key_values: Optional[Cache] = None,
  570. cache_position: Optional[torch.LongTensor] = None,
  571. **kwargs: Unpack[TransformersKwargs],
  572. ):
  573. batch_size, seq_len, _ = input_embeds.shape
  574. hidden_states = self.token_embedding_projection(input_embeds)
  575. hidden_states = F.dropout(hidden_states, p=self.config.dropout, training=self.training)
  576. if position_ids is None:
  577. position_ids = (
  578. torch.arange(input_embeds.shape[1], device=input_embeds.device).unsqueeze(0).expand(batch_size, -1)
  579. )
  580. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  581. for i, layer in enumerate(self.layers):
  582. hidden_states = layer(
  583. hidden_states,
  584. position_embeddings=position_embeddings,
  585. attention_mask=attention_mask,
  586. past_key_values=past_key_values,
  587. cache_position=cache_position,
  588. **kwargs,
  589. )
  590. return hidden_states
  591. def process_patch_lengths(patch_lengths: torch.Tensor, max_patch_length: Optional[int]) -> torch.Tensor:
  592. """
  593. Splits patch lengths into smaller segments if they exceed `max_patch_length`.
  594. Pads the result to uniform length across the batch.
  595. Args:
  596. patch_lengths (torch.Tensor): [batch_size, num_patches] tensor of patch lengths.
  597. max_patch_length (int, optional): Maximum allowed length per patch.
  598. Returns:
  599. torch.Tensor: [batch_size, max_len] tensor of split and padded patch lengths.
  600. """
  601. if max_patch_length is None:
  602. return patch_lengths
  603. batch_size = patch_lengths.size(0)
  604. processed = []
  605. for seq in patch_lengths:
  606. splits = []
  607. for length in seq[seq > 0]:
  608. length = length.item()
  609. full_chunks, remainder = divmod(length, max_patch_length)
  610. splits.extend([max_patch_length] * full_chunks)
  611. if remainder:
  612. splits.append(remainder)
  613. processed.append(splits)
  614. # Find max length to pad to
  615. max_len = max(len(splits) for splits in processed)
  616. padded = torch.zeros((batch_size, max_len), dtype=patch_lengths.dtype, device=patch_lengths.device)
  617. for i, splits in enumerate(processed):
  618. if splits:
  619. padded[i, : len(splits)] = torch.tensor(splits, dtype=patch_lengths.dtype, device=patch_lengths.device)
  620. # Trim zero columns
  621. if (padded != 0).any(dim=0).sum() < padded.shape[1]:
  622. last_nonzero = (padded != 0).any(dim=0).nonzero().max().item() + 1
  623. padded = padded[:, :last_nonzero]
  624. return padded
  625. class BltPatcher(BltPreTrainedModel):
  626. config: BltPatcherConfig
  627. def __init__(self, config: BltPatcherConfig):
  628. super().__init__(config)
  629. self.rotary_emb = BltRotaryEmbedding(config=self.config)
  630. self.layers = nn.ModuleList()
  631. for layer_idx in range(self.config.num_hidden_layers):
  632. self.layers.append(BltTransformerLayer(self.config, layer_idx))
  633. self.embed_tokens = nn.Embedding(self.config.vocab_size, self.config.hidden_size)
  634. self.norm = BltRMSNorm(self.config.hidden_size, eps=self.config.rms_norm_eps)
  635. self.lm_head = nn.Linear(
  636. self.config.hidden_size,
  637. self.config.vocab_size,
  638. bias=False,
  639. )
  640. def forward(
  641. self,
  642. input_ids: Optional[torch.LongTensor] = None,
  643. attention_mask: Optional[torch.Tensor] = None,
  644. position_ids: Optional[torch.LongTensor] = None,
  645. past_key_values: Optional[Cache] = None,
  646. inputs_embeds: Optional[torch.FloatTensor] = None,
  647. use_cache: Optional[bool] = None,
  648. cache_position: Optional[torch.LongTensor] = None,
  649. patch_size: Optional[int] = None,
  650. threshold: Optional[float] = None,
  651. max_patch_length: Optional[int] = None,
  652. **kwargs: Unpack[TransformersKwargs],
  653. ):
  654. if (input_ids is None) ^ (inputs_embeds is not None):
  655. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  656. if inputs_embeds is None:
  657. inputs_embeds = self.embed_tokens(input_ids)
  658. if use_cache and past_key_values is None:
  659. past_key_values = DynamicCache()
  660. if cache_position is None:
  661. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  662. cache_position = torch.arange(
  663. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  664. )
  665. if position_ids is None:
  666. position_ids = cache_position.unsqueeze(0)
  667. causal_mask = create_causal_mask(
  668. config=self.config,
  669. input_embeds=inputs_embeds,
  670. attention_mask=attention_mask,
  671. cache_position=cache_position,
  672. past_key_values=past_key_values,
  673. position_ids=position_ids,
  674. )
  675. hidden_states = inputs_embeds
  676. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  677. for layer in self.layers:
  678. hidden_states = layer(hidden_states, position_embeddings=position_embeddings, attention_mask=causal_mask)
  679. logits = self.lm_head(self.norm(hidden_states))
  680. prediction_entropies = torch.distributions.Categorical(logits=logits).entropy()
  681. batch_size, sequence_length = inputs_embeds.shape[:2]
  682. if patch_size is not None:
  683. patch_lengths = self.patch_lengths_from_entropies(
  684. entropies=prediction_entropies,
  685. sequence_length=sequence_length,
  686. patch_size=patch_size,
  687. threshold=threshold,
  688. )
  689. else:
  690. patch_lengths = torch.ones(
  691. (batch_size, sequence_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device
  692. )
  693. patch_lengths = process_patch_lengths(patch_lengths, max_patch_length)
  694. return prediction_entropies, patch_lengths, logits
  695. @staticmethod
  696. def patch_lengths_from_entropies(
  697. entropies,
  698. sequence_length,
  699. patch_size=None,
  700. threshold=None,
  701. ):
  702. """
  703. Computes patch lengths from token entropies.
  704. Depending on whether a threshold is provided, the function uses either:
  705. - Thresholding the entropy values (when `threshold` is set).
  706. """
  707. batch_size = entropies.shape[0]
  708. # Always include token 0 and 1 as starting tokens
  709. init_tokens = (
  710. torch.tensor([0, 1], dtype=torch.long, device=entropies.device).unsqueeze(0).repeat(batch_size, 1)
  711. )
  712. offset = init_tokens.shape[1]
  713. # Ignore first token entropy (BOS)
  714. entropies = entropies[:, 1:]
  715. # Threshold the entropy values to define patch start points
  716. patch_mask = entropies > threshold
  717. seq_len = patch_mask.shape[1]
  718. # Create patch IDs (token indices), and add a sentinel to ensure alignment
  719. token_indices = torch.arange(seq_len, device=entropies.device).unsqueeze(0).expand(batch_size, -1)
  720. sentinel = torch.full_like(token_indices, seq_len)
  721. padded_indices = torch.cat([token_indices, sentinel], dim=1)
  722. # Pad mask with inverse to align sentinel correctly
  723. padded_mask = torch.cat([patch_mask, ~patch_mask], dim=1)
  724. # Select indices where mask is True
  725. patch_starts = padded_indices[padded_mask].reshape(batch_size, seq_len)
  726. max_valid_patches = patch_mask.sum(dim=1).max()
  727. patch_starts = patch_starts[:, :max_valid_patches]
  728. # Offset patch starts to account for the two initial tokens
  729. patch_start_ids = torch.cat((init_tokens, patch_starts + offset), dim=1)
  730. # Compute patch end positions by shifting start positions
  731. last_token = torch.full_like(patch_start_ids[:, :1], sequence_length - 1)
  732. patch_ends = torch.cat((patch_start_ids[:, 1:] - 1, last_token), dim=1)
  733. patch_lengths = patch_ends - patch_start_ids + 1
  734. return patch_lengths
  735. def rolling_polynomial_hash(token_tensor, prime: int = 1000000007):
  736. """
  737. A polynomial rolling hash algorithm that converts sequences
  738. of tokens into hash values. The hash is computed as:
  739. hash = (token_0 * prime^0 + token_1 * prime^1 + ... + token_n * prime^n)
  740. The rolling hash allows the model to efficiently
  741. identify and encode recurring byte-level patterns in the input text.
  742. Args:
  743. token_tensor (torch.Tensor): [batch_size, seq_len, group_size] containing token IDs to hash
  744. prime (int): Prime number used as the base for the polynomial hash.
  745. Returns:
  746. torch.Tensor: Hash values of shape [batch_size, seq_len] where each value
  747. represents the hash of the corresponding token group
  748. Example:
  749. >>> tokens = torch.tensor([[1, 2, 3], [4, 5, 6]])
  750. >>> hashes = rolling_polynomial_hash(tokens, prime=31)
  751. >>> # hash[0] = 1*31^0 + 2*31^1 + 3*31^2
  752. >>> # hash[1] = 4*31^0 + 5*31^1 + 6*31^2
  753. """
  754. prime_tensor = torch.tensor(prime, dtype=torch.int64, device=token_tensor.device)
  755. powers = torch.arange(token_tensor.shape[-1], device=token_tensor.device)
  756. prime_powers = prime_tensor**powers
  757. return torch.sum(token_tensor * prime_powers, dim=-1)
  758. def byte_group_hash_function(
  759. token_ids: torch.Tensor, group_size: int = 2, prime: int = 1000000007, max_hash: int = 30000
  760. ):
  761. """Hash token groups and map to range [0, max_hash]."""
  762. with torch.no_grad():
  763. batch_size, seq_len = token_ids.shape
  764. # Add padding for sliding window
  765. padding = torch.zeros(batch_size, group_size - 1, dtype=torch.int64, device=token_ids.device)
  766. padded_tokens = torch.cat([padding, token_ids], dim=1)
  767. # Create sliding windows and compute hashes
  768. windows = padded_tokens.unfold(1, group_size, 1)
  769. hashes = rolling_polynomial_hash(windows, prime)
  770. hash_values = hashes % max_hash
  771. return hash_values
  772. def compute_hash_embeddings(
  773. local_encoder_tokens: torch.Tensor,
  774. local_encoder,
  775. encoder_hash_tok_embedding: nn.Embedding,
  776. encoder_hash_byte_group_nb_functions: int,
  777. encoder_hash_byte_group_size: list,
  778. encoder_hash_byte_group_vocab: int,
  779. ) -> torch.Tensor:
  780. """Compute token embeddings enhanced with hash-based embeddings."""
  781. # Available primes for hash functions
  782. primes = [
  783. 1000000007,
  784. 5915587277,
  785. 1500450271,
  786. 3267000013,
  787. 5754853343,
  788. 4093082899,
  789. 9576890767,
  790. 3628273133,
  791. 2860486313,
  792. 5463458053,
  793. 3367900313,
  794. ]
  795. embeddings = local_encoder.embed_tokens(local_encoder_tokens)
  796. embedding_idx = 0
  797. for func_nb in range(encoder_hash_byte_group_nb_functions):
  798. prime = primes[func_nb % len(primes)] # Cycle through primes if more functions than primes
  799. for group_size in encoder_hash_byte_group_size:
  800. hash_ids = byte_group_hash_function(local_encoder_tokens, group_size, prime, encoder_hash_byte_group_vocab)
  801. # Apply offset to get the correct slice of the fused embedding
  802. offset_hash_ids = hash_ids + embedding_idx * encoder_hash_byte_group_vocab
  803. embeddings += encoder_hash_tok_embedding(offset_hash_ids)
  804. embedding_idx += 1
  805. return embeddings
  806. def _prepare_patch_cross_attention_mask(
  807. patch_ids: torch.Tensor,
  808. num_patches: int,
  809. sequence_length: int,
  810. patches_as_queries: bool = False,
  811. cross_attn_k: int = 1,
  812. dtype: torch.dtype = torch.float32,
  813. ) -> tuple[torch.Tensor, torch.Tensor]:
  814. """
  815. Prepare cross-attention mask for patch-based attention, following mllama's robust approach.
  816. This function creates masks that control which patches can attend to which other patches,
  817. with support for query/key role swapping and cross-attention multipliers.
  818. Args:
  819. patch_ids (torch.Tensor): Tensor of shape [batch_size, seq_len] containing patch ids.
  820. num_patches (int): Total number of patches.
  821. sequence_length (int): Length of the sequence.
  822. patches_as_queries (bool): If True, patches are used as queries, otherwise as keys.
  823. cross_attn_k (int): Cross-attention multiplier for repeating patches.
  824. dtype (torch.dtype): Data type for the output mask.
  825. Returns:
  826. Tuple[torch.Tensor, torch.Tensor]:
  827. - cross_attention_mask: 4D tensor [batch_size, 1, q_len, kv_len]
  828. """
  829. batch_size, seq_len = patch_ids.shape
  830. device = patch_ids.device
  831. # Determine query and key lengths based on configuration
  832. if patches_as_queries:
  833. q_len = num_patches * cross_attn_k
  834. kv_len = sequence_length
  835. # Create patch-to-sequence mapping
  836. q_patch_ids = (
  837. torch.arange(num_patches, device=device)
  838. .unsqueeze(0)
  839. .unsqueeze(-1)
  840. .expand(batch_size, num_patches, seq_len)
  841. )
  842. kv_patch_ids = patch_ids.unsqueeze(1).expand(batch_size, num_patches, seq_len)
  843. else:
  844. q_len = sequence_length
  845. kv_len = num_patches * cross_attn_k
  846. # Create sequence-to-patch mapping
  847. q_patch_ids = patch_ids.unsqueeze(-1).expand(batch_size, seq_len, num_patches)
  848. kv_patch_ids = (
  849. torch.arange(num_patches, device=device).unsqueeze(0).unsqueeze(0).expand(batch_size, seq_len, num_patches)
  850. )
  851. # Create base attention mask - boolean mask where True means "should attend"
  852. # Exact patch matching
  853. cross_attention_mask = q_patch_ids == kv_patch_ids
  854. # Handle cross_attn_k multiplier by repeating along appropriate dimension
  855. repeat_dim = 1 if patches_as_queries else -1
  856. cross_attention_mask = cross_attention_mask.repeat_interleave(cross_attn_k, dim=repeat_dim)
  857. # Validate dimensions
  858. expected_shape = (batch_size, q_len, kv_len)
  859. if cross_attention_mask.shape != expected_shape:
  860. raise ValueError(
  861. f"Cross attention mask shape {cross_attention_mask.shape} doesn't match expected {expected_shape}"
  862. )
  863. # Reshape so it can be used by attn module - add head dimension
  864. cross_attention_mask = cross_attention_mask.unsqueeze(1) # [batch_size, 1, q_len, kv_len]
  865. # Invert the mask (following mllama pattern exactly)
  866. # True -> 0.0 (attend), False -> 1.0 (will become -inf)
  867. inverted_cross_attn_mask = 1.0 - cross_attention_mask.to(dtype)
  868. cross_attention_mask = inverted_cross_attn_mask.masked_fill(
  869. inverted_cross_attn_mask.to(torch.bool), torch.finfo(dtype).min
  870. )
  871. return cross_attention_mask
  872. class BltModel(BltPreTrainedModel):
  873. def __init__(self, config: BltConfig):
  874. super().__init__(config)
  875. self.gradient_checkpointing = False
  876. self.config = config
  877. self.local_encoder = BltLocalEncoder(config.encoder_config)
  878. self.global_transformer = BltGlobalTransformer(config.global_config)
  879. self.local_decoder = BltLocalDecoder(config.decoder_config)
  880. num_embeddings = config.encoder_hash_byte_group_nb_functions * len(config.encoder_hash_byte_group_size)
  881. total_vocab_size = config.encoder_hash_byte_group_vocab * num_embeddings
  882. self.encoder_hash_tok_embedding = nn.Embedding(total_vocab_size, config.encoder_config.hidden_size)
  883. if self.config.patch_in_forward:
  884. self.patcher = BltPatcher(config.patcher_config)
  885. self.patcher.eval()
  886. for param in self.patcher.parameters():
  887. param.requires_grad = False
  888. else:
  889. self.patcher = None
  890. self.post_init()
  891. @check_model_inputs()
  892. def forward(
  893. self,
  894. input_ids: Optional[torch.LongTensor] = None,
  895. patch_lengths: Optional[torch.Tensor] = None,
  896. attention_mask: Optional[torch.Tensor] = None,
  897. position_ids: Optional[torch.LongTensor] = None,
  898. past_key_values: Optional[Cache] = None,
  899. inputs_embeds: Optional[torch.FloatTensor] = None,
  900. use_cache: Optional[bool] = None,
  901. cache_position: Optional[torch.LongTensor] = None,
  902. **kwargs: Unpack[TransformersKwargs],
  903. ) -> BaseModelOutputWithPast:
  904. if (input_ids is None) ^ (inputs_embeds is not None):
  905. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  906. # Extract input embeddings as early as possible
  907. if inputs_embeds is not None:
  908. encoder_embeds = inputs_embeds
  909. batch_size, sequence_length, _ = inputs_embeds.shape
  910. else:
  911. batch_size, sequence_length = input_ids.shape
  912. encoder_embeds = compute_hash_embeddings(
  913. input_ids,
  914. self.local_encoder,
  915. self.encoder_hash_tok_embedding,
  916. self.config.encoder_hash_byte_group_nb_functions,
  917. self.config.encoder_hash_byte_group_size,
  918. self.config.encoder_hash_byte_group_vocab,
  919. )
  920. if patch_lengths is None:
  921. if self.config.patching_mode == "entropy" and self.patcher is not None:
  922. if input_ids is None:
  923. raise ValueError("input_ids is required for entropy-based patching")
  924. _, patch_lengths, _ = self.patcher(
  925. input_ids,
  926. patch_size=self.config.patch_size,
  927. threshold=self.config.patching_threshold,
  928. max_patch_length=self.config.max_patch_length,
  929. patching_batch_size=self.config.patching_batch_size,
  930. device=input_ids.device,
  931. )
  932. else:
  933. device = input_ids.device if input_ids is not None else inputs_embeds.device
  934. dtype = input_ids.dtype if input_ids is not None else inputs_embeds.dtype
  935. patch_lengths = process_patch_lengths(
  936. torch.ones((batch_size, sequence_length + 1), dtype=dtype, device=device),
  937. self.config.max_patch_length,
  938. )
  939. patch_ids = self._patch_ids_from_lengths(patch_lengths, sequence_length)
  940. if cache_position is None:
  941. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  942. cache_position = torch.arange(
  943. past_seen_tokens, past_seen_tokens + encoder_embeds.shape[1], device=encoder_embeds.device
  944. )
  945. if position_ids is None:
  946. position_ids = cache_position.unsqueeze(0)
  947. causal_mask = create_causal_mask(
  948. config=self.config,
  949. input_embeds=encoder_embeds,
  950. attention_mask=attention_mask,
  951. cache_position=cache_position,
  952. past_key_values=past_key_values,
  953. position_ids=position_ids,
  954. )
  955. cross_attn_mask_enc = _prepare_patch_cross_attention_mask(
  956. patch_ids=patch_ids,
  957. num_patches=patch_lengths.shape[1],
  958. sequence_length=sequence_length,
  959. patches_as_queries=True,
  960. cross_attn_k=self.config.cross_attn_k,
  961. dtype=encoder_embeds.dtype,
  962. )
  963. encoder_hidden_states, encoder_cross_states = self.local_encoder(
  964. input_ids=input_ids,
  965. inputs_embeds=encoder_embeds,
  966. attention_mask=causal_mask,
  967. position_ids=position_ids,
  968. encoder_attention_mask=cross_attn_mask_enc,
  969. num_patches=patch_lengths.shape[1],
  970. patch_ids=patch_ids,
  971. **kwargs,
  972. )
  973. encoder_cross_states = encoder_cross_states.view(batch_size, patch_lengths.shape[1], -1)
  974. global_cache_position = torch.arange(0, encoder_cross_states.shape[1], device=encoder_cross_states.device)
  975. global_position_ids = global_cache_position.unsqueeze(0)
  976. global_causal_mask = create_causal_mask(
  977. config=self.config,
  978. input_embeds=encoder_cross_states,
  979. attention_mask=None,
  980. cache_position=global_cache_position,
  981. past_key_values=None,
  982. position_ids=None,
  983. )
  984. global_hidden_states = self.global_transformer(
  985. input_embeds=encoder_cross_states,
  986. attention_mask=global_causal_mask,
  987. position_ids=global_position_ids,
  988. **kwargs,
  989. )
  990. decoder_patch_ids = self._patch_ids_from_lengths(patch_lengths[:, 1:], sequence_length)
  991. cross_attn_mask_dec = _prepare_patch_cross_attention_mask(
  992. patch_ids=decoder_patch_ids,
  993. num_patches=patch_lengths.shape[1],
  994. sequence_length=sequence_length,
  995. patches_as_queries=False,
  996. cross_attn_k=self.config.cross_attn_k,
  997. dtype=encoder_embeds.dtype,
  998. )
  999. output = self.local_decoder(
  1000. input_ids=input_ids,
  1001. inputs_embeds=encoder_hidden_states,
  1002. patch_embeds=global_hidden_states,
  1003. attention_mask=causal_mask,
  1004. position_ids=position_ids,
  1005. past_key_values=past_key_values,
  1006. cache_position=cache_position,
  1007. encoder_attention_mask=cross_attn_mask_dec,
  1008. **kwargs,
  1009. )
  1010. return BaseModelOutputWithPast(
  1011. last_hidden_state=output,
  1012. past_key_values=past_key_values,
  1013. )
  1014. def get_input_embeddings(self):
  1015. return self.local_encoder.embed_tokens
  1016. def set_input_embeddings(self, value):
  1017. self.local_encoder.embed_tokens = value
  1018. def _patch_ids_from_lengths(self, patch_lengths: torch.Tensor, seq_len: int) -> torch.Tensor:
  1019. batch_size = patch_lengths.shape[0]
  1020. patch_starts = torch.cat(
  1021. [
  1022. torch.zeros(batch_size, 1, dtype=patch_lengths.dtype, device=patch_lengths.device),
  1023. patch_lengths.cumsum(dim=-1)[:, :-1],
  1024. ],
  1025. dim=-1,
  1026. )
  1027. token_positions = torch.arange(seq_len, device=patch_lengths.device)
  1028. return (patch_starts.unsqueeze(1) <= token_positions.unsqueeze(0).unsqueeze(-1)).sum(dim=-1) - 1
  1029. @auto_docstring(
  1030. custom_intro="""
  1031. The Blt Text Model with a language modeling head on top.
  1032. """
  1033. )
  1034. class BltForCausalLM(BltPreTrainedModel, GenerationMixin):
  1035. config: BltConfig
  1036. _can_compile_fullgraph = False
  1037. base_model_prefix = "model"
  1038. _tied_weights_keys = ["lm_head.weight"]
  1039. def __init__(self, config: BltConfig):
  1040. super().__init__(config.get_text_config())
  1041. self.text_config = config.get_text_config()
  1042. self.vocab_size = config.vocab_size
  1043. self.model = BltModel(config)
  1044. self.lm_head = nn.Linear(config.decoder_config.hidden_size, config.vocab_size, bias=False)
  1045. self.post_init()
  1046. @can_return_tuple
  1047. @auto_docstring
  1048. def forward(
  1049. self,
  1050. input_ids: Optional[torch.LongTensor] = None,
  1051. attention_mask: Optional[torch.Tensor] = None,
  1052. position_ids: Optional[torch.LongTensor] = None,
  1053. cross_attention_states: Optional[torch.LongTensor] = None, # Keep for compatibility
  1054. cross_attention_mask: Optional[torch.LongTensor] = None,
  1055. full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  1056. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  1057. inputs_embeds: Optional[torch.FloatTensor] = None,
  1058. labels: Optional[torch.LongTensor] = None,
  1059. use_cache: Optional[bool] = None,
  1060. cache_position: Optional[torch.LongTensor] = None,
  1061. logits_to_keep: Union[int, torch.Tensor] = 0,
  1062. **kwargs: Unpack[TransformersKwargs],
  1063. ) -> Union[tuple, CausalLMOutputWithPast]:
  1064. r"""
  1065. cross_attention_states (`torch.FloatTensor`, *optional*):
  1066. Output of the vision model, used for cross-attention. This tensor contains the processed image features that
  1067. the language model will attend to.
  1068. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
  1069. Cross-attention mask to control the interaction between text tokens and image tiles.
  1070. This 4D tensor defines which image tiles each text token should attend to.
  1071. For each text token (in seq_length):
  1072. - 1 indicates the token **should attend** to the corresponding image tile
  1073. - 0 indicates the token **should not attend** to the corresponding image tile
  1074. full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
  1075. A tuple containing two tensors that mask out rows in the cross-attention mechanism:
  1076. - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
  1077. A value of 0 indicates that the corresponding text token's entire row in the cross-attention
  1078. matrix should be masked out (all image tokens ignored).
  1079. - The second tensor has the same shape and is used internally to apply the masking during
  1080. the forward pass of cross-attention layers.
  1081. This mask is derived from the cross_attention_mask and is used to handle cases where a text token
  1082. should not attend to any image token.
  1083. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1084. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1085. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1086. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1087. Example:
  1088. ```python
  1089. >>> from transformers import AutoTokenizer, BltForCausalLM
  1090. >>> model = BltForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
  1091. >>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
  1092. >>> prompt = "If I had to write a haiku, it would be:"
  1093. >>> inputs = tokenizer(prompt, return_tensors="pt")
  1094. >>> # Generate
  1095. >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
  1096. >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1097. >>> print(result)
  1098. If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
  1099. I love the idea of snowflakes gently falling, each one
  1100. ```
  1101. """
  1102. # Call parent forward but exclude cross_attention_states from model call
  1103. outputs = self.model(
  1104. input_ids=input_ids,
  1105. attention_mask=attention_mask,
  1106. position_ids=position_ids,
  1107. cross_attention_mask=cross_attention_mask,
  1108. full_text_row_masked_out_mask=full_text_row_masked_out_mask,
  1109. past_key_values=past_key_values,
  1110. inputs_embeds=inputs_embeds,
  1111. use_cache=use_cache,
  1112. cache_position=cache_position,
  1113. **kwargs,
  1114. )
  1115. hidden_states = outputs.last_hidden_state
  1116. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1117. logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
  1118. loss = None
  1119. if labels is not None:
  1120. loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
  1121. return CausalLMOutputWithPast(
  1122. loss=loss,
  1123. logits=logits,
  1124. past_key_values=outputs.past_key_values,
  1125. hidden_states=outputs.hidden_states,
  1126. attentions=outputs.attentions,
  1127. )
  1128. __all__ = ["BltPreTrainedModel", "BltModel", "BltPatcher", "BltForCausalLM"]