Leon commited on
Commit
f906a7f
1 Parent(s): cb23567

Upload 12 files

Browse files
added_tokens.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "</s>": 100353,
3
+ "<s>": 100352
4
+ }
configuration_aria.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+
22
+ from .moe_lm import AriaMoELMConfig
23
+ from .vision_encoder import AriaVisionConfig
24
+
25
+
26
+ # adapted from transformers.models.llava.configuration_llava.LlavaConfig
27
+ class AriaConfig(PretrainedConfig):
28
+ """
29
+ Configuration class for Aria model.
30
+
31
+ This class handles the configuration for both vision and text components of the Aria model,
32
+ as well as additional parameters for image token handling and projector mapping.
33
+
34
+ Args:
35
+ vision_config (AriaVisionConfig or dict): Configuration for the vision component.
36
+ text_config (AriaMoELMConfig or dict): Configuration for the text component.
37
+ projector_patch_to_query_dict (dict): Mapping of patch sizes to query dimensions.
38
+ ignore_index (int): Index to ignore in loss calculation.
39
+ image_token_index (int): Index used to represent image tokens.
40
+ **kwargs: Additional keyword arguments passed to the parent class.
41
+
42
+ Attributes:
43
+ model_type (str): Type of the model, set to "aria".
44
+ is_composition (bool): Whether the model is a composition of multiple components.
45
+ ignore_index (int): Index to ignore in loss calculation.
46
+ image_token_index (int): Index used to represent image tokens.
47
+ projector_patch_to_query_dict (dict): Mapping of patch sizes to query dimensions.
48
+ vision_config (AriaVisionConfig): Configuration for the vision component.
49
+ text_config (AriaMoELMConfig): Configuration for the text component.
50
+ """
51
+
52
+ model_type = "aria"
53
+ is_composition = False
54
+
55
+ def __init__(
56
+ self,
57
+ vision_config=AriaVisionConfig(),
58
+ text_config=AriaMoELMConfig(),
59
+ projector_patch_to_query_dict={
60
+ 1225: 128,
61
+ 4900: 256,
62
+ },
63
+ ignore_index=-100,
64
+ image_token_index=32000,
65
+ **kwargs,
66
+ ):
67
+ super().__init__(**kwargs)
68
+ self.ignore_index = ignore_index
69
+ self.image_token_index = image_token_index
70
+
71
+ attn_implementation = kwargs.pop("attn_implementation", None)
72
+
73
+ # Convert the keys and values of projector_patch_to_query_dict to integers
74
+ # This ensures consistency even if they were provided as strings
75
+ self.projector_patch_to_query_dict = {
76
+ int(k): int(v) for k, v in projector_patch_to_query_dict.items()
77
+ }
78
+
79
+ if isinstance(vision_config, dict) and "model_type" in vision_config:
80
+ vision_config = AriaVisionConfig(**vision_config)
81
+ vision_attn_implementation = (
82
+ "flash_attention_2"
83
+ if attn_implementation is None
84
+ else attn_implementation
85
+ )
86
+ vision_config._attn_implementation = vision_attn_implementation
87
+
88
+ self.vision_config = vision_config
89
+
90
+ if isinstance(text_config, dict) and "model_type" in text_config:
91
+ text_attn_implementation = (
92
+ "sdpa" if attn_implementation is None else attn_implementation
93
+ )
94
+ text_config = AriaMoELMConfig(**text_config)
95
+ text_config._attn_implementation = text_attn_implementation
96
+
97
+ self.text_config = text_config
modeling_aria.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ from dataclasses import dataclass
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ from torch import nn
26
+ from transformers import PreTrainedModel
27
+ from transformers.cache_utils import Cache
28
+ from transformers.modeling_outputs import ModelOutput
29
+ from transformers.utils import logging
30
+
31
+ from .configuration_aria import AriaConfig
32
+ from .moe_lm import AriaMoELMForCausalLM
33
+ from .projector import AriaProjector
34
+ from .vision_encoder import AriaVisionModel
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class AriaPretrainedModel(PreTrainedModel):
40
+ """
41
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
42
+ """
43
+
44
+ config_class = AriaConfig
45
+ base_model_prefix = "model"
46
+ _no_split_modules = []
47
+ supports_gradient_checkpointing = True
48
+ _skip_keys_device_placement = "past_key_values"
49
+ _supports_flash_attn_2 = True
50
+ _supports_cache_class = True
51
+
52
+ @property
53
+ def _supports_sdpa(self):
54
+ """
55
+ Retrieve language_model's attribute to check whether the model supports
56
+ SDPA (Scaled Dot Product Attention) or not.
57
+ """
58
+ return self.language_model._supports_sdpa
59
+
60
+
61
+ @dataclass
62
+ # Copied from transformers.models.llava.modeling_llava.LlavaCausalLMOutputWithPast with Llava->Aria
63
+ class AriaCausalLMOutputWithPast(ModelOutput):
64
+ """
65
+ Base class for Aria causal language model (or autoregressive) outputs.
66
+
67
+ Args:
68
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
69
+ Language modeling loss (for next-token prediction).
70
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
71
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
72
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
73
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
74
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
75
+
76
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
77
+ `past_key_values` input) to speed up sequential decoding.
78
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
79
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
80
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
81
+
82
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
83
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
84
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
85
+ sequence_length)`.
86
+
87
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
88
+ heads.
89
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
90
+ Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
91
+ sequence_length, hidden_size)`.
92
+
93
+ image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
94
+ """
95
+
96
+ loss: Optional[torch.FloatTensor] = None
97
+ logits: torch.FloatTensor = None
98
+ past_key_values: Optional[List[torch.FloatTensor]] = None
99
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
100
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
101
+ image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
102
+
103
+
104
+ def build_mm_projector(config: AriaConfig):
105
+ """
106
+ Builds and returns an AriaProjector instance based on the provided configuration.
107
+
108
+ Args:
109
+ config (AriaConfig): The configuration object containing necessary parameters.
110
+
111
+ Returns:
112
+ AriaProjector: An instance of the AriaProjector class.
113
+ """
114
+ return AriaProjector(
115
+ patch_to_query_dict=config.projector_patch_to_query_dict,
116
+ embed_dim=config.vision_config.hidden_size,
117
+ num_heads=config.vision_config.num_attention_heads,
118
+ kv_dim=config.vision_config.hidden_size,
119
+ ff_dim=config.text_config.hidden_size,
120
+ output_dim=config.text_config.hidden_size,
121
+ )
122
+
123
+
124
+ # adapted from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration
125
+ class AriaForConditionalGeneration(AriaPretrainedModel):
126
+ """
127
+ Aria model for conditional generation tasks.
128
+
129
+ This model combines a vision tower, a multi-modal projector, and a language model
130
+ to perform tasks that involve both image and text inputs.
131
+ """
132
+
133
+ def __init__(self, config: AriaConfig):
134
+ super().__init__(config)
135
+
136
+ self.vision_tower = AriaVisionModel(config.vision_config)
137
+ self.multi_modal_projector = build_mm_projector(config)
138
+ self.vocab_size = config.text_config.vocab_size
139
+ self.language_model = AriaMoELMForCausalLM(config.text_config)
140
+ self.pad_token_id = (
141
+ self.config.pad_token_id if self.config.pad_token_id is not None else -1
142
+ )
143
+ self.post_init()
144
+
145
+ def freeze_vit(self):
146
+ """Freeze the parameters of the vision tower."""
147
+ for param in self.vision_tower.parameters():
148
+ param.requires_grad = False
149
+
150
+ def freeze_projector(self):
151
+ """Freeze the parameters of the multi-modal projector."""
152
+ for param in self.multi_modal_projector.parameters():
153
+ param.requires_grad = False
154
+
155
+ def freeze_llm(self):
156
+ """Freeze the parameters of the language model."""
157
+ for param in self.language_model.parameters():
158
+ param.requires_grad = False
159
+
160
+ def get_input_embeddings(self) -> nn.Module:
161
+ """Retrieve the input embeddings from the language model."""
162
+ return self.language_model.get_input_embeddings()
163
+
164
+ def set_input_embeddings(self, value):
165
+ """Set the input embeddings for the language model."""
166
+ self.language_model.set_input_embeddings(value)
167
+
168
+ def set_moe_z_loss_coeff(self, value):
169
+ """
170
+ Set the z-loss coefficient for Mixture of Experts (MoE) models.
171
+
172
+ Args:
173
+ value: The z-loss coefficient value to set.
174
+ """
175
+ self.language_model.set_z_loss_coeff(value)
176
+
177
+ def set_moe_aux_loss_coeff(self, value):
178
+ """
179
+ Set the auxiliary loss coefficient for Mixture of Experts (MoE) models.
180
+
181
+ Args:
182
+ value: The auxiliary loss coefficient value to set.
183
+ """
184
+ self.language_model.set_aux_loss_coeff(value)
185
+
186
+ # copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration
187
+ def _merge_input_ids_with_image_features(
188
+ self, image_features, inputs_embeds, input_ids, attention_mask, labels
189
+ ):
190
+ """
191
+ Merge input IDs with image features to create a combined input representation.
192
+
193
+ This method handles the complex logic of interleaving text and image tokens,
194
+ adjusting attention masks and labels accordingly.
195
+
196
+ Args:
197
+ image_features (torch.Tensor): Processed image features.
198
+ inputs_embeds (torch.Tensor): Text input embeddings.
199
+ input_ids (torch.Tensor): Input token IDs.
200
+ attention_mask (torch.Tensor): Attention mask for input tokens.
201
+ labels (torch.Tensor, optional): Labels for language modeling.
202
+
203
+ Returns:
204
+ tuple: Contains the merged embeddings, updated attention mask,
205
+ updated labels, and position IDs.
206
+ """
207
+ num_images, num_image_patches, embed_dim = image_features.shape
208
+ batch_size, sequence_length = input_ids.shape
209
+ left_padding = not torch.sum(
210
+ input_ids[:, -1] == torch.tensor(self.pad_token_id)
211
+ )
212
+ # 1. Create a mask to know where special image tokens are
213
+ special_image_token_mask = input_ids == self.config.image_token_index
214
+ num_special_image_tokens = torch.sum(special_image_token_mask, dim=-1)
215
+ # Compute the maximum embed dimension
216
+ max_embed_dim = (
217
+ num_special_image_tokens.max() * (num_image_patches - 1)
218
+ ) + sequence_length
219
+ batch_indices, non_image_indices = torch.where(
220
+ input_ids != self.config.image_token_index
221
+ )
222
+
223
+ # 2. Compute the positions where text should be written
224
+ # Calculate new positions for text tokens in merged image-text sequence.
225
+ # `special_image_token_mask` identifies image tokens. Each image token will be replaced by `nb_text_tokens_per_images - 1` text tokens.
226
+ # `torch.cumsum` computes how each image token shifts subsequent text token positions.
227
+ # - 1 to adjust for zero-based indexing, as `cumsum` inherently increases indices by one.
228
+ new_token_positions = (
229
+ torch.cumsum((special_image_token_mask * (num_image_patches - 1) + 1), -1)
230
+ - 1
231
+ )
232
+ nb_image_pad = max_embed_dim - 1 - new_token_positions[:, -1]
233
+ if left_padding:
234
+ new_token_positions += nb_image_pad[:, None] # offset for left padding
235
+ text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
236
+
237
+ # 3. Create the full embedding, already padded to the maximum position
238
+ final_embedding = torch.zeros(
239
+ batch_size,
240
+ max_embed_dim,
241
+ embed_dim,
242
+ dtype=inputs_embeds.dtype,
243
+ device=inputs_embeds.device,
244
+ )
245
+ final_attention_mask = torch.zeros(
246
+ batch_size,
247
+ max_embed_dim,
248
+ dtype=attention_mask.dtype,
249
+ device=inputs_embeds.device,
250
+ )
251
+ if labels is not None:
252
+ final_labels = torch.full(
253
+ (batch_size, max_embed_dim),
254
+ self.config.ignore_index,
255
+ dtype=input_ids.dtype,
256
+ device=input_ids.device,
257
+ )
258
+ # In case the Vision model or the Language model has been offloaded to CPU, we need to manually
259
+ # set the corresponding tensors into their correct target device.
260
+ target_device = inputs_embeds.device
261
+ batch_indices, non_image_indices, text_to_overwrite = (
262
+ batch_indices.to(target_device),
263
+ non_image_indices.to(target_device),
264
+ text_to_overwrite.to(target_device),
265
+ )
266
+ attention_mask = attention_mask.to(target_device)
267
+
268
+ # 4. Fill the embeddings based on the mask. If we have ["hey" "<image>", "how", "are"]
269
+ # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the image features
270
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[
271
+ batch_indices, non_image_indices
272
+ ]
273
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[
274
+ batch_indices, non_image_indices
275
+ ]
276
+ if labels is not None:
277
+ final_labels[batch_indices, text_to_overwrite] = labels[
278
+ batch_indices, non_image_indices
279
+ ]
280
+
281
+ # 5. Fill the embeddings corresponding to the images. Anything that is not `text_positions` needs filling (#29835)
282
+ image_to_overwrite = torch.full(
283
+ (batch_size, max_embed_dim),
284
+ True,
285
+ dtype=torch.bool,
286
+ device=inputs_embeds.device,
287
+ )
288
+ image_to_overwrite[batch_indices, text_to_overwrite] = False
289
+ image_to_overwrite &= image_to_overwrite.cumsum(-1) - 1 >= nb_image_pad[
290
+ :, None
291
+ ].to(target_device)
292
+
293
+ if image_to_overwrite.sum() != image_features.shape[:-1].numel():
294
+ raise ValueError(
295
+ f"The input provided to the model are wrong. The number of image tokens is {torch.sum(special_image_token_mask)} while"
296
+ f" the number of image given to the model is {num_images}. This prevents correct indexing and breaks batch generation."
297
+ )
298
+
299
+ final_embedding[image_to_overwrite] = (
300
+ image_features.contiguous().reshape(-1, embed_dim).to(target_device)
301
+ )
302
+ final_attention_mask |= image_to_overwrite
303
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_(
304
+ (final_attention_mask == 0), 1
305
+ )
306
+
307
+ # 6. Mask out the embedding at padding positions, as we later use the past_key_value value to determine the non-attended tokens.
308
+ batch_indices, pad_indices = torch.where(input_ids == self.pad_token_id)
309
+ indices_to_mask = new_token_positions[batch_indices, pad_indices]
310
+
311
+ final_embedding[batch_indices, indices_to_mask] = 0
312
+
313
+ if labels is None:
314
+ final_labels = None
315
+
316
+ return final_embedding, final_attention_mask, final_labels, position_ids
317
+
318
+ def forward(
319
+ self,
320
+ input_ids: torch.LongTensor = None,
321
+ pixel_values: torch.FloatTensor = None,
322
+ pixel_mask: torch.LongTensor = None,
323
+ attention_mask: Optional[torch.Tensor] = None,
324
+ position_ids: Optional[torch.LongTensor] = None,
325
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
326
+ inputs_embeds: Optional[torch.FloatTensor] = None,
327
+ labels: Optional[torch.LongTensor] = None,
328
+ use_cache: Optional[bool] = None,
329
+ output_attentions: Optional[bool] = None,
330
+ output_hidden_states: Optional[bool] = None,
331
+ return_dict: Optional[bool] = None,
332
+ ) -> Union[Tuple, AriaCausalLMOutputWithPast]:
333
+ """
334
+ Forward pass of the AriaForConditionalGeneration model.
335
+
336
+ This method processes both text and image inputs, merges them if necessary,
337
+ and generates output using the language model.
338
+
339
+ Args:
340
+ input_ids (torch.LongTensor, optional): Input token ids.
341
+ pixel_values (torch.FloatTensor, optional): Pixel values of the images.
342
+ pixel_mask (torch.LongTensor, optional): Mask for the pixel values.
343
+ attention_mask (torch.Tensor, optional): Attention mask.
344
+ position_ids (torch.LongTensor, optional): Position ids.
345
+ past_key_values (List[torch.FloatTensor], optional): Past key values for efficient processing.
346
+ inputs_embeds (torch.FloatTensor, optional): Input embeddings.
347
+ labels (torch.LongTensor, optional): Labels for computing the language modeling loss.
348
+ use_cache (bool, optional): Whether to use the model's cache mechanism.
349
+ output_attentions (bool, optional): Whether to output attention weights.
350
+ output_hidden_states (bool, optional): Whether to output hidden states.
351
+ return_dict (bool, optional): Whether to return a ModelOutput object.
352
+
353
+ Returns:
354
+ Union[Tuple, AriaCausalLMOutputWithPast]: Model outputs.
355
+ """
356
+ output_attentions = (
357
+ output_attentions
358
+ if output_attentions is not None
359
+ else self.config.output_attentions
360
+ )
361
+ output_hidden_states = (
362
+ output_hidden_states
363
+ if output_hidden_states is not None
364
+ else self.config.output_hidden_states
365
+ )
366
+ return_dict = (
367
+ return_dict if return_dict is not None else self.config.use_return_dict
368
+ )
369
+
370
+ if inputs_embeds is None:
371
+ # 1. Extra the input embeddings
372
+ inputs_embeds = self.get_input_embeddings()(input_ids)
373
+
374
+ # 2. Merge text and images
375
+ if pixel_values is not None and input_ids.shape[1] != 1:
376
+ image_outputs, image_attn_mask = self.vision_tower(
377
+ pixel_values,
378
+ pixel_mask=pixel_mask,
379
+ )
380
+ selected_image_feature = image_outputs.last_hidden_state
381
+
382
+ image_features = self.multi_modal_projector(
383
+ selected_image_feature, attn_mask=image_attn_mask
384
+ )
385
+
386
+ inputs_embeds = inputs_embeds.to(image_features.dtype)
387
+ (
388
+ inputs_embeds,
389
+ attention_mask,
390
+ labels,
391
+ position_ids,
392
+ ) = self._merge_input_ids_with_image_features(
393
+ image_features, inputs_embeds, input_ids, attention_mask, labels
394
+ )
395
+
396
+ # In case input_ids.shape[1] == 1 & pixel_values != None & past_key_values != None, we are in the case of
397
+ # generation with cache
398
+ elif (
399
+ past_key_values is not None
400
+ and pixel_values is not None
401
+ and input_ids.shape[1] == 1
402
+ ):
403
+ # Retrieve the first layer to inspect the logits and mask out the hidden states
404
+ # that are set to 0
405
+ first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
406
+
407
+ # Sum all dimensions of head_dim (-2) to avoid random errors
408
+ # such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
409
+ batch_index, non_attended_tokens = torch.where(
410
+ first_layer_past_key_value.float().sum(-2) == 0
411
+ )
412
+
413
+ # Get the target length
414
+ target_length = input_ids.shape[1]
415
+ past_length = first_layer_past_key_value.shape[-1]
416
+
417
+ extended_attention_mask = torch.ones(
418
+ (attention_mask.shape[0], past_length),
419
+ dtype=attention_mask.dtype,
420
+ device=attention_mask.device,
421
+ )
422
+
423
+ # Filter out only the tokens that can be un-attended, this can happen
424
+ # if one uses Llava + Fused modules where the cache on the
425
+ # first iteration is already big enough, or if one passes custom cache
426
+ valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
427
+ new_batch_index = batch_index[valid_indices]
428
+ new_non_attended_tokens = non_attended_tokens[valid_indices]
429
+
430
+ # Zero-out the places where we don't need to attend
431
+ extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
432
+
433
+ attention_mask = torch.cat(
434
+ (extended_attention_mask, attention_mask[:, -target_length:]), dim=1
435
+ )
436
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
437
+
438
+ outputs = self.language_model(
439
+ attention_mask=attention_mask,
440
+ position_ids=position_ids,
441
+ past_key_values=past_key_values,
442
+ inputs_embeds=inputs_embeds,
443
+ use_cache=use_cache,
444
+ output_attentions=output_attentions,
445
+ output_hidden_states=output_hidden_states,
446
+ return_dict=return_dict,
447
+ )
448
+
449
+ logits = outputs[0]
450
+
451
+ loss = None
452
+ if labels is not None:
453
+ # Shift so that tokens < n predict n
454
+ if attention_mask is not None:
455
+ shift_attention_mask = attention_mask[..., 1:]
456
+ shift_logits = logits[..., :-1, :][
457
+ shift_attention_mask.to(logits.device) != 0
458
+ ].contiguous()
459
+ shift_labels = labels[..., 1:][
460
+ shift_attention_mask.to(labels.device) != 0
461
+ ].contiguous()
462
+ else:
463
+ shift_logits = logits[..., :-1, :].contiguous()
464
+ shift_labels = labels[..., 1:].contiguous()
465
+ # Flatten the tokens
466
+ loss_fct = nn.CrossEntropyLoss()
467
+ loss = loss_fct(
468
+ shift_logits.view(-1, shift_logits.size(-1)),
469
+ shift_labels.view(-1).to(shift_logits.device),
470
+ )
471
+
472
+ if not return_dict:
473
+ output = (logits,) + outputs[1:]
474
+ return (loss,) + output if loss is not None else output
475
+
476
+ return AriaCausalLMOutputWithPast(
477
+ loss=loss,
478
+ logits=logits,
479
+ past_key_values=outputs.past_key_values,
480
+ hidden_states=outputs.hidden_states,
481
+ attentions=outputs.attentions,
482
+ )
483
+
484
+ def prepare_inputs_for_generation(
485
+ self,
486
+ input_ids,
487
+ past_key_values=None,
488
+ inputs_embeds=None,
489
+ pixel_values=None,
490
+ pixel_mask=None,
491
+ attention_mask=None,
492
+ **kwargs,
493
+ ):
494
+ """
495
+ Prepare inputs for generation step.
496
+
497
+ This method prepares the inputs for the generation step, handling both
498
+ text and image inputs, and managing the model's cache mechanism.
499
+
500
+ Args:
501
+ input_ids (torch.LongTensor): Input token ids.
502
+ past_key_values (Cache or List[torch.FloatTensor], optional): Past key values for efficient processing.
503
+ inputs_embeds (torch.FloatTensor, optional): Input embeddings.
504
+ pixel_values (torch.FloatTensor, optional): Pixel values of the images.
505
+ pixel_mask (torch.LongTensor, optional): Mask for the pixel values.
506
+ attention_mask (torch.Tensor, optional): Attention mask.
507
+ **kwargs: Additional keyword arguments.
508
+
509
+ Returns:
510
+ dict: A dictionary containing the prepared inputs for the generation step.
511
+ """
512
+ if past_key_values is not None:
513
+ if isinstance(past_key_values, Cache):
514
+ cache_length = past_key_values.get_seq_length()
515
+ past_length = past_key_values.seen_tokens
516
+ else:
517
+ cache_length = past_length = past_key_values[0][0].shape[2]
518
+
519
+ # Keep only the unprocessed tokens:
520
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
521
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
522
+ # input)
523
+ if (
524
+ attention_mask is not None
525
+ and attention_mask.shape[1] > input_ids.shape[1]
526
+ ):
527
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
528
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
529
+ # input_ids based on the past_length.
530
+ elif past_length < input_ids.shape[1]:
531
+ input_ids = input_ids[:, past_length:]
532
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
533
+ elif self.config.image_token_index in input_ids:
534
+ input_ids = input_ids[:, input_ids.shape[1] - 1 :]
535
+ # If the cache has seen more tokens than it can hold, then the cache has a size limit. Let's discard the
536
+ # older attention values, as their corresponding values are not part of the input.
537
+ if cache_length < past_length and attention_mask is not None:
538
+ attention_mask = attention_mask[
539
+ :, -(cache_length + input_ids.shape[1]) :
540
+ ]
541
+
542
+ position_ids = kwargs.get("position_ids", None)
543
+ if attention_mask is not None and position_ids is None:
544
+ # create position_ids on the fly for batch generation
545
+ position_ids = attention_mask.long().cumsum(-1) - 1
546
+ position_ids.masked_fill_(attention_mask == 0, 1)
547
+ if past_key_values:
548
+ position_ids = position_ids[:, -input_ids.shape[1] :]
549
+
550
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
551
+ if inputs_embeds is not None and past_key_values is None:
552
+ model_inputs = {"inputs_embeds": inputs_embeds}
553
+ else:
554
+ model_inputs = {"input_ids": input_ids}
555
+
556
+ model_inputs.update(
557
+ {
558
+ "position_ids": position_ids,
559
+ "past_key_values": past_key_values,
560
+ "use_cache": kwargs.get("use_cache"),
561
+ "attention_mask": attention_mask,
562
+ "pixel_values": pixel_values,
563
+ "pixel_mask": pixel_mask,
564
+ }
565
+ )
566
+ return model_inputs
moe_lm.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ import logging
21
+ import os
22
+ from typing import Tuple
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+ from transformers import LlamaConfig
29
+ from transformers.models.llama.modeling_llama import (
30
+ ACT2FN,
31
+ LLAMA_ATTENTION_CLASSES,
32
+ LlamaDecoderLayer,
33
+ LlamaForCausalLM,
34
+ LlamaMLP,
35
+ LlamaModel,
36
+ LlamaRMSNorm,
37
+ LlamaRotaryEmbedding,
38
+ )
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ class AriaMoELMConfig(LlamaConfig):
44
+ """
45
+ Configuration class for AriaMoE language model.
46
+
47
+ This class extends the LlamaConfig to include additional parameters specific to the Mixture of Experts (MoE) architecture.
48
+ """
49
+
50
+ model_type = "aria_moe_lm"
51
+
52
+ def __init__(
53
+ self,
54
+ moe_intermediate_size: int = 4096,
55
+ moe_num_experts: int = 8,
56
+ moe_topk: int = 2,
57
+ moe_z_loss_coeff: float = 1e-5,
58
+ moe_aux_loss_coeff: float = 1e-3,
59
+ moe_num_shared_experts: int = 2,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Initialize the AriaMoELMConfig.
64
+
65
+ Args:
66
+ moe_intermediate_size (int): The intermediate size for MoE layers. Default is 4096.
67
+ moe_num_experts (int): The number of experts in the MoE layer. Default is 8.
68
+ moe_topk (int): The number of top experts to route to for each token. Default is 2.
69
+ moe_z_loss_coeff (float): The coefficient for the auxiliary z-loss. Default is 1e-5.
70
+ moe_aux_loss_coeff (float): The coefficient for the auxiliary load balancing loss. Default is 1e-3.
71
+ moe_num_shared_experts (int): The number of shared experts. Default is 2.
72
+ **kwargs: Additional keyword arguments to be passed to the parent LlamaConfig.
73
+ """
74
+ super().__init__(**kwargs)
75
+ self.moe_intermediate_size = moe_intermediate_size
76
+ self.moe_num_experts = moe_num_experts
77
+ self.moe_topk = moe_topk
78
+ self.moe_z_loss_coeff = moe_z_loss_coeff
79
+ self.moe_aux_loss_coeff = moe_aux_loss_coeff
80
+ self.moe_num_shared_experts = moe_num_shared_experts
81
+
82
+
83
+ # copied from https://github.com/NVIDIA/Megatron-LM/blob/54f1f78529cbc2b9cddad313e7f9d96ac0420a27/megatron/core/transformer/moe/moe_utils.py#L101-L142
84
+ class MoEAuxLossAutoScaler(torch.autograd.Function):
85
+ """An AutoScaler that compute and scales the grad for auxiliary loss."""
86
+
87
+ main_loss_backward_scale: torch.Tensor = torch.tensor(1.0)
88
+
89
+ @staticmethod
90
+ def forward(ctx, output: torch.Tensor, aux_loss: torch.Tensor):
91
+ """Preserve the aux_loss by storing it in the context to avoid garbage collection.
92
+
93
+ Args:
94
+ output (torch.Tensor): The output tensor.
95
+ aux_loss (torch.Tensor): The auxiliary loss tensor.
96
+
97
+ Returns:
98
+ torch.Tensor: The output tensor.
99
+ """
100
+ ctx.save_for_backward(aux_loss)
101
+ return output
102
+
103
+ @staticmethod
104
+ def backward(ctx, grad_output: torch.Tensor):
105
+ """Compute and scale the gradient for auxiliary loss..
106
+
107
+ Args:
108
+ grad_output (torch.Tensor): The gradient of the output.
109
+
110
+ Returns:
111
+ Tuple[torch.Tensor, torch.Tensor]: The gradient of the output, scaled auxiliary loss gradient.
112
+ """
113
+ (aux_loss,) = ctx.saved_tensors
114
+ aux_loss_backward_scale = MoEAuxLossAutoScaler.main_loss_backward_scale
115
+ scaled_aux_loss_grad = torch.ones_like(aux_loss) * aux_loss_backward_scale
116
+ return grad_output, scaled_aux_loss_grad
117
+
118
+ @staticmethod
119
+ def set_loss_scale(scale: torch.Tensor):
120
+ """set the scale of the aux loss.
121
+
122
+ Args:
123
+ scale (torch.Tensor): The scale value to set. Please ensure that the scale passed in matches the scale of the main_loss.
124
+ """
125
+ MoEAuxLossAutoScaler.main_loss_backward_scale = scale
126
+
127
+
128
+ def z_loss_func(logits, z_loss_coeff):
129
+ """Encourages the router's logits to remain small to enhance stability.
130
+ Please refer to the ST-MoE paper (https://arxiv.org/pdf/2202.08906.pdf) for details.
131
+
132
+ Args:
133
+ logits (torch.Tensor): The logits of the router.
134
+
135
+ Returns:
136
+ torch.Tensor: The logits after applying the z-loss.
137
+ """
138
+
139
+ z_loss = torch.mean(torch.square(torch.logsumexp(logits, dim=-1))) * z_loss_coeff
140
+ return z_loss
141
+
142
+
143
+ def switch_load_balancing_loss_func(
144
+ probs: torch.Tensor,
145
+ tokens_per_expert: torch.Tensor,
146
+ topk: int,
147
+ moe_aux_loss_coeff: float,
148
+ ):
149
+ """Calculate the auxiliary loss for better load balacing.
150
+ Please refer to the Switch Transformer paper (https://arxiv.org/abs/2101.03961) for details.
151
+
152
+ Args:
153
+ probs (torch.Tensor): The softmax probs output by the router for each token. [num_tokens, num_experts]
154
+ tokens_per_expert (torch.Tensor): The number of assigned tokens for each expert. [num_experts]
155
+
156
+ Returns:
157
+ torch.Tensor: The auxiliary loss for load balancing.
158
+ """
159
+ num_tokens = probs.shape[0] * topk
160
+ num_experts = probs.shape[1]
161
+
162
+ probs_mean_per_expert = probs.mean(dim=0)
163
+ aux_loss = torch.sum(probs_mean_per_expert * tokens_per_expert) * (
164
+ num_experts / num_tokens * moe_aux_loss_coeff
165
+ )
166
+ return aux_loss
167
+
168
+
169
+ # adapted from https://github.com/NVIDIA/Megatron-LM/blob/54f1f78529cbc2b9cddad313e7f9d96ac0420a27/megatron/core/transformer/moe/router.py#L96-L304
170
+ class TopKRouter(nn.Module):
171
+ """
172
+ Top-K Router for Mixture of Experts (MoE) models.
173
+
174
+ This router determines which experts should process each token based on the top-k scoring experts.
175
+ It also applies auxiliary losses to encourage load balancing among experts.
176
+
177
+ Args:
178
+ config (AriaMoELMConfig): Configuration object containing MoE-related parameters.
179
+ """
180
+
181
+ def __init__(self, config: AriaMoELMConfig):
182
+ super().__init__()
183
+ self.config = config
184
+
185
+ self.weight = nn.Parameter(
186
+ torch.empty((self.config.moe_num_experts, self.config.hidden_size))
187
+ )
188
+ # FIXME: initialize the weight
189
+
190
+ def gating(self, input: torch.Tensor) -> torch.Tensor:
191
+ """
192
+ Compute the gating logits for each token-expert pair.
193
+
194
+ Args:
195
+ input (torch.Tensor): Input tensor of shape [batch_size * seq_len, hidden_size].
196
+
197
+ Returns:
198
+ torch.Tensor: Logits tensor of shape [batch_size * seq_len, num_experts].
199
+ """
200
+ logits = torch.nn.functional.linear(input, self.weight)
201
+ return logits
202
+
203
+ def apply_z_loss(self, logits: torch.Tensor) -> torch.Tensor:
204
+ """
205
+ Apply z-loss to encourage router logits to remain small for enhanced stability.
206
+
207
+ Args:
208
+ logits (torch.Tensor): Router logits.
209
+
210
+ Returns:
211
+ torch.Tensor: Logits with z-loss applied.
212
+ """
213
+ z_loss = z_loss_func(logits, self.config.moe_z_loss_coeff)
214
+ logits = MoEAuxLossAutoScaler.apply(logits, z_loss)
215
+ return logits
216
+
217
+ def apply_aux_loss(
218
+ self,
219
+ logits: torch.Tensor,
220
+ tokens_per_expert: torch.Tensor,
221
+ activation: torch.Tensor,
222
+ ) -> torch.Tensor:
223
+ """
224
+ Apply auxiliary loss for load balancing among experts.
225
+
226
+ Args:
227
+ logits (torch.Tensor): Router logits.
228
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
229
+ activation (torch.Tensor): Activation values.
230
+
231
+ Returns:
232
+ torch.Tensor: Activation with auxiliary loss applied.
233
+ """
234
+ probs = torch.softmax(logits, dim=-1, dtype=torch.float32)
235
+ aux_loss = switch_load_balancing_loss_func(
236
+ probs,
237
+ tokens_per_expert,
238
+ self.config.moe_topk,
239
+ self.config.moe_aux_loss_coeff,
240
+ )
241
+ return MoEAuxLossAutoScaler.apply(activation, aux_loss)
242
+
243
+ def routing(
244
+ self, logits: torch.Tensor
245
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
246
+ """
247
+ Perform the routing operation to determine expert assignments.
248
+
249
+ Args:
250
+ logits (torch.Tensor): Router logits.
251
+
252
+ Returns:
253
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
254
+ - scores: Softmax probabilities for top-k experts.
255
+ - top_indices: Indices of top-k experts for each token.
256
+ - tokens_per_expert: Number of tokens assigned to each expert.
257
+ """
258
+ logits = self.apply_z_loss(logits)
259
+
260
+ top_logits, top_indices = torch.topk(logits, k=self.config.moe_topk, dim=1)
261
+ scores = torch.softmax(top_logits, dim=-1, dtype=torch.float32).type_as(logits)
262
+
263
+ tokens_per_expert = torch.histc(
264
+ top_indices.flatten(),
265
+ bins=self.config.moe_num_experts,
266
+ min=0,
267
+ max=self.config.moe_num_experts - 1,
268
+ )
269
+
270
+ scores = self.apply_aux_loss(logits, tokens_per_expert, scores)
271
+ return scores, top_indices, tokens_per_expert
272
+
273
+ def forward(
274
+ self, input: torch.Tensor
275
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
276
+ """
277
+ Forward pass of the TopKRouter.
278
+
279
+ Args:
280
+ input (torch.Tensor): Input tensor of shape [batch_size * seq_len, hidden_size].
281
+
282
+ Returns:
283
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
284
+ - scores: Softmax probabilities for top-k experts.
285
+ - top_indices: Indices of top-k experts for each token.
286
+ - tokens_per_expert: Number of tokens assigned to each expert.
287
+ """
288
+ logits = self.gating(input)
289
+ logits = logits.view(-1, self.config.moe_num_experts)
290
+ scores, top_indices, tokens_per_expert = self.routing(logits)
291
+ return scores, top_indices, tokens_per_expert
292
+
293
+
294
+ # adapted from https://github.com/NVIDIA/Megatron-LM/blob/54f1f78529cbc2b9cddad313e7f9d96ac0420a27/megatron/core/transformer/moe/token_dispatcher.py#L291-L587
295
+ class TokenDispatcher:
296
+ """
297
+ Handles the dispatching and gathering of tokens to and from experts.
298
+
299
+ This class is responsible for permuting tokens based on expert assignments and
300
+ unpermuting them after expert processing.
301
+
302
+ Args:
303
+ config (AriaMoELMConfig): Configuration object containing MoE-related parameters.
304
+ """
305
+
306
+ def __init__(self, config: AriaMoELMConfig):
307
+ self.config = config
308
+ self.hidden_states_shape = None
309
+ self.reversed_input_permutation_mapping = None
310
+
311
+ def token_permutation(
312
+ self, hidden_states: torch.Tensor, indices: torch.Tensor
313
+ ) -> torch.Tensor:
314
+ """
315
+ Permute tokens based on expert assignments.
316
+
317
+ Args:
318
+ hidden_states (torch.Tensor): Input hidden states.
319
+ indices (torch.Tensor): Expert assignment indices.
320
+
321
+ Returns:
322
+ torch.Tensor: Permuted tokens.
323
+ """
324
+ self.hidden_states_shape = hidden_states.shape
325
+ hidden_states = hidden_states.view(-1, hidden_states.size(-1))
326
+ flatten_indices = indices.flatten()
327
+ sorted_indices = torch.argsort(flatten_indices, stable=True)
328
+ permuted_tokens = hidden_states.index_select(
329
+ 0, sorted_indices // self.config.moe_topk
330
+ )
331
+ self.reversed_input_permutation_mapping = sorted_indices
332
+ return permuted_tokens
333
+
334
+ def token_unpermutation(
335
+ self, permuted_tokens: torch.Tensor, scores: torch.Tensor
336
+ ) -> torch.Tensor:
337
+ """
338
+ Unpermute tokens and combine expert outputs.
339
+
340
+ Args:
341
+ permuted_tokens (torch.Tensor): Tokens after expert processing.
342
+ scores (torch.Tensor): Expert assignment scores.
343
+
344
+ Returns:
345
+ torch.Tensor: Unpermuted and combined output.
346
+ """
347
+ num_unpermuted_tokens = scores.numel()
348
+ unpermuted_tokens = torch.zeros(
349
+ (num_unpermuted_tokens, permuted_tokens.size(1)),
350
+ dtype=permuted_tokens.dtype,
351
+ device=permuted_tokens.device,
352
+ )
353
+ unpermuted_tokens.index_copy_(
354
+ 0, self.reversed_input_permutation_mapping, permuted_tokens
355
+ )
356
+ unpermuted_tokens = unpermuted_tokens.reshape(
357
+ -1, self.config.moe_topk, permuted_tokens.size(1)
358
+ )
359
+
360
+ unpermuted_tokens = unpermuted_tokens * scores.unsqueeze(-1)
361
+ unpermuted_tokens = unpermuted_tokens.sum(dim=1).type_as(permuted_tokens)
362
+ output = unpermuted_tokens.view(self.hidden_states_shape)
363
+ return output
364
+
365
+
366
+ class SharedExpertMLP(LlamaMLP):
367
+ """
368
+ Shared Expert MLP for shared experts.
369
+
370
+ Unlike routed experts, shared experts process all tokens without routing.
371
+ This class reconfigures the intermediate size in comparison to the LlamaMLP.
372
+
373
+ Args:
374
+ config (AriaMoELMConfig): Configuration object for the AriaMoE language model.
375
+ """
376
+
377
+ def __init__(self, config: AriaMoELMConfig):
378
+ nn.Module.__init__(self)
379
+ self.config = config
380
+ self.hidden_size = config.hidden_size
381
+ self.intermediate_size = (
382
+ config.moe_intermediate_size * config.moe_num_shared_experts
383
+ )
384
+ self.gate_proj = nn.Linear(
385
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
386
+ )
387
+ self.up_proj = nn.Linear(
388
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
389
+ )
390
+ self.down_proj = nn.Linear(
391
+ self.intermediate_size, self.hidden_size, bias=config.mlp_bias
392
+ )
393
+ self.act_fn = ACT2FN[config.hidden_act]
394
+
395
+
396
+ def sequential_gemm(input, weight, tokens_per_expert):
397
+ """
398
+ Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
399
+
400
+ Args:
401
+ input (torch.Tensor): Input tensor of shape (num_tokens, in_features).
402
+ weight (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
403
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
404
+
405
+ Returns:
406
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
407
+ """
408
+ num_tokens = input.shape[0]
409
+ out_features = weight.shape[-1]
410
+ output = torch.zeros(
411
+ num_tokens, out_features, dtype=input.dtype, device=input.device
412
+ )
413
+
414
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
415
+ # Insert zero at the begining for offset index's convenience
416
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
417
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
418
+
419
+ for expert_num in range(weight.shape[0]):
420
+ start = cumsum_num_tokens[expert_num]
421
+ end = cumsum_num_tokens[expert_num + 1]
422
+ tokens = input[start:end]
423
+
424
+ out = torch.matmul(tokens, weight[expert_num])
425
+ output[start:end] = out
426
+ return output
427
+
428
+
429
+ class ExpertMLP(LlamaMLP):
430
+ """
431
+ Expert MLP for the Mixture of Experts (MoE) layer.
432
+
433
+ This class represents an individual expert in the MoE architecture. It's a modified
434
+ version of LlamaMLP with a configurable intermediate size specific to MoE.
435
+
436
+ Args:
437
+ config (AriaMoELMConfig): Configuration object for the AriaMoE language model.
438
+ """
439
+
440
+ def __init__(self, config: AriaMoELMConfig):
441
+ nn.Module.__init__(self)
442
+ self.config = config
443
+ self.hidden_size = config.hidden_size
444
+ self.intermediate_size = config.moe_intermediate_size
445
+ self.gate_proj = nn.Linear(
446
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
447
+ )
448
+ self.up_proj = nn.Linear(
449
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
450
+ )
451
+ self.down_proj = nn.Linear(
452
+ self.intermediate_size, self.hidden_size, bias=config.mlp_bias
453
+ )
454
+ self.act_fn = ACT2FN[config.hidden_act]
455
+
456
+
457
+ class SequentialMLP(nn.Module):
458
+ """
459
+ Sequential MLP for handling multiple experts in the Mixture of Experts (MoE) layer.
460
+
461
+ This class manages a collection of ExpertMLPs and processes tokens through them sequentially.
462
+
463
+ Args:
464
+ config (AriaMoELMConfig): Configuration object for the AriaMoE language model.
465
+ """
466
+
467
+ def __init__(self, config: AriaMoELMConfig):
468
+ super().__init__()
469
+ self.config = config
470
+ self.experts = nn.ModuleList(
471
+ [ExpertMLP(config) for _ in range(config.moe_num_experts)]
472
+ )
473
+
474
+ def forward(self, permuted_tokens: torch.Tensor, tokens_per_expert: torch.Tensor) -> torch.Tensor:
475
+ """
476
+ Forward pass of the SequentialMLP.
477
+
478
+ This method processes the permuted tokens through each expert sequentially,
479
+ based on the number of tokens assigned to each expert.
480
+
481
+ Args:
482
+ permuted_tokens (torch.Tensor): Permuted input tokens.
483
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
484
+
485
+ Returns:
486
+ torch.Tensor: Processed output from all experts.
487
+ """
488
+ output = torch.zeros_like(permuted_tokens)
489
+
490
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
491
+ # Insert zero at the beginning for offset index's convenience
492
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
493
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
494
+
495
+ for expert_num, expert in enumerate(self.experts):
496
+ start = cumsum_num_tokens[expert_num]
497
+ end = cumsum_num_tokens[expert_num + 1]
498
+ tokens = permuted_tokens[start:end]
499
+
500
+ out = expert(tokens)
501
+ output[start:end] = out
502
+ return output
503
+
504
+
505
+ class MoELayer(nn.Module):
506
+ """
507
+ Mixture of Experts (MoE) Layer for the AriaMoE model.
508
+
509
+ This layer implements the MoE mechanism, which routes input tokens to different experts
510
+ based on a routing algorithm, processes them through the experts, and then combines
511
+ the outputs.
512
+
513
+ Args:
514
+ config (AriaMoELMConfig): Configuration object for the MoE layer.
515
+ """
516
+
517
+ def __init__(self, config: AriaMoELMConfig):
518
+ super().__init__()
519
+
520
+ self.router = TopKRouter(config)
521
+ self.token_dispatcher = TokenDispatcher(config)
522
+ self.experts = SequentialMLP(config)
523
+ self.shared_experts = SharedExpertMLP(config)
524
+
525
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
526
+ """
527
+ Forward pass of the MoE Layer.
528
+
529
+ Args:
530
+ hidden_states (torch.Tensor): Input tensor of shape (batch_size, sequence_length, hidden_size).
531
+
532
+ Returns:
533
+ torch.Tensor: Output tensor after passing through the MoE layer.
534
+
535
+ Process:
536
+ 1. Route tokens to experts using the router.
537
+ 2. Permute tokens based on routing decisions.
538
+ 3. Process tokens through experts.
539
+ 4. Unpermute and combine expert outputs.
540
+ 5. Add shared expert output to the final result.
541
+ """
542
+ scores, indices, tokens_per_expert = self.router(hidden_states)
543
+
544
+ permuted_tokens = self.token_dispatcher.token_permutation(
545
+ hidden_states, indices
546
+ )
547
+
548
+ expert_output = self.experts(permuted_tokens, tokens_per_expert)
549
+
550
+ output = self.token_dispatcher.token_unpermutation(expert_output, scores)
551
+
552
+ shared_expert_output = self.shared_experts(hidden_states)
553
+ output += shared_expert_output
554
+ return output
555
+
556
+
557
+ class MoEDecoderLayer(LlamaDecoderLayer):
558
+ """
559
+ Custom Decoder Layer for the AriaMoE model which modifies the standard `LlamaDecoderLayer` by
560
+ replacing the traditional MLP with a Mixture of Experts (MoE) Layer.
561
+
562
+ Args:
563
+ config (LlamaConfig): Configuration object for the layer.
564
+ layer_idx (int): Index of the current layer in the model.
565
+ """
566
+
567
+ def __init__(self, config: LlamaConfig, layer_idx: int):
568
+ nn.Module.__init__(self)
569
+ self.hidden_size = config.hidden_size
570
+
571
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](
572
+ config=config, layer_idx=layer_idx
573
+ )
574
+
575
+ self.mlp = MoELayer(config)
576
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
577
+ self.post_attention_layernorm = LlamaRMSNorm(
578
+ config.hidden_size, eps=config.rms_norm_eps
579
+ )
580
+
581
+
582
+ class AriaMoELMModel(LlamaModel):
583
+ """
584
+ Custom LlamaModel for the AriaMoE model which modifies the standard LlamaModel by
585
+ replacing the `LlamaDecoderLayer` with `MoEDecoderLayer`.
586
+
587
+ This model implements a Mixture of Experts (MoE) approach, where each layer contains
588
+ multiple expert networks that specialize in different aspects of the input.
589
+
590
+ Args:
591
+ config (LlamaConfig): Configuration object for the model.
592
+ """
593
+
594
+ def __init__(self, config: LlamaConfig):
595
+ super().__init__(config)
596
+ self.padding_idx = config.pad_token_id
597
+ self.vocab_size = config.vocab_size
598
+
599
+ self.embed_tokens = nn.Embedding(
600
+ config.vocab_size, config.hidden_size, self.padding_idx
601
+ )
602
+ self.layers = nn.ModuleList(
603
+ [
604
+ MoEDecoderLayer(config, layer_idx)
605
+ for layer_idx in range(config.num_hidden_layers)
606
+ ]
607
+ )
608
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
609
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
610
+ self.gradient_checkpointing = False
611
+
612
+ # Initialize weights and apply final processing
613
+ self.post_init()
614
+
615
+
616
+ class AriaMoELMForCausalLM(LlamaForCausalLM):
617
+ """
618
+ AriaMoE model for causal language modeling tasks.
619
+
620
+ This class extends LlamaForCausalLM to incorporate the Mixture of Experts (MoE) approach,
621
+ allowing for more efficient and scalable language modeling.
622
+
623
+ Args:
624
+ config (AriaMoELMConfig): Configuration object for the model.
625
+ """
626
+
627
+ _tied_weights_keys = ["lm_head.weight"]
628
+ config_class = AriaMoELMConfig
629
+ _no_split_modules = ["MoEDecoderLayer"]
630
+
631
+ def __init__(self, config):
632
+ super().__init__(config)
633
+ self.model = AriaMoELMModel(config)
634
+ self.vocab_size = config.vocab_size
635
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
636
+
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def set_z_loss_coeff(self, z_loss_coeff: float):
641
+ """
642
+ Set the coefficient for the z-loss in the MoE routing.
643
+
644
+ Args:
645
+ z_loss_coeff (float): The coefficient for the z-loss.
646
+ """
647
+ self.config.moe_z_loss_coeff = z_loss_coeff
648
+
649
+ def set_aux_loss_coeff(self, aux_loss_coeff: float):
650
+ """
651
+ Set the coefficient for the auxiliary loss in the MoE routing.
652
+
653
+ Args:
654
+ aux_loss_coeff (float): The coefficient for the auxiliary loss.
655
+ """
656
+ self.config.moe_aux_loss_coeff = aux_loss_coeff
657
+
preprocessor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_transform": null,
3
+ "auto_map": {
4
+ "AutoImageProcessor": "vision_processor.AriaVisionProcessor",
5
+ "AutoProcessor": "processing_aria.AriaProcessor"
6
+ },
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "AriaVisionProcessor",
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "max_image_size": 980,
19
+ "min_image_size": 336,
20
+ "processor_class": "AriaProcessor"
21
+ }
processing_aria.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ import inspect
21
+ import logging
22
+ import re
23
+ from typing import List, Optional, Union
24
+
25
+ from transformers import AutoTokenizer, BatchFeature
26
+ from transformers.image_utils import ImageInput
27
+ from transformers.processing_utils import ProcessorMixin
28
+ from transformers.tokenization_utils import (
29
+ PaddingStrategy,
30
+ PreTokenizedInput,
31
+ TensorType,
32
+ TextInput,
33
+ TruncationStrategy,
34
+ )
35
+
36
+ from .vision_processor import AriaVisionProcessor
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ class AriaProcessor(ProcessorMixin):
42
+ """
43
+ AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer.
44
+ Args:
45
+ image_processor(AriaVisionProcessor): The AriaVisionProcessor to use for image preprocessing.
46
+ tokenizer(AutoTokenizer): The AutoTokenizer to use for tokenizing the text.
47
+ patch_size(int): The patch size to use for the image processor.
48
+ chat_template(str): The chat template to use for the tokenizer.
49
+ image_token(str): The image token to use for the tokenizer.
50
+ """
51
+
52
+ attributes = []
53
+ valid_kwargs = ["chat_template", "patch_size", "image_token"]
54
+ image_processor_class = None
55
+ tokenizer_class = "AutoTokenizer"
56
+
57
+ def __init__(
58
+ self,
59
+ image_processor: AriaVisionProcessor = None,
60
+ tokenizer: Union[AutoTokenizer, str] = None,
61
+ patch_size: int = 490,
62
+ chat_template: str = None,
63
+ image_token: str = "<|img|>",
64
+ ):
65
+ super().__init__(chat_template=chat_template)
66
+
67
+ if image_processor is None:
68
+ self.image_processor = AriaVisionProcessor(max_image_size=patch_size)
69
+ else:
70
+ self.image_processor = image_processor
71
+
72
+ if isinstance(tokenizer, str):
73
+ self.tokenizer = AutoTokenizer.from_pretrained(
74
+ tokenizer, trust_remote_code=True, use_fast=False
75
+ )
76
+ else:
77
+ self.tokenizer = tokenizer
78
+
79
+ if self.tokenizer is not None and self.tokenizer.pad_token is None:
80
+ self.tokenizer.pad_token = self.tokenizer.unk_token
81
+
82
+ self.image_token = image_token
83
+
84
+ # Copied from transformers.models.llava_next.processing_llave_next.LlavaNextProcessor.__call__
85
+ def __call__(
86
+ self,
87
+ text: Union[
88
+ TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]
89
+ ],
90
+ images: ImageInput = None,
91
+ padding: Union[bool, str, PaddingStrategy] = False,
92
+ truncation: Union[bool, str, TruncationStrategy] = None,
93
+ max_length: Optional[int] = None,
94
+ max_image_size: Optional[int] = 980,
95
+ split_image: Optional[bool] = False,
96
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
97
+ ) -> BatchFeature:
98
+ """
99
+ Main method to prepare for the model one or several sequences(s) and image(s). Please refer to the doctsring
100
+ of the above two methods for more information.
101
+
102
+ Args:
103
+ text (`str`, `List[str]`, `List[List[str]]`):
104
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
105
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
106
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
107
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
108
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
109
+ tensor. Both channels-first and channels-last formats are supported.
110
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
111
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
112
+ index) among:
113
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
114
+ sequence if provided).
115
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
116
+ acceptable input length for the model if that argument is not provided.
117
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
118
+ lengths).
119
+ max_length (`int`, *optional*):
120
+ Maximum length of the returned list and optionally padding length (see above).
121
+ max_image_size (`int`, *optional*):
122
+ Maximum size of the image to be processed.
123
+ split_image (`bool`, *optional*):
124
+ Whether to split the image into patches before processing.
125
+ truncation (`bool`, *optional*):
126
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
127
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
128
+ If set, will return tensors of a particular framework. Acceptable values are:
129
+
130
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
131
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
132
+ - `'np'`: Return NumPy `np.ndarray` objects.
133
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
134
+
135
+ Returns:
136
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
137
+
138
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
139
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
140
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
141
+ `None`).
142
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
143
+ - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
144
+ """
145
+ if isinstance(text, str):
146
+ text = [text]
147
+ elif not isinstance(text, list) and not isinstance(text[0], str):
148
+ raise ValueError(
149
+ "Invalid input text. Please provide a string, or a list of strings"
150
+ )
151
+
152
+ if images is not None:
153
+ image_inputs = self.image_processor(
154
+ images,
155
+ return_tensors=return_tensors,
156
+ max_image_size=max_image_size,
157
+ split_image=split_image,
158
+ )
159
+ # expand the image_token according to the num_crops of image
160
+ prompt_strings = []
161
+ crop_iter = iter(image_inputs.pop("num_crops"))
162
+ for prompt in text:
163
+ prompt_strings.append(
164
+ re.sub(
165
+ re.escape(self.image_token),
166
+ lambda _: next(crop_iter) * self.image_token,
167
+ prompt,
168
+ )
169
+ )
170
+
171
+ else:
172
+ image_inputs = {}
173
+ prompt_strings = text
174
+
175
+ text_inputs = self.tokenizer(
176
+ prompt_strings,
177
+ return_tensors=return_tensors,
178
+ padding=padding,
179
+ truncation=truncation,
180
+ max_length=max_length,
181
+ )
182
+
183
+ return BatchFeature(data={**text_inputs, **image_inputs})
184
+
185
+ @staticmethod
186
+ def _extract_kwargs(func: callable, **kwargs) -> dict:
187
+ """
188
+ Extract the kwargs that are valid for the given function.
189
+ """
190
+ return {
191
+ k: v for k, v in kwargs.items() if k in inspect.signature(func).parameters
192
+ }
193
+
194
+ def save_pretrained(self, save_directory, **kwargs):
195
+ """
196
+ Save both the image processor and tokenizer.
197
+ """
198
+ if self.image_processor is not None:
199
+ self.image_processor.save_pretrained(
200
+ save_directory,
201
+ **self._extract_kwargs(self.image_processor.save_pretrained, **kwargs),
202
+ )
203
+ if self.tokenizer is not None:
204
+ self.tokenizer.save_pretrained(
205
+ save_directory,
206
+ **self._extract_kwargs(self.tokenizer.save_pretrained, **kwargs),
207
+ )
208
+
209
+ @classmethod
210
+ def from_pretrained(
211
+ cls,
212
+ pretrained_model_name_or_path,
213
+ tokenizer_path=None,
214
+ image_processor_path=None,
215
+ **kwargs,
216
+ ):
217
+ """
218
+ Load both the image processor and tokenizer from a pretrained model path.
219
+ """
220
+ tokenizer_path = (
221
+ tokenizer_path
222
+ if tokenizer_path is not None
223
+ else pretrained_model_name_or_path
224
+ )
225
+ image_processor_path = (
226
+ image_processor_path
227
+ if image_processor_path is not None
228
+ else pretrained_model_name_or_path
229
+ )
230
+ image_processor = AriaVisionProcessor.from_pretrained(
231
+ image_processor_path,
232
+ **cls._extract_kwargs(AriaVisionProcessor.from_pretrained, **kwargs),
233
+ )
234
+ if "use_fast" in kwargs:
235
+ logger.warning("use_fast is not supported for AriaProcessor. Ignoring...")
236
+ kwargs.pop("use_fast")
237
+ try:
238
+ tokenizer = AutoTokenizer.from_pretrained(
239
+ tokenizer_path,
240
+ use_fast=False,
241
+ **cls._extract_kwargs(AutoTokenizer.from_pretrained, **kwargs),
242
+ )
243
+ chat_template = tokenizer.chat_template
244
+ except Exception as e:
245
+ logger.warning(f"Failed to load tokenizer from {tokenizer_path}: {e}")
246
+ tokenizer = None
247
+ chat_template = None
248
+ return cls(
249
+ image_processor=image_processor,
250
+ tokenizer=tokenizer,
251
+ chat_template=chat_template,
252
+ )
253
+
254
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
255
+ def batch_decode(self, *args, **kwargs):
256
+ """
257
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
258
+ refer to the docstring of this method for more information.
259
+ """
260
+ if self.tokenizer is None:
261
+ raise ValueError(
262
+ "Tokenizer is not initialized. Please provide a valid tokenizer."
263
+ )
264
+ return self.tokenizer.batch_decode(*args, **kwargs)
265
+
266
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
267
+ def decode(self, *args, **kwargs):
268
+ """
269
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
270
+ the docstring of this method for more information.
271
+ """
272
+ if self.tokenizer is None:
273
+ raise ValueError(
274
+ "Tokenizer is not initialized. Please provide a valid tokenizer."
275
+ )
276
+ return self.tokenizer.decode(*args, **kwargs)
277
+
278
+ @property
279
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
280
+ def model_input_names(self):
281
+ tokenizer_input_names = self.tokenizer.model_input_names
282
+ image_processor_input_names = self.image_processor.model_input_names
283
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
projector.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ from torch.nn.init import trunc_normal_
23
+ from transformers.activations import ACT2FN
24
+
25
+
26
+ class FFN(nn.Module):
27
+ """
28
+ Feed-Forward Network module.
29
+
30
+ Args:
31
+ embed_dim (int): Input embedding dimension.
32
+ ff_dim (int): Hidden dimension of the feed-forward network.
33
+ output_dim (int): Output dimension.
34
+ """
35
+
36
+ def __init__(self, embed_dim, ff_dim, output_dim):
37
+ super().__init__()
38
+ self.linear_in = nn.Linear(embed_dim, ff_dim, bias=False)
39
+ self.linear_out = nn.Linear(ff_dim, output_dim, bias=False)
40
+ self.act = ACT2FN["gelu_new"]
41
+
42
+ def forward(self, hidden_states):
43
+ hidden_states = self.act(self.linear_in(hidden_states))
44
+ hidden_states = self.linear_out(hidden_states)
45
+ return hidden_states
46
+
47
+
48
+ class CrossAttention(nn.Module):
49
+ """
50
+ Cross-Attention module.
51
+
52
+ Args:
53
+ kv_dim (int): Dimension of key and value.
54
+ embed_dim (int): Embedding dimension.
55
+ num_heads (int): Number of attention heads.
56
+ drop_out_rate (float): Dropout rate. Default is 0.
57
+ """
58
+
59
+ def __init__(self, kv_dim, embed_dim, num_heads, drop_out_rate=0):
60
+ super().__init__()
61
+ self.num_heads = num_heads
62
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
63
+ self.k_proj = nn.Linear(kv_dim, embed_dim, bias=False)
64
+ self.v_proj = nn.Linear(kv_dim, embed_dim, bias=False)
65
+
66
+ self.multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
67
+ self.linear = nn.Linear(embed_dim, embed_dim)
68
+ self.dropout = nn.Dropout(drop_out_rate)
69
+
70
+ self.layer_norm = nn.LayerNorm(embed_dim)
71
+ self.ln_kv = nn.LayerNorm(kv_dim)
72
+
73
+ def forward(self, x, hidden_states, attn_mask=None, add_residual=False):
74
+ """
75
+ Forward pass of the CrossAttention module.
76
+
77
+ Args:
78
+ x (torch.Tensor): Input tensor for key and value.
79
+ hidden_states (torch.Tensor): Input tensor for query.
80
+ attn_mask (torch.Tensor, optional): Attention mask. Default is None.
81
+ add_residual (bool): Whether to add residual connection. Default is False.
82
+
83
+ Returns:
84
+ torch.Tensor: Output tensor after cross-attention.
85
+ """
86
+ normed_hidden_states = self.layer_norm(hidden_states)
87
+ query = self.q_proj(normed_hidden_states).permute(1, 0, 2)
88
+
89
+ x = self.ln_kv(x)
90
+ key = self.k_proj(x).permute(1, 0, 2)
91
+ value = self.v_proj(x).permute(1, 0, 2)
92
+
93
+ attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
94
+
95
+ attn_output = attn_output.permute(1, 0, 2)
96
+
97
+ if add_residual:
98
+ attn_output = hidden_states + self.dropout(self.linear(attn_output))
99
+ else:
100
+ attn_output = self.dropout(self.linear(attn_output))
101
+
102
+ return attn_output
103
+
104
+
105
+ class AriaProjector(nn.Module):
106
+ """
107
+ A projection module with one cross attention layer and one FFN layer, which projects ViT's outputs into MoE's inputs.
108
+
109
+ Args:
110
+ patch_to_query_dict (dict): Maps patch numbers to their corresponding query numbers,
111
+ e.g., {1225: 128, 4900: 256}. This allows for different query sizes based on image resolution.
112
+ embed_dim (int): Embedding dimension.
113
+ num_heads (int): Number of attention heads.
114
+ kv_dim (int): Dimension of key and value.
115
+ ff_dim (int): Hidden dimension of the feed-forward network.
116
+ output_dim (int): Output dimension.
117
+ norm_layer (nn.Module): Normalization layer. Default is nn.LayerNorm.
118
+
119
+ Outputs:
120
+ A tensor with the shape of (batch_size, query_number, output_dim)
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ patch_to_query_dict,
126
+ embed_dim,
127
+ num_heads,
128
+ kv_dim,
129
+ ff_dim,
130
+ output_dim,
131
+ norm_layer=nn.LayerNorm,
132
+ ):
133
+ super().__init__()
134
+ self.patch_to_query_dict = patch_to_query_dict
135
+ self.embed_dim = embed_dim
136
+ self.num_heads = num_heads
137
+
138
+ self.query = nn.Parameter(
139
+ torch.zeros(max(patch_to_query_dict.values()), self.embed_dim)
140
+ )
141
+
142
+ trunc_normal_(self.query, std=0.02)
143
+
144
+ self.cross_attn = CrossAttention(kv_dim, embed_dim, num_heads)
145
+
146
+ self.ln_ffn = norm_layer(embed_dim)
147
+ self.ffn = FFN(embed_dim, ff_dim, output_dim)
148
+
149
+ self.apply(self._init_weights)
150
+
151
+ def _init_weights(self, m):
152
+ if isinstance(m, nn.Linear):
153
+ trunc_normal_(m.weight, std=0.02)
154
+ if isinstance(m, nn.Linear) and m.bias is not None:
155
+ nn.init.constant_(m.bias, 0)
156
+ elif isinstance(m, nn.LayerNorm):
157
+ nn.init.constant_(m.bias, 0)
158
+ nn.init.constant_(m.weight, 1.0)
159
+
160
+ def forward(self, x, attn_mask=None):
161
+ """
162
+ Forward pass of the Projector module.
163
+
164
+ Args:
165
+ x (torch.Tensor): Input tensor of shape (batch_size, num_patches, kv_dim).
166
+ attn_mask (torch.Tensor, optional): Attention mask. Default is None.
167
+
168
+ Returns:
169
+ torch.Tensor: Output tensor of shape (batch_size, query_number, output_dim).
170
+ """
171
+ bs = x.shape[0]
172
+ queries = self.query.unsqueeze(0).repeat(bs, 1, 1)
173
+
174
+ query_num = self.patch_to_query_dict.get(x.shape[1], None)
175
+ assert (
176
+ query_num is not None
177
+ ), f"Query number for {x.shape[1]} patches is not provided"
178
+
179
+ queries = queries[:, :query_num, :]
180
+
181
+ if attn_mask is not None:
182
+ attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
183
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
184
+
185
+ attention_out = self.cross_attn(x, queries, attn_mask=attn_mask)
186
+
187
+ out = self.ffn(self.ln_ffn(attention_out))
188
+
189
+ return out
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e429a008ed1045d14464933311e0b3258575980efc9db4e61f368e399c719d2a
3
+ size 1696299
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "100352": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "100353": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}{% elif message['content'] is iterable %}{% for item in message['content'] %}{% if item['type'] == 'text' %}{{ item['text'] }}{% elif item['type'] == 'image' %}<fim_prefix><|img|><fim_suffix>{% endif %}{% endfor %}{% endif %}<|im_end|>\n{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
33
+ "clean_up_tokenization_spaces": false,
34
+ "eos_token": "</s>",
35
+ "legacy": true,
36
+ "model_max_length": 1000000000000000019884624838656,
37
+ "pad_token": null,
38
+ "sp_model_kwargs": {},
39
+ "spaces_between_special_tokens": false,
40
+ "tokenizer_class": "LlamaTokenizer",
41
+ "unk_token": "<unk>",
42
+ "use_default_system_prompt": false
43
+ }
vision_encoder.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ """PyTorch Aria vision transformer."""
21
+
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from transformers import SiglipVisionConfig, SiglipVisionModel
27
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
28
+ from transformers.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer
29
+
30
+
31
+ class AriaVisionConfig(SiglipVisionConfig):
32
+ """Configuration class for AriaVisionModel."""
33
+
34
+ model_type = "aria_vision_model"
35
+
36
+ def __init__(
37
+ self,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(**kwargs)
41
+
42
+
43
+ class IdentityOp(torch.nn.Module):
44
+ """
45
+ An identity operation that returns the input unchanged.
46
+
47
+ This can be used as a placeholder or to maintain architectural consistency
48
+ when a specific operation is not needed.
49
+ """
50
+
51
+ def __init__(self, *args, **kwargs):
52
+ super().__init__()
53
+
54
+ def forward(self, x, *args, **kwargs):
55
+ return x
56
+
57
+
58
+ class AriaVisionTransformer(Idefics2VisionTransformer):
59
+ """
60
+ Aria Vision Transformer model based on Idefics2VisionTransformer.
61
+
62
+ This class extends the original Idefics2VisionTransformer by removing the post-layernorm operation.
63
+ """
64
+
65
+ def __init__(self, config: AriaVisionConfig):
66
+ super().__init__(config)
67
+ self.post_layernorm = IdentityOp()
68
+
69
+
70
+ class AriaVisionModel(SiglipVisionModel):
71
+ """
72
+ Aria Vision Model extends SiglipVisionModel to support pixel_mask.
73
+
74
+ The pixel_mask is a 2D boolean tensor that indicates which pixels in the input
75
+ image are actual content and which are padding. It has the same height and width
76
+ as the input image, where:
77
+ - True (1) values represent pixels from the original image
78
+ - False (0) values represent padding pixels
79
+
80
+ This mask helps the model focus on the relevant parts of the image during processing.
81
+ """
82
+
83
+ config_class = AriaVisionConfig
84
+ main_input_name = "pixel_values"
85
+ _supports_sdpa = False
86
+
87
+ def __init__(self, config: AriaVisionConfig):
88
+ super().__init__(config)
89
+ self.vision_model = AriaVisionTransformer(config)
90
+
91
+ # Initialize weights and apply final processing
92
+ self.post_init()
93
+
94
+ def forward(
95
+ self,
96
+ pixel_values: torch.Tensor,
97
+ pixel_mask: Optional[torch.BoolTensor] = None,
98
+ output_attentions: Optional[bool] = None,
99
+ output_hidden_states: Optional[bool] = None,
100
+ return_dict: Optional[bool] = None,
101
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
102
+ """
103
+ Forward pass of the AriaVisionModel.
104
+
105
+ Args:
106
+ pixel_values (torch.Tensor): The pixel values of the input images.
107
+ pixel_mask (Optional[torch.BoolTensor]): Mask for the pixel values.
108
+ output_attentions (Optional[bool]): Whether to output attentions.
109
+ output_hidden_states (Optional[bool]): Whether to output hidden states.
110
+ return_dict (Optional[bool]): Whether to return a ModelOutput object.
111
+
112
+ Returns:
113
+ Union[Tuple, BaseModelOutputWithPooling]: The model's output.
114
+ """
115
+ return_dict = (
116
+ return_dict if return_dict is not None else self.config.use_return_dict
117
+ )
118
+ patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
119
+
120
+ vit_oup = self.vision_model(
121
+ pixel_values=pixel_values,
122
+ patch_attention_mask=patch_attention_mask,
123
+ output_attentions=output_attentions,
124
+ output_hidden_states=output_hidden_states,
125
+ return_dict=return_dict,
126
+ )
127
+
128
+ image_atts = self._create_image_attention_mask(patch_attention_mask)
129
+
130
+ return vit_oup, image_atts
131
+
132
+ def _create_patch_attention_mask(self, pixel_mask):
133
+ if pixel_mask is None:
134
+ return None
135
+
136
+ patches_subgrid = pixel_mask.unfold(
137
+ dimension=1,
138
+ size=self.vision_model.config.patch_size,
139
+ step=self.vision_model.config.patch_size,
140
+ ).unfold(
141
+ dimension=2,
142
+ size=self.vision_model.config.patch_size,
143
+ step=self.vision_model.config.patch_size,
144
+ )
145
+ return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
146
+
147
+ def _create_image_attention_mask(self, patch_attention_mask):
148
+ if patch_attention_mask is None:
149
+ return None
150
+
151
+ flattened_mask = patch_attention_mask.flatten(1)
152
+ return torch.logical_not(flattened_mask)
vision_processor.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Rhymes AI. All rights reserved.
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing,
14
+ # software distributed under the License is distributed on an
15
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ # KIND, either express or implied. See the License for the
17
+ # specific language governing permissions and limitations
18
+ # under the License.
19
+
20
+ from typing import List, Optional, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from PIL import Image, ImageOps
25
+ from torchvision import transforms
26
+ from transformers import BaseImageProcessor, BatchFeature, TensorType
27
+
28
+
29
+ def _select_best_resolution(
30
+ img_width: int, img_height: int, target_ratios: List[List[int]], patch_size: int
31
+ ):
32
+ """
33
+ Selects the best resolution from a list of possible resolutions based on the original size.
34
+
35
+ Args:
36
+ img_width: the original widths of images.
37
+ img_height: the original heights of images.
38
+ target_ratios (2d numpy array): dimension size (M,2)
39
+ patch_size (int): image patch size
40
+
41
+ Returns:
42
+ tuple: The best fit resolution in the format (width, height).
43
+ """
44
+
45
+ aspect_ratio = img_width / img_height
46
+ best_ratio_diff = float("inf")
47
+ best_ratio_w, best_ratio_h = 1, 1
48
+ area = np.int32(img_height) * np.int32(img_height)
49
+ for ratio in target_ratios:
50
+ target_aspect_ratio = ratio[0] / ratio[1]
51
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
52
+ if ratio_diff < best_ratio_diff:
53
+ best_ratio_diff = ratio_diff
54
+ best_ratio_w, best_ratio_h = ratio[0], ratio[1]
55
+ elif (
56
+ ratio_diff == best_ratio_diff
57
+ and area > 0.5 * patch_size * patch_size * ratio[0] * ratio[1]
58
+ ):
59
+ best_ratio_w, best_ratio_h = ratio[0], ratio[1]
60
+
61
+ return best_ratio_w, best_ratio_h
62
+
63
+
64
+ def _split_image(
65
+ image: Image.Image,
66
+ split_image: bool,
67
+ split_ratio: List[List[int]],
68
+ patch_size: int,
69
+ ) -> List[Image.Image]:
70
+ """
71
+ Split image into multiple patches
72
+
73
+ Args:
74
+ image (PIL.Image): Input image.
75
+ split_image (bool): Whether to split the image into patches.
76
+ split_ratio (2d numpy array): dimension size (M,2)
77
+ patch_size (int): image patch size
78
+
79
+ Returns:
80
+ List[PIL.Image]: List of splitted images.
81
+ """
82
+ if split_image:
83
+ ratio_width, ratio_height = _select_best_resolution(
84
+ image.width, image.height, split_ratio, patch_size
85
+ )
86
+ resize_width = patch_size * ratio_width
87
+ resize_height = patch_size * ratio_height
88
+ blocks = ratio_width * ratio_height
89
+ resized_img = image.resize((resize_width, resize_height))
90
+ processed_images = []
91
+ for i in range(blocks):
92
+ box = (
93
+ (i % (resize_width // patch_size)) * patch_size,
94
+ (i // (resize_width // patch_size)) * patch_size,
95
+ ((i % (resize_width // patch_size)) + 1) * patch_size,
96
+ ((i // (resize_width // patch_size)) + 1) * patch_size,
97
+ )
98
+ # split the image
99
+ split_img = resized_img.crop(box)
100
+ processed_images.append(split_img)
101
+ assert len(processed_images) == blocks
102
+ if len(processed_images) != 1:
103
+ processed_images.insert(0, image)
104
+ return processed_images
105
+ else:
106
+ return [image]
107
+
108
+
109
+ def keep_ratio_resize_and_pixel_mask(
110
+ img: Image.Image, max_size, min_size=336, padding_value=0
111
+ ):
112
+ """
113
+ Resize an image while maintaining aspect ratio and create a pixel mask.
114
+
115
+ Args:
116
+ img (PIL.Image): Input image.
117
+ max_size (int): Maximum size for the larger dimension of the image.
118
+ min_size (int, optional): Minimum size for the smaller dimension. Defaults to 336.
119
+ padding_value (int, optional): Value used for padding. Defaults to 0.
120
+
121
+ Returns:
122
+ tuple: A tuple containing:
123
+ - PIL.Image: Resized and padded image.
124
+ - torch.Tensor: Boolean pixel mask. This mask is a 2D tensor of shape (max_size, max_size) where:
125
+ - True (1) values indicate pixels that belong to the original resized image.
126
+ - False (0) values indicate pixels that are part of the padding.
127
+ The mask helps distinguish between actual image content and padded areas in subsequent processing steps.
128
+ """
129
+ img = img.convert("RGB")
130
+ # rescale the given image, keep the aspect ratio
131
+ scale = max_size / max(img.size)
132
+
133
+ w, h = img.size
134
+ if w >= h:
135
+ new_size = (max_size, max(int(h * scale), min_size)) # w, h
136
+ else:
137
+ new_size = (max(int(w * scale), min_size), max_size) # w, h
138
+
139
+ img_resized = img.resize(new_size, resample=Image.Resampling.BICUBIC)
140
+
141
+ # padding the right/bottom
142
+ padding_right, padding_bottom = max_size - new_size[0], max_size - new_size[1]
143
+ img_padded = ImageOps.expand(
144
+ img_resized, (0, 0, padding_right, padding_bottom), fill=padding_value
145
+ )
146
+
147
+ # Create a pixel mask
148
+ pixel_mask = torch.zeros(max_size, max_size)
149
+ pixel_mask[: new_size[1], : new_size[0]] = 1
150
+ pixel_mask = pixel_mask.bool()
151
+ return img_padded, pixel_mask
152
+
153
+
154
+ class AriaVisionProcessor(BaseImageProcessor):
155
+ """
156
+ A vision processor for the Aria model that handles image preprocessing.
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ max_image_size=980,
162
+ min_image_size=336,
163
+ image_mean=[0.5, 0.5, 0.5],
164
+ image_std=[0.5, 0.5, 0.5],
165
+ **kwargs,
166
+ ):
167
+ """
168
+ Initialize the AriaVisionProcessor.
169
+
170
+ Args:
171
+ max_image_size (int, optional): Maximum image size. Defaults to 980.
172
+ min_image_size (int, optional): Minimum image size. Defaults to 336.
173
+ mean (list, optional): Mean values for normalization. Defaults to [0.5, 0.5, 0.5].
174
+ std (list, optional): Standard deviation values for normalization. Defaults to [0.5, 0.5, 0.5].
175
+ """
176
+ super().__init__(**kwargs)
177
+
178
+ self.max_image_size = max_image_size
179
+ self.min_image_size = min_image_size
180
+ self.image_mean = image_mean
181
+ self.image_std = image_std
182
+ self.auto_map = {
183
+ "AutoProcessor": "processing_aria.AriaProcessor",
184
+ "AutoImageProcessor": "vision_processor.AriaVisionProcessor",
185
+ }
186
+
187
+ # we make the transform a property so that it is lazily initialized,
188
+ # this could avoid the error "TypeError: Object of type Normalize is not JSON serializable"
189
+ # when we used save_pretrained or from_pretrained.
190
+ self._transform = None
191
+ self._set_processor_class("AriaProcessor")
192
+
193
+ @property
194
+ def transform(self):
195
+ if self._transform is None:
196
+ # Recreate the transform when accessed
197
+ self._transform = transforms.Compose(
198
+ [
199
+ transforms.ToTensor(),
200
+ transforms.Normalize(self.image_mean, self.image_std),
201
+ ]
202
+ )
203
+ return self._transform
204
+
205
+ def __call__(
206
+ self,
207
+ images: Union[Image.Image, List[Image.Image]],
208
+ max_image_size: Optional[int] = 980,
209
+ min_image_size: Optional[int] = 336,
210
+ return_tensors: Optional[Union[str, TensorType]] = "pt",
211
+ split_image: Optional[bool] = False,
212
+ split_ratio: Optional[List[List[int]]] = [
213
+ [1, 2],
214
+ [1, 3],
215
+ [1, 4],
216
+ [1, 5],
217
+ [1, 6],
218
+ [1, 7],
219
+ [1, 8],
220
+ [2, 4],
221
+ [2, 3],
222
+ [2, 2],
223
+ [2, 1],
224
+ [3, 1],
225
+ [3, 2],
226
+ [4, 1],
227
+ [4, 2],
228
+ [5, 1],
229
+ [6, 1],
230
+ [7, 1],
231
+ [8, 1],
232
+ ],
233
+ ):
234
+ """
235
+ Process a list of images.
236
+
237
+ Args:
238
+ images (list): List of PIL.Image objects.
239
+ max_image_size (int, optional): Override the default max image size. Defaults to None.
240
+ return_tensors (str or TensorType, optional): The type of tensor to return. Defaults to "pt".
241
+ split_image (bool, optional): Whether to split the image. Defaults to False.
242
+ split_ratio (list, optional): The ratio for splitting the image. Defaults to a list of common split ratios.
243
+ Returns:
244
+ BatchFeature: A BatchFeature object containing:
245
+ - 'pixel_values': Tensor of processed image pixel values.
246
+ - 'pixel_mask': Boolean pixel mask. This mask is a 2D tensor of shape (max_size, max_size) where:
247
+ - True (1) values indicate pixels that belong to the original resized image.
248
+ - False (0) values indicate pixels that are part of the padding.
249
+ The mask helps distinguish between actual image content and padded areas in subsequent processing steps.
250
+ - 'num_crops': Tensor of the number of crops for each image.
251
+ """
252
+ max_size = self.max_image_size if max_image_size is None else max_image_size
253
+ min_size = self.min_image_size if min_image_size is None else min_image_size
254
+
255
+ if max_size not in [490, 980]:
256
+ raise ValueError("max_image_size must be either 490 or 980")
257
+
258
+ if isinstance(images, Image.Image):
259
+ images = [images]
260
+
261
+ pixel_values = []
262
+ pixel_masks = []
263
+ num_crops = []
264
+
265
+ for image in images:
266
+ crop_images = _split_image(image, split_image, split_ratio, max_size)
267
+ num_crops.append(torch.tensor(len(crop_images)))
268
+ for crop_image in crop_images:
269
+ img_padded, pixel_mask = keep_ratio_resize_and_pixel_mask(
270
+ crop_image, max_size, min_size
271
+ )
272
+ img_padded = self.transform(img_padded)
273
+ pixel_values.append(img_padded)
274
+ pixel_masks.append(pixel_mask)
275
+
276
+ return BatchFeature(
277
+ data={
278
+ "pixel_values": torch.stack(pixel_values),
279
+ "pixel_mask": torch.stack(pixel_masks),
280
+ "num_crops": torch.stack(num_crops),
281
+ },
282
+ tensor_type=return_tensors,
283
+ )
284
+
285
+ def preprocess(
286
+ self,
287
+ images,
288
+ max_image_size=None,
289
+ min_image_size=None,
290
+ return_tensors: Optional[Union[str, TensorType]] = None,
291
+ split_image: Optional[bool] = False,
292
+ split_ratio: Optional[List[List[int]]] = [
293
+ [1, 2],
294
+ [1, 3],
295
+ [1, 4],
296
+ [1, 5],
297
+ [1, 6],
298
+ [1, 7],
299
+ [1, 8],
300
+ [2, 4],
301
+ [2, 3],
302
+ [2, 2],
303
+ [2, 1],
304
+ [3, 1],
305
+ [3, 2],
306
+ [4, 1],
307
+ [4, 2],
308
+ [5, 1],
309
+ [6, 1],
310
+ [7, 1],
311
+ [8, 1],
312
+ ],
313
+ ):
314
+ return self.__call__(
315
+ images,
316
+ max_image_size=max_image_size,
317
+ min_image_size=min_image_size,
318
+ return_tensors=return_tensors,
319
+ split_image=split_image,
320
+ split_ratio=split_ratio,
321
+ )