YingxuHe commited on
Commit
55377c0
·
verified ·
1 Parent(s): 4c96a72

Upload 4 files

Browse files
vllm_plugin_meralion/vllm_plugin_meralion/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from .vllm_meralion import MERaLiONForConditionalGeneration
4
+
5
+ def _custom_placeholder_str(self, modality: str,
6
+ current_count: int) -> Optional[str]:
7
+ # TODO: Let user specify how to insert image tokens into prompt
8
+ # (similar to chat template)
9
+ hf_config = self._model_config.hf_config
10
+ model_type = hf_config.model_type
11
+
12
+ if modality == "image":
13
+ if model_type == "phi3_v":
14
+ # Workaround since this token is not defined in the tokenizer
15
+ return f"<|image_{current_count}|>"
16
+ if model_type == "minicpmv":
17
+ return "(<image>./</image>)"
18
+ if model_type in ("blip-2", "chatglm", "fuyu", "paligemma",
19
+ "pixtral"):
20
+ # These models do not use image tokens in the prompt
21
+ return None
22
+ if model_type == "qwen":
23
+ return f"Picture {current_count}: <img></img>"
24
+ if model_type.startswith("llava"):
25
+ return self._cached_token_str(self._tokenizer,
26
+ hf_config.image_token_index)
27
+ if model_type in ("chameleon", "internvl_chat", "NVLM_D",
28
+ "h2ovl_chat"):
29
+ return "<image>"
30
+ if model_type == "mllama":
31
+ return "<|image|>"
32
+ if model_type == "qwen2_vl":
33
+ return "<|vision_start|><|image_pad|><|vision_end|>"
34
+ if model_type == "molmo":
35
+ return ""
36
+ if model_type == "idefics3":
37
+ return "<image>"
38
+
39
+ raise TypeError(f"Unknown {modality} model type: {model_type}")
40
+ elif modality == "audio":
41
+ if model_type == "ultravox":
42
+ return "<|reserved_special_token_0|>"
43
+ if model_type == "qwen2_audio":
44
+ return (f"Audio {current_count}: "
45
+ f"<|audio_bos|><|AUDIO|><|audio_eos|>")
46
+ if model_type == "meralion":
47
+ return "Given the following audio context: <SpeechHere>\n"
48
+ raise TypeError(f"Unknown model type: {model_type}")
49
+ elif modality == "video":
50
+ if model_type == "qwen2_vl":
51
+ return "<|vision_start|><|video_pad|><|vision_end|>"
52
+ if model_type.startswith("llava"):
53
+ return self._cached_token_str(self._tokenizer,
54
+ hf_config.video_token_index)
55
+ raise TypeError(f"Unknown {modality} model type: {model_type}")
56
+ else:
57
+ raise TypeError(f"Unknown modality: {modality}")
58
+
59
+ def register():
60
+ import vllm
61
+ from vllm import ModelRegistry
62
+
63
+ if "MERaLiONForConditionalGeneration" not in ModelRegistry.get_supported_archs():
64
+ ModelRegistry.register_model(
65
+ "MERaLiONForConditionalGeneration",
66
+ MERaLiONForConditionalGeneration
67
+ )
68
+
69
+ vllm.entrypoints.chat_utils.BaseMultiModalItemTracker._placeholder_str = _custom_placeholder_str
70
+
71
+
vllm_plugin_meralion/vllm_plugin_meralion/configuration_meralion.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MERaLiON AudioLLM model configuration"""
2
+
3
+ from collections import OrderedDict
4
+ from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
5
+
6
+ from transformers.configuration_utils import PretrainedConfig
7
+ from transformers.onnx import OnnxConfig
8
+ from transformers.utils import logging
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from transformers.feature_extraction_utils import FeatureExtractionMixin
13
+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase
14
+ from transformers.utils import TensorType
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ # fmt: off
21
+ NON_SPEECH_TOKENS = [
22
+ 1, 2, 7, 8, 9, 10, 14, 25,
23
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
24
+ 63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
25
+ 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
26
+ 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
27
+ 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786,
28
+ 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791,
29
+ 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409,
30
+ 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361
31
+ ]
32
+ NON_SPEECH_TOKENS_MULTI = [
33
+ 1, 2, 7, 8, 9, 10, 14, 25,
34
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
35
+ 63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
36
+ 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
37
+ 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
38
+ 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793,
39
+ 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675,
40
+ 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865,
41
+ 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362
42
+ ]
43
+ # fmt: on
44
+
45
+ # Copied from transformers.models.whisper.configuration_whisper.WhisperConfig
46
+ class MERaLiONSpeechConfig(PretrainedConfig):
47
+ r"""
48
+ This is the configuration class to store the configuration of a [`MERaLiONSpeechModel`]. It is used to instantiate a
49
+ MERaLiONSpeech model according to the specified arguments, defining the model architecture. Instantiating a configuration
50
+ with the defaults will yield a similar configuration to that of the MERaLiONSpeech
51
+ [openai/whisper-tiny](https://huggingface.co/openai/whisper-tiny) architecture.
52
+
53
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
54
+ documentation from [`PretrainedConfig`] for more information.
55
+
56
+
57
+ Args:
58
+ vocab_size (`int`, *optional*, defaults to 51865):
59
+ Vocabulary size of the MERaLiONSpeech model. Defines the number of different tokens that can be represented by the
60
+ `decoder_input_ids` passed when calling [`MERaLiONSpeechModel`]
61
+ num_mel_bins (`int`, *optional*, defaults to 80):
62
+ Number of mel features used per input features. Should correspond to the value used in the
63
+ `MERaLiONSpeechProcessor` class.
64
+ encoder_layers (`int`, *optional*, defaults to 4):
65
+ Number of encoder layers.
66
+ decoder_layers (`int`, *optional*, defaults to 4):
67
+ Number of decoder layers.
68
+ encoder_attention_heads (`int`, *optional*, defaults to 6):
69
+ Number of attention heads for each attention layer in the Transformer encoder.
70
+ decoder_attention_heads (`int`, *optional*, defaults to 6):
71
+ Number of attention heads for each attention layer in the Transformer decoder.
72
+ encoder_ffn_dim (`int`, *optional*, defaults to 1536):
73
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
74
+ decoder_ffn_dim (`int`, *optional*, defaults to 1536):
75
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
76
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
77
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
78
+ for more details.
79
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
80
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
81
+ for more details.
82
+ decoder_start_token_id (`int`, *optional*, defaults to 50257):
83
+ Corresponds to the "<|startoftranscript|>" token, which is automatically used when no `decoder_input_ids`
84
+ are provided to the `generate` function. It is used to guide the model`s generation process depending on
85
+ the task.
86
+ use_cache (`bool`, *optional*, defaults to `True`):
87
+ Whether or not the model should return the last key/values attentions (not used by all models).
88
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
89
+ Whether the model is used as an encoder/decoder or not.
90
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
91
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
92
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
93
+ d_model (`int`, *optional*, defaults to 384):
94
+ Dimensionality of the layers.
95
+ dropout (`float`, *optional*, defaults to 0.1):
96
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
97
+ attention_dropout (`float`, *optional*, defaults to 0.0):
98
+ The dropout ratio for the attention probabilities.
99
+ activation_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for activations inside the fully connected layer.
101
+ init_std (`float`, *optional*, defaults to 0.02):
102
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
103
+ scale_embedding (`bool`, *optional*, defaults to False):
104
+ Scale embeddings by diving by sqrt(d_model).
105
+ max_source_positions (`int`, *optional*, defaults to 1500):
106
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
107
+ max_target_positions (`int`, *optional*, defaults to 448):
108
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
109
+ just in case (e.g., 512 or 1024 or 2048).
110
+ pad_token_id (`int`, *optional*, defaults to 50256):
111
+ Padding token id.
112
+ bos_token_id (`int`, *optional*, defaults to 50256):
113
+ Begin of stream token id.
114
+ eos_token_id (`int`, *optional*, defaults to 50256):
115
+ End of stream token id.
116
+ suppress_tokens (`List[int]`, *optional*):
117
+ A list containing the non-speech tokens that will be used by the logit processor in the `generate`
118
+ function. NON_SPEECH_TOKENS and NON_SPEECH_TOKENS_MULTI each correspond to the `english-only` and the
119
+ `multilingual` model.
120
+ begin_suppress_tokens (`List[int]`, *optional*, defaults to `[220,50256]`):
121
+ A list containing tokens that will be supressed at the beginning of the sampling process. Initialized as
122
+ the token for `" "` (`blank_token_id`) and the `eos_token_id`
123
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
124
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
125
+ instance of [`MERaLiONSpeechForAudioClassification`].
126
+ classifier_proj_size (`int`, *optional*, defaults to 256):
127
+ Dimensionality of the projection before token mean-pooling for classification. Only relevant when using an
128
+ instance of [`MERaLiONSpeechForAudioClassification`].
129
+ apply_spec_augment (`bool`, *optional*, defaults to `False`):
130
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
131
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
132
+ Recognition](https://arxiv.org/abs/1904.08779).
133
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
134
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
135
+ procecure generates `mask_time_prob*len(time_axis)/mask_time_length` independent masks over the axis. If
136
+ reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
137
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
138
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment == True`.
139
+ mask_time_length (`int`, *optional*, defaults to 10):
140
+ Length of vector span along the time axis.
141
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
142
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
143
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
144
+ mask_time_min_masks''
145
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
146
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
147
+ masking procecure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
148
+ the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
149
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
150
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
151
+ True`.
152
+ mask_feature_length (`int`, *optional*, defaults to 10):
153
+ Length of vector span along the feature axis.
154
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
155
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
156
+ step, irrespectively of `mask_feature_prob`. Only relevant if
157
+ `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
158
+ median_filter_width (`int`, *optional*, defaults to 7):
159
+ Width of the median filter used to smoothen to cross-attention outputs when computing token timestamps.
160
+ Should be an odd number.
161
+ """
162
+
163
+ model_type = "meralion_speech_encoder"
164
+ keys_to_ignore_at_inference = ["past_key_values"]
165
+ attribute_map = {
166
+ "num_key_value_heads": "encoder_attention_heads",
167
+ "num_attention_heads": "encoder_attention_heads",
168
+ "hidden_size": "d_model",
169
+ }
170
+
171
+ def __init__(
172
+ self,
173
+ vocab_size=51865,
174
+ num_mel_bins=80,
175
+ encoder_layers=4,
176
+ encoder_attention_heads=6,
177
+ decoder_layers=4,
178
+ decoder_attention_heads=6,
179
+ decoder_ffn_dim=1536,
180
+ encoder_ffn_dim=1536,
181
+ encoder_layerdrop=0.0,
182
+ decoder_layerdrop=0.0,
183
+ decoder_start_token_id=50257,
184
+ use_cache=True,
185
+ is_encoder_decoder=True,
186
+ activation_function="gelu",
187
+ d_model=384,
188
+ dropout=0.0,
189
+ attention_dropout=0.0,
190
+ activation_dropout=0.0,
191
+ init_std=0.02,
192
+ scale_embedding=False,
193
+ max_source_positions=1500,
194
+ max_target_positions=448,
195
+ pad_token_id=50256,
196
+ bos_token_id=50256,
197
+ eos_token_id=50256,
198
+ suppress_tokens=None,
199
+ begin_suppress_tokens=[220, 50256],
200
+ use_weighted_layer_sum=False,
201
+ classifier_proj_size=256,
202
+ apply_spec_augment=False,
203
+ mask_time_prob=0.05,
204
+ mask_time_length=10,
205
+ mask_time_min_masks=2,
206
+ mask_feature_prob=0.0,
207
+ mask_feature_length=10,
208
+ mask_feature_min_masks=0,
209
+ median_filter_width=7,
210
+ **kwargs,
211
+ ):
212
+ self.vocab_size = vocab_size
213
+ self.num_mel_bins = num_mel_bins
214
+ self.d_model = d_model
215
+ self.encoder_layers = encoder_layers
216
+ self.encoder_attention_heads = encoder_attention_heads
217
+ self.decoder_layers = decoder_layers
218
+ self.decoder_attention_heads = decoder_attention_heads
219
+ self.decoder_ffn_dim = decoder_ffn_dim
220
+ self.encoder_ffn_dim = encoder_ffn_dim
221
+ self.dropout = dropout
222
+ self.attention_dropout = attention_dropout
223
+ self.activation_dropout = activation_dropout
224
+ self.activation_function = activation_function
225
+ self.init_std = init_std
226
+ self.encoder_layerdrop = encoder_layerdrop
227
+ self.decoder_layerdrop = decoder_layerdrop
228
+ self.use_cache = use_cache
229
+ self.num_hidden_layers = encoder_layers
230
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
231
+ self.max_source_positions = max_source_positions
232
+ self.max_target_positions = max_target_positions
233
+
234
+ # Audio Classification-specific parameters. Feel free to ignore for other classes.
235
+ self.classifier_proj_size = classifier_proj_size
236
+ self.use_weighted_layer_sum = use_weighted_layer_sum
237
+
238
+ # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
239
+ self.apply_spec_augment = apply_spec_augment
240
+ self.mask_time_prob = mask_time_prob
241
+ self.mask_time_length = mask_time_length
242
+ self.mask_time_min_masks = mask_time_min_masks
243
+ self.mask_feature_prob = mask_feature_prob
244
+ self.mask_feature_length = mask_feature_length
245
+ self.mask_feature_min_masks = mask_feature_min_masks
246
+
247
+ self.median_filter_width = median_filter_width
248
+
249
+ super().__init__(
250
+ pad_token_id=pad_token_id,
251
+ bos_token_id=bos_token_id,
252
+ eos_token_id=eos_token_id,
253
+ is_encoder_decoder=is_encoder_decoder,
254
+ decoder_start_token_id=decoder_start_token_id,
255
+ suppress_tokens=suppress_tokens,
256
+ begin_suppress_tokens=begin_suppress_tokens,
257
+ **kwargs,
258
+ )
259
+ @property
260
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
261
+ common_inputs = OrderedDict(
262
+ [
263
+ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}),
264
+ ]
265
+ )
266
+ if self.use_past:
267
+ common_inputs["decoder_input_ids"] = {0: "batch"}
268
+ else:
269
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
270
+
271
+ if self.use_past:
272
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
273
+
274
+ return common_inputs
275
+
276
+ def generate_dummy_inputs(
277
+ self,
278
+ preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
279
+ batch_size: int = -1,
280
+ seq_length: int = -1,
281
+ is_pair: bool = False,
282
+ framework: Optional["TensorType"] = None,
283
+ sampling_rate: int = 22050,
284
+ time_duration: float = 5.0,
285
+ frequency: int = 220,
286
+ ) -> Mapping[str, Any]:
287
+ dummy_inputs = OrderedDict()
288
+ encoder_inputs = OnnxConfig.generate_dummy_inputs(
289
+ self,
290
+ preprocessor=preprocessor.feature_extractor,
291
+ batch_size=batch_size,
292
+ framework=framework,
293
+ sampling_rate=sampling_rate,
294
+ time_duration=time_duration,
295
+ frequency=frequency,
296
+ )
297
+ encoder_sequence_length = encoder_inputs["input_features"].shape[2]
298
+ seq_length = encoder_sequence_length // 2 if self.use_past else seq_length
299
+
300
+ decoder_inputs = super().generate_dummy_inputs(
301
+ preprocessor.tokenizer, batch_size, seq_length, is_pair, framework
302
+ )
303
+
304
+ dummy_inputs["input_features"] = encoder_inputs.pop("input_features")
305
+ dummy_inputs["decoder_input_ids"] = decoder_inputs.pop("decoder_input_ids")
306
+
307
+ if "past_key_values" in decoder_inputs:
308
+ dummy_inputs["past_key_values"] = decoder_inputs.pop("past_key_values")
309
+
310
+ return dummy_inputs
311
+
312
+ @property
313
+ def atol_for_validation(self) -> float:
314
+ return 1e-3
315
+
316
+
317
+ # Copied from transformers.models.gemma2.configuration_gemma2.Gemma2Config
318
+ class MERaLiONTextConfig(PretrainedConfig):
319
+ r"""
320
+ This is the configuration class to store the configuration of a [`MERaLiONTextModel`]. It is used to instantiate an MERaLiONText
321
+ model according to the specified arguments, defining the model architecture.
322
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
323
+ documentation from [`PretrainedConfig`] for more information.
324
+ Args:
325
+ vocab_size (`int`, *optional*, defaults to 256000):
326
+ Vocabulary size of the MERaLiONText model. Defines the number of different tokens that can be represented by the
327
+ `inputs_ids` passed when calling [`MERaLiONTextModel`]
328
+ hidden_size (`int`, *optional*, defaults to 3072):
329
+ Dimension of the hidden representations.
330
+ intermediate_size (`int`, *optional*, defaults to 24576):
331
+ Dimension of the MLP representations.
332
+ num_hidden_layers (`int`, *optional*, defaults to 28):
333
+ Number of hidden layers in the Transformer decoder.
334
+ num_attention_heads (`int`, *optional*, defaults to 16):
335
+ Number of attention heads for each attention layer in the Transformer decoder.
336
+ num_key_value_heads (`int`, *optional*, defaults to 16):
337
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
338
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
339
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
340
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
341
+ by meanpooling all the original heads within that group. For more details checkout [this
342
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
343
+ `num_attention_heads`.
344
+ head_dim (`int`, *optional*, defaults to 256):
345
+ The attention head dimension.
346
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
347
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
348
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
349
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
350
+ The maximum sequence length that this model might ever be used with.
351
+ initializer_range (`float`, *optional*, defaults to 0.02):
352
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
353
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
354
+ The epsilon used by the rms normalization layers.
355
+ use_cache (`bool`, *optional*, defaults to `True`):
356
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
357
+ relevant if `config.is_decoder=True`.
358
+ pad_token_id (`int`, *optional*, defaults to 0):
359
+ Padding token id.
360
+ eos_token_id (`int`, *optional*, defaults to 1):
361
+ End of stream token id.
362
+ bos_token_id (`int`, *optional*, defaults to 2):
363
+ Beginning of stream token id.
364
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
365
+ Whether to tie weight embeddings
366
+ rope_theta (`float`, *optional*, defaults to 10000.0):
367
+ The base period of the RoPE embeddings.
368
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
369
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
370
+ attention_dropout (`float`, *optional*, defaults to 0.0):
371
+ The dropout ratio for the attention probabilities.
372
+ query_pre_attn_scalar (`float`, *optional*, defaults to 224): scaling factor used on the attention scores
373
+ sliding_window (`int`, *optional*, defaults to 4096): in MERaLiONText, every other layer uses sliding window attention. This is the
374
+ size of the sliding window.
375
+ final_logit_softcapping (`float`, *optional*, defaults to 30.0): scaling factor when applying tanh softcapping on the logits.
376
+ attn_logit_softcapping (`float`, *optional*, defaults to 50.0): scaling factor when applying tanh softcapping on the attention scores.
377
+ cache_implementation (`str`, *optional*, defaults to `"hybrid"`): the cache type to be used with `generate`.
378
+ """
379
+
380
+ model_type = "meralion_text_decoder"
381
+ keys_to_ignore_at_inference = ["past_key_values"]
382
+
383
+ def __init__(
384
+ self,
385
+ vocab_size=256000,
386
+ hidden_size=3072,
387
+ intermediate_size=24576,
388
+ num_hidden_layers=28,
389
+ num_attention_heads=16,
390
+ num_key_value_heads=16,
391
+ head_dim=256,
392
+ hidden_activation="gelu_pytorch_tanh",
393
+ max_position_embeddings=8192,
394
+ initializer_range=0.02,
395
+ rms_norm_eps=1e-6,
396
+ use_cache=True,
397
+ pad_token_id=0,
398
+ eos_token_id=1,
399
+ bos_token_id=2,
400
+ tie_word_embeddings=True,
401
+ rope_theta=10000.0,
402
+ attention_bias=False,
403
+ attention_dropout=0.0,
404
+ query_pre_attn_scalar=224,
405
+ sliding_window=4096,
406
+ final_logit_softcapping=30.0,
407
+ attn_logit_softcapping=50.0,
408
+ cache_implementation="hybrid",
409
+ **kwargs,
410
+ ):
411
+ super().__init__(
412
+ pad_token_id=pad_token_id,
413
+ bos_token_id=bos_token_id,
414
+ eos_token_id=eos_token_id,
415
+ tie_word_embeddings=tie_word_embeddings,
416
+ **kwargs,
417
+ )
418
+ self.vocab_size = vocab_size
419
+ self.max_position_embeddings = max_position_embeddings
420
+ self.hidden_size = hidden_size
421
+ self.intermediate_size = intermediate_size
422
+ self.num_hidden_layers = num_hidden_layers
423
+ self.num_attention_heads = num_attention_heads
424
+ self.head_dim = head_dim
425
+ self.num_key_value_heads = num_key_value_heads
426
+ self.initializer_range = initializer_range
427
+ self.rms_norm_eps = rms_norm_eps
428
+ self.use_cache = use_cache
429
+ self.rope_theta = rope_theta
430
+ self.attention_bias = attention_bias
431
+ self.attention_dropout = attention_dropout
432
+ self.hidden_activation = hidden_activation
433
+ self.query_pre_attn_scalar = query_pre_attn_scalar
434
+ self.sliding_window = sliding_window
435
+ self.final_logit_softcapping = final_logit_softcapping
436
+ self.attn_logit_softcapping = attn_logit_softcapping
437
+ self.cache_implementation = cache_implementation
438
+
439
+
440
+ class MERaLiONConfig(PretrainedConfig):
441
+ r"""
442
+ This is the configuration class to store the configuration of a [`MERaLiONForConditionalGeneration`]. It is used to instantiate an
443
+ MERaLiON model according to the specified arguments, defining the model architecture. Instantiating a configuration
444
+ with the defaults will yield a similar configuration to that of the MERaLiON.
445
+
446
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
447
+ documentation from [`PretrainedConfig`] for more information.
448
+
449
+ Args:
450
+ audio_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
451
+ The config object or dictionary of the audio backbone.
452
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
453
+ The config object or dictionary of the text backbone.
454
+ audio_token_index (`int`, *optional*, defaults to 151646):
455
+ The image token index to encode the image prompt.
456
+ """
457
+
458
+ model_type = "meralion"
459
+ is_composition = False
460
+
461
+ def __init__(
462
+ self,
463
+ speech_config=None,
464
+ text_config=None,
465
+ speech_mlp_scale_factor=15,
466
+ speech_token_index=255999,
467
+ **kwargs,
468
+ ):
469
+
470
+ if isinstance(speech_config, dict):
471
+ speech_config = MERaLiONSpeechConfig(**speech_config)
472
+ elif speech_config is None:
473
+ speech_config = MERaLiONSpeechConfig(
474
+ d_model=1280,
475
+ encoder_attention_heads=20,
476
+ encoder_ffn_dim=5120,
477
+ encoder_layerdrop=0.0,
478
+ encoder_layers=32,
479
+ num_mel_bins=128,
480
+ max_source_positions=1500,
481
+ scale_embedding=False,
482
+ activation_function="gelu",
483
+ )
484
+
485
+ self.speech_config = speech_config
486
+
487
+ if isinstance(text_config, dict):
488
+ text_config = MERaLiONTextConfig(**text_config)
489
+ elif text_config is None:
490
+ text_config = MERaLiONTextConfig()
491
+
492
+ self.text_config = text_config
493
+
494
+ self.speech_mlp_scale_factor = speech_mlp_scale_factor
495
+ self.speech_token_index = speech_token_index
496
+
497
+ self.sliding_window = self.text_config.sliding_window
498
+ self.hidden_size = self.text_config.hidden_size
499
+ self.num_attention_heads = self.text_config.num_attention_heads
500
+ self.num_hidden_layers = self.text_config.num_hidden_layers
501
+ self.num_key_value_heads = self.text_config.num_key_value_heads
502
+ self.head_dim = self.text_config.head_dim
503
+ self.intermediate_size = self.text_config.intermediate_size
504
+
505
+ super().__init__(**kwargs)
vllm_plugin_meralion/vllm_plugin_meralion/modeling_meralion.py ADDED
@@ -0,0 +1,1306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch MERaLiON AudioLLM model."""
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ import torch
8
+ import torch.utils.checkpoint
9
+ from torch import nn
10
+
11
+ from transformers.activations import ACT2FN
12
+ from transformers.cache_utils import EncoderDecoderCache, StaticCache, HybridCache
13
+ from transformers.generation import GenerationMixin
14
+ from transformers.modeling_outputs import ModelOutput, BaseModelOutput
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.utils import (
17
+ add_start_docstrings,
18
+ add_start_docstrings_to_model_forward,
19
+ is_flash_attn_2_available,
20
+ is_flash_attn_greater_or_equal_2_10,
21
+ logging,
22
+ replace_return_docstrings,
23
+ )
24
+
25
+ from .configuration_meralion import MERaLiONConfig, MERaLiONSpeechConfig
26
+ from .modeling_text_decoder import MERaLiONTextForCausalLM
27
+
28
+
29
+ if is_flash_attn_2_available():
30
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ _CONFIG_FOR_DOC = "MERaLiONConfig"
36
+
37
+
38
+ def sinusoids(length: int, channels: int, max_timescale: float = 10000) -> torch.Tensor:
39
+ """Returns sinusoids for positional embedding"""
40
+ if channels % 2 != 0:
41
+ raise ValueError(
42
+ f"Number of channels has to be divisible by 2 for sinusoidal positional embeddings, got {channels} channels."
43
+ )
44
+ log_timescale_increment = math.log(max_timescale) / (channels // 2 - 1)
45
+ inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2))
46
+ scaled_time = torch.arange(length).view(-1, 1) * inv_timescales.view(1, -1)
47
+ return torch.cat([scaled_time.sin(), scaled_time.cos()], dim=1)
48
+
49
+
50
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
51
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
52
+ """
53
+ Shift input ids one token to the right.
54
+ """
55
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
56
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
57
+ shifted_input_ids[:, 0] = decoder_start_token_id
58
+
59
+ if pad_token_id is None:
60
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
61
+ # replace possible -100 values in labels by `pad_token_id`
62
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
63
+
64
+ return shifted_input_ids
65
+
66
+
67
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
68
+ def _prepare_4d_causal_attention_mask_with_cache_position(
69
+ attention_mask: torch.Tensor,
70
+ sequence_length: int,
71
+ target_length: int,
72
+ dtype: torch.dtype,
73
+ device: torch.device,
74
+ min_dtype: float,
75
+ cache_position: torch.Tensor,
76
+ batch_size: int,
77
+ ):
78
+ """
79
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
80
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
81
+
82
+ Args:
83
+ attention_mask (`torch.Tensor`):
84
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
85
+ sequence_length (`int`):
86
+ The sequence length being processed.
87
+ target_length (`int`):
88
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
89
+ dtype (`torch.dtype`):
90
+ The dtype to use for the 4D attention mask.
91
+ device (`torch.device`):
92
+ The device to plcae the 4D attention mask on.
93
+ min_dtype (`float`):
94
+ The minimum value representable with the dtype `dtype`.
95
+ cache_position (`torch.Tensor`):
96
+ Indices depicting the position of the input sequence tokens in the sequence.
97
+ batch_size (`torch.Tensor`):
98
+ Batch size.
99
+ """
100
+ if attention_mask is not None and attention_mask.dim() == 4:
101
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
102
+ causal_mask = attention_mask
103
+ else:
104
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
105
+ if sequence_length != 1:
106
+ causal_mask = torch.triu(causal_mask, diagonal=1)
107
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
108
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
109
+ if attention_mask is not None:
110
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
111
+ mask_length = attention_mask.shape[-1]
112
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
113
+ padding_mask = padding_mask == 0
114
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
115
+ padding_mask, min_dtype
116
+ )
117
+ return causal_mask
118
+
119
+
120
+ class MERaLiONSpeechAttention(nn.Module):
121
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
122
+
123
+ def __init__(
124
+ self,
125
+ embed_dim: int,
126
+ num_heads: int,
127
+ dropout: float = 0.0,
128
+ is_decoder: bool = False,
129
+ bias: bool = True,
130
+ is_causal: bool = False,
131
+ layer_idx: Optional[int] = None,
132
+ config: Optional[MERaLiONSpeechConfig] = None,
133
+ ):
134
+ super().__init__()
135
+ self.embed_dim = embed_dim
136
+ self.num_heads = num_heads
137
+ self.dropout = dropout
138
+ self.head_dim = embed_dim // num_heads
139
+ self.config = config
140
+
141
+ if (self.head_dim * num_heads) != self.embed_dim:
142
+ raise ValueError(
143
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
144
+ f" and `num_heads`: {num_heads})."
145
+ )
146
+ self.scaling = self.head_dim**-0.5
147
+ self.is_decoder = is_decoder
148
+ self.is_causal = is_causal
149
+
150
+ if layer_idx is None and is_decoder:
151
+ logger.warning_once(
152
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
153
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
154
+ "when creating this class."
155
+ )
156
+ self.layer_idx = layer_idx
157
+
158
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
159
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
160
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
161
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
162
+
163
+ # Copied from transformers.models.bart.modeling_bart.BartAttention._shape with BART->speech
164
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
165
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
166
+
167
+ def forward(
168
+ self,
169
+ hidden_states: torch.Tensor,
170
+ key_value_states: Optional[torch.Tensor] = None,
171
+ past_key_value: Optional[EncoderDecoderCache] = None,
172
+ attention_mask: Optional[torch.Tensor] = None,
173
+ layer_head_mask: Optional[torch.Tensor] = None,
174
+ output_attentions: bool = False,
175
+ cache_position: Optional[torch.LongTensor] = None,
176
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
177
+ """Input shape: Batch x Time x Channel"""
178
+
179
+ # if key_value_states are provided this layer is used as a cross-attention layer
180
+ # for the decoder
181
+ is_cross_attention = key_value_states is not None
182
+ bsz, tgt_len, _ = hidden_states.size()
183
+
184
+ # get query proj
185
+ query_states = self._shape(self.q_proj(hidden_states) * self.scaling, tgt_len, bsz)
186
+
187
+ if past_key_value is not None:
188
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
189
+ if is_cross_attention:
190
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
191
+ past_key_value.is_updated[self.layer_idx] = True
192
+ past_key_value = past_key_value.cross_attention_cache
193
+ else:
194
+ past_key_value = past_key_value.self_attention_cache
195
+
196
+ # use key_value_states if cross attention
197
+ current_states = key_value_states if key_value_states is not None else hidden_states
198
+ if is_cross_attention and past_key_value and is_updated:
199
+ # reuse k,v, cross_attentions
200
+ key_states = past_key_value.key_cache[self.layer_idx]
201
+ value_states = past_key_value.value_cache[self.layer_idx]
202
+ else:
203
+ key_states = self._shape(self.k_proj(current_states), -1, bsz)
204
+ value_states = self._shape(self.v_proj(current_states), -1, bsz)
205
+ if past_key_value is not None:
206
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
207
+ cache_position = cache_position if not is_cross_attention else None
208
+ key_states, value_states = past_key_value.update(
209
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
210
+ )
211
+
212
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
213
+
214
+ if attention_mask is not None: # no matter the length, we just slice it
215
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
216
+ attn_weights = attn_weights + causal_mask
217
+
218
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
219
+
220
+ if layer_head_mask is not None:
221
+ if layer_head_mask.size() != (self.num_heads,):
222
+ raise ValueError(
223
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
224
+ f" {layer_head_mask.size()}"
225
+ )
226
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights
227
+
228
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
229
+ attn_output = torch.matmul(attn_probs, value_states)
230
+
231
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
232
+ raise ValueError(
233
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
234
+ f" {attn_output.size()}"
235
+ )
236
+
237
+ attn_output = attn_output.transpose(1, 2)
238
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
239
+ # partitioned across GPUs when using tensor-parallelism.
240
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
241
+
242
+ attn_output = self.out_proj(attn_output)
243
+
244
+ return attn_output, attn_weights, past_key_value
245
+
246
+
247
+ class MERaLiONSpeechFlashAttention2(MERaLiONSpeechAttention):
248
+ """
249
+ MERaLiONSpeech flash attention module. This module inherits from `MERaLiONSpeechAttention` as the weights of the module stays
250
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
251
+ flash attention and deal with padding tokens in case the input contains any of them.
252
+ """
253
+
254
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
255
+ def __init__(self, *args, **kwargs):
256
+ super().__init__(*args, **kwargs)
257
+
258
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
259
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
260
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
261
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
262
+
263
+ def forward(
264
+ self,
265
+ hidden_states: torch.Tensor,
266
+ key_value_states: Optional[torch.Tensor] = None,
267
+ past_key_value: Optional[EncoderDecoderCache] = None,
268
+ attention_mask: Optional[torch.Tensor] = None,
269
+ layer_head_mask: Optional[torch.Tensor] = None,
270
+ output_attentions: bool = False,
271
+ cache_position: Optional[torch.LongTensor] = None,
272
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
273
+ if isinstance(past_key_value, StaticCache):
274
+ raise ValueError(
275
+ "The `static` cache implementation is not compatible with `attn_implementation='flash_attention_2'`. "
276
+ "Use `attn_implementation='sdpa'` in the meantime, and open an issue at https://github.com/huggingface/transformers"
277
+ )
278
+ # SpeechFlashAttention2 attention does not support output_attentions
279
+ if output_attentions:
280
+ raise ValueError("SpeechFlashAttention2 attention does not support output_attentions")
281
+
282
+ # if key_value_states are provided this layer is used as a cross-attention layer
283
+ # for the decoder
284
+ is_cross_attention = key_value_states is not None
285
+ bsz, tgt_len, _ = hidden_states.size()
286
+
287
+ # get query proj
288
+ query_states = torch.reshape(self.q_proj(hidden_states), (bsz, tgt_len, self.num_heads, self.head_dim))
289
+
290
+ if past_key_value is not None:
291
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
292
+ if is_cross_attention:
293
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
294
+ past_key_value.is_updated[self.layer_idx] = True
295
+ past_key_value = past_key_value.cross_attention_cache
296
+ else:
297
+ past_key_value = past_key_value.self_attention_cache
298
+
299
+ # use key_value_states if cross attention
300
+ current_states = key_value_states if key_value_states is not None else hidden_states
301
+ if is_cross_attention and past_key_value and is_updated:
302
+ # reuse k,v, cross_attentions
303
+ key_states = past_key_value.key_cache[self.layer_idx]
304
+ value_states = past_key_value.value_cache[self.layer_idx]
305
+ else:
306
+ key_states = self._shape(self.k_proj(current_states), -1, bsz)
307
+ value_states = self._shape(self.v_proj(current_states), -1, bsz)
308
+ if past_key_value is not None:
309
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
310
+ cache_position = cache_position if not is_cross_attention else None
311
+ key_states, value_states = past_key_value.update(
312
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
313
+ )
314
+
315
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]
316
+ # We would need to refactor the KV cache to be able to avoid many of these transpose/reshape/view.
317
+ key_states = key_states.transpose(1, 2)
318
+ value_states = value_states.transpose(1, 2)
319
+
320
+ causal_mask = attention_mask
321
+ if attention_mask is not None: # no matter the length, we just slice it
322
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
323
+
324
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
325
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
326
+ # cast them back in the correct dtype just to be sure everything works as expected.
327
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
328
+ # in fp32. (LlamaRMSNorm handles it correctly)
329
+
330
+ input_dtype = query_states.dtype
331
+ if input_dtype == torch.float32:
332
+ if torch.is_autocast_enabled():
333
+ target_dtype = torch.get_autocast_gpu_dtype()
334
+ # Handle the case where the model is quantized
335
+ elif hasattr(self.config, "_pre_quantization_dtype"):
336
+ target_dtype = self.config._pre_quantization_dtype
337
+ else:
338
+ target_dtype = self.q_proj.weight.dtype
339
+
340
+ logger.warning_once(
341
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
342
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
343
+ f" {target_dtype}."
344
+ )
345
+
346
+ query_states = query_states.to(target_dtype)
347
+ key_states = key_states.to(target_dtype)
348
+ value_states = value_states.to(target_dtype)
349
+
350
+ attn_output = _flash_attention_forward(
351
+ query_states,
352
+ key_states,
353
+ value_states,
354
+ causal_mask,
355
+ tgt_len,
356
+ dropout=self.dropout if self.training else 0.0,
357
+ is_causal=self.is_causal,
358
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
359
+ )
360
+
361
+ attn_output = attn_output.reshape(bsz, tgt_len, -1)
362
+ attn_output = self.out_proj(attn_output)
363
+
364
+ if not output_attentions:
365
+ attn_weights = None
366
+
367
+ return attn_output, attn_weights, past_key_value
368
+
369
+
370
+ class MERaLiONSpeechSdpaAttention(MERaLiONSpeechAttention):
371
+ def forward(
372
+ self,
373
+ hidden_states: torch.Tensor,
374
+ key_value_states: Optional[torch.Tensor] = None,
375
+ past_key_value: Optional[EncoderDecoderCache] = None,
376
+ attention_mask: Optional[torch.Tensor] = None,
377
+ layer_head_mask: Optional[torch.Tensor] = None,
378
+ output_attentions: bool = False,
379
+ cache_position: Optional[torch.LongTensor] = None,
380
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
381
+ """Input shape: Batch x Time x Channel"""
382
+ if output_attentions or layer_head_mask is not None:
383
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
384
+ logger.warning_once(
385
+ "MERaLiONSpeechModel is using MERaLiONSpeechSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
386
+ ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
387
+ )
388
+ return super().forward(
389
+ hidden_states,
390
+ key_value_states=key_value_states,
391
+ past_key_value=past_key_value,
392
+ attention_mask=attention_mask,
393
+ layer_head_mask=layer_head_mask,
394
+ output_attentions=output_attentions,
395
+ cache_position=cache_position,
396
+ )
397
+
398
+ # if key_value_states are provided this layer is used as a cross-attention layer
399
+ # for the decoder
400
+ is_cross_attention = key_value_states is not None
401
+ bsz, tgt_len, _ = hidden_states.size()
402
+
403
+ # get query proj
404
+ query_states = self._shape(self.q_proj(hidden_states), tgt_len, bsz)
405
+
406
+ if past_key_value is not None:
407
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
408
+ if is_cross_attention:
409
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
410
+ past_key_value.is_updated[self.layer_idx] = True
411
+ past_key_value = past_key_value.cross_attention_cache
412
+ else:
413
+ past_key_value = past_key_value.self_attention_cache
414
+
415
+ # use key_value_states if cross attention
416
+ current_states = key_value_states if key_value_states is not None else hidden_states
417
+ if is_cross_attention and past_key_value and is_updated:
418
+ # reuse k,v, cross_attentions
419
+ key_states = past_key_value.key_cache[self.layer_idx]
420
+ value_states = past_key_value.value_cache[self.layer_idx]
421
+ else:
422
+ key_states = self._shape(self.k_proj(current_states), -1, bsz)
423
+ value_states = self._shape(self.v_proj(current_states), -1, bsz)
424
+ if past_key_value is not None:
425
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
426
+ cache_position = cache_position if not is_cross_attention else None
427
+ key_states, value_states = past_key_value.update(
428
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
429
+ )
430
+
431
+ causal_mask = attention_mask
432
+ if attention_mask is not None: # no matter the length, we just slice it
433
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
434
+
435
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
436
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
437
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
438
+ is_causal = True if self.is_causal and causal_mask is None and tgt_len > 1 else False
439
+
440
+ # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
441
+ # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
442
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
443
+ query_states,
444
+ key_states,
445
+ value_states,
446
+ attn_mask=causal_mask,
447
+ dropout_p=self.dropout if self.training else 0.0,
448
+ is_causal=is_causal,
449
+ )
450
+
451
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
452
+ raise ValueError(
453
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
454
+ f" {attn_output.size()}"
455
+ )
456
+
457
+ attn_output = attn_output.transpose(1, 2)
458
+
459
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
460
+ # partitioned across GPUs when using tensor-parallelism.
461
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
462
+
463
+ attn_output = self.out_proj(attn_output)
464
+
465
+ return attn_output, None, past_key_value
466
+
467
+
468
+ MERALION_SPEECH_ATTENTION_CLASSES = {
469
+ "eager": MERaLiONSpeechAttention,
470
+ "flash_attention_2": MERaLiONSpeechFlashAttention2,
471
+ "sdpa": MERaLiONSpeechSdpaAttention,
472
+ }
473
+
474
+
475
+ # Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Speech, MBART->WHISPER
476
+ class MERaLiONSpeechEncoderLayer(nn.Module):
477
+ def __init__(self, config: MERaLiONSpeechConfig):
478
+ super().__init__()
479
+ self.embed_dim = config.d_model
480
+
481
+ self.self_attn = MERALION_SPEECH_ATTENTION_CLASSES[config._attn_implementation](
482
+ embed_dim=self.embed_dim,
483
+ num_heads=config.encoder_attention_heads,
484
+ dropout=config.attention_dropout,
485
+ config=config,
486
+ )
487
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
488
+ self.dropout = config.dropout
489
+ self.activation_fn = ACT2FN[config.activation_function]
490
+ self.activation_dropout = config.activation_dropout
491
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
492
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
493
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states: torch.Tensor,
498
+ attention_mask: torch.Tensor,
499
+ layer_head_mask: torch.Tensor,
500
+ output_attentions: bool = False,
501
+ ) -> torch.Tensor:
502
+ """
503
+ Args:
504
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
505
+ attention_mask (`torch.FloatTensor`): attention mask of size
506
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
507
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
508
+ `(encoder_attention_heads,)`.
509
+ output_attentions (`bool`, *optional*):
510
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
511
+ returned tensors for more detail.
512
+ """
513
+ residual = hidden_states
514
+ hidden_states = self.self_attn_layer_norm(hidden_states)
515
+ hidden_states, attn_weights, _ = self.self_attn(
516
+ hidden_states=hidden_states,
517
+ attention_mask=attention_mask,
518
+ layer_head_mask=layer_head_mask,
519
+ output_attentions=output_attentions,
520
+ )
521
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
522
+ hidden_states = residual + hidden_states
523
+
524
+ residual = hidden_states
525
+ hidden_states = self.final_layer_norm(hidden_states)
526
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
527
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
528
+ hidden_states = self.fc2(hidden_states)
529
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
530
+ hidden_states = residual + hidden_states
531
+
532
+ if hidden_states.dtype == torch.float16 and (
533
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
534
+ ):
535
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
536
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
537
+
538
+ outputs = (hidden_states,)
539
+
540
+ if output_attentions:
541
+ outputs += (attn_weights,)
542
+
543
+ return outputs
544
+
545
+
546
+ class MERaLiONSpeechPreTrainedModel(PreTrainedModel):
547
+ config_class = MERaLiONSpeechConfig
548
+ base_model_prefix = "model"
549
+ main_input_name = "input_features"
550
+ supports_gradient_checkpointing = True
551
+ _no_split_modules = ["MERaLiONSpeechEncoderLayer", "MERaLiONSpeechDecoderLayer"]
552
+ _supports_flash_attn_2 = True
553
+ _supports_sdpa = True
554
+ _supports_cache_class = True
555
+ _supports_static_cache = True
556
+
557
+ def _init_weights(self, module):
558
+ std = self.config.init_std
559
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
560
+ module.weight.data.normal_(mean=0.0, std=std)
561
+ if module.bias is not None:
562
+ module.bias.data.zero_()
563
+ elif isinstance(module, nn.Embedding):
564
+ module.weight.data.normal_(mean=0.0, std=std)
565
+ if module.padding_idx is not None:
566
+ module.weight.data[module.padding_idx].zero_()
567
+ elif isinstance(module, MERaLiONSpeechEncoder):
568
+ with torch.no_grad():
569
+ embed_positions = module.embed_positions.weight
570
+ embed_positions.copy_(sinusoids(*embed_positions.shape))
571
+
572
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
573
+ """
574
+ Computes the output length of the convolutional layers
575
+ """
576
+ input_lengths = (input_lengths - 1) // 2 + 1
577
+
578
+ return input_lengths
579
+
580
+
581
+ MERALION_SPEECH_START_DOCSTRING = r"""
582
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
583
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
584
+ etc.)
585
+
586
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
587
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
588
+ and behavior.
589
+
590
+ Parameters:
591
+ config ([`MERaLiONSpeechConfig`]):
592
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
593
+ load the weights associated with the model, only the configuration. Check out the
594
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
595
+ """
596
+
597
+ MERALION_SPEECH_INPUTS_DOCSTRING = r"""
598
+ Args:
599
+ input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
600
+ Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by
601
+ loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
602
+ the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
603
+ [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
604
+ tensor of type `torch.FloatTensor`. See [`~SpeechFeatureExtractor.__call__`]
605
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
606
+ Mask to avoid performing *SpecAugment* data augmentation on padding token indices. Mask values selected in
607
+ `[0, 1]`:
608
+
609
+ - 1 for tokens that are **not masked**,
610
+ - 0 for tokens that are **masked**.
611
+
612
+ [What are attention masks?](../glossary#attention-mask)
613
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
614
+ Indices of decoder input sequence tokens in the vocabulary.
615
+
616
+ Indices can be obtained using [`SpeechTokenizer`]. See [`PreTrainedTokenizer.encode`] and
617
+ [`PreTrainedTokenizer.__call__`] for details.
618
+
619
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
620
+
621
+ Speech uses the `decoder_start_token_id` as the starting token for `decoder_input_ids` generation. If
622
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
623
+ `past_key_values`).
624
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
625
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
626
+ be used by default.
627
+
628
+ If you want to change padding behavior, you should read
629
+ [`modeling_speech._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the BART
630
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
631
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
632
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
633
+
634
+ - 1 indicates the head is **not masked**,
635
+ - 0 indicates the head is **masked**.
636
+
637
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
638
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
639
+
640
+ - 1 indicates the head is **not masked**,
641
+ - 0 indicates the head is **masked**.
642
+
643
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
644
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
645
+
646
+ - 1 indicates the head is **not masked**,
647
+ - 0 indicates the head is **masked**.
648
+
649
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
650
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
651
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
652
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
653
+ past_key_values (`EncoderDecoderCache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
654
+ Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are
655
+ four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and
656
+ in the cross-attention blocks (2). The `past_key_values` are returned when `use_cache=True` is passed or
657
+ when `config.use_cache=True`
658
+
659
+ Two formats are allowed:
660
+ - An [`~cache_utils.EncoderDecoderCache`] instance;
661
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
662
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
663
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
664
+
665
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
666
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
667
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
668
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
669
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
670
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
671
+ input (see `past_key_values`). This is useful if you want more control over how to convert
672
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
673
+ use_cache (`bool`, *optional*):
674
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
675
+ `past_key_values`).
676
+ output_attentions (`bool`, *optional*):
677
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
678
+ tensors for more detail.
679
+ output_hidden_states (`bool`, *optional*):
680
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
681
+ more detail.
682
+ return_dict (`bool`, *optional*):
683
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
684
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
685
+ Indices depicting the position of the input sequence tokens in the sequence. It is used to update the cache
686
+ in the correct position and to infer the complete sequence length.
687
+ """
688
+
689
+ MERALION_SPEECH_ENCODER_INPUTS_DOCSTRING = r"""
690
+ Args:
691
+ input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
692
+ Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by
693
+ loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
694
+ the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
695
+ [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
696
+ tensor of type `torch.FloatTensor`. See [`~SpeechFeatureExtractor.__call__`]
697
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
698
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
699
+
700
+ - 1 indicates the head is **not masked**,
701
+ - 0 indicates the head is **masked**.
702
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
703
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
704
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
705
+ hidden-states at the output of the last layer of the encoder.
706
+ output_attentions (`bool`, *optional*):
707
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
708
+ tensors for more detail.
709
+ output_hidden_states (`bool`, *optional*):
710
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
711
+ more detail.
712
+ return_dict (`bool`, *optional*):
713
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
714
+ """
715
+
716
+
717
+ class MERaLiONSpeechEncoder(MERaLiONSpeechPreTrainedModel):
718
+ """
719
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
720
+ [`MERaLiONSpeechEncoderLayer`].
721
+
722
+ Args:
723
+ config: MERaLiONSpeechConfig
724
+ """
725
+
726
+ def __init__(self, config: MERaLiONSpeechConfig):
727
+ super().__init__(config)
728
+ self.dropout = config.dropout
729
+ self.layerdrop = config.encoder_layerdrop
730
+
731
+ embed_dim = config.d_model
732
+ self.num_mel_bins = config.num_mel_bins
733
+ self.padding_idx = config.pad_token_id
734
+ self.max_source_positions = config.max_source_positions
735
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
736
+
737
+ self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)
738
+ self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)
739
+
740
+ self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim)
741
+ self.embed_positions.requires_grad_(False)
742
+
743
+ self.layers = nn.ModuleList([MERaLiONSpeechEncoderLayer(config) for _ in range(config.encoder_layers)])
744
+ self.layer_norm = nn.LayerNorm(config.d_model)
745
+
746
+ self.gradient_checkpointing = False
747
+ # Initialize weights and apply final processing
748
+ self.post_init()
749
+
750
+ def _freeze_parameters(self):
751
+ for param in self.parameters():
752
+ param.requires_grad = False
753
+ self._requires_grad = False
754
+
755
+ def get_input_embeddings(self) -> nn.Module:
756
+ return self.conv1
757
+
758
+ def set_input_embeddings(self, value: nn.Module):
759
+ self.conv1 = value
760
+
761
+ def forward(
762
+ self,
763
+ input_features,
764
+ attention_mask=None,
765
+ head_mask=None,
766
+ output_attentions=None,
767
+ output_hidden_states=None,
768
+ return_dict=None,
769
+ ):
770
+ r"""
771
+ Args:
772
+ input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):
773
+ Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
774
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a
775
+ `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
776
+ `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
777
+ and conversion into a tensor of type `torch.FloatTensor`. See [`~SpeechFeatureExtractor.__call__`]
778
+ attention_mask (`torch.Tensor`)`, *optional*):
779
+ Speech does not support masking of the `input_features`, this argument is preserved for compatibility,
780
+ but it is not used. By default the silence in the input log mel spectrogram are ignored.
781
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
782
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
783
+
784
+ - 1 indicates the head is **not masked**,
785
+ - 0 indicates the head is **masked**.
786
+ output_attentions (`bool`, *optional*):
787
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
788
+ returned tensors for more detail.
789
+ output_hidden_states (`bool`, *optional*):
790
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
791
+ for more detail.
792
+ return_dict (`bool`, *optional*):
793
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
794
+ """
795
+
796
+ expected_seq_length = self.config.max_source_positions * self.conv1.stride[0] * self.conv2.stride[0]
797
+ if input_features.shape[-1] != expected_seq_length:
798
+ raise ValueError(
799
+ f"Speech expects the mel input features to be of length {expected_seq_length}, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
800
+ )
801
+
802
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
803
+ output_hidden_states = (
804
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
805
+ )
806
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
807
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
808
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
809
+
810
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
811
+ embed_pos = self.embed_positions.weight
812
+
813
+ hidden_states = inputs_embeds + embed_pos
814
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
815
+
816
+ encoder_states = () if output_hidden_states else None
817
+ all_attentions = () if output_attentions else None
818
+
819
+ # check if head_mask has a correct number of layers specified if desired
820
+ if head_mask is not None:
821
+ assert head_mask.size()[0] == (
822
+ len(self.layers)
823
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
824
+
825
+ for idx, encoder_layer in enumerate(self.layers):
826
+ if output_hidden_states:
827
+ encoder_states = encoder_states + (hidden_states,)
828
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
829
+ to_drop = False
830
+ if self.training:
831
+ dropout_probability = torch.rand([])
832
+ if dropout_probability < self.layerdrop: # skip the layer
833
+ to_drop = True
834
+
835
+ if to_drop:
836
+ layer_outputs = (None, None)
837
+ else:
838
+ if self.gradient_checkpointing and self.training:
839
+ layer_outputs = self._gradient_checkpointing_func(
840
+ encoder_layer.__call__,
841
+ hidden_states,
842
+ None,
843
+ (head_mask[idx] if head_mask is not None else None),
844
+ output_attentions,
845
+ )
846
+ else:
847
+ layer_outputs = encoder_layer(
848
+ hidden_states,
849
+ None,
850
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
851
+ output_attentions=output_attentions,
852
+ )
853
+
854
+ hidden_states = layer_outputs[0]
855
+
856
+ if output_attentions:
857
+ all_attentions = all_attentions + (layer_outputs[1],)
858
+
859
+ hidden_states = self.layer_norm(hidden_states)
860
+ if output_hidden_states:
861
+ encoder_states = encoder_states + (hidden_states,)
862
+
863
+ if not return_dict:
864
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
865
+ return BaseModelOutput(
866
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
867
+ )
868
+
869
+
870
+ # copied from Qwen2AudioCausalLMOutputWithPast
871
+ @dataclass
872
+ class MERaLiONOutputWithPast(ModelOutput):
873
+ """
874
+ Base class for MERaLiON causal language model (or autoregressive) outputs.
875
+
876
+ Args:
877
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
878
+ Language modeling loss (for next-token prediction).
879
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
880
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
881
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
882
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
883
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
884
+
885
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
886
+ `past_key_values` input) to speed up sequential decoding.
887
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
888
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
889
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
890
+
891
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
892
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
893
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
894
+ sequence_length)`.
895
+
896
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
897
+ heads.
898
+ attention_mask (`torch.FloatTensor`, *optional*):
899
+ Attentions mask, used to update attention mask and position_ids.
900
+ """
901
+
902
+ loss: Optional[torch.FloatTensor] = None
903
+ logits: torch.FloatTensor = None
904
+ past_key_values: Optional[List[torch.FloatTensor]] = None
905
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
906
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
907
+ attention_mask: Optional[torch.FloatTensor] = None
908
+
909
+
910
+ MERALION_START_DOCSTRING = r"""
911
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
912
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
913
+ etc.)
914
+
915
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
916
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
917
+ and behavior.
918
+
919
+ Parameters:
920
+ config ([`MERaLiONConfig`]):
921
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
922
+ load the weights associated with the model, only the configuration. Check out the
923
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
924
+ """
925
+
926
+
927
+ @add_start_docstrings(
928
+ "The bare MERaLiON Model outputting raw hidden-states without any specific head on top.",
929
+ MERALION_START_DOCSTRING,
930
+ )
931
+ class MERaLiONPreTrainedModel(PreTrainedModel):
932
+ config_class = MERaLiONConfig
933
+ base_model_prefix = "model"
934
+ supports_gradient_checkpointing = True
935
+ _no_split_modules = ["MERaLiONSpeechEncoderLayer", "MERaLiONSpeechDecoderLayer", "MERaLiONTextDecoderLayer"]
936
+ _supports_flash_attn_2 = True
937
+ _supports_sdpa = True
938
+ _supports_cache_class = True
939
+ _supports_static_cache = True
940
+
941
+ def _init_weights(self, module):
942
+ # important: this ported version of Qwen2Audio isn't meant for training from scratch - only
943
+ # inference and fine-tuning - so the proper init weights code has been removed
944
+ std = self.config.init_std if hasattr(self.config, "init_std") else self.config.speech_config.init_std
945
+
946
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
947
+ module.weight.data.normal_(mean=0.0, std=std)
948
+ if module.bias is not None:
949
+ module.bias.data.zero_()
950
+ elif isinstance(module, nn.Embedding):
951
+ module.weight.data.normal_(mean=0.0, std=std)
952
+ if module.padding_idx is not None:
953
+ module.weight.data[module.padding_idx].zero_()
954
+
955
+ @property
956
+ def _supports_sdpa(self):
957
+ """
958
+ Retrieve language_model's attribute to check whether the model supports
959
+ SDPA or not.
960
+ """
961
+ return self.text_decoder._supports_sdpa
962
+
963
+ class MERaLiONSpeechAudioAdaper(nn.Module):
964
+ def __init__(
965
+ self,
966
+ config,
967
+ **kwargs
968
+ ):
969
+ super(MERaLiONSpeechAudioAdaper, self).__init__()
970
+ speech_audio_encoder_output_dim = config.speech_config.d_model
971
+ llm_input_hidden_size = config.text_config.hidden_size
972
+ speech_mlp_scale_factor = config.speech_mlp_scale_factor
973
+
974
+ self.speech_mlp_scale_factor = speech_mlp_scale_factor
975
+ self.mlp_adapter = nn.Sequential(
976
+ nn.Linear(
977
+ in_features=speech_audio_encoder_output_dim * speech_mlp_scale_factor,
978
+ out_features=speech_audio_encoder_output_dim
979
+ ),
980
+ nn.SiLU(),
981
+ nn.Dropout(0.1),
982
+ )
983
+
984
+ self.speech_llm_proj = nn.Sequential(
985
+ nn.Linear(
986
+ speech_audio_encoder_output_dim,
987
+ speech_audio_encoder_output_dim * 4
988
+ ),
989
+ nn.SiLU(),
990
+ nn.Dropout(0.1),
991
+
992
+ nn.Linear(
993
+ speech_audio_encoder_output_dim * 4,
994
+ llm_input_hidden_size
995
+ ),
996
+ )
997
+
998
+ def forward(self, speech_embeds, **kwargs):
999
+ B, T, C = speech_embeds.shape
1000
+ speech_embeds = self.mlp_adapter(
1001
+ speech_embeds.reshape(
1002
+ B,
1003
+ T // self.speech_mlp_scale_factor,
1004
+ C * self.speech_mlp_scale_factor,
1005
+ )
1006
+ )
1007
+ return self.speech_llm_proj(speech_embeds)
1008
+
1009
+
1010
+ MERALION_INPUTS_DOCSTRING = r"""
1011
+ Args:
1012
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1013
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1014
+ it.
1015
+
1016
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1017
+ [`PreTrainedTokenizer.__call__`] for details.
1018
+
1019
+ [What are input IDs?](../glossary#input-ids)
1020
+ input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, feature_sequence_length)`, *optional*):
1021
+ Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by
1022
+ loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
1023
+ the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
1024
+ [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
1025
+ tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
1026
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1027
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1028
+
1029
+ - 1 for tokens that are **not masked**,
1030
+ - 0 for tokens that are **masked**.
1031
+
1032
+ [What are attention masks?](../glossary#attention-mask)
1033
+
1034
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1035
+ [`PreTrainedTokenizer.__call__`] for details.
1036
+
1037
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1038
+ `past_key_values`).
1039
+
1040
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1041
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1042
+ information on the default strategy.
1043
+
1044
+ - 1 indicates the head is **not masked**,
1045
+ - 0 indicates the head is **masked**.
1046
+ feature_attention_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`, *optional*):
1047
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
1048
+
1049
+ - 1 for tokens that are **not masked**,
1050
+ - 0 for tokens that are **masked**.
1051
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1052
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1053
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
1054
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1055
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1056
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
1057
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1058
+
1059
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1060
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1061
+
1062
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1063
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1064
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1065
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1066
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1067
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1068
+ model's internal embedding lookup matrix.
1069
+ use_cache (`bool`, *optional*):
1070
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1071
+ `past_key_values`).
1072
+ output_attentions (`bool`, *optional*):
1073
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1074
+ tensors for more detail.
1075
+ output_hidden_states (`bool`, *optional*):
1076
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1077
+ more detail.
1078
+ return_dict (`bool`, *optional*):
1079
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1080
+ """
1081
+
1082
+ @add_start_docstrings(
1083
+ """The MERALION model which consists of a audio backbone and a language model.""",
1084
+ MERALION_START_DOCSTRING,
1085
+ )
1086
+ class MERaLiONForConditionalGeneration(MERaLiONPreTrainedModel, GenerationMixin):
1087
+ def __init__(self, config: MERaLiONConfig):
1088
+ config.text_config._attn_implementation = config._attn_implementation
1089
+ config.speech_config._attn_implementation = config._attn_implementation
1090
+
1091
+ super().__init__(config)
1092
+
1093
+ self.speech_encoder = MERaLiONSpeechEncoder(config.speech_config)
1094
+ # self.speech_encoder = AutoModel.from_config(config.audio_config, attn_implementation=config._attn_implementation)
1095
+
1096
+ self.ln_speech = nn.LayerNorm(config.speech_config.d_model)
1097
+ self.speech_audio_adapter = MERaLiONSpeechAudioAdaper(config)
1098
+ self.vocab_size = config.text_config.vocab_size
1099
+ self.text_decoder = MERaLiONTextForCausalLM(config.text_config)
1100
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
1101
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
1102
+ self.post_init()
1103
+
1104
+ @property
1105
+ def padding_side(self):
1106
+ return self._padding_side
1107
+
1108
+ @padding_side.setter
1109
+ def padding_side(self, padding_side: str):
1110
+ if padding_side not in ["left", "right"]:
1111
+ raise ValueError(f"{padding_side} is not `left` or `right`.")
1112
+ self._padding_side = padding_side
1113
+
1114
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_input_embeddings
1115
+ def get_input_embeddings(self):
1116
+ return self.text_decoder.get_input_embeddings()
1117
+
1118
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_input_embeddings
1119
+ def set_input_embeddings(self, value):
1120
+ self.text_decoder.set_input_embeddings(value)
1121
+
1122
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_output_embeddings
1123
+ def get_output_embeddings(self):
1124
+ return self.text_decoder.get_output_embeddings()
1125
+
1126
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_output_embeddings
1127
+ def set_output_embeddings(self, new_embeddings):
1128
+ self.text_decoder.set_output_embeddings(new_embeddings)
1129
+
1130
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_decoder
1131
+ def set_decoder(self, decoder):
1132
+ self.text_decoder.set_decoder(decoder)
1133
+
1134
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_decoder
1135
+ def get_decoder(self):
1136
+ return self.text_decoder.get_decoder()
1137
+
1138
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.tie_weights
1139
+ def tie_weights(self):
1140
+ return self.text_decoder.tie_weights()
1141
+
1142
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.resize_token_embeddings
1143
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
1144
+ model_embeds = self.text_decoder.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
1145
+ # update vocab size
1146
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
1147
+ self.vocab_size = model_embeds.num_embeddings
1148
+ return model_embeds
1149
+
1150
+ @add_start_docstrings_to_model_forward(MERALION_INPUTS_DOCSTRING)
1151
+ @replace_return_docstrings(output_type=MERaLiONOutputWithPast, config_class=_CONFIG_FOR_DOC)
1152
+ def forward(
1153
+ self,
1154
+ input_ids: torch.LongTensor = None,
1155
+ input_features: torch.FloatTensor = None,
1156
+ attention_mask: Optional[torch.Tensor] = None,
1157
+ feature_attention_mask: Optional[torch.Tensor] = None,
1158
+ position_ids: Optional[torch.LongTensor] = None,
1159
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1160
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1161
+ labels: Optional[torch.LongTensor] = None,
1162
+ use_cache: Optional[bool] = None,
1163
+ cache_position: Optional[torch.LongTensor] = None,
1164
+ output_attentions: Optional[bool] = None,
1165
+ output_hidden_states: Optional[bool] = None,
1166
+ return_dict: Optional[bool] = None,
1167
+ ) -> Union[Tuple, MERaLiONOutputWithPast]:
1168
+ r"""
1169
+ Args:
1170
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1171
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1172
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1173
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1174
+
1175
+ Returns:
1176
+ """
1177
+
1178
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1179
+ output_hidden_states = (
1180
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1181
+ )
1182
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1183
+
1184
+ speech_encoder_device = self.speech_encoder.device
1185
+
1186
+ if input_features is not None:
1187
+ input_features = input_features.to(speech_encoder_device)
1188
+ feature_attention_mask = feature_attention_mask.to(speech_encoder_device)
1189
+
1190
+ if inputs_embeds is None:
1191
+ speech_contexts_embeds = self.speech_encoder(input_features, attention_mask=feature_attention_mask).last_hidden_state
1192
+ speech_contexts_embeds = self.ln_speech(speech_contexts_embeds)
1193
+ speech_audio_contexts_embeds = self.speech_audio_adapter(speech_contexts_embeds)
1194
+
1195
+ inputs_embeds = self.text_decoder.base_model.embed_tokens(input_ids)
1196
+
1197
+ speech_mask = (input_ids == self.config.speech_token_index).unsqueeze(-1)
1198
+ speech_mask = speech_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
1199
+
1200
+ inputs_embeds = inputs_embeds.masked_scatter(speech_mask, speech_audio_contexts_embeds)
1201
+
1202
+ input_ids = None
1203
+
1204
+ outputs = self.text_decoder(
1205
+ input_ids=input_ids,
1206
+ attention_mask=attention_mask,
1207
+ position_ids=position_ids,
1208
+ past_key_values=past_key_values,
1209
+ inputs_embeds=inputs_embeds,
1210
+ use_cache=use_cache,
1211
+ cache_position=cache_position,
1212
+ output_attentions=output_attentions,
1213
+ output_hidden_states=output_hidden_states,
1214
+ return_dict=return_dict,
1215
+ labels=labels
1216
+ )
1217
+
1218
+ return outputs
1219
+
1220
+ # from transformers.models.gemma2.modeling_gemma2.Gemma2ForCausalLM.prepare_inputs_for_generation
1221
+ def prepare_inputs_for_generation(
1222
+ self,
1223
+ input_ids,
1224
+ attention_mask=None,
1225
+ input_features=None,
1226
+ feature_attention_mask=None,
1227
+ past_key_values=None,
1228
+ inputs_embeds=None,
1229
+ cache_position=None,
1230
+ position_ids=None,
1231
+ use_cache=None,
1232
+ **kwargs,
1233
+ ):
1234
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1235
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1236
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1237
+ is_first_step = cache_position[0].item() == 0
1238
+ if past_key_values is not None:
1239
+ if inputs_embeds is not None: # Exception 1
1240
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1241
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1242
+ input_ids = input_ids[:, cache_position]
1243
+
1244
+ if attention_mask is not None and position_ids is None:
1245
+ # create position_ids on the fly for batch generation
1246
+ position_ids = attention_mask.long().cumsum(-1) - 1
1247
+ position_ids.masked_fill_(attention_mask == 0, 1)
1248
+ if past_key_values:
1249
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1250
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s
1251
+ # `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride
1252
+ # during the decoding. Here, simply using `.contiguous()` is not sufficient as in the
1253
+ # batch size = 1 case, `position_ids` is already contiguous but with varying stride
1254
+ # which retriggers a capture.
1255
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1256
+
1257
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1258
+ if inputs_embeds is not None and is_first_step:
1259
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1260
+ else:
1261
+ # The clone here is for the same reason as for `position_ids`.
1262
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1263
+
1264
+ if (
1265
+ isinstance(past_key_values, HybridCache)
1266
+ and attention_mask.ndim == 2
1267
+ and not self.config._attn_implementation == "flash_attention_2"
1268
+ ):
1269
+ if model_inputs["inputs_embeds"] is not None:
1270
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1271
+ device = model_inputs["inputs_embeds"].device
1272
+ else:
1273
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1274
+ device = model_inputs["input_ids"].device
1275
+ dtype = self.text_decoder.lm_head.weight.dtype
1276
+ min_dtype = torch.finfo(dtype).min
1277
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1278
+ attention_mask,
1279
+ sequence_length=sequence_length,
1280
+ target_length=past_key_values.get_max_length(),
1281
+ dtype=dtype,
1282
+ device=device,
1283
+ min_dtype=min_dtype,
1284
+ cache_position=cache_position,
1285
+ batch_size=batch_size,
1286
+ )
1287
+
1288
+ model_inputs.update(
1289
+ {
1290
+ "attention_mask": attention_mask,
1291
+ "position_ids": position_ids,
1292
+ "cache_position": cache_position,
1293
+ "past_key_values": past_key_values,
1294
+ "use_cache": use_cache
1295
+ }
1296
+ )
1297
+
1298
+ # Input ids will only be used from the second step.
1299
+ if is_first_step:
1300
+ model_inputs["input_features"] = input_features
1301
+ model_inputs["feature_attention_mask"] = feature_attention_mask
1302
+
1303
+ return model_inputs
1304
+
1305
+ def _reorder_cache(self, *args, **kwargs):
1306
+ return self.text_decoder._reorder_cache(*args, **kwargs)
vllm_plugin_meralion/vllm_plugin_meralion/modeling_text_decoder.py ADDED
@@ -0,0 +1,1319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch MERaLiON AudioLLM model text decoder."""
2
+
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.utils.checkpoint
8
+
9
+ from transformers.activations import ACT2FN
10
+ from transformers.cache_utils import Cache, HybridCache
11
+ from transformers.generation import GenerationMixin
12
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
13
+ from transformers.modeling_outputs import (
14
+ BaseModelOutputWithPast,
15
+ CausalLMOutputWithPast,
16
+ SequenceClassifierOutputWithPast,
17
+ TokenClassifierOutput,
18
+ )
19
+ from transformers.modeling_utils import PreTrainedModel
20
+ from transformers.utils import (
21
+ add_code_sample_docstrings,
22
+ add_start_docstrings,
23
+ add_start_docstrings_to_model_forward,
24
+ is_flash_attn_greater_or_equal,
25
+ is_flash_attn_greater_or_equal_2_10,
26
+ logging,
27
+ replace_return_docstrings,
28
+ )
29
+ from .configuration_meralion import MERaLiONTextConfig
30
+
31
+
32
+ _CHECKPOINT_FOR_DOC = "MERaLiON/MERaLiON-AudioLLM-Whisper-SEA-LION"
33
+
34
+
35
+ class MERaLiONTextRMSNorm(nn.Module):
36
+ def __init__(self, dim: int, eps: float = 1e-6):
37
+ super().__init__()
38
+ self.eps = eps
39
+ self.weight = nn.Parameter(torch.zeros(dim))
40
+
41
+ def _norm(self, x):
42
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
43
+
44
+ def forward(self, x):
45
+ output = self._norm(x.float())
46
+ # Llama does x.to(float16) * w whilst MERaLiONText is (x * w).to(float16)
47
+ # See https://github.com/huggingface/transformers/pull/29402
48
+ output = output * (1.0 + self.weight.float())
49
+ return output.type_as(x)
50
+
51
+ def extra_repr(self):
52
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
53
+
54
+
55
+ class MERaLiONTextMLP(nn.Module):
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.config = config
59
+ self.hidden_size = config.hidden_size
60
+ self.intermediate_size = config.intermediate_size
61
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
62
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
63
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
64
+ self.act_fn = ACT2FN[config.hidden_activation]
65
+
66
+ def forward(self, x):
67
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
68
+
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+
73
+ class MERaLiONTextRotaryEmbedding(nn.Module):
74
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
75
+ super().__init__()
76
+
77
+ self.dim = dim
78
+ self.max_position_embeddings = max_position_embeddings
79
+ self.base = base
80
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
81
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
82
+
83
+ @torch.no_grad()
84
+ def forward(self, x, position_ids, seq_len=None):
85
+ # x: [bs, num_attention_heads, seq_len, head_size]
86
+ self.inv_freq.to(x.device)
87
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
88
+ position_ids_expanded = position_ids[:, None, :].float()
89
+ # Force float32 since bfloat16 loses precision on long contexts
90
+ # See https://github.com/huggingface/transformers/pull/29285
91
+ device_type = x.device.type
92
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
93
+ with torch.autocast(device_type=device_type, enabled=False):
94
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
95
+ emb = torch.cat((freqs, freqs), dim=-1)
96
+ cos = emb.cos()
97
+ sin = emb.sin()
98
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
99
+
100
+
101
+ def rotate_half(x):
102
+ """Rotates half the hidden dims of the input."""
103
+ x1 = x[..., : x.shape[-1] // 2]
104
+ x2 = x[..., x.shape[-1] // 2 :]
105
+ return torch.cat((-x2, x1), dim=-1)
106
+
107
+
108
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
109
+ """Applies Rotary Position Embedding to the query and key tensors.
110
+
111
+ Args:
112
+ q (`torch.Tensor`): The query tensor.
113
+ k (`torch.Tensor`): The key tensor.
114
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
115
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
116
+ position_ids (`torch.Tensor`, *optional*):
117
+ Deprecated and unused.
118
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
119
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
120
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
121
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
122
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
123
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
124
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
125
+ Returns:
126
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
127
+ """
128
+ cos = cos.unsqueeze(unsqueeze_dim)
129
+ sin = sin.unsqueeze(unsqueeze_dim)
130
+ q_embed = (q * cos) + (rotate_half(q) * sin)
131
+ k_embed = (k * cos) + (rotate_half(k) * sin)
132
+ return q_embed, k_embed
133
+
134
+
135
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
136
+ """
137
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
138
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
139
+ """
140
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
141
+ if n_rep == 1:
142
+ return hidden_states
143
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
144
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
145
+
146
+
147
+ class MERaLiONTextAttention(nn.Module):
148
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
149
+
150
+ def __init__(self, config: MERaLiONTextConfig, layer_idx: Optional[int] = None):
151
+ super().__init__()
152
+ self.config = config
153
+ self.layer_idx = layer_idx
154
+ if layer_idx is None:
155
+ logger.warning_once(
156
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
157
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
158
+ "when creating this class."
159
+ )
160
+
161
+ self.attention_dropout = config.attention_dropout
162
+ self.hidden_size = config.hidden_size
163
+ self.num_heads = config.num_attention_heads
164
+ self.head_dim = config.head_dim
165
+ self.num_key_value_heads = config.num_key_value_heads
166
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
167
+ self.max_position_embeddings = config.max_position_embeddings
168
+ self.rope_theta = config.rope_theta
169
+ self.is_causal = True
170
+ self.scaling = config.query_pre_attn_scalar**-0.5
171
+
172
+ if self.hidden_size % self.num_heads != 0:
173
+ raise ValueError(
174
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
175
+ f" and `num_heads`: {self.num_heads})."
176
+ )
177
+
178
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
179
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
180
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
181
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
182
+ self.sliding_window = config.sliding_window if not bool(layer_idx % 2) else None
183
+ self.rotary_emb = MERaLiONTextRotaryEmbedding(
184
+ self.head_dim,
185
+ max_position_embeddings=self.max_position_embeddings,
186
+ base=self.rope_theta,
187
+ )
188
+
189
+ def forward(
190
+ self,
191
+ hidden_states: torch.Tensor,
192
+ attention_mask: Optional[torch.Tensor] = None,
193
+ position_ids: Optional[torch.LongTensor] = None,
194
+ past_key_value: Optional[Cache] = None,
195
+ output_attentions: bool = False,
196
+ use_cache: bool = False,
197
+ cache_position: Optional[torch.LongTensor] = None,
198
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
199
+ bsz, q_len, _ = hidden_states.size()
200
+
201
+ query_states = self.q_proj(hidden_states)
202
+ key_states = self.k_proj(hidden_states)
203
+ value_states = self.v_proj(hidden_states)
204
+
205
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
206
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
207
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
208
+
209
+ cos, sin = self.rotary_emb(value_states, position_ids)
210
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
211
+
212
+ if past_key_value is not None:
213
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
214
+ cache_kwargs = {
215
+ "sin": sin,
216
+ "cos": cos,
217
+ "sliding_window": self.sliding_window,
218
+ "cache_position": cache_position,
219
+ }
220
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
221
+
222
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
223
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
224
+
225
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
226
+
227
+ if self.config.attn_logit_softcapping is not None:
228
+ attn_weights = attn_weights / self.config.attn_logit_softcapping
229
+ attn_weights = torch.tanh(attn_weights)
230
+ attn_weights = attn_weights * self.config.attn_logit_softcapping
231
+ if attention_mask is not None: # no matter the length, we just slice it
232
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
233
+ attn_weights = attn_weights + causal_mask
234
+
235
+ # upcast attention to fp32
236
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
237
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
238
+ attn_output = torch.matmul(attn_weights, value_states)
239
+
240
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
241
+ raise ValueError(
242
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
243
+ f" {attn_output.size()}"
244
+ )
245
+
246
+ attn_output = attn_output.transpose(1, 2).contiguous()
247
+
248
+ attn_output = attn_output.view(bsz, q_len, -1)
249
+ attn_output = self.o_proj(attn_output)
250
+
251
+ if not output_attentions:
252
+ attn_weights = None
253
+
254
+ return attn_output, attn_weights, past_key_value
255
+
256
+
257
+ class MERaLiONTextFlashAttention2(MERaLiONTextAttention):
258
+ """
259
+ MERaLiONText flash attention module. This module inherits from `MERaLiONTextAttention` as the weights of the module stays
260
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
261
+ flash attention and deal with padding tokens in case the input contains any of them.
262
+ """
263
+
264
+ def __init__(self, *args, **kwargs):
265
+ super().__init__(*args, **kwargs)
266
+
267
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
268
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
269
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
270
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
271
+
272
+ def forward(
273
+ self,
274
+ hidden_states: torch.Tensor,
275
+ attention_mask: Optional[torch.LongTensor] = None,
276
+ position_ids: Optional[torch.LongTensor] = None,
277
+ past_key_value: Optional[Cache] = None,
278
+ output_attentions: bool = False,
279
+ use_cache: bool = False,
280
+ cache_position: Optional[torch.LongTensor] = None,
281
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
282
+ output_attentions = False
283
+
284
+ bsz, q_len, _ = hidden_states.size()
285
+
286
+ query_states = self.q_proj(hidden_states)
287
+ key_states = self.k_proj(hidden_states)
288
+ value_states = self.v_proj(hidden_states)
289
+
290
+ # Flash attention requires the input to have the shape
291
+ # batch_size x seq_length x head_dim x hidden_dim
292
+ # therefore we just need to keep the original shape
293
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
294
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
295
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
296
+
297
+ cos, sin = self.rotary_emb(value_states, position_ids)
298
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
299
+
300
+ if past_key_value is not None:
301
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
302
+ cache_kwargs = {
303
+ "sin": sin,
304
+ "cos": cos,
305
+ "sliding_window": self.sliding_window,
306
+ "cache_position": cache_position,
307
+ }
308
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
309
+
310
+ if attention_mask is not None:
311
+ seq_len = attention_mask.shape[1]
312
+ key_states = key_states[:, :, :seq_len]
313
+ value_states = value_states[:, :, :seq_len]
314
+
315
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
316
+ # to be able to avoid many of these transpose/reshape/view.
317
+ query_states = query_states.transpose(1, 2)
318
+ key_states = key_states.transpose(1, 2)
319
+ value_states = value_states.transpose(1, 2)
320
+
321
+ dropout_rate = self.attention_dropout if self.training else 0.0
322
+
323
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
324
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
325
+ # cast them back in the correct dtype just to be sure everything works as expected.
326
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
327
+ # in fp32. (MERaLiONTextRMSNorm handles it correctly)
328
+
329
+ input_dtype = query_states.dtype
330
+ if input_dtype == torch.float32:
331
+ if torch.is_autocast_enabled():
332
+ target_dtype = torch.get_autocast_gpu_dtype()
333
+ # Handle the case where the model is quantized
334
+ elif hasattr(self.config, "_pre_quantization_dtype"):
335
+ target_dtype = self.config._pre_quantization_dtype
336
+ else:
337
+ target_dtype = self.q_proj.weight.dtype
338
+
339
+ logger.warning_once(
340
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
341
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
342
+ f" {target_dtype}."
343
+ )
344
+
345
+ query_states = query_states.to(target_dtype)
346
+ key_states = key_states.to(target_dtype)
347
+ value_states = value_states.to(target_dtype)
348
+
349
+ attn_output = _flash_attention_forward(
350
+ query_states,
351
+ key_states,
352
+ value_states,
353
+ attention_mask,
354
+ q_len,
355
+ dropout=dropout_rate,
356
+ softmax_scale=self.scaling,
357
+ is_causal=self.is_causal,
358
+ sliding_window=self.sliding_window,
359
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
360
+ softcap=self.config.attn_logit_softcapping if is_flash_attn_greater_or_equal("2.6.0") else None,
361
+ )
362
+
363
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
364
+ attn_output = self.o_proj(attn_output)
365
+
366
+ if not output_attentions:
367
+ attn_weights = None
368
+
369
+ return attn_output, attn_weights, past_key_value
370
+
371
+
372
+ class MERaLiONTextSdpaAttention(MERaLiONTextAttention):
373
+ """
374
+ MERaLiONText attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
375
+ `MERaLiONTextAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
376
+ SDPA API.
377
+ """
378
+
379
+ # Adapted from MERaLiONTextAttention.forward
380
+ def forward(
381
+ self,
382
+ hidden_states: torch.Tensor,
383
+ attention_mask: Optional[torch.Tensor] = None,
384
+ position_ids: Optional[torch.LongTensor] = None,
385
+ past_key_value: Optional[Cache] = None,
386
+ output_attentions: bool = False,
387
+ use_cache: bool = False,
388
+ cache_position: Optional[torch.LongTensor] = None,
389
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
390
+ if output_attentions:
391
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
392
+ logger.warning_once(
393
+ "MERaLiONTextModel is using MERaLiONTextSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
394
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
395
+ )
396
+ return super().forward(
397
+ hidden_states=hidden_states,
398
+ attention_mask=attention_mask,
399
+ position_ids=position_ids,
400
+ past_key_value=past_key_value,
401
+ output_attentions=output_attentions,
402
+ use_cache=use_cache,
403
+ cache_position=cache_position,
404
+ )
405
+
406
+ bsz, q_len, _ = hidden_states.size()
407
+
408
+ query_states = self.q_proj(hidden_states)
409
+ key_states = self.k_proj(hidden_states)
410
+ value_states = self.v_proj(hidden_states)
411
+
412
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
413
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
414
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
415
+
416
+ cos, sin = self.rotary_emb(value_states, position_ids)
417
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
418
+
419
+ if past_key_value is not None:
420
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
421
+ cache_kwargs = {
422
+ "sin": sin,
423
+ "cos": cos,
424
+ "sliding_window": self.sliding_window,
425
+ "cache_position": cache_position,
426
+ }
427
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
428
+
429
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
430
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
431
+
432
+ causal_mask = attention_mask
433
+ if attention_mask is not None:
434
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
435
+
436
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
437
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
438
+ if query_states.device.type == "cuda" and causal_mask is not None:
439
+ query_states = query_states.contiguous()
440
+ key_states = key_states.contiguous()
441
+ value_states = value_states.contiguous()
442
+
443
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
444
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
445
+ is_causal = True if causal_mask is None and q_len > 1 else False
446
+
447
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
448
+ query_states,
449
+ key_states,
450
+ value_states,
451
+ attn_mask=causal_mask,
452
+ dropout_p=self.attention_dropout if self.training else 0.0,
453
+ is_causal=is_causal,
454
+ scale=self.scaling,
455
+ )
456
+
457
+ attn_output = attn_output.transpose(1, 2).contiguous()
458
+ attn_output = attn_output.view(bsz, q_len, -1)
459
+
460
+ attn_output = self.o_proj(attn_output)
461
+
462
+ return attn_output, None, past_key_value
463
+
464
+
465
+ MERALION_TEXT_ATTENTION_CLASSES = {
466
+ "eager": MERaLiONTextAttention,
467
+ "flash_attention_2": MERaLiONTextFlashAttention2,
468
+ "sdpa": MERaLiONTextSdpaAttention,
469
+ }
470
+
471
+
472
+ class MERaLiONTextDecoderLayer(nn.Module):
473
+ def __init__(self, config: MERaLiONTextConfig, layer_idx: int):
474
+ super().__init__()
475
+ self.hidden_size = config.hidden_size
476
+ self.self_attn = MERALION_TEXT_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
477
+ self.mlp = MERaLiONTextMLP(config)
478
+ self.input_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
479
+ self.config = config
480
+ self.is_sliding = not bool(layer_idx % 2)
481
+ self.pre_feedforward_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
482
+ self.post_feedforward_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
483
+ self.sliding_window = config.sliding_window
484
+ self.post_attention_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
485
+
486
+ def forward(
487
+ self,
488
+ hidden_states: torch.Tensor,
489
+ attention_mask: Optional[torch.Tensor] = None,
490
+ position_ids: Optional[torch.LongTensor] = None,
491
+ past_key_value: Optional[Cache] = None,
492
+ output_attentions: Optional[bool] = False,
493
+ use_cache: Optional[bool] = False,
494
+ cache_position: Optional[torch.LongTensor] = None,
495
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
496
+ """
497
+ Args:
498
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
499
+ attention_mask (`torch.FloatTensor`, *optional*):
500
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
501
+ query_sequence_length, key_sequence_length)` if default attention is used.
502
+ output_attentions (`bool`, *optional*):
503
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
504
+ returned tensors for more detail.
505
+ use_cache (`bool`, *optional*):
506
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
507
+ (see `past_key_values`).
508
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
509
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
510
+ Indices depicting the position of the input sequence tokens in the sequence
511
+ kwargs (`dict`, *optional*):
512
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
513
+ into the model
514
+ """
515
+ if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
516
+ # Flash-attn is a 2D tensor
517
+ if self.config._attn_implementation == "flash_attention_2":
518
+ if past_key_value is not None: # when decoding
519
+ attention_mask = attention_mask[:, -self.sliding_window :]
520
+ else:
521
+ min_dtype = torch.finfo(hidden_states.dtype).min
522
+ sliding_window_mask = torch.tril(
523
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
524
+ )
525
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
526
+ if attention_mask.shape[-1] <= 1: # when decoding
527
+ attention_mask = attention_mask[:, :, :, -self.sliding_window :]
528
+
529
+ residual = hidden_states
530
+
531
+ hidden_states = self.input_layernorm(hidden_states)
532
+
533
+ # Self Attention
534
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
535
+ hidden_states=hidden_states,
536
+ attention_mask=attention_mask,
537
+ position_ids=position_ids,
538
+ past_key_value=past_key_value,
539
+ output_attentions=output_attentions,
540
+ use_cache=use_cache,
541
+ cache_position=cache_position,
542
+ )
543
+ hidden_states = self.post_attention_layernorm(hidden_states)
544
+ hidden_states = residual + hidden_states
545
+
546
+ residual = hidden_states
547
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
548
+ hidden_states = self.mlp(hidden_states)
549
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
550
+ hidden_states = residual + hidden_states
551
+
552
+ outputs = (hidden_states,)
553
+
554
+ if output_attentions:
555
+ outputs += (self_attn_weights,)
556
+
557
+ if use_cache:
558
+ outputs += (present_key_value,)
559
+
560
+ return outputs
561
+
562
+
563
+ MERALION_TEXT_START_DOCSTRING = r"""
564
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
565
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
566
+ etc.)
567
+
568
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
569
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
570
+ and behavior.
571
+
572
+ Parameters:
573
+ config ([`MERaLiONTextConfig`]):
574
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
575
+ load the weights associated with the model, only the configuration. Check out the
576
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
577
+ """
578
+
579
+
580
+ @add_start_docstrings(
581
+ "The bare MERaLiONText Model outputting raw hidden-states without any specific head on top.",
582
+ MERALION_TEXT_START_DOCSTRING,
583
+ )
584
+ class MERaLiONTextPreTrainedModel(PreTrainedModel):
585
+ config_class = MERaLiONTextConfig
586
+ base_model_prefix = "model"
587
+ supports_gradient_checkpointing = True
588
+ _no_split_modules = ["MERaLiONTextDecoderLayer"]
589
+ _skip_keys_device_placement = ["past_key_values"]
590
+ _supports_flash_attn_2 = True
591
+ _supports_sdpa = True
592
+ _supports_cache_class = True
593
+ _supports_quantized_cache = False
594
+ _supports_static_cache = True
595
+
596
+ def _init_weights(self, module):
597
+ std = self.config.initializer_range
598
+ if isinstance(module, nn.Linear):
599
+ module.weight.data.normal_(mean=0.0, std=std)
600
+ if module.bias is not None:
601
+ module.bias.data.zero_()
602
+ elif isinstance(module, nn.Embedding):
603
+ module.weight.data.normal_(mean=0.0, std=std)
604
+ if module.padding_idx is not None:
605
+ module.weight.data[module.padding_idx].zero_()
606
+
607
+ @classmethod
608
+ def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False):
609
+ """
610
+ Overloads `PreTrainedModel._check_and_enable_sdpa` so as to DISABLE torch SDPA by default on MERaLiONText models.
611
+ SDPA reduces the model performance on MERaLiONText because of the logits softcapping.
612
+ """
613
+ config = super()._check_and_enable_sdpa(config, hard_check_only=hard_check_only)
614
+
615
+ # if using the default path -> swap sdpa by eager
616
+ if not hard_check_only and config._attn_implementation == "sdpa":
617
+ config._attn_implementation = "eager"
618
+
619
+ return config
620
+
621
+
622
+ _CONFIG_FOR_DOC = "MERaLiONTextConfig"
623
+
624
+
625
+ MERALION_TEXT_INPUTS_DOCSTRING = r"""
626
+ Args:
627
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
628
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
629
+ it.
630
+
631
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
632
+ [`PreTrainedTokenizer.__call__`] for details.
633
+
634
+ [What are input IDs?](../glossary#input-ids)
635
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
636
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
637
+
638
+ - 1 for tokens that are **not masked**,
639
+ - 0 for tokens that are **masked**.
640
+
641
+ [What are attention masks?](../glossary#attention-mask)
642
+
643
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
644
+ [`PreTrainedTokenizer.__call__`] for details.
645
+
646
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
647
+ `past_key_values`).
648
+
649
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
650
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
651
+ information on the default strategy.
652
+
653
+ - 1 indicates the head is **not masked**,
654
+ - 0 indicates the head is **masked**.
655
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
656
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
657
+ config.n_positions - 1]`.
658
+
659
+ [What are position IDs?](../glossary#position-ids)
660
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
661
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
662
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
663
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
664
+
665
+ Two formats are allowed:
666
+ - a [`~cache_utils.Cache`] instance, see our
667
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
668
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
669
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
670
+ cache format.
671
+
672
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
673
+ legacy cache format will be returned.
674
+
675
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
676
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
677
+ of shape `(batch_size, sequence_length)`.
678
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
679
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
680
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
681
+ model's internal embedding lookup matrix.
682
+ use_cache (`bool`, *optional*):
683
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
684
+ `past_key_values`).
685
+ output_attentions (`bool`, *optional*):
686
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
687
+ tensors for more detail.
688
+ output_hidden_states (`bool`, *optional*):
689
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
690
+ more detail.
691
+ return_dict (`bool`, *optional*):
692
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
693
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
694
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
695
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
696
+ the complete sequence length.
697
+ """
698
+
699
+
700
+ @add_start_docstrings(
701
+ "The bare MERaLiONText Model outputting raw hidden-states without any specific head on top.",
702
+ MERALION_TEXT_START_DOCSTRING,
703
+ )
704
+ class MERaLiONTextModel(MERaLiONTextPreTrainedModel):
705
+ """
706
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MERaLiONTextDecoderLayer`]
707
+
708
+ Args:
709
+ config: MERaLiONTextConfig
710
+ """
711
+
712
+ def __init__(self, config: MERaLiONTextConfig):
713
+ super().__init__(config)
714
+ self.padding_idx = config.pad_token_id
715
+ self.vocab_size = config.vocab_size
716
+
717
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
718
+ self.layers = nn.ModuleList(
719
+ [MERaLiONTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
720
+ )
721
+ self.norm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
722
+ self.gradient_checkpointing = False
723
+
724
+ # Initialize weights and apply final processing
725
+ self.post_init()
726
+
727
+ def get_input_embeddings(self):
728
+ return self.embed_tokens
729
+
730
+ def set_input_embeddings(self, value):
731
+ self.embed_tokens = value
732
+
733
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
734
+ def forward(
735
+ self,
736
+ input_ids: torch.LongTensor = None,
737
+ attention_mask: Optional[torch.Tensor] = None,
738
+ position_ids: Optional[torch.LongTensor] = None,
739
+ past_key_values: Optional[HybridCache] = None,
740
+ inputs_embeds: Optional[torch.FloatTensor] = None,
741
+ use_cache: Optional[bool] = None,
742
+ output_attentions: Optional[bool] = None,
743
+ output_hidden_states: Optional[bool] = None,
744
+ return_dict: Optional[bool] = None,
745
+ cache_position: Optional[torch.LongTensor] = None,
746
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
747
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
748
+ output_hidden_states = (
749
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
750
+ )
751
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
752
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
753
+
754
+ if (input_ids is None) ^ (inputs_embeds is not None):
755
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
756
+
757
+ if self.gradient_checkpointing and self.training and use_cache:
758
+ logger.warning_once(
759
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
760
+ )
761
+ use_cache = False
762
+
763
+ if inputs_embeds is None:
764
+ inputs_embeds = self.embed_tokens(input_ids)
765
+
766
+ if use_cache and past_key_values is None and not self.training:
767
+ batch_size, seq_len, _ = inputs_embeds.shape
768
+ past_key_values = HybridCache(
769
+ self.config,
770
+ batch_size=batch_size,
771
+ max_cache_len=seq_len,
772
+ device=self.device,
773
+ dtype=inputs_embeds.dtype,
774
+ )
775
+
776
+ if cache_position is None:
777
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
778
+ cache_position = torch.arange(
779
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
780
+ )
781
+
782
+ if position_ids is None:
783
+ position_ids = cache_position.unsqueeze(0)
784
+
785
+ causal_mask = self._update_causal_mask(
786
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
787
+ )
788
+
789
+ # embed positions
790
+ hidden_states = inputs_embeds
791
+
792
+ # normalized
793
+ # MERaLiONText downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
794
+ # See https://github.com/huggingface/transformers/pull/29402
795
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
796
+ hidden_states = hidden_states * normalizer
797
+
798
+ # decoder layers
799
+ all_hidden_states = () if output_hidden_states else None
800
+ all_self_attns = () if output_attentions else None
801
+
802
+ for decoder_layer in self.layers:
803
+ if output_hidden_states:
804
+ all_hidden_states += (hidden_states,)
805
+
806
+ if self.gradient_checkpointing and self.training:
807
+ layer_outputs = self._gradient_checkpointing_func(
808
+ decoder_layer.__call__,
809
+ hidden_states,
810
+ causal_mask,
811
+ position_ids,
812
+ past_key_values,
813
+ output_attentions,
814
+ use_cache,
815
+ cache_position,
816
+ )
817
+ else:
818
+ layer_outputs = decoder_layer(
819
+ hidden_states,
820
+ attention_mask=causal_mask,
821
+ position_ids=position_ids,
822
+ past_key_value=past_key_values,
823
+ output_attentions=output_attentions,
824
+ use_cache=use_cache,
825
+ cache_position=cache_position,
826
+ )
827
+
828
+ hidden_states = layer_outputs[0]
829
+
830
+ if output_attentions:
831
+ all_self_attns += (layer_outputs[1],)
832
+
833
+ hidden_states = self.norm(hidden_states)
834
+
835
+ if output_hidden_states:
836
+ all_hidden_states += (hidden_states,)
837
+
838
+ next_cache = past_key_values if use_cache else None
839
+
840
+ if not return_dict:
841
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
842
+ return BaseModelOutputWithPast(
843
+ last_hidden_state=hidden_states,
844
+ past_key_values=next_cache,
845
+ hidden_states=all_hidden_states,
846
+ attentions=all_self_attns,
847
+ )
848
+
849
+ def _update_causal_mask(
850
+ self,
851
+ attention_mask: torch.Tensor,
852
+ input_tensor: torch.Tensor,
853
+ cache_position: torch.Tensor,
854
+ past_key_values: HybridCache,
855
+ output_attentions: bool,
856
+ ):
857
+ # Flash Attention currently doesn't support static cache but MERaLiONText work only with static cache.
858
+ # So we will pass in attention mask as is in any case, not only when ther's padding. Then we'll use its shape
859
+ # to cut out keys/values trailing 0 used in static cache. This workaround should be compile compatible
860
+ # as it doesn't cause dynamic control issues.
861
+ if self.config._attn_implementation == "flash_attention_2":
862
+ return attention_mask
863
+
864
+ dtype, device = input_tensor.dtype, input_tensor.device
865
+ sequence_length = input_tensor.shape[1]
866
+ if isinstance(past_key_values, HybridCache):
867
+ target_length = past_key_values.get_max_cache_shape()
868
+ else:
869
+ target_length = attention_mask.shape[-1] if attention_mask is not None else input_tensor.shape[1]
870
+
871
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
872
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
873
+ attention_mask,
874
+ sequence_length=sequence_length,
875
+ target_length=target_length,
876
+ dtype=dtype,
877
+ device=device,
878
+ cache_position=cache_position,
879
+ batch_size=input_tensor.shape[0],
880
+ )
881
+ return causal_mask
882
+
883
+ @staticmethod
884
+ def _prepare_4d_causal_attention_mask_with_cache_position(
885
+ attention_mask: torch.Tensor,
886
+ sequence_length: int,
887
+ target_length: int,
888
+ dtype: torch.dtype,
889
+ device: torch.device,
890
+ cache_position: torch.Tensor,
891
+ batch_size: int,
892
+ **kwargs,
893
+ ):
894
+ """
895
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
896
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
897
+
898
+ Args:
899
+ attention_mask (`torch.Tensor`):
900
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
901
+ `(batch_size, 1, query_length, key_value_length)`.
902
+ sequence_length (`int`):
903
+ The sequence length being processed.
904
+ target_length (`int`):
905
+ The target length: when generating with static cache, the mask should be as long as the static cache,
906
+ to account for the 0 padding, the part of the cache that is not filled yet.
907
+ dtype (`torch.dtype`):
908
+ The dtype to use for the 4D attention mask.
909
+ device (`torch.device`):
910
+ The device to plcae the 4D attention mask on.
911
+ cache_position (`torch.Tensor`):
912
+ Indices depicting the position of the input sequence tokens in the sequence.
913
+ batch_size (`torch.Tensor`):
914
+ Batch size.
915
+ """
916
+ if attention_mask is not None and attention_mask.dim() == 4:
917
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
918
+ causal_mask = attention_mask
919
+ else:
920
+ min_dtype = torch.finfo(dtype).min
921
+ causal_mask = torch.full(
922
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
923
+ )
924
+ if sequence_length != 1:
925
+ causal_mask = torch.triu(causal_mask, diagonal=1)
926
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
927
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
928
+ if attention_mask is not None:
929
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
930
+ mask_length = attention_mask.shape[-1]
931
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
932
+ padding_mask = padding_mask == 0
933
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
934
+ padding_mask, min_dtype
935
+ )
936
+
937
+ return causal_mask
938
+
939
+
940
+ class MERaLiONTextForCausalLM(MERaLiONTextPreTrainedModel, GenerationMixin):
941
+ _tied_weights_keys = ["lm_head.weight"]
942
+
943
+ def __init__(self, config):
944
+ super().__init__(config)
945
+ self.model = MERaLiONTextModel(config)
946
+ self.vocab_size = config.vocab_size
947
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
948
+
949
+ # Initialize weights and apply final processing
950
+ self.post_init()
951
+
952
+ def get_input_embeddings(self):
953
+ return self.model.embed_tokens
954
+
955
+ def set_input_embeddings(self, value):
956
+ self.model.embed_tokens = value
957
+
958
+ def get_output_embeddings(self):
959
+ return self.lm_head
960
+
961
+ def set_output_embeddings(self, new_embeddings):
962
+ self.lm_head = new_embeddings
963
+
964
+ def set_decoder(self, decoder):
965
+ self.model = decoder
966
+
967
+ def get_decoder(self):
968
+ return self.model
969
+
970
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
971
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
972
+ def forward(
973
+ self,
974
+ input_ids: torch.LongTensor = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ position_ids: Optional[torch.LongTensor] = None,
977
+ past_key_values: Optional[HybridCache] = None,
978
+ inputs_embeds: Optional[torch.FloatTensor] = None,
979
+ labels: Optional[torch.LongTensor] = None,
980
+ use_cache: Optional[bool] = None,
981
+ output_attentions: Optional[bool] = None,
982
+ output_hidden_states: Optional[bool] = None,
983
+ return_dict: Optional[bool] = None,
984
+ cache_position: Optional[torch.LongTensor] = None,
985
+ num_logits_to_keep: int = 0,
986
+ **loss_kwargs,
987
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
988
+ r"""
989
+ Args:
990
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
991
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
992
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
993
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
994
+
995
+ num_logits_to_keep (`int`, *optional*):
996
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
997
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
998
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
999
+
1000
+ Returns:
1001
+ """
1002
+
1003
+ if self.training and self.config._attn_implementation != "eager":
1004
+ logger.warning_once(
1005
+ "It is strongly recommended to train MERaLiONText models with the `eager` attention implementation "
1006
+ f"instead of `{self.config._attn_implementation}`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`."
1007
+ )
1008
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1009
+ output_hidden_states = (
1010
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1011
+ )
1012
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1013
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1014
+ outputs = self.model(
1015
+ input_ids=input_ids,
1016
+ attention_mask=attention_mask,
1017
+ position_ids=position_ids,
1018
+ past_key_values=past_key_values,
1019
+ inputs_embeds=inputs_embeds,
1020
+ use_cache=use_cache,
1021
+ output_attentions=output_attentions,
1022
+ output_hidden_states=output_hidden_states,
1023
+ return_dict=return_dict,
1024
+ cache_position=cache_position,
1025
+ )
1026
+
1027
+ hidden_states = outputs[0]
1028
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1029
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1030
+ if self.config.final_logit_softcapping is not None:
1031
+ logits = logits / self.config.final_logit_softcapping
1032
+ logits = torch.tanh(logits)
1033
+ logits = logits * self.config.final_logit_softcapping
1034
+
1035
+ loss = None
1036
+ if labels is not None:
1037
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1038
+
1039
+ if not return_dict:
1040
+ output = (logits,) + outputs[1:]
1041
+ return (loss,) + output if loss is not None else output
1042
+
1043
+ return CausalLMOutputWithPast(
1044
+ loss=loss,
1045
+ logits=logits,
1046
+ past_key_values=outputs.past_key_values,
1047
+ hidden_states=outputs.hidden_states,
1048
+ attentions=outputs.attentions,
1049
+ )
1050
+
1051
+ def prepare_inputs_for_generation(
1052
+ self,
1053
+ input_ids,
1054
+ past_key_values=None,
1055
+ attention_mask=None,
1056
+ inputs_embeds=None,
1057
+ cache_position=None,
1058
+ position_ids=None,
1059
+ use_cache=True,
1060
+ num_logits_to_keep=None,
1061
+ **kwargs,
1062
+ ):
1063
+ # Overwritten: has a special cache type, `HybridCache`
1064
+
1065
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1066
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1067
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1068
+ if past_key_values is not None:
1069
+ if inputs_embeds is not None: # Exception 1
1070
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1071
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1072
+ input_ids = input_ids[:, cache_position]
1073
+ if attention_mask is not None and position_ids is None:
1074
+ # create position_ids on the fly for batch generation
1075
+ position_ids = attention_mask.long().cumsum(-1) - 1
1076
+ position_ids.masked_fill_(attention_mask == 0, 1)
1077
+ if past_key_values:
1078
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1079
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s
1080
+ # `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride
1081
+ # during the decoding. Here, simply using `.contiguous()` is not sufficient as in the
1082
+ # batch size = 1 case, `position_ids` is already contiguous but with varying stride
1083
+ # which retriggers a capture.
1084
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1085
+
1086
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1087
+ if inputs_embeds is not None and cache_position[0] == 0:
1088
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1089
+ else:
1090
+ # The clone here is for the same reason as for `position_ids`.
1091
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1092
+
1093
+ if (
1094
+ isinstance(past_key_values, HybridCache)
1095
+ and attention_mask.ndim == 2
1096
+ and not self.config._attn_implementation == "flash_attention_2"
1097
+ ):
1098
+ if model_inputs["inputs_embeds"] is not None:
1099
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1100
+ device = model_inputs["inputs_embeds"].device
1101
+ else:
1102
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1103
+ device = model_inputs["input_ids"].device
1104
+
1105
+ attention_mask = self.model._prepare_4d_causal_attention_mask_with_cache_position(
1106
+ attention_mask,
1107
+ sequence_length=sequence_length,
1108
+ target_length=past_key_values.get_max_cache_shape(),
1109
+ dtype=self.lm_head.weight.dtype,
1110
+ device=device,
1111
+ cache_position=cache_position,
1112
+ batch_size=batch_size,
1113
+ )
1114
+
1115
+ if num_logits_to_keep is not None:
1116
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
1117
+
1118
+ model_inputs.update(
1119
+ {
1120
+ "position_ids": position_ids,
1121
+ "cache_position": cache_position,
1122
+ "past_key_values": past_key_values,
1123
+ "use_cache": use_cache,
1124
+ "attention_mask": attention_mask,
1125
+ }
1126
+ )
1127
+ return model_inputs
1128
+
1129
+
1130
+ @add_start_docstrings(
1131
+ """
1132
+ The MERaLiONText Model transformer with a sequence classification head on top (linear layer).
1133
+
1134
+ [`MERaLiONTextForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1135
+ (e.g. GPT-2) do.
1136
+
1137
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1138
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1139
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1140
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1141
+ each row of the batch).
1142
+ """,
1143
+ MERALION_TEXT_START_DOCSTRING,
1144
+ )
1145
+ class MERaLiONTextForSequenceClassification(MERaLiONTextPreTrainedModel):
1146
+ def __init__(self, config):
1147
+ super().__init__(config)
1148
+ self.num_labels = config.num_labels
1149
+ self.model = MERaLiONTextModel(config)
1150
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1151
+
1152
+ # Initialize weights and apply final processing
1153
+ self.post_init()
1154
+
1155
+ def get_input_embeddings(self):
1156
+ return self.model.embed_tokens
1157
+
1158
+ def set_input_embeddings(self, value):
1159
+ self.model.embed_tokens = value
1160
+
1161
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
1162
+ def forward(
1163
+ self,
1164
+ input_ids: Optional[torch.LongTensor] = None,
1165
+ attention_mask: Optional[torch.Tensor] = None,
1166
+ position_ids: Optional[torch.LongTensor] = None,
1167
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1168
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1169
+ labels: Optional[torch.LongTensor] = None,
1170
+ use_cache: Optional[bool] = None,
1171
+ output_attentions: Optional[bool] = None,
1172
+ output_hidden_states: Optional[bool] = None,
1173
+ return_dict: Optional[bool] = None,
1174
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1175
+ r"""
1176
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1177
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1178
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1179
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1180
+ """
1181
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1182
+
1183
+ transformer_outputs = self.model(
1184
+ input_ids,
1185
+ attention_mask=attention_mask,
1186
+ position_ids=position_ids,
1187
+ past_key_values=past_key_values,
1188
+ inputs_embeds=inputs_embeds,
1189
+ use_cache=use_cache,
1190
+ output_attentions=output_attentions,
1191
+ output_hidden_states=output_hidden_states,
1192
+ return_dict=return_dict,
1193
+ )
1194
+ hidden_states = transformer_outputs[0]
1195
+ logits = self.score(hidden_states)
1196
+
1197
+ if input_ids is not None:
1198
+ batch_size = input_ids.shape[0]
1199
+ else:
1200
+ batch_size = inputs_embeds.shape[0]
1201
+
1202
+ if self.config.pad_token_id is None and batch_size != 1:
1203
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1204
+ if self.config.pad_token_id is None:
1205
+ sequence_lengths = -1
1206
+ else:
1207
+ if input_ids is not None:
1208
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1209
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1210
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1211
+ sequence_lengths = sequence_lengths.to(logits.device)
1212
+ else:
1213
+ sequence_lengths = -1
1214
+
1215
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1216
+
1217
+ loss = None
1218
+ if labels is not None:
1219
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1220
+
1221
+ if not return_dict:
1222
+ output = (pooled_logits,) + transformer_outputs[1:]
1223
+ return ((loss,) + output) if loss is not None else output
1224
+
1225
+ return SequenceClassifierOutputWithPast(
1226
+ loss=loss,
1227
+ logits=pooled_logits,
1228
+ past_key_values=transformer_outputs.past_key_values,
1229
+ hidden_states=transformer_outputs.hidden_states,
1230
+ attentions=transformer_outputs.attentions,
1231
+ )
1232
+
1233
+
1234
+ @add_start_docstrings(
1235
+ """
1236
+ The MERaLiONText Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1237
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1238
+ """,
1239
+ MERALION_TEXT_START_DOCSTRING,
1240
+ )
1241
+ class MERaLiONTextForTokenClassification(MERaLiONTextPreTrainedModel):
1242
+ def __init__(self, config):
1243
+ super().__init__(config)
1244
+ self.num_labels = config.num_labels
1245
+ self.model = MERaLiONTextModel(config)
1246
+ if getattr(config, "classifier_dropout", None) is not None:
1247
+ classifier_dropout = config.classifier_dropout
1248
+ elif getattr(config, "hidden_dropout", None) is not None:
1249
+ classifier_dropout = config.hidden_dropout
1250
+ else:
1251
+ classifier_dropout = 0.1
1252
+ self.dropout = nn.Dropout(classifier_dropout)
1253
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1254
+
1255
+ # Initialize weights and apply final processing
1256
+ self.post_init()
1257
+
1258
+ def get_input_embeddings(self):
1259
+ return self.model.embed_tokens
1260
+
1261
+ def set_input_embeddings(self, value):
1262
+ self.model.embed_tokens = value
1263
+
1264
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
1265
+ @add_code_sample_docstrings(
1266
+ checkpoint=_CHECKPOINT_FOR_DOC,
1267
+ output_type=TokenClassifierOutput,
1268
+ config_class=_CONFIG_FOR_DOC,
1269
+ )
1270
+ def forward(
1271
+ self,
1272
+ input_ids: Optional[torch.LongTensor] = None,
1273
+ attention_mask: Optional[torch.Tensor] = None,
1274
+ position_ids: Optional[torch.LongTensor] = None,
1275
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1276
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1277
+ labels: Optional[torch.LongTensor] = None,
1278
+ use_cache: Optional[bool] = None,
1279
+ output_attentions: Optional[bool] = None,
1280
+ output_hidden_states: Optional[bool] = None,
1281
+ return_dict: Optional[bool] = None,
1282
+ ) -> Union[Tuple, TokenClassifierOutput]:
1283
+ r"""
1284
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1285
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1286
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1287
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1288
+ """
1289
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1290
+
1291
+ outputs = self.model(
1292
+ input_ids,
1293
+ attention_mask=attention_mask,
1294
+ position_ids=position_ids,
1295
+ past_key_values=past_key_values,
1296
+ inputs_embeds=inputs_embeds,
1297
+ use_cache=use_cache,
1298
+ output_attentions=output_attentions,
1299
+ output_hidden_states=output_hidden_states,
1300
+ return_dict=return_dict,
1301
+ )
1302
+ sequence_output = outputs[0]
1303
+ sequence_output = self.dropout(sequence_output)
1304
+ logits = self.score(sequence_output)
1305
+
1306
+ loss = None
1307
+ if labels is not None:
1308
+ loss = self.loss_function(logits, labels, self.config)
1309
+
1310
+ if not return_dict:
1311
+ output = (logits,) + outputs[2:]
1312
+ return ((loss,) + output) if loss is not None else output
1313
+
1314
+ return TokenClassifierOutput(
1315
+ loss=loss,
1316
+ logits=logits,
1317
+ hidden_states=outputs.hidden_states,
1318
+ attentions=outputs.attentions,
1319
+ )