JinghuiLuAstronaut commited on
Commit
e7fd14f
·
verified ·
1 Parent(s): 954a8bc

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/__init__.py +28 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/configuration_dac.py +78 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/feature_extraction_dac.py +170 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/modeling_dac.py +689 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paddleocr_vl/__init__.py +31 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py +1695 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/configuration_perceiver.py +114 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/image_processing_perceiver.py +124 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/image_processing_pil_perceiver.py +107 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/modeling_perceiver.py +0 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/tokenization_perceiver.py +197 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/__init__.py +27 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/configuration_swin.py +90 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/modeling_swin.py +1163 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/modular_swin.py +1122 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/__init__.py +30 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/configuration_wav2vec2.py +245 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/feature_extraction_wav2vec2.py +239 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/modeling_wav2vec2.py +2153 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/processing_wav2vec2.py +105 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/__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_dac import *
22
+ from .feature_extraction_dac import *
23
+ from .modeling_dac 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/configuration_dac.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript 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
+ """Dac model configuration"""
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring
23
+
24
+
25
+ @auto_docstring(checkpoint="descript/dac_16khz")
26
+ @strict
27
+ class DacConfig(PreTrainedConfig):
28
+ r"""
29
+ downsampling_ratios (`list[int]`, *optional*, defaults to `[2, 4, 8, 8]`):
30
+ Ratios for downsampling in the encoder. These are used in reverse order for upsampling in the decoder.
31
+ quantizer_dropout (`bool`, *optional*, defaults to 0):
32
+ Whether to apply dropout to the quantizer.
33
+ commitment_loss_weight (float, *optional*, defaults to 0.25):
34
+ Weight of the commitment loss term in the VQVAE loss function.
35
+ codebook_loss_weight (float, *optional*, defaults to 1.0):
36
+ Weight of the codebook loss term in the VQVAE loss function.
37
+
38
+ Example:
39
+
40
+ ```python
41
+ >>> from transformers import DacModel, DacConfig
42
+
43
+ >>> # Initializing a "descript/dac_16khz" style configuration
44
+ >>> configuration = DacConfig()
45
+
46
+ >>> # Initializing a model (with random weights) from the "descript/dac_16khz" style configuration
47
+ >>> model = DacModel(configuration)
48
+
49
+ >>> # Accessing the model configuration
50
+ >>> configuration = model.config
51
+ ```"""
52
+
53
+ model_type = "dac"
54
+
55
+ encoder_hidden_size: int = 64
56
+ downsampling_ratios: list[int] | tuple[int, ...] = (2, 4, 8, 8)
57
+ decoder_hidden_size: int = 1536
58
+ n_codebooks: int = 9
59
+ codebook_size: int = 1024
60
+ codebook_dim: int = 8
61
+ quantizer_dropout: float | int = 0.0
62
+ commitment_loss_weight: float = 0.25
63
+ codebook_loss_weight: float = 1.0
64
+ sampling_rate: int = 16000
65
+
66
+ def __post_init__(self, **kwargs):
67
+ self.upsampling_ratios = self.downsampling_ratios[::-1]
68
+ self.hidden_size = self.encoder_hidden_size * (2 ** len(self.downsampling_ratios))
69
+ self.hop_length = int(np.prod(self.downsampling_ratios))
70
+ super().__post_init__(**kwargs)
71
+
72
+ @property
73
+ def frame_rate(self) -> int:
74
+ hop_length = np.prod(self.upsampling_ratios)
75
+ return math.ceil(self.sampling_rate / hop_length)
76
+
77
+
78
+ __all__ = ["DacConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/feature_extraction_dac.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript 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
+ """Feature extractor class for DAC"""
15
+
16
+ import numpy as np
17
+
18
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
19
+ from ...feature_extraction_utils import BatchFeature
20
+ from ...utils import PaddingStrategy, TensorType, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class DacFeatureExtractor(SequenceFeatureExtractor):
27
+ r"""
28
+ Constructs an Dac feature extractor.
29
+
30
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
31
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
32
+
33
+ Args:
34
+ feature_size (`int`, *optional*, defaults to 1):
35
+ The feature dimension of the extracted features. Use 1 for mono, 2 for stereo.
36
+ sampling_rate (`int`, *optional*, defaults to 16000):
37
+ The sampling rate at which the audio waveform should be digitalized, expressed in hertz (Hz).
38
+ padding_value (`float`, *optional*, defaults to 0.0):
39
+ The value that is used for padding.
40
+ hop_length (`int`, *optional*, defaults to 512):
41
+ Overlap length between successive windows.
42
+ """
43
+
44
+ model_input_names = ["input_values", "n_quantizers"]
45
+
46
+ def __init__(
47
+ self,
48
+ feature_size: int = 1,
49
+ sampling_rate: int = 16000,
50
+ padding_value: float = 0.0,
51
+ hop_length: int = 512,
52
+ **kwargs,
53
+ ):
54
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
55
+ self.hop_length = hop_length
56
+
57
+ def __call__(
58
+ self,
59
+ raw_audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
60
+ padding: bool | str | PaddingStrategy | None = None,
61
+ truncation: bool | None = False,
62
+ max_length: int | None = None,
63
+ return_tensors: str | TensorType | None = None,
64
+ sampling_rate: int | None = None,
65
+ ) -> BatchFeature:
66
+ """
67
+ Main method to featurize and prepare for the model one or several sequence(s).
68
+
69
+ Args:
70
+ raw_audio (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
71
+ The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
72
+ values, a list of numpy arrays or a list of list of float values. The numpy array must be of shape
73
+ `(num_samples,)` for mono audio (`feature_size = 1`), or `(2, num_samples)` for stereo audio
74
+ (`feature_size = 2`).
75
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
76
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
77
+ index) among:
78
+
79
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
80
+ sequence if provided).
81
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
82
+ acceptable input length for the model if that argument is not provided.
83
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
84
+ lengths).
85
+ truncation (`bool`, *optional*, defaults to `False`):
86
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
87
+ max_length (`int`, *optional*):
88
+ Maximum length of the returned list and optionally padding length (see above).
89
+ return_tensors (`str` or [`~utils.TensorType`], *optional*, default to 'pt'):
90
+ If set, will return tensors instead of list of python integers. Acceptable values are:
91
+
92
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
93
+ - `'np'`: Return Numpy `np.ndarray` objects.
94
+ sampling_rate (`int`, *optional*):
95
+ The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
96
+ `sampling_rate` at the forward call to prevent silent errors.
97
+ """
98
+ if sampling_rate is not None:
99
+ if sampling_rate != self.sampling_rate:
100
+ raise ValueError(
101
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
102
+ f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
103
+ f" {self.sampling_rate} and not {sampling_rate}."
104
+ )
105
+ else:
106
+ logger.warning(
107
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
108
+ "Failing to do so can result in silent errors that might be hard to debug."
109
+ )
110
+
111
+ if padding and truncation:
112
+ raise ValueError("Both padding and truncation were set. Make sure you only set one.")
113
+ elif padding is None:
114
+ # by default let's pad the inputs
115
+ padding = True
116
+
117
+ is_batched = bool(
118
+ isinstance(raw_audio, (list, tuple)) and (isinstance(raw_audio[0], (np.ndarray, tuple, list)))
119
+ )
120
+
121
+ if is_batched:
122
+ raw_audio = [np.asarray(audio, dtype=np.float32).T for audio in raw_audio]
123
+ elif not is_batched and not isinstance(raw_audio, np.ndarray):
124
+ raw_audio = np.asarray(raw_audio, dtype=np.float32)
125
+ elif isinstance(raw_audio, np.ndarray) and raw_audio.dtype is np.dtype(np.float64):
126
+ raw_audio = raw_audio.astype(np.float32)
127
+
128
+ # always return batch
129
+ if not is_batched:
130
+ raw_audio = [np.asarray(raw_audio).T]
131
+
132
+ # verify inputs are valid
133
+ for idx, example in enumerate(raw_audio):
134
+ if example.ndim > 2:
135
+ raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}")
136
+ if self.feature_size == 1 and example.ndim != 1:
137
+ raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels")
138
+ if self.feature_size == 2:
139
+ raise ValueError("Stereo audio isn't supported for now")
140
+
141
+ input_values = BatchFeature({"input_values": raw_audio})
142
+
143
+ # normal padding on batch
144
+ padded_inputs = self.pad(
145
+ input_values,
146
+ max_length=max_length,
147
+ truncation=truncation,
148
+ padding=padding,
149
+ return_attention_mask=padding,
150
+ pad_to_multiple_of=self.hop_length,
151
+ )
152
+ if padding:
153
+ padded_inputs["padding_mask"] = padded_inputs.pop("attention_mask")
154
+ if padding:
155
+ padded_inputs.input_values = padded_inputs.input_values[:, np.newaxis, :]
156
+
157
+ input_values = []
158
+ for example in padded_inputs.pop("input_values"):
159
+ if self.feature_size == 1:
160
+ example = example[..., None]
161
+ input_values.append(example.T)
162
+
163
+ padded_inputs["input_values"] = input_values
164
+ if return_tensors is not None:
165
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
166
+
167
+ return padded_inputs
168
+
169
+
170
+ __all__ = ["DacFeatureExtractor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/dac/modeling_dac.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript 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
+ """Transformers DAC model."""
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from ... import initialization as init
25
+ from ...modeling_utils import PreTrainedAudioTokenizerBase
26
+ from ...utils import ModelOutput, auto_docstring
27
+ from .configuration_dac import DacConfig
28
+
29
+
30
+ @auto_docstring
31
+ @dataclass
32
+ class DacOutput(ModelOutput):
33
+ r"""
34
+ loss (`torch.Tensor`):
35
+ Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
36
+ audio_values (`torch.Tensor` of shape `(batch_size, input_length)`):
37
+ Reconstructed audio data.
38
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
39
+ Quantized continuous representation of input.
40
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_codebooks, time_steps)`):
41
+ Codebook indices for each codebook (quantized discrete representation of input).
42
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
43
+ Projected latents (continuous representation of input before quantization).
44
+ """
45
+
46
+ loss: torch.FloatTensor | None = None
47
+ audio_values: torch.FloatTensor | None = None
48
+ quantized_representation: torch.FloatTensor | None = None
49
+ audio_codes: torch.LongTensor | None = None
50
+ projected_latents: torch.FloatTensor | None = None
51
+
52
+
53
+ @auto_docstring
54
+ @dataclass
55
+ class DacEncoderOutput(ModelOutput):
56
+ r"""
57
+ loss (`torch.Tensor`):
58
+ Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
59
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`, *optional*):
60
+ Quantized continuous representation of input.
61
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
62
+ Codebook indices for each codebook (quantized discrete representation of input).
63
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`, *optional*):
64
+ Projected latents (continuous representation of input before quantization).
65
+ """
66
+
67
+ loss: torch.FloatTensor | None = None
68
+ quantized_representation: torch.FloatTensor | None = None
69
+ audio_codes: torch.FloatTensor | None = None
70
+ projected_latents: torch.FloatTensor | None = None
71
+
72
+
73
+ @auto_docstring
74
+ @dataclass
75
+ # Copied from transformers.models.encodec.modeling_encodec.EncodecDecoderOutput with Encodec->Dac, segment_length->input_length
76
+ class DacDecoderOutput(ModelOutput):
77
+ r"""
78
+ audio_values (`torch.FloatTensor` of shape `(batch_size, input_length)`, *optional*):
79
+ Decoded audio values, obtained using the decoder part of Dac.
80
+ """
81
+
82
+ audio_values: torch.FloatTensor | None = None
83
+
84
+
85
+ class Snake1d(nn.Module):
86
+ """
87
+ A 1-dimensional Snake activation function module.
88
+ """
89
+
90
+ def __init__(self, hidden_dim):
91
+ super().__init__()
92
+ self.alpha = nn.Parameter(torch.ones(1, hidden_dim, 1))
93
+
94
+ def forward(self, hidden_states):
95
+ shape = hidden_states.shape
96
+ hidden_states = hidden_states.reshape(shape[0], shape[1], -1)
97
+ hidden_states = hidden_states + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * hidden_states).pow(2)
98
+ hidden_states = hidden_states.reshape(shape)
99
+ return hidden_states
100
+
101
+
102
+ class DacVectorQuantize(nn.Module):
103
+ """
104
+ Implementation of VQ similar to Karpathy's repo (https://github.com/karpathy/deep-vector-quantization)
105
+
106
+ Additionally uses following tricks from improved VQGAN
107
+ (https://huggingface.co/papers/2110.04627):
108
+ 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
109
+ for improved codebook usage
110
+ 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
111
+ improves training stability
112
+ """
113
+
114
+ def __init__(self, config: DacConfig):
115
+ super().__init__()
116
+
117
+ self.codebook_dim = config.codebook_dim
118
+ self.in_proj = nn.Conv1d(config.hidden_size, config.codebook_dim, kernel_size=1)
119
+ self.out_proj = nn.Conv1d(config.codebook_dim, config.hidden_size, kernel_size=1)
120
+ self.codebook = nn.Embedding(config.codebook_size, config.codebook_dim)
121
+
122
+ def forward(self, hidden_state):
123
+ """
124
+ Quantizes the input tensor using a fixed codebook and returns the corresponding codebook vectors.
125
+
126
+ Args:
127
+ hidden_state (`torch.FloatTensor` of shape `(batch_size, dimension, time_steps)`):
128
+ Input tensor.
129
+
130
+ Returns:
131
+ quantized_representation (`torch.Tensor`of shape `(batch_size, dimension, time_steps)`):
132
+ Quantized continuous representation of input.
133
+ commitment_loss (`torch.FloatTensor`of shape `(1)`):
134
+ Commitment loss to train encoder to predict vectors closer to codebook entries.
135
+ codebook_loss (`torch.FloatTensor`of shape `(1)`):
136
+ Codebook loss to update the codebook.
137
+ audio_codes (`torch.LongTensor` of shape `(batch_size, time_steps)`):
138
+ Codebook indices for each codebook, quantized discrete representation of input.
139
+ projected_latents (torch.FloatTensor of shape `(batch_size, num_codebooks * dimension, time_steps)`):
140
+ Projected latents (continuous representation of input before quantization).
141
+ """
142
+
143
+ projected_latents = self.in_proj(hidden_state)
144
+ quantized_representation, audio_codes = self.decode_latents(projected_latents)
145
+
146
+ commitment_loss = F.mse_loss(projected_latents, quantized_representation.detach(), reduction="mean")
147
+ codebook_loss = F.mse_loss(quantized_representation, projected_latents.detach(), reduction="mean")
148
+ # noop in forward pass, straight-through gradient estimator in backward pass
149
+ quantized_representation = projected_latents + (quantized_representation - projected_latents).detach()
150
+ quantized_representation = self.out_proj(quantized_representation)
151
+
152
+ return quantized_representation, commitment_loss, codebook_loss, audio_codes, projected_latents
153
+
154
+ def decode_latents(self, hidden_states):
155
+ batch_size, hidden_dim, sequence_length = hidden_states.shape
156
+ encodings = hidden_states.permute(0, 2, 1).reshape(batch_size * sequence_length, hidden_dim)
157
+ codebook = self.codebook.weight # codebook: (N x D)
158
+
159
+ # L2 normalize encodings and codebook (ViT-VQGAN)
160
+ encodings = F.normalize(encodings)
161
+ codebook = F.normalize(codebook)
162
+
163
+ # Compute euclidean distance with codebook
164
+ l2_norm = encodings.pow(2).sum(1, keepdim=True)
165
+ dist = -(l2_norm - 2 * encodings @ codebook.t()) + codebook.pow(2).sum(1, keepdim=True).t()
166
+
167
+ indices = dist.max(1)[1]
168
+ indices = indices.reshape(hidden_states.size(0), -1)
169
+ quantized_representation = self.codebook(indices).transpose(1, 2)
170
+ return quantized_representation, indices
171
+
172
+
173
+ class DacResidualUnit(nn.Module):
174
+ """
175
+ A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations.
176
+ """
177
+
178
+ def __init__(self, dimension: int = 16, dilation: int = 1):
179
+ super().__init__()
180
+ pad = ((7 - 1) * dilation) // 2
181
+
182
+ self.snake1 = Snake1d(dimension)
183
+ self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad)
184
+ self.snake2 = Snake1d(dimension)
185
+ self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1)
186
+
187
+ def forward(self, hidden_state):
188
+ """
189
+ Forward pass through the residual unit.
190
+
191
+ Args:
192
+ hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
193
+ Input tensor .
194
+
195
+ Returns:
196
+ output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
197
+ Input tensor after passing through the residual unit.
198
+ """
199
+ output_tensor = hidden_state
200
+ output_tensor = self.conv1(self.snake1(output_tensor))
201
+ output_tensor = self.conv2(self.snake2(output_tensor))
202
+
203
+ padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2
204
+ if padding > 0:
205
+ hidden_state = hidden_state[..., padding:-padding]
206
+ output_tensor = hidden_state + output_tensor
207
+ return output_tensor
208
+
209
+
210
+ class DacEncoderBlock(nn.Module):
211
+ """Encoder block used in DAC encoder."""
212
+
213
+ def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
214
+ super().__init__()
215
+
216
+ dimension = config.encoder_hidden_size * 2**stride_index
217
+ self.res_unit1 = DacResidualUnit(dimension // 2, dilation=1)
218
+ self.res_unit2 = DacResidualUnit(dimension // 2, dilation=3)
219
+ self.res_unit3 = DacResidualUnit(dimension // 2, dilation=9)
220
+ self.snake1 = Snake1d(dimension // 2)
221
+ self.conv1 = nn.Conv1d(
222
+ dimension // 2, dimension, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2)
223
+ )
224
+
225
+ def forward(self, hidden_state):
226
+ hidden_state = self.res_unit1(hidden_state)
227
+ hidden_state = self.res_unit2(hidden_state)
228
+ hidden_state = self.snake1(self.res_unit3(hidden_state))
229
+ hidden_state = self.conv1(hidden_state)
230
+
231
+ return hidden_state
232
+
233
+
234
+ class DacDecoderBlock(nn.Module):
235
+ """Decoder block used in DAC decoder."""
236
+
237
+ def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
238
+ super().__init__()
239
+
240
+ input_dim = config.decoder_hidden_size // 2**stride_index
241
+ output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
242
+ self.snake1 = Snake1d(input_dim)
243
+ self.conv_t1 = nn.ConvTranspose1d(
244
+ input_dim,
245
+ output_dim,
246
+ kernel_size=2 * stride,
247
+ stride=stride,
248
+ padding=math.ceil(stride / 2),
249
+ )
250
+
251
+ self.res_unit1 = DacResidualUnit(output_dim, dilation=1)
252
+ self.res_unit2 = DacResidualUnit(output_dim, dilation=3)
253
+ self.res_unit3 = DacResidualUnit(output_dim, dilation=9)
254
+
255
+ def forward(self, hidden_state):
256
+ hidden_state = self.snake1(hidden_state)
257
+ hidden_state = self.conv_t1(hidden_state)
258
+ hidden_state = self.res_unit1(hidden_state)
259
+ hidden_state = self.res_unit2(hidden_state)
260
+ hidden_state = self.res_unit3(hidden_state)
261
+
262
+ return hidden_state
263
+
264
+
265
+ class DacResidualVectorQuantizer(nn.Module):
266
+ """
267
+ ResidualVectorQuantize block - Introduced in SoundStream: An end2end neural audio codec (https://huggingface.co/papers/2107.03312)
268
+ """
269
+
270
+ def __init__(self, config: DacConfig):
271
+ super().__init__()
272
+
273
+ n_codebooks = config.n_codebooks
274
+ quantizer_dropout = config.quantizer_dropout
275
+
276
+ self.n_codebooks = n_codebooks
277
+
278
+ self.quantizers = nn.ModuleList([DacVectorQuantize(config) for i in range(config.n_codebooks)])
279
+ self.quantizer_dropout = quantizer_dropout
280
+
281
+ def forward(self, hidden_state, n_quantizers: int | None = None):
282
+ """
283
+ Quantizes the input tensor using a fixed set of codebooks and returns corresponding codebook vectors.
284
+ Args:
285
+ hidden_state (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
286
+ Input tensor to be quantized.
287
+ n_quantizers (`int`, *optional*):
288
+ Number of quantizers to use. If specified and `self.quantizer_dropout` is True,
289
+ this argument is ignored during training, and a random number of quantizers is used.
290
+
291
+ Returns:
292
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
293
+ Quantized continuous representation of input.
294
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
295
+ Codebook indices for each codebook (quantized discrete representation of input).
296
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
297
+ Projected latents (continuous representation of input before quantization).
298
+ commitment_loss (`torch.Tensor` of shape `(1)`):
299
+ Commitment loss to train the encoder to predict vectors closer to codebook entries.
300
+ codebook_loss (`torch.Tensor` of shape `(1)`):
301
+ Codebook loss to update the codebook.
302
+ """
303
+
304
+ quantized_representation = 0
305
+ residual = hidden_state
306
+ commitment_loss = 0
307
+ codebook_loss = 0
308
+
309
+ audio_codes = []
310
+ projected_latents = []
311
+
312
+ n_quantizers = n_quantizers if n_quantizers is not None else self.n_codebooks
313
+ if self.training:
314
+ n_quantizers = torch.ones((hidden_state.shape[0],)) * self.n_codebooks + 1
315
+ dropout = torch.randint(1, self.n_codebooks + 1, (hidden_state.shape[0],))
316
+ n_dropout = int(hidden_state.shape[0] * self.quantizer_dropout)
317
+ n_quantizers[:n_dropout] = dropout[:n_dropout]
318
+ n_quantizers = n_quantizers.to(hidden_state.device)
319
+
320
+ for i, quantizer in enumerate(self.quantizers):
321
+ if self.training is False and i >= n_quantizers:
322
+ break
323
+
324
+ quantized_representation_i, commitment_loss_i, codebook_loss_i, indices_i, projected_latents_i = quantizer(
325
+ residual
326
+ )
327
+
328
+ # Create mask to apply quantizer dropout
329
+ mask = torch.full((hidden_state.shape[0],), i, device=hidden_state.device, dtype=torch.long) < n_quantizers
330
+ quantized_representation = quantized_representation + quantized_representation_i * mask[:, None, None]
331
+ residual = residual - quantized_representation_i
332
+
333
+ # Sum losses
334
+ commitment_loss += commitment_loss_i * mask
335
+ codebook_loss += codebook_loss_i * mask
336
+
337
+ audio_codes.append(indices_i)
338
+ projected_latents.append(projected_latents_i)
339
+
340
+ audio_codes = torch.stack(audio_codes, dim=1)
341
+ projected_latents = torch.cat(projected_latents, dim=1)
342
+
343
+ return quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss
344
+
345
+ def from_codes(self, audio_codes: torch.Tensor):
346
+ """
347
+ Reconstructs the continuous representation from quantized codes.
348
+
349
+ Args:
350
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
351
+ Quantized discrete representation of input.
352
+
353
+ Returns:
354
+ quantized_representation (`torch.Tensor`):
355
+ Quantized continuous representation of input.
356
+ projected_latents (`torch.Tensor`):
357
+ List of projected latents (continuous representations of input before quantization)
358
+ for each codebook.
359
+ audio_codes (`torch.Tensor`):
360
+ Codebook indices for each codebook.
361
+ """
362
+ quantized_representation = 0.0
363
+ projected_latents = []
364
+ n_codebooks = audio_codes.shape[1]
365
+ for i in range(n_codebooks):
366
+ projected_latents_i = self.quantizers[i].codebook(audio_codes[:, i, :]).transpose(1, 2)
367
+ projected_latents.append(projected_latents_i)
368
+ quantized_representation += self.quantizers[i].out_proj(projected_latents_i)
369
+ return quantized_representation, torch.cat(projected_latents, dim=1), audio_codes
370
+
371
+ def from_latents(self, latents: torch.Tensor):
372
+ """Reconstructs the quantized representation from unquantized latents.
373
+
374
+ Args:
375
+ latents (`torch.Tensor` of shape `(batch_size, total_latent_dimension, time_steps)`):
376
+ Continuous representation of input after projection.
377
+
378
+ Returns:
379
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
380
+ Quantized representation of the full-projected space.
381
+ quantized_latents (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
382
+ Quantized representation of the latent space (continuous representation before quantization).
383
+ """
384
+ quantized_representation = 0
385
+ quantized_latents = []
386
+ codes = []
387
+ codebook_dims_tensor = torch.tensor([0] + [q.codebook_dim for q in self.quantizers])
388
+ dims = torch.cumsum(codebook_dims_tensor, dim=0)
389
+
390
+ n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[0]
391
+ for i in range(n_codebooks):
392
+ hidden_dim_j, hidden_dim_k = dims[i], dims[i + 1]
393
+ latent_chunk = latents[:, hidden_dim_j:hidden_dim_k, :]
394
+ quantized_latents_i, codes_i = self.quantizers[i].decode_latents(latent_chunk)
395
+ quantized_latents.append(quantized_latents_i)
396
+ codes.append(codes_i)
397
+
398
+ quantized_with_ste = latent_chunk + (quantized_latents_i - latent_chunk)
399
+ quantized_representation_i = self.quantizers[i].out_proj(quantized_with_ste)
400
+ quantized_representation = quantized_representation + quantized_representation_i
401
+
402
+ return quantized_representation, torch.cat(quantized_latents, dim=1)
403
+
404
+
405
+ class DacDecoder(nn.Module):
406
+ """DAC Decoder"""
407
+
408
+ def __init__(self, config: DacConfig):
409
+ super().__init__()
410
+
411
+ input_channel = config.hidden_size
412
+ channels = config.decoder_hidden_size
413
+ strides = config.upsampling_ratios
414
+
415
+ # Add first conv layer
416
+ self.conv1 = nn.Conv1d(input_channel, channels, kernel_size=7, padding=3)
417
+
418
+ # Add upsampling + MRF blocks
419
+ block = []
420
+ for stride_index, stride in enumerate(strides):
421
+ block += [DacDecoderBlock(config, stride, stride_index)]
422
+
423
+ self.block = nn.ModuleList(block)
424
+ output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
425
+ self.snake1 = Snake1d(output_dim)
426
+ self.conv2 = nn.Conv1d(output_dim, 1, kernel_size=7, padding=3)
427
+ self.tanh = nn.Tanh()
428
+
429
+ def forward(self, hidden_state):
430
+ hidden_state = self.conv1(hidden_state)
431
+
432
+ for layer in self.block:
433
+ hidden_state = layer(hidden_state)
434
+
435
+ hidden_state = self.snake1(hidden_state)
436
+ hidden_state = self.conv2(hidden_state)
437
+ hidden_state = self.tanh(hidden_state)
438
+
439
+ return hidden_state
440
+
441
+
442
+ class DacEncoder(nn.Module):
443
+ """DAC Encoder"""
444
+
445
+ def __init__(self, config: DacConfig):
446
+ super().__init__()
447
+
448
+ strides = config.downsampling_ratios
449
+ # Create first convolution
450
+ self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3)
451
+
452
+ self.block = []
453
+ # Create EncoderBlocks that double channels as they downsample by `stride`
454
+ for stride_index, stride in enumerate(strides):
455
+ stride_index = stride_index + 1
456
+ self.block += [DacEncoderBlock(config, stride=stride, stride_index=stride_index)]
457
+
458
+ self.block = nn.ModuleList(self.block)
459
+ d_model = config.encoder_hidden_size * 2**stride_index
460
+ self.snake1 = Snake1d(d_model)
461
+ self.conv2 = nn.Conv1d(d_model, config.hidden_size, kernel_size=3, padding=1)
462
+
463
+ def forward(self, hidden_state):
464
+ hidden_state = self.conv1(hidden_state)
465
+
466
+ for module in self.block:
467
+ hidden_state = module(hidden_state)
468
+
469
+ hidden_state = self.snake1(hidden_state)
470
+ hidden_state = self.conv2(hidden_state)
471
+
472
+ return hidden_state
473
+
474
+
475
+ @auto_docstring
476
+ class DacPreTrainedModel(PreTrainedAudioTokenizerBase):
477
+ config: DacConfig
478
+ base_model_prefix = "dac"
479
+ main_input_name = "input_values"
480
+
481
+ @torch.no_grad()
482
+ def _init_weights(self, module):
483
+ if isinstance(module, nn.Conv1d):
484
+ init.trunc_normal_(module.weight, std=0.02)
485
+ init.constant_(module.bias, 0)
486
+ elif isinstance(module, Snake1d):
487
+ init.ones_(module.alpha)
488
+ elif isinstance(module, nn.ConvTranspose1d):
489
+ module.reset_parameters()
490
+ elif isinstance(module, nn.Embedding):
491
+ init.normal_(module.weight, mean=0.0, std=0.02)
492
+
493
+ def apply_weight_norm(self):
494
+ weight_norm = nn.utils.weight_norm
495
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
496
+ weight_norm = nn.utils.parametrizations.weight_norm
497
+
498
+ for layer in self.quantizer.quantizers:
499
+ weight_norm(layer.in_proj)
500
+ weight_norm(layer.out_proj)
501
+
502
+ weight_norm(self.encoder.conv1)
503
+ weight_norm(self.encoder.conv2)
504
+
505
+ for layer in self.encoder.block:
506
+ weight_norm(layer.conv1)
507
+ weight_norm(layer.res_unit1.conv1)
508
+ weight_norm(layer.res_unit1.conv2)
509
+ weight_norm(layer.res_unit2.conv1)
510
+ weight_norm(layer.res_unit2.conv2)
511
+ weight_norm(layer.res_unit3.conv1)
512
+ weight_norm(layer.res_unit3.conv2)
513
+
514
+ weight_norm(self.decoder.conv1)
515
+ weight_norm(self.decoder.conv2)
516
+
517
+ for layer in self.decoder.block:
518
+ weight_norm(layer.conv_t1)
519
+ weight_norm(layer.res_unit1.conv1)
520
+ weight_norm(layer.res_unit1.conv2)
521
+ weight_norm(layer.res_unit2.conv1)
522
+ weight_norm(layer.res_unit2.conv2)
523
+ weight_norm(layer.res_unit3.conv1)
524
+ weight_norm(layer.res_unit3.conv2)
525
+
526
+ def remove_weight_norm(self):
527
+ for layer in self.quantizer.quantizers:
528
+ nn.utils.remove_weight_norm(layer.in_proj)
529
+ nn.utils.remove_weight_norm(layer.out_proj)
530
+
531
+ nn.utils.remove_weight_norm(self.encoder.conv1)
532
+ nn.utils.remove_weight_norm(self.encoder.conv2)
533
+
534
+ for layer in self.encoder.block:
535
+ nn.utils.remove_weight_norm(layer.conv1)
536
+ nn.utils.remove_weight_norm(layer.res_unit1.conv1)
537
+ nn.utils.remove_weight_norm(layer.res_unit1.conv2)
538
+ nn.utils.remove_weight_norm(layer.res_unit2.conv1)
539
+ nn.utils.remove_weight_norm(layer.res_unit2.conv2)
540
+ nn.utils.remove_weight_norm(layer.res_unit3.conv1)
541
+ nn.utils.remove_weight_norm(layer.res_unit3.conv2)
542
+
543
+ nn.utils.remove_weight_norm(self.decoder.conv1)
544
+ nn.utils.remove_weight_norm(self.decoder.conv2)
545
+
546
+ for layer in self.decoder.block:
547
+ nn.utils.remove_weight_norm(layer.conv_t1)
548
+ nn.utils.remove_weight_norm(layer.res_unit1.conv1)
549
+ nn.utils.remove_weight_norm(layer.res_unit1.conv2)
550
+ nn.utils.remove_weight_norm(layer.res_unit2.conv1)
551
+ nn.utils.remove_weight_norm(layer.res_unit2.conv2)
552
+ nn.utils.remove_weight_norm(layer.res_unit3.conv1)
553
+ nn.utils.remove_weight_norm(layer.res_unit3.conv2)
554
+
555
+
556
+ @auto_docstring(
557
+ custom_intro="""
558
+ The DAC (Descript Audio Codec) model.
559
+ """
560
+ )
561
+ class DacModel(DacPreTrainedModel):
562
+ input_modalities = "audio"
563
+
564
+ def __init__(self, config: DacConfig):
565
+ super().__init__(config)
566
+ self.config = config
567
+
568
+ self.encoder = DacEncoder(config)
569
+ self.decoder = DacDecoder(config)
570
+
571
+ self.quantizer = DacResidualVectorQuantizer(config)
572
+
573
+ self.bits_per_codebook = int(math.log2(self.config.codebook_size))
574
+ if 2**self.bits_per_codebook != self.config.codebook_size:
575
+ raise ValueError("The codebook_size must be a power of 2.")
576
+
577
+ # Initialize weights and apply final processing
578
+ self.post_init()
579
+
580
+ @auto_docstring
581
+ def encode(
582
+ self,
583
+ input_values: torch.Tensor,
584
+ n_quantizers: int | None = None,
585
+ return_dict: bool | None = None,
586
+ ) -> tuple | DacEncoderOutput:
587
+ r"""
588
+ input_values (`torch.Tensor of shape `(batch_size, 1, time_steps)`):
589
+ Input audio data to encode,
590
+ n_quantizers (int, *optional*):
591
+ Number of quantizers to use. If None, all quantizers are used. Default is None.
592
+ """
593
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
594
+
595
+ quantized_representation = self.encoder(input_values)
596
+ quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss = self.quantizer(
597
+ quantized_representation, n_quantizers
598
+ )
599
+
600
+ loss = self.config.commitment_loss_weight * commitment_loss + self.config.codebook_loss_weight * codebook_loss
601
+
602
+ if not return_dict:
603
+ return (loss, quantized_representation, audio_codes, projected_latents)
604
+
605
+ return DacEncoderOutput(loss, quantized_representation, audio_codes, projected_latents)
606
+
607
+ @auto_docstring
608
+ def decode(
609
+ self,
610
+ quantized_representation: torch.Tensor | None = None,
611
+ audio_codes: torch.Tensor | None = None,
612
+ return_dict: bool | None = None,
613
+ ) -> tuple | DacDecoderOutput:
614
+ r"""
615
+ quantized_representation (torch.Tensor of shape `(batch_size, dimension, time_steps)`, *optional*):
616
+ Quantized continuous representation of input.
617
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
618
+ The codebook indices for each codebook, representing the quantized discrete
619
+ representation of the input. This parameter should be provided if you want
620
+ to decode directly from the audio codes (it will overwrite quantized_representation).
621
+ return_dict (`bool`, *optional*, defaults to `True`):
622
+ Whether to return a [`DacDecoderOutput`] instead of a plain tuple.
623
+ """
624
+
625
+ if quantized_representation is None and audio_codes is None:
626
+ raise ValueError("Either `quantized_representation` or `audio_codes` must be provided.")
627
+
628
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
629
+
630
+ if audio_codes is not None:
631
+ quantized_representation = self.quantizer.from_codes(audio_codes)[0]
632
+
633
+ audio_values = self.decoder(quantized_representation).squeeze(1)
634
+
635
+ if not return_dict:
636
+ return (audio_values,)
637
+
638
+ return DacDecoderOutput(audio_values)
639
+
640
+ @auto_docstring
641
+ def forward(
642
+ self,
643
+ input_values: torch.Tensor,
644
+ n_quantizers: int | None = None,
645
+ return_dict: bool | None = None,
646
+ ) -> tuple | DacOutput:
647
+ r"""
648
+ input_values (`torch.Tensor` of shape `(batch_size, 1, time_steps)`):
649
+ Audio data to encode.
650
+ n_quantizers (`int`, *optional*):
651
+ Number of quantizers to use. If `None`, all quantizers are used. Default is `None`.
652
+
653
+ Examples:
654
+
655
+ ```python
656
+ >>> from datasets import load_dataset, Audio
657
+ >>> from transformers import DacModel, AutoProcessor
658
+ >>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
659
+
660
+ >>> model = DacModel.from_pretrained("descript/dac_16khz")
661
+ >>> processor = AutoProcessor.from_pretrained("descript/dac_16khz")
662
+ >>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=processor.sampling_rate))
663
+ >>> audio_sample = librispeech_dummy[-1]["audio"]["array"]
664
+ >>> inputs = processor(raw_audio=audio_sample, sampling_rate=processor.sampling_rate, return_tensors="pt")
665
+
666
+ >>> encoder_outputs = model.encode(inputs["input_values"])
667
+ >>> # Get the intermediate audio codes
668
+ >>> audio_codes = encoder_outputs.audio_codes
669
+ >>> # Reconstruct the audio from its quantized representation
670
+ >>> audio_values = model.decode(encoder_outputs.quantized_representation)
671
+ >>> # or the equivalent with a forward pass
672
+ >>> audio_values = model(inputs["input_values"]).audio_values
673
+ ```"""
674
+
675
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
676
+ length = input_values.shape[-1]
677
+
678
+ loss, quantized_representation, audio_codes, projected_latents = self.encode(
679
+ input_values, n_quantizers, return_dict=False
680
+ )
681
+ audio_values = self.decode(quantized_representation, return_dict=False)[0][..., :length]
682
+
683
+ if not return_dict:
684
+ return (loss, audio_values, quantized_representation, audio_codes, projected_latents)
685
+
686
+ return DacOutput(loss, audio_values, quantized_representation, audio_codes, projected_latents)
687
+
688
+
689
+ __all__ = ["DacModel", "DacPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paddleocr_vl/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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_paddleocr_vl import *
23
+ from .image_processing_paddleocr_vl import *
24
+ from .image_processing_pil_paddleocr_vl import *
25
+ from .modeling_paddleocr_vl import *
26
+ from .processing_paddleocr_vl import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py ADDED
@@ -0,0 +1,1695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/paddleocr_vl/modular_paddleocr_vl.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_paddleocr_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The PaddlePaddle Team and The HuggingFace Inc. 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
+ import itertools
27
+ from collections.abc import Callable
28
+ from dataclasses import dataclass
29
+ from typing import Any, Optional
30
+
31
+ import torch
32
+ from torch import nn
33
+
34
+ from ... import initialization as init
35
+ from ...activations import ACT2FN, GELUActivation
36
+ from ...cache_utils import Cache, DynamicCache
37
+ from ...generation import GenerationMixin
38
+ from ...integrations import use_kernel_forward_from_hub
39
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
40
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
41
+ from ...modeling_layers import GradientCheckpointingLayer
42
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
43
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
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, logging, torch_compilable_check, torch_int
47
+ from ...utils.deprecation import deprecate_kwarg
48
+ from ...utils.generic import (
49
+ accepts_precomputed_kwargs,
50
+ is_flash_attention_requested,
51
+ maybe_autocast,
52
+ merge_with_config_defaults,
53
+ )
54
+ from ...utils.output_capturing import capture_outputs
55
+ from ...vision_utils import get_vision_cu_seqlens, get_vision_position_ids
56
+ from .configuration_paddleocr_vl import PaddleOCRTextConfig, PaddleOCRVisionConfig, PaddleOCRVLConfig
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ class PaddleOCRProjector(nn.Module):
63
+ def __init__(self, config: PaddleOCRVLConfig):
64
+ super().__init__()
65
+ self.merge_kernel_size = (config.vision_config.spatial_merge_size, config.vision_config.spatial_merge_size)
66
+
67
+ hidden_size = config.vision_config.hidden_size * self.merge_kernel_size[0] * self.merge_kernel_size[1]
68
+
69
+ self.pre_norm = torch.nn.LayerNorm(config.vision_config.hidden_size, eps=1e-05)
70
+ self.linear_1 = nn.Linear(hidden_size, hidden_size, bias=True)
71
+ self.act = GELUActivation()
72
+ self.linear_2 = nn.Linear(hidden_size, config.text_config.hidden_size, bias=True)
73
+
74
+ def forward(self, image_features: torch.Tensor, image_grid_thw: torch.Tensor) -> torch.Tensor:
75
+ image_features_chunks = image_features.split(image_grid_thw.prod(dim=1).tolist(), dim=0)
76
+ m1, m2 = self.merge_kernel_size
77
+
78
+ processed_features = []
79
+ for image_feature, image_grid in zip(image_features_chunks, image_grid_thw):
80
+ image_feature = self.pre_norm(image_feature)
81
+ t, h, w = image_grid
82
+ d = image_feature.shape[-1]
83
+ h_block = h // m1
84
+ w_block = w // m2
85
+
86
+ image_feature = image_feature.reshape(t, h_block, m1, w_block, m2, d)
87
+ image_feature = image_feature.transpose(2, 3)
88
+ image_feature = image_feature.reshape(t * h_block * w_block, m1 * m2 * d)
89
+
90
+ hidden_states = self.linear_1(image_feature)
91
+ hidden_states = self.act(hidden_states)
92
+ hidden_states = self.linear_2(hidden_states)
93
+ processed_features.append(hidden_states)
94
+
95
+ return torch.cat(processed_features, dim=0)
96
+
97
+
98
+ class PaddleOCRVisionRotaryEmbedding(nn.Module):
99
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
100
+
101
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
102
+ super().__init__()
103
+ self.dim = dim
104
+ self.theta = theta
105
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
106
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
107
+
108
+ def forward(self, position_ids: torch.Tensor) -> torch.Tensor:
109
+ return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1)
110
+
111
+
112
+ class PaddleOCRRotaryEmbedding(nn.Module):
113
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
114
+
115
+ def __init__(self, config: PaddleOCRVLConfig, device=None):
116
+ super().__init__()
117
+ self.max_seq_len_cached = config.max_position_embeddings
118
+ self.original_max_seq_len = config.max_position_embeddings
119
+
120
+ self.config = config
121
+
122
+ self.rope_type = self.config.rope_parameters["rope_type"]
123
+ rope_init_fn: Callable = self.compute_default_rope_parameters
124
+ if self.rope_type != "default":
125
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
126
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
127
+
128
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
129
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
130
+
131
+ @staticmethod
132
+ def compute_default_rope_parameters(
133
+ config: PaddleOCRVLConfig | None = None,
134
+ device: Optional["torch.device"] = None,
135
+ seq_len: int | None = None,
136
+ ) -> tuple["torch.Tensor", float]:
137
+ """
138
+ Computes the inverse frequencies according to the original RoPE implementation
139
+ Args:
140
+ config ([`~transformers.PreTrainedConfig`]):
141
+ The model configuration.
142
+ device (`torch.device`):
143
+ The device to use for initialization of the inverse frequencies.
144
+ seq_len (`int`, *optional*):
145
+ The current sequence length. Unused for this type of RoPE.
146
+ Returns:
147
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
148
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
149
+ """
150
+ base = config.rope_parameters["rope_theta"]
151
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
152
+
153
+ attention_factor = 1.0 # Unused in this type of RoPE
154
+
155
+ # Compute the inverse frequencies
156
+ inv_freq = 1.0 / (
157
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
158
+ )
159
+ return inv_freq, attention_factor
160
+
161
+ # Ignore copy
162
+ def forward(self, x, position_ids):
163
+ # In contrast to other models, PaddleOCR has different position ids for the grids
164
+ # So we expand the inv_freq to shape (3, ...)
165
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
166
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
167
+
168
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
169
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
170
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ cos = emb.cos() * self.attention_scaling
173
+ sin = emb.sin() * self.attention_scaling
174
+
175
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
176
+
177
+
178
+ class PaddleOCRMLP(nn.Module):
179
+ def __init__(self, config: PaddleOCRTextConfig):
180
+ super().__init__()
181
+ self.config = config
182
+ self.hidden_size = config.hidden_size
183
+ self.intermediate_size = config.intermediate_size
184
+
185
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
186
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
187
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
188
+ self.act_fn = ACT2FN[config.hidden_act]
189
+
190
+ def forward(self, x):
191
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
192
+ return down_proj
193
+
194
+
195
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
196
+ """
197
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
198
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
199
+ """
200
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
201
+ if n_rep == 1:
202
+ return hidden_states
203
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
204
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
205
+
206
+
207
+ def eager_attention_forward(
208
+ module: nn.Module,
209
+ query: torch.Tensor,
210
+ key: torch.Tensor,
211
+ value: torch.Tensor,
212
+ attention_mask: torch.Tensor | None,
213
+ scaling: float,
214
+ dropout: float = 0.0,
215
+ **kwargs,
216
+ ):
217
+ key_states = repeat_kv(key, module.num_key_value_groups)
218
+ value_states = repeat_kv(value, module.num_key_value_groups)
219
+
220
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
221
+ if attention_mask is not None:
222
+ attn_weights = attn_weights + attention_mask
223
+
224
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
225
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
226
+ attn_output = torch.matmul(attn_weights, value_states)
227
+ attn_output = attn_output.transpose(1, 2).contiguous()
228
+
229
+ return attn_output, attn_weights
230
+
231
+
232
+ def rotate_half(x):
233
+ """Rotates half the hidden dims of the input."""
234
+ x1 = x[..., : x.shape[-1] // 2]
235
+ x2 = x[..., x.shape[-1] // 2 :]
236
+ return torch.cat((-x2, x1), dim=-1)
237
+
238
+
239
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
240
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
241
+
242
+ Explanation:
243
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
244
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
245
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
246
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
247
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
248
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
249
+ difference with modern LLMs.
250
+
251
+ Args:
252
+ q (`torch.Tensor`): The query tensor.
253
+ k (`torch.Tensor`): The key tensor.
254
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
255
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
256
+ position_ids (`torch.Tensor`):
257
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
258
+ used to pass offsetted position ids when working with a KV-cache.
259
+ mrope_section(`List(int)`):
260
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
261
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
262
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
263
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
264
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
265
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
266
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
267
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
268
+ Returns:
269
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
270
+ """
271
+ mrope_section = mrope_section * 2
272
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
273
+ unsqueeze_dim
274
+ )
275
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
276
+ unsqueeze_dim
277
+ )
278
+
279
+ q_embed = (q * cos) + (rotate_half(q) * sin)
280
+ k_embed = (k * cos) + (rotate_half(k) * sin)
281
+ return q_embed, k_embed
282
+
283
+
284
+ class PaddleOCRAttention(nn.Module):
285
+ """
286
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
287
+ and "Generating Long Sequences with Sparse Transformers".
288
+ """
289
+
290
+ def __init__(self, config: PaddleOCRVLConfig, layer_idx: int | None = None):
291
+ super().__init__()
292
+ self.config = config
293
+ self.layer_idx = layer_idx
294
+ if layer_idx is None:
295
+ logger.warning_once(
296
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
297
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
298
+ "when creating this class."
299
+ )
300
+
301
+ self.hidden_size = config.hidden_size
302
+ self.num_heads = config.num_attention_heads
303
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
304
+ self.num_key_value_heads = config.num_key_value_heads
305
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
306
+ self.is_causal = True
307
+
308
+ self.attention_dropout = 0.0
309
+ self.rope_parameters = config.rope_parameters
310
+ self.scaling = self.head_dim**-0.5
311
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_bias)
312
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_bias)
313
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_bias)
314
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
315
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
316
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
317
+
318
+ def forward(
319
+ self,
320
+ hidden_states: torch.Tensor,
321
+ attention_mask: torch.Tensor | None = None,
322
+ position_ids: torch.LongTensor | None = None,
323
+ past_key_values: Cache | None = None,
324
+ output_attentions: bool = False,
325
+ use_cache: bool = False,
326
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
327
+ **kwargs: Unpack[FlashAttentionKwargs],
328
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
329
+ bsz, q_len, _ = hidden_states.size()
330
+
331
+ query_states = self.q_proj(hidden_states)
332
+ key_states = self.k_proj(hidden_states)
333
+ value_states = self.v_proj(hidden_states)
334
+
335
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
336
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
337
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
338
+
339
+ cos, sin = position_embeddings
340
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
341
+ query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"]
342
+ )
343
+
344
+ if past_key_values is not None:
345
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
346
+
347
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
348
+ self.config._attn_implementation, eager_attention_forward
349
+ )
350
+
351
+ attn_output, attn_weights = attention_interface(
352
+ self,
353
+ query_states,
354
+ key_states,
355
+ value_states,
356
+ attention_mask,
357
+ dropout=0.0 if not self.training else self.attention_dropout,
358
+ scaling=self.scaling,
359
+ sliding_window=self.sliding_window,
360
+ position_ids=position_ids, # pass positions for FA2
361
+ **kwargs,
362
+ )
363
+
364
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
365
+ attn_output = self.o_proj(attn_output)
366
+ return attn_output, attn_weights
367
+
368
+
369
+ @use_kernel_forward_from_hub("RMSNorm")
370
+ class PaddleOCRRMSNorm(nn.Module):
371
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
372
+ """
373
+ PaddleOCRRMSNorm is equivalent to T5LayerNorm
374
+ """
375
+ super().__init__()
376
+ self.weight = nn.Parameter(torch.ones(hidden_size))
377
+ self.variance_epsilon = eps
378
+
379
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
380
+ input_dtype = hidden_states.dtype
381
+ hidden_states = hidden_states.to(torch.float32)
382
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
383
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
384
+ return self.weight * hidden_states.to(input_dtype)
385
+
386
+ def extra_repr(self):
387
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
388
+
389
+
390
+ class PaddleOCRDecoderLayer(GradientCheckpointingLayer):
391
+ def __init__(self, config: PaddleOCRTextConfig, layer_idx: int):
392
+ super().__init__()
393
+ self.hidden_size = config.hidden_size
394
+
395
+ self.self_attn = PaddleOCRAttention(config=config, layer_idx=layer_idx)
396
+
397
+ self.mlp = PaddleOCRMLP(config)
398
+ self.input_layernorm = PaddleOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
399
+ self.post_attention_layernorm = PaddleOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
400
+
401
+ def forward(
402
+ self,
403
+ hidden_states: torch.Tensor,
404
+ attention_mask: torch.Tensor | None = None,
405
+ position_ids: torch.LongTensor | None = None,
406
+ past_key_values: Cache | None = None,
407
+ use_cache: bool | None = False,
408
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
409
+ **kwargs: Unpack[TransformersKwargs],
410
+ ) -> torch.Tensor:
411
+ residual = hidden_states
412
+ hidden_states = self.input_layernorm(hidden_states)
413
+ # Self Attention
414
+ hidden_states, _ = self.self_attn(
415
+ hidden_states=hidden_states,
416
+ attention_mask=attention_mask,
417
+ position_ids=position_ids,
418
+ past_key_values=past_key_values,
419
+ use_cache=use_cache,
420
+ position_embeddings=position_embeddings,
421
+ **kwargs,
422
+ )
423
+ hidden_states = residual + hidden_states
424
+
425
+ # Fully Connected
426
+ residual = hidden_states
427
+ hidden_states = self.post_attention_layernorm(hidden_states)
428
+ hidden_states = self.mlp(hidden_states)
429
+ hidden_states = residual + hidden_states
430
+ return hidden_states
431
+
432
+
433
+ @auto_docstring
434
+ class PaddleOCRVLPreTrainedModel(PreTrainedModel):
435
+ config: PaddleOCRVLConfig
436
+ base_model_prefix = "model"
437
+ supports_gradient_checkpointing = True
438
+ _no_split_modules = ["PaddleOCRDecoderLayer"]
439
+ _skip_keys_device_placement = ["past_key_values"]
440
+ _supports_flash_attn = True
441
+ _supports_sdpa = True
442
+ _supports_flex_attn = True
443
+
444
+ _can_compile_fullgraph = True
445
+ _supports_attention_backend = True
446
+
447
+ _can_record_outputs = {
448
+ "hidden_states": PaddleOCRDecoderLayer,
449
+ "attentions": PaddleOCRAttention,
450
+ }
451
+
452
+ def _init_weights(self, module):
453
+ super()._init_weights(module)
454
+ if isinstance(module, PaddleOCRVisionEmbeddings):
455
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
456
+ elif isinstance(module, PaddleOCRVisionRotaryEmbedding):
457
+ inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim))
458
+ init.copy_(module.inv_freq, inv_freq)
459
+
460
+
461
+ @auto_docstring
462
+ class PaddleOCRTextModel(PaddleOCRVLPreTrainedModel):
463
+ def __init__(self, config: PaddleOCRTextConfig):
464
+ super().__init__(config)
465
+ self.padding_idx = config.pad_token_id
466
+ self.vocab_size = config.vocab_size
467
+
468
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
469
+ self.layers = nn.ModuleList(
470
+ [PaddleOCRDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
471
+ )
472
+ self.norm = PaddleOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
473
+ self.rotary_emb = PaddleOCRRotaryEmbedding(config=config)
474
+ self.gradient_checkpointing = False
475
+
476
+ # Initialize weights and apply final processing
477
+ self.post_init()
478
+
479
+ @merge_with_config_defaults
480
+ @capture_outputs
481
+ @auto_docstring
482
+ def forward(
483
+ self,
484
+ input_ids: torch.LongTensor | None = None,
485
+ attention_mask: torch.Tensor | None = None,
486
+ position_ids: torch.LongTensor | None = None,
487
+ past_key_values: Cache | None = None,
488
+ inputs_embeds: torch.FloatTensor | None = None,
489
+ use_cache: bool | None = None,
490
+ **kwargs: Unpack[TransformersKwargs],
491
+ ) -> BaseModelOutputWithPast:
492
+ if (input_ids is None) ^ (inputs_embeds is not None):
493
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
494
+
495
+ if inputs_embeds is None:
496
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
497
+
498
+ if use_cache and past_key_values is None:
499
+ past_key_values = DynamicCache(config=self.config)
500
+
501
+ if position_ids is None:
502
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
503
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
504
+ position_ids = position_ids.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
505
+ elif position_ids.ndim == 2:
506
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
507
+
508
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
509
+ text_position_ids = position_ids[0]
510
+ position_ids = position_ids[1:]
511
+ else:
512
+ text_position_ids = None
513
+
514
+ causal_mask = create_causal_mask(
515
+ config=self.config,
516
+ inputs_embeds=inputs_embeds,
517
+ attention_mask=attention_mask,
518
+ past_key_values=past_key_values,
519
+ position_ids=text_position_ids,
520
+ )
521
+
522
+ hidden_states = inputs_embeds
523
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
524
+
525
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
526
+ hidden_states = decoder_layer(
527
+ hidden_states,
528
+ attention_mask=causal_mask,
529
+ position_embeddings=position_embeddings,
530
+ position_ids=text_position_ids,
531
+ past_key_values=past_key_values,
532
+ use_cache=use_cache,
533
+ **kwargs,
534
+ )
535
+
536
+ hidden_states = self.norm(hidden_states)
537
+ return BaseModelOutputWithPast(
538
+ last_hidden_state=hidden_states,
539
+ past_key_values=past_key_values,
540
+ )
541
+
542
+
543
+ class PaddleOCRVisionEmbeddings(nn.Module):
544
+ def __init__(self, config: PaddleOCRVisionConfig):
545
+ super().__init__()
546
+ self.config = config
547
+ self.embed_dim = config.hidden_size
548
+ self.image_size = config.image_size
549
+ self.patch_size = config.patch_size
550
+
551
+ self.patch_embedding = nn.Conv2d(
552
+ in_channels=config.num_channels,
553
+ out_channels=self.embed_dim,
554
+ kernel_size=self.patch_size,
555
+ stride=self.patch_size,
556
+ padding="valid",
557
+ )
558
+
559
+ self.num_patches = (self.image_size // self.patch_size) ** 2
560
+ self.num_positions = self.num_patches
561
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
562
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
563
+
564
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
565
+ """
566
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
567
+ images. This method is also adapted to support torch.jit tracing and no class embeddings.
568
+
569
+ Adapted from:
570
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
571
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
572
+ """
573
+ num_positions = self.position_embedding.weight.shape[0]
574
+
575
+ patch_pos_embed = self.position_embedding.weight.unsqueeze(0)
576
+
577
+ dim = embeddings.shape[-1]
578
+
579
+ sqrt_num_positions = torch_int(num_positions**0.5)
580
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
581
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
582
+
583
+ patch_pos_embed = nn.functional.interpolate(
584
+ patch_pos_embed,
585
+ size=(height, width),
586
+ mode="bilinear",
587
+ align_corners=False,
588
+ )
589
+
590
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
591
+ return patch_pos_embed
592
+
593
+ @deprecate_kwarg("image_grid_thw", new_name="grid_thw", version="5.11.0")
594
+ def forward(
595
+ self,
596
+ pixel_values: torch.FloatTensor,
597
+ grid_thw: torch.LongTensor | None = None,
598
+ ) -> torch.Tensor:
599
+ """
600
+ Args:
601
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, image_channels, patch_size, patch_size)`):
602
+ The tensors corresponding to the input images.
603
+ grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
604
+ The temporal, height and width of feature shape of each image in LLM.
605
+ """
606
+ batch_size, squence_len, channel, height, width = pixel_values.shape
607
+ target_dtype = self.patch_embedding.weight.dtype
608
+ pixel_values = pixel_values.reshape(batch_size * squence_len, channel, height, width)
609
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
610
+ embeddings = patch_embeds.flatten(-2).squeeze(-1)
611
+ embeddings = embeddings.reshape(batch_size, squence_len, -1)
612
+
613
+ start = 0
614
+ embeddings = embeddings.squeeze(0)
615
+ tmp_embeddings = []
616
+ for t, h, w in grid_thw:
617
+ end = start + t * h * w
618
+ image_embeddings = embeddings[start:end, :]
619
+ position_embedding = self.interpolate_pos_encoding(image_embeddings, h, w).squeeze(0).repeat(t, 1)
620
+ image_embeddings = image_embeddings + position_embedding
621
+ tmp_embeddings.append(image_embeddings)
622
+ start = end
623
+ embeddings = torch.concat(tmp_embeddings, dim=0)
624
+
625
+ return embeddings
626
+
627
+
628
+ def apply_rotary_pos_emb_vision(
629
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
630
+ ) -> tuple[torch.Tensor, torch.Tensor]:
631
+ orig_q_dtype = q.dtype
632
+ orig_k_dtype = k.dtype
633
+ q, k = q.float(), k.float()
634
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
635
+ q_embed = (q * cos) + (rotate_half(q) * sin)
636
+ k_embed = (k * cos) + (rotate_half(k) * sin)
637
+ q_embed = q_embed.to(orig_q_dtype)
638
+ k_embed = k_embed.to(orig_k_dtype)
639
+ return q_embed, k_embed
640
+
641
+
642
+ class PaddleOCRVisionAttention(nn.Module):
643
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
644
+
645
+ def __init__(self, config: PaddleOCRVisionConfig):
646
+ super().__init__()
647
+ self.config = config
648
+ self.embed_dim = config.hidden_size
649
+ self.num_heads = config.num_attention_heads
650
+ self.head_dim = self.embed_dim // self.num_heads
651
+ if self.head_dim * self.num_heads != self.embed_dim:
652
+ raise ValueError(
653
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
654
+ f" {self.num_heads})."
655
+ )
656
+ self.is_causal = False
657
+
658
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
659
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
660
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
661
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
662
+ self.num_key_value_groups = 1
663
+ self.scaling = self.head_dim**-0.5
664
+ self.attention_dropout = config.attention_dropout
665
+
666
+ def forward(
667
+ self,
668
+ hidden_states: torch.Tensor,
669
+ cu_seqlens: torch.Tensor,
670
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
671
+ **kwargs: Unpack[TransformersKwargs],
672
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
673
+ """
674
+ Args:
675
+ hidden_states (`torch.Tensor`):
676
+ Input to the layer of shape `(seq_len, embed_dim)`.
677
+ cu_seqlens (`torch.Tensor` of shape `(num_images_or_videos + 1,)`):
678
+ The cumulative sequence lengths of each image or video feature.
679
+ position_embeddings (`tuple(torch.Tensor, torch.Tensor)` of shape `(num_patches, head_dim // 2)`):
680
+ The cosine and sine position embeddings for vision attention.
681
+ """
682
+ seq_length = hidden_states.shape[0]
683
+ query_states = self.q_proj(hidden_states).view(seq_length, self.num_heads, self.head_dim)
684
+ key_states = self.k_proj(hidden_states).view(seq_length, self.num_heads, self.head_dim)
685
+ value_states = self.v_proj(hidden_states).view(seq_length, self.num_heads, self.head_dim)
686
+
687
+ cos, sin = position_embeddings
688
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
689
+
690
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
691
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
692
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
693
+
694
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
695
+ self.config._attn_implementation, eager_attention_forward
696
+ )
697
+
698
+ if is_flash_attention_requested(self.config):
699
+ # Flash Attention 2: Use cu_seqlens for variable length attention
700
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
701
+ attn_output, attn_weights = attention_interface(
702
+ self,
703
+ query_states,
704
+ key_states,
705
+ value_states,
706
+ attention_mask=None,
707
+ scaling=self.scaling,
708
+ dropout=0.0 if not self.training else self.attention_dropout,
709
+ cu_seq_lens_q=cu_seqlens,
710
+ cu_seq_lens_k=cu_seqlens,
711
+ max_length_q=max_seqlen,
712
+ max_length_k=max_seqlen,
713
+ is_causal=False,
714
+ **kwargs,
715
+ )
716
+ else:
717
+ # Other implementations: Process each chunk separately
718
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
719
+ splits = [
720
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
721
+ ]
722
+
723
+ attn_outputs, attn_weights = [], []
724
+ for q, k, v in zip(*splits):
725
+ attn_output, attn_weight = attention_interface(
726
+ self,
727
+ q,
728
+ k,
729
+ v,
730
+ attention_mask=None,
731
+ scaling=self.scaling,
732
+ dropout=0.0 if not self.training else self.attention_dropout,
733
+ is_causal=False,
734
+ **kwargs,
735
+ )
736
+ attn_outputs.append(attn_output)
737
+ attn_weights.append(attn_weight)
738
+
739
+ attn_output = torch.cat(attn_outputs, dim=1)
740
+
741
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
742
+ attn_output = self.out_proj(attn_output)
743
+
744
+ return attn_output, attn_weights
745
+
746
+
747
+ class PaddleOCRVisionMLP(nn.Module):
748
+ def __init__(self, config: PaddleOCRVisionConfig):
749
+ super().__init__()
750
+ self.config = config
751
+ self.activation_fn = ACT2FN[config.hidden_act]
752
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
753
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
754
+
755
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
756
+ hidden_states = self.fc1(hidden_states)
757
+ hidden_states = self.activation_fn(hidden_states)
758
+ hidden_states = self.fc2(hidden_states)
759
+ return hidden_states
760
+
761
+
762
+ class PaddleOCRVisionEncoderLayer(GradientCheckpointingLayer):
763
+ def __init__(self, config: PaddleOCRVisionConfig):
764
+ super().__init__()
765
+ self.embed_dim = config.hidden_size
766
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
767
+ self.self_attn = PaddleOCRVisionAttention(config=config)
768
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
769
+ self.mlp = PaddleOCRVisionMLP(config=config)
770
+
771
+ @auto_docstring
772
+ def forward(
773
+ self,
774
+ hidden_states: torch.Tensor,
775
+ cu_seqlens: torch.Tensor,
776
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
777
+ **kwargs: Unpack[TransformersKwargs],
778
+ ) -> torch.Tensor:
779
+ r"""
780
+ cu_seqlens (`torch.Tensor` of shape `(num_images_or_videos + 1,)`):
781
+ The cumulative sequence lengths of each image or video feature.
782
+ position_embeddings (`tuple(torch.Tensor, torch.Tensor)` of shape `(num_patches, head_dim // 2)`):
783
+ The cosine and sine position embeddings for vision attention.
784
+ """
785
+ residual = hidden_states
786
+
787
+ hidden_states = self.layer_norm1(hidden_states)
788
+ hidden_states, _ = self.self_attn(
789
+ hidden_states,
790
+ cu_seqlens=cu_seqlens,
791
+ position_embeddings=position_embeddings,
792
+ **kwargs,
793
+ )
794
+ hidden_states = residual + hidden_states
795
+
796
+ residual = hidden_states
797
+ hidden_states = self.layer_norm2(hidden_states)
798
+ hidden_states = self.mlp(hidden_states)
799
+ hidden_states = residual + hidden_states
800
+
801
+ return hidden_states
802
+
803
+
804
+ class PaddleOCRVisionEncoder(nn.Module):
805
+ """
806
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
807
+ [`PaddleOCRVisionEncoderLayer`].
808
+
809
+ Args:
810
+ config: PaddleOCRVisionConfig
811
+ """
812
+
813
+ def __init__(self, config: PaddleOCRVisionConfig):
814
+ super().__init__()
815
+ self.config = config
816
+ self.layers = nn.ModuleList([PaddleOCRVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
817
+ self.gradient_checkpointing = False
818
+ embed_dim = config.hidden_size
819
+ num_heads = config.num_attention_heads
820
+ head_dim = embed_dim // num_heads
821
+ self.rotary_pos_emb = PaddleOCRVisionRotaryEmbedding(head_dim // 2)
822
+
823
+ # Ignore copy
824
+ @can_return_tuple
825
+ @auto_docstring
826
+ @deprecate_kwarg("image_grid_thw", new_name="grid_thw", version="5.11.0")
827
+ def forward(
828
+ self,
829
+ inputs_embeds: torch.FloatTensor,
830
+ attention_mask: torch.Tensor | None = None,
831
+ grid_thw: torch.LongTensor | None = None,
832
+ **kwargs: Unpack[TransformersKwargs],
833
+ ) -> BaseModelOutput:
834
+ r"""
835
+ inputs_embeds (`torch.FloatTensor` of shape `(sequence_length, hidden_size)`, *optional*):
836
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
837
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
838
+ than the model's internal embedding lookup matrix.
839
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
840
+ The attention_mask used in forward function shape [batch_size X sequence_length] if not None.
841
+ grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
842
+ The temporal, height and width of feature shape of each image in LLM.
843
+ """
844
+ # Use merge_size=1: PaddleOCR merges patches in the projector (after the encoder),
845
+ # unlike Qwen which merges inside the encoder, so rotary positions here are simple (row, col).
846
+ position_ids = get_vision_position_ids(grid_thw, 1, kwargs=kwargs)
847
+ cu_seqlens = get_vision_cu_seqlens(grid_thw, kwargs=kwargs)
848
+
849
+ hidden_states = inputs_embeds
850
+ attention_mask = create_bidirectional_mask(
851
+ config=self.config,
852
+ inputs_embeds=inputs_embeds,
853
+ attention_mask=attention_mask,
854
+ )
855
+ rotary_embeddings = self.rotary_pos_emb(position_ids)
856
+ rotary_embeddings = rotary_embeddings.repeat(1, 2)
857
+ position_embeddings = (rotary_embeddings.cos(), rotary_embeddings.sin())
858
+
859
+ for encoder_layer in self.layers:
860
+ hidden_states = encoder_layer(
861
+ hidden_states,
862
+ cu_seqlens=cu_seqlens,
863
+ position_embeddings=position_embeddings,
864
+ **kwargs,
865
+ )
866
+
867
+ return BaseModelOutput(
868
+ last_hidden_state=hidden_states,
869
+ )
870
+
871
+
872
+ class PaddleOCRVisionTransformer(PaddleOCRVLPreTrainedModel):
873
+ config: PaddleOCRVisionConfig
874
+ main_input_name = "pixel_values"
875
+ input_modalities = "image"
876
+ _can_record_outputs = {
877
+ "hidden_states": PaddleOCRVisionEncoderLayer,
878
+ "attentions": PaddleOCRVisionAttention,
879
+ }
880
+
881
+ def __init__(self, config: PaddleOCRVisionConfig):
882
+ super().__init__(config)
883
+ self.config = config
884
+ embed_dim = config.hidden_size
885
+
886
+ self.embeddings = PaddleOCRVisionEmbeddings(config)
887
+ self.encoder = PaddleOCRVisionEncoder(config)
888
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
889
+
890
+ self.post_init()
891
+
892
+ @merge_with_config_defaults
893
+ @capture_outputs(tie_last_hidden_states=False)
894
+ @deprecate_kwarg("image_grid_thw", new_name="grid_thw", version="5.11.0")
895
+ def forward(
896
+ self,
897
+ pixel_values: torch.FloatTensor,
898
+ attention_mask: torch.Tensor | None = None,
899
+ grid_thw: torch.LongTensor | None = None,
900
+ **kwargs: Unpack[TransformersKwargs],
901
+ ) -> BaseModelOutputWithPooling:
902
+ """
903
+ Args:
904
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size * patch_size * image_channels)`):
905
+ The tensors corresponding to the input images.
906
+ attention_mask (`torch.Tensor`, *optional*):
907
+ The attention_mask used in forward function shape [batch_size X sequence_length] if not None.
908
+ grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
909
+ The temporal, height and width of feature shape of each image in LLM.
910
+ """
911
+ hidden_states = self.embeddings(pixel_values, grid_thw=grid_thw)
912
+ encoder_outputs: BaseModelOutput = self.encoder(
913
+ inputs_embeds=hidden_states,
914
+ grid_thw=grid_thw,
915
+ attention_mask=attention_mask,
916
+ **kwargs,
917
+ )
918
+
919
+ last_hidden_state = encoder_outputs.last_hidden_state
920
+ last_hidden_state = self.post_layernorm(last_hidden_state)
921
+
922
+ return BaseModelOutputWithPooling(
923
+ last_hidden_state=last_hidden_state,
924
+ pooler_output=None,
925
+ )
926
+
927
+
928
+ class PaddleOCRVisionModel(PaddleOCRVLPreTrainedModel):
929
+ config: PaddleOCRVisionConfig
930
+ main_input_name = "pixel_values"
931
+ input_modalities = "image"
932
+
933
+ def __init__(self, config: PaddleOCRVisionConfig):
934
+ super().__init__(config)
935
+
936
+ self.vision_model = PaddleOCRVisionTransformer(config)
937
+
938
+ # Initialize weights and apply final processing
939
+ self.post_init()
940
+
941
+ @deprecate_kwarg("image_grid_thw", new_name="grid_thw", version="5.11.0")
942
+ def forward(
943
+ self,
944
+ pixel_values: torch.FloatTensor,
945
+ grid_thw: torch.LongTensor | None = None,
946
+ **kwargs: Unpack[TransformersKwargs],
947
+ ) -> tuple | BaseModelOutputWithPooling:
948
+ """
949
+ Args:
950
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, image_channels, patch_size, patch_size)`):
951
+ The tensors corresponding to the input images.
952
+ grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
953
+ The temporal, height and width of feature shape of each image in LLM.
954
+ """
955
+ return self.vision_model(pixel_values=pixel_values, grid_thw=grid_thw, **kwargs)
956
+
957
+
958
+ @auto_docstring(
959
+ custom_intro="""
960
+ Base class for Llava outputs, with hidden states and attentions.
961
+ """
962
+ )
963
+ @dataclass
964
+ class PaddleOCRVLModelOutputWithPast(ModelOutput):
965
+ r"""
966
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
967
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
968
+
969
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
970
+ `past_key_values` input) to speed up sequential decoding.
971
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
972
+ The rope index difference between sequence length and multimodal rope.
973
+ """
974
+
975
+ last_hidden_state: torch.FloatTensor | None = None
976
+ past_key_values: Cache | None = None
977
+ hidden_states: tuple[torch.FloatTensor] | None = None
978
+ attentions: tuple[torch.FloatTensor] | None = None
979
+ rope_deltas: torch.LongTensor | None = None
980
+
981
+
982
+ @auto_docstring(
983
+ custom_intro="""
984
+ Base class for PaddleOCRVL causal language model (or autoregressive) outputs.
985
+ """
986
+ )
987
+ @dataclass
988
+ class PaddleOCRVLCausalLMOutputWithPast(ModelOutput):
989
+ r"""
990
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
991
+ Language modeling loss (for next-token prediction).
992
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
993
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
994
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
995
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
996
+
997
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
998
+ `past_key_values` input) to speed up sequential decoding.
999
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1000
+ The rope index difference between sequence length and multimodal rope.
1001
+ """
1002
+
1003
+ loss: torch.FloatTensor | None = None
1004
+ logits: torch.FloatTensor | None = None
1005
+ past_key_values: Cache | None = None
1006
+ hidden_states: tuple[torch.FloatTensor] | None = None
1007
+ attentions: tuple[torch.FloatTensor] | None = None
1008
+ rope_deltas: torch.LongTensor | None = None
1009
+
1010
+
1011
+ @auto_docstring
1012
+ class PaddleOCRVLModel(PaddleOCRVLPreTrainedModel):
1013
+ base_model_prefix = "model"
1014
+ # Reference: fix gemma3 grad acc #37208
1015
+ accepts_loss_kwargs = False
1016
+ _keys_to_ignore_on_load_unexpected = ["packing_position_embedding", "vision_model.head"]
1017
+
1018
+ def __init__(self, config: PaddleOCRVLConfig):
1019
+ super().__init__(config)
1020
+ self.visual = PaddleOCRVisionModel._from_config(config.vision_config)
1021
+ self.language_model = PaddleOCRTextModel._from_config(config.text_config)
1022
+ self.rope_deltas = None
1023
+ self.projector = PaddleOCRProjector(config)
1024
+
1025
+ # Initialize weights and apply final processing
1026
+ self.post_init()
1027
+
1028
+ def get_vision_position_ids(
1029
+ self,
1030
+ start_position: int,
1031
+ grid_thw: list[int, int, int] | torch.Tensor,
1032
+ temp_merge_size: int = 1,
1033
+ spatial_merge_size: int = 1,
1034
+ time_interval: int = 1,
1035
+ device: str | torch.device | None = None,
1036
+ ):
1037
+ """
1038
+ Compute 3D positional indices for vision tokens derived from a single image or video input.
1039
+
1040
+ The positions are generated from the input grid defined by temporal (T), height (H), and
1041
+ width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
1042
+ merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
1043
+
1044
+ Args:
1045
+ start_position (`int`):
1046
+ Offset added to all computed positional indices.
1047
+ grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
1048
+ The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
1049
+ temp_merge_size (`int`, *optional*):
1050
+ Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
1051
+ by this value. Defaults to 1.
1052
+ spatial_merge_size (`int`, *optional*):
1053
+ Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
1054
+ by this value. Defaults to 1.
1055
+ time_interval (`int`, *optional*):
1056
+ Spacing factor applied between consecutive temporal position indices.Defaults to 1.
1057
+ device (`str` or `torch.device`, *optional*):
1058
+ Device on which the resulting tensor is allocated. If `None`, uses the current default device.
1059
+
1060
+ Returns:
1061
+ torch.LongTensor of shape (3, sequence_length):
1062
+ Positional indices for temporal, height, and width dimensions,
1063
+ flattened into sequence form and offset by `start_position`.
1064
+ """
1065
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1066
+ grid_thw[0].item() // temp_merge_size,
1067
+ grid_thw[1].item() // spatial_merge_size,
1068
+ grid_thw[2].item() // spatial_merge_size,
1069
+ )
1070
+
1071
+ # Add `start_position` after arange for compile
1072
+ position_temporal = torch.arange(llm_grid_t, device=device) * time_interval
1073
+ position_width = torch.arange(llm_grid_w, device=device) + start_position
1074
+ position_height = torch.arange(llm_grid_h, device=device) + start_position
1075
+
1076
+ # Repeat the positions per each grid and per video frame. Repeat patterns are important
1077
+ # do not modify without checking values!
1078
+ position_width = position_width.repeat(llm_grid_h * llm_grid_t)
1079
+ position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
1080
+ # Important: add `start_positions` after applying `time_interval`, order matters
1081
+ position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
1082
+ vision_position_ids = torch.stack([position_temporal, position_height, position_width], dim=0)
1083
+
1084
+ return vision_position_ids
1085
+
1086
+ def get_rope_index(
1087
+ self,
1088
+ input_ids: torch.LongTensor,
1089
+ mm_token_type_ids: torch.IntTensor,
1090
+ image_grid_thw: torch.LongTensor | None = None,
1091
+ video_grid_thw: torch.LongTensor | None = None,
1092
+ attention_mask: torch.Tensor | None = None,
1093
+ **kwargs,
1094
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1095
+ """
1096
+ Calculate the 3D rope index based on image and video's sizes. The utility expects a `vision + text`
1097
+ sequence and will error out otherwise. For pure text sequence, please rely on model's auto-inferred
1098
+ position ids. In a mixed vision + text sequence, vision tokens use 3D RoPE (temporal, height, width)
1099
+ while text tokens use standard 1D RoPE.
1100
+
1101
+ Example:
1102
+ Temporal patches: 3; Height patches: 2; Width patches: 2
1103
+ Each vision input results in (temporal x height × width) positions. Here: 3 x 2 × 2 = 12 positions total.
1104
+
1105
+ Temporal position IDs are spaced by:
1106
+ `interval = tokens_per_second * temporal_patch_size / fps`
1107
+
1108
+ If fps = 1; tokens_per_second = 25; temporal_patch_size = 2, temporal IDs increase by 50 for each temporal patch:
1109
+ `[0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]`
1110
+
1111
+ Height IDs repeat per row: `[0, 0, 1, 1, ...]`
1112
+ Width IDs alternate per column: `[0, 1, 0, 1, ...]`
1113
+ Text tokens follow standard 1D RoPE and the position IDs grow consequently with a step of `1`
1114
+
1115
+ Args:
1116
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1117
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1118
+ it.
1119
+ mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`):
1120
+ Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
1121
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1122
+ The temporal, height and width of feature shape of each image in LLM.
1123
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1124
+ The temporal, height and width of feature shape of each video in LLM.
1125
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1126
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1127
+
1128
+ - 1 for tokens that are **not masked**,
1129
+ - 0 for tokens that are **masked**.
1130
+
1131
+ Returns:
1132
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
1133
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
1134
+ """
1135
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1136
+
1137
+ mrope_position_deltas = []
1138
+ position_ids = torch.zeros(
1139
+ 3,
1140
+ input_ids.shape[0],
1141
+ input_ids.shape[1],
1142
+ dtype=input_ids.dtype,
1143
+ device=input_ids.device,
1144
+ )
1145
+ grid_iters = {
1146
+ 1: iter(image_grid_thw) if image_grid_thw is not None else None,
1147
+ 2: iter(video_grid_thw) if video_grid_thw is not None else None,
1148
+ }
1149
+
1150
+ for batch_idx, current_input_ids in enumerate(input_ids):
1151
+ input_token_type = mm_token_type_ids[batch_idx]
1152
+ if attention_mask is not None:
1153
+ current_input_ids = current_input_ids[attention_mask[batch_idx].bool()]
1154
+ input_token_type = input_token_type[attention_mask[batch_idx].bool()]
1155
+
1156
+ input_type_group = []
1157
+ for key, group in itertools.groupby(enumerate(input_token_type.tolist()), lambda x: x[1]):
1158
+ group = list(group)
1159
+ start_index = group[0][0]
1160
+ end_index = group[-1][0] + 1
1161
+ input_type_group.append((key, start_index, end_index))
1162
+
1163
+ current_pos = 0
1164
+ llm_pos_ids_list = []
1165
+ for modality_type, start_idx, end_idx in input_type_group:
1166
+ # text == 0
1167
+ if modality_type == 0:
1168
+ text_len = end_idx - start_idx
1169
+ llm_pos_ids_list.append(
1170
+ torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos
1171
+ )
1172
+ current_pos += text_len
1173
+ # image == 1, video == 2
1174
+ else:
1175
+ grid_thw = next(grid_iters[modality_type])
1176
+ vision_position_ids = self.get_vision_position_ids(
1177
+ current_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device
1178
+ )
1179
+ llm_pos_ids_list.append(vision_position_ids)
1180
+ current_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size
1181
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1182
+ if attention_mask is not None:
1183
+ position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
1184
+ else:
1185
+ position_ids[:, batch_idx] = llm_positions.to(position_ids.device)
1186
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids))
1187
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
1188
+ return position_ids, mrope_position_deltas
1189
+
1190
+ @accepts_precomputed_kwargs(modality="image")
1191
+ @can_return_tuple
1192
+ @auto_docstring
1193
+ def get_image_features(
1194
+ self,
1195
+ pixel_values: torch.FloatTensor,
1196
+ image_grid_thw: torch.LongTensor | None = None,
1197
+ **kwargs: Unpack[TransformersKwargs],
1198
+ ) -> tuple | BaseModelOutputWithPooling:
1199
+ r"""
1200
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1201
+ The tensors corresponding to the input images.
1202
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1203
+ The temporal, height and width of feature shape of each image in LLM.
1204
+ """
1205
+ pixel_values = pixel_values.type(self.visual.dtype).unsqueeze(0)
1206
+ vision_outputs = self.visual(pixel_values=pixel_values, grid_thw=image_grid_thw, **kwargs)
1207
+ image_embeds = vision_outputs.last_hidden_state
1208
+ image_embeds = self.projector(image_embeds, image_grid_thw)
1209
+ vision_outputs.pooler_output = image_embeds
1210
+
1211
+ return vision_outputs
1212
+
1213
+ def get_placeholder_mask(
1214
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
1215
+ ):
1216
+ """
1217
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1218
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1219
+ """
1220
+ if input_ids is None:
1221
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1222
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1223
+ )
1224
+ special_image_mask = special_image_mask.all(-1)
1225
+ else:
1226
+ special_image_mask = input_ids == self.config.image_token_id
1227
+
1228
+ n_image_tokens = special_image_mask.sum()
1229
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1230
+ n_image_features = image_features.shape[0] * image_features.shape[1]
1231
+ torch_compilable_check(
1232
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
1233
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}",
1234
+ )
1235
+ return special_image_mask
1236
+
1237
+ def compute_3d_position_ids(
1238
+ self,
1239
+ input_ids: torch.Tensor | None,
1240
+ inputs_embeds: torch.Tensor | None,
1241
+ image_grid_thw: torch.Tensor | None = None,
1242
+ video_grid_thw: torch.Tensor | None = None,
1243
+ attention_mask: torch.Tensor | None = None,
1244
+ past_key_values: torch.Tensor | None = None,
1245
+ mm_token_type_ids: torch.IntTensor | None = None,
1246
+ ) -> torch.Tensor | None:
1247
+ past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length()
1248
+ has_multimodal = image_grid_thw is not None or video_grid_thw is not None
1249
+ if has_multimodal and mm_token_type_ids is None and input_ids is not None:
1250
+ raise ValueError(
1251
+ "Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
1252
+ "missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be "
1253
+ "computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`."
1254
+ )
1255
+ can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
1256
+
1257
+ if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0):
1258
+ position_ids, rope_deltas = self.get_rope_index(
1259
+ input_ids,
1260
+ image_grid_thw=image_grid_thw,
1261
+ video_grid_thw=video_grid_thw,
1262
+ attention_mask=attention_mask,
1263
+ mm_token_type_ids=mm_token_type_ids,
1264
+ )
1265
+ self.rope_deltas = rope_deltas
1266
+ # Use pre-calculated rope-deltas to infer correct 3D position ids during incremental
1267
+ # generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids
1268
+ # to recompute from). Skip when input_ids is provided without past_key_values to avoid shape
1269
+ # mismatches from stale rope_deltas (e.g., training forward pass after generation).
1270
+ elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None):
1271
+ batch_size, seq_length, _ = inputs_embeds.shape
1272
+ if attention_mask is not None:
1273
+ position_ids = attention_mask.long().cumsum(-1) - 1
1274
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
1275
+ position_ids = position_ids.view(1, batch_size, -1).repeat(3, 1, 1).to(inputs_embeds.device)
1276
+ else:
1277
+ position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length)
1278
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1).to(inputs_embeds.device)
1279
+ delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0)
1280
+ position_ids = position_ids + delta.to(device=inputs_embeds.device)
1281
+ else:
1282
+ # Can't build correct 3D positions. Let the model infer it
1283
+ position_ids = None
1284
+ return position_ids
1285
+
1286
+ @can_return_tuple
1287
+ def forward(
1288
+ self,
1289
+ input_ids: torch.LongTensor = None,
1290
+ attention_mask: torch.Tensor | None = None,
1291
+ position_ids: torch.LongTensor | None = None,
1292
+ past_key_values: list[torch.FloatTensor] | None = None,
1293
+ inputs_embeds: torch.FloatTensor | None = None,
1294
+ use_cache: bool | None = None,
1295
+ pixel_values: torch.Tensor | None = None,
1296
+ image_grid_thw: torch.LongTensor | None = None,
1297
+ mm_token_type_ids: torch.IntTensor | None = None,
1298
+ rope_deltas: torch.LongTensor | None = None,
1299
+ **kwargs,
1300
+ ) -> tuple | PaddleOCRVLModelOutputWithPast:
1301
+ r"""
1302
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1303
+ The temporal, height and width of feature shape of each image in LLM.
1304
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1305
+ The rope index difference between sequence length and multimodal rope.
1306
+ """
1307
+ if inputs_embeds is None:
1308
+ inputs_embeds = self.language_model.embed_tokens(input_ids)
1309
+
1310
+ if pixel_values is not None:
1311
+ image_embeds = self.get_image_features(
1312
+ pixel_values, image_grid_thw, return_dict=True, **kwargs
1313
+ ).pooler_output
1314
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
1315
+ image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds)
1316
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
1317
+
1318
+ if position_ids is None:
1319
+ position_ids = self.compute_3d_position_ids(
1320
+ input_ids=input_ids,
1321
+ image_grid_thw=image_grid_thw,
1322
+ inputs_embeds=inputs_embeds,
1323
+ attention_mask=attention_mask,
1324
+ past_key_values=past_key_values,
1325
+ mm_token_type_ids=mm_token_type_ids,
1326
+ )
1327
+
1328
+ outputs = self.language_model(
1329
+ input_ids=None,
1330
+ position_ids=position_ids,
1331
+ attention_mask=attention_mask,
1332
+ past_key_values=past_key_values,
1333
+ inputs_embeds=inputs_embeds,
1334
+ use_cache=use_cache,
1335
+ **kwargs,
1336
+ )
1337
+
1338
+ output = PaddleOCRVLModelOutputWithPast(
1339
+ last_hidden_state=outputs.last_hidden_state,
1340
+ past_key_values=outputs.past_key_values,
1341
+ hidden_states=outputs.hidden_states,
1342
+ attentions=outputs.attentions,
1343
+ rope_deltas=self.rope_deltas,
1344
+ )
1345
+
1346
+ return output
1347
+
1348
+
1349
+ class PaddleOCRVLForConditionalGeneration(PaddleOCRVLPreTrainedModel, GenerationMixin):
1350
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
1351
+ _keys_to_ignore_on_load_unexpected = ["packing_position_embedding", "vision_model.head"]
1352
+
1353
+ def __init__(self, config):
1354
+ super().__init__(config)
1355
+ self.model = PaddleOCRVLModel(config)
1356
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1357
+
1358
+ self.post_init()
1359
+
1360
+ @auto_docstring
1361
+ def get_image_features(
1362
+ self,
1363
+ pixel_values: torch.FloatTensor,
1364
+ image_grid_thw: torch.LongTensor | None = None,
1365
+ **kwargs: Unpack[TransformersKwargs],
1366
+ ) -> tuple | BaseModelOutputWithPooling:
1367
+ r"""
1368
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1369
+ The tensors corresponding to the input images.
1370
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1371
+ The temporal, height and width of feature shape of each image in LLM.
1372
+ """
1373
+ return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)
1374
+
1375
+ @can_return_tuple
1376
+ @auto_docstring
1377
+ def forward(
1378
+ self,
1379
+ input_ids: torch.LongTensor | None = None,
1380
+ attention_mask: torch.Tensor | None = None,
1381
+ position_ids: torch.LongTensor | None = None,
1382
+ past_key_values: Cache | None = None,
1383
+ inputs_embeds: torch.FloatTensor | None = None,
1384
+ labels: torch.LongTensor | None = None,
1385
+ use_cache: bool | None = None,
1386
+ pixel_values: torch.Tensor | None = None,
1387
+ image_grid_thw: torch.LongTensor | None = None,
1388
+ rope_deltas: torch.LongTensor | None = None,
1389
+ mm_token_type_ids: torch.IntTensor | None = None,
1390
+ logits_to_keep: int | torch.Tensor = 0,
1391
+ **kwargs: Unpack[TransformersKwargs],
1392
+ ) -> tuple | PaddleOCRVLCausalLMOutputWithPast:
1393
+ r"""
1394
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1395
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1396
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1397
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1398
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1399
+ The temporal, height and width of feature shape of each image in LLM.
1400
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1401
+ The rope index difference between sequence length and multimodal rope.
1402
+
1403
+ Example:
1404
+
1405
+ ```python
1406
+ >>> from transformers import AutoProcessor, PaddleOCRVLForConditionalGeneration
1407
+
1408
+ >>> model = PaddleOCRVLForConditionalGeneration.from_pretrained("PaddlePaddle/PaddleOCR-VL", dtype="bfloat16")
1409
+ >>> processor = AutoProcessor.from_pretrained("PaddlePaddle/PaddleOCR-VL")
1410
+
1411
+ >>> messages = [
1412
+ {
1413
+ "role": "user",
1414
+ "content": [
1415
+ {
1416
+ "type": "image",
1417
+ "image": "https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/ocr_demo.jpg",
1418
+ },
1419
+ {"type": "text", "text": "OCR:"},
1420
+ ],
1421
+ }
1422
+ ]
1423
+
1424
+ >>> inputs = processor.apply_chat_template(
1425
+ messages,
1426
+ tokenize=True,
1427
+ add_generation_prompt=True,
1428
+ return_dict=True,
1429
+ return_tensors="pt"
1430
+ ).to(model.device)
1431
+
1432
+ >>> # Generate
1433
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=1024)
1434
+ >>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
1435
+ >>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1436
+ >>> print(output_text)
1437
+ ```
1438
+ """
1439
+ outputs: PaddleOCRVLModelOutputWithPast = self.model(
1440
+ input_ids=input_ids,
1441
+ attention_mask=attention_mask,
1442
+ position_ids=position_ids,
1443
+ image_grid_thw=image_grid_thw,
1444
+ past_key_values=past_key_values,
1445
+ inputs_embeds=inputs_embeds,
1446
+ use_cache=use_cache,
1447
+ pixel_values=pixel_values,
1448
+ rope_deltas=rope_deltas,
1449
+ mm_token_type_ids=mm_token_type_ids,
1450
+ **kwargs,
1451
+ )
1452
+ hidden_states = outputs.last_hidden_state
1453
+
1454
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1455
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1456
+
1457
+ loss = None
1458
+ if labels is not None:
1459
+ loss = self.loss_function(
1460
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1461
+ )
1462
+
1463
+ return PaddleOCRVLCausalLMOutputWithPast(
1464
+ loss=loss,
1465
+ logits=logits,
1466
+ past_key_values=outputs.past_key_values,
1467
+ hidden_states=outputs.hidden_states,
1468
+ attentions=outputs.attentions,
1469
+ rope_deltas=outputs.rope_deltas,
1470
+ )
1471
+
1472
+ def prepare_inputs_for_generation(
1473
+ self,
1474
+ input_ids,
1475
+ past_key_values=None,
1476
+ attention_mask=None,
1477
+ inputs_embeds=None,
1478
+ position_ids=None,
1479
+ use_cache=True,
1480
+ pixel_values=None,
1481
+ pixel_values_videos=None,
1482
+ image_grid_thw=None,
1483
+ video_grid_thw=None,
1484
+ is_first_iteration=False,
1485
+ **kwargs,
1486
+ ):
1487
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1488
+
1489
+ model_inputs = super().prepare_inputs_for_generation(
1490
+ input_ids,
1491
+ past_key_values=past_key_values,
1492
+ attention_mask=attention_mask,
1493
+ inputs_embeds=inputs_embeds,
1494
+ position_ids=position_ids,
1495
+ pixel_values=pixel_values,
1496
+ pixel_values_videos=pixel_values_videos,
1497
+ image_grid_thw=image_grid_thw,
1498
+ video_grid_thw=video_grid_thw,
1499
+ use_cache=use_cache,
1500
+ is_first_iteration=is_first_iteration,
1501
+ **kwargs,
1502
+ )
1503
+
1504
+ if not is_first_iteration and use_cache:
1505
+ model_inputs["pixel_values"] = None
1506
+ model_inputs["pixel_values_videos"] = None
1507
+
1508
+ return model_inputs
1509
+
1510
+ def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
1511
+ # Overwritten -- requires 3D position ids
1512
+
1513
+ text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
1514
+
1515
+ # Early exit in case we are continuing generation from past kv
1516
+ past_length = 0
1517
+ if (cache := model_kwargs.get("past_key_values")) is not None:
1518
+ past_length = cache.get_seq_length()
1519
+ if past_length != 0 and self.model.rope_deltas is not None:
1520
+ position_ids = text_positions[None, ...] + self.model.rope_deltas
1521
+ return position_ids
1522
+
1523
+ # Otherwise compute 3d position ids for vision tokens and concat with text position ids
1524
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
1525
+ inputs_tensor = model_kwargs["input_ids"]
1526
+
1527
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
1528
+ if (
1529
+ is_input_ids
1530
+ and model_kwargs.get("mm_token_type_ids") is not None
1531
+ and (model_kwargs.get("image_grid_thw") is not None or model_kwargs.get("video_grid_thw") is not None)
1532
+ ):
1533
+ model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
1534
+ vision_positions, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
1535
+ self.model.rope_deltas = rope_deltas
1536
+ else:
1537
+ vision_positions = text_positions.unsqueeze(0).expand(3, -1, -1)
1538
+ self.model.rope_deltas = torch.zeros(
1539
+ inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device
1540
+ )
1541
+
1542
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
1543
+ text_positions = text_positions[None, ...]
1544
+ position_ids = torch.cat([text_positions, vision_positions], dim=0)
1545
+
1546
+ return position_ids
1547
+
1548
+ def _get_image_nums_and_video_nums(
1549
+ self,
1550
+ input_ids: torch.LongTensor | None,
1551
+ inputs_embeds: torch.Tensor | None = None,
1552
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1553
+ """
1554
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
1555
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
1556
+
1557
+ Args:
1558
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1559
+ Indices of input sequence tokens in the vocabulary.
1560
+
1561
+ Returns:
1562
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
1563
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
1564
+ """
1565
+ image_token_id = self.config.image_token_id
1566
+ video_token_id = self.config.video_token_id
1567
+ vision_start_token_id = self.config.vision_start_token_id
1568
+
1569
+ if inputs_embeds is not None:
1570
+ vision_start_mask = (
1571
+ inputs_embeds
1572
+ == self.get_input_embeddings()(
1573
+ torch.tensor(vision_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1574
+ )
1575
+ )[..., 0]
1576
+ image_mask = (
1577
+ inputs_embeds
1578
+ == self.get_input_embeddings()(
1579
+ torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
1580
+ )
1581
+ )[..., 0]
1582
+ video_mask = (
1583
+ inputs_embeds
1584
+ == self.get_input_embeddings()(
1585
+ torch.tensor(video_token_id, dtype=torch.long, device=inputs_embeds.device)
1586
+ )
1587
+ )[..., 0]
1588
+ else:
1589
+ vision_start_mask = input_ids == vision_start_token_id
1590
+ image_mask = input_ids == image_token_id
1591
+ video_mask = input_ids == video_token_id
1592
+
1593
+ vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1)
1594
+ image_nums = torch.sum(vision_first_mask & image_mask, dim=1)
1595
+ video_nums = torch.sum(vision_first_mask & video_mask, dim=1)
1596
+
1597
+ return image_nums, video_nums
1598
+
1599
+ def _expand_inputs_for_generation(
1600
+ self,
1601
+ expand_size: int = 1,
1602
+ is_encoder_decoder: bool = False,
1603
+ input_ids: torch.LongTensor | None = None,
1604
+ **model_kwargs,
1605
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
1606
+ # Overwritten -- Support for expanding tensors without a batch size dimension
1607
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
1608
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
1609
+ # image_grid_thw.shape[0] is sum(num_images for samples)
1610
+
1611
+ if expand_size == 1:
1612
+ return input_ids, model_kwargs
1613
+
1614
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
1615
+
1616
+ def _expand_dict_for_generation_visual(dict_to_expand):
1617
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1618
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
1619
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
1620
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
1621
+ )
1622
+
1623
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1624
+ samples = torch.split(x, lengths)
1625
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1626
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1627
+ return result
1628
+
1629
+ for key in dict_to_expand:
1630
+ if key == "pixel_values":
1631
+ # split images into samples
1632
+ samples = torch.split(image_grid_thw, list(image_nums))
1633
+ # compute the sequence length of images for each sample
1634
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1635
+ dict_to_expand[key] = _repeat_interleave_samples(
1636
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1637
+ )
1638
+ elif key == "image_grid_thw":
1639
+ # get the num of images for each sample
1640
+ lengths = list(image_nums)
1641
+ dict_to_expand[key] = _repeat_interleave_samples(
1642
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1643
+ )
1644
+ elif key == "pixel_values_videos":
1645
+ samples = torch.split(video_grid_thw, list(video_nums))
1646
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1647
+ dict_to_expand[key] = _repeat_interleave_samples(
1648
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1649
+ )
1650
+ elif key == "video_grid_thw":
1651
+ lengths = list(video_nums)
1652
+ dict_to_expand[key] = _repeat_interleave_samples(
1653
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1654
+ )
1655
+ elif key == "second_per_grid_ts":
1656
+ dict_to_expand[key] = _repeat_interleave_samples(
1657
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
1658
+ )
1659
+ return dict_to_expand
1660
+
1661
+ def _expand_dict_for_generation(dict_to_expand):
1662
+ for key in dict_to_expand:
1663
+ if key == "position_ids" and dict_to_expand[key].ndim == 3:
1664
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=1)
1665
+ elif (
1666
+ dict_to_expand[key] is not None
1667
+ and isinstance(dict_to_expand[key], torch.Tensor)
1668
+ and key not in visual_keys
1669
+ ):
1670
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1671
+ return dict_to_expand
1672
+
1673
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1674
+
1675
+ if input_ids is not None:
1676
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1677
+
1678
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1679
+
1680
+ if is_encoder_decoder:
1681
+ if model_kwargs.get("encoder_outputs") is None:
1682
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1683
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1684
+
1685
+ return input_ids, model_kwargs
1686
+
1687
+
1688
+ __all__ = [
1689
+ "PaddleOCRVLForConditionalGeneration",
1690
+ "PaddleOCRVLModel",
1691
+ "PaddleOCRVLPreTrainedModel",
1692
+ "PaddleOCRVisionTransformer",
1693
+ "PaddleOCRTextModel",
1694
+ "PaddleOCRVisionModel",
1695
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/configuration_perceiver.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Deepmind 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
+ """Perceiver 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="deepmind/language-perceiver")
23
+ @strict
24
+ class PerceiverConfig(PreTrainedConfig):
25
+ r"""
26
+ num_latents (`int`, *optional*, defaults to 256):
27
+ The number of latents.
28
+ d_latents (`int`, *optional*, defaults to 1280):
29
+ Dimension of the latent embeddings.
30
+ num_blocks (`int`, *optional*, defaults to 1):
31
+ Number of blocks in the Transformer encoder.
32
+ num_self_attends_per_block (`int`, *optional*, defaults to 26):
33
+ The number of self-attention layers per block.
34
+ num_self_attention_heads (`int`, *optional*, defaults to 8):
35
+ Number of attention heads for each self-attention layer in the Transformer encoder.
36
+ num_cross_attention_heads (`int`, *optional*, defaults to 8):
37
+ Number of attention heads for each cross-attention layer in the Transformer encoder.
38
+ qk_channels (`int`, *optional*):
39
+ Dimension to project the queries + keys before applying attention in the cross-attention and self-attention
40
+ layers of the encoder. Will default to preserving the dimension of the queries if not specified.
41
+ v_channels (`int`, *optional*):
42
+ Dimension to project the values before applying attention in the cross-attention and self-attention layers
43
+ of the encoder. Will default to preserving the dimension of the queries if not specified.
44
+ cross_attention_shape_for_attention (`str`, *optional*, defaults to `"kv"`):
45
+ Dimension to use when downsampling the queries and keys in the cross-attention layer of the encoder.
46
+ self_attention_widening_factor (`int`, *optional*, defaults to 1):
47
+ Dimension of the feed-forward layer in the cross-attention layer of the Transformer encoder.
48
+ cross_attention_widening_factor (`int`, *optional*, defaults to 1):
49
+ Dimension of the feed-forward layer in the self-attention layers of the Transformer encoder.
50
+ use_query_residual (`float`, *optional*, defaults to `True`):
51
+ Whether to add a query residual in the cross-attention layer of the encoder.
52
+ image_size (`int`, *optional*, defaults to 56):
53
+ Size of the images after preprocessing, for [`PerceiverForImageClassificationLearned`].
54
+ train_size (`list[int]`, *optional*, defaults to `[368, 496]`):
55
+ Training size of the images for the optical flow model.
56
+ num_frames (`int`, *optional*, defaults to 16):
57
+ Number of video frames used for the multimodal autoencoding model.
58
+ audio_samples_per_frame (`int`, *optional*, defaults to 1920):
59
+ Number of audio samples per frame for the multimodal autoencoding model.
60
+ samples_per_patch (`int`, *optional*, defaults to 16):
61
+ Number of audio samples per patch when preprocessing the audio for the multimodal autoencoding model.
62
+ output_shape (`list[int]`, *optional*, defaults to `[1, 16, 224, 224]`):
63
+ Shape of the output (batch_size, num_frames, height, width) for the video decoder queries of the multimodal
64
+ autoencoding model. This excludes the channel dimension.
65
+ output_num_channels (`int`, *optional*, defaults to 512):
66
+ Number of output channels for each modalitiy decoder.
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import PerceiverModel, PerceiverConfig
72
+
73
+ >>> # Initializing a Perceiver deepmind/language-perceiver style configuration
74
+ >>> configuration = PerceiverConfig()
75
+
76
+ >>> # Initializing a model from the deepmind/language-perceiver style configuration
77
+ >>> model = PerceiverModel(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "perceiver"
84
+
85
+ num_latents: int = 256
86
+ d_latents: int = 1280
87
+ d_model: int = 768
88
+ num_blocks: int = 1
89
+ num_self_attends_per_block: int = 26
90
+ num_self_attention_heads: int = 8
91
+ num_cross_attention_heads: int = 8
92
+ qk_channels: int | None = None
93
+ v_channels: int | None = None
94
+ cross_attention_shape_for_attention: str = "kv"
95
+ self_attention_widening_factor: int = 1
96
+ cross_attention_widening_factor: int = 1
97
+ hidden_act: str = "gelu"
98
+ attention_probs_dropout_prob: float | int = 0.1
99
+ initializer_range: float = 0.02
100
+ layer_norm_eps: float = 1e-12
101
+ use_query_residual: bool = True
102
+ vocab_size: int = 262
103
+ max_position_embeddings: int = 2048
104
+ image_size: int | list[int] | tuple[int, int] = 56
105
+ train_size: list[int] | tuple[int, ...] = (368, 496)
106
+ num_frames: int = 16
107
+ audio_samples_per_frame: int = 1920
108
+ samples_per_patch: int = 16
109
+ output_shape: list[int] | tuple[int, ...] = (1, 16, 224, 224)
110
+ output_num_channels: int = 512
111
+ _label_trainable_num_channels: int = 1024
112
+
113
+
114
+ __all__ = ["PerceiverConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/image_processing_perceiver.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Image processor class for Perceiver."""
15
+
16
+ import torch
17
+ from torchvision.transforms.v2 import functional as tvF
18
+
19
+ from ...image_processing_backends import TorchvisionBackend
20
+ from ...image_processing_utils import BatchFeature
21
+ from ...image_transforms import group_images_by_shape, reorder_images
22
+ from ...image_utils import (
23
+ IMAGENET_DEFAULT_MEAN,
24
+ IMAGENET_DEFAULT_STD,
25
+ PILImageResampling,
26
+ SizeDict,
27
+ )
28
+ from ...processing_utils import ImagesKwargs, Unpack
29
+ from ...utils import TensorType, auto_docstring
30
+
31
+
32
+ @auto_docstring
33
+ class PerceiverImageProcessor(TorchvisionBackend):
34
+ """Torchvision backend for Perceiver with custom center crop."""
35
+
36
+ resample = PILImageResampling.BICUBIC
37
+ image_mean = IMAGENET_DEFAULT_MEAN
38
+ image_std = IMAGENET_DEFAULT_STD
39
+ size = {"height": 224, "width": 224}
40
+ crop_size = {"height": 256, "width": 256}
41
+ do_resize = True
42
+ do_center_crop = True
43
+ do_rescale = True
44
+ do_normalize = True
45
+
46
+ def __init__(self, **kwargs: Unpack[ImagesKwargs]):
47
+ super().__init__(**kwargs)
48
+
49
+ def center_crop(
50
+ self,
51
+ image: "torch.Tensor",
52
+ size: SizeDict,
53
+ crop_size: SizeDict,
54
+ **kwargs,
55
+ ) -> "torch.Tensor":
56
+ """
57
+ Center crop an image to ((size.height / crop_size.height) * min_dim, (size.width / crop_size.width) * min_dim),
58
+ where min_dim is the minimum of the image height and width.
59
+ If the requested crop size exceeds the image dimensions along any edge, the image is padded with zeros before
60
+ center cropping.
61
+ """
62
+ if size.height is None or size.width is None:
63
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
64
+ if crop_size.height is None or crop_size.width is None:
65
+ raise ValueError(f"The crop_size dictionary must have keys 'height' and 'width'. Got {crop_size.keys()}")
66
+ height, width = image.shape[-2:]
67
+ min_dim = min(height, width)
68
+ cropped_height = int((size.height / crop_size.height) * min_dim)
69
+ cropped_width = int((size.width / crop_size.width) * min_dim)
70
+ return super().center_crop(
71
+ image,
72
+ SizeDict(height=cropped_height, width=cropped_width),
73
+ **kwargs,
74
+ )
75
+
76
+ def _preprocess(
77
+ self,
78
+ images: list["torch.Tensor"],
79
+ do_resize: bool,
80
+ size: SizeDict,
81
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
82
+ do_center_crop: bool,
83
+ crop_size: SizeDict,
84
+ do_rescale: bool,
85
+ rescale_factor: float,
86
+ do_normalize: bool,
87
+ image_mean: float | list[float] | None,
88
+ image_std: float | list[float] | None,
89
+ do_pad: bool | None,
90
+ pad_size: SizeDict | None,
91
+ disable_grouping: bool | None,
92
+ return_tensors: str | TensorType | None,
93
+ **kwargs,
94
+ ) -> BatchFeature:
95
+ """Custom preprocessing for Perceiver: center_crop -> resize -> rescale and normalize."""
96
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
97
+ cropped_images_grouped = {}
98
+ for shape, stacked_images in grouped_images.items():
99
+ if do_center_crop:
100
+ stacked_images = self.center_crop(stacked_images, size=size, crop_size=crop_size)
101
+ cropped_images_grouped[shape] = stacked_images
102
+ cropped_images = reorder_images(cropped_images_grouped, grouped_images_index)
103
+
104
+ grouped_images, grouped_images_index = group_images_by_shape(cropped_images, disable_grouping=disable_grouping)
105
+ resized_images_grouped = {}
106
+ for shape, stacked_images in grouped_images.items():
107
+ if do_resize:
108
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
109
+ resized_images_grouped[shape] = stacked_images
110
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
111
+
112
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
113
+ processed_images_grouped = {}
114
+ for shape, stacked_images in grouped_images.items():
115
+ stacked_images = self.rescale_and_normalize(
116
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
117
+ )
118
+ processed_images_grouped[shape] = stacked_images
119
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
120
+
121
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
122
+
123
+
124
+ __all__ = ["PerceiverImageProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/image_processing_pil_perceiver.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Image processor class for Perceiver."""
15
+
16
+ import numpy as np
17
+
18
+ from ...image_processing_backends import PilBackend
19
+ from ...image_processing_utils import BatchFeature
20
+ from ...image_utils import (
21
+ IMAGENET_DEFAULT_MEAN,
22
+ IMAGENET_DEFAULT_STD,
23
+ PILImageResampling,
24
+ SizeDict,
25
+ )
26
+ from ...processing_utils import ImagesKwargs, Unpack
27
+ from ...utils import TensorType, auto_docstring
28
+
29
+
30
+ @auto_docstring
31
+ class PerceiverImageProcessorPil(PilBackend):
32
+ """PIL backend for Perceiver with custom center crop."""
33
+
34
+ resample = PILImageResampling.BICUBIC
35
+ image_mean = IMAGENET_DEFAULT_MEAN
36
+ image_std = IMAGENET_DEFAULT_STD
37
+ size = {"height": 224, "width": 224}
38
+ crop_size = {"height": 256, "width": 256}
39
+ do_resize = True
40
+ do_center_crop = True
41
+ do_rescale = True
42
+ do_normalize = True
43
+
44
+ def __init__(self, **kwargs: Unpack[ImagesKwargs]):
45
+ super().__init__(**kwargs)
46
+
47
+ def center_crop(
48
+ self,
49
+ image: np.ndarray,
50
+ size: SizeDict,
51
+ crop_size: SizeDict,
52
+ **kwargs,
53
+ ) -> np.ndarray:
54
+ """
55
+ Center crop an image to ((size.height / crop_size.height) * min_dim, (size.width / crop_size.width) * min_dim),
56
+ where min_dim is the minimum of the image height and width.
57
+ If the requested crop size exceeds the image dimensions along any edge, the image is padded with zeros before
58
+ center cropping.
59
+ """
60
+ if size.height is None or size.width is None:
61
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
62
+ if crop_size.height is None or crop_size.width is None:
63
+ raise ValueError(f"The crop_size dictionary must have keys 'height' and 'width'. Got {crop_size.keys()}")
64
+ height, width = image.shape[-2:]
65
+ min_dim = min(height, width)
66
+ cropped_height = int((size.height / crop_size.height) * min_dim)
67
+ cropped_width = int((size.width / crop_size.width) * min_dim)
68
+ return super().center_crop(
69
+ image,
70
+ SizeDict(height=cropped_height, width=cropped_width),
71
+ **kwargs,
72
+ )
73
+
74
+ def _preprocess(
75
+ self,
76
+ images: list[np.ndarray],
77
+ do_resize: bool,
78
+ size: SizeDict,
79
+ resample: "PILImageResampling | None",
80
+ do_center_crop: bool,
81
+ crop_size: SizeDict,
82
+ do_rescale: bool,
83
+ rescale_factor: float,
84
+ do_normalize: bool,
85
+ image_mean: float | list[float] | None,
86
+ image_std: float | list[float] | None,
87
+ do_pad: bool | None,
88
+ pad_size: SizeDict | None,
89
+ return_tensors: str | TensorType | None,
90
+ **kwargs,
91
+ ) -> BatchFeature:
92
+ """Custom preprocessing for Perceiver: center_crop -> resize -> rescale and normalize."""
93
+ processed_images = []
94
+ for image in images:
95
+ if do_center_crop:
96
+ image = self.center_crop(image, size=size, crop_size=crop_size)
97
+ if do_resize:
98
+ image = self.resize(image=image, size=size, resample=resample)
99
+ if do_rescale:
100
+ image = self.rescale(image, rescale_factor)
101
+ if do_normalize:
102
+ image = self.normalize(image, image_mean, image_std)
103
+ processed_images.append(image)
104
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
105
+
106
+
107
+ __all__ = ["PerceiverImageProcessorPil"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/modeling_perceiver.py ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/perceiver/tokenization_perceiver.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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 Perceiver."""
15
+
16
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class PerceiverTokenizer(PreTrainedTokenizer):
24
+ """
25
+ Construct a Perceiver tokenizer. The Perceiver simply uses raw bytes utf-8 encoding.
26
+
27
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
28
+ this superclass for more information regarding those methods.
29
+
30
+ Args:
31
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
32
+ The token used for padding, for example when batching sequences of different lengths.
33
+ bos_token (`str`, *optional*, defaults to `"[BOS]"`):
34
+ The BOS token (reserved in the vocab, but not actually used).
35
+ eos_token (`str`, *optional*, defaults to `"[EOS]"`):
36
+ The end of sequence token (reserved in the vocab, but not actually used).
37
+
38
+ <Tip>
39
+
40
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
41
+ The token used is the `sep_token`.
42
+
43
+ </Tip>
44
+
45
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
46
+ The MASK token, useful for masked language modeling.
47
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
48
+ The CLS token (reserved in the vocab, but not actually used).
49
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
50
+ The separator token, which is used when building a sequence from two sequences.
51
+
52
+ """
53
+
54
+ model_input_names = ["input_ids", "attention_mask"]
55
+
56
+ def __init__(
57
+ self,
58
+ pad_token="[PAD]",
59
+ bos_token="[BOS]",
60
+ eos_token="[EOS]",
61
+ mask_token="[MASK]",
62
+ cls_token="[CLS]",
63
+ sep_token="[SEP]",
64
+ model_max_length=2048,
65
+ **kwargs,
66
+ ) -> None:
67
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
68
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
69
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
70
+ mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
71
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
72
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
73
+
74
+ self._utf_vocab_size = 2**8 # utf is 8 bits
75
+
76
+ # Since these tokens are not part of the vocabulary, we manually add them
77
+ self._added_tokens_decoder: dict[str, int] = {
78
+ 0: pad_token,
79
+ 1: bos_token,
80
+ 2: eos_token,
81
+ 3: mask_token,
82
+ 4: cls_token,
83
+ 5: sep_token,
84
+ }
85
+ self._num_special_tokens = len(self._added_tokens_decoder)
86
+ super().__init__(
87
+ pad_token=pad_token,
88
+ bos_token=bos_token,
89
+ eos_token=eos_token,
90
+ mask_token=mask_token,
91
+ cls_token=cls_token,
92
+ sep_token=sep_token,
93
+ model_max_length=model_max_length,
94
+ **kwargs,
95
+ )
96
+
97
+ def get_vocab(self) -> dict[str, int]:
98
+ vocab = {}
99
+ for i in range(self._utf_vocab_size):
100
+ token = chr(i)
101
+ vocab[token] = i + self._num_special_tokens
102
+ vocab.update(self.added_tokens_encoder)
103
+ return vocab
104
+
105
+ @property
106
+ def vocab_size(self):
107
+ return self._utf_vocab_size
108
+
109
+ def get_special_tokens_mask(
110
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
111
+ ) -> list[int]:
112
+ """
113
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
114
+ special tokens using the tokenizer `prepare_for_model` method.
115
+
116
+ Args:
117
+ token_ids_0 (`list[int]`):
118
+ List of IDs.
119
+ token_ids_1 (`list[int]`, *optional*):
120
+ Optional second list of IDs for sequence pairs.
121
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
122
+ Whether or not the token list is already formatted with special tokens for the model.
123
+
124
+ Returns:
125
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
126
+ """
127
+ if already_has_special_tokens:
128
+ return super().get_special_tokens_mask(
129
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
130
+ )
131
+
132
+ # normal case: some special tokens
133
+ if token_ids_1 is None:
134
+ return [1] + [0] * len(token_ids_0) + [1]
135
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
136
+
137
+ def build_inputs_with_special_tokens(
138
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
139
+ ) -> list[int]:
140
+ """
141
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks. A sequence has the
142
+ following format:
143
+
144
+ - single sequence: `[CLS] X [SEP]`
145
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
146
+
147
+ Args:
148
+ token_ids_0 (`list[int]`):
149
+ List of IDs to which the special tokens will be added.
150
+ token_ids_1 (`list[int]`, *optional*):
151
+ Optional second list of IDs for sequence pairs.
152
+
153
+ Returns:
154
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
155
+ """
156
+ if token_ids_1 is None:
157
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
158
+ else:
159
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1 + [self.sep_token_id]
160
+
161
+ def _tokenize(self, text: str) -> list[str]:
162
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
163
+ tokens = [chr(i) for i in text.encode("utf-8")]
164
+ return tokens
165
+
166
+ def _convert_token_to_id(self, token):
167
+ """Converts a token (str) in an id using the vocab."""
168
+ if len(token) != 1:
169
+ token_id = self.unk_token_id
170
+ else:
171
+ token_id = ord(token) + self._num_special_tokens
172
+ return token_id
173
+
174
+ def _convert_id_to_token(self, index):
175
+ """Converts an index (integer) in a token (str) using the vocab."""
176
+ token = chr(index - self._num_special_tokens)
177
+ return token
178
+
179
+ # TODO @ArthurZ refactor this as well....
180
+ def convert_tokens_to_string(self, tokens):
181
+ """Converts a sequence of tokens (string) in a single string."""
182
+ bstring = b""
183
+ for token in tokens:
184
+ if token in self.added_tokens_encoder:
185
+ tok_string = str(token).encode("utf-8")
186
+ else:
187
+ tok_string = bytes([ord(token)])
188
+ bstring += tok_string
189
+ string = bstring.decode("utf-8", errors="replace")
190
+ return string
191
+
192
+ # PerceiverTokenizer has no vocab file
193
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
194
+ return ()
195
+
196
+
197
+ __all__ = ["PerceiverTokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_swin import *
22
+ from .modeling_swin 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/configuration_swin.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Swin Transformer model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...backbone_utils import BackboneConfigMixin
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="microsoft/swin-tiny-patch4-window7-224")
24
+ @strict
25
+ class SwinConfig(BackboneConfigMixin, PreTrainedConfig):
26
+ r"""
27
+ depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
28
+ Depth of each layer in the Transformer encoder.
29
+ num_heads (`list(int)`, *optional*, defaults to `[3, 6, 12, 24]`):
30
+ Number of attention heads in each layer of the Transformer encoder.
31
+ window_size (`int`, *optional*, defaults to 7):
32
+ Size of windows.
33
+ encoder_stride (`int`, *optional*, defaults to 32):
34
+ Factor to increase the spatial resolution by in the decoder head for masked image modeling.
35
+
36
+ Example:
37
+
38
+ ```python
39
+ >>> from transformers import SwinConfig, SwinModel
40
+
41
+ >>> # Initializing a Swin microsoft/swin-tiny-patch4-window7-224 style configuration
42
+ >>> configuration = SwinConfig()
43
+
44
+ >>> # Initializing a model (with random weights) from the microsoft/swin-tiny-patch4-window7-224 style configuration
45
+ >>> model = SwinModel(configuration)
46
+
47
+ >>> # Accessing the model configuration
48
+ >>> configuration = model.config
49
+ ```"""
50
+
51
+ model_type = "swin"
52
+
53
+ attribute_map = {
54
+ "num_attention_heads": "num_heads",
55
+ "num_hidden_layers": "num_layers",
56
+ }
57
+
58
+ image_size: int | list[int] | tuple[int, int] = 224
59
+ patch_size: int | list[int] | tuple[int, int] = 4
60
+ num_channels: int = 3
61
+ embed_dim: int = 96
62
+ depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)
63
+ num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24)
64
+ window_size: int = 7
65
+ mlp_ratio: float | int = 4.0
66
+ qkv_bias: bool = True
67
+ hidden_dropout_prob: float | int = 0.0
68
+ attention_probs_dropout_prob: float | int = 0.0
69
+ drop_path_rate: float | int = 0.1
70
+ hidden_act: str = "gelu"
71
+ use_absolute_embeddings: bool = False
72
+ initializer_range: float = 0.02
73
+ layer_norm_eps: float = 1e-5
74
+ encoder_stride: int = 32
75
+ _out_features: list[str] | None = None
76
+ _out_indices: list[int] | None = None
77
+
78
+ def __post_init__(self, **kwargs):
79
+ self.num_layers = len(self.depths)
80
+ # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
81
+ # this indicates the channel dimension after the last stage of the model
82
+ self.hidden_size = int(self.embed_dim * 2 ** (len(self.depths) - 1))
83
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
84
+ self.set_output_features_output_indices(
85
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
86
+ )
87
+ super().__post_init__(**kwargs)
88
+
89
+
90
+ __all__ = ["SwinConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/modeling_swin.py ADDED
@@ -0,0 +1,1163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/swin/modular_swin.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_swin.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2022 Microsoft Research 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 collections.abc
22
+ import math
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass
25
+
26
+ import torch
27
+ from torch import nn
28
+
29
+ from ... import initialization as init
30
+ from ...activations import ACT2FN
31
+ from ...backbone_utils import BackboneMixin, filter_output_hidden_states
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import BackboneOutput
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
35
+ from ...processing_utils import Unpack
36
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_int
37
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
38
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
39
+ from .configuration_swin import SwinConfig
40
+
41
+
42
+ class SwinDropPath(nn.Module):
43
+ """Stochastic depth (DropPath) per sample, for residual blocks.
44
+
45
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
46
+ <https://arxiv.org/abs/1603.09382>`_.
47
+ """
48
+
49
+ def __init__(self, drop_prob: float = 0.0) -> None:
50
+ super().__init__()
51
+ self.drop_prob = drop_prob
52
+
53
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
54
+ if self.drop_prob == 0.0 or not self.training:
55
+ return hidden_states
56
+ keep_prob = 1 - self.drop_prob
57
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
58
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
59
+ random_tensor = torch.floor(random_tensor + keep_prob)
60
+ return hidden_states.div(keep_prob) * random_tensor
61
+
62
+ def extra_repr(self) -> str:
63
+ return f"p={self.drop_prob}"
64
+
65
+
66
+ @auto_docstring(
67
+ custom_intro="""
68
+ Swin encoder's outputs, with potential hidden states and attentions.
69
+ """
70
+ )
71
+ @dataclass
72
+ class SwinEncoderOutput(ModelOutput):
73
+ r"""
74
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
75
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
76
+ shape `(batch_size, hidden_size, height, width)`.
77
+
78
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
79
+ include the spatial dimensions.
80
+ """
81
+
82
+ last_hidden_state: torch.FloatTensor | None = None
83
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
84
+ attentions: tuple[torch.FloatTensor, ...] | None = None
85
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
86
+
87
+
88
+ @auto_docstring(
89
+ custom_intro="""
90
+ Swin model's outputs that also contains a pooling of the last hidden states.
91
+ """
92
+ )
93
+ @dataclass
94
+ class SwinModelOutput(ModelOutput):
95
+ r"""
96
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
97
+ Average pooling of the last layer hidden-state.
98
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
99
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
100
+ shape `(batch_size, hidden_size, height, width)`.
101
+
102
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
103
+ include the spatial dimensions.
104
+ """
105
+
106
+ last_hidden_state: torch.FloatTensor | None = None
107
+ pooler_output: torch.FloatTensor | None = None
108
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
109
+ attentions: tuple[torch.FloatTensor, ...] | None = None
110
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
111
+
112
+
113
+ @auto_docstring(
114
+ custom_intro="""
115
+ Swin masked image model outputs.
116
+ """
117
+ )
118
+ @dataclass
119
+ class SwinMaskedImageModelingOutput(ModelOutput):
120
+ r"""
121
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
122
+ Masked image modeling (MLM) loss.
123
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
124
+ Reconstructed pixel values.
125
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
126
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
127
+ shape `(batch_size, hidden_size, height, width)`.
128
+
129
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
130
+ include the spatial dimensions.
131
+ """
132
+
133
+ loss: torch.FloatTensor | None = None
134
+ reconstruction: torch.FloatTensor | None = None
135
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
136
+ attentions: tuple[torch.FloatTensor, ...] | None = None
137
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
138
+
139
+
140
+ @auto_docstring(
141
+ custom_intro="""
142
+ Swin outputs for image classification.
143
+ """
144
+ )
145
+ @dataclass
146
+ class SwinImageClassifierOutput(ModelOutput):
147
+ r"""
148
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
149
+ Classification (or regression if config.num_labels==1) loss.
150
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
151
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
152
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
153
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
154
+ shape `(batch_size, hidden_size, height, width)`.
155
+
156
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
157
+ include the spatial dimensions.
158
+ """
159
+
160
+ loss: torch.FloatTensor | None = None
161
+ logits: torch.FloatTensor | None = None
162
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
163
+ attentions: tuple[torch.FloatTensor, ...] | None = None
164
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
165
+
166
+
167
+ class SwinEmbeddings(nn.Module):
168
+ """
169
+ Construct the patch and position embeddings. Optionally, also the mask token.
170
+ """
171
+
172
+ def __init__(self, config, use_mask_token=False):
173
+ super().__init__()
174
+
175
+ self.patch_embeddings = SwinPatchEmbeddings(config)
176
+ num_patches = self.patch_embeddings.num_patches
177
+ self.patch_grid = self.patch_embeddings.grid_size
178
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
179
+
180
+ self.position_embeddings = (
181
+ nn.Parameter(torch.zeros(1, num_patches, config.embed_dim)) if config.use_absolute_embeddings else None
182
+ )
183
+
184
+ self.norm = nn.LayerNorm(config.embed_dim)
185
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
186
+ self.patch_size = config.patch_size
187
+ self.config = config
188
+
189
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
190
+ """
191
+ Interpolate pre-trained position encodings to support higher-resolution images at inference.
192
+ Unlike ViT, Swin has no CLS token, so position embeddings cover patch positions only.
193
+ """
194
+ num_patches = embeddings.shape[1]
195
+ num_positions = self.position_embeddings.shape[1]
196
+
197
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
198
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
199
+ return self.position_embeddings
200
+
201
+ dim = embeddings.shape[-1]
202
+
203
+ new_height = height // self.patch_size
204
+ new_width = width // self.patch_size
205
+
206
+ sqrt_num_positions = torch_int(num_positions**0.5)
207
+ patch_pos_embed = self.position_embeddings.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
208
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
209
+
210
+ patch_pos_embed = nn.functional.interpolate(
211
+ patch_pos_embed,
212
+ size=(new_height, new_width),
213
+ mode="bicubic",
214
+ align_corners=False,
215
+ )
216
+
217
+ return patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
218
+
219
+ def forward(
220
+ self,
221
+ pixel_values: torch.FloatTensor | None,
222
+ bool_masked_pos: torch.BoolTensor | None = None,
223
+ interpolate_pos_encoding: bool = False,
224
+ ) -> tuple[torch.Tensor]:
225
+ _, num_channels, height, width = pixel_values.shape
226
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
227
+ embeddings = self.norm(embeddings)
228
+ batch_size, seq_len, _ = embeddings.size()
229
+
230
+ if bool_masked_pos is not None:
231
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
232
+ # replace the masked visual tokens by mask_tokens
233
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
234
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
235
+
236
+ if self.position_embeddings is not None:
237
+ if interpolate_pos_encoding:
238
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
239
+ else:
240
+ embeddings = embeddings + self.position_embeddings
241
+
242
+ embeddings = self.dropout(embeddings)
243
+
244
+ return embeddings, output_dimensions
245
+
246
+
247
+ class SwinPatchEmbeddings(nn.Module):
248
+ """
249
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
250
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
251
+ Transformer.
252
+ """
253
+
254
+ def __init__(self, config):
255
+ super().__init__()
256
+ image_size, patch_size = config.image_size, config.patch_size
257
+ num_channels, hidden_size = config.num_channels, config.embed_dim
258
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
259
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
260
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
261
+ self.patch_size = patch_size
262
+ self.num_patches = num_patches
263
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
264
+
265
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
266
+
267
+ def maybe_pad(self, pixel_values, height, width):
268
+ """Pad pixel_values to be divisible by patch_size if needed."""
269
+ if width % self.patch_size[1] != 0:
270
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
271
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
272
+ if height % self.patch_size[0] != 0:
273
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
274
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
275
+ return pixel_values
276
+
277
+ def forward(self, pixel_values: torch.FloatTensor | None) -> tuple[torch.Tensor, tuple[int]]:
278
+ _, num_channels, height, width = pixel_values.shape
279
+ # pad the input to be divisible by self.patch_size, if needed
280
+ pixel_values = self.maybe_pad(pixel_values, height, width)
281
+ embeddings = self.projection(pixel_values)
282
+ _, _, height, width = embeddings.shape
283
+ output_dimensions = (height, width)
284
+ embeddings = embeddings.flatten(2).transpose(1, 2)
285
+
286
+ return embeddings, output_dimensions
287
+
288
+
289
+ class SwinPatchMerging(nn.Module):
290
+ """
291
+ Patch Merging Layer.
292
+
293
+ Args:
294
+ dim (`int`):
295
+ Number of input channels.
296
+ """
297
+
298
+ def __init__(self, dim: int) -> None:
299
+ super().__init__()
300
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
301
+ self.norm = nn.LayerNorm(4 * dim)
302
+
303
+ def maybe_pad(self, input_feature: torch.Tensor, height: int, width: int) -> torch.Tensor:
304
+ """Pad input feature map to be divisible by 2 in both spatial dimensions if needed."""
305
+ if (height % 2 == 1) or (width % 2 == 1):
306
+ input_feature = nn.functional.pad(input_feature, (0, 0, 0, width % 2, 0, height % 2))
307
+ return input_feature
308
+
309
+ def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor:
310
+ height, width = input_dimensions
311
+ # `dim` is height * width
312
+ batch_size, dim, num_channels = input_feature.shape
313
+
314
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
315
+ # pad input to be divisible by width and height, if needed
316
+ input_feature = self.maybe_pad(input_feature, height, width)
317
+ # Interleave rows and columns to produce [batch_size, height/2*width/2, 4*num_channels]
318
+ input_feature = torch.cat(
319
+ [input_feature[:, row::2, col::2, :] for col in range(2) for row in range(2)], dim=-1
320
+ )
321
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels)
322
+
323
+ input_feature = self.norm(input_feature)
324
+ input_feature = self.reduction(input_feature)
325
+
326
+ return input_feature
327
+
328
+
329
+ class SwinRelativePositionBias(nn.Module):
330
+ """
331
+ Relative position bias for Swin's window-based attention, following the style of BeitRelativePositionBias.
332
+
333
+ Unlike BeiT, Swin has no CLS token, so the table covers exactly (2*ws_h-1)*(2*ws_w-1) unique
334
+ relative positions. The lookup index is purely determined by window_size (static), so it is stored
335
+ as a non-persistent buffer (recomputed from config on load, never serialised). The table values
336
+ are learned parameters and must be re-read on every forward call.
337
+ """
338
+
339
+ def __init__(self, num_heads: int, window_size: tuple[int, int]):
340
+ super().__init__()
341
+ self.window_size = window_size
342
+ self.window_area = window_size[0] * window_size[1]
343
+ self.relative_position_bias_table = nn.Parameter(
344
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
345
+ )
346
+ # Non-persistent: fully determined by window_size, no need to serialise.
347
+ # Stored flat so forward avoids an extra .view() call.
348
+ self.register_buffer(
349
+ "relative_position_index",
350
+ self._create_relative_position_index().view(-1),
351
+ persistent=False,
352
+ )
353
+
354
+ def _create_relative_position_index(self) -> torch.Tensor:
355
+ coords_h = torch.arange(self.window_size[0])
356
+ coords_w = torch.arange(self.window_size[1])
357
+
358
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # 2, Wh, Ww
359
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
360
+
361
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
362
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
363
+
364
+ # shift to start from 0 and compute a unique flat index for each (dh, dw) pair
365
+ relative_coords[:, :, 0] += self.window_size[0] - 1
366
+ relative_coords[:, :, 1] += self.window_size[1] - 1
367
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
368
+
369
+ return relative_coords.sum(-1) # Wh*Ww, Wh*Ww
370
+
371
+ def forward(self) -> torch.Tensor:
372
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index]
373
+ relative_position_bias = relative_position_bias.view(self.window_area, self.window_area, -1)
374
+ return relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) # 1, num_heads, Wh*Ww, Wh*Ww
375
+
376
+
377
+ def eager_attention_forward(
378
+ module: nn.Module,
379
+ query: torch.Tensor,
380
+ key: torch.Tensor,
381
+ value: torch.Tensor,
382
+ attention_mask: torch.Tensor | None,
383
+ scaling: float | None = None,
384
+ dropout: float = 0.0,
385
+ **kwargs: Unpack[TransformersKwargs],
386
+ ):
387
+ if scaling is None:
388
+ scaling = query.size(-1) ** -0.5
389
+
390
+ # Take the dot product between "query" and "key" to get the raw attention scores.
391
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
392
+
393
+ if attention_mask is not None:
394
+ attn_weights = attn_weights + attention_mask
395
+
396
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
397
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
398
+
399
+ attn_output = torch.matmul(attn_weights, value)
400
+ attn_output = attn_output.transpose(1, 2).contiguous()
401
+
402
+ return attn_output, attn_weights
403
+
404
+
405
+ class SwinAttention(nn.Module):
406
+ def __init__(self, config: SwinConfig, hidden_size: int, num_attention_heads: int, window_size: int):
407
+ super().__init__()
408
+ self.config = config
409
+ self.num_attention_heads = num_attention_heads
410
+ self.head_dim = hidden_size // num_attention_heads
411
+ self.attention_dropout = config.attention_probs_dropout_prob
412
+ self.scaling = self.head_dim**-0.5
413
+ self.is_causal = False
414
+
415
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
416
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
417
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
418
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
419
+
420
+ self.relative_position_bias = SwinRelativePositionBias(num_attention_heads, (window_size, window_size))
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ attention_mask: torch.FloatTensor | None = None,
426
+ **kwargs: Unpack[TransformersKwargs],
427
+ ) -> tuple[torch.Tensor, torch.Tensor]:
428
+ # hidden_states: (batch_size * num_windows, window_size * window_size, channels)
429
+ input_shape = hidden_states.shape[:-1]
430
+ hidden_shape = (*input_shape, -1, self.head_dim)
431
+
432
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
433
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
434
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
435
+
436
+ # Combine relative position bias with the cyclic-shift attention mask for SW-MSA
437
+ relative_position_bias = self.relative_position_bias() # 1, num_heads, ws*ws, ws*ws
438
+ if attention_mask is not None:
439
+ # attention_mask: (num_windows, ws*ws, ws*ws)
440
+ num_windows = attention_mask.shape[0]
441
+ batch_size = input_shape[0] // num_windows
442
+ seq_len = input_shape[1]
443
+ # Expand to (batch * num_windows, 1, ws*ws, ws*ws) for broadcasting
444
+ attention_mask = (
445
+ attention_mask.unsqueeze(1) # (num_windows, 1, ws*ws, ws*ws)
446
+ .unsqueeze(0) # (1, num_windows, 1, ws*ws, ws*ws)
447
+ .expand(batch_size, -1, -1, -1, -1) # (batch, num_windows, 1, ws*ws, ws*ws)
448
+ .reshape(-1, 1, seq_len, seq_len) # (batch * num_windows, 1, ws*ws, ws*ws)
449
+ )
450
+ combined_mask = relative_position_bias + attention_mask
451
+ else:
452
+ combined_mask = relative_position_bias
453
+
454
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
455
+ self.config._attn_implementation, eager_attention_forward
456
+ )
457
+
458
+ attn_output, attn_weights = attention_interface(
459
+ self,
460
+ query_states,
461
+ key_states,
462
+ value_states,
463
+ combined_mask,
464
+ dropout=0.0 if not self.training else self.attention_dropout,
465
+ scaling=self.scaling,
466
+ **kwargs,
467
+ )
468
+
469
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
470
+ attn_output = self.o_proj(attn_output)
471
+
472
+ return attn_output, attn_weights
473
+
474
+
475
+ class SwinMLP(nn.Module):
476
+ def __init__(self, config: SwinConfig, dim: int):
477
+ super().__init__()
478
+ self.activation_fn = ACT2FN[config.hidden_act]
479
+ self.fc1 = nn.Linear(dim, int(config.mlp_ratio * dim))
480
+ self.fc2 = nn.Linear(int(config.mlp_ratio * dim), dim)
481
+
482
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
483
+ hidden_states = self.fc1(hidden_states)
484
+ hidden_states = self.activation_fn(hidden_states)
485
+ hidden_states = self.fc2(hidden_states)
486
+
487
+ return hidden_states
488
+
489
+
490
+ def window_partition(input_feature, window_size):
491
+ """
492
+ Partitions the given input into windows.
493
+ """
494
+ batch_size, height, width, num_channels = input_feature.shape
495
+ input_feature = input_feature.view(
496
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
497
+ )
498
+ windows = input_feature.transpose(2, 3).contiguous().view(-1, window_size, window_size, num_channels)
499
+ return windows
500
+
501
+
502
+ def window_reverse(windows, window_size, height, width):
503
+ """
504
+ Merges windows to produce higher resolution features.
505
+ """
506
+ num_channels = windows.shape[-1]
507
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
508
+ windows = windows.transpose(2, 3).contiguous().view(-1, height, width, num_channels)
509
+ return windows
510
+
511
+
512
+ class SwinLayer(GradientCheckpointingLayer):
513
+ def __init__(
514
+ self,
515
+ config: SwinConfig,
516
+ dim: int,
517
+ input_resolution: tuple[int, int],
518
+ num_heads: int,
519
+ drop_path_rate: float = 0.0,
520
+ shift_size: int = 0,
521
+ ):
522
+ super().__init__()
523
+ self.attention = SwinAttention(config, dim, num_heads, window_size=config.window_size)
524
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
525
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
526
+ self.mlp = SwinMLP(config, dim)
527
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
528
+ self.window_size = config.window_size
529
+ self.shift_size = shift_size
530
+ self.input_resolution = input_resolution
531
+ self.drop_path = SwinDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
532
+
533
+ def forward(
534
+ self,
535
+ hidden_states: torch.Tensor,
536
+ input_dimensions: tuple[int, int],
537
+ always_partition: bool = False,
538
+ **kwargs: Unpack[TransformersKwargs],
539
+ ) -> torch.Tensor:
540
+ if not always_partition:
541
+ self.set_shift_and_window_size(input_dimensions)
542
+ height, width = input_dimensions
543
+ batch_size, _, channels = hidden_states.size()
544
+ shortcut = hidden_states
545
+
546
+ hidden_states = self.layernorm_before(hidden_states)
547
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
548
+
549
+ # pad hidden_states to multiples of window size
550
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
551
+ _, height_pad, width_pad, _ = hidden_states.shape
552
+
553
+ hidden_states_windows = window_partition(self.cyclic_shift(hidden_states), self.window_size)
554
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
555
+ attn_mask = self.get_attn_mask(
556
+ height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
557
+ )
558
+
559
+ attention_output, attn_weights = self.attention(hidden_states_windows, attn_mask, **kwargs)
560
+ attention_output = self.dropout(attention_output)
561
+
562
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
563
+ attention_windows = self.cyclic_shift(
564
+ window_reverse(attention_windows, self.window_size, height_pad, width_pad), reverse=True
565
+ )
566
+
567
+ if pad_values[3] > 0 or pad_values[5] > 0:
568
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
569
+
570
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
571
+ hidden_states = shortcut + self.drop_path(attention_windows)
572
+
573
+ residual = hidden_states
574
+ hidden_states = self.layernorm_after(hidden_states)
575
+ hidden_states = self.mlp(hidden_states)
576
+ hidden_states = self.dropout(hidden_states) + residual
577
+
578
+ return hidden_states, attn_weights
579
+
580
+ def set_shift_and_window_size(self, input_resolution: tuple[int, int]) -> None:
581
+ """Clamp window and shift sizes when the window is larger than the input resolution."""
582
+ if min(input_resolution) <= self.window_size:
583
+ self.shift_size = torch_int(0)
584
+ self.window_size = (
585
+ torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
586
+ )
587
+
588
+ def get_attn_mask(self, height: int, width: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor | None:
589
+ """Build the cyclic-shift attention mask for shifted-window MSA; returns None when shift_size is 0."""
590
+ if self.shift_size > 0:
591
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
592
+ height_slices = (
593
+ slice(0, -self.window_size),
594
+ slice(-self.window_size, -self.shift_size),
595
+ slice(-self.shift_size, None),
596
+ )
597
+ width_slices = (
598
+ slice(0, -self.window_size),
599
+ slice(-self.window_size, -self.shift_size),
600
+ slice(-self.shift_size, None),
601
+ )
602
+ count = 0
603
+ for height_slice in height_slices:
604
+ for width_slice in width_slices:
605
+ img_mask[:, height_slice, width_slice, :] = count
606
+ count += 1
607
+
608
+ mask_windows = window_partition(img_mask, self.window_size)
609
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
610
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
611
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0)
612
+ else:
613
+ attn_mask = None
614
+ return attn_mask
615
+
616
+ def maybe_pad(self, hidden_states: torch.Tensor, height: int, width: int) -> tuple[torch.Tensor, tuple[int, ...]]:
617
+ """Pad feature map so both spatial dimensions are divisible by window_size."""
618
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
619
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
620
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
621
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
622
+ return hidden_states, pad_values
623
+
624
+ def cyclic_shift(self, hidden_states: torch.Tensor, reverse: bool = False) -> torch.Tensor:
625
+ """Apply a cyclic shift along the spatial dimensions for shifted-window attention."""
626
+ if self.shift_size > 0:
627
+ direction = 1 if reverse else -1
628
+ hidden_states = torch.roll(
629
+ hidden_states,
630
+ shifts=(direction * self.shift_size, direction * self.shift_size),
631
+ dims=(1, 2),
632
+ )
633
+ return hidden_states
634
+
635
+
636
+ class SwinStage(GradientCheckpointingLayer):
637
+ def __init__(
638
+ self,
639
+ config: SwinConfig,
640
+ dim: int,
641
+ input_resolution: tuple[int, int],
642
+ depth: int,
643
+ num_heads: int,
644
+ drop_path: list[float],
645
+ downsample,
646
+ ):
647
+ super().__init__()
648
+ self.config = config
649
+ self.blocks = nn.ModuleList(
650
+ [
651
+ SwinLayer(
652
+ config=config,
653
+ dim=dim,
654
+ input_resolution=input_resolution,
655
+ num_heads=num_heads,
656
+ drop_path_rate=drop_path[i],
657
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
658
+ )
659
+ for i in range(depth)
660
+ ]
661
+ )
662
+
663
+ self.downsample = downsample(dim=dim) if downsample is not None else None
664
+
665
+ def get_reshaped_hidden_states(
666
+ self,
667
+ hidden_states: torch.Tensor,
668
+ hidden_states_before_downsampling: torch.Tensor,
669
+ height: int,
670
+ width: int,
671
+ output_hidden_states_before_downsampling: bool,
672
+ ) -> torch.Tensor:
673
+ """
674
+ Select the spatial hidden states for this stage and reshape from (B, L, C) to (B, C, H, W).
675
+
676
+ The chosen state and its resolution depend on output_hidden_states_before_downsampling:
677
+ - True → pre-downsampling states at (height, width) — used by the backbone.
678
+ - False → post-downsampling states at half the resolution (if a downsampler exists).
679
+ """
680
+ if output_hidden_states_before_downsampling:
681
+ spatial_state, h, w = hidden_states_before_downsampling, height, width
682
+ elif self.downsample is not None:
683
+ spatial_state, h, w = hidden_states, (height + 1) // 2, (width + 1) // 2
684
+ else:
685
+ spatial_state, h, w = hidden_states, height, width
686
+
687
+ batch_size, _, hidden_size = spatial_state.shape
688
+ return spatial_state.view(batch_size, h, w, hidden_size).permute(0, 3, 1, 2).contiguous()
689
+
690
+ def forward(
691
+ self,
692
+ hidden_states: torch.Tensor,
693
+ input_dimensions: tuple[int, int],
694
+ always_partition: bool = False,
695
+ output_hidden_states_before_downsampling: bool = False,
696
+ **kwargs: Unpack[TransformersKwargs],
697
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
698
+ height, width = input_dimensions
699
+ last_attn_weights = None
700
+ for layer_module in self.blocks:
701
+ hidden_states, last_attn_weights = layer_module(
702
+ hidden_states, input_dimensions, always_partition=always_partition, **kwargs
703
+ )
704
+
705
+ hidden_states_before_downsampling = hidden_states
706
+ if self.downsample is not None:
707
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
708
+
709
+ reshaped_hidden_states = self.get_reshaped_hidden_states(
710
+ hidden_states, hidden_states_before_downsampling, height, width, output_hidden_states_before_downsampling
711
+ )
712
+
713
+ return hidden_states, reshaped_hidden_states, last_attn_weights
714
+
715
+
716
+ @auto_docstring
717
+ class SwinPreTrainedModel(PreTrainedModel):
718
+ config: SwinConfig
719
+ base_model_prefix = "swin"
720
+ main_input_name = "pixel_values"
721
+ input_modalities = ("image",)
722
+ supports_gradient_checkpointing = True
723
+ _no_split_modules = ["SwinStage"]
724
+ _supports_sdpa = True
725
+ _supports_flash_attn = False
726
+ _supports_flex_attn = False
727
+ _supports_attention_backend = True
728
+ _can_compile_fullgraph = True
729
+ _can_record_outputs = {
730
+ # capture_initial_hidden_state=True: prepend the embedding input (args[0] of SwinStage 0) so that
731
+ # hidden_states[0] has the same shape as the patch embeddings (num_patches, embed_dim).
732
+ "hidden_states": OutputRecorder(SwinStage, index=0, capture_initial_hidden_state=True),
733
+ # reshaped_hidden_states are collected explicitly by SwinEncoder (per stage) and the stem
734
+ # is prepended in SwinModel.forward, so they are NOT captured via hooks here.
735
+ # index=2: SwinStage returns (hidden_states, reshaped_hidden_states, last_attn_weights);
736
+ # capture the last block's attention weights at index 2, giving one entry per stage.
737
+ "attentions": OutputRecorder(SwinStage, index=2, capture_initial_hidden_state=False),
738
+ }
739
+ _input_embed_layer = "patch_embeddings"
740
+ # relative_position_index is now a non-persistent buffer (recomputed from window_size in __init__).
741
+ _keys_to_ignore_on_load_unexpected = [
742
+ r"attention\.self\.relative_position_index",
743
+ r"attention\.relative_position_bias\.relative_position_index",
744
+ ]
745
+
746
+ @torch.no_grad()
747
+ def _init_weights(self, module):
748
+ """Initialize the weights"""
749
+ super()._init_weights(module)
750
+ if isinstance(module, SwinEmbeddings):
751
+ if module.mask_token is not None:
752
+ init.zeros_(module.mask_token)
753
+ if module.position_embeddings is not None:
754
+ init.zeros_(module.position_embeddings)
755
+ elif isinstance(module, SwinRelativePositionBias):
756
+ init.zeros_(module.relative_position_bias_table)
757
+ init.copy_(module.relative_position_index, module._create_relative_position_index().view(-1))
758
+
759
+
760
+ class SwinEncoder(SwinPreTrainedModel):
761
+ def __init__(self, config: SwinConfig, grid_size: tuple[int, int]):
762
+ super().__init__(config)
763
+ self.num_layers = len(config.depths)
764
+ self.config = config
765
+ dpr = [config.drop_path_rate * i / max(sum(config.depths) - 1, 1) for i in range(sum(config.depths))]
766
+ self.layers = nn.ModuleList(
767
+ [
768
+ SwinStage(
769
+ config=config,
770
+ dim=int(config.embed_dim * 2**layer_idx),
771
+ input_resolution=(grid_size[0] // (2**layer_idx), grid_size[1] // (2**layer_idx)),
772
+ depth=config.depths[layer_idx],
773
+ num_heads=config.num_heads[layer_idx],
774
+ drop_path=dpr[sum(config.depths[:layer_idx]) : sum(config.depths[: layer_idx + 1])],
775
+ downsample=SwinPatchMerging if (layer_idx < self.num_layers - 1) else None,
776
+ )
777
+ for layer_idx in range(self.num_layers)
778
+ ]
779
+ )
780
+ self.post_init()
781
+
782
+ @merge_with_config_defaults
783
+ @capture_outputs(tie_last_hidden_states=False)
784
+ @auto_docstring
785
+ def forward(
786
+ self,
787
+ hidden_states: torch.Tensor,
788
+ input_dimensions: tuple[int, int],
789
+ always_partition: bool = False,
790
+ output_hidden_states: bool = False,
791
+ output_hidden_states_before_downsampling: bool = False,
792
+ **kwargs: Unpack[TransformersKwargs],
793
+ ) -> SwinEncoderOutput:
794
+ r"""
795
+ input_dimensions (`tuple[int, int]`):
796
+ Spatial `(height, width)` of the patch grid entering the encoder.
797
+ always_partition (`bool`, *optional*, defaults to `False`):
798
+ If `True`, always apply window partitioning regardless of input resolution.
799
+ output_hidden_states_before_downsampling (`bool`, *optional*, defaults to `False`):
800
+ If `True`, `reshaped_hidden_states` contains pre-downsampling feature maps.
801
+ """
802
+ all_reshaped_hidden_states = None
803
+ if output_hidden_states:
804
+ # Prepend the stem: hidden_states is the patch embedding output (B, N, C),
805
+ # reshape it to spatial (B, C, H, W) as the first reshaped hidden state.
806
+ batch_size, _, hidden_size = hidden_states.shape
807
+ stem_spatial = (
808
+ hidden_states.view(batch_size, *input_dimensions, hidden_size).permute(0, 3, 1, 2).contiguous()
809
+ )
810
+ all_reshaped_hidden_states = (stem_spatial,)
811
+
812
+ for layer_module in self.layers:
813
+ hidden_states, reshaped_hidden_state, _ = layer_module(
814
+ hidden_states,
815
+ input_dimensions,
816
+ always_partition=always_partition,
817
+ output_hidden_states_before_downsampling=output_hidden_states_before_downsampling,
818
+ **kwargs,
819
+ )
820
+ if output_hidden_states:
821
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
822
+ if layer_module.downsample is not None:
823
+ input_dimensions = ((input_dimensions[0] + 1) // 2, (input_dimensions[1] + 1) // 2)
824
+
825
+ return SwinEncoderOutput(
826
+ last_hidden_state=hidden_states,
827
+ reshaped_hidden_states=all_reshaped_hidden_states,
828
+ )
829
+
830
+
831
+ @auto_docstring
832
+ class SwinModel(SwinPreTrainedModel):
833
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
834
+ r"""
835
+ add_pooling_layer (`bool`, *optional*, defaults to `True`):
836
+ Whether or not to apply pooling layer.
837
+ use_mask_token (`bool`, *optional*, defaults to `False`):
838
+ Whether or not to create and apply mask tokens in the embedding layer.
839
+ """
840
+ super().__init__(config)
841
+ self.config = config
842
+ self.num_layers = len(config.depths)
843
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
844
+
845
+ self.embeddings = SwinEmbeddings(config, use_mask_token=use_mask_token)
846
+ self.encoder = SwinEncoder(config, self.embeddings.patch_grid)
847
+
848
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
849
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
850
+
851
+ # Initialize weights and apply final processing
852
+ self.post_init()
853
+
854
+ @can_return_tuple
855
+ @auto_docstring
856
+ def forward(
857
+ self,
858
+ pixel_values: torch.FloatTensor | None = None,
859
+ bool_masked_pos: torch.BoolTensor | None = None,
860
+ interpolate_pos_encoding: bool = False,
861
+ **kwargs: Unpack[TransformersKwargs],
862
+ ) -> SwinModelOutput:
863
+ r"""
864
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
865
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
866
+ """
867
+ # FIXME: output_hidden_states must be popped manually here because SwinEncoder takes it as an
868
+ # explicit argument (not via **kwargs), so it is not captured by the @capture_outputs decorator.
869
+ output_hidden_states = kwargs.pop("output_hidden_states", self.config.output_hidden_states)
870
+
871
+ embedding_output, input_dimensions = self.embeddings(
872
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
873
+ )
874
+
875
+ encoder_outputs = self.encoder(
876
+ embedding_output,
877
+ input_dimensions,
878
+ output_hidden_states=output_hidden_states,
879
+ **kwargs,
880
+ )
881
+
882
+ sequence_output = encoder_outputs.last_hidden_state
883
+ sequence_output = self.layernorm(sequence_output)
884
+
885
+ pooled_output = None
886
+ if self.pooler is not None:
887
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
888
+ pooled_output = torch.flatten(pooled_output, 1)
889
+
890
+ return SwinModelOutput(
891
+ last_hidden_state=sequence_output,
892
+ pooler_output=pooled_output,
893
+ hidden_states=encoder_outputs.hidden_states,
894
+ attentions=encoder_outputs.attentions,
895
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
896
+ )
897
+
898
+
899
+ @auto_docstring(
900
+ custom_intro="""
901
+ Swin Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).
902
+
903
+ <Tip>
904
+
905
+ Note that we provide a script to pre-train this model on custom data in our [examples
906
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
907
+
908
+ </Tip>
909
+ """
910
+ )
911
+ class SwinForMaskedImageModeling(SwinPreTrainedModel):
912
+ def __init__(self, config):
913
+ super().__init__(config)
914
+
915
+ self.swin = SwinModel(config, add_pooling_layer=False, use_mask_token=True)
916
+
917
+ num_features = int(config.embed_dim * 2 ** (config.num_layers - 1))
918
+ self.decoder = nn.Sequential(
919
+ nn.Conv2d(
920
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
921
+ ),
922
+ nn.PixelShuffle(config.encoder_stride),
923
+ )
924
+
925
+ # Initialize weights and apply final processing
926
+ self.post_init()
927
+
928
+ @can_return_tuple
929
+ @auto_docstring
930
+ def forward(
931
+ self,
932
+ pixel_values: torch.FloatTensor | None = None,
933
+ bool_masked_pos: torch.BoolTensor | None = None,
934
+ interpolate_pos_encoding: bool = False,
935
+ **kwargs: Unpack[TransformersKwargs],
936
+ ) -> SwinMaskedImageModelingOutput:
937
+ r"""
938
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
939
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
940
+
941
+ Examples:
942
+ ```python
943
+ >>> from transformers import AutoImageProcessor, SwinForMaskedImageModeling
944
+ >>> import torch
945
+ >>> from PIL import Image
946
+ >>> import httpx
947
+ >>> from io import BytesIO
948
+
949
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
950
+ >>> with httpx.stream("GET", url) as response:
951
+ ... image = Image.open(BytesIO(response.read()))
952
+
953
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-base-simmim-window6-192")
954
+ >>> model = SwinForMaskedImageModeling.from_pretrained("microsoft/swin-base-simmim-window6-192")
955
+
956
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
957
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
958
+ >>> # create random boolean mask of shape (batch_size, num_patches)
959
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
960
+
961
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
962
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
963
+ >>> list(reconstructed_pixel_values.shape)
964
+ [1, 3, 192, 192]
965
+ ```"""
966
+ outputs = self.swin(
967
+ pixel_values,
968
+ bool_masked_pos=bool_masked_pos,
969
+ interpolate_pos_encoding=interpolate_pos_encoding,
970
+ **kwargs,
971
+ )
972
+
973
+ sequence_output = outputs.last_hidden_state
974
+ # Reshape to (batch_size, num_channels, height, width)
975
+ sequence_output = sequence_output.transpose(1, 2)
976
+ batch_size, num_channels, sequence_length = sequence_output.shape
977
+ height = width = math.floor(sequence_length**0.5)
978
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
979
+
980
+ # Reconstruct pixel values
981
+ reconstructed_pixel_values = self.decoder(sequence_output)
982
+
983
+ masked_im_loss = None
984
+ if bool_masked_pos is not None:
985
+ size = self.config.image_size // self.config.patch_size
986
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
987
+ mask = (
988
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
989
+ .repeat_interleave(self.config.patch_size, 2)
990
+ .unsqueeze(1)
991
+ .contiguous()
992
+ )
993
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
994
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
995
+
996
+ return SwinMaskedImageModelingOutput(
997
+ loss=masked_im_loss,
998
+ reconstruction=reconstructed_pixel_values,
999
+ hidden_states=outputs.hidden_states,
1000
+ attentions=outputs.attentions,
1001
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1002
+ )
1003
+
1004
+
1005
+ @auto_docstring(
1006
+ custom_intro="""
1007
+ Swin Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
1008
+ the [CLS] token) e.g. for ImageNet.
1009
+
1010
+ <Tip>
1011
+
1012
+ Note that it's possible to fine-tune Swin on higher resolution images than the ones it has been trained on, by
1013
+ setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
1014
+ position embeddings to the higher resolution.
1015
+
1016
+ </Tip>
1017
+ """
1018
+ )
1019
+ class SwinForImageClassification(SwinPreTrainedModel):
1020
+ def __init__(self, config):
1021
+ super().__init__(config)
1022
+
1023
+ self.num_labels = config.num_labels
1024
+ self.swin = SwinModel(config)
1025
+
1026
+ # Classifier head
1027
+ self.classifier = (
1028
+ nn.Linear(self.swin.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
1029
+ )
1030
+
1031
+ # Initialize weights and apply final processing
1032
+ self.post_init()
1033
+
1034
+ @can_return_tuple
1035
+ @auto_docstring
1036
+ def forward(
1037
+ self,
1038
+ pixel_values: torch.FloatTensor | None = None,
1039
+ labels: torch.LongTensor | None = None,
1040
+ interpolate_pos_encoding: bool = False,
1041
+ **kwargs: Unpack[TransformersKwargs],
1042
+ ) -> SwinImageClassifierOutput:
1043
+ r"""
1044
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1045
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1046
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1047
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1048
+ """
1049
+ outputs = self.swin(
1050
+ pixel_values,
1051
+ interpolate_pos_encoding=interpolate_pos_encoding,
1052
+ **kwargs,
1053
+ )
1054
+
1055
+ pooled_output = outputs.pooler_output
1056
+
1057
+ logits = self.classifier(pooled_output)
1058
+
1059
+ loss = None
1060
+ if labels is not None:
1061
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
1062
+
1063
+ return SwinImageClassifierOutput(
1064
+ loss=loss,
1065
+ logits=logits,
1066
+ hidden_states=outputs.hidden_states,
1067
+ attentions=outputs.attentions,
1068
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1069
+ )
1070
+
1071
+
1072
+ @auto_docstring(
1073
+ custom_intro="""
1074
+ Swin backbone, to be used with frameworks like DETR and MaskFormer.
1075
+ """
1076
+ )
1077
+ class SwinBackbone(BackboneMixin, SwinPreTrainedModel):
1078
+ _keys_to_ignore_on_load_missing = [r"swin.layernorm.*"]
1079
+
1080
+ def __init__(self, config: SwinConfig):
1081
+ super().__init__(config)
1082
+
1083
+ self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
1084
+ self.swin = SwinModel(config, add_pooling_layer=False)
1085
+
1086
+ # Add layer norms to hidden states of out_features
1087
+ hidden_states_norms = {}
1088
+ for stage, num_channels in zip(self.out_features, self.channels):
1089
+ hidden_states_norms[stage] = nn.LayerNorm(num_channels)
1090
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
1091
+
1092
+ # Initialize weights and apply final processing
1093
+ self.post_init()
1094
+
1095
+ @can_return_tuple
1096
+ @filter_output_hidden_states
1097
+ @auto_docstring
1098
+ def forward(
1099
+ self,
1100
+ pixel_values: torch.Tensor,
1101
+ **kwargs: Unpack[TransformersKwargs],
1102
+ ) -> BackboneOutput:
1103
+ r"""
1104
+ Examples:
1105
+
1106
+ ```python
1107
+ >>> from transformers import AutoImageProcessor, AutoBackbone
1108
+ >>> import torch
1109
+ >>> from PIL import Image
1110
+ >>> import httpx
1111
+ >>> from io import BytesIO
1112
+
1113
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1114
+ >>> with httpx.stream("GET", url) as response:
1115
+ ... image = Image.open(BytesIO(response.read()))
1116
+
1117
+ >>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
1118
+ >>> model = AutoBackbone.from_pretrained(
1119
+ ... "microsoft/swin-tiny-patch4-window7-224", out_features=["stage1", "stage2", "stage3", "stage4"]
1120
+ ... )
1121
+
1122
+ >>> inputs = processor(image, return_tensors="pt")
1123
+ >>> outputs = model(**inputs)
1124
+ >>> feature_maps = outputs.feature_maps
1125
+ >>> list(feature_maps[-1].shape)
1126
+ [1, 768, 7, 7]
1127
+ ```
1128
+ """
1129
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
1130
+ # always_partition=True preserves shifted-window attention at all resolutions.
1131
+ # output_hidden_states_before_downsampling=True captures pre-downsampling feature maps per stage.
1132
+ outputs = self.swin(
1133
+ pixel_values,
1134
+ always_partition=True,
1135
+ output_hidden_states_before_downsampling=True,
1136
+ **kwargs,
1137
+ )
1138
+
1139
+ feature_maps = ()
1140
+ for stage, hidden_state in zip(self.stage_names, outputs.reshaped_hidden_states):
1141
+ if stage in self.out_features:
1142
+ batch_size, num_channels, height, width = hidden_state.shape
1143
+ hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous()
1144
+ hidden_state = hidden_state.view(batch_size, height * width, num_channels)
1145
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
1146
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
1147
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
1148
+ feature_maps += (hidden_state,)
1149
+
1150
+ return BackboneOutput(
1151
+ feature_maps=feature_maps,
1152
+ hidden_states=outputs.reshaped_hidden_states,
1153
+ attentions=outputs.attentions,
1154
+ )
1155
+
1156
+
1157
+ __all__ = [
1158
+ "SwinForImageClassification",
1159
+ "SwinForMaskedImageModeling",
1160
+ "SwinModel",
1161
+ "SwinPreTrainedModel",
1162
+ "SwinBackbone",
1163
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/swin/modular_swin.py ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Microsoft Research 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
+ """PyTorch Swin Transformer model."""
15
+
16
+ import collections.abc
17
+ import math
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ... import initialization as init
25
+ from ...activations import ACT2FN
26
+ from ...backbone_utils import BackboneMixin, filter_output_hidden_states
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import BackboneOutput
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
30
+ from ...processing_utils import Unpack
31
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging, torch_int
32
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
33
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
34
+ from ..vit.modeling_vit import (
35
+ PreTrainedModel,
36
+ ViTAttention,
37
+ ViTLayer,
38
+ ViTMLP,
39
+ ViTPreTrainedModel,
40
+ eager_attention_forward,
41
+ )
42
+ from .configuration_swin import SwinConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class SwinDropPath(nn.Module):
49
+ """Stochastic depth (DropPath) per sample, for residual blocks.
50
+
51
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
52
+ <https://arxiv.org/abs/1603.09382>`_.
53
+ """
54
+
55
+ def __init__(self, drop_prob: float = 0.0) -> None:
56
+ super().__init__()
57
+ self.drop_prob = drop_prob
58
+
59
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
60
+ if self.drop_prob == 0.0 or not self.training:
61
+ return hidden_states
62
+ keep_prob = 1 - self.drop_prob
63
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
64
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
65
+ random_tensor = torch.floor(random_tensor + keep_prob)
66
+ return hidden_states.div(keep_prob) * random_tensor
67
+
68
+ def extra_repr(self) -> str:
69
+ return f"p={self.drop_prob}"
70
+
71
+
72
+ @auto_docstring(
73
+ custom_intro="""
74
+ Swin encoder's outputs, with potential hidden states and attentions.
75
+ """
76
+ )
77
+ @dataclass
78
+ class SwinEncoderOutput(ModelOutput):
79
+ r"""
80
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
81
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
82
+ shape `(batch_size, hidden_size, height, width)`.
83
+
84
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
85
+ include the spatial dimensions.
86
+ """
87
+
88
+ last_hidden_state: torch.FloatTensor | None = None
89
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
90
+ attentions: tuple[torch.FloatTensor, ...] | None = None
91
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
92
+
93
+
94
+ @auto_docstring(
95
+ custom_intro="""
96
+ Swin model's outputs that also contains a pooling of the last hidden states.
97
+ """
98
+ )
99
+ @dataclass
100
+ class SwinModelOutput(ModelOutput):
101
+ r"""
102
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
103
+ Average pooling of the last layer hidden-state.
104
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
105
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
106
+ shape `(batch_size, hidden_size, height, width)`.
107
+
108
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
109
+ include the spatial dimensions.
110
+ """
111
+
112
+ last_hidden_state: torch.FloatTensor | None = None
113
+ pooler_output: torch.FloatTensor | None = None
114
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
115
+ attentions: tuple[torch.FloatTensor, ...] | None = None
116
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
117
+
118
+
119
+ @auto_docstring(
120
+ custom_intro="""
121
+ Swin masked image model outputs.
122
+ """
123
+ )
124
+ @dataclass
125
+ class SwinMaskedImageModelingOutput(ModelOutput):
126
+ r"""
127
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
128
+ Masked image modeling (MLM) loss.
129
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
130
+ Reconstructed pixel values.
131
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
132
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
133
+ shape `(batch_size, hidden_size, height, width)`.
134
+
135
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
136
+ include the spatial dimensions.
137
+ """
138
+
139
+ loss: torch.FloatTensor | None = None
140
+ reconstruction: torch.FloatTensor | None = None
141
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
142
+ attentions: tuple[torch.FloatTensor, ...] | None = None
143
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
144
+
145
+
146
+ @auto_docstring(
147
+ custom_intro="""
148
+ Swin outputs for image classification.
149
+ """
150
+ )
151
+ @dataclass
152
+ class SwinImageClassifierOutput(ModelOutput):
153
+ r"""
154
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
155
+ Classification (or regression if config.num_labels==1) loss.
156
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
157
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
158
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
159
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
160
+ shape `(batch_size, hidden_size, height, width)`.
161
+
162
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
163
+ include the spatial dimensions.
164
+ """
165
+
166
+ loss: torch.FloatTensor | None = None
167
+ logits: torch.FloatTensor | None = None
168
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
169
+ attentions: tuple[torch.FloatTensor, ...] | None = None
170
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
171
+
172
+
173
+ def window_partition(input_feature, window_size):
174
+ """
175
+ Partitions the given input into windows.
176
+ """
177
+ batch_size, height, width, num_channels = input_feature.shape
178
+ input_feature = input_feature.view(
179
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
180
+ )
181
+ windows = input_feature.transpose(2, 3).contiguous().view(-1, window_size, window_size, num_channels)
182
+ return windows
183
+
184
+
185
+ def window_reverse(windows, window_size, height, width):
186
+ """
187
+ Merges windows to produce higher resolution features.
188
+ """
189
+ num_channels = windows.shape[-1]
190
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
191
+ windows = windows.transpose(2, 3).contiguous().view(-1, height, width, num_channels)
192
+ return windows
193
+
194
+
195
+ class SwinEmbeddings(nn.Module):
196
+ """
197
+ Construct the patch and position embeddings. Optionally, also the mask token.
198
+ """
199
+
200
+ def __init__(self, config, use_mask_token=False):
201
+ super().__init__()
202
+
203
+ self.patch_embeddings = SwinPatchEmbeddings(config)
204
+ num_patches = self.patch_embeddings.num_patches
205
+ self.patch_grid = self.patch_embeddings.grid_size
206
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
207
+
208
+ self.position_embeddings = (
209
+ nn.Parameter(torch.zeros(1, num_patches, config.embed_dim)) if config.use_absolute_embeddings else None
210
+ )
211
+
212
+ self.norm = nn.LayerNorm(config.embed_dim)
213
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
214
+ self.patch_size = config.patch_size
215
+ self.config = config
216
+
217
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
218
+ """
219
+ Interpolate pre-trained position encodings to support higher-resolution images at inference.
220
+ Unlike ViT, Swin has no CLS token, so position embeddings cover patch positions only.
221
+ """
222
+ num_patches = embeddings.shape[1]
223
+ num_positions = self.position_embeddings.shape[1]
224
+
225
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
226
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
227
+ return self.position_embeddings
228
+
229
+ dim = embeddings.shape[-1]
230
+
231
+ new_height = height // self.patch_size
232
+ new_width = width // self.patch_size
233
+
234
+ sqrt_num_positions = torch_int(num_positions**0.5)
235
+ patch_pos_embed = self.position_embeddings.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
236
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
237
+
238
+ patch_pos_embed = nn.functional.interpolate(
239
+ patch_pos_embed,
240
+ size=(new_height, new_width),
241
+ mode="bicubic",
242
+ align_corners=False,
243
+ )
244
+
245
+ return patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
246
+
247
+ def forward(
248
+ self,
249
+ pixel_values: torch.FloatTensor | None,
250
+ bool_masked_pos: torch.BoolTensor | None = None,
251
+ interpolate_pos_encoding: bool = False,
252
+ ) -> tuple[torch.Tensor]:
253
+ _, num_channels, height, width = pixel_values.shape
254
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
255
+ embeddings = self.norm(embeddings)
256
+ batch_size, seq_len, _ = embeddings.size()
257
+
258
+ if bool_masked_pos is not None:
259
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
260
+ # replace the masked visual tokens by mask_tokens
261
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
262
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
263
+
264
+ if self.position_embeddings is not None:
265
+ if interpolate_pos_encoding:
266
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
267
+ else:
268
+ embeddings = embeddings + self.position_embeddings
269
+
270
+ embeddings = self.dropout(embeddings)
271
+
272
+ return embeddings, output_dimensions
273
+
274
+
275
+ class SwinPatchEmbeddings(nn.Module):
276
+ """
277
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
278
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
279
+ Transformer.
280
+ """
281
+
282
+ def __init__(self, config):
283
+ super().__init__()
284
+ image_size, patch_size = config.image_size, config.patch_size
285
+ num_channels, hidden_size = config.num_channels, config.embed_dim
286
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
287
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
288
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
289
+ self.patch_size = patch_size
290
+ self.num_patches = num_patches
291
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
292
+
293
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
294
+
295
+ def maybe_pad(self, pixel_values, height, width):
296
+ """Pad pixel_values to be divisible by patch_size if needed."""
297
+ if width % self.patch_size[1] != 0:
298
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
299
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
300
+ if height % self.patch_size[0] != 0:
301
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
302
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
303
+ return pixel_values
304
+
305
+ def forward(self, pixel_values: torch.FloatTensor | None) -> tuple[torch.Tensor, tuple[int]]:
306
+ _, num_channels, height, width = pixel_values.shape
307
+ # pad the input to be divisible by self.patch_size, if needed
308
+ pixel_values = self.maybe_pad(pixel_values, height, width)
309
+ embeddings = self.projection(pixel_values)
310
+ _, _, height, width = embeddings.shape
311
+ output_dimensions = (height, width)
312
+ embeddings = embeddings.flatten(2).transpose(1, 2)
313
+
314
+ return embeddings, output_dimensions
315
+
316
+
317
+ class SwinPatchMerging(nn.Module):
318
+ """
319
+ Patch Merging Layer.
320
+
321
+ Args:
322
+ dim (`int`):
323
+ Number of input channels.
324
+ """
325
+
326
+ def __init__(self, dim: int) -> None:
327
+ super().__init__()
328
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
329
+ self.norm = nn.LayerNorm(4 * dim)
330
+
331
+ def maybe_pad(self, input_feature: torch.Tensor, height: int, width: int) -> torch.Tensor:
332
+ """Pad input feature map to be divisible by 2 in both spatial dimensions if needed."""
333
+ if (height % 2 == 1) or (width % 2 == 1):
334
+ input_feature = nn.functional.pad(input_feature, (0, 0, 0, width % 2, 0, height % 2))
335
+ return input_feature
336
+
337
+ def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor:
338
+ height, width = input_dimensions
339
+ # `dim` is height * width
340
+ batch_size, dim, num_channels = input_feature.shape
341
+
342
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
343
+ # pad input to be divisible by width and height, if needed
344
+ input_feature = self.maybe_pad(input_feature, height, width)
345
+ # Interleave rows and columns to produce [batch_size, height/2*width/2, 4*num_channels]
346
+ input_feature = torch.cat(
347
+ [input_feature[:, row::2, col::2, :] for col in range(2) for row in range(2)], dim=-1
348
+ )
349
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels)
350
+
351
+ input_feature = self.norm(input_feature)
352
+ input_feature = self.reduction(input_feature)
353
+
354
+ return input_feature
355
+
356
+
357
+ class SwinRelativePositionBias(nn.Module):
358
+ """
359
+ Relative position bias for Swin's window-based attention, following the style of BeitRelativePositionBias.
360
+
361
+ Unlike BeiT, Swin has no CLS token, so the table covers exactly (2*ws_h-1)*(2*ws_w-1) unique
362
+ relative positions. The lookup index is purely determined by window_size (static), so it is stored
363
+ as a non-persistent buffer (recomputed from config on load, never serialised). The table values
364
+ are learned parameters and must be re-read on every forward call.
365
+ """
366
+
367
+ def __init__(self, num_heads: int, window_size: tuple[int, int]):
368
+ super().__init__()
369
+ self.window_size = window_size
370
+ self.window_area = window_size[0] * window_size[1]
371
+ self.relative_position_bias_table = nn.Parameter(
372
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
373
+ )
374
+ # Non-persistent: fully determined by window_size, no need to serialise.
375
+ # Stored flat so forward avoids an extra .view() call.
376
+ self.register_buffer(
377
+ "relative_position_index",
378
+ self._create_relative_position_index().view(-1),
379
+ persistent=False,
380
+ )
381
+
382
+ def _create_relative_position_index(self) -> torch.Tensor:
383
+ coords_h = torch.arange(self.window_size[0])
384
+ coords_w = torch.arange(self.window_size[1])
385
+
386
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # 2, Wh, Ww
387
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
388
+
389
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
390
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
391
+
392
+ # shift to start from 0 and compute a unique flat index for each (dh, dw) pair
393
+ relative_coords[:, :, 0] += self.window_size[0] - 1
394
+ relative_coords[:, :, 1] += self.window_size[1] - 1
395
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
396
+
397
+ return relative_coords.sum(-1) # Wh*Ww, Wh*Ww
398
+
399
+ def forward(self) -> torch.Tensor:
400
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index]
401
+ relative_position_bias = relative_position_bias.view(self.window_area, self.window_area, -1)
402
+ return relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) # 1, num_heads, Wh*Ww, Wh*Ww
403
+
404
+
405
+ class SwinAttention(ViTAttention):
406
+ def __init__(self, config: SwinConfig, hidden_size: int, num_attention_heads: int, window_size: int):
407
+ super().__init__(config)
408
+ self.num_attention_heads = num_attention_heads
409
+ self.head_dim = hidden_size // num_attention_heads
410
+ self.scaling = self.head_dim**-0.5
411
+
412
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
413
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
414
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=config.qkv_bias)
415
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
416
+
417
+ self.relative_position_bias = SwinRelativePositionBias(num_attention_heads, (window_size, window_size))
418
+
419
+ def forward(
420
+ self,
421
+ hidden_states: torch.Tensor,
422
+ attention_mask: torch.FloatTensor | None = None,
423
+ **kwargs: Unpack[TransformersKwargs],
424
+ ) -> tuple[torch.Tensor, torch.Tensor]:
425
+ # hidden_states: (batch_size * num_windows, window_size * window_size, channels)
426
+ input_shape = hidden_states.shape[:-1]
427
+ hidden_shape = (*input_shape, -1, self.head_dim)
428
+
429
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
430
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
431
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
432
+
433
+ # Combine relative position bias with the cyclic-shift attention mask for SW-MSA
434
+ relative_position_bias = self.relative_position_bias() # 1, num_heads, ws*ws, ws*ws
435
+ if attention_mask is not None:
436
+ # attention_mask: (num_windows, ws*ws, ws*ws)
437
+ num_windows = attention_mask.shape[0]
438
+ batch_size = input_shape[0] // num_windows
439
+ seq_len = input_shape[1]
440
+ # Expand to (batch * num_windows, 1, ws*ws, ws*ws) for broadcasting
441
+ attention_mask = (
442
+ attention_mask.unsqueeze(1) # (num_windows, 1, ws*ws, ws*ws)
443
+ .unsqueeze(0) # (1, num_windows, 1, ws*ws, ws*ws)
444
+ .expand(batch_size, -1, -1, -1, -1) # (batch, num_windows, 1, ws*ws, ws*ws)
445
+ .reshape(-1, 1, seq_len, seq_len) # (batch * num_windows, 1, ws*ws, ws*ws)
446
+ )
447
+ combined_mask = relative_position_bias + attention_mask
448
+ else:
449
+ combined_mask = relative_position_bias
450
+
451
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
452
+ self.config._attn_implementation, eager_attention_forward
453
+ )
454
+
455
+ attn_output, attn_weights = attention_interface(
456
+ self,
457
+ query_states,
458
+ key_states,
459
+ value_states,
460
+ combined_mask,
461
+ dropout=0.0 if not self.training else self.attention_dropout,
462
+ scaling=self.scaling,
463
+ **kwargs,
464
+ )
465
+
466
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
467
+ attn_output = self.o_proj(attn_output)
468
+
469
+ return attn_output, attn_weights
470
+
471
+
472
+ class SwinMLP(ViTMLP):
473
+ def __init__(self, config: SwinConfig, dim: int):
474
+ nn.Module.__init__(self)
475
+ self.activation_fn = ACT2FN[config.hidden_act]
476
+ self.fc1 = nn.Linear(dim, int(config.mlp_ratio * dim))
477
+ self.fc2 = nn.Linear(int(config.mlp_ratio * dim), dim)
478
+
479
+
480
+ class SwinLayer(ViTLayer):
481
+ def __init__(
482
+ self,
483
+ config: SwinConfig,
484
+ dim: int,
485
+ input_resolution: tuple[int, int],
486
+ num_heads: int,
487
+ drop_path_rate: float = 0.0,
488
+ shift_size: int = 0,
489
+ ):
490
+ super().__init__()
491
+ self.window_size = config.window_size
492
+ self.attention = SwinAttention(config, dim, num_heads, window_size=config.window_size)
493
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
494
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
495
+ self.mlp = SwinMLP(config, dim)
496
+ self.shift_size = shift_size
497
+ self.input_resolution = input_resolution
498
+ self.drop_path = SwinDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
499
+
500
+ def set_shift_and_window_size(self, input_resolution: tuple[int, int]) -> None:
501
+ """Clamp window and shift sizes when the window is larger than the input resolution."""
502
+ if min(input_resolution) <= self.window_size:
503
+ self.shift_size = torch_int(0)
504
+ self.window_size = (
505
+ torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
506
+ )
507
+
508
+ def get_attn_mask(self, height: int, width: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor | None:
509
+ """Build the cyclic-shift attention mask for shifted-window MSA; returns None when shift_size is 0."""
510
+ if self.shift_size > 0:
511
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
512
+ height_slices = (
513
+ slice(0, -self.window_size),
514
+ slice(-self.window_size, -self.shift_size),
515
+ slice(-self.shift_size, None),
516
+ )
517
+ width_slices = (
518
+ slice(0, -self.window_size),
519
+ slice(-self.window_size, -self.shift_size),
520
+ slice(-self.shift_size, None),
521
+ )
522
+ count = 0
523
+ for height_slice in height_slices:
524
+ for width_slice in width_slices:
525
+ img_mask[:, height_slice, width_slice, :] = count
526
+ count += 1
527
+
528
+ mask_windows = window_partition(img_mask, self.window_size)
529
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
530
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
531
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0)
532
+ else:
533
+ attn_mask = None
534
+ return attn_mask
535
+
536
+ def maybe_pad(self, hidden_states: torch.Tensor, height: int, width: int) -> tuple[torch.Tensor, tuple[int, ...]]:
537
+ """Pad feature map so both spatial dimensions are divisible by window_size."""
538
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
539
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
540
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
541
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
542
+ return hidden_states, pad_values
543
+
544
+ def cyclic_shift(self, hidden_states: torch.Tensor, reverse: bool = False) -> torch.Tensor:
545
+ """Apply a cyclic shift along the spatial dimensions for shifted-window attention."""
546
+ if self.shift_size > 0:
547
+ direction = 1 if reverse else -1
548
+ hidden_states = torch.roll(
549
+ hidden_states,
550
+ shifts=(direction * self.shift_size, direction * self.shift_size),
551
+ dims=(1, 2),
552
+ )
553
+ return hidden_states
554
+
555
+ def forward(
556
+ self,
557
+ hidden_states: torch.Tensor,
558
+ input_dimensions: tuple[int, int],
559
+ always_partition: bool = False,
560
+ **kwargs: Unpack[TransformersKwargs],
561
+ ) -> torch.Tensor:
562
+ if not always_partition:
563
+ self.set_shift_and_window_size(input_dimensions)
564
+ height, width = input_dimensions
565
+ batch_size, _, channels = hidden_states.size()
566
+ shortcut = hidden_states
567
+
568
+ hidden_states = self.layernorm_before(hidden_states)
569
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
570
+
571
+ # pad hidden_states to multiples of window size
572
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
573
+ _, height_pad, width_pad, _ = hidden_states.shape
574
+
575
+ hidden_states_windows = window_partition(self.cyclic_shift(hidden_states), self.window_size)
576
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
577
+ attn_mask = self.get_attn_mask(
578
+ height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
579
+ )
580
+
581
+ attention_output, attn_weights = self.attention(hidden_states_windows, attn_mask, **kwargs)
582
+ attention_output = self.dropout(attention_output)
583
+
584
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
585
+ attention_windows = self.cyclic_shift(
586
+ window_reverse(attention_windows, self.window_size, height_pad, width_pad), reverse=True
587
+ )
588
+
589
+ if pad_values[3] > 0 or pad_values[5] > 0:
590
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
591
+
592
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
593
+ hidden_states = shortcut + self.drop_path(attention_windows)
594
+
595
+ residual = hidden_states
596
+ hidden_states = self.layernorm_after(hidden_states)
597
+ hidden_states = self.mlp(hidden_states)
598
+ hidden_states = self.dropout(hidden_states) + residual
599
+
600
+ return hidden_states, attn_weights
601
+
602
+
603
+ class SwinStage(GradientCheckpointingLayer):
604
+ def __init__(
605
+ self,
606
+ config: SwinConfig,
607
+ dim: int,
608
+ input_resolution: tuple[int, int],
609
+ depth: int,
610
+ num_heads: int,
611
+ drop_path: list[float],
612
+ downsample,
613
+ ):
614
+ super().__init__()
615
+ self.config = config
616
+ self.blocks = nn.ModuleList(
617
+ [
618
+ SwinLayer(
619
+ config=config,
620
+ dim=dim,
621
+ input_resolution=input_resolution,
622
+ num_heads=num_heads,
623
+ drop_path_rate=drop_path[i],
624
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
625
+ )
626
+ for i in range(depth)
627
+ ]
628
+ )
629
+
630
+ self.downsample = downsample(dim=dim) if downsample is not None else None
631
+
632
+ def get_reshaped_hidden_states(
633
+ self,
634
+ hidden_states: torch.Tensor,
635
+ hidden_states_before_downsampling: torch.Tensor,
636
+ height: int,
637
+ width: int,
638
+ output_hidden_states_before_downsampling: bool,
639
+ ) -> torch.Tensor:
640
+ """
641
+ Select the spatial hidden states for this stage and reshape from (B, L, C) to (B, C, H, W).
642
+
643
+ The chosen state and its resolution depend on output_hidden_states_before_downsampling:
644
+ - True → pre-downsampling states at (height, width) — used by the backbone.
645
+ - False → post-downsampling states at half the resolution (if a downsampler exists).
646
+ """
647
+ if output_hidden_states_before_downsampling:
648
+ spatial_state, h, w = hidden_states_before_downsampling, height, width
649
+ elif self.downsample is not None:
650
+ spatial_state, h, w = hidden_states, (height + 1) // 2, (width + 1) // 2
651
+ else:
652
+ spatial_state, h, w = hidden_states, height, width
653
+
654
+ batch_size, _, hidden_size = spatial_state.shape
655
+ return spatial_state.view(batch_size, h, w, hidden_size).permute(0, 3, 1, 2).contiguous()
656
+
657
+ def forward(
658
+ self,
659
+ hidden_states: torch.Tensor,
660
+ input_dimensions: tuple[int, int],
661
+ always_partition: bool = False,
662
+ output_hidden_states_before_downsampling: bool = False,
663
+ **kwargs: Unpack[TransformersKwargs],
664
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
665
+ height, width = input_dimensions
666
+ last_attn_weights = None
667
+ for layer_module in self.blocks:
668
+ hidden_states, last_attn_weights = layer_module(
669
+ hidden_states, input_dimensions, always_partition=always_partition, **kwargs
670
+ )
671
+
672
+ hidden_states_before_downsampling = hidden_states
673
+ if self.downsample is not None:
674
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
675
+
676
+ reshaped_hidden_states = self.get_reshaped_hidden_states(
677
+ hidden_states, hidden_states_before_downsampling, height, width, output_hidden_states_before_downsampling
678
+ )
679
+
680
+ return hidden_states, reshaped_hidden_states, last_attn_weights
681
+
682
+
683
+ @auto_docstring
684
+ class SwinPreTrainedModel(ViTPreTrainedModel):
685
+ config: SwinConfig
686
+ _no_split_modules = ["SwinStage"]
687
+ _supports_flash_attn = False
688
+ _supports_flex_attn = False
689
+ # relative_position_index is now a non-persistent buffer (recomputed from window_size in __init__).
690
+ _keys_to_ignore_on_load_unexpected = [
691
+ r"attention\.self\.relative_position_index",
692
+ r"attention\.relative_position_bias\.relative_position_index",
693
+ ]
694
+ _can_record_outputs = {
695
+ # capture_initial_hidden_state=True: prepend the embedding input (args[0] of SwinStage 0) so that
696
+ # hidden_states[0] has the same shape as the patch embeddings (num_patches, embed_dim).
697
+ "hidden_states": OutputRecorder(SwinStage, index=0, capture_initial_hidden_state=True),
698
+ # reshaped_hidden_states are collected explicitly by SwinEncoder (per stage) and the stem
699
+ # is prepended in SwinModel.forward, so they are NOT captured via hooks here.
700
+ # index=2: SwinStage returns (hidden_states, reshaped_hidden_states, last_attn_weights);
701
+ # capture the last block's attention weights at index 2, giving one entry per stage.
702
+ "attentions": OutputRecorder(SwinStage, index=2, capture_initial_hidden_state=False),
703
+ }
704
+
705
+ @torch.no_grad()
706
+ def _init_weights(self, module):
707
+ """Initialize the weights"""
708
+ PreTrainedModel._init_weights(self, module)
709
+ if isinstance(module, SwinEmbeddings):
710
+ if module.mask_token is not None:
711
+ init.zeros_(module.mask_token)
712
+ if module.position_embeddings is not None:
713
+ init.zeros_(module.position_embeddings)
714
+ elif isinstance(module, SwinRelativePositionBias):
715
+ init.zeros_(module.relative_position_bias_table)
716
+ init.copy_(module.relative_position_index, module._create_relative_position_index().view(-1))
717
+
718
+
719
+ class SwinEncoder(SwinPreTrainedModel):
720
+ def __init__(self, config: SwinConfig, grid_size: tuple[int, int]):
721
+ super().__init__(config)
722
+ self.num_layers = len(config.depths)
723
+ self.config = config
724
+ dpr = [config.drop_path_rate * i / max(sum(config.depths) - 1, 1) for i in range(sum(config.depths))]
725
+ self.layers = nn.ModuleList(
726
+ [
727
+ SwinStage(
728
+ config=config,
729
+ dim=int(config.embed_dim * 2**layer_idx),
730
+ input_resolution=(grid_size[0] // (2**layer_idx), grid_size[1] // (2**layer_idx)),
731
+ depth=config.depths[layer_idx],
732
+ num_heads=config.num_heads[layer_idx],
733
+ drop_path=dpr[sum(config.depths[:layer_idx]) : sum(config.depths[: layer_idx + 1])],
734
+ downsample=SwinPatchMerging if (layer_idx < self.num_layers - 1) else None,
735
+ )
736
+ for layer_idx in range(self.num_layers)
737
+ ]
738
+ )
739
+ self.post_init()
740
+
741
+ @merge_with_config_defaults
742
+ @capture_outputs(tie_last_hidden_states=False)
743
+ @auto_docstring
744
+ def forward(
745
+ self,
746
+ hidden_states: torch.Tensor,
747
+ input_dimensions: tuple[int, int],
748
+ always_partition: bool = False,
749
+ output_hidden_states: bool = False,
750
+ output_hidden_states_before_downsampling: bool = False,
751
+ **kwargs: Unpack[TransformersKwargs],
752
+ ) -> SwinEncoderOutput:
753
+ r"""
754
+ input_dimensions (`tuple[int, int]`):
755
+ Spatial `(height, width)` of the patch grid entering the encoder.
756
+ always_partition (`bool`, *optional*, defaults to `False`):
757
+ If `True`, always apply window partitioning regardless of input resolution.
758
+ output_hidden_states_before_downsampling (`bool`, *optional*, defaults to `False`):
759
+ If `True`, `reshaped_hidden_states` contains pre-downsampling feature maps.
760
+ """
761
+ all_reshaped_hidden_states = None
762
+ if output_hidden_states:
763
+ # Prepend the stem: hidden_states is the patch embedding output (B, N, C),
764
+ # reshape it to spatial (B, C, H, W) as the first reshaped hidden state.
765
+ batch_size, _, hidden_size = hidden_states.shape
766
+ stem_spatial = (
767
+ hidden_states.view(batch_size, *input_dimensions, hidden_size).permute(0, 3, 1, 2).contiguous()
768
+ )
769
+ all_reshaped_hidden_states = (stem_spatial,)
770
+
771
+ for layer_module in self.layers:
772
+ hidden_states, reshaped_hidden_state, _ = layer_module(
773
+ hidden_states,
774
+ input_dimensions,
775
+ always_partition=always_partition,
776
+ output_hidden_states_before_downsampling=output_hidden_states_before_downsampling,
777
+ **kwargs,
778
+ )
779
+ if output_hidden_states:
780
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
781
+ if layer_module.downsample is not None:
782
+ input_dimensions = ((input_dimensions[0] + 1) // 2, (input_dimensions[1] + 1) // 2)
783
+
784
+ return SwinEncoderOutput(
785
+ last_hidden_state=hidden_states,
786
+ reshaped_hidden_states=all_reshaped_hidden_states,
787
+ )
788
+
789
+
790
+ @auto_docstring
791
+ class SwinModel(SwinPreTrainedModel):
792
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
793
+ r"""
794
+ add_pooling_layer (`bool`, *optional*, defaults to `True`):
795
+ Whether or not to apply pooling layer.
796
+ use_mask_token (`bool`, *optional*, defaults to `False`):
797
+ Whether or not to create and apply mask tokens in the embedding layer.
798
+ """
799
+ super().__init__(config)
800
+ self.config = config
801
+ self.num_layers = len(config.depths)
802
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
803
+
804
+ self.embeddings = SwinEmbeddings(config, use_mask_token=use_mask_token)
805
+ self.encoder = SwinEncoder(config, self.embeddings.patch_grid)
806
+
807
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
808
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
809
+
810
+ # Initialize weights and apply final processing
811
+ self.post_init()
812
+
813
+ @can_return_tuple
814
+ @auto_docstring
815
+ def forward(
816
+ self,
817
+ pixel_values: torch.FloatTensor | None = None,
818
+ bool_masked_pos: torch.BoolTensor | None = None,
819
+ interpolate_pos_encoding: bool = False,
820
+ **kwargs: Unpack[TransformersKwargs],
821
+ ) -> SwinModelOutput:
822
+ r"""
823
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
824
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
825
+ """
826
+ # FIXME: output_hidden_states must be popped manually here because SwinEncoder takes it as an
827
+ # explicit argument (not via **kwargs), so it is not captured by the @capture_outputs decorator.
828
+ output_hidden_states = kwargs.pop("output_hidden_states", self.config.output_hidden_states)
829
+
830
+ embedding_output, input_dimensions = self.embeddings(
831
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
832
+ )
833
+
834
+ encoder_outputs = self.encoder(
835
+ embedding_output,
836
+ input_dimensions,
837
+ output_hidden_states=output_hidden_states,
838
+ **kwargs,
839
+ )
840
+
841
+ sequence_output = encoder_outputs.last_hidden_state
842
+ sequence_output = self.layernorm(sequence_output)
843
+
844
+ pooled_output = None
845
+ if self.pooler is not None:
846
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
847
+ pooled_output = torch.flatten(pooled_output, 1)
848
+
849
+ return SwinModelOutput(
850
+ last_hidden_state=sequence_output,
851
+ pooler_output=pooled_output,
852
+ hidden_states=encoder_outputs.hidden_states,
853
+ attentions=encoder_outputs.attentions,
854
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
855
+ )
856
+
857
+
858
+ @auto_docstring(
859
+ custom_intro="""
860
+ Swin Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).
861
+
862
+ <Tip>
863
+
864
+ Note that we provide a script to pre-train this model on custom data in our [examples
865
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
866
+
867
+ </Tip>
868
+ """
869
+ )
870
+ class SwinForMaskedImageModeling(SwinPreTrainedModel):
871
+ def __init__(self, config):
872
+ super().__init__(config)
873
+
874
+ self.swin = SwinModel(config, add_pooling_layer=False, use_mask_token=True)
875
+
876
+ num_features = int(config.embed_dim * 2 ** (config.num_layers - 1))
877
+ self.decoder = nn.Sequential(
878
+ nn.Conv2d(
879
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
880
+ ),
881
+ nn.PixelShuffle(config.encoder_stride),
882
+ )
883
+
884
+ # Initialize weights and apply final processing
885
+ self.post_init()
886
+
887
+ @can_return_tuple
888
+ @auto_docstring
889
+ def forward(
890
+ self,
891
+ pixel_values: torch.FloatTensor | None = None,
892
+ bool_masked_pos: torch.BoolTensor | None = None,
893
+ interpolate_pos_encoding: bool = False,
894
+ **kwargs: Unpack[TransformersKwargs],
895
+ ) -> SwinMaskedImageModelingOutput:
896
+ r"""
897
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
898
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
899
+
900
+ Examples:
901
+ ```python
902
+ >>> from transformers import AutoImageProcessor, SwinForMaskedImageModeling
903
+ >>> import torch
904
+ >>> from PIL import Image
905
+ >>> import httpx
906
+ >>> from io import BytesIO
907
+
908
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
909
+ >>> with httpx.stream("GET", url) as response:
910
+ ... image = Image.open(BytesIO(response.read()))
911
+
912
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-base-simmim-window6-192")
913
+ >>> model = SwinForMaskedImageModeling.from_pretrained("microsoft/swin-base-simmim-window6-192")
914
+
915
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
916
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
917
+ >>> # create random boolean mask of shape (batch_size, num_patches)
918
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
919
+
920
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
921
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
922
+ >>> list(reconstructed_pixel_values.shape)
923
+ [1, 3, 192, 192]
924
+ ```"""
925
+ outputs = self.swin(
926
+ pixel_values,
927
+ bool_masked_pos=bool_masked_pos,
928
+ interpolate_pos_encoding=interpolate_pos_encoding,
929
+ **kwargs,
930
+ )
931
+
932
+ sequence_output = outputs.last_hidden_state
933
+ # Reshape to (batch_size, num_channels, height, width)
934
+ sequence_output = sequence_output.transpose(1, 2)
935
+ batch_size, num_channels, sequence_length = sequence_output.shape
936
+ height = width = math.floor(sequence_length**0.5)
937
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
938
+
939
+ # Reconstruct pixel values
940
+ reconstructed_pixel_values = self.decoder(sequence_output)
941
+
942
+ masked_im_loss = None
943
+ if bool_masked_pos is not None:
944
+ size = self.config.image_size // self.config.patch_size
945
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
946
+ mask = (
947
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
948
+ .repeat_interleave(self.config.patch_size, 2)
949
+ .unsqueeze(1)
950
+ .contiguous()
951
+ )
952
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
953
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
954
+
955
+ return SwinMaskedImageModelingOutput(
956
+ loss=masked_im_loss,
957
+ reconstruction=reconstructed_pixel_values,
958
+ hidden_states=outputs.hidden_states,
959
+ attentions=outputs.attentions,
960
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
961
+ )
962
+
963
+
964
+ @auto_docstring(
965
+ custom_intro="""
966
+ Swin Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
967
+ the [CLS] token) e.g. for ImageNet.
968
+
969
+ <Tip>
970
+
971
+ Note that it's possible to fine-tune Swin on higher resolution images than the ones it has been trained on, by
972
+ setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
973
+ position embeddings to the higher resolution.
974
+
975
+ </Tip>
976
+ """
977
+ )
978
+ class SwinForImageClassification(SwinPreTrainedModel):
979
+ def __init__(self, config):
980
+ super().__init__(config)
981
+
982
+ self.num_labels = config.num_labels
983
+ self.swin = SwinModel(config)
984
+
985
+ # Classifier head
986
+ self.classifier = (
987
+ nn.Linear(self.swin.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
988
+ )
989
+
990
+ # Initialize weights and apply final processing
991
+ self.post_init()
992
+
993
+ @can_return_tuple
994
+ @auto_docstring
995
+ def forward(
996
+ self,
997
+ pixel_values: torch.FloatTensor | None = None,
998
+ labels: torch.LongTensor | None = None,
999
+ interpolate_pos_encoding: bool = False,
1000
+ **kwargs: Unpack[TransformersKwargs],
1001
+ ) -> SwinImageClassifierOutput:
1002
+ r"""
1003
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1004
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1005
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1006
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1007
+ """
1008
+ outputs = self.swin(
1009
+ pixel_values,
1010
+ interpolate_pos_encoding=interpolate_pos_encoding,
1011
+ **kwargs,
1012
+ )
1013
+
1014
+ pooled_output = outputs.pooler_output
1015
+
1016
+ logits = self.classifier(pooled_output)
1017
+
1018
+ loss = None
1019
+ if labels is not None:
1020
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
1021
+
1022
+ return SwinImageClassifierOutput(
1023
+ loss=loss,
1024
+ logits=logits,
1025
+ hidden_states=outputs.hidden_states,
1026
+ attentions=outputs.attentions,
1027
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1028
+ )
1029
+
1030
+
1031
+ @auto_docstring(
1032
+ custom_intro="""
1033
+ Swin backbone, to be used with frameworks like DETR and MaskFormer.
1034
+ """
1035
+ )
1036
+ class SwinBackbone(BackboneMixin, SwinPreTrainedModel):
1037
+ _keys_to_ignore_on_load_missing = [r"swin.layernorm.*"]
1038
+
1039
+ def __init__(self, config: SwinConfig):
1040
+ super().__init__(config)
1041
+
1042
+ self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
1043
+ self.swin = SwinModel(config, add_pooling_layer=False)
1044
+
1045
+ # Add layer norms to hidden states of out_features
1046
+ hidden_states_norms = {}
1047
+ for stage, num_channels in zip(self.out_features, self.channels):
1048
+ hidden_states_norms[stage] = nn.LayerNorm(num_channels)
1049
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
1050
+
1051
+ # Initialize weights and apply final processing
1052
+ self.post_init()
1053
+
1054
+ @can_return_tuple
1055
+ @filter_output_hidden_states
1056
+ @auto_docstring
1057
+ def forward(
1058
+ self,
1059
+ pixel_values: torch.Tensor,
1060
+ **kwargs: Unpack[TransformersKwargs],
1061
+ ) -> BackboneOutput:
1062
+ r"""
1063
+ Examples:
1064
+
1065
+ ```python
1066
+ >>> from transformers import AutoImageProcessor, AutoBackbone
1067
+ >>> import torch
1068
+ >>> from PIL import Image
1069
+ >>> import httpx
1070
+ >>> from io import BytesIO
1071
+
1072
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1073
+ >>> with httpx.stream("GET", url) as response:
1074
+ ... image = Image.open(BytesIO(response.read()))
1075
+
1076
+ >>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
1077
+ >>> model = AutoBackbone.from_pretrained(
1078
+ ... "microsoft/swin-tiny-patch4-window7-224", out_features=["stage1", "stage2", "stage3", "stage4"]
1079
+ ... )
1080
+
1081
+ >>> inputs = processor(image, return_tensors="pt")
1082
+ >>> outputs = model(**inputs)
1083
+ >>> feature_maps = outputs.feature_maps
1084
+ >>> list(feature_maps[-1].shape)
1085
+ [1, 768, 7, 7]
1086
+ ```
1087
+ """
1088
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
1089
+ # always_partition=True preserves shifted-window attention at all resolutions.
1090
+ # output_hidden_states_before_downsampling=True captures pre-downsampling feature maps per stage.
1091
+ outputs = self.swin(
1092
+ pixel_values,
1093
+ always_partition=True,
1094
+ output_hidden_states_before_downsampling=True,
1095
+ **kwargs,
1096
+ )
1097
+
1098
+ feature_maps = ()
1099
+ for stage, hidden_state in zip(self.stage_names, outputs.reshaped_hidden_states):
1100
+ if stage in self.out_features:
1101
+ batch_size, num_channels, height, width = hidden_state.shape
1102
+ hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous()
1103
+ hidden_state = hidden_state.view(batch_size, height * width, num_channels)
1104
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
1105
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
1106
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
1107
+ feature_maps += (hidden_state,)
1108
+
1109
+ return BackboneOutput(
1110
+ feature_maps=feature_maps,
1111
+ hidden_states=outputs.reshaped_hidden_states,
1112
+ attentions=outputs.attentions,
1113
+ )
1114
+
1115
+
1116
+ __all__ = [
1117
+ "SwinForImageClassification",
1118
+ "SwinForMaskedImageModeling",
1119
+ "SwinModel",
1120
+ "SwinPreTrainedModel",
1121
+ "SwinBackbone",
1122
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/__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_wav2vec2 import *
22
+ from .feature_extraction_wav2vec2 import *
23
+ from .modeling_wav2vec2 import *
24
+ from .processing_wav2vec2 import *
25
+ from .tokenization_wav2vec2 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__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/configuration_wav2vec2.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Fairseq Authors 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
+ """Wav2Vec2 model configuration"""
15
+
16
+ import functools
17
+ import operator
18
+
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring
23
+
24
+
25
+ @auto_docstring(checkpoint="facebook/wav2vec2-base-960h")
26
+ @strict
27
+ class Wav2Vec2Config(PreTrainedConfig):
28
+ r"""
29
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
30
+ The dropout probability for output of the feature encoder.
31
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
32
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
33
+ final_dropout (`float`, *optional*, defaults to 0.1):
34
+ The dropout probability for the final projection layer of [`Wav2Vec2ForCTC`].
35
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
36
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
37
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
38
+ convolutional layers.
39
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
40
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
41
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
42
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
43
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
44
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
45
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
46
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
47
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
48
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
49
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
50
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
51
+ *conv_dim*.
52
+ conv_bias (`bool`, *optional*, defaults to `False`):
53
+ Whether the 1D convolutional layers have a bias.
54
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
55
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
56
+ embeddings layer.
57
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
58
+ Number of groups of 1D convolutional positional embeddings layer.
59
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
60
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
61
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
62
+ False` corresponds to applying layer norm after the attention layer.
63
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
64
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
65
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
66
+ Recognition](https://huggingface.co/papers/1904.08779).
67
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
68
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
69
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
70
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
71
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
72
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
73
+ mask_time_length (`int`, *optional*, defaults to 10):
74
+ Length of vector span along the time axis.
75
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
76
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
77
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
78
+ mask_time_min_masks''
79
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
80
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
81
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
82
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
83
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
84
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
85
+ True`.
86
+ mask_feature_length (`int`, *optional*, defaults to 10):
87
+ Length of vector span along the feature axis.
88
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
89
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
90
+ step, irrespectively of `mask_feature_prob`. Only relevant if
91
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
92
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
93
+ Number of entries in each quantization codebook (group).
94
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
95
+ Number of entries in each quantization codebook (group).
96
+ num_codevector_groups (`int`, *optional*, defaults to 2):
97
+ Number of codevector groups for product codevector quantization.
98
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
99
+ The temperature *kappa* in the contrastive loss.
100
+ num_negatives (`int`, *optional*, defaults to 100):
101
+ Number of negative samples for the contrastive loss.
102
+ codevector_dim (`int`, *optional*, defaults to 256):
103
+ Dimensionality of the quantized feature vectors.
104
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
105
+ Dimensionality of the final projection of both the quantized and the transformer features.
106
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
107
+ The weight of the codebook diversity loss component.
108
+ ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
109
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
110
+ instance of [`Wav2Vec2ForCTC`].
111
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
112
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
113
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
114
+ of [`Wav2Vec2ForCTC`].
115
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
116
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
117
+ instance of [`Wav2Vec2ForSequenceClassification`].
118
+ classifier_proj_size (`int`, *optional*, defaults to 256):
119
+ Dimensionality of the projection before token mean-pooling for classification.
120
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
121
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
122
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
123
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
124
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
125
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
126
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
127
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
128
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
129
+ xvector_output_dim (`int`, *optional*, defaults to 512):
130
+ Dimensionality of the *XVector* embedding vectors.
131
+ add_adapter (`bool`, *optional*, defaults to `False`):
132
+ Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for
133
+ warm-starting Wav2Vec2 for SpeechEncoderDecoder models.
134
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
135
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
136
+ adapter_stride (`int`, *optional*, defaults to 2):
137
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
138
+ num_adapter_layers (`int`, *optional*, defaults to 3):
139
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
140
+ True`.
141
+ output_hidden_size (`int`, *optional*):
142
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
143
+ if `add_adapter is True`.
144
+ adapter_attn_dim (`int`, *optional*):
145
+ Dimension of the attention adapter weights to be used in each attention block. An example of a model using
146
+ attention adapters is [facebook/mms-1b-all](https://huggingface.co/facebook/mms-1b-all).
147
+
148
+ Example:
149
+
150
+ ```python
151
+ >>> from transformers import Wav2Vec2Config, Wav2Vec2Model
152
+
153
+ >>> # Initializing a Wav2Vec2 facebook/wav2vec2-base-960h style configuration
154
+ >>> configuration = Wav2Vec2Config()
155
+
156
+ >>> # Initializing a model (with random weights) from the facebook/wav2vec2-base-960h style configuration
157
+ >>> model = Wav2Vec2Model(configuration)
158
+
159
+ >>> # Accessing the model configuration
160
+ >>> configuration = model.config
161
+ ```"""
162
+
163
+ model_type = "wav2vec2"
164
+
165
+ vocab_size: int | None = 32
166
+ hidden_size: int = 768
167
+ num_hidden_layers: int = 12
168
+ num_attention_heads: int = 12
169
+ intermediate_size: int = 3072
170
+ hidden_act: str = "gelu"
171
+ hidden_dropout: float | int = 0.1
172
+ activation_dropout: float | int = 0.1
173
+ attention_dropout: float | int = 0.1
174
+ feat_proj_dropout: float | int = 0.0
175
+ feat_quantizer_dropout: float | int = 0.0
176
+ final_dropout: float | int = 0.1
177
+ layerdrop: float | int = 0.1
178
+ initializer_range: float = 0.02
179
+ layer_norm_eps: float = 1e-5
180
+ feat_extract_norm: str = "group"
181
+ feat_extract_activation: str = "gelu"
182
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
183
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
184
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
185
+ conv_bias: bool = False
186
+ num_conv_pos_embeddings: int = 128
187
+ num_conv_pos_embedding_groups: int = 16
188
+ do_stable_layer_norm: bool = False
189
+ apply_spec_augment: bool = True
190
+ mask_time_prob: float | int = 0.05
191
+ mask_time_length: int = 10
192
+ mask_time_min_masks: int = 2
193
+ mask_feature_prob: float | int = 0.0
194
+ mask_feature_length: int = 10
195
+ mask_feature_min_masks: int = 0
196
+ num_codevectors_per_group: int = 320
197
+ num_codevector_groups: int = 2
198
+ contrastive_logits_temperature: float = 0.1
199
+ num_negatives: int = 100
200
+ codevector_dim: int = 256
201
+ proj_codevector_dim: int = 256
202
+ diversity_loss_weight: float = 0.1
203
+ ctc_loss_reduction: str = "sum"
204
+ ctc_zero_infinity: bool = False
205
+ use_weighted_layer_sum: bool = False
206
+ classifier_proj_size: int = 256
207
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
208
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
209
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
210
+ xvector_output_dim: int = 512
211
+ pad_token_id: int | None = 0
212
+ bos_token_id: int | None = 1
213
+ eos_token_id: int | list[int] | None = 2
214
+ add_adapter: bool = False
215
+ adapter_kernel_size: int = 3
216
+ adapter_stride: int = 2
217
+ num_adapter_layers: int = 3
218
+ output_hidden_size: int | None = None
219
+ adapter_attn_dim: int | None = None
220
+
221
+ def __post_init__(self, **kwargs):
222
+ self.num_feat_extract_layers = len(self.conv_dim)
223
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
224
+ super().__post_init__(**kwargs)
225
+
226
+ def validate_architecture(self):
227
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
228
+ if (
229
+ (len(self.conv_stride) != self.num_feat_extract_layers)
230
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
231
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
232
+ ):
233
+ raise ValueError(
234
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
235
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
236
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
237
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
238
+ )
239
+
240
+ @property
241
+ def inputs_to_logits_ratio(self):
242
+ return functools.reduce(operator.mul, self.conv_stride, 1)
243
+
244
+
245
+ __all__ = ["Wav2Vec2Config"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/feature_extraction_wav2vec2.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ Feature extractor class for Wav2Vec2
16
+ """
17
+
18
+ import numpy as np
19
+
20
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
21
+ from ...feature_extraction_utils import BatchFeature
22
+ from ...utils import PaddingStrategy, TensorType, logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class Wav2Vec2FeatureExtractor(SequenceFeatureExtractor):
29
+ r"""
30
+ Constructs a Wav2Vec2 feature extractor.
31
+
32
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
33
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
34
+
35
+ Args:
36
+ feature_size (`int`, *optional*, defaults to 1):
37
+ The feature dimension of the extracted features.
38
+ sampling_rate (`int`, *optional*, defaults to 16000):
39
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
40
+ padding_value (`float`, *optional*, defaults to 0.0):
41
+ The value that is used to fill the padding values.
42
+ do_normalize (`bool`, *optional*, defaults to `True`):
43
+ Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
44
+ improve the performance for some models, *e.g.*,
45
+ [wav2vec2-lv60](https://huggingface.co/models?search=lv60).
46
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
47
+ Whether or not [`~Wav2Vec2FeatureExtractor.__call__`] should return `attention_mask`.
48
+
49
+ <Tip>
50
+
51
+ Wav2Vec2 models that have set `config.feat_extract_norm == "group"`, such as
52
+ [wav2vec2-base](https://huggingface.co/facebook/wav2vec2-base-960h), have **not** been trained using
53
+ `attention_mask`. For such models, `input_values` should simply be padded with 0 and no `attention_mask`
54
+ should be passed.
55
+
56
+ For Wav2Vec2 models that have set `config.feat_extract_norm == "layer"`, such as
57
+ [wav2vec2-lv60](https://huggingface.co/facebook/wav2vec2-large-960h-lv60-self), `attention_mask` should be
58
+ passed for batched inference.
59
+
60
+ </Tip>"""
61
+
62
+ model_input_names = ["input_values", "attention_mask"]
63
+
64
+ def __init__(
65
+ self,
66
+ feature_size=1,
67
+ sampling_rate=16000,
68
+ padding_value=0.0,
69
+ return_attention_mask=False,
70
+ do_normalize=True,
71
+ **kwargs,
72
+ ):
73
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
74
+ self.return_attention_mask = return_attention_mask
75
+ self.do_normalize = do_normalize
76
+
77
+ @staticmethod
78
+ def zero_mean_unit_var_norm(
79
+ input_values: list[np.ndarray], attention_mask: list[np.ndarray], padding_value: float = 0.0
80
+ ) -> list[np.ndarray]:
81
+ """
82
+ Every array in the list is normalized to have zero mean and unit variance
83
+ """
84
+ if attention_mask is not None:
85
+ attention_mask = np.array(attention_mask, np.int32)
86
+ normed_input_values = []
87
+
88
+ for vector, length in zip(input_values, attention_mask.sum(-1)):
89
+ normed_slice = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
90
+ if length < normed_slice.shape[0]:
91
+ normed_slice[length:] = padding_value
92
+
93
+ normed_input_values.append(normed_slice)
94
+ else:
95
+ normed_input_values = [(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]
96
+
97
+ return normed_input_values
98
+
99
+ def __call__(
100
+ self,
101
+ raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
102
+ padding: bool | str | PaddingStrategy = False,
103
+ max_length: int | None = None,
104
+ truncation: bool = False,
105
+ pad_to_multiple_of: int | None = None,
106
+ return_attention_mask: bool | None = None,
107
+ return_tensors: str | TensorType | None = None,
108
+ sampling_rate: int | None = None,
109
+ **kwargs,
110
+ ) -> BatchFeature:
111
+ """
112
+ Main method to featurize and prepare for the model one or several sequence(s).
113
+
114
+ Args:
115
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
116
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
117
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
118
+ stereo, i.e. single float per timestep.
119
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
120
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
121
+ index) among:
122
+
123
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
124
+ sequence if provided).
125
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
126
+ acceptable input length for the model if that argument is not provided.
127
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
128
+ lengths).
129
+ max_length (`int`, *optional*):
130
+ Maximum length of the returned list and optionally padding length (see above).
131
+ truncation (`bool`):
132
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
133
+ pad_to_multiple_of (`int`, *optional*):
134
+ If set will pad the sequence to a multiple of the provided value.
135
+
136
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
137
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
138
+ return_attention_mask (`bool`, *optional*):
139
+ Whether to return the attention mask. If left to the default, will return the attention mask according
140
+ to the specific feature_extractor's default.
141
+
142
+ [What are attention masks?](../glossary#attention-mask)
143
+
144
+ <Tip>
145
+
146
+ Wav2Vec2 models that have set `config.feat_extract_norm == "group"`, such as
147
+ [wav2vec2-base](https://huggingface.co/facebook/wav2vec2-base-960h), have **not** been trained using
148
+ `attention_mask`. For such models, `input_values` should simply be padded with 0 and no
149
+ `attention_mask` should be passed.
150
+
151
+ For Wav2Vec2 models that have set `config.feat_extract_norm == "layer"`, such as
152
+ [wav2vec2-lv60](https://huggingface.co/facebook/wav2vec2-large-960h-lv60-self), `attention_mask` should
153
+ be passed for batched inference.
154
+
155
+ </Tip>
156
+
157
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
158
+ If set, will return tensors instead of list of python integers. Acceptable values are:
159
+
160
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
161
+ - `'np'`: Return Numpy `np.ndarray` objects.
162
+ sampling_rate (`int`, *optional*):
163
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
164
+ `sampling_rate` at the forward call to prevent silent errors.
165
+ padding_value (`float`, *optional*, defaults to 0.0):
166
+ """
167
+
168
+ if sampling_rate is not None:
169
+ if sampling_rate != self.sampling_rate:
170
+ raise ValueError(
171
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
172
+ f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
173
+ f" {self.sampling_rate} and not {sampling_rate}."
174
+ )
175
+ else:
176
+ logger.warning(
177
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
178
+ "Failing to do so can result in silent errors that might be hard to debug."
179
+ )
180
+
181
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
182
+ if is_batched_numpy and len(raw_speech.shape) > 2:
183
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
184
+ is_batched = is_batched_numpy or (
185
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
186
+ )
187
+
188
+ # always return batch
189
+ if not is_batched:
190
+ raw_speech = [raw_speech]
191
+
192
+ # convert into correct format for padding
193
+ encoded_inputs = BatchFeature({"input_values": raw_speech})
194
+
195
+ padded_inputs = self.pad(
196
+ encoded_inputs,
197
+ padding=padding,
198
+ max_length=max_length,
199
+ truncation=truncation,
200
+ pad_to_multiple_of=pad_to_multiple_of,
201
+ return_attention_mask=return_attention_mask,
202
+ )
203
+
204
+ # convert input values to correct format
205
+ input_values = padded_inputs["input_values"]
206
+ if not isinstance(input_values[0], np.ndarray):
207
+ padded_inputs["input_values"] = [np.asarray(array, dtype=np.float32) for array in input_values]
208
+ elif (
209
+ not isinstance(input_values, np.ndarray)
210
+ and isinstance(input_values[0], np.ndarray)
211
+ and input_values[0].dtype is np.dtype(np.float64)
212
+ ):
213
+ padded_inputs["input_values"] = [array.astype(np.float32) for array in input_values]
214
+ elif isinstance(input_values, np.ndarray) and input_values.dtype is np.dtype(np.float64):
215
+ padded_inputs["input_values"] = input_values.astype(np.float32)
216
+
217
+ # convert attention_mask to correct format
218
+ attention_mask = padded_inputs.get("attention_mask")
219
+ if attention_mask is not None:
220
+ padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
221
+
222
+ # zero-mean and unit-variance normalization
223
+ if self.do_normalize:
224
+ attention_mask = (
225
+ attention_mask
226
+ if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
227
+ else None
228
+ )
229
+ padded_inputs["input_values"] = self.zero_mean_unit_var_norm(
230
+ padded_inputs["input_values"], attention_mask=attention_mask, padding_value=self.padding_value
231
+ )
232
+
233
+ if return_tensors is not None:
234
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
235
+
236
+ return padded_inputs
237
+
238
+
239
+ __all__ = ["Wav2Vec2FeatureExtractor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/modeling_wav2vec2.py ADDED
@@ -0,0 +1,2153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Fairseq Authors 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
+ """PyTorch Wav2Vec2 model."""
15
+
16
+ import math
17
+ import warnings
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+ import torch
23
+ from safetensors.torch import load_file as safe_load_file
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ... import initialization as init
28
+ from ...activations import ACT2FN
29
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
30
+ from ...integrations.fsdp import is_fsdp_managed_module
31
+ from ...masking_utils import create_bidirectional_mask
32
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ CausalLMOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ Wav2Vec2BaseModelOutput,
40
+ XVectorOutput,
41
+ )
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, get_torch_context_manager_or_global_device
43
+ from ...processing_utils import Unpack
44
+ from ...utils import (
45
+ ModelOutput,
46
+ TransformersKwargs,
47
+ auto_docstring,
48
+ cached_file,
49
+ check_torch_load_is_safe,
50
+ is_peft_available,
51
+ logging,
52
+ )
53
+ from .configuration_wav2vec2 import Wav2Vec2Config
54
+
55
+
56
+ WAV2VEC2_ADAPTER_PT_FILE = "adapter.{}.bin"
57
+ WAV2VEC2_ADAPTER_SAFE_FILE = "adapter.{}.safetensors"
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+
63
+ _HIDDEN_STATES_START_POSITION = 2
64
+
65
+
66
+ @auto_docstring(
67
+ custom_intro="""
68
+ Output type of [`Wav2Vec2ForPreTraining`], with potential hidden states and attentions.
69
+ """
70
+ )
71
+ @dataclass
72
+ class Wav2Vec2ForPreTrainingOutput(ModelOutput):
73
+ r"""
74
+ loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
75
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
76
+ paper](https://huggingface.co/papers/2006.11477).
77
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
78
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
79
+ projected quantized states.
80
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
81
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
82
+ target vectors for contrastive loss.
83
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
84
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
85
+ contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
86
+ The contrastive loss (L_m) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
87
+ diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
88
+ The diversity loss (L_d) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
89
+ """
90
+
91
+ loss: torch.FloatTensor | None = None
92
+ projected_states: torch.FloatTensor | None = None
93
+ projected_quantized_states: torch.FloatTensor | None = None
94
+ codevector_perplexity: torch.FloatTensor | None = None
95
+ hidden_states: tuple[torch.FloatTensor] | None = None
96
+ attentions: tuple[torch.FloatTensor] | None = None
97
+ contrastive_loss: torch.FloatTensor | None = None
98
+ diversity_loss: torch.FloatTensor | None = None
99
+
100
+
101
+ def _compute_mask_indices(
102
+ shape: tuple[int, int],
103
+ mask_prob: float,
104
+ mask_length: int,
105
+ attention_mask: torch.LongTensor | None = None,
106
+ min_masks: int = 0,
107
+ ) -> np.ndarray:
108
+ """
109
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
110
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
111
+ CPU as part of the preprocessing during training.
112
+
113
+ Args:
114
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
115
+ the first element is the batch size and the second element is the length of the axis to span.
116
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
117
+ independently generated mask spans of length `mask_length` is computed by
118
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
119
+ actual percentage will be smaller.
120
+ mask_length: size of the mask
121
+ min_masks: minimum number of masked spans
122
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
123
+ each batch dimension.
124
+ """
125
+ batch_size, sequence_length = shape
126
+
127
+ if mask_length < 1:
128
+ raise ValueError("`mask_length` has to be bigger than 0.")
129
+
130
+ if mask_length > sequence_length:
131
+ raise ValueError(
132
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
133
+ f" and `sequence_length`: {sequence_length}`"
134
+ )
135
+
136
+ # epsilon is used for probabilistic rounding
137
+ epsilon = np.random.rand(1).item()
138
+
139
+ def compute_num_masked_span(input_length):
140
+ """Given input length, compute how many spans should be masked"""
141
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
142
+ num_masked_span = max(num_masked_span, min_masks)
143
+
144
+ # make sure num masked span <= sequence_length
145
+ if num_masked_span * mask_length > sequence_length:
146
+ num_masked_span = sequence_length // mask_length
147
+
148
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
149
+ if input_length - (mask_length - 1) < num_masked_span:
150
+ num_masked_span = max(input_length - (mask_length - 1), 0)
151
+
152
+ return num_masked_span
153
+
154
+ # compute number of masked spans in batch
155
+ input_lengths = (
156
+ attention_mask.detach().sum(-1).tolist()
157
+ if attention_mask is not None
158
+ else [sequence_length for _ in range(batch_size)]
159
+ )
160
+
161
+ # SpecAugment mask to fill
162
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
163
+ spec_aug_mask_idxs = []
164
+
165
+ max_num_masked_span = compute_num_masked_span(sequence_length)
166
+
167
+ if max_num_masked_span == 0:
168
+ return spec_aug_mask
169
+
170
+ for input_length in input_lengths:
171
+ # compute num of masked spans for this input
172
+ num_masked_span = compute_num_masked_span(input_length)
173
+
174
+ # get random indices to mask
175
+ spec_aug_mask_idx = np.random.choice(
176
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
177
+ )
178
+
179
+ # pick first sampled index that will serve as a dummy index to pad vector
180
+ # to ensure same dimension for all batches due to probabilistic rounding
181
+ # Picking first sample just pads those vectors twice.
182
+ if len(spec_aug_mask_idx) == 0:
183
+ # this case can only happen if `input_length` is strictly smaller then
184
+ # `sequence_length` in which case the last token has to be a padding
185
+ # token which we can use as a dummy mask id
186
+ dummy_mask_idx = sequence_length - 1
187
+ else:
188
+ dummy_mask_idx = spec_aug_mask_idx[0]
189
+
190
+ spec_aug_mask_idx = np.concatenate(
191
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
192
+ )
193
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
194
+
195
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
196
+
197
+ # expand masked indices to masked spans
198
+ spec_aug_mask_idxs = np.broadcast_to(
199
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
200
+ )
201
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
202
+
203
+ # add offset to the starting indexes so that indexes now create a span
204
+ offsets = np.arange(mask_length)[None, None, :]
205
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
206
+ batch_size, max_num_masked_span * mask_length
207
+ )
208
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
209
+
210
+ # ensure that we cannot have indices larger than sequence_length
211
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
212
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
213
+
214
+ # scatter indices to mask
215
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
216
+
217
+ return spec_aug_mask
218
+
219
+
220
+ def _sample_negative_indices(features_shape: tuple, num_negatives: int, mask_time_indices: np.ndarray | None = None):
221
+ """
222
+ Sample `num_negatives` vectors from feature vectors.
223
+ """
224
+ batch_size, sequence_length = features_shape
225
+
226
+ # generate indices of the positive vectors themselves, repeat them `num_negatives` times
227
+ sequence_length_range = np.arange(sequence_length)
228
+
229
+ # get `num_negatives` random vector indices from the same utterance
230
+ sampled_negative_indices = np.zeros(shape=(batch_size, sequence_length, num_negatives), dtype=np.int32)
231
+
232
+ mask_time_indices = (
233
+ mask_time_indices.astype(bool) if mask_time_indices is not None else np.ones(features_shape, dtype=bool)
234
+ )
235
+
236
+ for batch_idx in range(batch_size):
237
+ high = mask_time_indices[batch_idx].sum() - 1
238
+ mapped_masked_indices = sequence_length_range[mask_time_indices[batch_idx]]
239
+
240
+ feature_indices = np.broadcast_to(np.arange(high + 1)[:, None], (high + 1, num_negatives))
241
+ sampled_indices = np.random.randint(0, high, size=(high + 1, num_negatives))
242
+ # avoid sampling the same positive vector, but keep the distribution uniform
243
+ sampled_indices[sampled_indices >= feature_indices] += 1
244
+
245
+ # remap to actual indices
246
+ sampled_negative_indices[batch_idx][mask_time_indices[batch_idx]] = mapped_masked_indices[sampled_indices]
247
+
248
+ # correct for batch size
249
+ sampled_negative_indices[batch_idx] += batch_idx * sequence_length
250
+
251
+ return sampled_negative_indices
252
+
253
+
254
+ class Wav2Vec2NoLayerNormConvLayer(GradientCheckpointingLayer):
255
+ def __init__(self, config, layer_id=0):
256
+ super().__init__()
257
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
258
+ self.out_conv_dim = config.conv_dim[layer_id]
259
+
260
+ self.conv = nn.Conv1d(
261
+ self.in_conv_dim,
262
+ self.out_conv_dim,
263
+ kernel_size=config.conv_kernel[layer_id],
264
+ stride=config.conv_stride[layer_id],
265
+ bias=config.conv_bias,
266
+ )
267
+ self.activation = ACT2FN[config.feat_extract_activation]
268
+
269
+ def forward(self, hidden_states):
270
+ hidden_states = self.conv(hidden_states)
271
+ hidden_states = self.activation(hidden_states)
272
+ return hidden_states
273
+
274
+
275
+ class Wav2Vec2LayerNormConvLayer(GradientCheckpointingLayer):
276
+ def __init__(self, config, layer_id=0):
277
+ super().__init__()
278
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
279
+ self.out_conv_dim = config.conv_dim[layer_id]
280
+
281
+ self.conv = nn.Conv1d(
282
+ self.in_conv_dim,
283
+ self.out_conv_dim,
284
+ kernel_size=config.conv_kernel[layer_id],
285
+ stride=config.conv_stride[layer_id],
286
+ bias=config.conv_bias,
287
+ )
288
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
289
+ self.activation = ACT2FN[config.feat_extract_activation]
290
+
291
+ def forward(self, hidden_states):
292
+ hidden_states = self.conv(hidden_states)
293
+
294
+ hidden_states = hidden_states.transpose(-2, -1)
295
+ hidden_states = self.layer_norm(hidden_states)
296
+ hidden_states = hidden_states.transpose(-2, -1)
297
+
298
+ hidden_states = self.activation(hidden_states)
299
+ return hidden_states
300
+
301
+
302
+ class Wav2Vec2GroupNormConvLayer(GradientCheckpointingLayer):
303
+ def __init__(self, config, layer_id=0):
304
+ super().__init__()
305
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
306
+ self.out_conv_dim = config.conv_dim[layer_id]
307
+
308
+ self.conv = nn.Conv1d(
309
+ self.in_conv_dim,
310
+ self.out_conv_dim,
311
+ kernel_size=config.conv_kernel[layer_id],
312
+ stride=config.conv_stride[layer_id],
313
+ bias=config.conv_bias,
314
+ )
315
+ self.activation = ACT2FN[config.feat_extract_activation]
316
+
317
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
318
+
319
+ def forward(self, hidden_states):
320
+ hidden_states = self.conv(hidden_states)
321
+ hidden_states = self.layer_norm(hidden_states)
322
+ hidden_states = self.activation(hidden_states)
323
+ return hidden_states
324
+
325
+
326
+ class Wav2Vec2PositionalConvEmbedding(nn.Module):
327
+ def __init__(self, config):
328
+ super().__init__()
329
+ self.conv = nn.Conv1d(
330
+ config.hidden_size,
331
+ config.hidden_size,
332
+ kernel_size=config.num_conv_pos_embeddings,
333
+ padding=config.num_conv_pos_embeddings // 2,
334
+ groups=config.num_conv_pos_embedding_groups,
335
+ )
336
+
337
+ weight_norm = nn.utils.weight_norm
338
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
339
+ weight_norm = nn.utils.parametrizations.weight_norm
340
+
341
+ if is_deepspeed_zero3_enabled():
342
+ import deepspeed
343
+
344
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
345
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
346
+ if hasattr(self.conv, "parametrizations"):
347
+ weight_g = self.conv.parametrizations.weight.original0
348
+ weight_v = self.conv.parametrizations.weight.original1
349
+ else:
350
+ weight_g = self.conv.weight_g
351
+ weight_v = self.conv.weight_v
352
+ deepspeed.zero.register_external_parameter(self, weight_v)
353
+ deepspeed.zero.register_external_parameter(self, weight_g)
354
+ else:
355
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
356
+
357
+ self.padding = Wav2Vec2SamePadLayer(config.num_conv_pos_embeddings)
358
+ self.activation = ACT2FN[config.feat_extract_activation]
359
+
360
+ def forward(self, hidden_states):
361
+ hidden_states = hidden_states.transpose(1, 2)
362
+
363
+ hidden_states = self.conv(hidden_states)
364
+ hidden_states = self.padding(hidden_states)
365
+ hidden_states = self.activation(hidden_states)
366
+
367
+ hidden_states = hidden_states.transpose(1, 2)
368
+ return hidden_states
369
+
370
+
371
+ class Wav2Vec2SamePadLayer(nn.Module):
372
+ def __init__(self, num_conv_pos_embeddings):
373
+ super().__init__()
374
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
375
+
376
+ def forward(self, hidden_states):
377
+ if self.num_pad_remove > 0:
378
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
379
+ return hidden_states
380
+
381
+
382
+ class Wav2Vec2FeatureEncoder(nn.Module):
383
+ """Construct the features from raw audio waveform"""
384
+
385
+ def __init__(self, config):
386
+ super().__init__()
387
+
388
+ if config.feat_extract_norm == "group":
389
+ conv_layers = [Wav2Vec2GroupNormConvLayer(config, layer_id=0)] + [
390
+ Wav2Vec2NoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
391
+ ]
392
+ elif config.feat_extract_norm == "layer":
393
+ conv_layers = [
394
+ Wav2Vec2LayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
395
+ ]
396
+ else:
397
+ raise ValueError(
398
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
399
+ )
400
+ self.conv_layers = nn.ModuleList(conv_layers)
401
+ self.gradient_checkpointing = False
402
+ self._requires_grad = True
403
+
404
+ def _freeze_parameters(self):
405
+ for param in self.parameters():
406
+ param.requires_grad = False
407
+ self._requires_grad = False
408
+
409
+ def forward(self, input_values):
410
+ hidden_states = input_values[:, None]
411
+
412
+ # make sure hidden_states require grad for gradient_checkpointing
413
+ if self._requires_grad and self.training:
414
+ hidden_states.requires_grad = True
415
+
416
+ for conv_layer in self.conv_layers:
417
+ hidden_states = conv_layer(hidden_states)
418
+
419
+ return hidden_states
420
+
421
+
422
+ class Wav2Vec2FeatureProjection(nn.Module):
423
+ def __init__(self, config):
424
+ super().__init__()
425
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
426
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
427
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
428
+
429
+ def forward(self, hidden_states):
430
+ # non-projected hidden states are needed for quantization
431
+ norm_hidden_states = self.layer_norm(hidden_states)
432
+ hidden_states = self.projection(norm_hidden_states)
433
+ hidden_states = self.dropout(hidden_states)
434
+ return hidden_states, norm_hidden_states
435
+
436
+
437
+ # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
438
+ def eager_attention_forward(
439
+ module: nn.Module,
440
+ query: torch.Tensor,
441
+ key: torch.Tensor,
442
+ value: torch.Tensor,
443
+ attention_mask: torch.Tensor | None,
444
+ scaling: float | None = None,
445
+ dropout: float = 0.0,
446
+ **kwargs: Unpack[TransformersKwargs],
447
+ ):
448
+ if scaling is None:
449
+ scaling = query.size(-1) ** -0.5
450
+
451
+ # Take the dot product between "query" and "key" to get the raw attention scores.
452
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
453
+
454
+ if attention_mask is not None:
455
+ attn_weights = attn_weights + attention_mask
456
+
457
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
458
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
459
+
460
+ attn_output = torch.matmul(attn_weights, value)
461
+ attn_output = attn_output.transpose(1, 2).contiguous()
462
+
463
+ return attn_output, attn_weights
464
+
465
+
466
+ class Wav2Vec2Attention(nn.Module):
467
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
468
+
469
+ def __init__(
470
+ self,
471
+ embed_dim: int,
472
+ num_heads: int,
473
+ dropout: float = 0.0,
474
+ is_decoder: bool = False,
475
+ bias: bool = True,
476
+ is_causal: bool = False,
477
+ config: Wav2Vec2Config | None = None,
478
+ ):
479
+ super().__init__()
480
+ self.embed_dim = embed_dim
481
+ self.num_heads = num_heads
482
+ self.dropout = dropout
483
+ self.head_dim = embed_dim // num_heads
484
+ self.config = config
485
+
486
+ if (self.head_dim * num_heads) != self.embed_dim:
487
+ raise ValueError(
488
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
489
+ f" and `num_heads`: {num_heads})."
490
+ )
491
+ self.scaling = self.head_dim**-0.5
492
+ self.is_decoder = is_decoder
493
+ self.is_causal = is_causal
494
+
495
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
496
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
497
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
498
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
499
+
500
+ def forward(
501
+ self,
502
+ hidden_states: torch.Tensor,
503
+ key_value_states: torch.Tensor | None = None,
504
+ attention_mask: torch.Tensor | None = None,
505
+ output_attentions: bool | None = False,
506
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
507
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
508
+ **kwargs: Unpack[FlashAttentionKwargs],
509
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
510
+ """Input shape: Batch x Time x Channel"""
511
+
512
+ # if key_value_states are provided this layer is used as a cross-attention layer
513
+ # for the decoder
514
+ is_cross_attention = key_value_states is not None
515
+
516
+ # determine input shapes
517
+ input_shape = hidden_states.shape[:-1]
518
+
519
+ hidden_shape = (*input_shape, -1, self.head_dim)
520
+
521
+ # get query proj
522
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
523
+
524
+ current_states = key_value_states if is_cross_attention else hidden_states
525
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
526
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
527
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
528
+
529
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
530
+ self.config._attn_implementation, eager_attention_forward
531
+ )
532
+
533
+ attn_output, attn_weights = attention_interface(
534
+ self,
535
+ query_states,
536
+ key_states,
537
+ value_states,
538
+ attention_mask,
539
+ dropout=0.0 if not self.training else self.dropout,
540
+ scaling=self.scaling,
541
+ output_attentions=output_attentions,
542
+ **kwargs,
543
+ )
544
+
545
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
546
+ attn_output = self.out_proj(attn_output)
547
+
548
+ return attn_output, attn_weights, None
549
+
550
+
551
+ class Wav2Vec2FeedForward(nn.Module):
552
+ def __init__(self, config):
553
+ super().__init__()
554
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
555
+
556
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
557
+ if isinstance(config.hidden_act, str):
558
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
559
+ else:
560
+ self.intermediate_act_fn = config.hidden_act
561
+
562
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
563
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
564
+
565
+ def forward(self, hidden_states):
566
+ hidden_states = self.intermediate_dense(hidden_states)
567
+ hidden_states = self.intermediate_act_fn(hidden_states)
568
+ hidden_states = self.intermediate_dropout(hidden_states)
569
+
570
+ hidden_states = self.output_dense(hidden_states)
571
+ hidden_states = self.output_dropout(hidden_states)
572
+ return hidden_states
573
+
574
+
575
+ class Wav2Vec2EncoderLayer(GradientCheckpointingLayer):
576
+ def __init__(self, config):
577
+ super().__init__()
578
+ self.attention = Wav2Vec2Attention(
579
+ embed_dim=config.hidden_size,
580
+ num_heads=config.num_attention_heads,
581
+ dropout=config.attention_dropout,
582
+ is_decoder=False,
583
+ config=config,
584
+ )
585
+
586
+ self.dropout = nn.Dropout(config.hidden_dropout)
587
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
588
+ self.feed_forward = Wav2Vec2FeedForward(config)
589
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
590
+
591
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
592
+ attn_residual = hidden_states
593
+ hidden_states, attn_weights, _ = self.attention(
594
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
595
+ )
596
+ hidden_states = self.dropout(hidden_states)
597
+ hidden_states = attn_residual + hidden_states
598
+
599
+ hidden_states = self.layer_norm(hidden_states)
600
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
601
+ hidden_states = self.final_layer_norm(hidden_states)
602
+
603
+ outputs = (hidden_states,)
604
+
605
+ if output_attentions:
606
+ outputs += (attn_weights,)
607
+
608
+ return outputs
609
+
610
+
611
+ class Wav2Vec2EncoderLayerStableLayerNorm(GradientCheckpointingLayer):
612
+ def __init__(self, config):
613
+ super().__init__()
614
+ self.attention = Wav2Vec2Attention(
615
+ embed_dim=config.hidden_size,
616
+ num_heads=config.num_attention_heads,
617
+ dropout=config.attention_dropout,
618
+ is_decoder=False,
619
+ config=config,
620
+ )
621
+ self.dropout = nn.Dropout(config.hidden_dropout)
622
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
623
+ self.feed_forward = Wav2Vec2FeedForward(config)
624
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
625
+
626
+ if getattr(config, "adapter_attn_dim", None) is not None:
627
+ self.adapter_layer = Wav2Vec2AttnAdapterLayer(config)
628
+ else:
629
+ self.adapter_layer = None
630
+
631
+ def forward(
632
+ self,
633
+ hidden_states: torch.Tensor,
634
+ attention_mask: torch.Tensor | None = None,
635
+ output_attentions: bool = False,
636
+ ):
637
+ attn_residual = hidden_states
638
+ hidden_states = self.layer_norm(hidden_states)
639
+ hidden_states, attn_weights, _ = self.attention(
640
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
641
+ )
642
+ hidden_states = self.dropout(hidden_states)
643
+ hidden_states = attn_residual + hidden_states
644
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
645
+
646
+ if self.adapter_layer is not None:
647
+ hidden_states = hidden_states + self.adapter_layer(hidden_states)
648
+
649
+ outputs = (hidden_states,)
650
+
651
+ if output_attentions:
652
+ outputs += (attn_weights,)
653
+
654
+ return outputs
655
+
656
+
657
+ class Wav2Vec2Encoder(nn.Module):
658
+ def __init__(self, config):
659
+ super().__init__()
660
+ self.config = config
661
+ self.pos_conv_embed = Wav2Vec2PositionalConvEmbedding(config)
662
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
663
+ self.dropout = nn.Dropout(config.hidden_dropout)
664
+ self.layers = nn.ModuleList([Wav2Vec2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
665
+ self.gradient_checkpointing = False
666
+
667
+ def forward(
668
+ self,
669
+ hidden_states: torch.tensor,
670
+ attention_mask: torch.Tensor | None = None,
671
+ output_attentions: bool = False,
672
+ output_hidden_states: bool = False,
673
+ return_dict: bool = True,
674
+ ):
675
+ all_hidden_states = () if output_hidden_states else None
676
+ all_self_attentions = () if output_attentions else None
677
+
678
+ if attention_mask is not None:
679
+ # make sure padded tokens output 0
680
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
681
+ hidden_states[~expand_attention_mask] = 0
682
+
683
+ attention_mask = create_bidirectional_mask(
684
+ config=self.config,
685
+ inputs_embeds=hidden_states,
686
+ attention_mask=attention_mask,
687
+ )
688
+
689
+ position_embeddings = self.pos_conv_embed(hidden_states)
690
+ hidden_states = hidden_states + position_embeddings.to(hidden_states.device)
691
+ hidden_states = self.layer_norm(hidden_states)
692
+ hidden_states = self.dropout(hidden_states)
693
+
694
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
695
+
696
+ for layer in self.layers:
697
+ if output_hidden_states:
698
+ all_hidden_states = all_hidden_states + (hidden_states,)
699
+
700
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
701
+ dropout_probability = torch.rand([])
702
+
703
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
704
+ if not skip_the_layer or synced_gpus:
705
+ # under fsdp or deepspeed zero3 all gpus must run in sync
706
+ layer_outputs = layer(
707
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
708
+ )
709
+ hidden_states = layer_outputs[0]
710
+
711
+ if skip_the_layer:
712
+ layer_outputs = (None, None)
713
+
714
+ if output_attentions:
715
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
716
+
717
+ if output_hidden_states:
718
+ all_hidden_states = all_hidden_states + (hidden_states,)
719
+
720
+ if not return_dict:
721
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
722
+ return BaseModelOutput(
723
+ last_hidden_state=hidden_states,
724
+ hidden_states=all_hidden_states,
725
+ attentions=all_self_attentions,
726
+ )
727
+
728
+
729
+ class Wav2Vec2EncoderStableLayerNorm(nn.Module):
730
+ def __init__(self, config):
731
+ super().__init__()
732
+ self.config = config
733
+ self.pos_conv_embed = Wav2Vec2PositionalConvEmbedding(config)
734
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
735
+ self.dropout = nn.Dropout(config.hidden_dropout)
736
+ self.layers = nn.ModuleList(
737
+ [Wav2Vec2EncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
738
+ )
739
+ self.gradient_checkpointing = False
740
+
741
+ def forward(
742
+ self,
743
+ hidden_states,
744
+ attention_mask=None,
745
+ output_attentions=False,
746
+ output_hidden_states=False,
747
+ return_dict=True,
748
+ ):
749
+ all_hidden_states = () if output_hidden_states else None
750
+ all_self_attentions = () if output_attentions else None
751
+
752
+ if attention_mask is not None:
753
+ # make sure padded tokens output 0
754
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
755
+ hidden_states[~expand_attention_mask] = 0
756
+
757
+ attention_mask = create_bidirectional_mask(
758
+ config=self.config,
759
+ inputs_embeds=hidden_states,
760
+ attention_mask=attention_mask,
761
+ )
762
+
763
+ position_embeddings = self.pos_conv_embed(hidden_states)
764
+ hidden_states = hidden_states + position_embeddings
765
+ hidden_states = self.dropout(hidden_states)
766
+
767
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
768
+
769
+ for layer in self.layers:
770
+ if output_hidden_states:
771
+ all_hidden_states = all_hidden_states + (hidden_states,)
772
+
773
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
774
+ dropout_probability = torch.rand([])
775
+
776
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
777
+ if not skip_the_layer or synced_gpus:
778
+ # under fsdp or deepspeed zero3 all gpus must run in sync
779
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
780
+ layer_outputs = layer(
781
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
782
+ )
783
+ hidden_states = layer_outputs[0]
784
+
785
+ if skip_the_layer:
786
+ layer_outputs = (None, None)
787
+
788
+ if output_attentions:
789
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
790
+
791
+ hidden_states = self.layer_norm(hidden_states)
792
+
793
+ if output_hidden_states:
794
+ all_hidden_states = all_hidden_states + (hidden_states,)
795
+
796
+ if not return_dict:
797
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
798
+ return BaseModelOutput(
799
+ last_hidden_state=hidden_states,
800
+ hidden_states=all_hidden_states,
801
+ attentions=all_self_attentions,
802
+ )
803
+
804
+
805
+ class Wav2Vec2GumbelVectorQuantizer(nn.Module):
806
+ """
807
+ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
808
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
809
+ """
810
+
811
+ def __init__(self, config):
812
+ super().__init__()
813
+ self.num_groups = config.num_codevector_groups
814
+ self.num_vars = config.num_codevectors_per_group
815
+
816
+ if config.codevector_dim % self.num_groups != 0:
817
+ raise ValueError(
818
+ f"`config.codevector_dim {config.codevector_dim} must be divisible "
819
+ f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
820
+ )
821
+
822
+ # storage for codebook variables (codewords)
823
+ self.codevectors = nn.Parameter(
824
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
825
+ )
826
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
827
+
828
+ # can be decayed for training
829
+ self.temperature = 2
830
+
831
+ @staticmethod
832
+ def _compute_perplexity(probs, mask=None):
833
+ if mask is not None:
834
+ mask_extended = mask.flatten()[:, None, None].expand(probs.shape)
835
+ probs = torch.where(mask_extended, probs, torch.zeros_like(probs))
836
+ marginal_probs = probs.sum(dim=0) / mask.sum()
837
+ else:
838
+ marginal_probs = probs.mean(dim=0)
839
+
840
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
841
+ return perplexity
842
+
843
+ def forward(self, hidden_states, mask_time_indices=None):
844
+ batch_size, sequence_length, hidden_size = hidden_states.shape
845
+
846
+ # project to codevector dim
847
+ hidden_states = self.weight_proj(hidden_states)
848
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
849
+
850
+ if self.training:
851
+ # sample code vector probs via gumbel in differentiateable way
852
+ codevector_probs = nn.functional.gumbel_softmax(
853
+ hidden_states.float(), tau=self.temperature, hard=True
854
+ ).type_as(hidden_states)
855
+
856
+ # compute perplexity
857
+ codevector_soft_dist = torch.softmax(
858
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
859
+ )
860
+ perplexity = self._compute_perplexity(codevector_soft_dist, mask_time_indices)
861
+ else:
862
+ # take argmax in non-differentiable way
863
+ # comptute hard codevector distribution (one hot)
864
+ codevector_idx = hidden_states.argmax(dim=-1)
865
+ codevector_probs = hidden_states.new_zeros(hidden_states.shape).scatter_(
866
+ -1, codevector_idx.view(-1, 1), 1.0
867
+ )
868
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
869
+
870
+ perplexity = self._compute_perplexity(codevector_probs, mask_time_indices)
871
+
872
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
873
+ # use probs to retrieve codevectors
874
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
875
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
876
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
877
+
878
+ return codevectors, perplexity
879
+
880
+
881
+ class Wav2Vec2Adapter(nn.Module):
882
+ def __init__(self, config):
883
+ super().__init__()
884
+
885
+ # feature dim might need to be down-projected
886
+ if config.output_hidden_size != config.hidden_size:
887
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
888
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
889
+ else:
890
+ self.proj = self.proj_layer_norm = None
891
+
892
+ self.layers = nn.ModuleList(Wav2Vec2AdapterLayer(config) for _ in range(config.num_adapter_layers))
893
+ self.layerdrop = config.layerdrop
894
+
895
+ def forward(self, hidden_states):
896
+ # down project hidden_states if necessary
897
+ if self.proj is not None and self.proj_layer_norm is not None:
898
+ hidden_states = self.proj(hidden_states)
899
+ hidden_states = self.proj_layer_norm(hidden_states)
900
+
901
+ hidden_states = hidden_states.transpose(1, 2)
902
+
903
+ for layer in self.layers:
904
+ layerdrop_prob = np.random.random()
905
+ if not self.training or (layerdrop_prob > self.layerdrop):
906
+ hidden_states = layer(hidden_states)
907
+
908
+ hidden_states = hidden_states.transpose(1, 2)
909
+ return hidden_states
910
+
911
+
912
+ class Wav2Vec2AdapterLayer(nn.Module):
913
+ def __init__(self, config):
914
+ super().__init__()
915
+ self.conv = nn.Conv1d(
916
+ config.output_hidden_size,
917
+ 2 * config.output_hidden_size,
918
+ config.adapter_kernel_size,
919
+ stride=config.adapter_stride,
920
+ padding=1,
921
+ )
922
+
923
+ def forward(self, hidden_states):
924
+ hidden_states = self.conv(hidden_states)
925
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
926
+
927
+ return hidden_states
928
+
929
+
930
+ class Wav2Vec2AttnAdapterLayer(nn.Module):
931
+ def __init__(self, config):
932
+ """
933
+ Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
934
+ up training throughput.
935
+ """
936
+ super().__init__()
937
+ self.input_dim = config.adapter_attn_dim
938
+ self.hidden_dim = config.hidden_size
939
+
940
+ self.norm = nn.LayerNorm(self.hidden_dim)
941
+ self.linear_1 = nn.Linear(self.hidden_dim, self.input_dim)
942
+ self.act_fn = nn.ReLU()
943
+ self.linear_2 = nn.Linear(self.input_dim, self.hidden_dim)
944
+
945
+ def forward(self, hidden_states: torch.FloatTensor):
946
+ hidden_states = self.norm(hidden_states)
947
+
948
+ hidden_states = self.linear_1(hidden_states)
949
+ hidden_states = self.act_fn(hidden_states)
950
+ hidden_states = self.linear_2(hidden_states)
951
+
952
+ return hidden_states
953
+
954
+
955
+ @auto_docstring
956
+ class Wav2Vec2PreTrainedModel(PreTrainedModel):
957
+ config: Wav2Vec2Config
958
+ base_model_prefix = "wav2vec2"
959
+ main_input_name = "input_values"
960
+ input_modalities = "audio"
961
+ supports_gradient_checkpointing = True
962
+ _supports_flash_attn = True
963
+ _supports_sdpa = True
964
+ _supports_flex_attn = True
965
+
966
+ @torch.no_grad()
967
+ def _init_weights(self, module):
968
+ """Initialize the weights"""
969
+ # Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
970
+ if isinstance(module, Wav2Vec2ForPreTraining):
971
+ module.project_hid.reset_parameters()
972
+ module.project_q.reset_parameters()
973
+ # gumbel softmax requires special init
974
+ elif isinstance(module, Wav2Vec2GumbelVectorQuantizer):
975
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
976
+ init.zeros_(module.weight_proj.bias)
977
+ init.uniform_(module.codevectors)
978
+ elif isinstance(module, Wav2Vec2PositionalConvEmbedding):
979
+ init.normal_(
980
+ module.conv.weight,
981
+ mean=0,
982
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
983
+ )
984
+ init.constant_(module.conv.bias, 0)
985
+ elif isinstance(module, Wav2Vec2FeatureProjection):
986
+ k = math.sqrt(1 / module.projection.in_features)
987
+ init.uniform_(module.projection.weight, a=-k, b=k)
988
+ init.uniform_(module.projection.bias, a=-k, b=k)
989
+ elif isinstance(module, nn.Linear):
990
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
991
+
992
+ if module.bias is not None:
993
+ init.zeros_(module.bias)
994
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
995
+ init.zeros_(module.bias)
996
+ init.ones_(module.weight)
997
+ elif isinstance(module, nn.Conv1d):
998
+ init.kaiming_normal_(module.weight)
999
+
1000
+ if module.bias is not None:
1001
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
1002
+ init.uniform_(module.bias, a=-k, b=k)
1003
+
1004
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
1005
+ """
1006
+ Computes the output length of the convolutional layers
1007
+ """
1008
+
1009
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
1010
+
1011
+ def _conv_out_length(input_length, kernel_size, stride):
1012
+ # 1D convolutional layer output length formula taken
1013
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1014
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
1015
+
1016
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
1017
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
1018
+
1019
+ if add_adapter:
1020
+ for _ in range(self.config.num_adapter_layers):
1021
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
1022
+
1023
+ return input_lengths
1024
+
1025
+ def _get_feature_vector_attention_mask(
1026
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
1027
+ ):
1028
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
1029
+ # on inference mode.
1030
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
1031
+
1032
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
1033
+ output_lengths = output_lengths.to(torch.long)
1034
+
1035
+ batch_size = attention_mask.shape[0]
1036
+
1037
+ attention_mask = torch.zeros(
1038
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
1039
+ )
1040
+ # these two operations makes sure that all values before the output lengths idxs are attended to
1041
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
1042
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
1043
+ return attention_mask
1044
+
1045
+ def _get_adapters(self):
1046
+ if self.config.adapter_attn_dim is None:
1047
+ raise ValueError(f"{self.__class__} has no adapter layers. Make sure to define `config.adapter_attn_dim`.")
1048
+
1049
+ adapter_weights = {}
1050
+ for name, module in self.named_modules():
1051
+ if isinstance(module, Wav2Vec2AttnAdapterLayer):
1052
+ for param_name, param in module.named_parameters():
1053
+ adapter_weights[".".join([name, param_name])] = param
1054
+
1055
+ if isinstance(self, Wav2Vec2ForCTC):
1056
+ for name, param in self.lm_head.named_parameters():
1057
+ adapter_weights[".".join(["lm_head", name])] = param
1058
+
1059
+ return adapter_weights
1060
+
1061
+ def init_adapter_layers(self):
1062
+ """
1063
+ (Re-)initialize attention adapter layers and lm head for adapter-only fine-tuning
1064
+ """
1065
+ # init attention adapters
1066
+ for module in self.modules():
1067
+ if isinstance(module, Wav2Vec2AttnAdapterLayer):
1068
+ self._init_weights(module)
1069
+
1070
+ # init lm head
1071
+ if isinstance(self, Wav2Vec2ForCTC):
1072
+ self._init_weights(self.lm_head)
1073
+
1074
+ def load_adapter(self, target_lang: str, force_load=True, **kwargs):
1075
+ r"""
1076
+ Load a language adapter model from a pre-trained adapter model.
1077
+
1078
+ Parameters:
1079
+ target_lang (`str`):
1080
+ Has to be a language id of an existing adapter weight. Adapter weights are stored in the format
1081
+ adapter.<lang>.safetensors or adapter.<lang>.bin
1082
+ force_load (`bool`, defaults to `True`):
1083
+ Whether the weights shall be loaded even if `target_lang` matches `self.target_lang`.
1084
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
1085
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
1086
+ standard cache should not be used.
1087
+ force_download (`bool`, *optional*, defaults to `False`):
1088
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
1089
+ cached versions if they exist.
1090
+ proxies (`dict[str, str]`, *optional*):
1091
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
1092
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
1093
+ local_files_only(`bool`, *optional*, defaults to `False`):
1094
+ Whether or not to only look at local files (i.e., do not try to download the model).
1095
+ token (`str` or `bool`, *optional*):
1096
+ The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
1097
+ the token generated when running `hf auth login` (stored in `~/.huggingface`).
1098
+ revision (`str`, *optional*, defaults to `"main"`):
1099
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
1100
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
1101
+ identifier allowed by git.
1102
+
1103
+ <Tip>
1104
+
1105
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
1106
+
1107
+ </Tip>
1108
+
1109
+ mirror (`str`, *optional*):
1110
+ Mirror source to accelerate downloads in China. If you are from China and have an accessibility
1111
+ problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
1112
+ Please refer to the mirror site for more information.
1113
+
1114
+ <Tip>
1115
+
1116
+ Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to
1117
+ use this method in a firewalled environment.
1118
+
1119
+ </Tip>
1120
+
1121
+ Examples:
1122
+
1123
+ ```python
1124
+ >>> from transformers import Wav2Vec2ForCTC, AutoProcessor
1125
+
1126
+ >>> ckpt = "facebook/mms-1b-all"
1127
+ >>> processor = AutoProcessor.from_pretrained(ckpt)
1128
+ >>> model = Wav2Vec2ForCTC.from_pretrained(ckpt, target_lang="eng")
1129
+ >>> # set specific language
1130
+ >>> processor.tokenizer.set_target_lang("spa")
1131
+ >>> model.load_adapter("spa")
1132
+ ```
1133
+ """
1134
+ if self.config.adapter_attn_dim is None:
1135
+ raise ValueError(f"Cannot load_adapter for {target_lang} if `config.adapter_attn_dim` is not defined.")
1136
+
1137
+ if target_lang == self.target_lang and not force_load:
1138
+ logger.warning(f"Adapter weights are already set to {target_lang}.")
1139
+ return
1140
+
1141
+ cache_dir = kwargs.pop("cache_dir", None)
1142
+ force_download = kwargs.pop("force_download", False)
1143
+ proxies = kwargs.pop("proxies", None)
1144
+ local_files_only = kwargs.pop("local_files_only", False)
1145
+ token = kwargs.pop("token", None)
1146
+ revision = kwargs.pop("revision", None)
1147
+ use_safetensors = kwargs.pop("use_safetensors", None)
1148
+ model_path_or_id = self.config._name_or_path
1149
+ state_dict = None
1150
+
1151
+ # 1. Let's first try loading a safetensors adapter weight
1152
+ if use_safetensors is not False:
1153
+ filepath = WAV2VEC2_ADAPTER_SAFE_FILE.format(target_lang)
1154
+
1155
+ try:
1156
+ weight_path = cached_file(
1157
+ model_path_or_id,
1158
+ filename=filepath,
1159
+ force_download=force_download,
1160
+ proxies=proxies,
1161
+ local_files_only=local_files_only,
1162
+ token=token,
1163
+ revision=revision,
1164
+ cache_dir=cache_dir,
1165
+ )
1166
+
1167
+ state_dict = safe_load_file(weight_path)
1168
+
1169
+ except OSError:
1170
+ if use_safetensors:
1171
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
1172
+ # to the original exception.
1173
+ raise
1174
+
1175
+ except Exception:
1176
+ # For any other exception, we throw a generic error.
1177
+ if use_safetensors:
1178
+ raise OSError(
1179
+ f"Can't load the model for '{model_path_or_id}'. If you were trying to load it"
1180
+ " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
1181
+ f" same name. Otherwise, make sure '{model_path_or_id}' is the correct path to a"
1182
+ f" directory containing a file named {filepath}."
1183
+ )
1184
+
1185
+ # 2. If this didn't work let's try loading a PyTorch adapter weight
1186
+ if state_dict is None:
1187
+ filepath = WAV2VEC2_ADAPTER_PT_FILE.format(target_lang)
1188
+
1189
+ try:
1190
+ weight_path = cached_file(
1191
+ model_path_or_id,
1192
+ filename=filepath,
1193
+ force_download=force_download,
1194
+ proxies=proxies,
1195
+ local_files_only=local_files_only,
1196
+ token=token,
1197
+ revision=revision,
1198
+ cache_dir=cache_dir,
1199
+ )
1200
+
1201
+ check_torch_load_is_safe()
1202
+ state_dict = torch.load(
1203
+ weight_path,
1204
+ map_location="cpu",
1205
+ weights_only=True,
1206
+ )
1207
+
1208
+ except OSError:
1209
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
1210
+ # to the original exception.
1211
+ raise
1212
+
1213
+ except ValueError:
1214
+ raise
1215
+
1216
+ except Exception:
1217
+ # For any other exception, we throw a generic error.
1218
+ raise OSError(
1219
+ f"Can't load the model for '{model_path_or_id}'. If you were trying to load it"
1220
+ " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
1221
+ f" same name. Otherwise, make sure '{model_path_or_id}' is the correct path to a"
1222
+ f" directory containing a file named {filepath}."
1223
+ )
1224
+
1225
+ adapter_weights = self._get_adapters()
1226
+ unexpected_keys = set(state_dict.keys()) - set(adapter_weights.keys())
1227
+ missing_keys = set(adapter_weights.keys()) - set(state_dict.keys())
1228
+
1229
+ if len(unexpected_keys) > 0:
1230
+ raise ValueError(f"The adapter weights {weight_path} has unexpected keys: {', '.join(unexpected_keys)}.")
1231
+ elif len(missing_keys) > 0:
1232
+ raise ValueError(f"The adapter weights {weight_path} has missing keys: {', '.join(missing_keys)}.")
1233
+
1234
+ # make sure now vocab size is correct
1235
+ target_vocab_size = state_dict["lm_head.weight"].shape[0]
1236
+ if target_vocab_size != self.config.vocab_size:
1237
+ self.lm_head = nn.Linear(
1238
+ self.config.output_hidden_size, target_vocab_size, device=self.device, dtype=self.dtype
1239
+ )
1240
+ self.config.vocab_size = target_vocab_size
1241
+
1242
+ # make sure that adapter weights are put in exactly the same precision and device placement and overwritten adapter weights
1243
+ state_dict = {k: v.to(adapter_weights[k]) for k, v in state_dict.items()}
1244
+ self.load_state_dict(state_dict, strict=False)
1245
+
1246
+ # set target language correctly
1247
+ self.target_lang = target_lang
1248
+
1249
+
1250
+ @auto_docstring
1251
+ class Wav2Vec2Model(Wav2Vec2PreTrainedModel):
1252
+ def __init__(self, config: Wav2Vec2Config):
1253
+ super().__init__(config)
1254
+ self.config = config
1255
+ self.feature_extractor = Wav2Vec2FeatureEncoder(config)
1256
+ self.feature_projection = Wav2Vec2FeatureProjection(config)
1257
+
1258
+ # model only needs masking vector if mask prob is > 0.0
1259
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
1260
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
1261
+
1262
+ if config.do_stable_layer_norm:
1263
+ self.encoder = Wav2Vec2EncoderStableLayerNorm(config)
1264
+ else:
1265
+ self.encoder = Wav2Vec2Encoder(config)
1266
+
1267
+ self.adapter = Wav2Vec2Adapter(config) if config.add_adapter else None
1268
+
1269
+ # Initialize weights and apply final processing
1270
+ self.post_init()
1271
+
1272
+ def freeze_feature_encoder(self):
1273
+ """
1274
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1275
+ not be updated during training.
1276
+ """
1277
+ self.feature_extractor._freeze_parameters()
1278
+
1279
+ def _mask_hidden_states(
1280
+ self,
1281
+ hidden_states: torch.FloatTensor,
1282
+ mask_time_indices: torch.FloatTensor | None = None,
1283
+ attention_mask: torch.LongTensor | None = None,
1284
+ ):
1285
+ """
1286
+ Masks extracted features along time axis and/or along feature axis according to
1287
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1288
+ """
1289
+
1290
+ # `config.apply_spec_augment` can set masking to False
1291
+ if not getattr(self.config, "apply_spec_augment", True):
1292
+ return hidden_states
1293
+
1294
+ # generate indices & apply SpecAugment along time axis
1295
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1296
+
1297
+ if mask_time_indices is not None:
1298
+ # apply SpecAugment along time axis with given mask_time_indices
1299
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1300
+ elif self.config.mask_time_prob > 0 and self.training:
1301
+ mask_time_indices = _compute_mask_indices(
1302
+ (batch_size, sequence_length),
1303
+ mask_prob=self.config.mask_time_prob,
1304
+ mask_length=self.config.mask_time_length,
1305
+ attention_mask=attention_mask,
1306
+ min_masks=self.config.mask_time_min_masks,
1307
+ )
1308
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1309
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1310
+
1311
+ if self.config.mask_feature_prob > 0 and self.training:
1312
+ # generate indices & apply SpecAugment along feature axis
1313
+ mask_feature_indices = _compute_mask_indices(
1314
+ (batch_size, hidden_size),
1315
+ mask_prob=self.config.mask_feature_prob,
1316
+ mask_length=self.config.mask_feature_length,
1317
+ min_masks=self.config.mask_feature_min_masks,
1318
+ )
1319
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1320
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1321
+ hidden_states[mask_feature_indices] = 0
1322
+
1323
+ return hidden_states
1324
+
1325
+ @auto_docstring
1326
+ def forward(
1327
+ self,
1328
+ input_values: torch.Tensor | None,
1329
+ attention_mask: torch.Tensor | None = None,
1330
+ mask_time_indices: torch.FloatTensor | None = None,
1331
+ output_attentions: bool | None = None,
1332
+ output_hidden_states: bool | None = None,
1333
+ return_dict: bool | None = None,
1334
+ **kwargs,
1335
+ ) -> tuple | Wav2Vec2BaseModelOutput:
1336
+ r"""
1337
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1338
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1339
+ masked extracted features in *config.proj_codevector_dim* space.
1340
+ """
1341
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1342
+ output_hidden_states = (
1343
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1344
+ )
1345
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1346
+
1347
+ extract_features = self.feature_extractor(input_values)
1348
+ extract_features = extract_features.transpose(1, 2)
1349
+
1350
+ if attention_mask is not None:
1351
+ # compute reduced attention_mask corresponding to feature vectors
1352
+ attention_mask = self._get_feature_vector_attention_mask(
1353
+ extract_features.shape[1], attention_mask, add_adapter=False
1354
+ )
1355
+
1356
+ hidden_states, extract_features = self.feature_projection(extract_features)
1357
+ hidden_states = self._mask_hidden_states(
1358
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1359
+ )
1360
+
1361
+ encoder_outputs = self.encoder(
1362
+ hidden_states,
1363
+ attention_mask=attention_mask,
1364
+ output_attentions=output_attentions,
1365
+ output_hidden_states=output_hidden_states,
1366
+ return_dict=return_dict,
1367
+ )
1368
+
1369
+ hidden_states = encoder_outputs[0]
1370
+
1371
+ if self.adapter is not None:
1372
+ hidden_states = self.adapter(hidden_states)
1373
+
1374
+ if not return_dict:
1375
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1376
+
1377
+ return Wav2Vec2BaseModelOutput(
1378
+ last_hidden_state=hidden_states,
1379
+ extract_features=extract_features,
1380
+ hidden_states=encoder_outputs.hidden_states,
1381
+ attentions=encoder_outputs.attentions,
1382
+ )
1383
+
1384
+
1385
+ @auto_docstring(
1386
+ custom_intro="""
1387
+ Wav2Vec2 Model with a quantizer and `VQ` head on top.
1388
+ """
1389
+ )
1390
+ class Wav2Vec2ForPreTraining(Wav2Vec2PreTrainedModel):
1391
+ def __init__(self, config: Wav2Vec2Config):
1392
+ super().__init__(config)
1393
+ self.wav2vec2 = Wav2Vec2Model(config)
1394
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1395
+
1396
+ self.quantizer = Wav2Vec2GumbelVectorQuantizer(config)
1397
+
1398
+ self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)
1399
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def set_gumbel_temperature(self, temperature: int):
1405
+ """
1406
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1407
+ """
1408
+ self.quantizer.temperature = temperature
1409
+
1410
+ def freeze_feature_encoder(self):
1411
+ """
1412
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1413
+ not be updated during training.
1414
+ """
1415
+ self.wav2vec2.feature_extractor._freeze_parameters()
1416
+
1417
+ @staticmethod
1418
+ def compute_contrastive_logits(
1419
+ target_features: torch.FloatTensor,
1420
+ negative_features: torch.FloatTensor,
1421
+ predicted_features: torch.FloatTensor,
1422
+ temperature: float = 0.1,
1423
+ ):
1424
+ """
1425
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1426
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1427
+ """
1428
+ target_features = torch.cat([target_features, negative_features], dim=0)
1429
+
1430
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1).type_as(
1431
+ target_features
1432
+ )
1433
+
1434
+ # apply temperature
1435
+ logits = logits / temperature
1436
+ return logits
1437
+
1438
+ @auto_docstring
1439
+ def forward(
1440
+ self,
1441
+ input_values: torch.Tensor | None,
1442
+ attention_mask: torch.Tensor | None = None,
1443
+ mask_time_indices: torch.BoolTensor | None = None,
1444
+ sampled_negative_indices: torch.BoolTensor | None = None,
1445
+ output_attentions: bool | None = None,
1446
+ output_hidden_states: bool | None = None,
1447
+ return_dict: bool | None = None,
1448
+ **kwargs,
1449
+ ) -> tuple | Wav2Vec2ForPreTrainingOutput:
1450
+ r"""
1451
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1452
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1453
+ masked extracted features in *config.proj_codevector_dim* space.
1454
+ sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
1455
+ Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
1456
+ Required input for pre-training.
1457
+
1458
+ Example:
1459
+
1460
+ ```python
1461
+ >>> import torch
1462
+ >>> from transformers import AutoFeatureExtractor, Wav2Vec2ForPreTraining
1463
+ >>> from transformers.models.wav2vec2.modeling_wav2vec2 import _compute_mask_indices, _sample_negative_indices
1464
+ >>> from datasets import load_dataset
1465
+
1466
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
1467
+ >>> model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base")
1468
+
1469
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1470
+ >>> input_values = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt").input_values # Batch size 1
1471
+
1472
+ >>> # compute masked indices
1473
+ >>> batch_size, raw_sequence_length = input_values.shape
1474
+ >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length).item()
1475
+ >>> mask_time_indices = _compute_mask_indices(
1476
+ ... shape=(batch_size, sequence_length), mask_prob=0.2, mask_length=2
1477
+ ... )
1478
+ >>> sampled_negative_indices = _sample_negative_indices(
1479
+ ... features_shape=(batch_size, sequence_length),
1480
+ ... num_negatives=model.config.num_negatives,
1481
+ ... mask_time_indices=mask_time_indices,
1482
+ ... )
1483
+ >>> mask_time_indices = torch.tensor(data=mask_time_indices, device=input_values.device, dtype=torch.long)
1484
+ >>> sampled_negative_indices = torch.tensor(
1485
+ ... data=sampled_negative_indices, device=input_values.device, dtype=torch.long
1486
+ ... )
1487
+
1488
+ >>> with torch.no_grad():
1489
+ ... outputs = model(input_values, mask_time_indices=mask_time_indices)
1490
+
1491
+ >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)
1492
+ >>> cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)
1493
+
1494
+ >>> # show that cosine similarity is much higher than random
1495
+ >>> cosine_sim[mask_time_indices.to(torch.bool)].mean() > 0.5
1496
+ tensor(True)
1497
+
1498
+ >>> # for contrastive loss training model should be put into train mode
1499
+ >>> model = model.train()
1500
+ >>> loss = model(
1501
+ ... input_values, mask_time_indices=mask_time_indices, sampled_negative_indices=sampled_negative_indices
1502
+ ... ).loss
1503
+ ```"""
1504
+
1505
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1506
+
1507
+ if mask_time_indices is not None:
1508
+ mask_time_indices = mask_time_indices.to(torch.bool)
1509
+
1510
+ outputs = self.wav2vec2(
1511
+ input_values,
1512
+ attention_mask=attention_mask,
1513
+ output_attentions=output_attentions,
1514
+ output_hidden_states=output_hidden_states,
1515
+ mask_time_indices=mask_time_indices,
1516
+ return_dict=return_dict,
1517
+ )
1518
+
1519
+ # 1. project all transformed features (including masked) to final vq dim
1520
+ transformer_features = self.project_hid(outputs[0])
1521
+
1522
+ # 2. quantize all (unmasked) extracted features and project to final vq dim
1523
+ extract_features = self.dropout_features(outputs[1])
1524
+
1525
+ if attention_mask is not None:
1526
+ # compute reduced attention_mask corresponding to feature vectors
1527
+ attention_mask = self._get_feature_vector_attention_mask(
1528
+ extract_features.shape[1], attention_mask, add_adapter=False
1529
+ )
1530
+
1531
+ quantized_features, codevector_perplexity = self.quantizer(
1532
+ extract_features, mask_time_indices=mask_time_indices
1533
+ )
1534
+
1535
+ quantized_features = quantized_features.to(self.project_q.weight.dtype)
1536
+ quantized_features = self.project_q(quantized_features)
1537
+
1538
+ loss = contrastive_loss = diversity_loss = None
1539
+ if sampled_negative_indices is not None:
1540
+ batch_size, sequence_length, hidden_size = quantized_features.shape
1541
+
1542
+ # for training, we sample negatives
1543
+ # 3. sample K negatives (distractors) quantized states for contrastive loss
1544
+ # if attention_mask is passed, make sure that padded feature vectors cannot be sampled
1545
+ # sample negative quantized vectors BTC => (BxT)C
1546
+ negative_quantized_features = quantized_features.view(-1, hidden_size)[
1547
+ sampled_negative_indices.long().view(-1)
1548
+ ]
1549
+ negative_quantized_features = negative_quantized_features.view(
1550
+ batch_size, sequence_length, -1, hidden_size
1551
+ ).permute(2, 0, 1, 3)
1552
+
1553
+ # 4. compute logits, corresponding to `logs = sim(c_t, [q_t, \sim{q}_t]) / \kappa`
1554
+ # of equation (3) in https://huggingface.co/papers/2006.11477
1555
+ logits = self.compute_contrastive_logits(
1556
+ quantized_features[None, :],
1557
+ negative_quantized_features,
1558
+ transformer_features,
1559
+ self.config.contrastive_logits_temperature,
1560
+ )
1561
+
1562
+ # 5. if a negative vector is identical to the positive (i.e. when codebook utilization is low),
1563
+ # its cosine similarity will be masked
1564
+ neg_is_pos = (quantized_features == negative_quantized_features).all(-1)
1565
+
1566
+ if neg_is_pos.any():
1567
+ logits[1:][neg_is_pos] = float("-inf")
1568
+
1569
+ # 6. compute contrastive loss \mathbf{L}_m = cross_entropy(logs) =
1570
+ # -log(exp(sim(c_t, q_t)/\kappa) / \sum_{\sim{q}} exp(sim(c_t, \sim{q})/\kappa))
1571
+ logits = logits.transpose(0, 2).reshape(-1, logits.size(0))
1572
+ target = ((1 - mask_time_indices.long()) * -100).transpose(0, 1).flatten()
1573
+
1574
+ contrastive_loss = nn.functional.cross_entropy(logits.float(), target, reduction="sum")
1575
+ # 7. compute diversity loss: \mathbf{L}_d
1576
+ num_codevectors = self.config.num_codevectors_per_group * self.config.num_codevector_groups
1577
+ diversity_loss = ((num_codevectors - codevector_perplexity) / num_codevectors) * mask_time_indices.sum()
1578
+
1579
+ # 8. \mathbf{L} = \mathbf{L}_m + \alpha * \mathbf{L}_d
1580
+ loss = contrastive_loss + self.config.diversity_loss_weight * diversity_loss
1581
+
1582
+ if not return_dict:
1583
+ if loss is not None:
1584
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1585
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1586
+
1587
+ return Wav2Vec2ForPreTrainingOutput(
1588
+ loss=loss,
1589
+ projected_states=transformer_features,
1590
+ projected_quantized_states=quantized_features,
1591
+ codevector_perplexity=codevector_perplexity,
1592
+ hidden_states=outputs.hidden_states,
1593
+ attentions=outputs.attentions,
1594
+ contrastive_loss=contrastive_loss,
1595
+ diversity_loss=diversity_loss,
1596
+ )
1597
+
1598
+
1599
+ @auto_docstring(
1600
+ custom_intro="""
1601
+ Wav2Vec2 Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1602
+ """
1603
+ )
1604
+ class Wav2Vec2ForCTC(Wav2Vec2PreTrainedModel):
1605
+ def __init__(self, config, target_lang: str | None = None):
1606
+ r"""
1607
+ target_lang (`str`, *optional*):
1608
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1609
+ adapter.<lang>.bin. Only relevant when using an instance of [`Wav2Vec2ForCTC`] with adapters. Uses 'eng' by
1610
+ default.
1611
+ """
1612
+ super().__init__(config)
1613
+
1614
+ self.wav2vec2 = Wav2Vec2Model(config)
1615
+ self.dropout = nn.Dropout(config.final_dropout)
1616
+
1617
+ self.target_lang = target_lang
1618
+
1619
+ if config.vocab_size is None:
1620
+ raise ValueError(
1621
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1622
+ "does not define the vocabulary size of the language model head. Please "
1623
+ "instantiate the model as follows: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1624
+ "or define `vocab_size` of your model's configuration."
1625
+ )
1626
+ output_hidden_size = (
1627
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1628
+ )
1629
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1630
+
1631
+ # Initialize weights and apply final processing
1632
+ self.post_init()
1633
+
1634
+ def tie_weights(self, **kwargs):
1635
+ """
1636
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1637
+ passing `target_lang=...` to `from_pretrained(...)`.
1638
+
1639
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1640
+ """
1641
+
1642
+ if get_torch_context_manager_or_global_device() == torch.device("meta"):
1643
+ return
1644
+
1645
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1646
+ # correctly load adapter layers for Wav2Vec2 so that we do not have to introduce a new API to
1647
+ # [`PreTrainedModel`]. While slightly hacky, Wav2Vec2 never has to tie input and output embeddings, so that it is
1648
+ # ok to repurpose this function here.
1649
+ target_lang = self.target_lang
1650
+
1651
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1652
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1653
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1654
+ logger.info("By default `target_lang` is set to 'eng'.")
1655
+ elif target_lang is not None:
1656
+ self.load_adapter(target_lang, force_load=True)
1657
+
1658
+ def freeze_feature_encoder(self):
1659
+ """
1660
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1661
+ not be updated during training.
1662
+ """
1663
+ self.wav2vec2.feature_extractor._freeze_parameters()
1664
+
1665
+ def freeze_base_model(self):
1666
+ """
1667
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1668
+ be updated during training. Only the classification head will be updated.
1669
+ """
1670
+ for param in self.wav2vec2.parameters():
1671
+ param.requires_grad = False
1672
+
1673
+ @auto_docstring
1674
+ def forward(
1675
+ self,
1676
+ input_values: torch.Tensor | None,
1677
+ attention_mask: torch.Tensor | None = None,
1678
+ output_attentions: bool | None = None,
1679
+ output_hidden_states: bool | None = None,
1680
+ return_dict: bool | None = None,
1681
+ labels: torch.Tensor | None = None,
1682
+ **kwargs,
1683
+ ) -> tuple | CausalLMOutput:
1684
+ r"""
1685
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1686
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1687
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1688
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1689
+ config.vocab_size - 1]`.
1690
+ """
1691
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1692
+
1693
+ if labels is not None and labels.max() >= self.config.vocab_size:
1694
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1695
+
1696
+ outputs = self.wav2vec2(
1697
+ input_values,
1698
+ attention_mask=attention_mask,
1699
+ output_attentions=output_attentions,
1700
+ output_hidden_states=output_hidden_states,
1701
+ return_dict=return_dict,
1702
+ )
1703
+
1704
+ hidden_states = outputs[0]
1705
+ hidden_states = self.dropout(hidden_states)
1706
+
1707
+ logits = self.lm_head(hidden_states)
1708
+
1709
+ loss = None
1710
+ if labels is not None:
1711
+ # retrieve loss input_lengths from attention_mask
1712
+ attention_mask = (
1713
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1714
+ )
1715
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1716
+
1717
+ # assuming that padded tokens are filled with -100
1718
+ # when not being attended to
1719
+ labels_mask = labels >= 0
1720
+ target_lengths = labels_mask.sum(-1)
1721
+ flattened_targets = labels.masked_select(labels_mask)
1722
+
1723
+ # ctc_loss doesn't support fp16
1724
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1725
+
1726
+ with torch.backends.cudnn.flags(enabled=False):
1727
+ loss = nn.functional.ctc_loss(
1728
+ log_probs,
1729
+ flattened_targets,
1730
+ input_lengths,
1731
+ target_lengths,
1732
+ blank=self.config.pad_token_id,
1733
+ reduction=self.config.ctc_loss_reduction,
1734
+ zero_infinity=self.config.ctc_zero_infinity,
1735
+ )
1736
+
1737
+ if not return_dict:
1738
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1739
+ return ((loss,) + output) if loss is not None else output
1740
+
1741
+ return CausalLMOutput(
1742
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1743
+ )
1744
+
1745
+
1746
+ @auto_docstring(
1747
+ custom_intro="""
1748
+ Wav2Vec2 Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1749
+ SUPERB Keyword Spotting.
1750
+ """
1751
+ )
1752
+ class Wav2Vec2ForSequenceClassification(Wav2Vec2PreTrainedModel):
1753
+ def __init__(self, config):
1754
+ super().__init__(config)
1755
+
1756
+ if hasattr(config, "add_adapter") and config.add_adapter:
1757
+ raise ValueError(
1758
+ "Sequence classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)"
1759
+ )
1760
+ self.wav2vec2 = Wav2Vec2Model(config)
1761
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1762
+ if config.use_weighted_layer_sum:
1763
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1764
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1765
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1766
+
1767
+ # Initialize weights and apply final processing
1768
+ self.post_init()
1769
+
1770
+ def freeze_feature_encoder(self):
1771
+ """
1772
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1773
+ not be updated during training.
1774
+ """
1775
+ self.wav2vec2.feature_extractor._freeze_parameters()
1776
+
1777
+ def freeze_base_model(self):
1778
+ """
1779
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1780
+ be updated during training. Only the classification head will be updated.
1781
+ """
1782
+ for param in self.wav2vec2.parameters():
1783
+ param.requires_grad = False
1784
+
1785
+ @auto_docstring
1786
+ def forward(
1787
+ self,
1788
+ input_values: torch.Tensor | None,
1789
+ attention_mask: torch.Tensor | None = None,
1790
+ output_attentions: bool | None = None,
1791
+ output_hidden_states: bool | None = None,
1792
+ return_dict: bool | None = None,
1793
+ labels: torch.Tensor | None = None,
1794
+ **kwargs,
1795
+ ) -> tuple | SequenceClassifierOutput:
1796
+ r"""
1797
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1798
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1799
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1800
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1801
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1802
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
1803
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1804
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1805
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1806
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1807
+ """
1808
+
1809
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1810
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1811
+
1812
+ outputs = self.wav2vec2(
1813
+ input_values,
1814
+ attention_mask=attention_mask,
1815
+ output_attentions=output_attentions,
1816
+ output_hidden_states=output_hidden_states,
1817
+ return_dict=return_dict,
1818
+ )
1819
+
1820
+ if self.config.use_weighted_layer_sum:
1821
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1822
+ hidden_states = torch.stack(hidden_states, dim=1)
1823
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1824
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1825
+ else:
1826
+ hidden_states = outputs[0]
1827
+
1828
+ hidden_states = self.projector(hidden_states)
1829
+ if attention_mask is None:
1830
+ pooled_output = hidden_states.mean(dim=1)
1831
+ else:
1832
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1833
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1834
+ hidden_states[~expand_padding_mask] = 0.0
1835
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1836
+
1837
+ logits = self.classifier(pooled_output)
1838
+
1839
+ loss = None
1840
+ if labels is not None:
1841
+ loss_fct = CrossEntropyLoss()
1842
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1843
+
1844
+ if not return_dict:
1845
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1846
+ return ((loss,) + output) if loss is not None else output
1847
+
1848
+ return SequenceClassifierOutput(
1849
+ loss=loss,
1850
+ logits=logits,
1851
+ hidden_states=outputs.hidden_states,
1852
+ attentions=outputs.attentions,
1853
+ )
1854
+
1855
+
1856
+ @auto_docstring
1857
+ class Wav2Vec2ForAudioFrameClassification(Wav2Vec2PreTrainedModel):
1858
+ def __init__(self, config):
1859
+ super().__init__(config)
1860
+
1861
+ if hasattr(config, "add_adapter") and config.add_adapter:
1862
+ raise ValueError(
1863
+ "Audio frame classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)"
1864
+ )
1865
+ self.wav2vec2 = Wav2Vec2Model(config)
1866
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1867
+ if config.use_weighted_layer_sum:
1868
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1869
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1870
+ self.num_labels = config.num_labels
1871
+
1872
+ self.post_init()
1873
+
1874
+ def freeze_feature_encoder(self):
1875
+ """
1876
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1877
+ not be updated during training.
1878
+ """
1879
+ self.wav2vec2.feature_extractor._freeze_parameters()
1880
+
1881
+ def freeze_base_model(self):
1882
+ """
1883
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1884
+ be updated during training. Only the classification head will be updated.
1885
+ """
1886
+ for param in self.wav2vec2.parameters():
1887
+ param.requires_grad = False
1888
+
1889
+ @auto_docstring
1890
+ def forward(
1891
+ self,
1892
+ input_values: torch.Tensor | None,
1893
+ attention_mask: torch.Tensor | None = None,
1894
+ labels: torch.Tensor | None = None,
1895
+ output_attentions: bool | None = None,
1896
+ output_hidden_states: bool | None = None,
1897
+ return_dict: bool | None = None,
1898
+ **kwargs,
1899
+ ) -> tuple | TokenClassifierOutput:
1900
+ r"""
1901
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1902
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1903
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1904
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1905
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1906
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
1907
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1908
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1909
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1910
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1911
+ """
1912
+
1913
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1914
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1915
+
1916
+ outputs = self.wav2vec2(
1917
+ input_values,
1918
+ attention_mask=attention_mask,
1919
+ output_attentions=output_attentions,
1920
+ output_hidden_states=output_hidden_states,
1921
+ return_dict=return_dict,
1922
+ )
1923
+
1924
+ if self.config.use_weighted_layer_sum:
1925
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1926
+ hidden_states = torch.stack(hidden_states, dim=1)
1927
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1928
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1929
+ else:
1930
+ hidden_states = outputs[0]
1931
+
1932
+ logits = self.classifier(hidden_states)
1933
+
1934
+ loss = None
1935
+ if labels is not None:
1936
+ loss_fct = CrossEntropyLoss()
1937
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
1938
+
1939
+ if not return_dict:
1940
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1941
+ return output
1942
+
1943
+ return TokenClassifierOutput(
1944
+ loss=loss,
1945
+ logits=logits,
1946
+ hidden_states=outputs.hidden_states,
1947
+ attentions=outputs.attentions,
1948
+ )
1949
+
1950
+
1951
+ class AMSoftmaxLoss(nn.Module):
1952
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
1953
+ super().__init__()
1954
+ self.scale = scale
1955
+ self.margin = margin
1956
+ self.num_labels = num_labels
1957
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
1958
+ self.loss = nn.CrossEntropyLoss()
1959
+
1960
+ def forward(self, hidden_states, labels):
1961
+ labels = labels.flatten()
1962
+ weight = nn.functional.normalize(self.weight, dim=0)
1963
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
1964
+ cos_theta = torch.mm(hidden_states, weight)
1965
+ psi = cos_theta - self.margin
1966
+
1967
+ onehot = nn.functional.one_hot(labels, self.num_labels)
1968
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
1969
+ loss = self.loss(logits, labels)
1970
+
1971
+ return loss
1972
+
1973
+
1974
+ class TDNNLayer(nn.Module):
1975
+ def __init__(self, config, layer_id=0):
1976
+ super().__init__()
1977
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
1978
+ self.out_conv_dim = config.tdnn_dim[layer_id]
1979
+ self.kernel_size = config.tdnn_kernel[layer_id]
1980
+ self.dilation = config.tdnn_dilation[layer_id]
1981
+
1982
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
1983
+ self.activation = nn.ReLU()
1984
+
1985
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1986
+ if is_peft_available():
1987
+ from peft.tuners.lora import LoraLayer
1988
+
1989
+ if is_peft_available():
1990
+ if isinstance(self.kernel, LoraLayer):
1991
+ warnings.warn(
1992
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
1993
+ "You should exclude TDNNLayer from LoRA's target modules.",
1994
+ )
1995
+
1996
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
1997
+ hidden_states = hidden_states.transpose(1, 2)
1998
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
1999
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
2000
+ hidden_states = hidden_states.transpose(1, 2)
2001
+
2002
+ hidden_states = self.activation(hidden_states)
2003
+ return hidden_states
2004
+
2005
+
2006
+ @auto_docstring(
2007
+ custom_intro="""
2008
+ Wav2Vec2 Model with an XVector feature extraction head on top for tasks like Speaker Verification.
2009
+ """
2010
+ )
2011
+ class Wav2Vec2ForXVector(Wav2Vec2PreTrainedModel):
2012
+ def __init__(self, config):
2013
+ super().__init__(config)
2014
+
2015
+ self.wav2vec2 = Wav2Vec2Model(config)
2016
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
2017
+ if config.use_weighted_layer_sum:
2018
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
2019
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
2020
+
2021
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
2022
+ self.tdnn = nn.ModuleList(tdnn_layers)
2023
+
2024
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
2025
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
2026
+
2027
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
2028
+
2029
+ self.post_init()
2030
+
2031
+ def freeze_feature_encoder(self):
2032
+ """
2033
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
2034
+ not be updated during training.
2035
+ """
2036
+ self.wav2vec2.feature_extractor._freeze_parameters()
2037
+
2038
+ def freeze_base_model(self):
2039
+ """
2040
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
2041
+ be updated during training. Only the classification head will be updated.
2042
+ """
2043
+ for param in self.wav2vec2.parameters():
2044
+ param.requires_grad = False
2045
+
2046
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
2047
+ """
2048
+ Computes the output length of the TDNN layers
2049
+ """
2050
+
2051
+ def _conv_out_length(input_length, kernel_size, stride):
2052
+ # 1D convolutional layer output length formula taken
2053
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
2054
+ return (input_length - kernel_size) // stride + 1
2055
+
2056
+ for kernel_size in self.config.tdnn_kernel:
2057
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
2058
+
2059
+ return input_lengths
2060
+
2061
+ @auto_docstring
2062
+ def forward(
2063
+ self,
2064
+ input_values: torch.Tensor | None,
2065
+ attention_mask: torch.Tensor | None = None,
2066
+ output_attentions: bool | None = None,
2067
+ output_hidden_states: bool | None = None,
2068
+ return_dict: bool | None = None,
2069
+ labels: torch.Tensor | None = None,
2070
+ **kwargs,
2071
+ ) -> tuple | XVectorOutput:
2072
+ r"""
2073
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
2074
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
2075
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
2076
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
2077
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
2078
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
2079
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2080
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
2081
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2082
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2083
+ """
2084
+
2085
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
2086
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
2087
+
2088
+ outputs = self.wav2vec2(
2089
+ input_values,
2090
+ attention_mask=attention_mask,
2091
+ output_attentions=output_attentions,
2092
+ output_hidden_states=output_hidden_states,
2093
+ return_dict=return_dict,
2094
+ )
2095
+
2096
+ if self.config.use_weighted_layer_sum:
2097
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
2098
+ hidden_states = torch.stack(hidden_states, dim=1)
2099
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
2100
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
2101
+ else:
2102
+ hidden_states = outputs[0]
2103
+
2104
+ hidden_states = self.projector(hidden_states)
2105
+
2106
+ for tdnn_layer in self.tdnn:
2107
+ hidden_states = tdnn_layer(hidden_states)
2108
+
2109
+ # Statistic Pooling
2110
+ if attention_mask is None:
2111
+ mean_features = hidden_states.mean(dim=1)
2112
+ std_features = hidden_states.std(dim=1)
2113
+ else:
2114
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
2115
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
2116
+ mean_features = []
2117
+ std_features = []
2118
+ for i, length in enumerate(tdnn_output_lengths):
2119
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
2120
+ std_features.append(hidden_states[i, :length].std(dim=0))
2121
+ mean_features = torch.stack(mean_features)
2122
+ std_features = torch.stack(std_features)
2123
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
2124
+
2125
+ output_embeddings = self.feature_extractor(statistic_pooling)
2126
+ logits = self.classifier(output_embeddings)
2127
+
2128
+ loss = None
2129
+ if labels is not None:
2130
+ loss = self.objective(logits, labels)
2131
+
2132
+ if not return_dict:
2133
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
2134
+ return ((loss,) + output) if loss is not None else output
2135
+
2136
+ return XVectorOutput(
2137
+ loss=loss,
2138
+ logits=logits,
2139
+ embeddings=output_embeddings,
2140
+ hidden_states=outputs.hidden_states,
2141
+ attentions=outputs.attentions,
2142
+ )
2143
+
2144
+
2145
+ __all__ = [
2146
+ "Wav2Vec2ForAudioFrameClassification",
2147
+ "Wav2Vec2ForCTC",
2148
+ "Wav2Vec2ForPreTraining",
2149
+ "Wav2Vec2ForSequenceClassification",
2150
+ "Wav2Vec2ForXVector",
2151
+ "Wav2Vec2Model",
2152
+ "Wav2Vec2PreTrainedModel",
2153
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2/processing_wav2vec2.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ Speech processor class for Wav2Vec2
16
+ """
17
+
18
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
19
+ from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ class Wav2Vec2ProcessorKwargs(ProcessingKwargs, total=False):
24
+ _defaults = {}
25
+
26
+
27
+ @auto_docstring
28
+ class Wav2Vec2Processor(ProcessorMixin):
29
+ def __init__(self, feature_extractor, tokenizer):
30
+ super().__init__(feature_extractor, tokenizer)
31
+
32
+ @auto_docstring
33
+ def __call__(
34
+ self,
35
+ audio: AudioInput | None = None,
36
+ text: str | list[str] | TextInput | PreTokenizedInput | None = None,
37
+ **kwargs: Unpack[Wav2Vec2ProcessorKwargs],
38
+ ):
39
+ r"""
40
+ Returns:
41
+ This method returns the results of each `call` method. If both are used, the output is a dictionary containing the results of both.
42
+ """
43
+ if audio is None and text is None:
44
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
45
+
46
+ output_kwargs = self._merge_kwargs(
47
+ Wav2Vec2ProcessorKwargs,
48
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
49
+ **kwargs,
50
+ )
51
+
52
+ if audio is not None:
53
+ inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
54
+ if text is not None:
55
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
56
+
57
+ if text is None:
58
+ return inputs
59
+ elif audio is None:
60
+ return encodings
61
+ else:
62
+ inputs["labels"] = encodings["input_ids"]
63
+ return inputs
64
+
65
+ def pad(self, *args, **kwargs):
66
+ """
67
+ This method operates on batches of extracted features and/or tokenized text. It forwards all arguments to
68
+ [`Wav2Vec2FeatureExtractor.pad`] and/or [`PreTrainedTokenizer.pad`] depending on the input modality and returns their outputs. If both modalities are passed, [`Wav2Vec2FeatureExtractor.pad`] and [`PreTrainedTokenizer.pad`] are called.
69
+
70
+ Args:
71
+ input_features:
72
+ When the first argument is a dictionary containing a batch of tensors, or the `input_features` argument is present, it is passed to [`Wav2Vec2FeatureExtractor.pad`].
73
+ labels:
74
+ When the `label` argument is present, it is passed to [`PreTrainedTokenizer.pad`].
75
+
76
+ Returns:
77
+ This method returns the results of each `pad` method. If both are used, the output is a dictionary containing the results of both.
78
+ """
79
+ input_features = kwargs.pop("input_features", None)
80
+ labels = kwargs.pop("labels", None)
81
+ if len(args) > 0:
82
+ input_features = args[0]
83
+ args = args[1:]
84
+
85
+ if input_features is not None:
86
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
87
+ if labels is not None:
88
+ labels = self.tokenizer.pad(labels, **kwargs)
89
+
90
+ if labels is None:
91
+ return input_features
92
+ elif input_features is None:
93
+ return labels
94
+ else:
95
+ input_features["labels"] = labels["input_ids"]
96
+ return input_features
97
+
98
+ @property
99
+ def model_input_names(self):
100
+ # The processor doesn't return text ids and the model seems to not need them
101
+ feature_extractor_input_names = self.feature_extractor.model_input_names
102
+ return feature_extractor_input_names + ["labels"]
103
+
104
+
105
+ __all__ = ["Wav2Vec2Processor"]