codekingpro commited on
Commit
5035838
·
verified ·
1 Parent(s): 3cfa48a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/__init__.py +30 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/feature_extraction_clvp.py +237 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/modeling_clvp.py +1724 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/number_normalizer.py +243 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/processing_clvp.py +42 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/tokenization_clvp.py +273 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/code_llama/__init__.py +26 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/code_llama/tokenization_code_llama.py +358 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/__init__.py +29 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/configuration_codegen.py +77 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/modeling_codegen.py +486 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/tokenization_codegen.py +215 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/__init__.py +28 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/configuration_cohere.py +94 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/modeling_cohere.py +530 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/modular_cohere.py +326 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/tokenization_cohere.py +384 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/__init__.py +27 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/configuration_cohere2.py +107 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/modeling_cohere2.py +509 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/modular_cohere2.py +325 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/__init__.py +29 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/configuration_cohere2_vision.py +65 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/image_processing_cohere2_vision.py +293 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/modeling_cohere2_vision.py +388 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/modular_cohere2_vision.py +328 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/processing_cohere2_vision.py +169 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/__init__.py +30 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/configuration_cohere_asr.py +101 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/feature_extraction_cohere_asr.py +374 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/modeling_cohere_asr.py +659 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/modular_cohere_asr.py +526 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/processing_cohere_asr.py +188 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/__init__.py +28 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/configuration_colmodernvbert.py +81 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/modeling_colmodernvbert.py +158 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/modular_colmodernvbert.py +422 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/processing_colmodernvbert.py +566 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/__init__.py +28 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/configuration_colpali.py +64 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/modeling_colpali.py +169 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/modular_colpali.py +296 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/processing_colpali.py +367 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/__init__.py +28 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/configuration_colqwen2.py +65 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/modeling_colqwen2.py +205 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/modular_colqwen2.py +348 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/processing_colqwen2.py +355 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/conditional_detr/__init__.py +29 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py +119 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_clvp import *
22
+ from .feature_extraction_clvp import *
23
+ from .modeling_clvp import *
24
+ from .processing_clvp import *
25
+ from .tokenization_clvp import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/feature_extraction_clvp.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """
16
+ Feature extractor class for CLVP
17
+ """
18
+
19
+ import numpy as np
20
+
21
+ from ...audio_utils import mel_filter_bank, spectrogram, window_function
22
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...utils import TensorType, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class ClvpFeatureExtractor(SequenceFeatureExtractor):
31
+ r"""
32
+ Constructs a CLVP feature extractor.
33
+
34
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
35
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
36
+
37
+ This class extracts log-mel-spectrogram features from raw speech using a custom numpy implementation of the `Short
38
+ Time Fourier Transform` which should match pytorch's `torch.stft` equivalent.
39
+
40
+ Args:
41
+ feature_size (`int`, *optional*, defaults to 80):
42
+ The feature dimension of the extracted features.
43
+ sampling_rate (`int`, *optional*, defaults to 22050):
44
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
45
+ default_audio_length (`int`, *optional*, defaults to 6):
46
+ The default length of raw audio in seconds. If `max_length` is not set during `__call__` then it will
47
+ automatically be set to default_audio_length * `self.sampling_rate`.
48
+ hop_length (`int`, *optional*, defaults to 256):
49
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
50
+ chunk_length (`int`, *optional*, defaults to 30):
51
+ The maximum number of chunks of `sampling_rate` samples used to trim and pad longer or shorter audio
52
+ sequences.
53
+ n_fft (`int`, *optional*, defaults to 1024):
54
+ Size of the Fourier transform.
55
+ padding_value (`float`, *optional*, defaults to 0.0):
56
+ Padding value used to pad the audio. Should correspond to silences.
57
+ mel_norms (`list` of length `feature_size`, *optional*):
58
+ If `mel_norms` is provided then it will be used to normalize the log-mel spectrograms along each
59
+ mel-filter.
60
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
61
+ Whether to return the attention mask. If left to the default, it will return the attention mask.
62
+
63
+ [What are attention masks?](../glossary#attention-mask)
64
+ """
65
+
66
+ model_input_names = ["input_features", "attention_mask"]
67
+
68
+ def __init__(
69
+ self,
70
+ feature_size=80,
71
+ sampling_rate=22050,
72
+ default_audio_length=6,
73
+ hop_length=256,
74
+ chunk_length=30,
75
+ n_fft=1024,
76
+ padding_value=0.0,
77
+ mel_norms=None,
78
+ return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
79
+ **kwargs,
80
+ ):
81
+ super().__init__(
82
+ feature_size=feature_size,
83
+ sampling_rate=sampling_rate,
84
+ padding_value=padding_value,
85
+ return_attention_mask=return_attention_mask,
86
+ **kwargs,
87
+ )
88
+ self.n_fft = n_fft
89
+ self.hop_length = hop_length
90
+ self.chunk_length = chunk_length
91
+ self.n_samples = chunk_length * sampling_rate
92
+ self.nb_max_frames = self.n_samples // hop_length
93
+ self.sampling_rate = sampling_rate
94
+ self.default_audio_length = default_audio_length
95
+ self.mel_norms = mel_norms
96
+ self.mel_filters = mel_filter_bank(
97
+ num_frequency_bins=1 + (n_fft // 2),
98
+ num_mel_filters=feature_size,
99
+ min_frequency=0.0,
100
+ max_frequency=8000.0,
101
+ sampling_rate=sampling_rate,
102
+ norm="slaney",
103
+ mel_scale="htk",
104
+ )
105
+
106
+ def _np_extract_fbank_features(self, waveform: np.ndarray) -> np.ndarray:
107
+ """
108
+ This method first computes the log-mel spectrogram of the provided audio then applies normalization along the
109
+ each mel-filterbank, if `mel_norms` is provided.
110
+ """
111
+ log_spec = spectrogram(
112
+ waveform,
113
+ window_function(self.n_fft, "hann"),
114
+ frame_length=self.n_fft,
115
+ hop_length=self.hop_length,
116
+ power=2.0,
117
+ mel_filters=self.mel_filters,
118
+ log_mel=None,
119
+ )
120
+
121
+ log_spec = np.log(np.clip(log_spec, a_min=1e-5, a_max=None))
122
+
123
+ if self.mel_norms is not None:
124
+ log_spec = log_spec / np.array(self.mel_norms)[:, None]
125
+
126
+ return log_spec
127
+
128
+ def __call__(
129
+ self,
130
+ raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
131
+ sampling_rate: int | None = None,
132
+ truncation: bool = True,
133
+ pad_to_multiple_of: int | None = None,
134
+ return_tensors: str | TensorType | None = None,
135
+ return_attention_mask: bool | None = True,
136
+ padding: str | None = "max_length",
137
+ max_length: int | None = None,
138
+ **kwargs,
139
+ ) -> BatchFeature:
140
+ """
141
+ `ClvpFeatureExtractor` is used to extract various voice specific properties such as the pitch and tone of the
142
+ voice, speaking speed, and even speaking defects like a lisp or stuttering from a sample voice or `raw_speech`.
143
+
144
+ First the voice is padded or truncated in a way such that it becomes a waveform of `self.default_audio_length`
145
+ seconds long and then the log-mel spectrogram is extracted from it.
146
+
147
+ Args:
148
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
149
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
150
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
151
+ stereo, i.e. single float per timestep.
152
+ sampling_rate (`int`, *optional*):
153
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
154
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
155
+ pipeline.
156
+ truncation (`bool`, *optional*, default to `True`):
157
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
158
+ pad_to_multiple_of (`int`, *optional*):
159
+ If set will pad the sequence to a multiple of the provided value.
160
+
161
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
162
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
163
+ return_attention_mask (`bool`, *optional*, defaults to `True`):
164
+ Whether to return the attention mask. If left to the default, it will return the attention mask.
165
+
166
+ [What are attention masks?](../glossary#attention-mask)
167
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
168
+ If set, will return tensors instead of list of python integers. Acceptable values are:
169
+
170
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
171
+ - `'np'`: Return Numpy `np.ndarray` objects.
172
+ padding_value (`float`, *optional*, defaults to 0.0):
173
+ The value that is used to fill the padding values / vectors.
174
+ max_length (`int`, *optional*):
175
+ The maximum input length of the inputs.
176
+ """
177
+
178
+ if sampling_rate is not None:
179
+ if sampling_rate != self.sampling_rate:
180
+ raise ValueError(
181
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
182
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
183
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
184
+ )
185
+ else:
186
+ logger.warning(
187
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
188
+ "Failing to do so can result in silent errors that might be hard to debug."
189
+ )
190
+
191
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
192
+ if is_batched_numpy and len(raw_speech.shape) > 2:
193
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
194
+ is_batched = is_batched_numpy or (
195
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
196
+ )
197
+
198
+ if is_batched:
199
+ raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
200
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
201
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
202
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
203
+ raw_speech = raw_speech.astype(np.float32)
204
+
205
+ # always return batch
206
+ if not is_batched:
207
+ raw_speech = [np.asarray([raw_speech]).T]
208
+
209
+ batched_speech = BatchFeature({"input_features": raw_speech})
210
+
211
+ max_length = self.default_audio_length * self.sampling_rate if max_length is None else max_length
212
+
213
+ padded_inputs = self.pad(
214
+ batched_speech,
215
+ padding=padding,
216
+ max_length=max_length,
217
+ truncation=truncation,
218
+ pad_to_multiple_of=pad_to_multiple_of,
219
+ return_attention_mask=return_attention_mask,
220
+ )
221
+
222
+ # make sure list is in array format
223
+ input_features = padded_inputs.get("input_features").transpose(2, 0, 1)
224
+
225
+ input_features = [
226
+ self._np_extract_fbank_features(waveform).astype(np.float32) for waveform in input_features[0]
227
+ ]
228
+
229
+ if isinstance(input_features[0], list):
230
+ padded_inputs["input_features"] = [np.asarray(feature) for feature in input_features]
231
+ else:
232
+ padded_inputs["input_features"] = input_features
233
+
234
+ return padded_inputs.convert_to_tensors(return_tensors)
235
+
236
+
237
+ __all__ = ["ClvpFeatureExtractor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/modeling_clvp.py ADDED
@@ -0,0 +1,1724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ """PyTorch CLVP model."""
16
+
17
+ import copy
18
+ import math
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass
21
+
22
+ import torch
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ... import initialization as init
27
+ from ...activations import ACT2FN, get_activation
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationConfig, GenerationMixin
30
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
31
+ from ...modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ BaseModelOutputWithPooling,
34
+ CausalLMOutputWithCrossAttentions,
35
+ )
36
+ from ...modeling_utils import PreTrainedModel
37
+ from ...processing_utils import Unpack
38
+ from ...pytorch_utils import Conv1D
39
+ from ...utils import (
40
+ ModelOutput,
41
+ TransformersKwargs,
42
+ auto_docstring,
43
+ can_return_tuple,
44
+ logging,
45
+ )
46
+ from ...utils.generic import merge_with_config_defaults
47
+ from ...utils.output_capturing import capture_outputs
48
+ from .configuration_clvp import (
49
+ ClvpConfig,
50
+ ClvpDecoderConfig,
51
+ ClvpEncoderConfig,
52
+ )
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ # Copied from transformers.models.clip.modeling_clip.contrastive_loss
59
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
60
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
61
+
62
+
63
+ # Copied from transformers.models.clip.modeling_clip.image_text_contrastive_loss with image->speech
64
+ def speech_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor:
65
+ caption_loss = contrastive_loss(similarity)
66
+ speech_loss = contrastive_loss(similarity.T)
67
+ return (caption_loss + speech_loss) / 2.0
68
+
69
+
70
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
71
+ def rotate_half(x):
72
+ """Rotates half the hidden dims of the input."""
73
+ x1 = x[..., : x.shape[-1] // 2]
74
+ x2 = x[..., x.shape[-1] // 2 :]
75
+ return torch.cat((-x2, x1), dim=-1)
76
+
77
+
78
+ def apply_rotary_pos_emb(q, k, v, cos, sin, position_ids, unsqueeze_dim=1):
79
+ """Applies Rotary Position Embedding to the query and key tensors.
80
+
81
+ Args:
82
+ q (`torch.Tensor`): The query tensor.
83
+ k (`torch.Tensor`): The key tensor.
84
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
85
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
86
+ position_ids (`torch.Tensor`):
87
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
88
+ used to pass offsetted position ids when working with a KV-cache.
89
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
90
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
91
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
92
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
93
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
94
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
95
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
96
+ Returns:
97
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
98
+ """
99
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
100
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
101
+ q_embed = (q * cos) + (rotate_half(q) * sin)
102
+ k_embed = (k * cos) + (rotate_half(k) * sin)
103
+ v_embed = (v * cos) + (rotate_half(v) * sin)
104
+ return q_embed, k_embed, v_embed
105
+
106
+
107
+ def _pad_extra_bos_eos_tokens(
108
+ input_ids,
109
+ attention_mask=None,
110
+ pad_token_id=0,
111
+ bos_token_id=255,
112
+ eos_token_id=0,
113
+ add_bos_token=True,
114
+ add_eos_token=True,
115
+ ):
116
+ """
117
+ This method adds extra bos and eos tokens to input_ids and accordingly modifies the attention_mask which is used in
118
+ `ClvpConditioningEncoder` and the generation loop of the `ClvpModelForConditionalGeneration`.
119
+ """
120
+
121
+ # add the bos token at the beginning
122
+ if add_bos_token:
123
+ input_ids = torch.nn.functional.pad(input_ids, (1, 0), value=bos_token_id)
124
+ attention_mask = (
125
+ torch.nn.functional.pad(attention_mask, (1, 0), value=1) if attention_mask is not None else attention_mask
126
+ )
127
+
128
+ modified_input_ids = input_ids
129
+ if add_eos_token:
130
+ modified_input_ids = torch.zeros(
131
+ (input_ids.shape[0], input_ids.shape[1] + 1), dtype=input_ids.dtype, device=input_ids.device
132
+ )
133
+ for i, each_input_id in enumerate(input_ids):
134
+ # locate where the valid tokens end and then add the eos token
135
+ if torch.isin(each_input_id, pad_token_id).sum():
136
+ pos = torch.where(each_input_id == pad_token_id)[0].min()
137
+ modified_input_ids[i] = torch.concatenate(
138
+ [each_input_id[:pos], torch.tensor([eos_token_id], device=input_ids.device), each_input_id[pos:]]
139
+ )
140
+ else:
141
+ # if there are no pad tokens present, then add eos to the end
142
+ modified_input_ids[i] = torch.nn.functional.pad(each_input_id, (0, 1), value=eos_token_id)
143
+ attention_mask = (
144
+ torch.nn.functional.pad(attention_mask, (1, 0), value=1) if attention_mask is not None else attention_mask
145
+ )
146
+
147
+ return modified_input_ids, attention_mask
148
+
149
+
150
+ @auto_docstring(
151
+ custom_intro="""
152
+ Base class for CLVP encoder's outputs that contains a pooling of the last hidden states as well as a projection
153
+ output (a linear layer on top of the pooled output).
154
+ """
155
+ )
156
+ @dataclass
157
+ class ClvpEncoderOutput(ModelOutput):
158
+ r"""
159
+ embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when model is initialized with `with_projection=True`):
160
+ The embeddings obtained by applying the projection layer to the pooler_output.
161
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
162
+ The hidden state of the last layer of the model.
163
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
164
+ Pooled output of the `last_hidden_state`.
165
+ """
166
+
167
+ embeds: torch.FloatTensor | None = None
168
+ last_hidden_state: torch.FloatTensor | None = None
169
+ pooler_output: torch.FloatTensor | None = None
170
+ hidden_states: tuple[torch.FloatTensor] | None = None
171
+ attentions: tuple[torch.FloatTensor] | None = None
172
+
173
+
174
+ @dataclass
175
+ @auto_docstring
176
+ class ClvpOutput(ModelOutput):
177
+ r"""
178
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
179
+ Contrastive loss for speech-text similarity.
180
+ speech_ids (`torch.LongTensor`, *optional*):
181
+ speech_ids (or speech candidates) generated by the `ClvpForCausalLM` model.
182
+ logits_per_speech (`torch.FloatTensor` of shape `(speech_batch_size, text_batch_size)`):
183
+ The scaled dot product scores between `speech_embeds` and `text_embeds`. This represents the speech-text
184
+ similarity scores.
185
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, speech_batch_size)`):
186
+ The scaled dot product scores between `text_embeds` and `speech_embeds`. This represents the text-speech
187
+ similarity scores.
188
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
189
+ The text embeddings obtained by applying the projection layer to the pooled output of the text encoder
190
+ model.
191
+ speech_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
192
+ The speech embeddings obtained by applying the projection layer to the pooled output of the speech encoder
193
+ model.
194
+ text_model_output (`BaseModelOutputWithPooling`):
195
+ The pooled output of the `last_hidden_state` of the text encoder Model.
196
+ speech_model_output (`BaseModelOutputWithPooling`):
197
+ The pooled output of the `last_hidden_state` of the speech encoder Model.
198
+ decoder_hidden_states (`torch.FloatTensor`, *optional*):
199
+ The hidden states of the decoder model.
200
+ text_encoder_hidden_states (`torch.FloatTensor`, *optional*):
201
+ The hidden states of the text encoder model.
202
+ speech_encoder_hidden_states (`torch.FloatTensor`, *optional*):
203
+ The hidden states of the speech encoder model.
204
+ """
205
+
206
+ loss: torch.FloatTensor | None = None
207
+ speech_ids: torch.LongTensor | None = None
208
+ logits_per_speech: torch.FloatTensor | None = None
209
+ logits_per_text: torch.FloatTensor | None = None
210
+ text_embeds: torch.FloatTensor | None = None
211
+ speech_embeds: torch.FloatTensor | None = None
212
+ text_model_output: BaseModelOutputWithPooling = None
213
+ speech_model_output: BaseModelOutputWithPooling = None
214
+ decoder_hidden_states: torch.FloatTensor | None = None
215
+ text_encoder_hidden_states: torch.FloatTensor | None = None
216
+ speech_encoder_hidden_states: torch.FloatTensor | None = None
217
+
218
+
219
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Clvp
220
+ class ClvpRMSNorm(nn.Module):
221
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
222
+ """
223
+ ClvpRMSNorm is equivalent to T5LayerNorm
224
+ """
225
+ super().__init__()
226
+ self.weight = nn.Parameter(torch.ones(hidden_size))
227
+ self.variance_epsilon = eps
228
+
229
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
230
+ input_dtype = hidden_states.dtype
231
+ hidden_states = hidden_states.to(torch.float32)
232
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
233
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
234
+ return self.weight * hidden_states.to(input_dtype)
235
+
236
+ def extra_repr(self):
237
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
238
+
239
+
240
+ class ClvpRotaryPositionalEmbedding(nn.Module):
241
+ """
242
+ Rotary Position Embedding Class for CLVP. It was proposed in the paper 'ROFORMER: ENHANCED TRANSFORMER WITH ROTARY
243
+ POSITION EMBEDDING', Please see https://huggingface.co/papers/2104.09864.
244
+ """
245
+
246
+ def __init__(self, config):
247
+ super().__init__()
248
+ dim = max(config.projection_dim // (config.num_attention_heads * 2), 32)
249
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
250
+
251
+ self.register_buffer("inv_freq", inv_freq)
252
+ self.cached_sequence_length = None
253
+ self.cached_rotary_positional_embedding = None
254
+
255
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
256
+ sequence_length = hidden_states.shape[1]
257
+
258
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
259
+ return self.cached_rotary_positional_embedding
260
+
261
+ self.cached_sequence_length = sequence_length
262
+ time_stamps = torch.arange(sequence_length, device=hidden_states.device).type_as(self.inv_freq)
263
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
264
+ embeddings = torch.cat((freqs, freqs), dim=-1)
265
+
266
+ self.cached_rotary_positional_embedding = embeddings.unsqueeze(0)
267
+ return self.cached_rotary_positional_embedding
268
+
269
+
270
+ class ClvpSelfAttention(nn.Module):
271
+ """
272
+ Multi-headed attention to combine Absolute and Rotary Positional Embeddings into a single Attention module.
273
+ """
274
+
275
+ def __init__(self, config, layer_idx=None):
276
+ super().__init__()
277
+ self.config = config
278
+ self.embed_dim = config.hidden_size
279
+ self.num_heads = config.num_attention_heads
280
+ self.head_dim = self.embed_dim // self.num_heads
281
+ if self.head_dim * self.num_heads != self.embed_dim:
282
+ raise ValueError(
283
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
284
+ f" {self.num_heads})."
285
+ )
286
+ self.scale = self.head_dim**-0.5
287
+ self.dropout = config.attention_dropout
288
+ self.layer_idx = layer_idx
289
+
290
+ if hasattr(config, "max_position_embeddings"):
291
+ max_positions = config.max_position_embeddings
292
+ bias = torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool))
293
+ bias = bias.view(1, 1, max_positions, max_positions)
294
+ self.register_buffer("bias", bias, persistent=False)
295
+
296
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
297
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
298
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
299
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
300
+
301
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
302
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
303
+
304
+ def forward(
305
+ self,
306
+ hidden_states: torch.FloatTensor,
307
+ rotary_pos_emb: torch.FloatTensor | None = None,
308
+ attention_mask: torch.LongTensor | None = None,
309
+ position_ids: torch.LongTensor | None = None,
310
+ past_key_values: Cache | None = None,
311
+ use_cache: bool | None = False,
312
+ **kwargs: Unpack[TransformersKwargs],
313
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]:
314
+ # Raise error when position_ids is None but rotary_pos_emb is provided, because we need that when applying
315
+ # rotary_pos_emb to query and key states.
316
+ if rotary_pos_emb is not None and position_ids is None:
317
+ raise ValueError("`position_ids` must be provided when `rotary_pos_emb` is not None.")
318
+
319
+ bsz, _, embed_dim = hidden_states.size()
320
+
321
+ # get query proj
322
+ query_states = self._shape(self.q_proj(hidden_states), -1, bsz) * self.scale
323
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
324
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
325
+
326
+ if past_key_values is not None:
327
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
328
+
329
+ if rotary_pos_emb is not None:
330
+ rotary_emb_dim = rotary_pos_emb.shape[-1]
331
+
332
+ # Partial rotary embedding
333
+ query_rot, query_pass = (
334
+ query_states[..., :rotary_emb_dim],
335
+ query_states[..., rotary_emb_dim:],
336
+ )
337
+ key_rot, key_pass = (
338
+ key_states[..., :rotary_emb_dim],
339
+ key_states[..., rotary_emb_dim:],
340
+ )
341
+ value_rot, value_pass = (
342
+ value_states[..., :rotary_emb_dim],
343
+ value_states[..., rotary_emb_dim:],
344
+ )
345
+
346
+ cos, sin = rotary_pos_emb.cos().squeeze(0), rotary_pos_emb.sin().squeeze(0)
347
+ query_rot, key_rot, value_rot = apply_rotary_pos_emb(query_rot, key_rot, value_rot, cos, sin, position_ids)
348
+
349
+ # [batch_size, num_heads, seq_length, head_dim]
350
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
351
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
352
+ value_states = torch.cat((value_rot, value_pass), dim=-1)
353
+
354
+ tgt_len = query_states.shape[2]
355
+ src_len = key_states.shape[2]
356
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
357
+
358
+ if attention_mask is not None:
359
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
360
+ raise ValueError(
361
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
362
+ )
363
+ attn_weights = attn_weights + attention_mask
364
+
365
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
366
+
367
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
368
+ attn_output = torch.matmul(attn_probs, value_states)
369
+
370
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
371
+ raise ValueError(
372
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
373
+ f" {attn_output.size()}"
374
+ )
375
+
376
+ attn_output = attn_output.transpose(1, 2).contiguous()
377
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
378
+
379
+ attn_output = self.out_proj(attn_output)
380
+
381
+ return attn_output, attn_weights
382
+
383
+
384
+ class ClvpGatedLinearUnit(nn.Module):
385
+ """
386
+ `ClvpGatedLinearUnit` uses the second half of the `hidden_states` to act as a gate for the first half of the
387
+ `hidden_states` which controls the flow of data from the first of the tensor.
388
+ """
389
+
390
+ def __init__(self, config):
391
+ super().__init__()
392
+ self.activation_fn = ACT2FN[config.hidden_act]
393
+ self.proj = nn.Linear(config.hidden_size, config.intermediate_size * 2)
394
+
395
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
396
+ hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1)
397
+ return hidden_states * self.activation_fn(gate)
398
+
399
+
400
+ class ClvpEncoderMLP(nn.Module):
401
+ """
402
+ This MLP is used in CLVP speech or text encoder models.
403
+ """
404
+
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.config = config
408
+
409
+ self.fc1 = ClvpGatedLinearUnit(config)
410
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
411
+ self.dropout_layer = nn.Dropout(config.dropout)
412
+
413
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
414
+ hidden_states = self.fc1(hidden_states)
415
+ hidden_states = self.dropout_layer(hidden_states)
416
+ hidden_states = self.fc2(hidden_states)
417
+ return hidden_states
418
+
419
+
420
+ class ClvpEncoderLayer(nn.Module):
421
+ def __init__(self, config: ClvpConfig):
422
+ super().__init__()
423
+ self.config = config
424
+ self.embed_dim = config.hidden_size
425
+ self.self_attn = ClvpSelfAttention(config)
426
+ self.mlp = ClvpEncoderMLP(config)
427
+
428
+ self.input_rmsnorm = ClvpRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
429
+ self.post_attention_rmsnorm = ClvpRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
430
+
431
+ def forward(
432
+ self,
433
+ hidden_states: torch.FloatTensor,
434
+ rotary_pos_emb: torch.FloatTensor,
435
+ attention_mask: torch.LongTensor,
436
+ position_ids: torch.LongTensor,
437
+ **kwargs: Unpack[TransformersKwargs],
438
+ ) -> torch.FloatTensor:
439
+ residual = hidden_states
440
+
441
+ hidden_states = self.input_rmsnorm(hidden_states)
442
+
443
+ hidden_states, _ = self.self_attn(
444
+ hidden_states,
445
+ rotary_pos_emb=rotary_pos_emb,
446
+ attention_mask=attention_mask,
447
+ position_ids=position_ids,
448
+ **kwargs,
449
+ )
450
+
451
+ hidden_states = residual + hidden_states
452
+
453
+ residual = hidden_states
454
+ hidden_states = self.post_attention_rmsnorm(hidden_states)
455
+ hidden_states = self.mlp(hidden_states)
456
+ hidden_states = residual + hidden_states
457
+
458
+ return hidden_states
459
+
460
+
461
+ # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->Clvp
462
+ class ClvpSequenceSummary(nn.Module):
463
+ r"""
464
+ Compute a single vector summary of a sequence hidden states.
465
+
466
+ Args:
467
+ config ([`ClvpConfig`]):
468
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
469
+ config class of your model for the default values it uses):
470
+
471
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
472
+
473
+ - `"last"` -- Take the last token hidden state (like XLNet)
474
+ - `"first"` -- Take the first token hidden state (like Bert)
475
+ - `"mean"` -- Take the mean of all tokens hidden states
476
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
477
+ - `"attn"` -- Not implemented now, use multi-head attention
478
+
479
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
480
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
481
+ (otherwise to `config.hidden_size`).
482
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
483
+ another string or `None` will add no activation.
484
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
485
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
486
+ """
487
+
488
+ def __init__(self, config: ClvpConfig):
489
+ super().__init__()
490
+
491
+ self.summary_type = getattr(config, "summary_type", "last")
492
+ if self.summary_type == "attn":
493
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
494
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
495
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
496
+ raise NotImplementedError
497
+
498
+ self.summary = nn.Identity()
499
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
500
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
501
+ num_classes = config.num_labels
502
+ else:
503
+ num_classes = config.hidden_size
504
+ self.summary = nn.Linear(config.hidden_size, num_classes)
505
+
506
+ activation_string = getattr(config, "summary_activation", None)
507
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
508
+
509
+ self.first_dropout = nn.Identity()
510
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
511
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
512
+
513
+ self.last_dropout = nn.Identity()
514
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
515
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
516
+
517
+ def forward(
518
+ self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
519
+ ) -> torch.FloatTensor:
520
+ """
521
+ Compute a single vector summary of a sequence hidden states.
522
+
523
+ Args:
524
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
525
+ The hidden states of the last layer.
526
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
527
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
528
+
529
+ Returns:
530
+ `torch.FloatTensor`: The summary of the sequence hidden states.
531
+ """
532
+ if self.summary_type == "last":
533
+ output = hidden_states[:, -1]
534
+ elif self.summary_type == "first":
535
+ output = hidden_states[:, 0]
536
+ elif self.summary_type == "mean":
537
+ output = hidden_states.mean(dim=1)
538
+ elif self.summary_type == "cls_index":
539
+ if cls_index is None:
540
+ cls_index = torch.full_like(
541
+ hidden_states[..., :1, :],
542
+ hidden_states.shape[-2] - 1,
543
+ dtype=torch.long,
544
+ )
545
+ else:
546
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
547
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
548
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
549
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
550
+ elif self.summary_type == "attn":
551
+ raise NotImplementedError
552
+
553
+ output = self.first_dropout(output)
554
+ output = self.summary(output)
555
+ output = self.activation(output)
556
+ output = self.last_dropout(output)
557
+
558
+ return output
559
+
560
+
561
+ # Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP with GPT2->ClvpDecoderMLP
562
+ class ClvpDecoderMLP(nn.Module):
563
+ def __init__(self, intermediate_size, config):
564
+ super().__init__()
565
+ embed_dim = config.hidden_size
566
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
567
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
568
+ self.act = ACT2FN[config.activation_function]
569
+ self.dropout = nn.Dropout(config.resid_pdrop)
570
+
571
+ def forward(self, hidden_states: tuple[torch.FloatTensor] | None) -> torch.FloatTensor:
572
+ hidden_states = self.c_fc(hidden_states)
573
+ hidden_states = self.act(hidden_states)
574
+ hidden_states = self.c_proj(hidden_states)
575
+ hidden_states = self.dropout(hidden_states)
576
+ return hidden_states
577
+
578
+
579
+ class ClvpDecoderLayer(nn.Module):
580
+ def __init__(self, config, layer_idx=None):
581
+ super().__init__()
582
+ hidden_size = config.hidden_size
583
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
584
+
585
+ self.input_layernorm = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
586
+ self.attn = ClvpSelfAttention(config, layer_idx=layer_idx)
587
+ self.post_attention_layernorm = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
588
+
589
+ self.mlp = ClvpDecoderMLP(inner_dim, config)
590
+
591
+ def forward(
592
+ self,
593
+ hidden_states: torch.FloatTensor,
594
+ past_key_values: Cache | None = None,
595
+ attention_mask: torch.LongTensor | None = None,
596
+ position_ids: torch.LongTensor | None = None,
597
+ use_cache: bool | None = False,
598
+ **kwargs: Unpack[TransformersKwargs],
599
+ ) -> torch.Tensor:
600
+ residual = hidden_states
601
+ hidden_states = self.input_layernorm(hidden_states)
602
+ hidden_states, _ = self.attn(
603
+ hidden_states,
604
+ past_key_values=past_key_values,
605
+ attention_mask=attention_mask,
606
+ position_ids=position_ids,
607
+ use_cache=use_cache,
608
+ **kwargs,
609
+ )
610
+ # residual connection
611
+ hidden_states = hidden_states + residual
612
+
613
+ residual = hidden_states
614
+ hidden_states = self.post_attention_layernorm(hidden_states)
615
+ feed_forward_hidden_states = self.mlp(hidden_states)
616
+ # residual connection
617
+ hidden_states = residual + feed_forward_hidden_states
618
+
619
+ return hidden_states
620
+
621
+
622
+ class ClvpConditioningEncoder(nn.Module):
623
+ """
624
+ This class processes the log-mel spectrograms(extracted by the Feature Extractor) and text tokens(produced by the
625
+ tokenizer) as inputs for the decoder model.
626
+
627
+ First each log-mel spectrogram is processed into a single vector which captures valuable characteristics from each
628
+ of them, then the text tokens are converted into token embeddings and position embeddings are added afterwards.
629
+ Both of these vectors are concatenated and then passed to the decoder model.
630
+
631
+ The text tokens helps to incorporate the "text information" and the log-mel spectrogram is used to specify the
632
+ "voice characteristics" into the generated mel tokens.
633
+ """
634
+
635
+ def __init__(self, config: ClvpConfig):
636
+ super().__init__()
637
+
638
+ self.text_config = config.text_config
639
+ self.decoder_config = config.decoder_config
640
+
641
+ self.text_token_embedding = nn.Embedding(self.text_config.vocab_size, self.decoder_config.hidden_size)
642
+ self.text_position_embedding = nn.Embedding(
643
+ self.decoder_config.max_text_tokens, self.decoder_config.hidden_size
644
+ )
645
+
646
+ self.mel_conv = nn.Conv1d(self.decoder_config.feature_size, self.decoder_config.hidden_size, kernel_size=1)
647
+
648
+ # define group norms to be used before each attention layer
649
+ num_groups = self.compute_groupnorm_groups(self.decoder_config.hidden_size)
650
+ self.group_norms = nn.ModuleList(
651
+ [
652
+ nn.GroupNorm(num_groups, self.decoder_config.hidden_size, eps=1e-5, affine=True)
653
+ for _ in range(self.decoder_config.num_mel_attn_blocks)
654
+ ]
655
+ )
656
+
657
+ # define the attention layers
658
+ self.mel_attn_blocks = nn.ModuleList(
659
+ [ClvpSelfAttention(self.decoder_config) for _ in range(self.decoder_config.num_mel_attn_blocks)]
660
+ )
661
+
662
+ self.gradient_checkpointing = False
663
+
664
+ def compute_groupnorm_groups(self, channels: int, groups: int = 32):
665
+ """
666
+ Calculates the value of `num_groups` for nn.GroupNorm. This logic is taken from the official tortoise
667
+ repository. link :
668
+ https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/models/arch_util.py#L26
669
+ """
670
+ if channels <= 16:
671
+ groups = 8
672
+ elif channels <= 64:
673
+ groups = 16
674
+ while channels % groups != 0:
675
+ groups = int(groups / 2)
676
+
677
+ if groups <= 2:
678
+ raise ValueError(
679
+ f"Number of groups for the GroupNorm must be greater than 2, but it is {groups}."
680
+ f"Please consider using a different `hidden_size`"
681
+ )
682
+
683
+ return groups
684
+
685
+ def forward(
686
+ self,
687
+ input_features: torch.FloatTensor,
688
+ input_ids: torch.LongTensor | None = None,
689
+ inputs_embeds: torch.FloatTensor | None = None,
690
+ attention_mask: torch.LongTensor | None = None,
691
+ ):
692
+ # process text
693
+ if input_ids is not None and inputs_embeds is not None:
694
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
695
+ elif input_ids is not None:
696
+ batch_size, seq_length = input_ids.size()
697
+ elif inputs_embeds is not None:
698
+ batch_size, seq_length = inputs_embeds.size()[:-1]
699
+ else:
700
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
701
+
702
+ # construct attention mask if not given
703
+ if attention_mask is None:
704
+ attention_mask = torch.ones([batch_size, seq_length], dtype=torch.long, device=input_ids.device)
705
+
706
+ # We add bos and eos input_ids in the modeling file instead of the tokenizer file to keep the logic simple
707
+ # This logic is specific to ClvpConditioningEncoder and not used by other modules.
708
+ input_ids, attention_mask = _pad_extra_bos_eos_tokens(
709
+ input_ids,
710
+ attention_mask,
711
+ bos_token_id=self.text_config.bos_token_id,
712
+ eos_token_id=self.text_config.eos_token_id,
713
+ )
714
+
715
+ inputs_embeds = self.text_token_embedding(input_ids)
716
+ position_ids = attention_mask.cumsum(-1) - 1
717
+ position_embeds = self.text_position_embedding(position_ids)
718
+ text_embeds = inputs_embeds + position_embeds
719
+
720
+ if self.gradient_checkpointing and self.training:
721
+ # process each log-mel spectrogram into a single vector
722
+ mel_spec = torch.utils.checkpoint.checkpoint(self.mel_conv, input_features)
723
+
724
+ for i, mel_attn_block in enumerate(self.mel_attn_blocks):
725
+ residual_mel_spec = mel_spec.transpose(1, 2)
726
+
727
+ mel_spec = torch.utils.checkpoint.checkpoint(self.group_norms[i], mel_spec).transpose(1, 2)
728
+ mel_spec = torch.utils.checkpoint.checkpoint(mel_attn_block, mel_spec)[0] + residual_mel_spec
729
+ mel_spec = mel_spec.transpose(1, 2)
730
+
731
+ else:
732
+ # process each log-mel spectrogram into a single vector
733
+ mel_spec = self.mel_conv(input_features)
734
+
735
+ for i, mel_attn_block in enumerate(self.mel_attn_blocks):
736
+ residual_mel_spec = mel_spec.transpose(1, 2)
737
+
738
+ mel_spec = self.group_norms[i](mel_spec).transpose(1, 2)
739
+ mel_spec = mel_attn_block(mel_spec)[0] + residual_mel_spec
740
+ mel_spec = mel_spec.transpose(1, 2)
741
+
742
+ mel_spec = mel_spec[:, :, 0]
743
+ mel_spec = mel_spec.unsqueeze(1)
744
+
745
+ # repeat if there is either (1 text vs N audios) or (N texts vs 1 audio)
746
+ if text_embeds.shape[0] == 1 and mel_spec.shape[0] != 1:
747
+ text_embeds = text_embeds.repeat(mel_spec.shape[0], 1, 1)
748
+ elif text_embeds.shape[0] != 1 and mel_spec.shape[0] == 1:
749
+ mel_spec = mel_spec.repeat(text_embeds.shape[0], 1, 1)
750
+ # If there is N texts and M audios we will raise error since the number of text and audio must be same.
751
+ elif text_embeds.shape[0] != mel_spec.shape[0]:
752
+ raise ValueError(
753
+ f"The number of texts and number of audios must be same. "
754
+ f"Found {text_embeds.shape[0]} texts vs {mel_spec.shape[0]} audios"
755
+ )
756
+
757
+ return torch.concat([mel_spec, text_embeds], dim=1)
758
+
759
+
760
+ @auto_docstring
761
+ class ClvpPreTrainedModel(PreTrainedModel):
762
+ config: ClvpConfig
763
+ base_model_prefix = "model"
764
+ supports_gradient_checkpointing = True
765
+ _skip_keys_device_placement = "past_key_values"
766
+ _can_record_outputs = {
767
+ "hidden_states": (ClvpEncoderLayer, ClvpDecoderLayer),
768
+ "attentions": ClvpSelfAttention,
769
+ }
770
+
771
+ @torch.no_grad()
772
+ def _init_weights(self, module: nn.Module):
773
+ """Initialize the weights"""
774
+ factor = self.config.initializer_factor
775
+ if isinstance(module, nn.Embedding):
776
+ init.normal_(module.weight, mean=0.0, std=factor * 0.02)
777
+ elif isinstance(module, (nn.Linear, Conv1D, nn.Conv1d)):
778
+ init.normal_(module.weight, mean=0.0, std=factor * 0.02)
779
+ if module.bias is not None:
780
+ init.zeros_(module.bias)
781
+ elif isinstance(module, ClvpRMSNorm):
782
+ init.ones_(module.weight)
783
+ elif isinstance(module, ClvpEncoderMLP):
784
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
785
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
786
+ init.normal_(module.fc1.proj.weight if getattr(module.fc1, "proj") else module.fc1.weight, std=fc_std)
787
+ init.normal_(module.fc2.weight, std=in_proj_std)
788
+ elif isinstance(module, ClvpEncoder):
789
+ config = self.config.get_text_config()
790
+ factor = config.initializer_factor
791
+ init.normal_(module.projection.weight, mean=0.0, std=factor * (config.hidden_size**-0.5))
792
+ elif isinstance(module, ClvpConditioningEncoder):
793
+ init.normal_(module.mel_conv.weight, mean=0.0, std=factor)
794
+ init.zeros_(module.mel_conv.bias)
795
+ elif isinstance(module, ClvpForCausalLM):
796
+ for name, p in module.named_parameters():
797
+ if name == "c_proj.weight":
798
+ init.normal_(
799
+ p, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.num_hidden_layers)
800
+ )
801
+ elif isinstance(module, ClvpModelForConditionalGeneration):
802
+ init.constant_(module.logit_scale, self.config.logit_scale_init_value)
803
+ elif isinstance(module, ClvpSelfAttention):
804
+ if hasattr(module.config, "max_position_embeddings"):
805
+ max_positions = module.config.max_position_embeddings
806
+ bias = torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool))
807
+ bias = bias.view(1, 1, max_positions, max_positions)
808
+ init.copy_(module.bias, bias)
809
+ elif isinstance(module, ClvpRotaryPositionalEmbedding):
810
+ dim = max(self.config.projection_dim // (self.config.num_attention_heads * 2), 32)
811
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
812
+ init.copy_(module.inv_freq, inv_freq)
813
+ if isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
814
+ init.zeros_(module.bias)
815
+ init.ones_(module.weight)
816
+
817
+
818
+ class ClvpEncoder(ClvpPreTrainedModel):
819
+ """
820
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
821
+ [`ClvpEncoderLayer`].
822
+
823
+ Args:
824
+ config: ClvpConfig
825
+ """
826
+
827
+ config: ClvpEncoderConfig
828
+
829
+ def __init__(self, config: ClvpConfig):
830
+ super().__init__(config)
831
+
832
+ self.config = config
833
+ self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
834
+ self.rotary_pos_emb = ClvpRotaryPositionalEmbedding(config) if config.use_rotary_embedding else None
835
+ self.layers = nn.ModuleList([ClvpEncoderLayer(config) for _ in range(config.num_hidden_layers)])
836
+
837
+ self.sequence_summary = ClvpSequenceSummary(config)
838
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
839
+
840
+ self.projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
841
+
842
+ self.gradient_checkpointing = False
843
+
844
+ self.post_init()
845
+
846
+ def get_input_embeddings(self):
847
+ return self.token_embedding
848
+
849
+ def set_input_embeddings(self, value):
850
+ self.token_embedding = value
851
+
852
+ @merge_with_config_defaults
853
+ @capture_outputs
854
+ @auto_docstring
855
+ def forward(
856
+ self,
857
+ input_ids: torch.LongTensor | None = None,
858
+ inputs_embeds: torch.LongTensor | None = None,
859
+ attention_mask: torch.LongTensor | None = None,
860
+ position_ids: torch.LongTensor | None = None,
861
+ **kwargs: Unpack[TransformersKwargs],
862
+ ) -> ClvpEncoderOutput:
863
+ if (input_ids is None) ^ (inputs_embeds is not None):
864
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
865
+
866
+ if inputs_embeds is None:
867
+ inputs_embeds = self.token_embedding(input_ids)
868
+
869
+ # expand attention_mask and create position_ids if needed
870
+ attention_mask = create_bidirectional_mask(
871
+ config=self.config,
872
+ inputs_embeds=inputs_embeds,
873
+ attention_mask=attention_mask,
874
+ )
875
+
876
+ if position_ids is None:
877
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
878
+ position_ids = torch.arange(inputs_embeds.shape[1], dtype=torch.long, device=device)
879
+ position_ids = position_ids.unsqueeze(0)
880
+
881
+ rotary_pos_emb = self.rotary_pos_emb(inputs_embeds) if self.rotary_pos_emb is not None else None
882
+
883
+ hidden_states = inputs_embeds
884
+ for encoder_layer in self.layers:
885
+ hidden_states = encoder_layer(
886
+ hidden_states,
887
+ rotary_pos_emb,
888
+ attention_mask,
889
+ position_ids,
890
+ **kwargs,
891
+ )
892
+
893
+ last_hidden_state = self.final_layer_norm(hidden_states)
894
+
895
+ # take the mean over axis 1 and get pooled output
896
+ pooled_output = self.sequence_summary(last_hidden_state)
897
+
898
+ # apply the projection layer
899
+ embeds = self.projection(pooled_output)
900
+
901
+ return ClvpEncoderOutput(
902
+ embeds=embeds,
903
+ last_hidden_state=last_hidden_state,
904
+ pooler_output=pooled_output,
905
+ )
906
+
907
+
908
+ class ClvpDecoder(ClvpPreTrainedModel):
909
+ """
910
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`]
911
+ """
912
+
913
+ config: ClvpDecoderConfig
914
+
915
+ def __init__(self, config):
916
+ super().__init__(config)
917
+
918
+ self.config = config
919
+
920
+ self.input_embeds_layer = nn.Embedding(self.config.vocab_size, self.config.hidden_size)
921
+ self.position_embeds_layer = nn.Embedding(self.config.max_position_embeddings, self.config.hidden_size)
922
+
923
+ self.drop = nn.Dropout(self.config.embd_pdrop)
924
+ self.layers = nn.ModuleList(
925
+ [ClvpDecoderLayer(self.config, layer_idx=i) for i in range(self.config.num_hidden_layers)]
926
+ )
927
+ self.layer_norm = nn.LayerNorm(self.config.hidden_size, eps=self.config.layer_norm_epsilon)
928
+
929
+ self.gradient_checkpointing = False
930
+
931
+ # Initialize weights and apply final processing
932
+ self.post_init()
933
+
934
+ def get_input_embeddings(self):
935
+ return self.input_embeds_layer
936
+
937
+ def set_input_embeddings(self, new_embeddings):
938
+ self.input_embeds_layer = new_embeddings
939
+
940
+ @merge_with_config_defaults
941
+ @capture_outputs
942
+ @auto_docstring
943
+ def forward(
944
+ self,
945
+ input_ids: torch.LongTensor | None = None,
946
+ attention_mask: torch.FloatTensor | None = None,
947
+ token_type_ids: torch.LongTensor | None = None,
948
+ position_ids: torch.LongTensor | None = None,
949
+ past_key_values: Cache | None = None,
950
+ inputs_embeds: torch.FloatTensor | None = None,
951
+ use_cache: bool | None = None,
952
+ **kwargs: Unpack[TransformersKwargs],
953
+ ) -> BaseModelOutputWithPastAndCrossAttentions:
954
+ if (input_ids is None) ^ (inputs_embeds is not None):
955
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
956
+
957
+ if inputs_embeds is None:
958
+ inputs_embeds = self.input_embeds_layer(input_ids)
959
+
960
+ seq_len = inputs_embeds.shape[1]
961
+ if token_type_ids is not None:
962
+ token_type_ids = token_type_ids.view(-1, seq_len)
963
+
964
+ if use_cache and past_key_values is None:
965
+ past_key_values = DynamicCache(config=self.config)
966
+
967
+ if position_ids is None:
968
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
969
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
970
+ position_ids = position_ids.unsqueeze(0)
971
+
972
+ position_embeds = self.position_embeds_layer(position_ids)
973
+ inputs_embeds = inputs_embeds + position_embeds
974
+
975
+ attention_mask = create_causal_mask(
976
+ config=self.config,
977
+ inputs_embeds=inputs_embeds,
978
+ attention_mask=attention_mask,
979
+ past_key_values=past_key_values,
980
+ )
981
+
982
+ hidden_states = inputs_embeds
983
+
984
+ if token_type_ids is not None:
985
+ token_type_embeds = self.input_embeds_layer(token_type_ids)
986
+ hidden_states = hidden_states + token_type_embeds
987
+
988
+ hidden_states = self.drop(hidden_states)
989
+
990
+ output_shape = (
991
+ -1,
992
+ seq_len,
993
+ ) + (hidden_states.size(-1),)
994
+
995
+ for block in self.layers:
996
+ hidden_states = block(
997
+ hidden_states,
998
+ past_key_values=past_key_values,
999
+ attention_mask=attention_mask,
1000
+ position_ids=position_ids,
1001
+ use_cache=use_cache,
1002
+ **kwargs,
1003
+ )
1004
+
1005
+ hidden_states = self.layer_norm(hidden_states)
1006
+
1007
+ hidden_states = hidden_states.view(output_shape)
1008
+
1009
+ return BaseModelOutputWithPastAndCrossAttentions(
1010
+ last_hidden_state=hidden_states,
1011
+ past_key_values=past_key_values,
1012
+ )
1013
+
1014
+
1015
+ @auto_docstring
1016
+ class ClvpModel(ClvpPreTrainedModel):
1017
+ config: ClvpDecoderConfig
1018
+
1019
+ def __init__(self, config: ClvpDecoderConfig):
1020
+ super().__init__(config)
1021
+ self.config = config
1022
+ self.decoder = ClvpDecoder(self.config)
1023
+
1024
+ # Initialize weights and apply final processing
1025
+ self.post_init()
1026
+
1027
+ def get_input_embeddings(self):
1028
+ return self.decoder.input_embeds_layer
1029
+
1030
+ def set_input_embeddings(self, value):
1031
+ self.decoder.input_embeds_layer = value
1032
+
1033
+ @can_return_tuple
1034
+ @auto_docstring
1035
+ def forward(
1036
+ self,
1037
+ input_ids: torch.LongTensor | None = None,
1038
+ attention_mask: torch.FloatTensor | None = None,
1039
+ token_type_ids: torch.LongTensor | None = None,
1040
+ position_ids: torch.LongTensor | None = None,
1041
+ past_key_values: Cache | None = None,
1042
+ inputs_embeds: torch.FloatTensor | None = None,
1043
+ use_cache: bool | None = None,
1044
+ **kwargs: Unpack[TransformersKwargs],
1045
+ ) -> BaseModelOutputWithPastAndCrossAttentions:
1046
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
1047
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
1048
+ input_ids=input_ids,
1049
+ attention_mask=attention_mask,
1050
+ token_type_ids=token_type_ids,
1051
+ position_ids=position_ids,
1052
+ past_key_values=past_key_values,
1053
+ inputs_embeds=inputs_embeds,
1054
+ use_cache=use_cache,
1055
+ **kwargs,
1056
+ )
1057
+
1058
+ return BaseModelOutputWithPastAndCrossAttentions(
1059
+ last_hidden_state=decoder_outputs.last_hidden_state,
1060
+ past_key_values=decoder_outputs.past_key_values,
1061
+ hidden_states=decoder_outputs.hidden_states,
1062
+ attentions=decoder_outputs.attentions,
1063
+ cross_attentions=decoder_outputs.cross_attentions,
1064
+ )
1065
+
1066
+
1067
+ @auto_docstring(
1068
+ custom_intro="""
1069
+ The CLVP decoder model with a language modelling head on top.
1070
+ """
1071
+ )
1072
+ class ClvpForCausalLM(ClvpPreTrainedModel, GenerationMixin):
1073
+ config: ClvpDecoderConfig
1074
+
1075
+ def __init__(self, config):
1076
+ super().__init__(config)
1077
+
1078
+ self.config = config
1079
+ self.model = ClvpModel(self.config)
1080
+
1081
+ self.final_norm = nn.LayerNorm(self.config.hidden_size)
1082
+ self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=True)
1083
+
1084
+ # Initialize weights and apply final processing
1085
+ self.post_init()
1086
+
1087
+ def get_output_embeddings(self):
1088
+ return None
1089
+
1090
+ def get_input_embeddings(self):
1091
+ return self.model.decoder.input_embeds_layer
1092
+
1093
+ def set_input_embeddings(self, new_embeddings):
1094
+ self.model.decoder.input_embeds_layer = new_embeddings
1095
+
1096
+ def _prepare_model_inputs(
1097
+ self,
1098
+ inputs: torch.Tensor | None,
1099
+ bos_token_id: int | None,
1100
+ model_kwargs: dict[str, torch.Tensor],
1101
+ ) -> tuple[torch.Tensor, str | None, dict[str, torch.Tensor]]:
1102
+ """
1103
+ This function extracts the model-specific `inputs` for generation.
1104
+ """
1105
+ input_name = self.main_input_name
1106
+
1107
+ model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None}
1108
+
1109
+ inputs_kwarg = model_kwargs.pop(input_name, None)
1110
+ if inputs_kwarg is not None and inputs is not None:
1111
+ raise ValueError(
1112
+ f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed."
1113
+ f"Make sure to either pass {inputs} or {input_name}=..."
1114
+ )
1115
+ elif inputs_kwarg is not None:
1116
+ inputs = inputs_kwarg
1117
+
1118
+ if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
1119
+ model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
1120
+ inputs, bos_token_id, model_kwargs=model_kwargs
1121
+ )
1122
+ inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
1123
+
1124
+ # Check if conditioning_embeds are provided or not, if yes then concatenate the bos_token_id at the end of the conditioning_embeds.
1125
+ # Then we must subtract the positional_ids because during the forward pass it will be added anyways, so we must cancel them out here.
1126
+ conditioning_embeds = model_kwargs.get("conditioning_embeds")
1127
+
1128
+ if conditioning_embeds is not None:
1129
+ mel_start_token_embedding = self.model.decoder.input_embeds_layer(
1130
+ torch.full(
1131
+ (conditioning_embeds.shape[0], 1),
1132
+ fill_value=self.config.bos_token_id,
1133
+ device=conditioning_embeds.device,
1134
+ )
1135
+ )
1136
+ mel_start_token_embedding += self.model.decoder.position_embeds_layer(
1137
+ torch.full((conditioning_embeds.shape[0], 1), fill_value=0, device=conditioning_embeds.device)
1138
+ )
1139
+ conditioning_embeds = torch.concat([conditioning_embeds, mel_start_token_embedding], dim=1)
1140
+
1141
+ # subtract the positional_ids here
1142
+ if hasattr(model_kwargs, "attention_mask"):
1143
+ position_ids = model_kwargs["attention_mask"].long().cumsum(-1) - 1
1144
+ else:
1145
+ position_ids = torch.arange(
1146
+ 0, conditioning_embeds.shape[1], dtype=torch.long, device=conditioning_embeds.device
1147
+ )
1148
+ position_ids = position_ids.unsqueeze(0).repeat(conditioning_embeds.shape[0], 1)
1149
+
1150
+ model_kwargs["inputs_embeds"] = conditioning_embeds - self.model.decoder.position_embeds_layer(
1151
+ position_ids
1152
+ )
1153
+ model_kwargs["input_ids"] = (
1154
+ torch.ones((model_kwargs["inputs_embeds"].shape[0], 1), dtype=torch.long, device=self.device)
1155
+ * self.config.bos_token_id
1156
+ )
1157
+
1158
+ return model_kwargs["inputs_embeds"], "inputs_embeds", model_kwargs
1159
+
1160
+ inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
1161
+ return inputs, input_name, model_kwargs
1162
+
1163
+ def prepare_inputs_for_generation(
1164
+ self,
1165
+ input_ids,
1166
+ past_key_values=None,
1167
+ inputs_embeds=None,
1168
+ conditioning_embeds=None,
1169
+ is_first_iteration=False,
1170
+ **kwargs,
1171
+ ):
1172
+ # Overwritten: has `conditioning_embeds`-related logic
1173
+
1174
+ input_ids_length = input_ids.shape[-1]
1175
+
1176
+ model_inputs = super().prepare_inputs_for_generation(
1177
+ input_ids,
1178
+ past_key_values=past_key_values,
1179
+ inputs_embeds=inputs_embeds,
1180
+ is_first_iteration=is_first_iteration,
1181
+ **kwargs,
1182
+ )
1183
+ if conditioning_embeds is not None and not is_first_iteration:
1184
+ model_inputs["position_ids"] = torch.tensor([input_ids_length], dtype=torch.long, device=input_ids.device)
1185
+
1186
+ return model_inputs
1187
+
1188
+ @can_return_tuple
1189
+ @auto_docstring
1190
+ def forward(
1191
+ self,
1192
+ input_ids: torch.LongTensor | None = None,
1193
+ past_key_values: Cache | None = None,
1194
+ attention_mask: torch.FloatTensor | None = None,
1195
+ token_type_ids: torch.LongTensor | None = None,
1196
+ position_ids: torch.LongTensor | None = None,
1197
+ inputs_embeds: torch.FloatTensor | None = None,
1198
+ labels: torch.LongTensor | None = None,
1199
+ use_cache: bool | None = None,
1200
+ **kwargs: Unpack[TransformersKwargs],
1201
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
1202
+ r"""
1203
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1205
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1206
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1207
+ """
1208
+
1209
+ outputs: BaseModelOutputWithPastAndCrossAttentions = self.model(
1210
+ input_ids=input_ids,
1211
+ past_key_values=past_key_values,
1212
+ attention_mask=attention_mask,
1213
+ token_type_ids=token_type_ids,
1214
+ position_ids=position_ids,
1215
+ inputs_embeds=inputs_embeds,
1216
+ use_cache=use_cache,
1217
+ **kwargs,
1218
+ )
1219
+
1220
+ hidden_states = outputs.last_hidden_state
1221
+
1222
+ lm_logits = self.final_norm(hidden_states)
1223
+ lm_logits = self.lm_head(lm_logits)
1224
+
1225
+ loss = None
1226
+ if labels is not None:
1227
+ labels = labels.to(lm_logits.device)
1228
+ # Shift so that tokens < n predict n
1229
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1230
+ shift_labels = labels[..., 1:].contiguous()
1231
+ # Flatten the tokens
1232
+ loss_fct = CrossEntropyLoss()
1233
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1234
+
1235
+ return CausalLMOutputWithCrossAttentions(
1236
+ loss=loss,
1237
+ logits=lm_logits,
1238
+ past_key_values=outputs.past_key_values,
1239
+ hidden_states=outputs.hidden_states,
1240
+ attentions=outputs.attentions,
1241
+ cross_attentions=outputs.cross_attentions,
1242
+ )
1243
+
1244
+
1245
+ @auto_docstring(
1246
+ custom_intro="""
1247
+ The composite CLVP model with a text encoder, speech encoder and speech decoder model.
1248
+ """
1249
+ )
1250
+ class ClvpModelForConditionalGeneration(ClvpPreTrainedModel, GenerationMixin):
1251
+ def __init__(self, config: ClvpConfig):
1252
+ super().__init__(config)
1253
+
1254
+ if not isinstance(config.text_config, ClvpEncoderConfig):
1255
+ raise TypeError(
1256
+ "config.text_config is expected to be of type `ClvpEncoderConfig` but is of type"
1257
+ f" {type(config.text_config)}."
1258
+ )
1259
+
1260
+ if not isinstance(config.speech_config, ClvpEncoderConfig):
1261
+ raise TypeError(
1262
+ "config.speech_config is expected to be of type `ClvpEncoderConfig` but is of type"
1263
+ f" {type(config.speech_config)}."
1264
+ )
1265
+
1266
+ if not isinstance(config.decoder_config, ClvpDecoderConfig):
1267
+ raise TypeError(
1268
+ "config.decoder_config is expected to be of type `ClvpDecoderConfig` but is of type"
1269
+ f" {type(config.decoder_config)}."
1270
+ )
1271
+
1272
+ self.conditioning_encoder = ClvpConditioningEncoder(config)
1273
+
1274
+ self.speech_decoder_model = ClvpForCausalLM(config.decoder_config)
1275
+
1276
+ self.text_encoder_model = ClvpEncoder(config.text_config)
1277
+ self.speech_encoder_model = ClvpEncoder(config.speech_config)
1278
+
1279
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
1280
+
1281
+ # Initialize weights and apply final processing
1282
+ self.post_init()
1283
+
1284
+ # taken from the original repo,
1285
+ # link : https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/api.py#L117
1286
+ def fix_speech_decoder_output(self, speech_ids: torch.LongTensor) -> torch.LongTensor:
1287
+ """
1288
+ This method modifies the output of the decoder model, such as replacing the `eos_token_id` and changing the
1289
+ last few tokens of each sequence.
1290
+
1291
+ Args:
1292
+ speech_ids (`torch.LongTensor`):
1293
+ This refers to the output of the decoder model.
1294
+ """
1295
+ decoder_fixing_codes = self.config.decoder_config.decoder_fixing_codes
1296
+ speech_ids = speech_ids[:, 1:]
1297
+
1298
+ stop_token_indices = torch.where(speech_ids == self.speech_decoder_model.config.eos_token_id, 1, 0)
1299
+ speech_ids = torch.masked_fill(speech_ids, mask=stop_token_indices.bool(), value=decoder_fixing_codes[0])
1300
+
1301
+ for i, each_seq_stop_token_index in enumerate(stop_token_indices):
1302
+ # This means that no stop tokens were found so the sentence was still being generated, in that case we don't need
1303
+ # to apply any padding so just skip to the next sequence of tokens.
1304
+ if each_seq_stop_token_index.sum() == 0:
1305
+ continue
1306
+
1307
+ stm = each_seq_stop_token_index.argmax()
1308
+ speech_ids[i, stm:] = decoder_fixing_codes[0]
1309
+ if stm - 3 < speech_ids.shape[1]:
1310
+ speech_ids[i, -3:] = torch.tensor(
1311
+ [decoder_fixing_codes[1:]], device=speech_ids.device, dtype=torch.long
1312
+ )
1313
+
1314
+ return speech_ids
1315
+
1316
+ @can_return_tuple
1317
+ @auto_docstring(
1318
+ custom_intro="""
1319
+ This method can be used to extract text_embeds from a text. The text embeddings obtained by applying the
1320
+ projection layer to the pooled output of the CLVP text encoder model.
1321
+ """
1322
+ )
1323
+ def get_text_features(
1324
+ self,
1325
+ input_ids: torch.LongTensor | None = None,
1326
+ text_encoder_inputs_embeds: torch.FloatTensor | None = None,
1327
+ attention_mask: torch.LongTensor | None = None,
1328
+ **kwargs: Unpack[TransformersKwargs],
1329
+ ) -> tuple | ClvpEncoderOutput:
1330
+ r"""
1331
+ text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
1332
+ inputs_embeds for the text encoder model passed in place of `input_ids`.
1333
+
1334
+ Examples:
1335
+
1336
+ ```python
1337
+ >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
1338
+
1339
+ >>> # Define the Text
1340
+ >>> text = "This is an example text."
1341
+
1342
+ >>> # Define processor and model
1343
+ >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
1344
+ >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
1345
+
1346
+ >>> # Generate processor output and text embeds
1347
+ >>> processor_output = processor(text=text, return_tensors="pt")
1348
+ >>> text_embeds = model.get_text_features(input_ids=processor_output["input_ids"])
1349
+ ```
1350
+ """
1351
+ return self.text_encoder_model(
1352
+ input_ids=input_ids,
1353
+ inputs_embeds=text_encoder_inputs_embeds,
1354
+ attention_mask=attention_mask,
1355
+ **kwargs,
1356
+ )
1357
+
1358
+ def get_speech_features(
1359
+ self,
1360
+ speech_ids: torch.LongTensor | None = None,
1361
+ input_ids: torch.LongTensor | None = None,
1362
+ input_features: torch.FloatTensor | None = None,
1363
+ conditioning_encoder_inputs_embeds: torch.FloatTensor | None = None,
1364
+ attention_mask: torch.Tensor | None = None,
1365
+ generation_config: GenerationConfig | None = None,
1366
+ **kwargs,
1367
+ ) -> torch.FloatTensor:
1368
+ r"""
1369
+ This method can be used to extract speech_embeds. The speech embeddings are obtained by applying the speech
1370
+ model on speech_ids. If speech_ids is not present but both input_ids and input_features are given then the
1371
+ decoder model will be used to first generate the speech_ids and then applying the speech model.
1372
+
1373
+ Args:
1374
+ speech_ids (`torch.LongTensor` of shape `(batch_size, num_speech_ids)`, *optional*):
1375
+ Speech Tokens. Padding will be ignored by default should you provide it. If speech_ids are provided
1376
+ then input_ids and input_features will be automatically ignored.
1377
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1378
+ Input text Tokens. Processed from the [`ClvpTokenizer`]. If speech_ids is not provided, then input_ids
1379
+ and input_features will be used.
1380
+ conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
1381
+ inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
1382
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1383
+ Mask to avoid performing attention on padding speech token indices. Mask values selected in `[0, 1]`:
1384
+
1385
+ - 1 for tokens that are **not masked**,
1386
+ - 0 for tokens that are **masked**.
1387
+
1388
+ [What are attention masks?](../glossary#attention-mask)
1389
+ generation_config (`GenerationConfig`, *optional*):
1390
+ generation config to control the generation of speech_ids if they are not provided.
1391
+
1392
+ Returns:
1393
+ `torch.FloatTensor` of shape `(batch_size, output_dim)`:
1394
+ The speech embeddings obtained by applying the projection layer to the pooled output of the CLVP Speech
1395
+ Model.
1396
+
1397
+ Examples:
1398
+
1399
+ ```python
1400
+ >>> import datasets
1401
+ >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
1402
+
1403
+ >>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
1404
+ >>> text = "This is an example text."
1405
+ >>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1406
+ >>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
1407
+ >>> audio = ds.sort("id")["audio"][0]
1408
+ >>> audio_sample, sr = audio["array"], audio["sampling_rate"]
1409
+
1410
+ >>> # Define processor and model
1411
+ >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
1412
+ >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
1413
+
1414
+ >>> # Generate processor output and model output
1415
+ >>> processor_output = processor(raw_speech=audio_sample, sampling_rate=sr, text=text, return_tensors="pt")
1416
+ >>> speech_embeds = model.get_speech_features(
1417
+ ... input_ids=processor_output["input_ids"], input_features=processor_output["input_features"]
1418
+ ... )
1419
+ ```
1420
+ """
1421
+
1422
+ if speech_ids is None:
1423
+ if (input_ids is None and conditioning_encoder_inputs_embeds is None) or input_features is None:
1424
+ raise ValueError(
1425
+ "Either speech_ids or input_ids/conditioning_encoder_inputs_embeds and input_features must be provided."
1426
+ )
1427
+
1428
+ if generation_config is None:
1429
+ generation_config = self.generation_config
1430
+ generation_config.update(**kwargs)
1431
+
1432
+ conditioning_embeds = self.conditioning_encoder(
1433
+ input_features=input_features,
1434
+ input_ids=input_ids,
1435
+ inputs_embeds=conditioning_encoder_inputs_embeds,
1436
+ attention_mask=attention_mask,
1437
+ )
1438
+
1439
+ speech_ids = self.speech_decoder_model.generate(
1440
+ conditioning_embeds=conditioning_embeds,
1441
+ generation_config=generation_config,
1442
+ )
1443
+
1444
+ speech_ids = self.fix_speech_decoder_output(speech_ids[0])
1445
+
1446
+ outputs = self.speech_encoder_model(
1447
+ input_ids=speech_ids,
1448
+ attention_mask=attention_mask,
1449
+ )
1450
+
1451
+ return outputs[0]
1452
+
1453
+ @can_return_tuple
1454
+ @auto_docstring
1455
+ def forward(
1456
+ self,
1457
+ input_ids: torch.LongTensor | None = None,
1458
+ input_features: torch.FloatTensor | None = None,
1459
+ conditioning_encoder_inputs_embeds: torch.FloatTensor | None = None,
1460
+ text_encoder_inputs_embeds: torch.FloatTensor | None = None,
1461
+ attention_mask: torch.LongTensor | None = None,
1462
+ return_loss: bool | None = None,
1463
+ **kwargs: Unpack[TransformersKwargs],
1464
+ ) -> tuple | ClvpOutput:
1465
+ r"""
1466
+ conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
1467
+ inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
1468
+ text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
1469
+ inputs_embeds for the text encoder model passed in place of `input_ids`.
1470
+ return_loss (`bool`, *optional*):
1471
+ Whether or not to return the contrastive loss.
1472
+
1473
+ Examples:
1474
+
1475
+ ```python
1476
+ >>> import datasets
1477
+ >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
1478
+
1479
+ >>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
1480
+ >>> text = "This is an example text."
1481
+
1482
+ >>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1483
+ >>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
1484
+ >>> audio = ds.sort("id")["audio"][0]
1485
+ >>> audio_sample, sr = audio["array"], audio["sampling_rate"]
1486
+
1487
+ >>> # Define processor and model
1488
+ >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
1489
+ >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
1490
+
1491
+ >>> # processor outputs and model outputs
1492
+ >>> processor_output = processor(raw_speech=audio_sample, sampling_rate=sr, text=text, return_tensors="pt")
1493
+ >>> outputs = model(
1494
+ ... input_ids=processor_output["input_ids"],
1495
+ ... input_features=processor_output["input_features"],
1496
+ ... return_dict=True,
1497
+ ... )
1498
+ ```
1499
+ """
1500
+
1501
+ conditioning_embeds = self.conditioning_encoder(
1502
+ input_features=input_features,
1503
+ input_ids=input_ids,
1504
+ inputs_embeds=conditioning_encoder_inputs_embeds,
1505
+ attention_mask=attention_mask,
1506
+ )
1507
+
1508
+ decoder_outputs: CausalLMOutputWithCrossAttentions = self.speech_decoder_model(
1509
+ inputs_embeds=conditioning_embeds,
1510
+ **kwargs,
1511
+ )
1512
+
1513
+ speech_ids = decoder_outputs.logits
1514
+
1515
+ # since we will get the embeds of shape `(batch_size, seq_len, embedding_dim)` during the forward pass
1516
+ # we must convert it to tokens, to make it compaitable with speech_transformer
1517
+ if speech_ids.ndim == 3:
1518
+ speech_ids = speech_ids.argmax(2)
1519
+ speech_ids = self.fix_speech_decoder_output(speech_ids)
1520
+
1521
+ speech_outputs: ClvpEncoderOutput = self.speech_encoder_model(
1522
+ input_ids=speech_ids,
1523
+ **kwargs,
1524
+ )
1525
+
1526
+ text_outputs: ClvpEncoderOutput = self.text_encoder_model(
1527
+ input_ids=input_ids,
1528
+ inputs_embeds=text_encoder_inputs_embeds,
1529
+ attention_mask=attention_mask,
1530
+ **kwargs,
1531
+ )
1532
+
1533
+ speech_embeds = speech_outputs.embeds
1534
+ text_embeds = text_outputs.embeds
1535
+
1536
+ # normalized features
1537
+ speech_embeds = speech_embeds / speech_embeds.norm(p=2, dim=-1, keepdim=True)
1538
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1539
+
1540
+ # cosine similarity as logits
1541
+ logit_scale = self.logit_scale.exp()
1542
+ logits_per_text = torch.matmul(text_embeds, speech_embeds.t()) * logit_scale
1543
+ logits_per_speech = logits_per_text.t()
1544
+
1545
+ loss = None
1546
+ if return_loss:
1547
+ loss = speech_text_contrastive_loss(logits_per_text)
1548
+
1549
+ return ClvpOutput(
1550
+ loss=loss,
1551
+ logits_per_speech=logits_per_speech,
1552
+ logits_per_text=logits_per_text,
1553
+ text_embeds=text_embeds,
1554
+ speech_embeds=speech_embeds,
1555
+ text_model_output=text_outputs.pooler_output,
1556
+ speech_model_output=speech_outputs.pooler_output,
1557
+ decoder_hidden_states=decoder_outputs.hidden_states,
1558
+ text_encoder_hidden_states=text_outputs.hidden_states,
1559
+ speech_encoder_hidden_states=speech_outputs.hidden_states,
1560
+ )
1561
+
1562
+ @torch.no_grad()
1563
+ def generate(
1564
+ self,
1565
+ input_ids: torch.LongTensor | None = None,
1566
+ input_features: torch.FloatTensor | None = None,
1567
+ attention_mask: torch.LongTensor | None = None,
1568
+ generation_config: GenerationConfig | None = None,
1569
+ pad_to_max_mel_tokens: int | None = None,
1570
+ output_hidden_states: bool | None = None,
1571
+ **kwargs,
1572
+ ):
1573
+ """
1574
+ Generate method for `ClvpModelForConditionalGeneration`, this method calls the `generate` method of
1575
+ `ClvpForCausalLM` and then uses those generated `speech_ids` to process `text_embeds` and `speech_embeds` using
1576
+ `ClvpEncoder`.
1577
+
1578
+ Args:
1579
+ input_ids (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1580
+ Input text Tokens. Processed from the [`ClvpTokenizer`].
1581
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1582
+ Mask to avoid performing attention on padding text token indices. Mask values selected in `[0, 1]`:
1583
+
1584
+ - 1 for tokens that are **not masked**,
1585
+ - 0 for tokens that are **masked**.
1586
+
1587
+ [What are attention masks?](../glossary#attention-mask)
1588
+ generation_config (`~generation.GenerationConfig`, *optional*):
1589
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
1590
+ passed to generate matching the attributes of `generation_config` will override them. If
1591
+ `generation_config` is not provided, the default will be used, which had the following loading
1592
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
1593
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
1594
+ default values, whose documentation should be checked to parameterize generation.
1595
+ pad_to_max_mel_tokens (`int`, *optional*):
1596
+ Pads generated speech_ids to the specified value. This is to implement the same logic from the official
1597
+ repo, link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L430
1598
+ and to make sure the logits are same.
1599
+ This does not affect generation quality so please don't consider using it since it is less efficient.
1600
+ output_hidden_states (`bool`, *optional*):
1601
+ Whether or not to return the hidden states of decoder model, text encoder and speech encoder models.
1602
+
1603
+ Returns:
1604
+ `ClvpOutput` or tuple: A `ClvpOutput` (if `return_dict_in_generate=True` or when
1605
+ `config.return_dict_in_generate=True`) or a tuple.
1606
+ """
1607
+
1608
+ # If the input sequences are larger than (self.config.decoder_config.max_text_tokens - 3) then raise error,
1609
+ # because we need to add 3 tokens ( 1 bos tokens and 2 eos tokens) to the input_ids in ClvpConditioningEncoder to
1610
+ # properly sample
1611
+ sequence_length = input_ids.shape[-1]
1612
+ if sequence_length > (self.config.decoder_config.max_text_tokens - 3):
1613
+ raise ValueError(
1614
+ f"Maximum sequence length reached! Found input_ids of length {sequence_length}."
1615
+ f"Please make sure that the maximum length of input_ids is {self.config.decoder_config.max_text_tokens - 3}"
1616
+ )
1617
+
1618
+ if generation_config is None:
1619
+ generation_config = self.generation_config
1620
+
1621
+ generation_config = copy.deepcopy(generation_config)
1622
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
1623
+ generation_config.validate()
1624
+ self._validate_model_kwargs(model_kwargs.copy())
1625
+
1626
+ # pad input_ids as specified in the original repo
1627
+ # link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L380
1628
+ input_ids, attention_mask = _pad_extra_bos_eos_tokens(
1629
+ input_ids,
1630
+ attention_mask,
1631
+ add_bos_token=False,
1632
+ bos_token_id=self.config.text_config.bos_token_id,
1633
+ eos_token_id=self.config.text_config.eos_token_id,
1634
+ )
1635
+
1636
+ conditioning_embeds = self.conditioning_encoder(
1637
+ input_features=input_features,
1638
+ input_ids=input_ids,
1639
+ attention_mask=attention_mask,
1640
+ )
1641
+
1642
+ decoder_outputs = self.speech_decoder_model.generate(
1643
+ conditioning_embeds=conditioning_embeds,
1644
+ generation_config=generation_config,
1645
+ output_hidden_states=output_hidden_states,
1646
+ )
1647
+ if isinstance(decoder_outputs, ModelOutput):
1648
+ speech_ids = decoder_outputs.sequences
1649
+
1650
+ # pad to pad_to_max_mel_tokens if given, to replicate the original repo logic
1651
+ # link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L430
1652
+ if pad_to_max_mel_tokens is not None:
1653
+ padding_needed = pad_to_max_mel_tokens - speech_ids.shape[-1]
1654
+ speech_ids = torch.nn.functional.pad(
1655
+ speech_ids, (0, padding_needed), value=self.generation_config.eos_token_id
1656
+ )
1657
+
1658
+ speech_ids = self.fix_speech_decoder_output(speech_ids)
1659
+
1660
+ speech_outputs: ClvpEncoderOutput = self.speech_encoder_model(
1661
+ input_ids=speech_ids,
1662
+ output_hidden_states=output_hidden_states,
1663
+ return_dict=generation_config.return_dict_in_generate,
1664
+ )
1665
+ text_outputs: ClvpEncoderOutput = self.text_encoder_model(
1666
+ input_ids=input_ids,
1667
+ attention_mask=attention_mask,
1668
+ output_hidden_states=output_hidden_states,
1669
+ return_dict=generation_config.return_dict_in_generate,
1670
+ )
1671
+
1672
+ speech_embeds = speech_outputs.embeds
1673
+ text_embeds = text_outputs.embeds
1674
+
1675
+ # normalized features
1676
+ speech_embeds = speech_embeds / speech_embeds.norm(p=2, dim=-1, keepdim=True)
1677
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1678
+
1679
+ # cosine similarity as logits
1680
+ logit_scale = self.logit_scale.exp()
1681
+ logits_per_text = torch.matmul(text_embeds, speech_embeds.t()) * logit_scale
1682
+ logits_per_speech = logits_per_text.t()
1683
+
1684
+ if not generation_config.return_dict_in_generate:
1685
+ output = (
1686
+ speech_ids,
1687
+ logits_per_speech,
1688
+ logits_per_text,
1689
+ text_embeds,
1690
+ speech_embeds,
1691
+ text_outputs.pooler_output,
1692
+ speech_outputs.pooler_output,
1693
+ )
1694
+ if output_hidden_states:
1695
+ output += (
1696
+ decoder_outputs[-1],
1697
+ text_outputs.hidden_states,
1698
+ speech_outputs.hidden_states,
1699
+ )
1700
+
1701
+ return output
1702
+
1703
+ return ClvpOutput(
1704
+ speech_ids=speech_ids,
1705
+ logits_per_speech=logits_per_speech,
1706
+ logits_per_text=logits_per_text,
1707
+ text_embeds=text_embeds,
1708
+ speech_embeds=speech_embeds,
1709
+ text_model_output=text_outputs.pooler_output,
1710
+ speech_model_output=speech_outputs.pooler_output,
1711
+ decoder_hidden_states=decoder_outputs.hidden_states,
1712
+ text_encoder_hidden_states=text_outputs.hidden_states,
1713
+ speech_encoder_hidden_states=speech_outputs.hidden_states,
1714
+ )
1715
+
1716
+
1717
+ __all__ = [
1718
+ "ClvpModelForConditionalGeneration",
1719
+ "ClvpForCausalLM",
1720
+ "ClvpModel",
1721
+ "ClvpPreTrainedModel",
1722
+ "ClvpEncoder",
1723
+ "ClvpDecoder",
1724
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/number_normalizer.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """English Normalizer class for CLVP."""
16
+
17
+ import sys
18
+
19
+
20
+ if sys.version_info >= (3, 11):
21
+ # Atomic grouping support was only added to the core RE in Python 3.11
22
+ import re
23
+ else:
24
+ import regex as re
25
+
26
+
27
+ class EnglishNormalizer:
28
+ def __init__(self):
29
+ # List of (regular expression, replacement) pairs for abbreviations:
30
+ self._abbreviations = [
31
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
32
+ for x in [
33
+ ("mrs", "misess"),
34
+ ("mr", "mister"),
35
+ ("dr", "doctor"),
36
+ ("st", "saint"),
37
+ ("co", "company"),
38
+ ("jr", "junior"),
39
+ ("maj", "major"),
40
+ ("gen", "general"),
41
+ ("drs", "doctors"),
42
+ ("rev", "reverend"),
43
+ ("lt", "lieutenant"),
44
+ ("hon", "honorable"),
45
+ ("sgt", "sergeant"),
46
+ ("capt", "captain"),
47
+ ("esq", "esquire"),
48
+ ("ltd", "limited"),
49
+ ("col", "colonel"),
50
+ ("ft", "fort"),
51
+ ]
52
+ ]
53
+
54
+ self.ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
55
+ self.teens = [
56
+ "ten",
57
+ "eleven",
58
+ "twelve",
59
+ "thirteen",
60
+ "fourteen",
61
+ "fifteen",
62
+ "sixteen",
63
+ "seventeen",
64
+ "eighteen",
65
+ "nineteen",
66
+ ]
67
+ self.tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
68
+
69
+ def number_to_words(self, num: int) -> str:
70
+ """
71
+ Converts numbers(`int`) to words(`str`).
72
+
73
+ Please note that it only supports upto - "'nine hundred ninety-nine quadrillion, nine hundred ninety-nine
74
+ trillion, nine hundred ninety-nine billion, nine hundred ninety-nine million, nine hundred ninety-nine
75
+ thousand, nine hundred ninety-nine'" or `number_to_words(999_999_999_999_999_999)`.
76
+ """
77
+ if num == 0:
78
+ return "zero"
79
+ elif num < 0:
80
+ return "minus " + self.number_to_words(abs(num))
81
+ elif num < 10:
82
+ return self.ones[num]
83
+ elif num < 20:
84
+ return self.teens[num - 10]
85
+ elif num < 100:
86
+ return self.tens[num // 10] + ("-" + self.number_to_words(num % 10) if num % 10 != 0 else "")
87
+ elif num < 1000:
88
+ return (
89
+ self.ones[num // 100] + " hundred" + (" " + self.number_to_words(num % 100) if num % 100 != 0 else "")
90
+ )
91
+ elif num < 1_000_000:
92
+ return (
93
+ self.number_to_words(num // 1000)
94
+ + " thousand"
95
+ + (", " + self.number_to_words(num % 1000) if num % 1000 != 0 else "")
96
+ )
97
+ elif num < 1_000_000_000:
98
+ return (
99
+ self.number_to_words(num // 1_000_000)
100
+ + " million"
101
+ + (", " + self.number_to_words(num % 1_000_000) if num % 1_000_000 != 0 else "")
102
+ )
103
+ elif num < 1_000_000_000_000:
104
+ return (
105
+ self.number_to_words(num // 1_000_000_000)
106
+ + " billion"
107
+ + (", " + self.number_to_words(num % 1_000_000_000) if num % 1_000_000_000 != 0 else "")
108
+ )
109
+ elif num < 1_000_000_000_000_000:
110
+ return (
111
+ self.number_to_words(num // 1_000_000_000_000)
112
+ + " trillion"
113
+ + (", " + self.number_to_words(num % 1_000_000_000_000) if num % 1_000_000_000_000 != 0 else "")
114
+ )
115
+ elif num < 1_000_000_000_000_000_000:
116
+ return (
117
+ self.number_to_words(num // 1_000_000_000_000_000)
118
+ + " quadrillion"
119
+ + (
120
+ ", " + self.number_to_words(num % 1_000_000_000_000_000)
121
+ if num % 1_000_000_000_000_000 != 0
122
+ else ""
123
+ )
124
+ )
125
+ else:
126
+ return "number out of range"
127
+
128
+ def convert_to_ascii(self, text: str) -> str:
129
+ """
130
+ Converts unicode to ascii
131
+ """
132
+ return text.encode("ascii", "ignore").decode("utf-8")
133
+
134
+ def _expand_dollars(self, m: str) -> str:
135
+ """
136
+ This method is used to expand numerical dollar values into spoken words.
137
+ """
138
+ match = m.group(1)
139
+ parts = match.split(".")
140
+ if len(parts) > 2:
141
+ return match + " dollars" # Unexpected format
142
+
143
+ dollars = int(parts[0]) if parts[0] else 0
144
+ cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
145
+ if dollars and cents:
146
+ dollar_unit = "dollar" if dollars == 1 else "dollars"
147
+ cent_unit = "cent" if cents == 1 else "cents"
148
+ return "%s %s, %s %s" % (dollars, dollar_unit, cents, cent_unit)
149
+ elif dollars:
150
+ dollar_unit = "dollar" if dollars == 1 else "dollars"
151
+ return "%s %s" % (dollars, dollar_unit)
152
+ elif cents:
153
+ cent_unit = "cent" if cents == 1 else "cents"
154
+ return "%s %s" % (cents, cent_unit)
155
+ else:
156
+ return "zero dollars"
157
+
158
+ def _remove_commas(self, m: str) -> str:
159
+ """
160
+ This method is used to remove commas from sentences.
161
+ """
162
+ return m.group(1).replace(",", "")
163
+
164
+ def _expand_decimal_point(self, m: str) -> str:
165
+ """
166
+ This method is used to expand '.' into spoken word ' point '.
167
+ """
168
+ return m.group(1).replace(".", " point ")
169
+
170
+ def _expand_ordinal(self, num: str) -> str:
171
+ """
172
+ This method is used to expand ordinals such as '1st', '2nd' into spoken words.
173
+ """
174
+ ordinal_suffixes = {1: "st", 2: "nd", 3: "rd"}
175
+
176
+ num = int(num.group(0)[:-2])
177
+ if num % 100 >= 10 and num % 100 <= 20:
178
+ suffix = "th"
179
+ else:
180
+ suffix = ordinal_suffixes.get(num % 10, "th")
181
+ return self.number_to_words(num) + suffix
182
+
183
+ def _expand_number(self, m: str) -> str:
184
+ """
185
+ This method acts as a preprocessing step for numbers between 1000 and 3000 (same as the original repository,
186
+ link :
187
+ https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/utils/tokenizer.py#L86)
188
+ """
189
+ num = int(m.group(0))
190
+
191
+ if num > 1000 and num < 3000:
192
+ if num == 2000:
193
+ return "two thousand"
194
+ elif num > 2000 and num < 2010:
195
+ return "two thousand " + self.number_to_words(num % 100)
196
+ elif num % 100 == 0:
197
+ return self.number_to_words(num // 100) + " hundred"
198
+ else:
199
+ return self.number_to_words(num)
200
+ else:
201
+ return self.number_to_words(num)
202
+
203
+ def normalize_numbers(self, text: str) -> str:
204
+ """
205
+ This method is used to normalize numbers within a text such as converting the numbers to words, removing
206
+ commas, etc.
207
+ """
208
+ text = re.sub(r"([0-9][0-9,]+[0-9])", self._remove_commas, text)
209
+ text = re.sub(r"£([0-9,]*[0-9])", r"\1 pounds", text)
210
+ text = re.sub(r"\$([0-9.,]*[0-9])", self._expand_dollars, text)
211
+ text = re.sub(r"([0-9]++\.[0-9]+)", self._expand_decimal_point, text)
212
+ text = re.sub(r"[0-9]++(st|nd|rd|th)", self._expand_ordinal, text)
213
+ text = re.sub(r"[0-9]+", self._expand_number, text)
214
+ return text
215
+
216
+ def expand_abbreviations(self, text: str) -> str:
217
+ """
218
+ Expands the abbreviate words.
219
+ """
220
+ for regex, replacement in self._abbreviations:
221
+ text = re.sub(regex, replacement, text)
222
+ return text
223
+
224
+ def collapse_whitespace(self, text: str) -> str:
225
+ """
226
+ Removes multiple whitespaces
227
+ """
228
+ return re.sub(re.compile(r"\s+"), " ", text)
229
+
230
+ def __call__(self, text):
231
+ """
232
+ Converts text to ascii, numbers / number-like quantities to their spelt-out counterparts and expands
233
+ abbreviations
234
+ """
235
+
236
+ text = self.convert_to_ascii(text)
237
+ text = text.lower()
238
+ text = self.normalize_numbers(text)
239
+ text = self.expand_abbreviations(text)
240
+ text = self.collapse_whitespace(text)
241
+ text = text.replace('"', "")
242
+
243
+ return text
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/processing_clvp.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """
16
+ Processor class for CLVP
17
+ """
18
+
19
+ from ...processing_utils import ProcessorMixin
20
+ from ...utils import auto_docstring, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ @auto_docstring
27
+ class ClvpProcessor(ProcessorMixin):
28
+ def __init__(self, feature_extractor, tokenizer):
29
+ super().__init__(feature_extractor, tokenizer)
30
+
31
+ @auto_docstring
32
+ def __call__(self, *args, **kwargs):
33
+ raw_speech = kwargs.pop("raw_speech", None)
34
+ if raw_speech is not None:
35
+ logger.warning(
36
+ "Using `raw_speech` keyword argument is deprecated when calling ClvpProcessor, instead use `audio`."
37
+ )
38
+ kwargs["audio"] = raw_speech
39
+ return super().__call__(*args, **kwargs)
40
+
41
+
42
+ __all__ = ["ClvpProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/tokenization_clvp.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """Tokenization class for CLVP."""
15
+
16
+ import json
17
+ from functools import lru_cache
18
+
19
+ import regex as re
20
+
21
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
22
+ from ...utils import logging
23
+ from .number_normalizer import EnglishNormalizer
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {
29
+ "vocab_file": "vocab.json",
30
+ "merges_file": "merges.txt",
31
+ }
32
+
33
+
34
+ @lru_cache
35
+ def bytes_to_unicode():
36
+ """
37
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
38
+ characters the bpe code barfs on.
39
+
40
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
41
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
42
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
43
+ tables between utf-8 bytes and unicode strings.
44
+ """
45
+ bs = (
46
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
47
+ )
48
+ cs = bs[:]
49
+ n = 0
50
+ for b in range(2**8):
51
+ if b not in bs:
52
+ bs.append(b)
53
+ cs.append(2**8 + n)
54
+ n += 1
55
+ cs = [chr(n) for n in cs]
56
+ return dict(zip(bs, cs))
57
+
58
+
59
+ def get_pairs(word):
60
+ """
61
+ Return set of symbol pairs in a word.
62
+
63
+ Word is represented as tuple of symbols (symbols being variable-length strings).
64
+ """
65
+ pairs = set()
66
+ prev_char = word[0]
67
+ for char in word[1:]:
68
+ pairs.add((prev_char, char))
69
+ prev_char = char
70
+ return pairs
71
+
72
+
73
+ class ClvpTokenizer(PreTrainedTokenizer):
74
+ """
75
+ Construct a CLVP tokenizer. Based on byte-level Byte-Pair-Encoding.
76
+
77
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
78
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
79
+
80
+ ```python
81
+ >>> from transformers import ClvpTokenizer
82
+
83
+ >>> tokenizer = ClvpTokenizer.from_pretrained("susnato/clvp_dev")
84
+ >>> tokenizer("Hello world")["input_ids"]
85
+ [62, 84, 28, 2, 179, 79]
86
+
87
+ >>> tokenizer(" Hello world")["input_ids"]
88
+ [2, 62, 84, 28, 2, 179, 79]
89
+ ```
90
+
91
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
92
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
93
+
94
+ <Tip>
95
+
96
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
97
+
98
+ </Tip>
99
+
100
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
101
+ this superclass for more information regarding those methods.
102
+
103
+ Args:
104
+ vocab_file (`str`):
105
+ Path to the vocabulary file.
106
+ merges_file (`str`):
107
+ Path to the merges file.
108
+ errors (`str`, *optional*, defaults to `"replace"`):
109
+ Paradigm to follow when decoding bytes to UTF-8. See
110
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
111
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
112
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
113
+ token instead.
114
+ bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
115
+ The beginning of sequence token.
116
+ eos_token (`str`, *optional*, defaults to `"[STOP]"`):
117
+ The end of sequence token.
118
+ pad_token (`str`, *optional*, defaults to `"[STOP]"`):
119
+ The pad token of the sequence.
120
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
121
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
122
+ other word. (CLVP tokenizer detect beginning of words by the preceding space).
123
+ """
124
+
125
+ vocab_files_names = VOCAB_FILES_NAMES
126
+ model_input_names = [
127
+ "input_ids",
128
+ "attention_mask",
129
+ ]
130
+
131
+ def __init__(
132
+ self,
133
+ vocab_file,
134
+ merges_file,
135
+ errors="replace",
136
+ unk_token="[UNK]",
137
+ bos_token="<|endoftext|>",
138
+ eos_token="[STOP]",
139
+ pad_token="[STOP]",
140
+ add_prefix_space=False,
141
+ **kwargs,
142
+ ):
143
+ bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
144
+ eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
145
+ unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
146
+ pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
147
+
148
+ self._normalizer = None
149
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
150
+ self.encoder = json.load(vocab_handle)
151
+ self.decoder = {v: k for k, v in self.encoder.items()}
152
+ self.errors = errors # how to handle errors in decoding
153
+ self.byte_encoder = bytes_to_unicode()
154
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
155
+ with open(merges_file, encoding="utf-8") as merges_handle:
156
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
157
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
158
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
159
+ self.cache = {}
160
+ self.add_prefix_space = add_prefix_space
161
+
162
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
163
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
164
+
165
+ super().__init__(
166
+ errors=errors,
167
+ unk_token=unk_token,
168
+ bos_token=bos_token,
169
+ eos_token=eos_token,
170
+ pad_token=pad_token,
171
+ add_prefix_space=add_prefix_space,
172
+ special_tokens_pattern="none",
173
+ **kwargs,
174
+ )
175
+
176
+ @property
177
+ def vocab_size(self):
178
+ return len(self.encoder)
179
+
180
+ @property
181
+ def normalizer(self):
182
+ if self._normalizer is None:
183
+ self._normalizer = EnglishNormalizer()
184
+ return self._normalizer
185
+
186
+ def get_vocab(self):
187
+ return dict(self.encoder, **self.added_tokens_encoder)
188
+
189
+ def bpe(self, token):
190
+ if token in self.cache:
191
+ return self.cache[token]
192
+ word = tuple(token)
193
+ pairs = get_pairs(word)
194
+
195
+ if not pairs:
196
+ return token
197
+
198
+ while True:
199
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
200
+ if bigram not in self.bpe_ranks:
201
+ break
202
+ first, second = bigram
203
+ new_word = []
204
+ i = 0
205
+ while i < len(word):
206
+ try:
207
+ j = word.index(first, i)
208
+ except ValueError:
209
+ new_word.extend(word[i:])
210
+ break
211
+ else:
212
+ new_word.extend(word[i:j])
213
+ i = j
214
+
215
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
216
+ new_word.append(first + second)
217
+ i += 2
218
+ else:
219
+ new_word.append(word[i])
220
+ i += 1
221
+ new_word = tuple(new_word)
222
+ word = new_word
223
+ if len(word) == 1:
224
+ break
225
+ else:
226
+ pairs = get_pairs(word)
227
+ word = " ".join(word)
228
+ self.cache[token] = word
229
+ return word
230
+
231
+ def _tokenize(self, text):
232
+ """Tokenize a string."""
233
+ bpe_tokens = []
234
+ text = self.normalizer(text)
235
+ for token in re.findall(self.pat, text):
236
+ token = "".join(
237
+ self.byte_encoder[b] for b in token.encode("utf-8")
238
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
239
+
240
+ # if the token is "Ġ" we replace it with "[SPACE]" (if "[SPACE]" is present in the vocab), otherwise we keep the "Ġ".
241
+ bpe_tokens.extend(
242
+ "[SPACE]" if bpe_token == "\u0120" and "[SPACE]" in self.encoder else bpe_token
243
+ for bpe_token in self.bpe(token).split(" ")
244
+ )
245
+
246
+ return bpe_tokens
247
+
248
+ def _convert_token_to_id(self, token):
249
+ """Converts a token (str) in an id using the vocab."""
250
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
251
+
252
+ def _convert_id_to_token(self, index):
253
+ """Converts an index (integer) in a token (str) using the vocab."""
254
+ return self.decoder.get(index)
255
+
256
+ def convert_tokens_to_string(self, tokens):
257
+ """Converts a sequence of tokens (string) in a single string."""
258
+ text = "".join(tokens)
259
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
260
+ return text
261
+
262
+ def clean_up_tokenization(self, text):
263
+ text = "".join(text) if isinstance(text, list) else text
264
+ vocab_tokens = list(self.encoder.keys()) + list(self.added_tokens_encoder.keys())
265
+
266
+ text = text.replace("[SPACE]", " ") if "[SPACE]" in vocab_tokens else text
267
+ text = text.replace("[STOP]", " ") if "[STOP]" in vocab_tokens else text
268
+
269
+ text = text.replace(self.unk_token, "").replace(" ", " ").replace(" ", " ")
270
+ return text
271
+
272
+
273
+ __all__ = ["ClvpTokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/code_llama/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_code_llama import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/code_llama/tokenization_code_llama.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
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
+
16
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
17
+ from tokenizers.models import BPE
18
+
19
+ from ...tokenization_utils_tokenizers import TokenizersBackend
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
25
+
26
+ SPIECE_UNDERLINE = "▁"
27
+
28
+ B_INST, E_INST = "[INST]", "[/INST]"
29
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
30
+
31
+ # fmt: off
32
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
33
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
34
+ that your responses are socially unbiased and positive in nature.
35
+
36
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
37
+ correct. If you don't know the answer to a question, please don't share false information."""
38
+ # fmt: on
39
+
40
+
41
+ class CodeLlamaTokenizer(TokenizersBackend):
42
+ """
43
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
44
+
45
+ This uses notably ByteFallback and no normalization.
46
+
47
+ ```python
48
+ >>> from transformers import CodeLlamaTokenizer
49
+
50
+ >>> tokenizer = CodeLlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
51
+ >>> tokenizer.encode("Hello this is a test")
52
+ [1, 15043, 445, 338, 263, 1243]
53
+ ```
54
+
55
+ If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
56
+ call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
57
+ values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
58
+ [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
59
+
60
+
61
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
62
+ refer to this superclass for more information regarding those methods. The default configuration match that of
63
+ [meta-llama/CodeLlama-7b-Instruct-hf](https://huggingface.co/meta-llama/CodeLlama-7b-Instruct-hf/blob/main/tokenizer_config.json)
64
+ which supports prompt infilling.
65
+
66
+ Args:
67
+ clean_up_tokenization_spaces (`str`, *optional*, defaults to `False`):
68
+ Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra
69
+ spaces.
70
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
71
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
72
+ token instead.
73
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
74
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
75
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
76
+ The end of sequence token.
77
+ prefix_token (`str`, *optional*, defaults to `"▁<PRE>"`):
78
+ Prefix token used for infilling.
79
+ middle_token (`str`, *optional*, defaults to `"▁<MID>"`):
80
+ Middle token used for infilling.
81
+ suffix_token (`str`, *optional*, defaults to `"▁<SUF>"`):
82
+ Suffix token used for infilling.
83
+ eot_token (`str`, *optional*, defaults to `"▁<EOT>"`):
84
+ End of text token used for infilling.
85
+ fill_token (`str`, *optional*, defaults to `"<FILL_ME>"`):
86
+ The token used to split the input between the prefix and suffix.
87
+ additional_special_tokens (`list[str]`, *optional*):
88
+ Additional special tokens used by the tokenizer.
89
+ add_bos_token (`bool`, *optional*, defaults to `True`):
90
+ Whether to add a beginning of sequence token at the start of sequences.
91
+ add_eos_token (`bool`, *optional*, defaults to `False`):
92
+ Whether to add an end of sequence token at the end of sequences.
93
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
94
+ Whether or not the default system prompt for Llama should be used.
95
+ add_prefix_space (`bool`, *optional*):
96
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
97
+ other word.
98
+ vocab (`str`, `dict` or `list`, *optional*):
99
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
100
+ merges (`str` or `list`, *optional*):
101
+ Custom merges list. If not provided, merges are loaded from merges_file.
102
+ vocab_file (`str`, *optional*):
103
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
104
+ contains the vocabulary necessary to instantiate a tokenizer.
105
+ """
106
+
107
+ vocab_files_names = VOCAB_FILES_NAMES
108
+ padding_side = "left"
109
+ model_input_names = ["input_ids", "attention_mask"]
110
+ model = BPE
111
+
112
+ def __init__(
113
+ self,
114
+ vocab: str | dict[str, int] | None = None,
115
+ merges: str | list[str] | None = None,
116
+ clean_up_tokenization_spaces=False,
117
+ unk_token="<unk>",
118
+ bos_token="<s>",
119
+ eos_token="</s>",
120
+ prefix_token="▁<PRE>",
121
+ middle_token="▁<MID>",
122
+ suffix_token="▁<SUF>",
123
+ eot_token="▁<EOT>",
124
+ fill_token="<FILL_ME>",
125
+ additional_special_tokens=None,
126
+ use_default_system_prompt: bool = False,
127
+ add_prefix_space: bool | None = True,
128
+ add_bos_token: bool = True,
129
+ **kwargs,
130
+ ):
131
+ self.add_prefix_space = add_prefix_space if add_prefix_space is not None else True
132
+ self.use_default_system_prompt = use_default_system_prompt
133
+ additional_special_tokens = additional_special_tokens or []
134
+ for token in [prefix_token, middle_token, suffix_token, eot_token, fill_token]:
135
+ additional_special_tokens += [token] if token is not None else []
136
+
137
+ self._vocab = (
138
+ vocab
139
+ if vocab is not None
140
+ else {
141
+ str(unk_token): 0,
142
+ str(bos_token): 1,
143
+ str(eos_token): 2,
144
+ }
145
+ )
146
+
147
+ self._merges = merges or []
148
+ self._tokenizer = Tokenizer(
149
+ BPE(
150
+ vocab=self._vocab,
151
+ merges=self._merges,
152
+ fuse_unk=True,
153
+ byte_fallback=True,
154
+ dropout=None,
155
+ unk_token=str(unk_token),
156
+ )
157
+ )
158
+ prepend_scheme = "first" if self.add_prefix_space else "never"
159
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(
160
+ replacement="▁", prepend_scheme=prepend_scheme, split=False
161
+ )
162
+
163
+ self._tokenizer.decoder = decoders.Sequence(
164
+ [decoders.Replace("▁", " "), decoders.ByteFallback(), decoders.Fuse(), decoders.Strip(content=" ", left=1)]
165
+ )
166
+
167
+ super().__init__(
168
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
169
+ unk_token=unk_token,
170
+ bos_token=bos_token,
171
+ eos_token=eos_token,
172
+ use_default_system_prompt=use_default_system_prompt,
173
+ add_prefix_space=add_prefix_space,
174
+ prefix_token=prefix_token,
175
+ middle_token=middle_token,
176
+ suffix_token=suffix_token,
177
+ eot_token=eot_token,
178
+ fill_token=fill_token,
179
+ add_bos_token=add_bos_token,
180
+ additional_special_tokens=additional_special_tokens,
181
+ **kwargs,
182
+ )
183
+ self._prefix_token = prefix_token
184
+ self._middle_token = middle_token
185
+ self._suffix_token = suffix_token
186
+ self._eot_token = eot_token
187
+ self.fill_token = fill_token
188
+
189
+ @property
190
+ def prefix_token(self):
191
+ return self._prefix_token
192
+
193
+ @property
194
+ def prefix_id(self):
195
+ if self._prefix_token is None:
196
+ return None
197
+ return self.convert_tokens_to_ids(self.prefix_token)
198
+
199
+ @property
200
+ def middle_token(self):
201
+ return self._middle_token
202
+
203
+ @property
204
+ def middle_id(self):
205
+ if self._middle_token is None:
206
+ return None
207
+ return self.convert_tokens_to_ids(self.middle_token)
208
+
209
+ @property
210
+ def suffix_token(self):
211
+ return self._suffix_token
212
+
213
+ @property
214
+ def suffix_id(self):
215
+ if self._suffix_token is None:
216
+ return None
217
+ return self.convert_tokens_to_ids(self.suffix_token)
218
+
219
+ @property
220
+ def eot_id(self):
221
+ if self._eot_token is None:
222
+ return None
223
+ return self.convert_tokens_to_ids(self.eot_token)
224
+
225
+ @property
226
+ def eot_token(self):
227
+ return self._eot_token
228
+
229
+ def set_infilling_processor(self, reset, suffix_first=False, add_special_tokens=True):
230
+ """
231
+ Updates the normalizer to make sure the prompt format for `infilling` is respected. The infilling format is the
232
+ following: if suffix_first
233
+ " <PRE> <SUF>{suf} <MID> {pre}"
234
+ else:
235
+ " <PRE> {pre} <SUF>{suf} <MID>"
236
+
237
+ If `reset` is set to `True`, the `normalizer` and `post_processor` are reset to their "normal" behaviour, which
238
+ is to add a prefix space for the normalizer, and add a `bos_token` to the input text for the `post_processor`.
239
+ """
240
+ if reset:
241
+ self._tokenizer.normalizer = normalizers.Sequence(
242
+ [
243
+ normalizers.Prepend(prepend="▁"),
244
+ normalizers.Replace(pattern=" ", content="▁"),
245
+ ]
246
+ )
247
+ self.update_post_processor()
248
+ return
249
+
250
+ self._tokenizer.normalizer = normalizers.Replace(pattern=" ", content="▁")
251
+ pair = [self.bos_token] if self.add_bos_token and add_special_tokens else []
252
+ special_tokens = [(self.bos_token, self.bos_token_id)] if self.add_bos_token and add_special_tokens else []
253
+ if suffix_first:
254
+ # format as " <PRE> <SUF>{suf} <MID> {pre}"
255
+ pair += [self.prefix_token, self.suffix_token, "$B", self.middle_token, "$A"]
256
+ special_tokens += [
257
+ (self.prefix_token, self.prefix_id),
258
+ (self.suffix_token, self.suffix_id),
259
+ (self.middle_token, self.middle_id),
260
+ ]
261
+ else:
262
+ # format as " <PRE> {pre} <SUF>{suf} <MID>"
263
+ pair += [self.prefix_token, "$A", self.suffix_token, "$B", self.middle_token]
264
+ special_tokens += [
265
+ (self.prefix_token, self.prefix_id),
266
+ (self.suffix_token, self.suffix_id),
267
+ (self.middle_token, self.middle_id),
268
+ ]
269
+
270
+ if self.add_eos_token and add_special_tokens:
271
+ pair += [self.eos_token]
272
+ special_tokens += [(self.eos_token, self.eos_token_id)]
273
+ self._tokenizer.post_processor = processors.TemplateProcessing(
274
+ single="$A", pair=pair, special_tokens=special_tokens
275
+ )
276
+
277
+ def tokenize(self, text, suffix=None, suffix_first=False, **kwargs):
278
+ # Handle fill_token splitting
279
+ if self.fill_token is not None and self.fill_token in text and suffix is None:
280
+ text, suffix = text.split(self.fill_token)
281
+
282
+ # If no suffix, use standard tokenization
283
+ if suffix is None or len(suffix) < 1:
284
+ return super().tokenize(text, **kwargs)
285
+
286
+ # Check that infilling tokens are available
287
+ if None in (self.prefix_id, self.middle_id, self.suffix_id):
288
+ raise ValueError(
289
+ "The input either includes a `prefix` and a `suffix` used for the infilling task,"
290
+ f" or can be split on the {self.fill_token} token, creating a suffix and prefix,"
291
+ " but the model does not support `infilling`."
292
+ )
293
+
294
+ # Temporarily set infilling processor
295
+ self.set_infilling_processor(False, suffix_first=suffix_first, add_special_tokens=False)
296
+
297
+ # Remove text_pair and pair from kwargs if present to avoid conflict
298
+ kwargs.pop("text_pair", None)
299
+ kwargs.pop("pair", None)
300
+
301
+ # Tokenize with infilling format
302
+ # The processor will handle the special token arrangement
303
+ # Use pair=suffix (not text_pair) since base class tokenize expects 'pair' parameter
304
+ result = super().tokenize(" " + text, pair=suffix, **kwargs)
305
+
306
+ # Reset processor
307
+ self.set_infilling_processor(True)
308
+
309
+ return result
310
+
311
+ def _encode_plus(self, text, text_pair=None, suffix=None, suffix_first=False, add_special_tokens=True, **kwargs):
312
+ is_infilling = False
313
+
314
+ if suffix is not None:
315
+ text_pair = suffix
316
+ is_infilling = True
317
+ elif "suffix" in kwargs:
318
+ text_pair = kwargs.pop("suffix")
319
+ is_infilling = True
320
+
321
+ if isinstance(text, str) and self.fill_token is not None and self.fill_token in text and text_pair is None:
322
+ text, text_pair = text.split(self.fill_token)
323
+ is_infilling = True
324
+
325
+ if not is_infilling:
326
+ return super()._encode_plus(text, text_pair=text_pair, add_special_tokens=add_special_tokens, **kwargs)
327
+
328
+ if (
329
+ text_pair is None
330
+ or (isinstance(text_pair, str) and len(text_pair) < 1)
331
+ or (isinstance(text_pair, list) and len(text_pair) == 0)
332
+ ):
333
+ return super()._encode_plus(text, text_pair=text_pair, add_special_tokens=add_special_tokens, **kwargs)
334
+
335
+ if None in (self.prefix_id, self.middle_id, self.suffix_id):
336
+ raise ValueError(
337
+ "The input includes a `prefix` and a `suffix` used for the infilling task,"
338
+ " the `prefix_id, middle_id, suffix_id` must all be initialized. Current"
339
+ f" values : {self.prefix_id, self.middle_id, self.suffix_id}"
340
+ )
341
+
342
+ self.set_infilling_processor(False, suffix_first=suffix_first, add_special_tokens=add_special_tokens)
343
+ kwargs.pop("text_pair", None)
344
+
345
+ if isinstance(text, str):
346
+ text = " " + text
347
+ elif isinstance(text, list):
348
+ text = [" " + t if isinstance(t, str) else t for t in text]
349
+
350
+ result = super()._encode_plus(text, text_pair=text_pair, add_special_tokens=True, **kwargs)
351
+ self.set_infilling_processor(True)
352
+ return result
353
+
354
+
355
+ __all__ = ["CodeLlamaTokenizer", "CodeLlamaTokenizerFast"]
356
+
357
+ # Backward alias
358
+ CodeLlamaTokenizerFast = CodeLlamaTokenizer
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from ..gpt2.tokenization_gpt2 import GPT2Tokenizer as CodeGenTokenizerFast
22
+ from .configuration_codegen import *
23
+ from .modeling_codegen import *
24
+ from .tokenization_codegen import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/configuration_codegen.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Salesforce authors, The EleutherAI, and HuggingFace Teams. 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
+ """CodeGen model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="Salesforce/codegen-2B-mono")
23
+ @strict
24
+ class CodeGenConfig(PreTrainedConfig):
25
+ r"""
26
+ n_ctx (`int`, *optional*, defaults to 2048):
27
+ This attribute is used in `CodeGenModel.__init__` without any real effect.
28
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
29
+ rotary_dim (`int`, *optional*, defaults to 64):
30
+ Number of dimensions in the embedding that Rotary Position Embedding is applied to.
31
+ n_inner (`int`, *optional*):
32
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
33
+
34
+ Example:
35
+
36
+ ```python
37
+ >>> from transformers import CodeGenConfig, CodeGenModel
38
+
39
+ >>> # Initializing a CodeGen 6B configuration
40
+ >>> configuration = CodeGenConfig()
41
+
42
+ >>> # Initializing a model (with random weights) from the configuration
43
+ >>> model = CodeGenModel(configuration)
44
+
45
+ >>> # Accessing the model configuration
46
+ >>> configuration = model.config
47
+ ```"""
48
+
49
+ model_type = "codegen"
50
+ attribute_map = {
51
+ "max_position_embeddings": "n_positions",
52
+ "hidden_size": "n_embd",
53
+ "num_attention_heads": "n_head",
54
+ "num_hidden_layers": "n_layer",
55
+ }
56
+
57
+ vocab_size: int = 50400
58
+ n_positions: int = 2048
59
+ n_ctx: int = 2048
60
+ n_embd: int = 4096
61
+ n_layer: int = 28
62
+ n_head: int = 16
63
+ rotary_dim: int = 64
64
+ n_inner: int | None = None
65
+ activation_function: str = "gelu_new"
66
+ resid_pdrop: float | int = 0.0
67
+ embd_pdrop: float | int = 0.0
68
+ attn_pdrop: float | int = 0.0
69
+ layer_norm_epsilon: float = 1e-5
70
+ initializer_range: float = 0.02
71
+ use_cache: bool = True
72
+ bos_token_id: int | None = 50256
73
+ eos_token_id: int | list[int] | None = 50256
74
+ tie_word_embeddings: bool = False
75
+
76
+
77
+ __all__ = ["CodeGenConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/modeling_codegen.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Salesforce authors, The EleutherAI, and HuggingFace Teams. 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
+ """PyTorch CodeGen model."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ... import initialization as init
22
+ from ...activations import ACT2FN
23
+ from ...cache_utils import Cache, DynamicCache
24
+ from ...generation import GenerationMixin
25
+ from ...masking_utils import create_causal_mask
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ auto_docstring,
31
+ logging,
32
+ )
33
+ from .configuration_codegen import CodeGenConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ # Copied from transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
40
+ def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
41
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64) / dim))
42
+ sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.int64).float(), inv_freq).float()
43
+ return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
44
+
45
+
46
+ # Copied from transformers.models.gptj.modeling_gptj.rotate_every_two
47
+ def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
48
+ x1 = x[:, :, :, ::2]
49
+ x2 = x[:, :, :, 1::2]
50
+ x = torch.stack((-x2, x1), dim=-1)
51
+ return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
52
+
53
+
54
+ # Copied from transformers.models.gptj.modeling_gptj.apply_rotary_pos_emb
55
+ def apply_rotary_pos_emb(tensor: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
56
+ sin = torch.repeat_interleave(sin[:, :, None, :], 2, 3)
57
+ cos = torch.repeat_interleave(cos[:, :, None, :], 2, 3)
58
+ return (tensor * cos) + (rotate_every_two(tensor) * sin)
59
+
60
+
61
+ class CodeGenAttention(nn.Module):
62
+ def __init__(self, config, layer_idx=None):
63
+ super().__init__()
64
+
65
+ self.max_positions = config.max_position_embeddings
66
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
67
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
68
+ self.layer_idx = layer_idx
69
+ if layer_idx is None:
70
+ logger.warning_once(
71
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
72
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
73
+ "when creating this class."
74
+ )
75
+
76
+ self.embed_dim = config.hidden_size
77
+ self.num_attention_heads = config.num_attention_heads
78
+ self.head_dim = self.embed_dim // self.num_attention_heads
79
+ if self.head_dim * self.num_attention_heads != self.embed_dim:
80
+ raise ValueError(
81
+ f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
82
+ f" `num_attention_heads`: {self.num_attention_heads})."
83
+ )
84
+ self.scale_attn = math.sqrt(self.head_dim)
85
+ self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
86
+
87
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
88
+ self.rotary_dim = config.rotary_dim
89
+ self.pos_embd_dim = self.rotary_dim or self.embed_dim
90
+ self.register_buffer(
91
+ "embed_positions", create_sinusoidal_positions(self.max_positions, self.pos_embd_dim), persistent=False
92
+ )
93
+
94
+ def _split_heads(self, x, n_head, dim_head, mp_num):
95
+ reshaped = x.reshape(x.shape[:-1] + (n_head // mp_num, dim_head))
96
+ reshaped = reshaped.reshape(x.shape[:-2] + (-1,) + reshaped.shape[-1:])
97
+ return reshaped
98
+
99
+ def _merge_heads(self, tensor, num_attention_heads, attn_head_size):
100
+ """
101
+ Merges attn_head_size dim and num_attn_heads dim into n_ctx
102
+ """
103
+ if len(tensor.shape) == 5:
104
+ tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
105
+ elif len(tensor.shape) == 4:
106
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
107
+ else:
108
+ raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}")
109
+ new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
110
+ return tensor.view(new_shape)
111
+
112
+ def _attn(
113
+ self,
114
+ query,
115
+ key,
116
+ value,
117
+ attention_mask=None,
118
+ ):
119
+ # Keep the attention weights computation in fp32 to avoid overflow issues
120
+ query = query.to(torch.float32)
121
+ key = key.to(torch.float32)
122
+
123
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
124
+
125
+ if attention_mask is not None:
126
+ attn_weights = attn_weights + attention_mask
127
+
128
+ attn_weights = attn_weights / self.scale_attn
129
+ attn_weights = nn.Softmax(dim=-1)(attn_weights)
130
+ attn_weights = attn_weights.to(value.dtype)
131
+ attn_weights = self.attn_dropout(attn_weights)
132
+
133
+ attn_output = torch.matmul(attn_weights, value)
134
+
135
+ return attn_output, attn_weights
136
+
137
+ def forward(
138
+ self,
139
+ hidden_states: torch.FloatTensor | None,
140
+ layer_past: Cache | None = None,
141
+ attention_mask: torch.FloatTensor | None = None,
142
+ position_ids: torch.LongTensor | None = None,
143
+ use_cache: bool | None = False,
144
+ output_attentions: bool | None = False,
145
+ ) -> (
146
+ tuple[torch.Tensor, tuple[torch.Tensor]]
147
+ | tuple[torch.Tensor, tuple[torch.Tensor], tuple[torch.Tensor, ...]]
148
+ | None
149
+ ):
150
+ qkv = self.qkv_proj(hidden_states)
151
+ # TODO(enijkamp): factor out number of logical TPU-v4 cores or make forward pass agnostic
152
+ mp_num = 4
153
+ qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1))
154
+
155
+ local_dim = self.head_dim * self.num_attention_heads // mp_num
156
+ query, value, key = torch.split(qkv_split, local_dim, dim=-1)
157
+ query = self._split_heads(query, self.num_attention_heads, self.head_dim, mp_num=mp_num)
158
+ key = self._split_heads(key, self.num_attention_heads, self.head_dim, mp_num=mp_num)
159
+
160
+ value = self._split_heads(value, self.num_attention_heads, self.head_dim, mp_num=mp_num)
161
+ value = value.permute(0, 2, 1, 3)
162
+
163
+ embed_positions = self.embed_positions
164
+ if embed_positions.device != position_ids.device:
165
+ embed_positions = embed_positions.to(position_ids.device)
166
+ self.embed_positions = embed_positions
167
+
168
+ sincos = embed_positions[position_ids]
169
+ sin, cos = torch.split(sincos, sincos.shape[-1] // 2, dim=-1)
170
+
171
+ if self.rotary_dim is not None:
172
+ k_rot = key[:, :, :, : self.rotary_dim]
173
+ k_pass = key[:, :, :, self.rotary_dim :]
174
+
175
+ q_rot = query[:, :, :, : self.rotary_dim]
176
+ q_pass = query[:, :, :, self.rotary_dim :]
177
+
178
+ k_rot = apply_rotary_pos_emb(k_rot, sin, cos)
179
+ q_rot = apply_rotary_pos_emb(q_rot, sin, cos)
180
+
181
+ key = torch.cat([k_rot, k_pass], dim=-1)
182
+ query = torch.cat([q_rot, q_pass], dim=-1)
183
+ else:
184
+ key = apply_rotary_pos_emb(key, sin, cos)
185
+ query = apply_rotary_pos_emb(query, sin, cos)
186
+
187
+ key = key.permute(0, 2, 1, 3)
188
+ query = query.permute(0, 2, 1, 3)
189
+
190
+ # Note that this cast is quite ugly, but is not implemented before ROPE as k_rot in the original codebase is always in fp32.
191
+ # Reference: https://github.com/salesforce/CodeGen/blob/f210c3bb1216c975ad858cd4132c0fdeabf4bfc2/codegen1/jaxformer/hf/codegen/modeling_codegen.py#L38
192
+ if layer_past is not None:
193
+ key, value = layer_past.update(key.to(hidden_states.dtype), value, self.layer_idx)
194
+
195
+ # compute self-attention: V x Softmax(QK^T)
196
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask)
197
+
198
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_dim)
199
+ attn_output = self.out_proj(attn_output)
200
+ attn_output = self.resid_dropout(attn_output)
201
+ return attn_output, attn_weights
202
+
203
+
204
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJMLP with GPTJ->CodeGen
205
+ class CodeGenMLP(nn.Module):
206
+ def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
207
+ super().__init__()
208
+ embed_dim = config.n_embd
209
+
210
+ self.fc_in = nn.Linear(embed_dim, intermediate_size)
211
+ self.fc_out = nn.Linear(intermediate_size, embed_dim)
212
+
213
+ self.act = ACT2FN[config.activation_function]
214
+ self.dropout = nn.Dropout(config.resid_pdrop)
215
+
216
+ def forward(self, hidden_states: torch.FloatTensor | None) -> torch.FloatTensor:
217
+ hidden_states = self.fc_in(hidden_states)
218
+ hidden_states = self.act(hidden_states)
219
+ hidden_states = self.fc_out(hidden_states)
220
+ hidden_states = self.dropout(hidden_states)
221
+ return hidden_states
222
+
223
+
224
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJBlock with GPTJ->CodeGen
225
+ class CodeGenBlock(GradientCheckpointingLayer):
226
+ # Ignore copy
227
+ def __init__(self, config, layer_idx=None):
228
+ super().__init__()
229
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
230
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
231
+ self.attn = CodeGenAttention(config, layer_idx)
232
+ self.mlp = CodeGenMLP(inner_dim, config)
233
+
234
+ def forward(
235
+ self,
236
+ hidden_states: torch.FloatTensor | None,
237
+ layer_past: Cache | None = None,
238
+ attention_mask: torch.FloatTensor | None = None,
239
+ position_ids: torch.LongTensor | None = None,
240
+ use_cache: bool | None = False,
241
+ output_attentions: bool | None = False,
242
+ **kwargs,
243
+ ) -> tuple[torch.Tensor] | tuple[torch.Tensor, tuple[torch.FloatTensor, ...]] | None:
244
+ residual = hidden_states
245
+ hidden_states = self.ln_1(hidden_states)
246
+ attn_outputs, attn_weights = self.attn(
247
+ hidden_states=hidden_states,
248
+ layer_past=layer_past,
249
+ attention_mask=attention_mask,
250
+ position_ids=position_ids,
251
+ use_cache=use_cache,
252
+ output_attentions=output_attentions,
253
+ )
254
+ feed_forward_hidden_states = self.mlp(hidden_states)
255
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
256
+
257
+ return hidden_states, attn_weights
258
+
259
+
260
+ @auto_docstring
261
+ class CodeGenPreTrainedModel(PreTrainedModel):
262
+ config: CodeGenConfig
263
+ base_model_prefix = "transformer"
264
+ supports_gradient_checkpointing = True
265
+ _no_split_modules = ["CodeGenBlock"]
266
+ _skip_keys_device_placement = "past_key_values"
267
+ _can_compile_fullgraph = True
268
+
269
+ def _init_weights(self, module):
270
+ super()._init_weights(module)
271
+ if isinstance(module, CodeGenAttention):
272
+ init.copy_(module.embed_positions, create_sinusoidal_positions(module.max_positions, module.pos_embd_dim))
273
+
274
+
275
+ @auto_docstring
276
+ class CodeGenModel(CodeGenPreTrainedModel):
277
+ def __init__(self, config):
278
+ super().__init__(config)
279
+
280
+ self.embed_dim = config.n_embd
281
+ self.vocab_size = config.vocab_size
282
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
283
+ self.drop = nn.Dropout(config.embd_pdrop)
284
+ self.h = nn.ModuleList([CodeGenBlock(config, layer_idx=i) for i in range(config.n_layer)])
285
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
286
+ self.rotary_dim = min(config.rotary_dim, config.n_ctx // config.num_attention_heads)
287
+
288
+ self.gradient_checkpointing = False
289
+
290
+ # Initialize weights and apply final processing
291
+ self.post_init()
292
+
293
+ def get_input_embeddings(self):
294
+ return self.wte
295
+
296
+ def set_input_embeddings(self, new_embeddings):
297
+ self.wte = new_embeddings
298
+
299
+ @auto_docstring
300
+ def forward(
301
+ self,
302
+ input_ids: torch.LongTensor | None = None,
303
+ past_key_values: Cache | None = None,
304
+ attention_mask: torch.FloatTensor | None = None,
305
+ token_type_ids: torch.LongTensor | None = None,
306
+ position_ids: torch.LongTensor | None = None,
307
+ inputs_embeds: torch.FloatTensor | None = None,
308
+ use_cache: bool | None = None,
309
+ output_attentions: bool | None = None,
310
+ output_hidden_states: bool | None = None,
311
+ return_dict: bool | None = None,
312
+ **kwargs, # NOOP kwargs, for now
313
+ ) -> tuple | BaseModelOutputWithPast:
314
+ r"""
315
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_dim)`, *optional*):
316
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
317
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
318
+ model's internal embedding lookup matrix.
319
+ """
320
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
321
+ output_hidden_states = (
322
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
323
+ )
324
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
325
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
326
+
327
+ if (input_ids is None) ^ (inputs_embeds is not None):
328
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
329
+
330
+ if self.gradient_checkpointing and self.training:
331
+ if use_cache:
332
+ logger.warning_once(
333
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
334
+ )
335
+ use_cache = False
336
+
337
+ if inputs_embeds is None:
338
+ inputs_embeds = self.wte(input_ids)
339
+
340
+ if use_cache and past_key_values is None:
341
+ past_key_values = DynamicCache(config=self.config)
342
+
343
+ seq_length = inputs_embeds.shape[1]
344
+ if position_ids is None:
345
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
346
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
347
+ position_ids = position_ids.unsqueeze(0)
348
+
349
+ causal_mask = create_causal_mask(
350
+ config=self.config,
351
+ inputs_embeds=inputs_embeds,
352
+ attention_mask=attention_mask,
353
+ past_key_values=past_key_values,
354
+ position_ids=position_ids,
355
+ )
356
+
357
+ hidden_states = inputs_embeds
358
+
359
+ if token_type_ids is not None:
360
+ token_type_ids = token_type_ids.view(-1, seq_length)
361
+ token_type_embeds = self.wte(token_type_ids)
362
+ hidden_states = hidden_states + token_type_embeds
363
+
364
+ hidden_states = self.drop(hidden_states)
365
+ output_shape = (-1, seq_length, hidden_states.size(-1))
366
+
367
+ all_self_attentions = () if output_attentions else None
368
+ all_hidden_states = () if output_hidden_states else None
369
+ for i, block in enumerate(self.h):
370
+ if output_hidden_states:
371
+ all_hidden_states = all_hidden_states + (hidden_states,)
372
+
373
+ outputs = block(
374
+ hidden_states,
375
+ layer_past=past_key_values,
376
+ attention_mask=causal_mask,
377
+ position_ids=position_ids,
378
+ use_cache=use_cache,
379
+ output_attentions=output_attentions,
380
+ )
381
+
382
+ hidden_states = outputs[0]
383
+ if output_attentions:
384
+ all_self_attentions = all_self_attentions + (outputs[1],)
385
+
386
+ hidden_states = self.ln_f(hidden_states)
387
+
388
+ hidden_states = hidden_states.view(output_shape)
389
+ # Add last hidden state
390
+ if output_hidden_states:
391
+ all_hidden_states = all_hidden_states + (hidden_states,)
392
+
393
+ if not return_dict:
394
+ return tuple(
395
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
396
+ )
397
+
398
+ return BaseModelOutputWithPast(
399
+ last_hidden_state=hidden_states,
400
+ past_key_values=past_key_values,
401
+ hidden_states=all_hidden_states,
402
+ attentions=all_self_attentions,
403
+ )
404
+
405
+
406
+ @auto_docstring(
407
+ custom_intro="""
408
+ The CodeGen Model transformer with a language modeling head on top.
409
+ """
410
+ )
411
+ class CodeGenForCausalLM(CodeGenPreTrainedModel, GenerationMixin):
412
+ _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
413
+
414
+ def __init__(self, config):
415
+ super().__init__(config)
416
+ self.transformer = CodeGenModel(config)
417
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
418
+
419
+ # Initialize weights and apply final processing
420
+ self.post_init()
421
+
422
+ @auto_docstring
423
+ def forward(
424
+ self,
425
+ input_ids: torch.LongTensor | None = None,
426
+ past_key_values: Cache | None = None,
427
+ attention_mask: torch.FloatTensor | None = None,
428
+ token_type_ids: torch.LongTensor | None = None,
429
+ position_ids: torch.LongTensor | None = None,
430
+ inputs_embeds: torch.FloatTensor | None = None,
431
+ labels: torch.LongTensor | None = None,
432
+ use_cache: bool | None = None,
433
+ output_attentions: bool | None = None,
434
+ output_hidden_states: bool | None = None,
435
+ return_dict: bool | None = None,
436
+ logits_to_keep: int | torch.Tensor = 0,
437
+ **kwargs,
438
+ ) -> tuple | CausalLMOutputWithPast:
439
+ r"""
440
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_dim)`, *optional*):
441
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
442
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
443
+ model's internal embedding lookup matrix.
444
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
445
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
446
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
447
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
448
+ """
449
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
450
+
451
+ transformer_outputs = self.transformer(
452
+ input_ids,
453
+ past_key_values=past_key_values,
454
+ attention_mask=attention_mask,
455
+ token_type_ids=token_type_ids,
456
+ position_ids=position_ids,
457
+ inputs_embeds=inputs_embeds,
458
+ use_cache=use_cache,
459
+ output_attentions=output_attentions,
460
+ output_hidden_states=output_hidden_states,
461
+ return_dict=return_dict,
462
+ )
463
+
464
+ hidden_states = transformer_outputs[0]
465
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
466
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
467
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
468
+
469
+ loss = None
470
+ if labels is not None:
471
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
472
+
473
+ if not return_dict:
474
+ output = (logits,) + transformer_outputs[1:]
475
+ return ((loss,) + output) if loss is not None else output
476
+
477
+ return CausalLMOutputWithPast(
478
+ loss=loss,
479
+ logits=logits,
480
+ past_key_values=transformer_outputs.past_key_values,
481
+ hidden_states=transformer_outputs.hidden_states,
482
+ attentions=transformer_outputs.attentions,
483
+ )
484
+
485
+
486
+ __all__ = ["CodeGenForCausalLM", "CodeGenModel", "CodeGenPreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/codegen/tokenization_codegen.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Salesforce authors, The Open AI Team Authors and The HuggingFace Inc. team.
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
+ """Tokenization classes for CodeGen."""
15
+
16
+ import re
17
+ from typing import TYPE_CHECKING, Union
18
+
19
+ import numpy as np
20
+ from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
21
+ from tokenizers.models import BPE
22
+
23
+ from ...tokenization_utils_tokenizers import TokenizersBackend
24
+ from ...utils import is_torch_available, logging
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ if is_torch_available():
29
+ import torch
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
35
+
36
+
37
+ class CodeGenTokenizer(TokenizersBackend):
38
+ """
39
+ Construct a CodeGen tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
40
+ Byte-Pair-Encoding.
41
+
42
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
43
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
44
+
45
+ ```python
46
+ >>> from transformers import CodeGenTokenizer
47
+
48
+ >>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
49
+ >>> tokenizer("Hello world")["input_ids"]
50
+ [15496, 995]
51
+
52
+ >>> tokenizer(" Hello world")["input_ids"]
53
+ [18435, 995]
54
+ ```
55
+
56
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
57
+ the model was not pretrained this way, it might yield a decrease in performance.
58
+
59
+ <Tip>
60
+
61
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
62
+
63
+ </Tip>
64
+
65
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
66
+ refer to this superclass for more information regarding those methods.
67
+
68
+ Args:
69
+ vocab (`str` or `dict[str, int]`, *optional*):
70
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
71
+ merges (`str` or `list[str]`, *optional*):
72
+ Custom merges list. If not provided, merges are loaded from `merges_file`.
73
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
74
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
75
+ token instead.
76
+ bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
77
+ The beginning of sequence token.
78
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
79
+ The end of sequence token.
80
+ pad_token (`str`, *optional*):
81
+ The token used for padding, for example when batching sequences of different lengths.
82
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
83
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
84
+ other word. (CodeGen tokenizer detect beginning of words by the preceding space).
85
+ return_token_type_ids (`bool`, *optional*, defaults to `False`):
86
+ Whether to return token type IDs.
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+ model_input_names = ["input_ids", "attention_mask"]
91
+ model = BPE
92
+
93
+ def __init__(
94
+ self,
95
+ vocab: str | dict[str, int] | None = None,
96
+ merges: str | list[str] | None = None,
97
+ unk_token: str = "<|endoftext|>",
98
+ bos_token: str = "<|endoftext|>",
99
+ eos_token: str = "<|endoftext|>",
100
+ pad_token=None,
101
+ add_prefix_space: bool = False,
102
+ return_token_type_ids: bool = False,
103
+ **kwargs,
104
+ ):
105
+ self.return_token_type_ids = return_token_type_ids
106
+ if self.return_token_type_ids:
107
+ self.model_input_names.append("token_type_ids")
108
+
109
+ self.add_prefix_space = add_prefix_space
110
+
111
+ self._vocab = vocab if vocab is not None else {}
112
+ self._merges = merges or []
113
+
114
+ self._tokenizer = Tokenizer(
115
+ BPE(
116
+ vocab=self._vocab,
117
+ merges=self._merges,
118
+ dropout=None,
119
+ continuing_subword_prefix="",
120
+ end_of_word_suffix="",
121
+ fuse_unk=False,
122
+ )
123
+ )
124
+
125
+ self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
126
+ self._tokenizer.decoder = decoders.ByteLevel()
127
+ self._tokenizer.post_processor = processors.ByteLevel(
128
+ add_prefix_space=True, use_regex=True, trim_offsets=False
129
+ )
130
+
131
+ super().__init__(
132
+ unk_token=unk_token,
133
+ bos_token=bos_token,
134
+ eos_token=eos_token,
135
+ pad_token=pad_token,
136
+ add_prefix_space=add_prefix_space,
137
+ return_token_type_ids=return_token_type_ids,
138
+ **kwargs,
139
+ )
140
+
141
+ def decode(
142
+ self,
143
+ token_ids: Union[int, list[int], np.ndarray, "torch.Tensor"],
144
+ skip_special_tokens: bool = False,
145
+ clean_up_tokenization_spaces: bool | None = None,
146
+ truncate_before_pattern: list[str] | None = None,
147
+ **kwargs,
148
+ ) -> str:
149
+ """
150
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
151
+ tokens and clean up tokenization spaces.
152
+
153
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
154
+
155
+ Args:
156
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor]`):
157
+ List of tokenized input ids. Can be obtained using the `__call__` method.
158
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
159
+ Whether or not to remove special tokens in the decoding.
160
+ clean_up_tokenization_spaces (`bool`, *optional*):
161
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
162
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
163
+ truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
164
+ A list of regular expression strings that will be used to truncate the returned string. This can be
165
+ used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
166
+ of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
167
+ kwargs (additional keyword arguments, *optional*):
168
+ Will be passed to the underlying model specific decode method.
169
+
170
+ Returns:
171
+ `str`: The decoded sentence.
172
+ """
173
+
174
+ decoded_text = super().decode(
175
+ token_ids=token_ids,
176
+ skip_special_tokens=skip_special_tokens,
177
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
178
+ **kwargs,
179
+ )
180
+
181
+ if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
182
+ decoded_text = self.truncate(decoded_text, truncate_before_pattern)
183
+
184
+ return decoded_text
185
+
186
+ def truncate(self, completion, truncate_before_pattern):
187
+ def find_re(string, pattern, start_pos):
188
+ m = pattern.search(string, start_pos)
189
+ return m.start() if m else -1
190
+
191
+ terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
192
+
193
+ prints = list(re.finditer("^print", completion, re.MULTILINE))
194
+
195
+ if len(prints) > 1:
196
+ completion = completion[: prints[1].start()]
197
+
198
+ defs = list(re.finditer("^def", completion, re.MULTILINE))
199
+
200
+ if len(defs) > 1:
201
+ completion = completion[: defs[1].start()]
202
+
203
+ start_pos = 0
204
+
205
+ terminals_pos = [
206
+ pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
207
+ ]
208
+
209
+ if len(terminals_pos) > 0:
210
+ return completion[: min(terminals_pos)]
211
+ else:
212
+ return completion
213
+
214
+
215
+ __all__ = ["CodeGenTokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cohere import *
22
+ from .modeling_cohere import *
23
+ from .tokenization_cohere import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/configuration_cohere.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Cohere team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """Cohere model configuration"""
20
+
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...modeling_rope_utils import RopeParameters
25
+ from ...utils import auto_docstring
26
+
27
+
28
+ @auto_docstring(checkpoint="CohereForAI/c4ai-command-r-v01")
29
+ @strict
30
+ class CohereConfig(PreTrainedConfig):
31
+ r"""
32
+ logit_scale (`float`, *optional*, defaults to 0.0625):
33
+ The scaling factor for the output logits.
34
+
35
+ ```python
36
+ >>> from transformers import CohereModel, CohereConfig
37
+
38
+ >>> # Initializing a Cohere model configuration
39
+ >>> configuration = CohereConfig()
40
+
41
+ >>> # Initializing a model from the Cohere configuration
42
+ >>> model = CohereModel(configuration) # doctest: +SKIP
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config # doctest: +SKIP
46
+ ```
47
+ """
48
+
49
+ model_type = "cohere"
50
+ keys_to_ignore_at_inference = ["past_key_values"]
51
+ default_theta = 500000.0
52
+ base_model_tp_plan = {
53
+ "layers.*.self_attn.q_proj": "colwise",
54
+ "layers.*.self_attn.k_proj": "colwise",
55
+ "layers.*.self_attn.v_proj": "colwise",
56
+ "layers.*.self_attn.o_proj": "rowwise",
57
+ "layers.*.mlp.gate_proj": "colwise",
58
+ "layers.*.mlp.up_proj": "colwise",
59
+ "layers.*.mlp.down_proj": "rowwise",
60
+ }
61
+ base_model_pp_plan = {
62
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
63
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
64
+ "norm": (["hidden_states"], ["hidden_states"]),
65
+ }
66
+ vocab_size: int = 256000
67
+ hidden_size: int = 8192
68
+ intermediate_size: int = 22528
69
+ logit_scale: float | None = 0.0625
70
+ num_hidden_layers: int = 40
71
+ num_attention_heads: int = 64
72
+ num_key_value_heads: int | None = None
73
+ hidden_act: str = "silu"
74
+ max_position_embeddings: int = 8192
75
+ initializer_range: float = 0.02
76
+ layer_norm_eps: float | None = 1e-5
77
+ use_cache: bool = True
78
+ pad_token_id: int | None = 0
79
+ bos_token_id: int | None = 5
80
+ eos_token_id: int | list[int] | None = 255001
81
+ tie_word_embeddings: bool = True
82
+ rope_parameters: RopeParameters | dict | None = None
83
+ attention_bias: bool = False
84
+ attention_dropout: float | int | None = 0.0
85
+ use_qk_norm: bool | None = False
86
+
87
+ def __post_init__(self, **kwargs):
88
+ if self.num_key_value_heads is None:
89
+ self.num_key_value_heads = self.num_attention_heads
90
+
91
+ super().__post_init__(**kwargs)
92
+
93
+
94
+ __all__ = ["CohereConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/modeling_cohere.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere/modular_cohere.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 Cohere team. All rights reserved.
8
+ #
9
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
10
+ # and OPT implementations in this library. It has been modified from its
11
+ # original forms to accommodate minor architectural differences compared
12
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
13
+ #
14
+ # Licensed under the Apache License, Version 2.0 (the "License");
15
+ # you may not use this file except in compliance with the License.
16
+ # You may obtain a copy of the License at
17
+ #
18
+ # http://www.apache.org/licenses/LICENSE-2.0
19
+ #
20
+ # Unless required by applicable law or agreed to in writing, software
21
+ # distributed under the License is distributed on an "AS IS" BASIS,
22
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ # See the License for the specific language governing permissions and
24
+ # limitations under the License.
25
+
26
+ # This file is based on the LLama model definition file in transformers
27
+
28
+
29
+ from collections.abc import Callable
30
+ from typing import Optional
31
+
32
+ import torch
33
+ from torch import nn
34
+
35
+ from ...activations import ACT2FN
36
+ from ...cache_utils import Cache, DynamicCache
37
+ from ...generation import GenerationMixin
38
+ from ...integrations import use_kernelized_func
39
+ from ...masking_utils import create_causal_mask
40
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
41
+ from ...modeling_layers import GradientCheckpointingLayer
42
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
43
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
44
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
45
+ from ...processing_utils import Unpack
46
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
47
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
48
+ from ...utils.output_capturing import capture_outputs
49
+ from .configuration_cohere import CohereConfig
50
+
51
+
52
+ class CohereLayerNorm(nn.Module):
53
+ def __init__(self, hidden_size=None, eps=1e-5, bias=False):
54
+ """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim"""
55
+ super().__init__()
56
+ self.weight = nn.Parameter(torch.ones(hidden_size))
57
+ self.variance_epsilon = eps
58
+
59
+ def forward(self, hidden_states):
60
+ input_dtype = hidden_states.dtype
61
+ hidden_states = hidden_states.to(torch.float32)
62
+ mean = hidden_states.mean(-1, keepdim=True)
63
+ variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
64
+ hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon)
65
+ hidden_states = self.weight.to(torch.float32) * hidden_states
66
+ return hidden_states.to(input_dtype)
67
+
68
+
69
+ class CohereRotaryEmbedding(nn.Module):
70
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
71
+
72
+ def __init__(self, config: CohereConfig, device=None):
73
+ super().__init__()
74
+ self.max_seq_len_cached = config.max_position_embeddings
75
+ self.original_max_seq_len = config.max_position_embeddings
76
+
77
+ self.config = config
78
+
79
+ self.rope_type = self.config.rope_parameters["rope_type"]
80
+ rope_init_fn: Callable = self.compute_default_rope_parameters
81
+ if self.rope_type != "default":
82
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
83
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
84
+
85
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
86
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
87
+
88
+ @staticmethod
89
+ def compute_default_rope_parameters(
90
+ config: CohereConfig | None = None,
91
+ device: Optional["torch.device"] = None,
92
+ seq_len: int | None = None,
93
+ ) -> tuple["torch.Tensor", float]:
94
+ """
95
+ Computes the inverse frequencies according to the original RoPE implementation
96
+ Args:
97
+ config ([`~transformers.PreTrainedConfig`]):
98
+ The model configuration.
99
+ device (`torch.device`):
100
+ The device to use for initialization of the inverse frequencies.
101
+ seq_len (`int`, *optional*):
102
+ The current sequence length. Unused for this type of RoPE.
103
+ Returns:
104
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
105
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
106
+ """
107
+ base = config.rope_parameters["rope_theta"]
108
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
109
+
110
+ attention_factor = 1.0 # Unused in this type of RoPE
111
+
112
+ # Compute the inverse frequencies
113
+ inv_freq = 1.0 / (
114
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
115
+ )
116
+ return inv_freq, attention_factor
117
+
118
+ @torch.no_grad()
119
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
120
+ def forward(self, x, position_ids):
121
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
122
+ position_ids_expanded = position_ids[:, None, :].float()
123
+
124
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
125
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
126
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
127
+ emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
128
+ cos = emb.cos() * self.attention_scaling
129
+ sin = emb.sin() * self.attention_scaling
130
+
131
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
132
+
133
+
134
+ class CohereMLP(nn.Module):
135
+ def __init__(self, config):
136
+ super().__init__()
137
+ self.config = config
138
+ self.hidden_size = config.hidden_size
139
+ self.intermediate_size = config.intermediate_size
140
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
141
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
142
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
143
+ self.act_fn = ACT2FN[config.hidden_act]
144
+
145
+ def forward(self, x):
146
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
147
+ return down_proj
148
+
149
+
150
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
151
+ """
152
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
153
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
154
+ """
155
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
156
+ if n_rep == 1:
157
+ return hidden_states
158
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
159
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
160
+
161
+
162
+ def eager_attention_forward(
163
+ module: nn.Module,
164
+ query: torch.Tensor,
165
+ key: torch.Tensor,
166
+ value: torch.Tensor,
167
+ attention_mask: torch.Tensor | None,
168
+ scaling: float,
169
+ dropout: float = 0.0,
170
+ **kwargs: Unpack[TransformersKwargs],
171
+ ):
172
+ key_states = repeat_kv(key, module.num_key_value_groups)
173
+ value_states = repeat_kv(value, module.num_key_value_groups)
174
+
175
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
176
+ if attention_mask is not None:
177
+ attn_weights = attn_weights + attention_mask
178
+
179
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
180
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
181
+ attn_output = torch.matmul(attn_weights, value_states)
182
+ attn_output = attn_output.transpose(1, 2).contiguous()
183
+
184
+ return attn_output, attn_weights
185
+
186
+
187
+ def rotate_half(x):
188
+ # Split and rotate. Note that this function is different from e.g. Llama.
189
+ x1 = x[..., ::2]
190
+ x2 = x[..., 1::2]
191
+ rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
192
+ return rot_x
193
+
194
+
195
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
196
+ """Applies Rotary Position Embedding to the query and key tensors.
197
+
198
+ Args:
199
+ q (`torch.Tensor`): The query tensor.
200
+ k (`torch.Tensor`): The key tensor.
201
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
202
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
203
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
204
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
205
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
206
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
207
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
208
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
209
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
210
+ Returns:
211
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
212
+ """
213
+ dtype = q.dtype
214
+ q = q.float()
215
+ k = k.float()
216
+ cos = cos.unsqueeze(unsqueeze_dim)
217
+ sin = sin.unsqueeze(unsqueeze_dim)
218
+ q_embed = (q * cos) + (rotate_half(q) * sin)
219
+ k_embed = (k * cos) + (rotate_half(k) * sin)
220
+ return q_embed.to(dtype=dtype), k_embed.to(dtype=dtype)
221
+
222
+
223
+ @use_kernelized_func(apply_rotary_pos_emb)
224
+ class CohereAttention(nn.Module):
225
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
226
+
227
+ def __init__(self, config: CohereConfig, layer_idx: int | None = None):
228
+ super().__init__()
229
+ self.config = config
230
+ self.layer_idx = layer_idx
231
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
232
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
233
+ self.scaling = self.head_dim**-0.5
234
+ self.attention_dropout = config.attention_dropout
235
+ self.is_causal = True
236
+
237
+ self.q_proj = nn.Linear(
238
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
239
+ )
240
+ self.k_proj = nn.Linear(
241
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
242
+ )
243
+ self.v_proj = nn.Linear(
244
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
245
+ )
246
+ self.o_proj = nn.Linear(
247
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
248
+ )
249
+ self.use_qk_norm = config.use_qk_norm
250
+ if self.use_qk_norm:
251
+ # When sharding the model using Tensor Parallelism, need to be careful to use n_local_heads
252
+ self.q_norm = CohereLayerNorm(
253
+ hidden_size=(config.num_attention_heads, self.head_dim), eps=config.layer_norm_eps
254
+ )
255
+ self.k_norm = CohereLayerNorm(
256
+ hidden_size=(config.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps
257
+ )
258
+
259
+ def forward(
260
+ self,
261
+ hidden_states: torch.Tensor,
262
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
263
+ attention_mask: torch.Tensor | None,
264
+ past_key_values: Cache | None = None,
265
+ **kwargs: Unpack[FlashAttentionKwargs],
266
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
267
+ input_shape = hidden_states.shape[:-1]
268
+ hidden_shape = (*input_shape, -1, self.head_dim)
269
+
270
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
271
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
272
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
273
+
274
+ if self.use_qk_norm: # main diff from Llama
275
+ query_states = self.q_norm(query_states)
276
+ key_states = self.k_norm(key_states)
277
+
278
+ query_states = query_states.transpose(1, 2)
279
+ key_states = key_states.transpose(1, 2)
280
+ value_states = value_states.transpose(1, 2)
281
+
282
+ cos, sin = position_embeddings
283
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
284
+
285
+ if past_key_values is not None:
286
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
287
+
288
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
289
+ self.config._attn_implementation, eager_attention_forward
290
+ )
291
+
292
+ attn_output, attn_weights = attention_interface(
293
+ self,
294
+ query_states,
295
+ key_states,
296
+ value_states,
297
+ attention_mask,
298
+ dropout=0.0 if not self.training else self.attention_dropout,
299
+ scaling=self.scaling,
300
+ **kwargs,
301
+ )
302
+
303
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
304
+ attn_output = self.o_proj(attn_output)
305
+ return attn_output, attn_weights
306
+
307
+
308
+ class CohereDecoderLayer(GradientCheckpointingLayer):
309
+ def __init__(self, config: CohereConfig, layer_idx: int):
310
+ super().__init__()
311
+ self.hidden_size = config.hidden_size
312
+ self.self_attn = CohereAttention(config=config, layer_idx=layer_idx)
313
+ self.mlp = CohereMLP(config)
314
+ self.input_layernorm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
315
+
316
+ def forward(
317
+ self,
318
+ hidden_states: torch.Tensor,
319
+ attention_mask: torch.Tensor | None = None,
320
+ position_ids: torch.LongTensor | None = None,
321
+ past_key_values: Cache | None = None,
322
+ use_cache: bool | None = False,
323
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
324
+ **kwargs: Unpack[FlashAttentionKwargs],
325
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
326
+ """
327
+ Args:
328
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
329
+ attention_mask (`torch.FloatTensor`, *optional*):
330
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
331
+ query_sequence_length, key_sequence_length)` if default attention is used.
332
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
333
+ output_attentions (`bool`, *optional*):
334
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
335
+ returned tensors for more detail.
336
+ use_cache (`bool`, *optional*):
337
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
338
+ (see `past_key_values`).
339
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
340
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
341
+ with `head_dim` being the embedding dimension of each attention head.
342
+ """
343
+ residual = hidden_states
344
+ hidden_states = self.input_layernorm(hidden_states)
345
+
346
+ hidden_states_attention, _ = self.self_attn(
347
+ hidden_states=hidden_states,
348
+ attention_mask=attention_mask,
349
+ position_ids=position_ids,
350
+ past_key_values=past_key_values,
351
+ use_cache=use_cache,
352
+ position_embeddings=position_embeddings,
353
+ **kwargs,
354
+ )
355
+
356
+ hidden_states_mlp = self.mlp(hidden_states)
357
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
358
+ return hidden_states
359
+
360
+
361
+ @auto_docstring
362
+ class CoherePreTrainedModel(PreTrainedModel):
363
+ config: CohereConfig
364
+ base_model_prefix = "model"
365
+ supports_gradient_checkpointing = True
366
+ _no_split_modules = ["CohereDecoderLayer"]
367
+ _skip_keys_device_placement = ["past_key_values"]
368
+ _supports_flash_attn = True
369
+ _supports_sdpa = True
370
+ _supports_flex_attn = True
371
+
372
+ _can_compile_fullgraph = True
373
+ _supports_attention_backend = True
374
+ _can_record_outputs = {
375
+ "hidden_states": CohereDecoderLayer,
376
+ "attentions": CohereAttention,
377
+ }
378
+
379
+
380
+ @auto_docstring
381
+ class CohereModel(CoherePreTrainedModel):
382
+ def __init__(self, config: CohereConfig):
383
+ super().__init__(config)
384
+ self.padding_idx = config.pad_token_id
385
+ self.vocab_size = config.vocab_size
386
+
387
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
388
+ self.layers = nn.ModuleList(
389
+ [CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
390
+ )
391
+ self.norm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
392
+ self.rotary_emb = CohereRotaryEmbedding(config=config)
393
+ self.gradient_checkpointing = False
394
+
395
+ # Initialize weights and apply final processing
396
+ self.post_init()
397
+
398
+ @merge_with_config_defaults
399
+ @capture_outputs
400
+ @auto_docstring
401
+ def forward(
402
+ self,
403
+ input_ids: torch.LongTensor | None = None,
404
+ attention_mask: torch.Tensor | None = None,
405
+ position_ids: torch.LongTensor | None = None,
406
+ past_key_values: Cache | None = None,
407
+ inputs_embeds: torch.FloatTensor | None = None,
408
+ use_cache: bool | None = None,
409
+ **kwargs: Unpack[TransformersKwargs],
410
+ ) -> BaseModelOutputWithPast:
411
+ if (input_ids is None) ^ (inputs_embeds is not None):
412
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
413
+
414
+ if inputs_embeds is None:
415
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
416
+
417
+ if use_cache and past_key_values is None:
418
+ past_key_values = DynamicCache(config=self.config)
419
+
420
+ if position_ids is None:
421
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
422
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
423
+ position_ids = position_ids.unsqueeze(0)
424
+
425
+ causal_mask = create_causal_mask(
426
+ config=self.config,
427
+ inputs_embeds=inputs_embeds,
428
+ attention_mask=attention_mask,
429
+ past_key_values=past_key_values,
430
+ position_ids=position_ids,
431
+ )
432
+
433
+ hidden_states = inputs_embeds
434
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
435
+
436
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
437
+ hidden_states = decoder_layer(
438
+ hidden_states,
439
+ attention_mask=causal_mask,
440
+ position_embeddings=position_embeddings,
441
+ position_ids=position_ids,
442
+ past_key_values=past_key_values,
443
+ use_cache=use_cache,
444
+ **kwargs,
445
+ )
446
+
447
+ hidden_states = self.norm(hidden_states)
448
+ return BaseModelOutputWithPast(
449
+ last_hidden_state=hidden_states,
450
+ past_key_values=past_key_values,
451
+ )
452
+
453
+
454
+ @auto_docstring
455
+ class CohereForCausalLM(CoherePreTrainedModel, GenerationMixin):
456
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
457
+ _tp_plan = {"lm_head": "colwise_gather_output"}
458
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
459
+
460
+ def __init__(self, config):
461
+ super().__init__(config)
462
+ self.model = CohereModel(config)
463
+ self.vocab_size = config.vocab_size
464
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
465
+ self.logit_scale = config.logit_scale
466
+ self.tie_word_embeddings = config.tie_word_embeddings
467
+
468
+ # Initialize weights and apply final processing
469
+ self.post_init()
470
+
471
+ @can_return_tuple
472
+ @auto_docstring
473
+ def forward(
474
+ self,
475
+ input_ids: torch.LongTensor | None = None,
476
+ attention_mask: torch.Tensor | None = None,
477
+ position_ids: torch.LongTensor | None = None,
478
+ past_key_values: Cache | None = None,
479
+ inputs_embeds: torch.FloatTensor | None = None,
480
+ labels: torch.LongTensor | None = None,
481
+ use_cache: bool | None = None,
482
+ logits_to_keep: int | torch.Tensor = 0,
483
+ **kwargs: Unpack[TransformersKwargs],
484
+ ) -> CausalLMOutputWithPast:
485
+ r"""
486
+ Example:
487
+
488
+ ```python
489
+ >> from transformers import AutoTokenizer, CohereForCausalLM
490
+
491
+ >> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
492
+ >> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
493
+
494
+ >> prompt = "Hey, are you conscious? Can you talk to me?"
495
+ >> inputs = tokenizer(prompt, return_tensors="pt")
496
+
497
+ >> # Generate
498
+ >> generate_ids = model.generate(inputs.input_ids, max_length=30)
499
+ >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
500
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
501
+ ```"""
502
+ outputs: BaseModelOutputWithPast = self.model(
503
+ input_ids=input_ids,
504
+ attention_mask=attention_mask,
505
+ position_ids=position_ids,
506
+ past_key_values=past_key_values,
507
+ inputs_embeds=inputs_embeds,
508
+ use_cache=use_cache,
509
+ **kwargs,
510
+ )
511
+
512
+ hidden_states = outputs.last_hidden_state
513
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
514
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
515
+ logits = logits * self.logit_scale # main diff from Llama
516
+
517
+ loss = None
518
+ if labels is not None:
519
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
520
+
521
+ return CausalLMOutputWithPast(
522
+ loss=loss,
523
+ logits=logits,
524
+ past_key_values=outputs.past_key_values,
525
+ hidden_states=outputs.hidden_states,
526
+ attentions=outputs.attentions,
527
+ )
528
+
529
+
530
+ __all__ = ["CohereForCausalLM", "CohereModel", "CoherePreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/modular_cohere.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Cohere team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ # This file is based on the LLama model definition file in transformers
21
+
22
+ """PyTorch Cohere model."""
23
+
24
+ from collections.abc import Callable
25
+
26
+ import torch
27
+ from torch import nn
28
+
29
+ from ...cache_utils import Cache
30
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
31
+ from ...modeling_layers import GradientCheckpointingLayer
32
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
33
+ from ...modeling_rope_utils import dynamic_rope_update
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
35
+ from ...processing_utils import Unpack
36
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
37
+ from ...utils.generic import maybe_autocast
38
+ from ..llama.modeling_llama import (
39
+ LlamaAttention,
40
+ LlamaForCausalLM,
41
+ LlamaMLP,
42
+ LlamaModel,
43
+ LlamaRotaryEmbedding,
44
+ eager_attention_forward,
45
+ )
46
+ from .configuration_cohere import CohereConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ class CohereLayerNorm(nn.Module):
53
+ def __init__(self, hidden_size=None, eps=1e-5, bias=False):
54
+ """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim"""
55
+ super().__init__()
56
+ self.weight = nn.Parameter(torch.ones(hidden_size))
57
+ self.variance_epsilon = eps
58
+
59
+ def forward(self, hidden_states):
60
+ input_dtype = hidden_states.dtype
61
+ hidden_states = hidden_states.to(torch.float32)
62
+ mean = hidden_states.mean(-1, keepdim=True)
63
+ variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
64
+ hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon)
65
+ hidden_states = self.weight.to(torch.float32) * hidden_states
66
+ return hidden_states.to(input_dtype)
67
+
68
+
69
+ class CohereRotaryEmbedding(LlamaRotaryEmbedding):
70
+ @torch.no_grad()
71
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
72
+ def forward(self, x, position_ids):
73
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
74
+ position_ids_expanded = position_ids[:, None, :].float()
75
+
76
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
77
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
78
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
79
+ emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
80
+ cos = emb.cos() * self.attention_scaling
81
+ sin = emb.sin() * self.attention_scaling
82
+
83
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
84
+
85
+
86
+ def rotate_half(x):
87
+ # Split and rotate. Note that this function is different from e.g. Llama.
88
+ x1 = x[..., ::2]
89
+ x2 = x[..., 1::2]
90
+ rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
91
+ return rot_x
92
+
93
+
94
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
95
+ """Applies Rotary Position Embedding to the query and key tensors.
96
+
97
+ Args:
98
+ q (`torch.Tensor`): The query tensor.
99
+ k (`torch.Tensor`): The key tensor.
100
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
101
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
102
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
103
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
104
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
105
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
106
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
107
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
108
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
109
+ Returns:
110
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
111
+ """
112
+ dtype = q.dtype
113
+ q = q.float()
114
+ k = k.float()
115
+ cos = cos.unsqueeze(unsqueeze_dim)
116
+ sin = sin.unsqueeze(unsqueeze_dim)
117
+ q_embed = (q * cos) + (rotate_half(q) * sin)
118
+ k_embed = (k * cos) + (rotate_half(k) * sin)
119
+ return q_embed.to(dtype=dtype), k_embed.to(dtype=dtype)
120
+
121
+
122
+ class CohereMLP(LlamaMLP):
123
+ def __init__(self, config):
124
+ super().__init__(config)
125
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
126
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
127
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
128
+
129
+
130
+ class CohereAttention(LlamaAttention):
131
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
132
+
133
+ def __init__(self, config: CohereConfig, layer_idx: int | None = None):
134
+ super().__init__(config, layer_idx)
135
+ self.use_qk_norm = config.use_qk_norm
136
+ if self.use_qk_norm:
137
+ # When sharding the model using Tensor Parallelism, need to be careful to use n_local_heads
138
+ self.q_norm = CohereLayerNorm(
139
+ hidden_size=(config.num_attention_heads, self.head_dim), eps=config.layer_norm_eps
140
+ )
141
+ self.k_norm = CohereLayerNorm(
142
+ hidden_size=(config.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps
143
+ )
144
+
145
+ def forward(
146
+ self,
147
+ hidden_states: torch.Tensor,
148
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
149
+ attention_mask: torch.Tensor | None,
150
+ past_key_values: Cache | None = None,
151
+ **kwargs: Unpack[FlashAttentionKwargs],
152
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
153
+ input_shape = hidden_states.shape[:-1]
154
+ hidden_shape = (*input_shape, -1, self.head_dim)
155
+
156
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
157
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
158
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
159
+
160
+ if self.use_qk_norm: # main diff from Llama
161
+ query_states = self.q_norm(query_states)
162
+ key_states = self.k_norm(key_states)
163
+
164
+ query_states = query_states.transpose(1, 2)
165
+ key_states = key_states.transpose(1, 2)
166
+ value_states = value_states.transpose(1, 2)
167
+
168
+ cos, sin = position_embeddings
169
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
170
+
171
+ if past_key_values is not None:
172
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
173
+
174
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
175
+ self.config._attn_implementation, eager_attention_forward
176
+ )
177
+
178
+ attn_output, attn_weights = attention_interface(
179
+ self,
180
+ query_states,
181
+ key_states,
182
+ value_states,
183
+ attention_mask,
184
+ dropout=0.0 if not self.training else self.attention_dropout,
185
+ scaling=self.scaling,
186
+ **kwargs,
187
+ )
188
+
189
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
190
+ attn_output = self.o_proj(attn_output)
191
+ return attn_output, attn_weights
192
+
193
+
194
+ class CohereDecoderLayer(GradientCheckpointingLayer):
195
+ def __init__(self, config: CohereConfig, layer_idx: int):
196
+ super().__init__()
197
+ self.hidden_size = config.hidden_size
198
+ self.self_attn = CohereAttention(config=config, layer_idx=layer_idx)
199
+ self.mlp = CohereMLP(config)
200
+ self.input_layernorm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
201
+
202
+ def forward(
203
+ self,
204
+ hidden_states: torch.Tensor,
205
+ attention_mask: torch.Tensor | None = None,
206
+ position_ids: torch.LongTensor | None = None,
207
+ past_key_values: Cache | None = None,
208
+ use_cache: bool | None = False,
209
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
210
+ **kwargs: Unpack[FlashAttentionKwargs],
211
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
212
+ """
213
+ Args:
214
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
215
+ attention_mask (`torch.FloatTensor`, *optional*):
216
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
217
+ query_sequence_length, key_sequence_length)` if default attention is used.
218
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
219
+ output_attentions (`bool`, *optional*):
220
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
221
+ returned tensors for more detail.
222
+ use_cache (`bool`, *optional*):
223
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
224
+ (see `past_key_values`).
225
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
226
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
227
+ with `head_dim` being the embedding dimension of each attention head.
228
+ """
229
+ residual = hidden_states
230
+ hidden_states = self.input_layernorm(hidden_states)
231
+
232
+ hidden_states_attention, _ = self.self_attn(
233
+ hidden_states=hidden_states,
234
+ attention_mask=attention_mask,
235
+ position_ids=position_ids,
236
+ past_key_values=past_key_values,
237
+ use_cache=use_cache,
238
+ position_embeddings=position_embeddings,
239
+ **kwargs,
240
+ )
241
+
242
+ hidden_states_mlp = self.mlp(hidden_states)
243
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
244
+ return hidden_states
245
+
246
+
247
+ class CohereModel(LlamaModel):
248
+ def __init__(self, config: CohereConfig):
249
+ super().__init__(config)
250
+ self.layers = nn.ModuleList(
251
+ [CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
252
+ )
253
+ self.norm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
254
+
255
+
256
+ class CohereForCausalLM(LlamaForCausalLM):
257
+ def __init__(self, config):
258
+ super().__init__(config)
259
+ self.model = CohereModel(config)
260
+ self.logit_scale = config.logit_scale
261
+ self.tie_word_embeddings = config.tie_word_embeddings
262
+
263
+ @can_return_tuple
264
+ @auto_docstring
265
+ def forward(
266
+ self,
267
+ input_ids: torch.LongTensor | None = None,
268
+ attention_mask: torch.Tensor | None = None,
269
+ position_ids: torch.LongTensor | None = None,
270
+ past_key_values: Cache | None = None,
271
+ inputs_embeds: torch.FloatTensor | None = None,
272
+ labels: torch.LongTensor | None = None,
273
+ use_cache: bool | None = None,
274
+ logits_to_keep: int | torch.Tensor = 0,
275
+ **kwargs: Unpack[TransformersKwargs],
276
+ ) -> CausalLMOutputWithPast:
277
+ r"""
278
+ Example:
279
+
280
+ ```python
281
+ >> from transformers import AutoTokenizer, CohereForCausalLM
282
+
283
+ >> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
284
+ >> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
285
+
286
+ >> prompt = "Hey, are you conscious? Can you talk to me?"
287
+ >> inputs = tokenizer(prompt, return_tensors="pt")
288
+
289
+ >> # Generate
290
+ >> generate_ids = model.generate(inputs.input_ids, max_length=30)
291
+ >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
292
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
293
+ ```"""
294
+ outputs: BaseModelOutputWithPast = self.model(
295
+ input_ids=input_ids,
296
+ attention_mask=attention_mask,
297
+ position_ids=position_ids,
298
+ past_key_values=past_key_values,
299
+ inputs_embeds=inputs_embeds,
300
+ use_cache=use_cache,
301
+ **kwargs,
302
+ )
303
+
304
+ hidden_states = outputs.last_hidden_state
305
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
306
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
307
+ logits = logits * self.logit_scale # main diff from Llama
308
+
309
+ loss = None
310
+ if labels is not None:
311
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
312
+
313
+ return CausalLMOutputWithPast(
314
+ loss=loss,
315
+ logits=logits,
316
+ past_key_values=outputs.past_key_values,
317
+ hidden_states=outputs.hidden_states,
318
+ attentions=outputs.attentions,
319
+ )
320
+
321
+
322
+ __all__ = [
323
+ "CohereForCausalLM",
324
+ "CohereModel",
325
+ "CoherePreTrainedModel", # noqa: F822
326
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere/tokenization_cohere.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Cohere 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
+ # This file is based on the tokenization_llama.py file in transformers
16
+
17
+ from typing import Literal
18
+
19
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers
20
+ from tokenizers.models import BPE
21
+
22
+ from ...tokenization_utils_tokenizers import TokenizersBackend
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
28
+
29
+ PRETRAINED_VOCAB_FILES_MAP = {
30
+ "tokenizer_file": {
31
+ "Cohere/Command-nightly": "https://huggingface.co/Cohere/Command-nightly/blob/main/tokenizer.json",
32
+ },
33
+ }
34
+
35
+ # fmt: off
36
+ DEFAULT_SYSTEM_PROMPT = "You are Command-R, a brilliant, sophisticated, AI-assistant trained to assist human users by providing thorough responses. You are trained by Cohere."
37
+ DEFAULT_RAG_PREAMBLE = """## Task and Context
38
+ You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
39
+
40
+ ## Style Guide
41
+ Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling."""
42
+ # fmt: on
43
+
44
+
45
+ class CohereTokenizer(TokenizersBackend):
46
+ """
47
+ Construct a Cohere tokenizer. Based on byte-level Byte-Pair-Encoding.
48
+
49
+ This uses notably ByteFallback and NFC normalization.
50
+
51
+ ```python
52
+ >>> from transformers import AutoTokenizer
53
+
54
+ >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
55
+ >>> tokenizer.encode("Hello this is a test")
56
+ [5, 28339, 2075, 1801, 1671, 3282]
57
+ ```
58
+
59
+ If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
60
+ call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
61
+ values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
62
+ [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
63
+
64
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
65
+ the model was not pretrained this way, it might yield a decrease in performance.
66
+
67
+ <Tip>
68
+
69
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
70
+
71
+ </Tip>
72
+
73
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
74
+ refer to this superclass for more information regarding those methods.
75
+
76
+ Args:
77
+ vocab_file (`str`, *optional*):
78
+ Path to the vocabulary file.
79
+ merges_file (`str`, *optional*):
80
+ Path to the merges file.
81
+ tokenizer_file (`str`, *optional*):
82
+ [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
83
+ contains everything needed to load the tokenizer.
84
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
85
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
86
+ extra spaces.
87
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<UNK>"`):
88
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
89
+ token instead.
90
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<BOS_TOKEN>"`):
91
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
92
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|END_OF_TURN_TOKEN|>"`):
93
+ The end of sequence token.
94
+ add_bos_token (`bool`, *optional*, defaults to `True`):
95
+ Whether or not to add an `bos_token` at the start of sequences.
96
+ add_eos_token (`bool`, *optional*, defaults to `False`):
97
+ Whether or not to add an `eos_token` at the end of sequences.
98
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
99
+ Whether or not the default system prompt for Cohere tokenizer should be used.
100
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
101
+ Whether or not the tokenizer should automatically add a prefix space
102
+ vocab (`str`, `dict` or `list`, *optional*):
103
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
104
+ merges (`str` or `list[str]`, *optional*):
105
+ Custom merges list. If not provided, merges are loaded from `merges_file`.
106
+ """
107
+
108
+ vocab_files_names = VOCAB_FILES_NAMES
109
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
110
+ padding_side = "left"
111
+ model_input_names = ["input_ids", "attention_mask"]
112
+ model = BPE
113
+ # No `max_model_input_sizes`
114
+
115
+ def __init__(
116
+ self,
117
+ vocab: str | dict[str, int] | None = None,
118
+ merges: str | list[str] | None = None,
119
+ errors: str = "replace",
120
+ unk_token: str = "<UNK>",
121
+ bos_token: str = "<BOS_TOKEN>",
122
+ eos_token: str = "<|END_OF_TURN_TOKEN|>",
123
+ pad_token: str = "<PAD>",
124
+ cls_token: str = "<CLS>",
125
+ sep_token: str = "<SEP>",
126
+ mask_token: str = "<MASK_TOKEN>",
127
+ use_default_system_prompt: bool = False,
128
+ add_prefix_space: bool = False,
129
+ **kwargs,
130
+ ):
131
+ self.use_default_system_prompt = use_default_system_prompt
132
+ self.add_prefix_space = add_prefix_space
133
+ self.grounded_generation_template = kwargs.pop("grounded_generation_template", None)
134
+ self.tool_use_template = kwargs.pop("tool_use_template", None)
135
+
136
+ self._vocab = (
137
+ vocab
138
+ if vocab is not None
139
+ else {
140
+ str(pad_token): 0,
141
+ str(unk_token): 1,
142
+ str(cls_token): 2,
143
+ str(sep_token): 3,
144
+ str(mask_token): 4,
145
+ str(bos_token): 5,
146
+ }
147
+ )
148
+
149
+ self._merges = merges or []
150
+ self._tokenizer = Tokenizer(
151
+ BPE(
152
+ vocab=self._vocab,
153
+ merges=self._merges,
154
+ dropout=None,
155
+ continuing_subword_prefix="",
156
+ end_of_word_suffix="",
157
+ fuse_unk=False,
158
+ )
159
+ )
160
+
161
+ self._tokenizer.normalizer = normalizers.NFC()
162
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
163
+ [
164
+ pre_tokenizers.Digits(individual_digits=True),
165
+ pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space, trim_offsets=True),
166
+ ]
167
+ )
168
+ self._tokenizer.decoder = decoders.ByteLevel(add_prefix_space=add_prefix_space, trim_offsets=True)
169
+
170
+ super().__init__(
171
+ errors=errors,
172
+ unk_token=unk_token,
173
+ bos_token=bos_token,
174
+ eos_token=eos_token,
175
+ pad_token=pad_token,
176
+ cls_token=cls_token,
177
+ sep_token=sep_token,
178
+ mask_token=mask_token,
179
+ use_default_system_prompt=use_default_system_prompt,
180
+ add_prefix_space=add_prefix_space,
181
+ **kwargs,
182
+ )
183
+
184
+ self._post_init()
185
+
186
+ def apply_tool_use_template(
187
+ self,
188
+ conversation: list[dict[str, str]],
189
+ tools: list[dict],
190
+ **kwargs,
191
+ ) -> str | list[int]:
192
+ """Create a Command-R tool-use prompt.
193
+
194
+ Once rendered, the prompt instructs the model to generate a list of actions to perform on a set of user supplied tools
195
+ to help carry out the user's requests.
196
+
197
+ Conceptually, this works in the same way as `apply_chat_format`, but takes an additional `tools` parameter.
198
+
199
+ Converts a chat in the form of a list of dictionaries with `"role"` and `"content"` keys and a list of available
200
+ tools for the model to use into a prompt string, or a list of token ids.
201
+ This method will use the tokenizer's `default_tool_use_template` template specified at the class level.
202
+ You can override the default template using the `tool_use_template` kwarg but the quality of your results may decrease.
203
+
204
+ Args:
205
+ conversation (list[dict[str, str]]): A list of dicts
206
+ with "role" and "content" keys, representing the chat history so far.
207
+ tools (list[Dict]): a list of tools to render into the prompt for the model to choose from.
208
+ See an example at the bottom of the docstring.
209
+ The format should be:
210
+ * name (str): The name of the tool to be called. Valid names contain only the characters a-z,
211
+ A-Z, 0-9, _ and must not begin with a digit.
212
+ * description (str): The description of what the tool does, the model uses the description to
213
+ choose when and how to call the function.
214
+ * parameter_definitions (list[Dict]): The input parameters of the tool. Accepts a dictionary
215
+ where the key is the name of the parameter and the value is the parameter spec.
216
+ Valid parameter names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.
217
+ Parameter specs are as follows:
218
+ * description (str): The description of the parameter.
219
+ * type (str): the type of the parameter - most effective for python builtin data types, such as 'str', 'bool'
220
+ * required: boolean: Denotes whether the parameter is always present (required) or not. Defaults to not required.
221
+ add_generation_prompt (bool, *optional*): Whether to end the prompt with the token(s) that indicate
222
+ the start of an assistant message. This is useful when you want to generate a response from the model.
223
+ Note that this argument will be passed to the chat template, and so it must be supported in the
224
+ template for this argument to have any effect.
225
+ tokenize (`bool`, defaults to `True`):
226
+ Whether to tokenize the output. If `False`, the output will be a string.
227
+ padding (`bool`, defaults to `False`):
228
+ Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`.
229
+ truncation (`bool`, defaults to `False`):
230
+ Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.
231
+ max_length (`int`, *optional*):
232
+ Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If
233
+ not specified, the tokenizer's `max_length` attribute will be used as a default.
234
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
235
+ If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable
236
+ values are:
237
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
238
+ - `'np'`: Return NumPy `np.ndarray` objects.
239
+ return_dict (`bool`, *optional*, defaults to `False`):
240
+ Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
241
+ **tokenizer_kwargs: Additional kwargs to pass to the tokenizer.
242
+
243
+ Returns:
244
+ `str`: A rendered prompt string.
245
+ or if tokenize=True:
246
+ `list[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This
247
+ output is ready to pass to the model, either directly or via methods like `generate()`.
248
+
249
+ Examples:
250
+
251
+ ```python
252
+ >> tokenizer = CohereTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
253
+ >> tools = [
254
+ {
255
+ "name": "internet_search",
256
+ "description": "Returns a list of relevant document snippets for a textual query retrieved from the internet",
257
+ "parameter_definitions": {
258
+ "query": {
259
+ "description": "Query to search the internet with",
260
+ "type": "str",
261
+ "required": True,
262
+ }
263
+ },
264
+ },
265
+ {
266
+ "name": "directly_answer",
267
+ "description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
268
+ "parameter_definitions": {},
269
+ },
270
+ ]
271
+ >> conversation = [
272
+ {"role": "user", "content": "Whats the biggest penguin in the world?"},
273
+ ]
274
+ >> # Render the prompt, ready for user to inspect, or for input into the model
275
+ >> prompt = tokenizer.apply_tool_use_template(conversation, tools=tools, tokenize=False, add_generation_prompt=True)
276
+ >> print(prompt)
277
+ >> inputs = tokenizer.encode(grounded_generation_prompt, add_special_tokens=False, return_tensors='pt')
278
+ >> outputs = model.generate(inputs, max_new_tokens=128)
279
+ >> print(tokenizer.decode(outputs[0]))
280
+ [
281
+ {
282
+ "tool_name": "internet_search",
283
+ "parameters": {
284
+ "query": "biggest penguin in the world"
285
+ }
286
+ }
287
+ ]
288
+ ```
289
+ """
290
+ return self.apply_chat_template(
291
+ conversation,
292
+ chat_template="tool_use",
293
+ tools=tools,
294
+ **kwargs,
295
+ )
296
+
297
+ def apply_grounded_generation_template(
298
+ self,
299
+ conversation: list[dict[str, str]],
300
+ documents: list[dict],
301
+ citation_mode: Literal["fast", "accurate"] = "accurate",
302
+ **kwargs,
303
+ ) -> str | list[int]:
304
+ """Create a Command-R grounded generation (aka RAG) prompt.
305
+
306
+ Once rendered, the prompt instructs the model to generate a response with citations in, based on supplied documents.
307
+
308
+ Conceptually, this works in the same way as `apply_chat_format`, but takes additional `documents`
309
+ and parameter `citation_mode` parameters.
310
+
311
+ Converts a list of dictionaries with `"role"` and `"content"` keys and a list of
312
+ documents for the model to ground its response on into a prompt string, or a list of token ids.
313
+ This method will use the tokenizer's `grounded_generation_template` template specified at the class level.
314
+ You can override the default template using the `grounded_generation_template` kwarg but the quality of your results may decrease.
315
+
316
+ Args:
317
+ conversation (list[dict[str, str]]): A list of dicts
318
+ with "role" and "content" keys, representing the chat history so far.
319
+ documents (list[dict[str, str]): A list of dicts, representing documents or tool outputs to ground your
320
+ generation on. A document is a semistructured dict, with a string to string mapping. Common fields are
321
+ `url`, `title`, `snippet` etc but should be descriptive of the key. They will get rendered into the prompt.
322
+ citation_mode: either "accurate" (prompt the model to generate an answer first, then rewrite it with citation
323
+ spans in) or "fast", where the prompt instructs the model to generate an answer with citations in directly.
324
+ The former has higher quality citations, the latter requires fewer tokens to be generated.
325
+ add_generation_prompt (bool, *optional*): Whether to end the prompt with the token(s) that indicate
326
+ the start of an assistant message. This is useful when you want to generate a response from the model.
327
+ Note that this argument will be passed to the chat template, and so it must be supported in the
328
+ template for this argument to have any effect.
329
+ tokenize (`bool`, defaults to `True`):
330
+ Whether to tokenize the output. If `False`, the output will be a string.
331
+ padding (`bool`, defaults to `False`):
332
+ Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`.
333
+ truncation (`bool`, defaults to `False`):
334
+ Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.
335
+ max_length (`int`, *optional*):
336
+ Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If
337
+ not specified, the tokenizer's `max_length` attribute will be used as a default.
338
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
339
+ If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable
340
+ values are:
341
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
342
+ - `'np'`: Return NumPy `np.ndarray` objects.
343
+ return_dict (`bool`, *optional*, defaults to `False`):
344
+ Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
345
+ **tokenizer_kwargs: Additional kwargs to pass to the tokenizer.
346
+
347
+ Returns:
348
+ `str`: A rendered prompt string.
349
+ or if tokenize=True:
350
+ `list[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This
351
+ output is ready to pass to the model, either directly or via methods like `generate()`.
352
+
353
+ Examples:
354
+
355
+ ```python
356
+ >> tokenizer = CohereTokenizer.from_pretrained('CohereForAI/c4ai-command-r-v01')
357
+
358
+ >> # define documents:
359
+ >> documents = [
360
+ { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
361
+ { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."}
362
+ ]
363
+ >> # define a conversation:
364
+ >> conversation = [
365
+ {"role": "user", "content": "Whats the biggest penguin in the world?"}
366
+ ]
367
+ >> # render the prompt, ready for user to inspect, or for input into the model:
368
+ >> grounded_generation_prompt = tokenizer.apply_grounded_generation_template(conversation, documents=documents, tokenize=False, add_generation_prompt=True)
369
+ >> print(grounded_generation_prompt)
370
+ >> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
371
+ >> outputs = model.generate(inputs, max_new_tokens=128)
372
+ >> print(tokenizer.decode(outputs[0]))
373
+ ```
374
+ """
375
+ return self.apply_chat_template(
376
+ conversation,
377
+ chat_template="rag",
378
+ documents=documents,
379
+ citation_mode=citation_mode,
380
+ **kwargs,
381
+ )
382
+
383
+
384
+ __all__ = ["CohereTokenizer"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Cohere and The HuggingFace Inc. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cohere2 import *
22
+ from .modeling_cohere2 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/configuration_cohere2.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere2/modular_cohere2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 Cohere Inc. HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...modeling_rope_utils import RopeParameters
25
+ from ...utils import auto_docstring
26
+
27
+
28
+ @auto_docstring(checkpoint="CohereForAI/c4ai-command-r-v01")
29
+ @strict
30
+ class Cohere2Config(PreTrainedConfig):
31
+ r"""
32
+ logit_scale (`float`, *optional*, defaults to 0.0625):
33
+ The scaling factor for the output logits.
34
+
35
+ ```python
36
+ >>> from transformers import Cohere2Model, Cohere2Config
37
+
38
+ >>> # Initializing a Cohere Nextmodel configuration
39
+ >>> configuration = Cohere2Config()
40
+
41
+ >>> # Initializing a model from the Cohere2 configuration
42
+ >>> model = Cohere2Model(configuration) # doctest: +SKIP
43
+
44
+ >>> # Accessing the model configuration
45
+ >>> configuration = model.config # doctest: +SKIP
46
+ ```
47
+ """
48
+
49
+ model_type = "cohere2"
50
+ keys_to_ignore_at_inference = ["past_key_values"]
51
+ base_model_tp_plan = {
52
+ "layers.*.self_attn.q_proj": "colwise",
53
+ "layers.*.self_attn.k_proj": "colwise",
54
+ "layers.*.self_attn.v_proj": "colwise",
55
+ "layers.*.self_attn.o_proj": "rowwise",
56
+ "layers.*.mlp.gate_proj": "colwise",
57
+ "layers.*.mlp.up_proj": "colwise",
58
+ "layers.*.mlp.down_proj": "rowwise",
59
+ }
60
+ base_model_pp_plan = {
61
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
62
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
63
+ "norm": (["hidden_states"], ["hidden_states"]),
64
+ }
65
+
66
+ vocab_size: int = 256000
67
+ hidden_size: int = 8192
68
+ intermediate_size: int = 22528
69
+ logit_scale: float = 0.0625
70
+ num_hidden_layers: int = 40
71
+ num_attention_heads: int = 64
72
+ num_key_value_heads: int | None = None
73
+ hidden_act: str = "silu"
74
+ max_position_embeddings: int = 8192
75
+ initializer_range: float = 0.02
76
+ layer_norm_eps: float = 1e-5
77
+ use_cache: bool = True
78
+ pad_token_id: int | None = 0
79
+ bos_token_id: int | None = 5
80
+ eos_token_id: int | list[int] | None = 255001
81
+ tie_word_embeddings: bool = True
82
+ rope_parameters: RopeParameters | dict | None = None
83
+ attention_bias: bool = False
84
+ attention_dropout: float | int = 0.0
85
+ sliding_window: int | None = 4096
86
+ layer_types: list[str] | None = None
87
+
88
+ def __post_init__(self, **kwargs):
89
+ if self.num_key_value_heads is None:
90
+ self.num_key_value_heads = self.num_attention_heads
91
+
92
+ # Need to specify head_dim in the config so it can be used in the attention forward functions
93
+ self.head_dim = self.hidden_size // self.num_attention_heads
94
+
95
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
96
+ if self.layer_types is None:
97
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
98
+ _sliding_window_pattern = kwargs.pop("sliding_window_pattern", 4)
99
+ self.layer_types = [
100
+ "sliding_attention" if bool((i + 1) % _sliding_window_pattern) else "full_attention"
101
+ for i in range(self.num_hidden_layers)
102
+ ]
103
+
104
+ super().__post_init__(**kwargs)
105
+
106
+
107
+ __all__ = ["Cohere2Config"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/modeling_cohere2.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere2/modular_cohere2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 Cohere Inc. HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ from collections.abc import Callable
22
+ from typing import Optional
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationMixin
30
+ from ...integrations import use_kernelized_func
31
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
34
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from ...processing_utils import Unpack
37
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
38
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
39
+ from ...utils.output_capturing import capture_outputs
40
+ from .configuration_cohere2 import Cohere2Config
41
+
42
+
43
+ class Cohere2RotaryEmbedding(nn.Module):
44
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
45
+
46
+ def __init__(self, config: Cohere2Config, device=None):
47
+ super().__init__()
48
+ self.max_seq_len_cached = config.max_position_embeddings
49
+ self.original_max_seq_len = config.max_position_embeddings
50
+
51
+ self.config = config
52
+
53
+ self.rope_type = self.config.rope_parameters["rope_type"]
54
+ rope_init_fn: Callable = self.compute_default_rope_parameters
55
+ if self.rope_type != "default":
56
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
57
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
58
+
59
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
60
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
61
+
62
+ @staticmethod
63
+ def compute_default_rope_parameters(
64
+ config: Cohere2Config | None = None,
65
+ device: Optional["torch.device"] = None,
66
+ seq_len: int | None = None,
67
+ ) -> tuple["torch.Tensor", float]:
68
+ """
69
+ Computes the inverse frequencies according to the original RoPE implementation
70
+ Args:
71
+ config ([`~transformers.PreTrainedConfig`]):
72
+ The model configuration.
73
+ device (`torch.device`):
74
+ The device to use for initialization of the inverse frequencies.
75
+ seq_len (`int`, *optional*):
76
+ The current sequence length. Unused for this type of RoPE.
77
+ Returns:
78
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
79
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
80
+ """
81
+ base = config.rope_parameters["rope_theta"]
82
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
83
+
84
+ attention_factor = 1.0 # Unused in this type of RoPE
85
+
86
+ # Compute the inverse frequencies
87
+ inv_freq = 1.0 / (
88
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
89
+ )
90
+ return inv_freq, attention_factor
91
+
92
+ @torch.no_grad()
93
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
94
+ def forward(self, x, position_ids):
95
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
96
+ position_ids_expanded = position_ids[:, None, :].float()
97
+
98
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
99
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
100
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
101
+ emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
102
+ cos = emb.cos() * self.attention_scaling
103
+ sin = emb.sin() * self.attention_scaling
104
+
105
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
106
+
107
+
108
+ class Cohere2LayerNorm(nn.Module):
109
+ def __init__(self, hidden_size=None, eps=1e-5, bias=False):
110
+ """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim"""
111
+ super().__init__()
112
+ self.weight = nn.Parameter(torch.ones(hidden_size))
113
+ self.variance_epsilon = eps
114
+
115
+ def forward(self, hidden_states):
116
+ input_dtype = hidden_states.dtype
117
+ hidden_states = hidden_states.to(torch.float32)
118
+ mean = hidden_states.mean(-1, keepdim=True)
119
+ variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
120
+ hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon)
121
+ hidden_states = self.weight.to(torch.float32) * hidden_states
122
+ return hidden_states.to(input_dtype)
123
+
124
+
125
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
126
+ """
127
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
128
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
129
+ """
130
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
131
+ if n_rep == 1:
132
+ return hidden_states
133
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
134
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
135
+
136
+
137
+ def eager_attention_forward(
138
+ module: nn.Module,
139
+ query: torch.Tensor,
140
+ key: torch.Tensor,
141
+ value: torch.Tensor,
142
+ attention_mask: torch.Tensor | None,
143
+ scaling: float,
144
+ dropout: float = 0.0,
145
+ **kwargs: Unpack[TransformersKwargs],
146
+ ):
147
+ key_states = repeat_kv(key, module.num_key_value_groups)
148
+ value_states = repeat_kv(value, module.num_key_value_groups)
149
+
150
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
151
+ if attention_mask is not None:
152
+ attn_weights = attn_weights + attention_mask
153
+
154
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
155
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
156
+ attn_output = torch.matmul(attn_weights, value_states)
157
+ attn_output = attn_output.transpose(1, 2).contiguous()
158
+
159
+ return attn_output, attn_weights
160
+
161
+
162
+ def rotate_half(x):
163
+ # Split and rotate. Note that this function is different from e.g. Llama.
164
+ x1 = x[..., ::2]
165
+ x2 = x[..., 1::2]
166
+ rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
167
+ return rot_x
168
+
169
+
170
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
171
+ """Applies Rotary Position Embedding to the query and key tensors.
172
+
173
+ Args:
174
+ q (`torch.Tensor`): The query tensor.
175
+ k (`torch.Tensor`): The key tensor.
176
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
177
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
178
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
179
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
180
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
181
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
182
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
183
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
184
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
185
+ Returns:
186
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
187
+ """
188
+ dtype = q.dtype
189
+ q = q.float()
190
+ k = k.float()
191
+ cos = cos.unsqueeze(unsqueeze_dim)
192
+ sin = sin.unsqueeze(unsqueeze_dim)
193
+ q_embed = (q * cos) + (rotate_half(q) * sin)
194
+ k_embed = (k * cos) + (rotate_half(k) * sin)
195
+ return q_embed.to(dtype=dtype), k_embed.to(dtype=dtype)
196
+
197
+
198
+ @use_kernelized_func(apply_rotary_pos_emb)
199
+ class Cohere2Attention(nn.Module):
200
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
201
+
202
+ def __init__(self, config: Cohere2Config, layer_idx: int | None = None):
203
+ super().__init__()
204
+ self.config = config
205
+ self.layer_idx = layer_idx
206
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
207
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
208
+ self.scaling = self.head_dim**-0.5
209
+ self.attention_dropout = config.attention_dropout
210
+ self.is_causal = True
211
+ layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
212
+ self.sliding_window = config.sliding_window if layer_type == "sliding_attention" else None
213
+
214
+ self.q_proj = nn.Linear(
215
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
216
+ )
217
+ self.k_proj = nn.Linear(
218
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
219
+ )
220
+ self.v_proj = nn.Linear(
221
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
222
+ )
223
+ self.o_proj = nn.Linear(
224
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
225
+ )
226
+
227
+ def forward(
228
+ self,
229
+ hidden_states: torch.Tensor,
230
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
231
+ attention_mask: torch.Tensor | None,
232
+ past_key_values: Cache | None = None,
233
+ **kwargs: Unpack[TransformersKwargs],
234
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
235
+ input_shape = hidden_states.shape[:-1]
236
+ hidden_shape = (*input_shape, -1, self.head_dim)
237
+
238
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
239
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
240
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
241
+
242
+ cos, sin = position_embeddings
243
+ if self.sliding_window is not None:
244
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
245
+
246
+ if past_key_values is not None:
247
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
248
+
249
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
250
+ self.config._attn_implementation, eager_attention_forward
251
+ )
252
+
253
+ attn_output, attn_weights = attention_interface(
254
+ self,
255
+ query_states,
256
+ key_states,
257
+ value_states,
258
+ attention_mask,
259
+ dropout=0.0 if not self.training else self.attention_dropout,
260
+ scaling=self.scaling,
261
+ sliding_window=self.sliding_window,
262
+ **kwargs,
263
+ )
264
+
265
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
266
+ attn_output = self.o_proj(attn_output)
267
+ return attn_output, attn_weights
268
+
269
+
270
+ class Cohere2MLP(nn.Module):
271
+ def __init__(self, config):
272
+ super().__init__()
273
+ self.config = config
274
+ self.hidden_size = config.hidden_size
275
+ self.intermediate_size = config.intermediate_size
276
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
277
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
278
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
279
+ self.act_fn = ACT2FN[config.hidden_act]
280
+
281
+ def forward(self, x):
282
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
283
+ return down_proj
284
+
285
+
286
+ class Cohere2DecoderLayer(GradientCheckpointingLayer):
287
+ def __init__(self, config: Cohere2Config, layer_idx: int):
288
+ super().__init__()
289
+ self.hidden_size = config.hidden_size
290
+ self.self_attn = Cohere2Attention(config=config, layer_idx=layer_idx)
291
+ self.mlp = Cohere2MLP(config)
292
+ self.input_layernorm = Cohere2LayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
293
+
294
+ def forward(
295
+ self,
296
+ hidden_states: torch.Tensor,
297
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
298
+ attention_mask: torch.Tensor | None = None,
299
+ past_key_values: Cache | None = None,
300
+ use_cache: bool | None = False,
301
+ **kwargs: Unpack[TransformersKwargs],
302
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
303
+ """
304
+ Args:
305
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
306
+ attention_mask (`torch.FloatTensor`, *optional*):
307
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
308
+ query_sequence_length, key_sequence_length)` if default attention is used.
309
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
310
+ output_attentions (`bool`, *optional*):
311
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
312
+ returned tensors for more detail.
313
+ use_cache (`bool`, *optional*):
314
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
315
+ (see `past_key_values`).
316
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
317
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
318
+ with `head_dim` being the embedding dimension of each attention head.
319
+ """
320
+ residual = hidden_states
321
+ hidden_states = self.input_layernorm(hidden_states)
322
+ hidden_states_attention, _ = self.self_attn(
323
+ hidden_states=hidden_states,
324
+ position_embeddings=position_embeddings,
325
+ attention_mask=attention_mask,
326
+ past_key_values=past_key_values,
327
+ use_cache=use_cache,
328
+ **kwargs,
329
+ )
330
+
331
+ hidden_states_mlp = self.mlp(hidden_states)
332
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
333
+ return hidden_states
334
+
335
+
336
+ @auto_docstring
337
+ class Cohere2PreTrainedModel(PreTrainedModel):
338
+ config: Cohere2Config
339
+ base_model_prefix = "model"
340
+ supports_gradient_checkpointing = True
341
+ _no_split_modules = ["Cohere2DecoderLayer"]
342
+ _skip_keys_device_placement = ["past_key_values"]
343
+ _supports_flash_attn = True
344
+ _supports_sdpa = True
345
+ _supports_flex_attn = True
346
+
347
+ _can_compile_fullgraph = True
348
+ _supports_attention_backend = True
349
+ _can_record_outputs = {
350
+ "hidden_states": Cohere2DecoderLayer,
351
+ "attentions": Cohere2Attention,
352
+ }
353
+
354
+
355
+ @auto_docstring
356
+ class Cohere2Model(Cohere2PreTrainedModel):
357
+ def __init__(self, config: Cohere2Config):
358
+ super().__init__(config)
359
+ self.padding_idx = config.pad_token_id
360
+ self.vocab_size = config.vocab_size
361
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
362
+ self.layers = nn.ModuleList(
363
+ [Cohere2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
364
+ )
365
+ self.norm = Cohere2LayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
366
+ self.rotary_emb = Cohere2RotaryEmbedding(config)
367
+ self.gradient_checkpointing = False
368
+
369
+ # Initialize weights and apply final processing
370
+ self.post_init()
371
+
372
+ @merge_with_config_defaults
373
+ @capture_outputs
374
+ @auto_docstring
375
+ def forward(
376
+ self,
377
+ input_ids: torch.LongTensor | None = None,
378
+ attention_mask: torch.Tensor | None = None,
379
+ position_ids: torch.LongTensor | None = None,
380
+ past_key_values: Cache | None = None,
381
+ inputs_embeds: torch.FloatTensor | None = None,
382
+ use_cache: bool | None = None,
383
+ **kwargs: Unpack[TransformersKwargs],
384
+ ) -> BaseModelOutputWithPast:
385
+ if (input_ids is None) ^ (inputs_embeds is not None):
386
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
387
+
388
+ if inputs_embeds is None:
389
+ inputs_embeds = self.embed_tokens(input_ids)
390
+
391
+ if use_cache and past_key_values is None:
392
+ past_key_values = DynamicCache(config=self.config)
393
+
394
+ if position_ids is None:
395
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
396
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
397
+ position_ids = position_ids.unsqueeze(0)
398
+
399
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
400
+ mask_kwargs = {
401
+ "config": self.config,
402
+ "inputs_embeds": inputs_embeds,
403
+ "attention_mask": attention_mask,
404
+ "past_key_values": past_key_values,
405
+ "position_ids": position_ids,
406
+ }
407
+ causal_mask_mapping = {
408
+ "full_attention": create_causal_mask(**mask_kwargs),
409
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
410
+ }
411
+
412
+ hidden_states = inputs_embeds
413
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
414
+
415
+ for i, decoder_layer in enumerate(self.layers):
416
+ hidden_states = decoder_layer(
417
+ hidden_states,
418
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
419
+ position_embeddings=position_embeddings,
420
+ past_key_values=past_key_values,
421
+ use_cache=use_cache,
422
+ position_ids=position_ids,
423
+ **kwargs,
424
+ )
425
+
426
+ hidden_states = self.norm(hidden_states)
427
+ return BaseModelOutputWithPast(
428
+ last_hidden_state=hidden_states,
429
+ past_key_values=past_key_values,
430
+ )
431
+
432
+
433
+ @auto_docstring
434
+ class Cohere2ForCausalLM(Cohere2PreTrainedModel, GenerationMixin):
435
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
436
+ _tp_plan = {"lm_head": "colwise_gather_output"}
437
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
438
+
439
+ def __init__(self, config):
440
+ super().__init__(config)
441
+ self.model = Cohere2Model(config)
442
+ self.vocab_size = config.vocab_size
443
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
444
+ self.logit_scale = config.logit_scale
445
+ self.tie_word_embeddings = config.tie_word_embeddings
446
+
447
+ # Initialize weights and apply final processing
448
+ self.post_init()
449
+
450
+ @can_return_tuple
451
+ @auto_docstring
452
+ def forward(
453
+ self,
454
+ input_ids: torch.LongTensor | None = None,
455
+ attention_mask: torch.Tensor | None = None,
456
+ position_ids: torch.LongTensor | None = None,
457
+ past_key_values: Cache | None = None,
458
+ inputs_embeds: torch.FloatTensor | None = None,
459
+ labels: torch.LongTensor | None = None,
460
+ use_cache: bool | None = None,
461
+ logits_to_keep: int | torch.Tensor = 0,
462
+ **kwargs: Unpack[TransformersKwargs],
463
+ ) -> CausalLMOutputWithPast:
464
+ r"""
465
+ Example:
466
+
467
+ ```python
468
+ >> from transformers import AutoTokenizer, Cohere2ForCausalLM
469
+
470
+ >> model = Cohere2ForCausalLM.from_pretrained("Cohere2ForAI/c4ai-command-r-v01")
471
+ >> tokenizer = AutoTokenizer.from_pretrained("Cohere2ForAI/c4ai-command-r-v01")
472
+
473
+ >> prompt = "Hey, are you conscious? Can you talk to me?"
474
+ >> inputs = tokenizer(prompt, return_tensors="pt")
475
+
476
+ >> # Generate
477
+ >> generate_ids = model.generate(inputs.input_ids, max_length=30)
478
+ >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
479
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
480
+ ```"""
481
+ outputs: BaseModelOutputWithPast = self.model(
482
+ input_ids=input_ids,
483
+ attention_mask=attention_mask,
484
+ position_ids=position_ids,
485
+ past_key_values=past_key_values,
486
+ inputs_embeds=inputs_embeds,
487
+ use_cache=use_cache,
488
+ **kwargs,
489
+ )
490
+
491
+ hidden_states = outputs.last_hidden_state
492
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
493
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
494
+ logits = logits * self.logit_scale # main diff from Llama
495
+
496
+ loss = None
497
+ if labels is not None:
498
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
499
+
500
+ return CausalLMOutputWithPast(
501
+ loss=loss,
502
+ logits=logits,
503
+ past_key_values=outputs.past_key_values,
504
+ hidden_states=outputs.hidden_states,
505
+ attentions=outputs.attentions,
506
+ )
507
+
508
+
509
+ __all__ = ["Cohere2ForCausalLM", "Cohere2Model", "Cohere2PreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2/modular_cohere2.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Cohere Inc. HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from collections.abc import Callable
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...cache_utils import Cache, DynamicCache
22
+ from ...configuration_utils import PreTrainedConfig
23
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
24
+ from ...modeling_outputs import BaseModelOutputWithPast
25
+ from ...modeling_rope_utils import (
26
+ RopeParameters,
27
+ dynamic_rope_update,
28
+ )
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs, auto_docstring, logging
32
+ from ...utils.generic import maybe_autocast
33
+ from ..cohere.modeling_cohere import (
34
+ CohereAttention,
35
+ CohereDecoderLayer,
36
+ CohereForCausalLM,
37
+ CohereLayerNorm,
38
+ CoherePreTrainedModel,
39
+ CohereRotaryEmbedding,
40
+ apply_rotary_pos_emb,
41
+ eager_attention_forward,
42
+ )
43
+ from ..gemma2.modeling_gemma2 import Gemma2Model
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ @auto_docstring(checkpoint="CohereForAI/c4ai-command-r-v01")
50
+ @strict
51
+ class Cohere2Config(PreTrainedConfig):
52
+ r"""
53
+ logit_scale (`float`, *optional*, defaults to 0.0625):
54
+ The scaling factor for the output logits.
55
+
56
+ ```python
57
+ >>> from transformers import Cohere2Model, Cohere2Config
58
+
59
+ >>> # Initializing a Cohere Nextmodel configuration
60
+ >>> configuration = Cohere2Config()
61
+
62
+ >>> # Initializing a model from the Cohere2 configuration
63
+ >>> model = Cohere2Model(configuration) # doctest: +SKIP
64
+
65
+ >>> # Accessing the model configuration
66
+ >>> configuration = model.config # doctest: +SKIP
67
+ ```
68
+ """
69
+
70
+ model_type = "cohere2"
71
+ keys_to_ignore_at_inference = ["past_key_values"]
72
+ base_model_tp_plan = {
73
+ "layers.*.self_attn.q_proj": "colwise",
74
+ "layers.*.self_attn.k_proj": "colwise",
75
+ "layers.*.self_attn.v_proj": "colwise",
76
+ "layers.*.self_attn.o_proj": "rowwise",
77
+ "layers.*.mlp.gate_proj": "colwise",
78
+ "layers.*.mlp.up_proj": "colwise",
79
+ "layers.*.mlp.down_proj": "rowwise",
80
+ }
81
+ base_model_pp_plan = {
82
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
83
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
84
+ "norm": (["hidden_states"], ["hidden_states"]),
85
+ }
86
+
87
+ vocab_size: int = 256000
88
+ hidden_size: int = 8192
89
+ intermediate_size: int = 22528
90
+ logit_scale: float = 0.0625
91
+ num_hidden_layers: int = 40
92
+ num_attention_heads: int = 64
93
+ num_key_value_heads: int | None = None
94
+ hidden_act: str = "silu"
95
+ max_position_embeddings: int = 8192
96
+ initializer_range: float = 0.02
97
+ layer_norm_eps: float = 1e-5
98
+ use_cache: bool = True
99
+ pad_token_id: int | None = 0
100
+ bos_token_id: int | None = 5
101
+ eos_token_id: int | list[int] | None = 255001
102
+ tie_word_embeddings: bool = True
103
+ rope_parameters: RopeParameters | dict | None = None
104
+ attention_bias: bool = False
105
+ attention_dropout: float | int = 0.0
106
+ sliding_window: int | None = 4096
107
+ layer_types: list[str] | None = None
108
+
109
+ def __post_init__(self, **kwargs):
110
+ if self.num_key_value_heads is None:
111
+ self.num_key_value_heads = self.num_attention_heads
112
+
113
+ # Need to specify head_dim in the config so it can be used in the attention forward functions
114
+ self.head_dim = self.hidden_size // self.num_attention_heads
115
+
116
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
117
+ if self.layer_types is None:
118
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
119
+ _sliding_window_pattern = kwargs.pop("sliding_window_pattern", 4)
120
+ self.layer_types = [
121
+ "sliding_attention" if bool((i + 1) % _sliding_window_pattern) else "full_attention"
122
+ for i in range(self.num_hidden_layers)
123
+ ]
124
+
125
+ super().__post_init__(**kwargs)
126
+
127
+
128
+ class Cohere2RotaryEmbedding(CohereRotaryEmbedding):
129
+ @torch.no_grad()
130
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
131
+ def forward(self, x, position_ids):
132
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
133
+ position_ids_expanded = position_ids[:, None, :].float()
134
+
135
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
136
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
137
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
138
+ emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
139
+ cos = emb.cos() * self.attention_scaling
140
+ sin = emb.sin() * self.attention_scaling
141
+
142
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
143
+
144
+
145
+ class Cohere2LayerNorm(CohereLayerNorm):
146
+ pass
147
+
148
+
149
+ class Cohere2Attention(CohereAttention):
150
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
151
+
152
+ def __init__(self, config: Cohere2Config, layer_idx: int | None = None):
153
+ nn.Module.__init__(self)
154
+ self.config = config
155
+ self.layer_idx = layer_idx
156
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
157
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
158
+ self.scaling = self.head_dim**-0.5
159
+ self.attention_dropout = config.attention_dropout
160
+ self.is_causal = True
161
+ layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
162
+ self.sliding_window = config.sliding_window if layer_type == "sliding_attention" else None
163
+
164
+ self.q_proj = nn.Linear(
165
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
166
+ )
167
+ self.k_proj = nn.Linear(
168
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
169
+ )
170
+ self.v_proj = nn.Linear(
171
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
172
+ )
173
+ self.o_proj = nn.Linear(
174
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
175
+ )
176
+
177
+ def forward(
178
+ self,
179
+ hidden_states: torch.Tensor,
180
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
181
+ attention_mask: torch.Tensor | None,
182
+ past_key_values: Cache | None = None,
183
+ **kwargs: Unpack[TransformersKwargs],
184
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
185
+ input_shape = hidden_states.shape[:-1]
186
+ hidden_shape = (*input_shape, -1, self.head_dim)
187
+
188
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
189
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
190
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
191
+
192
+ cos, sin = position_embeddings
193
+ if self.sliding_window is not None:
194
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
195
+
196
+ if past_key_values is not None:
197
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
198
+
199
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
200
+ self.config._attn_implementation, eager_attention_forward
201
+ )
202
+
203
+ attn_output, attn_weights = attention_interface(
204
+ self,
205
+ query_states,
206
+ key_states,
207
+ value_states,
208
+ attention_mask,
209
+ dropout=0.0 if not self.training else self.attention_dropout,
210
+ scaling=self.scaling,
211
+ sliding_window=self.sliding_window,
212
+ **kwargs,
213
+ )
214
+
215
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
216
+ attn_output = self.o_proj(attn_output)
217
+ return attn_output, attn_weights
218
+
219
+
220
+ class Cohere2DecoderLayer(CohereDecoderLayer):
221
+ def __init__(self, config: Cohere2Config, layer_idx: int):
222
+ super().__init__(config, layer_idx)
223
+
224
+ def forward(
225
+ self,
226
+ hidden_states: torch.Tensor,
227
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
228
+ attention_mask: torch.Tensor | None = None,
229
+ past_key_values: Cache | None = None,
230
+ use_cache: bool | None = False,
231
+ **kwargs: Unpack[TransformersKwargs],
232
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
233
+ residual = hidden_states
234
+ hidden_states = self.input_layernorm(hidden_states)
235
+ hidden_states_attention, _ = self.self_attn(
236
+ hidden_states=hidden_states,
237
+ position_embeddings=position_embeddings,
238
+ attention_mask=attention_mask,
239
+ past_key_values=past_key_values,
240
+ use_cache=use_cache,
241
+ **kwargs,
242
+ )
243
+
244
+ hidden_states_mlp = self.mlp(hidden_states)
245
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
246
+ return hidden_states
247
+
248
+
249
+ class Cohere2PreTrainedModel(CoherePreTrainedModel):
250
+ config: Cohere2Config
251
+ _can_record_outputs = {
252
+ "hidden_states": Cohere2DecoderLayer,
253
+ "attentions": Cohere2Attention,
254
+ }
255
+
256
+
257
+ class Cohere2Model(Gemma2Model):
258
+ def __init__(self, config: Cohere2Config):
259
+ super().__init__(config)
260
+ self.norm = Cohere2LayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
261
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
262
+
263
+ def forward(
264
+ self,
265
+ input_ids: torch.LongTensor | None = None,
266
+ attention_mask: torch.Tensor | None = None,
267
+ position_ids: torch.LongTensor | None = None,
268
+ past_key_values: Cache | None = None,
269
+ inputs_embeds: torch.FloatTensor | None = None,
270
+ use_cache: bool | None = None,
271
+ **kwargs: Unpack[TransformersKwargs],
272
+ ) -> BaseModelOutputWithPast:
273
+ if (input_ids is None) ^ (inputs_embeds is not None):
274
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
275
+
276
+ if inputs_embeds is None:
277
+ inputs_embeds = self.embed_tokens(input_ids)
278
+
279
+ if use_cache and past_key_values is None:
280
+ past_key_values = DynamicCache(config=self.config)
281
+
282
+ if position_ids is None:
283
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
284
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
285
+ position_ids = position_ids.unsqueeze(0)
286
+
287
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
288
+ mask_kwargs = {
289
+ "config": self.config,
290
+ "inputs_embeds": inputs_embeds,
291
+ "attention_mask": attention_mask,
292
+ "past_key_values": past_key_values,
293
+ "position_ids": position_ids,
294
+ }
295
+ causal_mask_mapping = {
296
+ "full_attention": create_causal_mask(**mask_kwargs),
297
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
298
+ }
299
+
300
+ hidden_states = inputs_embeds
301
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
302
+
303
+ for i, decoder_layer in enumerate(self.layers):
304
+ hidden_states = decoder_layer(
305
+ hidden_states,
306
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
307
+ position_embeddings=position_embeddings,
308
+ past_key_values=past_key_values,
309
+ use_cache=use_cache,
310
+ position_ids=position_ids,
311
+ **kwargs,
312
+ )
313
+
314
+ hidden_states = self.norm(hidden_states)
315
+ return BaseModelOutputWithPast(
316
+ last_hidden_state=hidden_states,
317
+ past_key_values=past_key_values,
318
+ )
319
+
320
+
321
+ class Cohere2ForCausalLM(CohereForCausalLM):
322
+ pass
323
+
324
+
325
+ __all__ = ["Cohere2Config", "Cohere2ForCausalLM", "Cohere2Model", "Cohere2PreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cohere2_vision import *
22
+ from .image_processing_cohere2_vision import *
23
+ from .modeling_cohere2_vision import *
24
+ from .processing_cohere2_vision import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/configuration_cohere2_vision.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 the Cohere Inc. 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
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+ from ..auto import CONFIG_MAPPING, AutoConfig
21
+
22
+
23
+ @auto_docstring(checkpoint="CohereLabs/command-a-vision-07-2025")
24
+ @strict
25
+ class Cohere2VisionConfig(PreTrainedConfig):
26
+ r"""
27
+ downsample_factor (`int`, *optional*, defaults to 2):
28
+ The factor by which to downsample the input image.
29
+ alignment_intermediate_size (`int`, *optional*, defaults to 36864):
30
+ The size of the intermediate layer for alignment.
31
+ """
32
+
33
+ model_type = "cohere2_vision"
34
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
35
+
36
+ vision_config: dict | PreTrainedConfig | None = None
37
+ text_config: dict | PreTrainedConfig | None = None
38
+ downsample_factor: int = 2
39
+ image_token_id: int = 255036
40
+ alignment_intermediate_size: int = 36864
41
+ tie_word_embeddings: bool = True
42
+
43
+ def __post_init__(self, **kwargs):
44
+ if isinstance(self.vision_config, dict):
45
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "siglip_vision_model")
46
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
47
+ elif self.vision_config is None:
48
+ self.vision_config = CONFIG_MAPPING["siglip_vision_model"](
49
+ hidden_size=1152,
50
+ intermediate_size=3072,
51
+ image_size=512,
52
+ num_hidden_layers=27,
53
+ num_attention_heads=12,
54
+ )
55
+
56
+ if isinstance(self.text_config, dict):
57
+ self.text_config["model_type"] = self.text_config.get("model_type", "cohere2")
58
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
59
+ elif self.text_config is None:
60
+ self.text_config = CONFIG_MAPPING["cohere2"](tie_word_embeddings=self.tie_word_embeddings)
61
+
62
+ super().__post_init__(**kwargs)
63
+
64
+
65
+ __all__ = ["Cohere2VisionConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/image_processing_cohere2_vision.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere2_vision/modular_cohere2_vision.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere2_vision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 the Cohere Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from functools import lru_cache
22
+
23
+ import numpy as np
24
+ import torch
25
+ from torchvision.transforms.v2 import functional as tvF
26
+
27
+ from ...image_processing_backends import TorchvisionBackend
28
+ from ...image_processing_utils import BatchFeature
29
+ from ...image_transforms import group_images_by_shape, reorder_images
30
+ from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling, SizeDict
31
+ from ...processing_utils import ImagesKwargs, Unpack
32
+ from ...utils import TensorType, auto_docstring
33
+
34
+
35
+ class Cohere2VisionImageProcessorKwargs(ImagesKwargs, total=False):
36
+ r"""
37
+ crop_to_patches (`bool`, *optional*, defaults to `False`):
38
+ Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
39
+ `preprocess` method.
40
+ min_patches (`int`, *optional*, defaults to 1):
41
+ The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
42
+ set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method.
43
+ max_patches (`int`, *optional*, defaults to 12):
44
+ The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
45
+ set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method.
46
+ """
47
+
48
+ crop_to_patches: bool
49
+ min_patches: int
50
+ max_patches: int
51
+
52
+
53
+ @lru_cache(maxsize=10)
54
+ def get_all_supported_aspect_ratios(max_image_tiles: int) -> list[tuple[int, int]]:
55
+ """
56
+ Computes all allowed aspect ratios for a given maximum number of input tiles.
57
+
58
+ This function calculates all possible arrangements of tiles that can be formed
59
+ within the constraint of the maximum number of tiles. Each arrangement is
60
+ represented by its aspect ratio (width/height) and the corresponding tile configuration.
61
+
62
+ Args:
63
+ max_image_tiles (`int`):
64
+ The maximum number of tiles allowed.
65
+
66
+ Returns:
67
+ `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
68
+ configuration in terms of number of tiles.
69
+
70
+ Example:
71
+ >>> get_all_supported_aspect_ratios(4)
72
+ [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)]
73
+
74
+ """
75
+ aspect_ratios = []
76
+ for width in range(1, max_image_tiles + 1):
77
+ for height in range(1, max_image_tiles + 1):
78
+ if width * height <= max_image_tiles:
79
+ aspect_ratios.append((width, height))
80
+ return aspect_ratios
81
+
82
+
83
+ def get_optimal_tiled_canvas(
84
+ original_image_size: tuple[int, int],
85
+ target_tile_size: tuple[int, int],
86
+ min_image_tiles: int,
87
+ max_image_tiles: int,
88
+ ) -> tuple[int, int]:
89
+ possible_resolutions = get_all_supported_aspect_ratios(max_image_tiles)
90
+ possible_resolutions = sorted(possible_resolutions, key=lambda x: x[0] * x[1])
91
+ image_height, image_width = original_image_size
92
+ patch_size_height, patch_size_width = target_tile_size # (height == width)
93
+
94
+ candidate_resolutions = np.array(possible_resolutions) * patch_size_height
95
+ # tiles following (width, height) order to align with aspect ratio convention
96
+ tile_size = np.stack([image_width, image_height])
97
+ required_scales = candidate_resolutions / tile_size
98
+ required_scale = np.min(required_scales, axis=-1, keepdims=True) # [n_resolutions, 1]
99
+ if np.all(required_scale < 1):
100
+ # We are forced to downscale, so try to minimize the amount of downscaling
101
+ best_grid = possible_resolutions[np.argmax(required_scale)]
102
+ else:
103
+ # Pick the resolution that required the least upscaling so that it most closely fits the image
104
+ required_scale = np.where(required_scale < 1.0, 10e9, required_scale)
105
+ best_grid = possible_resolutions[np.argmin(required_scale)]
106
+ return best_grid # (width, height)
107
+
108
+
109
+ @auto_docstring
110
+ class Cohere2VisionImageProcessor(TorchvisionBackend):
111
+ valid_kwargs = Cohere2VisionImageProcessorKwargs
112
+ resample = PILImageResampling.BICUBIC
113
+ image_mean = OPENAI_CLIP_MEAN
114
+ image_std = OPENAI_CLIP_STD
115
+ size = {"height": 512, "width": 512}
116
+ do_resize = True
117
+ do_rescale = True
118
+ do_normalize = True
119
+ do_convert_rgb = True
120
+ crop_to_patches = True
121
+ min_patches = 1
122
+ max_patches = 12
123
+ patch_size = 16
124
+
125
+ def __init__(self, **kwargs: Unpack[Cohere2VisionImageProcessorKwargs]):
126
+ super().__init__(**kwargs)
127
+
128
+ def crop_image_to_patches(
129
+ self,
130
+ images: "torch.Tensor",
131
+ min_patches: int,
132
+ max_patches: int,
133
+ use_thumbnail: bool = True,
134
+ patch_size: SizeDict | None = None,
135
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
136
+ ):
137
+ """
138
+ Crop the images to patches and return a list of cropped images.
139
+ The number of patches and their grid arrangement are determined by the original image size,
140
+ the target patch size and the minimum and maximum number of patches.
141
+ The aspect ratio of the patches grid is chosen to be the closest to the original image aspect ratio.
142
+
143
+ Args:
144
+ images (`torch.Tensor`):
145
+ The images to be cropped.
146
+ min_patches (`int`):
147
+ The minimum number of patches to be extracted from the image.
148
+ max_patches (`int`):
149
+ The maximum number of patches to be extracted from the image.
150
+ use_thumbnail (`bool`, *optional*, defaults to `True`):
151
+ Whether to add a thumbnail image to the list of cropped patches.
152
+ patch_size (`SizeDict`, *optional*):
153
+ The size of the output patches.
154
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
155
+ Resampling filter to use when resizing.
156
+ """
157
+ patch_size_height, patch_size_width = patch_size.height, patch_size.width
158
+ original_height, original_width = images.shape[-2:]
159
+ # find the closest aspect ratio to the target
160
+ num_columns, num_rows = get_optimal_tiled_canvas(
161
+ (original_height, original_width), (patch_size_height, patch_size_width), min_patches, max_patches
162
+ )
163
+
164
+ # calculate the target width and height
165
+ target_width = patch_size_width * num_columns
166
+ target_height = patch_size_height * num_rows
167
+ num_blocks = num_columns * num_rows
168
+
169
+ # resize the image so that each patch is of patch_size
170
+ resized_image = self.resize(images, SizeDict(height=target_height, width=target_width), resample=resample)
171
+ # split the image into patches
172
+ processed_images = []
173
+ for i in range(num_blocks):
174
+ column = i % num_columns
175
+ row = i // num_columns
176
+ box = (
177
+ column * patch_size_width,
178
+ row * patch_size_height,
179
+ (column + 1) * patch_size_width,
180
+ (row + 1) * patch_size_height,
181
+ )
182
+ # split the image
183
+ patch_image = resized_image[..., box[1] : box[3], box[0] : box[2]]
184
+ processed_images.append(patch_image)
185
+
186
+ if use_thumbnail and len(processed_images) != 1:
187
+ thumbnail_img = self.resize(images, patch_size, resample=resample)
188
+ processed_images.append(thumbnail_img)
189
+
190
+ processed_images = torch.stack(processed_images, dim=0).transpose(0, 1).contiguous()
191
+
192
+ return processed_images
193
+
194
+ def _preprocess(
195
+ self,
196
+ images: list["torch.Tensor"],
197
+ do_resize: bool,
198
+ size: SizeDict,
199
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
200
+ do_rescale: bool,
201
+ rescale_factor: float,
202
+ do_normalize: bool,
203
+ image_mean: float | list[float] | None,
204
+ image_std: float | list[float] | None,
205
+ disable_grouping: bool | None,
206
+ return_tensors: str | TensorType | None,
207
+ crop_to_patches: bool = False,
208
+ min_patches: int = 1,
209
+ max_patches: int = 12,
210
+ **kwargs,
211
+ ) -> BatchFeature:
212
+ if crop_to_patches:
213
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
214
+ processed_images_grouped = {}
215
+ num_patches = {}
216
+ for shape, stacked_images in grouped_images.items():
217
+ stacked_images = self.crop_image_to_patches(
218
+ stacked_images,
219
+ min_patches,
220
+ max_patches,
221
+ patch_size=size,
222
+ resample=resample,
223
+ )
224
+ processed_images_grouped[shape] = stacked_images
225
+ num_patches[shape] = [stacked_images.shape[1]] * stacked_images.shape[0]
226
+ images = reorder_images(processed_images_grouped, grouped_images_index)
227
+ images = [image for images_list in images for image in images_list]
228
+ num_patches = reorder_images(num_patches, grouped_images_index)
229
+ else:
230
+ num_patches = [1] * len(images)
231
+
232
+ # Group images by size for batched resizing
233
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
234
+ resized_images_grouped = {}
235
+ for shape, stacked_images in grouped_images.items():
236
+ if do_resize:
237
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
238
+ resized_images_grouped[shape] = stacked_images
239
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
240
+
241
+ # Group images by size for further processing
242
+ # Needed in case do_resize is False, or resize returns images with different sizes
243
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
244
+ processed_images_grouped = {}
245
+ for shape, stacked_images in grouped_images.items():
246
+ stacked_images = self.rescale_and_normalize(
247
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
248
+ )
249
+ processed_images_grouped[shape] = stacked_images
250
+
251
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
252
+
253
+ return BatchFeature(
254
+ data={"pixel_values": processed_images, "num_patches": num_patches}, tensor_type=return_tensors
255
+ )
256
+
257
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
258
+ """
259
+ A utility that returns number patches for a given image size.
260
+
261
+ Args:
262
+ height (`int`):
263
+ Height of the input image.
264
+ width (`int`):
265
+ Width of the input image.
266
+ images_kwargs (`dict`, *optional*)
267
+ Any kwargs to override defaults of the image processor.
268
+ Returns:
269
+ `int`: Number of patches per image.
270
+ """
271
+ min_patches = images_kwargs.get("min_patches", self.min_patches) if images_kwargs else self.min_patches
272
+ max_patches = images_kwargs.get("max_patches", self.max_patches) if images_kwargs else self.max_patches
273
+ patch_size = images_kwargs.get("patch_size", self.size) if images_kwargs else self.size
274
+ crop_to_patches = (
275
+ images_kwargs.get("crop_to_patches", self.crop_to_patches) if images_kwargs else self.crop_to_patches
276
+ )
277
+
278
+ num_patches = 1
279
+ if crop_to_patches and max_patches > 1:
280
+ if isinstance(patch_size, dict):
281
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
282
+ else:
283
+ patch_height, patch_width = patch_size.height, patch_size.width
284
+ num_columns, num_rows = get_optimal_tiled_canvas(
285
+ (height, width), (patch_height, patch_width), min_patches, max_patches
286
+ )
287
+ if num_columns * num_rows > 1:
288
+ num_patches += num_columns * num_rows
289
+
290
+ return num_patches
291
+
292
+
293
+ __all__ = ["Cohere2VisionImageProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/modeling_cohere2_vision.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere2_vision/modular_cohere2_vision.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere2_vision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 the Cohere Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from dataclasses import dataclass
21
+
22
+ import torch
23
+ from torch import nn
24
+
25
+ from ...cache_utils import Cache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
32
+ from ..auto import AutoModel
33
+ from .configuration_cohere2_vision import Cohere2VisionConfig
34
+
35
+
36
+ class Cohere2VisionMultiModalProjector(nn.Module):
37
+ def __init__(self, config: Cohere2VisionConfig):
38
+ super().__init__()
39
+ self.config = config
40
+ self.downsample_factor = config.downsample_factor
41
+ self.intermediate_size = config.alignment_intermediate_size
42
+ self.linear_1 = nn.Linear(
43
+ config.vision_config.hidden_size * (config.downsample_factor**2), self.intermediate_size, bias=True
44
+ )
45
+ self.act = nn.SiLU()
46
+ self.linear_2 = nn.Linear(self.intermediate_size // 2, config.text_config.hidden_size, bias=True)
47
+
48
+ def pixel_shuffle(self, image_features): # B, S, D
49
+ batch_size, seq_length, feature_dim = image_features.shape
50
+ height = width = int(seq_length**0.5)
51
+ image_features = image_features.reshape(image_features.shape[0], width, height, -1)
52
+ channels = image_features.shape[-1]
53
+ image_features = image_features.reshape(
54
+ batch_size, width, int(height / self.downsample_factor), int(channels * self.downsample_factor)
55
+ )
56
+ image_features = image_features.permute(0, 2, 1, 3)
57
+ image_features = image_features.reshape(
58
+ batch_size, int(height / self.downsample_factor), int(width / self.downsample_factor), -1
59
+ )
60
+ image_features = image_features.permute(0, 2, 1, 3)
61
+ return image_features
62
+
63
+ def forward(self, image_features):
64
+ image_features = self.pixel_shuffle(image_features)
65
+ hidden_states = self.linear_1(image_features)
66
+
67
+ # Split along last dimension and apply SwiGLU
68
+ x, gate = hidden_states.chunk(2, dim=-1)
69
+ hidden_states = self.act(gate) * x
70
+
71
+ hidden_states = self.linear_2(hidden_states)
72
+ return hidden_states
73
+
74
+
75
+ @dataclass
76
+ @auto_docstring(
77
+ custom_intro="""
78
+ Base class for Cohere2Vision outputs, with hidden states and attentions.
79
+ """
80
+ )
81
+ class Cohere2VisionModelOutputWithPast(BaseModelOutputWithPast):
82
+ r"""
83
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
84
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
85
+
86
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
87
+ `past_key_values` input) to speed up sequential decoding.
88
+ image_hidden_states (`torch.FloatTensor`, *optional*):
89
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
90
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
91
+ """
92
+
93
+ image_hidden_states: torch.FloatTensor | None = None
94
+
95
+
96
+ @auto_docstring(
97
+ custom_intro="""
98
+ Base class for Cohere2Vision causal language model (or autoregressive) outputs.
99
+ """
100
+ )
101
+ @dataclass
102
+ class Cohere2VisionCausalLMOutputWithPast(ModelOutput):
103
+ r"""
104
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
105
+ Language modeling loss (for next-token prediction).
106
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
107
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
108
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
109
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
110
+
111
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
112
+ `past_key_values` input) to speed up sequential decoding.
113
+ image_hidden_states (`torch.FloatTensor`, *optional*):
114
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
115
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
116
+ """
117
+
118
+ loss: torch.FloatTensor | None = None
119
+ logits: torch.FloatTensor | None = None
120
+ past_key_values: Cache | None = None
121
+ hidden_states: tuple[torch.FloatTensor] | None = None
122
+ attentions: tuple[torch.FloatTensor] | None = None
123
+ image_hidden_states: torch.FloatTensor | None = None
124
+
125
+
126
+ @auto_docstring
127
+ class Cohere2VisionPreTrainedModel(PreTrainedModel):
128
+ config: Cohere2VisionConfig
129
+ base_model_prefix = "model"
130
+ input_modalities = ("image", "text")
131
+ supports_gradient_checkpointing = True
132
+ _skip_keys_device_placement = "past_key_values"
133
+
134
+ _supports_flash_attn = True
135
+ _supports_sdpa = True
136
+ _can_compile_fullgraph = False
137
+ _supports_flex_attn = True
138
+ _supports_attention_backend = True
139
+
140
+
141
+ @auto_docstring(
142
+ custom_intro="""
143
+ The Cohere2Vision model which consists of a vision backbone and a language model, without a language modeling head.
144
+ """
145
+ )
146
+ class Cohere2VisionModel(Cohere2VisionPreTrainedModel):
147
+ def __init__(self, config: Cohere2VisionConfig):
148
+ super().__init__(config)
149
+ self.vision_tower = AutoModel.from_config(config.vision_config)
150
+
151
+ self.multi_modal_projector = Cohere2VisionMultiModalProjector(config)
152
+ self.language_model = AutoModel.from_config(config.text_config)
153
+ self.post_init()
154
+
155
+ def get_input_embeddings(self):
156
+ return self.language_model.get_input_embeddings()
157
+
158
+ def set_input_embeddings(self, value):
159
+ self.language_model.set_input_embeddings(value)
160
+
161
+ @can_return_tuple
162
+ @auto_docstring(
163
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
164
+ )
165
+ def get_image_features(
166
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
167
+ ) -> tuple | BaseModelOutputWithPooling:
168
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
169
+ selected_image_feature = image_outputs.last_hidden_state
170
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature)
171
+
172
+ return image_outputs
173
+
174
+ def get_placeholder_mask(
175
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
176
+ ):
177
+ """
178
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
179
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
180
+ """
181
+ if input_ids is None:
182
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
183
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
184
+ )
185
+ special_image_mask = special_image_mask.all(-1)
186
+ else:
187
+ special_image_mask = input_ids == self.config.image_token_id
188
+
189
+ n_image_tokens = special_image_mask.sum()
190
+ n_image_features = image_features.shape[0] * image_features.shape[1]
191
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
192
+ torch_compilable_check(
193
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
194
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
195
+ )
196
+ return special_image_mask
197
+
198
+ @can_return_tuple
199
+ @auto_docstring
200
+ def forward(
201
+ self,
202
+ input_ids: torch.LongTensor | None = None,
203
+ pixel_values: torch.FloatTensor | None = None,
204
+ attention_mask: torch.Tensor | None = None,
205
+ position_ids: torch.LongTensor | None = None,
206
+ past_key_values: Cache | None = None,
207
+ inputs_embeds: torch.FloatTensor | None = None,
208
+ use_cache: bool | None = None,
209
+ **kwargs: Unpack[FlashAttentionKwargs],
210
+ ) -> tuple | Cohere2VisionModelOutputWithPast:
211
+ if (input_ids is None) ^ (inputs_embeds is not None):
212
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
213
+
214
+ if inputs_embeds is None:
215
+ inputs_embeds = self.get_input_embeddings()(input_ids)
216
+
217
+ if pixel_values is not None:
218
+ image_features = self.get_image_features(pixel_values, return_dict=True).pooler_output
219
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
220
+ special_image_mask = self.get_placeholder_mask(
221
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
222
+ )
223
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
224
+
225
+ outputs = self.language_model(
226
+ attention_mask=attention_mask,
227
+ position_ids=position_ids,
228
+ past_key_values=past_key_values,
229
+ inputs_embeds=inputs_embeds,
230
+ use_cache=use_cache,
231
+ **kwargs,
232
+ )
233
+
234
+ return Cohere2VisionModelOutputWithPast(
235
+ last_hidden_state=outputs.last_hidden_state,
236
+ past_key_values=outputs.past_key_values,
237
+ hidden_states=outputs.hidden_states,
238
+ attentions=outputs.attentions,
239
+ image_hidden_states=image_features if pixel_values is not None else None,
240
+ )
241
+
242
+
243
+ @auto_docstring(
244
+ custom_intro="""
245
+ The COHERE2_VISION model which consists of a vision backbone and a language model.
246
+ """
247
+ )
248
+ class Cohere2VisionForConditionalGeneration(Cohere2VisionPreTrainedModel, GenerationMixin):
249
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
250
+
251
+ def __init__(self, config: Cohere2VisionConfig):
252
+ super().__init__(config)
253
+ self.model = Cohere2VisionModel(config)
254
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
255
+ self.post_init()
256
+
257
+ def get_input_embeddings(self):
258
+ return self.model.get_input_embeddings()
259
+
260
+ def set_input_embeddings(self, value):
261
+ self.model.set_input_embeddings(value)
262
+
263
+ def get_output_embeddings(self) -> nn.Module:
264
+ return self.lm_head
265
+
266
+ @auto_docstring
267
+ def get_image_features(
268
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
269
+ ) -> tuple | BaseModelOutputWithPooling:
270
+ return self.model.get_image_features(pixel_values=pixel_values, **kwargs)
271
+
272
+ @can_return_tuple
273
+ @auto_docstring
274
+ def forward(
275
+ self,
276
+ input_ids: torch.LongTensor | None = None,
277
+ pixel_values: torch.FloatTensor | None = None,
278
+ attention_mask: torch.Tensor | None = None,
279
+ position_ids: torch.LongTensor | None = None,
280
+ past_key_values: Cache | None = None,
281
+ inputs_embeds: torch.FloatTensor | None = None,
282
+ labels: torch.LongTensor | None = None,
283
+ use_cache: bool | None = None,
284
+ logits_to_keep: int | torch.Tensor = 0,
285
+ image_sizes: torch.Tensor | None = None,
286
+ **kwargs: Unpack[TransformersKwargs],
287
+ ) -> tuple | Cohere2VisionCausalLMOutputWithPast:
288
+ r"""
289
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
290
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
291
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
292
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
293
+
294
+ Example:
295
+
296
+ ```python
297
+ >>> from transformers import AutoProcessor, Cohere2VisionForConditionalGeneration
298
+ >>> import torch
299
+
300
+ >>> processor = AutoProcessor.from_pretrained("CohereLabs/command-a-vision-07-2025", use_fast=True)
301
+ >>> model = Cohere2VisionForConditionalGeneration.from_pretrained("CohereLabs/command-a-vision-07-2025", device_map="auto")
302
+
303
+ >>> messages = [
304
+ ... {
305
+ ... "role": "user",
306
+ ... "content": [
307
+ ... {
308
+ ... "type": "image",
309
+ ... "url": "https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg",
310
+ ... },
311
+ ... {"type": "text", "text": "what is in this image?"},
312
+ ... ],
313
+ ... },
314
+ ... ]
315
+
316
+ >>> inputs = processor.apply_chat_template(
317
+ ... messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt",
318
+ ... ).to(model.device)
319
+
320
+ >>> gen_tokens = model.generate(**inputs, max_new_tokens=300, do_sample=True, temperature=0.3)
321
+ >>> processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
322
+ ```"""
323
+ outputs = self.model(
324
+ input_ids=input_ids,
325
+ pixel_values=pixel_values,
326
+ attention_mask=attention_mask,
327
+ position_ids=position_ids,
328
+ past_key_values=past_key_values,
329
+ inputs_embeds=inputs_embeds,
330
+ use_cache=use_cache,
331
+ image_sizes=image_sizes,
332
+ **kwargs,
333
+ )
334
+
335
+ hidden_states = outputs[0]
336
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
337
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
338
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
339
+
340
+ loss = None
341
+ if labels is not None:
342
+ loss = self.loss_function(
343
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
344
+ )
345
+
346
+ return Cohere2VisionCausalLMOutputWithPast(
347
+ loss=loss,
348
+ logits=logits,
349
+ past_key_values=outputs.past_key_values,
350
+ hidden_states=outputs.hidden_states,
351
+ attentions=outputs.attentions,
352
+ image_hidden_states=outputs.image_hidden_states,
353
+ )
354
+
355
+ def prepare_inputs_for_generation(
356
+ self,
357
+ input_ids,
358
+ past_key_values=None,
359
+ inputs_embeds=None,
360
+ pixel_values=None,
361
+ attention_mask=None,
362
+ logits_to_keep=None,
363
+ is_first_iteration=False,
364
+ **kwargs,
365
+ ):
366
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
367
+
368
+ model_inputs = super().prepare_inputs_for_generation(
369
+ input_ids,
370
+ past_key_values=past_key_values,
371
+ inputs_embeds=inputs_embeds,
372
+ attention_mask=attention_mask,
373
+ logits_to_keep=logits_to_keep,
374
+ is_first_iteration=is_first_iteration,
375
+ **kwargs,
376
+ )
377
+
378
+ if is_first_iteration or not kwargs.get("use_cache", True):
379
+ # Pixel values are used only in the first iteration if available
380
+ # In subsequent iterations, they are already merged with text and cached
381
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
382
+ # iteration with a question and cached system prompt (continue generate from cache)
383
+ model_inputs["pixel_values"] = pixel_values
384
+
385
+ return model_inputs
386
+
387
+
388
+ __all__ = ["Cohere2VisionForConditionalGeneration", "Cohere2VisionPreTrainedModel", "Cohere2VisionModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/modular_cohere2_vision.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 the Cohere Inc. 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
+ """PyTorch AyaVision model."""
15
+
16
+ from functools import lru_cache
17
+
18
+ import numpy as np
19
+ import torch
20
+ from torch import nn
21
+
22
+ from transformers.models.aya_vision.modeling_aya_vision import (
23
+ AyaVisionCausalLMOutputWithPast,
24
+ AyaVisionForConditionalGeneration,
25
+ AyaVisionModel,
26
+ AyaVisionModelOutputWithPast,
27
+ AyaVisionPreTrainedModel,
28
+ )
29
+ from transformers.models.got_ocr2.image_processing_got_ocr2 import GotOcr2ImageProcessor
30
+
31
+ from ...cache_utils import Cache
32
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from ...modeling_outputs import BaseModelOutputWithPooling
34
+ from ...processing_utils import ImagesKwargs, Unpack
35
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
36
+ from .configuration_cohere2_vision import Cohere2VisionConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class Cohere2VisionMultiModalProjector(nn.Module):
43
+ def __init__(self, config: Cohere2VisionConfig):
44
+ super().__init__()
45
+ self.config = config
46
+ self.downsample_factor = config.downsample_factor
47
+ self.intermediate_size = config.alignment_intermediate_size
48
+ self.linear_1 = nn.Linear(
49
+ config.vision_config.hidden_size * (config.downsample_factor**2), self.intermediate_size, bias=True
50
+ )
51
+ self.act = nn.SiLU()
52
+ self.linear_2 = nn.Linear(self.intermediate_size // 2, config.text_config.hidden_size, bias=True)
53
+
54
+ def pixel_shuffle(self, image_features): # B, S, D
55
+ batch_size, seq_length, feature_dim = image_features.shape
56
+ height = width = int(seq_length**0.5)
57
+ image_features = image_features.reshape(image_features.shape[0], width, height, -1)
58
+ channels = image_features.shape[-1]
59
+ image_features = image_features.reshape(
60
+ batch_size, width, int(height / self.downsample_factor), int(channels * self.downsample_factor)
61
+ )
62
+ image_features = image_features.permute(0, 2, 1, 3)
63
+ image_features = image_features.reshape(
64
+ batch_size, int(height / self.downsample_factor), int(width / self.downsample_factor), -1
65
+ )
66
+ image_features = image_features.permute(0, 2, 1, 3)
67
+ return image_features
68
+
69
+ def forward(self, image_features):
70
+ image_features = self.pixel_shuffle(image_features)
71
+ hidden_states = self.linear_1(image_features)
72
+
73
+ # Split along last dimension and apply SwiGLU
74
+ x, gate = hidden_states.chunk(2, dim=-1)
75
+ hidden_states = self.act(gate) * x
76
+
77
+ hidden_states = self.linear_2(hidden_states)
78
+ return hidden_states
79
+
80
+
81
+ class Cohere2VisionModelOutputWithPast(AyaVisionModelOutputWithPast):
82
+ pass
83
+
84
+
85
+ class Cohere2VisionCausalLMOutputWithPast(AyaVisionCausalLMOutputWithPast):
86
+ pass
87
+
88
+
89
+ class Cohere2VisionPreTrainedModel(AyaVisionPreTrainedModel):
90
+ base_model_prefix = "model"
91
+
92
+
93
+ class Cohere2VisionModel(AyaVisionModel):
94
+ @can_return_tuple
95
+ @auto_docstring(
96
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
97
+ )
98
+ def get_image_features(
99
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
100
+ ) -> tuple | BaseModelOutputWithPooling:
101
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
102
+ selected_image_feature = image_outputs.last_hidden_state
103
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature)
104
+
105
+ return image_outputs
106
+
107
+ def forward(
108
+ self,
109
+ input_ids: torch.LongTensor | None = None,
110
+ pixel_values: torch.FloatTensor | None = None,
111
+ attention_mask: torch.Tensor | None = None,
112
+ position_ids: torch.LongTensor | None = None,
113
+ past_key_values: Cache | None = None,
114
+ inputs_embeds: torch.FloatTensor | None = None,
115
+ use_cache: bool | None = None,
116
+ **kwargs: Unpack[FlashAttentionKwargs],
117
+ ) -> tuple | Cohere2VisionModelOutputWithPast:
118
+ if (input_ids is None) ^ (inputs_embeds is not None):
119
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
120
+
121
+ if inputs_embeds is None:
122
+ inputs_embeds = self.get_input_embeddings()(input_ids)
123
+
124
+ if pixel_values is not None:
125
+ image_features = self.get_image_features(pixel_values, return_dict=True).pooler_output
126
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
127
+ special_image_mask = self.get_placeholder_mask(
128
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
129
+ )
130
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
131
+
132
+ outputs = self.language_model(
133
+ attention_mask=attention_mask,
134
+ position_ids=position_ids,
135
+ past_key_values=past_key_values,
136
+ inputs_embeds=inputs_embeds,
137
+ use_cache=use_cache,
138
+ **kwargs,
139
+ )
140
+
141
+ return Cohere2VisionModelOutputWithPast(
142
+ last_hidden_state=outputs.last_hidden_state,
143
+ past_key_values=outputs.past_key_values,
144
+ hidden_states=outputs.hidden_states,
145
+ attentions=outputs.attentions,
146
+ image_hidden_states=image_features if pixel_values is not None else None,
147
+ )
148
+
149
+
150
+ class Cohere2VisionForConditionalGeneration(AyaVisionForConditionalGeneration):
151
+ @auto_docstring
152
+ def get_image_features(
153
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
154
+ ) -> tuple | BaseModelOutputWithPooling:
155
+ return self.model.get_image_features(pixel_values=pixel_values, **kwargs)
156
+
157
+ def forward(
158
+ self,
159
+ input_ids: torch.LongTensor | None = None,
160
+ pixel_values: torch.FloatTensor | None = None,
161
+ attention_mask: torch.Tensor | None = None,
162
+ position_ids: torch.LongTensor | None = None,
163
+ past_key_values: Cache | None = None,
164
+ inputs_embeds: torch.FloatTensor | None = None,
165
+ labels: torch.LongTensor | None = None,
166
+ use_cache: bool | None = None,
167
+ logits_to_keep: int | torch.Tensor = 0,
168
+ image_sizes: torch.Tensor | None = None,
169
+ **kwargs: Unpack[TransformersKwargs],
170
+ ) -> tuple | Cohere2VisionCausalLMOutputWithPast:
171
+ r"""
172
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
173
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
174
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
175
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
176
+
177
+ Example:
178
+
179
+ ```python
180
+ >>> from transformers import AutoProcessor, Cohere2VisionForConditionalGeneration
181
+ >>> import torch
182
+
183
+ >>> processor = AutoProcessor.from_pretrained("CohereLabs/command-a-vision-07-2025", use_fast=True)
184
+ >>> model = Cohere2VisionForConditionalGeneration.from_pretrained("CohereLabs/command-a-vision-07-2025", device_map="auto")
185
+
186
+ >>> messages = [
187
+ ... {
188
+ ... "role": "user",
189
+ ... "content": [
190
+ ... {
191
+ ... "type": "image",
192
+ ... "url": "https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg",
193
+ ... },
194
+ ... {"type": "text", "text": "what is in this image?"},
195
+ ... ],
196
+ ... },
197
+ ... ]
198
+
199
+ >>> inputs = processor.apply_chat_template(
200
+ ... messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt",
201
+ ... ).to(model.device)
202
+
203
+ >>> gen_tokens = model.generate(**inputs, max_new_tokens=300, do_sample=True, temperature=0.3)
204
+ >>> processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
205
+ ```"""
206
+ outputs = self.model(
207
+ input_ids=input_ids,
208
+ pixel_values=pixel_values,
209
+ attention_mask=attention_mask,
210
+ position_ids=position_ids,
211
+ past_key_values=past_key_values,
212
+ inputs_embeds=inputs_embeds,
213
+ use_cache=use_cache,
214
+ image_sizes=image_sizes,
215
+ **kwargs,
216
+ )
217
+
218
+ hidden_states = outputs[0]
219
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
220
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
221
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
222
+
223
+ loss = None
224
+ if labels is not None:
225
+ loss = self.loss_function(
226
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
227
+ )
228
+
229
+ return Cohere2VisionCausalLMOutputWithPast(
230
+ loss=loss,
231
+ logits=logits,
232
+ past_key_values=outputs.past_key_values,
233
+ hidden_states=outputs.hidden_states,
234
+ attentions=outputs.attentions,
235
+ image_hidden_states=outputs.image_hidden_states,
236
+ )
237
+
238
+
239
+ @lru_cache(maxsize=10)
240
+ def get_all_supported_aspect_ratios(max_image_tiles: int) -> list[tuple[int, int]]:
241
+ """
242
+ Computes all allowed aspect ratios for a given maximum number of input tiles.
243
+
244
+ This function calculates all possible arrangements of tiles that can be formed
245
+ within the constraint of the maximum number of tiles. Each arrangement is
246
+ represented by its aspect ratio (width/height) and the corresponding tile configuration.
247
+
248
+ Args:
249
+ max_image_tiles (`int`):
250
+ The maximum number of tiles allowed.
251
+
252
+ Returns:
253
+ `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
254
+ configuration in terms of number of tiles.
255
+
256
+ Example:
257
+ >>> get_all_supported_aspect_ratios(4)
258
+ [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)]
259
+
260
+ """
261
+ aspect_ratios = []
262
+ for width in range(1, max_image_tiles + 1):
263
+ for height in range(1, max_image_tiles + 1):
264
+ if width * height <= max_image_tiles:
265
+ aspect_ratios.append((width, height))
266
+ return aspect_ratios
267
+
268
+
269
+ def get_optimal_tiled_canvas(
270
+ original_image_size: tuple[int, int],
271
+ target_tile_size: tuple[int, int],
272
+ min_image_tiles: int,
273
+ max_image_tiles: int,
274
+ ) -> tuple[int, int]:
275
+ possible_resolutions = get_all_supported_aspect_ratios(max_image_tiles)
276
+ possible_resolutions = sorted(possible_resolutions, key=lambda x: x[0] * x[1])
277
+ image_height, image_width = original_image_size
278
+ patch_size_height, patch_size_width = target_tile_size # (height == width)
279
+
280
+ candidate_resolutions = np.array(possible_resolutions) * patch_size_height
281
+ # tiles following (width, height) order to align with aspect ratio convention
282
+ tile_size = np.stack([image_width, image_height])
283
+ required_scales = candidate_resolutions / tile_size
284
+ required_scale = np.min(required_scales, axis=-1, keepdims=True) # [n_resolutions, 1]
285
+ if np.all(required_scale < 1):
286
+ # We are forced to downscale, so try to minimize the amount of downscaling
287
+ best_grid = possible_resolutions[np.argmax(required_scale)]
288
+ else:
289
+ # Pick the resolution that required the least upscaling so that it most closely fits the image
290
+ required_scale = np.where(required_scale < 1.0, 10e9, required_scale)
291
+ best_grid = possible_resolutions[np.argmin(required_scale)]
292
+ return best_grid # (width, height)
293
+
294
+
295
+ class Cohere2VisionImageProcessorKwargs(ImagesKwargs, total=False):
296
+ r"""
297
+ crop_to_patches (`bool`, *optional*, defaults to `False`):
298
+ Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
299
+ `preprocess` method.
300
+ min_patches (`int`, *optional*, defaults to 1):
301
+ The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
302
+ set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method.
303
+ max_patches (`int`, *optional*, defaults to 12):
304
+ The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
305
+ set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method.
306
+ """
307
+
308
+ crop_to_patches: bool
309
+ min_patches: int
310
+ max_patches: int
311
+
312
+
313
+ @auto_docstring
314
+ class Cohere2VisionImageProcessor(GotOcr2ImageProcessor):
315
+ size = {"height": 512, "width": 512}
316
+ min_patches = 1
317
+ max_patches = 12
318
+ crop_to_patches = True
319
+ patch_size = 16
320
+ valid_kwargs = Cohere2VisionImageProcessorKwargs
321
+
322
+
323
+ __all__ = [
324
+ "Cohere2VisionForConditionalGeneration",
325
+ "Cohere2VisionPreTrainedModel",
326
+ "Cohere2VisionModel",
327
+ "Cohere2VisionImageProcessor",
328
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere2_vision/processing_cohere2_vision.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 HuggingFace Inc. 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
+
16
+ from ...image_processing_utils import BatchFeature
17
+ from ...image_utils import ImageInput
18
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
19
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ class Cohere2VisionProcessorKwargs(ProcessingKwargs, total=False):
24
+ _defaults = {
25
+ "text_kwargs": {
26
+ "padding_side": "left",
27
+ "padding": True,
28
+ "return_mm_token_type_ids": False,
29
+ },
30
+ }
31
+
32
+
33
+ @auto_docstring
34
+ class Cohere2VisionProcessor(ProcessorMixin):
35
+ def __init__(
36
+ self,
37
+ image_processor=None,
38
+ tokenizer=None,
39
+ chat_template=None,
40
+ **kwargs,
41
+ ):
42
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
43
+
44
+ self.patch_size = self.image_processor.patch_size
45
+ self.boi_token = tokenizer.boi_token
46
+ self.eoi_token = tokenizer.eoi_token
47
+ self.image_token = tokenizer.image_token
48
+ self.img_line_break_token = tokenizer.img_line_break_token
49
+ self.image_token_id = tokenizer.image_token_id
50
+
51
+ self.image_ids = tokenizer.convert_tokens_to_ids(
52
+ [
53
+ self.image_token,
54
+ self.boi_token,
55
+ self.eoi_token,
56
+ self.img_line_break_token,
57
+ ]
58
+ )
59
+
60
+ @auto_docstring
61
+ def __call__(
62
+ self,
63
+ images: ImageInput | None = None,
64
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
65
+ **kwargs: Unpack[Cohere2VisionProcessorKwargs],
66
+ ) -> BatchFeature:
67
+ r"""
68
+ Returns:
69
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
70
+
71
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
72
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
73
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
74
+ `None`).
75
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
76
+ """
77
+ if text is None:
78
+ raise ValueError("You have to specify text.")
79
+ elif not isinstance(text, (list, tuple)):
80
+ text = [text]
81
+
82
+ output_kwargs = self._merge_kwargs(
83
+ Cohere2VisionProcessorKwargs,
84
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
85
+ **kwargs,
86
+ )
87
+
88
+ # Process images
89
+ image_inputs = {}
90
+ if images is not None:
91
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
92
+ batch_num_patches = iter(image_inputs.pop("num_patches"))
93
+ processed_text = []
94
+ for sample in text:
95
+ while self.image_token in sample:
96
+ num_patches = next(batch_num_patches)
97
+ img_patches_per_tile = int(self.patch_size**2)
98
+
99
+ img_string = f"{self.boi_token}"
100
+ for idx in range(1, num_patches):
101
+ img_string += "<placeholder>" * img_patches_per_tile + self.img_line_break_token
102
+ img_string += "<placeholder>" * img_patches_per_tile + self.img_line_break_token
103
+ img_string += f"{self.eoi_token}"
104
+
105
+ sample = sample.replace(self.image_token, img_string, 1)
106
+ processed_text.append(sample)
107
+ text = [sample.replace("<placeholder>", self.image_token) for sample in processed_text]
108
+
109
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
110
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
111
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
112
+
113
+ if return_mm_token_type_ids:
114
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
115
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
116
+
117
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
118
+ """
119
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
120
+
121
+ Args:
122
+ image_sizes (`list[list[int]]`, *optional*):
123
+ The input sizes formatted as (height, width) per each image.
124
+
125
+ Returns:
126
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
127
+ input modalities, along with other useful data.
128
+ """
129
+
130
+ vision_data = {}
131
+ if image_sizes is not None:
132
+ images_kwargs = Cohere2VisionProcessorKwargs._defaults.get("images_kwargs", {})
133
+ images_kwargs.update(kwargs)
134
+
135
+ num_image_patches = [
136
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
137
+ for image_size in image_sizes
138
+ ]
139
+
140
+ token_per_patch = int(self.patch_size**2)
141
+ num_image_tokens = [
142
+ 2 + sum(token_per_patch + 1 for _ in range(num_patches)) for num_patches in num_image_patches
143
+ ] # Add +2 and +1 for BOI/EOI and image break tokens
144
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
145
+
146
+ return MultiModalData(**vision_data)
147
+
148
+ def batch_decode(self, *args, **kwargs):
149
+ """
150
+ This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
151
+ refer to the docstring of this method for more information.
152
+ """
153
+ return self.tokenizer.batch_decode(*args, **kwargs)
154
+
155
+ def decode(self, *args, **kwargs):
156
+ """
157
+ This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
158
+ the docstring of this method for more information.
159
+ """
160
+ return self.tokenizer.decode(*args, **kwargs)
161
+
162
+ @property
163
+ def model_input_names(self):
164
+ tokenizer_input_names = self.tokenizer.model_input_names
165
+ image_processor_input_names = self.image_processor.model_input_names
166
+ return list(tokenizer_input_names) + list(image_processor_input_names)
167
+
168
+
169
+ __all__ = ["Cohere2VisionProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_cohere_asr import *
23
+ from .feature_extraction_cohere_asr import *
24
+ from .modeling_cohere_asr import *
25
+ from .processing_cohere_asr import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/configuration_cohere_asr.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ from huggingface_hub.dataclasses import strict
16
+
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...utils import auto_docstring
19
+ from ..auto import CONFIG_MAPPING
20
+ from ..parakeet.configuration_parakeet import ParakeetEncoderConfig
21
+
22
+
23
+ @auto_docstring(checkpoint="CohereLabs/cohere-transcribe-03-2026")
24
+ @strict
25
+ class CohereAsrConfig(PreTrainedConfig):
26
+ r"""
27
+ Example:
28
+
29
+ ```python
30
+ >>> from transformers import CohereAsrForConditionalGeneration, CohereAsrConfig
31
+
32
+ >>> configuration = CohereAsrConfig()
33
+ >>> model = CohereAsrForConditionalGeneration(configuration)
34
+ >>> configuration = model.config
35
+ ```"""
36
+
37
+ model_type = "cohere_asr"
38
+ sub_configs = {"encoder_config": ParakeetEncoderConfig}
39
+
40
+ _default_encoder_config_kwargs = {
41
+ "hidden_size": 1280,
42
+ "num_hidden_layers": 48,
43
+ "num_attention_heads": 8,
44
+ "intermediate_size": 5120,
45
+ "hidden_act": "silu",
46
+ "attention_bias": True,
47
+ "convolution_bias": True,
48
+ "conv_kernel_size": 9,
49
+ "subsampling_factor": 8,
50
+ "subsampling_conv_channels": 256,
51
+ "num_mel_bins": 128,
52
+ "subsampling_conv_kernel_size": 3,
53
+ "subsampling_conv_stride": 2,
54
+ "dropout": 0.0,
55
+ "dropout_positions": 0.0,
56
+ "layerdrop": 0.0,
57
+ "activation_dropout": 0.0,
58
+ "attention_dropout": 0.0,
59
+ "max_position_embeddings": 5000,
60
+ "scale_input": False,
61
+ "initializer_range": 0.02,
62
+ }
63
+
64
+ encoder_config: dict | PreTrainedConfig | None = None
65
+ vocab_size: int = 16384
66
+ hidden_size: int = 1024
67
+ num_hidden_layers: int = 8
68
+ num_attention_heads: int = 8
69
+ num_key_value_heads: int | None = None
70
+ intermediate_size: int = 4096
71
+ hidden_act: str = "relu"
72
+ max_position_embeddings: int = 1024
73
+ pad_token_id: int | None = 2
74
+ eos_token_id: int | None = 3
75
+ bos_token_id: int | None = 4
76
+ is_encoder_decoder: bool = True
77
+ initializer_range: float = 0.02
78
+ attention_dropout: float | int = 0.0
79
+ attention_bias: bool = True
80
+ decoder_start_token_id: int | None = None
81
+ tie_word_embeddings: bool = False
82
+ head_dim: int | None = None
83
+
84
+ def __post_init__(self, **kwargs):
85
+ if self.head_dim is None:
86
+ self.head_dim = self.hidden_size // self.num_attention_heads
87
+ if self.num_key_value_heads is None:
88
+ self.num_key_value_heads = self.num_attention_heads
89
+
90
+ if isinstance(self.encoder_config, dict):
91
+ self.encoder_config["model_type"] = self.encoder_config.get("model_type", "parakeet_encoder")
92
+ self.encoder_config = CONFIG_MAPPING[self.encoder_config["model_type"]](
93
+ **{**self._default_encoder_config_kwargs, **self.encoder_config}
94
+ )
95
+ elif self.encoder_config is None:
96
+ self.encoder_config = CONFIG_MAPPING["parakeet_encoder"](**self._default_encoder_config_kwargs)
97
+
98
+ super().__post_init__(**kwargs)
99
+
100
+
101
+ __all__ = ["CohereAsrConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/feature_extraction_cohere_asr.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. 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 numpy as np
16
+ import torch
17
+
18
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
19
+ from ...feature_extraction_utils import BatchFeature
20
+ from ...utils import TensorType, is_librosa_available, logging
21
+ from ...utils.import_utils import requires
22
+
23
+
24
+ if is_librosa_available():
25
+ import librosa
26
+
27
+
28
+ EPSILON = 1e-5
29
+ LOG_ZERO_GUARD_VALUE = 2**-24
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ @requires(backends=("torch", "librosa"))
36
+ class CohereAsrFeatureExtractor(SequenceFeatureExtractor):
37
+ r"""
38
+ Constructs a CohereAsr feature extractor.
39
+
40
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
41
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
42
+
43
+ This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the `Short Time
44
+ Fourier Transform` which should match pytorch's `torch.stft` equivalent.
45
+
46
+ Args:
47
+ feature_size (`int`, *optional*, defaults to 128):
48
+ The feature dimension of the extracted features.
49
+ sampling_rate (`int`, *optional*, defaults to 16000):
50
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
51
+ hop_length (`int`, *optional*, defaults to 160):
52
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
53
+ n_fft (`int`, *optional*, defaults to 512):
54
+ Size of the Fourier transform.
55
+ win_length (`int`, *optional*, defaults to 400):
56
+ The window length for the STFT computation.
57
+ preemphasis (`float`, *optional*, defaults to 0.97):
58
+ A preemphasis filter coefficient. 0.0 means no preemphasis filter.
59
+ padding_value (`float`, *optional*, defaults to 0.0):
60
+ Padding value used to pad the audio. Should correspond to silences.
61
+ dither (`float`, *optional*, defaults to 1e-05):
62
+ Amount of deterministic dither noise to add before feature extraction. Each sample is seeded by its
63
+ valid waveform length so that dither is batch-composition invariant. Set to 0.0 to disable.
64
+ max_audio_clip_s (`float`, *optional*, defaults to 35.0):
65
+ Maximum duration in seconds for a single audio chunk. Audio longer than
66
+ `max_audio_clip_s - overlap_chunk_second` is split at energy-based boundaries.
67
+ overlap_chunk_second (`float`, *optional*, defaults to 5.0):
68
+ Size in seconds of the boundary search window used when splitting long audio. This is not actual
69
+ overlap between chunks — it defines how far back from the chunk boundary to search for a quiet
70
+ split point.
71
+ min_energy_window_samples (`int`, *optional*, defaults to 1600):
72
+ Size in samples of the sliding window used to find the quietest point when splitting audio chunks.
73
+ """
74
+
75
+ model_input_names = ["input_features", "attention_mask"]
76
+
77
+ def __init__(
78
+ self,
79
+ feature_size=128,
80
+ sampling_rate=16000,
81
+ hop_length=160,
82
+ n_fft=512,
83
+ win_length=400,
84
+ preemphasis=0.97,
85
+ padding_value=0.0,
86
+ dither=1e-5,
87
+ max_audio_clip_s=35.0,
88
+ overlap_chunk_second=5.0,
89
+ min_energy_window_samples=1600,
90
+ **kwargs,
91
+ ):
92
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
93
+
94
+ self.hop_length = hop_length
95
+ self.n_fft = n_fft
96
+ self.win_length = win_length
97
+ self.preemphasis = preemphasis
98
+ self.dither = dither
99
+ self.max_audio_clip_s = max_audio_clip_s
100
+ self.overlap_chunk_second = overlap_chunk_second
101
+ self.min_energy_window_samples = min_energy_window_samples
102
+
103
+ # TODO: @eustlb, for now we use librosa to compute the mel filters
104
+ # indeed mel_filter_bank uses np.float64 (while librosa uses np.float32), giving numerical differences
105
+ mel_filters = librosa.filters.mel(
106
+ sr=sampling_rate, n_fft=n_fft, n_mels=feature_size, fmin=0.0, fmax=sampling_rate / 2, norm="slaney"
107
+ )
108
+ self.mel_filters = torch.from_numpy(mel_filters).to(torch.float32)
109
+
110
+ def _find_split_point_energy(self, waveform: torch.Tensor, start_idx: int, end_idx: int) -> int:
111
+ segment = waveform[start_idx:end_idx]
112
+ if segment.shape[0] <= self.min_energy_window_samples:
113
+ return (start_idx + end_idx) // 2
114
+
115
+ min_energy = float("inf")
116
+ quietest_idx = start_idx
117
+ upper = segment.shape[0] - self.min_energy_window_samples
118
+ for i in range(0, upper, self.min_energy_window_samples):
119
+ window = segment[i : i + self.min_energy_window_samples]
120
+ energy = torch.sqrt(torch.mean(window * window)).item()
121
+ if energy < min_energy:
122
+ min_energy = energy
123
+ quietest_idx = start_idx + i
124
+ return quietest_idx
125
+
126
+ def _split_audio_chunks_energy(self, waveform: torch.Tensor) -> list[torch.Tensor]:
127
+ chunk_size = max(1, int(round(self.max_audio_clip_s * self.sampling_rate)))
128
+ boundary_context_size = max(1, int(round(self.overlap_chunk_second * self.sampling_rate)))
129
+ total_samples = waveform.shape[0]
130
+
131
+ if total_samples <= chunk_size:
132
+ return [waveform]
133
+
134
+ chunks_meta: list[tuple[int, int]] = []
135
+ idx = 0
136
+ while idx < total_samples:
137
+ if idx + chunk_size >= total_samples:
138
+ chunks_meta.append((idx, total_samples))
139
+ break
140
+
141
+ search_start = max(idx, idx + chunk_size - boundary_context_size)
142
+ search_end = min(idx + chunk_size, total_samples)
143
+ if search_end <= search_start:
144
+ split_point = idx + chunk_size
145
+ else:
146
+ split_point = self._find_split_point_energy(waveform, search_start, search_end)
147
+
148
+ split_point = max(idx + 1, min(split_point, total_samples))
149
+ chunks_meta.append((idx, split_point))
150
+ idx = split_point
151
+
152
+ return [waveform[start:end] for start, end in chunks_meta if end > start]
153
+
154
+ def _apply_dither(self, waveform: torch.Tensor, audio_lengths: torch.Tensor) -> torch.Tensor:
155
+ if self.dither <= 0:
156
+ return waveform
157
+ generator = torch.Generator(device=waveform.device)
158
+ for i in range(waveform.shape[0]):
159
+ valid_samples = min(int(audio_lengths[i].item()), waveform.shape[1])
160
+ if valid_samples <= 0:
161
+ continue
162
+ generator.manual_seed(valid_samples)
163
+ noise = torch.randn(valid_samples, dtype=waveform.dtype, device=waveform.device, generator=generator)
164
+ waveform[i, :valid_samples] += self.dither * noise
165
+ return waveform
166
+
167
+ def _torch_extract_fbank_features(self, waveform, device="cpu"):
168
+ # spectrogram
169
+ window = torch.hann_window(self.win_length, periodic=False, device=device)
170
+ stft = torch.stft(
171
+ waveform,
172
+ self.n_fft,
173
+ hop_length=self.hop_length,
174
+ win_length=self.win_length,
175
+ window=window,
176
+ return_complex=True,
177
+ pad_mode="constant",
178
+ )
179
+ # Let's match original implementation
180
+ magnitudes = torch.view_as_real(stft)
181
+ magnitudes = torch.sqrt(magnitudes.pow(2).sum(-1))
182
+ magnitudes = magnitudes.pow(2)
183
+
184
+ # log mel spectrogram
185
+ mel_filters = self.mel_filters.to(device)
186
+ mel_spec = mel_filters @ magnitudes
187
+ mel_spec = torch.log(mel_spec + LOG_ZERO_GUARD_VALUE)
188
+
189
+ # (batch_size, num_mel_filters, num_frames) -> (batch_size, num_frames, num_mel_filters)
190
+ mel_spec = mel_spec.permute(0, 2, 1)
191
+
192
+ return mel_spec
193
+
194
+ def __call__(
195
+ self,
196
+ raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
197
+ truncation: bool = False,
198
+ pad_to_multiple_of: int | None = None,
199
+ return_tensors: str | TensorType | None = None,
200
+ return_attention_mask: bool | None = None,
201
+ padding: str | None = "longest",
202
+ max_length: int | None = None,
203
+ sampling_rate: int | None = None,
204
+ do_normalize: bool | None = None,
205
+ device: str | None = "cpu",
206
+ return_token_timestamps: bool | None = None,
207
+ **kwargs,
208
+ ) -> BatchFeature:
209
+ """
210
+ Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch for
211
+ the STFT computation if available, otherwise a slower NumPy based one.
212
+
213
+ Args:
214
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
215
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
216
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
217
+ stereo, i.e. single float per timestep.
218
+ truncation (`bool`, *optional*, default to `True`):
219
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
220
+ pad_to_multiple_of (`int`, *optional*, defaults to None):
221
+ If set will pad the sequence to a multiple of the provided value.
222
+
223
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
224
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
225
+ return_attention_mask (`bool`, *optional*):
226
+ Whether to return the attention mask. If left to the default, will return the attention mask according
227
+ to the specific feature_extractor's default.
228
+
229
+ [What are attention masks?](../glossary#attention-mask)
230
+
231
+ <Tip>
232
+
233
+ For CohereAsr models, `attention_mask` should always be passed for batched inference, to avoid subtle
234
+ bugs.
235
+
236
+ </Tip>
237
+
238
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
239
+ If set, will return tensors instead of list of python integers. Acceptable values are:
240
+
241
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
242
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
243
+ - `'np'`: Return Numpy `np.ndarray` objects.
244
+ sampling_rate (`int`, *optional*):
245
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
246
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
247
+ pipeline.
248
+ padding_value (`float`, *optional*, defaults to 0.0):
249
+ The value that is used to fill the padding values / vectors.
250
+ do_normalize (`bool`, *optional*, defaults to `False`):
251
+ Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
252
+ improve the performance of the model.
253
+ device (`str`, *optional*, defaults to `'cpu'`):
254
+ Specifies the device for computation of the log-mel spectrogram of audio signals in the
255
+ `_torch_extract_fbank_features` method. (e.g., "cpu", "cuda")
256
+ return_token_timestamps (`bool`, *optional*, defaults to `None`):
257
+ Deprecated. Use `return_attention_mask` instead from which the number of frames can be inferred.
258
+
259
+ Whether or not to return the number of frames of the input raw_speech.
260
+ These num_frames can be used by the model to compute word level timestamps.
261
+ """
262
+ if sampling_rate is not None:
263
+ if sampling_rate != self.sampling_rate:
264
+ raise ValueError(
265
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
266
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
267
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
268
+ )
269
+ else:
270
+ logger.warning(
271
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
272
+ "Failing to do so can result in silent errors that might be hard to debug."
273
+ )
274
+
275
+ # Convert to torch tensor
276
+ if isinstance(raw_speech, np.ndarray):
277
+ raw_speech = torch.tensor(raw_speech)
278
+ elif isinstance(raw_speech, (list, tuple)) and isinstance(raw_speech[0], np.ndarray):
279
+ raw_speech = [torch.tensor(speech) for speech in raw_speech]
280
+
281
+ is_batched_torch = isinstance(raw_speech, torch.Tensor) and len(raw_speech.shape) > 1
282
+ if is_batched_torch and len(raw_speech.shape) > 2:
283
+ logger.warning(
284
+ f"Only mono-channel audio is supported for input to {self.__class__.__name__}. "
285
+ "We will take the mean of the channels to convert to mono."
286
+ )
287
+ raw_speech = raw_speech.mean(-1)
288
+
289
+ is_batched_sequence = isinstance(raw_speech, (list, tuple))
290
+ if is_batched_sequence:
291
+ for speech in raw_speech:
292
+ if len(speech.shape) > 1:
293
+ logger.warning(
294
+ f"Only mono-channel audio is supported for input to {self.__class__.__name__}. "
295
+ "We will take the mean of the channels to convert to mono."
296
+ )
297
+ speech = speech.mean(-1)
298
+
299
+ if is_batched_torch or is_batched_sequence:
300
+ raw_speech = [speech.to(torch.float32) for speech in raw_speech]
301
+ else:
302
+ raw_speech = [raw_speech.to(torch.float32)]
303
+
304
+ # Chunk long audio at energy-based boundaries
305
+ fast_path_threshold_s = max(0.0, self.max_audio_clip_s - self.overlap_chunk_second)
306
+ audio_chunk_index: list[tuple[int, int | None]] = []
307
+ chunked_speech: list[torch.Tensor] = []
308
+ for sample_idx, speech in enumerate(raw_speech):
309
+ duration_s = speech.shape[0] / self.sampling_rate
310
+ if duration_s <= fast_path_threshold_s:
311
+ chunked_speech.append(speech)
312
+ audio_chunk_index.append((sample_idx, None))
313
+ else:
314
+ chunks = self._split_audio_chunks_energy(speech)
315
+ for chunk_idx, chunk in enumerate(chunks):
316
+ chunked_speech.append(chunk)
317
+ audio_chunk_index.append((sample_idx, chunk_idx))
318
+
319
+ raw_speech = [speech[:, None] for speech in chunked_speech]
320
+
321
+ audio_lengths = [len(speech) for speech in raw_speech]
322
+ batched_speech = BatchFeature({"input_features": raw_speech, "audio_lengths": audio_lengths})
323
+
324
+ padded_inputs = self.pad(
325
+ batched_speech,
326
+ padding=padding,
327
+ max_length=max_length,
328
+ truncation=truncation,
329
+ pad_to_multiple_of=pad_to_multiple_of,
330
+ return_tensors="pt",
331
+ )
332
+ input_features = padded_inputs.input_features.squeeze(-1)
333
+
334
+ # dithering
335
+ input_features = self._apply_dither(input_features, padded_inputs.audio_lengths)
336
+
337
+ # preemphasis
338
+ if self.preemphasis is not None:
339
+ timemask = torch.arange(input_features.shape[1], device=input_features.device).unsqueeze(
340
+ 0
341
+ ) < padded_inputs.audio_lengths.unsqueeze(1)
342
+ input_features = torch.cat(
343
+ [input_features[:, :1], input_features[:, 1:] - self.preemphasis * input_features[:, :-1]], dim=1
344
+ )
345
+ input_features = input_features.masked_fill(~timemask, 0.0)
346
+
347
+ input_features = self._torch_extract_fbank_features(input_features, device)
348
+ features_lengths = torch.floor_divide(
349
+ padded_inputs.audio_lengths + self.n_fft // 2 * 2 - self.n_fft, self.hop_length
350
+ )
351
+ attention_mask = torch.arange(input_features.shape[1], device=device)[None, :] < features_lengths[:, None]
352
+
353
+ # normalize mel features, ignoring padding
354
+ mask = attention_mask.unsqueeze(-1)
355
+ input_features_masked = input_features * mask
356
+ mean = input_features_masked.sum(dim=1) / features_lengths.unsqueeze(-1)
357
+ mean = mean.unsqueeze(1)
358
+ variance = ((input_features_masked - mean) ** 2 * mask).sum(dim=1) / (features_lengths - 1).unsqueeze(-1)
359
+ std = torch.sqrt(variance).unsqueeze(1)
360
+ input_features = (input_features - mean) / (std + EPSILON)
361
+ input_features *= mask
362
+
363
+ result = BatchFeature(
364
+ data={
365
+ "input_features": input_features,
366
+ "attention_mask": attention_mask,
367
+ },
368
+ tensor_type=return_tensors,
369
+ )
370
+ result["audio_chunk_index"] = audio_chunk_index
371
+ return result
372
+
373
+
374
+ __all__ = ["CohereAsrFeatureExtractor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/modeling_cohere_asr.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cohere_asr/modular_cohere_asr.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cohere_asr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
28
+ from ...generation import GenerationMixin
29
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
30
+ from ...modeling_layers import GradientCheckpointingLayer
31
+ from ...modeling_outputs import (
32
+ BaseModelOutput,
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ Seq2SeqLMOutput,
35
+ Seq2SeqModelOutput,
36
+ )
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring
40
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
41
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
42
+ from ..auto.modeling_auto import AutoModel
43
+ from .configuration_cohere_asr import CohereAsrConfig
44
+
45
+
46
+ class CohereAsrDecoderMLP(nn.Module):
47
+ def __init__(self, config):
48
+ super().__init__()
49
+ self.config = config
50
+ self.activation_fn = ACT2FN[config.hidden_act]
51
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
52
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
53
+
54
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
55
+ hidden_states = self.fc1(hidden_states)
56
+ hidden_states = self.activation_fn(hidden_states)
57
+ hidden_states = self.fc2(hidden_states)
58
+ return hidden_states
59
+
60
+
61
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
62
+ """
63
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
64
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
65
+ """
66
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
67
+ if n_rep == 1:
68
+ return hidden_states
69
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
70
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
71
+
72
+
73
+ def eager_attention_forward(
74
+ module: nn.Module,
75
+ query: torch.Tensor,
76
+ key: torch.Tensor,
77
+ value: torch.Tensor,
78
+ attention_mask: torch.Tensor | None,
79
+ scaling: float,
80
+ dropout: float = 0.0,
81
+ **kwargs: Unpack[TransformersKwargs],
82
+ ):
83
+ key_states = repeat_kv(key, module.num_key_value_groups)
84
+ value_states = repeat_kv(value, module.num_key_value_groups)
85
+
86
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
87
+ if attention_mask is not None:
88
+ attn_weights = attn_weights + attention_mask
89
+
90
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
91
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
92
+ attn_output = torch.matmul(attn_weights, value_states)
93
+ attn_output = attn_output.transpose(1, 2).contiguous()
94
+
95
+ return attn_output, attn_weights
96
+
97
+
98
+ # Modular automatically inherits RoPE, hence no inheritance for now
99
+ class CohereAsrSelfAttention(nn.Module):
100
+ def __init__(self, config: CohereAsrConfig, layer_idx: int):
101
+ super().__init__()
102
+ self.config = config
103
+ self.layer_idx = layer_idx
104
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
105
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
106
+ self.scaling = self.head_dim**-0.5
107
+ self.attention_dropout = config.attention_dropout
108
+ self.is_causal = True
109
+
110
+ self.q_proj = nn.Linear(
111
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
112
+ )
113
+ self.k_proj = nn.Linear(
114
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
115
+ )
116
+ self.v_proj = nn.Linear(
117
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
118
+ )
119
+ self.o_proj = nn.Linear(
120
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
121
+ )
122
+
123
+ def forward(
124
+ self,
125
+ hidden_states: torch.Tensor,
126
+ attention_mask: torch.Tensor,
127
+ past_key_values: Cache | None = None,
128
+ **kwargs,
129
+ ):
130
+ input_shape = hidden_states.shape[:-1]
131
+ hidden_shape = (*input_shape, -1, self.head_dim)
132
+
133
+ query_states = self.q_proj(hidden_states)
134
+ key_states = self.k_proj(hidden_states)
135
+ value_states = self.v_proj(hidden_states)
136
+
137
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
138
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
139
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
140
+
141
+ if past_key_values is not None:
142
+ past_key_values = past_key_values.self_attention_cache
143
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
144
+
145
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
146
+ self.config._attn_implementation, eager_attention_forward
147
+ )
148
+
149
+ attn_output, attn_weights = attention_interface(
150
+ self,
151
+ query_states,
152
+ key_states,
153
+ value_states,
154
+ attention_mask,
155
+ dropout=0.0 if not self.training else self.attention_dropout,
156
+ scaling=self.scaling,
157
+ **kwargs,
158
+ )
159
+
160
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
161
+ attn_output = self.o_proj(attn_output)
162
+ return attn_output, attn_weights
163
+
164
+
165
+ # Modular automatically inherits RoPE, hence no inheritance for now
166
+ class CohereAsrCrossAttention(nn.Module):
167
+ def __init__(self, config: CohereAsrConfig, layer_idx: int):
168
+ super().__init__()
169
+ self.config = config
170
+ self.layer_idx = layer_idx
171
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
172
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
173
+ self.scaling = self.head_dim**-0.5
174
+ self.attention_dropout = config.attention_dropout
175
+ self.is_causal = False
176
+
177
+ self.q_proj = nn.Linear(
178
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
179
+ )
180
+ self.k_proj = nn.Linear(
181
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
182
+ )
183
+ self.v_proj = nn.Linear(
184
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
185
+ )
186
+ self.o_proj = nn.Linear(
187
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
188
+ )
189
+
190
+ def forward(
191
+ self,
192
+ hidden_states: torch.Tensor,
193
+ encoder_hidden_states: torch.Tensor | None = None,
194
+ attention_mask: torch.Tensor | None = None,
195
+ past_key_values: Cache | None = None,
196
+ **kwargs: Unpack[TransformersKwargs],
197
+ ):
198
+ # determine input shapes
199
+ bsz, tgt_len = hidden_states.shape[:-1]
200
+ src_len = encoder_hidden_states.shape[1]
201
+
202
+ q_input_shape = (bsz, tgt_len, -1, self.head_dim)
203
+ kv_input_shape = (bsz, src_len, -1, self.head_dim)
204
+
205
+ # get query proj
206
+ query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
207
+
208
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
209
+ if past_key_values is not None and is_updated:
210
+ # reuse k,v, cross_attentions
211
+ key_states = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
212
+ value_states = past_key_values.cross_attention_cache.layers[self.layer_idx].values
213
+ else:
214
+ key_states = self.k_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2)
215
+ value_states = self.v_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2)
216
+
217
+ if past_key_values is not None:
218
+ # save all states to the cache
219
+ key_states, value_states = past_key_values.cross_attention_cache.update(
220
+ key_states, value_states, self.layer_idx
221
+ )
222
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
223
+ past_key_values.is_updated[self.layer_idx] = True
224
+
225
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
226
+ self.config._attn_implementation, eager_attention_forward
227
+ )
228
+
229
+ attn_output, attn_weights = attention_interface(
230
+ self,
231
+ query_states,
232
+ key_states,
233
+ value_states,
234
+ attention_mask,
235
+ dropout=0.0 if not self.training else self.attention_dropout,
236
+ scaling=self.scaling,
237
+ **kwargs,
238
+ )
239
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
240
+ attn_output = self.o_proj(attn_output)
241
+ return attn_output, attn_weights
242
+
243
+
244
+ class CohereAsrDecoderLayer(GradientCheckpointingLayer):
245
+ def __init__(self, config, layer_idx=None):
246
+ super().__init__()
247
+ self.self_attn = CohereAsrSelfAttention(config=config, layer_idx=layer_idx)
248
+ self.encoder_attn = CohereAsrCrossAttention(config=config, layer_idx=layer_idx)
249
+
250
+ self.mlp = CohereAsrDecoderMLP(config)
251
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
252
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
253
+ self.final_layernorm = nn.LayerNorm(config.hidden_size)
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ attention_mask: torch.Tensor | None = None,
259
+ encoder_hidden_states: torch.Tensor | None = None,
260
+ encoder_attention_mask: torch.Tensor | None = None,
261
+ position_ids: torch.LongTensor | None = None,
262
+ encoder_position_ids: torch.LongTensor | None = None,
263
+ past_key_values: Cache | None = None,
264
+ **kwargs: Unpack[TransformersKwargs],
265
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
266
+ residual = hidden_states
267
+ hidden_states = self.input_layernorm(hidden_states)
268
+
269
+ hidden_states, _ = self.self_attn(
270
+ hidden_states=hidden_states,
271
+ attention_mask=attention_mask,
272
+ position_ids=position_ids,
273
+ past_key_values=past_key_values,
274
+ **kwargs,
275
+ )
276
+ hidden_states = residual + hidden_states
277
+
278
+ if encoder_hidden_states is not None:
279
+ residual = hidden_states
280
+ hidden_states = self.post_attention_layernorm(hidden_states)
281
+ hidden_states, _ = self.encoder_attn(
282
+ hidden_states=hidden_states,
283
+ encoder_hidden_states=encoder_hidden_states,
284
+ attention_mask=encoder_attention_mask,
285
+ past_key_values=past_key_values,
286
+ )
287
+ hidden_states = residual + hidden_states
288
+
289
+ residual = hidden_states
290
+ hidden_states = self.final_layernorm(hidden_states)
291
+ hidden_states = self.mlp(hidden_states)
292
+ hidden_states = residual + hidden_states
293
+ return hidden_states
294
+
295
+
296
+ @auto_docstring
297
+ class CohereAsrPreTrainedModel(PreTrainedModel):
298
+ config: CohereAsrConfig
299
+ base_model_prefix = "model"
300
+ main_input_name = "input_features"
301
+ input_modalities = "audio"
302
+ supports_gradient_checkpointing = True
303
+ _no_split_modules = ["CohereAsrEncoderLayer", "CohereAsrDecoderLayer"]
304
+ _supports_flash_attn = True
305
+ _supports_sdpa = True
306
+
307
+ _can_compile_fullgraph = True
308
+ _keys_to_ignore_on_load_unexpected = [r"preprocessor\.featurizer\..*"]
309
+ # TODO arthur, how do we separate when it cross / self coming from different layer?
310
+
311
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
312
+ """
313
+ Computes the output length of the convolutional layers
314
+ """
315
+ output_conv1_length = int((input_lengths - 127) / 64 + 1)
316
+ output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
317
+ output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
318
+
319
+ return output_conv3_length
320
+
321
+
322
+ @auto_docstring
323
+ class CohereAsrDecoder(CohereAsrPreTrainedModel):
324
+ main_input_name = "input_ids"
325
+ _can_record_outputs = {
326
+ "attentions": OutputRecorder(CohereAsrSelfAttention, index=1, layer_name="self_attn"),
327
+ "hidden_states": CohereAsrDecoderLayer,
328
+ "cross_attentions": OutputRecorder(CohereAsrCrossAttention, index=1, layer_name="encoder_attn"),
329
+ }
330
+
331
+ def __init__(self, config):
332
+ super().__init__(config)
333
+ self.padding_idx = config.pad_token_id
334
+ self.vocab_size = config.vocab_size
335
+
336
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
337
+ self.layers = nn.ModuleList([CohereAsrDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
338
+ self.norm = nn.LayerNorm(config.hidden_size)
339
+ self.gradient_checkpointing = False
340
+ self.pos_emb = nn.Embedding(config.max_position_embeddings, config.hidden_size)
341
+ self.embedding_layernorm = nn.LayerNorm(config.hidden_size)
342
+ self.proj = nn.Linear(config.encoder_config.hidden_size, config.hidden_size, bias=True)
343
+
344
+ # Initialize weights and apply final processing
345
+ self.post_init()
346
+
347
+ @merge_with_config_defaults
348
+ @capture_outputs
349
+ def forward(
350
+ self,
351
+ input_ids: torch.LongTensor | None = None,
352
+ attention_mask: torch.Tensor | None = None,
353
+ position_ids: torch.LongTensor | None = None,
354
+ past_key_values: Cache | None = None,
355
+ inputs_embeds: torch.FloatTensor | None = None,
356
+ use_cache: bool | None = None,
357
+ encoder_hidden_states: torch.FloatTensor | None = None,
358
+ encoder_attention_mask: torch.Tensor | None = None,
359
+ **kwargs: Unpack[TransformersKwargs],
360
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
361
+ r"""
362
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
363
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
364
+ of the decoder.
365
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
366
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
367
+ - 1 for tokens that are **not masked**,
368
+ - 0 for tokens that are **masked**.
369
+ [What are attention masks?](../glossary#attention-mask)
370
+ """
371
+ encoder_hidden_states = self.proj(encoder_hidden_states)
372
+ if (input_ids is None) ^ (inputs_embeds is not None):
373
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
374
+
375
+ if inputs_embeds is None:
376
+ inputs_embeds = self.embed_tokens(input_ids)
377
+
378
+ if use_cache and past_key_values is None:
379
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
380
+
381
+ if position_ids is None:
382
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
383
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
384
+ position_ids = position_ids.unsqueeze(0)
385
+
386
+ # Fixed sinusoidal position embedding added to token embeddings, then layernorm
387
+ pos_emb = self.pos_emb(position_ids.squeeze(0))
388
+ pos_emb = pos_emb.to(inputs_embeds.device)
389
+ inputs_embeds = self.embedding_layernorm(inputs_embeds + pos_emb)
390
+
391
+ causal_mask = create_causal_mask(
392
+ config=self.config,
393
+ inputs_embeds=inputs_embeds,
394
+ attention_mask=attention_mask,
395
+ past_key_values=past_key_values,
396
+ position_ids=position_ids,
397
+ )
398
+ encoder_attention_mask = create_bidirectional_mask(
399
+ config=self.config,
400
+ inputs_embeds=inputs_embeds,
401
+ attention_mask=encoder_attention_mask,
402
+ encoder_hidden_states=encoder_hidden_states,
403
+ )
404
+
405
+ hidden_states = inputs_embeds
406
+ for decoder_layer in self.layers:
407
+ hidden_states = decoder_layer(
408
+ hidden_states,
409
+ causal_mask,
410
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
411
+ encoder_attention_mask=encoder_attention_mask,
412
+ position_ids=position_ids,
413
+ past_key_values=past_key_values,
414
+ **kwargs,
415
+ )
416
+
417
+ hidden_states = self.norm(hidden_states)
418
+
419
+ return BaseModelOutputWithPastAndCrossAttentions(
420
+ last_hidden_state=hidden_states,
421
+ past_key_values=past_key_values if use_cache else None,
422
+ )
423
+
424
+
425
+ @auto_docstring
426
+ class CohereAsrModel(CohereAsrPreTrainedModel):
427
+ def __init__(self, config):
428
+ super().__init__(config)
429
+ self.encoder = AutoModel.from_config(config.encoder_config)
430
+ self.decoder = CohereAsrDecoder(config)
431
+ # Initialize weights and apply final processing
432
+ self.post_init()
433
+
434
+ def get_input_embeddings(self):
435
+ return self.decoder.embed_tokens
436
+
437
+ def set_input_embeddings(self, value):
438
+ self.decoder.embed_tokens = value
439
+
440
+ def freeze_encoder(self):
441
+ """
442
+ Calling this function will disable the gradient computation for the CohereAsr encoder so that its parameters will
443
+ not be updated during training.
444
+ """
445
+ self.encoder._freeze_parameters()
446
+
447
+ def _mask_input_features(self):
448
+ """
449
+ Masks extracted features along time axis and/or along feature axis according to
450
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
451
+ """
452
+ raise AttributeError("Not needed for CohereAsr")
453
+
454
+ @can_return_tuple
455
+ @auto_docstring
456
+ def forward(
457
+ self,
458
+ input_features: torch.FloatTensor | None = None,
459
+ attention_mask: torch.LongTensor | None = None,
460
+ decoder_input_ids: torch.LongTensor | None = None,
461
+ decoder_attention_mask: torch.LongTensor | None = None,
462
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
463
+ past_key_values: EncoderDecoderCache | None = None,
464
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
465
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
466
+ use_cache: bool | None = None,
467
+ **kwargs: Unpack[TransformersKwargs],
468
+ ) -> Seq2SeqModelOutput:
469
+ r"""
470
+ input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
471
+ Float values of the raw speech waveform. Raw speech waveform can be
472
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
473
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
474
+ the soundfile library (`pip install soundfile`). To prepare the array into
475
+ `input_features`, the [`AutoFeatureExtractor`] should be used for padding
476
+ and conversion into a tensor of type `torch.FloatTensor`.
477
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
478
+ Indices of positions of each input sequence tokens in the position embeddings.
479
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
480
+
481
+ Example:
482
+
483
+ ```python
484
+ >>> import torch
485
+ >>> from transformers import AutoFeatureExtractor, CohereAsrModel
486
+ >>> from datasets import load_dataset
487
+
488
+ >>> model = CohereAsrModel.from_pretrained("UsefulSensors/cohere_asr-tiny")
489
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/cohere_asr-tiny")
490
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
491
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
492
+ >>> input_features = inputs.input_features
493
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
494
+ >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
495
+ >>> list(last_hidden_state.shape)
496
+ [1, 2, 288]
497
+ ```
498
+ """
499
+ # Main difference: uses `input_features` instead of `input_values`
500
+ if encoder_outputs is None:
501
+ encoder_outputs: BaseModelOutput = self.encoder(input_features, attention_mask=attention_mask, **kwargs)
502
+
503
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
504
+ input_ids=decoder_input_ids,
505
+ attention_mask=decoder_attention_mask,
506
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
507
+ encoder_attention_mask=encoder_outputs.attention_mask,
508
+ past_key_values=past_key_values,
509
+ inputs_embeds=decoder_inputs_embeds,
510
+ position_ids=decoder_position_ids,
511
+ use_cache=use_cache,
512
+ **kwargs,
513
+ )
514
+
515
+ return Seq2SeqModelOutput(
516
+ last_hidden_state=decoder_outputs.last_hidden_state,
517
+ past_key_values=decoder_outputs.past_key_values,
518
+ decoder_hidden_states=decoder_outputs.hidden_states,
519
+ decoder_attentions=decoder_outputs.attentions,
520
+ cross_attentions=decoder_outputs.cross_attentions,
521
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
522
+ encoder_hidden_states=encoder_outputs.hidden_states,
523
+ encoder_attentions=encoder_outputs.attentions,
524
+ )
525
+
526
+
527
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
528
+ """
529
+ Shift input ids one token to the right.
530
+ """
531
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
532
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
533
+ shifted_input_ids[:, 0] = decoder_start_token_id
534
+
535
+ if pad_token_id is None:
536
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
537
+ # replace possible -100 values in labels by `pad_token_id`
538
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
539
+
540
+ return shifted_input_ids
541
+
542
+
543
+ @auto_docstring(
544
+ custom_intro="""
545
+ The CohereAsr Model with a language modeling head. Can be used for automatic speech recognition.
546
+ """
547
+ )
548
+ class CohereAsrForConditionalGeneration(CohereAsrPreTrainedModel, GenerationMixin):
549
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
550
+
551
+ def __init__(self, config):
552
+ super().__init__(config)
553
+ self.model = CohereAsrModel(config)
554
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
555
+
556
+ # Initialize weights and apply final processing
557
+ self.post_init()
558
+
559
+ def get_output_embeddings(self):
560
+ return self.proj_out
561
+
562
+ def set_output_embeddings(self, new_embeddings):
563
+ self.proj_out = new_embeddings
564
+
565
+ def get_input_embeddings(self) -> nn.Module:
566
+ return self.model.get_input_embeddings()
567
+
568
+ @can_return_tuple
569
+ @auto_docstring
570
+ def forward(
571
+ self,
572
+ input_features: torch.FloatTensor | None = None,
573
+ attention_mask: torch.LongTensor | None = None,
574
+ decoder_input_ids: torch.LongTensor | None = None,
575
+ decoder_attention_mask: torch.LongTensor | None = None,
576
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
577
+ past_key_values: EncoderDecoderCache | None = None,
578
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
579
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
580
+ use_cache: bool | None = None,
581
+ labels: torch.LongTensor | None = None,
582
+ **kwargs: Unpack[TransformersKwargs],
583
+ ) -> Seq2SeqLMOutput:
584
+ r"""
585
+ input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
586
+ Float values of the raw speech waveform. Raw speech waveform can be
587
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
588
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
589
+ the soundfile library (`pip install soundfile`). To prepare the array into
590
+ `input_features`, the [`AutoFeatureExtractor`] should be used for padding
591
+ and conversion into a tensor of type `torch.FloatTensor`.
592
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
593
+ Indices of positions of each input sequence tokens in the position embeddings.
594
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
595
+
596
+ Example:
597
+
598
+ ```python
599
+ >>> import torch
600
+ >>> from transformers import AutoProcessor, CohereAsrForConditionalGeneration
601
+ >>> from datasets import load_dataset
602
+
603
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/cohere_asr-tiny")
604
+ >>> model = CohereAsrForConditionalGeneration.from_pretrained("UsefulSensors/cohere_asr-tiny")
605
+
606
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
607
+
608
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
609
+ >>> input_features = inputs.input_features
610
+
611
+ >>> generated_ids = model.generate(input_features, max_new_tokens=100)
612
+
613
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
614
+ >>> transcription
615
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
616
+ ```"""
617
+ # Main difference: uses `input_features` instead of `input_values`
618
+ if labels is not None:
619
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
620
+ decoder_input_ids = shift_tokens_right(
621
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
622
+ )
623
+
624
+ outputs: Seq2SeqModelOutput = self.model(
625
+ input_features,
626
+ attention_mask=attention_mask,
627
+ decoder_input_ids=decoder_input_ids,
628
+ encoder_outputs=encoder_outputs,
629
+ decoder_attention_mask=decoder_attention_mask,
630
+ past_key_values=past_key_values,
631
+ decoder_inputs_embeds=decoder_inputs_embeds,
632
+ decoder_position_ids=decoder_position_ids,
633
+ use_cache=use_cache,
634
+ **kwargs,
635
+ )
636
+ logits = self.proj_out(outputs.last_hidden_state)
637
+
638
+ loss = None
639
+ if labels is not None:
640
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
641
+
642
+ return Seq2SeqLMOutput(
643
+ loss=loss,
644
+ logits=logits,
645
+ past_key_values=outputs.past_key_values,
646
+ decoder_hidden_states=outputs.decoder_hidden_states,
647
+ decoder_attentions=outputs.decoder_attentions,
648
+ cross_attentions=outputs.cross_attentions,
649
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
650
+ encoder_hidden_states=outputs.encoder_hidden_states,
651
+ encoder_attentions=outputs.encoder_attentions,
652
+ )
653
+
654
+ def prepare_inputs_for_generation(self, *args, audio_chunk_index=None, **kwargs):
655
+ # audio_chunk_index is returned by the processor but not used by the model, absorb it here
656
+ return super().prepare_inputs_for_generation(*args, **kwargs)
657
+
658
+
659
+ __all__ = ["CohereAsrPreTrainedModel", "CohereAsrModel", "CohereAsrForConditionalGeneration"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/modular_cohere_asr.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ from collections.abc import Callable
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
21
+ from ...generation import GenerationMixin
22
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
23
+ from ...modeling_layers import GradientCheckpointingLayer
24
+ from ...modeling_outputs import (
25
+ BaseModelOutput,
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ Seq2SeqLMOutput,
28
+ Seq2SeqModelOutput,
29
+ )
30
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
31
+ from ...processing_utils import Unpack
32
+ from ...utils import TransformersKwargs, auto_docstring
33
+ from ...utils.generic import can_return_tuple
34
+ from ...utils.output_capturing import OutputRecorder
35
+ from ..auto.modeling_auto import AutoModel
36
+ from ..clip.modeling_clip import CLIPMLP
37
+ from ..moonshine.modeling_moonshine import (
38
+ MoonshineDecoder,
39
+ MoonshineForConditionalGeneration,
40
+ MoonshineModel,
41
+ MoonshinePreTrainedModel,
42
+ eager_attention_forward,
43
+ shift_tokens_right,
44
+ )
45
+ from .configuration_cohere_asr import CohereAsrConfig
46
+
47
+
48
+ class CohereAsrDecoderMLP(CLIPMLP):
49
+ pass
50
+
51
+
52
+ # Modular automatically inherits RoPE, hence no inheritance for now
53
+ class CohereAsrSelfAttention(nn.Module):
54
+ def __init__(self, config: CohereAsrConfig, layer_idx: int):
55
+ super().__init__()
56
+ self.config = config
57
+ self.layer_idx = layer_idx
58
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
59
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
60
+ self.scaling = self.head_dim**-0.5
61
+ self.attention_dropout = config.attention_dropout
62
+ self.is_causal = True
63
+
64
+ self.q_proj = nn.Linear(
65
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
66
+ )
67
+ self.k_proj = nn.Linear(
68
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
69
+ )
70
+ self.v_proj = nn.Linear(
71
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
72
+ )
73
+ self.o_proj = nn.Linear(
74
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
75
+ )
76
+
77
+ def forward(
78
+ self,
79
+ hidden_states: torch.Tensor,
80
+ attention_mask: torch.Tensor,
81
+ past_key_values: Cache | None = None,
82
+ **kwargs,
83
+ ):
84
+ input_shape = hidden_states.shape[:-1]
85
+ hidden_shape = (*input_shape, -1, self.head_dim)
86
+
87
+ query_states = self.q_proj(hidden_states)
88
+ key_states = self.k_proj(hidden_states)
89
+ value_states = self.v_proj(hidden_states)
90
+
91
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
92
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
93
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
94
+
95
+ if past_key_values is not None:
96
+ past_key_values = past_key_values.self_attention_cache
97
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
98
+
99
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
100
+ self.config._attn_implementation, eager_attention_forward
101
+ )
102
+
103
+ attn_output, attn_weights = attention_interface(
104
+ self,
105
+ query_states,
106
+ key_states,
107
+ value_states,
108
+ attention_mask,
109
+ dropout=0.0 if not self.training else self.attention_dropout,
110
+ scaling=self.scaling,
111
+ **kwargs,
112
+ )
113
+
114
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
115
+ attn_output = self.o_proj(attn_output)
116
+ return attn_output, attn_weights
117
+
118
+
119
+ # Modular automatically inherits RoPE, hence no inheritance for now
120
+ class CohereAsrCrossAttention(nn.Module):
121
+ def __init__(self, config: CohereAsrConfig, layer_idx: int):
122
+ super().__init__()
123
+ self.config = config
124
+ self.layer_idx = layer_idx
125
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
126
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
127
+ self.scaling = self.head_dim**-0.5
128
+ self.attention_dropout = config.attention_dropout
129
+ self.is_causal = False
130
+
131
+ self.q_proj = nn.Linear(
132
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
133
+ )
134
+ self.k_proj = nn.Linear(
135
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
136
+ )
137
+ self.v_proj = nn.Linear(
138
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
139
+ )
140
+ self.o_proj = nn.Linear(
141
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
142
+ )
143
+
144
+ def forward(
145
+ self,
146
+ hidden_states: torch.Tensor,
147
+ encoder_hidden_states: torch.Tensor | None = None,
148
+ attention_mask: torch.Tensor | None = None,
149
+ past_key_values: Cache | None = None,
150
+ **kwargs: Unpack[TransformersKwargs],
151
+ ):
152
+ # determine input shapes
153
+ bsz, tgt_len = hidden_states.shape[:-1]
154
+ src_len = encoder_hidden_states.shape[1]
155
+
156
+ q_input_shape = (bsz, tgt_len, -1, self.head_dim)
157
+ kv_input_shape = (bsz, src_len, -1, self.head_dim)
158
+
159
+ # get query proj
160
+ query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
161
+
162
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
163
+ if past_key_values is not None and is_updated:
164
+ # reuse k,v, cross_attentions
165
+ key_states = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
166
+ value_states = past_key_values.cross_attention_cache.layers[self.layer_idx].values
167
+ else:
168
+ key_states = self.k_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2)
169
+ value_states = self.v_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2)
170
+
171
+ if past_key_values is not None:
172
+ # save all states to the cache
173
+ key_states, value_states = past_key_values.cross_attention_cache.update(
174
+ key_states, value_states, self.layer_idx
175
+ )
176
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
177
+ past_key_values.is_updated[self.layer_idx] = True
178
+
179
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
180
+ self.config._attn_implementation, eager_attention_forward
181
+ )
182
+
183
+ attn_output, attn_weights = attention_interface(
184
+ self,
185
+ query_states,
186
+ key_states,
187
+ value_states,
188
+ attention_mask,
189
+ dropout=0.0 if not self.training else self.attention_dropout,
190
+ scaling=self.scaling,
191
+ **kwargs,
192
+ )
193
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
194
+ attn_output = self.o_proj(attn_output)
195
+ return attn_output, attn_weights
196
+
197
+
198
+ class CohereAsrDecoderLayer(GradientCheckpointingLayer):
199
+ def __init__(self, config, layer_idx=None):
200
+ super().__init__()
201
+ self.self_attn = CohereAsrSelfAttention(config=config, layer_idx=layer_idx)
202
+ self.encoder_attn = CohereAsrCrossAttention(config=config, layer_idx=layer_idx)
203
+
204
+ self.mlp = CohereAsrDecoderMLP(config)
205
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
206
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
207
+ self.final_layernorm = nn.LayerNorm(config.hidden_size)
208
+
209
+ def forward(
210
+ self,
211
+ hidden_states: torch.Tensor,
212
+ attention_mask: torch.Tensor | None = None,
213
+ encoder_hidden_states: torch.Tensor | None = None,
214
+ encoder_attention_mask: torch.Tensor | None = None,
215
+ position_ids: torch.LongTensor | None = None,
216
+ encoder_position_ids: torch.LongTensor | None = None,
217
+ past_key_values: Cache | None = None,
218
+ **kwargs: Unpack[TransformersKwargs],
219
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
220
+ residual = hidden_states
221
+ hidden_states = self.input_layernorm(hidden_states)
222
+
223
+ hidden_states, _ = self.self_attn(
224
+ hidden_states=hidden_states,
225
+ attention_mask=attention_mask,
226
+ position_ids=position_ids,
227
+ past_key_values=past_key_values,
228
+ **kwargs,
229
+ )
230
+ hidden_states = residual + hidden_states
231
+
232
+ if encoder_hidden_states is not None:
233
+ residual = hidden_states
234
+ hidden_states = self.post_attention_layernorm(hidden_states)
235
+ hidden_states, _ = self.encoder_attn(
236
+ hidden_states=hidden_states,
237
+ encoder_hidden_states=encoder_hidden_states,
238
+ attention_mask=encoder_attention_mask,
239
+ past_key_values=past_key_values,
240
+ )
241
+ hidden_states = residual + hidden_states
242
+
243
+ residual = hidden_states
244
+ hidden_states = self.final_layernorm(hidden_states)
245
+ hidden_states = self.mlp(hidden_states)
246
+ hidden_states = residual + hidden_states
247
+ return hidden_states
248
+
249
+
250
+ class CohereAsrPreTrainedModel(MoonshinePreTrainedModel):
251
+ main_input_name = "input_features"
252
+ _keys_to_ignore_on_load_unexpected = [r"preprocessor\.featurizer\..*"]
253
+
254
+
255
+ class CohereAsrDecoder(MoonshineDecoder):
256
+ _can_record_outputs = {
257
+ "attentions": OutputRecorder(CohereAsrSelfAttention, index=1, layer_name="self_attn"),
258
+ "hidden_states": CohereAsrDecoderLayer,
259
+ "cross_attentions": OutputRecorder(CohereAsrCrossAttention, index=1, layer_name="encoder_attn"),
260
+ }
261
+
262
+ def __init__(self, config):
263
+ super().__init__(config)
264
+ del self.rotary_emb
265
+ self.norm = nn.LayerNorm(config.hidden_size)
266
+ self.pos_emb = nn.Embedding(config.max_position_embeddings, config.hidden_size)
267
+ self.embedding_layernorm = nn.LayerNorm(config.hidden_size)
268
+ self.proj = nn.Linear(config.encoder_config.hidden_size, config.hidden_size, bias=True)
269
+ self.post_init()
270
+
271
+ def forward(
272
+ self,
273
+ input_ids: torch.LongTensor | None = None,
274
+ attention_mask: torch.Tensor | None = None,
275
+ position_ids: torch.LongTensor | None = None,
276
+ past_key_values: Cache | None = None,
277
+ inputs_embeds: torch.FloatTensor | None = None,
278
+ use_cache: bool | None = None,
279
+ encoder_hidden_states: torch.FloatTensor | None = None,
280
+ encoder_attention_mask: torch.Tensor | None = None,
281
+ **kwargs: Unpack[TransformersKwargs],
282
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
283
+ r"""
284
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
285
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
286
+ of the decoder.
287
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
288
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
289
+ - 1 for tokens that are **not masked**,
290
+ - 0 for tokens that are **masked**.
291
+ [What are attention masks?](../glossary#attention-mask)
292
+ """
293
+ encoder_hidden_states = self.proj(encoder_hidden_states)
294
+ if (input_ids is None) ^ (inputs_embeds is not None):
295
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
296
+
297
+ if inputs_embeds is None:
298
+ inputs_embeds = self.embed_tokens(input_ids)
299
+
300
+ if use_cache and past_key_values is None:
301
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
302
+
303
+ if position_ids is None:
304
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
305
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
306
+ position_ids = position_ids.unsqueeze(0)
307
+
308
+ # Fixed sinusoidal position embedding added to token embeddings, then layernorm
309
+ pos_emb = self.pos_emb(position_ids.squeeze(0))
310
+ pos_emb = pos_emb.to(inputs_embeds.device)
311
+ inputs_embeds = self.embedding_layernorm(inputs_embeds + pos_emb)
312
+
313
+ causal_mask = create_causal_mask(
314
+ config=self.config,
315
+ inputs_embeds=inputs_embeds,
316
+ attention_mask=attention_mask,
317
+ past_key_values=past_key_values,
318
+ position_ids=position_ids,
319
+ )
320
+ encoder_attention_mask = create_bidirectional_mask(
321
+ config=self.config,
322
+ inputs_embeds=inputs_embeds,
323
+ attention_mask=encoder_attention_mask,
324
+ encoder_hidden_states=encoder_hidden_states,
325
+ )
326
+
327
+ hidden_states = inputs_embeds
328
+ for decoder_layer in self.layers:
329
+ hidden_states = decoder_layer(
330
+ hidden_states,
331
+ causal_mask,
332
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
333
+ encoder_attention_mask=encoder_attention_mask,
334
+ position_ids=position_ids,
335
+ past_key_values=past_key_values,
336
+ **kwargs,
337
+ )
338
+
339
+ hidden_states = self.norm(hidden_states)
340
+
341
+ return BaseModelOutputWithPastAndCrossAttentions(
342
+ last_hidden_state=hidden_states,
343
+ past_key_values=past_key_values if use_cache else None,
344
+ )
345
+
346
+
347
+ class CohereAsrModel(MoonshineModel):
348
+ def __init__(self, config):
349
+ super().__init__(config)
350
+ self.encoder = AutoModel.from_config(config.encoder_config)
351
+
352
+ @can_return_tuple
353
+ @auto_docstring
354
+ def forward(
355
+ self,
356
+ input_features: torch.FloatTensor | None = None,
357
+ attention_mask: torch.LongTensor | None = None,
358
+ decoder_input_ids: torch.LongTensor | None = None,
359
+ decoder_attention_mask: torch.LongTensor | None = None,
360
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
361
+ past_key_values: EncoderDecoderCache | None = None,
362
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
363
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
364
+ use_cache: bool | None = None,
365
+ **kwargs: Unpack[TransformersKwargs],
366
+ ) -> Seq2SeqModelOutput:
367
+ r"""
368
+ input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
369
+ Float values of the raw speech waveform. Raw speech waveform can be
370
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
371
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
372
+ the soundfile library (`pip install soundfile`). To prepare the array into
373
+ `input_features`, the [`AutoFeatureExtractor`] should be used for padding
374
+ and conversion into a tensor of type `torch.FloatTensor`.
375
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
376
+ Indices of positions of each input sequence tokens in the position embeddings.
377
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
378
+
379
+ Example:
380
+
381
+ ```python
382
+ >>> import torch
383
+ >>> from transformers import AutoFeatureExtractor, CohereAsrModel
384
+ >>> from datasets import load_dataset
385
+
386
+ >>> model = CohereAsrModel.from_pretrained("UsefulSensors/cohere_asr-tiny")
387
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/cohere_asr-tiny")
388
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
389
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
390
+ >>> input_features = inputs.input_features
391
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
392
+ >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
393
+ >>> list(last_hidden_state.shape)
394
+ [1, 2, 288]
395
+ ```
396
+ """
397
+ # Main difference: uses `input_features` instead of `input_values`
398
+ if encoder_outputs is None:
399
+ encoder_outputs: BaseModelOutput = self.encoder(input_features, attention_mask=attention_mask, **kwargs)
400
+
401
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
402
+ input_ids=decoder_input_ids,
403
+ attention_mask=decoder_attention_mask,
404
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
405
+ encoder_attention_mask=encoder_outputs.attention_mask,
406
+ past_key_values=past_key_values,
407
+ inputs_embeds=decoder_inputs_embeds,
408
+ position_ids=decoder_position_ids,
409
+ use_cache=use_cache,
410
+ **kwargs,
411
+ )
412
+
413
+ return Seq2SeqModelOutput(
414
+ last_hidden_state=decoder_outputs.last_hidden_state,
415
+ past_key_values=decoder_outputs.past_key_values,
416
+ decoder_hidden_states=decoder_outputs.hidden_states,
417
+ decoder_attentions=decoder_outputs.attentions,
418
+ cross_attentions=decoder_outputs.cross_attentions,
419
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
420
+ encoder_hidden_states=encoder_outputs.hidden_states,
421
+ encoder_attentions=encoder_outputs.attentions,
422
+ )
423
+
424
+
425
+ class CohereAsrForConditionalGeneration(MoonshineForConditionalGeneration):
426
+ def __init__(self, config):
427
+ super().__init__(config)
428
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
429
+ self.post_init()
430
+
431
+ @can_return_tuple
432
+ @auto_docstring
433
+ def forward(
434
+ self,
435
+ input_features: torch.FloatTensor | None = None,
436
+ attention_mask: torch.LongTensor | None = None,
437
+ decoder_input_ids: torch.LongTensor | None = None,
438
+ decoder_attention_mask: torch.LongTensor | None = None,
439
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
440
+ past_key_values: EncoderDecoderCache | None = None,
441
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
442
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
443
+ use_cache: bool | None = None,
444
+ labels: torch.LongTensor | None = None,
445
+ **kwargs: Unpack[TransformersKwargs],
446
+ ) -> Seq2SeqLMOutput:
447
+ r"""
448
+ input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
449
+ Float values of the raw speech waveform. Raw speech waveform can be
450
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
451
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
452
+ the soundfile library (`pip install soundfile`). To prepare the array into
453
+ `input_features`, the [`AutoFeatureExtractor`] should be used for padding
454
+ and conversion into a tensor of type `torch.FloatTensor`.
455
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
456
+ Indices of positions of each input sequence tokens in the position embeddings.
457
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
458
+
459
+ Example:
460
+
461
+ ```python
462
+ >>> import torch
463
+ >>> from transformers import AutoProcessor, CohereAsrForConditionalGeneration
464
+ >>> from datasets import load_dataset
465
+
466
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/cohere_asr-tiny")
467
+ >>> model = CohereAsrForConditionalGeneration.from_pretrained("UsefulSensors/cohere_asr-tiny")
468
+
469
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
470
+
471
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
472
+ >>> input_features = inputs.input_features
473
+
474
+ >>> generated_ids = model.generate(input_features, max_new_tokens=100)
475
+
476
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
477
+ >>> transcription
478
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
479
+ ```"""
480
+ # Main difference: uses `input_features` instead of `input_values`
481
+ if labels is not None:
482
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
483
+ decoder_input_ids = shift_tokens_right(
484
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
485
+ )
486
+
487
+ outputs: Seq2SeqModelOutput = self.model(
488
+ input_features,
489
+ attention_mask=attention_mask,
490
+ decoder_input_ids=decoder_input_ids,
491
+ encoder_outputs=encoder_outputs,
492
+ decoder_attention_mask=decoder_attention_mask,
493
+ past_key_values=past_key_values,
494
+ decoder_inputs_embeds=decoder_inputs_embeds,
495
+ decoder_position_ids=decoder_position_ids,
496
+ use_cache=use_cache,
497
+ **kwargs,
498
+ )
499
+ logits = self.proj_out(outputs.last_hidden_state)
500
+
501
+ loss = None
502
+ if labels is not None:
503
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
504
+
505
+ return Seq2SeqLMOutput(
506
+ loss=loss,
507
+ logits=logits,
508
+ past_key_values=outputs.past_key_values,
509
+ decoder_hidden_states=outputs.decoder_hidden_states,
510
+ decoder_attentions=outputs.decoder_attentions,
511
+ cross_attentions=outputs.cross_attentions,
512
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
513
+ encoder_hidden_states=outputs.encoder_hidden_states,
514
+ encoder_attentions=outputs.encoder_attentions,
515
+ )
516
+
517
+ def prepare_inputs_for_generation(self, *args, audio_chunk_index=None, **kwargs):
518
+ # audio_chunk_index is returned by the processor but not used by the model, absorb it here
519
+ return GenerationMixin.prepare_inputs_for_generation(self, *args, **kwargs)
520
+
521
+
522
+ __all__ = [
523
+ "CohereAsrPreTrainedModel",
524
+ "CohereAsrModel",
525
+ "CohereAsrForConditionalGeneration",
526
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/cohere_asr/processing_cohere_asr.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Inc. 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
+ from ...audio_utils import AudioInput, make_list_of_audio
16
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
17
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
18
+ from ...utils import auto_docstring, is_torch_available, logging
19
+ from ...utils.import_utils import requires
20
+
21
+
22
+ if is_torch_available():
23
+ import torch
24
+
25
+
26
+ LANGUAGES = {"ar", "de", "el", "en", "es", "fr", "it", "ja", "ko", "nl", "pl", "pt", "vi", "zh"}
27
+ _NO_SPACE_LANGS = {"ja", "zh"}
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class CohereAsrProcessorKwargs(ProcessingKwargs, total=False):
34
+ _defaults = {
35
+ "audio_kwargs": {
36
+ "sampling_rate": 16000,
37
+ "padding": "longest",
38
+ "return_attention_mask": True,
39
+ },
40
+ "text_kwargs": {
41
+ "padding": True,
42
+ "padding_side": "right",
43
+ "add_special_tokens": False,
44
+ },
45
+ "common_kwargs": {"return_tensors": "pt"},
46
+ }
47
+
48
+
49
+ @auto_docstring
50
+ @requires(backends=("torch",))
51
+ class CohereAsrProcessor(ProcessorMixin):
52
+ def __init__(self, feature_extractor, tokenizer):
53
+ super().__init__(feature_extractor, tokenizer)
54
+
55
+ def get_decoder_prompt_ids(self, language: str, punctuation: bool = True) -> list[int]:
56
+ """Build the decoder prompt token IDs for the given language and punctuation settings."""
57
+ if language not in LANGUAGES:
58
+ raise ValueError(
59
+ f"Unsupported language: {language!r}. Supported languages: {', '.join(sorted(LANGUAGES))}."
60
+ )
61
+ pnc_token = "<|pnc|>" if punctuation else "<|nopnc|>"
62
+ tokens = [
63
+ "▁",
64
+ "<|startofcontext|>",
65
+ "<|startoftranscript|>",
66
+ "<|emo:undefined|>",
67
+ f"<|{language}|>",
68
+ f"<|{language}|>",
69
+ pnc_token,
70
+ "<|noitn|>",
71
+ "<|notimestamp|>",
72
+ "<|nodiarize|>",
73
+ ]
74
+ return self.tokenizer.convert_tokens_to_ids(tokens)
75
+
76
+ @auto_docstring
77
+ def __call__(
78
+ self,
79
+ audio: AudioInput,
80
+ language: str,
81
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
82
+ punctuation: bool = True,
83
+ sampling_rate: int | None = None,
84
+ **kwargs: Unpack[CohereAsrProcessorKwargs],
85
+ ):
86
+ r"""
87
+ language (`str`):
88
+ Language code (e.g. `"en"`, `"es"`, `"fr"`) used to build the decoder prompt. The processor
89
+ constructs the full decoder prompt and returns `decoder_input_ids` alongside the audio features.
90
+ punctuation (`bool`, defaults to `True`):
91
+ Whether to enable punctuation in the decoder prompt.
92
+ sampling_rate (`int`, *optional*):
93
+ The sampling rate of the input audio in Hz. This should match the sampling rate expected by the feature
94
+ extractor (defaults to 16000 Hz). If provided, it will be validated against the processor's expected
95
+ sampling rate, and an error will be raised if they don't match. If not provided, a warning will be
96
+ issued and the default sampling rate will be assumed.
97
+ """
98
+ audio = make_list_of_audio(audio)
99
+
100
+ output_kwargs = self._merge_kwargs(
101
+ CohereAsrProcessorKwargs,
102
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
103
+ **kwargs,
104
+ )
105
+
106
+ if sampling_rate is None:
107
+ logger.warning_once(
108
+ f"You've provided audio without specifying the sampling rate. It will be assumed to be {output_kwargs['audio_kwargs']['sampling_rate']}, which can result in silent errors."
109
+ )
110
+ elif sampling_rate != output_kwargs["audio_kwargs"]["sampling_rate"]:
111
+ raise ValueError(
112
+ f"The sampling rate of the audio ({sampling_rate}) does not match the sampling rate of the processor ({output_kwargs['audio_kwargs']['sampling_rate']}). Please provide resampled the audio to the expected sampling rate."
113
+ )
114
+
115
+ inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
116
+
117
+ prompt_ids = self.get_decoder_prompt_ids(language=language, punctuation=punctuation)
118
+ batch_size = inputs["input_features"].shape[0]
119
+ inputs["decoder_input_ids"] = torch.tensor([prompt_ids] * batch_size, dtype=torch.long)
120
+
121
+ if text is not None:
122
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
123
+ inputs["labels"] = encodings["input_ids"]
124
+
125
+ return inputs
126
+
127
+ def decode(self, *args, audio_chunk_index=None, language=None, **kwargs):
128
+ texts = self.tokenizer.decode(*args, **kwargs)
129
+ if audio_chunk_index is None:
130
+ return texts
131
+ if language is None:
132
+ raise ValueError("`language` must be provided when `audio_chunk_index` is given.")
133
+ separator = "" if language in _NO_SPACE_LANGS else " "
134
+ return self._reassemble_chunk_texts(texts, audio_chunk_index, separator)
135
+
136
+ @staticmethod
137
+ def _reassemble_chunk_texts(
138
+ texts: list[str],
139
+ audio_chunk_index: list[tuple[int, int | None]],
140
+ separator: str = " ",
141
+ ) -> list[str]:
142
+ """Reassemble per-chunk transcription texts back into per-sample strings.
143
+
144
+ When audio inputs are longer than the feature extractor's `max_audio_clip_s`, they are split into
145
+ overlapping chunks before being fed to the model. This means a single original audio sample can
146
+ produce multiple decoded text segments. This method reverses that chunking: it groups the decoded
147
+ texts by their original sample index using `chunk_map`, orders the chunks, and joins them
148
+ with `separator` to reconstruct one transcription string per input sample.
149
+
150
+ Args:
151
+ texts: Decoded text strings, one per model output (i.e. one per chunk).
152
+ audio_chunk_index: List of `(sample_idx, chunk_idx)` tuples that map each entry in
153
+ `texts` back to its original sample and chunk position. A `chunk_idx` of `None`
154
+ indicates the sample was not chunked.
155
+ separator: String used to join chunks belonging to the same sample. Defaults to a
156
+ space; callers pass an empty string for languages that don't use spaces between
157
+ words (e.g. Chinese, Japanese).
158
+
159
+ Returns:
160
+ A list of reassembled transcription strings, one per original input sample.
161
+ """
162
+ max_sample_idx = max(sample_idx for sample_idx, _ in audio_chunk_index)
163
+ outputs = [""] * (max_sample_idx + 1)
164
+ chunked = {}
165
+
166
+ for (sample_idx, chunk_idx), text in zip(audio_chunk_index, texts):
167
+ if chunk_idx is None:
168
+ outputs[sample_idx] = text
169
+ else:
170
+ if sample_idx not in chunked:
171
+ chunked[sample_idx] = []
172
+ chunked[sample_idx].append((chunk_idx, text))
173
+
174
+ for sample_idx, chunk_items in chunked.items():
175
+ chunk_items.sort(key=lambda item: item[0])
176
+ non_empty = [t for _, t in chunk_items if t and t.strip()]
177
+ parts = [non_empty[0].rstrip()] + [t.strip() for t in non_empty[1:]]
178
+ outputs[sample_idx] = separator.join(parts)
179
+
180
+ return outputs
181
+
182
+ @property
183
+ def model_input_names(self):
184
+ feature_extractor_input_names = self.feature_extractor.model_input_names
185
+ return feature_extractor_input_names + ["labels"]
186
+
187
+
188
+ __all__ = ["CohereAsrProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_colmodernvbert import *
22
+ from .modeling_colmodernvbert import *
23
+ from .processing_colmodernvbert import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/configuration_colmodernvbert.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colmodernvbert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...utils import auto_docstring, logging
26
+ from ..auto import CONFIG_MAPPING
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ @auto_docstring(checkpoint="ModernVBERT/colmodernvbert-merged")
33
+ @strict
34
+ class ColModernVBertConfig(PreTrainedConfig):
35
+ r"""
36
+ Example:
37
+
38
+ ```python
39
+ from transformers import ColModernVBertConfig, ColModernVBertForRetrieval
40
+
41
+ config = ColModernVBertConfig()
42
+ model = ColModernVBertForRetrieval(config)
43
+ ```
44
+ """
45
+
46
+ model_type = "colmodernvbert"
47
+ sub_configs = {"vlm_config": PreTrainedConfig}
48
+
49
+ vlm_config: dict | PreTrainedConfig | None = None
50
+ embedding_dim: int = 128
51
+ initializer_range: float = 0.02
52
+
53
+ def __post_init__(self, **kwargs):
54
+ if self.vlm_config is None:
55
+ self.vlm_config = CONFIG_MAPPING["modernvbert"]()
56
+ logger.info(
57
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `ModernVBertConfig` with default values."
58
+ )
59
+ elif isinstance(self.vlm_config, dict):
60
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
61
+
62
+ if not hasattr(self.vlm_config, "vocab_size"):
63
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
64
+ if self.vlm_config is None:
65
+ self.vlm_config = CONFIG_MAPPING["qwen2_vl"]()
66
+ logger.info(
67
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `Qwen2VLConfig` with default values."
68
+ )
69
+ elif isinstance(self.vlm_config, dict):
70
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
71
+
72
+ if not hasattr(self.vlm_config, "vocab_size"):
73
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
74
+
75
+ super().__post_init__(**kwargs)
76
+
77
+ def get_text_config(self, *args, **kwargs) -> PreTrainedConfig:
78
+ return self.vlm_config.get_text_config(*args, **kwargs)
79
+
80
+
81
+ __all__ = ["ColModernVBertConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/modeling_colmodernvbert.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colmodernvbert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from dataclasses import dataclass
22
+
23
+ import torch
24
+ from torch import nn
25
+
26
+ from ... import initialization as init
27
+ from ...modeling_utils import PreTrainedModel
28
+ from ...processing_utils import Unpack
29
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring
30
+ from ...utils.generic import can_return_tuple
31
+ from ..auto.modeling_auto import AutoModel
32
+ from .configuration_colmodernvbert import ColModernVBertConfig
33
+
34
+
35
+ @auto_docstring
36
+ class ColModernVBertPreTrainedModel(PreTrainedModel):
37
+ config: ColModernVBertConfig
38
+ base_model_prefix = "model"
39
+ input_modalities = ("image", "text")
40
+ _no_split_modules = []
41
+ _supports_sdpa = True
42
+ _supports_flash_attn = True
43
+ _supports_flex_attn = True
44
+
45
+ @torch.no_grad()
46
+ def _init_weights(self, module):
47
+ std = (
48
+ self.config.initializer_range
49
+ if hasattr(self.config, "initializer_range")
50
+ else self.config.vlm_config.text_config.initializer_range
51
+ )
52
+
53
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
54
+ init.normal_(module.weight, mean=0.0, std=std)
55
+ if module.bias is not None:
56
+ init.zeros_(module.bias)
57
+ elif isinstance(module, nn.Embedding):
58
+ init.normal_(module.weight, mean=0.0, std=std)
59
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
60
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
61
+ init.zeros_(module.weight[module.padding_idx])
62
+
63
+
64
+ @auto_docstring(
65
+ custom_intro="""
66
+ Base class for ColModernVBert embeddings output.
67
+ """
68
+ )
69
+ @dataclass
70
+ class ColModernVBertForRetrievalOutput(ModelOutput):
71
+ r"""
72
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
73
+ Language modeling loss (for next-token prediction).
74
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
75
+ The embeddings of the model.
76
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` and `pixel_values` are provided):
77
+ Tuple of `torch.FloatTensor` (one for the output of the image modality projection + one for the output of each layer) of shape
78
+ `(batch_size, num_channels, image_size, image_size)`.
79
+ Hidden-states of the image encoder at the output of each layer plus the initial modality projection outputs.
80
+ """
81
+
82
+ loss: torch.FloatTensor | None = None
83
+ embeddings: torch.Tensor | None = None
84
+ hidden_states: tuple[torch.FloatTensor] | None = None
85
+ image_hidden_states: tuple[torch.FloatTensor] | None = None
86
+ attentions: tuple[torch.FloatTensor] | None = None
87
+
88
+
89
+ @auto_docstring(
90
+ custom_intro="""
91
+ Following the ColPali approach, ColModernVBert leverages VLMs to construct efficient multi-vector embeddings directly
92
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
93
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
94
+ introduced in ColBERT.
95
+
96
+ Using ColModernVBert removes the need for potentially complex and brittle layout recognition and OCR pipelines with
97
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
98
+
99
+ ColModernVBert is trained on top of ModernVBert, and was introduced in the following paper:
100
+ [*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
101
+
102
+ ColModernVBert is part of the ColVision model family, which was introduced with ColPali in the following paper:
103
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
104
+ """
105
+ )
106
+ class ColModernVBertForRetrieval(ColModernVBertPreTrainedModel):
107
+ base_model_prefix = "vlm"
108
+
109
+ def __init__(self, config: ColModernVBertConfig):
110
+ super().__init__(config)
111
+ self.config = config
112
+ self.vocab_size = config.vlm_config.text_config.vocab_size
113
+ self.vlm = AutoModel.from_config(config.vlm_config)
114
+
115
+ self.embedding_dim = self.config.embedding_dim
116
+ self.embedding_proj_layer = nn.Linear(
117
+ self.config.vlm_config.text_config.hidden_size,
118
+ self.embedding_dim,
119
+ )
120
+
121
+ self.post_init()
122
+
123
+ @can_return_tuple
124
+ @auto_docstring
125
+ def forward(
126
+ self,
127
+ input_ids: torch.LongTensor | None = None,
128
+ pixel_values: torch.FloatTensor | None = None,
129
+ attention_mask: torch.Tensor | None = None,
130
+ **kwargs: Unpack[TransformersKwargs],
131
+ ) -> ColModernVBertForRetrievalOutput:
132
+ vlm_output = self.vlm(
133
+ input_ids=input_ids,
134
+ attention_mask=attention_mask,
135
+ pixel_values=pixel_values,
136
+ **kwargs,
137
+ )
138
+
139
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
140
+ proj_dtype = self.embedding_proj_layer.weight.dtype
141
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
142
+
143
+ # L2 normalization
144
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
145
+
146
+ if attention_mask is not None:
147
+ attention_mask = attention_mask.to(dtype=embeddings.dtype, device=embeddings.device)
148
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
149
+
150
+ return ColModernVBertForRetrievalOutput(
151
+ embeddings=embeddings,
152
+ hidden_states=vlm_output.hidden_states,
153
+ attentions=vlm_output.attentions,
154
+ image_hidden_states=vlm_output.image_hidden_states,
155
+ )
156
+
157
+
158
+ __all__ = ["ColModernVBertForRetrieval", "ColModernVBertPreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/modular_colmodernvbert.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. 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
+ from dataclasses import dataclass
16
+ from typing import Optional, Union
17
+
18
+ import torch
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...feature_extraction_utils import BatchFeature
23
+ from ...image_utils import ImageInput, is_valid_image
24
+ from ...processing_utils import Unpack
25
+ from ...tokenization_utils_base import TextInput
26
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
27
+ from ...utils.generic import can_return_tuple
28
+ from ...utils.import_utils import requires
29
+ from ..auto import CONFIG_MAPPING
30
+ from ..auto.modeling_auto import AutoModel
31
+ from ..colpali.modeling_colpali import ColPaliForRetrieval, ColPaliPreTrainedModel
32
+ from ..colqwen2.configuration_colqwen2 import ColQwen2Config
33
+ from ..idefics3.processing_idefics3 import Idefics3Processor, Idefics3ProcessorKwargs
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ @auto_docstring(checkpoint="ModernVBERT/colmodernvbert-merged")
40
+ @strict
41
+ class ColModernVBertConfig(ColQwen2Config):
42
+ r"""
43
+ Example:
44
+
45
+ ```python
46
+ from transformers import ColModernVBertConfig, ColModernVBertForRetrieval
47
+
48
+ config = ColModernVBertConfig()
49
+ model = ColModernVBertForRetrieval(config)
50
+ ```
51
+ """
52
+
53
+ model_type = "colmodernvbert"
54
+ sub_configs = {"vlm_config": PreTrainedConfig}
55
+
56
+ vlm_config: dict | PreTrainedConfig | None = None
57
+ embedding_dim: int = 128
58
+ initializer_range: float = 0.02
59
+
60
+ def __post_init__(self, **kwargs):
61
+ if self.vlm_config is None:
62
+ self.vlm_config = CONFIG_MAPPING["modernvbert"]()
63
+ logger.info(
64
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `ModernVBertConfig` with default values."
65
+ )
66
+ elif isinstance(self.vlm_config, dict):
67
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
68
+
69
+ if not hasattr(self.vlm_config, "vocab_size"):
70
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
71
+
72
+ super().__post_init__(**kwargs)
73
+
74
+
75
+ class ColModernVBertProcessorKwargs(Idefics3ProcessorKwargs, total=False):
76
+ _defaults = {
77
+ "text_kwargs": {
78
+ "padding": "longest",
79
+ },
80
+ "images_kwargs": {
81
+ "return_row_col_info": True,
82
+ "data_format": "channels_first",
83
+ "do_convert_rgb": True,
84
+ },
85
+ "common_kwargs": {"return_tensors": "pt"},
86
+ }
87
+
88
+
89
+ @requires(backends=("torch",))
90
+ @auto_docstring
91
+ class ColModernVBertProcessor(Idefics3Processor):
92
+ r"""
93
+ Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as
94
+ well as to compute the late-interaction retrieval score.
95
+
96
+ [`ColModernVBertProcessor`] offers all the functionalities of [`ModernVBertProcessor`]. See the [`~ModernVBertProcessor.__call__`]
97
+ for more information.
98
+
99
+ Args:
100
+ image_processor ([`Idefics3ImageProcessor`]): An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
101
+ tokenizer (`PreTrainedTokenizerFast`, *optional*): An instance of [`PreTrainedTokenizerFast`]. This should correspond with the model's text model. The tokenizer is a required input.
102
+ image_seq_len (`int`, *optional*, defaults to 64): The length of the image sequence i.e. the number of <image> tokens per image in the input.
103
+ visual_prompt_prefix (`Optional`, *optional*): A prefix to be prepended to visual prompts.
104
+ query_prefix (`Optional`, *optional*): A prefix to be prepended to query prompts.
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ image_processor,
110
+ tokenizer=None,
111
+ chat_template=None,
112
+ image_seq_len: int = 64,
113
+ visual_prompt_prefix: str | None = None,
114
+ query_prefix: str | None = None,
115
+ **kwargs,
116
+ ):
117
+ r"""
118
+ image_seq_len (`int`, *optional*, defaults to 64):
119
+ The length of the image sequence i.e. the number of <image> tokens per image in the input.
120
+ visual_prompt_prefix (`str`, *optional*):
121
+ A string that gets tokenized and prepended to the image tokens.
122
+ query_prefix (`str`, *optional*):
123
+ A prefix to be used for the query.
124
+ """
125
+ chat_template = None # ColModernVBert does not use chat templates
126
+
127
+ super().__init__(
128
+ image_processor,
129
+ tokenizer,
130
+ chat_template=chat_template,
131
+ image_seq_len=image_seq_len,
132
+ **kwargs,
133
+ )
134
+
135
+ self.visual_prompt_prefix = visual_prompt_prefix or (
136
+ f"<|begin_of_text|>User:{self.image_token}Describe the image.<end_of_utterance>\nAssistant:"
137
+ )
138
+ self.query_prefix = query_prefix or ""
139
+ self.query_augmentation_token = self.end_of_utterance_token
140
+
141
+ def process_images(
142
+ self,
143
+ images: ImageInput | None = None,
144
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
145
+ ) -> BatchFeature:
146
+ """
147
+ Prepare for the model one or several image(s). Handles input validation, RGB conversion,
148
+ and prepends the `visual_prompt_prefix` to each image. Optionally computes labels from
149
+ `token_type_ids` when a `suffix` is provided in `text_kwargs`.
150
+
151
+ Args:
152
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
153
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
154
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
155
+ number of channels, H and W are image height and width.
156
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
157
+ If set, will return tensors of a particular framework. Acceptable values are:
158
+
159
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
160
+ - `'np'`: Return NumPy `np.ndarray` objects.
161
+
162
+ Returns:
163
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
164
+
165
+ - **input_ids** -- List of token ids to be fed to a model.
166
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
167
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
168
+ `None`).
169
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
170
+ """
171
+ output_kwargs = self._merge_kwargs(
172
+ ColModernVBertProcessorKwargs,
173
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
174
+ **kwargs,
175
+ )
176
+
177
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
178
+
179
+ return_token_type_ids = suffix is not None
180
+
181
+ # Normalize input to a flat list of images
182
+ if is_valid_image(images):
183
+ images = [images]
184
+ elif isinstance(images, list) and is_valid_image(images[0]):
185
+ pass
186
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
187
+ raise ValueError("images must be an image, list of images or list of list of images")
188
+
189
+ # Ensure all images are in RGB format
190
+ images = [image.convert("RGB") for image in images]
191
+
192
+ # Pair each image with the visual prompt prefix for the VLM backbone
193
+ batch_doc = self.__call__(
194
+ text=[self.visual_prompt_prefix] * len(images),
195
+ images=images,
196
+ images_kwargs=output_kwargs["images_kwargs"],
197
+ text_kwargs=output_kwargs["text_kwargs"],
198
+ )
199
+
200
+ # When suffix is provided, generate labels by masking non-suffix tokens
201
+ if return_token_type_ids:
202
+ labels = batch_doc["input_ids"].masked_fill(batch_doc["token_type_ids"] == 0, -100)
203
+ batch_doc.update({"labels": labels})
204
+
205
+ return batch_doc
206
+
207
+ def process_queries(
208
+ self,
209
+ text: TextInput | list[TextInput],
210
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
211
+ ) -> BatchFeature:
212
+ """
213
+ Prepare for the model one or several text queries. Handles input validation, prepends the
214
+ `query_prefix`, and appends query augmentation tokens (used to pad query embeddings for
215
+ better late-interaction retrieval performance).
216
+
217
+ Args:
218
+ text (`str`, `list[str]`, `list[list[str]]`):
219
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
220
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
221
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
222
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
223
+ If set, will return tensors of a particular framework. Acceptable values are:
224
+
225
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
226
+ - `'np'`: Return NumPy `np.ndarray` objects.
227
+
228
+ Returns:
229
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
230
+
231
+ - **input_ids** -- List of token ids to be fed to a model.
232
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
233
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
234
+ `None`).
235
+ """
236
+ output_kwargs = self._merge_kwargs(
237
+ ColModernVBertProcessorKwargs,
238
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
239
+ **kwargs,
240
+ )
241
+
242
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
243
+
244
+ if isinstance(text, str):
245
+ text = [text]
246
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
247
+ raise ValueError("Text must be a string or a list of strings")
248
+
249
+ # Default suffix: repeat the augmentation token to pad query embeddings
250
+ if suffix is None:
251
+ suffix = self.query_augmentation_token * 10
252
+
253
+ # Build final queries: prefix + original query + augmentation suffix
254
+ texts_query: list[str] = [self.query_prefix + query + suffix for query in text]
255
+
256
+ batch_query = self.__call__(
257
+ text=texts_query,
258
+ return_token_type_ids=False,
259
+ text_kwargs=output_kwargs["text_kwargs"],
260
+ )
261
+
262
+ return batch_query
263
+
264
+ def score_retrieval(
265
+ self,
266
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
267
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
268
+ batch_size: int = 128,
269
+ output_dtype: Optional["torch.dtype"] = None,
270
+ output_device: Union["torch.device", str] = "cpu",
271
+ ) -> "torch.Tensor":
272
+ """
273
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
274
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
275
+ image of a document page.
276
+
277
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
278
+ should be fed as:
279
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
280
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
281
+ obtained by padding the list of tensors.
282
+
283
+ Args:
284
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
285
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
286
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
287
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
288
+ If `None`, the dtype of the input embeddings is used.
289
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
290
+
291
+ Returns:
292
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
293
+ tensor is saved on the "cpu" device.
294
+ """
295
+
296
+ if len(query_embeddings) == 0:
297
+ raise ValueError("No queries provided")
298
+ if len(passage_embeddings) == 0:
299
+ raise ValueError("No passages provided")
300
+
301
+ if query_embeddings[0].device != passage_embeddings[0].device:
302
+ raise ValueError("Queries and passages must be on the same device")
303
+
304
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
305
+ raise ValueError("Queries and passages must have the same dtype")
306
+
307
+ if output_dtype is None:
308
+ output_dtype = query_embeddings[0].dtype
309
+
310
+ scores: list[torch.Tensor] = []
311
+
312
+ for i in range(0, len(query_embeddings), batch_size):
313
+ batch_scores: list[torch.Tensor] = []
314
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
315
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
316
+ )
317
+ for j in range(0, len(passage_embeddings), batch_size):
318
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
319
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
320
+ )
321
+ batch_scores.append(
322
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
323
+ )
324
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
325
+
326
+ return torch.cat(scores, dim=0)
327
+
328
+
329
+ @auto_docstring
330
+ class ColModernVBertPreTrainedModel(ColPaliPreTrainedModel):
331
+ config: ColModernVBertConfig
332
+
333
+
334
+ @auto_docstring(
335
+ custom_intro="""
336
+ Base class for ColModernVBert embeddings output.
337
+ """
338
+ )
339
+ @dataclass
340
+ class ColModernVBertForRetrievalOutput(ModelOutput):
341
+ r"""
342
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
343
+ Language modeling loss (for next-token prediction).
344
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
345
+ The embeddings of the model.
346
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` and `pixel_values` are provided):
347
+ Tuple of `torch.FloatTensor` (one for the output of the image modality projection + one for the output of each layer) of shape
348
+ `(batch_size, num_channels, image_size, image_size)`.
349
+ Hidden-states of the image encoder at the output of each layer plus the initial modality projection outputs.
350
+ """
351
+
352
+ loss: torch.FloatTensor | None = None
353
+ embeddings: torch.Tensor | None = None
354
+ hidden_states: tuple[torch.FloatTensor] | None = None
355
+ image_hidden_states: tuple[torch.FloatTensor] | None = None
356
+ attentions: tuple[torch.FloatTensor] | None = None
357
+
358
+
359
+ @auto_docstring(
360
+ custom_intro="""
361
+ Following the ColPali approach, ColModernVBert leverages VLMs to construct efficient multi-vector embeddings directly
362
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
363
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
364
+ introduced in ColBERT.
365
+
366
+ Using ColModernVBert removes the need for potentially complex and brittle layout recognition and OCR pipelines with
367
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
368
+
369
+ ColModernVBert is trained on top of ModernVBert, and was introduced in the following paper:
370
+ [*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
371
+
372
+ ColModernVBert is part of the ColVision model family, which was introduced with ColPali in the following paper:
373
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
374
+ """
375
+ )
376
+ class ColModernVBertForRetrieval(ColPaliForRetrieval):
377
+ def __init__(self, config: ColModernVBertConfig):
378
+ super().__init__(config)
379
+ self.vlm = AutoModel.from_config(config.vlm_config)
380
+ self.post_init()
381
+
382
+ @can_return_tuple
383
+ @auto_docstring
384
+ def forward(
385
+ self,
386
+ input_ids: torch.LongTensor | None = None,
387
+ pixel_values: torch.FloatTensor | None = None,
388
+ attention_mask: torch.Tensor | None = None,
389
+ **kwargs: Unpack[TransformersKwargs],
390
+ ) -> ColModernVBertForRetrievalOutput:
391
+ vlm_output = self.vlm(
392
+ input_ids=input_ids,
393
+ attention_mask=attention_mask,
394
+ pixel_values=pixel_values,
395
+ **kwargs,
396
+ )
397
+
398
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
399
+ proj_dtype = self.embedding_proj_layer.weight.dtype
400
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
401
+
402
+ # L2 normalization
403
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
404
+
405
+ if attention_mask is not None:
406
+ attention_mask = attention_mask.to(dtype=embeddings.dtype, device=embeddings.device)
407
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
408
+
409
+ return ColModernVBertForRetrievalOutput(
410
+ embeddings=embeddings,
411
+ hidden_states=vlm_output.hidden_states,
412
+ attentions=vlm_output.attentions,
413
+ image_hidden_states=vlm_output.image_hidden_states,
414
+ )
415
+
416
+
417
+ __all__ = [
418
+ "ColModernVBertConfig",
419
+ "ColModernVBertForRetrieval",
420
+ "ColModernVBertPreTrainedModel",
421
+ "ColModernVBertProcessor",
422
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colmodernvbert/processing_colmodernvbert.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colmodernvbert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import re
22
+ from itertools import accumulate
23
+ from typing import TYPE_CHECKING, Optional, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+
28
+ from ...feature_extraction_utils import BatchFeature
29
+ from ...image_utils import ImageInput, is_valid_image, load_image
30
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
31
+ from ...tokenization_utils_base import AddedToken, BatchEncoding, TextInput
32
+ from ...utils import auto_docstring
33
+ from ...utils.import_utils import requires
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ from ...tokenization_utils_base import PreTokenizedInput
38
+
39
+
40
+ class ColModernVBertProcessorKwargs(ProcessingKwargs, total=False):
41
+ _defaults = {
42
+ "text_kwargs": {
43
+ "padding": "longest",
44
+ },
45
+ "images_kwargs": {
46
+ "return_row_col_info": True,
47
+ "data_format": "channels_first",
48
+ "do_convert_rgb": True,
49
+ },
50
+ "common_kwargs": {"return_tensors": "pt"},
51
+ }
52
+
53
+
54
+ def is_url(val) -> bool:
55
+ return isinstance(val, str) and val.startswith("http")
56
+
57
+
58
+ def is_image_or_image_url(elem):
59
+ return is_url(elem) or is_valid_image(elem)
60
+
61
+
62
+ def _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token):
63
+ """Prompt with expanded image tokens for when the image is split into patches."""
64
+ text_split_images = ""
65
+ for n_h in range(image_rows):
66
+ for n_w in range(image_cols):
67
+ text_split_images += (
68
+ f"{fake_token_around_image}" + f"<row_{n_h + 1}_col_{n_w + 1}>" + f"{image_token}" * image_seq_len
69
+ )
70
+ text_split_images += "\n"
71
+
72
+ text_split_images += (
73
+ f"\n{fake_token_around_image}"
74
+ + f"{global_img_token}"
75
+ + f"{image_token}" * image_seq_len
76
+ + f"{fake_token_around_image}"
77
+ )
78
+ return text_split_images
79
+
80
+
81
+ def _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token):
82
+ """Prompt with expanded image tokens for a single image."""
83
+ return (
84
+ f"{fake_token_around_image}"
85
+ + f"{global_img_token}"
86
+ + f"{image_token}" * image_seq_len
87
+ + f"{fake_token_around_image}"
88
+ )
89
+
90
+
91
+ def get_image_prompt_string(
92
+ image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token
93
+ ):
94
+ if image_rows == 0 and image_cols == 0:
95
+ return _prompt_single_image(
96
+ image_seq_len,
97
+ fake_token_around_image=fake_token_around_image,
98
+ image_token=image_token,
99
+ global_img_token=global_img_token,
100
+ )
101
+ return _prompt_split_image(
102
+ image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token
103
+ )
104
+
105
+
106
+ @requires(backends=("torch",))
107
+ @auto_docstring
108
+ class ColModernVBertProcessor(ProcessorMixin):
109
+ r"""
110
+ Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as
111
+ well as to compute the late-interaction retrieval score.
112
+
113
+ [`ColModernVBertProcessor`] offers all the functionalities of [`ModernVBertProcessor`]. See the [`~ModernVBertProcessor.__call__`]
114
+ for more information.
115
+
116
+ Args:
117
+ image_processor ([`Idefics3ImageProcessor`]): An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
118
+ tokenizer (`PreTrainedTokenizerFast`, *optional*): An instance of [`PreTrainedTokenizerFast`]. This should correspond with the model's text model. The tokenizer is a required input.
119
+ image_seq_len (`int`, *optional*, defaults to 64): The length of the image sequence i.e. the number of <image> tokens per image in the input.
120
+ visual_prompt_prefix (`Optional`, *optional*): A prefix to be prepended to visual prompts.
121
+ query_prefix (`Optional`, *optional*): A prefix to be prepended to query prompts.
122
+ """
123
+
124
+ def __init__(
125
+ self,
126
+ image_processor,
127
+ tokenizer=None,
128
+ chat_template=None,
129
+ image_seq_len: int = 64,
130
+ visual_prompt_prefix: str | None = None,
131
+ query_prefix: str | None = None,
132
+ **kwargs,
133
+ ):
134
+ r"""
135
+ image_seq_len (`int`, *optional*, defaults to 64):
136
+ The length of the image sequence i.e. the number of <image> tokens per image in the input.
137
+ visual_prompt_prefix (`str`, *optional*):
138
+ A string that gets tokenized and prepended to the image tokens.
139
+ query_prefix (`str`, *optional*):
140
+ A prefix to be used for the query.
141
+ """
142
+ chat_template = None # ColModernVBert does not use chat templates
143
+ self.fake_image_token = AddedToken("<fake_token_around_image>", normalized=False, special=True).content
144
+ self.image_token = AddedToken("<image>", normalized=False, special=True).content
145
+ self.end_of_utterance_token = AddedToken("<end_of_utterance>", normalized=False, special=True).content
146
+ self.global_image_tag = "<global-img>" # https://github.com/huggingface/transformers/pull/32473/files/8063e5e17362571b693f1db95167f5443a3be1b2#r1734825341
147
+ self.image_seq_len = image_seq_len
148
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
149
+ self.fake_image_token_id = tokenizer.convert_tokens_to_ids(self.fake_image_token)
150
+ self.global_image_token_id = tokenizer.convert_tokens_to_ids(self.global_image_tag)
151
+ self.row_col_ids = [
152
+ tokenizer.convert_tokens_to_ids(f"<row_{i + 1}_col_{j + 1}>") for i in range(6) for j in range(6)
153
+ ]
154
+
155
+ # This regex matches one or more occurrences of <global-img> tags (optionally surrounded by newline characters)
156
+ # or <row_x_col_y> tags (where x and y are digits, also optionally surrounded by newline characters).
157
+ self._regex_to_remove_extra_special_tokens = re.compile(r"(\n?<global-img>\n?|<row_\d+_col_\d+>\n?)+")
158
+
159
+ tokens_to_add = {
160
+ "additional_special_tokens": [
161
+ self.fake_image_token,
162
+ self.image_token,
163
+ self.end_of_utterance_token,
164
+ ]
165
+ }
166
+ tokenizer.add_special_tokens(tokens_to_add)
167
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
168
+
169
+ super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
170
+
171
+ self.visual_prompt_prefix = visual_prompt_prefix or (
172
+ f"<|begin_of_text|>User:{self.image_token}Describe the image.<end_of_utterance>\nAssistant:"
173
+ )
174
+ self.query_prefix = query_prefix or ""
175
+ self.query_augmentation_token = self.end_of_utterance_token
176
+
177
+ def _extract_images_from_prompts(self, prompts):
178
+ prompt_images = []
179
+ for prompt in prompts:
180
+ images = []
181
+ for elem in prompt:
182
+ if is_valid_image(elem):
183
+ images.append(elem)
184
+ elif is_url(elem):
185
+ images.append(load_image(elem))
186
+ prompt_images.append(images)
187
+ return prompt_images
188
+
189
+ @auto_docstring
190
+ def __call__(
191
+ self,
192
+ images: ImageInput | list[ImageInput] | list[list[ImageInput]] = None,
193
+ text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
194
+ image_seq_len: int | None = None,
195
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
196
+ ) -> BatchEncoding:
197
+ r"""
198
+ image_seq_len (`int`, *optional*):
199
+ The length of the image sequence. If not provided, the default value of self.image_seq_len is used.
200
+ image_seq_len should be equal to int(((image_size // patch_size) ** 2) / (scale_factor**2))
201
+ """
202
+ if text is None and images is None:
203
+ raise ValueError("You must provide either `text` or `images`.")
204
+
205
+ output_kwargs = self._merge_kwargs(
206
+ ColModernVBertProcessorKwargs,
207
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
208
+ **kwargs,
209
+ )
210
+
211
+ image_seq_len = image_seq_len if image_seq_len is not None else self.image_seq_len
212
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
213
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
214
+
215
+ n_images_in_text = []
216
+ n_images_in_images = []
217
+ inputs = {}
218
+
219
+ if text is not None:
220
+ if isinstance(text, str):
221
+ text = [text]
222
+ elif not isinstance(text, list) and not isinstance(text[0], str):
223
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
224
+ n_images_in_text = [sample.count(self.image_token) for sample in text]
225
+
226
+ if images is not None:
227
+ if is_image_or_image_url(images):
228
+ images = [[images]]
229
+ elif isinstance(images, (list, tuple)) and is_image_or_image_url(images[0]):
230
+ if text is not None:
231
+ if sum(n_images_in_text) != len(images):
232
+ raise ValueError(
233
+ f"The total number of {self.image_token} tokens in the prompts should be the same as the number of images passed."
234
+ f" Found {sum(n_images_in_text)} {self.image_token} tokens and {len(images)} images."
235
+ )
236
+ # Reorganize the images to match the prompts
237
+ cumsum_images_in_text = [0] + list(accumulate(n_images_in_text))
238
+ images = [
239
+ images[cumsum_images_in_text[i] : cumsum_images_in_text[i + 1]]
240
+ for i in range(len(n_images_in_text))
241
+ ]
242
+ else:
243
+ images = [images]
244
+ elif (
245
+ not isinstance(images, (list, tuple))
246
+ and not isinstance(images[0], (list, tuple))
247
+ and not is_image_or_image_url(images[0][0])
248
+ ):
249
+ raise ValueError(
250
+ "Invalid input images. Please provide a single image or a list of images or a list of list of images."
251
+ )
252
+ n_images_in_images = [len(sample) for sample in images]
253
+
254
+ # Load images if they are URLs
255
+ images = [[load_image(im) if is_url(im) else im for im in sample] for sample in images]
256
+
257
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
258
+ inputs.update(image_inputs)
259
+
260
+ if text is not None:
261
+ if n_images_in_images != n_images_in_text:
262
+ raise ValueError(
263
+ f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
264
+ )
265
+
266
+ image_rows = inputs.pop("rows", [[0] * n_images for n_images in n_images_in_text])
267
+ image_cols = inputs.pop("cols", [[0] * n_images for n_images in n_images_in_text])
268
+
269
+ fake_image_token = self.fake_image_token
270
+ image_token = self.image_token
271
+ global_img_token = self.global_image_tag
272
+
273
+ prompt_strings = []
274
+ batch_image_seq_lengths = []
275
+ for sample, sample_rows, sample_cols in zip(text, image_rows, image_cols):
276
+ # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
277
+ image_prompt_strings = []
278
+ image_seq_lengths = []
279
+ for n_rows, n_cols in zip(sample_rows, sample_cols):
280
+ image_prompt_string = get_image_prompt_string(
281
+ n_rows,
282
+ n_cols,
283
+ image_seq_len,
284
+ image_token=image_token,
285
+ fake_token_around_image=fake_image_token,
286
+ global_img_token=global_img_token,
287
+ )
288
+ # Add +2 and +3 for special BOI/EOI/fake_image_wrapper tokens
289
+ row_length = (self.image_seq_len + 2) * n_cols + 1
290
+ image_seq_lengths.append((self.image_seq_len + 3) + row_length * n_rows)
291
+ image_prompt_strings.append(image_prompt_string)
292
+
293
+ batch_image_seq_lengths.append(image_seq_lengths)
294
+ split_sample = sample.split(image_token)
295
+ if len(split_sample) == 0:
296
+ raise ValueError("The image token should be present in the text.")
297
+
298
+ # Place in the image prompt strings where the image tokens are
299
+ sample = split_sample[0]
300
+ for i, image_prompt_string in enumerate(image_prompt_strings):
301
+ sample += image_prompt_string + split_sample[i + 1]
302
+ prompt_strings.append(sample)
303
+
304
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
305
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
306
+ inputs.update(text_inputs)
307
+
308
+ elif text is not None:
309
+ if any(n_images_in_text):
310
+ raise ValueError(
311
+ f"Found {sum(n_images_in_text)} {self.image_token} tokens in the text but no images were passed."
312
+ )
313
+ text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
314
+ inputs.update(text_inputs)
315
+
316
+ if return_mm_token_type_ids:
317
+ inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(inputs["input_ids"], batch_image_seq_lengths)
318
+ return BatchFeature(data=inputs, tensor_type=return_tensors)
319
+
320
+ def create_mm_token_type_ids(self, input_ids: list, batch_image_seq_lengths: list[int]) -> list[list[int]]:
321
+ # We have to iterate for each list separately because inputs
322
+ # might be non-padded lists and we can't cast numpy on that!
323
+ # Then cast numpy as each input for faster indexing
324
+ mm_token_type_ids = []
325
+ for i, seq_lengths in enumerate(batch_image_seq_lengths):
326
+ array_ids = np.array(input_ids[i])
327
+ mm_token_types = np.zeros_like(array_ids)
328
+ image_start_positions = np.where(array_ids == self.fake_image_token_id)[0]
329
+ j = 0
330
+ for seq_len in seq_lengths:
331
+ if j >= len(image_start_positions):
332
+ break
333
+ start = image_start_positions[j]
334
+ end = start + seq_len
335
+ mm_token_types[start:end] = 1
336
+ j = np.searchsorted(image_start_positions, end)
337
+ mm_token_type_ids.append(mm_token_types.tolist())
338
+
339
+ return mm_token_type_ids
340
+
341
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
342
+ """
343
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
344
+
345
+ Args:
346
+ image_sizes (`list[list[int]]`, *optional*):
347
+ The input sizes formatted as (height, width) per each image.
348
+
349
+ Returns:
350
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
351
+ input modalities, along with other useful data.
352
+ """
353
+
354
+ vision_data = {}
355
+ if image_sizes is not None:
356
+ images_kwargs = ColModernVBertProcessorKwargs._defaults.get("images_kwargs", {})
357
+ images_kwargs.update(kwargs)
358
+
359
+ num_image_row_cols = [
360
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
361
+ for image_size in image_sizes
362
+ ]
363
+
364
+ base_image_length = self.image_seq_len + 3
365
+ col_length = self.image_seq_len + 2
366
+ num_image_tokens = []
367
+ num_image_patches = []
368
+
369
+ for num_patches, num_rows, num_cols in num_image_row_cols:
370
+ row_length = col_length * num_cols + 1
371
+ num_image_tokens.append(base_image_length + (row_length * num_rows))
372
+ num_image_patches.append(num_patches)
373
+
374
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
375
+
376
+ return MultiModalData(**vision_data)
377
+
378
+ def process_images(
379
+ self,
380
+ images: ImageInput | None = None,
381
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
382
+ ) -> BatchFeature:
383
+ """
384
+ Prepare for the model one or several image(s). Handles input validation, RGB conversion,
385
+ and prepends the `visual_prompt_prefix` to each image. Optionally computes labels from
386
+ `token_type_ids` when a `suffix` is provided in `text_kwargs`.
387
+
388
+ Args:
389
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
390
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
391
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
392
+ number of channels, H and W are image height and width.
393
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
394
+ If set, will return tensors of a particular framework. Acceptable values are:
395
+
396
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
397
+ - `'np'`: Return NumPy `np.ndarray` objects.
398
+
399
+ Returns:
400
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
401
+
402
+ - **input_ids** -- List of token ids to be fed to a model.
403
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
404
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
405
+ `None`).
406
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
407
+ """
408
+ output_kwargs = self._merge_kwargs(
409
+ ColModernVBertProcessorKwargs,
410
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
411
+ **kwargs,
412
+ )
413
+
414
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
415
+
416
+ return_token_type_ids = suffix is not None
417
+
418
+ # Normalize input to a flat list of images
419
+ if is_valid_image(images):
420
+ images = [images]
421
+ elif isinstance(images, list) and is_valid_image(images[0]):
422
+ pass
423
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
424
+ raise ValueError("images must be an image, list of images or list of list of images")
425
+
426
+ # Ensure all images are in RGB format
427
+ images = [image.convert("RGB") for image in images]
428
+
429
+ # Pair each image with the visual prompt prefix for the VLM backbone
430
+ batch_doc = self.__call__(
431
+ text=[self.visual_prompt_prefix] * len(images),
432
+ images=images,
433
+ images_kwargs=output_kwargs["images_kwargs"],
434
+ text_kwargs=output_kwargs["text_kwargs"],
435
+ )
436
+
437
+ # When suffix is provided, generate labels by masking non-suffix tokens
438
+ if return_token_type_ids:
439
+ labels = batch_doc["input_ids"].masked_fill(batch_doc["token_type_ids"] == 0, -100)
440
+ batch_doc.update({"labels": labels})
441
+
442
+ return batch_doc
443
+
444
+ def process_queries(
445
+ self,
446
+ text: TextInput | list[TextInput],
447
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
448
+ ) -> BatchFeature:
449
+ """
450
+ Prepare for the model one or several text queries. Handles input validation, prepends the
451
+ `query_prefix`, and appends query augmentation tokens (used to pad query embeddings for
452
+ better late-interaction retrieval performance).
453
+
454
+ Args:
455
+ text (`str`, `list[str]`, `list[list[str]]`):
456
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
457
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
458
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
459
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
460
+ If set, will return tensors of a particular framework. Acceptable values are:
461
+
462
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
463
+ - `'np'`: Return NumPy `np.ndarray` objects.
464
+
465
+ Returns:
466
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
467
+
468
+ - **input_ids** -- List of token ids to be fed to a model.
469
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
470
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
471
+ `None`).
472
+ """
473
+ output_kwargs = self._merge_kwargs(
474
+ ColModernVBertProcessorKwargs,
475
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
476
+ **kwargs,
477
+ )
478
+
479
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
480
+
481
+ if isinstance(text, str):
482
+ text = [text]
483
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
484
+ raise ValueError("Text must be a string or a list of strings")
485
+
486
+ # Default suffix: repeat the augmentation token to pad query embeddings
487
+ if suffix is None:
488
+ suffix = self.query_augmentation_token * 10
489
+
490
+ # Build final queries: prefix + original query + augmentation suffix
491
+ texts_query: list[str] = [self.query_prefix + query + suffix for query in text]
492
+
493
+ batch_query = self.__call__(
494
+ text=texts_query,
495
+ return_token_type_ids=False,
496
+ text_kwargs=output_kwargs["text_kwargs"],
497
+ )
498
+
499
+ return batch_query
500
+
501
+ def score_retrieval(
502
+ self,
503
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
504
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
505
+ batch_size: int = 128,
506
+ output_dtype: Optional["torch.dtype"] = None,
507
+ output_device: Union["torch.device", str] = "cpu",
508
+ ) -> "torch.Tensor":
509
+ """
510
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
511
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
512
+ image of a document page.
513
+
514
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
515
+ should be fed as:
516
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
517
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
518
+ obtained by padding the list of tensors.
519
+
520
+ Args:
521
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
522
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
523
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
524
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
525
+ If `None`, the dtype of the input embeddings is used.
526
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
527
+
528
+ Returns:
529
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
530
+ tensor is saved on the "cpu" device.
531
+ """
532
+
533
+ if len(query_embeddings) == 0:
534
+ raise ValueError("No queries provided")
535
+ if len(passage_embeddings) == 0:
536
+ raise ValueError("No passages provided")
537
+
538
+ if query_embeddings[0].device != passage_embeddings[0].device:
539
+ raise ValueError("Queries and passages must be on the same device")
540
+
541
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
542
+ raise ValueError("Queries and passages must have the same dtype")
543
+
544
+ if output_dtype is None:
545
+ output_dtype = query_embeddings[0].dtype
546
+
547
+ scores: list[torch.Tensor] = []
548
+
549
+ for i in range(0, len(query_embeddings), batch_size):
550
+ batch_scores: list[torch.Tensor] = []
551
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
552
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
553
+ )
554
+ for j in range(0, len(passage_embeddings), batch_size):
555
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
556
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
557
+ )
558
+ batch_scores.append(
559
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
560
+ )
561
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
562
+
563
+ return torch.cat(scores, dim=0)
564
+
565
+
566
+ __all__ = ["ColModernVBertProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_colpali import *
22
+ from .modeling_colpali import *
23
+ from .processing_colpali import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/configuration_colpali.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
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
+ """ColPali model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring, logging
20
+ from ..auto import CONFIG_MAPPING, AutoConfig
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ @auto_docstring(checkpoint="vidore/colpali-v1.2")
27
+ @strict
28
+ class ColPaliConfig(PreTrainedConfig):
29
+ r"""
30
+ Example:
31
+
32
+ ```python
33
+ from transformers.models.colpali import ColPaliConfig, ColPaliForRetrieval
34
+
35
+ config = ColPaliConfig()
36
+ model = ColPaliForRetrieval(config)
37
+ ```
38
+ """
39
+
40
+ model_type = "colpali"
41
+ sub_configs = {"vlm_config": PreTrainedConfig, "text_config": AutoConfig}
42
+
43
+ vlm_config: dict | PreTrainedConfig | None = None
44
+ text_config: dict | PreTrainedConfig | None = None
45
+ embedding_dim: int = 128
46
+
47
+ def __post_init__(self, **kwargs):
48
+ if self.vlm_config is None:
49
+ self.vlm_config = CONFIG_MAPPING["paligemma"]()
50
+ logger.info(
51
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `PaliGemmaConfig` with default values."
52
+ )
53
+ elif isinstance(self.vlm_config, dict):
54
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
55
+
56
+ self.text_config = self.text_config if self.text_config is not None else self.vlm_config.text_config
57
+ if isinstance(self.text_config, dict):
58
+ self.text_config["model_type"] = self.text_config.get("model_type", "gemma")
59
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
60
+
61
+ super().__post_init__(**kwargs)
62
+
63
+
64
+ __all__ = ["ColPaliConfig"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/modeling_colpali.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
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
+ """PyTorch ColPali model"""
15
+
16
+ from dataclasses import dataclass
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers import AutoModel
22
+
23
+ from ... import initialization as init
24
+ from ...cache_utils import Cache
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...processing_utils import Unpack
27
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
28
+ from .configuration_colpali import ColPaliConfig
29
+
30
+
31
+ @auto_docstring
32
+ class ColPaliPreTrainedModel(PreTrainedModel):
33
+ config: ColPaliConfig
34
+ base_model_prefix = "model"
35
+ input_modalities = ("image", "text")
36
+ _no_split_modules = []
37
+ _supports_sdpa = True
38
+ _supports_flash_attn = True
39
+ _supports_flex_attn = True
40
+
41
+ @torch.no_grad()
42
+ def _init_weights(self, module):
43
+ std = (
44
+ self.config.initializer_range
45
+ if hasattr(self.config, "initializer_range")
46
+ else self.config.vlm_config.text_config.initializer_range
47
+ )
48
+
49
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
50
+ init.normal_(module.weight, mean=0.0, std=std)
51
+ if module.bias is not None:
52
+ init.zeros_(module.bias)
53
+ elif isinstance(module, nn.Embedding):
54
+ init.normal_(module.weight, mean=0.0, std=std)
55
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
56
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
57
+ init.zeros_(module.weight[module.padding_idx])
58
+
59
+
60
+ @auto_docstring(
61
+ custom_intro="""
62
+ Base class for ColPali embeddings output.
63
+ """
64
+ )
65
+ @dataclass
66
+ class ColPaliForRetrievalOutput(ModelOutput):
67
+ r"""
68
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
69
+ Language modeling loss (for next-token prediction).
70
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
71
+ The embeddings of the model.
72
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
73
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
74
+
75
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
76
+ `past_key_values` input) to speed up sequential decoding.
77
+ image_hidden_states (`torch.FloatTensor`, *optional*):
78
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
79
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
80
+ """
81
+
82
+ loss: torch.FloatTensor | None = None
83
+ embeddings: torch.Tensor | None = None
84
+ past_key_values: Cache | None = None
85
+ hidden_states: tuple[torch.FloatTensor] | None = None
86
+ attentions: tuple[torch.FloatTensor] | None = None
87
+ image_hidden_states: torch.FloatTensor | None = None
88
+
89
+
90
+ @auto_docstring(
91
+ custom_intro="""
92
+ The ColPali architecture leverages VLMs to construct efficient multi-vector embeddings directly
93
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
94
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
95
+ introduced in ColBERT.
96
+
97
+ Using ColPali removes the need for potentially complex and brittle layout recognition and OCR pipelines with a
98
+ single model that can take into account both the textual and visual content (layout, charts, etc.) of a document.
99
+
100
+ ColPali is part of the ColVision model family, which was first introduced in the following paper:
101
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
102
+ """
103
+ )
104
+ class ColPaliForRetrieval(ColPaliPreTrainedModel):
105
+ base_model_prefix = "vlm"
106
+
107
+ def __init__(self, config: ColPaliConfig):
108
+ super().__init__(config)
109
+ self.config = config
110
+ self.vocab_size = config.vlm_config.text_config.vocab_size
111
+
112
+ self.vlm = AutoModel.from_config(config.vlm_config)
113
+
114
+ self.embedding_dim = self.config.embedding_dim
115
+ self.embedding_proj_layer = nn.Linear(
116
+ self.config.vlm_config.text_config.hidden_size,
117
+ self.embedding_dim,
118
+ )
119
+
120
+ self.post_init()
121
+
122
+ @can_return_tuple
123
+ @auto_docstring
124
+ def forward(
125
+ self,
126
+ input_ids: torch.LongTensor | None = None,
127
+ pixel_values: torch.FloatTensor | None = None,
128
+ attention_mask: torch.Tensor | None = None,
129
+ **kwargs: Unpack[TransformersKwargs],
130
+ ) -> ColPaliForRetrievalOutput:
131
+ if pixel_values is not None:
132
+ pixel_values = pixel_values.to(dtype=self.dtype)
133
+ output_hidden_states = kwargs.pop("output_hidden_states", None)
134
+ if output_hidden_states is None:
135
+ output_hidden_states = self.config.output_hidden_states
136
+
137
+ vlm_output = self.vlm(
138
+ input_ids=input_ids,
139
+ attention_mask=attention_mask,
140
+ pixel_values=pixel_values,
141
+ output_hidden_states=True,
142
+ **kwargs,
143
+ )
144
+ vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
145
+ vlm_image_hidden_states = vlm_output.image_hidden_states if pixel_values is not None else None
146
+
147
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
148
+ proj_dtype = self.embedding_proj_layer.weight.dtype
149
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
150
+
151
+ # L2 normalization
152
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
153
+
154
+ if attention_mask is not None:
155
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
156
+
157
+ return ColPaliForRetrievalOutput(
158
+ embeddings=embeddings,
159
+ past_key_values=vlm_output.past_key_values,
160
+ hidden_states=vlm_hidden_states,
161
+ attentions=vlm_output.attentions,
162
+ image_hidden_states=vlm_image_hidden_states,
163
+ )
164
+
165
+
166
+ __all__ = [
167
+ "ColPaliForRetrieval",
168
+ "ColPaliPreTrainedModel",
169
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/modular_colpali.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
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
+
16
+ from typing import Optional, Union
17
+
18
+ from transformers.models.paligemma.processing_paligemma import IMAGE_TOKEN, PaliGemmaProcessor, build_string_from_input
19
+
20
+ from ...feature_extraction_utils import BatchFeature
21
+ from ...image_utils import ImageInput, make_flat_list_of_images
22
+ from ...processing_utils import ProcessingKwargs, Unpack
23
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
24
+ from ...utils import is_torch_available, logging
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
34
+ _defaults = {
35
+ "text_kwargs": {
36
+ "padding": "longest",
37
+ },
38
+ "images_kwargs": {
39
+ "data_format": "channels_first",
40
+ "do_convert_rgb": True,
41
+ },
42
+ "common_kwargs": {"return_tensors": "pt"},
43
+ }
44
+
45
+
46
+ class ColPaliProcessor(PaliGemmaProcessor):
47
+ def __init__(
48
+ self,
49
+ image_processor=None,
50
+ tokenizer=None,
51
+ chat_template=None,
52
+ visual_prompt_prefix: str = "Describe the image.",
53
+ query_prefix: str = "Question: ",
54
+ ):
55
+ r"""
56
+ visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
57
+ A string that gets tokenized and prepended to the image tokens.
58
+ query_prefix (`str`, *optional*, defaults to `"Question: "`):
59
+ A prefix to be used for the query.
60
+ """
61
+ self.visual_prompt_prefix = visual_prompt_prefix
62
+ self.query_prefix = query_prefix
63
+ super().__init__(image_processor=image_processor, tokenizer=tokenizer, chat_template=chat_template)
64
+
65
+ @property
66
+ def query_augmentation_token(self) -> str:
67
+ """
68
+ Return the query augmentation token.
69
+
70
+ Query augmentation buffers are used as reasoning buffers during inference.
71
+ """
72
+ return self.tokenizer.pad_token
73
+
74
+ def __call__(
75
+ self,
76
+ images: ImageInput | None = None,
77
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
78
+ **kwargs: Unpack[ColPaliProcessorKwargs],
79
+ ) -> BatchFeature:
80
+ r"""
81
+ Returns:
82
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
83
+
84
+ - **input_ids** -- List of token ids to be fed to a model.
85
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
86
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
87
+ `None`).
88
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
89
+ """
90
+ output_kwargs = self._merge_kwargs(
91
+ ColPaliProcessorKwargs,
92
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
93
+ **kwargs,
94
+ )
95
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
96
+
97
+ return_token_type_ids = True
98
+
99
+ if text is None and images is None:
100
+ raise ValueError("Either text or images must be provided")
101
+ if text is not None and images is not None:
102
+ raise ValueError("Only one of text or images can be processed at a time")
103
+
104
+ if images is not None:
105
+ images = self.image_processor.fetch_images(images)
106
+ images = make_flat_list_of_images(images)
107
+ texts_doc = [self.visual_prompt_prefix] * len(images)
108
+ images = [self.image_processor.process_image(image) for image in images]
109
+
110
+ input_strings = [
111
+ build_string_from_input(
112
+ prompt=prompt,
113
+ bos_token=self.tokenizer.bos_token,
114
+ image_seq_len=self.image_seq_length,
115
+ image_token=IMAGE_TOKEN,
116
+ num_images=len(image_list) if isinstance(image_list, list) else 1,
117
+ )
118
+ for prompt, image_list in zip(texts_doc, images)
119
+ ]
120
+ pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
121
+
122
+ # max_length has to account for the image tokens
123
+ if output_kwargs["text_kwargs"].get("max_length", None) is not None:
124
+ output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
125
+
126
+ inputs = self.tokenizer(
127
+ input_strings,
128
+ return_token_type_ids=return_token_type_ids,
129
+ **output_kwargs["text_kwargs"],
130
+ )
131
+
132
+ return_data = {**inputs, "pixel_values": pixel_values}
133
+
134
+ if return_token_type_ids:
135
+ labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
136
+ return_data.update({"labels": labels})
137
+
138
+ return BatchFeature(data=return_data)
139
+
140
+ elif text is not None:
141
+ if isinstance(text, str):
142
+ text = [text]
143
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
144
+ raise ValueError("Text must be a string or a list of strings")
145
+
146
+ if suffix is None:
147
+ suffix = self.query_augmentation_token * 10
148
+
149
+ texts_query: list[str] = []
150
+ for query in text:
151
+ query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
152
+ texts_query.append(query)
153
+
154
+ output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
155
+
156
+ batch_query = self.tokenizer(
157
+ texts_query,
158
+ return_token_type_ids=return_token_type_ids,
159
+ **output_kwargs["text_kwargs"],
160
+ )
161
+
162
+ return batch_query
163
+
164
+ def process_images(
165
+ self,
166
+ images: ImageInput | None = None,
167
+ **kwargs: Unpack[ColPaliProcessorKwargs],
168
+ ) -> BatchFeature:
169
+ """
170
+ Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
171
+ [`ColPaliProcessor.__call__`].
172
+
173
+ This method forwards the `images` and `kwargs` arguments to the image processor.
174
+
175
+ Args:
176
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
177
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
178
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
179
+ number of channels, H and W are image height and width.
180
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
181
+ If set, will return tensors of a particular framework. Acceptable values are:
182
+
183
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
184
+ - `'np'`: Return NumPy `np.ndarray` objects.
185
+
186
+ Returns:
187
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
188
+
189
+ - **input_ids** -- List of token ids to be fed to a model.
190
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
191
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
192
+ `None`).
193
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
194
+ """
195
+ return self.__call__(images=images, **kwargs)
196
+
197
+ def process_queries(
198
+ self,
199
+ text: TextInput | list[TextInput],
200
+ **kwargs: Unpack[ColPaliProcessorKwargs],
201
+ ) -> BatchFeature:
202
+ """
203
+ Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
204
+ [`ColPaliProcessor.__call__`].
205
+
206
+ This method forwards the `text` and `kwargs` arguments to the tokenizer.
207
+
208
+ Args:
209
+ text (`str`, `list[str]`, `list[list[str]]`):
210
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
211
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
212
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
213
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
214
+ If set, will return tensors of a particular framework. Acceptable values are:
215
+
216
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
217
+ - `'np'`: Return NumPy `np.ndarray` objects.
218
+
219
+ Returns:
220
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
221
+
222
+ - **input_ids** -- List of token ids to be fed to a model.
223
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
224
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
225
+ `None`).
226
+ """
227
+ return self.__call__(text=text, **kwargs)
228
+
229
+ def score_retrieval(
230
+ self,
231
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
232
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
233
+ batch_size: int = 128,
234
+ output_dtype: Optional["torch.dtype"] = None,
235
+ output_device: Union["torch.device", str] = "cpu",
236
+ ) -> "torch.Tensor":
237
+ """
238
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
239
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
240
+ image of a document page.
241
+
242
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
243
+ should be fed as:
244
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
245
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
246
+ obtained by padding the list of tensors.
247
+
248
+ Args:
249
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
250
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
251
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
252
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
253
+ If `None`, the dtype of the input embeddings is used.
254
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
255
+
256
+ Returns:
257
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
258
+ tensor is saved on the "cpu" device.
259
+ """
260
+
261
+ if len(query_embeddings) == 0:
262
+ raise ValueError("No queries provided")
263
+ if len(passage_embeddings) == 0:
264
+ raise ValueError("No passages provided")
265
+
266
+ if query_embeddings[0].device != passage_embeddings[0].device:
267
+ raise ValueError("Queries and passages must be on the same device")
268
+
269
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
270
+ raise ValueError("Queries and passages must have the same dtype")
271
+
272
+ if output_dtype is None:
273
+ output_dtype = query_embeddings[0].dtype
274
+
275
+ scores: list[torch.Tensor] = []
276
+
277
+ for i in range(0, len(query_embeddings), batch_size):
278
+ batch_scores: list[torch.Tensor] = []
279
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
280
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
281
+ )
282
+ for j in range(0, len(passage_embeddings), batch_size):
283
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
284
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
285
+ )
286
+ batch_scores.append(
287
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
288
+ )
289
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
290
+
291
+ return torch.cat(scores, dim=0)
292
+
293
+
294
+ __all__ = [
295
+ "ColPaliProcessor",
296
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colpali/processing_colpali.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colpali/modular_colpali.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colpali.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from typing import Optional, Union
23
+
24
+ from ...feature_extraction_utils import BatchFeature
25
+ from ...image_utils import ImageInput, make_flat_list_of_images
26
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
27
+ from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
28
+ from ...utils import auto_docstring, is_torch_available
29
+
30
+
31
+ if is_torch_available():
32
+ import torch
33
+
34
+
35
+ class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
36
+ _defaults = {
37
+ "text_kwargs": {
38
+ "padding": "longest",
39
+ },
40
+ "images_kwargs": {
41
+ "data_format": "channels_first",
42
+ "do_convert_rgb": True,
43
+ },
44
+ "common_kwargs": {"return_tensors": "pt"},
45
+ }
46
+
47
+
48
+ IMAGE_TOKEN = "<image>"
49
+ EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
50
+
51
+
52
+ def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
53
+ """
54
+ Builds a string from the input prompt and image tokens.
55
+ For example, for the call:
56
+ build_string_from_input(
57
+ prompt="Prefix str"
58
+ bos_token="<s>",
59
+ image_seq_len=3,
60
+ image_token="<im>",
61
+ )
62
+ The output will be:
63
+ "<im><im><im><s>Initial str"
64
+ Args:
65
+ prompt (`list[Union[str, ImageInput]]`): The input prompt.
66
+ bos_token (`str`): The beginning of sentence token.
67
+ image_seq_len (`int`): The length of the image sequence.
68
+ image_token (`str`): The image token.
69
+ num_images (`int`): Number of images in the prompt.
70
+ """
71
+ return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
72
+
73
+
74
+ @auto_docstring
75
+ class ColPaliProcessor(ProcessorMixin):
76
+ def __init__(
77
+ self,
78
+ image_processor=None,
79
+ tokenizer=None,
80
+ chat_template=None,
81
+ visual_prompt_prefix: str = "Describe the image.",
82
+ query_prefix: str = "Question: ",
83
+ ):
84
+ r"""
85
+ visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
86
+ A string that gets tokenized and prepended to the image tokens.
87
+ query_prefix (`str`, *optional*, defaults to `"Question: "`):
88
+ A prefix to be used for the query.
89
+ """
90
+ self.visual_prompt_prefix = visual_prompt_prefix
91
+ self.query_prefix = query_prefix
92
+ if not hasattr(image_processor, "image_seq_length"):
93
+ raise ValueError("Image processor is missing an `image_seq_length` attribute.")
94
+
95
+ self.image_seq_length = image_processor.image_seq_length
96
+
97
+ if not hasattr(tokenizer, "image_token"):
98
+ image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
99
+ tokens_to_add = {"additional_special_tokens": [image_token]}
100
+ tokenizer.add_special_tokens(tokens_to_add)
101
+ self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
102
+ self.image_token = IMAGE_TOKEN
103
+ else:
104
+ self.image_token_id = tokenizer.image_token_id
105
+ self.image_token = tokenizer.image_token
106
+
107
+ tokenizer.add_tokens(EXTRA_TOKENS)
108
+ tokenizer.add_bos_token = False
109
+ tokenizer.add_eos_token = False
110
+
111
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
112
+
113
+ @auto_docstring
114
+ def __call__(
115
+ self,
116
+ images: ImageInput | None = None,
117
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
118
+ **kwargs: Unpack[ColPaliProcessorKwargs],
119
+ ) -> BatchFeature:
120
+ r"""
121
+ Returns:
122
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
123
+
124
+ - **input_ids** -- List of token ids to be fed to a model.
125
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
126
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
127
+ `None`).
128
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
129
+ """
130
+ output_kwargs = self._merge_kwargs(
131
+ ColPaliProcessorKwargs,
132
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
133
+ **kwargs,
134
+ )
135
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
136
+
137
+ return_token_type_ids = True
138
+
139
+ if text is None and images is None:
140
+ raise ValueError("Either text or images must be provided")
141
+ if text is not None and images is not None:
142
+ raise ValueError("Only one of text or images can be processed at a time")
143
+
144
+ if images is not None:
145
+ images = self.image_processor.fetch_images(images)
146
+ images = make_flat_list_of_images(images)
147
+ texts_doc = [self.visual_prompt_prefix] * len(images)
148
+ images = [self.image_processor.process_image(image) for image in images]
149
+
150
+ input_strings = [
151
+ build_string_from_input(
152
+ prompt=prompt,
153
+ bos_token=self.tokenizer.bos_token,
154
+ image_seq_len=self.image_seq_length,
155
+ image_token=IMAGE_TOKEN,
156
+ num_images=len(image_list) if isinstance(image_list, list) else 1,
157
+ )
158
+ for prompt, image_list in zip(texts_doc, images)
159
+ ]
160
+ pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
161
+
162
+ # max_length has to account for the image tokens
163
+ if output_kwargs["text_kwargs"].get("max_length", None) is not None:
164
+ output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
165
+
166
+ inputs = self.tokenizer(
167
+ input_strings,
168
+ return_token_type_ids=return_token_type_ids,
169
+ **output_kwargs["text_kwargs"],
170
+ )
171
+
172
+ return_data = {**inputs, "pixel_values": pixel_values}
173
+
174
+ if return_token_type_ids:
175
+ labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
176
+ return_data.update({"labels": labels})
177
+
178
+ return BatchFeature(data=return_data)
179
+
180
+ elif text is not None:
181
+ if isinstance(text, str):
182
+ text = [text]
183
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
184
+ raise ValueError("Text must be a string or a list of strings")
185
+
186
+ if suffix is None:
187
+ suffix = self.query_augmentation_token * 10
188
+
189
+ texts_query: list[str] = []
190
+ for query in text:
191
+ query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
192
+ texts_query.append(query)
193
+
194
+ output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
195
+
196
+ batch_query = self.tokenizer(
197
+ texts_query,
198
+ return_token_type_ids=return_token_type_ids,
199
+ **output_kwargs["text_kwargs"],
200
+ )
201
+
202
+ return batch_query
203
+
204
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
205
+ """
206
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
207
+
208
+ Args:
209
+ image_sizes (list[list[str]], *optional*):
210
+ The input sizes formatted as (height, width) per each image.
211
+ Returns:
212
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
213
+ input modalities, along with other useful data.
214
+ """
215
+ vision_data = {}
216
+ if image_sizes is not None:
217
+ num_image_tokens = [self.image_seq_length] * len(image_sizes)
218
+ num_image_patches = [1] * len(image_sizes)
219
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
220
+ return MultiModalData(**vision_data)
221
+
222
+ @property
223
+ def model_input_names(self):
224
+ tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids", "labels"]
225
+ image_processor_input_names = self.image_processor.model_input_names
226
+ return list(tokenizer_input_names + image_processor_input_names)
227
+
228
+ @property
229
+ def query_augmentation_token(self) -> str:
230
+ """
231
+ Return the query augmentation token.
232
+
233
+ Query augmentation buffers are used as reasoning buffers during inference.
234
+ """
235
+ return self.tokenizer.pad_token
236
+
237
+ def process_images(
238
+ self,
239
+ images: ImageInput | None = None,
240
+ **kwargs: Unpack[ColPaliProcessorKwargs],
241
+ ) -> BatchFeature:
242
+ """
243
+ Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
244
+ [`ColPaliProcessor.__call__`].
245
+
246
+ This method forwards the `images` and `kwargs` arguments to the image processor.
247
+
248
+ Args:
249
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
250
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
251
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
252
+ number of channels, H and W are image height and width.
253
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
254
+ If set, will return tensors of a particular framework. Acceptable values are:
255
+
256
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
257
+ - `'np'`: Return NumPy `np.ndarray` objects.
258
+
259
+ Returns:
260
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
261
+
262
+ - **input_ids** -- List of token ids to be fed to a model.
263
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
264
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
265
+ `None`).
266
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
267
+ """
268
+ return self.__call__(images=images, **kwargs)
269
+
270
+ def process_queries(
271
+ self,
272
+ text: TextInput | list[TextInput],
273
+ **kwargs: Unpack[ColPaliProcessorKwargs],
274
+ ) -> BatchFeature:
275
+ """
276
+ Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
277
+ [`ColPaliProcessor.__call__`].
278
+
279
+ This method forwards the `text` and `kwargs` arguments to the tokenizer.
280
+
281
+ Args:
282
+ text (`str`, `list[str]`, `list[list[str]]`):
283
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
284
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
285
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
286
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
287
+ If set, will return tensors of a particular framework. Acceptable values are:
288
+
289
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
290
+ - `'np'`: Return NumPy `np.ndarray` objects.
291
+
292
+ Returns:
293
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
294
+
295
+ - **input_ids** -- List of token ids to be fed to a model.
296
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
297
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
298
+ `None`).
299
+ """
300
+ return self.__call__(text=text, **kwargs)
301
+
302
+ def score_retrieval(
303
+ self,
304
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
305
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
306
+ batch_size: int = 128,
307
+ output_dtype: Optional["torch.dtype"] = None,
308
+ output_device: Union["torch.device", str] = "cpu",
309
+ ) -> "torch.Tensor":
310
+ """
311
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
312
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
313
+ image of a document page.
314
+
315
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
316
+ should be fed as:
317
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
318
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
319
+ obtained by padding the list of tensors.
320
+
321
+ Args:
322
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
323
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
324
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
325
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
326
+ If `None`, the dtype of the input embeddings is used.
327
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
328
+
329
+ Returns:
330
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
331
+ tensor is saved on the "cpu" device.
332
+ """
333
+
334
+ if len(query_embeddings) == 0:
335
+ raise ValueError("No queries provided")
336
+ if len(passage_embeddings) == 0:
337
+ raise ValueError("No passages provided")
338
+
339
+ if query_embeddings[0].device != passage_embeddings[0].device:
340
+ raise ValueError("Queries and passages must be on the same device")
341
+
342
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
343
+ raise ValueError("Queries and passages must have the same dtype")
344
+
345
+ if output_dtype is None:
346
+ output_dtype = query_embeddings[0].dtype
347
+
348
+ scores: list[torch.Tensor] = []
349
+
350
+ for i in range(0, len(query_embeddings), batch_size):
351
+ batch_scores: list[torch.Tensor] = []
352
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
353
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
354
+ )
355
+ for j in range(0, len(passage_embeddings), batch_size):
356
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
357
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
358
+ )
359
+ batch_scores.append(
360
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
361
+ )
362
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
363
+
364
+ return torch.cat(scores, dim=0)
365
+
366
+
367
+ __all__ = ["ColPaliProcessor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_colqwen2 import *
22
+ from .modeling_colqwen2 import *
23
+ from .processing_colqwen2 import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/configuration_colqwen2.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team.
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
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring, logging
20
+ from ..auto import CONFIG_MAPPING
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ @auto_docstring(checkpoint="vidore/colqwen2-v1.0-hf")
27
+ @strict
28
+ class ColQwen2Config(PreTrainedConfig):
29
+ r"""
30
+ Example:
31
+
32
+ ```python
33
+ from transformers.models.colqwen2 import ColQwen2Config, ColQwen2ForRetrieval
34
+
35
+ config = ColQwen2Config()
36
+ model = ColQwen2ForRetrieval(config)
37
+ ```
38
+ """
39
+
40
+ model_type = "colqwen2"
41
+ sub_configs = {"vlm_config": PreTrainedConfig}
42
+
43
+ vlm_config: dict | PreTrainedConfig | None = None
44
+ embedding_dim: int = 128
45
+ initializer_range: float = 0.02
46
+
47
+ def __post_init__(self, **kwargs):
48
+ if self.vlm_config is None:
49
+ self.vlm_config = CONFIG_MAPPING["qwen2_vl"]()
50
+ logger.info(
51
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `Qwen2VLConfig` with default values."
52
+ )
53
+ elif isinstance(self.vlm_config, dict):
54
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
55
+
56
+ if not hasattr(self.vlm_config, "vocab_size"):
57
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
58
+
59
+ super().__post_init__(**kwargs)
60
+
61
+ def get_text_config(self, *args, **kwargs) -> PreTrainedConfig:
62
+ return self.vlm_config.get_text_config(*args, **kwargs)
63
+
64
+
65
+ __all__ = ["ColQwen2Config"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/modeling_colqwen2.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colqwen2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from dataclasses import dataclass
22
+
23
+ from torch import nn
24
+
25
+ from transformers import AutoModel
26
+
27
+ from ... import initialization as init
28
+ from ...cache_utils import Cache
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torch_available
31
+ from .configuration_colqwen2 import ColQwen2Config
32
+
33
+
34
+ if is_torch_available():
35
+ import torch
36
+
37
+
38
+ @auto_docstring
39
+ class ColQwen2PreTrainedModel(PreTrainedModel):
40
+ config: ColQwen2Config
41
+ base_model_prefix = "model"
42
+ input_modalities = ("image", "text")
43
+ _no_split_modules = []
44
+ _supports_sdpa = True
45
+ _supports_flash_attn = True
46
+ _supports_flex_attn = True
47
+
48
+ @torch.no_grad()
49
+ def _init_weights(self, module):
50
+ std = (
51
+ self.config.initializer_range
52
+ if hasattr(self.config, "initializer_range")
53
+ else self.config.vlm_config.text_config.initializer_range
54
+ )
55
+
56
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
57
+ init.normal_(module.weight, mean=0.0, std=std)
58
+ if module.bias is not None:
59
+ init.zeros_(module.bias)
60
+ elif isinstance(module, nn.Embedding):
61
+ init.normal_(module.weight, mean=0.0, std=std)
62
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
63
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
64
+ init.zeros_(module.weight[module.padding_idx])
65
+
66
+
67
+ @auto_docstring(
68
+ custom_intro="""
69
+ Base class for ColQwen2 embeddings output.
70
+ """
71
+ )
72
+ @dataclass
73
+ class ColQwen2ForRetrievalOutput(ModelOutput):
74
+ r"""
75
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
76
+ Language modeling loss (for next-token prediction).
77
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
78
+ The embeddings of the model.
79
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
80
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
81
+
82
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
83
+ `past_key_values` input) to speed up sequential decoding.
84
+ """
85
+
86
+ loss: torch.FloatTensor | None = None
87
+ embeddings: torch.Tensor | None = None
88
+ past_key_values: Cache | None = None
89
+ hidden_states: tuple[torch.FloatTensor] | None = None
90
+ attentions: tuple[torch.FloatTensor] | None = None
91
+
92
+
93
+ @auto_docstring(
94
+ custom_intro="""
95
+ Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
96
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
97
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
98
+ introduced in ColBERT.
99
+
100
+ Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
101
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
102
+
103
+ ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
104
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
105
+ """
106
+ )
107
+ class ColQwen2ForRetrieval(ColQwen2PreTrainedModel):
108
+ base_model_prefix = "vlm"
109
+
110
+ def __init__(self, config: ColQwen2Config):
111
+ super().__init__(config)
112
+ self.config = config
113
+ self.vocab_size = config.vlm_config.text_config.vocab_size
114
+
115
+ self.vlm = AutoModel.from_config(config.vlm_config)
116
+
117
+ self.embedding_dim = self.config.embedding_dim
118
+ self.embedding_proj_layer = nn.Linear(
119
+ self.config.vlm_config.text_config.hidden_size,
120
+ self.embedding_dim,
121
+ )
122
+
123
+ self.post_init()
124
+
125
+ @can_return_tuple
126
+ @auto_docstring
127
+ def forward(
128
+ self,
129
+ input_ids: torch.LongTensor | None = None,
130
+ attention_mask: torch.Tensor | None = None,
131
+ position_ids: torch.LongTensor | None = None,
132
+ past_key_values: Cache | None = None,
133
+ labels: torch.LongTensor | None = None,
134
+ inputs_embeds: torch.FloatTensor | None = None,
135
+ use_cache: bool | None = None,
136
+ output_attentions: bool | None = None,
137
+ output_hidden_states: bool | None = None,
138
+ return_dict: bool | None = None,
139
+ pixel_values: torch.Tensor | None = None,
140
+ image_grid_thw: torch.LongTensor | None = None,
141
+ **kwargs,
142
+ ) -> ColQwen2ForRetrievalOutput:
143
+ r"""
144
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
145
+ The temporal, height and width of feature shape of each image in LLM.
146
+ """
147
+ # Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
148
+ if pixel_values is not None and image_grid_thw is not None:
149
+ # NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
150
+ offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,)
151
+ arange = torch.arange(pixel_values.shape[1], device=offsets.device) # (max_len,)
152
+ mask = arange.unsqueeze(0) < offsets.unsqueeze(1) # (batch_size, max_len)
153
+ pixel_values = pixel_values[mask] # (total_valid_patches, channels, height, width)
154
+
155
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
156
+
157
+ output_hidden_states = (
158
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
159
+ )
160
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
161
+
162
+ # Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
163
+ if inputs_embeds is None:
164
+ inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
165
+
166
+ if pixel_values is not None:
167
+ image_embeds = self.vlm.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True).pooler_output
168
+ image_mask = (
169
+ (input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
170
+ )
171
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
172
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
173
+
174
+ vlm_output = self.vlm(
175
+ input_ids=None,
176
+ position_ids=position_ids,
177
+ attention_mask=attention_mask,
178
+ past_key_values=past_key_values,
179
+ inputs_embeds=inputs_embeds,
180
+ use_cache=use_cache,
181
+ output_attentions=output_attentions,
182
+ output_hidden_states=output_hidden_states,
183
+ return_dict=return_dict,
184
+ )
185
+
186
+ vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
187
+
188
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
189
+ proj_dtype = self.embedding_proj_layer.weight.dtype
190
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
191
+
192
+ # L2 normalization
193
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
194
+ if attention_mask is not None:
195
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
196
+
197
+ return ColQwen2ForRetrievalOutput(
198
+ embeddings=embeddings,
199
+ past_key_values=vlm_output.past_key_values,
200
+ hidden_states=vlm_hidden_states,
201
+ attentions=vlm_output.attentions,
202
+ )
203
+
204
+
205
+ __all__ = ["ColQwen2ForRetrieval", "ColQwen2PreTrainedModel"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/modular_colqwen2.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team.
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
+ from dataclasses import dataclass
16
+
17
+ from ...cache_utils import Cache
18
+ from ...feature_extraction_utils import BatchFeature
19
+ from ...image_utils import ImageInput, is_valid_image
20
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
21
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
22
+ from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torch_available, logging
23
+ from ..colpali.modeling_colpali import ColPaliForRetrieval, ColPaliPreTrainedModel
24
+ from ..colpali.processing_colpali import ColPaliProcessor
25
+ from .configuration_colqwen2 import ColQwen2Config
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ class ColQwen2ProcessorKwargs(ProcessingKwargs, total=False):
35
+ _defaults = {
36
+ "text_kwargs": {
37
+ "padding": "longest",
38
+ },
39
+ "images_kwargs": {
40
+ "data_format": "channels_first",
41
+ "do_convert_rgb": True,
42
+ },
43
+ "common_kwargs": {"return_tensors": "pt"},
44
+ }
45
+
46
+
47
+ class ColQwen2Processor(ColPaliProcessor):
48
+ def __init__(
49
+ self,
50
+ image_processor=None,
51
+ tokenizer=None,
52
+ chat_template=None,
53
+ visual_prompt_prefix: str | None = None,
54
+ query_prefix: str | None = None,
55
+ **kwargs,
56
+ ):
57
+ r"""
58
+ visual_prompt_prefix (`str`, *optional*, defaults to `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`):
59
+ A string that gets tokenized and prepended to the image tokens.
60
+ query_prefix (`str`, *optional*, defaults to `"Query: "`):
61
+ A prefix to be used for the query.
62
+ """
63
+ ProcessorMixin.__init__(self, image_processor, tokenizer, chat_template=chat_template)
64
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
65
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
66
+
67
+ self.visual_prompt_prefix = visual_prompt_prefix or (
68
+ "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"
69
+ )
70
+ self.query_prefix = query_prefix or "Query: "
71
+
72
+ def __call__(
73
+ self,
74
+ images: ImageInput | None = None,
75
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
76
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
77
+ ) -> BatchFeature:
78
+ r"""
79
+ Returns:
80
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
81
+
82
+ - **input_ids** -- List of token ids to be fed to a model.
83
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
84
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
85
+ `None`).
86
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
87
+ """
88
+ output_kwargs = self._merge_kwargs(
89
+ ColQwen2ProcessorKwargs,
90
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
91
+ **kwargs,
92
+ )
93
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
94
+
95
+ return_token_type_ids = suffix is not None
96
+
97
+ if text is None and images is None:
98
+ raise ValueError("Either text or images must be provided")
99
+ if text is not None and images is not None:
100
+ raise ValueError("Only one of text or images can be processed at a time")
101
+
102
+ if images is not None:
103
+ if is_valid_image(images):
104
+ images = [images]
105
+ elif isinstance(images, list) and is_valid_image(images[0]):
106
+ pass
107
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
108
+ raise ValueError("images must be an image, list of images or list of list of images")
109
+
110
+ texts_doc = [self.visual_prompt_prefix] * len(images)
111
+
112
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
113
+ image_grid_thw = image_inputs["image_grid_thw"]
114
+
115
+ if image_grid_thw is not None:
116
+ merge_length = self.image_processor.merge_size**2
117
+ index = 0
118
+ for i in range(len(texts_doc)):
119
+ while self.image_token in texts_doc[i]:
120
+ texts_doc[i] = texts_doc[i].replace(
121
+ self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
122
+ )
123
+ index += 1
124
+ texts_doc[i] = texts_doc[i].replace("<|placeholder|>", self.image_token)
125
+
126
+ text_inputs = self.tokenizer(
127
+ texts_doc,
128
+ return_token_type_ids=False,
129
+ **output_kwargs["text_kwargs"],
130
+ )
131
+
132
+ return_data = BatchFeature(data={**text_inputs, **image_inputs})
133
+
134
+ # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs.
135
+ offsets = return_data["image_grid_thw"][:, 1] * return_data["image_grid_thw"][:, 2] # (batch_size,)
136
+
137
+ # Split the pixel_values tensor into a list of tensors, one per image
138
+ pixel_values = list(
139
+ torch.split(return_data["pixel_values"], offsets.tolist())
140
+ ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)]
141
+
142
+ # Pad the list of pixel_value tensors to the same length along the sequence dimension
143
+ return_data["pixel_values"] = torch.nn.utils.rnn.pad_sequence(
144
+ pixel_values, batch_first=True
145
+ ) # (batch_size, max_num_patches, pixel_values)
146
+
147
+ if return_token_type_ids:
148
+ labels = return_data["input_ids"].masked_fill(return_data["token_type_ids"] == 0, -100)
149
+ return_data.update({"labels": labels})
150
+
151
+ return return_data
152
+
153
+ elif text is not None:
154
+ if isinstance(text, str):
155
+ text = [text]
156
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
157
+ raise ValueError("Text must be a string or a list of strings")
158
+
159
+ if suffix is None:
160
+ suffix = self.query_augmentation_token * 10
161
+
162
+ texts_query: list[str] = []
163
+
164
+ for query in text:
165
+ augmented_query = self.query_prefix + query + suffix
166
+ texts_query.append(augmented_query)
167
+
168
+ batch_query = self.tokenizer(
169
+ texts_query,
170
+ return_token_type_ids=False,
171
+ **output_kwargs["text_kwargs"],
172
+ )
173
+
174
+ return batch_query
175
+
176
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
177
+ """
178
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
179
+ Args:
180
+ image_sizes (`list[list[int]]`, *optional*):
181
+ The input sizes formatted as (height, width) per each image.
182
+ Returns:
183
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
184
+ input modalities, along with other useful data.
185
+ """
186
+
187
+ vision_data = {}
188
+ if image_sizes is not None:
189
+ images_kwargs = ColQwen2ProcessorKwargs._defaults.get("images_kwargs", {})
190
+ images_kwargs.update(kwargs)
191
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
192
+
193
+ num_image_patches = [
194
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
195
+ for image_size in image_sizes
196
+ ]
197
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
198
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
199
+
200
+ return MultiModalData(**vision_data)
201
+
202
+ @property
203
+ def model_input_names(self):
204
+ tokenizer_input_names = self.tokenizer.model_input_names
205
+ image_processor_input_names = self.image_processor.model_input_names
206
+
207
+ # ColQwen doesn't process videos. Make a copy of list when removing
208
+ # otherwise `self.feature_extractor.model_input_names` is also modified
209
+ image_processor_input_names = [
210
+ name for name in image_processor_input_names if name not in ["pixel_values_videos", "video_grid_thw"]
211
+ ]
212
+ return tokenizer_input_names + image_processor_input_names
213
+
214
+
215
+ class ColQwen2PreTrainedModel(ColPaliPreTrainedModel):
216
+ pass
217
+
218
+
219
+ @auto_docstring(
220
+ custom_intro="""
221
+ Base class for ColQwen2 embeddings output.
222
+ """
223
+ )
224
+ @dataclass
225
+ class ColQwen2ForRetrievalOutput(ModelOutput):
226
+ r"""
227
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
228
+ Language modeling loss (for next-token prediction).
229
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
230
+ The embeddings of the model.
231
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
232
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
233
+
234
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
235
+ `past_key_values` input) to speed up sequential decoding.
236
+ """
237
+
238
+ loss: torch.FloatTensor | None = None
239
+ embeddings: torch.Tensor | None = None
240
+ past_key_values: Cache | None = None
241
+ hidden_states: tuple[torch.FloatTensor] | None = None
242
+ attentions: tuple[torch.FloatTensor] | None = None
243
+
244
+
245
+ @auto_docstring(
246
+ custom_intro="""
247
+ Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
248
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
249
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
250
+ introduced in ColBERT.
251
+
252
+ Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
253
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
254
+
255
+ ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
256
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
257
+ """
258
+ )
259
+ class ColQwen2ForRetrieval(ColPaliForRetrieval):
260
+ def __init__(self, config: ColQwen2Config):
261
+ super().__init__(config)
262
+ del self._tied_weights_keys
263
+
264
+ @can_return_tuple
265
+ @auto_docstring
266
+ def forward(
267
+ self,
268
+ input_ids: torch.LongTensor | None = None,
269
+ attention_mask: torch.Tensor | None = None,
270
+ position_ids: torch.LongTensor | None = None,
271
+ past_key_values: Cache | None = None,
272
+ labels: torch.LongTensor | None = None,
273
+ inputs_embeds: torch.FloatTensor | None = None,
274
+ use_cache: bool | None = None,
275
+ output_attentions: bool | None = None,
276
+ output_hidden_states: bool | None = None,
277
+ return_dict: bool | None = None,
278
+ pixel_values: torch.Tensor | None = None,
279
+ image_grid_thw: torch.LongTensor | None = None,
280
+ **kwargs,
281
+ ) -> ColQwen2ForRetrievalOutput:
282
+ r"""
283
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
284
+ The temporal, height and width of feature shape of each image in LLM.
285
+ """
286
+ # Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
287
+ if pixel_values is not None and image_grid_thw is not None:
288
+ # NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
289
+ offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,)
290
+ arange = torch.arange(pixel_values.shape[1], device=offsets.device) # (max_len,)
291
+ mask = arange.unsqueeze(0) < offsets.unsqueeze(1) # (batch_size, max_len)
292
+ pixel_values = pixel_values[mask] # (total_valid_patches, channels, height, width)
293
+
294
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
295
+
296
+ output_hidden_states = (
297
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
298
+ )
299
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
300
+
301
+ # Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
302
+ if inputs_embeds is None:
303
+ inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
304
+
305
+ if pixel_values is not None:
306
+ image_embeds = self.vlm.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True).pooler_output
307
+ image_mask = (
308
+ (input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
309
+ )
310
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
311
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
312
+
313
+ vlm_output = self.vlm(
314
+ input_ids=None,
315
+ position_ids=position_ids,
316
+ attention_mask=attention_mask,
317
+ past_key_values=past_key_values,
318
+ inputs_embeds=inputs_embeds,
319
+ use_cache=use_cache,
320
+ output_attentions=output_attentions,
321
+ output_hidden_states=output_hidden_states,
322
+ return_dict=return_dict,
323
+ )
324
+
325
+ vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
326
+
327
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
328
+ proj_dtype = self.embedding_proj_layer.weight.dtype
329
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
330
+
331
+ # L2 normalization
332
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
333
+ if attention_mask is not None:
334
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
335
+
336
+ return ColQwen2ForRetrievalOutput(
337
+ embeddings=embeddings,
338
+ past_key_values=vlm_output.past_key_values,
339
+ hidden_states=vlm_hidden_states,
340
+ attentions=vlm_output.attentions,
341
+ )
342
+
343
+
344
+ __all__ = [
345
+ "ColQwen2ForRetrieval",
346
+ "ColQwen2PreTrainedModel",
347
+ "ColQwen2Processor",
348
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/colqwen2/processing_colqwen2.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_colqwen2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from typing import Optional, Union
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...image_utils import ImageInput, is_valid_image
25
+ from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
26
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
27
+ from ...utils import auto_docstring, is_torch_available
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+
34
+ class ColQwen2ProcessorKwargs(ProcessingKwargs, total=False):
35
+ _defaults = {
36
+ "text_kwargs": {
37
+ "padding": "longest",
38
+ },
39
+ "images_kwargs": {
40
+ "data_format": "channels_first",
41
+ "do_convert_rgb": True,
42
+ },
43
+ "common_kwargs": {"return_tensors": "pt"},
44
+ }
45
+
46
+
47
+ @auto_docstring
48
+ class ColQwen2Processor(ProcessorMixin):
49
+ def __init__(
50
+ self,
51
+ image_processor=None,
52
+ tokenizer=None,
53
+ chat_template=None,
54
+ visual_prompt_prefix: str | None = None,
55
+ query_prefix: str | None = None,
56
+ **kwargs,
57
+ ):
58
+ r"""
59
+ visual_prompt_prefix (`str`, *optional*, defaults to `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`):
60
+ A string that gets tokenized and prepended to the image tokens.
61
+ query_prefix (`str`, *optional*, defaults to `"Query: "`):
62
+ A prefix to be used for the query.
63
+ """
64
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
65
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
66
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
67
+
68
+ self.visual_prompt_prefix = visual_prompt_prefix or (
69
+ "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"
70
+ )
71
+ self.query_prefix = query_prefix or "Query: "
72
+
73
+ @auto_docstring
74
+ def __call__(
75
+ self,
76
+ images: ImageInput | None = None,
77
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
78
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
79
+ ) -> BatchFeature:
80
+ r"""
81
+ Returns:
82
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
83
+
84
+ - **input_ids** -- List of token ids to be fed to a model.
85
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
86
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
87
+ `None`).
88
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
89
+ """
90
+ output_kwargs = self._merge_kwargs(
91
+ ColQwen2ProcessorKwargs,
92
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
93
+ **kwargs,
94
+ )
95
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
96
+
97
+ return_token_type_ids = suffix is not None
98
+
99
+ if text is None and images is None:
100
+ raise ValueError("Either text or images must be provided")
101
+ if text is not None and images is not None:
102
+ raise ValueError("Only one of text or images can be processed at a time")
103
+
104
+ if images is not None:
105
+ if is_valid_image(images):
106
+ images = [images]
107
+ elif isinstance(images, list) and is_valid_image(images[0]):
108
+ pass
109
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
110
+ raise ValueError("images must be an image, list of images or list of list of images")
111
+
112
+ texts_doc = [self.visual_prompt_prefix] * len(images)
113
+
114
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
115
+ image_grid_thw = image_inputs["image_grid_thw"]
116
+
117
+ if image_grid_thw is not None:
118
+ merge_length = self.image_processor.merge_size**2
119
+ index = 0
120
+ for i in range(len(texts_doc)):
121
+ while self.image_token in texts_doc[i]:
122
+ texts_doc[i] = texts_doc[i].replace(
123
+ self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
124
+ )
125
+ index += 1
126
+ texts_doc[i] = texts_doc[i].replace("<|placeholder|>", self.image_token)
127
+
128
+ text_inputs = self.tokenizer(
129
+ texts_doc,
130
+ return_token_type_ids=False,
131
+ **output_kwargs["text_kwargs"],
132
+ )
133
+
134
+ return_data = BatchFeature(data={**text_inputs, **image_inputs})
135
+
136
+ # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs.
137
+ offsets = return_data["image_grid_thw"][:, 1] * return_data["image_grid_thw"][:, 2] # (batch_size,)
138
+
139
+ # Split the pixel_values tensor into a list of tensors, one per image
140
+ pixel_values = list(
141
+ torch.split(return_data["pixel_values"], offsets.tolist())
142
+ ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)]
143
+
144
+ # Pad the list of pixel_value tensors to the same length along the sequence dimension
145
+ return_data["pixel_values"] = torch.nn.utils.rnn.pad_sequence(
146
+ pixel_values, batch_first=True
147
+ ) # (batch_size, max_num_patches, pixel_values)
148
+
149
+ if return_token_type_ids:
150
+ labels = return_data["input_ids"].masked_fill(return_data["token_type_ids"] == 0, -100)
151
+ return_data.update({"labels": labels})
152
+
153
+ return return_data
154
+
155
+ elif text is not None:
156
+ if isinstance(text, str):
157
+ text = [text]
158
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
159
+ raise ValueError("Text must be a string or a list of strings")
160
+
161
+ if suffix is None:
162
+ suffix = self.query_augmentation_token * 10
163
+
164
+ texts_query: list[str] = []
165
+
166
+ for query in text:
167
+ augmented_query = self.query_prefix + query + suffix
168
+ texts_query.append(augmented_query)
169
+
170
+ batch_query = self.tokenizer(
171
+ texts_query,
172
+ return_token_type_ids=False,
173
+ **output_kwargs["text_kwargs"],
174
+ )
175
+
176
+ return batch_query
177
+
178
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
179
+ """
180
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
181
+ Args:
182
+ image_sizes (`list[list[int]]`, *optional*):
183
+ The input sizes formatted as (height, width) per each image.
184
+ Returns:
185
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
186
+ input modalities, along with other useful data.
187
+ """
188
+
189
+ vision_data = {}
190
+ if image_sizes is not None:
191
+ images_kwargs = ColQwen2ProcessorKwargs._defaults.get("images_kwargs", {})
192
+ images_kwargs.update(kwargs)
193
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
194
+
195
+ num_image_patches = [
196
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
197
+ for image_size in image_sizes
198
+ ]
199
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
200
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
201
+
202
+ return MultiModalData(**vision_data)
203
+
204
+ @property
205
+ def model_input_names(self):
206
+ tokenizer_input_names = self.tokenizer.model_input_names
207
+ image_processor_input_names = self.image_processor.model_input_names
208
+
209
+ # ColQwen doesn't process videos. Make a copy of list when removing
210
+ # otherwise `self.feature_extractor.model_input_names` is also modified
211
+ image_processor_input_names = [
212
+ name for name in image_processor_input_names if name not in ["pixel_values_videos", "video_grid_thw"]
213
+ ]
214
+ return tokenizer_input_names + image_processor_input_names
215
+
216
+ @property
217
+ def query_augmentation_token(self) -> str:
218
+ """
219
+ Return the query augmentation token.
220
+
221
+ Query augmentation buffers are used as reasoning buffers during inference.
222
+ """
223
+ return self.tokenizer.pad_token
224
+
225
+ def process_images(
226
+ self,
227
+ images: ImageInput | None = None,
228
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
229
+ ) -> BatchFeature:
230
+ """
231
+ Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColQwen2Processor's
232
+ [`ColQwen2Processor.__call__`].
233
+
234
+ This method forwards the `images` and `kwargs` arguments to the image processor.
235
+
236
+ Args:
237
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
238
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
239
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
240
+ number of channels, H and W are image height and width.
241
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
242
+ If set, will return tensors of a particular framework. Acceptable values are:
243
+
244
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
245
+ - `'np'`: Return NumPy `np.ndarray` objects.
246
+
247
+ Returns:
248
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
249
+
250
+ - **input_ids** -- List of token ids to be fed to a model.
251
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
252
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
253
+ `None`).
254
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
255
+ """
256
+ return self.__call__(images=images, **kwargs)
257
+
258
+ def process_queries(
259
+ self,
260
+ text: TextInput | list[TextInput],
261
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
262
+ ) -> BatchFeature:
263
+ """
264
+ Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColQwen2Processor's
265
+ [`ColQwen2Processor.__call__`].
266
+
267
+ This method forwards the `text` and `kwargs` arguments to the tokenizer.
268
+
269
+ Args:
270
+ text (`str`, `list[str]`, `list[list[str]]`):
271
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
272
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
273
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
274
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
275
+ If set, will return tensors of a particular framework. Acceptable values are:
276
+
277
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
278
+ - `'np'`: Return NumPy `np.ndarray` objects.
279
+
280
+ Returns:
281
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
282
+
283
+ - **input_ids** -- List of token ids to be fed to a model.
284
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
285
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
286
+ `None`).
287
+ """
288
+ return self.__call__(text=text, **kwargs)
289
+
290
+ def score_retrieval(
291
+ self,
292
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
293
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
294
+ batch_size: int = 128,
295
+ output_dtype: Optional["torch.dtype"] = None,
296
+ output_device: Union["torch.device", str] = "cpu",
297
+ ) -> "torch.Tensor":
298
+ """
299
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
300
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
301
+ image of a document page.
302
+
303
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
304
+ should be fed as:
305
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
306
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
307
+ obtained by padding the list of tensors.
308
+
309
+ Args:
310
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
311
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
312
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
313
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
314
+ If `None`, the dtype of the input embeddings is used.
315
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
316
+
317
+ Returns:
318
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
319
+ tensor is saved on the "cpu" device.
320
+ """
321
+
322
+ if len(query_embeddings) == 0:
323
+ raise ValueError("No queries provided")
324
+ if len(passage_embeddings) == 0:
325
+ raise ValueError("No passages provided")
326
+
327
+ if query_embeddings[0].device != passage_embeddings[0].device:
328
+ raise ValueError("Queries and passages must be on the same device")
329
+
330
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
331
+ raise ValueError("Queries and passages must have the same dtype")
332
+
333
+ if output_dtype is None:
334
+ output_dtype = query_embeddings[0].dtype
335
+
336
+ scores: list[torch.Tensor] = []
337
+
338
+ for i in range(0, len(query_embeddings), batch_size):
339
+ batch_scores: list[torch.Tensor] = []
340
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
341
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
342
+ )
343
+ for j in range(0, len(passage_embeddings), batch_size):
344
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
345
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
346
+ )
347
+ batch_scores.append(
348
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
349
+ )
350
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
351
+
352
+ return torch.cat(scores, dim=0)
353
+
354
+
355
+ __all__ = ["ColQwen2Processor"]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/conditional_detr/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_conditional_detr import *
22
+ from .image_processing_conditional_detr import *
23
+ from .image_processing_pil_conditional_detr import *
24
+ from .modeling_conditional_detr import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. 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
+ """Conditional DETR model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+ from ..auto import AutoConfig
22
+
23
+
24
+ @auto_docstring(checkpoint="microsoft/conditional-detr-resnet-50")
25
+ @strict
26
+ class ConditionalDetrConfig(PreTrainedConfig):
27
+ r"""
28
+ num_queries (`int`, *optional*, defaults to 100):
29
+ Number of object queries, i.e. detection slots. This is the maximal number of objects
30
+ [`ConditionalDetrModel`] can detect in a single image. For COCO, we recommend 100 queries.
31
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
32
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
33
+ position_embedding_type (`str`, *optional*, defaults to `"sine"`):
34
+ Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
35
+ dilation (`bool`, *optional*, defaults to `False`):
36
+ Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
37
+ `use_timm_backbone` = `True`.
38
+
39
+ Examples:
40
+
41
+ ```python
42
+ >>> from transformers import ConditionalDetrConfig, ConditionalDetrModel
43
+
44
+ >>> # Initializing a Conditional DETR microsoft/conditional-detr-resnet-50 style configuration
45
+ >>> configuration = ConditionalDetrConfig()
46
+
47
+ >>> # Initializing a model (with random weights) from the microsoft/conditional-detr-resnet-50 style configuration
48
+ >>> model = ConditionalDetrModel(configuration)
49
+
50
+ >>> # Accessing the model configuration
51
+ >>> configuration = model.config
52
+ ```"""
53
+
54
+ model_type = "conditional_detr"
55
+ sub_configs = {"backbone_config": AutoConfig}
56
+ keys_to_ignore_at_inference = ["past_key_values"]
57
+ attribute_map = {
58
+ "hidden_size": "d_model",
59
+ "num_attention_heads": "encoder_attention_heads",
60
+ "num_hidden_layers": "encoder_layers",
61
+ }
62
+
63
+ backbone_config: dict | PreTrainedConfig | None = None
64
+ num_channels: int = 3
65
+ num_queries: int = 300
66
+ encoder_layers: int = 6
67
+ encoder_ffn_dim: int = 2048
68
+ encoder_attention_heads: int = 8
69
+ decoder_layers: int = 6
70
+ decoder_ffn_dim: int = 2048
71
+ decoder_attention_heads: int = 8
72
+ encoder_layerdrop: float | int = 0.0
73
+ decoder_layerdrop: float | int = 0.0
74
+ is_encoder_decoder: bool = True
75
+ activation_function: str = "relu"
76
+ d_model: int = 256
77
+ dropout: float | int = 0.1
78
+ attention_dropout: float | int = 0.0
79
+ activation_dropout: float | int = 0.0
80
+ init_std: float = 0.02
81
+ init_xavier_std: float = 1.0
82
+ auxiliary_loss: bool = False
83
+ position_embedding_type: str = "sine"
84
+ dilation: bool = False
85
+ class_cost: int = 2
86
+ bbox_cost: int = 5
87
+ giou_cost: int = 2
88
+ mask_loss_coefficient: int = 1
89
+ dice_loss_coefficient: int = 1
90
+ cls_loss_coefficient: int = 2
91
+ bbox_loss_coefficient: int = 5
92
+ giou_loss_coefficient: int = 2
93
+ focal_alpha: float = 0.25
94
+
95
+ def __post_init__(self, **kwargs):
96
+ # Init timm backbone with hardcoded values for BC
97
+ backbone_kwargs = kwargs.get("backbone_kwargs", {})
98
+ timm_default_kwargs = {
99
+ "num_channels": backbone_kwargs.get("num_channels", self.num_channels),
100
+ "features_only": True,
101
+ "use_pretrained_backbone": False,
102
+ "out_indices": backbone_kwargs.get("out_indices", [1, 2, 3, 4]),
103
+ }
104
+ if self.dilation:
105
+ timm_default_kwargs["output_stride"] = backbone_kwargs.get("output_stride", 16)
106
+
107
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
108
+ backbone_config=self.backbone_config,
109
+ default_backbone="resnet50",
110
+ default_config_type="resnet",
111
+ default_config_kwargs={"out_features": ["stage4"]},
112
+ timm_default_kwargs=timm_default_kwargs,
113
+ **kwargs,
114
+ )
115
+
116
+ super().__post_init__(**kwargs)
117
+
118
+
119
+ __all__ = ["ConditionalDetrConfig"]