modeling_mllama.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. # coding=utf-8
  2. # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch Mllama model."""
  16. import math
  17. from typing import Callable, Optional, Union
  18. import torch
  19. import torch.nn.functional as F
  20. from torch import nn
  21. from ...activations import ACT2FN
  22. from ...cache_utils import Cache, DynamicCache
  23. from ...generation import GenerationMixin
  24. from ...modeling_attn_mask_utils import AttentionMaskConverter
  25. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  26. from ...modeling_layers import GradientCheckpointingLayer
  27. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, CausalLMOutputWithPast
  28. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  29. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  30. from ...processing_utils import Unpack
  31. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
  32. from ...utils.deprecation import deprecate_kwarg
  33. from ...utils.generic import OutputRecorder, check_model_inputs
  34. from .configuration_mllama import MllamaConfig, MllamaTextConfig, MllamaVisionConfig
  35. if is_torch_flex_attn_available():
  36. from torch.nn.attention.flex_attention import BlockMask
  37. from ...integrations.flex_attention import make_flex_block_causal_mask
  38. logger = logging.get_logger(__name__)
  39. def _prepare_cross_attention_mask(
  40. cross_attention_mask: torch.Tensor,
  41. num_vision_tokens: int,
  42. dtype: str,
  43. ) -> tuple[torch.Tensor, torch.Tensor]:
  44. # reshape so it can be used by attn module
  45. batch_size, text_total_length, *_ = cross_attention_mask.shape
  46. cross_attention_mask = cross_attention_mask.repeat_interleave(num_vision_tokens, dim=3)
  47. cross_attention_mask = cross_attention_mask.view(batch_size, text_total_length, -1)
  48. cross_attention_mask = cross_attention_mask.unsqueeze(1)
  49. # invert the mask
  50. inverted_cross_attn_mask = (1.0 - cross_attention_mask).to(dtype)
  51. cross_attention_mask = inverted_cross_attn_mask.masked_fill(
  52. inverted_cross_attn_mask.to(torch.bool), torch.finfo(dtype).min
  53. )
  54. # apply full-row bias, which return 4D tensor of shape [B, H, S1, 1] where value is 0 if the a full row in cross attn mask's
  55. # last dimension contains negative infinity values, otherwise it's 1
  56. negative_inf_value = torch.finfo(dtype).min
  57. full_text_row_masked_out_mask = (
  58. (cross_attention_mask != negative_inf_value).any(dim=-1).type_as(cross_attention_mask)[..., None]
  59. )
  60. cross_attention_mask *= full_text_row_masked_out_mask
  61. return cross_attention_mask, full_text_row_masked_out_mask
  62. def _prepare_aspect_ratio_attention_mask(
  63. aspect_ratio_mask: torch.Tensor,
  64. num_patches: int,
  65. target_length: int,
  66. dtype: torch.dtype,
  67. ) -> torch.Tensor:
  68. # Expand aspect ratio mask to target_length
  69. batch_size, max_num_tiles = aspect_ratio_mask.shape
  70. attention_mask = aspect_ratio_mask.view(batch_size, max_num_tiles, 1, 1).to(dtype)
  71. attention_mask = attention_mask.repeat(1, 1, target_length, 1)
  72. # Mask padding patches
  73. pad_patches = target_length - num_patches
  74. attention_mask[:, :, -pad_patches:] = 0
  75. # Invert the mask (0 -> 1, 1 -> 0)
  76. attention_mask = 1 - attention_mask
  77. # Reshape to 2D and create 4D attention mask
  78. # (batch_size, 1, max_num_tiles * target_length, max_num_tiles * target_length)
  79. attention_mask = attention_mask.reshape(batch_size, max_num_tiles * target_length, 1)
  80. attention_mask = attention_mask @ attention_mask.transpose(-1, -2) * torch.finfo(dtype).min
  81. attention_mask = attention_mask.unsqueeze(1)
  82. return attention_mask
  83. class MllamaPrecomputedAspectRatioEmbedding(nn.Module):
  84. def __init__(self, config: MllamaVisionConfig, is_gated: bool = True):
  85. super().__init__()
  86. self.max_num_tiles = config.max_num_tiles
  87. self.hidden_size = config.hidden_size
  88. self.max_aspect_ratio_id = config.max_aspect_ratio_id
  89. self.is_gated = is_gated
  90. self.embedding = nn.Embedding(self.max_aspect_ratio_id + 1, self.max_num_tiles * self.hidden_size)
  91. if is_gated:
  92. self.gate = nn.Parameter(torch.zeros(1))
  93. def forward(self, hidden_state: torch.Tensor, aspect_ratio_ids: torch.Tensor) -> torch.Tensor:
  94. embeddings = self.embedding(aspect_ratio_ids)
  95. embeddings = embeddings.reshape(-1, self.max_num_tiles, 1, self.hidden_size)
  96. if self.is_gated:
  97. embeddings = embeddings * self.gate.tanh()
  98. hidden_state = hidden_state + embeddings
  99. return hidden_state
  100. class MllamaPrecomputedPositionEmbedding(nn.Module):
  101. def __init__(self, config: MllamaVisionConfig):
  102. super().__init__()
  103. self.max_num_tiles = config.max_num_tiles
  104. self.max_aspect_ratio_id = config.max_aspect_ratio_id
  105. self.num_patches = (config.image_size // config.patch_size) ** 2 + 1
  106. self.hidden_size = config.hidden_size
  107. self.scale = config.hidden_size**-0.5
  108. self.gate = nn.Parameter(torch.zeros(1))
  109. # position embedding
  110. position_embedding = torch.randn(self.num_patches, self.hidden_size)
  111. self.embedding = nn.Parameter(self.scale * position_embedding)
  112. # tile position embedding
  113. self.tile_embedding = nn.Embedding(
  114. self.max_aspect_ratio_id + 1, self.max_num_tiles * self.num_patches * self.hidden_size
  115. )
  116. def forward(self, hidden_state: torch.Tensor, aspect_ratio_ids: torch.Tensor) -> torch.Tensor:
  117. # position embeddings
  118. gated_position_embedding = (1 - self.gate.tanh()) * self.embedding
  119. hidden_state = hidden_state + gated_position_embedding.view(1, 1, self.num_patches, self.hidden_size)
  120. # precomputed tile position embeddings
  121. tile_position_embedding = self.tile_embedding(aspect_ratio_ids)
  122. batch_size = hidden_state.shape[0]
  123. tile_position_embedding = tile_position_embedding.reshape(
  124. batch_size, self.max_num_tiles, self.num_patches, self.hidden_size
  125. )
  126. gated_tile_position_embedding = self.gate.tanh() * tile_position_embedding
  127. hidden_state = hidden_state + gated_tile_position_embedding
  128. return hidden_state
  129. # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->MllamaVision
  130. class MllamaVisionMLP(nn.Module):
  131. def __init__(self, config):
  132. super().__init__()
  133. self.config = config
  134. self.activation_fn = ACT2FN[config.hidden_act]
  135. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
  136. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  137. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  138. hidden_states = self.fc1(hidden_states)
  139. hidden_states = self.activation_fn(hidden_states)
  140. hidden_states = self.fc2(hidden_states)
  141. return hidden_states
  142. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  143. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  144. """
  145. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  146. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  147. """
  148. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  149. if n_rep == 1:
  150. return hidden_states
  151. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  152. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  153. # Copied from transformers.models.llama.modeling_llama.eager_attention_forward
  154. def eager_attention_forward(
  155. module: nn.Module,
  156. query: torch.Tensor,
  157. key: torch.Tensor,
  158. value: torch.Tensor,
  159. attention_mask: Optional[torch.Tensor],
  160. scaling: float,
  161. dropout: float = 0.0,
  162. **kwargs: Unpack[TransformersKwargs],
  163. ):
  164. key_states = repeat_kv(key, module.num_key_value_groups)
  165. value_states = repeat_kv(value, module.num_key_value_groups)
  166. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  167. if attention_mask is not None:
  168. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  169. attn_weights = attn_weights + causal_mask
  170. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  171. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  172. attn_output = torch.matmul(attn_weights, value_states)
  173. attn_output = attn_output.transpose(1, 2).contiguous()
  174. return attn_output, attn_weights
  175. class MllamaVisionAttention(nn.Module):
  176. def __init__(self, config: MllamaVisionConfig):
  177. super().__init__()
  178. self.config = config
  179. self.embed_dim = config.hidden_size
  180. self.num_heads = config.attention_heads
  181. self.head_dim = config.hidden_size // config.attention_heads
  182. self.scaling = self.head_dim**-0.5
  183. self.num_key_value_groups = 1
  184. self.q_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
  185. self.k_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
  186. self.v_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
  187. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.embed_dim, bias=False)
  188. def forward(
  189. self,
  190. hidden_state: torch.Tensor,
  191. attention_mask: Optional[torch.Tensor] = None,
  192. **kwargs,
  193. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  194. query = self.q_proj(hidden_state)
  195. key = self.k_proj(hidden_state)
  196. value = self.v_proj(hidden_state)
  197. batch_size, q_seq_len, _ = query.shape
  198. _, kv_seq_len, _ = key.shape
  199. query = query.view(batch_size, q_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
  200. key = key.view(batch_size, kv_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
  201. value = value.view(batch_size, kv_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
  202. attention_interface: Callable = eager_attention_forward
  203. if self.config._attn_implementation != "eager":
  204. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  205. attn_output, attn_weights = attention_interface(
  206. self,
  207. query,
  208. key,
  209. value,
  210. attention_mask,
  211. dropout=0.0,
  212. scaling=self.scaling,
  213. **kwargs,
  214. )
  215. attn_output = attn_output.reshape(batch_size, q_seq_len, -1).contiguous()
  216. attn_output = self.o_proj(attn_output)
  217. return attn_output, attn_weights
  218. class MllamaVisionEncoderLayer(nn.Module):
  219. def __init__(self, config: MllamaVisionConfig, is_gated: bool = False):
  220. super().__init__()
  221. self.hidden_size = config.hidden_size
  222. self.num_attention_heads = config.attention_heads
  223. self.is_gated = is_gated
  224. self.intermediate_size = config.intermediate_size
  225. self.self_attn = MllamaVisionAttention(config)
  226. self.mlp = MllamaVisionMLP(config)
  227. self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
  228. self.post_attention_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
  229. if is_gated:
  230. self.gate_attn = nn.Parameter(torch.ones(1) * math.pi / 4)
  231. self.gate_ffn = nn.Parameter(torch.ones(1) * math.pi / 4)
  232. def forward(
  233. self,
  234. hidden_state: torch.Tensor,
  235. attention_mask: Optional[torch.Tensor] = None,
  236. ):
  237. # Self Attention
  238. residual = hidden_state
  239. hidden_state = self.input_layernorm(hidden_state)
  240. hidden_state, attn_weights = self.self_attn(hidden_state, attention_mask=attention_mask)
  241. if self.is_gated:
  242. hidden_state = self.gate_attn.tanh() * hidden_state
  243. hidden_state = residual + hidden_state
  244. # Feed forward
  245. residual = hidden_state
  246. hidden_state = self.post_attention_layernorm(hidden_state)
  247. hidden_state = self.mlp(hidden_state)
  248. if self.is_gated:
  249. hidden_state = self.gate_ffn.tanh() * hidden_state
  250. hidden_state = residual + hidden_state
  251. return hidden_state
  252. class MllamaVisionEncoder(nn.Module):
  253. """
  254. Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
  255. [`MllamaEncoderLayer`].
  256. Args:
  257. config: MllamaConfig
  258. """
  259. def __init__(self, config: MllamaVisionConfig, num_layers=32, is_gated=False):
  260. super().__init__()
  261. self.config = config
  262. self.layers = nn.ModuleList([MllamaVisionEncoderLayer(config, is_gated) for _ in range(num_layers)])
  263. self.gradient_checkpointing = False
  264. self.config = config
  265. def forward(
  266. self,
  267. hidden_states: torch.Tensor,
  268. attention_mask: Optional[torch.Tensor] = None,
  269. ) -> BaseModelOutput:
  270. r"""
  271. Args:
  272. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  273. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
  274. This is useful if you want more control over how to convert `input_ids` indices into associated vectors
  275. than the model's internal embedding lookup matrix.
  276. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  277. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  278. - 1 for tokens that are **not masked**,
  279. - 0 for tokens that are **masked**.
  280. [What are attention masks?](../glossary#attention-mask)
  281. """
  282. encoder_states = ()
  283. for encoder_layer in self.layers:
  284. hidden_states = encoder_layer(
  285. hidden_state=hidden_states,
  286. attention_mask=attention_mask,
  287. )
  288. encoder_states = encoder_states + (hidden_states,)
  289. return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states)
  290. # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->MllamaText
  291. class MllamaTextRMSNorm(nn.Module):
  292. def __init__(self, hidden_size, eps=1e-6):
  293. """
  294. MllamaTextRMSNorm is equivalent to T5LayerNorm
  295. """
  296. super().__init__()
  297. self.weight = nn.Parameter(torch.ones(hidden_size))
  298. self.variance_epsilon = eps
  299. def forward(self, hidden_states):
  300. input_dtype = hidden_states.dtype
  301. hidden_states = hidden_states.to(torch.float32)
  302. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  303. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  304. return self.weight * hidden_states.to(input_dtype)
  305. def extra_repr(self):
  306. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  307. class MllamaTextCrossAttention(nn.Module):
  308. """Multi-headed attention from 'Attention Is All You Need' paper"""
  309. def __init__(
  310. self,
  311. config: Optional[MllamaTextConfig] = None,
  312. layer_idx: Optional[int] = None,
  313. ):
  314. super().__init__()
  315. self.config = config
  316. self.num_heads = self.config.num_attention_heads
  317. self.num_key_value_heads = self.config.num_key_value_heads
  318. self.dropout = config.dropout
  319. self.hidden_size = config.hidden_size
  320. self.head_dim = config.hidden_size // self.num_heads
  321. self.layer_idx = layer_idx
  322. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  323. self.scaling = self.head_dim**-0.5
  324. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  325. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  326. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  327. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  328. self.q_norm = MllamaTextRMSNorm(self.head_dim, eps=config.rms_norm_eps)
  329. self.k_norm = MllamaTextRMSNorm(self.head_dim, eps=config.rms_norm_eps)
  330. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  331. def forward(
  332. self,
  333. hidden_states: torch.Tensor,
  334. cross_attention_states: Optional[torch.Tensor] = None,
  335. past_key_values: Optional[Cache] = None,
  336. attention_mask: Optional[torch.Tensor] = None,
  337. use_cache: Optional[bool] = None,
  338. cache_position: Optional[torch.LongTensor] = None,
  339. **kwargs,
  340. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  341. """Input shape: Batch x Time x Channel"""
  342. bsz, q_len, _ = hidden_states.size()
  343. query_states = self.q_proj(hidden_states)
  344. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  345. query_states = self.q_norm(query_states)
  346. if cross_attention_states is not None:
  347. key_states = self.k_proj(cross_attention_states)
  348. value_states = self.v_proj(cross_attention_states)
  349. key_states = key_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  350. value_states = value_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  351. key_states = self.k_norm(key_states)
  352. if past_key_values is not None:
  353. # if we have a new image + new tokens, we only computed key_states on that new image
  354. # we still update the cross key states, past_image, new_image. And use it!
  355. key_states, value_states = past_key_values.update(
  356. key_states, value_states, self.layer_idx, {"cache_position": cache_position}
  357. )
  358. elif cache_position[0] != 0:
  359. key_states, value_states = (
  360. past_key_values.layers[self.layer_idx].keys,
  361. past_key_values.layers[self.layer_idx].values,
  362. )
  363. else:
  364. raise ValueError(
  365. "Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!"
  366. )
  367. attention_interface: Callable = eager_attention_forward
  368. if self.config._attn_implementation != "eager":
  369. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  370. attn_output, attn_weights = attention_interface(
  371. self,
  372. query_states,
  373. key_states,
  374. value_states,
  375. attention_mask,
  376. dropout=0.0 if not self.training else self.dropout,
  377. scaling=self.scaling,
  378. **kwargs,
  379. )
  380. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  381. attn_output = self.o_proj(attn_output)
  382. return attn_output, attn_weights
  383. # Copied from transformers.models.llama.modeling_llama.rotate_half
  384. def rotate_half(x):
  385. """Rotates half the hidden dims of the input."""
  386. x1 = x[..., : x.shape[-1] // 2]
  387. x2 = x[..., x.shape[-1] // 2 :]
  388. return torch.cat((-x2, x1), dim=-1)
  389. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  390. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  391. """Applies Rotary Position Embedding to the query and key tensors.
  392. Args:
  393. q (`torch.Tensor`): The query tensor.
  394. k (`torch.Tensor`): The key tensor.
  395. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  396. sin (`torch.Tensor`): The sine part of the rotary embedding.
  397. position_ids (`torch.Tensor`, *optional*):
  398. Deprecated and unused.
  399. unsqueeze_dim (`int`, *optional*, defaults to 1):
  400. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  401. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  402. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  403. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  404. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  405. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  406. Returns:
  407. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  408. """
  409. cos = cos.unsqueeze(unsqueeze_dim)
  410. sin = sin.unsqueeze(unsqueeze_dim)
  411. q_embed = (q * cos) + (rotate_half(q) * sin)
  412. k_embed = (k * cos) + (rotate_half(k) * sin)
  413. return q_embed, k_embed
  414. class MllamaTextSelfAttention(nn.Module):
  415. def __init__(self, config: MllamaTextConfig, layer_idx: int):
  416. super().__init__()
  417. self.config = config
  418. self.num_heads = config.num_attention_heads
  419. self.dropout = config.dropout
  420. self.hidden_size = config.hidden_size
  421. self.num_key_value_heads = config.num_key_value_heads
  422. self.head_dim = config.hidden_size // self.num_heads
  423. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  424. self.scaling = self.head_dim**-0.5
  425. self.rope_theta = config.rope_theta
  426. self.layer_idx = layer_idx
  427. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  428. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  429. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  430. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  431. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  432. def forward(
  433. self,
  434. hidden_states: torch.Tensor,
  435. attention_mask: torch.Tensor,
  436. position_embeddings: torch.Tensor,
  437. use_cache: bool = False,
  438. past_key_values=None,
  439. cache_position=None,
  440. **kwargs,
  441. ):
  442. bsz, q_len, _ = hidden_states.size()
  443. query_states = self.q_proj(hidden_states)
  444. key_states = self.k_proj(hidden_states)
  445. value_states = self.v_proj(hidden_states)
  446. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  447. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  448. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  449. cos, sin = position_embeddings
  450. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  451. if past_key_values is not None:
  452. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  453. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  454. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  455. attention_interface: Callable = eager_attention_forward
  456. if self.config._attn_implementation != "eager":
  457. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  458. attn_output, attn_weights = attention_interface(
  459. self,
  460. query_states,
  461. key_states,
  462. value_states,
  463. attention_mask,
  464. dropout=0.0 if not self.training else self.dropout,
  465. scaling=self.scaling,
  466. **kwargs,
  467. )
  468. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  469. attn_output = self.o_proj(attn_output)
  470. return attn_output, attn_weights
  471. # Copied from transformers.models.gemma2.modeling_gemma2.Gemma2MLP with Gemma2->MllamaText
  472. class MllamaTextMLP(nn.Module):
  473. def __init__(self, config):
  474. super().__init__()
  475. self.config = config
  476. self.hidden_size = config.hidden_size
  477. self.intermediate_size = config.intermediate_size
  478. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  479. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  480. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  481. # Ignore copy
  482. self.act_fn = ACT2FN[config.hidden_act]
  483. def forward(self, x):
  484. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  485. return down_proj
  486. # Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer
  487. class MllamaSelfAttentionDecoderLayer(GradientCheckpointingLayer):
  488. def __init__(self, config: MllamaTextConfig, layer_idx: int):
  489. super().__init__()
  490. self.hidden_size = config.hidden_size
  491. self.self_attn = MllamaTextSelfAttention(config=config, layer_idx=layer_idx)
  492. self.mlp = MllamaTextMLP(config)
  493. self.input_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  494. self.post_attention_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  495. self.layer_idx = layer_idx
  496. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  497. def forward(
  498. self,
  499. hidden_states: torch.Tensor,
  500. cross_attention_states: Optional[torch.Tensor] = None,
  501. cross_attention_mask: Optional[torch.Tensor] = None,
  502. attention_mask: Optional[torch.Tensor] = None,
  503. full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  504. position_ids: Optional[torch.LongTensor] = None,
  505. past_key_values: Optional[Cache] = None,
  506. use_cache: Optional[bool] = False,
  507. cache_position: Optional[torch.LongTensor] = None,
  508. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  509. **kwargs: Unpack[FlashAttentionKwargs],
  510. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  511. """
  512. Args:
  513. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  514. attention_mask (`torch.FloatTensor`, *optional*):
  515. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  516. query_sequence_length, key_sequence_length)` if default attention is used.
  517. use_cache (`bool`, *optional*):
  518. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  519. (see `past_key_values`).
  520. past_key_values (`Cache`, *optional*): cached past key and value projection states
  521. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  522. Indices depicting the position of the input sequence tokens in the sequence
  523. position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
  524. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  525. with `head_dim` being the embedding dimension of each attention head.
  526. kwargs (`dict`, *optional*):
  527. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  528. into the model
  529. """
  530. residual = hidden_states
  531. hidden_states = self.input_layernorm(hidden_states)
  532. # Self Attention
  533. hidden_states, self_attn_weights = self.self_attn(
  534. hidden_states=hidden_states,
  535. attention_mask=attention_mask,
  536. position_ids=position_ids,
  537. past_key_values=past_key_values,
  538. use_cache=use_cache,
  539. cache_position=cache_position,
  540. position_embeddings=position_embeddings,
  541. **kwargs,
  542. )
  543. hidden_states = residual + hidden_states
  544. # Fully Connected
  545. residual = hidden_states
  546. hidden_states = self.post_attention_layernorm(hidden_states)
  547. hidden_states = self.mlp(hidden_states)
  548. hidden_states = residual + hidden_states
  549. return hidden_states
  550. class MllamaCrossAttentionDecoderLayer(GradientCheckpointingLayer):
  551. """Cross-attention transformer block with tanh-gated attention and feedforward."""
  552. def __init__(self, config: MllamaTextConfig, layer_idx: int) -> None:
  553. super().__init__()
  554. self.layer_idx = layer_idx
  555. self.cross_attn = MllamaTextCrossAttention(config, layer_idx=layer_idx)
  556. self.input_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  557. self.cross_attn_attn_gate = torch.nn.Parameter(torch.zeros(1))
  558. self.mlp = MllamaTextMLP(config)
  559. self.post_attention_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  560. self.cross_attn_mlp_gate = torch.nn.Parameter(torch.zeros(1))
  561. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  562. def forward(
  563. self,
  564. hidden_states: torch.Tensor,
  565. cross_attention_states: torch.Tensor,
  566. cross_attention_mask: torch.Tensor,
  567. attention_mask: torch.Tensor,
  568. full_text_row_masked_out_mask: tuple[torch.Tensor, torch.Tensor],
  569. position_ids: Optional[torch.LongTensor] = None,
  570. past_key_values: Optional[Cache] = None,
  571. use_cache: Optional[bool] = False,
  572. cache_position: Optional[torch.LongTensor] = None,
  573. position_embeddings: Optional[torch.Tensor] = None,
  574. **kwargs: Unpack[FlashAttentionKwargs],
  575. ) -> tuple[torch.Tensor]:
  576. residual = hidden_states
  577. hidden_states = self.input_layernorm(hidden_states)
  578. hidden_states, attn_weights = self.cross_attn(
  579. hidden_states=hidden_states,
  580. attention_mask=cross_attention_mask,
  581. cross_attention_states=cross_attention_states,
  582. past_key_values=past_key_values,
  583. cache_position=cache_position,
  584. **kwargs,
  585. )
  586. hidden_states = residual + self.cross_attn_attn_gate.tanh() * hidden_states
  587. residual = hidden_states
  588. hidden_states = self.post_attention_layernorm(hidden_states)
  589. hidden_states = self.mlp(hidden_states)
  590. if full_text_row_masked_out_mask is not None:
  591. hidden_states = full_text_row_masked_out_mask[:, 0] * hidden_states # type: ignore
  592. hidden_states = residual + self.cross_attn_mlp_gate.tanh() * hidden_states
  593. return hidden_states
  594. class MllamaRotaryEmbedding(nn.Module):
  595. inv_freq: torch.Tensor # fix linting for `register_buffer`
  596. def __init__(self, config: MllamaTextConfig, device=None):
  597. super().__init__()
  598. self.rope_type = config.rope_scaling["rope_type"]
  599. self.max_seq_len_cached = config.max_position_embeddings
  600. self.original_max_seq_len = config.max_position_embeddings
  601. self.config = config
  602. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  603. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  604. self.register_buffer("inv_freq", inv_freq, persistent=False)
  605. self.original_inv_freq = self.inv_freq
  606. @torch.no_grad()
  607. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  608. def forward(self, x, position_ids):
  609. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  610. position_ids_expanded = position_ids[:, None, :].float()
  611. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  612. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  613. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  614. emb = torch.cat((freqs, freqs), dim=-1)
  615. cos = emb.cos() * self.attention_scaling
  616. sin = emb.sin() * self.attention_scaling
  617. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  618. @auto_docstring
  619. class MllamaPreTrainedModel(PreTrainedModel):
  620. config: MllamaConfig
  621. base_model_prefix = ""
  622. supports_gradient_checkpointing = True
  623. _no_split_modules = [
  624. "MllamaVisionEncoderLayer",
  625. "MllamaCrossAttentionDecoderLayer",
  626. "MllamaSelfAttentionDecoderLayer",
  627. ]
  628. _can_compile_fullgraph = False # static cache cannot have different shapes for each layer
  629. _supports_sdpa = True
  630. _supports_flash_attn = True
  631. _supports_flex_attn = True
  632. _supports_attention_backend = True
  633. _can_record_outputs = {
  634. "hidden_states": [MllamaSelfAttentionDecoderLayer, MllamaCrossAttentionDecoderLayer],
  635. "attentions": [
  636. OutputRecorder(MllamaTextSelfAttention, index=1, layer_name="self_attn"),
  637. OutputRecorder(MllamaTextSelfAttention, index=1, layer_name="cross_attn"),
  638. OutputRecorder(MllamaTextCrossAttention, index=1, layer_name="cross_attn"),
  639. ],
  640. }
  641. def _init_weights(self, module):
  642. std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
  643. if isinstance(module, (nn.Linear, nn.Conv2d)):
  644. module.weight.data.normal_(mean=0.0, std=std)
  645. if module.bias is not None:
  646. module.bias.data.zero_()
  647. elif isinstance(module, nn.Embedding):
  648. module.weight.data.normal_(mean=0.0, std=std)
  649. if module.padding_idx is not None:
  650. module.weight.data[module.padding_idx].zero_()
  651. elif isinstance(module, nn.LayerNorm):
  652. module.weight.data.fill_(1.0)
  653. module.bias.data.zero_()
  654. elif isinstance(module, MllamaTextRMSNorm):
  655. module.weight.data.fill_(1.0)
  656. elif isinstance(module, MllamaVisionModel):
  657. nn.init.normal_(module.class_embedding.data, std=std)
  658. elif isinstance(module, MllamaPrecomputedPositionEmbedding):
  659. nn.init.normal_(module.embedding.data, std=std)
  660. nn.init.zeros_(module.gate.data)
  661. elif isinstance(module, MllamaVisionEncoderLayer) and module.is_gated:
  662. nn.init.normal_(module.gate_attn.data, std=std)
  663. nn.init.normal_(module.gate_ffn.data, std=std)
  664. elif isinstance(module, MllamaCrossAttentionDecoderLayer):
  665. module.cross_attn_attn_gate.data.zero_()
  666. module.cross_attn_mlp_gate.data.zero_()
  667. elif isinstance(module, MllamaPrecomputedAspectRatioEmbedding):
  668. if module.is_gated:
  669. module.gate.data.zero_()
  670. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
  671. def _update_causal_mask(
  672. self,
  673. attention_mask: Union[torch.Tensor, "BlockMask"],
  674. input_tensor: torch.Tensor,
  675. cache_position: torch.Tensor,
  676. past_key_values: Cache,
  677. output_attentions: bool = False,
  678. ):
  679. if self.config._attn_implementation == "flash_attention_2":
  680. if attention_mask is not None and (attention_mask == 0.0).any():
  681. return attention_mask
  682. return None
  683. if self.config._attn_implementation == "flex_attention":
  684. if isinstance(attention_mask, torch.Tensor):
  685. attention_mask = make_flex_block_causal_mask(attention_mask)
  686. return attention_mask
  687. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  688. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  689. # to infer the attention mask.
  690. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  691. using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
  692. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  693. if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
  694. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  695. attention_mask,
  696. inputs_embeds=input_tensor,
  697. past_key_values_length=past_seen_tokens,
  698. is_training=self.training,
  699. ):
  700. return None
  701. dtype = input_tensor.dtype
  702. sequence_length = input_tensor.shape[1]
  703. if using_compilable_cache:
  704. target_length = past_key_values.get_max_cache_shape()
  705. else:
  706. target_length = (
  707. attention_mask.shape[-1]
  708. if isinstance(attention_mask, torch.Tensor)
  709. else past_seen_tokens + sequence_length + 1
  710. )
  711. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  712. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  713. attention_mask,
  714. sequence_length=sequence_length,
  715. target_length=target_length,
  716. dtype=dtype,
  717. cache_position=cache_position,
  718. batch_size=input_tensor.shape[0],
  719. )
  720. if (
  721. self.config._attn_implementation == "sdpa"
  722. and attention_mask is not None
  723. and attention_mask.device.type in ["cuda", "xpu", "npu"]
  724. and not output_attentions
  725. ):
  726. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  727. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  728. # Details: https://github.com/pytorch/pytorch/issues/110213
  729. min_dtype = torch.finfo(dtype).min
  730. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  731. return causal_mask
  732. @staticmethod
  733. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  734. def _prepare_4d_causal_attention_mask_with_cache_position(
  735. attention_mask: torch.Tensor,
  736. sequence_length: int,
  737. target_length: int,
  738. dtype: torch.dtype,
  739. cache_position: torch.Tensor,
  740. batch_size: int,
  741. **kwargs,
  742. ):
  743. """
  744. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  745. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  746. Args:
  747. attention_mask (`torch.Tensor`):
  748. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  749. `(batch_size, 1, query_length, key_value_length)`.
  750. sequence_length (`int`):
  751. The sequence length being processed.
  752. target_length (`int`):
  753. The target length: when generating with static cache, the mask should be as long as the static cache,
  754. to account for the 0 padding, the part of the cache that is not filled yet.
  755. dtype (`torch.dtype`):
  756. The dtype to use for the 4D attention mask.
  757. cache_position (`torch.Tensor`):
  758. Indices depicting the position of the input sequence tokens in the sequence.
  759. batch_size (`torch.Tensor`):
  760. Batch size.
  761. """
  762. if attention_mask is not None and attention_mask.dim() == 4:
  763. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  764. causal_mask = attention_mask
  765. else:
  766. min_dtype = torch.finfo(dtype).min
  767. causal_mask = torch.full(
  768. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  769. )
  770. if sequence_length != 1:
  771. causal_mask = torch.triu(causal_mask, diagonal=1)
  772. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  773. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  774. if attention_mask is not None:
  775. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  776. mask_length = attention_mask.shape[-1]
  777. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  778. causal_mask.device
  779. )
  780. padding_mask = padding_mask == 0
  781. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  782. padding_mask, min_dtype
  783. )
  784. return causal_mask
  785. @auto_docstring(
  786. custom_intro="""
  787. The Mllama Vision Model which consists of two vision encoders.
  788. """
  789. )
  790. class MllamaVisionModel(MllamaPreTrainedModel):
  791. config: MllamaVisionConfig
  792. base_model_prefix = "vision_model"
  793. def __init__(self, config: MllamaVisionConfig):
  794. super().__init__(config)
  795. self.image_size = config.image_size
  796. self.patch_size = config.patch_size
  797. self.max_num_tiles = config.max_num_tiles
  798. self.hidden_size = config.hidden_size
  799. self.num_channels = config.num_channels
  800. self.intermediate_layers_indices = config.intermediate_layers_indices
  801. self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
  802. self.scale = config.hidden_size**-0.5
  803. self.patch_embedding = nn.Conv2d(
  804. in_channels=config.num_channels,
  805. out_channels=self.hidden_size,
  806. kernel_size=self.patch_size,
  807. stride=self.patch_size,
  808. padding="valid",
  809. bias=False,
  810. )
  811. self.class_embedding = nn.Parameter(self.scale * torch.randn(self.hidden_size))
  812. self.gated_positional_embedding = MllamaPrecomputedPositionEmbedding(config)
  813. self.pre_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
  814. self.post_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
  815. # layer norms
  816. self.layernorm_pre = nn.LayerNorm(self.hidden_size)
  817. self.layernorm_post = nn.LayerNorm(self.hidden_size)
  818. # encoders
  819. self.transformer = MllamaVisionEncoder(config, config.num_hidden_layers, is_gated=False)
  820. self.global_transformer = MllamaVisionEncoder(config, config.num_global_layers, is_gated=True)
  821. self.post_init()
  822. def get_input_embeddings(self):
  823. """
  824. This function is used to fetch the first embedding layer to activate grads on inputs.
  825. """
  826. return self.patch_embedding
  827. def apply_class_embedding(self, hidden_state: torch.Tensor) -> torch.Tensor:
  828. batch_size, _, hidden_size = hidden_state.shape
  829. class_embedding = self.class_embedding.expand(batch_size, 1, hidden_size)
  830. hidden_state = torch.cat([class_embedding, hidden_state], dim=1)
  831. return hidden_state
  832. @check_model_inputs()
  833. @auto_docstring
  834. def forward(
  835. self, pixel_values: torch.Tensor, aspect_ratio_ids: torch.Tensor, aspect_ratio_mask: torch.Tensor, **kwargs
  836. ) -> BaseModelOutput:
  837. r"""
  838. aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
  839. Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
  840. These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
  841. For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
  842. - An image with aspect ratio [1, 1] would have ID 1
  843. - An image with aspect ratio [1, 2] would have ID 2
  844. - An image with aspect ratio [2, 1] would have ID 3
  845. The id 0 is reserved for padding (i.e., no image).
  846. If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
  847. aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
  848. Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
  849. - 1 for tiles that are **not masked**,
  850. - 0 for tiles that are **masked**.
  851. Example:
  852. ```python
  853. >>> from PIL import Image
  854. >>> import requests
  855. >>> from transformers import AutoProcessor, MllamaVisionModel
  856. >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
  857. >>> model = MllamaVisionModel.from_pretrained(checkpoint)
  858. >>> processor = AutoProcessor.from_pretrained(checkpoint)
  859. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  860. >>> image = Image.open(requests.get(url, stream=True).raw)
  861. >>> inputs = processor(images=image, return_tensors="pt")
  862. >>> output = model(**inputs)
  863. >>> print(output.last_hidden_state.shape)
  864. torch.Size([1, 1, 4, 1025, 7680])
  865. ```
  866. """
  867. batch_size, num_concurrent_media, num_tiles, num_channels, height, width = pixel_values.shape
  868. pixel_values = pixel_values.reshape(batch_size * num_concurrent_media * num_tiles, num_channels, height, width)
  869. aspect_ratio_ids = aspect_ratio_ids.reshape(batch_size * num_concurrent_media, -1)
  870. # Patch embedding
  871. target_dtype = self.patch_embedding.weight.dtype
  872. target_device = self.patch_embedding.weight.device
  873. patch_embeds = self.patch_embedding(pixel_values.to(target_device, target_dtype))
  874. hidden_state = patch_embeds.flatten(2).transpose(1, 2)
  875. # Tile embeddings
  876. _, num_patches, dim = hidden_state.shape
  877. hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, -1, dim)
  878. hidden_state = self.pre_tile_positional_embedding(hidden_state, aspect_ratio_ids)
  879. # Add cls token
  880. hidden_state = hidden_state.reshape(batch_size * num_concurrent_media * num_tiles, num_patches, dim)
  881. hidden_state = self.apply_class_embedding(hidden_state)
  882. num_patches += 1
  883. # Position embeddings
  884. hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, num_patches, dim)
  885. hidden_state = self.gated_positional_embedding(hidden_state, aspect_ratio_ids)
  886. hidden_state = self.layernorm_pre(hidden_state)
  887. # Compute the number of tokens to pad
  888. num_padding_patches = (8 - (hidden_state.shape[-2] % 8)) % 8
  889. # Compute padding tuple for pad function
  890. padding = (0, 0, 0, num_padding_patches) # (pad_left, pad_right, pad_left for dim -2, pad_right for dim -2)
  891. # Pad the tensor
  892. hidden_state = F.pad(hidden_state, padding, mode="constant", value=0)
  893. slice_index = -num_padding_patches if num_padding_patches > 0 else None
  894. # Prepare attention mask
  895. attention_mask = aspect_ratio_mask.reshape(batch_size * num_concurrent_media, -1)
  896. attention_mask = _prepare_aspect_ratio_attention_mask(
  897. aspect_ratio_mask=attention_mask,
  898. num_patches=self.num_patches,
  899. target_length=hidden_state.shape[2],
  900. dtype=self.dtype,
  901. )
  902. # Apply encoder
  903. hidden_state = hidden_state.view(batch_size * num_concurrent_media, -1, dim)
  904. output = self.transformer(
  905. hidden_state,
  906. attention_mask=attention_mask,
  907. )
  908. hidden_state = output.last_hidden_state
  909. hidden_state = self.layernorm_post(hidden_state)
  910. # Apply global encoder
  911. hidden_state = hidden_state.reshape(
  912. batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
  913. )
  914. hidden_state = self.post_tile_positional_embedding(hidden_state, aspect_ratio_ids)
  915. hidden_state = hidden_state.reshape(
  916. batch_size * num_concurrent_media, num_tiles * (num_patches + num_padding_patches), dim
  917. )
  918. global_output = self.global_transformer(
  919. hidden_state,
  920. attention_mask=attention_mask,
  921. )
  922. hidden_state = global_output.last_hidden_state
  923. # Remove padding form hidden state
  924. hidden_state = hidden_state.reshape(
  925. batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
  926. )
  927. hidden_state = hidden_state[:, :, :slice_index]
  928. hidden_state = hidden_state.reshape(batch_size, num_concurrent_media, num_tiles, num_patches, dim)
  929. # Collect intermediate layer outputs from encoder output
  930. all_intermediate_hidden_states = [output.hidden_states[i] for i in self.intermediate_layers_indices]
  931. intermediate_hidden_states = torch.stack(all_intermediate_hidden_states, dim=-1)
  932. # Remove padding from intermediate hidden states
  933. intermediate_hidden_states = intermediate_hidden_states.reshape(
  934. batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, -1
  935. )
  936. intermediate_hidden_states = intermediate_hidden_states[:, :, :slice_index]
  937. intermediate_hidden_states = intermediate_hidden_states.reshape(
  938. batch_size, num_concurrent_media, num_tiles, num_patches, -1
  939. )
  940. # Concatenate final hidden state and intermediate hidden states
  941. hidden_state = torch.cat([hidden_state, intermediate_hidden_states], dim=-1)
  942. return BaseModelOutput(last_hidden_state=hidden_state)
  943. @auto_docstring(
  944. custom_intro="""
  945. The Mllama Text Model which consists of transformer with self and cross attention layers.
  946. """
  947. )
  948. class MllamaTextModel(MllamaPreTrainedModel):
  949. config: MllamaTextConfig
  950. base_model_prefix = "language_model.model"
  951. def __init__(self, config: MllamaTextConfig):
  952. super().__init__(config)
  953. self.padding_idx = config.pad_token_id
  954. self.vocab_size = config.vocab_size
  955. self.embed_tokens = nn.Embedding(config.vocab_size + 8, config.hidden_size, self.padding_idx)
  956. self.cross_attention_layers = config.cross_attention_layers
  957. layers = []
  958. for layer_idx in range(config.num_hidden_layers):
  959. if layer_idx in self.cross_attention_layers:
  960. layers.append(MllamaCrossAttentionDecoderLayer(config, layer_idx))
  961. else:
  962. layers.append(MllamaSelfAttentionDecoderLayer(config, layer_idx))
  963. self.layers = nn.ModuleList(layers)
  964. self.norm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  965. self.rotary_emb = MllamaRotaryEmbedding(config=config)
  966. self.gradient_checkpointing = False
  967. self.post_init()
  968. @check_model_inputs()
  969. @can_return_tuple
  970. @auto_docstring
  971. def forward(
  972. self,
  973. input_ids: Optional[torch.LongTensor] = None,
  974. attention_mask: Optional[torch.Tensor] = None,
  975. position_ids: Optional[torch.LongTensor] = None,
  976. cross_attention_states: Optional[torch.FloatTensor] = None,
  977. cross_attention_mask: Optional[torch.Tensor] = None,
  978. full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  979. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  980. inputs_embeds: Optional[torch.FloatTensor] = None,
  981. use_cache: Optional[bool] = None,
  982. cache_position: Optional[torch.LongTensor] = None,
  983. **kwargs: Unpack[FlashAttentionKwargs],
  984. ) -> BaseModelOutputWithPast:
  985. r"""
  986. cross_attention_states (`torch.FloatTensor`, *optional*):
  987. Output of the vision model, used for cross-attention. This tensor contains the processed image features that
  988. the language model will attend to.
  989. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
  990. Cross-attention mask to control the interaction between text tokens and image tiles.
  991. This 4D tensor defines which image tiles each text token should attend to.
  992. For each text token (in seq_length):
  993. - 1 indicates the token **should attend** to the corresponding image tile
  994. - 0 indicates the token **should not attend** to the corresponding image tile
  995. full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
  996. A tuple containing two tensors that mask out rows in the cross-attention mechanism:
  997. - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
  998. A value of 0 indicates that the corresponding text token's entire row in the cross-attention
  999. matrix should be masked out (all image tokens ignored).
  1000. - The second tensor has the same shape and is used internally to apply the masking during
  1001. the forward pass of cross-attention layers.
  1002. This mask is derived from the cross_attention_mask and is used to handle cases where a text token
  1003. should not attend to any image token.
  1004. Example:
  1005. ```python
  1006. >>> from transformers import AutoProcessor, MllamaTextModel
  1007. >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
  1008. >>> model = MllamaTextModel.from_pretrained(checkpoint)
  1009. >>> processor = AutoProcessor.from_pretrained(checkpoint)
  1010. >>> text = "<|image|>If I had to write a haiku for this one"
  1011. >>> inputs = processor(text=text, return_tensors="pt")
  1012. >>> output = model(**inputs)
  1013. >>> print(output.last_hidden_state.shape)
  1014. torch.Size([1, 13, 4096])
  1015. ```
  1016. """
  1017. use_cache = use_cache if use_cache is not None else self.config.use_cache
  1018. if (input_ids is None) ^ (inputs_embeds is not None):
  1019. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  1020. if inputs_embeds is None:
  1021. inputs_embeds = self.embed_tokens(input_ids)
  1022. hidden_states = inputs_embeds
  1023. if use_cache and past_key_values is None:
  1024. past_key_values = DynamicCache(config=self.config)
  1025. if cache_position is None:
  1026. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  1027. cache_position = torch.arange(
  1028. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  1029. )
  1030. if position_ids is None:
  1031. position_ids = cache_position.unsqueeze(0)
  1032. causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, past_key_values)
  1033. # create position embeddings to be shared across the decoder layers
  1034. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  1035. # decoder layers
  1036. for idx, decoder_layer in enumerate(self.layers):
  1037. # For text-only path we should skip cross attention layers.
  1038. # Let's check if the layer is cross attention layer and if we have cross attention states
  1039. # or cached cross attention states.
  1040. is_cross_attention_layer = idx in self.cross_attention_layers
  1041. is_cross_attention_cache_empty = past_key_values is None or (
  1042. past_key_values is not None and past_key_values.get_seq_length(idx) == 0
  1043. )
  1044. if is_cross_attention_layer and cross_attention_states is None and is_cross_attention_cache_empty:
  1045. continue
  1046. hidden_states = decoder_layer(
  1047. hidden_states,
  1048. cross_attention_states=cross_attention_states,
  1049. cross_attention_mask=cross_attention_mask,
  1050. attention_mask=causal_mask,
  1051. full_text_row_masked_out_mask=full_text_row_masked_out_mask,
  1052. position_ids=position_ids,
  1053. past_key_values=past_key_values,
  1054. use_cache=use_cache,
  1055. cache_position=cache_position,
  1056. position_embeddings=position_embeddings,
  1057. **kwargs,
  1058. )
  1059. hidden_states = self.norm(hidden_states)
  1060. return BaseModelOutputWithPast(
  1061. last_hidden_state=hidden_states,
  1062. past_key_values=past_key_values,
  1063. )
  1064. @auto_docstring(
  1065. custom_intro="""
  1066. The Mllama Text Model with a language modeling head on top.
  1067. """
  1068. )
  1069. class MllamaForCausalLM(MllamaPreTrainedModel, GenerationMixin):
  1070. config: MllamaTextConfig
  1071. _can_compile_fullgraph = True # only the LLM without cross attn can do compile
  1072. base_model_prefix = "language_model"
  1073. _tied_weights_keys = ["lm_head.weight"]
  1074. def __init__(self, config):
  1075. super().__init__(config.get_text_config())
  1076. self.text_config = config.get_text_config()
  1077. self.vocab_size = self.text_config.vocab_size
  1078. self.model = MllamaTextModel._from_config(self.text_config)
  1079. self.lm_head = nn.Linear(self.text_config.hidden_size, self.vocab_size, bias=False)
  1080. self.post_init()
  1081. @can_return_tuple
  1082. @auto_docstring
  1083. def forward(
  1084. self,
  1085. input_ids: Optional[torch.LongTensor] = None,
  1086. attention_mask: Optional[torch.Tensor] = None,
  1087. position_ids: Optional[torch.LongTensor] = None,
  1088. cross_attention_states: Optional[torch.LongTensor] = None,
  1089. cross_attention_mask: Optional[torch.LongTensor] = None,
  1090. full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  1091. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  1092. inputs_embeds: Optional[torch.FloatTensor] = None,
  1093. labels: Optional[torch.LongTensor] = None,
  1094. use_cache: Optional[bool] = None,
  1095. cache_position: Optional[torch.LongTensor] = None,
  1096. logits_to_keep: Union[int, torch.Tensor] = 0,
  1097. **kwargs: Unpack[TransformersKwargs],
  1098. ) -> Union[tuple, CausalLMOutputWithPast]:
  1099. r"""
  1100. cross_attention_states (`torch.FloatTensor`, *optional*):
  1101. Output of the vision model, used for cross-attention. This tensor contains the processed image features that
  1102. the language model will attend to.
  1103. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
  1104. Cross-attention mask to control the interaction between text tokens and image tiles.
  1105. This 4D tensor defines which image tiles each text token should attend to.
  1106. For each text token (in seq_length):
  1107. - 1 indicates the token **should attend** to the corresponding image tile
  1108. - 0 indicates the token **should not attend** to the corresponding image tile
  1109. full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
  1110. A tuple containing two tensors that mask out rows in the cross-attention mechanism:
  1111. - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
  1112. A value of 0 indicates that the corresponding text token's entire row in the cross-attention
  1113. matrix should be masked out (all image tokens ignored).
  1114. - The second tensor has the same shape and is used internally to apply the masking during
  1115. the forward pass of cross-attention layers.
  1116. This mask is derived from the cross_attention_mask and is used to handle cases where a text token
  1117. should not attend to any image token.
  1118. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1119. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1120. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1121. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1122. Example:
  1123. ```python
  1124. >>> from transformers import AutoTokenizer, MllamaForCausalLM
  1125. >>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
  1126. >>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
  1127. >>> prompt = "If I had to write a haiku, it would be:"
  1128. >>> inputs = tokenizer(prompt, return_tensors="pt")
  1129. >>> # Generate
  1130. >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
  1131. >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1132. >>> print(result)
  1133. If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
  1134. I love the idea of snowflakes gently falling, each one
  1135. ```
  1136. """
  1137. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  1138. outputs = self.model(
  1139. input_ids=input_ids,
  1140. cross_attention_states=cross_attention_states,
  1141. attention_mask=attention_mask,
  1142. position_ids=position_ids,
  1143. cross_attention_mask=cross_attention_mask,
  1144. full_text_row_masked_out_mask=full_text_row_masked_out_mask,
  1145. past_key_values=past_key_values,
  1146. inputs_embeds=inputs_embeds,
  1147. use_cache=use_cache,
  1148. cache_position=cache_position,
  1149. **kwargs,
  1150. )
  1151. hidden_states = outputs.last_hidden_state
  1152. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1153. logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
  1154. loss = None
  1155. if labels is not None:
  1156. loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
  1157. return CausalLMOutputWithPast(
  1158. loss=loss,
  1159. logits=logits,
  1160. past_key_values=outputs.past_key_values,
  1161. hidden_states=outputs.hidden_states,
  1162. attentions=outputs.attentions,
  1163. )
  1164. @auto_docstring(
  1165. custom_intro="""
  1166. The Mllama model which consists of a vision encoder and a language model without language modeling head.
  1167. """
  1168. )
  1169. class MllamaModel(MllamaPreTrainedModel):
  1170. _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
  1171. def __init__(self, config: MllamaConfig):
  1172. super().__init__(config)
  1173. self.vocab_size = config.text_config.vocab_size
  1174. self.hidden_size = config.text_config.hidden_size
  1175. self.max_num_tiles = config.vision_config.max_num_tiles
  1176. self.vision_output_dim = config.vision_config.vision_output_dim
  1177. self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
  1178. self.vision_model = MllamaVisionModel._from_config(config.vision_config)
  1179. self.language_model = MllamaTextModel._from_config(config.text_config)
  1180. self.multi_modal_projector = nn.Linear(
  1181. config.vision_config.vision_output_dim,
  1182. config.text_config.hidden_size,
  1183. bias=True,
  1184. )
  1185. self.post_init()
  1186. def get_input_embeddings(self):
  1187. return self.language_model.get_input_embeddings()
  1188. def set_input_embeddings(self, value):
  1189. self.language_model.set_input_embeddings(value)
  1190. def set_decoder(self, decoder):
  1191. self.language_model = decoder
  1192. def get_decoder(self):
  1193. return self.language_model
  1194. @check_model_inputs()
  1195. @can_return_tuple
  1196. @auto_docstring
  1197. def forward(
  1198. self,
  1199. input_ids: Optional[torch.LongTensor] = None,
  1200. pixel_values: Optional[torch.FloatTensor] = None,
  1201. aspect_ratio_mask: Optional[torch.Tensor] = None,
  1202. aspect_ratio_ids: Optional[torch.Tensor] = None,
  1203. attention_mask: Optional[torch.Tensor] = None,
  1204. cross_attention_mask: Optional[torch.Tensor] = None,
  1205. cross_attention_states: Optional[torch.Tensor] = None,
  1206. position_ids: Optional[torch.LongTensor] = None,
  1207. past_key_values: Optional[Cache] = None,
  1208. inputs_embeds: Optional[torch.FloatTensor] = None,
  1209. use_cache: Optional[bool] = None,
  1210. cache_position: Optional[torch.LongTensor] = None,
  1211. **kwargs: Unpack[FlashAttentionKwargs],
  1212. ) -> BaseModelOutputWithPast:
  1213. r"""
  1214. aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
  1215. Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
  1216. - 1 for tiles that are **not masked**,
  1217. - 0 for tiles that are **masked**.
  1218. aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
  1219. Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
  1220. These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
  1221. For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
  1222. - An image with aspect ratio [1, 1] would have ID 1
  1223. - An image with aspect ratio [1, 2] would have ID 2
  1224. - An image with aspect ratio [2, 1] would have ID 3
  1225. The id 0 is reserved for padding (i.e., no image).
  1226. If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
  1227. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
  1228. Cross-attention mask to control the interaction between text tokens and image tiles.
  1229. This 4D tensor defines which image tiles each text token should attend to.
  1230. For each text token (in seq_length):
  1231. - 1 indicates the token **should attend** to the corresponding image tile
  1232. - 0 indicates the token **should not attend** to the corresponding image tile
  1233. cross_attention_states (`torch.FloatTensor`, *optional*):
  1234. Output of the vision model, used for cross-attention. This tensor contains the processed image features that
  1235. the language model will attend to.
  1236. """
  1237. if (input_ids is None) ^ (inputs_embeds is not None):
  1238. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  1239. if pixel_values is not None and cross_attention_states is not None:
  1240. raise ValueError("`pixel_values` and `cross_attention_states` cannot be provided simultaneously")
  1241. if pixel_values is not None:
  1242. if aspect_ratio_ids is None:
  1243. raise ValueError("`aspect_ratio_ids` must be provided if `pixel_values` is provided")
  1244. # get vision tokens from vision model
  1245. vision_outputs = self.vision_model(
  1246. pixel_values=pixel_values,
  1247. aspect_ratio_ids=aspect_ratio_ids,
  1248. aspect_ratio_mask=aspect_ratio_mask,
  1249. )
  1250. cross_attention_states = vision_outputs.last_hidden_state
  1251. cross_attention_states = self.multi_modal_projector(cross_attention_states).reshape(
  1252. -1, cross_attention_states.shape[-2], self.hidden_size
  1253. )
  1254. if cross_attention_mask is not None:
  1255. cross_attention_mask, full_text_row_masked_out_mask = _prepare_cross_attention_mask(
  1256. cross_attention_mask,
  1257. num_vision_tokens=self.vision_model.num_patches,
  1258. dtype=self.dtype,
  1259. )
  1260. else:
  1261. full_text_row_masked_out_mask = None
  1262. if cross_attention_mask is not None and cache_position is not None:
  1263. cross_attention_mask = cross_attention_mask[:, :, cache_position]
  1264. full_text_row_masked_out_mask = full_text_row_masked_out_mask[:, :, cache_position]
  1265. outputs = self.language_model(
  1266. input_ids=input_ids,
  1267. attention_mask=attention_mask,
  1268. position_ids=position_ids,
  1269. cross_attention_states=cross_attention_states,
  1270. cross_attention_mask=cross_attention_mask,
  1271. full_text_row_masked_out_mask=full_text_row_masked_out_mask,
  1272. past_key_values=past_key_values,
  1273. use_cache=use_cache,
  1274. inputs_embeds=inputs_embeds,
  1275. cache_position=cache_position,
  1276. **kwargs,
  1277. )
  1278. return BaseModelOutputWithPast(
  1279. last_hidden_state=outputs.last_hidden_state,
  1280. past_key_values=outputs.past_key_values,
  1281. hidden_states=outputs.hidden_states,
  1282. attentions=outputs.attentions,
  1283. )
  1284. @auto_docstring(
  1285. custom_intro="""
  1286. The Mllama model which consists of a vision encoder and a language model.
  1287. """,
  1288. )
  1289. class MllamaForConditionalGeneration(MllamaPreTrainedModel, GenerationMixin):
  1290. _checkpoint_conversion_mapping = {
  1291. "^language_model.model": "model.language_model",
  1292. "^vision_model": "model.vision_model",
  1293. "^multi_modal_projector": "model.multi_modal_projector",
  1294. "^language_model.lm_head": "lm_head",
  1295. }
  1296. _tied_weights_keys = ["lm_head.weight"]
  1297. def __init__(self, config: MllamaConfig):
  1298. super().__init__(config)
  1299. self.model = MllamaModel(config)
  1300. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  1301. self.post_init()
  1302. def get_input_embeddings(self):
  1303. return self.model.get_input_embeddings()
  1304. def set_input_embeddings(self, value):
  1305. self.model.set_input_embeddings(value)
  1306. def set_decoder(self, decoder):
  1307. self.model.set_decoder(decoder)
  1308. def get_decoder(self):
  1309. return self.model.get_decoder()
  1310. # Make modules available through conditional class for BC
  1311. @property
  1312. def language_model(self):
  1313. return self.model.language_model
  1314. @property
  1315. def vision_model(self):
  1316. return self.model.vision_model
  1317. @can_return_tuple
  1318. @auto_docstring
  1319. def forward(
  1320. self,
  1321. input_ids: Optional[torch.LongTensor] = None,
  1322. pixel_values: Optional[torch.FloatTensor] = None,
  1323. aspect_ratio_mask: Optional[torch.Tensor] = None,
  1324. aspect_ratio_ids: Optional[torch.Tensor] = None,
  1325. attention_mask: Optional[torch.Tensor] = None,
  1326. cross_attention_mask: Optional[torch.Tensor] = None,
  1327. cross_attention_states: Optional[torch.Tensor] = None,
  1328. position_ids: Optional[torch.LongTensor] = None,
  1329. past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
  1330. inputs_embeds: Optional[torch.FloatTensor] = None,
  1331. labels: Optional[torch.LongTensor] = None,
  1332. use_cache: Optional[bool] = None,
  1333. cache_position: Optional[torch.LongTensor] = None,
  1334. logits_to_keep: Union[int, torch.Tensor] = 0,
  1335. **kwargs: Unpack[TransformersKwargs],
  1336. ) -> Union[tuple, CausalLMOutputWithPast]:
  1337. r"""
  1338. aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
  1339. Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:
  1340. - 1 for tiles that are **not masked**,
  1341. - 0 for tiles that are **masked**.
  1342. aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
  1343. Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
  1344. These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.
  1345. For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
  1346. - An image with aspect ratio [1, 1] would have ID 1
  1347. - An image with aspect ratio [1, 2] would have ID 2
  1348. - An image with aspect ratio [2, 1] would have ID 3
  1349. The id 0 is reserved for padding (i.e., no image).
  1350. If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
  1351. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
  1352. Cross-attention mask to control the interaction between text tokens and image tiles.
  1353. This 4D tensor defines which image tiles each text token should attend to.
  1354. For each text token (in seq_length):
  1355. - 1 indicates the token **should attend** to the corresponding image tile
  1356. - 0 indicates the token **should not attend** to the corresponding image tile
  1357. cross_attention_states (`torch.FloatTensor`, *optional*):
  1358. Output of the vision model, used for cross-attention. This tensor contains the processed image features that
  1359. the language model will attend to.
  1360. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1361. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1362. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1363. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1364. Example:
  1365. ```python
  1366. >>> from PIL import Image
  1367. >>> import requests
  1368. >>> from transformers import AutoProcessor, MllamaForConditionalGeneration
  1369. >>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
  1370. >>> model = MllamaForConditionalGeneration.from_pretrained(checkpoint)
  1371. >>> processor = AutoProcessor.from_pretrained(checkpoint)
  1372. >>> prompt = "<|image|>If I had to write a haiku for this one"
  1373. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  1374. >>> image = Image.open(requests.get(url, stream=True).raw)
  1375. >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
  1376. >>> # Generate
  1377. >>> output = model.generate(**inputs, max_new_tokens=15)
  1378. >>> prompt_len = inputs.input_ids.shape[-1]
  1379. >>> generated_ids = output[:, prompt_len:]
  1380. >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
  1381. >>> print(generated_text)
  1382. [', it would be:.\\nA stop sign in Chinatown.\\n']
  1383. ```
  1384. """
  1385. outputs = self.model(
  1386. input_ids=input_ids,
  1387. pixel_values=pixel_values,
  1388. aspect_ratio_mask=aspect_ratio_mask,
  1389. aspect_ratio_ids=aspect_ratio_ids,
  1390. cross_attention_mask=cross_attention_mask,
  1391. cross_attention_states=cross_attention_states,
  1392. attention_mask=attention_mask,
  1393. position_ids=position_ids,
  1394. past_key_values=past_key_values,
  1395. inputs_embeds=inputs_embeds,
  1396. use_cache=use_cache,
  1397. cache_position=cache_position,
  1398. **kwargs,
  1399. )
  1400. hidden_states = outputs.last_hidden_state
  1401. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1402. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1403. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1404. loss = None
  1405. if labels is not None:
  1406. loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs)
  1407. return CausalLMOutputWithPast(
  1408. loss=loss,
  1409. logits=logits,
  1410. past_key_values=outputs.past_key_values,
  1411. hidden_states=outputs.hidden_states,
  1412. attentions=outputs.attentions,
  1413. )
  1414. def prepare_inputs_for_generation(
  1415. self,
  1416. input_ids=None,
  1417. inputs_embeds=None,
  1418. attention_mask=None,
  1419. position_ids=None,
  1420. pixel_values=None,
  1421. aspect_ratio_ids=None,
  1422. aspect_ratio_mask=None,
  1423. cross_attention_mask=None,
  1424. past_key_values=None,
  1425. use_cache=False,
  1426. cache_position=None,
  1427. logits_to_keep=None,
  1428. **kwargs,
  1429. ):
  1430. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  1431. model_inputs = super().prepare_inputs_for_generation(
  1432. input_ids,
  1433. past_key_values=past_key_values,
  1434. use_cache=use_cache,
  1435. inputs_embeds=inputs_embeds,
  1436. position_ids=position_ids,
  1437. attention_mask=attention_mask,
  1438. pixel_values=pixel_values,
  1439. aspect_ratio_ids=aspect_ratio_ids,
  1440. aspect_ratio_mask=aspect_ratio_mask,
  1441. cross_attention_mask=cross_attention_mask,
  1442. cache_position=cache_position,
  1443. logits_to_keep=logits_to_keep,
  1444. **kwargs,
  1445. )
  1446. # If we're in pre-fill or cacheless decoding step, then we need pixel_values and aspect ratios
  1447. # to compute image hidden states, otherwise they are cached within each cross attn layer
  1448. if cache_position[0] != 0:
  1449. model_inputs["pixel_values"] = None
  1450. model_inputs["aspect_ratio_ids"] = None
  1451. model_inputs["aspect_ratio_mask"] = None
  1452. return model_inputs
  1453. def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
  1454. cross_attention_mask_prev = model_kwargs.get("cross_attention_mask", None)
  1455. model_kwargs = super()._update_model_kwargs_for_generation(
  1456. outputs=outputs,
  1457. model_kwargs=model_kwargs,
  1458. is_encoder_decoder=is_encoder_decoder,
  1459. **kwargs,
  1460. )
  1461. # add cross-attn mask for new token
  1462. if cross_attention_mask_prev is not None:
  1463. model_kwargs["cross_attention_mask"] = torch.cat(
  1464. [cross_attention_mask_prev, cross_attention_mask_prev[:, -1:, ...]], dim=1
  1465. )
  1466. return model_kwargs
  1467. __all__ = [
  1468. "MllamaForConditionalGeneration",
  1469. "MllamaForCausalLM",
  1470. "MllamaTextModel",
  1471. "MllamaVisionModel",
  1472. "MllamaPreTrainedModel",
  1473. "MllamaModel",
  1474. ]