JinghuiLuAstronaut commited on
Commit
ae92d4a
·
verified ·
1 Parent(s): 9d2cae1

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/bloom/__init__.py +28 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bloom/modeling_bloom.py +987 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/__init__.py +29 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/configuration_d_fine.py +242 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/modeling_d_fine.py +2109 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/modular_d_fine.py +1016 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/__init__.py +32 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/configuration_got_ocr2.py +132 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/image_processing_got_ocr2.py +307 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/modeling_got_ocr2.py +771 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/configuration_moonshine.py +116 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/modeling_moonshine.py +953 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/modular_moonshine.py +795 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/__init__.py +28 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/configuration_musicgen.py +156 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/modeling_musicgen.py +0 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/processing_musicgen.py +86 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_5_omni/__init__.py +28 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py +0 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py +0 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bloom/__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_bloom import *
22
+ from .modeling_bloom import *
23
+ from .tokenization_bloom 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/bloom/modeling_bloom.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 HuggingFace Inc. team and BigScience workshop.
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 BLOOM model."""
15
+
16
+ import math
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
21
+ from torch.nn import functional as F
22
+
23
+ from ...cache_utils import Cache, DynamicCache, StaticCache
24
+ from ...generation import GenerationMixin
25
+ from ...masking_utils import create_causal_mask
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import (
28
+ BaseModelOutputWithPastAndCrossAttentions,
29
+ CausalLMOutputWithCrossAttentions,
30
+ QuestionAnsweringModelOutput,
31
+ SequenceClassifierOutputWithPast,
32
+ TokenClassifierOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ auto_docstring,
37
+ logging,
38
+ )
39
+ from .configuration_bloom import BloomConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
46
+ """
47
+ Link to paper: https://huggingface.co/papers/2108.12409 Alibi tensor is not causal as the original paper mentions, it
48
+ relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
49
+ `softmax(l+a) = softmax(l)`. Based on
50
+ https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
51
+ TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.
52
+
53
+ Args:
54
+ Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
55
+ attention_mask (`torch.Tensor`):
56
+ Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
57
+ num_heads (`int`):
58
+ number of heads
59
+ dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
60
+ dtype of the output tensor
61
+ """
62
+ batch_size, seq_length = attention_mask.shape
63
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
64
+ base = torch.tensor(
65
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
66
+ )
67
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
68
+ slopes = torch.pow(base, powers)
69
+
70
+ if closest_power_of_2 != num_heads:
71
+ extra_base = torch.tensor(
72
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
73
+ )
74
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
75
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
76
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
77
+
78
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
79
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
80
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
81
+ # => the query_length dimension will then be broadcasted correctly
82
+ # This is more or less identical to T5's relative position bias:
83
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
84
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
85
+ alibi = slopes[..., None] * arange_tensor
86
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
87
+
88
+
89
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
90
+ """
91
+ Dropout add function
92
+
93
+ Args:
94
+ x (`torch.tensor`):
95
+ input tensor
96
+ residual (`torch.tensor`):
97
+ residual tensor
98
+ prob (`float`):
99
+ dropout probability
100
+ training (`bool`):
101
+ training mode
102
+ """
103
+ out = F.dropout(x, p=prob, training=training)
104
+ out = residual + out
105
+ return out
106
+
107
+
108
+ def bloom_gelu_forward(x: torch.Tensor) -> torch.Tensor:
109
+ """
110
+ Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
111
+ make the model jitable.
112
+
113
+ Args:
114
+ x (`torch.tensor`):
115
+ input hidden states
116
+ """
117
+ return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
118
+
119
+
120
+ def bloom_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
121
+ """
122
+ gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
123
+ 0.3989423 * x * torch.exp(-0.5 * x * x)
124
+
125
+ Args:
126
+ g (`torch.tensor`):
127
+ gradient output tensor
128
+ x (`torch.tensor`):
129
+ input tensor
130
+ """
131
+ x = x[0] # x is a tuple of 1 element, needs to unpack it first
132
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
133
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
134
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
135
+ return ff * g
136
+
137
+
138
+ class GeLUFunction(torch.autograd.Function):
139
+ @staticmethod
140
+ def forward(ctx, input: torch.Tensor) -> torch.Tensor:
141
+ ctx.save_for_backward(input)
142
+ return bloom_gelu_forward(input)
143
+
144
+ @staticmethod
145
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
146
+ input = ctx.saved_tensors
147
+ tmp = bloom_gelu_back(grad_output, input)
148
+ return tmp
149
+
150
+
151
+ class BloomGelu(nn.Module):
152
+ """
153
+ Partly copied from Megatron-DeepSpeed code and adapted for our needs
154
+ """
155
+
156
+ def __init__(self):
157
+ super().__init__()
158
+
159
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
160
+ return GeLUFunction.apply(x)
161
+
162
+
163
+ class BloomAttention(nn.Module):
164
+ def __init__(self, config: BloomConfig, layer_idx: int | None = None):
165
+ super().__init__()
166
+
167
+ self.pretraining_tp = config.pretraining_tp
168
+ self.slow_but_exact = config.slow_but_exact
169
+
170
+ self.hidden_size = config.hidden_size
171
+ self.num_heads = config.n_head
172
+ self.head_dim = self.hidden_size // self.num_heads
173
+ self.split_size = self.hidden_size
174
+ self.hidden_dropout = config.hidden_dropout
175
+
176
+ if self.head_dim * self.num_heads != self.hidden_size:
177
+ raise ValueError(
178
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
179
+ f" {self.num_heads})."
180
+ )
181
+
182
+ # Layer-wise attention scaling
183
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
184
+ self.beta = 1.0
185
+ self.layer_idx = layer_idx
186
+ if layer_idx is None:
187
+ logger.warning_once(
188
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
189
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
190
+ "when creating this class."
191
+ )
192
+
193
+ self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
194
+ self.dense = nn.Linear(self.hidden_size, self.hidden_size)
195
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
196
+
197
+ def _reshape(self, fused_qkv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
198
+ """
199
+ Split the last dimension into (num_heads, head_dim) and reshapes to (bs, heads, len, dim) shape
200
+ without making any copies, results share same memory storage as `fused_qkv`
201
+
202
+ Args:
203
+ fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]
204
+
205
+ Returns:
206
+ query: [batch_size, num_heads, seq_length, head_dim]
207
+ key: [batch_size, num_heads, seq_length, head_dim]
208
+ value: [batch_size, num_heads, seq_length, head_dim]
209
+ """
210
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
211
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
212
+ query_layer = fused_qkv[..., 0, :].transpose(1, 2)
213
+ key_layer = fused_qkv[..., 1, :].transpose(1, 2)
214
+ value_layer = fused_qkv[..., 2, :].transpose(1, 2)
215
+ return query_layer, key_layer, value_layer
216
+
217
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
218
+ """
219
+ Merge heads together over the last dimension
220
+
221
+ Args:
222
+ x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]
223
+
224
+ Returns:
225
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
226
+ """
227
+ # What we want to achieve is:
228
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
229
+ batch_size_and_num_heads, seq_length, _ = x.shape
230
+ batch_size = batch_size_and_num_heads // self.num_heads
231
+
232
+ # First view to decompose the batch size
233
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
234
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
235
+
236
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
237
+ x = x.permute(0, 2, 1, 3)
238
+
239
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
240
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
241
+
242
+ def forward(
243
+ self,
244
+ hidden_states: torch.Tensor,
245
+ residual: torch.Tensor,
246
+ alibi: torch.Tensor,
247
+ attention_mask: torch.Tensor,
248
+ layer_past: Cache | None = None,
249
+ use_cache: bool = False,
250
+ output_attentions: bool = False,
251
+ **kwargs,
252
+ ):
253
+ batch_size, q_length, _ = hidden_states.shape
254
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
255
+ # 3 x [batch_size, num_heads, seq_length, head_dim]
256
+ query_layer, key_layer, value_layer = self._reshape(fused_qkv)
257
+
258
+ if layer_past is not None:
259
+ key_layer, value_layer = layer_past.update(key_layer, value_layer, self.layer_idx)
260
+
261
+ # reshape qkv for further computations
262
+ query_layer = query_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
263
+ key_layer = key_layer.reshape(batch_size * self.num_heads, -1, self.head_dim).transpose(-1, -2)
264
+ value_layer = value_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
265
+
266
+ # [batch_size * num_heads, q_length, kv_length]
267
+ attention_scores = alibi.baddbmm(
268
+ batch1=query_layer,
269
+ batch2=key_layer,
270
+ beta=self.beta,
271
+ alpha=self.inv_norm_factor,
272
+ )
273
+
274
+ # change view to [batch_size, num_heads, q_length, kv_length]
275
+ attn_weights = attention_scores.view(batch_size, self.num_heads, q_length, -1)
276
+ if attention_mask is not None:
277
+ attn_weights = attn_weights + attention_mask
278
+
279
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype
280
+ attention_probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_layer.dtype)
281
+
282
+ # [batch_size, num_heads, q_length, kv_length]
283
+ attention_probs = self.attention_dropout(attention_probs)
284
+
285
+ # change view [batch_size x num_heads, q_length, kv_length]
286
+ attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, -1)
287
+
288
+ # matmul: [batch_size * num_heads, q_length, head_dim]
289
+ context_layer = torch.bmm(attention_probs_reshaped, value_layer)
290
+
291
+ # change view [batch_size, q_length, num_heads * head_dim]
292
+ context_layer = self._merge_heads(context_layer)
293
+
294
+ # aggregate results across tp ranks. See here: https://github.com/pytorch/pytorch/issues/76232
295
+ if self.pretraining_tp > 1 and self.slow_but_exact:
296
+ slices = self.hidden_size / self.pretraining_tp
297
+ output_tensor = torch.zeros_like(context_layer)
298
+ for i in range(self.pretraining_tp):
299
+ output_tensor = output_tensor + F.linear(
300
+ context_layer[:, :, int(i * slices) : int((i + 1) * slices)],
301
+ self.dense.weight[:, int(i * slices) : int((i + 1) * slices)],
302
+ )
303
+ else:
304
+ output_tensor = self.dense(context_layer)
305
+
306
+ output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
307
+ return output_tensor, attention_probs
308
+
309
+
310
+ class BloomMLP(nn.Module):
311
+ def __init__(self, config: BloomConfig):
312
+ super().__init__()
313
+ hidden_size = config.hidden_size
314
+
315
+ self.pretraining_tp = config.pretraining_tp
316
+ self.slow_but_exact = config.slow_but_exact
317
+ self.dense_h_to_4h = nn.Linear(hidden_size, 4 * hidden_size)
318
+ self.gelu_impl = BloomGelu()
319
+ self.dense_4h_to_h = nn.Linear(4 * hidden_size, hidden_size)
320
+ self.hidden_dropout = config.hidden_dropout
321
+
322
+ def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
323
+ hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states))
324
+
325
+ if self.pretraining_tp > 1 and self.slow_but_exact:
326
+ intermediate_output = torch.zeros_like(residual)
327
+ slices = self.dense_4h_to_h.weight.shape[-1] / self.pretraining_tp
328
+ for i in range(self.pretraining_tp):
329
+ intermediate_output = intermediate_output + F.linear(
330
+ hidden_states[:, :, int(i * slices) : int((i + 1) * slices)],
331
+ self.dense_4h_to_h.weight[:, int(i * slices) : int((i + 1) * slices)],
332
+ )
333
+ else:
334
+ intermediate_output = self.dense_4h_to_h(hidden_states)
335
+
336
+ output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
337
+
338
+ return output
339
+
340
+
341
+ class BloomBlock(GradientCheckpointingLayer):
342
+ def __init__(self, config: BloomConfig, layer_idx: int | None = None):
343
+ super().__init__()
344
+ hidden_size = config.hidden_size
345
+
346
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
347
+ self.num_heads = config.n_head
348
+ self.self_attention = BloomAttention(config, layer_idx)
349
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
350
+
351
+ self.mlp = BloomMLP(config)
352
+
353
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
354
+ self.hidden_dropout = config.hidden_dropout
355
+
356
+ def forward(
357
+ self,
358
+ hidden_states: torch.Tensor,
359
+ alibi: torch.Tensor,
360
+ attention_mask: torch.Tensor,
361
+ layer_past: Cache | None = None,
362
+ use_cache: bool = False,
363
+ output_attentions: bool = False,
364
+ **kwargs,
365
+ ):
366
+ # hidden_states: [batch_size, seq_length, hidden_size]
367
+
368
+ # Layer norm at the beginning of the transformer layer.
369
+ layernorm_output = self.input_layernorm(hidden_states)
370
+
371
+ # Layer norm post the self attention.
372
+ if self.apply_residual_connection_post_layernorm:
373
+ residual = layernorm_output
374
+ else:
375
+ residual = hidden_states
376
+
377
+ # Self attention.
378
+ attention_output, attn_weights = self.self_attention(
379
+ layernorm_output,
380
+ residual,
381
+ layer_past=layer_past,
382
+ attention_mask=attention_mask,
383
+ alibi=alibi,
384
+ use_cache=use_cache,
385
+ output_attentions=output_attentions,
386
+ )
387
+
388
+ layernorm_output = self.post_attention_layernorm(attention_output)
389
+
390
+ # Get residual
391
+ if self.apply_residual_connection_post_layernorm:
392
+ residual = layernorm_output
393
+ else:
394
+ residual = attention_output
395
+
396
+ # MLP.
397
+ output = self.mlp(layernorm_output, residual)
398
+
399
+ return output, attn_weights # hidden_states, attentions
400
+
401
+
402
+ @auto_docstring
403
+ class BloomPreTrainedModel(PreTrainedModel):
404
+ config: BloomConfig
405
+ base_model_prefix = "transformer"
406
+ supports_gradient_checkpointing = True
407
+ _no_split_modules = ["BloomBlock"]
408
+ _skip_keys_device_placement = ["past_key_values"]
409
+ _can_compile_fullgraph = True
410
+
411
+
412
+ @auto_docstring
413
+ class BloomModel(BloomPreTrainedModel):
414
+ def __init__(self, config: BloomConfig):
415
+ super().__init__(config)
416
+
417
+ self.embed_dim = config.hidden_size
418
+ self.num_heads = config.n_head
419
+
420
+ # Embedding + LN Embedding
421
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
422
+ self.word_embeddings_layernorm = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
423
+
424
+ # Transformer blocks
425
+ self.h = nn.ModuleList([BloomBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
426
+
427
+ # Final Layer Norm
428
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
429
+
430
+ self.gradient_checkpointing = False
431
+
432
+ # Initialize weights and apply final processing
433
+ self.post_init()
434
+
435
+ def build_alibi_tensor(self, attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
436
+ return build_alibi_tensor(attention_mask, num_heads, dtype)
437
+
438
+ def get_input_embeddings(self):
439
+ return self.word_embeddings
440
+
441
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
442
+ self.word_embeddings = new_embeddings
443
+
444
+ @auto_docstring
445
+ def forward(
446
+ self,
447
+ input_ids: torch.LongTensor | None = None,
448
+ past_key_values: Cache | None = None,
449
+ attention_mask: torch.Tensor | None = None,
450
+ inputs_embeds: torch.LongTensor | None = None,
451
+ use_cache: bool | None = None,
452
+ output_attentions: bool | None = None,
453
+ output_hidden_states: bool | None = None,
454
+ return_dict: bool | None = None,
455
+ **kwargs,
456
+ ) -> tuple[torch.Tensor, ...] | BaseModelOutputWithPastAndCrossAttentions:
457
+ r"""
458
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
459
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
460
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
461
+
462
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
463
+ `input_ids`.
464
+
465
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
466
+ [`PreTrainedTokenizer.__call__`] for details.
467
+
468
+ [What are input IDs?](../glossary#input-ids)
469
+ """
470
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
471
+ output_hidden_states = (
472
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
473
+ )
474
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
475
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
476
+
477
+ if (input_ids is None) ^ (inputs_embeds is not None):
478
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
479
+
480
+ if self.gradient_checkpointing and self.training and use_cache:
481
+ logger.warning_once(
482
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
483
+ )
484
+ use_cache = False
485
+
486
+ if inputs_embeds is None:
487
+ inputs_embeds = self.word_embeddings(input_ids)
488
+
489
+ if use_cache and past_key_values is None:
490
+ past_key_values = DynamicCache(config=self.config)
491
+
492
+ batch_size, seq_length, _ = inputs_embeds.shape
493
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
494
+ seq_length_with_past = seq_length + past_length
495
+
496
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
497
+
498
+ all_self_attentions = () if output_attentions else None
499
+ all_hidden_states = () if output_hidden_states else None
500
+
501
+ # Compute alibi tensor: check build_alibi_tensor documentation
502
+ if attention_mask is None:
503
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
504
+ else:
505
+ attention_mask = attention_mask.to(hidden_states.device)
506
+
507
+ alibi = self.build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
508
+ causal_mask = create_causal_mask(
509
+ config=self.config,
510
+ inputs_embeds=inputs_embeds,
511
+ attention_mask=attention_mask,
512
+ past_key_values=past_key_values,
513
+ )
514
+
515
+ for i, block in enumerate(self.h):
516
+ if output_hidden_states:
517
+ all_hidden_states = all_hidden_states + (hidden_states,)
518
+
519
+ outputs = block(
520
+ hidden_states,
521
+ layer_past=past_key_values,
522
+ attention_mask=causal_mask,
523
+ use_cache=use_cache,
524
+ output_attentions=output_attentions,
525
+ alibi=alibi,
526
+ )
527
+
528
+ hidden_states = outputs[0]
529
+ if output_attentions:
530
+ all_self_attentions = all_self_attentions + (outputs[1],)
531
+
532
+ # Add last hidden state
533
+ hidden_states = self.ln_f(hidden_states)
534
+
535
+ if output_hidden_states:
536
+ all_hidden_states = all_hidden_states + (hidden_states,)
537
+
538
+ if not return_dict:
539
+ return tuple(
540
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
541
+ )
542
+
543
+ return BaseModelOutputWithPastAndCrossAttentions(
544
+ last_hidden_state=hidden_states,
545
+ past_key_values=past_key_values,
546
+ hidden_states=all_hidden_states,
547
+ attentions=all_self_attentions,
548
+ )
549
+
550
+
551
+ @auto_docstring(
552
+ custom_intro="""
553
+ The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
554
+ embeddings).
555
+ """
556
+ )
557
+ class BloomForCausalLM(BloomPreTrainedModel, GenerationMixin):
558
+ _tied_weights_keys = {"lm_head.weight": "transformer.word_embeddings.weight"}
559
+
560
+ def __init__(self, config: BloomConfig):
561
+ super().__init__(config)
562
+ self.transformer = BloomModel(config)
563
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
564
+
565
+ # Initialize weights and apply final processing
566
+ self.post_init()
567
+
568
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
569
+ self.lm_head = new_embeddings
570
+
571
+ def prepare_inputs_for_generation(
572
+ self,
573
+ input_ids,
574
+ past_key_values=None,
575
+ attention_mask=None,
576
+ inputs_embeds=None,
577
+ use_cache=True,
578
+ is_first_iteration=False,
579
+ **kwargs,
580
+ ):
581
+ # Overwritten because of the fixed-shape attention mask creation
582
+
583
+ model_inputs = super().prepare_inputs_for_generation(
584
+ input_ids,
585
+ past_key_values=past_key_values,
586
+ attention_mask=attention_mask,
587
+ inputs_embeds=inputs_embeds,
588
+ use_cache=use_cache,
589
+ is_first_iteration=is_first_iteration,
590
+ **kwargs,
591
+ )
592
+
593
+ # This part differs from other models because BLOOM needs a 2D mask to construct alibi tensor
594
+ # The only difference is the usage of 2D instead of 4D mask, but the shape will be static
595
+ if isinstance(past_key_values, StaticCache) and attention_mask is not None:
596
+ target_length = past_key_values.get_max_cache_shape()
597
+ batch_size, seq_length = attention_mask.shape
598
+ diff = target_length - seq_length
599
+
600
+ new_attn_mask = torch.zeros(batch_size, diff, device=attention_mask.device, dtype=attention_mask.dtype)
601
+ attention_mask = torch.cat([attention_mask, new_attn_mask], dim=-1)
602
+ model_inputs["attention_mask"] = attention_mask
603
+
604
+ return model_inputs
605
+
606
+ @auto_docstring
607
+ def forward(
608
+ self,
609
+ input_ids: torch.LongTensor | None = None,
610
+ past_key_values: Cache | None = None,
611
+ attention_mask: torch.Tensor | None = None,
612
+ inputs_embeds: torch.Tensor | None = None,
613
+ labels: torch.Tensor | None = None,
614
+ use_cache: bool | None = None,
615
+ output_attentions: bool | None = None,
616
+ output_hidden_states: bool | None = None,
617
+ return_dict: bool | None = None,
618
+ logits_to_keep: int | torch.Tensor = 0,
619
+ **kwargs,
620
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
621
+ r"""
622
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
623
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
624
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
625
+
626
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
627
+ `input_ids`.
628
+
629
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
630
+ [`PreTrainedTokenizer.__call__`] for details.
631
+
632
+ [What are input IDs?](../glossary#input-ids)
633
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
634
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
635
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
636
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
637
+ """
638
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
639
+
640
+ transformer_outputs = self.transformer(
641
+ input_ids,
642
+ past_key_values=past_key_values,
643
+ attention_mask=attention_mask,
644
+ inputs_embeds=inputs_embeds,
645
+ use_cache=use_cache,
646
+ output_attentions=output_attentions,
647
+ output_hidden_states=output_hidden_states,
648
+ return_dict=return_dict,
649
+ )
650
+
651
+ hidden_states = transformer_outputs[0]
652
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
653
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
654
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
655
+
656
+ loss = None
657
+ if labels is not None:
658
+ loss = self.loss_function(
659
+ logits,
660
+ labels,
661
+ vocab_size=self.config.vocab_size,
662
+ num_items_in_batch=kwargs.get("num_items_in_batch"),
663
+ )
664
+
665
+ if not return_dict:
666
+ output = (logits,) + transformer_outputs[1:]
667
+ return ((loss,) + output) if loss is not None else output
668
+
669
+ return CausalLMOutputWithCrossAttentions(
670
+ loss=loss,
671
+ logits=logits,
672
+ past_key_values=transformer_outputs.past_key_values,
673
+ hidden_states=transformer_outputs.hidden_states,
674
+ attentions=transformer_outputs.attentions,
675
+ )
676
+
677
+
678
+ @auto_docstring(
679
+ custom_intro="""
680
+ The Bloom Model transformer with a sequence classification head on top (linear layer).
681
+
682
+ [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
683
+ (e.g. GPT-1) do.
684
+
685
+ Since it does classification on the last token, it requires to know the position of the last token. If a
686
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
687
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
688
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
689
+ each row of the batch).
690
+ """
691
+ )
692
+ class BloomForSequenceClassification(BloomPreTrainedModel):
693
+ def __init__(self, config: BloomConfig):
694
+ super().__init__(config)
695
+ self.num_labels = config.num_labels
696
+ self.transformer = BloomModel(config)
697
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
698
+
699
+ # Initialize weights and apply final processing
700
+ self.post_init()
701
+
702
+ @auto_docstring
703
+ def forward(
704
+ self,
705
+ input_ids: torch.LongTensor | None = None,
706
+ past_key_values: Cache | None = None,
707
+ attention_mask: torch.Tensor | None = None,
708
+ inputs_embeds: torch.Tensor | None = None,
709
+ labels: torch.Tensor | None = None,
710
+ use_cache: bool | None = None,
711
+ output_attentions: bool | None = None,
712
+ output_hidden_states: bool | None = None,
713
+ return_dict: bool | None = None,
714
+ **kwargs,
715
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutputWithPast:
716
+ r"""
717
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
718
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
719
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
720
+
721
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
722
+ `input_ids`.
723
+
724
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
725
+ [`PreTrainedTokenizer.__call__`] for details.
726
+
727
+ [What are input IDs?](../glossary#input-ids)
728
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
729
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
730
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
731
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
732
+ """
733
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
734
+
735
+ transformer_outputs = self.transformer(
736
+ input_ids,
737
+ past_key_values=past_key_values,
738
+ attention_mask=attention_mask,
739
+ inputs_embeds=inputs_embeds,
740
+ use_cache=use_cache,
741
+ output_attentions=output_attentions,
742
+ output_hidden_states=output_hidden_states,
743
+ return_dict=return_dict,
744
+ )
745
+
746
+ hidden_states = transformer_outputs[0]
747
+ logits = self.score(hidden_states)
748
+
749
+ if input_ids is not None:
750
+ batch_size = input_ids.shape[0]
751
+ else:
752
+ batch_size = inputs_embeds.shape[0]
753
+
754
+ if self.config.pad_token_id is None and batch_size != 1:
755
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
756
+ if self.config.pad_token_id is None:
757
+ last_non_pad_token = -1
758
+ elif input_ids is not None:
759
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
760
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
761
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
762
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
763
+ else:
764
+ last_non_pad_token = -1
765
+ logger.warning_once(
766
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
767
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
768
+ )
769
+
770
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
771
+
772
+ loss = None
773
+ if labels is not None:
774
+ if self.config.problem_type is None:
775
+ if self.num_labels == 1:
776
+ self.config.problem_type = "regression"
777
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
778
+ self.config.problem_type = "single_label_classification"
779
+ else:
780
+ self.config.problem_type = "multi_label_classification"
781
+
782
+ if self.config.problem_type == "regression":
783
+ loss_fct = MSELoss()
784
+ if self.num_labels == 1:
785
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
786
+ else:
787
+ loss = loss_fct(pooled_logits, labels)
788
+ elif self.config.problem_type == "single_label_classification":
789
+ loss_fct = CrossEntropyLoss()
790
+ loss = loss_fct(pooled_logits, labels)
791
+ elif self.config.problem_type == "multi_label_classification":
792
+ loss_fct = BCEWithLogitsLoss()
793
+ loss = loss_fct(pooled_logits, labels)
794
+ if not return_dict:
795
+ output = (pooled_logits,) + transformer_outputs[1:]
796
+ return ((loss,) + output) if loss is not None else output
797
+
798
+ return SequenceClassifierOutputWithPast(
799
+ loss=loss,
800
+ logits=pooled_logits,
801
+ past_key_values=transformer_outputs.past_key_values,
802
+ hidden_states=transformer_outputs.hidden_states,
803
+ attentions=transformer_outputs.attentions,
804
+ )
805
+
806
+
807
+ @auto_docstring
808
+ class BloomForTokenClassification(BloomPreTrainedModel):
809
+ def __init__(self, config: BloomConfig):
810
+ super().__init__(config)
811
+ self.num_labels = config.num_labels
812
+
813
+ self.transformer = BloomModel(config)
814
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
815
+ classifier_dropout = config.classifier_dropout
816
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
817
+ classifier_dropout = config.hidden_dropout
818
+ else:
819
+ classifier_dropout = 0.1
820
+ self.dropout = nn.Dropout(classifier_dropout)
821
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
822
+
823
+ # Initialize weights and apply final processing
824
+ self.post_init()
825
+
826
+ @auto_docstring
827
+ def forward(
828
+ self,
829
+ input_ids: torch.LongTensor | None = None,
830
+ past_key_values: Cache | None = None,
831
+ attention_mask: torch.Tensor | None = None,
832
+ inputs_embeds: torch.Tensor | None = None,
833
+ labels: torch.Tensor | None = None,
834
+ use_cache: bool | None = None,
835
+ output_attentions: bool | None = None,
836
+ output_hidden_states: bool | None = None,
837
+ return_dict: bool | None = None,
838
+ **kwargs,
839
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
840
+ r"""
841
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
842
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
843
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
844
+
845
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
846
+ `input_ids`.
847
+
848
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
849
+ [`PreTrainedTokenizer.__call__`] for details.
850
+
851
+ [What are input IDs?](../glossary#input-ids)
852
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
853
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
854
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
855
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
856
+ """
857
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
858
+
859
+ transformer_outputs = self.transformer(
860
+ input_ids,
861
+ past_key_values=past_key_values,
862
+ attention_mask=attention_mask,
863
+ inputs_embeds=inputs_embeds,
864
+ use_cache=use_cache,
865
+ output_attentions=output_attentions,
866
+ output_hidden_states=output_hidden_states,
867
+ return_dict=return_dict,
868
+ )
869
+
870
+ hidden_states = transformer_outputs[0]
871
+ hidden_states = self.dropout(hidden_states)
872
+ logits = self.classifier(hidden_states)
873
+
874
+ loss = None
875
+ if labels is not None:
876
+ # move labels to correct device
877
+ labels = labels.to(logits.device)
878
+ batch_size, seq_length = labels.shape
879
+ loss_fct = CrossEntropyLoss()
880
+ loss = loss_fct(
881
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
882
+ )
883
+
884
+ if not return_dict:
885
+ output = (logits,) + transformer_outputs[2:]
886
+ return ((loss,) + output) if loss is not None else output
887
+
888
+ return TokenClassifierOutput(
889
+ loss=loss,
890
+ logits=logits,
891
+ hidden_states=transformer_outputs.hidden_states,
892
+ attentions=transformer_outputs.attentions,
893
+ )
894
+
895
+
896
+ @auto_docstring
897
+ class BloomForQuestionAnswering(BloomPreTrainedModel):
898
+ def __init__(self, config):
899
+ super().__init__(config)
900
+ self.transformer = BloomModel(config)
901
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
902
+
903
+ # Initialize weights and apply final processing
904
+ self.post_init()
905
+
906
+ @auto_docstring
907
+ def forward(
908
+ self,
909
+ input_ids: torch.LongTensor | None = None,
910
+ attention_mask: torch.FloatTensor | None = None,
911
+ inputs_embeds: torch.FloatTensor | None = None,
912
+ start_positions: torch.LongTensor | None = None,
913
+ end_positions: torch.LongTensor | None = None,
914
+ output_attentions: bool | None = None,
915
+ output_hidden_states: bool | None = None,
916
+ return_dict: bool | None = None,
917
+ **kwargs,
918
+ ) -> tuple | QuestionAnsweringModelOutput:
919
+ r"""
920
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
921
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
922
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
923
+
924
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
925
+ `input_ids`.
926
+
927
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
928
+ [`PreTrainedTokenizer.__call__`] for details.
929
+
930
+ [What are input IDs?](../glossary#input-ids)
931
+ """
932
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
933
+
934
+ outputs = self.transformer(
935
+ input_ids,
936
+ attention_mask=attention_mask,
937
+ inputs_embeds=inputs_embeds,
938
+ output_attentions=output_attentions,
939
+ output_hidden_states=output_hidden_states,
940
+ return_dict=return_dict,
941
+ )
942
+
943
+ sequence_output = outputs[0]
944
+
945
+ logits = self.qa_outputs(sequence_output)
946
+ start_logits, end_logits = logits.split(1, dim=-1)
947
+ start_logits = start_logits.squeeze(-1).contiguous()
948
+ end_logits = end_logits.squeeze(-1).contiguous()
949
+
950
+ total_loss = None
951
+ if start_positions is not None and end_positions is not None:
952
+ # If we are on multi-GPU, split add a dimension
953
+ if len(start_positions.size()) > 1:
954
+ start_positions = start_positions.squeeze(-1)
955
+ if len(end_positions.size()) > 1:
956
+ end_positions = end_positions.squeeze(-1)
957
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
958
+ ignored_index = start_logits.size(1)
959
+ start_positions = start_positions.clamp(0, ignored_index)
960
+ end_positions = end_positions.clamp(0, ignored_index)
961
+
962
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
963
+ start_loss = loss_fct(start_logits, start_positions)
964
+ end_loss = loss_fct(end_logits, end_positions)
965
+ total_loss = (start_loss + end_loss) / 2
966
+
967
+ if not return_dict:
968
+ output = (start_logits, end_logits) + outputs[2:]
969
+ return ((total_loss,) + output) if total_loss is not None else output
970
+
971
+ return QuestionAnsweringModelOutput(
972
+ loss=total_loss,
973
+ start_logits=start_logits,
974
+ end_logits=end_logits,
975
+ hidden_states=outputs.hidden_states,
976
+ attentions=outputs.attentions,
977
+ )
978
+
979
+
980
+ __all__ = [
981
+ "BloomForCausalLM",
982
+ "BloomModel",
983
+ "BloomPreTrainedModel",
984
+ "BloomForSequenceClassification",
985
+ "BloomForTokenClassification",
986
+ "BloomForQuestionAnswering",
987
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import TYPE_CHECKING
17
+
18
+ from ...utils import _LazyModule
19
+ from ...utils.import_utils import define_import_structure
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .configuration_d_fine import *
24
+ from .modeling_d_fine import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/configuration_d_fine.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/d_fine/modular_d_fine.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_d_fine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from huggingface_hub.dataclasses import strict
21
+
22
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...utils import auto_docstring
25
+ from ..auto import AutoConfig
26
+
27
+
28
+ # TODO: Attribute map assignment logic should be fixed in modular
29
+ # as well as super() call parsing because otherwise we cannot re-write args after initialization
30
+ @auto_docstring(checkpoint="ustc-community/dfine-xlarge-coco")
31
+ @strict
32
+ class DFineConfig(PreTrainedConfig):
33
+ r"""
34
+ initializer_bias_prior_prob (`float`, *optional*):
35
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
36
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
37
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
38
+ Whether to freeze the batch normalization layers in the backbone.
39
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
40
+ Multi level features input for encoder.
41
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
42
+ Strides used in each feature map.
43
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
44
+ Indexes of the projected layers to be used in the encoder.
45
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
46
+ The temperature parameter used to create the positional encodings.
47
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
50
+ eval_size (`tuple[int, int]`, *optional*):
51
+ Height and width used to computes the effective height and width of the position embeddings after taking
52
+ into account the stride.
53
+ normalize_before (`bool`, *optional*, defaults to `False`):
54
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
55
+ feed-forward modules.
56
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
57
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
58
+ num_queries (`int`, *optional*, defaults to 300):
59
+ Number of object queries.
60
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
61
+ Multi level features dimension for decoder
62
+ num_feature_levels (`int`, *optional*, defaults to 3):
63
+ The number of input feature levels.
64
+ decoder_n_points (`int`, *optional*, defaults to 4):
65
+ The number of sampled keys in each feature level for each attention head in the decoder.
66
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
67
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
68
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
69
+ num_denoising (`int`, *optional*, defaults to 100):
70
+ The total number of denoising tasks or queries to be used for contrastive denoising.
71
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
72
+ The fraction of denoising labels to which random noise should be added.
73
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
74
+ Scale or magnitude of noise to be added to the bounding boxes.
75
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
76
+ Indicates whether the initial query embeddings for the decoder should be learned during training
77
+ anchor_image_size (`tuple[int, int]`, *optional*):
78
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
79
+ with_box_refine (`bool`, *optional*, defaults to `True`):
80
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
81
+ based on the predictions from the previous layer.
82
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
83
+ Parameter alpha used by the Hungarian Matcher.
84
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
85
+ Parameter gamma used by the Hungarian Matcher.
86
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
87
+ The relative weight of the class loss used by the Hungarian Matcher.
88
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
89
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
90
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
91
+ The relative weight of the giou loss of used by the Hungarian Matcher.
92
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
93
+ Parameter informing if focal focal should be used.
94
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
95
+ Parameter alpha used to compute the focal loss.
96
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
97
+ Parameter gamma used to compute the focal loss.
98
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
99
+ Relative weight of the varifocal loss in the object detection loss.
100
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
101
+ Relative weight of the L1 bounding box loss in the object detection loss.
102
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
103
+ Relative weight of the generalized IoU loss in the object detection loss.
104
+ weight_loss_fgl (`float`, *optional*, defaults to 0.15):
105
+ Relative weight of the fine-grained localization loss in the object detection loss.
106
+ weight_loss_ddf (`float`, *optional*, defaults to 1.5):
107
+ Relative weight of the decoupled distillation focal loss in the object detection loss.
108
+ eval_idx (`int`, *optional*, defaults to -1):
109
+ Index of the decoder layer to use for evaluation. If negative, counts from the end
110
+ (e.g., -1 means use the last layer). This allows for early prediction in the decoder
111
+ stack while still training later layers.
112
+ layer_scale (`float`, *optional*, defaults to `1.0`):
113
+ Scaling factor for the hidden dimension in later decoder layers. Used to adjust the
114
+ model capacity after the evaluation layer.
115
+ max_num_bins (`int`, *optional*, defaults to 32):
116
+ Maximum number of bins for the distribution-guided bounding box refinement.
117
+ Higher values allow for more fine-grained localization but increase computation.
118
+ reg_scale (`float`, *optional*, defaults to 4.0):
119
+ Scale factor for the regression distribution. Controls the range and granularity
120
+ of the bounding box refinement process.
121
+ depth_mult (`float`, *optional*, defaults to 1.0):
122
+ Multiplier for the number of blocks in RepNCSPELAN4 layers. Used to scale the model's
123
+ depth while maintaining its architecture.
124
+ top_prob_values (`int`, *optional*, defaults to 4):
125
+ Number of top probability values to consider from each corner's distribution.
126
+ lqe_hidden_dim (`int`, *optional*, defaults to 64):
127
+ Hidden dimension size for the Location Quality Estimator (LQE) network.
128
+ lqe_layers (`int`, *optional*, defaults to 2):
129
+ Number of layers in the Location Quality Estimator MLP.
130
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
131
+ Offset scale used in deformable attention.
132
+ decoder_method (`str`, *optional*, defaults to `"default"`):
133
+ The method to use for the decoder: `"default"` or `"discrete"`.
134
+ up (`float`, *optional*, defaults to 0.5):
135
+ Controls the upper bounds of the Weighting Function.
136
+ """
137
+
138
+ model_type = "d_fine"
139
+ sub_configs = {"backbone_config": AutoConfig}
140
+ layer_types = ["basic", "bottleneck"]
141
+ attribute_map = {
142
+ "hidden_size": "d_model",
143
+ "num_attention_heads": "encoder_attention_heads",
144
+ }
145
+
146
+ initializer_range: float = 0.01
147
+ initializer_bias_prior_prob: float | None = None
148
+ layer_norm_eps: float = 1e-5
149
+ batch_norm_eps: float = 1e-5
150
+ backbone_config: dict | PreTrainedConfig | None = None
151
+ freeze_backbone_batch_norms: bool = True
152
+
153
+ # encoder HybridEncoder
154
+ encoder_hidden_dim: int = 256
155
+ encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
156
+ feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
157
+ encoder_layers: int = 1
158
+ encoder_ffn_dim: int = 1024
159
+ encoder_attention_heads: int = 8
160
+ dropout: float | int = 0.0
161
+ activation_dropout: float | int = 0.0
162
+ encode_proj_layers: list[int] | tuple[int, ...] = (2,)
163
+ positional_encoding_temperature: int = 10000
164
+ encoder_activation_function: str = "gelu"
165
+ activation_function: str = "silu"
166
+ eval_size: int | None = None
167
+ normalize_before: bool = False
168
+ hidden_expansion: float = 1.0
169
+
170
+ # decoder DFineTransformer
171
+ d_model: int = 256
172
+ num_queries: int = 300
173
+ decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
174
+ decoder_ffn_dim: int = 1024
175
+ num_feature_levels: int = 3
176
+ decoder_n_points: int | list[int] = 4
177
+ decoder_layers: int = 6
178
+ decoder_attention_heads: int = 8
179
+ decoder_activation_function: str = "relu"
180
+ attention_dropout: float | int = 0.0
181
+ num_denoising: int = 100
182
+ label_noise_ratio: float = 0.5
183
+ box_noise_scale: float = 1.0
184
+ learn_initial_query: bool = False
185
+ anchor_image_size: int | list[int] | None = None
186
+ with_box_refine: bool = True
187
+
188
+ # Loss
189
+ matcher_alpha: float = 0.25
190
+ matcher_gamma: float = 2.0
191
+ matcher_class_cost: float = 2.0
192
+ matcher_bbox_cost: float = 5.0
193
+ matcher_giou_cost: float = 2.0
194
+ use_focal_loss: bool = True
195
+ auxiliary_loss: bool = True
196
+ focal_loss_alpha: float = 0.75
197
+ focal_loss_gamma: float = 2.0
198
+ weight_loss_vfl: float = 1.0
199
+ weight_loss_bbox: float = 5.0
200
+ weight_loss_giou: float = 2.0
201
+ weight_loss_fgl: float = 0.15
202
+ weight_loss_ddf: float = 1.5
203
+ eos_coefficient: float = 1e-4
204
+ eval_idx: int = -1
205
+ layer_scale: int | float = 1.0
206
+ max_num_bins: int = 32
207
+ reg_scale: float = 4.0
208
+ depth_mult: float = 1.0
209
+ top_prob_values: int = 4
210
+ lqe_hidden_dim: int = 64
211
+ lqe_layers: int = 2
212
+ decoder_offset_scale: float = 0.5
213
+ decoder_method: str = "default"
214
+ up: float = 0.5
215
+ tie_word_embeddings: bool = True
216
+ is_encoder_decoder: bool = True
217
+
218
+ def __post_init__(self, **kwargs):
219
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
220
+ backbone_config=self.backbone_config,
221
+ default_config_type="hgnet_v2",
222
+ default_config_kwargs={"out_indices": [2, 3, 4]},
223
+ **kwargs,
224
+ )
225
+ self.head_dim = self.d_model // self.decoder_attention_heads
226
+ super().__post_init__(**kwargs)
227
+
228
+ def validate_architecture(self):
229
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
230
+ if isinstance(self.decoder_n_points, list):
231
+ if len(self.decoder_n_points) != self.num_feature_levels:
232
+ raise ValueError(
233
+ f"Length of decoder_n_points list ({len(self.decoder_n_points)}) must match num_feature_levels ({self.num_feature_levels})."
234
+ )
235
+
236
+ if self.head_dim * self.decoder_attention_heads != self.d_model:
237
+ raise ValueError(
238
+ f"Embedded dimension {self.d_model} must be divisible by decoder_attention_heads {self.decoder_attention_heads}"
239
+ )
240
+
241
+
242
+ __all__ = ["DFineConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/modeling_d_fine.py ADDED
@@ -0,0 +1,2109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/d_fine/modular_d_fine.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_d_fine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import math
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from torch import Tensor
28
+
29
+ from ... import initialization as init
30
+ from ...activations import ACT2CLS
31
+ from ...backbone_utils import load_backbone
32
+ from ...image_transforms import center_to_corners_format, corners_to_center_format
33
+ from ...modeling_outputs import BaseModelOutput
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
35
+ from ...processing_utils import Unpack
36
+ from ...pytorch_utils import compile_compatible_method_lru_cache
37
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_compilable_check, torch_int
38
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
39
+ from ...utils.output_capturing import capture_outputs
40
+ from .configuration_d_fine import DFineConfig
41
+
42
+
43
+ @auto_docstring(
44
+ custom_intro="""
45
+ Base class for outputs of the DFineDecoder. This class adds two attributes to
46
+ BaseModelOutputWithCrossAttentions, namely:
47
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
48
+ - a stacked tensor of intermediate reference points.
49
+ """
50
+ )
51
+ @dataclass
52
+ class DFineDecoderOutput(ModelOutput):
53
+ r"""
54
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
55
+ Stacked intermediate hidden states (output of each layer of the decoder).
56
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
57
+ Stacked intermediate logits (logits of each layer of the decoder).
58
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
59
+ Stacked intermediate reference points (reference points of each layer of the decoder).
60
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
61
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
62
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
63
+ Stacked initial reference points (initial reference points of each layer of the decoder).
64
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
65
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
66
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
67
+ used to compute the weighted average in the cross-attention heads.
68
+ """
69
+
70
+ last_hidden_state: torch.FloatTensor | None = None
71
+ intermediate_hidden_states: torch.FloatTensor | None = None
72
+ intermediate_logits: torch.FloatTensor | None = None
73
+ intermediate_reference_points: torch.FloatTensor | None = None
74
+ intermediate_predicted_corners: torch.FloatTensor | None = None
75
+ initial_reference_points: torch.FloatTensor | None = None
76
+ hidden_states: tuple[torch.FloatTensor] | None = None
77
+ attentions: tuple[torch.FloatTensor] | None = None
78
+ cross_attentions: tuple[torch.FloatTensor] | None = None
79
+
80
+
81
+ class DFineMLP(nn.Module):
82
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, act: str = "relu"):
83
+ super().__init__()
84
+ self.num_layers = num_layers
85
+ hidden_dims = [hidden_dim] * (num_layers - 1)
86
+ input_dims = [input_dim] + hidden_dims
87
+ output_dims = hidden_dims + [output_dim]
88
+ self.layers = nn.ModuleList(nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(input_dims, output_dims))
89
+ self.act = ACT2CLS[act]()
90
+
91
+ def forward(self, stat_features: torch.Tensor) -> torch.Tensor:
92
+ for i, layer in enumerate(self.layers):
93
+ stat_features = self.act(layer(stat_features)) if i < self.num_layers - 1 else layer(stat_features)
94
+ return stat_features
95
+
96
+
97
+ class DFineGate(nn.Module):
98
+ def __init__(self, d_model: int):
99
+ super().__init__()
100
+ self.gate = nn.Linear(2 * d_model, 2 * d_model)
101
+ self.norm = nn.LayerNorm(d_model)
102
+
103
+ def forward(self, second_residual: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
104
+ gate_input = torch.cat([second_residual, hidden_states], dim=-1)
105
+ gates = torch.sigmoid(self.gate(gate_input))
106
+ gate1, gate2 = gates.chunk(2, dim=-1)
107
+ hidden_states = self.norm(gate1 * second_residual + gate2 * hidden_states)
108
+ return hidden_states
109
+
110
+
111
+ class DFineFrozenBatchNorm2d(nn.Module):
112
+ """
113
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
114
+
115
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
116
+ torchvision.models.resnet[18,34,50,101] produce nans.
117
+ """
118
+
119
+ def __init__(self, n):
120
+ super().__init__()
121
+ self.register_buffer("weight", torch.ones(n))
122
+ self.register_buffer("bias", torch.zeros(n))
123
+ self.register_buffer("running_mean", torch.zeros(n))
124
+ self.register_buffer("running_var", torch.ones(n))
125
+
126
+ def _load_from_state_dict(
127
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
128
+ ):
129
+ num_batches_tracked_key = prefix + "num_batches_tracked"
130
+ if num_batches_tracked_key in state_dict:
131
+ del state_dict[num_batches_tracked_key]
132
+
133
+ super()._load_from_state_dict(
134
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
135
+ )
136
+
137
+ def forward(self, x):
138
+ # move reshapes to the beginning
139
+ # to make it user-friendly
140
+ weight = self.weight.reshape(1, -1, 1, 1)
141
+ bias = self.bias.reshape(1, -1, 1, 1)
142
+ running_var = self.running_var.reshape(1, -1, 1, 1)
143
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
144
+ epsilon = 1e-5
145
+ scale = weight * (running_var + epsilon).rsqrt()
146
+ bias = bias - running_mean * scale
147
+ return x * scale + bias
148
+
149
+
150
+ def multi_scale_deformable_attention_v2(
151
+ value: Tensor,
152
+ value_spatial_shapes: Tensor,
153
+ sampling_locations: Tensor,
154
+ attention_weights: Tensor,
155
+ num_points_list: list[int],
156
+ method="default",
157
+ ) -> Tensor:
158
+ batch_size, _, num_heads, hidden_dim = value.shape
159
+ _, num_queries, num_heads, num_levels, num_points = sampling_locations.shape
160
+ value_list = (
161
+ value.permute(0, 2, 3, 1)
162
+ .flatten(0, 1)
163
+ .split([height * width for height, width in value_spatial_shapes], dim=-1)
164
+ )
165
+ # sampling_offsets [8, 480, 8, 12, 2]
166
+ if method == "default":
167
+ sampling_grids = 2 * sampling_locations - 1
168
+ elif method == "discrete":
169
+ sampling_grids = sampling_locations
170
+ sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
171
+ sampling_grids = sampling_grids.split(num_points_list, dim=-2)
172
+ sampling_value_list = []
173
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
174
+ # batch_size, height*width, num_heads, hidden_dim
175
+ # -> batch_size, height*width, num_heads*hidden_dim
176
+ # -> batch_size, num_heads*hidden_dim, height*width
177
+ # -> batch_size*num_heads, hidden_dim, height, width
178
+ value_l_ = value_list[level_id].reshape(batch_size * num_heads, hidden_dim, height, width)
179
+ # batch_size, num_queries, num_heads, num_points, 2
180
+ # -> batch_size, num_heads, num_queries, num_points, 2
181
+ # -> batch_size*num_heads, num_queries, num_points, 2
182
+ sampling_grid_l_ = sampling_grids[level_id]
183
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
184
+ if method == "default":
185
+ sampling_value_l_ = nn.functional.grid_sample(
186
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
187
+ )
188
+ elif method == "discrete":
189
+ sampling_coord = (sampling_grid_l_ * torch.tensor([[width, height]], device=value.device) + 0.5).to(
190
+ torch.int64
191
+ )
192
+
193
+ # Separate clamping for x and y coordinates
194
+ sampling_coord_x = sampling_coord[..., 0].clamp(0, width - 1)
195
+ sampling_coord_y = sampling_coord[..., 1].clamp(0, height - 1)
196
+
197
+ # Combine the clamped coordinates
198
+ sampling_coord = torch.stack([sampling_coord_x, sampling_coord_y], dim=-1)
199
+ sampling_coord = sampling_coord.reshape(batch_size * num_heads, num_queries * num_points_list[level_id], 2)
200
+ sampling_idx = (
201
+ torch.arange(sampling_coord.shape[0], device=value.device)
202
+ .unsqueeze(-1)
203
+ .repeat(1, sampling_coord.shape[1])
204
+ )
205
+ sampling_value_l_ = value_l_[sampling_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]]
206
+ sampling_value_l_ = sampling_value_l_.transpose(1, 2).reshape(
207
+ batch_size * num_heads, hidden_dim, num_queries, num_points_list[level_id]
208
+ )
209
+ sampling_value_list.append(sampling_value_l_)
210
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
211
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
212
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
213
+ attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(
214
+ batch_size * num_heads, 1, num_queries, sum(num_points_list)
215
+ )
216
+ output = (
217
+ (torch.concat(sampling_value_list, dim=-1) * attention_weights)
218
+ .sum(-1)
219
+ .view(batch_size, num_heads * hidden_dim, num_queries)
220
+ )
221
+ return output.transpose(1, 2).contiguous()
222
+
223
+
224
+ class DFineMultiscaleDeformableAttention(nn.Module):
225
+ def __init__(self, config: DFineConfig):
226
+ """
227
+ D-Fine version of multiscale deformable attention
228
+ """
229
+ super().__init__()
230
+ self.d_model = config.d_model
231
+ self.n_heads = config.decoder_attention_heads
232
+ self.n_levels = config.num_feature_levels
233
+ self.offset_scale = config.decoder_offset_scale
234
+ self.decoder_method = config.decoder_method
235
+ self.n_points = config.decoder_n_points
236
+
237
+ if isinstance(self.n_points, list):
238
+ num_points_list = self.n_points
239
+ else:
240
+ num_points_list = [self.n_points for _ in range(self.n_levels)]
241
+
242
+ self.num_points_list = num_points_list
243
+ num_points_scale = [1 / n for n in self.num_points_list for _ in range(n)]
244
+ self.register_buffer("num_points_scale", torch.tensor(num_points_scale, dtype=torch.float32))
245
+
246
+ self.total_points = self.n_heads * sum(self.num_points_list)
247
+
248
+ self.sampling_offsets = nn.Linear(self.d_model, self.total_points * 2)
249
+ self.attention_weights = nn.Linear(self.d_model, self.total_points)
250
+
251
+ self.ms_deformable_attn_core = multi_scale_deformable_attention_v2
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ attention_mask: torch.Tensor | None = None,
257
+ reference_points=None,
258
+ encoder_hidden_states=None,
259
+ spatial_shapes=None,
260
+ spatial_shapes_list=None,
261
+ **kwargs: Unpack[TransformersKwargs],
262
+ ) -> tuple[torch.Tensor, torch.Tensor]:
263
+ batch_size, num_queries, _ = hidden_states.shape
264
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
265
+
266
+ torch_compilable_check(
267
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
268
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
269
+ )
270
+
271
+ # Reshape for multi-head attention
272
+ value = encoder_hidden_states.reshape(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
273
+ if attention_mask is not None:
274
+ value = value.masked_fill(~attention_mask[..., None], float(0))
275
+
276
+ sampling_offsets: torch.Tensor = self.sampling_offsets(hidden_states)
277
+ sampling_offsets = sampling_offsets.reshape(
278
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list), 2
279
+ )
280
+
281
+ attention_weights = self.attention_weights(hidden_states).reshape(
282
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list)
283
+ )
284
+ attention_weights = F.softmax(attention_weights, dim=-1)
285
+
286
+ if reference_points.shape[-1] == 2:
287
+ offset_normalizer = torch.tensor(spatial_shapes)
288
+ offset_normalizer = offset_normalizer.flip([1]).reshape(1, 1, 1, self.n_levels, 1, 2)
289
+ sampling_locations = (
290
+ reference_points.reshape(batch_size, sequence_length, 1, self.n_levels, 1, 2)
291
+ + sampling_offsets / offset_normalizer
292
+ )
293
+ elif reference_points.shape[-1] == 4:
294
+ # reference_points [8, 480, None, 1, 4]
295
+ # sampling_offsets [8, 480, 8, 12, 2]
296
+ num_points_scale = self.num_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
297
+ offset = sampling_offsets * num_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
298
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
299
+ else:
300
+ raise ValueError(
301
+ f"Last dim of reference_points must be 2 or 4, but get {reference_points.shape[-1]} instead."
302
+ )
303
+
304
+ output = self.ms_deformable_attn_core(
305
+ value,
306
+ spatial_shapes_list,
307
+ sampling_locations,
308
+ attention_weights,
309
+ self.num_points_list,
310
+ self.decoder_method,
311
+ )
312
+
313
+ return output, attention_weights
314
+
315
+
316
+ class DFineConvNormLayer(nn.Module):
317
+ def __init__(
318
+ self,
319
+ config: DFineConfig,
320
+ in_channels: int,
321
+ out_channels: int,
322
+ kernel_size: int,
323
+ stride: int,
324
+ groups: int = 1,
325
+ padding: int | None = None,
326
+ activation: str | None = None,
327
+ ):
328
+ super().__init__()
329
+ self.conv = nn.Conv2d(
330
+ in_channels,
331
+ out_channels,
332
+ kernel_size,
333
+ stride,
334
+ groups=groups,
335
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
336
+ bias=False,
337
+ )
338
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
339
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
340
+
341
+ def forward(self, hidden_state):
342
+ hidden_state = self.conv(hidden_state)
343
+ hidden_state = self.norm(hidden_state)
344
+ hidden_state = self.activation(hidden_state)
345
+ return hidden_state
346
+
347
+
348
+ class DFineRepVggBlock(nn.Module):
349
+ """
350
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
351
+ """
352
+
353
+ def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
354
+ super().__init__()
355
+
356
+ activation = config.activation_function
357
+ hidden_channels = in_channels
358
+ self.conv1 = DFineConvNormLayer(config, hidden_channels, out_channels, 3, 1, padding=1)
359
+ self.conv2 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, padding=0)
360
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
361
+
362
+ def forward(self, x):
363
+ y = self.conv1(x) + self.conv2(x)
364
+ return self.activation(y)
365
+
366
+
367
+ class DFineCSPRepLayer(nn.Module):
368
+ """
369
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
370
+ """
371
+
372
+ def __init__(
373
+ self, config: DFineConfig, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0
374
+ ):
375
+ super().__init__()
376
+ activation = config.activation_function
377
+
378
+ hidden_channels = int(out_channels * expansion)
379
+ self.conv1 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
380
+ self.conv2 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
381
+ self.bottlenecks = nn.ModuleList(
382
+ [DFineRepVggBlock(config, hidden_channels, hidden_channels) for _ in range(num_blocks)]
383
+ )
384
+ if hidden_channels != out_channels:
385
+ self.conv3 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
386
+ else:
387
+ self.conv3 = nn.Identity()
388
+
389
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
390
+ hidden_state_1 = self.conv1(hidden_state)
391
+ for bottleneck in self.bottlenecks:
392
+ hidden_state_1 = bottleneck(hidden_state_1)
393
+ hidden_state_2 = self.conv2(hidden_state)
394
+ hidden_state_3 = self.conv3(hidden_state_1 + hidden_state_2)
395
+ return hidden_state_3
396
+
397
+
398
+ class DFineRepNCSPELAN4(nn.Module):
399
+ def __init__(self, config: DFineConfig, act: str = "silu", numb_blocks: int = 3):
400
+ super().__init__()
401
+ conv1_dim = config.encoder_hidden_dim * 2
402
+ conv2_dim = config.encoder_hidden_dim
403
+ conv3_dim = config.encoder_hidden_dim * 2
404
+ conv4_dim = round(config.hidden_expansion * config.encoder_hidden_dim // 2)
405
+ self.conv_dim = conv3_dim // 2
406
+ self.conv1 = DFineConvNormLayer(config, conv1_dim, conv3_dim, 1, 1, activation=act)
407
+ self.csp_rep1 = DFineCSPRepLayer(config, conv3_dim // 2, conv4_dim, num_blocks=numb_blocks)
408
+ self.conv2 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
409
+ self.csp_rep2 = DFineCSPRepLayer(config, conv4_dim, conv4_dim, num_blocks=numb_blocks)
410
+ self.conv3 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
411
+ self.conv4 = DFineConvNormLayer(config, conv3_dim + (2 * conv4_dim), conv2_dim, 1, 1, activation=act)
412
+
413
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
414
+ # Split initial features into two branches after first convolution
415
+ split_features = list(self.conv1(input_features).split((self.conv_dim, self.conv_dim), 1))
416
+
417
+ # Process branches sequentially
418
+ branch1 = self.csp_rep1(split_features[-1])
419
+ branch1 = self.conv2(branch1)
420
+ branch2 = self.csp_rep2(branch1)
421
+ branch2 = self.conv3(branch2)
422
+
423
+ split_features.extend([branch1, branch2])
424
+ merged_features = torch.cat(split_features, 1)
425
+ merged_features = self.conv4(merged_features)
426
+ return merged_features
427
+
428
+
429
+ class DFineSCDown(nn.Module):
430
+ def __init__(self, config: DFineConfig, kernel_size: int, stride: int):
431
+ super().__init__()
432
+ self.conv1 = DFineConvNormLayer(config, config.encoder_hidden_dim, config.encoder_hidden_dim, 1, 1)
433
+ self.conv2 = DFineConvNormLayer(
434
+ config,
435
+ config.encoder_hidden_dim,
436
+ config.encoder_hidden_dim,
437
+ kernel_size,
438
+ stride,
439
+ config.encoder_hidden_dim,
440
+ )
441
+
442
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
443
+ input_features = self.conv1(input_features)
444
+ input_features = self.conv2(input_features)
445
+ return input_features
446
+
447
+
448
+ def eager_attention_forward(
449
+ module: nn.Module,
450
+ query: torch.Tensor,
451
+ key: torch.Tensor,
452
+ value: torch.Tensor,
453
+ attention_mask: torch.Tensor | None,
454
+ scaling: float | None = None,
455
+ dropout: float = 0.0,
456
+ **kwargs: Unpack[TransformersKwargs],
457
+ ):
458
+ if scaling is None:
459
+ scaling = query.size(-1) ** -0.5
460
+
461
+ # Take the dot product between "query" and "key" to get the raw attention scores.
462
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
463
+
464
+ if attention_mask is not None:
465
+ attn_weights = attn_weights + attention_mask
466
+
467
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
468
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
469
+
470
+ attn_output = torch.matmul(attn_weights, value)
471
+ attn_output = attn_output.transpose(1, 2).contiguous()
472
+
473
+ return attn_output, attn_weights
474
+
475
+
476
+ class DFineSelfAttention(nn.Module):
477
+ """
478
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
479
+
480
+ In D_FINE, position embeddings are added to both queries and keys (but not values) in self-attention.
481
+ """
482
+
483
+ def __init__(
484
+ self,
485
+ config: DFineConfig,
486
+ hidden_size: int,
487
+ num_attention_heads: int,
488
+ dropout: float = 0.0,
489
+ bias: bool = True,
490
+ ):
491
+ super().__init__()
492
+ self.config = config
493
+ self.head_dim = hidden_size // num_attention_heads
494
+ self.scaling = self.head_dim**-0.5
495
+ self.attention_dropout = dropout
496
+ self.is_causal = False
497
+
498
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
499
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
500
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
501
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
502
+
503
+ def forward(
504
+ self,
505
+ hidden_states: torch.Tensor,
506
+ attention_mask: torch.Tensor | None = None,
507
+ position_embeddings: torch.Tensor | None = None,
508
+ **kwargs: Unpack[TransformersKwargs],
509
+ ) -> tuple[torch.Tensor, torch.Tensor]:
510
+ """
511
+ Position embeddings are added to both queries and keys (but not values).
512
+ """
513
+ input_shape = hidden_states.shape[:-1]
514
+ hidden_shape = (*input_shape, -1, self.head_dim)
515
+
516
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
517
+
518
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
519
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
520
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
521
+
522
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
523
+ self.config._attn_implementation, eager_attention_forward
524
+ )
525
+
526
+ attn_output, attn_weights = attention_interface(
527
+ self,
528
+ query_states,
529
+ key_states,
530
+ value_states,
531
+ attention_mask,
532
+ dropout=0.0 if not self.training else self.attention_dropout,
533
+ scaling=self.scaling,
534
+ **kwargs,
535
+ )
536
+
537
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
538
+ attn_output = self.o_proj(attn_output)
539
+ return attn_output, attn_weights
540
+
541
+
542
+ class DFineEncoderLayer(nn.Module):
543
+ def __init__(self, config: DFineConfig):
544
+ super().__init__()
545
+ self.normalize_before = config.normalize_before
546
+ self.hidden_size = config.encoder_hidden_dim
547
+
548
+ # self-attention
549
+ self.self_attn = DFineSelfAttention(
550
+ config=config,
551
+ hidden_size=self.hidden_size,
552
+ num_attention_heads=config.num_attention_heads,
553
+ dropout=config.dropout,
554
+ )
555
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
556
+ self.dropout = config.dropout
557
+ self.mlp = DFineMLP(
558
+ self.hidden_size, config.encoder_ffn_dim, self.hidden_size, 2, config.encoder_activation_function
559
+ )
560
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
561
+
562
+ def forward(
563
+ self,
564
+ hidden_states: torch.Tensor,
565
+ attention_mask: torch.Tensor,
566
+ spatial_position_embeddings: torch.Tensor | None = None,
567
+ **kwargs: Unpack[TransformersKwargs],
568
+ ) -> torch.Tensor:
569
+ """
570
+ Args:
571
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
572
+ attention_mask (`torch.FloatTensor`): attention mask of size
573
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
574
+ values.
575
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
576
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
577
+ the queries and keys in self-attention (but not to values).
578
+ """
579
+ residual = hidden_states
580
+ if self.normalize_before:
581
+ hidden_states = self.self_attn_layer_norm(hidden_states)
582
+
583
+ hidden_states, _ = self.self_attn(
584
+ hidden_states=hidden_states,
585
+ attention_mask=attention_mask,
586
+ position_embeddings=spatial_position_embeddings,
587
+ **kwargs,
588
+ )
589
+
590
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
591
+ hidden_states = residual + hidden_states
592
+ if not self.normalize_before:
593
+ hidden_states = self.self_attn_layer_norm(hidden_states)
594
+
595
+ if self.normalize_before:
596
+ hidden_states = self.final_layer_norm(hidden_states)
597
+ residual = hidden_states
598
+
599
+ hidden_states = self.mlp(hidden_states)
600
+
601
+ hidden_states = residual + hidden_states
602
+ if not self.normalize_before:
603
+ hidden_states = self.final_layer_norm(hidden_states)
604
+
605
+ if self.training:
606
+ if not torch.isfinite(hidden_states).all():
607
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
608
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
609
+
610
+ return hidden_states
611
+
612
+
613
+ def build_2d_sinusoidal_position_embedding(
614
+ height: int,
615
+ width: int,
616
+ embed_dim: int = 256,
617
+ temperature: float = 10000.0,
618
+ cls_token: bool = False,
619
+ device: torch.device | None = None,
620
+ dtype: torch.dtype = torch.float32,
621
+ ) -> torch.Tensor:
622
+ """2D sinusoidal position embeddings for an image patch grid.
623
+
624
+ Each (h, w) position gets an ``embed_dim``-dimensional vector laid out as
625
+ ``[sin_h | cos_h | sin_w | cos_w]``, with row-major (H-outer) patch ordering.
626
+
627
+ Args:
628
+ height: Grid height in patches.
629
+ width: Grid width in patches.
630
+ embed_dim: Total embedding dimension; must be divisible by 4.
631
+ temperature: Base for the frequency decay.
632
+ cls_token: If `True`, prepend a zero row for a CLS token.
633
+ device: Target device; defaults to CPU.
634
+ dtype: Output dtype; frequency arithmetic uses float64 internally.
635
+
636
+ Returns:
637
+ Tensor of shape ``(height * width [+1], embed_dim)``.
638
+ """
639
+ if embed_dim % 4 != 0:
640
+ raise ValueError(f"`embed_dim` must be divisible by 4, got {embed_dim}")
641
+
642
+ pos_dim = embed_dim // 4
643
+ omega = torch.arange(pos_dim, dtype=torch.float64, device=device) / pos_dim
644
+ omega = 1.0 / temperature**omega # (D/4,)
645
+
646
+ grid_h = torch.arange(height, dtype=torch.float64, device=device)
647
+ grid_w = torch.arange(width, dtype=torch.float64, device=device)
648
+ grid_h, grid_w = torch.meshgrid(grid_h, grid_w, indexing="ij") # (H, W) each
649
+
650
+ emb_h = grid_h.flatten().outer(omega) # (H*W, D/4)
651
+ emb_w = grid_w.flatten().outer(omega) # (H*W, D/4)
652
+
653
+ pos_embed = torch.cat([emb_h.sin(), emb_h.cos(), emb_w.sin(), emb_w.cos()], dim=1)
654
+
655
+ if cls_token:
656
+ pos_embed = torch.cat([torch.zeros(1, embed_dim, dtype=torch.float64, device=device), pos_embed], dim=0)
657
+
658
+ return pos_embed.to(dtype)
659
+
660
+
661
+ class DFineSinePositionEmbedding(nn.Module):
662
+ """
663
+ 2D sinusoidal position embedding used in RT-DETR hybrid encoder.
664
+ """
665
+
666
+ def __init__(self, embed_dim: int = 256, temperature: int = 10000):
667
+ super().__init__()
668
+ self.embed_dim = embed_dim
669
+ self.temperature = temperature
670
+
671
+ @staticmethod
672
+ @compile_compatible_method_lru_cache(maxsize=32)
673
+ def _cached_build_2d_sinusoidal_position_embedding(*args, **kwargs) -> torch.Tensor:
674
+ return build_2d_sinusoidal_position_embedding(*args, **kwargs)
675
+
676
+ def forward(
677
+ self,
678
+ width: int,
679
+ height: int,
680
+ device: torch.device | str,
681
+ dtype: torch.dtype,
682
+ ) -> torch.Tensor:
683
+ """
684
+ Generate 2D sinusoidal position embeddings.
685
+
686
+ Returns:
687
+ Position embeddings of shape (1, height*width, embed_dim)
688
+ """
689
+ return self._cached_build_2d_sinusoidal_position_embedding(
690
+ height=torch_int(height),
691
+ width=torch_int(width),
692
+ embed_dim=self.embed_dim,
693
+ temperature=self.temperature,
694
+ device=device,
695
+ dtype=dtype,
696
+ ).unsqueeze(0)
697
+
698
+
699
+ class DFineAIFILayer(nn.Module):
700
+ """
701
+ AIFI (Attention-based Intra-scale Feature Interaction) layer used in RT-DETR hybrid encoder.
702
+ """
703
+
704
+ def __init__(self, config: DFineConfig):
705
+ super().__init__()
706
+ self.config = config
707
+ self.encoder_hidden_dim = config.encoder_hidden_dim
708
+ self.eval_size = config.eval_size
709
+
710
+ self.position_embedding = DFineSinePositionEmbedding(
711
+ embed_dim=self.encoder_hidden_dim,
712
+ temperature=config.positional_encoding_temperature,
713
+ )
714
+ self.layers = nn.ModuleList([DFineEncoderLayer(config) for _ in range(config.encoder_layers)])
715
+
716
+ def forward(
717
+ self,
718
+ hidden_states: torch.Tensor,
719
+ **kwargs: Unpack[TransformersKwargs],
720
+ ) -> torch.Tensor:
721
+ """
722
+ Args:
723
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, channels, height, width)`):
724
+ Feature map to process.
725
+ """
726
+ batch_size = hidden_states.shape[0]
727
+ height, width = hidden_states.shape[2:]
728
+
729
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
730
+
731
+ if self.training or self.eval_size is None:
732
+ pos_embed = self.position_embedding(
733
+ width=width,
734
+ height=height,
735
+ device=hidden_states.device,
736
+ dtype=hidden_states.dtype,
737
+ )
738
+ else:
739
+ pos_embed = None
740
+
741
+ for layer in self.layers:
742
+ hidden_states = layer(
743
+ hidden_states,
744
+ attention_mask=None,
745
+ spatial_position_embeddings=pos_embed,
746
+ **kwargs,
747
+ )
748
+
749
+ hidden_states = (
750
+ hidden_states.transpose(1, 2).reshape(batch_size, self.encoder_hidden_dim, height, width).contiguous()
751
+ )
752
+
753
+ return hidden_states
754
+
755
+
756
+ class DFineIntegral(nn.Module):
757
+ """
758
+ A static layer that calculates integral results from a distribution.
759
+
760
+ This layer computes the target location using the formula: `sum{Pr(n) * W(n)}`,
761
+ where Pr(n) is the softmax probability vector representing the discrete
762
+ distribution, and W(n) is the non-uniform Weighting Function.
763
+
764
+ Args:
765
+ max_num_bins (int): Max number of the discrete bins. Default is 32.
766
+ It can be adjusted based on the dataset or task requirements.
767
+ """
768
+
769
+ def __init__(self, config: DFineConfig):
770
+ super().__init__()
771
+ self.max_num_bins = config.max_num_bins
772
+
773
+ def forward(self, pred_corners: torch.Tensor, project: torch.Tensor) -> torch.Tensor:
774
+ batch_size, num_queries, _ = pred_corners.shape
775
+ pred_corners = F.softmax(pred_corners.reshape(-1, self.max_num_bins + 1), dim=1)
776
+ pred_corners = F.linear(pred_corners, project.to(pred_corners.device)).reshape(-1, 4)
777
+ pred_corners = pred_corners.reshape(batch_size, num_queries, -1)
778
+ return pred_corners
779
+
780
+
781
+ class DFineLQE(nn.Module):
782
+ def __init__(self, config: DFineConfig):
783
+ super().__init__()
784
+ self.top_prob_values = config.top_prob_values
785
+ self.max_num_bins = config.max_num_bins
786
+ self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
787
+
788
+ def forward(self, scores: torch.Tensor, pred_corners: torch.Tensor) -> torch.Tensor:
789
+ batch_size, length, _ = pred_corners.size()
790
+ prob = F.softmax(pred_corners.reshape(batch_size, length, 4, self.max_num_bins + 1), dim=-1)
791
+ prob_topk, _ = prob.topk(self.top_prob_values, dim=-1)
792
+ stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
793
+ quality_score = self.reg_conf(stat.reshape(batch_size, length, -1))
794
+ scores = scores + quality_score
795
+ return scores
796
+
797
+
798
+ class DFineDecoderLayer(nn.Module):
799
+ def __init__(self, config: DFineConfig):
800
+ super().__init__()
801
+ self.hidden_size = config.d_model
802
+
803
+ # self-attention
804
+ self.self_attn = DFineSelfAttention(
805
+ config=config,
806
+ hidden_size=self.hidden_size,
807
+ num_attention_heads=config.decoder_attention_heads,
808
+ dropout=config.attention_dropout,
809
+ )
810
+ self.dropout = config.dropout
811
+
812
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
813
+
814
+ # override the encoder attention module with d-fine version
815
+ self.encoder_attn = DFineMultiscaleDeformableAttention(config=config)
816
+ self.mlp = DFineMLP(
817
+ self.hidden_size, config.decoder_ffn_dim, self.hidden_size, 2, config.decoder_activation_function
818
+ )
819
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
820
+ # gate
821
+ self.gateway = DFineGate(config.d_model)
822
+
823
+ def forward(
824
+ self,
825
+ hidden_states: torch.Tensor,
826
+ position_embeddings: torch.Tensor | None = None,
827
+ reference_points=None,
828
+ spatial_shapes=None,
829
+ spatial_shapes_list=None,
830
+ encoder_hidden_states: torch.Tensor | None = None,
831
+ encoder_attention_mask: torch.Tensor | None = None,
832
+ **kwargs: Unpack[TransformersKwargs],
833
+ ) -> torch.Tensor:
834
+ """
835
+ Args:
836
+ hidden_states (`torch.FloatTensor`):
837
+ Input to the layer of shape `(batch, seq_len, hidden_size)`.
838
+ object_queries_position_embeddings (`torch.FloatTensor`, *optional*):
839
+ Position embeddings for the object query slots. These are added to both queries and keys
840
+ in the self-attention layer (not values).
841
+ reference_points (`torch.FloatTensor`, *optional*):
842
+ Reference points.
843
+ spatial_shapes (`torch.LongTensor`, *optional*):
844
+ Spatial shapes.
845
+ level_start_index (`torch.LongTensor`, *optional*):
846
+ Level start index.
847
+ encoder_hidden_states (`torch.FloatTensor`):
848
+ cross attention input to the layer of shape `(batch, seq_len, hidden_size)`
849
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
850
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
851
+ values.
852
+ """
853
+ residual = hidden_states
854
+
855
+ # Self Attention
856
+ hidden_states, _ = self.self_attn(
857
+ hidden_states=hidden_states,
858
+ attention_mask=encoder_attention_mask,
859
+ position_embeddings=position_embeddings,
860
+ **kwargs,
861
+ )
862
+
863
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
864
+ hidden_states = residual + hidden_states
865
+ hidden_states = self.self_attn_layer_norm(hidden_states)
866
+
867
+ residual = hidden_states
868
+
869
+ # Cross-Attention
870
+ hidden_states = hidden_states if position_embeddings is None else hidden_states + position_embeddings
871
+ hidden_states, _ = self.encoder_attn(
872
+ hidden_states=hidden_states,
873
+ encoder_hidden_states=encoder_hidden_states,
874
+ reference_points=reference_points,
875
+ spatial_shapes=spatial_shapes,
876
+ spatial_shapes_list=spatial_shapes_list,
877
+ )
878
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
879
+ hidden_states = self.gateway(residual, hidden_states)
880
+
881
+ # Fully Connected
882
+ residual = hidden_states
883
+ hidden_states = self.mlp(hidden_states)
884
+ hidden_states = residual + hidden_states
885
+ hidden_states = self.final_layer_norm(hidden_states.clamp(min=-65504, max=65504))
886
+
887
+ return hidden_states
888
+
889
+
890
+ class DFineMLPPredictionHead(nn.Module):
891
+ """
892
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
893
+ height and width of a bounding box w.r.t. an image.
894
+
895
+ """
896
+
897
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
898
+ super().__init__()
899
+ self.num_layers = num_layers
900
+ h = [hidden_dim] * (num_layers - 1)
901
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
902
+
903
+ def forward(self, x):
904
+ for i, layer in enumerate(self.layers):
905
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
906
+ return x
907
+
908
+
909
+ @auto_docstring
910
+ class DFinePreTrainedModel(PreTrainedModel):
911
+ config: DFineConfig
912
+ base_model_prefix = "d_fine"
913
+ main_input_name = "pixel_values"
914
+ input_modalities = ("image",)
915
+ _no_split_modules = [r"DFineHybridEncoder", r"DFineDecoderLayer"]
916
+ _supports_sdpa = True
917
+ _supports_flash_attn = True
918
+ _supports_attention_backend = True
919
+ _supports_flex_attn = True
920
+
921
+ @torch.no_grad()
922
+ def _init_weights(self, module):
923
+ """Initialize the weights"""
924
+ super()._init_weights(module)
925
+ # initialize linear layer bias value according to a given probability value.
926
+ if isinstance(module, (DFineForObjectDetection, DFineDecoder)):
927
+ if module.class_embed is not None:
928
+ for layer in module.class_embed:
929
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
930
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
931
+ init.xavier_uniform_(layer.weight)
932
+ init.constant_(layer.bias, bias)
933
+
934
+ if module.bbox_embed is not None:
935
+ for layer in module.bbox_embed:
936
+ init.constant_(layer.layers[-1].weight, 0)
937
+ init.constant_(layer.layers[-1].bias, 0)
938
+
939
+ if hasattr(module, "reg_scale"):
940
+ init.constant_(module.reg_scale, self.config.reg_scale)
941
+
942
+ if hasattr(module, "up"):
943
+ init.constant_(module.up, self.config.up)
944
+
945
+ if isinstance(module, DFineMultiscaleDeformableAttention):
946
+ init.constant_(module.sampling_offsets.weight, 0.0)
947
+ default_dtype = torch.get_default_dtype()
948
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
949
+ 2.0 * math.pi / module.n_heads
950
+ )
951
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
952
+ grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
953
+ grid_init = grid_init.reshape(module.n_heads, 1, 2).tile([1, sum(module.num_points_list), 1])
954
+ scaling = torch.concat([torch.arange(1, n + 1) for n in module.num_points_list]).reshape(1, -1, 1)
955
+ grid_init *= scaling
956
+ init.copy_(module.sampling_offsets.bias, grid_init.flatten())
957
+
958
+ init.constant_(module.attention_weights.weight, 0.0)
959
+ init.constant_(module.attention_weights.bias, 0.0)
960
+
961
+ num_points_scale = [1 / n for n in module.num_points_list for _ in range(n)]
962
+ init.copy_(module.num_points_scale, torch.tensor(num_points_scale, dtype=torch.float32))
963
+
964
+ if isinstance(module, DFineModel):
965
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
966
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
967
+ init.xavier_uniform_(module.enc_score_head.weight)
968
+ init.constant_(module.enc_score_head.bias, bias)
969
+
970
+ if isinstance(module, DFineGate):
971
+ bias = float(-math.log((1 - 0.5) / 0.5))
972
+ init.constant_(module.gate.bias, bias)
973
+ init.constant_(module.gate.weight, 0)
974
+
975
+ if isinstance(module, DFineLQE):
976
+ init.constant_(module.reg_conf.layers[-1].bias, 0)
977
+ init.constant_(module.reg_conf.layers[-1].weight, 0)
978
+
979
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
980
+ init.xavier_uniform_(module.weight_embedding.weight)
981
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
982
+ init.xavier_uniform_(module.denoising_class_embed.weight)
983
+
984
+
985
+ class DFineHybridEncoder(DFinePreTrainedModel):
986
+ """
987
+ Hybrid encoder consisting of AIFI (Attention-based Intra-scale Feature Interaction) layers,
988
+ a top-down Feature Pyramid Network (FPN) and a bottom-up Path Aggregation Network (PAN).
989
+ More details on the paper: https://huggingface.co/papers/2304.08069
990
+
991
+ Args:
992
+ config: DFineConfig
993
+ """
994
+
995
+ _can_record_outputs = {
996
+ "hidden_states": DFineAIFILayer,
997
+ "attentions": DFineSelfAttention,
998
+ }
999
+
1000
+ def __init__(self, config: DFineConfig):
1001
+ super().__init__(config)
1002
+ self.config = config
1003
+ self.in_channels = config.encoder_in_channels
1004
+ self.num_fpn_stages = len(self.in_channels) - 1
1005
+ self.feat_strides = config.feat_strides
1006
+ self.encoder_hidden_dim = config.encoder_hidden_dim
1007
+ self.encode_proj_layers = config.encode_proj_layers
1008
+ self.positional_encoding_temperature = config.positional_encoding_temperature
1009
+ self.eval_size = config.eval_size
1010
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
1011
+ self.out_strides = self.feat_strides
1012
+
1013
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
1014
+ self.aifi = nn.ModuleList([DFineAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
1015
+
1016
+ # top-down fpn
1017
+ self.lateral_convs = nn.ModuleList()
1018
+ self.fpn_blocks = nn.ModuleList()
1019
+ for _ in range(len(self.in_channels) - 1, 0, -1):
1020
+ lateral_layer = DFineConvNormLayer(config, self.encoder_hidden_dim, self.encoder_hidden_dim, 1, 1)
1021
+ self.lateral_convs.append(lateral_layer)
1022
+ num_blocks = round(3 * config.depth_mult)
1023
+ fpn_layer = DFineRepNCSPELAN4(config, numb_blocks=num_blocks)
1024
+ self.fpn_blocks.append(fpn_layer)
1025
+
1026
+ # bottom-up pan
1027
+ self.downsample_convs = nn.ModuleList()
1028
+ self.pan_blocks = nn.ModuleList()
1029
+ for _ in range(len(self.in_channels) - 1):
1030
+ self.downsample_convs.append(DFineSCDown(config, 3, 2))
1031
+ num_blocks = round(3 * config.depth_mult)
1032
+ self.pan_blocks.append(DFineRepNCSPELAN4(config, numb_blocks=num_blocks))
1033
+
1034
+ self.post_init()
1035
+
1036
+ @merge_with_config_defaults
1037
+ @capture_outputs(tie_last_hidden_states=False)
1038
+ def forward(
1039
+ self,
1040
+ inputs_embeds=None,
1041
+ **kwargs: Unpack[TransformersKwargs],
1042
+ ) -> BaseModelOutput:
1043
+ r"""
1044
+ Args:
1045
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1046
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
1047
+ """
1048
+ feature_maps = inputs_embeds
1049
+
1050
+ # AIFI: Apply transformer encoder to specified feature levels
1051
+ if self.config.encoder_layers > 0:
1052
+ for i, enc_ind in enumerate(self.encode_proj_layers):
1053
+ feature_maps[enc_ind] = self.aifi[i](feature_maps[enc_ind], **kwargs)
1054
+
1055
+ # top-down FPN
1056
+ fpn_feature_maps = [feature_maps[-1]]
1057
+ for idx, (lateral_conv, fpn_block) in enumerate(zip(self.lateral_convs, self.fpn_blocks)):
1058
+ backbone_feature_map = feature_maps[self.num_fpn_stages - idx - 1]
1059
+ top_fpn_feature_map = fpn_feature_maps[-1]
1060
+ # apply lateral block
1061
+ top_fpn_feature_map = lateral_conv(top_fpn_feature_map)
1062
+ fpn_feature_maps[-1] = top_fpn_feature_map
1063
+ # apply fpn block
1064
+ top_fpn_feature_map = F.interpolate(top_fpn_feature_map, scale_factor=2.0, mode="nearest")
1065
+ fused_feature_map = torch.concat([top_fpn_feature_map, backbone_feature_map], dim=1)
1066
+ new_fpn_feature_map = fpn_block(fused_feature_map)
1067
+ fpn_feature_maps.append(new_fpn_feature_map)
1068
+
1069
+ fpn_feature_maps.reverse()
1070
+
1071
+ # bottom-up PAN
1072
+ pan_feature_maps = [fpn_feature_maps[0]]
1073
+ for idx, (downsample_conv, pan_block) in enumerate(zip(self.downsample_convs, self.pan_blocks)):
1074
+ top_pan_feature_map = pan_feature_maps[-1]
1075
+ fpn_feature_map = fpn_feature_maps[idx + 1]
1076
+ downsampled_feature_map = downsample_conv(top_pan_feature_map)
1077
+ fused_feature_map = torch.concat([downsampled_feature_map, fpn_feature_map], dim=1)
1078
+ new_pan_feature_map = pan_block(fused_feature_map)
1079
+ pan_feature_maps.append(new_pan_feature_map)
1080
+
1081
+ return BaseModelOutput(last_hidden_state=pan_feature_maps)
1082
+
1083
+
1084
+ def inverse_sigmoid(x, eps=1e-5):
1085
+ x = x.clamp(min=0, max=1)
1086
+ x1 = x.clamp(min=eps)
1087
+ x2 = (1 - x).clamp(min=eps)
1088
+ return torch.log(x1 / x2)
1089
+
1090
+
1091
+ def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:
1092
+ """
1093
+ Generates the non-uniform Weighting Function W(n) for bounding box regression.
1094
+
1095
+ Args:
1096
+ max_num_bins (int): Max number of the discrete bins.
1097
+ up (Tensor): Controls upper bounds of the sequence,
1098
+ where maximum offset is ±up * H / W.
1099
+ reg_scale (float): Controls the curvature of the Weighting Function.
1100
+ Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
1101
+ and steeper weights at both ends.
1102
+ Returns:
1103
+ Tensor: Sequence of Weighting Function.
1104
+ """
1105
+ upper_bound1 = abs(up[0]) * abs(reg_scale)
1106
+ upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
1107
+ step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))
1108
+ left_values = [-((step) ** i) + 1 for i in range(max_num_bins // 2 - 1, 0, -1)]
1109
+ right_values = [(step) ** i - 1 for i in range(1, max_num_bins // 2)]
1110
+ values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]
1111
+ values = torch.cat(values, 0)
1112
+ return values
1113
+
1114
+
1115
+ def distance2bbox(points, distance: torch.Tensor, reg_scale: float) -> torch.Tensor:
1116
+ """
1117
+ Decodes edge-distances into bounding box coordinates.
1118
+
1119
+ Args:
1120
+ points (`torch.Tensor`):
1121
+ (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
1122
+ distance (`torch.Tensor`):
1123
+ (batch_size, num_boxes, 4) or (num_boxes, 4), representing distances from the point to the left, top, right, and bottom boundaries.
1124
+ reg_scale (`float`):
1125
+ Controls the curvature of the Weighting Function.
1126
+ Returns:
1127
+ `torch.Tensor`: Bounding boxes in (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
1128
+ """
1129
+ reg_scale = abs(reg_scale)
1130
+ top_left_x = points[..., 0] - (0.5 * reg_scale + distance[..., 0]) * (points[..., 2] / reg_scale)
1131
+ top_left_y = points[..., 1] - (0.5 * reg_scale + distance[..., 1]) * (points[..., 3] / reg_scale)
1132
+ bottom_right_x = points[..., 0] + (0.5 * reg_scale + distance[..., 2]) * (points[..., 2] / reg_scale)
1133
+ bottom_right_y = points[..., 1] + (0.5 * reg_scale + distance[..., 3]) * (points[..., 3] / reg_scale)
1134
+
1135
+ bboxes = torch.stack([top_left_x, top_left_y, bottom_right_x, bottom_right_y], -1)
1136
+
1137
+ return corners_to_center_format(bboxes)
1138
+
1139
+
1140
+ class DFineDecoder(DFinePreTrainedModel):
1141
+ """
1142
+ D-FINE Decoder implementing Fine-grained Distribution Refinement (FDR).
1143
+
1144
+ This decoder refines object detection predictions through iterative updates across multiple layers,
1145
+ utilizing attention mechanisms, location quality estimators, and distribution refinement techniques
1146
+ to improve bounding box accuracy and robustness.
1147
+ """
1148
+
1149
+ _can_record_outputs = {
1150
+ "hidden_states": DFineDecoderLayer,
1151
+ "attentions": DFineSelfAttention,
1152
+ "cross_attentions": DFineMultiscaleDeformableAttention,
1153
+ }
1154
+
1155
+ def __init__(self, config: DFineConfig):
1156
+ super().__init__(config)
1157
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
1158
+
1159
+ self.dropout = config.dropout
1160
+ self.layers = nn.ModuleList(
1161
+ [DFineDecoderLayer(config) for _ in range(config.decoder_layers)]
1162
+ + [DFineDecoderLayer(config) for _ in range(config.decoder_layers - self.eval_idx - 1)]
1163
+ )
1164
+ self.query_pos_head = DFineMLPPredictionHead(4, 2 * config.d_model, config.d_model, num_layers=2)
1165
+
1166
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
1167
+ self.bbox_embed = None
1168
+ self.class_embed = None
1169
+ self.reg_scale = nn.Parameter(torch.tensor([config.reg_scale]), requires_grad=False)
1170
+ self.max_num_bins = config.max_num_bins
1171
+ self.d_model = config.d_model
1172
+ self.layer_scale = config.layer_scale
1173
+ self.pre_bbox_head = DFineMLP(config.hidden_size, config.hidden_size, 4, 3)
1174
+ self.integral = DFineIntegral(config)
1175
+ self.num_head = config.decoder_attention_heads
1176
+ self.up = nn.Parameter(torch.tensor([config.up]), requires_grad=False)
1177
+ self.lqe_layers = nn.ModuleList([DFineLQE(config) for _ in range(config.decoder_layers)])
1178
+
1179
+ # Initialize weights and apply final processing
1180
+ self.post_init()
1181
+
1182
+ @merge_with_config_defaults
1183
+ @capture_outputs
1184
+ def forward(
1185
+ self,
1186
+ encoder_hidden_states: torch.Tensor,
1187
+ reference_points: torch.Tensor,
1188
+ inputs_embeds: torch.Tensor,
1189
+ spatial_shapes,
1190
+ level_start_index=None,
1191
+ spatial_shapes_list=None,
1192
+ encoder_attention_mask=None,
1193
+ memory_mask=None,
1194
+ **kwargs: Unpack[TransformersKwargs],
1195
+ ) -> DFineDecoderOutput:
1196
+ r"""
1197
+ Args:
1198
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1199
+ The query embeddings that are passed into the decoder.
1200
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1201
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1202
+ of the decoder.
1203
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
1205
+ in `[0, 1]`:
1206
+ - 1 for pixels that are real (i.e. **not masked**),
1207
+ - 0 for pixels that are padding (i.e. **masked**).
1208
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
1209
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
1210
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
1211
+ Spatial shapes of the feature maps.
1212
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
1213
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
1214
+ """
1215
+ if inputs_embeds is not None:
1216
+ hidden_states = inputs_embeds
1217
+
1218
+ # decoder layers
1219
+ intermediate = ()
1220
+ intermediate_reference_points = ()
1221
+ intermediate_logits = ()
1222
+ intermediate_predicted_corners = ()
1223
+ initial_reference_points = ()
1224
+
1225
+ output_detach = pred_corners_undetach = 0
1226
+
1227
+ project = weighting_function(self.max_num_bins, self.up, self.reg_scale)
1228
+ ref_points_detach = F.sigmoid(reference_points)
1229
+
1230
+ for i, decoder_layer in enumerate(self.layers):
1231
+ ref_points_input = ref_points_detach.unsqueeze(2)
1232
+ query_pos_embed = self.query_pos_head(ref_points_detach).clamp(min=-10, max=10)
1233
+
1234
+ hidden_states = decoder_layer(
1235
+ hidden_states,
1236
+ position_embeddings=query_pos_embed,
1237
+ reference_points=ref_points_input,
1238
+ spatial_shapes=spatial_shapes,
1239
+ spatial_shapes_list=spatial_shapes_list,
1240
+ encoder_hidden_states=encoder_hidden_states,
1241
+ encoder_attention_mask=encoder_attention_mask,
1242
+ **kwargs,
1243
+ )
1244
+
1245
+ if i == 0:
1246
+ # Initial bounding box predictions with inverse sigmoid refinement
1247
+ new_reference_points = F.sigmoid(
1248
+ self.pre_bbox_head(hidden_states) + inverse_sigmoid(ref_points_detach)
1249
+ )
1250
+ ref_points_initial = new_reference_points.detach()
1251
+
1252
+ # Refine bounding box corners using FDR, integrating previous layer's corrections
1253
+ if self.bbox_embed is not None:
1254
+ pred_corners = self.bbox_embed[i](hidden_states + output_detach) + pred_corners_undetach
1255
+ inter_ref_bbox = distance2bbox(
1256
+ ref_points_initial, self.integral(pred_corners, project), self.reg_scale
1257
+ )
1258
+ pred_corners_undetach = pred_corners
1259
+ ref_points_detach = inter_ref_bbox.detach()
1260
+
1261
+ output_detach = hidden_states.detach()
1262
+
1263
+ intermediate += (hidden_states,)
1264
+
1265
+ if self.class_embed is not None and (self.training or i == self.eval_idx):
1266
+ scores = self.class_embed[i](hidden_states)
1267
+ # Add initial logits and reference points with pre-bbox head
1268
+ if i == 0:
1269
+ intermediate_logits += (scores,)
1270
+ intermediate_reference_points += (new_reference_points,)
1271
+ # Lqe does not affect the performance here.
1272
+ scores = self.lqe_layers[i](scores, pred_corners)
1273
+ intermediate_logits += (scores,)
1274
+ intermediate_reference_points += (inter_ref_bbox,)
1275
+ initial_reference_points += (ref_points_initial,)
1276
+ intermediate_predicted_corners += (pred_corners,)
1277
+
1278
+ # Keep batch_size as first dimension
1279
+ intermediate = torch.stack(intermediate)
1280
+ if self.class_embed is not None and self.bbox_embed is not None:
1281
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
1282
+ intermediate_predicted_corners = torch.stack(intermediate_predicted_corners, dim=1)
1283
+ initial_reference_points = torch.stack(initial_reference_points, dim=1)
1284
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
1285
+
1286
+ return DFineDecoderOutput(
1287
+ last_hidden_state=hidden_states,
1288
+ intermediate_hidden_states=intermediate,
1289
+ intermediate_logits=intermediate_logits,
1290
+ intermediate_reference_points=intermediate_reference_points,
1291
+ intermediate_predicted_corners=intermediate_predicted_corners,
1292
+ initial_reference_points=initial_reference_points,
1293
+ )
1294
+
1295
+
1296
+ @auto_docstring(
1297
+ custom_intro="""
1298
+ Base class for outputs of the RT-DETR encoder-decoder model.
1299
+ """
1300
+ )
1301
+ @dataclass
1302
+ class DFineModelOutput(ModelOutput):
1303
+ r"""
1304
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1305
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
1306
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
1307
+ Stacked intermediate hidden states (output of each layer of the decoder).
1308
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
1309
+ Stacked intermediate logits (logits of each layer of the decoder).
1310
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1311
+ Stacked intermediate reference points (reference points of each layer of the decoder).
1312
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1313
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
1314
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1315
+ Initial reference points used for the first decoder layer.
1316
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1317
+ Initial reference points sent through the Transformer decoder.
1318
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
1319
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1320
+ picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e.
1321
+ foreground and background).
1322
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`):
1323
+ Logits of predicted bounding boxes coordinates in the encoder stage.
1324
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1325
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1326
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
1327
+ foreground and background).
1328
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1329
+ Logits of predicted bounding boxes coordinates in the first stage.
1330
+ denoising_meta_values (`dict`):
1331
+ Extra dictionary for the denoising related values.
1332
+ """
1333
+
1334
+ last_hidden_state: torch.FloatTensor | None = None
1335
+ intermediate_hidden_states: torch.FloatTensor | None = None
1336
+ intermediate_logits: torch.FloatTensor | None = None
1337
+ intermediate_reference_points: torch.FloatTensor | None = None
1338
+ intermediate_predicted_corners: torch.FloatTensor | None = None
1339
+ initial_reference_points: torch.FloatTensor | None = None
1340
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
1341
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
1342
+ cross_attentions: tuple[torch.FloatTensor] | None = None
1343
+ encoder_last_hidden_state: torch.FloatTensor | None = None
1344
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
1345
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
1346
+ init_reference_points: torch.FloatTensor | None = None
1347
+ enc_topk_logits: torch.FloatTensor | None = None
1348
+ enc_topk_bboxes: torch.FloatTensor | None = None
1349
+ enc_outputs_class: torch.FloatTensor | None = None
1350
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
1351
+ denoising_meta_values: dict | None = None
1352
+
1353
+
1354
+ def replace_batch_norm(model):
1355
+ r"""
1356
+ Recursively replace all `torch.nn.BatchNorm2d` with `DFineFrozenBatchNorm2d`.
1357
+
1358
+ Args:
1359
+ model (torch.nn.Module):
1360
+ input model
1361
+ """
1362
+ for name, module in model.named_children():
1363
+ if isinstance(module, nn.BatchNorm2d):
1364
+ new_module = DFineFrozenBatchNorm2d(module.num_features)
1365
+
1366
+ if module.weight.device != torch.device("meta"):
1367
+ new_module.weight.copy_(module.weight)
1368
+ new_module.bias.copy_(module.bias)
1369
+ new_module.running_mean.copy_(module.running_mean)
1370
+ new_module.running_var.copy_(module.running_var)
1371
+
1372
+ model._modules[name] = new_module
1373
+
1374
+ if len(list(module.children())) > 0:
1375
+ replace_batch_norm(module)
1376
+
1377
+
1378
+ class DFineConvEncoder(nn.Module):
1379
+ """
1380
+ Convolutional backbone using the modeling_d_fine_resnet.py.
1381
+
1382
+ nn.BatchNorm2d layers are replaced by DFineFrozenBatchNorm2d as defined above.
1383
+ https://github.com/lyuwenyu/RT-DETR/blob/main/DFine_pytorch/src/nn/backbone/presnet.py#L142
1384
+ """
1385
+
1386
+ def __init__(self, config):
1387
+ super().__init__()
1388
+
1389
+ backbone = load_backbone(config)
1390
+
1391
+ if config.freeze_backbone_batch_norms:
1392
+ # replace batch norm by frozen batch norm
1393
+ with torch.no_grad():
1394
+ replace_batch_norm(backbone)
1395
+ self.model = backbone
1396
+ self.intermediate_channel_sizes = self.model.channels
1397
+
1398
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
1399
+ # send pixel_values through the model to get list of feature maps
1400
+ features = self.model(pixel_values).feature_maps
1401
+
1402
+ out = []
1403
+ for feature_map in features:
1404
+ # downsample pixel_mask to match shape of corresponding feature_map
1405
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
1406
+ out.append((feature_map, mask))
1407
+ return out
1408
+
1409
+
1410
+ def get_contrastive_denoising_training_group(
1411
+ targets,
1412
+ num_classes,
1413
+ num_queries,
1414
+ class_embed,
1415
+ num_denoising_queries=100,
1416
+ label_noise_ratio=0.5,
1417
+ box_noise_scale=1.0,
1418
+ ):
1419
+ """
1420
+ Creates a contrastive denoising training group using ground-truth samples. It adds noise to labels and boxes.
1421
+
1422
+ Args:
1423
+ targets (`list[dict]`):
1424
+ The target objects, each containing 'class_labels' and 'boxes' for objects in an image.
1425
+ num_classes (`int`):
1426
+ Total number of classes in the dataset.
1427
+ num_queries (`int`):
1428
+ Number of query slots in the transformer.
1429
+ class_embed (`callable`):
1430
+ A function or a model layer to embed class labels.
1431
+ num_denoising_queries (`int`, *optional*, defaults to 100):
1432
+ Number of denoising queries.
1433
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
1434
+ Ratio of noise applied to labels.
1435
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
1436
+ Scale of noise applied to bounding boxes.
1437
+ Returns:
1438
+ `tuple` comprising various elements:
1439
+ - **input_query_class** (`torch.FloatTensor`) --
1440
+ Class queries with applied label noise.
1441
+ - **input_query_bbox** (`torch.FloatTensor`) --
1442
+ Bounding box queries with applied box noise.
1443
+ - **attn_mask** (`torch.FloatTensor`) --
1444
+ Attention mask for separating denoising and reconstruction queries.
1445
+ - **denoising_meta_values** (`dict`) --
1446
+ Metadata including denoising positive indices, number of groups, and split sizes.
1447
+ """
1448
+
1449
+ if num_denoising_queries <= 0:
1450
+ return None, None, None, None
1451
+
1452
+ num_ground_truths = [len(t["class_labels"]) for t in targets]
1453
+ device = targets[0]["class_labels"].device
1454
+
1455
+ max_gt_num = max(num_ground_truths)
1456
+ if max_gt_num == 0:
1457
+ return None, None, None, None
1458
+
1459
+ num_groups_denoising_queries = num_denoising_queries // max_gt_num
1460
+ num_groups_denoising_queries = 1 if num_groups_denoising_queries == 0 else num_groups_denoising_queries
1461
+ # pad gt to max_num of a batch
1462
+ batch_size = len(num_ground_truths)
1463
+
1464
+ input_query_class = torch.full([batch_size, max_gt_num], num_classes, dtype=torch.int32, device=device)
1465
+ input_query_bbox = torch.zeros([batch_size, max_gt_num, 4], device=device)
1466
+ pad_gt_mask = torch.zeros([batch_size, max_gt_num], dtype=torch.bool, device=device)
1467
+
1468
+ for i in range(batch_size):
1469
+ num_gt = num_ground_truths[i]
1470
+ if num_gt > 0:
1471
+ input_query_class[i, :num_gt] = targets[i]["class_labels"]
1472
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
1473
+ pad_gt_mask[i, :num_gt] = 1
1474
+ # each group has positive and negative queries.
1475
+ input_query_class = input_query_class.tile([1, 2 * num_groups_denoising_queries])
1476
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_groups_denoising_queries, 1])
1477
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_groups_denoising_queries])
1478
+ # positive and negative mask
1479
+ negative_gt_mask = torch.zeros([batch_size, max_gt_num * 2, 1], device=device)
1480
+ negative_gt_mask[:, max_gt_num:] = 1
1481
+ negative_gt_mask = negative_gt_mask.tile([1, num_groups_denoising_queries, 1])
1482
+ positive_gt_mask = 1 - negative_gt_mask
1483
+ # contrastive denoising training positive index
1484
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
1485
+ denoise_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
1486
+ denoise_positive_idx = torch.split(
1487
+ denoise_positive_idx, [n * num_groups_denoising_queries for n in num_ground_truths]
1488
+ )
1489
+ # total denoising queries
1490
+ num_denoising_queries = torch_int(max_gt_num * 2 * num_groups_denoising_queries)
1491
+
1492
+ if label_noise_ratio > 0:
1493
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
1494
+ # randomly put a new one here
1495
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
1496
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
1497
+
1498
+ if box_noise_scale > 0:
1499
+ known_bbox = center_to_corners_format(input_query_bbox)
1500
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
1501
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
1502
+ rand_part = torch.rand_like(input_query_bbox)
1503
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
1504
+ rand_part *= rand_sign
1505
+ known_bbox += rand_part * diff
1506
+ known_bbox.clip_(min=0.0, max=1.0)
1507
+ input_query_bbox = corners_to_center_format(known_bbox)
1508
+ input_query_bbox = inverse_sigmoid(input_query_bbox)
1509
+
1510
+ input_query_class = class_embed(input_query_class)
1511
+
1512
+ target_size = num_denoising_queries + num_queries
1513
+ attn_mask = torch.full([target_size, target_size], 0, dtype=torch.float, device=device)
1514
+ # match query cannot see the reconstruction
1515
+ attn_mask[num_denoising_queries:, :num_denoising_queries] = -torch.inf
1516
+
1517
+ # reconstructions cannot see each other
1518
+ for i in range(num_groups_denoising_queries):
1519
+ idx_block_start = max_gt_num * 2 * i
1520
+ idx_block_end = max_gt_num * 2 * (i + 1)
1521
+ attn_mask[idx_block_start:idx_block_end, :idx_block_start] = -torch.inf
1522
+ attn_mask[idx_block_start:idx_block_end, idx_block_end:num_denoising_queries] = -torch.inf
1523
+
1524
+ denoising_meta_values = {
1525
+ "dn_positive_idx": denoise_positive_idx,
1526
+ "dn_num_group": num_groups_denoising_queries,
1527
+ "dn_num_split": [num_denoising_queries, num_queries],
1528
+ }
1529
+
1530
+ return input_query_class, input_query_bbox, attn_mask, denoising_meta_values
1531
+
1532
+
1533
+ @auto_docstring(
1534
+ custom_intro="""
1535
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting raw hidden states without any head on top.
1536
+ """
1537
+ )
1538
+ class DFineModel(DFinePreTrainedModel):
1539
+ def __init__(self, config: DFineConfig):
1540
+ super().__init__(config)
1541
+
1542
+ # Create backbone
1543
+ self.backbone = DFineConvEncoder(config)
1544
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
1545
+ num_backbone_outs = len(config.decoder_in_channels)
1546
+ encoder_input_proj_list = []
1547
+ for i in range(num_backbone_outs):
1548
+ in_channels = intermediate_channel_sizes[i]
1549
+ encoder_input_proj_list.append(
1550
+ nn.Sequential(
1551
+ nn.Conv2d(in_channels, config.encoder_hidden_dim, kernel_size=1, bias=False),
1552
+ nn.BatchNorm2d(config.encoder_hidden_dim),
1553
+ )
1554
+ )
1555
+ self.encoder_input_proj = nn.ModuleList(encoder_input_proj_list)
1556
+ self.encoder = DFineHybridEncoder(config=config)
1557
+
1558
+ # denoising part
1559
+ if config.num_denoising > 0:
1560
+ self.denoising_class_embed = nn.Embedding(
1561
+ config.num_labels + 1, config.d_model, padding_idx=config.num_labels
1562
+ )
1563
+
1564
+ # decoder embedding
1565
+ if config.learn_initial_query:
1566
+ self.weight_embedding = nn.Embedding(config.num_queries, config.d_model)
1567
+
1568
+ # encoder head
1569
+ self.enc_output = nn.Sequential(
1570
+ nn.Linear(config.d_model, config.d_model),
1571
+ nn.LayerNorm(config.d_model, eps=config.layer_norm_eps),
1572
+ )
1573
+ self.enc_score_head = nn.Linear(config.d_model, config.num_labels)
1574
+ self.enc_bbox_head = DFineMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
1575
+
1576
+ # init encoder output anchors and valid_mask
1577
+ if config.anchor_image_size:
1578
+ self.anchors, self.valid_mask = self.generate_anchors(dtype=self.dtype)
1579
+ num_backbone_outs = len(config.decoder_in_channels)
1580
+ decoder_input_proj_list = []
1581
+ for i in range(num_backbone_outs):
1582
+ in_channels = config.decoder_in_channels[i]
1583
+ decoder_input_proj_list.append(
1584
+ nn.Sequential(
1585
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False),
1586
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
1587
+ )
1588
+ )
1589
+ for _ in range(config.num_feature_levels - num_backbone_outs):
1590
+ decoder_input_proj_list.append(
1591
+ nn.Sequential(
1592
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False),
1593
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
1594
+ )
1595
+ )
1596
+ in_channels = config.d_model
1597
+ self.decoder = DFineDecoder(config)
1598
+ decoder_input_proj = []
1599
+ in_channels = config.decoder_in_channels[-1]
1600
+ for _ in range(num_backbone_outs):
1601
+ if config.hidden_size == config.decoder_in_channels[-1]:
1602
+ decoder_input_proj.append(nn.Identity())
1603
+ else:
1604
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False)
1605
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1606
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1607
+ for _ in range(config.num_feature_levels - num_backbone_outs):
1608
+ if config.hidden_size == config.decoder_in_channels[-1]:
1609
+ decoder_input_proj.append(nn.Identity())
1610
+ else:
1611
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False)
1612
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1613
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1614
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj)
1615
+
1616
+ self.post_init()
1617
+
1618
+ def freeze_backbone(self):
1619
+ for param in self.backbone.parameters():
1620
+ param.requires_grad_(False)
1621
+
1622
+ def unfreeze_backbone(self):
1623
+ for param in self.backbone.parameters():
1624
+ param.requires_grad_(True)
1625
+
1626
+ @staticmethod
1627
+ @compile_compatible_method_lru_cache(maxsize=32)
1628
+ def _cached_generate_anchors(
1629
+ spatial_shapes: tuple[tuple[int, int], ...],
1630
+ grid_size: float,
1631
+ device: torch.device | str = "cpu",
1632
+ dtype: torch.dtype = torch.float32,
1633
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1634
+ anchors = []
1635
+ for level, (height, width) in enumerate(spatial_shapes):
1636
+ grid_y, grid_x = torch.meshgrid(
1637
+ torch.arange(end=height, device=device).to(dtype),
1638
+ torch.arange(end=width, device=device).to(dtype),
1639
+ indexing="ij",
1640
+ )
1641
+ grid_xy = torch.stack([grid_x, grid_y], -1)
1642
+ grid_xy = grid_xy.unsqueeze(0) + 0.5
1643
+ grid_xy[..., 0] /= width
1644
+ grid_xy[..., 1] /= height
1645
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**level)
1646
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
1647
+ # define the valid range for anchor coordinates
1648
+ eps = 1e-2
1649
+ anchors = torch.concat(anchors, 1)
1650
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
1651
+ anchors = torch.log(anchors / (1 - anchors))
1652
+ anchors = torch.where(valid_mask, anchors, torch.tensor(torch.finfo(dtype).max, dtype=dtype, device=device))
1653
+
1654
+ return anchors, valid_mask
1655
+
1656
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
1657
+ if spatial_shapes is None:
1658
+ spatial_shapes = (
1659
+ (int(self.config.anchor_image_size[0] / s), int(self.config.anchor_image_size[1] / s))
1660
+ for s in self.config.feat_strides
1661
+ )
1662
+ return self._cached_generate_anchors(spatial_shapes, grid_size, device, dtype)
1663
+
1664
+ @auto_docstring
1665
+ @can_return_tuple
1666
+ def forward(
1667
+ self,
1668
+ pixel_values: torch.FloatTensor,
1669
+ pixel_mask: torch.LongTensor | None = None,
1670
+ encoder_outputs: torch.FloatTensor | None = None,
1671
+ inputs_embeds: torch.FloatTensor | None = None,
1672
+ labels: list[dict] | None = None,
1673
+ **kwargs: Unpack[TransformersKwargs],
1674
+ ) -> tuple[torch.FloatTensor] | DFineModelOutput:
1675
+ r"""
1676
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1677
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1678
+ can choose to directly pass a flattened representation of an image.
1679
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
1680
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
1681
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
1682
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
1683
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
1684
+
1685
+ Examples:
1686
+
1687
+ ```python
1688
+ >>> from transformers import AutoImageProcessor, DFineModel
1689
+ >>> from PIL import Image
1690
+ >>> import httpx
1691
+ >>> from io import BytesIO
1692
+
1693
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1694
+ >>> with httpx.stream("GET", url) as response:
1695
+ ... image = Image.open(BytesIO(response.read()))
1696
+
1697
+ >>> image_processor = AutoImageProcessor.from_pretrained("PekingU/DFine_r50vd")
1698
+ >>> model = DFineModel.from_pretrained("PekingU/DFine_r50vd")
1699
+
1700
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1701
+
1702
+ >>> outputs = model(**inputs)
1703
+
1704
+ >>> last_hidden_states = outputs.last_hidden_state
1705
+ >>> list(last_hidden_states.shape)
1706
+ [1, 300, 256]
1707
+ ```"""
1708
+ if pixel_values is None and inputs_embeds is None:
1709
+ raise ValueError("You have to specify either pixel_values or inputs_embeds")
1710
+
1711
+ if inputs_embeds is None:
1712
+ batch_size, num_channels, height, width = pixel_values.shape
1713
+ device = pixel_values.device
1714
+ if pixel_mask is None:
1715
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
1716
+ features = self.backbone(pixel_values, pixel_mask)
1717
+ proj_feats = [self.encoder_input_proj[level](source) for level, (source, mask) in enumerate(features)]
1718
+ else:
1719
+ batch_size = inputs_embeds.shape[0]
1720
+ device = inputs_embeds.device
1721
+ proj_feats = inputs_embeds
1722
+
1723
+ if encoder_outputs is None:
1724
+ encoder_outputs = self.encoder(
1725
+ proj_feats,
1726
+ **kwargs,
1727
+ )
1728
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
1729
+ elif not isinstance(encoder_outputs, BaseModelOutput):
1730
+ encoder_outputs = BaseModelOutput(
1731
+ last_hidden_state=encoder_outputs[0],
1732
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1733
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1734
+ )
1735
+
1736
+ # Equivalent to def _get_encoder_input
1737
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/DFine_pytorch/src/zoo/DFine/DFine_decoder.py#L412
1738
+ sources = []
1739
+ for level, source in enumerate(encoder_outputs.last_hidden_state):
1740
+ sources.append(self.decoder_input_proj[level](source))
1741
+
1742
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
1743
+ if self.config.num_feature_levels > len(sources):
1744
+ _len_sources = len(sources)
1745
+ sources.append(self.decoder_input_proj[_len_sources](encoder_outputs.last_hidden_state)[-1])
1746
+ for i in range(_len_sources + 1, self.config.num_feature_levels):
1747
+ sources.append(self.decoder_input_proj[i](encoder_outputs.last_hidden_state[-1]))
1748
+
1749
+ # Prepare encoder inputs (by flattening)
1750
+ source_flatten = []
1751
+ spatial_shapes_list = []
1752
+ spatial_shapes = torch.empty((len(sources), 2), device=device, dtype=torch.long)
1753
+ for level, source in enumerate(sources):
1754
+ height, width = source.shape[-2:]
1755
+ spatial_shapes[level, 0] = height
1756
+ spatial_shapes[level, 1] = width
1757
+ spatial_shapes_list.append((height, width))
1758
+ source = source.flatten(2).transpose(1, 2)
1759
+ source_flatten.append(source)
1760
+ source_flatten = torch.cat(source_flatten, 1)
1761
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
1762
+
1763
+ # prepare denoising training
1764
+ if self.training and self.config.num_denoising > 0 and labels is not None:
1765
+ (
1766
+ denoising_class,
1767
+ denoising_bbox_unact,
1768
+ attention_mask,
1769
+ denoising_meta_values,
1770
+ ) = get_contrastive_denoising_training_group(
1771
+ targets=labels,
1772
+ num_classes=self.config.num_labels,
1773
+ num_queries=self.config.num_queries,
1774
+ class_embed=self.denoising_class_embed,
1775
+ num_denoising_queries=self.config.num_denoising,
1776
+ label_noise_ratio=self.config.label_noise_ratio,
1777
+ box_noise_scale=self.config.box_noise_scale,
1778
+ )
1779
+ else:
1780
+ denoising_class, denoising_bbox_unact, attention_mask, denoising_meta_values = None, None, None, None
1781
+
1782
+ batch_size = len(source_flatten)
1783
+ device = source_flatten.device
1784
+ dtype = source_flatten.dtype
1785
+
1786
+ # prepare input for decoder
1787
+ if self.training or self.config.anchor_image_size is None:
1788
+ # Pass spatial_shapes as tuple to make it hashable and make sure
1789
+ # lru_cache is working for generate_anchors()
1790
+ spatial_shapes_tuple = tuple(spatial_shapes_list)
1791
+ anchors, valid_mask = self.generate_anchors(spatial_shapes_tuple, device=device, dtype=dtype)
1792
+ else:
1793
+ anchors, valid_mask = self.anchors, self.valid_mask
1794
+ anchors, valid_mask = anchors.to(device, dtype), valid_mask.to(device, dtype)
1795
+
1796
+ # use the valid_mask to selectively retain values in the feature map where the mask is `True`
1797
+ memory = valid_mask.to(source_flatten.dtype) * source_flatten
1798
+
1799
+ output_memory = self.enc_output(memory)
1800
+
1801
+ enc_outputs_class = self.enc_score_head(output_memory)
1802
+ enc_outputs_coord_logits = self.enc_bbox_head(output_memory) + anchors
1803
+
1804
+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.config.num_queries, dim=1)
1805
+
1806
+ reference_points_unact = enc_outputs_coord_logits.gather(
1807
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_logits.shape[-1])
1808
+ )
1809
+
1810
+ enc_topk_bboxes = F.sigmoid(reference_points_unact)
1811
+ if denoising_bbox_unact is not None:
1812
+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)
1813
+
1814
+ enc_topk_logits = enc_outputs_class.gather(
1815
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])
1816
+ )
1817
+
1818
+ # extract region features
1819
+ if self.config.learn_initial_query:
1820
+ target = self.weight_embedding.tile([batch_size, 1, 1])
1821
+ else:
1822
+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
1823
+ target = target.detach()
1824
+
1825
+ if denoising_class is not None:
1826
+ target = torch.concat([denoising_class, target], 1)
1827
+
1828
+ init_reference_points = reference_points_unact.detach()
1829
+
1830
+ # decoder
1831
+ decoder_outputs = self.decoder(
1832
+ inputs_embeds=target,
1833
+ encoder_hidden_states=source_flatten,
1834
+ encoder_attention_mask=attention_mask,
1835
+ reference_points=init_reference_points,
1836
+ spatial_shapes=spatial_shapes,
1837
+ spatial_shapes_list=spatial_shapes_list,
1838
+ level_start_index=level_start_index,
1839
+ **kwargs,
1840
+ )
1841
+
1842
+ return DFineModelOutput(
1843
+ last_hidden_state=decoder_outputs.last_hidden_state,
1844
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
1845
+ intermediate_logits=decoder_outputs.intermediate_logits,
1846
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
1847
+ intermediate_predicted_corners=decoder_outputs.intermediate_predicted_corners,
1848
+ initial_reference_points=decoder_outputs.initial_reference_points,
1849
+ decoder_hidden_states=decoder_outputs.hidden_states,
1850
+ decoder_attentions=decoder_outputs.attentions,
1851
+ cross_attentions=decoder_outputs.cross_attentions,
1852
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1853
+ encoder_hidden_states=encoder_outputs.hidden_states,
1854
+ encoder_attentions=encoder_outputs.attentions,
1855
+ init_reference_points=init_reference_points,
1856
+ enc_topk_logits=enc_topk_logits,
1857
+ enc_topk_bboxes=enc_topk_bboxes,
1858
+ enc_outputs_class=enc_outputs_class,
1859
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
1860
+ denoising_meta_values=denoising_meta_values,
1861
+ )
1862
+
1863
+
1864
+ @auto_docstring(
1865
+ custom_intro="""
1866
+ Output type of [`DFineForObjectDetection`].
1867
+ """
1868
+ )
1869
+ @dataclass
1870
+ class DFineObjectDetectionOutput(ModelOutput):
1871
+ r"""
1872
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
1873
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
1874
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
1875
+ scale-invariant IoU loss.
1876
+ loss_dict (`Dict`, *optional*):
1877
+ A dictionary containing the individual losses. Useful for logging.
1878
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
1879
+ Classification logits (including no-object) for all queries.
1880
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1881
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
1882
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
1883
+ possible padding). You can use [`~DFineImageProcessor.post_process_object_detection`] to retrieve the
1884
+ unnormalized (absolute) bounding boxes.
1885
+ auxiliary_outputs (`list[Dict]`, *optional*):
1886
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
1887
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
1888
+ `pred_boxes`) for each decoder layer.
1889
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1890
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
1891
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
1892
+ Stacked intermediate hidden states (output of each layer of the decoder).
1893
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, config.num_labels)`):
1894
+ Stacked intermediate logits (logits of each layer of the decoder).
1895
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1896
+ Stacked intermediate reference points (reference points of each layer of the decoder).
1897
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1898
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
1899
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1900
+ Stacked initial reference points (initial reference points of each layer of the decoder).
1901
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1902
+ Initial reference points sent through the Transformer decoder.
1903
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1904
+ Logits of predicted bounding boxes coordinates in the encoder.
1905
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1906
+ Logits of predicted bounding boxes coordinates in the encoder.
1907
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1908
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1909
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
1910
+ foreground and background).
1911
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1912
+ Logits of predicted bounding boxes coordinates in the first stage.
1913
+ denoising_meta_values (`dict`):
1914
+ Extra dictionary for the denoising related values
1915
+ """
1916
+
1917
+ loss: torch.FloatTensor | None = None
1918
+ loss_dict: dict | None = None
1919
+ logits: torch.FloatTensor | None = None
1920
+ pred_boxes: torch.FloatTensor | None = None
1921
+ auxiliary_outputs: list[dict] | None = None
1922
+ last_hidden_state: torch.FloatTensor | None = None
1923
+ intermediate_hidden_states: torch.FloatTensor | None = None
1924
+ intermediate_logits: torch.FloatTensor | None = None
1925
+ intermediate_reference_points: torch.FloatTensor | None = None
1926
+ intermediate_predicted_corners: torch.FloatTensor | None = None
1927
+ initial_reference_points: torch.FloatTensor | None = None
1928
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
1929
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
1930
+ cross_attentions: tuple[torch.FloatTensor] | None = None
1931
+ encoder_last_hidden_state: torch.FloatTensor | None = None
1932
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
1933
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
1934
+ init_reference_points: tuple[torch.FloatTensor] | None = None
1935
+ enc_topk_logits: torch.FloatTensor | None = None
1936
+ enc_topk_bboxes: torch.FloatTensor | None = None
1937
+ enc_outputs_class: torch.FloatTensor | None = None
1938
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
1939
+ denoising_meta_values: dict | None = None
1940
+
1941
+
1942
+ @auto_docstring(
1943
+ custom_intro="""
1944
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting bounding boxes and logits to be further
1945
+ decoded into scores and classes.
1946
+ """
1947
+ )
1948
+ class DFineForObjectDetection(DFinePreTrainedModel):
1949
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
1950
+ # We can't initialize the model on meta device as some weights are modified during the initialization
1951
+ _no_split_modules = None
1952
+ _tied_weights_keys = {
1953
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
1954
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
1955
+ "class_embed": "model.decoder.class_embed",
1956
+ "bbox_embed": "model.decoder.bbox_embed",
1957
+ }
1958
+
1959
+ def __init__(self, config: DFineConfig):
1960
+ super().__init__(config)
1961
+
1962
+ # D-FINE encoder-decoder model
1963
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
1964
+ self.model = DFineModel(config)
1965
+ scaled_dim = round(config.layer_scale * config.hidden_size)
1966
+ num_pred = config.decoder_layers
1967
+ self.class_embed = nn.ModuleList([nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)])
1968
+ self.bbox_embed = nn.ModuleList(
1969
+ [
1970
+ DFineMLP(config.hidden_size, config.hidden_size, 4 * (config.max_num_bins + 1), 3)
1971
+ for _ in range(self.eval_idx + 1)
1972
+ ]
1973
+ + [
1974
+ DFineMLP(scaled_dim, scaled_dim, 4 * (config.max_num_bins + 1), 3)
1975
+ for _ in range(config.decoder_layers - self.eval_idx - 1)
1976
+ ]
1977
+ )
1978
+
1979
+ self.model.decoder.class_embed = self.class_embed
1980
+ self.model.decoder.bbox_embed = self.bbox_embed
1981
+ # Initialize weights and apply final processing
1982
+ self.post_init()
1983
+
1984
+ def _set_aux_loss(self, outputs_class, outputs_coord):
1985
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
1986
+
1987
+ @auto_docstring
1988
+ @can_return_tuple
1989
+ def forward(
1990
+ self,
1991
+ pixel_values: torch.FloatTensor,
1992
+ pixel_mask: torch.LongTensor | None = None,
1993
+ encoder_outputs: torch.FloatTensor | None = None,
1994
+ inputs_embeds: torch.FloatTensor | None = None,
1995
+ labels: list[dict] | None = None,
1996
+ **kwargs: Unpack[TransformersKwargs],
1997
+ ) -> tuple[torch.FloatTensor] | DFineObjectDetectionOutput:
1998
+ r"""
1999
+ Example:
2000
+
2001
+ ```python
2002
+ >>> import torch
2003
+ >>> from transformers.image_utils import load_image
2004
+ >>> from transformers import AutoImageProcessor, DFineForObjectDetection
2005
+
2006
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
2007
+ >>> image = load_image(url)
2008
+
2009
+ >>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
2010
+ >>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")
2011
+
2012
+ >>> # prepare image for the model
2013
+ >>> inputs = image_processor(images=image, return_tensors="pt")
2014
+
2015
+ >>> # forward pass
2016
+ >>> outputs = model(**inputs)
2017
+
2018
+ >>> logits = outputs.logits
2019
+ >>> list(logits.shape)
2020
+ [1, 300, 80]
2021
+
2022
+ >>> boxes = outputs.pred_boxes
2023
+ >>> list(boxes.shape)
2024
+ [1, 300, 4]
2025
+
2026
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
2027
+ >>> target_sizes = torch.tensor([image.size[::-1]])
2028
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
2029
+ >>> result = results[0] # first image in batch
2030
+
2031
+ >>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
2032
+ ... box = [round(i, 2) for i in box.tolist()]
2033
+ ... print(
2034
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
2035
+ ... f"{round(score.item(), 3)} at location {box}"
2036
+ ... )
2037
+ Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
2038
+ Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
2039
+ Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
2040
+ Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
2041
+ ```
2042
+ """
2043
+ outputs = self.model(
2044
+ pixel_values,
2045
+ pixel_mask=pixel_mask,
2046
+ encoder_outputs=encoder_outputs,
2047
+ inputs_embeds=inputs_embeds,
2048
+ labels=labels,
2049
+ **kwargs,
2050
+ )
2051
+
2052
+ denoising_meta_values = outputs.denoising_meta_values if self.training else None
2053
+
2054
+ outputs_class = outputs.intermediate_logits
2055
+ outputs_coord = outputs.intermediate_reference_points
2056
+ predicted_corners = outputs.intermediate_predicted_corners
2057
+ initial_reference_points = outputs.initial_reference_points
2058
+
2059
+ logits = outputs_class[:, -1]
2060
+ pred_boxes = outputs_coord[:, -1]
2061
+
2062
+ loss, loss_dict, auxiliary_outputs, enc_topk_logits, enc_topk_bboxes = None, None, None, None, None
2063
+ if labels is not None:
2064
+ enc_topk_logits = outputs.enc_topk_logits
2065
+ enc_topk_bboxes = outputs.enc_topk_bboxes
2066
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
2067
+ logits,
2068
+ labels,
2069
+ self.device,
2070
+ pred_boxes,
2071
+ self.config,
2072
+ outputs_class,
2073
+ outputs_coord,
2074
+ enc_topk_logits=enc_topk_logits,
2075
+ enc_topk_bboxes=enc_topk_bboxes,
2076
+ denoising_meta_values=denoising_meta_values,
2077
+ predicted_corners=predicted_corners,
2078
+ initial_reference_points=initial_reference_points,
2079
+ **kwargs,
2080
+ )
2081
+
2082
+ return DFineObjectDetectionOutput(
2083
+ loss=loss,
2084
+ loss_dict=loss_dict,
2085
+ logits=logits,
2086
+ pred_boxes=pred_boxes,
2087
+ auxiliary_outputs=auxiliary_outputs,
2088
+ last_hidden_state=outputs.last_hidden_state,
2089
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
2090
+ intermediate_logits=outputs.intermediate_logits,
2091
+ intermediate_reference_points=outputs.intermediate_reference_points,
2092
+ intermediate_predicted_corners=outputs.intermediate_predicted_corners,
2093
+ initial_reference_points=outputs.initial_reference_points,
2094
+ decoder_hidden_states=outputs.decoder_hidden_states,
2095
+ decoder_attentions=outputs.decoder_attentions,
2096
+ cross_attentions=outputs.cross_attentions,
2097
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
2098
+ encoder_hidden_states=outputs.encoder_hidden_states,
2099
+ encoder_attentions=outputs.encoder_attentions,
2100
+ init_reference_points=outputs.init_reference_points,
2101
+ enc_topk_logits=outputs.enc_topk_logits,
2102
+ enc_topk_bboxes=outputs.enc_topk_bboxes,
2103
+ enc_outputs_class=outputs.enc_outputs_class,
2104
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
2105
+ denoising_meta_values=outputs.denoising_meta_values,
2106
+ )
2107
+
2108
+
2109
+ __all__ = ["DFineModel", "DFinePreTrainedModel", "DFineForObjectDetection"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/d_fine/modular_d_fine.py ADDED
@@ -0,0 +1,1016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ... import initialization as init
22
+ from ...activations import ACT2CLS
23
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...image_transforms import corners_to_center_format
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...processing_utils import Unpack
28
+ from ...utils import TransformersKwargs, auto_docstring, logging, torch_compilable_check
29
+ from ..auto import AutoConfig
30
+ from ..rt_detr.modeling_rt_detr import (
31
+ RTDetrAIFILayer,
32
+ RTDetrConvNormLayer,
33
+ RTDetrDecoder,
34
+ RTDetrDecoderLayer,
35
+ RTDetrDecoderOutput,
36
+ RTDetrEncoderLayer,
37
+ RTDetrForObjectDetection,
38
+ RTDetrFrozenBatchNorm2d,
39
+ RTDetrHybridEncoder,
40
+ RTDetrMLPPredictionHead,
41
+ RTDetrModel,
42
+ RTDetrPreTrainedModel,
43
+ RTDetrRepVggBlock,
44
+ inverse_sigmoid,
45
+ )
46
+ from ..rt_detr_v2.modeling_rt_detr_v2 import multi_scale_deformable_attention_v2
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ # TODO: Attribute map assignment logic should be fixed in modular
53
+ # as well as super() call parsing because otherwise we cannot re-write args after initialization
54
+ @auto_docstring(checkpoint="ustc-community/dfine-xlarge-coco")
55
+ @strict
56
+ class DFineConfig(PreTrainedConfig):
57
+ r"""
58
+ initializer_bias_prior_prob (`float`, *optional*):
59
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
60
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
61
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
62
+ Whether to freeze the batch normalization layers in the backbone.
63
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
64
+ Multi level features input for encoder.
65
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
66
+ Strides used in each feature map.
67
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
68
+ Indexes of the projected layers to be used in the encoder.
69
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
70
+ The temperature parameter used to create the positional encodings.
71
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
72
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
73
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
74
+ eval_size (`tuple[int, int]`, *optional*):
75
+ Height and width used to computes the effective height and width of the position embeddings after taking
76
+ into account the stride.
77
+ normalize_before (`bool`, *optional*, defaults to `False`):
78
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
79
+ feed-forward modules.
80
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
81
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
82
+ num_queries (`int`, *optional*, defaults to 300):
83
+ Number of object queries.
84
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
85
+ Multi level features dimension for decoder
86
+ num_feature_levels (`int`, *optional*, defaults to 3):
87
+ The number of input feature levels.
88
+ decoder_n_points (`int`, *optional*, defaults to 4):
89
+ The number of sampled keys in each feature level for each attention head in the decoder.
90
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
91
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
92
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
93
+ num_denoising (`int`, *optional*, defaults to 100):
94
+ The total number of denoising tasks or queries to be used for contrastive denoising.
95
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
96
+ The fraction of denoising labels to which random noise should be added.
97
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
98
+ Scale or magnitude of noise to be added to the bounding boxes.
99
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
100
+ Indicates whether the initial query embeddings for the decoder should be learned during training
101
+ anchor_image_size (`tuple[int, int]`, *optional*):
102
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
103
+ with_box_refine (`bool`, *optional*, defaults to `True`):
104
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
105
+ based on the predictions from the previous layer.
106
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
107
+ Parameter alpha used by the Hungarian Matcher.
108
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
109
+ Parameter gamma used by the Hungarian Matcher.
110
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
111
+ The relative weight of the class loss used by the Hungarian Matcher.
112
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
113
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
114
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
115
+ The relative weight of the giou loss of used by the Hungarian Matcher.
116
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
117
+ Parameter informing if focal focal should be used.
118
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
119
+ Parameter alpha used to compute the focal loss.
120
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
121
+ Parameter gamma used to compute the focal loss.
122
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
123
+ Relative weight of the varifocal loss in the object detection loss.
124
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
125
+ Relative weight of the L1 bounding box loss in the object detection loss.
126
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
127
+ Relative weight of the generalized IoU loss in the object detection loss.
128
+ weight_loss_fgl (`float`, *optional*, defaults to 0.15):
129
+ Relative weight of the fine-grained localization loss in the object detection loss.
130
+ weight_loss_ddf (`float`, *optional*, defaults to 1.5):
131
+ Relative weight of the decoupled distillation focal loss in the object detection loss.
132
+ eval_idx (`int`, *optional*, defaults to -1):
133
+ Index of the decoder layer to use for evaluation. If negative, counts from the end
134
+ (e.g., -1 means use the last layer). This allows for early prediction in the decoder
135
+ stack while still training later layers.
136
+ layer_scale (`float`, *optional*, defaults to `1.0`):
137
+ Scaling factor for the hidden dimension in later decoder layers. Used to adjust the
138
+ model capacity after the evaluation layer.
139
+ max_num_bins (`int`, *optional*, defaults to 32):
140
+ Maximum number of bins for the distribution-guided bounding box refinement.
141
+ Higher values allow for more fine-grained localization but increase computation.
142
+ reg_scale (`float`, *optional*, defaults to 4.0):
143
+ Scale factor for the regression distribution. Controls the range and granularity
144
+ of the bounding box refinement process.
145
+ depth_mult (`float`, *optional*, defaults to 1.0):
146
+ Multiplier for the number of blocks in RepNCSPELAN4 layers. Used to scale the model's
147
+ depth while maintaining its architecture.
148
+ top_prob_values (`int`, *optional*, defaults to 4):
149
+ Number of top probability values to consider from each corner's distribution.
150
+ lqe_hidden_dim (`int`, *optional*, defaults to 64):
151
+ Hidden dimension size for the Location Quality Estimator (LQE) network.
152
+ lqe_layers (`int`, *optional*, defaults to 2):
153
+ Number of layers in the Location Quality Estimator MLP.
154
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
155
+ Offset scale used in deformable attention.
156
+ decoder_method (`str`, *optional*, defaults to `"default"`):
157
+ The method to use for the decoder: `"default"` or `"discrete"`.
158
+ up (`float`, *optional*, defaults to 0.5):
159
+ Controls the upper bounds of the Weighting Function.
160
+ """
161
+
162
+ model_type = "d_fine"
163
+ sub_configs = {"backbone_config": AutoConfig}
164
+ layer_types = ["basic", "bottleneck"]
165
+ attribute_map = {
166
+ "hidden_size": "d_model",
167
+ "num_attention_heads": "encoder_attention_heads",
168
+ }
169
+
170
+ initializer_range: float = 0.01
171
+ initializer_bias_prior_prob: float | None = None
172
+ layer_norm_eps: float = 1e-5
173
+ batch_norm_eps: float = 1e-5
174
+ backbone_config: dict | PreTrainedConfig | None = None
175
+ freeze_backbone_batch_norms: bool = True
176
+
177
+ # encoder HybridEncoder
178
+ encoder_hidden_dim: int = 256
179
+ encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
180
+ feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
181
+ encoder_layers: int = 1
182
+ encoder_ffn_dim: int = 1024
183
+ encoder_attention_heads: int = 8
184
+ dropout: float | int = 0.0
185
+ activation_dropout: float | int = 0.0
186
+ encode_proj_layers: list[int] | tuple[int, ...] = (2,)
187
+ positional_encoding_temperature: int = 10000
188
+ encoder_activation_function: str = "gelu"
189
+ activation_function: str = "silu"
190
+ eval_size: int | None = None
191
+ normalize_before: bool = False
192
+ hidden_expansion: float = 1.0
193
+
194
+ # decoder DFineTransformer
195
+ d_model: int = 256
196
+ num_queries: int = 300
197
+ decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
198
+ decoder_ffn_dim: int = 1024
199
+ num_feature_levels: int = 3
200
+ decoder_n_points: int | list[int] = 4
201
+ decoder_layers: int = 6
202
+ decoder_attention_heads: int = 8
203
+ decoder_activation_function: str = "relu"
204
+ attention_dropout: float | int = 0.0
205
+ num_denoising: int = 100
206
+ label_noise_ratio: float = 0.5
207
+ box_noise_scale: float = 1.0
208
+ learn_initial_query: bool = False
209
+ anchor_image_size: int | list[int] | None = None
210
+ with_box_refine: bool = True
211
+
212
+ # Loss
213
+ matcher_alpha: float = 0.25
214
+ matcher_gamma: float = 2.0
215
+ matcher_class_cost: float = 2.0
216
+ matcher_bbox_cost: float = 5.0
217
+ matcher_giou_cost: float = 2.0
218
+ use_focal_loss: bool = True
219
+ auxiliary_loss: bool = True
220
+ focal_loss_alpha: float = 0.75
221
+ focal_loss_gamma: float = 2.0
222
+ weight_loss_vfl: float = 1.0
223
+ weight_loss_bbox: float = 5.0
224
+ weight_loss_giou: float = 2.0
225
+ weight_loss_fgl: float = 0.15
226
+ weight_loss_ddf: float = 1.5
227
+ eos_coefficient: float = 1e-4
228
+ eval_idx: int = -1
229
+ layer_scale: int | float = 1.0
230
+ max_num_bins: int = 32
231
+ reg_scale: float = 4.0
232
+ depth_mult: float = 1.0
233
+ top_prob_values: int = 4
234
+ lqe_hidden_dim: int = 64
235
+ lqe_layers: int = 2
236
+ decoder_offset_scale: float = 0.5
237
+ decoder_method: str = "default"
238
+ up: float = 0.5
239
+ tie_word_embeddings: bool = True
240
+ is_encoder_decoder: bool = True
241
+
242
+ def __post_init__(self, **kwargs):
243
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
244
+ backbone_config=self.backbone_config,
245
+ default_config_type="hgnet_v2",
246
+ default_config_kwargs={"out_indices": [2, 3, 4]},
247
+ **kwargs,
248
+ )
249
+ self.head_dim = self.d_model // self.decoder_attention_heads
250
+ super().__post_init__(**kwargs)
251
+
252
+ def validate_architecture(self):
253
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
254
+ if isinstance(self.decoder_n_points, list):
255
+ if len(self.decoder_n_points) != self.num_feature_levels:
256
+ raise ValueError(
257
+ f"Length of decoder_n_points list ({len(self.decoder_n_points)}) must match num_feature_levels ({self.num_feature_levels})."
258
+ )
259
+
260
+ if self.head_dim * self.decoder_attention_heads != self.d_model:
261
+ raise ValueError(
262
+ f"Embedded dimension {self.d_model} must be divisible by decoder_attention_heads {self.decoder_attention_heads}"
263
+ )
264
+
265
+
266
+ class DFineDecoderOutput(RTDetrDecoderOutput):
267
+ pass
268
+
269
+
270
+ def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:
271
+ """
272
+ Generates the non-uniform Weighting Function W(n) for bounding box regression.
273
+
274
+ Args:
275
+ max_num_bins (int): Max number of the discrete bins.
276
+ up (Tensor): Controls upper bounds of the sequence,
277
+ where maximum offset is ±up * H / W.
278
+ reg_scale (float): Controls the curvature of the Weighting Function.
279
+ Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
280
+ and steeper weights at both ends.
281
+ Returns:
282
+ Tensor: Sequence of Weighting Function.
283
+ """
284
+ upper_bound1 = abs(up[0]) * abs(reg_scale)
285
+ upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
286
+ step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))
287
+ left_values = [-((step) ** i) + 1 for i in range(max_num_bins // 2 - 1, 0, -1)]
288
+ right_values = [(step) ** i - 1 for i in range(1, max_num_bins // 2)]
289
+ values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]
290
+ values = torch.cat(values, 0)
291
+ return values
292
+
293
+
294
+ def distance2bbox(points, distance: torch.Tensor, reg_scale: float) -> torch.Tensor:
295
+ """
296
+ Decodes edge-distances into bounding box coordinates.
297
+
298
+ Args:
299
+ points (`torch.Tensor`):
300
+ (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
301
+ distance (`torch.Tensor`):
302
+ (batch_size, num_boxes, 4) or (num_boxes, 4), representing distances from the point to the left, top, right, and bottom boundaries.
303
+ reg_scale (`float`):
304
+ Controls the curvature of the Weighting Function.
305
+ Returns:
306
+ `torch.Tensor`: Bounding boxes in (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
307
+ """
308
+ reg_scale = abs(reg_scale)
309
+ top_left_x = points[..., 0] - (0.5 * reg_scale + distance[..., 0]) * (points[..., 2] / reg_scale)
310
+ top_left_y = points[..., 1] - (0.5 * reg_scale + distance[..., 1]) * (points[..., 3] / reg_scale)
311
+ bottom_right_x = points[..., 0] + (0.5 * reg_scale + distance[..., 2]) * (points[..., 2] / reg_scale)
312
+ bottom_right_y = points[..., 1] + (0.5 * reg_scale + distance[..., 3]) * (points[..., 3] / reg_scale)
313
+
314
+ bboxes = torch.stack([top_left_x, top_left_y, bottom_right_x, bottom_right_y], -1)
315
+
316
+ return corners_to_center_format(bboxes)
317
+
318
+
319
+ class DFineMLP(nn.Module):
320
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, act: str = "relu"):
321
+ super().__init__()
322
+ self.num_layers = num_layers
323
+ hidden_dims = [hidden_dim] * (num_layers - 1)
324
+ input_dims = [input_dim] + hidden_dims
325
+ output_dims = hidden_dims + [output_dim]
326
+ self.layers = nn.ModuleList(nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(input_dims, output_dims))
327
+ self.act = ACT2CLS[act]()
328
+
329
+ def forward(self, stat_features: torch.Tensor) -> torch.Tensor:
330
+ for i, layer in enumerate(self.layers):
331
+ stat_features = self.act(layer(stat_features)) if i < self.num_layers - 1 else layer(stat_features)
332
+ return stat_features
333
+
334
+
335
+ class DFineGate(nn.Module):
336
+ def __init__(self, d_model: int):
337
+ super().__init__()
338
+ self.gate = nn.Linear(2 * d_model, 2 * d_model)
339
+ self.norm = nn.LayerNorm(d_model)
340
+
341
+ def forward(self, second_residual: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
342
+ gate_input = torch.cat([second_residual, hidden_states], dim=-1)
343
+ gates = torch.sigmoid(self.gate(gate_input))
344
+ gate1, gate2 = gates.chunk(2, dim=-1)
345
+ hidden_states = self.norm(gate1 * second_residual + gate2 * hidden_states)
346
+ return hidden_states
347
+
348
+
349
+ class DFineFrozenBatchNorm2d(RTDetrFrozenBatchNorm2d):
350
+ pass
351
+
352
+
353
+ class DFineMultiscaleDeformableAttention(nn.Module):
354
+ def __init__(self, config: DFineConfig):
355
+ """
356
+ D-Fine version of multiscale deformable attention
357
+ """
358
+ super().__init__()
359
+ self.d_model = config.d_model
360
+ self.n_heads = config.decoder_attention_heads
361
+ self.n_levels = config.num_feature_levels
362
+ self.offset_scale = config.decoder_offset_scale
363
+ self.decoder_method = config.decoder_method
364
+ self.n_points = config.decoder_n_points
365
+
366
+ if isinstance(self.n_points, list):
367
+ num_points_list = self.n_points
368
+ else:
369
+ num_points_list = [self.n_points for _ in range(self.n_levels)]
370
+
371
+ self.num_points_list = num_points_list
372
+ num_points_scale = [1 / n for n in self.num_points_list for _ in range(n)]
373
+ self.register_buffer("num_points_scale", torch.tensor(num_points_scale, dtype=torch.float32))
374
+
375
+ self.total_points = self.n_heads * sum(self.num_points_list)
376
+
377
+ self.sampling_offsets = nn.Linear(self.d_model, self.total_points * 2)
378
+ self.attention_weights = nn.Linear(self.d_model, self.total_points)
379
+
380
+ self.ms_deformable_attn_core = multi_scale_deformable_attention_v2
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ attention_mask: torch.Tensor | None = None,
386
+ reference_points=None,
387
+ encoder_hidden_states=None,
388
+ spatial_shapes=None,
389
+ spatial_shapes_list=None,
390
+ **kwargs: Unpack[TransformersKwargs],
391
+ ) -> tuple[torch.Tensor, torch.Tensor]:
392
+ batch_size, num_queries, _ = hidden_states.shape
393
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
394
+
395
+ torch_compilable_check(
396
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
397
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
398
+ )
399
+
400
+ # Reshape for multi-head attention
401
+ value = encoder_hidden_states.reshape(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
402
+ if attention_mask is not None:
403
+ value = value.masked_fill(~attention_mask[..., None], float(0))
404
+
405
+ sampling_offsets: torch.Tensor = self.sampling_offsets(hidden_states)
406
+ sampling_offsets = sampling_offsets.reshape(
407
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list), 2
408
+ )
409
+
410
+ attention_weights = self.attention_weights(hidden_states).reshape(
411
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list)
412
+ )
413
+ attention_weights = F.softmax(attention_weights, dim=-1)
414
+
415
+ if reference_points.shape[-1] == 2:
416
+ offset_normalizer = torch.tensor(spatial_shapes)
417
+ offset_normalizer = offset_normalizer.flip([1]).reshape(1, 1, 1, self.n_levels, 1, 2)
418
+ sampling_locations = (
419
+ reference_points.reshape(batch_size, sequence_length, 1, self.n_levels, 1, 2)
420
+ + sampling_offsets / offset_normalizer
421
+ )
422
+ elif reference_points.shape[-1] == 4:
423
+ # reference_points [8, 480, None, 1, 4]
424
+ # sampling_offsets [8, 480, 8, 12, 2]
425
+ num_points_scale = self.num_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
426
+ offset = sampling_offsets * num_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
427
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
428
+ else:
429
+ raise ValueError(
430
+ f"Last dim of reference_points must be 2 or 4, but get {reference_points.shape[-1]} instead."
431
+ )
432
+
433
+ output = self.ms_deformable_attn_core(
434
+ value,
435
+ spatial_shapes_list,
436
+ sampling_locations,
437
+ attention_weights,
438
+ self.num_points_list,
439
+ self.decoder_method,
440
+ )
441
+
442
+ return output, attention_weights
443
+
444
+
445
+ class DFineConvNormLayer(RTDetrConvNormLayer):
446
+ def __init__(
447
+ self,
448
+ config: DFineConfig,
449
+ in_channels: int,
450
+ out_channels: int,
451
+ kernel_size: int,
452
+ stride: int,
453
+ groups: int = 1,
454
+ padding: int | None = None,
455
+ activation: str | None = None,
456
+ ):
457
+ super().__init__(config, in_channels, out_channels, kernel_size, stride, padding=None, activation=activation)
458
+ self.conv = nn.Conv2d(
459
+ in_channels,
460
+ out_channels,
461
+ kernel_size,
462
+ stride,
463
+ groups=groups,
464
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
465
+ bias=False,
466
+ )
467
+
468
+
469
+ class DFineRepVggBlock(RTDetrRepVggBlock):
470
+ def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
471
+ super().__init__(config)
472
+ hidden_channels = in_channels
473
+ self.conv1 = DFineConvNormLayer(config, hidden_channels, out_channels, 3, 1, padding=1)
474
+ self.conv2 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, padding=0)
475
+
476
+
477
+ class DFineCSPRepLayer(nn.Module):
478
+ """
479
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
480
+ """
481
+
482
+ def __init__(
483
+ self, config: DFineConfig, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0
484
+ ):
485
+ super().__init__()
486
+ activation = config.activation_function
487
+
488
+ hidden_channels = int(out_channels * expansion)
489
+ self.conv1 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
490
+ self.conv2 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
491
+ self.bottlenecks = nn.ModuleList(
492
+ [DFineRepVggBlock(config, hidden_channels, hidden_channels) for _ in range(num_blocks)]
493
+ )
494
+ if hidden_channels != out_channels:
495
+ self.conv3 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
496
+ else:
497
+ self.conv3 = nn.Identity()
498
+
499
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
500
+ hidden_state_1 = self.conv1(hidden_state)
501
+ for bottleneck in self.bottlenecks:
502
+ hidden_state_1 = bottleneck(hidden_state_1)
503
+ hidden_state_2 = self.conv2(hidden_state)
504
+ hidden_state_3 = self.conv3(hidden_state_1 + hidden_state_2)
505
+ return hidden_state_3
506
+
507
+
508
+ class DFineRepNCSPELAN4(nn.Module):
509
+ def __init__(self, config: DFineConfig, act: str = "silu", numb_blocks: int = 3):
510
+ super().__init__()
511
+ conv1_dim = config.encoder_hidden_dim * 2
512
+ conv2_dim = config.encoder_hidden_dim
513
+ conv3_dim = config.encoder_hidden_dim * 2
514
+ conv4_dim = round(config.hidden_expansion * config.encoder_hidden_dim // 2)
515
+ self.conv_dim = conv3_dim // 2
516
+ self.conv1 = DFineConvNormLayer(config, conv1_dim, conv3_dim, 1, 1, activation=act)
517
+ self.csp_rep1 = DFineCSPRepLayer(config, conv3_dim // 2, conv4_dim, num_blocks=numb_blocks)
518
+ self.conv2 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
519
+ self.csp_rep2 = DFineCSPRepLayer(config, conv4_dim, conv4_dim, num_blocks=numb_blocks)
520
+ self.conv3 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
521
+ self.conv4 = DFineConvNormLayer(config, conv3_dim + (2 * conv4_dim), conv2_dim, 1, 1, activation=act)
522
+
523
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
524
+ # Split initial features into two branches after first convolution
525
+ split_features = list(self.conv1(input_features).split((self.conv_dim, self.conv_dim), 1))
526
+
527
+ # Process branches sequentially
528
+ branch1 = self.csp_rep1(split_features[-1])
529
+ branch1 = self.conv2(branch1)
530
+ branch2 = self.csp_rep2(branch1)
531
+ branch2 = self.conv3(branch2)
532
+
533
+ split_features.extend([branch1, branch2])
534
+ merged_features = torch.cat(split_features, 1)
535
+ merged_features = self.conv4(merged_features)
536
+ return merged_features
537
+
538
+
539
+ class DFineSCDown(nn.Module):
540
+ def __init__(self, config: DFineConfig, kernel_size: int, stride: int):
541
+ super().__init__()
542
+ self.conv1 = DFineConvNormLayer(config, config.encoder_hidden_dim, config.encoder_hidden_dim, 1, 1)
543
+ self.conv2 = DFineConvNormLayer(
544
+ config,
545
+ config.encoder_hidden_dim,
546
+ config.encoder_hidden_dim,
547
+ kernel_size,
548
+ stride,
549
+ config.encoder_hidden_dim,
550
+ )
551
+
552
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
553
+ input_features = self.conv1(input_features)
554
+ input_features = self.conv2(input_features)
555
+ return input_features
556
+
557
+
558
+ class DFineEncoderLayer(RTDetrEncoderLayer):
559
+ def __init__(self, config: DFineConfig):
560
+ super().__init__(config)
561
+ self.mlp = DFineMLP(
562
+ self.hidden_size, config.encoder_ffn_dim, self.hidden_size, 2, config.encoder_activation_function
563
+ )
564
+
565
+
566
+ class DFineAIFILayer(RTDetrAIFILayer):
567
+ pass
568
+
569
+
570
+ class DFineIntegral(nn.Module):
571
+ """
572
+ A static layer that calculates integral results from a distribution.
573
+
574
+ This layer computes the target location using the formula: `sum{Pr(n) * W(n)}`,
575
+ where Pr(n) is the softmax probability vector representing the discrete
576
+ distribution, and W(n) is the non-uniform Weighting Function.
577
+
578
+ Args:
579
+ max_num_bins (int): Max number of the discrete bins. Default is 32.
580
+ It can be adjusted based on the dataset or task requirements.
581
+ """
582
+
583
+ def __init__(self, config: DFineConfig):
584
+ super().__init__()
585
+ self.max_num_bins = config.max_num_bins
586
+
587
+ def forward(self, pred_corners: torch.Tensor, project: torch.Tensor) -> torch.Tensor:
588
+ batch_size, num_queries, _ = pred_corners.shape
589
+ pred_corners = F.softmax(pred_corners.reshape(-1, self.max_num_bins + 1), dim=1)
590
+ pred_corners = F.linear(pred_corners, project.to(pred_corners.device)).reshape(-1, 4)
591
+ pred_corners = pred_corners.reshape(batch_size, num_queries, -1)
592
+ return pred_corners
593
+
594
+
595
+ class DFineLQE(nn.Module):
596
+ def __init__(self, config: DFineConfig):
597
+ super().__init__()
598
+ self.top_prob_values = config.top_prob_values
599
+ self.max_num_bins = config.max_num_bins
600
+ self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
601
+
602
+ def forward(self, scores: torch.Tensor, pred_corners: torch.Tensor) -> torch.Tensor:
603
+ batch_size, length, _ = pred_corners.size()
604
+ prob = F.softmax(pred_corners.reshape(batch_size, length, 4, self.max_num_bins + 1), dim=-1)
605
+ prob_topk, _ = prob.topk(self.top_prob_values, dim=-1)
606
+ stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
607
+ quality_score = self.reg_conf(stat.reshape(batch_size, length, -1))
608
+ scores = scores + quality_score
609
+ return scores
610
+
611
+
612
+ class DFineDecoderLayer(RTDetrDecoderLayer):
613
+ def __init__(self, config: DFineConfig):
614
+ super().__init__(config)
615
+
616
+ # override the encoder attention module with d-fine version
617
+ self.encoder_attn = DFineMultiscaleDeformableAttention(config=config)
618
+ # gate
619
+ self.gateway = DFineGate(config.d_model)
620
+ self.mlp = DFineMLP(
621
+ self.hidden_size, config.decoder_ffn_dim, self.hidden_size, 2, config.decoder_activation_function
622
+ )
623
+
624
+ del self.encoder_attn_layer_norm
625
+
626
+ def forward(
627
+ self,
628
+ hidden_states: torch.Tensor,
629
+ position_embeddings: torch.Tensor | None = None,
630
+ reference_points=None,
631
+ spatial_shapes=None,
632
+ spatial_shapes_list=None,
633
+ encoder_hidden_states: torch.Tensor | None = None,
634
+ encoder_attention_mask: torch.Tensor | None = None,
635
+ **kwargs: Unpack[TransformersKwargs],
636
+ ) -> torch.Tensor:
637
+ residual = hidden_states
638
+
639
+ # Self Attention
640
+ hidden_states, _ = self.self_attn(
641
+ hidden_states=hidden_states,
642
+ attention_mask=encoder_attention_mask,
643
+ position_embeddings=position_embeddings,
644
+ **kwargs,
645
+ )
646
+
647
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
648
+ hidden_states = residual + hidden_states
649
+ hidden_states = self.self_attn_layer_norm(hidden_states)
650
+
651
+ residual = hidden_states
652
+
653
+ # Cross-Attention
654
+ hidden_states = hidden_states if position_embeddings is None else hidden_states + position_embeddings
655
+ hidden_states, _ = self.encoder_attn(
656
+ hidden_states=hidden_states,
657
+ encoder_hidden_states=encoder_hidden_states,
658
+ reference_points=reference_points,
659
+ spatial_shapes=spatial_shapes,
660
+ spatial_shapes_list=spatial_shapes_list,
661
+ )
662
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
663
+ hidden_states = self.gateway(residual, hidden_states)
664
+
665
+ # Fully Connected
666
+ residual = hidden_states
667
+ hidden_states = self.mlp(hidden_states)
668
+ hidden_states = residual + hidden_states
669
+ hidden_states = self.final_layer_norm(hidden_states.clamp(min=-65504, max=65504))
670
+
671
+ return hidden_states
672
+
673
+
674
+ class DFineMLPPredictionHead(RTDetrMLPPredictionHead):
675
+ pass
676
+
677
+
678
+ class DFinePreTrainedModel(RTDetrPreTrainedModel):
679
+ @torch.no_grad()
680
+ def _init_weights(self, module):
681
+ """Initialize the weights"""
682
+ PreTrainedModel._init_weights(self, module)
683
+ # initialize linear layer bias value according to a given probability value.
684
+ if isinstance(module, (DFineForObjectDetection, DFineDecoder)):
685
+ if module.class_embed is not None:
686
+ for layer in module.class_embed:
687
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
688
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
689
+ init.xavier_uniform_(layer.weight)
690
+ init.constant_(layer.bias, bias)
691
+
692
+ if module.bbox_embed is not None:
693
+ for layer in module.bbox_embed:
694
+ init.constant_(layer.layers[-1].weight, 0)
695
+ init.constant_(layer.layers[-1].bias, 0)
696
+
697
+ if hasattr(module, "reg_scale"):
698
+ init.constant_(module.reg_scale, self.config.reg_scale)
699
+
700
+ if hasattr(module, "up"):
701
+ init.constant_(module.up, self.config.up)
702
+
703
+ if isinstance(module, DFineMultiscaleDeformableAttention):
704
+ init.constant_(module.sampling_offsets.weight, 0.0)
705
+ default_dtype = torch.get_default_dtype()
706
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
707
+ 2.0 * math.pi / module.n_heads
708
+ )
709
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
710
+ grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
711
+ grid_init = grid_init.reshape(module.n_heads, 1, 2).tile([1, sum(module.num_points_list), 1])
712
+ scaling = torch.concat([torch.arange(1, n + 1) for n in module.num_points_list]).reshape(1, -1, 1)
713
+ grid_init *= scaling
714
+ init.copy_(module.sampling_offsets.bias, grid_init.flatten())
715
+
716
+ init.constant_(module.attention_weights.weight, 0.0)
717
+ init.constant_(module.attention_weights.bias, 0.0)
718
+
719
+ num_points_scale = [1 / n for n in module.num_points_list for _ in range(n)]
720
+ init.copy_(module.num_points_scale, torch.tensor(num_points_scale, dtype=torch.float32))
721
+
722
+ if isinstance(module, DFineModel):
723
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
724
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
725
+ init.xavier_uniform_(module.enc_score_head.weight)
726
+ init.constant_(module.enc_score_head.bias, bias)
727
+
728
+ if isinstance(module, DFineGate):
729
+ bias = float(-math.log((1 - 0.5) / 0.5))
730
+ init.constant_(module.gate.bias, bias)
731
+ init.constant_(module.gate.weight, 0)
732
+
733
+ if isinstance(module, DFineLQE):
734
+ init.constant_(module.reg_conf.layers[-1].bias, 0)
735
+ init.constant_(module.reg_conf.layers[-1].weight, 0)
736
+
737
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
738
+ init.xavier_uniform_(module.weight_embedding.weight)
739
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
740
+ init.xavier_uniform_(module.denoising_class_embed.weight)
741
+
742
+
743
+ class DFineHybridEncoder(RTDetrHybridEncoder):
744
+ def __init__(self, config: DFineConfig):
745
+ DFinePreTrainedModel.__init__(config)
746
+ self.config = config
747
+ self.in_channels = config.encoder_in_channels
748
+ self.num_fpn_stages = len(self.in_channels) - 1
749
+ self.feat_strides = config.feat_strides
750
+ self.encoder_hidden_dim = config.encoder_hidden_dim
751
+ self.encode_proj_layers = config.encode_proj_layers
752
+ self.positional_encoding_temperature = config.positional_encoding_temperature
753
+ self.eval_size = config.eval_size
754
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
755
+ self.out_strides = self.feat_strides
756
+
757
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
758
+ self.aifi = nn.ModuleList([DFineAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
759
+
760
+ # top-down fpn
761
+ self.lateral_convs = nn.ModuleList()
762
+ self.fpn_blocks = nn.ModuleList()
763
+ for _ in range(len(self.in_channels) - 1, 0, -1):
764
+ lateral_layer = DFineConvNormLayer(config, self.encoder_hidden_dim, self.encoder_hidden_dim, 1, 1)
765
+ self.lateral_convs.append(lateral_layer)
766
+ num_blocks = round(3 * config.depth_mult)
767
+ fpn_layer = DFineRepNCSPELAN4(config, numb_blocks=num_blocks)
768
+ self.fpn_blocks.append(fpn_layer)
769
+
770
+ # bottom-up pan
771
+ self.downsample_convs = nn.ModuleList()
772
+ self.pan_blocks = nn.ModuleList()
773
+ for _ in range(len(self.in_channels) - 1):
774
+ self.downsample_convs.append(DFineSCDown(config, 3, 2))
775
+ num_blocks = round(3 * config.depth_mult)
776
+ self.pan_blocks.append(DFineRepNCSPELAN4(config, numb_blocks=num_blocks))
777
+
778
+ self.post_init()
779
+
780
+
781
+ class DFineDecoder(RTDetrDecoder):
782
+ """
783
+ D-FINE Decoder implementing Fine-grained Distribution Refinement (FDR).
784
+
785
+ This decoder refines object detection predictions through iterative updates across multiple layers,
786
+ utilizing attention mechanisms, location quality estimators, and distribution refinement techniques
787
+ to improve bounding box accuracy and robustness.
788
+ """
789
+
790
+ def __init__(self, config: DFineConfig):
791
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
792
+ super().__init__(config=config)
793
+ self.reg_scale = nn.Parameter(torch.tensor([config.reg_scale]), requires_grad=False)
794
+ self.max_num_bins = config.max_num_bins
795
+ self.d_model = config.d_model
796
+ self.layer_scale = config.layer_scale
797
+ self.pre_bbox_head = DFineMLP(config.hidden_size, config.hidden_size, 4, 3)
798
+ self.integral = DFineIntegral(config)
799
+ self.num_head = config.decoder_attention_heads
800
+ self.up = nn.Parameter(torch.tensor([config.up]), requires_grad=False)
801
+ self.lqe_layers = nn.ModuleList([DFineLQE(config) for _ in range(config.decoder_layers)])
802
+ self.layers = nn.ModuleList(
803
+ [DFineDecoderLayer(config) for _ in range(config.decoder_layers)]
804
+ + [DFineDecoderLayer(config) for _ in range(config.decoder_layers - self.eval_idx - 1)]
805
+ )
806
+
807
+ def forward(
808
+ self,
809
+ encoder_hidden_states: torch.Tensor,
810
+ reference_points: torch.Tensor,
811
+ inputs_embeds: torch.Tensor,
812
+ spatial_shapes,
813
+ level_start_index=None,
814
+ spatial_shapes_list=None,
815
+ encoder_attention_mask=None,
816
+ memory_mask=None,
817
+ **kwargs: Unpack[TransformersKwargs],
818
+ ) -> DFineDecoderOutput:
819
+ if inputs_embeds is not None:
820
+ hidden_states = inputs_embeds
821
+
822
+ # decoder layers
823
+ intermediate = ()
824
+ intermediate_reference_points = ()
825
+ intermediate_logits = ()
826
+ intermediate_predicted_corners = ()
827
+ initial_reference_points = ()
828
+
829
+ output_detach = pred_corners_undetach = 0
830
+
831
+ project = weighting_function(self.max_num_bins, self.up, self.reg_scale)
832
+ ref_points_detach = F.sigmoid(reference_points)
833
+
834
+ for i, decoder_layer in enumerate(self.layers):
835
+ ref_points_input = ref_points_detach.unsqueeze(2)
836
+ query_pos_embed = self.query_pos_head(ref_points_detach).clamp(min=-10, max=10)
837
+
838
+ hidden_states = decoder_layer(
839
+ hidden_states,
840
+ position_embeddings=query_pos_embed,
841
+ reference_points=ref_points_input,
842
+ spatial_shapes=spatial_shapes,
843
+ spatial_shapes_list=spatial_shapes_list,
844
+ encoder_hidden_states=encoder_hidden_states,
845
+ encoder_attention_mask=encoder_attention_mask,
846
+ **kwargs,
847
+ )
848
+
849
+ if i == 0:
850
+ # Initial bounding box predictions with inverse sigmoid refinement
851
+ new_reference_points = F.sigmoid(
852
+ self.pre_bbox_head(hidden_states) + inverse_sigmoid(ref_points_detach)
853
+ )
854
+ ref_points_initial = new_reference_points.detach()
855
+
856
+ # Refine bounding box corners using FDR, integrating previous layer's corrections
857
+ if self.bbox_embed is not None:
858
+ pred_corners = self.bbox_embed[i](hidden_states + output_detach) + pred_corners_undetach
859
+ inter_ref_bbox = distance2bbox(
860
+ ref_points_initial, self.integral(pred_corners, project), self.reg_scale
861
+ )
862
+ pred_corners_undetach = pred_corners
863
+ ref_points_detach = inter_ref_bbox.detach()
864
+
865
+ output_detach = hidden_states.detach()
866
+
867
+ intermediate += (hidden_states,)
868
+
869
+ if self.class_embed is not None and (self.training or i == self.eval_idx):
870
+ scores = self.class_embed[i](hidden_states)
871
+ # Add initial logits and reference points with pre-bbox head
872
+ if i == 0:
873
+ intermediate_logits += (scores,)
874
+ intermediate_reference_points += (new_reference_points,)
875
+ # Lqe does not affect the performance here.
876
+ scores = self.lqe_layers[i](scores, pred_corners)
877
+ intermediate_logits += (scores,)
878
+ intermediate_reference_points += (inter_ref_bbox,)
879
+ initial_reference_points += (ref_points_initial,)
880
+ intermediate_predicted_corners += (pred_corners,)
881
+
882
+ # Keep batch_size as first dimension
883
+ intermediate = torch.stack(intermediate)
884
+ if self.class_embed is not None and self.bbox_embed is not None:
885
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
886
+ intermediate_predicted_corners = torch.stack(intermediate_predicted_corners, dim=1)
887
+ initial_reference_points = torch.stack(initial_reference_points, dim=1)
888
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
889
+
890
+ return DFineDecoderOutput(
891
+ last_hidden_state=hidden_states,
892
+ intermediate_hidden_states=intermediate,
893
+ intermediate_logits=intermediate_logits,
894
+ intermediate_reference_points=intermediate_reference_points,
895
+ intermediate_predicted_corners=intermediate_predicted_corners,
896
+ initial_reference_points=initial_reference_points,
897
+ )
898
+
899
+
900
+ class DFineModel(RTDetrModel):
901
+ def __init__(self, config: DFineConfig):
902
+ super().__init__(config)
903
+ del self.decoder_input_proj
904
+ self.encoder = DFineHybridEncoder(config=config)
905
+ num_backbone_outs = len(config.decoder_in_channels)
906
+ decoder_input_proj = []
907
+ in_channels = config.decoder_in_channels[-1]
908
+ for _ in range(num_backbone_outs):
909
+ if config.hidden_size == config.decoder_in_channels[-1]:
910
+ decoder_input_proj.append(nn.Identity())
911
+ else:
912
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False)
913
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
914
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
915
+ for _ in range(config.num_feature_levels - num_backbone_outs):
916
+ if config.hidden_size == config.decoder_in_channels[-1]:
917
+ decoder_input_proj.append(nn.Identity())
918
+ else:
919
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False)
920
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
921
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
922
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj)
923
+ self.decoder = DFineDecoder(config)
924
+
925
+
926
+ class DFineForObjectDetection(RTDetrForObjectDetection):
927
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
928
+ # We can't initialize the model on meta device as some weights are modified during the initialization
929
+ _no_split_modules = None
930
+ _tied_weights_keys = {
931
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
932
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
933
+ "class_embed": "model.decoder.class_embed",
934
+ "bbox_embed": "model.decoder.bbox_embed",
935
+ }
936
+
937
+ def __init__(self, config: DFineConfig):
938
+ DFinePreTrainedModel.__init__(self, config)
939
+
940
+ # D-FINE encoder-decoder model
941
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
942
+ self.model = DFineModel(config)
943
+ scaled_dim = round(config.layer_scale * config.hidden_size)
944
+ num_pred = config.decoder_layers
945
+ self.class_embed = nn.ModuleList([nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)])
946
+ self.bbox_embed = nn.ModuleList(
947
+ [
948
+ DFineMLP(config.hidden_size, config.hidden_size, 4 * (config.max_num_bins + 1), 3)
949
+ for _ in range(self.eval_idx + 1)
950
+ ]
951
+ + [
952
+ DFineMLP(scaled_dim, scaled_dim, 4 * (config.max_num_bins + 1), 3)
953
+ for _ in range(config.decoder_layers - self.eval_idx - 1)
954
+ ]
955
+ )
956
+
957
+ self.model.decoder.class_embed = self.class_embed
958
+ self.model.decoder.bbox_embed = self.bbox_embed
959
+ # Initialize weights and apply final processing
960
+ self.post_init()
961
+
962
+ def forward(**super_kwargs):
963
+ r"""
964
+ Example:
965
+
966
+ ```python
967
+ >>> import torch
968
+ >>> from transformers.image_utils import load_image
969
+ >>> from transformers import AutoImageProcessor, DFineForObjectDetection
970
+
971
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
972
+ >>> image = load_image(url)
973
+
974
+ >>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
975
+ >>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")
976
+
977
+ >>> # prepare image for the model
978
+ >>> inputs = image_processor(images=image, return_tensors="pt")
979
+
980
+ >>> # forward pass
981
+ >>> outputs = model(**inputs)
982
+
983
+ >>> logits = outputs.logits
984
+ >>> list(logits.shape)
985
+ [1, 300, 80]
986
+
987
+ >>> boxes = outputs.pred_boxes
988
+ >>> list(boxes.shape)
989
+ [1, 300, 4]
990
+
991
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
992
+ >>> target_sizes = torch.tensor([image.size[::-1]])
993
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
994
+ >>> result = results[0] # first image in batch
995
+
996
+ >>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
997
+ ... box = [round(i, 2) for i in box.tolist()]
998
+ ... print(
999
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1000
+ ... f"{round(score.item(), 3)} at location {box}"
1001
+ ... )
1002
+ Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
1003
+ Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
1004
+ Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
1005
+ Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
1006
+ ```
1007
+ """
1008
+ super().forward(**super_kwargs)
1009
+
1010
+
1011
+ __all__ = [
1012
+ "DFineConfig",
1013
+ "DFineModel",
1014
+ "DFinePreTrainedModel",
1015
+ "DFineForObjectDetection",
1016
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_got_ocr2 import *
22
+ from .image_processing_got_ocr2 import *
23
+ from .image_processing_pil_got_ocr2 import *
24
+ from .modeling_got_ocr2 import *
25
+ from .processing_got_ocr2 import *
26
+
27
+
28
+ else:
29
+ import sys
30
+
31
+ _file = globals()["__file__"]
32
+ 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/got_ocr2/configuration_got_ocr2.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/got_ocr2/modular_got_ocr2.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_got_ocr2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...utils import auto_docstring
26
+ from ..auto import CONFIG_MAPPING, AutoConfig
27
+
28
+
29
+ @auto_docstring(checkpoint="facebook/sam-vit-huge")
30
+ @strict
31
+ class GotOcr2VisionConfig(PreTrainedConfig):
32
+ r"""
33
+ output_channels (`int`, *optional*, defaults to 256):
34
+ Dimensionality of the output channels in the Patch Encoder.
35
+ use_abs_pos (`bool`, *optional*, defaults to `True`):
36
+ Whether to use absolute position embedding.
37
+ use_rel_pos (`bool`, *optional*, defaults to `True`):
38
+ Whether to use relative position embedding.
39
+ window_size (`int`, *optional*, defaults to 14):
40
+ Window size for relative position.
41
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
42
+ The indexes of the global attention layers.
43
+ mlp_dim (`int`, *optional*, defaults to 3072):
44
+ The dimensionality of the MLP layer in the Transformer encoder.
45
+ """
46
+
47
+ base_config_key = "vision_config"
48
+ hidden_size: int = 768
49
+ output_channels: int = 256
50
+ num_hidden_layers: int = 12
51
+ num_attention_heads: int = 12
52
+ num_channels: int = 3
53
+ image_size: int | list[int] | tuple[int, int] = 1024
54
+ patch_size: int | list[int] | tuple[int, int] = 16
55
+ hidden_act: str = "gelu"
56
+ layer_norm_eps: float = 1e-06
57
+ attention_dropout: float | int = 0.0
58
+ initializer_range: float = 1e-10
59
+ qkv_bias: bool = True
60
+ use_abs_pos: bool = True
61
+ use_rel_pos: bool = True
62
+ window_size: int = 14
63
+ global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
64
+ mlp_dim: int = 3072
65
+
66
+
67
+ @auto_docstring(checkpoint="facebook/sam-vit-huge")
68
+ @strict
69
+ class GotOcr2Config(PreTrainedConfig):
70
+ r"""
71
+ Example:
72
+
73
+ ```python
74
+ >>> from transformers import GotOcr2ForConditionalGeneration, GotOcr2Config
75
+
76
+ >>> # Initializing a GotOcr2 style configuration
77
+ >>> configuration = GotOcr2Config()
78
+
79
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
80
+ >>> model = GotOcr2ForConditionalGeneration(configuration)
81
+
82
+ >>> # Accessing the model configuration
83
+ >>> configuration = model.config
84
+ ```"""
85
+
86
+ model_type = "got_ocr2"
87
+ attribute_map = {
88
+ "image_token_id": "image_token_index",
89
+ }
90
+ sub_configs = {"text_config": AutoConfig, "vision_config": GotOcr2VisionConfig}
91
+
92
+ vision_config: dict | PreTrainedConfig | None = None
93
+ text_config: dict | PreTrainedConfig | None = None
94
+ image_token_index: int = 151859
95
+ image_seq_length: int = 576
96
+ tie_word_embeddings: bool = True
97
+
98
+ def __post_init__(self, **kwargs):
99
+ if self.vision_config is None:
100
+ self.vision_config = GotOcr2VisionConfig()
101
+ elif isinstance(self.vision_config, dict):
102
+ self.vision_config = GotOcr2VisionConfig(**self.vision_config)
103
+
104
+ if isinstance(self.text_config, dict):
105
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
106
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
107
+ elif self.text_config is None:
108
+ self.text_config = CONFIG_MAPPING["qwen2"](
109
+ vocab_size=151860,
110
+ hidden_size=1024,
111
+ intermediate_size=2816,
112
+ num_hidden_layers=24,
113
+ num_attention_heads=16,
114
+ num_key_value_heads=16,
115
+ hidden_act="silu",
116
+ max_position_embeddings=32768,
117
+ initializer_range=0.02,
118
+ rms_norm_eps=1e-6,
119
+ use_cache=True,
120
+ tie_word_embeddings=self.tie_word_embeddings,
121
+ rope_theta=1000000.0,
122
+ rope_parameters=None,
123
+ use_sliding_window=False,
124
+ sliding_window=4096,
125
+ max_window_layers=21,
126
+ attention_dropout=0.0,
127
+ )
128
+
129
+ super().__post_init__(**kwargs)
130
+
131
+
132
+ __all__ = ["GotOcr2VisionConfig", "GotOcr2Config"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/image_processing_got_ocr2.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Got-OCR-2."""
15
+
16
+ from functools import lru_cache
17
+
18
+ import torch
19
+ from torchvision.transforms.v2 import functional as tvF
20
+
21
+ from ...image_processing_backends import TorchvisionBackend
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_transforms import group_images_by_shape, reorder_images
24
+ from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling, SizeDict
25
+ from ...processing_utils import ImagesKwargs, Unpack
26
+ from ...utils import (
27
+ TensorType,
28
+ auto_docstring,
29
+ )
30
+
31
+
32
+ class GotOcr2ImageProcessorKwargs(ImagesKwargs, total=False):
33
+ r"""
34
+ crop_to_patches (`bool`, *optional*, defaults to `self.crop_to_patches`):
35
+ Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
36
+ `preprocess` method.
37
+ min_patches (`int`, *optional*, defaults to `self.min_patches`):
38
+ The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
39
+ set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method.
40
+ max_patches (`int`, *optional*, defaults to `self.max_patches`):
41
+ The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
42
+ set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method.
43
+ """
44
+
45
+ crop_to_patches: bool
46
+ min_patches: int
47
+ max_patches: int
48
+
49
+
50
+ @lru_cache(maxsize=10)
51
+ def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> list[tuple[int, int]]:
52
+ """
53
+ Computes all allowed aspect ratios for a given minimum and maximum number of input tiles.
54
+
55
+ This function calculates all possible arrangements of tiles that can be formed
56
+ within the constraint of the minimum and maximum number of tiles. Each arrangement is
57
+ represented by its aspect ratio (width/height) and the corresponding tile configuration.
58
+
59
+ Args:
60
+ min_image_tiles (`int`):
61
+ The minimum number of tiles allowed.
62
+ max_image_tiles (`int`):
63
+ The maximum number of tiles allowed.
64
+
65
+ Returns:
66
+ `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
67
+ configuration in terms of number of tiles.
68
+
69
+ Example:
70
+ >>> get_all_supported_aspect_ratios(1, 4)
71
+ [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)]
72
+
73
+ """
74
+ aspect_ratios = []
75
+ for width in range(1, max_image_tiles + 1):
76
+ for height in range(1, max_image_tiles + 1):
77
+ if width * height <= max_image_tiles and width * height >= min_image_tiles:
78
+ aspect_ratios.append((width, height))
79
+
80
+ aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1])
81
+
82
+ return aspect_ratios
83
+
84
+
85
+ @lru_cache(maxsize=100)
86
+ def get_optimal_tiled_canvas(
87
+ original_image_size: tuple[int, int],
88
+ target_tile_size: tuple[int, int],
89
+ min_image_tiles: int,
90
+ max_image_tiles: int,
91
+ ) -> tuple[int, int]:
92
+ """
93
+ Given a minimum and maximum number of tiles, find the canvas with the closest aspect ratio to the
94
+ original image aspect ratio.
95
+ In case of tie-breaking condition when two canvases have the same aspect ratio difference, we favor the canvas with
96
+ more tiles, until the area covered by the tiles is more than twice the target area, in order to avoid unnecessarily
97
+ excessive tiling.
98
+ """
99
+ possible_tile_arrangements = get_all_supported_aspect_ratios(min_image_tiles, max_image_tiles)
100
+
101
+ original_height, original_width = original_image_size
102
+ target_tile_height, target_tile_width = target_tile_size
103
+ aspect_ratio = original_width / original_height
104
+ area = original_width * original_height
105
+
106
+ # find the grid with the best aspect ratio
107
+ best_ratio_diff = float("inf")
108
+ best_grid = (1, 1)
109
+ for grid in possible_tile_arrangements:
110
+ grid_aspect_ratio = grid[0] / grid[1]
111
+ ratio_diff = abs(aspect_ratio - grid_aspect_ratio)
112
+ if ratio_diff < best_ratio_diff:
113
+ best_ratio_diff = ratio_diff
114
+ best_grid = grid
115
+ elif ratio_diff == best_ratio_diff:
116
+ # if the aspect ratio difference is the same, we favor the grid with more patches
117
+ # until the area covered by the patches is more than twice the original image area
118
+ if area > 0.5 * target_tile_height * target_tile_width * grid[0] * grid[1]:
119
+ best_grid = grid
120
+
121
+ return best_grid
122
+
123
+
124
+ @auto_docstring
125
+ class GotOcr2ImageProcessor(TorchvisionBackend):
126
+ valid_kwargs = GotOcr2ImageProcessorKwargs
127
+ resample = PILImageResampling.BICUBIC
128
+ image_mean = OPENAI_CLIP_MEAN
129
+ image_std = OPENAI_CLIP_STD
130
+ size = {"height": 384, "width": 384}
131
+ do_resize = True
132
+ do_rescale = True
133
+ do_normalize = True
134
+ do_convert_rgb = True
135
+ crop_to_patches = False
136
+ min_patches = 1
137
+ max_patches = 12
138
+
139
+ def __init__(self, **kwargs: Unpack[GotOcr2ImageProcessorKwargs]):
140
+ super().__init__(**kwargs)
141
+
142
+ def crop_image_to_patches(
143
+ self,
144
+ images: "torch.Tensor",
145
+ min_patches: int,
146
+ max_patches: int,
147
+ use_thumbnail: bool = True,
148
+ patch_size: SizeDict | None = None,
149
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
150
+ ):
151
+ """
152
+ Crop the images to patches and return a list of cropped images.
153
+ The number of patches and their grid arrangement are determined by the original image size,
154
+ the target patch size and the minimum and maximum number of patches.
155
+ The aspect ratio of the patches grid is chosen to be the closest to the original image aspect ratio.
156
+
157
+ Args:
158
+ images (`torch.Tensor`):
159
+ The images to be cropped.
160
+ min_patches (`int`):
161
+ The minimum number of patches to be extracted from the image.
162
+ max_patches (`int`):
163
+ The maximum number of patches to be extracted from the image.
164
+ use_thumbnail (`bool`, *optional*, defaults to `True`):
165
+ Whether to add a thumbnail image to the list of cropped patches.
166
+ patch_size (`SizeDict`, *optional*):
167
+ The size of the output patches.
168
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
169
+ Resampling filter to use when resizing.
170
+ """
171
+ patch_size_height, patch_size_width = patch_size.height, patch_size.width
172
+ original_height, original_width = images.shape[-2:]
173
+ # find the closest aspect ratio to the target
174
+ num_columns, num_rows = get_optimal_tiled_canvas(
175
+ (original_height, original_width), (patch_size_height, patch_size_width), min_patches, max_patches
176
+ )
177
+
178
+ # calculate the target width and height
179
+ target_width = patch_size_width * num_columns
180
+ target_height = patch_size_height * num_rows
181
+ num_blocks = num_columns * num_rows
182
+
183
+ # resize the image so that each patch is of patch_size
184
+ resized_image = self.resize(images, SizeDict(height=target_height, width=target_width), resample=resample)
185
+ # split the image into patches
186
+ processed_images = []
187
+ for i in range(num_blocks):
188
+ column = i % num_columns
189
+ row = i // num_columns
190
+ box = (
191
+ column * patch_size_width,
192
+ row * patch_size_height,
193
+ (column + 1) * patch_size_width,
194
+ (row + 1) * patch_size_height,
195
+ )
196
+ # split the image
197
+ patch_image = resized_image[..., box[1] : box[3], box[0] : box[2]]
198
+ processed_images.append(patch_image)
199
+
200
+ if use_thumbnail and len(processed_images) != 1:
201
+ thumbnail_img = self.resize(images, patch_size, resample=resample)
202
+ processed_images.append(thumbnail_img)
203
+
204
+ processed_images = torch.stack(processed_images, dim=0).transpose(0, 1).contiguous()
205
+
206
+ return processed_images
207
+
208
+ def _preprocess(
209
+ self,
210
+ images: list["torch.Tensor"],
211
+ do_resize: bool,
212
+ size: SizeDict,
213
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
214
+ do_rescale: bool,
215
+ rescale_factor: float,
216
+ do_normalize: bool,
217
+ image_mean: float | list[float] | None,
218
+ image_std: float | list[float] | None,
219
+ disable_grouping: bool | None,
220
+ return_tensors: str | TensorType | None,
221
+ crop_to_patches: bool = False,
222
+ min_patches: int = 1,
223
+ max_patches: int = 12,
224
+ **kwargs,
225
+ ) -> BatchFeature:
226
+ if crop_to_patches:
227
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
228
+ processed_images_grouped = {}
229
+ num_patches = {}
230
+ for shape, stacked_images in grouped_images.items():
231
+ stacked_images = self.crop_image_to_patches(
232
+ stacked_images,
233
+ min_patches,
234
+ max_patches,
235
+ patch_size=size,
236
+ resample=resample,
237
+ )
238
+ processed_images_grouped[shape] = stacked_images
239
+ num_patches[shape] = [stacked_images.shape[1]] * stacked_images.shape[0]
240
+ images = reorder_images(processed_images_grouped, grouped_images_index)
241
+ images = [image for images_list in images for image in images_list]
242
+ num_patches = reorder_images(num_patches, grouped_images_index)
243
+ else:
244
+ num_patches = [1] * len(images)
245
+
246
+ # Group images by size for batched resizing
247
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
248
+ resized_images_grouped = {}
249
+ for shape, stacked_images in grouped_images.items():
250
+ if do_resize:
251
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
252
+ resized_images_grouped[shape] = stacked_images
253
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
254
+
255
+ # Group images by size for further processing
256
+ # Needed in case do_resize is False, or resize returns images with different sizes
257
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
258
+ processed_images_grouped = {}
259
+ for shape, stacked_images in grouped_images.items():
260
+ stacked_images = self.rescale_and_normalize(
261
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
262
+ )
263
+ processed_images_grouped[shape] = stacked_images
264
+
265
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
266
+
267
+ return BatchFeature(
268
+ data={"pixel_values": processed_images, "num_patches": num_patches}, tensor_type=return_tensors
269
+ )
270
+
271
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
272
+ """
273
+ A utility that returns number patches for a given image size.
274
+
275
+ Args:
276
+ height (`int`):
277
+ Height of the input image.
278
+ width (`int`):
279
+ Width of the input image.
280
+ images_kwargs (`dict`, *optional*)
281
+ Any kwargs to override defaults of the image processor.
282
+ Returns:
283
+ `int`: Number of patches per image.
284
+ """
285
+ min_patches = images_kwargs.get("min_patches", self.min_patches) if images_kwargs else self.min_patches
286
+ max_patches = images_kwargs.get("max_patches", self.max_patches) if images_kwargs else self.max_patches
287
+ patch_size = images_kwargs.get("patch_size", self.size) if images_kwargs else self.size
288
+ crop_to_patches = (
289
+ images_kwargs.get("crop_to_patches", self.crop_to_patches) if images_kwargs else self.crop_to_patches
290
+ )
291
+
292
+ num_patches = 1
293
+ if crop_to_patches and max_patches > 1:
294
+ if isinstance(patch_size, dict):
295
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
296
+ else:
297
+ patch_height, patch_width = patch_size.height, patch_size.width
298
+ num_columns, num_rows = get_optimal_tiled_canvas(
299
+ (height, width), (patch_height, patch_width), min_patches, max_patches
300
+ )
301
+ if num_columns * num_rows > 1:
302
+ num_patches += num_columns * num_rows
303
+
304
+ return num_patches
305
+
306
+
307
+ __all__ = ["GotOcr2ImageProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/got_ocr2/modeling_got_ocr2.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/got_ocr2/modular_got_ocr2.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_got_ocr2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ import collections
23
+ from dataclasses import dataclass
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+
29
+ from ... import initialization as init
30
+ from ...activations import ACT2FN
31
+ from ...cache_utils import Cache
32
+ from ...generation import GenerationMixin
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...processing_utils import Unpack
37
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
38
+ from ...utils.generic import merge_with_config_defaults
39
+ from ...utils.output_capturing import capture_outputs
40
+ from ..auto import AutoModel
41
+ from .configuration_got_ocr2 import GotOcr2Config, GotOcr2VisionConfig
42
+
43
+
44
+ class GotOcr2MLPBlock(nn.Module):
45
+ def __init__(self, config):
46
+ super().__init__()
47
+ self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
48
+ self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
49
+ self.act = ACT2FN[config.hidden_act]
50
+
51
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
52
+ hidden_states = self.lin1(hidden_states)
53
+ hidden_states = self.act(hidden_states)
54
+ hidden_states = self.lin2(hidden_states)
55
+ return hidden_states
56
+
57
+
58
+ class GotOcr2VisionAttention(nn.Module):
59
+ """Multi-head Attention block with relative position embeddings."""
60
+
61
+ def __init__(self, config, window_size):
62
+ super().__init__()
63
+ input_size = (
64
+ (config.image_size // config.patch_size, config.image_size // config.patch_size)
65
+ if window_size == 0
66
+ else (window_size, window_size)
67
+ )
68
+
69
+ self.num_attention_heads = config.num_attention_heads
70
+ head_dim = config.hidden_size // config.num_attention_heads
71
+ self.scale = head_dim**-0.5
72
+ self.dropout = config.attention_dropout
73
+
74
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
75
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size)
76
+
77
+ self.use_rel_pos = config.use_rel_pos
78
+ if self.use_rel_pos:
79
+ if input_size is None:
80
+ raise ValueError("Input size must be provided if using relative positional encoding.")
81
+
82
+ # initialize relative positional embeddings
83
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
84
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
85
+
86
+ def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
87
+ """
88
+ Get relative positional embeddings according to the relative positions of
89
+ query and key sizes.
90
+
91
+ Args:
92
+ q_size (int):
93
+ size of the query.
94
+ k_size (int):
95
+ size of key k.
96
+ rel_pos (`torch.Tensor`):
97
+ relative position embeddings (L, channel).
98
+
99
+ Returns:
100
+ Extracted positional embeddings according to relative positions.
101
+ """
102
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
103
+ # Interpolate rel pos.
104
+ rel_pos_resized = F.interpolate(
105
+ rel_pos.reshape(1, rel_pos.shape[0], -1).transpose(1, 2),
106
+ size=max_rel_dist,
107
+ mode="linear",
108
+ )
109
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
110
+
111
+ # Scale the coords with short length if shapes for q and k are different.
112
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
113
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
114
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
115
+
116
+ return rel_pos_resized[relative_coords.long()]
117
+
118
+ def get_decomposed_rel_pos(
119
+ self,
120
+ query: torch.Tensor,
121
+ rel_pos_h: torch.Tensor,
122
+ rel_pos_w: torch.Tensor,
123
+ q_size: tuple[int, int],
124
+ k_size: tuple[int, int],
125
+ ) -> torch.Tensor:
126
+ """
127
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
128
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
129
+
130
+ Args:
131
+ query (`torch.Tensor`):
132
+ query q in the attention layer with shape (batch_size, query_height * query_width, channel).
133
+ rel_pos_h (`torch.Tensor`):
134
+ relative position embeddings (Lh, channel) for height axis.
135
+ rel_pos_w (`torch.Tensor`):
136
+ relative position embeddings (Lw, channel) for width axis.
137
+ q_size (tuple):
138
+ spatial sequence size of query q with (query_height, query_width).
139
+ k_size (tuple):
140
+ spatial sequence size of key k with (key_height, key_width).
141
+
142
+ Returns:
143
+ decomposed_rel_pos (`torch.Tensor`):
144
+ decomposed relative position embeddings.
145
+ """
146
+ query_height, query_width = q_size
147
+ key_height, key_width = k_size
148
+ relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
149
+ relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
150
+
151
+ batch_size, _, dim = query.shape
152
+ reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
153
+ rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
154
+ rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
155
+
156
+ decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
157
+
158
+ return decomposed_rel_pos
159
+
160
+ def forward(self, hidden_states: torch.Tensor, output_attentions=None) -> tuple[torch.Tensor, torch.Tensor]:
161
+ batch_size, height, width, _ = hidden_states.shape
162
+ # qkv with shape (3, batch_size, nHead, height * width, channel)
163
+ qkv = (
164
+ self.qkv(hidden_states)
165
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
166
+ .permute(2, 0, 3, 1, 4)
167
+ )
168
+ # q, k, v with shape (batch_size * nHead, height * width, channel)
169
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
170
+
171
+ attn_weights = (query * self.scale) @ key.transpose(-2, -1)
172
+
173
+ if self.use_rel_pos:
174
+ decomposed_rel_pos = self.get_decomposed_rel_pos(
175
+ query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
176
+ )
177
+ decomposed_rel_pos = decomposed_rel_pos.reshape_as(attn_weights)
178
+ attn_weights = attn_weights + decomposed_rel_pos
179
+
180
+ attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
181
+
182
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
183
+
184
+ attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
185
+ attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
186
+
187
+ attn_output = self.proj(attn_output)
188
+ return attn_output, attn_weights
189
+
190
+
191
+ class GotOcr2VisionLayer(GradientCheckpointingLayer):
192
+ def __init__(self, config, window_size):
193
+ super().__init__()
194
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
195
+ self.attn = GotOcr2VisionAttention(config, window_size)
196
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
197
+ self.mlp = GotOcr2MLPBlock(config)
198
+ self.window_size = window_size
199
+
200
+ def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
201
+ """
202
+ Args:
203
+ Partition into non-overlapping windows with padding if needed.
204
+ hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
205
+ size.
206
+
207
+ Returns:
208
+ windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
209
+ (pad_height, pad_width): padded height and width before partition
210
+ """
211
+ batch_size, height, width, channel = hidden_states.shape
212
+
213
+ pad_h = (window_size - height % window_size) % window_size
214
+ pad_w = (window_size - width % window_size) % window_size
215
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
216
+ pad_height, pad_width = height + pad_h, width + pad_w
217
+
218
+ hidden_states = hidden_states.reshape(
219
+ batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
220
+ )
221
+ windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
222
+ return windows, (pad_height, pad_width)
223
+
224
+ def window_unpartition(
225
+ self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
226
+ ) -> torch.Tensor:
227
+ """
228
+ Args:
229
+ Window unpartition into original sequences and removing padding.
230
+ hidden_states (tensor):
231
+ input tokens with [batch_size * num_windows, window_size, window_size, channel].
232
+ window_size (int):
233
+ window size.
234
+ padding_shape (Tuple):
235
+ padded height and width (pad_height, pad_width).
236
+ original_shape (Tuple): original height and width (height, width) before padding.
237
+
238
+ Returns:
239
+ hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
240
+ """
241
+ pad_height, pad_width = padding_shape
242
+ height, width = original_shape
243
+ batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
244
+ hidden_states = windows.reshape(
245
+ batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
246
+ )
247
+ hidden_states = (
248
+ hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
249
+ )
250
+
251
+ hidden_states = hidden_states[:, :height, :width, :].contiguous()
252
+ return hidden_states
253
+
254
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
255
+ residual = hidden_states
256
+ hidden_states = self.layer_norm1(hidden_states)
257
+ # Window partition
258
+ if self.window_size > 0:
259
+ height, width = hidden_states.shape[1], hidden_states.shape[2]
260
+ hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
261
+
262
+ hidden_states, attn_weights = self.attn(
263
+ hidden_states=hidden_states,
264
+ )
265
+ # Reverse window partition
266
+ if self.window_size > 0:
267
+ hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
268
+
269
+ hidden_states = residual + hidden_states
270
+ layernorm_output = self.layer_norm2(hidden_states)
271
+ hidden_states = hidden_states + self.mlp(layernorm_output)
272
+ return hidden_states
273
+
274
+
275
+ @auto_docstring
276
+ class GotOcr2PreTrainedModel(PreTrainedModel):
277
+ config: GotOcr2Config
278
+ base_model_prefix = "model"
279
+ input_modalities = ("image", "text")
280
+ supports_gradient_checkpointing = True
281
+ _skip_keys_device_placement = ["past_key_values"]
282
+ _supports_flash_attn = False
283
+ _supports_sdpa = False
284
+
285
+ _can_compile_fullgraph = True
286
+ _supports_flex_attn = False
287
+ _supports_attention_backend = True
288
+
289
+ @torch.no_grad()
290
+ def _init_weights(self, module):
291
+ super()._init_weights(module)
292
+ if isinstance(module, GotOcr2VisionAttention):
293
+ if module.use_rel_pos:
294
+ init.zeros_(module.rel_pos_h)
295
+ init.zeros_(module.rel_pos_w)
296
+ elif isinstance(module, GotOcr2VisionEncoder):
297
+ if module.pos_embed is not None:
298
+ init.zeros_(module.pos_embed)
299
+
300
+
301
+ @auto_docstring(
302
+ custom_intro="""
303
+ Base class for got_ocr2 vision model's outputs that also contains image embeddings obtained by applying the projection
304
+ layer to the pooler_output.
305
+ """
306
+ )
307
+ @dataclass
308
+ class GotOcr2VisionEncoderOutput(ModelOutput):
309
+ r"""
310
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
311
+ The image embeddings obtained by applying the projection layer to the pooler_output.
312
+ """
313
+
314
+ image_embeds: torch.FloatTensor | None = None
315
+ last_hidden_state: torch.FloatTensor | None = None
316
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
317
+ attentions: tuple[torch.FloatTensor, ...] | None = None
318
+
319
+
320
+ class GotOcr2PatchEmbeddings(nn.Module):
321
+ """
322
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
323
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
324
+ Transformer.
325
+ """
326
+
327
+ def __init__(self, config):
328
+ super().__init__()
329
+ image_size, patch_size = config.image_size, config.patch_size
330
+ num_channels, hidden_size = config.num_channels, config.hidden_size
331
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
332
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
333
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
334
+ self.image_size = image_size
335
+ self.patch_size = patch_size
336
+ self.num_channels = num_channels
337
+ self.num_patches = num_patches
338
+
339
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
340
+
341
+ def forward(self, pixel_values):
342
+ batch_size, num_channels, height, width = pixel_values.shape
343
+ if num_channels != self.num_channels:
344
+ raise ValueError(
345
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
346
+ )
347
+ if height != self.image_size[0] or width != self.image_size[1]:
348
+ raise ValueError(
349
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
350
+ )
351
+ embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
352
+ return embeddings
353
+
354
+
355
+ class GotOcr2LayerNorm(nn.LayerNorm):
356
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
357
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
358
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
359
+ """
360
+
361
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
362
+ super().__init__(normalized_shape, eps=eps, **kwargs)
363
+ if data_format not in ["channels_last", "channels_first"]:
364
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
365
+ self.data_format = data_format
366
+
367
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
368
+ """
369
+ Args:
370
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
371
+ """
372
+ if self.data_format == "channels_first":
373
+ features = features.permute(0, 2, 3, 1)
374
+ features = super().forward(features)
375
+ features = features.permute(0, 3, 1, 2)
376
+ else:
377
+ features = super().forward(features)
378
+ return features
379
+
380
+
381
+ class GotOcr2VisionNeck(nn.Module):
382
+ def __init__(self, config: GotOcr2VisionConfig):
383
+ super().__init__()
384
+ self.config = config
385
+
386
+ self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
387
+ self.layer_norm1 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
388
+ self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
389
+ self.layer_norm2 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
390
+
391
+ def forward(self, hidden_states):
392
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
393
+ hidden_states = self.conv1(hidden_states)
394
+ hidden_states = self.layer_norm1(hidden_states)
395
+
396
+ hidden_states = self.conv2(hidden_states)
397
+ hidden_states = self.layer_norm2(hidden_states)
398
+ return hidden_states
399
+
400
+
401
+ class GotOcr2VisionEncoder(GotOcr2PreTrainedModel):
402
+ _can_record_outputs = {"hidden_states": GotOcr2VisionLayer, "attentions": GotOcr2VisionAttention}
403
+ input_modalities = ("image",)
404
+
405
+ def __init__(self, config: GotOcr2VisionConfig):
406
+ super().__init__(config)
407
+ self.config = config
408
+ self.image_size = config.image_size
409
+ self.patch_embed = GotOcr2PatchEmbeddings(config)
410
+
411
+ self.pos_embed = None
412
+ if config.use_abs_pos:
413
+ # Initialize absolute positional embedding with pretrain image size.
414
+ self.pos_embed = nn.Parameter(
415
+ torch.zeros(
416
+ 1,
417
+ config.image_size // config.patch_size,
418
+ config.image_size // config.patch_size,
419
+ config.hidden_size,
420
+ )
421
+ )
422
+
423
+ self.layers = nn.ModuleList()
424
+ for i in range(config.num_hidden_layers):
425
+ layer = GotOcr2VisionLayer(
426
+ config,
427
+ window_size=config.window_size if i not in config.global_attn_indexes else 0,
428
+ )
429
+ self.layers.append(layer)
430
+
431
+ self.neck = GotOcr2VisionNeck(config)
432
+
433
+ self.gradient_checkpointing = False
434
+ self.post_init()
435
+
436
+ def get_input_embeddings(self):
437
+ return self.patch_embed
438
+
439
+ @merge_with_config_defaults
440
+ @capture_outputs(tie_last_hidden_states=False)
441
+ def forward(
442
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
443
+ ) -> tuple | GotOcr2VisionEncoderOutput:
444
+ if pixel_values is None:
445
+ raise ValueError("You have to specify pixel_values")
446
+
447
+ hidden_states = self.patch_embed(pixel_values)
448
+ if self.pos_embed is not None:
449
+ hidden_states = hidden_states + self.pos_embed
450
+ for layer_module in self.layers:
451
+ hidden_states = layer_module(hidden_states)
452
+ hidden_states = self.neck(hidden_states)
453
+ return GotOcr2VisionEncoderOutput(
454
+ last_hidden_state=hidden_states,
455
+ )
456
+
457
+
458
+ class GotOcr2MultiModalProjector(nn.Module):
459
+ def __init__(self, config: GotOcr2Config):
460
+ super().__init__()
461
+ vision_output_channels = config.vision_config.output_channels
462
+ language_hidden_size = config.text_config.hidden_size
463
+ self.conv_upsampler1 = nn.Conv2d(
464
+ vision_output_channels, vision_output_channels * 2, kernel_size=3, stride=2, padding=1, bias=False
465
+ )
466
+ self.conv_upsampler2 = nn.Conv2d(
467
+ vision_output_channels * 2, language_hidden_size, kernel_size=3, stride=2, padding=1, bias=False
468
+ )
469
+ self.multimodal_projector = nn.Linear(language_hidden_size, language_hidden_size)
470
+
471
+ def forward(self, vision_embeddings: torch.Tensor) -> torch.Tensor:
472
+ hidden_state = self.conv_upsampler1(vision_embeddings)
473
+ hidden_state = self.conv_upsampler2(hidden_state)
474
+ hidden_state = hidden_state.flatten(2).permute(0, 2, 1)
475
+ hidden_state = self.multimodal_projector(hidden_state)
476
+ return hidden_state
477
+
478
+
479
+ @auto_docstring(
480
+ custom_intro="""
481
+ Base class for GotOcr2 causal language model (or autoregressive) outputs.
482
+ """
483
+ )
484
+ @dataclass
485
+ class GotOcr2CausalLMOutputWithPast(ModelOutput):
486
+ r"""
487
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
488
+ Language modeling loss (for next-token prediction).
489
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
490
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
491
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
492
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
493
+
494
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
495
+ `past_key_values` input) to speed up sequential decoding.
496
+ image_hidden_states (`torch.FloatTensor`, *optional*):
497
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
498
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
499
+ """
500
+
501
+ loss: torch.FloatTensor | None = None
502
+ logits: torch.FloatTensor | None = None
503
+ past_key_values: Cache | None = None
504
+ hidden_states: tuple[torch.FloatTensor] | None = None
505
+ attentions: tuple[torch.FloatTensor] | None = None
506
+ image_hidden_states: torch.FloatTensor | None = None
507
+
508
+
509
+ @auto_docstring(
510
+ custom_intro="""
511
+ Base class for GotOcr2 outputs, with hidden states and attentions.
512
+ """
513
+ )
514
+ @dataclass
515
+ class GotOcr2ModelOutputWithPast(BaseModelOutputWithPast):
516
+ r"""
517
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
518
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
519
+
520
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
521
+ `past_key_values` input) to speed up sequential decoding.
522
+ image_hidden_states (`torch.FloatTensor`, *optional*):
523
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
524
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
525
+ """
526
+
527
+ image_hidden_states: torch.FloatTensor | None = None
528
+
529
+
530
+ @auto_docstring(
531
+ custom_intro="""
532
+ The GotOcr2 model which consists of a vision backbone and a language model, without a language modeling head.
533
+ """
534
+ )
535
+ class GotOcr2Model(GotOcr2PreTrainedModel):
536
+ def __init__(self, config: GotOcr2Config):
537
+ super().__init__(config)
538
+ self.vision_tower = GotOcr2VisionEncoder(config.vision_config)
539
+
540
+ self.multi_modal_projector = GotOcr2MultiModalProjector(config)
541
+ self.language_model = AutoModel.from_config(config.text_config)
542
+ self.post_init()
543
+
544
+ @can_return_tuple
545
+ @auto_docstring(
546
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
547
+ )
548
+ def get_image_features(
549
+ self,
550
+ pixel_values: torch.FloatTensor,
551
+ **kwargs: Unpack[TransformersKwargs],
552
+ ) -> tuple | BaseModelOutputWithPooling:
553
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
554
+ last_hidden_state = image_outputs.last_hidden_state
555
+ image_outputs.pooler_output = self.multi_modal_projector(last_hidden_state)
556
+
557
+ return image_outputs
558
+
559
+ def get_placeholder_mask(
560
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
561
+ ):
562
+ """
563
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
564
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
565
+ """
566
+ if input_ids is None:
567
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
568
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
569
+ )
570
+ special_image_mask = special_image_mask.all(-1)
571
+ else:
572
+ special_image_mask = input_ids == self.config.image_token_id
573
+
574
+ n_image_tokens = special_image_mask.sum()
575
+ n_image_features = image_features.shape[0] * image_features.shape[1]
576
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
577
+ torch_compilable_check(
578
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
579
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
580
+ )
581
+ return special_image_mask
582
+
583
+ @can_return_tuple
584
+ @auto_docstring
585
+ def forward(
586
+ self,
587
+ input_ids: torch.LongTensor | None = None,
588
+ pixel_values: torch.FloatTensor | None = None,
589
+ attention_mask: torch.Tensor | None = None,
590
+ position_ids: torch.LongTensor | None = None,
591
+ past_key_values: Cache | None = None,
592
+ inputs_embeds: torch.FloatTensor | None = None,
593
+ use_cache: bool | None = None,
594
+ **kwargs: Unpack[TransformersKwargs],
595
+ ) -> tuple | GotOcr2ModelOutputWithPast:
596
+ if (input_ids is None) ^ (inputs_embeds is not None):
597
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
598
+
599
+ if inputs_embeds is None:
600
+ inputs_embeds = self.get_input_embeddings()(input_ids)
601
+
602
+ if pixel_values is not None:
603
+ image_features = self.get_image_features(
604
+ pixel_values=pixel_values.to(inputs_embeds.dtype), return_dict=True
605
+ ).pooler_output
606
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
607
+ special_image_mask = self.get_placeholder_mask(
608
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
609
+ )
610
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
611
+
612
+ outputs = self.language_model(
613
+ attention_mask=attention_mask,
614
+ position_ids=position_ids,
615
+ past_key_values=past_key_values,
616
+ inputs_embeds=inputs_embeds,
617
+ use_cache=use_cache,
618
+ return_dict=True,
619
+ **kwargs,
620
+ )
621
+
622
+ return GotOcr2ModelOutputWithPast(
623
+ last_hidden_state=outputs.last_hidden_state,
624
+ past_key_values=outputs.past_key_values,
625
+ hidden_states=outputs.hidden_states,
626
+ attentions=outputs.attentions,
627
+ image_hidden_states=image_features if pixel_values is not None else None,
628
+ )
629
+
630
+
631
+ @auto_docstring(
632
+ custom_intro="""
633
+ The GOT_OCR2 model which consists of a vision backbone and a language model.
634
+ """
635
+ )
636
+ class GotOcr2ForConditionalGeneration(GotOcr2PreTrainedModel, GenerationMixin):
637
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
638
+
639
+ def __init__(self, config: GotOcr2Config):
640
+ super().__init__(config)
641
+ self.model = GotOcr2Model(config)
642
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
643
+ self.post_init()
644
+
645
+ def get_output_embeddings(self) -> nn.Module:
646
+ return self.lm_head
647
+
648
+ @auto_docstring
649
+ def get_image_features(
650
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
651
+ ) -> tuple | BaseModelOutputWithPooling:
652
+ return self.model.get_image_features(pixel_values=pixel_values, **kwargs)
653
+
654
+ @can_return_tuple
655
+ @auto_docstring
656
+ def forward(
657
+ self,
658
+ input_ids: torch.LongTensor | None = None,
659
+ pixel_values: torch.FloatTensor | None = None,
660
+ attention_mask: torch.Tensor | None = None,
661
+ position_ids: torch.LongTensor | None = None,
662
+ past_key_values: Cache | None = None,
663
+ inputs_embeds: torch.FloatTensor | None = None,
664
+ labels: torch.LongTensor | None = None,
665
+ use_cache: bool | None = None,
666
+ logits_to_keep: int | torch.Tensor = 0,
667
+ **kwargs: Unpack[TransformersKwargs],
668
+ ) -> tuple | GotOcr2CausalLMOutputWithPast:
669
+ r"""
670
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
671
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
672
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
673
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
674
+
675
+ Example:
676
+
677
+ ```python
678
+ >>> from PIL import Image
679
+ >>> import httpx
680
+ >>> from io import BytesIO
681
+ >>> from transformers import AutoProcessor, GotOcr2ForConditionalGeneration, TextStreamer
682
+
683
+ >>> model = GotOcr2ForConditionalGeneration.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf").to("cuda")
684
+ >>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
685
+
686
+ >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
687
+ >>> with httpx.stream("GET", url) as response:
688
+ ... image = Image.open(BytesIO(response.read()))
689
+
690
+ >>> inputs = processor(image, return_tensors="pt", color="green").to("cuda")
691
+
692
+ >>> # Generate
693
+ >>> streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
694
+ >>> generate_ids = model.generate(
695
+ ... **inputs,
696
+ ... do_sample=False,
697
+ ... tokenizer = processor.tokenizer,
698
+ ... stop_strings='<|im_end|>',
699
+ ... streamer=streamer,
700
+ ... max_new_tokens=4096,
701
+ ... )
702
+ "You should keep in mind what features from the module should be used, especially
703
+ when you're planning to sell a template."
704
+ ```"""
705
+ outputs = self.model(
706
+ input_ids=input_ids,
707
+ pixel_values=pixel_values,
708
+ attention_mask=attention_mask,
709
+ position_ids=position_ids,
710
+ past_key_values=past_key_values,
711
+ inputs_embeds=inputs_embeds,
712
+ use_cache=use_cache,
713
+ return_dict=True,
714
+ logits_to_keep=logits_to_keep,
715
+ **kwargs,
716
+ )
717
+
718
+ hidden_states = outputs[0]
719
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
720
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
721
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
722
+
723
+ loss = None
724
+ if labels is not None:
725
+ loss = self.loss_function(
726
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
727
+ )
728
+
729
+ return GotOcr2CausalLMOutputWithPast(
730
+ loss=loss,
731
+ logits=logits,
732
+ past_key_values=outputs.past_key_values,
733
+ hidden_states=outputs.hidden_states,
734
+ attentions=outputs.attentions,
735
+ image_hidden_states=outputs.image_hidden_states,
736
+ )
737
+
738
+ def prepare_inputs_for_generation(
739
+ self,
740
+ input_ids,
741
+ past_key_values=None,
742
+ inputs_embeds=None,
743
+ pixel_values=None,
744
+ attention_mask=None,
745
+ logits_to_keep=None,
746
+ is_first_iteration=False,
747
+ **kwargs,
748
+ ):
749
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
750
+
751
+ model_inputs = super().prepare_inputs_for_generation(
752
+ input_ids,
753
+ past_key_values=past_key_values,
754
+ inputs_embeds=inputs_embeds,
755
+ attention_mask=attention_mask,
756
+ logits_to_keep=logits_to_keep,
757
+ is_first_iteration=is_first_iteration,
758
+ **kwargs,
759
+ )
760
+
761
+ if is_first_iteration or not kwargs.get("use_cache", True):
762
+ # Pixel values are used only in the first iteration if available
763
+ # In subsequent iterations, they are already merged with text and cached
764
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
765
+ # iteration with a question and cached system prompt (continue generate from cache)
766
+ model_inputs["pixel_values"] = pixel_values
767
+
768
+ return model_inputs
769
+
770
+
771
+ __all__ = ["GotOcr2PreTrainedModel", "GotOcr2Model", "GotOcr2ForConditionalGeneration"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/configuration_moonshine.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.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_moonshine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from huggingface_hub.dataclasses import strict
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...modeling_rope_utils import RopeParameters
25
+ from ...utils import auto_docstring
26
+
27
+
28
+ @auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
29
+ @strict
30
+ class MoonshineConfig(PreTrainedConfig):
31
+ r"""
32
+ encoder_num_key_value_heads (`int`, *optional*):
33
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
34
+ `encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
35
+ `encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
36
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
37
+ by meanpooling all the original heads within that group. For more details, check out [this
38
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
39
+ `num_attention_heads`.
40
+ decoder_num_key_value_heads (`int`, *optional*):
41
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
42
+ `decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
43
+ `decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
44
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
45
+ by meanpooling all the original heads within that group. For more details, check out [this
46
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
47
+ `decoder_num_attention_heads`.
48
+ pad_head_dim_to_multiple_of (`int`, *optional*):
49
+ Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
50
+ optimized attention implementations.
51
+ encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
52
+ The non-linear activation function (function or string) in the encoder.
53
+ decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54
+ The non-linear activation function (function or string) in the decoder.
55
+
56
+ Example:
57
+
58
+ ```python
59
+ >>> from transformers import MoonshineModel, MoonshineConfig
60
+
61
+ >>> # Initializing a Moonshine style configuration
62
+ >>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
63
+
64
+ >>> # Initializing a model from the configuration
65
+ >>> model = MoonshineModel(configuration)
66
+
67
+ >>> # Accessing the model configuration
68
+ >>> configuration = model.config
69
+ ```"""
70
+
71
+ model_type = "moonshine"
72
+ keys_to_ignore_at_inference = ["past_key_values"]
73
+ attribute_map = {
74
+ "num_key_value_heads": "decoder_num_key_value_heads",
75
+ "num_attention_heads": "decoder_num_attention_heads",
76
+ "num_hidden_layers": "decoder_num_hidden_layers",
77
+ "hidden_act": "decoder_hidden_act",
78
+ }
79
+
80
+ vocab_size: int = 32768
81
+ hidden_size: int = 288
82
+ intermediate_size: int = 1152
83
+ encoder_num_hidden_layers: int = 6
84
+ decoder_num_hidden_layers: int = 6
85
+ encoder_num_attention_heads: int = 8
86
+ decoder_num_attention_heads: int = 8
87
+ encoder_num_key_value_heads: int | None = None
88
+ decoder_num_key_value_heads: int | None = None
89
+ pad_head_dim_to_multiple_of: int | None = None
90
+ encoder_hidden_act: str = "gelu"
91
+ decoder_hidden_act: str = "silu"
92
+ max_position_embeddings: int = 512
93
+ initializer_range: float = 0.02
94
+ decoder_start_token_id: int = 1
95
+ use_cache: bool = True
96
+ rope_parameters: RopeParameters | dict | None = None
97
+ is_encoder_decoder: bool = True
98
+ attention_bias: bool = False
99
+ attention_dropout: float | int = 0.0
100
+ bos_token_id: int | None = 1
101
+ eos_token_id: int | list[int] | None = 2
102
+ pad_token_id: int | None = None
103
+ tie_word_embeddings: bool = True
104
+
105
+ def __post_init__(self, **kwargs):
106
+ if self.encoder_num_key_value_heads is None:
107
+ self.encoder_num_key_value_heads = self.encoder_num_attention_heads
108
+
109
+ if self.decoder_num_key_value_heads is None:
110
+ self.decoder_num_key_value_heads = self.decoder_num_attention_heads
111
+
112
+ kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
113
+ super().__post_init__(**kwargs)
114
+
115
+
116
+ __all__ = ["MoonshineConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/modeling_moonshine.py ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.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_moonshine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
30
+ from ...generation import GenerationMixin
31
+ from ...integrations import use_kernelized_func
32
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import (
36
+ BaseModelOutput,
37
+ BaseModelOutputWithPast,
38
+ BaseModelOutputWithPastAndCrossAttentions,
39
+ Seq2SeqLMOutput,
40
+ Seq2SeqModelOutput,
41
+ )
42
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
43
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
44
+ from ...processing_utils import Unpack
45
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
46
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
47
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
48
+ from .configuration_moonshine import MoonshineConfig
49
+
50
+
51
+ @auto_docstring(
52
+ custom_intro="""
53
+ Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
54
+ """
55
+ )
56
+ @dataclass
57
+ class MoonshineEncoderModelOutput(BaseModelOutput):
58
+ r"""
59
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
60
+ Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
61
+ sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
62
+
63
+ - 1 for tokens that are **not masked**,
64
+ - 0 for tokens that are **masked**.
65
+ """
66
+
67
+ attention_mask: torch.Tensor | None = None
68
+
69
+
70
+ class MoonshineEncoderMLP(nn.Module):
71
+ def __init__(self, config, hidden_act):
72
+ super().__init__()
73
+ self.config = config
74
+ self.activation_fn = ACT2FN[hidden_act]
75
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
76
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
77
+
78
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
79
+ hidden_states = self.fc1(hidden_states)
80
+ hidden_states = self.activation_fn(hidden_states)
81
+ hidden_states = self.fc2(hidden_states)
82
+ return hidden_states
83
+
84
+
85
+ class MoonshineDecoderMLP(nn.Module):
86
+ def __init__(self, config, hidden_act):
87
+ super().__init__()
88
+ self.config = config
89
+ self.activation_fn = ACT2FN[hidden_act]
90
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
91
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
92
+
93
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
94
+ hidden_states = self.fc1(hidden_states)
95
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
96
+ hidden_states = self.activation_fn(gate) * hidden_states
97
+ hidden_states = self.fc2(hidden_states)
98
+ return hidden_states
99
+
100
+
101
+ class MoonshineRotaryEmbedding(nn.Module):
102
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
103
+
104
+ def __init__(self, config: MoonshineConfig, device=None):
105
+ super().__init__()
106
+ self.max_seq_len_cached = config.max_position_embeddings
107
+ self.original_max_seq_len = config.max_position_embeddings
108
+
109
+ self.config = config
110
+
111
+ self.rope_type = self.config.rope_parameters["rope_type"]
112
+ rope_init_fn: Callable = self.compute_default_rope_parameters
113
+ if self.rope_type != "default":
114
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
115
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
116
+
117
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
118
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
119
+
120
+ @staticmethod
121
+ def compute_default_rope_parameters(
122
+ config: MoonshineConfig | None = None,
123
+ device: Optional["torch.device"] = None,
124
+ seq_len: int | None = None,
125
+ ) -> tuple["torch.Tensor", float]:
126
+ """
127
+ Computes the inverse frequencies according to the original RoPE implementation
128
+ Args:
129
+ config ([`~transformers.PreTrainedConfig`]):
130
+ The model configuration.
131
+ device (`torch.device`):
132
+ The device to use for initialization of the inverse frequencies.
133
+ seq_len (`int`, *optional*):
134
+ The current sequence length. Unused for this type of RoPE.
135
+ Returns:
136
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
137
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
138
+ """
139
+ base = config.rope_parameters["rope_theta"]
140
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
141
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
142
+ dim = int(head_dim * partial_rotary_factor)
143
+
144
+ attention_factor = 1.0 # Unused in this type of RoPE
145
+
146
+ # Compute the inverse frequencies
147
+ inv_freq = 1.0 / (
148
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
149
+ )
150
+ return inv_freq, attention_factor
151
+
152
+ @torch.no_grad()
153
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
154
+ def forward(self, x, position_ids):
155
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
156
+ position_ids_expanded = position_ids[:, None, :].float()
157
+
158
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
159
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
160
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
161
+ emb = torch.cat((freqs, freqs), dim=-1)
162
+ cos = emb.cos() * self.attention_scaling
163
+ sin = emb.sin() * self.attention_scaling
164
+
165
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
166
+
167
+
168
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
169
+ """
170
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
171
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
172
+ """
173
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
174
+ if n_rep == 1:
175
+ return hidden_states
176
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
177
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
178
+
179
+
180
+ def eager_attention_forward(
181
+ module: nn.Module,
182
+ query: torch.Tensor,
183
+ key: torch.Tensor,
184
+ value: torch.Tensor,
185
+ attention_mask: torch.Tensor | None,
186
+ scaling: float,
187
+ dropout: float = 0.0,
188
+ **kwargs: Unpack[TransformersKwargs],
189
+ ):
190
+ key_states = repeat_kv(key, module.num_key_value_groups)
191
+ value_states = repeat_kv(value, module.num_key_value_groups)
192
+
193
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
194
+ if attention_mask is not None:
195
+ attn_weights = attn_weights + attention_mask
196
+
197
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
198
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
199
+ attn_output = torch.matmul(attn_weights, value_states)
200
+ attn_output = attn_output.transpose(1, 2).contiguous()
201
+
202
+ return attn_output, attn_weights
203
+
204
+
205
+ def rotate_half(x):
206
+ """Rotates half the hidden dims of the input."""
207
+ x1 = x[..., 0::2]
208
+ x2 = x[..., 1::2]
209
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
210
+
211
+
212
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
213
+ """Applies Rotary Position Embedding to the query and key tensors.
214
+
215
+ Args:
216
+ q (`torch.Tensor`): The query tensor.
217
+ k (`torch.Tensor`): The key tensor.
218
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
219
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
220
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
221
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
222
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
223
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
224
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
225
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
226
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
227
+ Returns:
228
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
229
+ """
230
+ cos = cos.unsqueeze(unsqueeze_dim)
231
+ sin = sin.unsqueeze(unsqueeze_dim)
232
+
233
+ # Interleave them instead of usual shape
234
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
235
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
236
+
237
+ # Keep half or full tensor for later concatenation
238
+ rotary_dim = cos.shape[-1]
239
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
240
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
241
+
242
+ # Apply rotary embeddings on the first half or full tensor
243
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
244
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
245
+
246
+ # Concatenate back to full shape
247
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
248
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
249
+ return q_embed, k_embed
250
+
251
+
252
+ @use_kernelized_func(apply_rotary_pos_emb)
253
+ class MoonshineAttention(nn.Module):
254
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
255
+
256
+ def __init__(
257
+ self,
258
+ config: MoonshineConfig,
259
+ layer_idx: int,
260
+ is_causal: bool,
261
+ num_attention_heads: int,
262
+ num_key_value_heads: int,
263
+ ):
264
+ super().__init__()
265
+ config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
266
+ self.config = config
267
+ self.layer_idx = layer_idx
268
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
269
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
270
+ self.scaling = self.head_dim**-0.5
271
+ self.attention_dropout = config.attention_dropout
272
+ self.is_causal = is_causal
273
+
274
+ self.q_proj = nn.Linear(
275
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
276
+ )
277
+ self.k_proj = nn.Linear(
278
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
279
+ )
280
+ self.v_proj = nn.Linear(
281
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
282
+ )
283
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
284
+
285
+ # Pad head dimension to the next specified multiple.
286
+ if self.config.pad_head_dim_to_multiple_of is not None:
287
+ target_multiple = self.config.pad_head_dim_to_multiple_of
288
+ target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
289
+ self.head_dim_padding = target_head_dim - self.head_dim
290
+ else:
291
+ self.head_dim_padding = 0
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.Tensor,
296
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
297
+ attention_mask: torch.Tensor | None = None,
298
+ past_key_values: Cache | None = None,
299
+ key_value_states: torch.Tensor | None = None,
300
+ **kwargs: Unpack[FlashAttentionKwargs],
301
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
302
+ bsz, q_len = hidden_states.shape[:-1]
303
+
304
+ query_states = (
305
+ self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
306
+ )
307
+
308
+ is_cross_attention = key_value_states is not None
309
+ if past_key_values is not None:
310
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
311
+ if is_cross_attention:
312
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
313
+ past_key_values.is_updated[self.layer_idx] = True
314
+ past_key_values = past_key_values.cross_attention_cache
315
+ else:
316
+ past_key_values = past_key_values.self_attention_cache
317
+
318
+ # use key_value_states if cross attention
319
+ current_states = key_value_states if key_value_states is not None else hidden_states
320
+ if is_cross_attention and past_key_values and is_updated:
321
+ key_states = past_key_values.layers[self.layer_idx].keys
322
+ value_states = past_key_values.layers[self.layer_idx].values
323
+ else:
324
+ key_states = (
325
+ self.k_proj(current_states)
326
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
327
+ .transpose(1, 2)
328
+ )
329
+ value_states = (
330
+ self.v_proj(current_states)
331
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
332
+ .transpose(1, 2)
333
+ )
334
+ if is_cross_attention and past_key_values is not None:
335
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
336
+
337
+ if not is_cross_attention:
338
+ cos, sin = position_embeddings
339
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
340
+
341
+ if past_key_values is not None:
342
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
343
+
344
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
345
+ self.config._attn_implementation, eager_attention_forward
346
+ )
347
+
348
+ is_causal = self.is_causal and attention_mask is None and q_len > 1
349
+
350
+ if self.head_dim_padding > 0:
351
+ query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
352
+ key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
353
+ value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
354
+
355
+ attn_output, attn_weights = attention_interface(
356
+ self,
357
+ query_states,
358
+ key_states,
359
+ value_states,
360
+ attention_mask,
361
+ dropout=0.0 if not self.training else self.attention_dropout,
362
+ scaling=self.scaling,
363
+ is_causal=is_causal,
364
+ **kwargs,
365
+ )
366
+
367
+ if self.head_dim_padding > 0:
368
+ attn_output = attn_output[..., : -self.head_dim_padding]
369
+
370
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
371
+ attn_output = self.o_proj(attn_output)
372
+ return attn_output, attn_weights
373
+
374
+
375
+ class MoonshineEncoderLayer(GradientCheckpointingLayer):
376
+ def __init__(self, config: MoonshineConfig, layer_idx: int):
377
+ super().__init__()
378
+ self.hidden_size = config.hidden_size
379
+
380
+ self.self_attn = MoonshineAttention(
381
+ config=config,
382
+ layer_idx=layer_idx,
383
+ is_causal=False,
384
+ num_attention_heads=config.encoder_num_attention_heads,
385
+ num_key_value_heads=config.encoder_num_key_value_heads,
386
+ )
387
+
388
+ self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
389
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
390
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
391
+
392
+ def forward(
393
+ self,
394
+ hidden_states: torch.Tensor,
395
+ attention_mask: torch.Tensor | None = None,
396
+ position_ids: torch.LongTensor | None = None,
397
+ past_key_values: Cache | None = None,
398
+ use_cache: bool | None = False,
399
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
400
+ **kwargs: Unpack[TransformersKwargs],
401
+ ) -> torch.Tensor:
402
+ residual = hidden_states
403
+ hidden_states = self.input_layernorm(hidden_states)
404
+ # Self Attention
405
+ hidden_states, _ = self.self_attn(
406
+ hidden_states=hidden_states,
407
+ attention_mask=attention_mask,
408
+ position_ids=position_ids,
409
+ past_key_values=past_key_values,
410
+ use_cache=use_cache,
411
+ position_embeddings=position_embeddings,
412
+ **kwargs,
413
+ )
414
+ hidden_states = residual + hidden_states
415
+
416
+ # Fully Connected
417
+ residual = hidden_states
418
+ hidden_states = self.post_attention_layernorm(hidden_states)
419
+ hidden_states = self.mlp(hidden_states)
420
+ hidden_states = residual + hidden_states
421
+ return hidden_states
422
+
423
+
424
+ class MoonshineDecoderLayer(GradientCheckpointingLayer):
425
+ def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
426
+ super().__init__()
427
+ self.hidden_size = config.hidden_size
428
+
429
+ self.self_attn = MoonshineAttention(
430
+ config=config,
431
+ layer_idx=layer_idx,
432
+ is_causal=True,
433
+ num_attention_heads=config.num_attention_heads,
434
+ num_key_value_heads=config.num_key_value_heads,
435
+ )
436
+ self.encoder_attn = MoonshineAttention(
437
+ config=config,
438
+ layer_idx=layer_idx,
439
+ is_causal=False,
440
+ num_attention_heads=config.num_attention_heads,
441
+ num_key_value_heads=config.num_key_value_heads,
442
+ )
443
+
444
+ self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
445
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
446
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
447
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
448
+
449
+ def forward(
450
+ self,
451
+ hidden_states: torch.Tensor,
452
+ attention_mask: torch.Tensor | None = None,
453
+ encoder_hidden_states: torch.Tensor | None = None,
454
+ encoder_attention_mask: torch.Tensor | None = None,
455
+ position_ids: torch.LongTensor | None = None,
456
+ encoder_position_ids: torch.LongTensor | None = None,
457
+ past_key_values: Cache | None = None,
458
+ use_cache: bool | None = False,
459
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
460
+ encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
461
+ **kwargs: Unpack[TransformersKwargs],
462
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
463
+ residual = hidden_states
464
+ hidden_states = self.input_layernorm(hidden_states)
465
+
466
+ hidden_states, _ = self.self_attn(
467
+ hidden_states=hidden_states,
468
+ attention_mask=attention_mask,
469
+ position_ids=position_ids,
470
+ past_key_values=past_key_values,
471
+ use_cache=use_cache,
472
+ position_embeddings=position_embeddings,
473
+ **kwargs,
474
+ )
475
+ hidden_states = residual + hidden_states
476
+
477
+ if encoder_hidden_states is not None:
478
+ residual = hidden_states
479
+ hidden_states = self.post_attention_layernorm(hidden_states)
480
+ hidden_states, _ = self.encoder_attn(
481
+ hidden_states=hidden_states,
482
+ key_value_states=encoder_hidden_states,
483
+ attention_mask=encoder_attention_mask,
484
+ past_key_values=past_key_values,
485
+ use_cache=use_cache,
486
+ )
487
+ hidden_states = residual + hidden_states
488
+
489
+ residual = hidden_states
490
+ hidden_states = self.final_layernorm(hidden_states)
491
+ hidden_states = self.mlp(hidden_states)
492
+ hidden_states = residual + hidden_states
493
+ return hidden_states
494
+
495
+
496
+ @auto_docstring
497
+ class MoonshinePreTrainedModel(PreTrainedModel):
498
+ config: MoonshineConfig
499
+ base_model_prefix = "model"
500
+ main_input_name = "input_values"
501
+ input_modalities = "audio"
502
+ supports_gradient_checkpointing = True
503
+ _no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
504
+ _supports_flash_attn = True
505
+ _supports_sdpa = True
506
+
507
+ _can_compile_fullgraph = True
508
+ # TODO arthur, how do we separate when it cross / self coming from different layer?
509
+
510
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
511
+ """
512
+ Computes the output length of the convolutional layers
513
+ """
514
+ output_conv1_length = int((input_lengths - 127) / 64 + 1)
515
+ output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
516
+ output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
517
+
518
+ return output_conv3_length
519
+
520
+
521
+ class MoonshineEncoder(MoonshinePreTrainedModel):
522
+ """
523
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
524
+
525
+ Args:
526
+ config: MoonshineConfig
527
+ """
528
+
529
+ main_input_name = "input_values"
530
+ _can_record_outputs = {
531
+ "attentions": MoonshineAttention,
532
+ "hidden_states": MoonshineEncoderLayer,
533
+ }
534
+
535
+ def __init__(self, config: MoonshineConfig):
536
+ super().__init__(config)
537
+ self.config = config
538
+ embed_dim = config.hidden_size
539
+
540
+ self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
541
+ self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
542
+ self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
543
+ self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
544
+
545
+ self.layers = nn.ModuleList(
546
+ [MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
547
+ )
548
+ self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
549
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
550
+ self.gradient_checkpointing = False
551
+ self.post_init()
552
+
553
+ def get_input_embeddings(self) -> nn.Module:
554
+ return self.conv1
555
+
556
+ def set_input_embeddings(self, value: nn.Module):
557
+ self.conv1 = value
558
+
559
+ @merge_with_config_defaults
560
+ @capture_outputs
561
+ def forward(
562
+ self,
563
+ input_values: torch.FloatTensor,
564
+ attention_mask: torch.Tensor | None = None,
565
+ **kwargs: Unpack[TransformersKwargs],
566
+ ) -> tuple | BaseModelOutputWithPast:
567
+ r"""
568
+ Args:
569
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
570
+ Float values of the raw speech waveform. Raw speech waveform can be
571
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
572
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
573
+ the soundfile library (`pip install soundfile`). To prepare the array into
574
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
575
+ and conversion into a tensor of type `torch.FloatTensor`.
576
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
577
+ Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
578
+ - 1 for tokens that are **not masked**,
579
+ - 0 for tokens that are **masked**.
580
+ [What are attention masks?](../glossary#attention-mask)
581
+ """
582
+ input_values = input_values.unsqueeze(1)
583
+ hidden_states = nn.functional.tanh(self.conv1(input_values))
584
+ hidden_states = self.groupnorm(hidden_states)
585
+ hidden_states = nn.functional.gelu(self.conv2(hidden_states))
586
+ hidden_states = nn.functional.gelu(self.conv3(hidden_states))
587
+ hidden_states = hidden_states.permute(0, 2, 1)
588
+
589
+ # attention mask downsampling
590
+ output_attention_mask = None
591
+ if attention_mask is not None:
592
+ mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
593
+ downsample_stride = 64 * 3 * 2 # conv strides
594
+ attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
595
+ output_attention_mask = attention_mask
596
+
597
+ attention_mask = create_bidirectional_mask(
598
+ config=self.config,
599
+ inputs_embeds=hidden_states,
600
+ attention_mask=attention_mask,
601
+ encoder_hidden_states=hidden_states,
602
+ )
603
+
604
+ position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
605
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
606
+
607
+ for encoder_layer in self.layers:
608
+ hidden_states = encoder_layer(
609
+ hidden_states,
610
+ attention_mask=attention_mask,
611
+ position_ids=position_ids,
612
+ position_embeddings=position_embeddings,
613
+ **kwargs,
614
+ )
615
+
616
+ hidden_states = self.layer_norm(hidden_states)
617
+
618
+ return MoonshineEncoderModelOutput(
619
+ last_hidden_state=hidden_states,
620
+ attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
621
+ )
622
+
623
+
624
+ @auto_docstring
625
+ class MoonshineDecoder(MoonshinePreTrainedModel):
626
+ main_input_name = "input_ids"
627
+ _can_record_outputs = {
628
+ "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
629
+ "hidden_states": MoonshineDecoderLayer,
630
+ "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
631
+ }
632
+
633
+ def __init__(self, config: MoonshineConfig):
634
+ super().__init__(config)
635
+ self.padding_idx = config.pad_token_id
636
+ self.vocab_size = config.vocab_size
637
+
638
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
639
+ self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
640
+ self.norm = nn.LayerNorm(config.hidden_size, bias=False)
641
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
642
+ self.gradient_checkpointing = False
643
+
644
+ # Initialize weights and apply final processing
645
+ self.post_init()
646
+
647
+ @merge_with_config_defaults
648
+ @capture_outputs
649
+ def forward(
650
+ self,
651
+ input_ids: torch.LongTensor | None = None,
652
+ attention_mask: torch.Tensor | None = None,
653
+ position_ids: torch.LongTensor | None = None,
654
+ past_key_values: Cache | None = None,
655
+ inputs_embeds: torch.FloatTensor | None = None,
656
+ use_cache: bool | None = None,
657
+ encoder_hidden_states: torch.FloatTensor | None = None,
658
+ encoder_attention_mask: torch.Tensor | None = None,
659
+ **kwargs: Unpack[TransformersKwargs],
660
+ ) -> tuple | BaseModelOutputWithPast:
661
+ r"""
662
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
663
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
664
+ of the decoder.
665
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
666
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
667
+ - 1 for tokens that are **not masked**,
668
+ - 0 for tokens that are **masked**.
669
+ [What are attention masks?](../glossary#attention-mask)
670
+ """
671
+ if (input_ids is None) ^ (inputs_embeds is not None):
672
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
673
+
674
+ if inputs_embeds is None:
675
+ inputs_embeds = self.embed_tokens(input_ids)
676
+
677
+ if use_cache and past_key_values is None:
678
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
679
+
680
+ if position_ids is None:
681
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
682
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
683
+ position_ids = position_ids.unsqueeze(0)
684
+
685
+ causal_mask = create_causal_mask(
686
+ config=self.config,
687
+ inputs_embeds=inputs_embeds,
688
+ attention_mask=attention_mask,
689
+ past_key_values=past_key_values,
690
+ position_ids=position_ids,
691
+ )
692
+ encoder_attention_mask = create_bidirectional_mask(
693
+ config=self.config,
694
+ inputs_embeds=inputs_embeds,
695
+ attention_mask=encoder_attention_mask,
696
+ encoder_hidden_states=encoder_hidden_states,
697
+ )
698
+
699
+ hidden_states = inputs_embeds
700
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
701
+
702
+ for decoder_layer in self.layers:
703
+ hidden_states = decoder_layer(
704
+ hidden_states,
705
+ causal_mask,
706
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
707
+ encoder_attention_mask=encoder_attention_mask,
708
+ position_ids=position_ids,
709
+ past_key_values=past_key_values,
710
+ use_cache=use_cache,
711
+ position_embeddings=position_embeddings,
712
+ **kwargs,
713
+ )
714
+
715
+ hidden_states = self.norm(hidden_states)
716
+
717
+ return BaseModelOutputWithPastAndCrossAttentions(
718
+ last_hidden_state=hidden_states,
719
+ past_key_values=past_key_values if use_cache else None,
720
+ )
721
+
722
+
723
+ @auto_docstring
724
+ class MoonshineModel(MoonshinePreTrainedModel):
725
+ def __init__(self, config: MoonshineConfig):
726
+ super().__init__(config)
727
+
728
+ self.encoder = MoonshineEncoder(config)
729
+ self.decoder = MoonshineDecoder(config)
730
+ # Initialize weights and apply final processing
731
+ self.post_init()
732
+
733
+ def get_input_embeddings(self):
734
+ return self.decoder.embed_tokens
735
+
736
+ def set_input_embeddings(self, value):
737
+ self.decoder.embed_tokens = value
738
+
739
+ def freeze_encoder(self):
740
+ """
741
+ Calling this function will disable the gradient computation for the Moonshine encoder so that its parameters will
742
+ not be updated during training.
743
+ """
744
+ self.encoder._freeze_parameters()
745
+
746
+ def _mask_input_features(self):
747
+ """
748
+ Masks extracted features along time axis and/or along feature axis according to
749
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
750
+ """
751
+ raise AttributeError("Not needed for Moonshine")
752
+
753
+ @can_return_tuple
754
+ @auto_docstring
755
+ def forward(
756
+ self,
757
+ input_values: torch.FloatTensor | None = None,
758
+ attention_mask: torch.LongTensor | None = None,
759
+ decoder_input_ids: torch.LongTensor | None = None,
760
+ decoder_attention_mask: torch.LongTensor | None = None,
761
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
762
+ past_key_values: EncoderDecoderCache | None = None,
763
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
764
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
765
+ use_cache: bool | None = None,
766
+ **kwargs: Unpack[TransformersKwargs],
767
+ ) -> Seq2SeqModelOutput:
768
+ r"""
769
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
770
+ Float values of the raw speech waveform. Raw speech waveform can be
771
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
772
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
773
+ the soundfile library (`pip install soundfile`). To prepare the array into
774
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
775
+ and conversion into a tensor of type `torch.FloatTensor`.
776
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
777
+ Indices of positions of each input sequence tokens in the position embeddings.
778
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
779
+
780
+ Example:
781
+
782
+ ```python
783
+ >>> import torch
784
+ >>> from transformers import AutoFeatureExtractor, MoonshineModel
785
+ >>> from datasets import load_dataset
786
+
787
+ >>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
788
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
789
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
790
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
791
+ >>> input_values = inputs.input_values
792
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
793
+ >>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
794
+ >>> list(last_hidden_state.shape)
795
+ [1, 2, 288]
796
+ ```
797
+ """
798
+ if encoder_outputs is None:
799
+ encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
800
+
801
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
802
+ input_ids=decoder_input_ids,
803
+ attention_mask=decoder_attention_mask,
804
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
805
+ encoder_attention_mask=encoder_outputs.attention_mask,
806
+ past_key_values=past_key_values,
807
+ inputs_embeds=decoder_inputs_embeds,
808
+ position_ids=decoder_position_ids,
809
+ use_cache=use_cache,
810
+ **kwargs,
811
+ )
812
+
813
+ return Seq2SeqModelOutput(
814
+ last_hidden_state=decoder_outputs.last_hidden_state,
815
+ past_key_values=decoder_outputs.past_key_values,
816
+ decoder_hidden_states=decoder_outputs.hidden_states,
817
+ decoder_attentions=decoder_outputs.attentions,
818
+ cross_attentions=decoder_outputs.cross_attentions,
819
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
820
+ encoder_hidden_states=encoder_outputs.hidden_states,
821
+ encoder_attentions=encoder_outputs.attentions,
822
+ )
823
+
824
+
825
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
826
+ """
827
+ Shift input ids one token to the right.
828
+ """
829
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
830
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
831
+ shifted_input_ids[:, 0] = decoder_start_token_id
832
+
833
+ if pad_token_id is None:
834
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
835
+ # replace possible -100 values in labels by `pad_token_id`
836
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
837
+
838
+ return shifted_input_ids
839
+
840
+
841
+ @auto_docstring(
842
+ custom_intro="""
843
+ The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
844
+ """
845
+ )
846
+ class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
847
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
848
+
849
+ def __init__(self, config: MoonshineConfig):
850
+ super().__init__(config)
851
+ self.model = MoonshineModel(config)
852
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
853
+
854
+ # Initialize weights and apply final processing
855
+ self.post_init()
856
+
857
+ def get_output_embeddings(self):
858
+ return self.proj_out
859
+
860
+ def set_output_embeddings(self, new_embeddings):
861
+ self.proj_out = new_embeddings
862
+
863
+ def get_input_embeddings(self) -> nn.Module:
864
+ return self.model.get_input_embeddings()
865
+
866
+ @can_return_tuple
867
+ @auto_docstring
868
+ def forward(
869
+ self,
870
+ input_values: torch.FloatTensor | None = None,
871
+ attention_mask: torch.LongTensor | None = None,
872
+ decoder_input_ids: torch.LongTensor | None = None,
873
+ decoder_attention_mask: torch.LongTensor | None = None,
874
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
875
+ past_key_values: EncoderDecoderCache | None = None,
876
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
877
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
878
+ use_cache: bool | None = None,
879
+ labels: torch.LongTensor | None = None,
880
+ **kwargs: Unpack[TransformersKwargs],
881
+ ) -> Seq2SeqLMOutput:
882
+ r"""
883
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
884
+ Float values of the raw speech waveform. Raw speech waveform can be
885
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
886
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
887
+ the soundfile library (`pip install soundfile`). To prepare the array into
888
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
889
+ and conversion into a tensor of type `torch.FloatTensor`.
890
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
891
+ Indices of positions of each input sequence tokens in the position embeddings.
892
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
893
+
894
+ Example:
895
+
896
+ ```python
897
+ >>> import torch
898
+ >>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
899
+ >>> from datasets import load_dataset
900
+
901
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
902
+ >>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
903
+
904
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
905
+
906
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
907
+ >>> input_values = inputs.input_values
908
+
909
+ >>> generated_ids = model.generate(input_values, max_new_tokens=100)
910
+
911
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
912
+ >>> transcription
913
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
914
+ ```"""
915
+
916
+ if labels is not None:
917
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
918
+ decoder_input_ids = shift_tokens_right(
919
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
920
+ )
921
+
922
+ outputs: Seq2SeqModelOutput = self.model(
923
+ input_values,
924
+ attention_mask=attention_mask,
925
+ decoder_input_ids=decoder_input_ids,
926
+ encoder_outputs=encoder_outputs,
927
+ decoder_attention_mask=decoder_attention_mask,
928
+ past_key_values=past_key_values,
929
+ decoder_inputs_embeds=decoder_inputs_embeds,
930
+ decoder_position_ids=decoder_position_ids,
931
+ use_cache=use_cache,
932
+ **kwargs,
933
+ )
934
+ logits = self.proj_out(outputs.last_hidden_state)
935
+
936
+ loss = None
937
+ if labels is not None:
938
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
939
+
940
+ return Seq2SeqLMOutput(
941
+ loss=loss,
942
+ logits=logits,
943
+ past_key_values=outputs.past_key_values,
944
+ decoder_hidden_states=outputs.decoder_hidden_states,
945
+ decoder_attentions=outputs.decoder_attentions,
946
+ cross_attentions=outputs.cross_attentions,
947
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
948
+ encoder_hidden_states=outputs.encoder_hidden_states,
949
+ encoder_attentions=outputs.encoder_attentions,
950
+ )
951
+
952
+
953
+ __all__ = ["MoonshineModel", "MoonshinePreTrainedModel", "MoonshineForConditionalGeneration"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine/modular_moonshine.py ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from huggingface_hub.dataclasses import strict
21
+
22
+ from ...activations import ACT2FN
23
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
24
+ from ...configuration_utils import PreTrainedConfig
25
+ from ...generation import GenerationMixin
26
+ from ...masking_utils import create_bidirectional_mask, create_causal_mask
27
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPast,
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ Seq2SeqLMOutput,
34
+ Seq2SeqModelOutput,
35
+ )
36
+ from ...modeling_rope_utils import RopeParameters
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
40
+ from ...utils.generic import merge_with_config_defaults
41
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
42
+ from ..glm.modeling_glm import GlmAttention, GlmRotaryEmbedding, apply_rotary_pos_emb
43
+ from ..llama.modeling_llama import LlamaDecoderLayer, LlamaModel, eager_attention_forward
44
+ from ..whisper.modeling_whisper import WhisperModel, shift_tokens_right
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ @auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
51
+ @strict
52
+ class MoonshineConfig(PreTrainedConfig):
53
+ r"""
54
+ encoder_num_key_value_heads (`int`, *optional*):
55
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
56
+ `encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
57
+ `encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
58
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
59
+ by meanpooling all the original heads within that group. For more details, check out [this
60
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
61
+ `num_attention_heads`.
62
+ decoder_num_key_value_heads (`int`, *optional*):
63
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
64
+ `decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
65
+ `decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
66
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
67
+ by meanpooling all the original heads within that group. For more details, check out [this
68
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
69
+ `decoder_num_attention_heads`.
70
+ pad_head_dim_to_multiple_of (`int`, *optional*):
71
+ Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
72
+ optimized attention implementations.
73
+ encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
74
+ The non-linear activation function (function or string) in the encoder.
75
+ decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
76
+ The non-linear activation function (function or string) in the decoder.
77
+
78
+ Example:
79
+
80
+ ```python
81
+ >>> from transformers import MoonshineModel, MoonshineConfig
82
+
83
+ >>> # Initializing a Moonshine style configuration
84
+ >>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
85
+
86
+ >>> # Initializing a model from the configuration
87
+ >>> model = MoonshineModel(configuration)
88
+
89
+ >>> # Accessing the model configuration
90
+ >>> configuration = model.config
91
+ ```"""
92
+
93
+ model_type = "moonshine"
94
+ keys_to_ignore_at_inference = ["past_key_values"]
95
+ attribute_map = {
96
+ "num_key_value_heads": "decoder_num_key_value_heads",
97
+ "num_attention_heads": "decoder_num_attention_heads",
98
+ "num_hidden_layers": "decoder_num_hidden_layers",
99
+ "hidden_act": "decoder_hidden_act",
100
+ }
101
+
102
+ vocab_size: int = 32768
103
+ hidden_size: int = 288
104
+ intermediate_size: int = 1152
105
+ encoder_num_hidden_layers: int = 6
106
+ decoder_num_hidden_layers: int = 6
107
+ encoder_num_attention_heads: int = 8
108
+ decoder_num_attention_heads: int = 8
109
+ encoder_num_key_value_heads: int | None = None
110
+ decoder_num_key_value_heads: int | None = None
111
+ pad_head_dim_to_multiple_of: int | None = None
112
+ encoder_hidden_act: str = "gelu"
113
+ decoder_hidden_act: str = "silu"
114
+ max_position_embeddings: int = 512
115
+ initializer_range: float = 0.02
116
+ decoder_start_token_id: int = 1
117
+ use_cache: bool = True
118
+ rope_parameters: RopeParameters | dict | None = None
119
+ is_encoder_decoder: bool = True
120
+ attention_bias: bool = False
121
+ attention_dropout: float | int = 0.0
122
+ bos_token_id: int | None = 1
123
+ eos_token_id: int | list[int] | None = 2
124
+ pad_token_id: int | None = None
125
+ tie_word_embeddings: bool = True
126
+
127
+ def __post_init__(self, **kwargs):
128
+ if self.encoder_num_key_value_heads is None:
129
+ self.encoder_num_key_value_heads = self.encoder_num_attention_heads
130
+
131
+ if self.decoder_num_key_value_heads is None:
132
+ self.decoder_num_key_value_heads = self.decoder_num_attention_heads
133
+
134
+ kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
135
+ super().__post_init__(**kwargs)
136
+
137
+
138
+ @auto_docstring(
139
+ custom_intro="""
140
+ Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
141
+ """
142
+ )
143
+ @dataclass
144
+ class MoonshineEncoderModelOutput(BaseModelOutput):
145
+ r"""
146
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
147
+ Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
148
+ sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
149
+
150
+ - 1 for tokens that are **not masked**,
151
+ - 0 for tokens that are **masked**.
152
+ """
153
+
154
+ attention_mask: torch.Tensor | None = None
155
+
156
+
157
+ class MoonshineEncoderMLP(nn.Module):
158
+ def __init__(self, config, hidden_act):
159
+ super().__init__()
160
+ self.config = config
161
+ self.activation_fn = ACT2FN[hidden_act]
162
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
163
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
164
+
165
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
166
+ hidden_states = self.fc1(hidden_states)
167
+ hidden_states = self.activation_fn(hidden_states)
168
+ hidden_states = self.fc2(hidden_states)
169
+ return hidden_states
170
+
171
+
172
+ class MoonshineDecoderMLP(nn.Module):
173
+ def __init__(self, config, hidden_act):
174
+ super().__init__()
175
+ self.config = config
176
+ self.activation_fn = ACT2FN[hidden_act]
177
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
178
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
179
+
180
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
181
+ hidden_states = self.fc1(hidden_states)
182
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
183
+ hidden_states = self.activation_fn(gate) * hidden_states
184
+ hidden_states = self.fc2(hidden_states)
185
+ return hidden_states
186
+
187
+
188
+ class MoonshineRotaryEmbedding(GlmRotaryEmbedding):
189
+ pass
190
+
191
+
192
+ class MoonshineAttention(GlmAttention):
193
+ def __init__(
194
+ self,
195
+ config: MoonshineConfig,
196
+ layer_idx: int,
197
+ is_causal: bool,
198
+ num_attention_heads: int,
199
+ num_key_value_heads: int,
200
+ ):
201
+ config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
202
+ super().__init__(config, layer_idx)
203
+ self.is_causal = is_causal
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+
206
+ # Pad head dimension to the next specified multiple.
207
+ if self.config.pad_head_dim_to_multiple_of is not None:
208
+ target_multiple = self.config.pad_head_dim_to_multiple_of
209
+ target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
210
+ self.head_dim_padding = target_head_dim - self.head_dim
211
+ else:
212
+ self.head_dim_padding = 0
213
+
214
+ def forward(
215
+ self,
216
+ hidden_states: torch.Tensor,
217
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
218
+ attention_mask: torch.Tensor | None = None,
219
+ past_key_values: Cache | None = None,
220
+ key_value_states: torch.Tensor | None = None,
221
+ **kwargs: Unpack[FlashAttentionKwargs],
222
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
223
+ bsz, q_len = hidden_states.shape[:-1]
224
+
225
+ query_states = (
226
+ self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
227
+ )
228
+
229
+ is_cross_attention = key_value_states is not None
230
+ if past_key_values is not None:
231
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
232
+ if is_cross_attention:
233
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
234
+ past_key_values.is_updated[self.layer_idx] = True
235
+ past_key_values = past_key_values.cross_attention_cache
236
+ else:
237
+ past_key_values = past_key_values.self_attention_cache
238
+
239
+ # use key_value_states if cross attention
240
+ current_states = key_value_states if key_value_states is not None else hidden_states
241
+ if is_cross_attention and past_key_values and is_updated:
242
+ key_states = past_key_values.layers[self.layer_idx].keys
243
+ value_states = past_key_values.layers[self.layer_idx].values
244
+ else:
245
+ key_states = (
246
+ self.k_proj(current_states)
247
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
248
+ .transpose(1, 2)
249
+ )
250
+ value_states = (
251
+ self.v_proj(current_states)
252
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
253
+ .transpose(1, 2)
254
+ )
255
+ if is_cross_attention and past_key_values is not None:
256
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
257
+
258
+ if not is_cross_attention:
259
+ cos, sin = position_embeddings
260
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
261
+
262
+ if past_key_values is not None:
263
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
264
+
265
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
266
+ self.config._attn_implementation, eager_attention_forward
267
+ )
268
+
269
+ is_causal = self.is_causal and attention_mask is None and q_len > 1
270
+
271
+ if self.head_dim_padding > 0:
272
+ query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
273
+ key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
274
+ value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
275
+
276
+ attn_output, attn_weights = attention_interface(
277
+ self,
278
+ query_states,
279
+ key_states,
280
+ value_states,
281
+ attention_mask,
282
+ dropout=0.0 if not self.training else self.attention_dropout,
283
+ scaling=self.scaling,
284
+ is_causal=is_causal,
285
+ **kwargs,
286
+ )
287
+
288
+ if self.head_dim_padding > 0:
289
+ attn_output = attn_output[..., : -self.head_dim_padding]
290
+
291
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
292
+ attn_output = self.o_proj(attn_output)
293
+ return attn_output, attn_weights
294
+
295
+
296
+ class MoonshineEncoderLayer(LlamaDecoderLayer):
297
+ def __init__(self, config: MoonshineConfig, layer_idx: int):
298
+ super().__init__(config, layer_idx)
299
+
300
+ self.self_attn = MoonshineAttention(
301
+ config=config,
302
+ layer_idx=layer_idx,
303
+ is_causal=False,
304
+ num_attention_heads=config.encoder_num_attention_heads,
305
+ num_key_value_heads=config.encoder_num_key_value_heads,
306
+ )
307
+
308
+ self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
309
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
310
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
311
+
312
+
313
+ class MoonshineDecoderLayer(GradientCheckpointingLayer):
314
+ def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
315
+ super().__init__()
316
+ self.hidden_size = config.hidden_size
317
+
318
+ self.self_attn = MoonshineAttention(
319
+ config=config,
320
+ layer_idx=layer_idx,
321
+ is_causal=True,
322
+ num_attention_heads=config.num_attention_heads,
323
+ num_key_value_heads=config.num_key_value_heads,
324
+ )
325
+ self.encoder_attn = MoonshineAttention(
326
+ config=config,
327
+ layer_idx=layer_idx,
328
+ is_causal=False,
329
+ num_attention_heads=config.num_attention_heads,
330
+ num_key_value_heads=config.num_key_value_heads,
331
+ )
332
+
333
+ self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
334
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
335
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
336
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
337
+
338
+ def forward(
339
+ self,
340
+ hidden_states: torch.Tensor,
341
+ attention_mask: torch.Tensor | None = None,
342
+ encoder_hidden_states: torch.Tensor | None = None,
343
+ encoder_attention_mask: torch.Tensor | None = None,
344
+ position_ids: torch.LongTensor | None = None,
345
+ encoder_position_ids: torch.LongTensor | None = None,
346
+ past_key_values: Cache | None = None,
347
+ use_cache: bool | None = False,
348
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
349
+ encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
350
+ **kwargs: Unpack[TransformersKwargs],
351
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
352
+ residual = hidden_states
353
+ hidden_states = self.input_layernorm(hidden_states)
354
+
355
+ hidden_states, _ = self.self_attn(
356
+ hidden_states=hidden_states,
357
+ attention_mask=attention_mask,
358
+ position_ids=position_ids,
359
+ past_key_values=past_key_values,
360
+ use_cache=use_cache,
361
+ position_embeddings=position_embeddings,
362
+ **kwargs,
363
+ )
364
+ hidden_states = residual + hidden_states
365
+
366
+ if encoder_hidden_states is not None:
367
+ residual = hidden_states
368
+ hidden_states = self.post_attention_layernorm(hidden_states)
369
+ hidden_states, _ = self.encoder_attn(
370
+ hidden_states=hidden_states,
371
+ key_value_states=encoder_hidden_states,
372
+ attention_mask=encoder_attention_mask,
373
+ past_key_values=past_key_values,
374
+ use_cache=use_cache,
375
+ )
376
+ hidden_states = residual + hidden_states
377
+
378
+ residual = hidden_states
379
+ hidden_states = self.final_layernorm(hidden_states)
380
+ hidden_states = self.mlp(hidden_states)
381
+ hidden_states = residual + hidden_states
382
+ return hidden_states
383
+
384
+
385
+ @auto_docstring
386
+ class MoonshinePreTrainedModel(PreTrainedModel):
387
+ config: MoonshineConfig
388
+ base_model_prefix = "model"
389
+ main_input_name = "input_values"
390
+ input_modalities = "audio"
391
+ supports_gradient_checkpointing = True
392
+ _no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
393
+ _supports_flash_attn = True
394
+ _supports_sdpa = True
395
+
396
+ _can_compile_fullgraph = True
397
+ # TODO arthur, how do we separate when it cross / self coming from different layer?
398
+
399
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
400
+ """
401
+ Computes the output length of the convolutional layers
402
+ """
403
+ output_conv1_length = int((input_lengths - 127) / 64 + 1)
404
+ output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
405
+ output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
406
+
407
+ return output_conv3_length
408
+
409
+
410
+ class MoonshineEncoder(MoonshinePreTrainedModel):
411
+ """
412
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
413
+
414
+ Args:
415
+ config: MoonshineConfig
416
+ """
417
+
418
+ main_input_name = "input_values"
419
+ _can_record_outputs = {
420
+ "attentions": MoonshineAttention,
421
+ "hidden_states": MoonshineEncoderLayer,
422
+ }
423
+
424
+ def __init__(self, config: MoonshineConfig):
425
+ super().__init__(config)
426
+ self.config = config
427
+ embed_dim = config.hidden_size
428
+
429
+ self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
430
+ self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
431
+ self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
432
+ self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
433
+
434
+ self.layers = nn.ModuleList(
435
+ [MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
436
+ )
437
+ self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
438
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
439
+ self.gradient_checkpointing = False
440
+ self.post_init()
441
+
442
+ def get_input_embeddings(self) -> nn.Module:
443
+ return self.conv1
444
+
445
+ def set_input_embeddings(self, value: nn.Module):
446
+ self.conv1 = value
447
+
448
+ @merge_with_config_defaults
449
+ @capture_outputs
450
+ def forward(
451
+ self,
452
+ input_values: torch.FloatTensor,
453
+ attention_mask: torch.Tensor | None = None,
454
+ **kwargs: Unpack[TransformersKwargs],
455
+ ) -> tuple | BaseModelOutputWithPast:
456
+ r"""
457
+ Args:
458
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
459
+ Float values of the raw speech waveform. Raw speech waveform can be
460
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
461
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
462
+ the soundfile library (`pip install soundfile`). To prepare the array into
463
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
464
+ and conversion into a tensor of type `torch.FloatTensor`.
465
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
466
+ Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
467
+ - 1 for tokens that are **not masked**,
468
+ - 0 for tokens that are **masked**.
469
+ [What are attention masks?](../glossary#attention-mask)
470
+ """
471
+ input_values = input_values.unsqueeze(1)
472
+ hidden_states = nn.functional.tanh(self.conv1(input_values))
473
+ hidden_states = self.groupnorm(hidden_states)
474
+ hidden_states = nn.functional.gelu(self.conv2(hidden_states))
475
+ hidden_states = nn.functional.gelu(self.conv3(hidden_states))
476
+ hidden_states = hidden_states.permute(0, 2, 1)
477
+
478
+ # attention mask downsampling
479
+ output_attention_mask = None
480
+ if attention_mask is not None:
481
+ mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
482
+ downsample_stride = 64 * 3 * 2 # conv strides
483
+ attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
484
+ output_attention_mask = attention_mask
485
+
486
+ attention_mask = create_bidirectional_mask(
487
+ config=self.config,
488
+ inputs_embeds=hidden_states,
489
+ attention_mask=attention_mask,
490
+ encoder_hidden_states=hidden_states,
491
+ )
492
+
493
+ position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
494
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
495
+
496
+ for encoder_layer in self.layers:
497
+ hidden_states = encoder_layer(
498
+ hidden_states,
499
+ attention_mask=attention_mask,
500
+ position_ids=position_ids,
501
+ position_embeddings=position_embeddings,
502
+ **kwargs,
503
+ )
504
+
505
+ hidden_states = self.layer_norm(hidden_states)
506
+
507
+ return MoonshineEncoderModelOutput(
508
+ last_hidden_state=hidden_states,
509
+ attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
510
+ )
511
+
512
+
513
+ class MoonshineDecoder(LlamaModel):
514
+ main_input_name = "input_ids"
515
+ _can_record_outputs = {
516
+ "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
517
+ "hidden_states": MoonshineDecoderLayer,
518
+ "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
519
+ }
520
+
521
+ def __init__(self, config: MoonshineConfig):
522
+ super().__init__(config)
523
+ self.norm = nn.LayerNorm(config.hidden_size, bias=False)
524
+ self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
525
+
526
+ @merge_with_config_defaults
527
+ @capture_outputs
528
+ def forward(
529
+ self,
530
+ input_ids: torch.LongTensor | None = None,
531
+ attention_mask: torch.Tensor | None = None,
532
+ position_ids: torch.LongTensor | None = None,
533
+ past_key_values: Cache | None = None,
534
+ inputs_embeds: torch.FloatTensor | None = None,
535
+ use_cache: bool | None = None,
536
+ encoder_hidden_states: torch.FloatTensor | None = None,
537
+ encoder_attention_mask: torch.Tensor | None = None,
538
+ **kwargs: Unpack[TransformersKwargs],
539
+ ) -> tuple | BaseModelOutputWithPast:
540
+ r"""
541
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
542
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
543
+ of the decoder.
544
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
545
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
546
+ - 1 for tokens that are **not masked**,
547
+ - 0 for tokens that are **masked**.
548
+ [What are attention masks?](../glossary#attention-mask)
549
+ """
550
+ if (input_ids is None) ^ (inputs_embeds is not None):
551
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
552
+
553
+ if inputs_embeds is None:
554
+ inputs_embeds = self.embed_tokens(input_ids)
555
+
556
+ if use_cache and past_key_values is None:
557
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
558
+
559
+ if position_ids is None:
560
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
561
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
562
+ position_ids = position_ids.unsqueeze(0)
563
+
564
+ causal_mask = create_causal_mask(
565
+ config=self.config,
566
+ inputs_embeds=inputs_embeds,
567
+ attention_mask=attention_mask,
568
+ past_key_values=past_key_values,
569
+ position_ids=position_ids,
570
+ )
571
+ encoder_attention_mask = create_bidirectional_mask(
572
+ config=self.config,
573
+ inputs_embeds=inputs_embeds,
574
+ attention_mask=encoder_attention_mask,
575
+ encoder_hidden_states=encoder_hidden_states,
576
+ )
577
+
578
+ hidden_states = inputs_embeds
579
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
580
+
581
+ for decoder_layer in self.layers:
582
+ hidden_states = decoder_layer(
583
+ hidden_states,
584
+ causal_mask,
585
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
586
+ encoder_attention_mask=encoder_attention_mask,
587
+ position_ids=position_ids,
588
+ past_key_values=past_key_values,
589
+ use_cache=use_cache,
590
+ position_embeddings=position_embeddings,
591
+ **kwargs,
592
+ )
593
+
594
+ hidden_states = self.norm(hidden_states)
595
+
596
+ return BaseModelOutputWithPastAndCrossAttentions(
597
+ last_hidden_state=hidden_states,
598
+ past_key_values=past_key_values if use_cache else None,
599
+ )
600
+
601
+
602
+ class MoonshineModel(WhisperModel):
603
+ def _mask_input_features(self):
604
+ raise AttributeError("Not needed for Moonshine")
605
+
606
+ @can_return_tuple
607
+ @auto_docstring
608
+ def forward(
609
+ self,
610
+ input_values: torch.FloatTensor | None = None,
611
+ attention_mask: torch.LongTensor | None = None,
612
+ decoder_input_ids: torch.LongTensor | None = None,
613
+ decoder_attention_mask: torch.LongTensor | None = None,
614
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
615
+ past_key_values: EncoderDecoderCache | None = None,
616
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
617
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
618
+ use_cache: bool | None = None,
619
+ **kwargs: Unpack[TransformersKwargs],
620
+ ) -> Seq2SeqModelOutput:
621
+ r"""
622
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
623
+ Float values of the raw speech waveform. Raw speech waveform can be
624
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
625
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
626
+ the soundfile library (`pip install soundfile`). To prepare the array into
627
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
628
+ and conversion into a tensor of type `torch.FloatTensor`.
629
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
630
+ Indices of positions of each input sequence tokens in the position embeddings.
631
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
632
+
633
+ Example:
634
+
635
+ ```python
636
+ >>> import torch
637
+ >>> from transformers import AutoFeatureExtractor, MoonshineModel
638
+ >>> from datasets import load_dataset
639
+
640
+ >>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
641
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
642
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
643
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
644
+ >>> input_values = inputs.input_values
645
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
646
+ >>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
647
+ >>> list(last_hidden_state.shape)
648
+ [1, 2, 288]
649
+ ```
650
+ """
651
+ if encoder_outputs is None:
652
+ encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
653
+
654
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
655
+ input_ids=decoder_input_ids,
656
+ attention_mask=decoder_attention_mask,
657
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
658
+ encoder_attention_mask=encoder_outputs.attention_mask,
659
+ past_key_values=past_key_values,
660
+ inputs_embeds=decoder_inputs_embeds,
661
+ position_ids=decoder_position_ids,
662
+ use_cache=use_cache,
663
+ **kwargs,
664
+ )
665
+
666
+ return Seq2SeqModelOutput(
667
+ last_hidden_state=decoder_outputs.last_hidden_state,
668
+ past_key_values=decoder_outputs.past_key_values,
669
+ decoder_hidden_states=decoder_outputs.hidden_states,
670
+ decoder_attentions=decoder_outputs.attentions,
671
+ cross_attentions=decoder_outputs.cross_attentions,
672
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
673
+ encoder_hidden_states=encoder_outputs.hidden_states,
674
+ encoder_attentions=encoder_outputs.attentions,
675
+ )
676
+
677
+
678
+ @auto_docstring(
679
+ custom_intro="""
680
+ The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
681
+ """
682
+ )
683
+ class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
684
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
685
+
686
+ def __init__(self, config: MoonshineConfig):
687
+ super().__init__(config)
688
+ self.model = MoonshineModel(config)
689
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
690
+
691
+ # Initialize weights and apply final processing
692
+ self.post_init()
693
+
694
+ def get_output_embeddings(self):
695
+ return self.proj_out
696
+
697
+ def set_output_embeddings(self, new_embeddings):
698
+ self.proj_out = new_embeddings
699
+
700
+ def get_input_embeddings(self) -> nn.Module:
701
+ return self.model.get_input_embeddings()
702
+
703
+ @can_return_tuple
704
+ @auto_docstring
705
+ def forward(
706
+ self,
707
+ input_values: torch.FloatTensor | None = None,
708
+ attention_mask: torch.LongTensor | None = None,
709
+ decoder_input_ids: torch.LongTensor | None = None,
710
+ decoder_attention_mask: torch.LongTensor | None = None,
711
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
712
+ past_key_values: EncoderDecoderCache | None = None,
713
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
714
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
715
+ use_cache: bool | None = None,
716
+ labels: torch.LongTensor | None = None,
717
+ **kwargs: Unpack[TransformersKwargs],
718
+ ) -> Seq2SeqLMOutput:
719
+ r"""
720
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
721
+ Float values of the raw speech waveform. Raw speech waveform can be
722
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
723
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
724
+ the soundfile library (`pip install soundfile`). To prepare the array into
725
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
726
+ and conversion into a tensor of type `torch.FloatTensor`.
727
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
728
+ Indices of positions of each input sequence tokens in the position embeddings.
729
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
730
+
731
+ Example:
732
+
733
+ ```python
734
+ >>> import torch
735
+ >>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
736
+ >>> from datasets import load_dataset
737
+
738
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
739
+ >>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
740
+
741
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
742
+
743
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
744
+ >>> input_values = inputs.input_values
745
+
746
+ >>> generated_ids = model.generate(input_values, max_new_tokens=100)
747
+
748
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
749
+ >>> transcription
750
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
751
+ ```"""
752
+
753
+ if labels is not None:
754
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
755
+ decoder_input_ids = shift_tokens_right(
756
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
757
+ )
758
+
759
+ outputs: Seq2SeqModelOutput = self.model(
760
+ input_values,
761
+ attention_mask=attention_mask,
762
+ decoder_input_ids=decoder_input_ids,
763
+ encoder_outputs=encoder_outputs,
764
+ decoder_attention_mask=decoder_attention_mask,
765
+ past_key_values=past_key_values,
766
+ decoder_inputs_embeds=decoder_inputs_embeds,
767
+ decoder_position_ids=decoder_position_ids,
768
+ use_cache=use_cache,
769
+ **kwargs,
770
+ )
771
+ logits = self.proj_out(outputs.last_hidden_state)
772
+
773
+ loss = None
774
+ if labels is not None:
775
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
776
+
777
+ return Seq2SeqLMOutput(
778
+ loss=loss,
779
+ logits=logits,
780
+ past_key_values=outputs.past_key_values,
781
+ decoder_hidden_states=outputs.decoder_hidden_states,
782
+ decoder_attentions=outputs.decoder_attentions,
783
+ cross_attentions=outputs.cross_attentions,
784
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
785
+ encoder_hidden_states=outputs.encoder_hidden_states,
786
+ encoder_attentions=outputs.encoder_attentions,
787
+ )
788
+
789
+
790
+ __all__ = [
791
+ "MoonshineConfig",
792
+ "MoonshineModel",
793
+ "MoonshinePreTrainedModel",
794
+ "MoonshineForConditionalGeneration",
795
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/__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_musicgen import *
22
+ from .modeling_musicgen import *
23
+ from .processing_musicgen 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/musicgen/configuration_musicgen.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Meta AI 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
+ """MusicGen model configuration"""
15
+
16
+ from typing import ClassVar
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring
22
+ from ..auto.configuration_auto import AutoConfig
23
+
24
+
25
+ @auto_docstring(checkpoint="facebook/musicgen-small")
26
+ @strict
27
+ class MusicgenDecoderConfig(PreTrainedConfig):
28
+ model_type = "musicgen_decoder"
29
+ base_config_key = "decoder_config"
30
+ keys_to_ignore_at_inference = ["past_key_values"]
31
+
32
+ vocab_size: int = 2048
33
+ max_position_embeddings: int = 2048
34
+ num_hidden_layers: int = 24
35
+ ffn_dim: int = 4096
36
+ num_attention_heads: int = 16
37
+ layerdrop: float | int = 0.0
38
+ use_cache: bool = True
39
+ activation_function: str = "gelu"
40
+ hidden_size: int = 1024
41
+ dropout: float | int = 0.1
42
+ attention_dropout: float | int = 0.0
43
+ activation_dropout: float | int = 0.0
44
+ initializer_factor: float = 0.02
45
+ scale_embedding: bool = False
46
+ num_codebooks: int = 4
47
+ audio_channels: int = 1
48
+ pad_token_id: int | None = 2048
49
+ bos_token_id: int | None = 2048
50
+ eos_token_id: int | list[int] | None = None
51
+ tie_word_embeddings: bool = False
52
+ is_decoder: bool = False
53
+ add_cross_attention: bool = False
54
+ cross_attention_hidden_size: int | None = None
55
+
56
+ def validate_architecture(self):
57
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
58
+ if self.audio_channels not in [1, 2]:
59
+ raise ValueError(f"Expected 1 (mono) or 2 (stereo) audio channels, got {self.audio_channels} channels.")
60
+
61
+
62
+ @auto_docstring(checkpoint="facebook/musicgen-small")
63
+ @strict
64
+ class MusicgenConfig(PreTrainedConfig):
65
+ r"""
66
+ text_encoder (`Union[dict, `PretrainedConfig`]`):
67
+ An instance of a configuration object that defines the text encoder config.
68
+ audio_encoder (`Union[dict, `PretrainedConfig`]`):
69
+ An instance of a configuration object that defines the audio encoder config.
70
+ decoder (`Union[dict, `PretrainedConfig`]`):
71
+ An instance of a configuration object that defines the decoder config.
72
+
73
+ Example:
74
+
75
+ ```python
76
+ >>> from transformers import (
77
+ ... MusicgenConfig,
78
+ ... MusicgenDecoderConfig,
79
+ ... T5Config,
80
+ ... EncodecConfig,
81
+ ... MusicgenForConditionalGeneration,
82
+ ... )
83
+
84
+ >>> # Initializing text encoder, audio encoder, and decoder model configurations
85
+ >>> text_encoder_config = T5Config()
86
+ >>> audio_encoder_config = EncodecConfig()
87
+ >>> decoder_config = MusicgenDecoderConfig()
88
+
89
+ >>> configuration = MusicgenConfig(
90
+ ... text_encoder=text_encoder_config,
91
+ ... audio_encoder=audio_encoder_config,
92
+ ... decoder=decoder_config,
93
+ ... )
94
+
95
+ >>> # Initializing a MusicgenForConditionalGeneration (with random weights) from the facebook/musicgen-small style configuration
96
+ >>> model = MusicgenForConditionalGeneration(configuration)
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ >>> config_text_encoder = model.config.text_encoder
101
+ >>> config_audio_encoder = model.config.audio_encoder
102
+ >>> config_decoder = model.config.decoder
103
+
104
+ >>> # Saving the model, including its configuration
105
+ >>> model.save_pretrained("musicgen-model")
106
+
107
+ >>> # loading model and config from pretrained folder
108
+ >>> musicgen_config = MusicgenConfig.from_pretrained("musicgen-model")
109
+ >>> model = MusicgenForConditionalGeneration.from_pretrained("musicgen-model", config=musicgen_config)
110
+ ```"""
111
+
112
+ model_type: ClassVar[str] = "musicgen"
113
+ sub_configs: ClassVar[dict[str, type[PreTrainedConfig]]] = {
114
+ "text_encoder": AutoConfig,
115
+ "audio_encoder": AutoConfig,
116
+ "decoder": MusicgenDecoderConfig,
117
+ }
118
+ has_no_defaults_at_init: ClassVar[bool] = True
119
+
120
+ text_encoder: dict | PreTrainedConfig = None
121
+ audio_encoder: dict | PreTrainedConfig = None
122
+ decoder: dict | PreTrainedConfig = None
123
+ initializer_factor: float = 0.02
124
+
125
+ def __post_init__(self, **kwargs):
126
+ if isinstance(self.text_encoder, dict):
127
+ text_encoder_model_type = self.text_encoder.pop("model_type")
128
+ self.text_encoder = AutoConfig.for_model(text_encoder_model_type, **self.text_encoder)
129
+ elif self.text_encoder is None:
130
+ raise ValueError(
131
+ f"A configuration of type {self.model_type} cannot be instantiated because text_encoder is not passed"
132
+ )
133
+
134
+ if isinstance(self.audio_encoder, dict):
135
+ audio_encoder_model_type = self.audio_encoder.pop("model_type")
136
+ self.audio_encoder = AutoConfig.for_model(audio_encoder_model_type, **self.audio_encoder)
137
+ elif self.audio_encoder is None:
138
+ raise ValueError(
139
+ f"A configuration of type {self.model_type} cannot be instantiated because audio_encoder is not passed"
140
+ )
141
+
142
+ if isinstance(self.decoder, dict):
143
+ self.decoder = MusicgenDecoderConfig(**self.decoder)
144
+ elif self.decoder is None:
145
+ self.decoder = MusicgenDecoderConfig()
146
+
147
+ self.is_encoder_decoder = True
148
+ super().__post_init__(**kwargs)
149
+
150
+ @property
151
+ # This is a property because you might want to change the codec model on the fly
152
+ def sampling_rate(self):
153
+ return self.audio_encoder.sampling_rate
154
+
155
+
156
+ __all__ = ["MusicgenConfig", "MusicgenDecoderConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen/modeling_musicgen.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/musicgen/processing_musicgen.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Text/audio processor class for MusicGen
16
+ """
17
+
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...utils import auto_docstring, to_numpy
24
+
25
+
26
+ @auto_docstring
27
+ class MusicgenProcessor(ProcessorMixin):
28
+ def __init__(self, feature_extractor, tokenizer):
29
+ super().__init__(feature_extractor, tokenizer)
30
+
31
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
32
+ return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
33
+
34
+ @auto_docstring
35
+ def __call__(self, *args, **kwargs):
36
+ if len(args) > 0:
37
+ kwargs["audio"] = args[0]
38
+ return super().__call__(*args, **kwargs)
39
+
40
+ def batch_decode(self, *args, **kwargs):
41
+ """
42
+ This method is used to decode either batches of audio outputs from the MusicGen model, or batches of token ids
43
+ from the tokenizer. In the case of decoding token ids, this method forwards all its arguments to T5Tokenizer's
44
+ [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
45
+ """
46
+ audio_values = kwargs.pop("audio", None)
47
+ padding_mask = kwargs.pop("padding_mask", None)
48
+
49
+ if len(args) > 0:
50
+ audio_values = args[0]
51
+ args = args[1:]
52
+
53
+ if audio_values is not None:
54
+ return self._decode_audio(audio_values, padding_mask=padding_mask)
55
+ else:
56
+ return self.tokenizer.batch_decode(*args, **kwargs)
57
+
58
+ def _decode_audio(self, audio_values, padding_mask: Any = None) -> list[np.ndarray]:
59
+ """
60
+ This method strips any padding from the audio values to return a list of numpy audio arrays.
61
+ """
62
+ audio_values = to_numpy(audio_values)
63
+ bsz, channels, seq_len = audio_values.shape
64
+
65
+ if padding_mask is None:
66
+ return list(audio_values)
67
+
68
+ padding_mask = to_numpy(padding_mask)
69
+
70
+ # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
71
+ # token (so that the generated audio values are **not** treated as padded tokens)
72
+ difference = seq_len - padding_mask.shape[-1]
73
+ padding_value = 1 - self.feature_extractor.padding_value
74
+ padding_mask = np.pad(padding_mask, ((0, 0), (0, difference)), "constant", constant_values=padding_value)
75
+
76
+ audio_values = audio_values.tolist()
77
+ for i in range(bsz):
78
+ sliced_audio = np.asarray(audio_values[i])[
79
+ padding_mask[i][None, :] != self.feature_extractor.padding_value
80
+ ]
81
+ audio_values[i] = sliced_audio.reshape(channels, -1)
82
+
83
+ return audio_values
84
+
85
+
86
+ __all__ = ["MusicgenProcessor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/qwen2_5_omni/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen2_5_omni import *
22
+ from .modeling_qwen2_5_omni import *
23
+ from .processing_qwen2_5_omni 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/qwen2_5_omni/modeling_qwen2_5_omni.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/qwen2_5_omni/modular_qwen2_5_omni.py ADDED
The diff for this file is too large to render. See raw diff