modeling_aria.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2024 The Rhymes-AI Teams Authors and The 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 dataclasses import dataclass
  22. from typing import Callable, Optional, Union
  23. import torch
  24. from torch import nn
  25. from ...activations import ACT2FN
  26. from ...cache_utils import Cache, DynamicCache
  27. from ...generation import GenerationMixin
  28. from ...integrations import use_kernel_forward_from_hub
  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, ModelOutput
  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 check_model_inputs
  39. from ..auto import AutoModel
  40. from .configuration_aria import AriaConfig, AriaTextConfig
  41. @use_kernel_forward_from_hub("RMSNorm")
  42. class AriaTextRMSNorm(nn.Module):
  43. def __init__(self, hidden_size, eps=1e-6):
  44. """
  45. AriaTextRMSNorm is equivalent to T5LayerNorm
  46. """
  47. super().__init__()
  48. self.weight = nn.Parameter(torch.ones(hidden_size))
  49. self.variance_epsilon = eps
  50. def forward(self, hidden_states):
  51. input_dtype = hidden_states.dtype
  52. hidden_states = hidden_states.to(torch.float32)
  53. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  54. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  55. return self.weight * hidden_states.to(input_dtype)
  56. def extra_repr(self):
  57. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  58. class AriaProjectorMLP(nn.Module):
  59. """
  60. Feed-Forward Network module for the Aria Projector.
  61. Args:
  62. in_features (`int`):
  63. Input embedding dimension.
  64. hidden_features (`int`):
  65. Hidden dimension of the feed-forward network.
  66. output_dim (`int`):
  67. Output dimension.
  68. """
  69. def __init__(self, in_features, hidden_features, output_dim):
  70. super().__init__()
  71. self.linear_in = nn.Linear(in_features, hidden_features, bias=False)
  72. self.linear_out = nn.Linear(hidden_features, output_dim, bias=False)
  73. self.act = ACT2FN["gelu_new"]
  74. def forward(self, hidden_states):
  75. hidden_states = self.act(self.linear_in(hidden_states))
  76. hidden_states = self.linear_out(hidden_states)
  77. return hidden_states
  78. class AriaCrossAttention(nn.Module):
  79. """
  80. Aria Cross-Attention module.
  81. Args:
  82. config (`AriaConfig`):
  83. The configuration to use.
  84. """
  85. def __init__(self, config: AriaConfig, dropout_rate: float = 0):
  86. super().__init__()
  87. hidden_size = config.vision_config.hidden_size
  88. num_heads = config.vision_config.num_attention_heads
  89. self.num_heads = num_heads
  90. self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
  91. self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
  92. self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
  93. # Original code here: https://github.com/rhymes-ai/Aria/blob/719ff4e52b727443cba3793b0e27fe64e0244fe1/aria/model/projector.py#L48
  94. self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, batch_first=True)
  95. self.linear = nn.Linear(hidden_size, hidden_size)
  96. self.dropout = nn.Dropout(dropout_rate)
  97. self.layer_norm = nn.LayerNorm(hidden_size)
  98. self.layer_norm_kv = nn.LayerNorm(hidden_size)
  99. def forward(self, key_value_states, hidden_states, attn_mask=None):
  100. """
  101. Forward pass of the AriaCrossAttention module.
  102. Args:
  103. key_value_states (`torch.Tensor`):
  104. Input tensor for key and value.
  105. hidden_states (`torch.Tensor`):
  106. Input tensor for query.
  107. attn_mask (`torch.Tensor`, *optional*, defaults to None):
  108. Attention mask.
  109. Returns:
  110. torch.Tensor:
  111. Output tensor after cross-attention.
  112. """
  113. query = self.q_proj(self.layer_norm(hidden_states))
  114. key_value_states = self.layer_norm_kv(key_value_states)
  115. key = self.k_proj(key_value_states)
  116. value = self.v_proj(key_value_states)
  117. attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
  118. attn_output = self.dropout(self.linear(attn_output))
  119. return attn_output
  120. class AriaProjector(nn.Module):
  121. """
  122. Aria Projector module.
  123. This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
  124. Args:
  125. config (`AriaConfig`):
  126. Configuration object for the model.
  127. """
  128. def __init__(
  129. self,
  130. config: AriaConfig,
  131. ):
  132. super().__init__()
  133. self.patch_to_query_dict = config.projector_patch_to_query_dict
  134. self.in_features = config.vision_config.hidden_size
  135. self.num_heads = config.vision_config.num_attention_heads
  136. self.kv_dim = config.vision_config.hidden_size
  137. self.hidden_features = config.text_config.hidden_size
  138. self.output_dim = config.text_config.hidden_size
  139. self.query = nn.Parameter(torch.zeros(config.max_value_projector_patch_to_query_dict, self.in_features))
  140. self.cross_attn = AriaCrossAttention(config)
  141. self.layer_norm = nn.LayerNorm(self.in_features)
  142. self.feed_forward = AriaProjectorMLP(self.in_features, self.hidden_features, self.output_dim)
  143. def forward(self, key_value_states: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
  144. """
  145. Forward pass of the Projector module.
  146. Args:
  147. key_value_states (`torch.Tensor`):
  148. Input tensor of shape (batch_size, num_patches, kv_dim).
  149. attn_mask (`torch.Tensor`, *optional*, default is None):
  150. Attention mask.
  151. Returns:
  152. `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
  153. """
  154. batch_size, num_patches = key_value_states.shape[0], key_value_states.shape[1]
  155. if num_patches not in self.patch_to_query_dict:
  156. raise KeyError(
  157. f"Number of patches {num_patches} not found in patch_to_query_dict amongst possible values {self.patch_to_query_dict.keys()}."
  158. )
  159. query_num = self.patch_to_query_dict[num_patches]
  160. queries = self.query[:query_num].unsqueeze(0).repeat(batch_size, 1, 1)
  161. if attn_mask is not None:
  162. attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
  163. attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
  164. attention_out = self.cross_attn(key_value_states, queries, attn_mask=attn_mask)
  165. out = self.feed_forward(self.layer_norm(attention_out))
  166. return out
  167. class AriaSharedExpertsMLP(nn.Module):
  168. """
  169. Shared Expert MLP for shared experts.
  170. Unlike routed experts, shared experts process all tokens without routing.
  171. This class reconfigures the intermediate size in comparison to the LlamaMLP.
  172. Args:
  173. config (`AriaTextConfig`): Configuration object for the Aria language model.
  174. """
  175. def __init__(self, config: AriaTextConfig):
  176. super().__init__()
  177. self.config = config
  178. self.hidden_size = config.hidden_size
  179. self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
  180. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  181. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  182. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
  183. self.act_fn = ACT2FN[config.hidden_act]
  184. def forward(self, x):
  185. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  186. return down_proj
  187. def sequential_experts_gemm(token_states, expert_weights, tokens_per_expert):
  188. """
  189. Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
  190. Args:
  191. token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
  192. expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
  193. tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
  194. Returns:
  195. torch.Tensor: Output tensor of shape (num_tokens, out_features).
  196. """
  197. num_tokens = token_states.shape[0]
  198. out_features = expert_weights.shape[-1]
  199. output = torch.zeros(num_tokens, out_features, dtype=token_states.dtype, device=token_states.device)
  200. cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
  201. # Insert zero at the beginning for offset index's convenience
  202. zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
  203. cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
  204. for expert_num in range(expert_weights.shape[0]):
  205. start = cumsum_num_tokens[expert_num]
  206. end = cumsum_num_tokens[expert_num + 1]
  207. tokens = token_states[start:end]
  208. out = torch.matmul(tokens, expert_weights[expert_num])
  209. output[start:end] = out
  210. return output
  211. class AriaGroupedExpertsGemm(nn.Module):
  212. """
  213. Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
  214. This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
  215. for optimized performance. If the grouped_gemm library is not installed, it gracefully
  216. falls back to a sequential GEMM implementation, which may be slower but ensures
  217. functionality.
  218. Args:
  219. in_features (`int`):
  220. Number of input features.
  221. out_features (`int`):
  222. Number of output features.
  223. groups (`int`):
  224. Number of expert groups.
  225. """
  226. def __init__(self, in_features, out_features, groups):
  227. super().__init__()
  228. self.in_features = in_features
  229. self.out_features = out_features
  230. self.groups = groups
  231. self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))
  232. def forward(self, input, tokens_per_expert):
  233. """
  234. Perform grouped matrix multiplication.
  235. Args:
  236. input (`torch.Tensor`):
  237. Input tensor of shape (num_tokens, in_features).
  238. tokens_per_expert (`torch.Tensor`):
  239. Number of tokens assigned to each expert.
  240. Returns:
  241. torch.Tensor: Output tensor of shape (num_tokens, out_features).
  242. """
  243. return sequential_experts_gemm(
  244. input,
  245. self.weight,
  246. tokens_per_expert.cpu(),
  247. )
  248. class AriaGroupedExpertsMLP(nn.Module):
  249. """
  250. Grouped MLP module for Mixture of Experts.
  251. Args:
  252. config (`AriaTextConfig`):
  253. Configuration object for the model.
  254. """
  255. def __init__(self, config: AriaTextConfig) -> None:
  256. super().__init__()
  257. self.config = config
  258. self.fc1 = AriaGroupedExpertsGemm(config.hidden_size, config.intermediate_size * 2, config.moe_num_experts)
  259. self.fc2 = AriaGroupedExpertsGemm(config.intermediate_size, config.hidden_size, config.moe_num_experts)
  260. def forward(self, permuted_tokens, tokens_per_expert):
  261. """
  262. Forward pass of the Grouped MLP.
  263. Args:
  264. permuted_tokens (torch.Tensor): Permuted input tokens.
  265. tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
  266. Returns:
  267. torch.Tensor: Output tensor after passing through the MLP.
  268. """
  269. fc1_output = self.fc1(permuted_tokens, tokens_per_expert)
  270. projection, gate = torch.chunk(fc1_output, 2, dim=-1)
  271. fc1_output = nn.functional.silu(projection) * gate
  272. fc2_output = self.fc2(fc1_output, tokens_per_expert)
  273. return fc2_output
  274. # Token permutation adapted from https://github.com/NVIDIA/Megatron-LM/blob/54f1f78529cbc2b9cddad313e7f9d96ac0420a27/megatron/core/transformer/moe/token_dispatcher.py#L291-L587
  275. class AriaTextMoELayer(nn.Module):
  276. """
  277. Aria Text Mixture of Experts (MoE) Layer.
  278. This layer applies a gating mechanism to route input tokens to different experts.
  279. Args:
  280. config (`AriaTextConfig`):
  281. Configuration object for the text component of the model.
  282. """
  283. def __init__(self, config: AriaTextConfig):
  284. super().__init__()
  285. self.router = nn.Linear(config.hidden_size, config.moe_num_experts, bias=False)
  286. self.experts = AriaGroupedExpertsMLP(config)
  287. self.shared_experts = AriaSharedExpertsMLP(config)
  288. self.config = config
  289. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  290. """
  291. Forward pass of the MoE Layer.
  292. Args:
  293. hidden_states (`torch.Tensor`):
  294. Input tensor of shape (batch_size, sequence_length, hidden_size).
  295. Returns:
  296. torch.Tensor: Output tensor after passing through the MoE layer.
  297. Process:
  298. 1. Route tokens to experts using the router.
  299. 2. Permute tokens based on routing decisions.
  300. 3. Process tokens through experts.
  301. 4. Unpermute and combine expert outputs.
  302. 5. Add shared expert output to the final result.
  303. """
  304. original_shape = hidden_states.shape
  305. hidden_states = hidden_states.view(-1, hidden_states.size(-1))
  306. # Top K Routing
  307. logits = self.router(hidden_states)
  308. top_logits, top_indices = torch.topk(logits, k=self.config.moe_topk, dim=1)
  309. scores = nn.functional.softmax(top_logits, dim=-1)
  310. original_dtype = top_indices.dtype
  311. tokens_per_expert = torch.histc(
  312. top_indices.flatten().to(torch.float32),
  313. bins=self.config.moe_num_experts,
  314. min=0,
  315. max=self.config.moe_num_experts - 1,
  316. ).to(original_dtype)
  317. indices = top_indices
  318. # Token permutation
  319. flatten_indices = indices.view(-1)
  320. sorted_indices = torch.argsort(flatten_indices)
  321. permuted_tokens = hidden_states.index_select(0, sorted_indices // self.config.moe_topk)
  322. # Process through experts
  323. expert_output = self.experts(permuted_tokens, tokens_per_expert)
  324. # Token unpermutation
  325. unpermuted_tokens = torch.zeros(
  326. (scores.shape[0] * self.config.moe_topk, expert_output.size(1)),
  327. dtype=expert_output.dtype,
  328. device=expert_output.device,
  329. )
  330. unpermuted_tokens.index_copy_(0, sorted_indices, expert_output)
  331. unpermuted_tokens = unpermuted_tokens.view(-1, self.config.moe_topk, expert_output.size(1))
  332. output = (unpermuted_tokens * scores.unsqueeze(-1)).sum(dim=1).view(original_shape)
  333. # Add shared expert output
  334. shared_expert_output = self.shared_experts(hidden_states.view(original_shape))
  335. return output + shared_expert_output
  336. def rotate_half(x):
  337. """Rotates half the hidden dims of the input."""
  338. x1 = x[..., : x.shape[-1] // 2]
  339. x2 = x[..., x.shape[-1] // 2 :]
  340. return torch.cat((-x2, x1), dim=-1)
  341. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  342. """Applies Rotary Position Embedding to the query and key tensors.
  343. Args:
  344. q (`torch.Tensor`): The query tensor.
  345. k (`torch.Tensor`): The key tensor.
  346. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  347. sin (`torch.Tensor`): The sine part of the rotary embedding.
  348. position_ids (`torch.Tensor`, *optional*):
  349. Deprecated and unused.
  350. unsqueeze_dim (`int`, *optional*, defaults to 1):
  351. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  352. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  353. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  354. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  355. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  356. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  357. Returns:
  358. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  359. """
  360. cos = cos.unsqueeze(unsqueeze_dim)
  361. sin = sin.unsqueeze(unsqueeze_dim)
  362. q_embed = (q * cos) + (rotate_half(q) * sin)
  363. k_embed = (k * cos) + (rotate_half(k) * sin)
  364. return q_embed, k_embed
  365. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  366. """
  367. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  368. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  369. """
  370. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  371. if n_rep == 1:
  372. return hidden_states
  373. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  374. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  375. def eager_attention_forward(
  376. module: nn.Module,
  377. query: torch.Tensor,
  378. key: torch.Tensor,
  379. value: torch.Tensor,
  380. attention_mask: Optional[torch.Tensor],
  381. scaling: float,
  382. dropout: float = 0.0,
  383. **kwargs: Unpack[TransformersKwargs],
  384. ):
  385. key_states = repeat_kv(key, module.num_key_value_groups)
  386. value_states = repeat_kv(value, module.num_key_value_groups)
  387. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  388. if attention_mask is not None:
  389. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  390. attn_weights = attn_weights + causal_mask
  391. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  392. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  393. attn_output = torch.matmul(attn_weights, value_states)
  394. attn_output = attn_output.transpose(1, 2).contiguous()
  395. return attn_output, attn_weights
  396. class AriaTextAttention(nn.Module):
  397. """Multi-headed attention from 'Attention Is All You Need' paper"""
  398. def __init__(self, config: AriaTextConfig, layer_idx: int):
  399. super().__init__()
  400. self.config = config
  401. self.layer_idx = layer_idx
  402. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  403. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  404. self.scaling = self.head_dim**-0.5
  405. self.attention_dropout = config.attention_dropout
  406. self.is_causal = True
  407. self.q_proj = nn.Linear(
  408. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  409. )
  410. self.k_proj = nn.Linear(
  411. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  412. )
  413. self.v_proj = nn.Linear(
  414. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  415. )
  416. self.o_proj = nn.Linear(
  417. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  418. )
  419. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  420. def forward(
  421. self,
  422. hidden_states: torch.Tensor,
  423. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  424. attention_mask: Optional[torch.Tensor],
  425. past_key_values: Optional[Cache] = None,
  426. cache_position: Optional[torch.LongTensor] = None,
  427. **kwargs: Unpack[TransformersKwargs],
  428. ) -> tuple[torch.Tensor, torch.Tensor]:
  429. input_shape = hidden_states.shape[:-1]
  430. hidden_shape = (*input_shape, -1, self.head_dim)
  431. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  432. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  433. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  434. cos, sin = position_embeddings
  435. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  436. if past_key_values is not None:
  437. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  438. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  439. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  440. attention_interface: Callable = eager_attention_forward
  441. if self.config._attn_implementation != "eager":
  442. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  443. attn_output, attn_weights = attention_interface(
  444. self,
  445. query_states,
  446. key_states,
  447. value_states,
  448. attention_mask,
  449. dropout=0.0 if not self.training else self.attention_dropout,
  450. scaling=self.scaling,
  451. **kwargs,
  452. )
  453. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  454. attn_output = self.o_proj(attn_output)
  455. return attn_output, attn_weights
  456. class AriaTextDecoderLayer(GradientCheckpointingLayer):
  457. """
  458. Aria Text Decoder Layer.
  459. This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.
  460. Args:
  461. config (`AriaTextConfig`):
  462. Configuration object for the text component of the model.
  463. layer_idx (`int`):
  464. Index of the layer.
  465. """
  466. def __init__(self, config: AriaTextConfig, layer_idx: int):
  467. super().__init__()
  468. self.hidden_size = config.hidden_size
  469. self.self_attn = AriaTextAttention(config=config, layer_idx=layer_idx)
  470. self.mlp = AriaTextMoELayer(config)
  471. self.input_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  472. self.post_attention_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  473. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  474. def forward(
  475. self,
  476. hidden_states: torch.Tensor,
  477. attention_mask: Optional[torch.Tensor] = None,
  478. position_ids: Optional[torch.LongTensor] = None,
  479. past_key_values: Optional[Cache] = None,
  480. use_cache: Optional[bool] = False,
  481. cache_position: Optional[torch.LongTensor] = None,
  482. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  483. **kwargs: Unpack[TransformersKwargs],
  484. ) -> torch.Tensor:
  485. residual = hidden_states
  486. hidden_states = self.input_layernorm(hidden_states)
  487. # Self Attention
  488. hidden_states, _ = self.self_attn(
  489. hidden_states=hidden_states,
  490. attention_mask=attention_mask,
  491. position_ids=position_ids,
  492. past_key_values=past_key_values,
  493. use_cache=use_cache,
  494. cache_position=cache_position,
  495. position_embeddings=position_embeddings,
  496. **kwargs,
  497. )
  498. hidden_states = residual + hidden_states
  499. # Fully Connected
  500. residual = hidden_states
  501. hidden_states = self.post_attention_layernorm(hidden_states)
  502. hidden_states = self.mlp(hidden_states)
  503. hidden_states = residual + hidden_states
  504. return hidden_states
  505. @auto_docstring
  506. class AriaTextPreTrainedModel(PreTrainedModel):
  507. config: AriaTextConfig
  508. base_model_prefix = "model"
  509. _no_split_modules = ["AriaTextDecoderLayer", "AriaGroupedExpertsGemm"]
  510. supports_gradient_checkpointing = True
  511. _skip_keys_device_placement = "past_key_values"
  512. _supports_flash_attn = True
  513. _supports_sdpa = True
  514. _supports_attention_backend = True
  515. _can_record_outputs = {
  516. "hidden_states": AriaTextDecoderLayer,
  517. "attentions": AriaTextAttention,
  518. }
  519. def _init_weights(self, module):
  520. super()._init_weights(module)
  521. if isinstance(module, AriaGroupedExpertsGemm):
  522. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  523. @auto_docstring
  524. class AriaPreTrainedModel(PreTrainedModel):
  525. config: AriaConfig
  526. base_model_prefix = ""
  527. supports_gradient_checkpointing = True
  528. _no_split_modules = ["AriaDecoderLayer"]
  529. _skip_keys_device_placement = ["past_key_values"]
  530. _supports_flash_attn = True
  531. _supports_sdpa = True
  532. _supports_flex_attn = True
  533. _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing)
  534. _supports_attention_backend = True
  535. _can_record_outputs = {
  536. "hidden_states": AriaTextDecoderLayer,
  537. "attentions": AriaTextAttention,
  538. }
  539. def _init_weights(self, module):
  540. super()._init_weights(module)
  541. if isinstance(module, AriaProjector):
  542. nn.init.trunc_normal_(module.query, std=self.config.initializer_range)
  543. class AriaTextRotaryEmbedding(nn.Module):
  544. inv_freq: torch.Tensor # fix linting for `register_buffer`
  545. def __init__(self, config: AriaTextConfig, device=None):
  546. super().__init__()
  547. # BC: "rope_type" was originally "type"
  548. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  549. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  550. else:
  551. self.rope_type = "default"
  552. self.max_seq_len_cached = config.max_position_embeddings
  553. self.original_max_seq_len = config.max_position_embeddings
  554. self.config = config
  555. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  556. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  557. self.register_buffer("inv_freq", inv_freq, persistent=False)
  558. self.original_inv_freq = self.inv_freq
  559. @torch.no_grad()
  560. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  561. def forward(self, x, position_ids):
  562. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  563. position_ids_expanded = position_ids[:, None, :].float()
  564. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  565. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  566. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  567. emb = torch.cat((freqs, freqs), dim=-1)
  568. cos = emb.cos() * self.attention_scaling
  569. sin = emb.sin() * self.attention_scaling
  570. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  571. @auto_docstring
  572. class AriaTextModel(AriaTextPreTrainedModel):
  573. def __init__(self, config: AriaTextConfig):
  574. super().__init__(config)
  575. self.padding_idx = config.pad_token_id
  576. self.vocab_size = config.vocab_size
  577. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  578. self.layers = nn.ModuleList(
  579. [AriaTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  580. )
  581. self.norm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  582. self.rotary_emb = AriaTextRotaryEmbedding(config=config)
  583. self.gradient_checkpointing = False
  584. # Initialize weights and apply final processing
  585. self.post_init()
  586. @check_model_inputs()
  587. @auto_docstring
  588. def forward(
  589. self,
  590. input_ids: Optional[torch.LongTensor] = None,
  591. attention_mask: Optional[torch.Tensor] = None,
  592. position_ids: Optional[torch.LongTensor] = None,
  593. past_key_values: Optional[Cache] = None,
  594. inputs_embeds: Optional[torch.FloatTensor] = None,
  595. cache_position: Optional[torch.LongTensor] = None,
  596. use_cache: Optional[bool] = None,
  597. **kwargs: Unpack[TransformersKwargs],
  598. ) -> BaseModelOutputWithPast:
  599. if (input_ids is None) ^ (inputs_embeds is not None):
  600. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  601. if inputs_embeds is None:
  602. inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
  603. if use_cache and past_key_values is None:
  604. past_key_values = DynamicCache(config=self.config)
  605. if cache_position is None:
  606. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  607. cache_position: torch.Tensor = torch.arange(
  608. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  609. )
  610. if position_ids is None:
  611. position_ids = cache_position.unsqueeze(0)
  612. causal_mask = create_causal_mask(
  613. config=self.config,
  614. input_embeds=inputs_embeds,
  615. attention_mask=attention_mask,
  616. cache_position=cache_position,
  617. past_key_values=past_key_values,
  618. position_ids=position_ids,
  619. )
  620. hidden_states = inputs_embeds
  621. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  622. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  623. hidden_states = decoder_layer(
  624. hidden_states,
  625. attention_mask=causal_mask,
  626. position_ids=position_ids,
  627. past_key_values=past_key_values,
  628. cache_position=cache_position,
  629. position_embeddings=position_embeddings,
  630. **kwargs,
  631. )
  632. hidden_states = self.norm(hidden_states)
  633. return BaseModelOutputWithPast(
  634. last_hidden_state=hidden_states,
  635. past_key_values=past_key_values,
  636. )
  637. @auto_docstring
  638. class AriaTextForCausalLM(AriaTextPreTrainedModel, GenerationMixin):
  639. _tied_weights_keys = ["lm_head.weight"]
  640. _tp_plan = {"lm_head": "colwise_rep"}
  641. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  642. def __init__(self, config: AriaTextConfig):
  643. super().__init__(config)
  644. self.model = AriaTextModel(config)
  645. self.vocab_size = config.vocab_size
  646. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  647. # Initialize weights and apply final processing
  648. self.post_init()
  649. @auto_docstring
  650. def forward(
  651. self,
  652. input_ids: Optional[torch.LongTensor] = None,
  653. attention_mask: Optional[torch.Tensor] = None,
  654. position_ids: Optional[torch.LongTensor] = None,
  655. past_key_values: Optional[Cache] = None,
  656. inputs_embeds: Optional[torch.FloatTensor] = None,
  657. labels: Optional[torch.LongTensor] = None,
  658. use_cache: Optional[bool] = None,
  659. cache_position: Optional[torch.LongTensor] = None,
  660. logits_to_keep: Union[int, torch.Tensor] = 0,
  661. **kwargs: Unpack[TransformersKwargs],
  662. ) -> CausalLMOutputWithPast:
  663. r"""
  664. Example:
  665. ```python
  666. >>> from transformers import AutoTokenizer, AriaTextForCausalLM
  667. >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
  668. >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
  669. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  670. >>> inputs = tokenizer(prompt, return_tensors="pt")
  671. >>> # Generate
  672. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  673. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  674. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  675. ```"""
  676. outputs: BaseModelOutputWithPast = self.model(
  677. input_ids=input_ids,
  678. attention_mask=attention_mask,
  679. position_ids=position_ids,
  680. past_key_values=past_key_values,
  681. inputs_embeds=inputs_embeds,
  682. use_cache=use_cache,
  683. cache_position=cache_position,
  684. **kwargs,
  685. )
  686. hidden_states = outputs.last_hidden_state
  687. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  688. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  689. logits = self.lm_head(hidden_states[:, slice_indices, :])
  690. loss = None
  691. if labels is not None:
  692. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  693. return CausalLMOutputWithPast(
  694. loss=loss,
  695. logits=logits,
  696. past_key_values=outputs.past_key_values,
  697. hidden_states=outputs.hidden_states,
  698. attentions=outputs.attentions,
  699. )
  700. @dataclass
  701. @auto_docstring(
  702. custom_intro="""
  703. Base class for Aria causal language model (or autoregressive) outputs.
  704. """
  705. )
  706. class AriaCausalLMOutputWithPast(ModelOutput):
  707. r"""
  708. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  709. Language modeling loss (for next-token prediction).
  710. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  711. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  712. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  713. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  714. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  715. `past_key_values` input) to speed up sequential decoding.
  716. image_hidden_states (`torch.FloatTensor`, *optional*):
  717. A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
  718. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
  719. """
  720. loss: Optional[torch.FloatTensor] = None
  721. logits: Optional[torch.FloatTensor] = None
  722. past_key_values: Optional[Cache] = None
  723. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  724. attentions: Optional[tuple[torch.FloatTensor]] = None
  725. image_hidden_states: Optional[torch.FloatTensor] = None
  726. @dataclass
  727. @auto_docstring(
  728. custom_intro="""
  729. Base class for Aria outputs, with hidden states and attentions.
  730. """
  731. )
  732. class AriaModelOutputWithPast(BaseModelOutputWithPast):
  733. r"""
  734. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  735. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  736. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  737. `past_key_values` input) to speed up sequential decoding.
  738. image_hidden_states (`torch.FloatTensor`, *optional*):
  739. A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
  740. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
  741. """
  742. image_hidden_states: Optional[torch.FloatTensor] = None
  743. @auto_docstring(
  744. custom_intro="""
  745. The Aria model which consists of a vision backbone and a language model, without a language modeling head.
  746. """
  747. )
  748. class AriaModel(AriaPreTrainedModel):
  749. _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
  750. def __init__(self, config: AriaConfig):
  751. super().__init__(config)
  752. self.vision_tower = AutoModel.from_config(config.vision_config)
  753. self.multi_modal_projector = AriaProjector(config)
  754. self.language_model = AutoModel.from_config(config.text_config)
  755. self.post_init()
  756. def get_input_embeddings(self):
  757. return self.language_model.get_input_embeddings()
  758. def set_input_embeddings(self, value):
  759. self.language_model.set_input_embeddings(value)
  760. def set_decoder(self, decoder):
  761. self.language_model = decoder
  762. def get_decoder(self):
  763. return self.language_model
  764. def get_image_features(
  765. self,
  766. pixel_values: torch.FloatTensor,
  767. pixel_mask: Optional[torch.FloatTensor] = None,
  768. vision_feature_layer: int = -1,
  769. ):
  770. """
  771. Obtains image last hidden states from the vision tower and apply multimodal projection.
  772. Args:
  773. pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
  774. The tensors corresponding to the input images.
  775. pixel_mask (`torch.FloatTensor]`, *optional*):
  776. The tensors corresponding to the input image mask.
  777. vision_feature_layer (`Union[int, list[int]]`, *optional*):
  778. The index of the layer to select the vision feature. If multiple indices are provided,
  779. the vision feature of the corresponding indices will be concatenated to form the
  780. vision features.
  781. Returns:
  782. image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
  783. """
  784. vision_feature_layer = (
  785. vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
  786. )
  787. patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
  788. image_outputs = self.vision_tower(
  789. pixel_values, patch_attention_mask=patch_attention_mask, output_hidden_states=True
  790. )
  791. image_attn_mask = None
  792. if patch_attention_mask is not None:
  793. flattened_mask = patch_attention_mask.flatten(1)
  794. image_attn_mask = torch.logical_not(flattened_mask)
  795. selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
  796. image_features = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
  797. return image_features
  798. def get_placeholder_mask(
  799. self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
  800. ):
  801. """
  802. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  803. equal to the length of multimodal features. If the lengths are different, an error is raised.
  804. """
  805. if input_ids is None:
  806. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  807. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  808. )
  809. special_image_mask = special_image_mask.all(-1)
  810. else:
  811. special_image_mask = input_ids == self.config.image_token_id
  812. n_image_tokens = special_image_mask.sum()
  813. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  814. n_image_features = image_features.shape[0] * image_features.shape[1]
  815. if inputs_embeds[special_image_mask].numel() != image_features.numel():
  816. raise ValueError(
  817. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
  818. )
  819. return special_image_mask
  820. @can_return_tuple
  821. @auto_docstring
  822. def forward(
  823. self,
  824. input_ids: Optional[torch.LongTensor] = None,
  825. pixel_values: Optional[torch.FloatTensor] = None,
  826. pixel_mask: Optional[torch.LongTensor] = None,
  827. attention_mask: Optional[torch.Tensor] = None,
  828. position_ids: Optional[torch.LongTensor] = None,
  829. past_key_values: Optional[Cache] = None,
  830. inputs_embeds: Optional[torch.FloatTensor] = None,
  831. use_cache: Optional[bool] = None,
  832. cache_position: Optional[torch.LongTensor] = None,
  833. **kwargs: Unpack[FlashAttentionKwargs],
  834. ) -> Union[tuple, AriaModelOutputWithPast]:
  835. if inputs_embeds is None:
  836. inputs_embeds = self.get_input_embeddings()(input_ids)
  837. # 2. Merge text and images
  838. if pixel_values is not None and inputs_embeds.shape[1] != 1:
  839. image_features = self.get_image_features(
  840. pixel_values=pixel_values,
  841. pixel_mask=pixel_mask,
  842. vision_feature_layer=self.config.vision_feature_layer,
  843. )
  844. image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
  845. special_image_mask = self.get_placeholder_mask(
  846. input_ids, inputs_embeds=inputs_embeds, image_features=image_features
  847. )
  848. inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
  849. outputs = self.language_model(
  850. attention_mask=attention_mask,
  851. position_ids=position_ids,
  852. past_key_values=past_key_values,
  853. inputs_embeds=inputs_embeds,
  854. use_cache=use_cache,
  855. cache_position=cache_position,
  856. **kwargs,
  857. )
  858. return AriaModelOutputWithPast(
  859. last_hidden_state=outputs.last_hidden_state,
  860. past_key_values=outputs.past_key_values if use_cache else None,
  861. hidden_states=outputs.hidden_states,
  862. attentions=outputs.attentions,
  863. image_hidden_states=image_features if pixel_values is not None else None,
  864. )
  865. def _create_patch_attention_mask(self, pixel_mask):
  866. if pixel_mask is None:
  867. return None
  868. patches_subgrid = pixel_mask.unfold(
  869. dimension=1,
  870. size=self.vision_tower.config.patch_size,
  871. step=self.vision_tower.config.patch_size,
  872. )
  873. patches_subgrid = patches_subgrid.unfold(
  874. dimension=2,
  875. size=self.vision_tower.config.patch_size,
  876. step=self.vision_tower.config.patch_size,
  877. )
  878. return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
  879. @auto_docstring(
  880. custom_intro="""
  881. Aria model for conditional generation tasks.
  882. This model combines a vision tower, a multi-modal projector, and a language model
  883. to perform tasks that involve both image and text inputs.
  884. """
  885. )
  886. class AriaForConditionalGeneration(AriaPreTrainedModel, GenerationMixin):
  887. _checkpoint_conversion_mapping = {
  888. "^language_model.model": "model.language_model",
  889. "^vision_tower": "model.vision_tower",
  890. "^multi_modal_projector": "model.multi_modal_projector",
  891. "^language_model.lm_head": "lm_head",
  892. }
  893. _tied_weights_keys = ["lm_head.weight"]
  894. def __init__(self, config: AriaConfig):
  895. super().__init__(config)
  896. self.model = AriaModel(config)
  897. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  898. self.post_init()
  899. def get_input_embeddings(self):
  900. return self.model.get_input_embeddings()
  901. def set_input_embeddings(self, value):
  902. self.model.set_input_embeddings(value)
  903. def get_output_embeddings(self) -> nn.Module:
  904. return self.lm_head
  905. def set_decoder(self, decoder):
  906. self.model.set_decoder(decoder)
  907. def get_decoder(self):
  908. return self.model.get_decoder()
  909. def get_image_features(
  910. self,
  911. pixel_values: torch.FloatTensor,
  912. pixel_mask: Optional[torch.FloatTensor] = None,
  913. vision_feature_layer: int = -1,
  914. ):
  915. return self.model.get_image_features(
  916. pixel_values=pixel_values,
  917. pixel_mask=pixel_mask,
  918. vision_feature_layer=vision_feature_layer,
  919. )
  920. # Make modules available through conditional class for BC
  921. @property
  922. def language_model(self):
  923. return self.model.language_model
  924. @property
  925. def vision_tower(self):
  926. return self.model.vision_tower
  927. @property
  928. def multi_modal_projector(self):
  929. return self.model.multi_modal_projector
  930. @can_return_tuple
  931. @auto_docstring
  932. def forward(
  933. self,
  934. input_ids: Optional[torch.LongTensor] = None,
  935. pixel_values: Optional[torch.FloatTensor] = None,
  936. pixel_mask: Optional[torch.LongTensor] = None,
  937. attention_mask: Optional[torch.Tensor] = None,
  938. position_ids: Optional[torch.LongTensor] = None,
  939. past_key_values: Optional[Cache] = None,
  940. inputs_embeds: Optional[torch.FloatTensor] = None,
  941. labels: Optional[torch.LongTensor] = None,
  942. use_cache: Optional[bool] = None,
  943. logits_to_keep: Union[int, torch.Tensor] = 0,
  944. cache_position: Optional[torch.LongTensor] = None,
  945. **kwargs: Unpack[TransformersKwargs],
  946. ) -> Union[tuple, AriaCausalLMOutputWithPast]:
  947. r"""
  948. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  949. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  950. config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
  951. Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
  952. computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  953. Example:
  954. ```python
  955. >>> import requests
  956. >>> import torch
  957. >>> from PIL import Image
  958. >>> from io import BytesIO
  959. >>> from transformers import AutoProcessor, AutoModel
  960. >>> from transformers.image_utils import load_image
  961. >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
  962. >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
  963. >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
  964. >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
  965. >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
  966. >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")
  967. >>> # Create inputs
  968. >>> messages = [
  969. ... {
  970. ... "role": "user",
  971. ... "content": [
  972. ... {"type": "image"},
  973. ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
  974. ... {"type": "image"},
  975. ... {"type": "text", "text": "What can we see in this image?"},
  976. ... ]
  977. ... },
  978. ... {
  979. ... "role": "user",
  980. ... "content": [
  981. ... {"type": "image"},
  982. ... {"type": "text", "text": "In which city is that bridge located?"},
  983. ... ]
  984. ... }
  985. ... ]
  986. >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
  987. >>> images = [[image1, image2], [image3]]
  988. >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)
  989. >>> # Generate
  990. >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
  991. >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
  992. >>> print(generated_texts[0])
  993. Assistant: There are buildings, trees, lights, and water visible in this image.
  994. >>> print(generated_texts[1])
  995. Assistant: The bridge is in San Francisco.
  996. ```"""
  997. outputs = self.model(
  998. input_ids=input_ids,
  999. pixel_values=pixel_values,
  1000. pixel_mask=pixel_mask,
  1001. attention_mask=attention_mask,
  1002. position_ids=position_ids,
  1003. past_key_values=past_key_values,
  1004. inputs_embeds=inputs_embeds,
  1005. use_cache=use_cache,
  1006. cache_position=cache_position,
  1007. **kwargs,
  1008. )
  1009. hidden_states = outputs[0]
  1010. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1011. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1012. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1013. loss = None
  1014. if labels is not None:
  1015. loss = self.loss_function(
  1016. logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
  1017. )
  1018. return AriaCausalLMOutputWithPast(
  1019. loss=loss,
  1020. logits=logits,
  1021. past_key_values=outputs.past_key_values,
  1022. hidden_states=outputs.hidden_states,
  1023. attentions=outputs.attentions,
  1024. )
  1025. def prepare_inputs_for_generation(
  1026. self,
  1027. input_ids,
  1028. past_key_values=None,
  1029. inputs_embeds=None,
  1030. pixel_values=None,
  1031. pixel_mask=None,
  1032. attention_mask=None,
  1033. cache_position=None,
  1034. logits_to_keep=None,
  1035. **kwargs,
  1036. ):
  1037. model_inputs = super().prepare_inputs_for_generation(
  1038. input_ids,
  1039. past_key_values=past_key_values,
  1040. inputs_embeds=inputs_embeds,
  1041. attention_mask=attention_mask,
  1042. cache_position=cache_position,
  1043. logits_to_keep=logits_to_keep,
  1044. **kwargs,
  1045. )
  1046. if cache_position[0] == 0:
  1047. # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
  1048. # Otherwise we need pixel values to be passed to model
  1049. model_inputs["pixel_values"] = pixel_values
  1050. model_inputs["pixel_mask"] = pixel_mask
  1051. return model_inputs
  1052. __all__ = [
  1053. "AriaForConditionalGeneration",
  1054. "AriaPreTrainedModel",
  1055. "AriaTextPreTrainedModel",
  1056. "AriaTextModel",
  1057. "AriaModel",
  1058. "AriaTextForCausalLM",
  1059. ]