HemanthSai7 commited on
Commit
3188a15
·
verified ·
1 Parent(s): d1e491b

Delete modeling_rope_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_rope_utils.py +0 -944
modeling_rope_utils.py DELETED
@@ -1,944 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import math
16
- import warnings
17
- from functools import wraps
18
- from typing import TYPE_CHECKING, Optional, TypedDict
19
-
20
- from .utils import is_torch_available, logging
21
-
22
-
23
- logger = logging.get_logger(__name__)
24
-
25
-
26
- if is_torch_available():
27
- import torch
28
-
29
- if TYPE_CHECKING:
30
- from .configuration_utils import PreTrainedConfig
31
-
32
-
33
- def dynamic_rope_update(rope_forward):
34
- """
35
- Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE
36
- (i.e. a RoPE implementation that may recompute its frequencies in the forward pass).
37
-
38
- Args:
39
- rope_forward (Callable):
40
- The forward pass of the RoPE implementation.
41
-
42
- Returns:
43
- The decorated forward pass.
44
- """
45
-
46
- def longrope_frequency_update(self, position_ids, device, layer_type=None):
47
- """Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
48
- seq_len = torch.max(position_ids) + 1
49
-
50
- if layer_type is None:
51
- rope_type = self.rope_type
52
- original_inv_freq = self.original_inv_freq
53
- prefix = ""
54
- original_max_position_embeddings = self.config.rope_parameters["original_max_position_embeddings"]
55
- else:
56
- rope_type = self.rope_type[layer_type]
57
- original_inv_freq = getattr(self, f"{layer_type}_original_inv_freq")
58
- prefix = f"{layer_type}_"
59
- original_max_position_embeddings = self.config.rope_parameters[layer_type][
60
- "original_max_position_embeddings"
61
- ]
62
-
63
- if seq_len > original_max_position_embeddings:
64
- if not hasattr(self, f"{layer_type}_long_inv_freq"):
65
- rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
66
- long_inv_freq, _ = rope_init_fn(
67
- self.config,
68
- device,
69
- seq_len=original_max_position_embeddings + 1,
70
- layer_type=layer_type,
71
- )
72
- self.register_buffer(f"{prefix}inv_freq", long_inv_freq, persistent=False)
73
- setattr(self, f"{prefix}long_inv_freq", long_inv_freq)
74
- else:
75
- # This .to() is needed if the model has been moved to a device after being initialized (because
76
- # the buffer is automatically moved, but not the original copy)
77
- original_inv_freq = original_inv_freq.to(device)
78
- self.register_buffer(f"{prefix}inv_freq", original_inv_freq, persistent=False)
79
- setattr(self, f"{prefix}original_inv_freq", original_inv_freq)
80
-
81
- def dynamic_frequency_update(self, position_ids, device, layer_type=None):
82
- """
83
- dynamic RoPE layers should recompute `inv_freq` in the following situations:
84
- 1 - growing beyond the cached sequence length (allow scaling)
85
- 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
86
- """
87
- seq_len = torch.max(position_ids) + 1
88
- if layer_type is None:
89
- rope_type = self.rope_type
90
- max_seq_len_cached = self.max_seq_len_cached
91
- original_inv_freq = self.original_inv_freq
92
- prefix = ""
93
- else:
94
- rope_type = self.rope_type[layer_type]
95
- max_seq_len_cached = getattr(self, f"{layer_type}_max_seq_len_cached", self.max_seq_len_cached)
96
- original_inv_freq = getattr(self, f"{layer_type}_original_inv_freq")
97
- prefix = f"{layer_type}_"
98
-
99
- if seq_len > max_seq_len_cached: # growth
100
- rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
101
- inv_freq, self.attention_scaling = rope_init_fn(
102
- self.config,
103
- device,
104
- seq_len=seq_len,
105
- layer_type=layer_type,
106
- )
107
- # TODO joao: may break with compilation
108
- self.register_buffer(f"{prefix}inv_freq", inv_freq, persistent=False)
109
- setattr(self, f"{layer_type}_max_seq_len_cached", seq_len)
110
-
111
- if seq_len < self.original_max_seq_len and max_seq_len_cached > self.original_max_seq_len: # reset
112
- # This .to() is needed if the model has been moved to a device after being initialized (because
113
- # the buffer is automatically moved, but not the original copy)
114
- original_inv_freq = original_inv_freq.to(device)
115
- self.register_buffer(f"{prefix}inv_freq", original_inv_freq, persistent=False)
116
- setattr(self, f"{prefix}original_inv_freq", original_inv_freq)
117
- setattr(self, f"{layer_type}_max_seq_len_cached", self.original_max_seq_len)
118
-
119
- @wraps(rope_forward)
120
- def wrapper(self, x, position_ids, layer_type=None):
121
- rope_type = self.rope_type if layer_type is None else self.rope_type[layer_type]
122
- kwargs = {"layer_type": layer_type} if layer_type is not None else {}
123
- if "dynamic" in rope_type:
124
- dynamic_frequency_update(self, position_ids, device=x.device, **kwargs)
125
- elif rope_type == "longrope":
126
- longrope_frequency_update(self, position_ids, device=x.device, **kwargs)
127
- return rope_forward(self, x, position_ids, **kwargs)
128
-
129
- return wrapper
130
-
131
-
132
- def _compute_linear_scaling_rope_parameters(
133
- config: Optional["PreTrainedConfig"] = None,
134
- device: Optional["torch.device"] = None,
135
- seq_len: int | None = None,
136
- layer_type: str | None = None,
137
- ) -> tuple["torch.Tensor", float]:
138
- """
139
- Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev
140
- Args:
141
- config ([`~transformers."PreTrainedConfig"`]):
142
- The model configuration. This function assumes that the config will provide at least the following
143
- properties:
144
-
145
- * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
146
- * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
147
- * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
148
-
149
- Additionally, this function will make use of the following properties if they are found in the config:
150
-
151
- * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
152
- derived as hidden_size // num_attention_heads.
153
- * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
154
- the first fraction of the head_dim. Defaults to 1.0.
155
- device (`torch.device`):
156
- The device to use for initialization of the inverse frequencies.
157
- seq_len (`int`, *optional*):
158
- The current sequence length. Unused for this type of RoPE.
159
-
160
- Returns:
161
- Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
162
- post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
163
- """
164
- # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
165
- config.standardize_rope_params()
166
- rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
167
- factor = rope_parameters_dict["factor"]
168
-
169
- # Gets the default RoPE parameters
170
- base = rope_parameters_dict["rope_theta"]
171
- partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0)
172
- head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
173
- dim = int(head_dim * partial_rotary_factor)
174
- attention_factor = 1.0 # Unused in this type of RoPE
175
-
176
- # Compute the inverse frequencies
177
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
178
-
179
- # Then applies linear scaling to the frequencies.
180
- # NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so
181
- # applying scaling to the inverse frequencies is equivalent.
182
- inv_freq /= factor
183
- return inv_freq, attention_factor
184
-
185
-
186
- def _compute_dynamic_ntk_parameters(
187
- config: Optional["PreTrainedConfig"] = None,
188
- device: Optional["torch.device"] = None,
189
- seq_len: int | None = None,
190
- layer_type: str | None = None,
191
- ) -> tuple["torch.Tensor", float]:
192
- """
193
- Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla
194
-
195
- Args:
196
- config ([`~transformers."PreTrainedConfig"`]):
197
- The model configuration. This function assumes that the config will provide at least the following
198
- properties:
199
-
200
- * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
201
- * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
202
- * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
203
- * max_position_embeddings (`int`): The default sequence length used to update the dynamic RoPE at
204
- inference time
205
- * rope_parameters (`dict[str, float]`): The standard RoPE scaling parameters, from which `factor`
206
- will be accessed. The value of `factor` is used to determine the new base frequency, along with the
207
- current sequence length (seq_len), the maximum positional embeddings (max_position_embeddings), and the
208
- computed dimensionality (dim) of the rotary embeddings. If seq_len <= max_position_embeddings, this
209
- factor has no effect. If seq_len <= max_position_embeddings, this factor effectively stretches the
210
- context window using an exponent derived from `dim`.
211
-
212
- Additionally, this function will make use of the following properties if they are found in the config:
213
-
214
- * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
215
- derived as hidden_size // num_attention_heads.
216
- * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
217
- the first fraction of the head_dim. Defaults to 1.0.
218
- device (`torch.device`):
219
- The device to use for initialization of the inverse frequencies.
220
- seq_len (`int`, *optional*):
221
- The current sequence length, used to update the dynamic RoPE at inference time. If `None` or shorter than
222
- max_position_embeddings, this value will be overridden by max_position_embeddings.
223
-
224
- Returns:
225
- Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
226
- post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
227
- """
228
- # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
229
- config.standardize_rope_params()
230
- rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
231
-
232
- base = rope_parameters_dict["rope_theta"]
233
- partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0)
234
- head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
235
- dim = int(head_dim * partial_rotary_factor)
236
- factor = rope_parameters_dict["factor"]
237
- attention_factor = 1.0 # Unused in this type of RoPE
238
-
239
- # seq_len: default to max_position_embeddings, e.g. at init time
240
- if seq_len is None:
241
- seq_len = config.max_position_embeddings
242
- elif isinstance(seq_len, torch.Tensor):
243
- seq_len = torch.maximum(
244
- seq_len,
245
- torch.tensor(config.max_position_embeddings, dtype=seq_len.dtype, device=seq_len.device),
246
- )
247
- else:
248
- seq_len = max(seq_len, config.max_position_embeddings)
249
-
250
- # Compute the inverse frequencies
251
- base = base * ((factor * seq_len / config.max_position_embeddings) - (factor - 1)) ** (dim / (dim - 2))
252
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
253
- return inv_freq, attention_factor
254
-
255
-
256
- def _compute_yarn_parameters(
257
- config: "PreTrainedConfig",
258
- device: Optional["torch.device"] = None,
259
- seq_len: int | None = None,
260
- layer_type: str | None = None,
261
- ) -> tuple["torch.Tensor", float]:
262
- """
263
- Computes the inverse frequencies with NTK scaling. Please refer to the
264
- [original paper](https://huggingface.co/papers/2309.00071)
265
-
266
- Args:
267
- config ([`~transformers."PreTrainedConfig"`]):
268
- The model configuration. This function assumes that the config will provide at least the following
269
- properties:
270
-
271
- * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
272
- * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
273
- * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
274
- * max_position_embeddings (`int`): The maximum length of the positional embeddings.
275
- * rope_parameters (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following
276
- keys will be accessed:
277
- * `attention_factor` (`float`, *optional*): The scaling factor to be applied to the computed cos/sin.
278
- If None, the value is inferred from `factor`, `mscale`, and `mscale_all_dim` as available.
279
- * `beta_fast` (`float`, *optional*, defaults to 32): Parameter to set the boundary for extrapolation
280
- (only) in the linear ramp function.
281
- * `beta_slow` (`float`, *optional*, defaults to 1): Parameter to set the boundary for interpolation
282
- (only) in the linear ramp function.
283
- * `factor` (`float`, *optional*): The scaling factor applied when interpolating the position IDs to
284
- extend the possible context length. Additionally, if `attention_factor` is None, the log of this
285
- value is used to compute a value for `attention_factor`, possibly in conjunciton with `mscale` and
286
- `mscale_all_dim`, if provided.
287
- * `mscale` (`float`, *optional*): If `attention_factor` is None and both `mscale` and
288
- `mscale_all_dim` are provided, `mscale` acts scalar augmenting `log(factor)` when computing the
289
- numerator for the inferred value of `attention_factor`. If not provided, `attention_factor` will be
290
- calculated based on `factor` only.
291
- * `mscale_all_dim` (`float`, *optional*): If `attention_factor` is None and both `mscale` and
292
- `mscale_all_dim` are provided, `mscale_all_dim` acts scalar augmenting `log(factor)` when computing
293
- the denominator for the inferred value of `attention_factor`. If not provided, `attention_factor`
294
- will be calculated based on `factor` only.
295
- * `original_max_position_embeddings` (`int`): The original max position embeddings used during pretraining.
296
- * `truncate` (`bool`, *optional*): Whether to truncate the correction range.
297
-
298
- Additionally, this function will make use of the following properties if they are found in the config:
299
-
300
- * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
301
- derived as hidden_size // num_attention_heads.
302
- * partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies
303
- will be returned for the first fraction of the head_dim.
304
- device (`torch.device`):
305
- The device to use for initialization of the inverse frequencies.
306
- seq_len (`int`, *optional*):
307
- The current sequence length. Unused for this type of RoPE.
308
-
309
- Returns:
310
- Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
311
- post-processing scaling factor applied to the computed cos/sin.
312
- """
313
- # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
314
- config.standardize_rope_params()
315
- rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
316
-
317
- base = rope_parameters_dict["rope_theta"]
318
- partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0)
319
- head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
320
- dim = int(head_dim * partial_rotary_factor)
321
-
322
- factor = rope_parameters_dict["factor"]
323
- attention_factor = rope_parameters_dict.get("attention_factor")
324
- mscale = rope_parameters_dict.get("mscale")
325
- mscale_all_dim = rope_parameters_dict.get("mscale_all_dim")
326
- original_max_position_embeddings = rope_parameters_dict["original_max_position_embeddings"]
327
-
328
- # NOTE: DeekSeek-V3 (and potentially other models) have `original_max_position_embeddings` field
329
- # containing the pretrained value. They use the ratio between `max_position_embeddings` and this value
330
- # to compute the default attention scaling factor, instead of using `factor`.
331
- if factor is None:
332
- factor = config.max_position_embeddings / original_max_position_embeddings
333
-
334
- def get_mscale(scale, mscale=1):
335
- if scale <= 1:
336
- return 1.0
337
- return 0.1 * mscale * math.log(scale) + 1.0
338
-
339
- # Sets the attention factor as suggested in the paper
340
- if attention_factor is None:
341
- if mscale and mscale_all_dim:
342
- attention_factor = float(get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dim))
343
- else:
344
- attention_factor = get_mscale(factor)
345
-
346
- # Optional config options
347
- # beta_fast/beta_slow: as suggested in the paper, default to 32/1 (correspondingly)
348
- beta_fast = rope_parameters_dict.get("beta_fast") or 32
349
- beta_slow = rope_parameters_dict.get("beta_slow") or 1
350
-
351
- # Compute the inverse frequencies
352
- def find_correction_dim(num_rotations, dim, base, max_position_embeddings):
353
- """Inverse dimension formula to find the dimension based on the number of rotations"""
354
- return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
355
-
356
- def find_correction_range(low_rot, high_rot, dim, base, max_position_embeddings, truncate):
357
- """Find dimension range bounds based on rotations"""
358
- low = find_correction_dim(low_rot, dim, base, max_position_embeddings)
359
- high = find_correction_dim(high_rot, dim, base, max_position_embeddings)
360
- if truncate:
361
- low = math.floor(low)
362
- high = math.ceil(high)
363
- return max(low, 0), min(high, dim - 1)
364
-
365
- def linear_ramp_factor(min, max, dim):
366
- if min == max:
367
- max += 0.001 # Prevent singularity
368
-
369
- linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
370
- ramp_func = torch.clamp(linear_func, 0, 1)
371
- return ramp_func
372
-
373
- # Note on variable naming: "interpolation" comes from the original technique, where we interpolate the position IDs
374
- # to expand the possible context length. In other words, interpolation = apply scaling factor.
375
- pos_freqs = base ** (torch.arange(0, dim, 2).to(device=device, dtype=torch.float) / dim)
376
- inv_freq_extrapolation = 1.0 / pos_freqs
377
- inv_freq_interpolation = 1.0 / (factor * pos_freqs)
378
-
379
- truncate = config.rope_parameters.get("truncate", True)
380
- low, high = find_correction_range(beta_fast, beta_slow, dim, base, original_max_position_embeddings, truncate)
381
-
382
- # Get n-dimensional rotational scaling corrected for extrapolation
383
- inv_freq_extrapolation_factor = 1 - linear_ramp_factor(low, high, dim // 2).to(device=device, dtype=torch.float)
384
- inv_freq = (
385
- inv_freq_interpolation * (1 - inv_freq_extrapolation_factor)
386
- + inv_freq_extrapolation * inv_freq_extrapolation_factor
387
- )
388
- return inv_freq, attention_factor
389
-
390
-
391
- def _compute_longrope_parameters(
392
- config: "PreTrainedConfig",
393
- device: Optional["torch.device"] = None,
394
- seq_len: int | None = None,
395
- layer_type: str | None = None,
396
- ) -> tuple["torch.Tensor", float]:
397
- """
398
- Computes the inverse frequencies with LongRoPE scaling. Please refer to the
399
- [original implementation](https://github.com/microsoft/LongRoPE)
400
-
401
- Args:
402
- config ([`~transformers."PreTrainedConfig"`]):
403
- The model configuration. This function assumes that the config will provide at least the following
404
- properties:
405
-
406
- * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
407
- * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
408
- * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
409
- * max_position_embeddings (`int`): The maximum length of the positional embeddings.
410
- * original_max_position_embeddings (`int`, *optional*): The original max position embeddings used during
411
- pretraining. If not provided, defaults to `max_position_embeddings`.
412
- * rope_parameters (`dict[str, float]`): The standard RoPE scaling parameters, from which the following keys
413
- will be accessed:
414
- * `attention_factor` (`float`, *optional*): The scaling factor to be applied on the attention
415
- computation. If unspecified, it defaults to value recommended by the implementation, inferred from
416
- the value of `factor`.
417
- * `factor` (`float`, *optional*): The scaling factor to apply to the RoPE embeddings. If both
418
- `max_position_embeddings` and `original_max_position_embeddings` are provided, this value will be
419
- overridden s the ratio between those values.
420
- * `long_factor` (`float`, *optional*): The scale factor applied when computing the inverse
421
- frequencies if `seq_len` is provided and greater than `original_max_position_embeddings`.
422
- * `short_factor` (`float`, *optional*): The scale factor applied when computing the inverse
423
- frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`.
424
-
425
- Additionally, this function will make use of the following properties if they are found in the config:
426
-
427
- * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
428
- derived as hidden_size // num_attention_heads.
429
- * partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies
430
- will be returned for the first fraction of the head_dim.
431
- device (`torch.device`):
432
- The device to use for initialization of the inverse frequencies.
433
- seq_len (`int`, *optional*):
434
- The current sequence length.
435
-
436
- Returns:
437
- Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
438
- post-processing scaling factor applied to the computed cos/sin.
439
- """
440
- # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
441
- config.standardize_rope_params()
442
- rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
443
-
444
- base = rope_parameters_dict["rope_theta"]
445
- partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0)
446
- head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
447
- dim = int(head_dim * partial_rotary_factor)
448
-
449
- long_factor = rope_parameters_dict["long_factor"]
450
- short_factor = rope_parameters_dict["short_factor"]
451
- factor = rope_parameters_dict.get("factor")
452
- attention_factor = rope_parameters_dict.get("attention_factor")
453
- original_max_position_embeddings = rope_parameters_dict["original_max_position_embeddings"]
454
-
455
- # NOTE: Phi3 (and potentially other models) modify `max_position_embeddings` and have a
456
- # `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two
457
- # values to compute the default attention scaling factor, instead of using `factor`.
458
- if factor is None:
459
- factor = config.max_position_embeddings / original_max_position_embeddings
460
-
461
- # Sets the attention factor as suggested in the paper
462
- if attention_factor is None:
463
- if factor <= 1.0:
464
- attention_factor = 1.0
465
- else:
466
- attention_factor = math.sqrt(1 + math.log(factor) / math.log(original_max_position_embeddings))
467
-
468
- # Compute the inverse frequencies -- scaled based on the target sequence length
469
- if seq_len and seq_len > original_max_position_embeddings:
470
- ext_factors = torch.tensor(long_factor, dtype=torch.float32, device=device)
471
- else:
472
- ext_factors = torch.tensor(short_factor, dtype=torch.float32, device=device)
473
- inv_freq_shape = torch.arange(0, dim, 2, dtype=torch.int64, device=device).float() / dim
474
- inv_freq = 1.0 / (ext_factors * base**inv_freq_shape)
475
-
476
- return inv_freq, attention_factor
477
-
478
-
479
- def _compute_llama3_parameters(
480
- config: "PreTrainedConfig",
481
- device: Optional["torch.device"] = None,
482
- seq_len: int | None = None,
483
- layer_type: str | None = None,
484
- ) -> tuple["torch.Tensor", float]:
485
- """
486
- Computes the inverse frequencies for llama 3.1.
487
-
488
- Args:
489
- config ([`~transformers."PreTrainedConfig"`]):
490
- The model configuration. This function assumes that the config will provide at least the following
491
- properties:
492
-
493
- * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
494
- * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
495
- * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
496
- * rope_parameters (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following
497
- keys will be accessed:
498
- * `factor` (`float`, *optional*): The scaling factor applied to the inverse frequencies when 1) the
499
- wavelength is greater than `low_freq_wavelen` prior to smoothing, and 2) to all inverse frequencies
500
- during smoothing.
501
- * `high_freq_factor` (`float`): The scale factor used to compute `high_freq_wavelen` and
502
- the value for the denominator of the smoothing factor prior to the `low_freq_factor` shift.
503
- * `low_freq_factor` (`float`): The scale factor used to compute `low_freq_wavelen` and
504
- the shift applied to the numerator and denominator of the smoothing factor.
505
- frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`.
506
- * `original_max_position_embeddings` (`int`): The original max position embeddings used
507
- during pretraining. If not provided, the function falls back to `max_position_embeddings`.
508
-
509
- Additionally, this function will make use of the following properties if they are found in the config:
510
-
511
- * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
512
- derived as hidden_size // num_attention_heads.
513
- * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
514
- the first fraction of the head_dim. Defaults to 1.0.
515
- device (`torch.device`):
516
- The device to use for initialization of the inverse frequencies.
517
- seq_len (`int`, *optional*):
518
- The current sequence length. Unused for this type of RoPE.
519
- Returns:
520
- Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
521
- post-processing scaling factor applied to the computed cos/sin.
522
- """
523
- # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
524
- config.standardize_rope_params()
525
- rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters
526
-
527
- # Gets the default RoPE parameters
528
- base = rope_parameters_dict["rope_theta"]
529
- partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0)
530
- head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
531
- dim = int(head_dim * partial_rotary_factor)
532
- attention_factor = 1.0 # Unused in this type of RoPE
533
-
534
- # Compute the inverse frequencies
535
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
536
-
537
- factor = rope_parameters_dict["factor"] # `8` in the original implementation
538
- low_freq_factor = rope_parameters_dict["low_freq_factor"] # `1` in the original implementation
539
- high_freq_factor = rope_parameters_dict["high_freq_factor"] # `4` in the original implementation
540
- old_context_len = rope_parameters_dict["original_max_position_embeddings"] # `8192` in the original implementation
541
-
542
- low_freq_wavelen = old_context_len / low_freq_factor
543
- high_freq_wavelen = old_context_len / high_freq_factor
544
-
545
- wavelen = 2 * math.pi / inv_freq
546
- # wavelen < high_freq_wavelen: do nothing
547
- # wavelen > low_freq_wavelen: divide by factor
548
- inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)
549
- # otherwise: interpolate between the two, using a smooth factor
550
- smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
551
- smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama
552
- is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)
553
- inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)
554
-
555
- return inv_freq_llama, attention_factor
556
-
557
-
558
- # This maps the "rope_type" string field in rope config to the corresponding function to compute the RoPE parameters
559
- # from the model config. You can append new {'rope_type': callable} pairs to this rope_parameters to enable custom RoPE
560
- # parameterizations, as long as the callable has the same signature.
561
- ROPE_INIT_FUNCTIONS = {
562
- "linear": _compute_linear_scaling_rope_parameters,
563
- "dynamic": _compute_dynamic_ntk_parameters,
564
- "yarn": _compute_yarn_parameters,
565
- "longrope": _compute_longrope_parameters,
566
- "llama3": _compute_llama3_parameters,
567
- }
568
-
569
-
570
- class RopeParameters(TypedDict, total=False):
571
- """
572
- Args:
573
- rope_theta (`float`):
574
- The base period of the RoPE embeddings.
575
- rope_type (`str`, *optional*, defaults to "default"):
576
- The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
577
- 'llama3'], with 'default' being the original RoPE implementation.
578
- partial_rotary_factor (`float`, *optional*):
579
- The percentage of the query and key head embedding on which RoPE will be applied.
580
- factor (`float`, *optional*):
581
- Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
582
- most scaling types, a `factor` of x will enable the model to handle sequences of length x *
583
- original maximum pre-trained length.
584
- original_max_position_embeddings (`int`, *optional*):
585
- Used with 'yarn', 'longrope' and 'llama3'. The original max position embeddings used during
586
- pretraining.
587
- attention_factor (`float`, *optional*):
588
- Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
589
- computation. If unspecified, it defaults to value recommended by the implementation, using the
590
- `factor` field to infer the suggested value.
591
- beta_fast (`float`, *optional*):
592
- Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
593
- ramp function. If unspecified, it defaults to 32.
594
- beta_slow (`float`, *optional*):
595
- Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
596
- ramp function. If unspecified, it defaults to 1.
597
- short_factor (`list[float]`, *optional*):
598
- Only used with 'longrope'. The scaling factor to be applied to short contexts (<
599
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
600
- size divided by the number of attention heads divided by 2
601
- long_factor (`list[float]`, *optional*):
602
- Only used with 'longrope'. The scaling factor to be applied to long contexts (<
603
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
604
- size divided by the number of attention heads divided by 2
605
- low_freq_factor (`float`, *optional*):
606
- Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
607
- high_freq_factor (`float`, *optional*):
608
- Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
609
- """
610
-
611
- rope_theta: float
612
- rope_type: str | None
613
- partial_rotary_factor: float | None
614
- factor: float | None
615
- original_max_position_embeddings: int | None
616
- attention_factor: float | None
617
- beta_fast: float | None
618
- beta_slow: float | None
619
- short_factor: list[float] | None
620
- long_factor: list[float] | None
621
- low_freq_factor: float | None
622
- high_freq_factor: float | None
623
-
624
-
625
- class RotaryEmbeddingConfigMixin:
626
- """
627
- A Mixin containing the functionality to standardize and validate RoPE parameters.
628
- """
629
-
630
- default_theta = 10_000.0
631
- ignore_keys_at_rope_validation = set()
632
-
633
- def convert_rope_params_to_dict(self, **kwargs):
634
- rope_scaling = kwargs.pop("rope_scaling", None)
635
- self.rope_parameters = rope_scaling or self.rope_parameters
636
- self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {}
637
-
638
- # Standardize and validate the correctness of rotary position embeddings parameters. Priority for these parameters is:
639
- # 1. Values in `rope_parameters` dict (where they should be after standardization)
640
- # 2. Values in `kwargs` (i.e. it's in config.json but not MyConfig.__init__'s args)
641
- # 3. Values in the config's attributes (i.e. it's in MyConfig.__init__'s args)
642
- # 4. Default values (i.e. not present at all but other RoPE parameters are present)
643
- rope_theta = kwargs.pop("rope_theta", getattr(self, "rope_theta", self.default_theta))
644
- self.rope_parameters.setdefault("rope_theta", rope_theta)
645
-
646
- partial_rotary_factor = kwargs.get("partial_rotary_factor", getattr(self, "partial_rotary_factor", None))
647
- if partial_rotary_factor is not None:
648
- self.rope_parameters.setdefault("partial_rotary_factor", partial_rotary_factor)
649
- self.ignore_keys_at_rope_validation = self.ignore_keys_at_rope_validation | {"partial_rotary_factor"}
650
-
651
- self.standardize_rope_params()
652
- return kwargs
653
-
654
- def standardize_rope_params(self):
655
- """
656
- Helper to standardize the config's rope params field by ensuring the params are defined for each
657
- later type. For old model the fn will duplicate a single rope param in each layer type (backward compatibility)
658
- """
659
- # Move `rope_theta` and `partial_rotary_factor` to the `rope_parameters`, if not there yet
660
- rope_theta = getattr(self, "rope_theta", None)
661
- partial_rotary_factor = getattr(self, "partial_rotary_factor", None)
662
- rope_parameters = getattr(self, "rope_parameters", None) or {}
663
- layer_types = getattr(self, "layer_types", None)
664
-
665
- # Case 0: no RoPE params defined
666
- if not (rope_parameters or rope_theta):
667
- # partial_rotary_factor without rope_theta is invalid, so we don't check for it here
668
- logger.warning("`standardize_rope_params` was called but no RoPE parameters were found.")
669
- return
670
- # Case 1: RoPE param keys do not intersect with possible `layer_types` -> one global dict
671
- elif layer_types is None or rope_parameters == {} or not set(rope_parameters.keys()).issubset(layer_types):
672
- rope_parameters.setdefault("rope_type", rope_parameters.get("type", "default"))
673
- rope_parameters.setdefault("rope_theta", rope_theta)
674
- if partial_rotary_factor is not None:
675
- rope_parameters["partial_rotary_factor"] = partial_rotary_factor
676
-
677
- # Move pretraining-time maximum length to rope parameter dict for RoPE types with scaling
678
- if rope_parameters["rope_type"] in ["llama3", "yarn", "longrope"]:
679
- if hasattr(self, "original_max_position_embeddings"):
680
- # NOTE: Phi3 (and potentially other models) save `original_max_position_embeddings` field
681
- # containing the pretrained value outside rope parameters. This is an exception case where we
682
- # give priority to `self.original_max_position_embeddings
683
- self.rope_parameters["original_max_position_embeddings"] = self.original_max_position_embeddings
684
- else:
685
- self.rope_parameters.setdefault("original_max_position_embeddings", self.max_position_embeddings)
686
-
687
- # Case 2: different RoPE for each layer -> several params as nested dict
688
- else:
689
- for layer_type in set(layer_types):
690
- rope_parameters[layer_type].setdefault("rope_type", rope_parameters[layer_type].get("type", "default"))
691
- rope_parameters[layer_type].setdefault("rope_theta", rope_theta)
692
- if partial_rotary_factor is not None:
693
- rope_parameters[layer_type]["partial_rotary_factor"] = partial_rotary_factor
694
-
695
- if rope_parameters[layer_type]["rope_type"] in ["llama3", "yarn", "longrope"]:
696
- self.rope_parameters[layer_type].setdefault(
697
- "original_max_position_embeddings", self.max_position_embeddings
698
- )
699
-
700
- self.rope_parameters = rope_parameters
701
-
702
- def validate_rope(self: "PreTrainedConfig"):
703
- """
704
- Validate the RoPE config arguments, given a `"PreTrainedConfig"` object
705
- """
706
- # Don't validate if no rope_parameters found (`None`) or if it's an empty dict
707
- # Note that validation runs every time a new config is created, even if config is non-RoPE
708
- rope_parameters_dict = getattr(self, "rope_parameters", None)
709
- if not rope_parameters_dict:
710
- return
711
-
712
- if getattr(self, "layer_types", None) is not None and set(rope_parameters_dict.keys()).issubset(
713
- self.layer_types
714
- ):
715
- pass
716
- else:
717
- rope_parameters_dict = {"full_attention": rope_parameters_dict}
718
-
719
- for rope_parameters in rope_parameters_dict.values():
720
- rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
721
- validation_fn = getattr(self, f"_validate_{rope_type}_rope_parameters", None)
722
- rope_parameters["rope_type"] = rope_type
723
-
724
- if validation_fn is not None:
725
- validation_fn(rope_parameters, ignore_keys=self.ignore_keys_at_rope_validation)
726
- else:
727
- logger.warning(
728
- f"Missing validation function in 'RotaryEmbeddingConfigMixin' for 'rope_type'='{rope_type}'"
729
- )
730
-
731
- def _validate_default_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
732
- required_keys = {"rope_type", "rope_theta"}
733
- received_keys = set(rope_parameters.keys())
734
- rope_type = rope_parameters["rope_type"]
735
- self._check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
736
-
737
- def _validate_linear_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
738
- required_keys = {"rope_type", "factor", "rope_theta"}
739
- received_keys = set(rope_parameters.keys())
740
- rope_type = rope_parameters["rope_type"]
741
- self._check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
742
-
743
- factor = rope_parameters["factor"]
744
- if factor is None or not isinstance(factor, float) or factor < 1.0:
745
- logger.warning(f"`rope_parameters`'s factor field must be a float >= 1, got {factor}")
746
-
747
- def _validate_dynamic_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
748
- required_keys = {"rope_type", "factor"}
749
- received_keys = set(rope_parameters.keys())
750
- rope_type = rope_parameters["rope_type"]
751
- self._check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
752
-
753
- factor = rope_parameters["factor"]
754
- if factor is None or not isinstance(factor, float) or factor < 1.0:
755
- logger.warning(f"`rope_parameters`'s factor field must be a float >= 1, got {factor}")
756
-
757
- def _validate_yarn_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
758
- required_keys = {"rope_type", "factor", "rope_theta", "original_max_position_embeddings"}
759
- optional_keys = {
760
- "attention_factor",
761
- "beta_fast",
762
- "beta_slow",
763
- "mscale",
764
- "mscale_all_dim",
765
- "truncate",
766
- }
767
- received_keys = set(rope_parameters.keys())
768
- rope_type = rope_parameters["rope_type"]
769
- self._check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
770
-
771
- factor = rope_parameters["factor"]
772
- if factor is None or not isinstance(factor, float) or factor < 1.0:
773
- logger.warning(f"`rope_parameters`'s factor field must be a float >= 1, got {factor}")
774
-
775
- attention_factor = rope_parameters.get("attention_factor")
776
- if attention_factor is not None and (not isinstance(attention_factor, float) or attention_factor < 0):
777
- logger.warning(
778
- f"`rope_parameters`'s attention_factor field must be a float greater than 0, got {attention_factor}"
779
- )
780
- beta_fast = rope_parameters.get("beta_fast")
781
- if beta_fast is not None and not isinstance(beta_fast, float):
782
- logger.warning(f"`rope_parameters`'s beta_fast field must be a float, got {beta_fast}")
783
- beta_slow = rope_parameters.get("beta_slow")
784
- if beta_slow is not None and not isinstance(beta_slow, float):
785
- logger.warning(f"`rope_parameters`'s beta_slow field must be a float, got {beta_slow}")
786
-
787
- if (beta_fast or 32) < (beta_slow or 1):
788
- logger.warning(
789
- f"`rope_parameters`'s beta_fast field must be greater than beta_slow, got beta_fast={beta_fast} "
790
- f"(defaults to 32 if None) and beta_slow={beta_slow} (defaults to 1 if None)"
791
- )
792
-
793
- # Double-check: `factor` should be the ratio between the pre-yarn and post-yarn context lengths.
794
- # NOTE: we might get `implicit_factor == 1` if config's `original_max_position_embeddings` was
795
- # inferred from `max_position_embeddings` during standardization
796
- original_max_position_embeddings = self.rope_parameters["original_max_position_embeddings"]
797
- implicit_factor = self.max_position_embeddings / original_max_position_embeddings
798
- if implicit_factor != factor and implicit_factor != 1:
799
- logger.warning_once(
800
- f"The explicitly set RoPE scaling factor (config.rope_parameters['factor'] = {factor}) does not match "
801
- "the ratio implicitly set by other parameters (implicit factor = "
802
- "post-yarn context length / pre-yarn context length = "
803
- "config.max_position_embeddings / config.rope_parameters['original_max_position_embeddings'] = "
804
- f"{implicit_factor}). Using the explicit factor ({factor}) in YaRN. This may cause unexpected "
805
- "behaviour in model usage, please correct the 'original_max_position_embeddings' fields in the model config."
806
- )
807
-
808
- def _validate_longrope_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
809
- required_keys = {"rope_type", "short_factor", "long_factor", "rope_theta", "original_max_position_embeddings"}
810
- optional_keys = {"attention_factor", "factor"}
811
- received_keys = set(rope_parameters.keys())
812
- rope_type = rope_parameters["rope_type"]
813
- self._check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
814
-
815
- partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
816
- head_dim = getattr(self, "head_dim", self.hidden_size // self.num_attention_heads)
817
- dim = int(head_dim * partial_rotary_factor)
818
-
819
- short_factor = rope_parameters.get("short_factor")
820
- if not isinstance(short_factor, list) and all(isinstance(x, (int, float)) for x in short_factor):
821
- logger.warning(f"`rope_parameters`'s short_factor field must be a list of numbers, got {short_factor}")
822
- if len(short_factor) != dim // 2:
823
- logger.warning(
824
- f"`rope_parameters`'s short_factor field must have length {dim // 2}, got {len(short_factor)}"
825
- )
826
-
827
- long_factor = rope_parameters.get("long_factor")
828
- if not isinstance(long_factor, list) and all(isinstance(x, (int, float)) for x in long_factor):
829
- logger.warning(f"`rope_parameters`'s long_factor field must be a list of numbers, got {long_factor}")
830
- if len(long_factor) != dim // 2:
831
- logger.warning(
832
- f"`rope_parameters`'s long_factor field must have length {dim // 2}, got {len(long_factor)}"
833
- )
834
-
835
- factor = rope_parameters.get("factor")
836
- original_max_position_embeddings = rope_parameters["original_max_position_embeddings"]
837
-
838
- # Handle Phi3 divergence: we prefer the use of `attention_factor` and/or `factor` over
839
- # `original_max_position_embeddings` to compute internal variables. The latter is undesirable
840
- if factor is None and original_max_position_embeddings is not None:
841
- logger.warning_once(
842
- "This model config has set a `rope_parameters['original_max_position_embeddings']` field, to be used together with "
843
- "`max_position_embeddings` to determine a scaling factor. Please set the `factor` field of `rope_parameters`"
844
- "with this ratio instead -- we recommend the use of this field over `original_max_position_embeddings`, "
845
- "as it is compatible with most model architectures."
846
- )
847
- elif factor is None and original_max_position_embeddings is None:
848
- logger.warning("Missing required keys in `rope_parameters`: 'factor'")
849
- elif not isinstance(factor, float) or factor < 1.0:
850
- logger.warning(f"`rope_parameters`'s factor field must be a float >= 1, got {factor}")
851
-
852
- attention_factor = rope_parameters.get("attention_factor")
853
- if attention_factor is not None and (not isinstance(attention_factor, float) or attention_factor < 0.0):
854
- logger.warning(
855
- f"`rope_parameters`'s attention_factor field must be a float greater than 0, got {attention_factor}"
856
- )
857
-
858
- def _validate_llama3_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None):
859
- required_keys = {
860
- "rope_type",
861
- "factor",
862
- "original_max_position_embeddings",
863
- "low_freq_factor",
864
- "high_freq_factor",
865
- "rope_theta",
866
- }
867
- rope_type = rope_parameters["rope_type"]
868
- received_keys = set(rope_parameters.keys())
869
- self._check_received_keys(rope_type, received_keys, required_keys, ignore_keys=ignore_keys)
870
-
871
- factor = rope_parameters["factor"]
872
- if factor is None or not isinstance(factor, float) or factor < 1.0:
873
- logger.warning(f"`rope_parameters`'s factor field must be a float >= 1, got {factor}")
874
-
875
- low_freq_factor = rope_parameters["low_freq_factor"]
876
- high_freq_factor = rope_parameters["high_freq_factor"]
877
- if low_freq_factor is None or not isinstance(low_freq_factor, float):
878
- logger.warning(f"`rope_parameters`'s low_freq_factor field must be a float, got {low_freq_factor}")
879
- if high_freq_factor is None or not isinstance(high_freq_factor, float):
880
- logger.warning(f"`rope_parameters`'s high_freq_factor field must be a float, got {high_freq_factor}")
881
- if high_freq_factor <= low_freq_factor:
882
- logger.warning(
883
- "`rope_parameters`'s high_freq_factor field must be greater than low_freq_factor, got high_freq_factor="
884
- f"{high_freq_factor} and low_freq_factor={low_freq_factor}"
885
- )
886
-
887
- original_max_position_embeddings = rope_parameters["original_max_position_embeddings"]
888
- if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
889
- logger.warning(
890
- "`rope_parameters`'s original_max_position_embeddings field must be an integer, got "
891
- f"{original_max_position_embeddings}"
892
- )
893
- if original_max_position_embeddings >= self.max_position_embeddings:
894
- logger.warning(
895
- "`rope_parameters`'s original_max_position_embeddings field must be less than max_position_embeddings, got "
896
- f"{original_max_position_embeddings} and max_position_embeddings={self.max_position_embeddings}"
897
- )
898
-
899
- @staticmethod
900
- def _check_received_keys(
901
- rope_type: str,
902
- received_keys: set,
903
- required_keys: set,
904
- optional_keys: set | None = None,
905
- ignore_keys: set | None = None,
906
- ):
907
- """Compare the received keys in `config.rope_parameters` against the expected and optional keys"""
908
- # BC: "rope_type" was originally "type" -- let's check for "rope_type" when "type" is present
909
- if "type" in received_keys:
910
- received_keys -= {"type"}
911
- required_keys.add("rope_type")
912
-
913
- optional_keys = optional_keys or set()
914
- if "partial_rotary_factor" not in optional_keys:
915
- optional_keys.add("partial_rotary_factor")
916
-
917
- # Some models need to store model-specific keys, and we don't want to throw warning at them
918
- if ignore_keys is not None:
919
- received_keys -= ignore_keys
920
-
921
- missing_keys = required_keys - received_keys
922
- if missing_keys:
923
- raise KeyError(f"Missing required keys in `rope_parameters` for 'rope_type'='{rope_type}': {missing_keys}")
924
-
925
- unused_keys = received_keys - required_keys - optional_keys
926
- if unused_keys:
927
- logger.warning(f"Unrecognized keys in `rope_parameters` for 'rope_type'='{rope_type}': {unused_keys}")
928
-
929
-
930
- def rope_config_validation(config: RotaryEmbeddingConfigMixin, ignore_keys: set | None = None):
931
- """
932
- This is a deprecated function.
933
- It has been kept for backward compatibility with custom code models.
934
- """
935
- warnings.warn(
936
- "`rope_config_validation` is deprecated and has been removed. "
937
- "Its functionality has been moved to RotaryEmbeddingConfigMixin.validate_rope method. "
938
- "PreTrainedConfig inherits this class, so please call self.validate_rope() instead. "
939
- "Also, make sure to use the new rope_parameters syntax. "
940
- "You can call self.standardize_rope_params() in the meantime.",
941
- FutureWarning,
942
- )
943
- config.standardize_rope_params()
944
- config.validate_rope()