Feature Extraction
Transformers
Safetensors
English
Chinese
emova
Omni-modal-LLM
Multi-modal-LLM
Emotional-spoken-dialogue
custom_code
Eval Results
KaiChen1998 commited on
Commit
4153415
·
verified ·
1 Parent(s): 709a849

Upload 3 files

Browse files
Files changed (3) hide show
  1. modeling_emova.py +816 -0
  2. modeling_qwen2vit.py +335 -0
  3. modeling_rope_utils.py +558 -0
modeling_emova.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch EMOVA model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from functools import partial
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+
27
+ from transformers import PreTrainedModel
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache
30
+ from transformers.image_processing_utils import select_best_resolution
31
+ from transformers.modeling_outputs import ModelOutput
32
+ from transformers.utils import (
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ replace_return_docstrings,
37
+ )
38
+ from transformers.models.auto import AutoModel, AutoModelForCausalLM
39
+
40
+ from .configuration_emova import EMOVAConfig
41
+ from .modeling_qwen2vit import Qwen2VisionTower
42
+
43
+ from timm.models.regnet import RegStage
44
+
45
+ try:
46
+ from timm.layers import LayerNorm2d
47
+ except:
48
+ from timm.models.layers import LayerNorm2d
49
+ from einops import rearrange
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CONFIG_FOR_DOC = "EMOVAConfig"
54
+
55
+
56
+ @dataclass
57
+ class EMOVACausalLMOutputWithPast(ModelOutput):
58
+ """
59
+ Base class for EMOVA causal language model (or autoregressive) outputs.
60
+
61
+ Args:
62
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
63
+ Language modeling loss (for next-token prediction).
64
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
65
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
66
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
67
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
68
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
69
+
70
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
71
+ `past_key_values` input) to speed up sequential decoding.
72
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
74
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
75
+
76
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
77
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
78
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
79
+ sequence_length)`.
80
+
81
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
82
+ heads.
83
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
84
+ Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
85
+ sequence_length, hidden_size)`.
86
+
87
+ image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
88
+ """
89
+
90
+ loss: Optional[torch.FloatTensor] = None
91
+ logits: torch.FloatTensor = None
92
+ past_key_values: Optional[List[torch.FloatTensor]] = None
93
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
94
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
95
+ image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
96
+
97
+
98
+ class EMOVAMultiModalProjector(nn.Sequential):
99
+ # CAbstractor
100
+ def __init__(self, config):
101
+ super(EMOVAMultiModalProjector, self).__init__()
102
+ hidden_size = config.text_config.hidden_size
103
+ mm_hidden_size = config.vision_config.hidden_size
104
+ mlp_depth = config.mm_projector_config['mlp_depth']
105
+
106
+ modules = [nn.Linear(mm_hidden_size, hidden_size)]
107
+ for _ in range(1, mlp_depth):
108
+ modules.append(nn.GELU())
109
+ modules.append(nn.Linear(hidden_size, hidden_size))
110
+ super(EMOVAMultiModalProjector, self).__init__(*modules)
111
+
112
+
113
+ EMOVA_START_DOCSTRING = r"""
114
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
115
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
116
+ etc.)
117
+
118
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
119
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
120
+ and behavior.
121
+
122
+ Parameters:
123
+ config ([`EMOVAConfig`] or [`EMOVAVisionConfig`]):
124
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
125
+ load the weights associated with the model, only the configuration. Check out the
126
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
127
+ """
128
+
129
+
130
+ @add_start_docstrings(
131
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
132
+ EMOVA_START_DOCSTRING,
133
+ )
134
+ class EMOVAPreTrainedModel(PreTrainedModel):
135
+ config_class = EMOVAConfig
136
+ base_model_prefix = "model"
137
+ supports_gradient_checkpointing = True
138
+ _no_split_modules = ["EMOVAVisionAttention"]
139
+ _skip_keys_device_placement = "past_key_values"
140
+ _supports_flash_attn_2 = True
141
+ _supports_cache_class = True
142
+
143
+ def _init_weights(self, module):
144
+ std = (
145
+ self.config.initializer_range
146
+ if hasattr(self.config, "initializer_range")
147
+ else self.config.text_config.initializer_range
148
+ )
149
+
150
+ if hasattr(module, "class_embedding"):
151
+ module.class_embedding.data.normal_(mean=0.0, std=std)
152
+
153
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
154
+ module.weight.data.normal_(mean=0.0, std=std)
155
+ if module.bias is not None:
156
+ module.bias.data.zero_()
157
+ elif isinstance(module, nn.Embedding):
158
+ module.weight.data.normal_(mean=0.0, std=std)
159
+ if module.padding_idx is not None:
160
+ module.weight.data[module.padding_idx].zero_()
161
+
162
+ @property
163
+ def _supports_sdpa(self):
164
+ """
165
+ Retrieve language_model's attribute to check whether the model supports
166
+ SDPA or not.
167
+ """
168
+ return self.language_model._supports_sdpa
169
+
170
+
171
+ EMOVA_INPUTS_DOCSTRING = r"""
172
+ Args:
173
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
174
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
175
+ it.
176
+
177
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
178
+ [`PreTrainedTokenizer.__call__`] for details.
179
+
180
+ [What are input IDs?](../glossary#input-ids)
181
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
182
+ The tensors corresponding to the input images. Pixel values can be obtained using
183
+ [`AutoImageProcessor`]. See [`EMOVAImageProcessor.__call__`] for details. [`EMOVAProcessor`] uses
184
+ [`EMOVAImageProcessor`] for processing images.
185
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
186
+ The sizes of the images in the batch, being (height, width) for each image.
187
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
188
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
189
+
190
+ - 1 for tokens that are **not masked**,
191
+ - 0 for tokens that are **masked**.
192
+
193
+ [What are attention masks?](../glossary#attention-mask)
194
+
195
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
196
+ [`PreTrainedTokenizer.__call__`] for details.
197
+
198
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
199
+ `past_key_values`).
200
+
201
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
202
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
203
+ information on the default strategy.
204
+
205
+ - 1 indicates the head is **not masked**,
206
+ - 0 indicates the head is **masked**.
207
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
208
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
209
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
210
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
211
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
212
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
213
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
214
+
215
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
216
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
217
+
218
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
219
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
220
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
221
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
222
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
223
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
224
+ model's internal embedding lookup matrix.
225
+ vision_feature_layer (`int`, *optional*, defaults to -2):
226
+ The index of the layer to select the vision feature.
227
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
228
+ The feature selection strategy used to select the vision feature from the vision backbone.
229
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
230
+ If `"full"`, the full vision features are used.
231
+ use_cache (`bool`, *optional*):
232
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
233
+ `past_key_values`).
234
+ output_attentions (`bool`, *optional*):
235
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
236
+ tensors for more detail.
237
+ output_hidden_states (`bool`, *optional*):
238
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
239
+ more detail.
240
+ return_dict (`bool`, *optional*):
241
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
242
+ """
243
+
244
+
245
+ @add_start_docstrings(
246
+ """The EMOVA model which consists of a vision backbone and a language model.""",
247
+ EMOVA_START_DOCSTRING,
248
+ )
249
+ class EMOVAForConditionalGeneration(EMOVAPreTrainedModel):
250
+ def __init__(self, config: EMOVAConfig, **kwargs):
251
+ super().__init__(config)
252
+ self.vision_tower = Qwen2VisionTower(config.vision_config)
253
+ self.multi_modal_projector = EMOVAMultiModalProjector(config)
254
+
255
+ self.vocab_size = config.text_config.vocab_size
256
+ self.language_model = AutoModelForCausalLM.from_config(
257
+ config.text_config, attn_implementation=config._attn_implementation
258
+ )
259
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
260
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
261
+ self.post_init()
262
+
263
+ @property
264
+ def padding_side(self):
265
+ return self._padding_side
266
+
267
+ @padding_side.setter
268
+ def padding_side(self, padding_side: str):
269
+ if padding_side not in ["left", "right"]:
270
+ raise ValueError(f"{padding_side} is not `left` or `right`.")
271
+ self._padding_side = padding_side
272
+
273
+ def get_input_embeddings(self):
274
+ return self.language_model.get_input_embeddings()
275
+
276
+ def set_input_embeddings(self, value):
277
+ self.language_model.set_input_embeddings(value)
278
+
279
+ def get_output_embeddings(self):
280
+ return self.language_model.get_output_embeddings()
281
+
282
+ def set_output_embeddings(self, new_embeddings):
283
+ self.language_model.set_output_embeddings(new_embeddings)
284
+
285
+ def set_decoder(self, decoder):
286
+ self.language_model.set_decoder(decoder)
287
+
288
+ def get_decoder(self):
289
+ return self.language_model.get_decoder()
290
+
291
+ def tie_weights(self):
292
+ return self.language_model.tie_weights()
293
+
294
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
295
+ model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
296
+ # update vocab size
297
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
298
+ self.vocab_size = model_embeds.num_embeddings
299
+ return model_embeds
300
+
301
+ def _merge_input_ids_with_image_features(
302
+ self,
303
+ image_features,
304
+ feature_lens,
305
+ inputs_embeds,
306
+ input_ids,
307
+ attention_mask,
308
+ position_ids=None,
309
+ labels=None,
310
+ image_token_index=None,
311
+ ignore_index=-100,
312
+ ):
313
+ """
314
+ Merge input_ids with with image features into final embeddings
315
+
316
+ Args:
317
+ image_features (`torch.Tensor` of shape `(all_feature_lens, embed_dim)`):
318
+ All vision vectors of all images in the batch
319
+ feature_lens (`torch.LongTensor` of shape `(num_images)`):
320
+ The length of visual embeddings of each image as stacked in `image_features`
321
+ inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, embed_dim)`):
322
+ Token embeddings before merging with visual embeddings
323
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
324
+ Input_ids of tokens, possibly filled with image token
325
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
326
+ Mask to avoid performing attention on padding token indices.
327
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
328
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
329
+ config.n_positions - 1]`.
330
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*)
331
+ :abels need to be recalculated to support training (if provided)
332
+ image_token_index (`int`, *optional*)
333
+ Token id used to indicate the special "image" token. Defaults to `config.image_token_index`
334
+ ignore_index (`int`, *optional*)
335
+ Value that is used to pad `labels` and will be ignored when calculated loss. Default: -100.
336
+ Returns:
337
+ final_embedding, final_attention_mask, position_ids, final_labels
338
+
339
+ Explanation:
340
+ each image has variable length embeddings, with length specified by feature_lens
341
+ image_features is concatenation of all visual embed vectors
342
+ task: fill each <image> with the correct number of visual embeddings
343
+ Example:
344
+ X (5 patches), Y (3 patches), Z (8)
345
+ X, Y are in the same sequence (in-context learning)
346
+ if right padding
347
+ input_ids: [
348
+ a b c d e f X g h i j k Y l m
349
+ o p q r Z s t u v _ _ _ _ _ _
350
+ ]
351
+ input_ids should be: [
352
+ a b c d e f X X X X X g h i j k Y Y Y l m
353
+ o p q r Z Z Z Z Z Z Z Z s t u v _ _ _ _ _
354
+ ]
355
+ labels should be: [
356
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
357
+ o p q r _ _ _ _ _ _ _ _ s t u v _ _ _ _ _
358
+ ]
359
+ elif left padding
360
+ input_ids: [
361
+ a b c d e f X g h i j k Y l m
362
+ _ _ _ _ _ _ o p q r Z s t u v
363
+ ]
364
+ input_ids should be: [
365
+ a b c d e f X X X X X g h i j k Y Y Y l m
366
+ _ _ _ _ _ o p q r Z Z Z Z Z Z Z Z s t u v
367
+ ]
368
+ labels should be: [
369
+ a b c d e f _ _ _ _ _ g h i j k _ _ _ l m
370
+ _ _ _ _ _ o p q r _ _ _ _ _ _ _ _ s t u v
371
+ ]
372
+ Edge cases:
373
+ * If tokens are same but image token sizes are different, then cannot infer left or right padding
374
+ ```python
375
+ cat_img = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
376
+ chart_img = Image.open(requests.get("https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true", stream=True).raw)
377
+ prompts = [
378
+ "[INST] <image>\nWhat is shown in this image? [/INST]",
379
+ "[INST] <image>\nWhat is shown in this image? [/INST]",
380
+ ]
381
+ inputs = processor(prompts, [chart_img, cat_img], return_tensors='pt', padding=True).to("cuda")
382
+ chart_img has 2634 tokens, while cat_img has 2340 tokens
383
+ ```
384
+
385
+ input_ids: [
386
+ a b c d X g h
387
+ i j Y k l m n
388
+ ]
389
+ where X is 3 tokens while Y is 5, this mean after merge
390
+ if left-padding (batched generation)
391
+ input_ids should be: [
392
+ _ _ a b c d X X X g h
393
+ i j Y Y Y Y Y k l m n
394
+ ]
395
+ elif (right padding) (training)
396
+ input_ids should be: [
397
+ a b c d X X X g h _ _
398
+ i j Y Y Y Y Y k l m n
399
+ ]
400
+ """
401
+ image_token_index = image_token_index if image_token_index is not None else self.config.image_token_index
402
+ ignore_index = ignore_index if ignore_index is not None else self.config.ignore_index
403
+
404
+ with torch.no_grad():
405
+ num_images = feature_lens.size(0)
406
+ num_image_features, embed_dim = image_features.shape
407
+ if feature_lens.sum() != num_image_features:
408
+ raise ValueError(f"{feature_lens=} / {feature_lens.sum()} != {image_features.shape=}")
409
+ batch_size = input_ids.shape[0]
410
+ _left_padding = torch.any(attention_mask[:, 0] == 0)
411
+ _right_padding = torch.any(attention_mask[:, -1] == 0)
412
+
413
+ left_padding = True if not self.training else False
414
+ if batch_size > 1 and not self.training:
415
+ if _left_padding and not _right_padding:
416
+ left_padding = True
417
+ elif not _left_padding and _right_padding:
418
+ left_padding = False
419
+ elif not _left_padding and not _right_padding:
420
+ # both side is 1, so cannot tell
421
+ left_padding = self.padding_side == "left"
422
+ else:
423
+ # invalid attention_mask
424
+ raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
425
+
426
+ # Whether to turn off right padding
427
+ # 1. Create a mask to know where special image tokens are
428
+ special_image_token_mask = input_ids == image_token_index
429
+ # special_image_token_mask: [bsz, seqlen]
430
+ num_special_image_tokens = torch.sum(special_image_token_mask, dim=-1)
431
+ # num_special_image_tokens: [bsz]
432
+ # Reserve for padding of num_images
433
+ total_num_special_image_tokens = torch.sum(special_image_token_mask)
434
+ if total_num_special_image_tokens != num_images:
435
+ raise ValueError(
436
+ f"Number of image tokens in input_ids ({total_num_special_image_tokens}) different from num_images ({num_images})."
437
+ )
438
+ # Compute the maximum embed dimension
439
+ # max_image_feature_lens is max_feature_lens per batch
440
+ feature_lens = feature_lens.to(input_ids.device)
441
+ feature_lens_batch = feature_lens.split(num_special_image_tokens.tolist(), dim=0)
442
+ feature_lens_batch_sum = torch.tensor([x.sum() for x in feature_lens_batch], device=input_ids.device)
443
+ embed_sequence_lengths = (
444
+ (attention_mask == 1).long().sum(-1) - num_special_image_tokens + feature_lens_batch_sum
445
+ )
446
+ max_embed_dim = embed_sequence_lengths.max()
447
+
448
+ batch_indices, non_image_indices = torch.where((input_ids != image_token_index) & (attention_mask == 1))
449
+ # 2. Compute the positions where text should be written
450
+ # Calculate new positions for text tokens in merged image-text sequence.
451
+ # `special_image_token_mask` identifies image tokens. Each image token will be replaced by `nb_text_tokens_per_images` text tokens.
452
+ # `torch.cumsum` computes how each image token shifts subsequent text token positions.
453
+ # - 1 to adjust for zero-based indexing, as `cumsum` inherently increases indices by one.
454
+ # ! instead of special_image_token_mask * (num_image_patches - 1)
455
+ # special_image_token_mask * (num_feature_len - 1)
456
+ special_image_token_mask = special_image_token_mask.long()
457
+ special_image_token_mask[special_image_token_mask == 1] = feature_lens - 1
458
+ new_token_positions = torch.cumsum((special_image_token_mask + 1), -1) - 1
459
+ if left_padding:
460
+ # shift right token positions so that they are ending at the same number
461
+ # the below here was incorrect? new_token_positions += new_token_positions[:, -1].max() - new_token_positions[:, -1:]
462
+ new_token_positions += max_embed_dim - 1 - new_token_positions[:, -1:]
463
+
464
+ text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
465
+
466
+ # 3. Create the full embedding, already padded to the maximum position
467
+ final_embedding = torch.zeros(
468
+ batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
469
+ )
470
+ final_attention_mask = torch.zeros(
471
+ batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device
472
+ )
473
+ final_input_ids = torch.full(
474
+ (batch_size, max_embed_dim), self.pad_token_id, dtype=input_ids.dtype, device=inputs_embeds.device
475
+ )
476
+ # In case the Vision model or the Language model has been offloaded to CPU, we need to manually
477
+ # set the corresponding tensors into their correct target device.
478
+ target_device = inputs_embeds.device
479
+ batch_indices, non_image_indices, text_to_overwrite = (
480
+ batch_indices.to(target_device),
481
+ non_image_indices.to(target_device),
482
+ text_to_overwrite.to(target_device),
483
+ )
484
+ attention_mask = attention_mask.to(target_device)
485
+ input_ids = input_ids.to(target_device)
486
+
487
+ # 4. Fill the embeddings based on the mask. If we have ["hey" "<image>", "how", "are"]
488
+ # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the image features
489
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_image_indices]
490
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_image_indices]
491
+ final_input_ids[batch_indices, text_to_overwrite] = input_ids[batch_indices, non_image_indices]
492
+ final_labels = None
493
+ if labels is not None:
494
+ labels = labels.to(target_device)
495
+ final_labels = torch.full_like(final_attention_mask, ignore_index).to(torch.long)
496
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_image_indices]
497
+
498
+ # 5. Fill the embeddings corresponding to the images. Anything that is not `text_positions` needs filling (#29835)
499
+ with torch.no_grad():
500
+ image_to_overwrite = torch.full(
501
+ (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
502
+ )
503
+ image_to_overwrite[batch_indices, text_to_overwrite] = False
504
+ embed_indices = torch.arange(max_embed_dim).unsqueeze(0).to(target_device)
505
+ embed_indices = embed_indices.expand(batch_size, max_embed_dim)
506
+ embed_seq_lens = embed_sequence_lengths[:, None].to(target_device)
507
+
508
+ if left_padding:
509
+ # exclude padding on the left
510
+ max_embed_dim = max_embed_dim.to(target_device)
511
+ val = (max_embed_dim - embed_indices) <= embed_seq_lens
512
+ else:
513
+ # exclude padding on the right
514
+ val = embed_indices < embed_seq_lens
515
+ image_to_overwrite &= val
516
+
517
+ if image_to_overwrite.sum() != num_image_features:
518
+ raise ValueError(
519
+ f"{image_to_overwrite.sum()=} != {num_image_features=} The input provided to the model are wrong. "
520
+ f"The number of image tokens is {torch.sum(special_image_token_mask)} while"
521
+ f" the number of image given to the model is {num_images}. "
522
+ f"This prevents correct indexing and breaks batch generation."
523
+ )
524
+ final_embedding[image_to_overwrite] = image_features.contiguous().reshape(-1, embed_dim).to(target_device)
525
+ final_attention_mask |= image_to_overwrite
526
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
527
+
528
+ return final_embedding, final_attention_mask, position_ids, final_labels, final_input_ids
529
+
530
+ @add_start_docstrings_to_model_forward(EMOVA_INPUTS_DOCSTRING)
531
+ @replace_return_docstrings(output_type=EMOVACausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
532
+ def forward(
533
+ self,
534
+ input_ids: torch.LongTensor = None,
535
+ pixel_values: torch.FloatTensor = None,
536
+ image_sizes: Optional[torch.LongTensor] = None,
537
+ attention_mask: Optional[torch.Tensor] = None,
538
+ position_ids: Optional[torch.LongTensor] = None,
539
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
540
+ inputs_embeds: Optional[torch.FloatTensor] = None,
541
+ vision_feature_layer: Optional[int] = None,
542
+ vision_feature_select_strategy: Optional[str] = None,
543
+ labels: Optional[torch.LongTensor] = None,
544
+ use_cache: Optional[bool] = None,
545
+ output_attentions: Optional[bool] = None,
546
+ output_hidden_states: Optional[bool] = None,
547
+ return_dict: Optional[bool] = None,
548
+ ) -> Union[Tuple, EMOVACausalLMOutputWithPast]:
549
+ r"""
550
+ Args:
551
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
552
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
553
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
554
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
555
+
556
+ Returns:
557
+
558
+ Example:
559
+
560
+ ```python
561
+ >>> from PIL import Image
562
+ >>> import requests
563
+ >>> from transformers import AutoProcessor, EMOVAForConditionalGeneration
564
+
565
+ >>> model = EMOVAForConditionalGeneration.from_pretrained("Emova-ollm/emova-qwen-2-5-7b-hf")
566
+ >>> processor = AutoProcessor.from_pretrained("Emova-ollm/emova-qwen-2-5-7b-hf")
567
+
568
+ >>> prompt = "<image>\nWhat is shown in this image?"
569
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
570
+ >>> image = Image.open(requests.get(url, stream=True).raw)
571
+
572
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
573
+
574
+ >>> # Generate
575
+ >>> generate_ids = model.generate(**inputs, max_length=30)
576
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
577
+ "\nWhat is shown in this image? The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
578
+ ```"""
579
+
580
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
581
+ output_hidden_states = (
582
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
583
+ )
584
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
585
+
586
+ if inputs_embeds is None:
587
+ # 1. Extract the input embeddings
588
+ # In case image_token_index is not in the embeddings (extra token but embedding don't have it)
589
+ for_inputs_embeds_ids = input_ids.clone()
590
+ for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
591
+ inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
592
+
593
+ # 2. Merge text and images
594
+ if pixel_values is not None and input_ids.shape[1] != 1 and pixel_values.size(0) > 0:
595
+ # ! infer image_num_patches from image_sizes
596
+
597
+ image_features = self.vision_tower(pixel_values.to(self.dtype), image_sizes)
598
+ image_features = self.multi_modal_projector(image_features)
599
+
600
+ spatial_merge_size = self.vision_tower.spatial_merge_size
601
+ feature_lens = torch.as_tensor(
602
+ [t * h * w // (self.vision_tower.spatial_merge_size ** 2) for t, h, w in image_sizes])
603
+ image_num_patches = sum(feature_lens)
604
+
605
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
606
+ inputs_embeds = inputs_embeds.to(image_features.dtype)
607
+ inputs_embeds, attention_mask, position_ids, labels, _ = self._merge_input_ids_with_image_features(
608
+ image_features,
609
+ feature_lens,
610
+ inputs_embeds,
611
+ input_ids,
612
+ attention_mask,
613
+ position_ids,
614
+ labels=labels,
615
+ )
616
+
617
+ # pixel_values is not None but is empty ---> text only cases
618
+ elif pixel_values is not None and input_ids.shape[1] != 1 and pixel_values.size(0) == 0:
619
+ # there are no images
620
+ pass
621
+
622
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
623
+ # generation with cache
624
+ elif past_key_values is not None and pixel_values is not None and input_ids.shape[1] == 1:
625
+ # Retrieve the first layer to inspect the logits and mask out the hidden states
626
+ # that are set to 0
627
+ first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]
628
+
629
+ # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
630
+ batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)
631
+
632
+ # Get the target length
633
+ target_length = input_ids.shape[1]
634
+ past_length = first_layer_past_key_value.shape[-1]
635
+
636
+ extended_attention_mask = torch.ones(
637
+ (attention_mask.shape[0], past_length),
638
+ dtype=attention_mask.dtype,
639
+ device=attention_mask.device,
640
+ )
641
+
642
+ # Filter out only the tokens that can be un-attended, this can happen
643
+ # if one uses EMOVA + Fused modules where the cache on the
644
+ # first iteration is already big enough, or if one passes custom cache
645
+ valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
646
+ new_batch_index = batch_index[valid_indices]
647
+ new_non_attended_tokens = non_attended_tokens[valid_indices]
648
+
649
+ # Zero-out the places where we don't need to attend
650
+ extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0
651
+
652
+ attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)
653
+
654
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
655
+
656
+ outputs = self.language_model(
657
+ attention_mask=attention_mask.to(inputs_embeds.device),
658
+ position_ids=position_ids,
659
+ past_key_values=past_key_values,
660
+ inputs_embeds=inputs_embeds,
661
+ use_cache=use_cache,
662
+ output_attentions=output_attentions,
663
+ output_hidden_states=output_hidden_states,
664
+ return_dict=return_dict,
665
+ )
666
+
667
+ logits = outputs[0]
668
+
669
+ loss = None
670
+ if labels is not None:
671
+ # Shift so that tokens < n predict n
672
+ if attention_mask is not None:
673
+ shift_attention_mask = attention_mask[..., 1:]
674
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
675
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
676
+ else:
677
+ shift_logits = logits[..., :-1, :].contiguous()
678
+ shift_labels = labels[..., 1:].contiguous()
679
+ # Flatten the tokens
680
+ loss_fct = nn.CrossEntropyLoss()
681
+ loss = loss_fct(
682
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
683
+ )
684
+
685
+ if not return_dict:
686
+ output = (logits,) + outputs[1:]
687
+ return (loss,) + output if loss is not None else output
688
+
689
+ return EMOVACausalLMOutputWithPast(
690
+ loss=loss,
691
+ logits=logits,
692
+ past_key_values=outputs.past_key_values,
693
+ hidden_states=outputs.hidden_states,
694
+ attentions=outputs.attentions,
695
+ )
696
+
697
+ def prepare_inputs_for_generation(
698
+ self,
699
+ input_ids,
700
+ past_key_values=None,
701
+ inputs_embeds=None,
702
+ pixel_values=None,
703
+ image_sizes=None,
704
+ attention_mask=None,
705
+ **kwargs,
706
+ ):
707
+ if past_key_values is not None:
708
+ if isinstance(past_key_values, Cache):
709
+ cache_length = past_key_values.get_seq_length()
710
+ past_length = past_key_values.seen_tokens
711
+ else:
712
+ cache_length = past_length = past_key_values[0][0].shape[2]
713
+
714
+ # Keep only the unprocessed tokens:
715
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
716
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
717
+ # input)
718
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
719
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
720
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
721
+ # input_ids based on the past_length.
722
+ elif past_length < input_ids.shape[1]:
723
+ input_ids = input_ids[:, past_length:]
724
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
725
+ elif self.config.image_token_index in input_ids:
726
+ input_ids = input_ids[:, input_ids.shape[1] - 1:]
727
+ # If the cache has seen more tokens than it can hold, then the cache has a size limit. Let's discard the
728
+ # older attention values, as their corresponding values are not part of the input.
729
+ if cache_length < past_length and attention_mask is not None:
730
+ attention_mask = attention_mask[:, -(cache_length + input_ids.shape[1]):]
731
+
732
+ position_ids = kwargs.get("position_ids", None)
733
+ if attention_mask is not None and position_ids is None:
734
+ # create position_ids on the fly for batch generation
735
+ position_ids = attention_mask.long().cumsum(-1) - 1
736
+ position_ids.masked_fill_(attention_mask == 0, 1)
737
+ if past_key_values:
738
+ position_ids = position_ids[:, -input_ids.shape[1]:]
739
+
740
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
741
+ if inputs_embeds is not None and past_key_values is None:
742
+ model_inputs = {"inputs_embeds": inputs_embeds}
743
+ else:
744
+ model_inputs = {"input_ids": input_ids}
745
+
746
+ model_inputs.update(
747
+ {
748
+ "position_ids": position_ids,
749
+ "past_key_values": past_key_values,
750
+ "use_cache": kwargs.get("use_cache"),
751
+ "attention_mask": attention_mask,
752
+ "pixel_values": pixel_values,
753
+ "image_sizes": image_sizes,
754
+ }
755
+ )
756
+ return model_inputs
757
+
758
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
759
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
760
+ verbose=False):
761
+ raise RuntimeError("!!!")
762
+
763
+ if history is None and pixel_values is not None and '<image>' not in question:
764
+ question = '<image>\n' + question
765
+
766
+ if num_patches_list is None:
767
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
768
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
769
+
770
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
771
+ self.img_context_token_id = img_context_token_id
772
+
773
+ template = get_conv_template(self.template)
774
+ template.system_message = self.system_message
775
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
776
+
777
+ history = [] if history is None else history
778
+ for (old_question, old_answer) in history:
779
+ template.append_message(template.roles[0], old_question)
780
+ template.append_message(template.roles[1], old_answer)
781
+ template.append_message(template.roles[0], question)
782
+ template.append_message(template.roles[1], None)
783
+ query = template.get_prompt()
784
+
785
+ if verbose and pixel_values is not None:
786
+ image_bs = pixel_values.shape[0]
787
+ print(f'dynamic ViT batch size: {image_bs}')
788
+
789
+ for num_patches in num_patches_list:
790
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
791
+ query = query.replace('<image>', image_tokens, 1)
792
+
793
+ model_inputs = tokenizer(query, return_tensors='pt')
794
+ input_ids = model_inputs['input_ids'].cuda()
795
+ attention_mask = model_inputs['attention_mask'].cuda()
796
+ generation_config['eos_token_id'] = eos_token_id
797
+ generation_output = self.generate(
798
+ pixel_values=pixel_values,
799
+ input_ids=input_ids,
800
+ attention_mask=attention_mask,
801
+ **generation_config
802
+ )
803
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
804
+ response = response.split(template.sep)[0].strip()
805
+ history.append((question, response))
806
+ if return_history:
807
+ return response, history
808
+ else:
809
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
810
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
811
+ if verbose:
812
+ print(query_to_print, response)
813
+ return response
814
+
815
+ def _reorder_cache(self, *args, **kwargs):
816
+ return self.language_model._reorder_cache(*args, **kwargs)
modeling_qwen2vit.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2-VL model."""
21
+
22
+ import math
23
+ from dataclasses import dataclass
24
+ from typing import Any, Dict, List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch.nn import CrossEntropyLoss, LayerNorm
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ is_flash_attn_2_available,
36
+ logging,
37
+ )
38
+ from .configuration_qwen2vit import Qwen2VLVisionConfig
39
+
40
+ if is_flash_attn_2_available():
41
+ from flash_attn import flash_attn_varlen_func
42
+
43
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
44
+ else:
45
+ flash_attn_varlen_func = None
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
51
+ def rotate_half(x):
52
+ """Rotates half the hidden dims of the input."""
53
+ x1 = x[..., : x.shape[-1] // 2]
54
+ x2 = x[..., x.shape[-1] // 2:]
55
+ return torch.cat((-x2, x1), dim=-1)
56
+
57
+
58
+ def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
59
+ orig_dtype = tensor.dtype
60
+ tensor = tensor.float()
61
+ cos = freqs.cos()
62
+ sin = freqs.sin()
63
+ cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
64
+ sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
65
+ output = (tensor * cos) + (rotate_half(tensor) * sin)
66
+ output = output.to(orig_dtype)
67
+ return output
68
+
69
+
70
+ class VisionRotaryEmbedding(nn.Module):
71
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
72
+ super().__init__()
73
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
74
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
75
+
76
+ def forward(self, seqlen: int) -> torch.Tensor:
77
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
78
+ freqs = torch.outer(seq, self.inv_freq)
79
+ return freqs
80
+
81
+
82
+ class PatchEmbed(nn.Module):
83
+ def __init__(
84
+ self,
85
+ patch_size: int = 14,
86
+ temporal_patch_size: int = 2,
87
+ in_channels: int = 3,
88
+ embed_dim: int = 1152,
89
+ ) -> None:
90
+ super().__init__()
91
+ self.patch_size = patch_size
92
+ self.temporal_patch_size = temporal_patch_size
93
+ self.in_channels = in_channels
94
+ self.embed_dim = embed_dim
95
+
96
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
97
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
98
+
99
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
100
+ target_dtype = self.proj.weight.dtype
101
+ hidden_states = hidden_states.view(
102
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
103
+ )
104
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
105
+ return hidden_states
106
+
107
+
108
+ class PatchMerger(nn.Module):
109
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
110
+ super().__init__()
111
+ self.hidden_size = context_dim * (spatial_merge_size ** 2)
112
+ self.ln_q = LayerNorm(context_dim, eps=1e-6)
113
+ self.mlp = nn.Sequential(
114
+ nn.Linear(self.hidden_size, self.hidden_size),
115
+ nn.GELU(),
116
+ nn.Linear(self.hidden_size, dim),
117
+ )
118
+
119
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
120
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
121
+ return x
122
+
123
+
124
+ class VisionMlp(nn.Module):
125
+ def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
126
+ super().__init__()
127
+ self.fc1 = nn.Linear(dim, hidden_dim)
128
+ self.act = ACT2FN[hidden_act]
129
+ self.fc2 = nn.Linear(hidden_dim, dim)
130
+
131
+ def forward(self, x) -> torch.Tensor:
132
+ return self.fc2(self.act(self.fc1(x)))
133
+
134
+
135
+ class VisionAttention(nn.Module):
136
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
137
+ super().__init__()
138
+ self.num_heads = num_heads
139
+ self.head_dim = dim // num_heads
140
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
141
+ self.proj = nn.Linear(dim, dim)
142
+
143
+ def forward(
144
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
145
+ ) -> torch.Tensor:
146
+ seq_length = hidden_states.shape[0]
147
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
148
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
149
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
150
+
151
+ attention_mask = torch.full(
152
+ [1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
153
+ )
154
+ for i in range(1, len(cu_seqlens)):
155
+ attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = 0
156
+
157
+ q = q.transpose(0, 1)
158
+ k = k.transpose(0, 1)
159
+ v = v.transpose(0, 1)
160
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
161
+ attn_weights = attn_weights + attention_mask
162
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
163
+ attn_output = torch.matmul(attn_weights, v)
164
+ attn_output = attn_output.transpose(0, 1)
165
+ attn_output = attn_output.reshape(seq_length, -1)
166
+ attn_output = self.proj(attn_output)
167
+ return attn_output
168
+
169
+
170
+ class VisionFlashAttention2(nn.Module):
171
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
172
+ super().__init__()
173
+ self.num_heads = num_heads
174
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
175
+ self.proj = nn.Linear(dim, dim)
176
+
177
+ def forward(
178
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
179
+ ) -> torch.Tensor:
180
+ seq_length = hidden_states.shape[0]
181
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
182
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
183
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
184
+
185
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
186
+ attn_output = flash_attn_varlen_func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen).reshape(
187
+ seq_length, -1
188
+ )
189
+ attn_output = self.proj(attn_output)
190
+ return attn_output
191
+
192
+
193
+ class VisionSdpaAttention(nn.Module):
194
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
195
+ super().__init__()
196
+ self.num_heads = num_heads
197
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
198
+ self.proj = nn.Linear(dim, dim)
199
+
200
+ def forward(
201
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
202
+ ) -> torch.Tensor:
203
+ seq_length = hidden_states.shape[0]
204
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
205
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
206
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
207
+
208
+ attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
209
+ for i in range(1, len(cu_seqlens)):
210
+ attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = True
211
+ q = q.transpose(0, 1)
212
+ k = k.transpose(0, 1)
213
+ v = v.transpose(0, 1)
214
+ attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0)
215
+ attn_output = attn_output.transpose(0, 1)
216
+ attn_output = attn_output.reshape(seq_length, -1)
217
+ attn_output = self.proj(attn_output)
218
+ return attn_output
219
+
220
+
221
+ QWEN2_VL_VISION_ATTENTION_CLASSES = {
222
+ "eager": VisionAttention,
223
+ "flash_attention_2": VisionFlashAttention2,
224
+ "sdpa": VisionSdpaAttention,
225
+ }
226
+
227
+
228
+ class Qwen2VLVisionBlock(nn.Module):
229
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
230
+ super().__init__()
231
+ self.norm1 = LayerNorm(config.embed_dim, eps=1e-6)
232
+ self.norm2 = LayerNorm(config.embed_dim, eps=1e-6)
233
+ mlp_hidden_dim = int(config.embed_dim * config.mlp_ratio)
234
+
235
+ self.attn = QWEN2_VL_VISION_ATTENTION_CLASSES[attn_implementation](
236
+ config.embed_dim, num_heads=config.num_heads
237
+ )
238
+ self.mlp = VisionMlp(dim=config.embed_dim, hidden_dim=mlp_hidden_dim, hidden_act=config.hidden_act)
239
+
240
+ def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor:
241
+ hidden_states = hidden_states + self.attn(
242
+ self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb
243
+ )
244
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
245
+ return hidden_states
246
+
247
+
248
+ class Qwen2VisionTower(PreTrainedModel):
249
+ config_class = Qwen2VLVisionConfig
250
+ _no_split_modules = ["Qwen2VLVisionBlock"]
251
+ base_model_prefix = "model"
252
+ supports_gradient_checkpointing = True
253
+ _supports_flash_attn_2 = True
254
+ _supports_sdpa = True
255
+
256
+ def _init_weights(self, module):
257
+ std = self.config.initializer_range
258
+ if isinstance(module, (nn.Linear, nn.Conv3d)):
259
+ module.weight.data.normal_(mean=0.0, std=std)
260
+ if module.bias is not None:
261
+ module.bias.data.zero_()
262
+ elif isinstance(module, nn.Embedding):
263
+ module.weight.data.normal_(mean=0.0, std=std)
264
+ if module.padding_idx is not None:
265
+ module.weight.data[module.padding_idx].zero_()
266
+
267
+ def __init__(self, config) -> None:
268
+ super().__init__(config)
269
+ self.spatial_merge_size = config.spatial_merge_size
270
+
271
+ self.patch_embed = PatchEmbed(
272
+ patch_size=config.patch_size,
273
+ temporal_patch_size=config.temporal_patch_size,
274
+ in_channels=config.in_channels,
275
+ embed_dim=config.embed_dim,
276
+ )
277
+
278
+ head_dim = config.embed_dim // config.num_heads
279
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
280
+
281
+ self.blocks = nn.ModuleList(
282
+ [Qwen2VLVisionBlock(config, "eager") for _ in range(config.depth)]
283
+ )
284
+ self.merger = PatchMerger(
285
+ dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size
286
+ )
287
+
288
+ def get_dtype(self) -> torch.dtype:
289
+ return self.blocks[0].mlp.fc2.weight.dtype
290
+
291
+ def get_device(self) -> torch.device:
292
+ return self.blocks[0].mlp.fc2.weight.device
293
+
294
+ def rot_pos_emb(self, grid_thw):
295
+ pos_ids = []
296
+ for t, h, w in grid_thw:
297
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
298
+ hpos_ids = hpos_ids.reshape(
299
+ h // self.spatial_merge_size,
300
+ self.spatial_merge_size,
301
+ w // self.spatial_merge_size,
302
+ self.spatial_merge_size,
303
+ )
304
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
305
+ hpos_ids = hpos_ids.flatten()
306
+
307
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
308
+ wpos_ids = wpos_ids.reshape(
309
+ h // self.spatial_merge_size,
310
+ self.spatial_merge_size,
311
+ w // self.spatial_merge_size,
312
+ self.spatial_merge_size,
313
+ )
314
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
315
+ wpos_ids = wpos_ids.flatten()
316
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
317
+ pos_ids = torch.cat(pos_ids, dim=0)
318
+ max_grid_size = grid_thw[:, 1:].max()
319
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
320
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
321
+ return rotary_pos_emb
322
+
323
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
324
+ hidden_states = self.patch_embed(hidden_states)
325
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
326
+
327
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
328
+ dim=0, dtype=torch.int32
329
+ )
330
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
331
+
332
+ for blk in self.blocks:
333
+ hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb)
334
+
335
+ return self.merger(hidden_states)
modeling_rope_utils.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from typing import Optional, Tuple
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import is_torch_available, logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ if is_torch_available():
24
+ import torch
25
+
26
+
27
+ def _compute_default_rope_parameters(
28
+ config: Optional[PretrainedConfig] = None,
29
+ device: Optional["torch.device"] = None,
30
+ seq_len: Optional[int] = None,
31
+ **rope_kwargs,
32
+ ) -> Tuple["torch.Tensor", float]:
33
+ """
34
+ Computes the inverse frequencies according to the original RoPE implementation
35
+ Args:
36
+ config ([`~transformers.PretrainedConfig`]):
37
+ The model configuration.
38
+ device (`torch.device`):
39
+ The device to use for initialization of the inverse frequencies.
40
+ seq_len (`int`, *optional*):
41
+ The current sequence length. Unused for this type of RoPE.
42
+ rope_kwargs (`Dict`, *optional*):
43
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
44
+ Returns:
45
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
46
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
47
+ """
48
+ if config is not None and len(rope_kwargs) > 0:
49
+ raise ValueError(
50
+ "Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
51
+ f"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
52
+ )
53
+ if len(rope_kwargs) > 0:
54
+ base = rope_kwargs["base"]
55
+ dim = rope_kwargs["dim"]
56
+ elif config is not None:
57
+ base = config.rope_theta
58
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
59
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
60
+ dim = int(head_dim * partial_rotary_factor)
61
+
62
+ attention_factor = 1.0 # Unused in this type of RoPE
63
+
64
+ # Compute the inverse frequencies
65
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))
66
+ return inv_freq, attention_factor
67
+
68
+
69
+ def _compute_linear_scaling_rope_parameters(
70
+ config: Optional[PretrainedConfig] = None,
71
+ device: Optional["torch.device"] = None,
72
+ seq_len: Optional[int] = None,
73
+ **rope_kwargs,
74
+ ) -> Tuple["torch.Tensor", float]:
75
+ """
76
+ Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev
77
+ Args:
78
+ config ([`~transformers.PretrainedConfig`]):
79
+ The model configuration.
80
+ device (`torch.device`):
81
+ The device to use for initialization of the inverse frequencies.
82
+ seq_len (`int`, *optional*):
83
+ The current sequence length. Unused for this type of RoPE.
84
+ rope_kwargs (`Dict`, *optional*):
85
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
86
+ Returns:
87
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
88
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
89
+ """
90
+ if config is not None and len(rope_kwargs) > 0:
91
+ raise ValueError(
92
+ "Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
93
+ f"`_compute_linear_scaling_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
94
+ )
95
+ if len(rope_kwargs) > 0:
96
+ factor = rope_kwargs["factor"]
97
+ elif config is not None:
98
+ factor = config.rope_scaling["factor"]
99
+
100
+ # Gets the default RoPE parameters
101
+ inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)
102
+
103
+ # Then applies linear scaling to the frequencies.
104
+ # NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so
105
+ # applying scaling to the inverse frequencies is equivalent.
106
+ inv_freq /= factor
107
+ return inv_freq, attention_factor
108
+
109
+
110
+ def _compute_dynamic_ntk_parameters(
111
+ config: Optional[PretrainedConfig] = None,
112
+ device: Optional["torch.device"] = None,
113
+ seq_len: Optional[int] = None,
114
+ **rope_kwargs,
115
+ ) -> Tuple["torch.Tensor", float]:
116
+ """
117
+ Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla
118
+ Args:
119
+ config ([`~transformers.PretrainedConfig`]):
120
+ The model configuration.
121
+ device (`torch.device`):
122
+ The device to use for initialization of the inverse frequencies.
123
+ seq_len (`int`, *optional*):
124
+ The current sequence length, used to update the dynamic RoPE at inference time.
125
+ rope_kwargs (`Dict`, *optional*):
126
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
127
+ Returns:
128
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
129
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
130
+ """
131
+ # TODO (joao): use the new `original_max_position_embeddings` from rope_scaling
132
+ if config is not None and len(rope_kwargs) > 0:
133
+ raise ValueError(
134
+ "Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
135
+ f"`_compute_dynamic_ntk_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
136
+ )
137
+ if len(rope_kwargs) > 0:
138
+ base = rope_kwargs["base"]
139
+ dim = rope_kwargs["dim"]
140
+ max_position_embeddings = rope_kwargs["max_position_embeddings"]
141
+ factor = rope_kwargs["factor"]
142
+ elif config is not None:
143
+ base = config.rope_theta
144
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
145
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
146
+ dim = int(head_dim * partial_rotary_factor)
147
+ max_position_embeddings = config.max_position_embeddings
148
+ factor = config.rope_scaling["factor"]
149
+
150
+ attention_factor = 1.0 # Unused in this type of RoPE
151
+
152
+ # seq_len: default to max_position_embeddings, e.g. at init time
153
+ seq_len = seq_len if seq_len is not None and seq_len > max_position_embeddings else max_position_embeddings
154
+
155
+ # Compute the inverse frequencies
156
+ base = base * ((factor * seq_len / max_position_embeddings) - (factor - 1)) ** (dim / (dim - 2))
157
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))
158
+ return inv_freq, attention_factor
159
+
160
+
161
+ def _compute_yarn_parameters(
162
+ config: PretrainedConfig, device: "torch.device", seq_len: Optional[int] = None, **rope_kwargs
163
+ ) -> Tuple["torch.Tensor", float]:
164
+ """
165
+ Computes the inverse frequencies with NTK scaling. Please refer to the
166
+ [original paper](https://arxiv.org/abs/2309.00071)
167
+ Args:
168
+ config ([`~transformers.PretrainedConfig`]):
169
+ The model configuration.
170
+ device (`torch.device`):
171
+ The device to use for initialization of the inverse frequencies.
172
+ seq_len (`int`, *optional*):
173
+ The current sequence length. Unused for this type of RoPE.
174
+ rope_kwargs (`Dict`, *optional*):
175
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
176
+ Returns:
177
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
178
+ post-processing scaling factor applied to the computed cos/sin.
179
+ """
180
+ # No need to keep BC with yarn, unreleased when this new pattern was created.
181
+ if len(rope_kwargs) > 0:
182
+ raise ValueError(
183
+ f"Unexpected arguments: `**rope_kwargs` should be unset in `_compute_yarn_parameters`, got {rope_kwargs}"
184
+ )
185
+
186
+ base = config.rope_theta
187
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
188
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
189
+ dim = int(head_dim * partial_rotary_factor)
190
+ max_position_embeddings = config.max_position_embeddings
191
+ factor = config.rope_scaling["factor"]
192
+
193
+ # Sets the attention factor as suggested in the paper
194
+ attention_factor = config.rope_scaling.get("attention_factor")
195
+ if attention_factor is None:
196
+ attention_factor = 0.1 * math.log(factor) + 1.0
197
+
198
+ # Optional config options
199
+ # beta_fast/beta_slow: as suggested in the paper, default to 32/1 (correspondingly)
200
+ beta_fast = config.rope_scaling.get("beta_fast") or 32
201
+ beta_slow = config.rope_scaling.get("beta_slow") or 1
202
+
203
+ # Compute the inverse frequencies
204
+ def find_correction_dim(num_rotations, dim, base, max_position_embeddings):
205
+ """Inverse dimension formula to find the dimension based on the number of rotations"""
206
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
207
+
208
+ def find_correction_range(low_rot, high_rot, dim, base, max_position_embeddings):
209
+ """Find dimension range bounds based on rotations"""
210
+ low = math.floor(find_correction_dim(low_rot, dim, base, max_position_embeddings))
211
+ high = math.ceil(find_correction_dim(high_rot, dim, base, max_position_embeddings))
212
+ return max(low, 0), min(high, dim - 1)
213
+
214
+ def linear_ramp_factor(min, max, dim):
215
+ if min == max:
216
+ max += 0.001 # Prevent singularity
217
+
218
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
219
+ ramp_func = torch.clamp(linear_func, 0, 1)
220
+ return ramp_func
221
+
222
+ # Note on variable naming: "interpolation" comes from the original technique, where we interpolate the position IDs
223
+ # to expand the possible context length. In other words, interpolation = apply scaling factor.
224
+ pos_freqs = base ** (torch.arange(0, dim, 2).float().to(device) / dim)
225
+ inv_freq_extrapolation = 1.0 / pos_freqs
226
+ inv_freq_interpolation = 1.0 / (factor * pos_freqs)
227
+
228
+ low, high = find_correction_range(beta_fast, beta_slow, dim, base, max_position_embeddings)
229
+
230
+ # Get n-dimensional rotational scaling corrected for extrapolation
231
+ inv_freq_extrapolation_factor = 1 - linear_ramp_factor(low, high, dim // 2).float().to(device)
232
+ inv_freq = (
233
+ inv_freq_interpolation * (1 - inv_freq_extrapolation_factor)
234
+ + inv_freq_extrapolation * inv_freq_extrapolation_factor
235
+ )
236
+
237
+ return inv_freq, attention_factor
238
+
239
+
240
+ def _compute_longrope_parameters(
241
+ config: PretrainedConfig, device: "torch.device", seq_len: Optional[int] = None, **rope_kwargs
242
+ ) -> Tuple["torch.Tensor", float]:
243
+ """
244
+ Computes the inverse frequencies with LongRoPE scaling. Please refer to the
245
+ [original implementation](https://github.com/microsoft/LongRoPE)
246
+ Args:
247
+ config ([`~transformers.PretrainedConfig`]):
248
+ The model configuration.
249
+ device (`torch.device`):
250
+ The device to use for initialization of the inverse frequencies.
251
+ seq_len (`int`, *optional*):
252
+ The current sequence length. Unused for this type of RoPE.
253
+ rope_kwargs (`Dict`, *optional*):
254
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
255
+ Returns:
256
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
257
+ post-processing scaling factor applied to the computed cos/sin.
258
+ """
259
+ # TODO (joao): use the new `original_max_position_embeddings` from rope_scaling
260
+ # No need to keep BC with longrope, unreleased when this new pattern was created.
261
+ if len(rope_kwargs) > 0:
262
+ raise ValueError(
263
+ "Unexpected arguments: `**rope_kwargs` should be unset in `_compute_longrope_parameters`, got "
264
+ f"{rope_kwargs}"
265
+ )
266
+
267
+ base = config.rope_theta
268
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
269
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
270
+ dim = int(head_dim * partial_rotary_factor)
271
+ long_factor = config.rope_scaling["long_factor"]
272
+ short_factor = config.rope_scaling["short_factor"]
273
+ factor = config.rope_scaling.get("factor")
274
+ attention_factor = config.rope_scaling.get("attention_factor")
275
+
276
+ # NOTE: Phi3 (and potentially other models) modify `max_position_embeddings` and have a
277
+ # `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two
278
+ # values to compute the default attention scaling factor, instead of using `factor`.
279
+ if hasattr(config, "original_max_position_embeddings"):
280
+ max_position_embeddings = config.original_max_position_embeddings
281
+ expanded_max_position_embeddings = config.max_position_embeddings
282
+ factor = expanded_max_position_embeddings / max_position_embeddings
283
+ else:
284
+ max_position_embeddings = config.max_position_embeddings
285
+ expanded_max_position_embeddings = max_position_embeddings * factor
286
+
287
+ # Sets the attention factor as suggested in the paper
288
+ if attention_factor is None:
289
+ if factor <= 1.0:
290
+ attention_factor = 1.0
291
+ else:
292
+ attention_factor = math.sqrt(1 + math.log(factor) / math.log(max_position_embeddings))
293
+
294
+ # Compute the inverse frequencies -- scaled based on the target sequence length
295
+ if expanded_max_position_embeddings > max_position_embeddings:
296
+ ext_factors = torch.tensor(long_factor, dtype=torch.float32, device=device)
297
+ else:
298
+ ext_factors = torch.tensor(short_factor, dtype=torch.float32, device=device)
299
+ inv_freq_shape = torch.arange(0, dim, 2, dtype=torch.int64, device=device).float() / dim
300
+ inv_freq = 1.0 / (ext_factors * base ** inv_freq_shape)
301
+
302
+ return inv_freq, attention_factor
303
+
304
+
305
+ def _compute_llama3_parameters(
306
+ config: PretrainedConfig, device: "torch.device", seq_len: Optional[int] = None, **rope_kwargs
307
+ ) -> Tuple["torch.Tensor", float]:
308
+ """
309
+ Computes the inverse frequencies for llama 3.1.
310
+
311
+ Args:
312
+ config ([`~transformers.PretrainedConfig`]):
313
+ The model configuration.
314
+ device (`torch.device`):
315
+ The device to use for initialization of the inverse frequencies.
316
+ seq_len (`int`, *optional*):
317
+ The current sequence length. Unused for this type of RoPE.
318
+ rope_kwargs (`Dict`, *optional*):
319
+ BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
320
+ Returns:
321
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
322
+ post-processing scaling factor applied to the computed cos/sin.
323
+ """
324
+ # Gets the default RoPE parameters
325
+ inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)
326
+
327
+ factor = config.rope_scaling["factor"] # `8` in the original implementation
328
+ low_freq_factor = config.rope_scaling["low_freq_factor"] # `1` in the original implementation
329
+ high_freq_factor = config.rope_scaling["high_freq_factor"] # `4` in the original implementation
330
+ old_context_len = config.rope_scaling["original_max_position_embeddings"] # `8192` in the original implementation
331
+
332
+ low_freq_wavelen = old_context_len / low_freq_factor
333
+ high_freq_wavelen = old_context_len / high_freq_factor
334
+
335
+ wavelen = 2 * math.pi / inv_freq
336
+ # wavelen < high_freq_wavelen: do nothing
337
+ # wavelen > low_freq_wavelen: divide by factor
338
+ inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)
339
+ # otherwise: interpolate between the two, using a smooth factor
340
+ smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
341
+ smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama
342
+ is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)
343
+ inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)
344
+
345
+ return inv_freq_llama, attention_factor
346
+
347
+
348
+ # This maps the "rope_type" string field in rope config to the corresponding function to compute the RoPE parameters
349
+ # from the model config. You can append new {'rope_type': callable} pairs to this dictionary to enable custom RoPE
350
+ # parameterizations, as long as the callable has the same signature.
351
+ ROPE_INIT_FUNCTIONS = {
352
+ "default": _compute_default_rope_parameters,
353
+ "linear": _compute_linear_scaling_rope_parameters,
354
+ "dynamic": _compute_dynamic_ntk_parameters,
355
+ "yarn": _compute_yarn_parameters,
356
+ "longrope": _compute_longrope_parameters,
357
+ "llama3": _compute_llama3_parameters,
358
+ }
359
+
360
+
361
+ def _check_received_keys(rope_type: str, received_keys: set, required_keys: set, optional_keys: Optional[set] = None):
362
+ """Compare the received keys in `config.rope_scaling` against the expected and optional keys"""
363
+ # BC: "rope_type" was originally "type" -- let's check for "rope_type" when "type" is present
364
+ if "type" in received_keys:
365
+ received_keys -= {"type"}
366
+ required_keys.add("rope_type")
367
+
368
+ missing_keys = required_keys - received_keys
369
+ if missing_keys:
370
+ raise KeyError(f"Missing required keys in `rope_scaling` for 'rope_type'='{rope_type}': {missing_keys}")
371
+
372
+ if optional_keys is not None:
373
+ unused_keys = received_keys - required_keys - optional_keys
374
+ else:
375
+ unused_keys = received_keys - required_keys
376
+ if unused_keys:
377
+ logger.warning(f"Unrecognized keys in `rope_scaling` for 'rope_type'='{rope_type}': {unused_keys}")
378
+
379
+
380
+ def _validate_default_rope_parameters(config: PretrainedConfig):
381
+ rope_scaling = config.rope_scaling
382
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
383
+ required_keys = {"rope_type"}
384
+ received_keys = set(rope_scaling.keys())
385
+ _check_received_keys(rope_type, received_keys, required_keys)
386
+
387
+
388
+ def _validate_linear_scaling_rope_parameters(config: PretrainedConfig):
389
+ rope_scaling = config.rope_scaling
390
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
391
+ required_keys = {"rope_type", "factor"}
392
+ received_keys = set(rope_scaling.keys())
393
+ _check_received_keys(rope_type, received_keys, required_keys)
394
+
395
+ factor = rope_scaling["factor"]
396
+ if factor is None or not isinstance(factor, float) or factor < 1.0:
397
+ logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
398
+
399
+
400
+ def _validate_dynamic_scaling_rope_parameters(config: PretrainedConfig):
401
+ rope_scaling = config.rope_scaling
402
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
403
+ required_keys = {"rope_type", "factor"}
404
+ # TODO (joao): update logic for the inclusion of `original_max_position_embeddings`
405
+ optional_keys = {"original_max_position_embeddings"}
406
+ received_keys = set(rope_scaling.keys())
407
+ _check_received_keys(rope_type, received_keys, required_keys, optional_keys)
408
+
409
+ factor = rope_scaling["factor"]
410
+ if factor is None or not isinstance(factor, float) or factor < 1.0:
411
+ logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
412
+
413
+
414
+ def _validate_yarn_parameters(config: PretrainedConfig):
415
+ rope_scaling = config.rope_scaling
416
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
417
+ required_keys = {"rope_type", "factor"}
418
+ optional_keys = {"attention_factor", "beta_fast", "beta_slow"}
419
+ received_keys = set(rope_scaling.keys())
420
+ _check_received_keys(rope_type, received_keys, required_keys, optional_keys)
421
+
422
+ factor = rope_scaling["factor"]
423
+ if factor is None or not isinstance(factor, float) or factor < 1.0:
424
+ logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
425
+
426
+ attention_factor = rope_scaling.get("attention_factor")
427
+ if attention_factor is not None and (not isinstance(attention_factor, float) or attention_factor < 0):
428
+ logger.warning(
429
+ f"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}"
430
+ )
431
+ beta_fast = rope_scaling.get("beta_fast")
432
+ if beta_fast is not None and not isinstance(beta_fast, float):
433
+ logger.warning(f"`rope_scaling`'s beta_fast field must be a float, got {beta_fast}")
434
+ beta_slow = rope_scaling.get("beta_slow")
435
+ if beta_slow is not None and not isinstance(beta_slow, float):
436
+ logger.warning(f"`rope_scaling`'s beta_slow field must be a float, got {beta_slow}")
437
+
438
+ if (beta_fast or 32) < (beta_slow or 1):
439
+ logger.warning(
440
+ f"`rope_scaling`'s beta_fast field must be greater than beta_slow, got beta_fast={beta_fast} "
441
+ f"(defaults to 32 if None) and beta_slow={beta_slow} (defaults to 1 if None)"
442
+ )
443
+
444
+
445
+ def _validate_longrope_parameters(config: PretrainedConfig):
446
+ rope_scaling = config.rope_scaling
447
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
448
+ required_keys = {"rope_type", "short_factor", "long_factor"}
449
+ # TODO (joao): update logic for the inclusion of `original_max_position_embeddings`
450
+ optional_keys = {"attention_factor", "factor", "original_max_position_embeddings"}
451
+ received_keys = set(rope_scaling.keys())
452
+ _check_received_keys(rope_type, received_keys, required_keys, optional_keys)
453
+
454
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
455
+ head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
456
+ dim = int(head_dim * partial_rotary_factor)
457
+
458
+ short_factor = rope_scaling.get("short_factor")
459
+ if not isinstance(short_factor, list) and all(isinstance(x, (int, float)) for x in short_factor):
460
+ logger.warning(f"`rope_scaling`'s short_factor field must be a list of numbers, got {short_factor}")
461
+ if not len(short_factor) == dim // 2:
462
+ logger.warning(f"`rope_scaling`'s short_factor field must have length {dim // 2}, got {len(short_factor)}")
463
+
464
+ long_factor = rope_scaling.get("long_factor")
465
+ if not isinstance(long_factor, list) and all(isinstance(x, (int, float)) for x in long_factor):
466
+ logger.warning(f"`rope_scaling`'s long_factor field must be a list of numbers, got {long_factor}")
467
+ if not len(long_factor) == dim // 2:
468
+ logger.warning(f"`rope_scaling`'s long_factor field must have length {dim // 2}, got {len(long_factor)}")
469
+
470
+ # Handle Phi3 divergence: prefer the use of `attention_factor` and/or `factor` over
471
+ # `original_max_position_embeddings` to compute internal variables. The latter lives outside `rope_scaling` and is
472
+ # unique to longrope (= undesirable)
473
+ if hasattr(config, "original_max_position_embeddings"):
474
+ logger.warning_once(
475
+ "This model has set a `original_max_position_embeddings` field, to be used together with "
476
+ "`max_position_embeddings` to determine a scaling factor. Please set the `factor` field of `rope_scaling`"
477
+ "with this ratio instead -- we recommend the use of this field over `original_max_position_embeddings`, "
478
+ "as it is compatible with most model architectures."
479
+ )
480
+ else:
481
+ factor = rope_scaling.get("factor")
482
+ if factor is None:
483
+ logger.warning("Missing required keys in `rope_scaling`: 'factor'")
484
+ elif not isinstance(factor, float) or factor < 1.0:
485
+ logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
486
+
487
+ attention_factor = rope_scaling.get("attention_factor")
488
+ if attention_factor is not None:
489
+ if not isinstance(attention_factor, float) or attention_factor < 0.0:
490
+ logger.warning(
491
+ f"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}"
492
+ )
493
+
494
+
495
+ def _validate_llama3_parameters(config: PretrainedConfig):
496
+ rope_scaling = config.rope_scaling
497
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None)) # BC: "rope_type" was originally "type"
498
+ required_keys = {"rope_type", "factor", "original_max_position_embeddings", "low_freq_factor", "high_freq_factor"}
499
+ received_keys = set(rope_scaling.keys())
500
+ _check_received_keys(rope_type, received_keys, required_keys)
501
+
502
+ factor = rope_scaling["factor"]
503
+ if factor is None or not isinstance(factor, float) or factor < 1.0:
504
+ logger.warning(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
505
+
506
+ low_freq_factor = rope_scaling["low_freq_factor"]
507
+ high_freq_factor = rope_scaling["high_freq_factor"]
508
+ if low_freq_factor is None or not isinstance(low_freq_factor, float):
509
+ logger.warning(f"`rope_scaling`'s low_freq_factor field must be a float, got {low_freq_factor}")
510
+ if high_freq_factor is None or not isinstance(high_freq_factor, float):
511
+ logger.warning(f"`rope_scaling`'s high_freq_factor field must be a float, got {high_freq_factor}")
512
+ if high_freq_factor <= low_freq_factor:
513
+ logger.warning(
514
+ "`rope_scaling`'s high_freq_factor field must be greater than low_freq_factor, got high_freq_factor="
515
+ f"{high_freq_factor} and low_freq_factor={low_freq_factor}"
516
+ )
517
+
518
+ original_max_position_embeddings = rope_scaling["original_max_position_embeddings"]
519
+ if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
520
+ logger.warning(
521
+ "`rope_scaling`'s original_max_position_embeddings field must be an integer, got "
522
+ f"{original_max_position_embeddings}"
523
+ )
524
+ if original_max_position_embeddings >= config.max_position_embeddings:
525
+ logger.warning(
526
+ "`rope_scaling`'s original_max_position_embeddings field must be less than max_position_embeddings, got "
527
+ f"{original_max_position_embeddings} and max_position_embeddings={config.max_position_embeddings}"
528
+ )
529
+
530
+
531
+ # Like `ROPE_INIT_FUNCTIONS`, this validation function mapping can be dynamically updated for custom RoPE types.
532
+ ROPE_VALIDATION_FUNCTIONS = {
533
+ "default": _validate_default_rope_parameters,
534
+ "linear": _validate_linear_scaling_rope_parameters,
535
+ "dynamic": _validate_dynamic_scaling_rope_parameters,
536
+ "yarn": _validate_yarn_parameters,
537
+ "longrope": _validate_longrope_parameters,
538
+ "llama3": _validate_llama3_parameters,
539
+ }
540
+
541
+
542
+ def rope_config_validation(config: PretrainedConfig):
543
+ """
544
+ Validate the RoPE config arguments, given a `PretrainedConfig` object
545
+ """
546
+ rope_scaling = getattr(config, "rope_scaling", None) # not a default parameter in `PretrainedConfig`
547
+ if rope_scaling is None:
548
+ return
549
+
550
+ # BC: "rope_type" was originally "type"
551
+ rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", "default"))
552
+ validation_fn = ROPE_VALIDATION_FUNCTIONS.get(rope_type)
553
+ if validation_fn is not None:
554
+ validation_fn(config)
555
+ else:
556
+ logger.warning(
557
+ f"Missing validation function mapping in `ROPE_VALIDATION_FUNCTIONS` for 'rope_type'='{rope_type}'"
558
+ )