michaelu0826 commited on
Commit
1f598ee
·
verified ·
1 Parent(s): cfc4047

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/__init__.cpython-311.pyc +0 -0
  2. lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-311.pyc +0 -0
  3. lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/modular_olmoe.cpython-311.pyc +0 -0
  4. lib/python3.11/site-packages/transformers/models/olmoe/modular_olmoe.py +279 -0
  5. lib/python3.11/site-packages/transformers/models/omdet_turbo/__init__.py +28 -0
  6. lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/__init__.cpython-311.pyc +0 -0
  7. lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-311.pyc +0 -0
  8. lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-311.pyc +0 -0
  9. lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-311.pyc +0 -0
  10. lib/python3.11/site-packages/transformers/models/omdet_turbo/configuration_omdet_turbo.py +189 -0
  11. lib/python3.11/site-packages/transformers/models/omdet_turbo/modeling_omdet_turbo.py +1657 -0
  12. lib/python3.11/site-packages/transformers/models/omdet_turbo/processing_omdet_turbo.py +353 -0
  13. lib/python3.11/site-packages/transformers/models/oneformer/__init__.py +30 -0
  14. lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-311.pyc +0 -0
  15. lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-311.pyc +0 -0
  16. lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-311.pyc +0 -0
  17. lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-311.pyc +0 -0
  18. lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/processing_oneformer.cpython-311.pyc +0 -0
  19. lib/python3.11/site-packages/transformers/models/oneformer/configuration_oneformer.py +158 -0
  20. lib/python3.11/site-packages/transformers/models/oneformer/image_processing_oneformer.py +969 -0
  21. lib/python3.11/site-packages/transformers/models/oneformer/image_processing_pil_oneformer.py +1008 -0
  22. lib/python3.11/site-packages/transformers/models/oneformer/modeling_oneformer.py +0 -0
  23. lib/python3.11/site-packages/transformers/models/oneformer/processing_oneformer.py +181 -0
  24. lib/python3.11/site-packages/transformers/models/openai/__init__.py +28 -0
  25. lib/python3.11/site-packages/transformers/models/openai/__pycache__/__init__.cpython-311.pyc +0 -0
  26. lib/python3.11/site-packages/transformers/models/openai/__pycache__/configuration_openai.cpython-311.pyc +0 -0
  27. lib/python3.11/site-packages/transformers/models/openai/__pycache__/modeling_openai.cpython-311.pyc +0 -0
  28. lib/python3.11/site-packages/transformers/models/openai/__pycache__/tokenization_openai.cpython-311.pyc +0 -0
  29. lib/python3.11/site-packages/transformers/models/openai/configuration_openai.py +103 -0
  30. lib/python3.11/site-packages/transformers/models/openai/modeling_openai.py +728 -0
  31. lib/python3.11/site-packages/transformers/models/openai/tokenization_openai.py +98 -0
  32. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__init__.py +27 -0
  33. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/__init__.cpython-311.pyc +0 -0
  34. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/configuration_openai_privacy_filter.cpython-311.pyc +0 -0
  35. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/modeling_openai_privacy_filter.cpython-311.pyc +0 -0
  36. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/modular_openai_privacy_filter.cpython-311.pyc +0 -0
  37. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/configuration_openai_privacy_filter.py +118 -0
  38. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/modeling_openai_privacy_filter.py +512 -0
  39. lib/python3.11/site-packages/transformers/models/openai_privacy_filter/modular_openai_privacy_filter.py +404 -0
  40. lib/python3.11/site-packages/transformers/models/opt/__init__.py +27 -0
  41. lib/python3.11/site-packages/transformers/models/opt/__pycache__/__init__.cpython-311.pyc +0 -0
  42. lib/python3.11/site-packages/transformers/models/opt/__pycache__/configuration_opt.cpython-311.pyc +0 -0
  43. lib/python3.11/site-packages/transformers/models/opt/__pycache__/modeling_opt.cpython-311.pyc +0 -0
  44. lib/python3.11/site-packages/transformers/models/opt/configuration_opt.py +83 -0
  45. lib/python3.11/site-packages/transformers/models/opt/modeling_opt.py +751 -0
  46. lib/python3.11/site-packages/transformers/models/ovis2/__init__.py +31 -0
  47. lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/__init__.cpython-311.pyc +0 -0
  48. lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/configuration_ovis2.cpython-311.pyc +0 -0
  49. lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/image_processing_ovis2.cpython-311.pyc +0 -0
  50. lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/image_processing_pil_ovis2.cpython-311.pyc +0 -0
lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (775 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-311.pyc ADDED
Binary file (40.9 kB). View file
 
lib/python3.11/site-packages/transformers/models/olmoe/__pycache__/modular_olmoe.cpython-311.pyc ADDED
Binary file (16.3 kB). View file
 
lib/python3.11/site-packages/transformers/models/olmoe/modular_olmoe.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ """PyTorch OLMoE model."""
13
+
14
+ from collections.abc import Callable
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ... import initialization as init
20
+ from ...cache_utils import Cache, DynamicCache
21
+ from ...generation import GenerationMixin
22
+ from ...masking_utils import create_causal_mask
23
+ from ...modeling_outputs import MoeModelOutputWithPast
24
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
25
+ from ...processing_utils import Unpack
26
+ from ...utils import TransformersKwargs, auto_docstring, logging
27
+ from ...utils.output_capturing import OutputRecorder
28
+ from ..gemma.modeling_gemma import GemmaMLP
29
+ from ..llama.modeling_llama import (
30
+ LlamaAttention,
31
+ LlamaDecoderLayer,
32
+ LlamaRMSNorm,
33
+ LlamaRotaryEmbedding,
34
+ apply_rotary_pos_emb,
35
+ eager_attention_forward,
36
+ )
37
+ from ..mixtral.modeling_mixtral import MixtralExperts, MixtralForCausalLM, MixtralModel
38
+ from ..qwen2_moe.modeling_qwen2_moe import Qwen2MoeTopKRouter
39
+ from .configuration_olmoe import OlmoeConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class OlmoeRMSNorm(LlamaRMSNorm):
46
+ def __init__(self, hidden_size, eps=1e-5):
47
+ super().__init__(hidden_size, eps)
48
+
49
+
50
+ class OlmoeRotaryEmbedding(LlamaRotaryEmbedding):
51
+ pass
52
+
53
+
54
+ class OlmoeMLP(GemmaMLP):
55
+ pass
56
+
57
+
58
+ class OlmoeAttention(LlamaAttention):
59
+ def __init__(self, config: OlmoeConfig, layer_idx: int | None = None):
60
+ super().__init__(config, layer_idx)
61
+ self.q_norm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
62
+ self.k_norm = OlmoeRMSNorm(
63
+ (config.hidden_size // config.num_attention_heads) * config.num_key_value_heads, eps=config.rms_norm_eps
64
+ )
65
+
66
+ def forward(
67
+ self,
68
+ hidden_states: torch.Tensor,
69
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
70
+ attention_mask: torch.Tensor | None,
71
+ past_key_values: Cache | None = None,
72
+ **kwargs: Unpack[TransformersKwargs],
73
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
74
+ input_shape = hidden_states.shape[:-1]
75
+ hidden_shape = (*input_shape, -1, self.head_dim)
76
+
77
+ query_states = self.q_norm(self.q_proj(hidden_states))
78
+ key_states = self.k_norm(self.k_proj(hidden_states))
79
+ value_states = self.v_proj(hidden_states)
80
+
81
+ if self.config.clip_qkv is not None: # Diff with llama
82
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
83
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
84
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
85
+
86
+ query_states = query_states.view(*hidden_shape).transpose(1, 2)
87
+ key_states = key_states.view(*hidden_shape).transpose(1, 2)
88
+ value_states = value_states.view(*hidden_shape).transpose(1, 2)
89
+ cos, sin = position_embeddings
90
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
91
+
92
+ if past_key_values is not None:
93
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
94
+
95
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
96
+ self.config._attn_implementation, eager_attention_forward
97
+ )
98
+
99
+ attn_output, attn_weights = attention_interface(
100
+ self,
101
+ query_states,
102
+ key_states,
103
+ value_states,
104
+ attention_mask,
105
+ dropout=0.0 if not self.training else self.attention_dropout,
106
+ scaling=self.scaling,
107
+ sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
108
+ **kwargs,
109
+ )
110
+
111
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
112
+ attn_output = self.o_proj(attn_output)
113
+ return attn_output, attn_weights
114
+
115
+
116
+ class OlmoeExperts(MixtralExperts):
117
+ pass
118
+
119
+
120
+ class OlmoeTopKRouter(Qwen2MoeTopKRouter):
121
+ pass
122
+
123
+
124
+ class OlmoeSparseMoeBlock(nn.Module):
125
+ def __init__(self, config):
126
+ super().__init__()
127
+ self.gate = OlmoeTopKRouter(config)
128
+ self.experts = OlmoeExperts(config)
129
+
130
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
131
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
132
+ hidden_states = hidden_states.view(-1, hidden_dim)
133
+ _, top_k_weights, top_k_index = self.gate(hidden_states)
134
+ final_hidden_states = self.experts(hidden_states, top_k_index, top_k_weights).reshape(
135
+ batch_size, sequence_length, hidden_dim
136
+ )
137
+ return final_hidden_states
138
+
139
+
140
+ class OlmoeDecoderLayer(LlamaDecoderLayer):
141
+ def __init__(self, config: OlmoeConfig, layer_idx: int):
142
+ super().__init__(config, layer_idx)
143
+ self.hidden_size = config.hidden_size
144
+ self.self_attn = OlmoeAttention(config=config, layer_idx=layer_idx)
145
+ self.mlp = OlmoeSparseMoeBlock(config)
146
+ self.input_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
147
+ self.post_attention_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
148
+
149
+
150
+ @auto_docstring
151
+ class OlmoePreTrainedModel(PreTrainedModel):
152
+ config: OlmoeConfig
153
+ base_model_prefix = "model"
154
+ supports_gradient_checkpointing = True
155
+ _no_split_modules = ["OlmoeDecoderLayer"]
156
+ _skip_keys_device_placement = ["past_key_values"]
157
+ _supports_flash_attn = True
158
+ _supports_sdpa = True
159
+ _can_record_outputs = {
160
+ "router_logits": OutputRecorder(OlmoeTopKRouter, index=0),
161
+ "hidden_states": OlmoeDecoderLayer,
162
+ "attentions": OlmoeAttention,
163
+ }
164
+
165
+ _supports_attention_backend = True
166
+
167
+ @torch.no_grad()
168
+ def _init_weights(self, module):
169
+ PreTrainedModel._init_weights(self, module)
170
+ if isinstance(module, OlmoeExperts):
171
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
172
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
173
+ elif isinstance(module, OlmoeTopKRouter):
174
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
175
+
176
+
177
+ @auto_docstring
178
+ class OlmoeModel(MixtralModel):
179
+ def __init__(self, config: OlmoeConfig):
180
+ super().__init__(config)
181
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
182
+ self.layers = nn.ModuleList(
183
+ [OlmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
184
+ )
185
+ self.norm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
186
+ self.rotary_emb = OlmoeRotaryEmbedding(config=config)
187
+
188
+ def forward(
189
+ self,
190
+ input_ids: torch.LongTensor | None = None,
191
+ attention_mask: torch.Tensor | None = None,
192
+ position_ids: torch.LongTensor | None = None,
193
+ past_key_values: Cache | None = None,
194
+ inputs_embeds: torch.FloatTensor | None = None,
195
+ use_cache: bool | None = None,
196
+ **kwargs: Unpack[TransformersKwargs],
197
+ ) -> MoeModelOutputWithPast:
198
+ if (input_ids is None) ^ (inputs_embeds is not None):
199
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
200
+
201
+ if use_cache and past_key_values is None:
202
+ past_key_values = DynamicCache(config=self.config)
203
+
204
+ if inputs_embeds is None:
205
+ inputs_embeds = self.embed_tokens(input_ids)
206
+
207
+ if position_ids is None:
208
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
209
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
210
+ position_ids = position_ids.unsqueeze(0)
211
+
212
+ causal_mask = create_causal_mask( # diff with mixtral: no sliding
213
+ config=self.config,
214
+ inputs_embeds=inputs_embeds,
215
+ attention_mask=attention_mask,
216
+ past_key_values=past_key_values,
217
+ position_ids=position_ids,
218
+ )
219
+
220
+ hidden_states = inputs_embeds
221
+
222
+ # create position embeddings to be shared across the decoder layers
223
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
224
+
225
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
226
+ hidden_states = decoder_layer(
227
+ hidden_states,
228
+ position_embeddings=position_embeddings,
229
+ attention_mask=causal_mask,
230
+ position_ids=position_ids,
231
+ past_key_values=past_key_values,
232
+ use_cache=use_cache,
233
+ **kwargs,
234
+ )
235
+
236
+ hidden_states = self.norm(hidden_states)
237
+
238
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
239
+ last_hidden_state=hidden_states,
240
+ past_key_values=past_key_values,
241
+ )
242
+
243
+
244
+ class OlmoeForCausalLM(MixtralForCausalLM, GenerationMixin):
245
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
246
+
247
+ def __init__(self, config):
248
+ super().__init__(config)
249
+ self.model = OlmoeModel(config)
250
+ self.num_experts = config.num_experts
251
+
252
+ def forward(self, **super_kwargs):
253
+ r"""
254
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
255
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
256
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
257
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
258
+
259
+ Example:
260
+
261
+ ```python
262
+ >>> from transformers import AutoTokenizer, OlmoeForCausalLM
263
+
264
+ >>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")
265
+ >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")
266
+
267
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
268
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
269
+
270
+ >>> # Generate
271
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
272
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
273
+ 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
274
+ ```
275
+ """
276
+ return super().forward(**super_kwargs)
277
+
278
+
279
+ __all__ = ["OlmoeForCausalLM", "OlmoeModel", "OlmoePreTrainedModel"]
lib/python3.11/site-packages/transformers/models/omdet_turbo/__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_omdet_turbo import *
22
+ from .modeling_omdet_turbo import *
23
+ from .processing_omdet_turbo 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__)
lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (837 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-311.pyc ADDED
Binary file (10.3 kB). View file
 
lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-311.pyc ADDED
Binary file (94.4 kB). View file
 
lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-311.pyc ADDED
Binary file (18.6 kB). View file
 
lib/python3.11/site-packages/transformers/models/omdet_turbo/configuration_omdet_turbo.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """OmDet-Turbo model configuration"""
15
+
16
+ from typing import Literal
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring, logging
23
+ from ..auto import CONFIG_MAPPING, AutoConfig
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ @auto_docstring(checkpoint="omlab/omdet-turbo-swin-tiny-hf")
30
+ @strict
31
+ class OmDetTurboConfig(PreTrainedConfig):
32
+ r"""
33
+ apply_layernorm_after_vision_backbone (`bool`, *optional*, defaults to `True`):
34
+ Whether to apply layer normalization on the feature maps of the vision backbone output.
35
+ disable_custom_kernels (`bool`, *optional*, defaults to `False`):
36
+ Whether to disable custom kernels.
37
+ text_projection_in_dim (`int`, *optional*, defaults to 512):
38
+ The input dimension for the text projection.
39
+ text_projection_out_dim (`int`, *optional*, defaults to 512):
40
+ The output dimension for the text projection.
41
+ task_encoder_hidden_dim (`int`, *optional*, defaults to 1024):
42
+ The feedforward dimension for the task encoder.
43
+ class_embed_dim (`int`, *optional*, defaults to 512):
44
+ The dimension of the classes embeddings.
45
+ class_distance_type (`str`, *optional*, defaults to `"cosine"`):
46
+ The type of distance to compare predicted classes to projected classes embeddings.
47
+ Can be `"cosine"` or `"dot"`.
48
+ num_queries (`int`, *optional*, defaults to 900):
49
+ The number of queries.
50
+ csp_activation (`str`, *optional*, defaults to `"silu"`):
51
+ The activation function of the Cross Stage Partial (CSP) networks of the encoder.
52
+ conv_norm_activation (`str`, *optional*, defaults to `"gelu"`):
53
+ The activation function of the ConvNormLayer layers of the encoder.
54
+ encoder_feedforward_activation (`str`, *optional*, defaults to `"relu"`):
55
+ The activation function for the feedforward network of the encoder.
56
+ encoder_feedforward_dropout (`float`, *optional*, defaults to 0.0):
57
+ The dropout rate following the activation of the encoder feedforward network.
58
+ hidden_expansion (`int`, *optional*, defaults to 1):
59
+ The hidden expansion of the CSP networks in the encoder.
60
+ vision_features_channels (`tuple(int)`, *optional*, defaults to `[256, 256, 256]`):
61
+ The projected vision features channels used as inputs for the decoder.
62
+ encoder_in_channels (`List(int)`, *optional*, defaults to `[192, 384, 768]`):
63
+ The input channels for the encoder.
64
+ encoder_projection_indices (`List(int)`, *optional*, defaults to `[2]`):
65
+ The indices of the input features projected by each layers.
66
+ encoder_dim_feedforward (`int`, *optional*, defaults to 2048):
67
+ The feedforward dimension for the encoder.
68
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
69
+ The positional encoding temperature in the encoder.
70
+ num_feature_levels (`int`, *optional*, defaults to 3):
71
+ The number of feature levels for the multi-scale deformable attention module of the decoder.
72
+ decoder_activation (`str`, *optional*, defaults to `"relu"`):
73
+ The activation function for the decoder.
74
+ decoder_dim_feedforward (`int`, *optional*, defaults to 2048):
75
+ The feedforward dimension for the decoder.
76
+ decoder_num_points (`int`, *optional*, defaults to 4):
77
+ The number of points sampled in the decoder multi-scale deformable attention module.
78
+ decoder_dropout (`float`, *optional*, defaults to 0.0):
79
+ The dropout rate for the decoder.
80
+ eval_size (`tuple[int, int]`, *optional*):
81
+ Height and width used to computes the effective height and width of the position embeddings after taking
82
+ into account the stride (see RTDetr).
83
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
84
+ Whether to learn the initial query.
85
+ cache_size (`int`, *optional*, defaults to 100):
86
+ The cache size for the classes and prompts caches.
87
+
88
+ Examples:
89
+
90
+ ```python
91
+ >>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection
92
+
93
+ >>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
94
+ >>> configuration = OmDetTurboConfig()
95
+
96
+ >>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
97
+ >>> model = OmDetTurboForObjectDetection(configuration)
98
+
99
+ >>> # Accessing the model configuration
100
+ >>> configuration = model.config
101
+ ```"""
102
+
103
+ model_type = "omdet-turbo"
104
+ sub_configs = {"backbone_config": AutoConfig, "text_config": AutoConfig}
105
+ attribute_map = {
106
+ "encoder_hidden_dim": "d_model",
107
+ "num_attention_heads": "encoder_attention_heads",
108
+ }
109
+
110
+ text_config: dict | PreTrainedConfig | None = None
111
+ backbone_config: dict | PreTrainedConfig | None = None
112
+ apply_layernorm_after_vision_backbone: bool = True
113
+ image_size: int | list[int] | tuple[int, int] = 640
114
+ disable_custom_kernels: bool = False
115
+ layer_norm_eps: float = 1e-5
116
+ batch_norm_eps: float = 1e-5
117
+ init_std: float = 0.02
118
+ text_projection_in_dim: int = 512
119
+ text_projection_out_dim: int = 512
120
+ task_encoder_hidden_dim: int = 1024
121
+ class_embed_dim: int = 512
122
+ class_distance_type: Literal["cosine", "dot"] = "cosine"
123
+ num_queries: int = 900
124
+ csp_activation: str = "silu"
125
+ conv_norm_activation: str = "gelu"
126
+ encoder_feedforward_activation: str = "relu"
127
+ encoder_feedforward_dropout: float | int = 0.0
128
+ encoder_dropout: float | int = 0.0
129
+ hidden_expansion: int = 1
130
+ encoder_hidden_dim: int = 256
131
+ vision_features_channels: list[int] | tuple[int, ...] = (256, 256, 256)
132
+ encoder_in_channels: list[int] | tuple[int, ...] = (192, 384, 768)
133
+ encoder_projection_indices: list[int] | tuple[int, ...] = (2,)
134
+ encoder_attention_heads: int = 8
135
+ encoder_dim_feedforward: int = 2048
136
+ encoder_layers: int = 1
137
+ positional_encoding_temperature: int = 10000
138
+ num_feature_levels: int = 3
139
+ decoder_hidden_dim: int = 256
140
+ decoder_num_heads: int = 8
141
+ decoder_num_layers: int = 6
142
+ decoder_activation: str = "relu"
143
+ decoder_dim_feedforward: int = 2048
144
+ decoder_num_points: int = 4
145
+ decoder_dropout: float | int = 0.0
146
+ eval_size: int | None = None
147
+ learn_initial_query: bool = False
148
+ cache_size: int = 100
149
+ is_encoder_decoder: bool = True
150
+
151
+ def __post_init__(self, **kwargs):
152
+ # Init timm backbone with hardcoded values for BC
153
+ timm_default_kwargs = {
154
+ "out_indices": [1, 2, 3],
155
+ "img_size": self.image_size,
156
+ "always_partition": True,
157
+ }
158
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
159
+ backbone_config=self.backbone_config,
160
+ default_backbone="swin_tiny_patch4_window7_224",
161
+ default_config_type="swin",
162
+ default_config_kwargs={"image_size": self.image_size, "out_indices": [2, 3, 4]},
163
+ timm_default_kwargs=timm_default_kwargs,
164
+ **kwargs,
165
+ )
166
+
167
+ # Extract timm.create_model kwargs; TimmBackbone doesn't forward arbitrary config attrs to timm
168
+ self.timm_kwargs = {}
169
+ if getattr(self.backbone_config, "model_type", None) == "timm_backbone":
170
+ for attr in ("img_size", "always_partition"):
171
+ if hasattr(self.backbone_config, attr):
172
+ self.timm_kwargs[attr] = getattr(self.backbone_config, attr)
173
+
174
+ if self.text_config is None:
175
+ logger.info("`text_config` is `None`. Initializing the config with the default `clip_text_model`")
176
+ self.text_config = CONFIG_MAPPING["clip_text_model"]()
177
+ elif isinstance(self.text_config, dict):
178
+ text_model_type = self.text_config.get("model_type")
179
+ self.text_config = CONFIG_MAPPING[text_model_type](**self.text_config)
180
+
181
+ super().__post_init__(**kwargs)
182
+
183
+ def to_dict(self):
184
+ output = super().to_dict()
185
+ output.pop("timm_kwargs", None)
186
+ return output
187
+
188
+
189
+ __all__ = ["OmDetTurboConfig"]
lib/python3.11/site-packages/transformers/models/omdet_turbo/modeling_omdet_turbo.py ADDED
@@ -0,0 +1,1657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Om Research Lab and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch OmDet-Turbo model."""
15
+
16
+ import math
17
+ import warnings
18
+ from collections import OrderedDict
19
+ from dataclasses import dataclass
20
+ from functools import lru_cache
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from torch import Tensor
26
+
27
+ from ... import initialization as init
28
+ from ...activations import ACT2CLS, ACT2FN
29
+ from ...integrations import use_kernel_forward_from_hub
30
+ from ...masking_utils import create_bidirectional_mask
31
+ from ...modeling_layers import GradientCheckpointingLayer
32
+ from ...modeling_utils import PreTrainedModel
33
+ from ...processing_utils import Unpack
34
+ from ...utils import (
35
+ ModelOutput,
36
+ TransformersKwargs,
37
+ auto_docstring,
38
+ logging,
39
+ torch_compilable_check,
40
+ )
41
+ from ..auto import AutoBackbone, AutoModel
42
+ from .configuration_omdet_turbo import OmDetTurboConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ @auto_docstring(
49
+ custom_intro="""
50
+ Base class for outputs of the OmDetTurboHybridEncoder.
51
+ """
52
+ )
53
+ @dataclass
54
+ class OmDetTurboEncoderOutput(ModelOutput):
55
+ r"""
56
+ last_hidden_state (`torch.FloatTensor`):
57
+ Last hidden states of the encoder.
58
+ extracted_states (`tuple[torch.FloatTensor]`):
59
+ The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
60
+ """
61
+
62
+ last_hidden_state: torch.FloatTensor | None = None
63
+ hidden_states: tuple[torch.FloatTensor] | None = None
64
+ attentions: tuple[torch.FloatTensor] | None = None
65
+ extracted_states: tuple[torch.FloatTensor] | None = None
66
+
67
+
68
+ @auto_docstring(
69
+ custom_intro="""
70
+ Base class for outputs of the OmDetTurboDecoder.
71
+ """
72
+ )
73
+ @dataclass
74
+ class OmDetTurboDecoderOutput(ModelOutput):
75
+ r"""
76
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
77
+ Sequence of hidden-states at the output of the last layer of the decoder.
78
+ decoder_coords (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
79
+ The predicted coordinates of the objects.
80
+ decoder_classes (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
81
+ The predicted classes of the objects.
82
+ encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
83
+ The predicted coordinates of the objects from the encoder.
84
+ encoder_class_logits (`tuple[torch.FloatTensor]` of shape `(batch_size, num_queries, num_classes)`):
85
+ The predicted class of the objects from the encoder.
86
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
87
+ The initial reference points.
88
+ intermediate_reference_points (`tuple[tuple[torch.FloatTensor]]`):
89
+ The intermediate reference points.
90
+ """
91
+
92
+ last_hidden_state: torch.FloatTensor | None = None
93
+ hidden_states: tuple[torch.FloatTensor] | None = None
94
+ attentions: tuple[tuple[torch.FloatTensor]] | None = None
95
+ decoder_coords: torch.FloatTensor | None = None
96
+ decoder_classes: torch.FloatTensor | None = None
97
+ encoder_coord_logits: torch.FloatTensor | None = None
98
+ encoder_class_logits: tuple[torch.FloatTensor] | None = None
99
+ init_reference_points: torch.FloatTensor | None = None
100
+ intermediate_reference_points: tuple[tuple[torch.FloatTensor]] = None
101
+
102
+
103
+ @auto_docstring(
104
+ custom_intro="""
105
+ Output type of [`OmDetTurboObjectDetectionOutput`].
106
+ """
107
+ )
108
+ @dataclass
109
+ class OmDetTurboObjectDetectionOutput(ModelOutput):
110
+ r"""
111
+ loss (`torch.FloatTensor`):
112
+ The loss value.
113
+ decoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
114
+ The predicted coordinates logits of the objects.
115
+ decoder_class_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
116
+ The predicted class of the objects.
117
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
118
+ The initial reference points.
119
+ intermediate_reference_points (`tuple[tuple[torch.FloatTensor]]`):
120
+ The intermediate reference points.
121
+ encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
122
+ The predicted coordinates of the objects from the encoder.
123
+ encoder_class_logits (`tuple[torch.FloatTensor]`):
124
+ The predicted class of the objects from the encoder.
125
+ encoder_extracted_states (`torch.FloatTensor`):
126
+ The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
127
+ decoder_hidden_states (`tuple[torch.FloatTensor]`, *optional*):
128
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
129
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
130
+ plus the initial embedding outputs.
131
+ decoder_attentions (`tuple[tuple[torch.FloatTensor]]`, *optional*):
132
+ Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
133
+ sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
134
+ weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
135
+ encoder_hidden_states (`tuple[torch.FloatTensor]`, *optional*):
136
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
137
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
138
+ plus the initial embedding outputs.
139
+ encoder_attentions (`tuple[tuple[torch.FloatTensor]]`, *optional*):
140
+ Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
141
+ sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
142
+ weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
143
+ classes_structure (`torch.LongTensor`, *optional*):
144
+ The number of queried classes for each image.
145
+ """
146
+
147
+ loss: torch.FloatTensor | None = None
148
+ decoder_coord_logits: torch.FloatTensor | None = None
149
+ decoder_class_logits: torch.FloatTensor | None = None
150
+ init_reference_points: torch.FloatTensor | None = None
151
+ intermediate_reference_points: tuple[tuple[torch.FloatTensor]] | None = None
152
+ encoder_coord_logits: torch.FloatTensor | None = None
153
+ encoder_class_logits: tuple[torch.FloatTensor] | None = None
154
+ encoder_extracted_states: torch.FloatTensor | None = None
155
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
156
+ decoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
157
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
158
+ encoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
159
+ classes_structure: torch.LongTensor | None = None
160
+
161
+
162
+ @use_kernel_forward_from_hub("MultiScaleDeformableAttention")
163
+ # Copied from transformers.models.deformable_detr.modeling_deformable_detr.MultiScaleDeformableAttention
164
+ class MultiScaleDeformableAttention(nn.Module):
165
+ def forward(
166
+ self,
167
+ value: Tensor,
168
+ value_spatial_shapes: Tensor,
169
+ value_spatial_shapes_list: list[tuple],
170
+ level_start_index: Tensor,
171
+ sampling_locations: Tensor,
172
+ attention_weights: Tensor,
173
+ im2col_step: int,
174
+ ):
175
+ batch_size, _, num_heads, hidden_dim = value.shape
176
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
177
+ value_list = value.split([height * width for height, width in value_spatial_shapes_list], dim=1)
178
+ sampling_grids = 2 * sampling_locations - 1
179
+ sampling_value_list = []
180
+ for level_id, (height, width) in enumerate(value_spatial_shapes_list):
181
+ # batch_size, height*width, num_heads, hidden_dim
182
+ # -> batch_size, height*width, num_heads*hidden_dim
183
+ # -> batch_size, num_heads*hidden_dim, height*width
184
+ # -> batch_size*num_heads, hidden_dim, height, width
185
+ value_l_ = (
186
+ value_list[level_id]
187
+ .flatten(2)
188
+ .transpose(1, 2)
189
+ .reshape(batch_size * num_heads, hidden_dim, height, width)
190
+ )
191
+ # batch_size, num_queries, num_heads, num_points, 2
192
+ # -> batch_size, num_heads, num_queries, num_points, 2
193
+ # -> batch_size*num_heads, num_queries, num_points, 2
194
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1)
195
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
196
+ sampling_value_l_ = nn.functional.grid_sample(
197
+ value_l_,
198
+ sampling_grid_l_,
199
+ mode="bilinear",
200
+ padding_mode="zeros",
201
+ align_corners=False,
202
+ )
203
+ sampling_value_list.append(sampling_value_l_)
204
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
205
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
206
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
207
+ attention_weights = attention_weights.transpose(1, 2).reshape(
208
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
209
+ )
210
+ output = (
211
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
212
+ .sum(-1)
213
+ .view(batch_size, num_heads * hidden_dim, num_queries)
214
+ )
215
+ return output.transpose(1, 2).contiguous()
216
+
217
+
218
+ class OmDetTurboLRUCache:
219
+ def __init__(self, capacity: int):
220
+ self.cache = OrderedDict()
221
+ self.capacity = capacity
222
+ self.current_load = 0
223
+
224
+ def has(self, key) -> bool:
225
+ return key in self.cache
226
+
227
+ def get(self, key):
228
+ """
229
+ Get the value of the key if the key exists in the cache, otherwise return None.
230
+ Move the key to the end of the cache to show that it was recently used.
231
+ """
232
+ if key not in self.cache:
233
+ return None
234
+ self.cache.move_to_end(key)
235
+ return self.cache[key]
236
+
237
+ def put(self, key, value) -> None:
238
+ """
239
+ Add the key-value pair to the cache.
240
+ Move the key to the end of the cache to show that it was recently used.
241
+ If the cache is full, remove the first key (least recently used).
242
+ """
243
+ if key not in self.cache:
244
+ self.current_load += 1
245
+ if self.current_load > self.capacity:
246
+ self.cache.popitem(last=False)
247
+ self.current_load -= 1
248
+
249
+ self.cache[key] = value
250
+ self.cache.move_to_end(key)
251
+
252
+
253
+ class OmDetTurboLanguageBackbone(nn.Module):
254
+ def __init__(self, config: OmDetTurboConfig):
255
+ super().__init__()
256
+ self.model = AutoModel.from_config(config.text_config)
257
+ self.text_projection = nn.Parameter(torch.zeros(config.text_projection_in_dim, config.text_projection_out_dim))
258
+
259
+ def forward(self, hidden_states, mask=None, encode_type="task"):
260
+ text_outputs = self.model(hidden_states)
261
+ pooled_output = text_outputs[0]
262
+ if encode_type == "task":
263
+ if mask is None:
264
+ raise ValueError("mask is required for task encoding")
265
+ max_len = (mask != 0).sum(1).max().item()
266
+ truncated_mask = mask[:, :max_len]
267
+ truncated_output = pooled_output[:, :max_len, :]
268
+ return truncated_output.transpose(0, 1), truncated_mask
269
+ elif encode_type == "class":
270
+ max_pooled_output = pooled_output[torch.arange(pooled_output.shape[0]), hidden_states.argmax(dim=-1)]
271
+ projected_output = max_pooled_output @ self.text_projection
272
+ return projected_output
273
+ else:
274
+ raise ValueError(f"encode_type {encode_type} is not supported")
275
+
276
+
277
+ class OmDetTurboVisionBackbone(nn.Module):
278
+ def __init__(self, config: OmDetTurboConfig):
279
+ super().__init__()
280
+ self.apply_layernorm_after_vision_backbone = config.apply_layernorm_after_vision_backbone
281
+ self.vision_backbone = AutoBackbone.from_config(config.backbone_config, **getattr(config, "timm_kwargs", {}))
282
+ self.layer_norms = nn.ModuleList(
283
+ [nn.LayerNorm(in_channel_dim, eps=config.layer_norm_eps) for in_channel_dim in config.encoder_in_channels]
284
+ )
285
+
286
+ def forward(self, pixel_values):
287
+ outputs = self.vision_backbone(pixel_values).feature_maps
288
+ if self.apply_layernorm_after_vision_backbone:
289
+ outputs = [
290
+ layer_norm(output).permute(0, 3, 1, 2).contiguous()
291
+ for layer_norm, output in zip(self.layer_norms, outputs)
292
+ ]
293
+
294
+ return outputs
295
+
296
+
297
+ # Copied from transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrMultiscaleDeformableAttention with DeformableDetr->OmDetTurbo, Deformable DETR->OmDet-Turbo
298
+ class OmDetTurboMultiscaleDeformableAttention(nn.Module):
299
+ """
300
+ Multiscale deformable attention as proposed in Deformable DETR.
301
+ """
302
+
303
+ def __init__(self, config: OmDetTurboConfig, num_heads: int, n_points: int):
304
+ super().__init__()
305
+
306
+ self.attn = MultiScaleDeformableAttention()
307
+
308
+ if config.d_model % num_heads != 0:
309
+ raise ValueError(
310
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
311
+ )
312
+ dim_per_head = config.d_model // num_heads
313
+ # check if dim_per_head is power of 2
314
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
315
+ warnings.warn(
316
+ "You'd better set embed_dim (d_model) in OmDetTurboMultiscaleDeformableAttention to make the"
317
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
318
+ " implementation."
319
+ )
320
+
321
+ self.im2col_step = 64
322
+
323
+ self.d_model = config.d_model
324
+ self.n_levels = config.num_feature_levels
325
+ self.n_heads = num_heads
326
+ self.n_points = n_points
327
+
328
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
329
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
330
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
331
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
332
+
333
+ self.disable_custom_kernels = config.disable_custom_kernels
334
+
335
+ def forward(
336
+ self,
337
+ hidden_states: torch.Tensor,
338
+ attention_mask: torch.Tensor | None = None,
339
+ encoder_hidden_states=None,
340
+ encoder_attention_mask=None,
341
+ position_embeddings: torch.Tensor | None = None,
342
+ reference_points=None,
343
+ spatial_shapes=None,
344
+ spatial_shapes_list=None,
345
+ level_start_index=None,
346
+ **kwargs: Unpack[TransformersKwargs],
347
+ ) -> tuple[torch.Tensor, torch.Tensor]:
348
+ # add position embeddings to the hidden states before projecting to queries and keys
349
+ if position_embeddings is not None:
350
+ hidden_states = hidden_states + position_embeddings
351
+
352
+ batch_size, num_queries, _ = hidden_states.shape
353
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
354
+ # Ignore copy
355
+ total_elements = sum(shape[0] * shape[1] for shape in spatial_shapes_list)
356
+ torch_compilable_check(
357
+ total_elements == sequence_length,
358
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
359
+ )
360
+
361
+ value = self.value_proj(encoder_hidden_states)
362
+ if attention_mask is not None:
363
+ # we invert the attention_mask
364
+ value = value.masked_fill(~attention_mask[..., None], float(0))
365
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
366
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
367
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
368
+ )
369
+ attention_weights = self.attention_weights(hidden_states).view(
370
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
371
+ )
372
+ attention_weights = F.softmax(attention_weights, -1).view(
373
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
374
+ )
375
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
376
+ num_coordinates = reference_points.shape[-1]
377
+ if num_coordinates == 2:
378
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
379
+ sampling_locations = (
380
+ reference_points[:, :, None, :, None, :]
381
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
382
+ )
383
+ elif num_coordinates == 4:
384
+ sampling_locations = (
385
+ reference_points[:, :, None, :, None, :2]
386
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
387
+ )
388
+ else:
389
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
390
+
391
+ output = self.attn(
392
+ value,
393
+ spatial_shapes,
394
+ spatial_shapes_list,
395
+ level_start_index,
396
+ sampling_locations,
397
+ attention_weights,
398
+ self.im2col_step,
399
+ )
400
+
401
+ output = self.output_proj(output)
402
+
403
+ return output, attention_weights
404
+
405
+
406
+ # Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrConvNormLayer with RTDetr->OmDetTurbo
407
+ class OmDetTurboConvNormLayer(nn.Module):
408
+ def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
409
+ super().__init__()
410
+ self.conv = nn.Conv2d(
411
+ in_channels,
412
+ out_channels,
413
+ kernel_size,
414
+ stride,
415
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
416
+ bias=False,
417
+ )
418
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
419
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
420
+
421
+ def forward(self, hidden_state):
422
+ hidden_state = self.conv(hidden_state)
423
+ hidden_state = self.norm(hidden_state)
424
+ hidden_state = self.activation(hidden_state)
425
+ return hidden_state
426
+
427
+
428
+ # Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrRepVggBlock with RTDetr->OmDetTurbo, activation_function->csp_activation
429
+ class OmDetTurboRepVggBlock(nn.Module):
430
+ """
431
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
432
+ """
433
+
434
+ def __init__(self, config: OmDetTurboConfig):
435
+ super().__init__()
436
+
437
+ activation = config.csp_activation
438
+ hidden_channels = int(config.encoder_hidden_dim * config.hidden_expansion)
439
+ self.conv1 = OmDetTurboConvNormLayer(config, hidden_channels, hidden_channels, 3, 1, padding=1)
440
+ self.conv2 = OmDetTurboConvNormLayer(config, hidden_channels, hidden_channels, 1, 1, padding=0)
441
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
442
+
443
+ def forward(self, x):
444
+ y = self.conv1(x) + self.conv2(x)
445
+ return self.activation(y)
446
+
447
+
448
+ # Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrCSPRepLayer with RTDetr->OmDetTurbo, activation_function->csp_activation
449
+ class OmDetTurboCSPRepLayer(nn.Module):
450
+ """
451
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
452
+ """
453
+
454
+ def __init__(self, config: OmDetTurboConfig):
455
+ super().__init__()
456
+
457
+ in_channels = config.encoder_hidden_dim * 2
458
+ out_channels = config.encoder_hidden_dim
459
+ num_blocks = 3
460
+ activation = config.csp_activation
461
+
462
+ hidden_channels = int(out_channels * config.hidden_expansion)
463
+ self.conv1 = OmDetTurboConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
464
+ self.conv2 = OmDetTurboConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
465
+ self.bottlenecks = nn.Sequential(*[OmDetTurboRepVggBlock(config) for _ in range(num_blocks)])
466
+ if hidden_channels != out_channels:
467
+ self.conv3 = OmDetTurboConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
468
+ else:
469
+ self.conv3 = nn.Identity()
470
+
471
+ def forward(self, hidden_state):
472
+ hidden_state_1 = self.conv1(hidden_state)
473
+ hidden_state_1 = self.bottlenecks(hidden_state_1)
474
+ hidden_state_2 = self.conv2(hidden_state)
475
+ return self.conv3(hidden_state_1 + hidden_state_2)
476
+
477
+
478
+ class OmDetTurboMultiheadAttention(nn.Module):
479
+ """Equivalent implementation of nn.MultiheadAttention with `batch_first=True`."""
480
+
481
+ def __init__(self, config, hidden_size, num_attention_heads, dropout):
482
+ super().__init__()
483
+ if hidden_size % num_attention_heads != 0:
484
+ raise ValueError(
485
+ f"The hidden size ({hidden_size}) is not a multiple of the number of attention "
486
+ f"heads ({num_attention_heads})"
487
+ )
488
+ self.num_attention_heads = num_attention_heads
489
+ self.attention_head_size = int(hidden_size / num_attention_heads)
490
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
491
+ self.query = nn.Linear(hidden_size, self.all_head_size)
492
+ self.key = nn.Linear(hidden_size, self.all_head_size)
493
+ self.value = nn.Linear(hidden_size, self.all_head_size)
494
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
495
+ self.dropout = nn.Dropout(dropout)
496
+
497
+ def forward(
498
+ self,
499
+ queries: torch.Tensor,
500
+ keys: torch.Tensor,
501
+ values: torch.Tensor,
502
+ attention_mask: torch.FloatTensor | None = None,
503
+ output_attentions: bool | None = False,
504
+ ) -> tuple[torch.Tensor]:
505
+ batch_size, seq_length, _ = queries.shape
506
+ query_layer = (
507
+ self.query(queries)
508
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
509
+ .transpose(1, 2)
510
+ )
511
+ key_layer = (
512
+ self.key(keys).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
513
+ )
514
+ value_layer = (
515
+ self.value(values).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
516
+ )
517
+
518
+ # Take the dot product between "query" and "key" to get the raw attention scores.
519
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
520
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
521
+
522
+ if attention_mask is not None:
523
+ attention_scores = attention_scores + attention_mask
524
+
525
+ # Normalize the attention scores to probabilities.
526
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
527
+
528
+ # This is actually dropping out entire tokens to attend to, which might
529
+ # seem a bit unusual, but is taken from the original Transformer paper.
530
+ attention_probs = self.dropout(attention_probs)
531
+
532
+ context_layer = torch.matmul(attention_probs, value_layer)
533
+
534
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
535
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
536
+ context_layer = context_layer.view(new_context_layer_shape)
537
+
538
+ context_layer = self.out_proj(context_layer)
539
+
540
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
541
+
542
+ return outputs
543
+
544
+
545
+ class OmDetTurboEncoderLayer(nn.Module):
546
+ def __init__(self, config: OmDetTurboConfig):
547
+ super().__init__()
548
+ self.self_attn = OmDetTurboMultiheadAttention(
549
+ config,
550
+ hidden_size=config.encoder_hidden_dim,
551
+ num_attention_heads=config.num_attention_heads,
552
+ dropout=config.encoder_dropout,
553
+ )
554
+ self.self_attn_layer_norm = nn.LayerNorm(config.encoder_hidden_dim, eps=config.layer_norm_eps)
555
+ self.dropout = nn.Dropout(config.encoder_dropout)
556
+ self.activation_fn = ACT2FN[config.encoder_feedforward_activation]
557
+ self.encoder_feedforward_dropout = nn.Dropout(config.encoder_feedforward_dropout)
558
+ self.fc1 = nn.Linear(config.encoder_hidden_dim, config.encoder_dim_feedforward)
559
+ self.fc2 = nn.Linear(config.encoder_dim_feedforward, config.encoder_hidden_dim)
560
+ self.final_layer_norm = nn.LayerNorm(config.encoder_hidden_dim, eps=config.layer_norm_eps)
561
+
562
+ @staticmethod
563
+ def with_pos_embed(tensor, pos_embed):
564
+ return tensor if pos_embed is None else tensor + pos_embed
565
+
566
+ def forward(
567
+ self,
568
+ hidden_states: torch.Tensor,
569
+ attention_mask: torch.Tensor,
570
+ position_embeddings: torch.Tensor | None = None,
571
+ output_attentions: bool = False,
572
+ ):
573
+ """
574
+ Args:
575
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
576
+ attention_mask (`torch.FloatTensor`): attention mask of size
577
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
578
+ values.
579
+ position_embeddings (`torch.FloatTensor`, *optional*):
580
+ Object queries (also called content embeddings), to be added to the hidden states.
581
+ output_attentions (`bool`, *optional*, defaults to `False`):
582
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
583
+ returned tensors for more detail.
584
+ """
585
+ residual = hidden_states
586
+ query = key = self.with_pos_embed(hidden_states, position_embeddings)
587
+
588
+ hidden_states = self.self_attn(
589
+ queries=query,
590
+ keys=key,
591
+ values=hidden_states,
592
+ attention_mask=attention_mask,
593
+ output_attentions=output_attentions,
594
+ )
595
+ hidden_states, attentions = hidden_states if output_attentions else (hidden_states[0], None)
596
+ hidden_states = self.dropout(hidden_states)
597
+ hidden_states = residual + hidden_states
598
+ hidden_states = self.self_attn_layer_norm(hidden_states)
599
+ residual = hidden_states
600
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
601
+ hidden_states = self.encoder_feedforward_dropout(hidden_states)
602
+ hidden_states = self.fc2(hidden_states)
603
+ hidden_states = self.dropout(hidden_states)
604
+ hidden_states = residual + hidden_states
605
+ hidden_states = self.final_layer_norm(hidden_states)
606
+ if self.training:
607
+ if not torch.isfinite(hidden_states).all():
608
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
609
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
610
+
611
+ if output_attentions:
612
+ return hidden_states, attentions
613
+
614
+ return (hidden_states,)
615
+
616
+
617
+ class OmDetTurboEncoder(nn.Module):
618
+ def __init__(self, config: OmDetTurboConfig):
619
+ super().__init__()
620
+
621
+ self.layers = nn.ModuleList([OmDetTurboEncoderLayer(config) for _ in range(config.encoder_layers)])
622
+
623
+ def forward(
624
+ self, src, src_mask=None, pos_embed=None, output_attentions: bool = False
625
+ ) -> tuple[torch.Tensor | tuple[torch.Tensor]]:
626
+ hidden_states = src
627
+ attention = () if output_attentions else None
628
+ for layer in self.layers:
629
+ hidden_states = layer(
630
+ hidden_states,
631
+ attention_mask=src_mask,
632
+ position_embeddings=pos_embed,
633
+ output_attentions=output_attentions,
634
+ )
635
+ if output_attentions:
636
+ attention = attention + (hidden_states[1],)
637
+ hidden_states = hidden_states[0]
638
+
639
+ return hidden_states, attention
640
+
641
+
642
+ class OmDetTurboHybridEncoder(nn.Module):
643
+ """
644
+ Encoder consisting of channel projection layers, a set of `OmDetTurboEncoder`, a top-down Feature Pyramid Network
645
+ (FPN) and a bottom-up Path Aggregation Network (PAN). More details on the paper: https://huggingface.co/papers/2304.08069
646
+
647
+ Args:
648
+ config: OmDetTurboConfig
649
+ """
650
+
651
+ def __init__(self, config: OmDetTurboConfig):
652
+ super().__init__()
653
+ self.config = config
654
+ self.in_channels = config.encoder_in_channels
655
+ self.encoder_hidden_dim = config.encoder_hidden_dim
656
+ self.encoder_projection_indices = config.encoder_projection_indices
657
+ self.positional_encoding_temperature = config.positional_encoding_temperature
658
+ self.eval_size = config.eval_size
659
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
660
+
661
+ self.channel_projection_layers = nn.ModuleList()
662
+ for in_channel in self.in_channels:
663
+ self.channel_projection_layers.append(
664
+ nn.Sequential(
665
+ nn.Conv2d(in_channel, self.encoder_hidden_dim, kernel_size=(1, 1), bias=False),
666
+ nn.BatchNorm2d(self.encoder_hidden_dim),
667
+ )
668
+ )
669
+
670
+ # encoder transformer
671
+ self.encoder = nn.ModuleList([OmDetTurboEncoder(config) for _ in range(len(self.encoder_projection_indices))])
672
+ # top-down fpn
673
+ self.lateral_convs = nn.ModuleList()
674
+ self.fpn_blocks = nn.ModuleList()
675
+ for _ in range(len(self.in_channels) - 1, 0, -1):
676
+ self.lateral_convs.append(
677
+ OmDetTurboConvNormLayer(
678
+ config,
679
+ in_channels=self.encoder_hidden_dim,
680
+ out_channels=self.encoder_hidden_dim,
681
+ kernel_size=1,
682
+ stride=1,
683
+ activation=config.conv_norm_activation,
684
+ )
685
+ )
686
+ self.fpn_blocks.append(OmDetTurboCSPRepLayer(config))
687
+
688
+ # bottom-up pan
689
+ self.downsample_convs = nn.ModuleList()
690
+ self.pan_blocks = nn.ModuleList()
691
+ for _ in range(len(self.in_channels) - 1):
692
+ self.downsample_convs.append(
693
+ OmDetTurboConvNormLayer(
694
+ config,
695
+ in_channels=self.encoder_hidden_dim,
696
+ out_channels=self.encoder_hidden_dim,
697
+ kernel_size=3,
698
+ stride=2,
699
+ activation=config.conv_norm_activation,
700
+ )
701
+ )
702
+ self.pan_blocks.append(OmDetTurboCSPRepLayer(config))
703
+
704
+ @staticmethod
705
+ def build_2d_sincos_position_embedding(
706
+ width, height, embed_dim=256, temperature=10000.0, device="cpu", dtype=torch.float32
707
+ ):
708
+ grid_w = torch.arange(int(width), dtype=dtype, device=device)
709
+ grid_h = torch.arange(int(height), dtype=dtype, device=device)
710
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing="ij")
711
+ if embed_dim % 4 != 0:
712
+ raise ValueError("Embed dimension must be divisible by 4 for 2D sin-cos position embedding")
713
+ pos_dim = embed_dim // 4
714
+ omega = torch.arange(pos_dim, dtype=dtype, device=device) / pos_dim
715
+ omega = 1.0 / (temperature**omega)
716
+
717
+ out_w = grid_w.flatten()[..., None] @ omega[None]
718
+ out_h = grid_h.flatten()[..., None] @ omega[None]
719
+
720
+ return torch.concat([out_w.sin(), out_w.cos(), out_h.sin(), out_h.cos()], dim=1)[None, :, :]
721
+
722
+ def forward(
723
+ self,
724
+ inputs_embeddings=None,
725
+ output_attentions=None,
726
+ output_hidden_states=None,
727
+ return_dict=None,
728
+ ):
729
+ r"""
730
+ Args:
731
+ inputs_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
732
+ Flattened feature map (output of the backbone + projection layers) that is passed to the encoder.
733
+ output_attentions (`bool`, *optional*):
734
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
735
+ returned tensors for more detail.
736
+ output_hidden_states (`bool`, *optional*):
737
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
738
+ for more detail.
739
+ return_dict (`bool`, *optional*):
740
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
741
+ """
742
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
743
+ output_hidden_states = (
744
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
745
+ )
746
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
747
+
748
+ hidden_states = inputs_embeddings
749
+
750
+ encoder_states = () if output_hidden_states else None
751
+ all_attentions = () if output_attentions else None
752
+ # get projection features
753
+ projected_features = [self.channel_projection_layers[i](feature) for i, feature in enumerate(hidden_states)]
754
+ # encoder
755
+ for encoder_layer_index, feature_to_project_index in enumerate(self.encoder_projection_indices):
756
+ if output_hidden_states:
757
+ encoder_states = encoder_states + (projected_features[feature_to_project_index],)
758
+ height, width = projected_features[feature_to_project_index].shape[2:]
759
+ # flatten [batch, channel, height, width] to [batch, height*width, channel]
760
+ src_flatten = projected_features[feature_to_project_index].flatten(2).permute(0, 2, 1)
761
+ if self.training or self.eval_size is None:
762
+ pos_embed = self.build_2d_sincos_position_embedding(
763
+ width,
764
+ height,
765
+ self.encoder_hidden_dim,
766
+ self.positional_encoding_temperature,
767
+ device=src_flatten.device,
768
+ dtype=src_flatten.dtype,
769
+ ).to(src_flatten.device, src_flatten.dtype)
770
+ else:
771
+ pos_embed = None
772
+ layer_outputs = self.encoder[encoder_layer_index](
773
+ src_flatten,
774
+ pos_embed=pos_embed,
775
+ output_attentions=output_attentions,
776
+ )
777
+ projected_features[feature_to_project_index] = (
778
+ layer_outputs[0].permute(0, 2, 1).reshape(-1, self.encoder_hidden_dim, height, width).contiguous()
779
+ )
780
+
781
+ if output_attentions:
782
+ all_attentions = all_attentions + (layer_outputs[1],)
783
+
784
+ if output_hidden_states:
785
+ encoder_states = encoder_states + (projected_features[feature_to_project_index],)
786
+
787
+ # Feature Pyramid Network (FPN)
788
+ fpn_feature_maps = [projected_features[-1]]
789
+ for idx in range(len(self.in_channels) - 1, 0, -1):
790
+ feat_high = fpn_feature_maps[0]
791
+ feat_low = projected_features[idx - 1]
792
+ feat_high = self.lateral_convs[len(self.in_channels) - 1 - idx](feat_high)
793
+ fpn_feature_maps[0] = feat_high
794
+ upsample_feat = F.interpolate(feat_high, scale_factor=2.0, mode="nearest")
795
+ fps_map = self.fpn_blocks[len(self.in_channels) - 1 - idx](torch.concat([upsample_feat, feat_low], dim=1))
796
+ fpn_feature_maps.insert(0, fps_map)
797
+
798
+ # Path Aggregation Network (PAN)
799
+ fpn_states = [fpn_feature_maps[0]]
800
+ for idx in range(len(self.in_channels) - 1):
801
+ feat_low = fpn_states[-1]
802
+ feat_high = fpn_feature_maps[idx + 1]
803
+ downsample_feat = self.downsample_convs[idx](feat_low)
804
+ hidden_states = self.pan_blocks[idx](
805
+ torch.concat([downsample_feat, feat_high.to(downsample_feat.device)], dim=1)
806
+ )
807
+ fpn_states.append(hidden_states)
808
+ if not return_dict:
809
+ return (fpn_states[-1], encoder_states, all_attentions, fpn_states)
810
+ return OmDetTurboEncoderOutput(
811
+ last_hidden_state=fpn_states[-1],
812
+ hidden_states=encoder_states,
813
+ attentions=all_attentions,
814
+ extracted_states=fpn_states,
815
+ )
816
+
817
+
818
+ class OmDetTurboMLPWithDropout(nn.Module):
819
+ def __init__(self, config):
820
+ super().__init__()
821
+ self.linear1 = nn.Linear(config.class_embed_dim, config.task_encoder_hidden_dim)
822
+ self.activation = ACT2FN[config.decoder_activation]
823
+ self.dropout = nn.Dropout(config.decoder_dropout)
824
+ self.linear2 = nn.Linear(config.task_encoder_hidden_dim, config.class_embed_dim)
825
+
826
+ def forward(self, x):
827
+ return self.linear2(self.dropout(self.activation(self.linear1(x))))
828
+
829
+
830
+ class OmDetTurboMLP(nn.Module):
831
+ """Very simple multi-layer perceptron (also called FFN)"""
832
+
833
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
834
+ super().__init__()
835
+ self.num_layers = num_layers
836
+ hidden_layers_dims = [hidden_dim] * (num_layers - 1)
837
+ layers_dims = [input_dim] + hidden_layers_dims + [output_dim]
838
+ self.layers = nn.ModuleList(
839
+ [nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(layers_dims[:-1], layers_dims[1:])]
840
+ )
841
+
842
+ def forward(self, x):
843
+ for i, layer in enumerate(self.layers):
844
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
845
+ return x
846
+
847
+
848
+ class OmDetTurboResidualLayer(nn.Module):
849
+ """
850
+ A residual connection followed by a layer norm.
851
+ """
852
+
853
+ def __init__(self, config):
854
+ super().__init__()
855
+ self.norm1 = nn.LayerNorm(config.class_embed_dim, eps=config.layer_norm_eps)
856
+ self.dropout = nn.Dropout(config.decoder_dropout)
857
+
858
+ def forward(self, x, y):
859
+ return self.norm1(x + self.dropout(y))
860
+
861
+
862
+ class OmDetTurboTaskEncoder(nn.Module):
863
+ def __init__(self, config):
864
+ super().__init__()
865
+ self.mlp = OmDetTurboMLPWithDropout(config)
866
+ self.res1 = OmDetTurboResidualLayer(config)
867
+
868
+ def forward(self, x):
869
+ mlp_out = self.mlp(x)
870
+ x = self.res1(x, mlp_out)
871
+ return x
872
+
873
+
874
+ class OmDetTurboDeformableTransformerDecoderLayer(GradientCheckpointingLayer):
875
+ """
876
+ A single layer of the Deformable Transformer Decoder.
877
+ """
878
+
879
+ def __init__(self, config):
880
+ super().__init__()
881
+ # self attention
882
+ self.self_attn = OmDetTurboMultiheadAttention(
883
+ config,
884
+ hidden_size=config.decoder_hidden_dim,
885
+ num_attention_heads=config.decoder_num_heads,
886
+ dropout=config.decoder_dropout,
887
+ )
888
+ self.dropout1 = nn.Dropout(config.decoder_dropout)
889
+ self.norm1 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
890
+
891
+ # cross attention
892
+ self.cross_attn = OmDetTurboMultiscaleDeformableAttention(
893
+ config, num_heads=config.decoder_num_heads, n_points=config.decoder_num_points
894
+ )
895
+ self.dropout2 = nn.Dropout(config.decoder_dropout)
896
+ self.norm2 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
897
+
898
+ # feed forward network
899
+ self.linear1 = nn.Linear(config.decoder_hidden_dim, config.decoder_dim_feedforward)
900
+ self.act = ACT2FN[config.decoder_activation]
901
+ self.dropout3 = nn.Dropout(config.decoder_dropout)
902
+ self.linear2 = nn.Linear(config.decoder_dim_feedforward, config.decoder_hidden_dim)
903
+ self.dropout4 = nn.Dropout(config.decoder_dropout)
904
+ self.norm3 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
905
+
906
+ self.output_attentions = config.output_attentions
907
+ self.output_hidden_states = config.output_hidden_states
908
+
909
+ @staticmethod
910
+ def with_pos_embed(tensor, pos):
911
+ return tensor if pos is None else tensor + pos
912
+
913
+ def forward(
914
+ self,
915
+ decoder_embeddings,
916
+ task_features,
917
+ reference_points,
918
+ vision_features,
919
+ vision_shapes,
920
+ vision_shapes_list,
921
+ level_start_index=None,
922
+ attention_mask=None,
923
+ padding_mask=None,
924
+ query_position=None,
925
+ output_attentions=None,
926
+ output_hidden_states=None,
927
+ ):
928
+ output_attentions = output_attentions if output_attentions is not None else self.output_attentions
929
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.output_hidden_states
930
+
931
+ origin_embedding_len = decoder_embeddings.shape[1]
932
+
933
+ # self attention
934
+ query = key = self.with_pos_embed(decoder_embeddings, query_position)
935
+ # combine task_features with query, key, value
936
+ task_features = task_features.transpose(0, 1)
937
+ query = torch.cat((query, task_features), dim=1)
938
+ key = torch.cat((key, task_features), dim=1)
939
+ decoder_embeddings = torch.cat((decoder_embeddings, task_features), dim=1)
940
+
941
+ outputs = self.self_attn(
942
+ query,
943
+ key,
944
+ decoder_embeddings,
945
+ attention_mask=attention_mask,
946
+ output_attentions=output_attentions,
947
+ )
948
+ context, self_attention = outputs if output_attentions else (outputs[0], None)
949
+ decoder_embeddings = decoder_embeddings + self.dropout1(context)
950
+ decoder_embeddings = self.norm1(decoder_embeddings)
951
+
952
+ task_features = decoder_embeddings[:, origin_embedding_len:, :].transpose(0, 1)
953
+ decoder_embeddings = decoder_embeddings[:, :origin_embedding_len, :]
954
+
955
+ # cross attention
956
+ hidden_states = self.with_pos_embed(decoder_embeddings, query_position)
957
+ reference_points = reference_points.unsqueeze(2)
958
+ outputs, cross_attention = self.cross_attn(
959
+ hidden_states=hidden_states,
960
+ attention_mask=padding_mask,
961
+ encoder_hidden_states=vision_features,
962
+ reference_points=reference_points,
963
+ spatial_shapes=vision_shapes,
964
+ spatial_shapes_list=vision_shapes_list,
965
+ level_start_index=level_start_index,
966
+ )
967
+ decoder_embeddings = decoder_embeddings + self.dropout2(outputs)
968
+ residual = self.norm2(decoder_embeddings)
969
+
970
+ # feed forward network
971
+ decoder_embeddings = self.linear2(self.dropout3(self.act(self.linear1(residual))))
972
+ decoder_embeddings = residual + self.dropout4(decoder_embeddings)
973
+ decoder_embeddings = self.norm3(decoder_embeddings)
974
+
975
+ return (
976
+ decoder_embeddings,
977
+ task_features,
978
+ self_attention if output_attentions else None,
979
+ cross_attention if output_attentions else None,
980
+ )
981
+
982
+
983
+ @auto_docstring
984
+ class OmDetTurboPreTrainedModel(PreTrainedModel):
985
+ config: OmDetTurboConfig
986
+ base_model_prefix = "model"
987
+ main_input_name = "pixel_values"
988
+ input_modalities = ("image", "text")
989
+
990
+ @torch.no_grad()
991
+ def _init_weights(self, module):
992
+ def linear_init_(module_to_init):
993
+ bound = 1 / math.sqrt(module_to_init.weight.shape[0])
994
+ init.uniform_(module_to_init.weight, -bound, bound)
995
+ if hasattr(module_to_init, "bias") and module_to_init.bias is not None:
996
+ init.uniform_(module_to_init.bias, -bound, bound)
997
+
998
+ if isinstance(module, OmDetTurboEncoderLayer):
999
+ linear_init_(module.fc1)
1000
+ linear_init_(module.fc2)
1001
+ elif isinstance(module, OmDetTurboDecoder):
1002
+ init.constant_(module.encoder_bbox_head.layers[-1].weight, 0.0)
1003
+ init.constant_(module.encoder_bbox_head.layers[-1].bias, 0.0)
1004
+ for mlp in module.decoder_bbox_head:
1005
+ init.constant_(mlp.layers[-1].weight, 0.0)
1006
+ init.constant_(mlp.layers[-1].bias, 0.0)
1007
+ linear_init_(module.encoder_vision_features[0])
1008
+ init.xavier_uniform_(module.encoder_vision_features[0].weight)
1009
+ if module.learn_initial_query:
1010
+ init.xavier_uniform_(module.tgt_embed.weight)
1011
+ init.xavier_uniform_(module.query_position_head.layers[0].weight)
1012
+ init.xavier_uniform_(module.query_position_head.layers[1].weight)
1013
+ for layer in module.channel_projection_layers:
1014
+ init.xavier_uniform_(layer[0].weight)
1015
+ elif isinstance(module, OmDetTurboLanguageBackbone):
1016
+ init.normal_(module.text_projection, std=self.config.text_projection_in_dim**-0.5)
1017
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
1018
+ init.normal_(module.weight, mean=0.0, std=self.config.init_std)
1019
+ if module.bias is not None:
1020
+ init.zeros_(module.bias)
1021
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
1022
+ init.ones_(module.weight)
1023
+ init.zeros_(module.bias)
1024
+ if getattr(module, "running_mean", None) is not None:
1025
+ init.zeros_(module.running_mean)
1026
+ init.ones_(module.running_var)
1027
+ init.zeros_(module.num_batches_tracked)
1028
+
1029
+ def _set_gradient_checkpointing(self, module, value=False):
1030
+ if isinstance(module, OmDetTurboDecoder):
1031
+ module.gradient_checkpointing = value
1032
+
1033
+ @staticmethod
1034
+ def _get_cache_key_at_index(input_ids, attention_mask, index):
1035
+ input_ids = input_ids[index]
1036
+ input_mask = attention_mask[index]
1037
+ cache_key = tuple(input_ids[input_mask != 0].tolist())
1038
+ return cache_key
1039
+
1040
+ def get_cached_class_embeddings(self, classes_input_ids, classes_attention_mask):
1041
+ not_cached_index = []
1042
+ not_cached_classes = []
1043
+ total_embeddings = []
1044
+ for idx, _ in enumerate(classes_input_ids):
1045
+ cache_key = self._get_cache_key_at_index(classes_input_ids, classes_attention_mask, idx)
1046
+ if self.language_cache_class.has(cache_key):
1047
+ total_embeddings.append(self.language_cache_class.get(cache_key))
1048
+ else:
1049
+ total_embeddings.append(None)
1050
+ not_cached_index.append(idx)
1051
+ not_cached_classes.append(cache_key)
1052
+
1053
+ if not_cached_classes:
1054
+ not_cached_classes_ids = torch.stack([classes_input_ids[idx] for idx in not_cached_index])
1055
+ embeddings = self.language_backbone(not_cached_classes_ids, encode_type="class")
1056
+ for idx, emb in enumerate(embeddings):
1057
+ idx_to_put = not_cached_index[idx]
1058
+ total_embeddings[idx_to_put] = emb
1059
+ self.language_cache_class.put(not_cached_classes[idx], emb)
1060
+
1061
+ total_class_embs = torch.stack(total_embeddings).to(self.device)
1062
+ return total_class_embs
1063
+
1064
+ def get_cached_task_embeddings(self, tasks_input_ids, tasks_attention_mask):
1065
+ not_cached_index = []
1066
+ not_cached_tasks = []
1067
+ total_task_features = []
1068
+ total_task_masks = []
1069
+ for idx, _ in enumerate(tasks_input_ids):
1070
+ cache_key = self._get_cache_key_at_index(tasks_input_ids, tasks_attention_mask, idx)
1071
+ if self.language_cache_prompt.has(cache_key):
1072
+ task_feature, task_mask = self.language_cache_prompt.get(cache_key)
1073
+ total_task_features.append(task_feature)
1074
+ total_task_masks.append(task_mask)
1075
+ else:
1076
+ total_task_features.append(None)
1077
+ total_task_masks.append(None)
1078
+ not_cached_index.append(idx)
1079
+ not_cached_tasks.append(cache_key)
1080
+
1081
+ if not_cached_tasks:
1082
+ not_cached_index_ids = torch.stack([tasks_input_ids[idx] for idx in not_cached_index])
1083
+ not_cached_mask = torch.stack([tasks_attention_mask[idx] for idx in not_cached_index])
1084
+ embeddings, masks = self.language_backbone(not_cached_index_ids, mask=not_cached_mask, encode_type="task")
1085
+
1086
+ for idx in range(embeddings.shape[1]):
1087
+ emb = embeddings[:, [idx], :]
1088
+ idx_to_put = not_cached_index[idx]
1089
+ cur_mask = torch.unsqueeze(masks[idx], dim=0).to(self.device)
1090
+ total_task_features[idx_to_put] = emb
1091
+ total_task_masks[idx_to_put] = cur_mask
1092
+ self.language_cache_prompt.put(not_cached_tasks[idx], (emb, cur_mask))
1093
+
1094
+ # pad before concat if needed
1095
+ max_len = max(task.shape[0] for task in total_task_features)
1096
+ for idx, task in enumerate(total_task_features):
1097
+ if task.shape[0] < max_len:
1098
+ pad_size = max_len - task.shape[0]
1099
+ total_task_features[idx] = F.pad(task, (0, 0, 0, 0, 0, pad_size))
1100
+ total_task_masks[idx] = F.pad(total_task_masks[idx], (0, pad_size))
1101
+
1102
+ total_task_features = torch.cat(total_task_features, dim=1).to(self.device)
1103
+ total_task_masks = torch.cat(total_task_masks, dim=0).to(self.device)
1104
+
1105
+ return total_task_features, total_task_masks
1106
+
1107
+ def get_language_embedding(
1108
+ self,
1109
+ classes_input_ids,
1110
+ classes_attention_mask,
1111
+ tasks_input_ids,
1112
+ tasks_attention_mask,
1113
+ classes_structure,
1114
+ ):
1115
+ batched_classes_embeddings = self.get_cached_class_embeddings(classes_input_ids, classes_attention_mask)
1116
+ # regroup class embeddings using saved structure
1117
+ max_class_size = torch.max(classes_structure)
1118
+ class_embeddings_regrouped = []
1119
+ start = 0
1120
+ for size in classes_structure:
1121
+ pad_size = max_class_size - size
1122
+ class_embeddings_regrouped.append(
1123
+ F.pad(batched_classes_embeddings[start : start + size], (0, 0, 0, pad_size)).unsqueeze(1)
1124
+ )
1125
+ start += size
1126
+ class_embeddings = torch.cat(class_embeddings_regrouped, dim=1)
1127
+
1128
+ task_embeddings, task_mask = self.get_cached_task_embeddings(tasks_input_ids, tasks_attention_mask)
1129
+
1130
+ return class_embeddings, task_embeddings, task_mask
1131
+
1132
+
1133
+ def _cosine_similarity_scaled(a, b, logit_scale):
1134
+ a = a / a.norm(dim=2, keepdim=True).clamp_min(1e-12)
1135
+ b = b / b.norm(dim=1, keepdim=True).clamp_min(1e-12)
1136
+ logit_scale = logit_scale.exp()
1137
+ logits_per_image = logit_scale * torch.bmm(a, b)
1138
+ return logits_per_image
1139
+
1140
+
1141
+ def get_class_similarity(class_distance_type, cls_feature, class_proj):
1142
+ logit_scale = torch.tensor(1 / 0.07).log()
1143
+ if class_distance_type == "cosine":
1144
+ class_logits = _cosine_similarity_scaled(cls_feature, class_proj, logit_scale)
1145
+ elif class_distance_type == "dot":
1146
+ class_logits = torch.bmm(cls_feature, class_proj)
1147
+ else:
1148
+ raise Exception(f"Unknown class_distance_type {class_distance_type}")
1149
+ return class_logits
1150
+
1151
+
1152
+ def _inverse_sigmoid(x, eps=1e-5):
1153
+ x = x.clamp(min=0, max=1)
1154
+ x1 = x.clamp(min=eps)
1155
+ x2 = (1 - x).clamp(min=eps)
1156
+ return torch.log(x1 / x2)
1157
+
1158
+
1159
+ class OmDetTurboDecoder(OmDetTurboPreTrainedModel):
1160
+ def __init__(self, config: OmDetTurboConfig):
1161
+ self.config = config
1162
+ super().__init__(config)
1163
+ self.gradient_checkpointing = False
1164
+
1165
+ hidden_dim = config.decoder_hidden_dim
1166
+ self.num_queries = config.num_queries
1167
+ self.class_distance_type = config.class_distance_type
1168
+ self.learn_initial_query = config.learn_initial_query
1169
+
1170
+ # backbone feature projection
1171
+ self.channel_projection_layers = nn.ModuleList(
1172
+ nn.Sequential(nn.Conv2d(x, hidden_dim, 1, bias=False), nn.BatchNorm2d(hidden_dim))
1173
+ for x in config.vision_features_channels
1174
+ )
1175
+ self.task_encoder = OmDetTurboTaskEncoder(config)
1176
+ if config.class_embed_dim != hidden_dim:
1177
+ self.task_project = nn.Linear(config.class_embed_dim, hidden_dim)
1178
+
1179
+ # Transformer module
1180
+ self.layers = nn.ModuleList(
1181
+ [OmDetTurboDeformableTransformerDecoderLayer(config) for _ in range(config.decoder_num_layers)]
1182
+ )
1183
+ self.decoder_num_layers = config.decoder_num_layers
1184
+ # decoder embedding
1185
+ if self.learn_initial_query:
1186
+ self.tgt_embed = nn.Embedding(self.num_queries, hidden_dim)
1187
+ self.query_position_head = OmDetTurboMLP(
1188
+ input_dim=4, hidden_dim=2 * hidden_dim, output_dim=hidden_dim, num_layers=2
1189
+ )
1190
+
1191
+ # encoder head
1192
+ self.encoder_vision_features = nn.Sequential(
1193
+ nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim, eps=config.layer_norm_eps)
1194
+ )
1195
+ self.encoder_class_head = nn.Linear(config.class_embed_dim, hidden_dim)
1196
+ self.encoder_bbox_head = OmDetTurboMLP(input_dim=hidden_dim, hidden_dim=hidden_dim, output_dim=4, num_layers=3)
1197
+
1198
+ # decoder head
1199
+ self.decoder_class_head = nn.ModuleList(
1200
+ [nn.Linear(config.class_embed_dim, hidden_dim) for _ in range(config.decoder_num_layers)]
1201
+ )
1202
+ self.decoder_bbox_head = nn.ModuleList(
1203
+ [OmDetTurboMLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(config.decoder_num_layers)]
1204
+ )
1205
+
1206
+ # Initialize weights and apply final processing
1207
+ self.post_init()
1208
+
1209
+ @lru_cache(maxsize=32)
1210
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
1211
+ # We always generate anchors in float32 to preserve equivalence between
1212
+ # dynamic and static anchor inference
1213
+ # Ignore copy
1214
+ if spatial_shapes is None:
1215
+ raise ValueError("spatial_shapes must be provided")
1216
+
1217
+ anchors = []
1218
+ for level, (height, width) in enumerate(spatial_shapes):
1219
+ grid_y, grid_x = torch.meshgrid(
1220
+ torch.arange(end=height, dtype=dtype, device=device),
1221
+ torch.arange(end=width, dtype=dtype, device=device),
1222
+ indexing="ij",
1223
+ )
1224
+ grid_xy = torch.stack([grid_x, grid_y], -1)
1225
+ valid_wh = torch.tensor([width, height], dtype=dtype, device=device)
1226
+ grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_wh
1227
+ wh = torch.ones_like(grid_xy, dtype=dtype, device=device) * grid_size * (2.0**level)
1228
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
1229
+ # define the valid range for anchor coordinates
1230
+ eps = 1e-2
1231
+ anchors = torch.concat(anchors, 1)
1232
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
1233
+ anchors = torch.log(anchors / (1 - anchors))
1234
+ anchors = torch.where(valid_mask, anchors, torch.inf)
1235
+
1236
+ return anchors, valid_mask
1237
+
1238
+ def _get_encoder_input(self, vision_features):
1239
+ # get projection features
1240
+ vision_features = [self.channel_projection_layers[i](feat) for i, feat in enumerate(vision_features)]
1241
+ # get encoder inputs
1242
+ new_vision_features = []
1243
+ new_vision_shapes_list = []
1244
+ for feat in vision_features:
1245
+ height, width = feat.shape[2:]
1246
+ # [batch_size, channels, height, width] -> [batch_size, height*width, channels]
1247
+ new_vision_features.append(feat.flatten(2).permute(0, 2, 1))
1248
+ # [num_feature_levels, 2]
1249
+ new_vision_shapes_list.append((height, width))
1250
+
1251
+ # [batch_size, height*width, channels]
1252
+ new_vision_features = torch.cat(new_vision_features, 1)
1253
+ new_vision_shapes = torch.tensor(new_vision_shapes_list, dtype=torch.int64, device=vision_features[0].device)
1254
+ level_start_index = torch.cat((new_vision_shapes.new_zeros((1,)), new_vision_shapes.prod(1).cumsum(0)[:-1]))
1255
+
1256
+ return new_vision_features, new_vision_shapes, new_vision_shapes_list, level_start_index
1257
+
1258
+ def _get_decoder_input(
1259
+ self, vision_features, vision_shapes, class_features, denoise_embeddings=None, denoise_bboxes=None
1260
+ ):
1261
+ batch_size = len(vision_features)
1262
+ # prepare input for decoder
1263
+ anchors, valid_mask = self.generate_anchors(
1264
+ vision_shapes, device=vision_features.device, dtype=vision_features.dtype
1265
+ )
1266
+ predicted_class_features = self.encoder_vision_features(
1267
+ torch.where(
1268
+ valid_mask,
1269
+ vision_features,
1270
+ torch.tensor(0.0, dtype=vision_features.dtype, device=vision_features.device),
1271
+ )
1272
+ )
1273
+
1274
+ original_class_projected = self.encoder_class_head(class_features).permute(1, 2, 0)
1275
+ encoder_class_similarity = get_class_similarity(
1276
+ self.class_distance_type, predicted_class_features, original_class_projected
1277
+ )
1278
+
1279
+ # dynamic anchors + static content
1280
+ # (batch_size, height*width, 4)
1281
+ encoder_outputs_bboxes = self.encoder_bbox_head(predicted_class_features) + anchors
1282
+
1283
+ # query selection
1284
+ # (batch_size, num_queries)
1285
+ topk_ind = torch.topk(encoder_class_similarity.max(-1).values, self.num_queries, dim=1).indices.view(-1)
1286
+ # (batch_size, num_queries)
1287
+ batch_ind = (
1288
+ torch.arange(end=batch_size, dtype=topk_ind.dtype, device=topk_ind.device)
1289
+ .unsqueeze(-1)
1290
+ .repeat(1, self.num_queries)
1291
+ .view(-1)
1292
+ )
1293
+
1294
+ reference_points = encoder_outputs_bboxes[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
1295
+ encoder_bboxes = reference_points.sigmoid()
1296
+ if denoise_bboxes is not None:
1297
+ reference_points = torch.cat([denoise_bboxes, reference_points], 1)
1298
+ if self.training:
1299
+ reference_points = reference_points.detach()
1300
+ encoder_class_similarity = encoder_class_similarity[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
1301
+
1302
+ if self.learn_initial_query:
1303
+ embeddings = self.tgt_embed.weight.unsqueeze(0).repeat(batch_size, 1, 1)
1304
+ else:
1305
+ embeddings = predicted_class_features[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
1306
+ if self.training:
1307
+ embeddings = embeddings.detach()
1308
+ if denoise_embeddings is not None:
1309
+ embeddings = torch.cat([denoise_embeddings, embeddings], 1)
1310
+
1311
+ return embeddings, reference_points, encoder_bboxes, encoder_class_similarity, anchors
1312
+
1313
+ def forward(
1314
+ self,
1315
+ vision_features,
1316
+ class_features,
1317
+ task_features,
1318
+ task_mask,
1319
+ output_attentions=None,
1320
+ output_hidden_states=None,
1321
+ return_dict=None,
1322
+ **kwargs,
1323
+ ):
1324
+ """
1325
+ Args:
1326
+ vision_features (`torch.FloatTensor`): The sequence of vision features. shape depends on the vision
1327
+ backbone.
1328
+ class_features (`torch.FloatTensor`): The sequence of class features of shape
1329
+ `(class_sequence_length, batch_size, class_embed_dim)`.
1330
+ task_features (`torch.FloatTensor`): The sequence of task features of shape
1331
+ `(task_sequence_length, batch_size, decoder_hidden_dim)`.
1332
+ task_mask (`torch.LongTensor`): The mask for the task features of shape `(batch_size, task_sequence_length)`.
1333
+ output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention
1334
+ layers. See `attentions` under returned tensors for more detail.
1335
+ output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See
1336
+ `hidden_states` under returned tensors for more detail.
1337
+ return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain
1338
+ tuple.
1339
+ """
1340
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1341
+ output_hidden_states = (
1342
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1343
+ )
1344
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1345
+
1346
+ vision_features, vision_shapes, vision_shapes_list, level_start_index = self._get_encoder_input(
1347
+ vision_features
1348
+ )
1349
+
1350
+ # todo add denoising for training
1351
+ denoise_embeddings, denoise_bboxes, key_padding_mask = None, None, None
1352
+ batch_size = task_mask.shape[0]
1353
+
1354
+ # compose attn_mask for vision_emb and task_emb fusion
1355
+ task_features = self.task_encoder(task_features)
1356
+ if self.task_project is not None:
1357
+ task_features = self.task_project(task_features)
1358
+ src_key_mask = (task_mask == 0).detach()
1359
+ attn_mask_len = self.num_queries
1360
+ fusion_size = attn_mask_len + task_features.shape[0]
1361
+ key_padding_mask = torch.zeros([batch_size, fusion_size], dtype=torch.bool).to(task_features.device)
1362
+ key_padding_mask[:, attn_mask_len:] = src_key_mask
1363
+ decoder_embeddings, reference_points, encoder_bboxes, encoder_class_similarity, init_reference_points = (
1364
+ self._get_decoder_input(
1365
+ vision_features, tuple(vision_shapes_list), class_features, denoise_embeddings, denoise_bboxes
1366
+ )
1367
+ )
1368
+ attention_mask = create_bidirectional_mask(
1369
+ config=self.config,
1370
+ inputs_embeds=torch.ones_like(key_padding_mask, dtype=decoder_embeddings.dtype)[..., None],
1371
+ attention_mask=~key_padding_mask,
1372
+ )
1373
+
1374
+ all_hidden_states = () if output_hidden_states else None
1375
+ all_attns = () if output_attentions else None
1376
+ all_self_attns = () if output_attentions else None
1377
+ all_cross_attns = () if output_attentions else None
1378
+ predicted_class_features = decoder_embeddings
1379
+
1380
+ if output_hidden_states:
1381
+ all_hidden_states = all_hidden_states + (predicted_class_features,)
1382
+ decoder_bboxes = []
1383
+ decoder_classes = []
1384
+ last_refined_bbox = None
1385
+ reference_points = reference_points.sigmoid()
1386
+ for i, layer in enumerate(self.layers):
1387
+ predicted_class_features, task_features, self_attention, cross_attention = layer(
1388
+ predicted_class_features,
1389
+ task_features,
1390
+ reference_points,
1391
+ vision_features,
1392
+ vision_shapes,
1393
+ vision_shapes_list,
1394
+ level_start_index=level_start_index,
1395
+ attention_mask=attention_mask,
1396
+ query_position=self.query_position_head(reference_points),
1397
+ output_attentions=output_attentions,
1398
+ output_hidden_states=output_hidden_states,
1399
+ )
1400
+ if output_attentions:
1401
+ all_self_attns = all_self_attns + (self_attention,)
1402
+ all_cross_attns = all_cross_attns + (cross_attention,)
1403
+ if output_hidden_states:
1404
+ all_hidden_states = all_hidden_states + (predicted_class_features,)
1405
+
1406
+ refined_bbox = torch.sigmoid(
1407
+ self.decoder_bbox_head[i](predicted_class_features) + _inverse_sigmoid(reference_points)
1408
+ )
1409
+ original_class_projected = self.decoder_class_head[i](class_features).permute(1, 2, 0)
1410
+ if self.training:
1411
+ decoder_classes.append(
1412
+ get_class_similarity(
1413
+ class_distance_type=self.class_distance_type,
1414
+ cls_feature=predicted_class_features,
1415
+ class_proj=original_class_projected,
1416
+ )
1417
+ )
1418
+ if i == 0:
1419
+ decoder_bboxes.append(refined_bbox)
1420
+ else:
1421
+ decoder_bboxes.append(
1422
+ torch.sigmoid(
1423
+ self.decoder_bbox_head[i](predicted_class_features) + _inverse_sigmoid(last_refined_bbox)
1424
+ )
1425
+ )
1426
+ elif i == self.decoder_num_layers - 1:
1427
+ decoder_classes.append(
1428
+ get_class_similarity(self.class_distance_type, predicted_class_features, original_class_projected)
1429
+ )
1430
+ decoder_bboxes.append(refined_bbox)
1431
+ break
1432
+ last_refined_bbox = refined_bbox
1433
+ reference_points = refined_bbox.detach() if self.training else refined_bbox
1434
+ if output_attentions:
1435
+ all_attns += (all_self_attns, all_cross_attns)
1436
+
1437
+ last_hidden_state = predicted_class_features
1438
+ decoder_bboxes = torch.stack(decoder_bboxes)
1439
+ decoder_classes = torch.stack(decoder_classes)
1440
+
1441
+ if not return_dict:
1442
+ return (
1443
+ last_hidden_state,
1444
+ all_hidden_states,
1445
+ all_attns,
1446
+ decoder_bboxes,
1447
+ decoder_classes,
1448
+ encoder_bboxes,
1449
+ encoder_class_similarity,
1450
+ init_reference_points,
1451
+ reference_points,
1452
+ )
1453
+
1454
+ return OmDetTurboDecoderOutput(
1455
+ last_hidden_state=last_hidden_state,
1456
+ hidden_states=all_hidden_states,
1457
+ attentions=all_attns,
1458
+ decoder_coords=decoder_bboxes,
1459
+ decoder_classes=decoder_classes,
1460
+ encoder_coord_logits=encoder_bboxes,
1461
+ encoder_class_logits=encoder_class_similarity,
1462
+ init_reference_points=init_reference_points,
1463
+ intermediate_reference_points=reference_points,
1464
+ )
1465
+
1466
+
1467
+ @auto_docstring(
1468
+ custom_intro="""
1469
+ OmDetTurbo Model (consisting of a vision and a text backbone, and encoder-decoder architecture) outputting
1470
+ bounding boxes and classes scores for tasks such as COCO detection.
1471
+ """
1472
+ )
1473
+ class OmDetTurboForObjectDetection(OmDetTurboPreTrainedModel):
1474
+ def __init__(self, config: OmDetTurboConfig):
1475
+ super().__init__(config)
1476
+ self.vision_backbone = OmDetTurboVisionBackbone(config)
1477
+ self.language_backbone = OmDetTurboLanguageBackbone(config)
1478
+ self.encoder = OmDetTurboHybridEncoder(config)
1479
+ self.decoder = OmDetTurboDecoder(config)
1480
+ self.num_queries = config.num_queries
1481
+
1482
+ self.language_cache_class = OmDetTurboLRUCache(config.cache_size)
1483
+ self.language_cache_prompt = OmDetTurboLRUCache(config.cache_size)
1484
+ self.vocab_size = config.text_config.vocab_size
1485
+ self.post_init()
1486
+
1487
+ def get_input_embeddings(self):
1488
+ return self.language_backbone.model.get_input_embeddings()
1489
+
1490
+ def set_input_embeddings(self, value):
1491
+ self.language_backbone.model.set_input_embeddings(value)
1492
+
1493
+ def resize_token_embeddings(
1494
+ self, new_num_tokens: int | None = None, pad_to_multiple_of=None, mean_resizing: bool = True
1495
+ ) -> nn.Embedding:
1496
+ model_embeds = self.language_backbone.model.resize_token_embeddings(
1497
+ new_num_tokens=new_num_tokens, pad_to_multiple_of=pad_to_multiple_of, mean_resizing=mean_resizing
1498
+ )
1499
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
1500
+ self.vocab_size = model_embeds.num_embeddings
1501
+ return model_embeds
1502
+
1503
+ @auto_docstring
1504
+ def forward(
1505
+ self,
1506
+ pixel_values: torch.FloatTensor,
1507
+ classes_input_ids: torch.LongTensor,
1508
+ classes_attention_mask: torch.LongTensor,
1509
+ tasks_input_ids: torch.LongTensor,
1510
+ tasks_attention_mask: torch.LongTensor,
1511
+ classes_structure: torch.LongTensor,
1512
+ labels: torch.LongTensor | None = None,
1513
+ output_attentions: bool | None = None,
1514
+ output_hidden_states: bool | None = None,
1515
+ return_dict: bool | None = None,
1516
+ **kwargs,
1517
+ ) -> tuple[torch.FloatTensor] | OmDetTurboObjectDetectionOutput:
1518
+ r"""
1519
+ classes_input_ids (`torch.LongTensor` of shape `(total_classes (>= batch_size), sequence_length)`):
1520
+ Indices of input classes sequence tokens in the vocabulary of the language model.
1521
+ Several classes can be provided for each tasks, thus the tokenized classes are flattened
1522
+ and the structure of the classes is provided in the `classes_structure` argument.
1523
+
1524
+ Indices can be obtained using [`OmDetTurboProcessor`]. See [`OmDetTurboProcessor.__call__`] for
1525
+ details.
1526
+
1527
+ [What are input IDs?](../glossary#input-ids)
1528
+ classes_attention_mask (`torch.BoolTensor` of shape `(total_classes (>= batch_size), num_classes, sequence_length)`):
1529
+ Attention mask for the classes. This is a binary mask that indicates which tokens should be attended to,
1530
+ and which should not.
1531
+ tasks_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1532
+ Indices of input tasks sequence tokens in the vocabulary of the language model.
1533
+
1534
+ Indices can be obtained using [`OmDetTurboProcessor`]. See [`OmDetTurboProcessor.__call__`] for
1535
+ details.
1536
+
1537
+ [What are input IDs?](../glossary#input-ids)
1538
+ tasks_attention_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
1539
+ Attention mask for the tasks. This is a binary mask that indicates which tokens should be attended to,
1540
+ and which should not.
1541
+ classes_structure (torch.LongTensor of shape `(batch_size)`):
1542
+ Structure of the classes. This tensor indicates the number of classes for each task.
1543
+
1544
+ Examples:
1545
+
1546
+ ```python
1547
+ >>> import httpx
1548
+ >>> from io import BytesIO
1549
+ >>> from PIL import Image
1550
+
1551
+ >>> from transformers import AutoProcessor, OmDetTurboForObjectDetection
1552
+
1553
+ >>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
1554
+ >>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
1555
+
1556
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1557
+ >>> with httpx.stream("GET", url) as response:
1558
+ ... image = Image.open(BytesIO(response.read()))
1559
+ >>> classes = ["cat", "remote"]
1560
+ >>> task = "Detect {}.".format(", ".join(classes))
1561
+ >>> inputs = processor(image, text=classes, task=task, return_tensors="pt")
1562
+
1563
+ >>> outputs = model(**inputs)
1564
+
1565
+ >>> # convert outputs (bounding boxes and class logits)
1566
+ >>> results = processor.post_process_grounded_object_detection(
1567
+ ... outputs,
1568
+ ... classes=classes,
1569
+ ... target_sizes=[image.size[::-1]],
1570
+ ... score_threshold=0.3,
1571
+ ... nms_threshold=0.3,
1572
+ >>> )[0]
1573
+ >>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
1574
+ ... box = [round(i, 1) for i in box.tolist()]
1575
+ ... print(
1576
+ ... f"Detected {class_name} with confidence "
1577
+ ... f"{round(score.item(), 2)} at location {box}"
1578
+ ... )
1579
+ Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
1580
+ Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
1581
+ Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
1582
+ Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]
1583
+ ```"""
1584
+ if labels is not None:
1585
+ raise NotImplementedError("Training is not implemented yet")
1586
+
1587
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1588
+ output_hidden_states = (
1589
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1590
+ )
1591
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1592
+
1593
+ loss = None
1594
+ image_features = self.vision_backbone(pixel_values)
1595
+ encoder_outputs = self.encoder(
1596
+ image_features,
1597
+ output_attentions=output_attentions,
1598
+ output_hidden_states=output_hidden_states,
1599
+ return_dict=return_dict,
1600
+ )
1601
+ class_features, task_features, task_mask = self.get_language_embedding(
1602
+ classes_input_ids,
1603
+ classes_attention_mask,
1604
+ tasks_input_ids,
1605
+ tasks_attention_mask,
1606
+ classes_structure,
1607
+ )
1608
+ encoder_extracted_states = encoder_outputs.extracted_states if return_dict else encoder_outputs[-1]
1609
+ decoder_outputs = self.decoder(
1610
+ encoder_extracted_states,
1611
+ class_features,
1612
+ task_features,
1613
+ task_mask,
1614
+ output_attentions=output_attentions,
1615
+ output_hidden_states=output_hidden_states,
1616
+ return_dict=return_dict,
1617
+ )
1618
+
1619
+ if not return_dict:
1620
+ return tuple(
1621
+ output
1622
+ for output in [
1623
+ loss,
1624
+ decoder_outputs[3][-1],
1625
+ decoder_outputs[4][-1],
1626
+ decoder_outputs[7],
1627
+ decoder_outputs[8],
1628
+ decoder_outputs[5],
1629
+ decoder_outputs[6],
1630
+ encoder_outputs[-1],
1631
+ decoder_outputs[1],
1632
+ decoder_outputs[2],
1633
+ encoder_outputs[1],
1634
+ encoder_outputs[2],
1635
+ classes_structure,
1636
+ ]
1637
+ if output is not None
1638
+ )
1639
+
1640
+ return OmDetTurboObjectDetectionOutput(
1641
+ loss=loss,
1642
+ decoder_coord_logits=decoder_outputs.decoder_coords[-1],
1643
+ decoder_class_logits=decoder_outputs.decoder_classes[-1],
1644
+ init_reference_points=decoder_outputs.init_reference_points,
1645
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
1646
+ encoder_coord_logits=decoder_outputs.encoder_coord_logits,
1647
+ encoder_class_logits=decoder_outputs.encoder_class_logits,
1648
+ encoder_extracted_states=encoder_outputs.extracted_states,
1649
+ decoder_hidden_states=decoder_outputs.hidden_states,
1650
+ decoder_attentions=decoder_outputs.attentions,
1651
+ encoder_hidden_states=encoder_outputs.hidden_states,
1652
+ encoder_attentions=encoder_outputs.attentions,
1653
+ classes_structure=classes_structure,
1654
+ )
1655
+
1656
+
1657
+ __all__ = ["OmDetTurboForObjectDetection", "OmDetTurboPreTrainedModel"]
lib/python3.11/site-packages/transformers/models/omdet_turbo/processing_omdet_turbo.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Processor class for OmDet-Turbo.
16
+ """
17
+
18
+ from typing import TYPE_CHECKING
19
+
20
+ from ...feature_extraction_utils import BatchFeature
21
+ from ...image_transforms import center_to_corners_format
22
+ from ...image_utils import ImageInput
23
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
24
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
25
+ from ...utils import (
26
+ TensorType,
27
+ auto_docstring,
28
+ is_torch_available,
29
+ is_torchvision_available,
30
+ )
31
+ from ...utils.import_utils import requires
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ from .modeling_omdet_turbo import OmDetTurboObjectDetectionOutput
36
+
37
+
38
+ class OmDetTurboTextKwargs(TextKwargs, total=False):
39
+ """
40
+ task (`str`, `list[str]`, `TextInput`, or `PreTokenizedInput`, *optional*):
41
+ The detection task description(s) to encode. If not provided, a default task description is generated
42
+ from the `text` input (e.g., "Detect {text}."). Can be a single string, a list of strings (one per image),
43
+ or pre-tokenized input. The task description guides the model on what objects to detect in the images.
44
+ """
45
+
46
+ task: str | list[str] | TextInput | PreTokenizedInput | None
47
+
48
+
49
+ if is_torch_available():
50
+ import torch
51
+
52
+
53
+ if is_torchvision_available():
54
+ from torchvision.ops.boxes import batched_nms
55
+
56
+
57
+ class OmDetTurboProcessorKwargs(ProcessingKwargs, total=False):
58
+ text_kwargs: OmDetTurboTextKwargs
59
+ _defaults = {
60
+ "text_kwargs": {
61
+ "add_special_tokens": True,
62
+ "padding": "max_length",
63
+ "truncation": True,
64
+ "max_length": 77,
65
+ "stride": 0,
66
+ "return_overflowing_tokens": False,
67
+ "return_special_tokens_mask": False,
68
+ "return_offsets_mapping": False,
69
+ "return_token_type_ids": False,
70
+ "return_length": False,
71
+ "verbose": True,
72
+ "task": None,
73
+ },
74
+ }
75
+
76
+
77
+ def clip_boxes(box, box_size: tuple[int, int]):
78
+ """
79
+ Clip the boxes by limiting x coordinates to the range [0, width]
80
+ and y coordinates to the range [0, height].
81
+
82
+ Args:
83
+ box (Tensor): The box to be clipped.
84
+ box_size (height, width): The clipping box's size.
85
+ """
86
+ assert torch.isfinite(box).all(), "Box tensor contains infinite or NaN!"
87
+ height, width = box_size
88
+ x1 = box[:, 0].clamp(min=0, max=width)
89
+ y1 = box[:, 1].clamp(min=0, max=height)
90
+ x2 = box[:, 2].clamp(min=0, max=width)
91
+ y2 = box[:, 3].clamp(min=0, max=height)
92
+ box = torch.stack((x1, y1, x2, y2), dim=-1)
93
+
94
+ return box
95
+
96
+
97
+ def compute_score(boxes):
98
+ """
99
+ Compute logit scores per class for each box (proposal) and an array of class indices
100
+ corresponding to each proposal, flattened across the proposal_num.
101
+ The indices in `classes` will later be used to filter and match the predicted classes
102
+ with the input class names.
103
+ """
104
+ num_classes = boxes.shape[2]
105
+ proposal_num = boxes.shape[1]
106
+ scores = torch.sigmoid(boxes)
107
+ classes = torch.arange(num_classes, device=boxes.device).unsqueeze(0).repeat(proposal_num, 1).flatten(0, 1)
108
+ return scores, classes
109
+
110
+
111
+ def _post_process_boxes_for_image(
112
+ boxes: "torch.Tensor",
113
+ scores: "torch.Tensor",
114
+ labels: "torch.Tensor",
115
+ image_num_classes: int,
116
+ image_size: tuple[int, int],
117
+ threshold: float,
118
+ nms_threshold: float,
119
+ max_num_det: int | None = None,
120
+ ) -> tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]:
121
+ """
122
+ Filter predicted results using given thresholds and NMS.
123
+
124
+ Args:
125
+ boxes (`torch.Tensor`):
126
+ A Tensor of predicted class-specific or class-agnostic boxes for the image.
127
+ Shape (num_queries, max_num_classes_in_batch * 4) if doing class-specific regression,
128
+ or (num_queries, 4) if doing class-agnostic regression.
129
+ scores (`torch.Tensor` of shape (num_queries, max_num_classes_in_batch + 1)):
130
+ A Tensor of predicted class scores for the image.
131
+ labels (`torch.Tensor` of shape (num_queries * (max_num_classes_in_batch + 1),)):
132
+ A Tensor of predicted labels for the image.
133
+ image_num_classes (`int`):
134
+ The number of classes queried for detection on the image.
135
+ image_size (`tuple[int, int]`):
136
+ A tuple of (height, width) for the image.
137
+ threshold (`float`):
138
+ Only return detections with a confidence score exceeding this threshold.
139
+ nms_threshold (`float`):
140
+ The threshold to use for box non-maximum suppression. Value in [0, 1].
141
+ max_num_det (`int`, *optional*):
142
+ The maximum number of detections to return. Default is None.
143
+
144
+ Returns:
145
+ Tuple: A tuple with the following:
146
+ "boxes" (Tensor): A tensor of shape (num_filtered_objects, 4), containing the predicted boxes in (x1, y1, x2, y2) format.
147
+ "scores" (Tensor): A tensor of shape (num_filtered_objects,), containing the predicted confidence scores for each detection.
148
+ "labels" (Tensor): A tensor of ids, where each id is the predicted class id for the corresponding detection
149
+ """
150
+
151
+ # Filter by max number of detections
152
+ proposal_num = len(boxes) if max_num_det is None else max_num_det
153
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(proposal_num, sorted=False)
154
+ labels_per_image = labels[topk_indices]
155
+ boxes_per_image = boxes.view(-1, 1, 4).repeat(1, scores.shape[1], 1).view(-1, 4)
156
+ boxes_per_image = boxes_per_image[topk_indices]
157
+
158
+ # Convert and scale boxes to original image size
159
+ boxes_per_image = center_to_corners_format(boxes_per_image)
160
+ boxes_per_image = boxes_per_image * torch.tensor(image_size[::-1]).repeat(2).to(boxes_per_image.device)
161
+
162
+ # Filtering by confidence score
163
+ filter_mask = scores_per_image > threshold # R x K
164
+ score_keep = filter_mask.nonzero(as_tuple=False).view(-1)
165
+ boxes_per_image = boxes_per_image[score_keep]
166
+ scores_per_image = scores_per_image[score_keep]
167
+ labels_per_image = labels_per_image[score_keep]
168
+
169
+ # Ensure we did not overflow to non existing classes
170
+ filter_classes_mask = labels_per_image < image_num_classes
171
+ classes_keep = filter_classes_mask.nonzero(as_tuple=False).view(-1)
172
+ boxes_per_image = boxes_per_image[classes_keep]
173
+ scores_per_image = scores_per_image[classes_keep]
174
+ labels_per_image = labels_per_image[classes_keep]
175
+
176
+ # NMS
177
+ keep = batched_nms(boxes_per_image, scores_per_image, labels_per_image, nms_threshold)
178
+ boxes_per_image = boxes_per_image[keep]
179
+ scores_per_image = scores_per_image[keep]
180
+ labels_per_image = labels_per_image[keep]
181
+
182
+ # Clip to image size
183
+ boxes_per_image = clip_boxes(boxes_per_image, image_size)
184
+
185
+ return boxes_per_image, scores_per_image, labels_per_image
186
+
187
+
188
+ @requires(backends=("vision", "torchvision"))
189
+ @auto_docstring
190
+ class OmDetTurboProcessor(ProcessorMixin):
191
+ def __init__(self, image_processor, tokenizer):
192
+ super().__init__(image_processor, tokenizer)
193
+
194
+ @auto_docstring
195
+ def __call__(
196
+ self,
197
+ images: ImageInput | None = None,
198
+ text: list[str] | list[list[str]] | None = None,
199
+ **kwargs: Unpack[OmDetTurboProcessorKwargs],
200
+ ) -> BatchFeature:
201
+ if images is None or text is None:
202
+ raise ValueError("You have to specify both `images` and `text`")
203
+
204
+ output_kwargs = self._merge_kwargs(
205
+ OmDetTurboProcessorKwargs,
206
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
207
+ **kwargs,
208
+ )
209
+
210
+ if isinstance(text, str):
211
+ text = text.strip(" ").split(",")
212
+
213
+ if not (len(text) and isinstance(text[0], (list, tuple))):
214
+ text = [text]
215
+
216
+ task = output_kwargs["text_kwargs"].pop("task", None)
217
+ if task is None:
218
+ task = [f"Detect {', '.join(text_single)}." for text_single in text]
219
+ elif not isinstance(task, (list, tuple)):
220
+ task = [task]
221
+
222
+ encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
223
+ tasks_encoding = self.tokenizer(text=task, **output_kwargs["text_kwargs"])
224
+
225
+ classes = text
226
+
227
+ classes_structure = torch.tensor([len(class_single) for class_single in classes], dtype=torch.long)
228
+ classes_flattened = [class_single for class_batch in classes for class_single in class_batch]
229
+ classes_encoding = self.tokenizer(text=classes_flattened, **output_kwargs["text_kwargs"])
230
+
231
+ encoding = BatchFeature()
232
+ encoding.update({f"tasks_{key}": value for key, value in tasks_encoding.items()})
233
+ encoding.update({f"classes_{key}": value for key, value in classes_encoding.items()})
234
+ encoding.update({"classes_structure": classes_structure})
235
+ encoding.update(encoding_image_processor)
236
+
237
+ return encoding
238
+
239
+ @property
240
+ def model_input_names(self):
241
+ image_processor_input_names = self.image_processor.model_input_names
242
+ tokenizer_input_names = [
243
+ "classes_attention_mask",
244
+ "tasks_attention_mask",
245
+ "tasks_input_ids",
246
+ "classes_input_ids",
247
+ "classes_structure",
248
+ ]
249
+ return tokenizer_input_names + image_processor_input_names
250
+
251
+ def _get_default_image_size(self) -> tuple[int, int]:
252
+ height = (
253
+ self.image_processor.size["height"]
254
+ if "height" in self.image_processor.size
255
+ else self.image_processor.size["shortest_edge"]
256
+ )
257
+ width = (
258
+ self.image_processor.size["width"]
259
+ if "width" in self.image_processor.size
260
+ else self.image_processor.size["longest_edge"]
261
+ )
262
+ return height, width
263
+
264
+ def post_process_grounded_object_detection(
265
+ self,
266
+ outputs: "OmDetTurboObjectDetectionOutput",
267
+ text_labels: list[str] | list[list[str]] | None = None,
268
+ threshold: float = 0.3,
269
+ nms_threshold: float = 0.5,
270
+ target_sizes: TensorType | list[tuple] | None = None,
271
+ max_num_det: int | None = None,
272
+ ):
273
+ """
274
+ Converts the raw output of [`OmDetTurboForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
275
+ bottom_right_x, bottom_right_y) format and get the associated text class.
276
+
277
+ Args:
278
+ outputs ([`OmDetTurboObjectDetectionOutput`]):
279
+ Raw outputs of the model.
280
+ text_labels (Union[list[str], list[list[str]]], *optional*):
281
+ The input classes names. If not provided, `text_labels` will be set to `None` in `outputs`.
282
+ threshold (float, defaults to 0.3):
283
+ Only return detections with a confidence score exceeding this threshold.
284
+ nms_threshold (float, defaults to 0.5):
285
+ The threshold to use for box non-maximum suppression. Value in [0, 1].
286
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
287
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
288
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
289
+ max_num_det (`int`, *optional*):
290
+ The maximum number of detections to return.
291
+ Returns:
292
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, classes and boxes for an image
293
+ in the batch as predicted by the model.
294
+ """
295
+
296
+ batch_size = len(outputs.decoder_coord_logits)
297
+
298
+ # Inputs consistency check for target sizes
299
+ if target_sizes is None:
300
+ height, width = self._get_default_image_size()
301
+ target_sizes = [(height, width)] * batch_size
302
+
303
+ if any(len(image_size) != 2 for image_size in target_sizes):
304
+ raise ValueError(
305
+ "Each element of target_sizes must contain the size (height, width) of each image of the batch"
306
+ )
307
+
308
+ if len(target_sizes) != batch_size:
309
+ raise ValueError("Make sure that you pass in as many target sizes as output sequences")
310
+
311
+ # Inputs consistency check for text labels
312
+ if text_labels is not None and isinstance(text_labels[0], str):
313
+ text_labels = [text_labels]
314
+
315
+ if text_labels is not None and len(text_labels) != batch_size:
316
+ raise ValueError("Make sure that you pass in as many classes group as output sequences")
317
+
318
+ # Convert target_sizes to list for easier handling
319
+ if isinstance(target_sizes, torch.Tensor):
320
+ target_sizes = target_sizes.tolist()
321
+
322
+ batch_boxes = outputs.decoder_coord_logits
323
+ batch_logits = outputs.decoder_class_logits
324
+ batch_num_classes = outputs.classes_structure
325
+
326
+ batch_scores, batch_labels = compute_score(batch_logits)
327
+
328
+ results = []
329
+ for boxes, scores, image_size, image_num_classes in zip(
330
+ batch_boxes, batch_scores, target_sizes, batch_num_classes
331
+ ):
332
+ boxes, scores, labels = _post_process_boxes_for_image(
333
+ boxes=boxes,
334
+ scores=scores,
335
+ labels=batch_labels,
336
+ image_num_classes=image_num_classes,
337
+ image_size=image_size,
338
+ threshold=threshold,
339
+ nms_threshold=nms_threshold,
340
+ max_num_det=max_num_det,
341
+ )
342
+ result = {"boxes": boxes, "scores": scores, "labels": labels, "text_labels": None}
343
+ results.append(result)
344
+
345
+ # Add text labels
346
+ if text_labels is not None:
347
+ for result, image_text_labels in zip(results, text_labels):
348
+ result["text_labels"] = [image_text_labels[idx] for idx in result["labels"]]
349
+
350
+ return results
351
+
352
+
353
+ __all__ = ["OmDetTurboProcessor"]
lib/python3.11/site-packages/transformers/models/oneformer/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_oneformer import *
22
+ from .image_processing_oneformer import *
23
+ from .image_processing_pil_oneformer import *
24
+ from .modeling_oneformer import *
25
+ from .processing_oneformer import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (929 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-311.pyc ADDED
Binary file (8.06 kB). View file
 
lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-311.pyc ADDED
Binary file (44.4 kB). View file
 
lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-311.pyc ADDED
Binary file (47.7 kB). View file
 
lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/processing_oneformer.cpython-311.pyc ADDED
Binary file (9.88 kB). View file
 
lib/python3.11/site-packages/transformers/models/oneformer/configuration_oneformer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 SHI Labs 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
+ """OneFormer model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+ from ..auto import AutoConfig
22
+
23
+
24
+ @auto_docstring(checkpoint="shi-labs/oneformer_ade20k_swin_tiny")
25
+ @strict
26
+ class OneFormerConfig(PreTrainedConfig):
27
+ r"""
28
+ ignore_value (`int`, *optional*, defaults to 255):
29
+ Values to be ignored in GT label while calculating loss.
30
+ num_queries (`int`, *optional*, defaults to 150):
31
+ Number of object queries.
32
+ contrastive_weight (`float`, *optional*, defaults to 0.5):
33
+ Weight for contrastive loss.
34
+ contrastive_temperature (`float`, *optional*, defaults to 0.07):
35
+ Initial value for scaling the contrastive logits.
36
+ train_num_points (`int`, *optional*, defaults to 12544):
37
+ Number of points to sample while calculating losses on mask predictions.
38
+ oversample_ratio (`float`, *optional*, defaults to 3.0):
39
+ Ratio to decide how many points to oversample.
40
+ importance_sample_ratio (`float`, *optional*, defaults to 0.75):
41
+ Ratio of points that are sampled via importance sampling..
42
+ is_training (`bool`, *optional*, defaults to `False`):
43
+ Whether to run in training or inference mode.
44
+ output_auxiliary_logits (`bool`, *optional*, defaults to `True`):
45
+ Whether to return intermediate predictions from transformer decoder.
46
+ strides (`list`, *optional*, defaults to `[4, 8, 16, 32]`):
47
+ List containing the strides for feature maps in the encoder.
48
+ task_seq_len (`int`, *optional*, defaults to 77):
49
+ Sequence length for tokenizing text list input.
50
+ text_encoder_width (`int`, *optional*, defaults to 256):
51
+ Hidden size for text encoder.
52
+ text_encoder_context_length (`int`, *optional*, defaults to 77):
53
+ Input sequence length for text encoder.
54
+ text_encoder_num_layers (`int`, *optional*, defaults to 6):
55
+ Number of layers for transformer in text encoder.
56
+ text_encoder_vocab_size (`int`, *optional*, defaults to 49408):
57
+ Vocabulary size for tokenizer.
58
+ text_encoder_proj_layers (`int`, *optional*, defaults to 2):
59
+ Number of layers in MLP for project text queries.
60
+ text_encoder_n_ctx (`int`, *optional*, defaults to 16):
61
+ Number of learnable text context queries.
62
+ conv_dim (`int`, *optional*, defaults to 256):
63
+ Feature map dimension to map outputs from the backbone.
64
+ mask_dim (`int`, *optional*, defaults to 256):
65
+ Dimension for feature maps in pixel decoder.
66
+ hidden_dim (`int`, *optional*, defaults to 256):
67
+ Dimension for hidden states in transformer decoder.
68
+ encoder_feedforward_dim (`int`, *optional*, defaults to 1024):
69
+ Dimension for FFN layer in pixel decoder.
70
+ norm (`str`, *optional*, defaults to `"GN"`):
71
+ Type of normalization.
72
+ use_task_norm (`bool`, *optional*, defaults to `True`):
73
+ Whether to normalize the task token.
74
+ dim_feedforward (`int`, *optional*, defaults to 2048):
75
+ Dimension for FFN layer in transformer decoder.
76
+ pre_norm (`bool`, *optional*, defaults to `False`):
77
+ Whether to normalize hidden states before attention layers in transformer decoder.
78
+ enforce_input_proj (`bool`, *optional*, defaults to `False`):
79
+ Whether to project hidden states in transformer decoder.
80
+ query_dec_layers (`int`, *optional*, defaults to 2):
81
+ Number of layers in query transformer.
82
+ common_stride (`int`, *optional*, defaults to 4):
83
+ Common stride used for features in pixel decoder.
84
+
85
+ Examples:
86
+ ```python
87
+ >>> from transformers import OneFormerConfig, OneFormerModel
88
+
89
+ >>> # Initializing a OneFormer shi-labs/oneformer_ade20k_swin_tiny configuration
90
+ >>> configuration = OneFormerConfig()
91
+ >>> # Initializing a model (with random weights) from the shi-labs/oneformer_ade20k_swin_tiny style configuration
92
+ >>> model = OneFormerModel(configuration)
93
+ >>> # Accessing the model configuration
94
+ >>> configuration = model.config
95
+ ```
96
+ """
97
+
98
+ model_type = "oneformer"
99
+ sub_configs = {"backbone_config": AutoConfig}
100
+ attribute_map = {"hidden_size": "hidden_dim", "num_hidden_layers": "decoder_layers"}
101
+
102
+ backbone_config: dict | PreTrainedConfig | None = None
103
+ ignore_value: int = 255
104
+ num_queries: int = 150
105
+ no_object_weight: float = 0.1
106
+ class_weight: float = 2.0
107
+ mask_weight: float = 5.0
108
+ dice_weight: float = 5.0
109
+ contrastive_weight: float = 0.5
110
+ contrastive_temperature: float = 0.07
111
+ train_num_points: int = 12544
112
+ oversample_ratio: float = 3.0
113
+ importance_sample_ratio: float = 0.75
114
+ init_std: float = 0.02
115
+ init_xavier_std: float = 1.0
116
+ layer_norm_eps: float = 1e-05
117
+ is_training: bool = False
118
+ use_auxiliary_loss: bool = True
119
+ output_auxiliary_logits: bool = True
120
+ strides: list[int] | tuple[int, ...] = (4, 8, 16, 32)
121
+ task_seq_len: int = 77
122
+ text_encoder_width: int = 256
123
+ text_encoder_context_length: int = 77
124
+ text_encoder_num_layers: int = 6
125
+ text_encoder_vocab_size: int = 49408
126
+ text_encoder_proj_layers: int = 2
127
+ text_encoder_n_ctx: int = 16
128
+ conv_dim: int = 256
129
+ mask_dim: int = 256
130
+ hidden_dim: int = 256
131
+ encoder_feedforward_dim: int = 1024
132
+ norm: str = "GN"
133
+ encoder_layers: int = 6
134
+ decoder_layers: int = 10
135
+ use_task_norm: bool = True
136
+ num_attention_heads: int = 8
137
+ dropout: float | int = 0.1
138
+ dim_feedforward: int = 2048
139
+ pre_norm: bool = False
140
+ enforce_input_proj: bool = False
141
+ query_dec_layers: int = 2
142
+ common_stride: int = 4
143
+
144
+ def __post_init__(self, **kwargs):
145
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
146
+ backbone_config=self.backbone_config,
147
+ default_config_type="swin",
148
+ default_config_kwargs={
149
+ "drop_path_rate": 0.3,
150
+ "out_features": ["stage1", "stage2", "stage3", "stage4"],
151
+ },
152
+ **kwargs,
153
+ )
154
+
155
+ super().__post_init__(**kwargs)
156
+
157
+
158
+ __all__ = ["OneFormerConfig"]
lib/python3.11/site-packages/transformers/models/oneformer/image_processing_oneformer.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 SHI Labs 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
+ """Image processor class for OneFormer."""
15
+
16
+ import json
17
+ import os
18
+ from typing import Union
19
+
20
+ import torch
21
+ from torch import nn
22
+ from torchvision.transforms.v2 import functional as tvF
23
+
24
+ from ...image_processing_backends import TorchvisionBackend
25
+ from ...image_processing_utils import BatchFeature
26
+ from ...image_transforms import group_images_by_shape, reorder_images
27
+ from ...image_utils import (
28
+ IMAGENET_DEFAULT_MEAN,
29
+ IMAGENET_DEFAULT_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ SizeDict,
34
+ get_max_height_width,
35
+ )
36
+ from ...processing_utils import ImagesKwargs, Unpack
37
+ from ...utils import (
38
+ TensorType,
39
+ auto_docstring,
40
+ logging,
41
+ )
42
+
43
+
44
+ try:
45
+ from huggingface_hub import hf_hub_download
46
+ from huggingface_hub.utils import RepositoryNotFoundError
47
+ except ImportError:
48
+ hf_hub_download = None
49
+ RepositoryNotFoundError = None
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ class OneFormerImageProcessorKwargs(ImagesKwargs, total=False):
56
+ r"""
57
+ repo_path (`str`, *optional*, defaults to `shi-labs/oneformer_demo`):
58
+ Path to a local directory or HuggingFace Hub repository containing model metadata.
59
+ class_info_file (`str`, *optional*):
60
+ Path to the JSON file within the repository that contains class metadata.
61
+ num_text (`int`, *optional*):
62
+ Number of text queries for the text encoder, used as task-guiding prompts.
63
+ num_labels (`int`, *optional*):
64
+ Number of semantic classes for segmentation, determining the output layer's size.
65
+ ignore_index (`int`, *optional*):
66
+ Label to ignore in segmentation maps, often used for padding.
67
+ do_reduce_labels (`bool`, *optional*, defaults to `False`):
68
+ Whether to decrement all label values by 1, mapping the background class to `ignore_index`.
69
+ """
70
+
71
+ repo_path: str | None
72
+ class_info_file: str | None
73
+ num_text: int | None
74
+ num_labels: int | None
75
+ ignore_index: int | None
76
+ do_reduce_labels: bool
77
+
78
+
79
+ def prepare_metadata(class_info):
80
+ metadata = {}
81
+ class_names = []
82
+ thing_ids = []
83
+ for key, info in class_info.items():
84
+ metadata[key] = info["name"]
85
+ class_names.append(info["name"])
86
+ if info["isthing"]:
87
+ thing_ids.append(int(key))
88
+ metadata["thing_ids"] = thing_ids
89
+ metadata["class_names"] = class_names
90
+ return metadata
91
+
92
+
93
+ def load_metadata(repo_id, class_info_file):
94
+ fname = os.path.join("" if repo_id is None else repo_id, class_info_file)
95
+
96
+ if not os.path.exists(fname) or not os.path.isfile(fname):
97
+ if repo_id is None:
98
+ raise ValueError(f"Could not file {fname} locally. repo_id must be defined if loading from the hub")
99
+ if hf_hub_download is None:
100
+ raise ImportError(
101
+ "huggingface_hub is required to download metadata files. Install it with `pip install huggingface_hub`"
102
+ )
103
+ # We try downloading from a dataset by default for backward compatibility
104
+ try:
105
+ fname = hf_hub_download(repo_id, class_info_file, repo_type="dataset")
106
+ except RepositoryNotFoundError:
107
+ fname = hf_hub_download(repo_id, class_info_file)
108
+
109
+ with open(fname, "r") as f:
110
+ class_info = json.load(f)
111
+
112
+ return class_info
113
+
114
+
115
+ def make_pixel_mask(image: "torch.Tensor", output_size: tuple[int, int]) -> "torch.Tensor":
116
+ """
117
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
118
+
119
+ Args:
120
+ image (`torch.Tensor`):
121
+ Image to make the pixel mask for.
122
+ output_size (`Tuple[int, int]`):
123
+ Output size of the mask.
124
+ """
125
+
126
+ input_height, input_width = image.shape[-2], image.shape[-1]
127
+ mask = torch.zeros(output_size, dtype=torch.int64)
128
+ mask[:input_height, :input_width] = 1
129
+ return mask
130
+
131
+
132
+ def binary_mask_to_rle(mask):
133
+ """
134
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
135
+
136
+ Args:
137
+ mask (`torch.Tensor` or `numpy.array`):
138
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
139
+ segment_id or class_id.
140
+ Returns:
141
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
142
+ format.
143
+ """
144
+ import numpy as np
145
+
146
+ # Convert to torch tensor if numpy array
147
+ if isinstance(mask, np.ndarray):
148
+ mask = torch.from_numpy(mask)
149
+
150
+ pixels = mask.flatten()
151
+ pixels = torch.concat(
152
+ [
153
+ torch.tensor([0], device=pixels.device, dtype=pixels.dtype),
154
+ pixels,
155
+ torch.tensor([0], device=pixels.device, dtype=pixels.dtype),
156
+ ]
157
+ )
158
+ runs = torch.where(pixels[1:] != pixels[:-1])[0] + 1
159
+ runs[1::2] -= runs[::2]
160
+ return list(runs)
161
+
162
+
163
+ def convert_segmentation_to_rle(segmentation):
164
+ """
165
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
166
+
167
+ Args:
168
+ segmentation (`torch.Tensor` or `numpy.array`):
169
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
170
+ Returns:
171
+ `List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
172
+ """
173
+ segment_ids = torch.unique(segmentation)
174
+
175
+ run_length_encodings = []
176
+ for idx in segment_ids:
177
+ mask = torch.where(segmentation == idx, 1, 0)
178
+ rle = binary_mask_to_rle(mask)
179
+ run_length_encodings.append(rle)
180
+
181
+ return run_length_encodings
182
+
183
+
184
+ def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
185
+ """
186
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
187
+ `labels`.
188
+
189
+ Args:
190
+ masks (`torch.Tensor`):
191
+ A tensor of shape `(num_queries, height, width)`.
192
+ scores (`torch.Tensor`):
193
+ A tensor of shape `(num_queries)`.
194
+ labels (`torch.Tensor`):
195
+ A tensor of shape `(num_queries)`.
196
+ object_mask_threshold (`float`):
197
+ A number between 0 and 1 used to binarize the masks.
198
+ Raises:
199
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
200
+ Returns:
201
+ `Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
202
+ < `object_mask_threshold`.
203
+ """
204
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
205
+ raise ValueError("mask, scores and labels must have the same shape!")
206
+
207
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
208
+
209
+ return masks[to_keep], scores[to_keep], labels[to_keep]
210
+
211
+
212
+ def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
213
+ # Get the mask associated with the k class
214
+ mask_k = mask_labels == k
215
+ mask_k_area = mask_k.sum()
216
+
217
+ # Compute the area of all the stuff in query k
218
+ original_area = (mask_probs[k] >= mask_threshold).sum()
219
+ mask_exists = mask_k_area > 0 and original_area > 0
220
+
221
+ # Eliminate disconnected tiny segments
222
+ if mask_exists:
223
+ area_ratio = mask_k_area / original_area
224
+ if not area_ratio.item() > overlap_mask_area_threshold:
225
+ mask_exists = False
226
+
227
+ return mask_exists, mask_k
228
+
229
+
230
+ def compute_segments(
231
+ mask_probs,
232
+ pred_scores,
233
+ pred_labels,
234
+ mask_threshold: float = 0.5,
235
+ overlap_mask_area_threshold: float = 0.8,
236
+ label_ids_to_fuse: set[int] | None = None,
237
+ target_size: tuple[int, int] | None = None,
238
+ ):
239
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
240
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
241
+
242
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
243
+ segments: list[dict] = []
244
+
245
+ if target_size is not None:
246
+ mask_probs = tvF.resize(
247
+ mask_probs.unsqueeze(0),
248
+ size=target_size,
249
+ interpolation=tvF.InterpolationMode.BILINEAR,
250
+ )[0]
251
+
252
+ current_segment_id = 0
253
+
254
+ mask_probs *= pred_scores.view(-1, 1, 1)
255
+ mask_labels = mask_probs.argmax(0) # [height, width]
256
+
257
+ stuff_memory_list: dict[str, int] = {}
258
+ for k in range(pred_labels.shape[0]):
259
+ pred_class = pred_labels[k].item()
260
+ should_fuse = pred_class in label_ids_to_fuse
261
+
262
+ mask_exists, mask_k = check_segment_validity(
263
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
264
+ )
265
+
266
+ if mask_exists:
267
+ if pred_class in stuff_memory_list:
268
+ current_segment_id = stuff_memory_list[pred_class]
269
+ else:
270
+ current_segment_id += 1
271
+
272
+ segmentation[mask_k] = current_segment_id
273
+ segment_score = round(pred_scores[k].item(), 6)
274
+ segments.append(
275
+ {
276
+ "id": current_segment_id,
277
+ "label_id": pred_class,
278
+ "was_fused": should_fuse,
279
+ "score": segment_score,
280
+ }
281
+ )
282
+ if should_fuse:
283
+ stuff_memory_list[pred_class] = current_segment_id
284
+
285
+ return segmentation, segments
286
+
287
+
288
+ @auto_docstring
289
+ class OneFormerImageProcessor(TorchvisionBackend):
290
+ resample = PILImageResampling.BILINEAR
291
+ image_mean = IMAGENET_DEFAULT_MEAN
292
+ image_std = IMAGENET_DEFAULT_STD
293
+ size = {"shortest_edge": 800, "longest_edge": 1333}
294
+ crop_size = None
295
+ do_resize = True
296
+ do_rescale = True
297
+ do_normalize = True
298
+ default_to_square = False
299
+ do_center_crop = False
300
+ do_convert_rgb = True
301
+ rescale_factor = 1 / 255
302
+ ignore_index = None
303
+ do_reduce_labels = False
304
+ repo_path = "shi-labs/oneformer_demo"
305
+ class_info_file = None
306
+ num_text = None
307
+ num_labels = None
308
+ valid_kwargs = OneFormerImageProcessorKwargs
309
+ model_input_names = ["pixel_values", "pixel_mask", "task_inputs"]
310
+
311
+ def __init__(self, **kwargs: Unpack[OneFormerImageProcessorKwargs]):
312
+ super().__init__(**kwargs)
313
+ if self.class_info_file:
314
+ self.metadata = prepare_metadata(load_metadata(self.repo_path, self.class_info_file))
315
+
316
+ @auto_docstring
317
+ def preprocess(
318
+ self,
319
+ images: ImageInput,
320
+ task_inputs: list[str] | None = None,
321
+ segmentation_maps: ImageInput | None = None,
322
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
323
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
324
+ ) -> BatchFeature:
325
+ r"""
326
+ task_inputs (`list[str]`, *optional*):
327
+ List of tasks (`"panoptic"`, `"instance"`, `"semantic"`) for each image in the batch.
328
+ segmentation_maps (`ImageInput`, *optional*):
329
+ The segmentation maps.
330
+ instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *optional*):
331
+ A mapping from instance IDs to semantic IDs.
332
+ """
333
+ return super().preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
334
+
335
+ def _preprocess_image_like_inputs(
336
+ self,
337
+ images: ImageInput,
338
+ task_inputs: list[str] | None,
339
+ segmentation_maps: ImageInput,
340
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
341
+ do_convert_rgb: bool,
342
+ input_data_format: ChannelDimension,
343
+ device: Union[str, "torch.device"] | None = None,
344
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
345
+ ) -> BatchFeature:
346
+ """
347
+ Preprocess image-like inputs.
348
+ To be overridden by subclasses when image-like inputs other than images should be processed.
349
+ It can be used for segmentation maps, depth maps, etc.
350
+ """
351
+ # Prepare input images
352
+ images = self._prepare_image_like_inputs(
353
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
354
+ )
355
+ if segmentation_maps is not None:
356
+ segmentation_maps = self._prepare_image_like_inputs(
357
+ images=segmentation_maps,
358
+ expected_ndims=2,
359
+ do_convert_rgb=False,
360
+ input_data_format=ChannelDimension.FIRST,
361
+ )
362
+ return self._preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
363
+
364
+ def _preprocess(
365
+ self,
366
+ images: list["torch.Tensor"],
367
+ task_inputs: list[str] | None,
368
+ segmentation_maps: list["torch.Tensor"],
369
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
370
+ do_resize: bool,
371
+ size: SizeDict,
372
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
373
+ do_rescale: bool,
374
+ rescale_factor: float,
375
+ do_normalize: bool,
376
+ image_mean: float | list[float] | None,
377
+ image_std: float | list[float] | None,
378
+ ignore_index: int | None,
379
+ do_reduce_labels: bool | None,
380
+ disable_grouping: bool | None,
381
+ return_tensors: str | TensorType | None,
382
+ **kwargs,
383
+ ) -> BatchFeature:
384
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
385
+
386
+ processed_images_grouped = {}
387
+
388
+ for shape, stacked_images in grouped_images.items():
389
+ if do_resize:
390
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
391
+ stacked_images = self.rescale_and_normalize(
392
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
393
+ )
394
+ processed_images_grouped[shape] = stacked_images
395
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
396
+
397
+ processed_segmentation_maps = None
398
+ if segmentation_maps is not None:
399
+ grouped_segmentation_maps, grouped_segmentation_maps_index = group_images_by_shape(
400
+ segmentation_maps, disable_grouping=disable_grouping
401
+ )
402
+ processed_segmentation_maps_grouped = {}
403
+ for shape, stacked_segmentation_maps in grouped_segmentation_maps.items():
404
+ if do_resize:
405
+ stacked_segmentation_maps = self.resize(
406
+ stacked_segmentation_maps, size=size, resample=tvF.InterpolationMode.NEAREST_EXACT
407
+ )
408
+ processed_segmentation_maps_grouped[shape] = stacked_segmentation_maps
409
+ processed_segmentation_maps = reorder_images(
410
+ processed_segmentation_maps_grouped, grouped_segmentation_maps_index
411
+ )
412
+
413
+ encoded_inputs = self.encode_inputs(
414
+ processed_images,
415
+ task_inputs,
416
+ segmentation_maps=processed_segmentation_maps,
417
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
418
+ ignore_index=ignore_index,
419
+ do_reduce_labels=do_reduce_labels,
420
+ return_tensors=return_tensors,
421
+ )
422
+
423
+ return encoded_inputs
424
+
425
+ def _pad_image(
426
+ self,
427
+ image: "torch.Tensor",
428
+ output_size: tuple[int, int],
429
+ constant_values: float = 0,
430
+ ) -> "torch.Tensor":
431
+ """
432
+ Pad an image with zeros to the given size using torch operations.
433
+
434
+ Args:
435
+ image (`torch.Tensor`):
436
+ Image tensor in channel-first format (C, H, W).
437
+ output_size (`tuple[int, int]`):
438
+ Target output size (height, width).
439
+ constant_values (`float`, *optional*, defaults to 0):
440
+ The value to use for padding.
441
+
442
+ Returns:
443
+ `torch.Tensor`: The padded image.
444
+ """
445
+ input_height, input_width = image.shape[1], image.shape[2]
446
+ output_height, output_width = output_size
447
+
448
+ pad_bottom = output_height - input_height
449
+ pad_right = output_width - input_width
450
+
451
+ padded_image = tvF.pad(image, padding=[0, 0, pad_right, pad_bottom], fill=constant_values)
452
+
453
+ return padded_image
454
+
455
+ def pad(
456
+ self,
457
+ images: list["torch.Tensor"],
458
+ return_pixel_mask: bool = True,
459
+ return_tensors: str | TensorType | None = None,
460
+ ) -> BatchFeature:
461
+ """
462
+ Pad a batch of images to the same size using torch operations.
463
+
464
+ Args:
465
+ images (`List[torch.Tensor]`):
466
+ List of image tensors in channel-first format.
467
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
468
+ Whether to return pixel masks.
469
+ return_tensors (`str` or `TensorType`, *optional*):
470
+ The type of tensors to return.
471
+
472
+ Returns:
473
+ `BatchFeature`: Padded images and optional pixel masks.
474
+ """
475
+ outputs = super().pad(images, return_mask=return_pixel_mask)
476
+ padded_images = outputs[0] if return_pixel_mask else outputs
477
+ pixel_masks = outputs[1] if return_pixel_mask else None
478
+
479
+ if return_tensors:
480
+ padded_images = torch.stack(padded_images, dim=0)
481
+ if return_pixel_mask:
482
+ pixel_masks = torch.stack(pixel_masks, dim=0)
483
+
484
+ data = {"pixel_values": padded_images}
485
+ if return_pixel_mask:
486
+ data["pixel_mask"] = pixel_masks
487
+
488
+ return BatchFeature(data=data, tensor_type=return_tensors)
489
+
490
+ def convert_segmentation_map_to_binary_masks(
491
+ self,
492
+ segmentation_map: "torch.Tensor",
493
+ instance_id_to_semantic_id: dict[int, int] | None = None,
494
+ ignore_index: int | None = None,
495
+ do_reduce_labels: bool = False,
496
+ ):
497
+ if do_reduce_labels and ignore_index is None:
498
+ raise ValueError("If `do_reduce_labels` is True, `ignore_index` must be provided.")
499
+
500
+ if do_reduce_labels:
501
+ segmentation_map = torch.where(segmentation_map == 0, ignore_index, segmentation_map - 1)
502
+
503
+ all_labels = torch.unique(segmentation_map)
504
+
505
+ if ignore_index is not None:
506
+ all_labels = all_labels[all_labels != ignore_index]
507
+
508
+ binary_masks = [(segmentation_map == i) for i in all_labels]
509
+
510
+ if binary_masks:
511
+ binary_masks = torch.stack(binary_masks, dim=0)
512
+ else:
513
+ binary_masks = torch.zeros((0, *segmentation_map.shape), device=segmentation_map.device)
514
+
515
+ # Convert instance ids to class ids
516
+ if instance_id_to_semantic_id is not None:
517
+ labels = torch.zeros(all_labels.shape[0], device=segmentation_map.device)
518
+
519
+ for i, label in enumerate(all_labels):
520
+ class_id = instance_id_to_semantic_id[(label.item() + 1 if do_reduce_labels else label.item())]
521
+ labels[i] = class_id - 1 if do_reduce_labels else class_id
522
+ else:
523
+ labels = all_labels
524
+
525
+ return (
526
+ binary_masks.float(),
527
+ labels.long(),
528
+ )
529
+
530
+ def get_semantic_annotations(self, label, num_class_obj):
531
+ annotation_classes = label["classes"]
532
+ annotation_masks = label["masks"]
533
+
534
+ texts = ["a semantic photo"] * self.num_text
535
+ classes = []
536
+ masks = []
537
+
538
+ for idx in range(len(annotation_classes)):
539
+ class_id = annotation_classes[idx]
540
+ mask = annotation_masks[idx]
541
+ if not torch.all(mask == 0):
542
+ if class_id not in classes:
543
+ cls_name = self.metadata[str(class_id.cpu().item())]
544
+ classes.append(class_id)
545
+ masks.append(mask)
546
+ num_class_obj[cls_name] += 1
547
+ else:
548
+ idx = classes.index(class_id)
549
+ masks[idx] += mask
550
+ masks[idx] = torch.clamp(masks[idx], 0, 1)
551
+
552
+ num = 0
553
+ for i, cls_name in enumerate(self.metadata["class_names"]):
554
+ if num_class_obj[cls_name] > 0:
555
+ for _ in range(num_class_obj[cls_name]):
556
+ if num >= len(texts):
557
+ break
558
+ texts[num] = f"a photo with a {cls_name}"
559
+ num += 1
560
+
561
+ classes = torch.stack(classes)
562
+ masks = torch.stack(masks)
563
+ return classes, masks, texts
564
+
565
+ def get_instance_annotations(self, label, num_class_obj):
566
+ annotation_classes = label["classes"]
567
+ annotation_masks = label["masks"]
568
+
569
+ texts = ["an instance photo"] * self.num_text
570
+ classes = []
571
+ masks = []
572
+
573
+ for idx in range(len(annotation_classes)):
574
+ class_id = annotation_classes[idx]
575
+ mask = annotation_masks[idx]
576
+
577
+ if class_id in self.metadata["thing_ids"]:
578
+ if not torch.all(mask == 0):
579
+ cls_name = self.metadata[str(class_id.cpu().item())]
580
+ classes.append(class_id)
581
+ masks.append(mask)
582
+ num_class_obj[cls_name] += 1
583
+
584
+ num = 0
585
+ for i, cls_name in enumerate(self.metadata["class_names"]):
586
+ if num_class_obj[cls_name] > 0:
587
+ for _ in range(num_class_obj[cls_name]):
588
+ if num >= len(texts):
589
+ break
590
+ texts[num] = f"a photo with a {cls_name}"
591
+ num += 1
592
+
593
+ classes = torch.stack(classes)
594
+ masks = torch.stack(masks)
595
+ return classes, masks, texts
596
+
597
+ def get_panoptic_annotations(self, label, num_class_obj):
598
+ annotation_classes = label["classes"]
599
+ annotation_masks = label["masks"]
600
+
601
+ texts = ["an panoptic photo"] * self.num_text
602
+ classes = []
603
+ masks = []
604
+ for idx in range(len(annotation_classes)):
605
+ class_id = annotation_classes[idx]
606
+ mask = annotation_masks[idx] if hasattr(annotation_masks[idx], "data") else annotation_masks[idx]
607
+ if not torch.all(mask == 0):
608
+ cls_name = self.metadata[str(class_id.cpu().item())]
609
+ classes.append(class_id)
610
+ masks.append(mask)
611
+ num_class_obj[cls_name] += 1
612
+
613
+ num = 0
614
+ for i, cls_name in enumerate(self.metadata["class_names"]):
615
+ if num_class_obj[cls_name] > 0:
616
+ for _ in range(num_class_obj[cls_name]):
617
+ if num >= len(texts):
618
+ break
619
+ texts[num] = f"a photo with a {cls_name}"
620
+ num += 1
621
+
622
+ classes = torch.stack(classes)
623
+ masks = torch.stack(masks)
624
+ return classes, masks, texts
625
+
626
+ def encode_inputs(
627
+ self,
628
+ pixel_values_list: list["ImageInput"],
629
+ task_inputs: list[str] | None = None,
630
+ segmentation_maps: list["ImageInput"] | None = None,
631
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
632
+ ignore_index: int | None = None,
633
+ do_reduce_labels: bool = False,
634
+ return_tensors: str | TensorType | None = None,
635
+ ) -> BatchFeature:
636
+ ignore_index = self.ignore_index if ignore_index is None else ignore_index
637
+ do_reduce_labels = self.do_reduce_labels if do_reduce_labels is None else do_reduce_labels
638
+ if task_inputs is None:
639
+ task_inputs = ["panoptic"]
640
+ pixel_values_list = self._prepare_image_like_inputs(
641
+ pixel_values_list, input_data_format=ChannelDimension.FIRST
642
+ )
643
+ if segmentation_maps is not None:
644
+ segmentation_maps = self._prepare_image_like_inputs(
645
+ images=segmentation_maps,
646
+ expected_ndims=2,
647
+ do_convert_rgb=False,
648
+ input_data_format=ChannelDimension.FIRST,
649
+ )
650
+ pad_size = get_max_height_width(pixel_values_list)
651
+ encoded_inputs = self.pad(pixel_values_list, return_tensors=return_tensors)
652
+
653
+ annotations = None
654
+ if segmentation_maps is not None:
655
+ annotations = []
656
+ for idx, segmentation_map in enumerate(segmentation_maps):
657
+ # Use instance2class_id mapping per image
658
+ if isinstance(instance_id_to_semantic_id, list):
659
+ instance_id = instance_id_to_semantic_id[idx]
660
+ else:
661
+ instance_id = instance_id_to_semantic_id
662
+
663
+ # Convert segmentation map to binary masks using torch operations
664
+ masks, classes = self.convert_segmentation_map_to_binary_masks(
665
+ segmentation_map,
666
+ instance_id,
667
+ ignore_index=ignore_index,
668
+ do_reduce_labels=do_reduce_labels,
669
+ )
670
+
671
+ annotations.append({"masks": masks, "classes": classes})
672
+
673
+ if annotations is not None:
674
+ mask_labels = []
675
+ class_labels = []
676
+ text_inputs = []
677
+ num_class_obj = dict.fromkeys(self.metadata["class_names"], 0)
678
+
679
+ for i, label in enumerate(annotations):
680
+ task = task_inputs[i]
681
+
682
+ if task == "semantic":
683
+ classes, masks, texts = self.get_semantic_annotations(label, num_class_obj)
684
+ elif task == "instance":
685
+ classes, masks, texts = self.get_instance_annotations(label, num_class_obj)
686
+ elif task == "panoptic":
687
+ classes, masks, texts = self.get_panoptic_annotations(label, num_class_obj)
688
+ else:
689
+ raise ValueError(f"{task} was not expected, expected `semantic`, `instance` or `panoptic`")
690
+ # Pad masks to max size using torch operations
691
+ padded_masks = [
692
+ self._pad_image(image=mask, output_size=pad_size, constant_values=ignore_index) for mask in masks
693
+ ]
694
+ padded_masks = torch.cat(padded_masks, dim=0)
695
+ mask_labels.append(padded_masks)
696
+ class_labels.append(classes)
697
+ text_inputs.append(texts)
698
+
699
+ encoded_inputs["mask_labels"] = mask_labels
700
+ encoded_inputs["class_labels"] = class_labels
701
+ encoded_inputs["text_inputs"] = text_inputs
702
+
703
+ encoded_inputs["task_inputs"] = [f"the task is {task_input}" for task_input in task_inputs]
704
+ return encoded_inputs
705
+
706
+ def post_process_semantic_segmentation(
707
+ self, outputs, target_sizes: list[tuple[int, int]] | None = None
708
+ ) -> "torch.Tensor":
709
+ """
710
+ Converts the output of [`MaskFormerForInstanceSegmentation`] into semantic segmentation maps. Only supports
711
+ PyTorch.
712
+
713
+ Args:
714
+ outputs ([`MaskFormerForInstanceSegmentation`]):
715
+ Raw outputs of the model.
716
+ target_sizes (`List[Tuple[int, int]]`, *optional*):
717
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
718
+ final size (height, width) of each prediction. If left to None, predictions will not be resized.
719
+ Returns:
720
+ `List[torch.Tensor]`:
721
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
722
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
723
+ `torch.Tensor` correspond to a semantic class id.
724
+ """
725
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
726
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
727
+
728
+ # Remove the null class `[..., :-1]`
729
+ masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
730
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
731
+
732
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
733
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
734
+ batch_size = class_queries_logits.shape[0]
735
+
736
+ # Resize logits and compute semantic segmentation maps
737
+ if target_sizes is not None:
738
+ if batch_size != len(target_sizes):
739
+ raise ValueError(
740
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
741
+ )
742
+
743
+ semantic_segmentation = []
744
+ for idx in range(batch_size):
745
+ resized_logits = tvF.resize(
746
+ segmentation[idx].unsqueeze(dim=0),
747
+ size=target_sizes[idx],
748
+ interpolation=tvF.InterpolationMode.BILINEAR,
749
+ )
750
+ semantic_map = resized_logits[0].argmax(dim=0)
751
+ semantic_segmentation.append(semantic_map)
752
+ else:
753
+ semantic_segmentation = segmentation.argmax(dim=1)
754
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
755
+
756
+ return semantic_segmentation
757
+
758
+ def post_process_instance_segmentation(
759
+ self,
760
+ outputs,
761
+ task_type: str = "instance",
762
+ is_demo: bool = True,
763
+ threshold: float = 0.5,
764
+ mask_threshold: float = 0.5,
765
+ overlap_mask_area_threshold: float = 0.8,
766
+ target_sizes: list[tuple[int, int]] | None = None,
767
+ return_coco_annotation: bool | None = False,
768
+ ):
769
+ """
770
+ Converts the output of [`OneFormerForUniversalSegmentationOutput`] into image instance segmentation
771
+ predictions. Only supports PyTorch.
772
+
773
+ Args:
774
+ outputs ([`OneFormerForUniversalSegmentationOutput`]):
775
+ The outputs from [`OneFormerForUniversalSegmentationOutput`].
776
+ task_type (`str`, *optional*, defaults to "instance"):
777
+ The post processing depends on the task token input. If the `task_type` is "panoptic", we need to
778
+ ignore the stuff predictions.
779
+ is_demo (`bool`, *optional)*, defaults to `True`):
780
+ Whether the model is in demo mode. If true, use threshold to predict final masks.
781
+ threshold (`float`, *optional*, defaults to 0.5):
782
+ The probability score threshold to keep predicted instance masks.
783
+ mask_threshold (`float`, *optional*, defaults to 0.5):
784
+ Threshold to use when turning the predicted masks into binary values.
785
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
786
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
787
+ instance mask.
788
+ target_sizes (`List[Tuple]`, *optional*):
789
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
790
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
791
+ resized.
792
+ return_coco_annotation (`bool`, *optional)*, defaults to `False`):
793
+ Whether to return predictions in COCO format.
794
+
795
+ Returns:
796
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
797
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
798
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
799
+ to the corresponding `target_sizes` entry.
800
+ - **segments_info** -- A dictionary that contains additional information on each segment.
801
+ - **id** -- an integer representing the `segment_id`.
802
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
803
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
804
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
805
+ - **score** -- Prediction score of segment with `segment_id`.
806
+ """
807
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
808
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
809
+
810
+ device = masks_queries_logits.device
811
+ batch_size = class_queries_logits.shape[0]
812
+ num_queries = class_queries_logits.shape[1]
813
+ num_classes = class_queries_logits.shape[-1] - 1
814
+
815
+ # Loop over items in batch size
816
+ results: list[dict[str, torch.Tensor]] = []
817
+
818
+ for i in range(batch_size):
819
+ # [Q, K]
820
+ scores = nn.functional.softmax(class_queries_logits[i], dim=-1)[:, :-1]
821
+ labels = torch.arange(num_classes, device=device).unsqueeze(0).repeat(num_queries, 1).flatten(0, 1)
822
+
823
+ # scores_per_image, topk_indices = scores.flatten(0, 1).topk(self.num_queries, sorted=False)
824
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(num_queries, sorted=False)
825
+ labels_per_image = labels[topk_indices]
826
+
827
+ topk_indices = torch.div(topk_indices, num_classes, rounding_mode="floor")
828
+ # mask_pred = mask_pred.unsqueeze(1).repeat(1, self.sem_seg_head.num_classes, 1).flatten(0, 1)
829
+ mask_pred = masks_queries_logits[i][topk_indices]
830
+
831
+ # Only consider scores with confidence over [threshold] for demo
832
+ if is_demo:
833
+ keep = scores_per_image > threshold
834
+ scores_per_image = scores_per_image[keep]
835
+ labels_per_image = labels_per_image[keep]
836
+ mask_pred = mask_pred[keep]
837
+
838
+ # if this is panoptic segmentation, we only keep the "thing" classes
839
+ if task_type == "panoptic":
840
+ keep = torch.zeros_like(scores_per_image).bool()
841
+ for j, lab in enumerate(labels_per_image):
842
+ keep[j] = lab in self.metadata["thing_ids"]
843
+
844
+ scores_per_image = scores_per_image[keep]
845
+ labels_per_image = labels_per_image[keep]
846
+ mask_pred = mask_pred[keep]
847
+
848
+ if mask_pred.shape[0] <= 0:
849
+ height, width = target_sizes[i] if target_sizes is not None else mask_pred.shape[1:]
850
+ segmentation = torch.zeros((height, width)) - 1
851
+ results.append({"segmentation": segmentation, "segments_info": []})
852
+ continue
853
+
854
+ if "ade20k" in self.class_info_file and not is_demo and "instance" in task_type:
855
+ for j in range(labels_per_image.shape[0]):
856
+ labels_per_image[j] = self.metadata["thing_ids"].index(labels_per_image[j].item())
857
+
858
+ # Get segmentation map and segment information of batch item
859
+ target_size = target_sizes[i] if target_sizes is not None else None
860
+ segmentation, segments = compute_segments(
861
+ mask_pred,
862
+ scores_per_image,
863
+ labels_per_image,
864
+ mask_threshold,
865
+ overlap_mask_area_threshold,
866
+ set(),
867
+ target_size,
868
+ )
869
+
870
+ # Return segmentation map in run-length encoding (RLE) format
871
+ if return_coco_annotation:
872
+ segmentation = convert_segmentation_to_rle(segmentation)
873
+
874
+ results.append({"segmentation": segmentation, "segments_info": segments})
875
+ return results
876
+
877
+ # Copied from transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessor.post_process_panoptic_segmentation
878
+ def post_process_panoptic_segmentation(
879
+ self,
880
+ outputs,
881
+ threshold: float = 0.5,
882
+ mask_threshold: float = 0.5,
883
+ overlap_mask_area_threshold: float = 0.8,
884
+ label_ids_to_fuse: set[int] | None = None,
885
+ target_sizes: list[tuple[int, int]] | None = None,
886
+ ) -> list[dict]:
887
+ """
888
+ Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into image panoptic segmentation
889
+ predictions. Only supports PyTorch.
890
+
891
+ Args:
892
+ outputs ([`MaskFormerForInstanceSegmentationOutput`]):
893
+ The outputs from [`MaskFormerForInstanceSegmentation`].
894
+ threshold (`float`, *optional*, defaults to 0.5):
895
+ The probability score threshold to keep predicted instance masks.
896
+ mask_threshold (`float`, *optional*, defaults to 0.5):
897
+ Threshold to use when turning the predicted masks into binary values.
898
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
899
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
900
+ instance mask.
901
+ label_ids_to_fuse (`Set[int]`, *optional*):
902
+ The labels in this state will have all their instances be fused together. For instance we could say
903
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
904
+ set, but not the one for person.
905
+ target_sizes (`list[Tuple]`, *optional*):
906
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
907
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
908
+ resized.
909
+
910
+ Returns:
911
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
912
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
913
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
914
+ to the corresponding `target_sizes` entry.
915
+ - **segments_info** -- A dictionary that contains additional information on each segment.
916
+ - **id** -- an integer representing the `segment_id`.
917
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
918
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
919
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
920
+ - **score** -- Prediction score of segment with `segment_id`.
921
+ """
922
+
923
+ if label_ids_to_fuse is None:
924
+ logger.warning("`label_ids_to_fuse` unset. No instance will be fused.")
925
+ label_ids_to_fuse = set()
926
+
927
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
928
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
929
+
930
+ batch_size = class_queries_logits.shape[0]
931
+ num_labels = class_queries_logits.shape[-1] - 1
932
+
933
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
934
+
935
+ # Predicted label and score of each query (batch_size, num_queries)
936
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
937
+
938
+ # Loop over items in batch size
939
+ results: list[dict[str, TensorType]] = []
940
+
941
+ for i in range(batch_size):
942
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
943
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
944
+ )
945
+
946
+ # No mask found
947
+ if mask_probs_item.shape[0] <= 0:
948
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
949
+ segmentation = torch.zeros((height, width)) - 1
950
+ results.append({"segmentation": segmentation, "segments_info": []})
951
+ continue
952
+
953
+ # Get segmentation map and segment information of batch item
954
+ target_size = target_sizes[i] if target_sizes is not None else None
955
+ segmentation, segments = compute_segments(
956
+ mask_probs=mask_probs_item,
957
+ pred_scores=pred_scores_item,
958
+ pred_labels=pred_labels_item,
959
+ mask_threshold=mask_threshold,
960
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
961
+ label_ids_to_fuse=label_ids_to_fuse,
962
+ target_size=target_size,
963
+ )
964
+
965
+ results.append({"segmentation": segmentation, "segments_info": segments})
966
+ return results
967
+
968
+
969
+ __all__ = ["OneFormerImageProcessor"]
lib/python3.11/site-packages/transformers/models/oneformer/image_processing_pil_oneformer.py ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 SHI Labs 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
+ """Image processor class for OneFormer."""
15
+
16
+ import json
17
+ import os
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_backends import PilBackend
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_transforms import PaddingMode
24
+ from ...image_transforms import pad as np_pad
25
+ from ...image_utils import (
26
+ IMAGENET_DEFAULT_MEAN,
27
+ IMAGENET_DEFAULT_STD,
28
+ ChannelDimension,
29
+ ImageInput,
30
+ PILImageResampling,
31
+ SizeDict,
32
+ get_image_size,
33
+ get_max_height_width,
34
+ )
35
+ from ...processing_utils import ImagesKwargs, Unpack
36
+ from ...utils import TensorType, auto_docstring, is_torch_available, is_torchvision_available, logging
37
+ from ...utils.import_utils import requires
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ if is_torch_available():
43
+ import torch
44
+ from torch import nn
45
+
46
+ if is_torchvision_available():
47
+ import torchvision.transforms.v2.functional as tvF
48
+
49
+ try:
50
+ from huggingface_hub import hf_hub_download
51
+ from huggingface_hub.utils import RepositoryNotFoundError
52
+ except ImportError:
53
+ hf_hub_download = None
54
+ RepositoryNotFoundError = None
55
+
56
+
57
+ def make_pixel_mask(image: np.ndarray, output_size: tuple[int, int]) -> np.ndarray:
58
+ """
59
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
60
+
61
+ Args:
62
+ image (`np.ndarray`):
63
+ Image to make the pixel mask for.
64
+ output_size (`Tuple[int, int]`):
65
+ Output size of the mask.
66
+ """
67
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
68
+ mask = np.zeros(output_size, dtype=np.int64)
69
+ mask[:input_height, :input_width] = 1
70
+ return mask
71
+
72
+
73
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs
74
+ class OneFormerImageProcessorKwargs(ImagesKwargs, total=False):
75
+ r"""
76
+ repo_path (`str`, *optional*, defaults to `shi-labs/oneformer_demo`):
77
+ Path to a local directory or HuggingFace Hub repository containing model metadata.
78
+ class_info_file (`str`, *optional*):
79
+ Path to the JSON file within the repository that contains class metadata.
80
+ num_text (`int`, *optional*):
81
+ Number of text queries for the text encoder, used as task-guiding prompts.
82
+ num_labels (`int`, *optional*):
83
+ Number of semantic classes for segmentation, determining the output layer's size.
84
+ ignore_index (`int`, *optional*):
85
+ Label to ignore in segmentation maps, often used for padding.
86
+ do_reduce_labels (`bool`, *optional*, defaults to `False`):
87
+ Whether to decrement all label values by 1, mapping the background class to `ignore_index`.
88
+ """
89
+
90
+ repo_path: str | None
91
+ class_info_file: str | None
92
+ num_text: int | None
93
+ num_labels: int | None
94
+ ignore_index: int | None
95
+ do_reduce_labels: bool
96
+
97
+
98
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.binary_mask_to_rle
99
+ def binary_mask_to_rle(mask):
100
+ """
101
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
102
+
103
+ Args:
104
+ mask (`torch.Tensor` or `numpy.array`):
105
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
106
+ segment_id or class_id.
107
+ Returns:
108
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
109
+ format.
110
+ """
111
+ from ...utils import is_torch_tensor
112
+
113
+ if is_torch_tensor(mask):
114
+ mask = mask.numpy()
115
+
116
+ pixels = mask.flatten()
117
+ pixels = np.concatenate([[0], pixels, [0]])
118
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
119
+ runs[1::2] -= runs[::2]
120
+ return list(runs)
121
+
122
+
123
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.check_segment_validity
124
+ def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
125
+ # Get the mask associated with the k class
126
+ mask_k = mask_labels == k
127
+ mask_k_area = mask_k.sum()
128
+
129
+ # Compute the area of all the stuff in query k
130
+ original_area = (mask_probs[k] >= mask_threshold).sum()
131
+ mask_exists = mask_k_area > 0 and original_area > 0
132
+
133
+ # Eliminate disconnected tiny segments
134
+ if mask_exists:
135
+ area_ratio = mask_k_area / original_area
136
+ if not area_ratio.item() > overlap_mask_area_threshold:
137
+ mask_exists = False
138
+
139
+ return mask_exists, mask_k
140
+
141
+
142
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.compute_segments
143
+ def compute_segments(
144
+ mask_probs,
145
+ pred_scores,
146
+ pred_labels,
147
+ mask_threshold: float = 0.5,
148
+ overlap_mask_area_threshold: float = 0.8,
149
+ label_ids_to_fuse: set[int] | None = None,
150
+ target_size: tuple[int, int] | None = None,
151
+ ):
152
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
153
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
154
+
155
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
156
+ segments: list[dict] = []
157
+
158
+ if target_size is not None:
159
+ mask_probs = tvF.resize(
160
+ mask_probs.unsqueeze(0),
161
+ size=target_size,
162
+ interpolation=tvF.InterpolationMode.BILINEAR,
163
+ )[0]
164
+
165
+ current_segment_id = 0
166
+
167
+ mask_probs *= pred_scores.view(-1, 1, 1)
168
+ mask_labels = mask_probs.argmax(0) # [height, width]
169
+
170
+ stuff_memory_list: dict[str, int] = {}
171
+ for k in range(pred_labels.shape[0]):
172
+ pred_class = pred_labels[k].item()
173
+ should_fuse = pred_class in label_ids_to_fuse
174
+
175
+ mask_exists, mask_k = check_segment_validity(
176
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
177
+ )
178
+
179
+ if mask_exists:
180
+ if pred_class in stuff_memory_list:
181
+ current_segment_id = stuff_memory_list[pred_class]
182
+ else:
183
+ current_segment_id += 1
184
+
185
+ segmentation[mask_k] = current_segment_id
186
+ segment_score = round(pred_scores[k].item(), 6)
187
+ segments.append(
188
+ {
189
+ "id": current_segment_id,
190
+ "label_id": pred_class,
191
+ "was_fused": should_fuse,
192
+ "score": segment_score,
193
+ }
194
+ )
195
+ if should_fuse:
196
+ stuff_memory_list[pred_class] = current_segment_id
197
+
198
+ return segmentation, segments
199
+
200
+
201
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.convert_segmentation_to_rle
202
+ def convert_segmentation_to_rle(segmentation):
203
+ """
204
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
205
+
206
+ Args:
207
+ segmentation (`torch.Tensor` or `numpy.array`):
208
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
209
+ Returns:
210
+ `List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
211
+ """
212
+ segment_ids = torch.unique(segmentation)
213
+
214
+ run_length_encodings = []
215
+ for idx in segment_ids:
216
+ mask = torch.where(segmentation == idx, 1, 0)
217
+ rle = binary_mask_to_rle(mask)
218
+ run_length_encodings.append(rle)
219
+
220
+ return run_length_encodings
221
+
222
+
223
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.load_metadata
224
+ def load_metadata(repo_id, class_info_file):
225
+ fname = os.path.join("" if repo_id is None else repo_id, class_info_file)
226
+
227
+ if not os.path.exists(fname) or not os.path.isfile(fname):
228
+ if repo_id is None:
229
+ raise ValueError(f"Could not file {fname} locally. repo_id must be defined if loading from the hub")
230
+ if hf_hub_download is None:
231
+ raise ImportError(
232
+ "huggingface_hub is required to download metadata files. Install it with `pip install huggingface_hub`"
233
+ )
234
+ # We try downloading from a dataset by default for backward compatibility
235
+ try:
236
+ fname = hf_hub_download(repo_id, class_info_file, repo_type="dataset")
237
+ except RepositoryNotFoundError:
238
+ fname = hf_hub_download(repo_id, class_info_file)
239
+
240
+ with open(fname, "r") as f:
241
+ class_info = json.load(f)
242
+
243
+ return class_info
244
+
245
+
246
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.prepare_metadata
247
+ def prepare_metadata(class_info):
248
+ metadata = {}
249
+ class_names = []
250
+ thing_ids = []
251
+ for key, info in class_info.items():
252
+ metadata[key] = info["name"]
253
+ class_names.append(info["name"])
254
+ if info["isthing"]:
255
+ thing_ids.append(int(key))
256
+ metadata["thing_ids"] = thing_ids
257
+ metadata["class_names"] = class_names
258
+ return metadata
259
+
260
+
261
+ # Adapted from transformers.models.oneformer.image_processing_oneformer.remove_low_and_no_objects
262
+ def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
263
+ """
264
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
265
+ `labels`.
266
+
267
+ Args:
268
+ masks (`torch.Tensor`):
269
+ A tensor of shape `(num_queries, height, width)`.
270
+ scores (`torch.Tensor`):
271
+ A tensor of shape `(num_queries)`.
272
+ labels (`torch.Tensor`):
273
+ A tensor of shape `(num_queries)`.
274
+ object_mask_threshold (`float`):
275
+ A number between 0 and 1 used to binarize the masks.
276
+ Raises:
277
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
278
+ Returns:
279
+ `Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
280
+ < `object_mask_threshold`.
281
+ """
282
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
283
+ raise ValueError("mask, scores and labels must have the same shape!")
284
+
285
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
286
+
287
+ return masks[to_keep], scores[to_keep], labels[to_keep]
288
+
289
+
290
+ @auto_docstring
291
+ @requires(backends=("torch",))
292
+ class OneFormerImageProcessorPil(PilBackend):
293
+ resample = PILImageResampling.BILINEAR
294
+ image_mean = IMAGENET_DEFAULT_MEAN
295
+ image_std = IMAGENET_DEFAULT_STD
296
+ size = {"shortest_edge": 800, "longest_edge": 1333}
297
+ crop_size = None
298
+ do_resize = True
299
+ do_rescale = True
300
+ do_normalize = True
301
+ default_to_square = False
302
+ do_center_crop = False
303
+ do_convert_rgb = True
304
+ rescale_factor = 1 / 255
305
+ ignore_index = None
306
+ do_reduce_labels = False
307
+ repo_path = "shi-labs/oneformer_demo"
308
+ class_info_file = None
309
+ num_text = None
310
+ num_labels = None
311
+ valid_kwargs = OneFormerImageProcessorKwargs
312
+ model_input_names = ["pixel_values", "pixel_mask", "task_inputs"]
313
+
314
+ def __init__(self, **kwargs: Unpack[OneFormerImageProcessorKwargs]):
315
+ super().__init__(**kwargs)
316
+ if self.class_info_file:
317
+ self.metadata = prepare_metadata(load_metadata(self.repo_path, self.class_info_file))
318
+
319
+ @auto_docstring
320
+ def preprocess(
321
+ self,
322
+ images: ImageInput,
323
+ task_inputs: list[str] | None = None,
324
+ segmentation_maps: ImageInput | None = None,
325
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
326
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
327
+ ) -> BatchFeature:
328
+ r"""
329
+ task_inputs (`list[str]`, *optional*):
330
+ List of tasks (`"panoptic"`, `"instance"`, `"semantic"`) for each image in the batch.
331
+ segmentation_maps (`ImageInput`, *optional*):
332
+ The segmentation maps.
333
+ instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *optional*):
334
+ A mapping from instance IDs to semantic IDs.
335
+ """
336
+ return super().preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
337
+
338
+ def _preprocess_image_like_inputs(
339
+ self,
340
+ images: ImageInput,
341
+ task_inputs: list[str] | None,
342
+ segmentation_maps: ImageInput,
343
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
344
+ do_convert_rgb: bool,
345
+ input_data_format: ChannelDimension,
346
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
347
+ ) -> BatchFeature:
348
+ """
349
+ Preprocess image-like inputs.
350
+ To be overridden by subclasses when image-like inputs other than images should be processed.
351
+ It can be used for segmentation maps, depth maps, etc.
352
+ """
353
+ # Prepare input images
354
+ images = self._prepare_image_like_inputs(
355
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format
356
+ )
357
+ if segmentation_maps is not None:
358
+ segmentation_maps = self._prepare_image_like_inputs(
359
+ images=segmentation_maps,
360
+ expected_ndims=2,
361
+ do_convert_rgb=False,
362
+ input_data_format=ChannelDimension.FIRST,
363
+ )
364
+ return self._preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
365
+
366
+ def _preprocess(
367
+ self,
368
+ images: list[np.ndarray],
369
+ task_inputs: list[str] | None,
370
+ segmentation_maps: list[np.ndarray],
371
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
372
+ do_resize: bool,
373
+ size: SizeDict,
374
+ resample: PILImageResampling | None,
375
+ do_rescale: bool,
376
+ rescale_factor: float,
377
+ do_normalize: bool,
378
+ image_mean: float | list[float] | None,
379
+ image_std: float | list[float] | None,
380
+ ignore_index: int | None,
381
+ do_reduce_labels: bool | None,
382
+ return_tensors: str | TensorType | None,
383
+ **kwargs,
384
+ ) -> BatchFeature:
385
+ # Process images one by one (no batching in PIL backend)
386
+ processed_images = []
387
+ processed_segmentation_maps = None
388
+ if segmentation_maps is not None:
389
+ processed_segmentation_maps = []
390
+
391
+ for idx, image in enumerate(images):
392
+ if do_resize:
393
+ image = self.resize(image=image, size=size, resample=resample)
394
+ if do_rescale:
395
+ image = self.rescale(image, rescale_factor)
396
+ if do_normalize:
397
+ image = self.normalize(image, image_mean, image_std)
398
+ processed_images.append(image)
399
+
400
+ if segmentation_maps is not None:
401
+ seg_map = segmentation_maps[idx]
402
+ if do_resize:
403
+ seg_map = self.resize(image=seg_map, size=size, resample=PILImageResampling.NEAREST)
404
+ processed_segmentation_maps.append(seg_map)
405
+
406
+ encoded_inputs = self.encode_inputs(
407
+ processed_images,
408
+ task_inputs,
409
+ segmentation_maps=processed_segmentation_maps,
410
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
411
+ ignore_index=ignore_index,
412
+ do_reduce_labels=do_reduce_labels,
413
+ return_tensors=return_tensors,
414
+ )
415
+
416
+ return encoded_inputs
417
+
418
+ def _pad_image(self, image: np.ndarray, output_size: tuple[int, int], constant_values: float = 0) -> np.ndarray:
419
+ """
420
+ Pad an image with zeros to the given size using numpy operations.
421
+
422
+ Args:
423
+ image (`np.ndarray`):
424
+ Image array in channel-first format (C, H, W) or (H, W).
425
+ output_size (`tuple[int, int]`):
426
+ Target output size (height, width).
427
+ constant_values (`float`, *optional*, defaults to 0):
428
+ The value to use for padding.
429
+
430
+ Returns:
431
+ `np.ndarray`: The padded image.
432
+ """
433
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
434
+ output_height, output_width = output_size
435
+
436
+ pad_bottom = output_height - input_height
437
+ pad_right = output_width - input_width
438
+
439
+ # For 2D arrays (masks), use np.pad directly
440
+ # For 3D arrays (images), use np_pad which handles channel dimension
441
+ if image.ndim == 2:
442
+ padding = ((0, pad_bottom), (0, pad_right))
443
+ padded_image = np.pad(image, padding, mode="constant", constant_values=constant_values)
444
+ else:
445
+ padding = ((0, pad_bottom), (0, pad_right))
446
+ padded_image = np_pad(
447
+ image,
448
+ padding,
449
+ mode=PaddingMode.CONSTANT,
450
+ constant_values=constant_values,
451
+ data_format=ChannelDimension.FIRST,
452
+ input_data_format=ChannelDimension.FIRST,
453
+ )
454
+
455
+ return padded_image
456
+
457
+ def pad(
458
+ self, images: list[np.ndarray], return_pixel_mask: bool = True, return_tensors: str | TensorType | None = None
459
+ ) -> BatchFeature:
460
+ """
461
+ Pad a batch of images to the same size using numpy operations.
462
+
463
+ Args:
464
+ images (`List[np.ndarray]`):
465
+ List of image arrays in channel-first format.
466
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
467
+ Whether to return pixel masks.
468
+ return_tensors (`str` or `TensorType`, *optional*):
469
+ The type of tensors to return.
470
+
471
+ Returns:
472
+ `BatchFeature`: Padded images and optional pixel masks.
473
+ """
474
+ pad_size = get_max_height_width(images, input_data_format=ChannelDimension.FIRST)
475
+
476
+ padded_images = []
477
+ pixel_masks = []
478
+ for image in images:
479
+ padded_image = self._pad_image(image, pad_size, constant_values=0)
480
+ padded_images.append(padded_image)
481
+ if return_pixel_mask:
482
+ pixel_mask = make_pixel_mask(image, pad_size)
483
+ pixel_masks.append(pixel_mask)
484
+
485
+ if return_tensors == "pt":
486
+ padded_images = [torch.from_numpy(img) for img in padded_images]
487
+ padded_images = torch.stack(padded_images, dim=0)
488
+ if return_pixel_mask:
489
+ pixel_masks = [torch.from_numpy(mask) for mask in pixel_masks]
490
+ pixel_masks = torch.stack(pixel_masks, dim=0)
491
+
492
+ data = {"pixel_values": padded_images}
493
+ if return_pixel_mask:
494
+ data["pixel_mask"] = pixel_masks
495
+
496
+ return BatchFeature(data=data, tensor_type=return_tensors)
497
+
498
+ def convert_segmentation_map_to_binary_masks(
499
+ self,
500
+ segmentation_map: np.ndarray,
501
+ instance_id_to_semantic_id: dict[int, int] | None = None,
502
+ ignore_index: int | None = None,
503
+ do_reduce_labels: bool = False,
504
+ ):
505
+ """Convert segmentation map to binary masks using NumPy operations."""
506
+ if do_reduce_labels and ignore_index is None:
507
+ raise ValueError("If `do_reduce_labels` is True, `ignore_index` must be provided.")
508
+
509
+ if do_reduce_labels:
510
+ segmentation_map = np.where(segmentation_map == 0, ignore_index, segmentation_map - 1)
511
+
512
+ all_labels = np.unique(segmentation_map)
513
+
514
+ if ignore_index is not None:
515
+ all_labels = all_labels[all_labels != ignore_index]
516
+
517
+ binary_masks = [(segmentation_map == i) for i in all_labels]
518
+ if binary_masks:
519
+ binary_masks = np.stack(binary_masks, axis=0)
520
+ else:
521
+ binary_masks = np.zeros((0, *segmentation_map.shape), dtype=np.float32)
522
+
523
+ # Convert instance ids to class ids
524
+ if instance_id_to_semantic_id is not None:
525
+ labels = np.zeros(all_labels.shape[0], dtype=np.int64)
526
+
527
+ for i, label in enumerate(all_labels):
528
+ class_id = instance_id_to_semantic_id[(int(label) + 1 if do_reduce_labels else int(label))]
529
+ labels[i] = class_id - 1 if do_reduce_labels else class_id
530
+ else:
531
+ labels = all_labels.astype(np.int64)
532
+ return binary_masks.astype(np.float32), labels
533
+
534
+ def get_semantic_annotations(self, label, num_class_obj):
535
+ annotation_classes = label["classes"]
536
+ annotation_masks = label["masks"]
537
+
538
+ texts = ["a semantic photo"] * self.num_text
539
+ classes = []
540
+ masks = []
541
+
542
+ for idx in range(len(annotation_classes)):
543
+ class_id = annotation_classes[idx]
544
+ mask = annotation_masks[idx]
545
+ if not np.all(mask == 0):
546
+ if class_id not in classes:
547
+ cls_name = self.metadata[str(class_id)]
548
+ classes.append(class_id)
549
+ masks.append(mask)
550
+ num_class_obj[cls_name] += 1
551
+ else:
552
+ idx = classes.index(class_id)
553
+ masks[idx] += mask
554
+ masks[idx] = np.clip(masks[idx], 0, 1)
555
+
556
+ num = 0
557
+ for i, cls_name in enumerate(self.metadata["class_names"]):
558
+ if num_class_obj[cls_name] > 0:
559
+ for _ in range(num_class_obj[cls_name]):
560
+ if num >= len(texts):
561
+ break
562
+ texts[num] = f"a photo with a {cls_name}"
563
+ num += 1
564
+
565
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
566
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
567
+ if masks:
568
+ masks = np.stack(masks, axis=0)
569
+ else:
570
+ # Empty masks - use shape from first annotation mask if available
571
+ if annotation_masks and len(annotation_masks) > 0:
572
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
573
+ else:
574
+ mask_shape = (0, 0)
575
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
576
+ return classes, masks, texts
577
+
578
+ def get_instance_annotations(self, label, num_class_obj):
579
+ annotation_classes = label["classes"]
580
+ annotation_masks = label["masks"]
581
+
582
+ texts = ["an instance photo"] * self.num_text
583
+ classes = []
584
+ masks = []
585
+
586
+ for idx in range(len(annotation_classes)):
587
+ class_id = annotation_classes[idx]
588
+ mask = annotation_masks[idx]
589
+
590
+ if class_id in self.metadata["thing_ids"]:
591
+ if not np.all(mask == 0):
592
+ cls_name = self.metadata[str(class_id)]
593
+ classes.append(class_id)
594
+ masks.append(mask)
595
+ num_class_obj[cls_name] += 1
596
+
597
+ num = 0
598
+ for i, cls_name in enumerate(self.metadata["class_names"]):
599
+ if num_class_obj[cls_name] > 0:
600
+ for _ in range(num_class_obj[cls_name]):
601
+ if num >= len(texts):
602
+ break
603
+ texts[num] = f"a photo with a {cls_name}"
604
+ num += 1
605
+
606
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
607
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
608
+ if masks:
609
+ masks = np.stack(masks, axis=0)
610
+ else:
611
+ # Empty masks - use shape from first annotation mask if available
612
+ if annotation_masks and len(annotation_masks) > 0:
613
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
614
+ else:
615
+ mask_shape = (0, 0)
616
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
617
+ return classes, masks, texts
618
+
619
+ def get_panoptic_annotations(self, label, num_class_obj):
620
+ annotation_classes = label["classes"]
621
+ annotation_masks = label["masks"]
622
+
623
+ texts = ["an panoptic photo"] * self.num_text
624
+ classes = []
625
+ masks = []
626
+ for idx in range(len(annotation_classes)):
627
+ class_id = annotation_classes[idx]
628
+ mask = annotation_masks[idx] if hasattr(annotation_masks[idx], "data") else annotation_masks[idx]
629
+ if not np.all(mask == 0):
630
+ cls_name = self.metadata[str(class_id)]
631
+ classes.append(class_id)
632
+ masks.append(mask)
633
+ num_class_obj[cls_name] += 1
634
+
635
+ num = 0
636
+ for i, cls_name in enumerate(self.metadata["class_names"]):
637
+ if num_class_obj[cls_name] > 0:
638
+ for _ in range(num_class_obj[cls_name]):
639
+ if num >= len(texts):
640
+ break
641
+ texts[num] = f"a photo with a {cls_name}"
642
+ num += 1
643
+
644
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
645
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
646
+ if masks:
647
+ masks = np.stack(masks, axis=0)
648
+ else:
649
+ # Empty masks - use shape from first annotation mask if available
650
+ if annotation_masks and len(annotation_masks) > 0:
651
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
652
+ else:
653
+ mask_shape = (0, 0)
654
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
655
+ return classes, masks, texts
656
+
657
+ def encode_inputs(
658
+ self,
659
+ pixel_values_list: list[np.ndarray],
660
+ task_inputs: list[str] | None = None,
661
+ segmentation_maps: list[np.ndarray] | None = None,
662
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
663
+ ignore_index: int | None = None,
664
+ do_reduce_labels: bool = False,
665
+ return_tensors: str | TensorType | None = None,
666
+ ) -> BatchFeature:
667
+ ignore_index = self.ignore_index if ignore_index is None else ignore_index
668
+ do_reduce_labels = self.do_reduce_labels if do_reduce_labels is None else do_reduce_labels
669
+ if task_inputs is None:
670
+ task_inputs = ["panoptic"]
671
+ pixel_values_list = self._prepare_image_like_inputs(
672
+ pixel_values_list, input_data_format=ChannelDimension.FIRST
673
+ )
674
+ if segmentation_maps is not None:
675
+ segmentation_maps = self._prepare_image_like_inputs(
676
+ images=segmentation_maps,
677
+ expected_ndims=2,
678
+ do_convert_rgb=False,
679
+ input_data_format=ChannelDimension.FIRST,
680
+ )
681
+ pad_size = get_max_height_width(pixel_values_list, input_data_format=ChannelDimension.FIRST)
682
+ encoded_inputs = self.pad(pixel_values_list, return_tensors=return_tensors)
683
+
684
+ annotations = None
685
+ if segmentation_maps is not None:
686
+ annotations = []
687
+ for idx, segmentation_map in enumerate(segmentation_maps):
688
+ # Use instance2class_id mapping per image
689
+ if isinstance(instance_id_to_semantic_id, list):
690
+ instance_id = instance_id_to_semantic_id[idx]
691
+ else:
692
+ instance_id = instance_id_to_semantic_id
693
+
694
+ # Squeeze channel dimension if present
695
+ if segmentation_map.ndim == 3 and segmentation_map.shape[0] == 1:
696
+ segmentation_map = segmentation_map.squeeze(0)
697
+
698
+ # Convert segmentation map to binary masks using numpy operations
699
+ masks, classes = self.convert_segmentation_map_to_binary_masks(
700
+ segmentation_map, instance_id, ignore_index=ignore_index, do_reduce_labels=do_reduce_labels
701
+ )
702
+
703
+ annotations.append({"masks": masks, "classes": classes})
704
+
705
+ if annotations is not None:
706
+ mask_labels = []
707
+ class_labels = []
708
+ text_inputs = []
709
+ num_class_obj = dict.fromkeys(self.metadata["class_names"], 0)
710
+
711
+ for i, label in enumerate(annotations):
712
+ task = task_inputs[i]
713
+
714
+ if task == "semantic":
715
+ classes, masks, texts = self.get_semantic_annotations(label, num_class_obj)
716
+ elif task == "instance":
717
+ classes, masks, texts = self.get_instance_annotations(label, num_class_obj)
718
+ elif task == "panoptic":
719
+ classes, masks, texts = self.get_panoptic_annotations(label, num_class_obj)
720
+ else:
721
+ raise ValueError(f"{task} was not expected, expected `semantic`, `instance` or `panoptic`")
722
+ # Pad masks to max size using numpy operations
723
+ # masks is a 3D array (num_masks, H, W), iterate to get 2D slices
724
+ padded_masks = [
725
+ self._pad_image(image=mask, output_size=pad_size, constant_values=ignore_index) for mask in masks
726
+ ]
727
+ # Stack padded masks back into 3D array (num_masks, padded_H, padded_W)
728
+ padded_masks = (
729
+ np.stack(padded_masks, axis=0) if padded_masks else np.zeros((0, *pad_size), dtype=np.float32)
730
+ )
731
+ mask_labels.append(padded_masks)
732
+ class_labels.append(classes)
733
+ text_inputs.append(texts)
734
+
735
+ encoded_inputs["mask_labels"] = [
736
+ torch.from_numpy(mask_label) if return_tensors == "pt" else mask_label for mask_label in mask_labels
737
+ ]
738
+ encoded_inputs["class_labels"] = [
739
+ torch.from_numpy(class_label) if return_tensors == "pt" else class_label
740
+ for class_label in class_labels
741
+ ]
742
+ encoded_inputs["text_inputs"] = text_inputs
743
+
744
+ encoded_inputs["task_inputs"] = [f"the task is {task_input}" for task_input in task_inputs]
745
+ return encoded_inputs
746
+
747
+ def post_process_semantic_segmentation(
748
+ self, outputs, target_sizes: list[tuple[int, int]] | None = None
749
+ ) -> "torch.Tensor":
750
+ """
751
+ Converts the output of [`MaskFormerForInstanceSegmentation`] into semantic segmentation maps. Only supports
752
+ PyTorch.
753
+
754
+ Args:
755
+ outputs ([`MaskFormerForInstanceSegmentation`]):
756
+ Raw outputs of the model.
757
+ target_sizes (`List[Tuple[int, int]]`, *optional*):
758
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
759
+ final size (height, width) of each prediction. If left to None, predictions will not be resized.
760
+ Returns:
761
+ `List[torch.Tensor]`:
762
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
763
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
764
+ `torch.Tensor` correspond to a semantic class id.
765
+ """
766
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
767
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
768
+
769
+ # Remove the null class `[..., :-1]`
770
+ masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
771
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
772
+
773
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
774
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
775
+ batch_size = class_queries_logits.shape[0]
776
+
777
+ # Resize logits and compute semantic segmentation maps
778
+ if target_sizes is not None:
779
+ if batch_size != len(target_sizes):
780
+ raise ValueError(
781
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
782
+ )
783
+
784
+ semantic_segmentation = []
785
+ for idx in range(batch_size):
786
+ resized_logits = torch.nn.functional.interpolate(
787
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
788
+ )
789
+ semantic_map = resized_logits[0].argmax(dim=0)
790
+ semantic_segmentation.append(semantic_map)
791
+ else:
792
+ semantic_segmentation = segmentation.argmax(dim=1)
793
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
794
+
795
+ return semantic_segmentation
796
+
797
+ def post_process_instance_segmentation(
798
+ self,
799
+ outputs,
800
+ task_type: str = "instance",
801
+ is_demo: bool = True,
802
+ threshold: float = 0.5,
803
+ mask_threshold: float = 0.5,
804
+ overlap_mask_area_threshold: float = 0.8,
805
+ target_sizes: list[tuple[int, int]] | None = None,
806
+ return_coco_annotation: bool | None = False,
807
+ ):
808
+ """
809
+ Converts the output of [`OneFormerForUniversalSegmentationOutput`] into image instance segmentation
810
+ predictions. Only supports PyTorch.
811
+
812
+ Args:
813
+ outputs ([`OneFormerForUniversalSegmentationOutput`]):
814
+ The outputs from [`OneFormerForUniversalSegmentationOutput`].
815
+ task_type (`str`, *optional*, defaults to "instance"):
816
+ The post processing depends on the task token input. If the `task_type` is "panoptic", we need to
817
+ ignore the stuff predictions.
818
+ is_demo (`bool`, *optional)*, defaults to `True`):
819
+ Whether the model is in demo mode. If true, use threshold to predict final masks.
820
+ threshold (`float`, *optional*, defaults to 0.5):
821
+ The probability score threshold to keep predicted instance masks.
822
+ mask_threshold (`float`, *optional*, defaults to 0.5):
823
+ Threshold to use when turning the predicted masks into binary values.
824
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
825
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
826
+ instance mask.
827
+ target_sizes (`List[Tuple]`, *optional*):
828
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
829
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
830
+ resized.
831
+ return_coco_annotation (`bool`, *optional)*, defaults to `False`):
832
+ Whether to return predictions in COCO format.
833
+
834
+ Returns:
835
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
836
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
837
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
838
+ to the corresponding `target_sizes` entry.
839
+ - **segments_info** -- A dictionary that contains additional information on each segment.
840
+ - **id** -- an integer representing the `segment_id`.
841
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
842
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
843
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
844
+ - **score** -- Prediction score of segment with `segment_id`.
845
+ """
846
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
847
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
848
+
849
+ device = masks_queries_logits.device
850
+ batch_size = class_queries_logits.shape[0]
851
+ num_queries = class_queries_logits.shape[1]
852
+ num_classes = class_queries_logits.shape[-1] - 1
853
+
854
+ # Loop over items in batch size
855
+ results: list[dict[str, torch.Tensor]] = []
856
+
857
+ for i in range(batch_size):
858
+ # [Q, K]
859
+ scores = nn.functional.softmax(class_queries_logits[i], dim=-1)[:, :-1]
860
+ labels = torch.arange(num_classes, device=device).unsqueeze(0).repeat(num_queries, 1).flatten(0, 1)
861
+
862
+ # scores_per_image, topk_indices = scores.flatten(0, 1).topk(self.num_queries, sorted=False)
863
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(num_queries, sorted=False)
864
+ labels_per_image = labels[topk_indices]
865
+
866
+ topk_indices = torch.div(topk_indices, num_classes, rounding_mode="floor")
867
+ # mask_pred = mask_pred.unsqueeze(1).repeat(1, self.sem_seg_head.num_classes, 1).flatten(0, 1)
868
+ mask_pred = masks_queries_logits[i][topk_indices]
869
+
870
+ # Only consider scores with confidence over [threshold] for demo
871
+ if is_demo:
872
+ keep = scores_per_image > threshold
873
+ scores_per_image = scores_per_image[keep]
874
+ labels_per_image = labels_per_image[keep]
875
+ mask_pred = mask_pred[keep]
876
+
877
+ # if this is panoptic segmentation, we only keep the "thing" classes
878
+ if task_type == "panoptic":
879
+ keep = torch.zeros_like(scores_per_image).bool()
880
+ for j, lab in enumerate(labels_per_image):
881
+ keep[j] = lab in self.metadata["thing_ids"]
882
+
883
+ scores_per_image = scores_per_image[keep]
884
+ labels_per_image = labels_per_image[keep]
885
+ mask_pred = mask_pred[keep]
886
+
887
+ if mask_pred.shape[0] <= 0:
888
+ height, width = target_sizes[i] if target_sizes is not None else mask_pred.shape[1:]
889
+ segmentation = torch.zeros((height, width)) - 1
890
+ results.append({"segmentation": segmentation, "segments_info": []})
891
+ continue
892
+
893
+ if "ade20k" in self.class_info_file and not is_demo and "instance" in task_type:
894
+ for j in range(labels_per_image.shape[0]):
895
+ labels_per_image[j] = self.metadata["thing_ids"].index(labels_per_image[j].item())
896
+
897
+ # Get segmentation map and segment information of batch item
898
+ target_size = target_sizes[i] if target_sizes is not None else None
899
+ segmentation, segments = compute_segments(
900
+ mask_pred,
901
+ scores_per_image,
902
+ labels_per_image,
903
+ mask_threshold,
904
+ overlap_mask_area_threshold,
905
+ set(),
906
+ target_size,
907
+ )
908
+
909
+ # Return segmentation map in run-length encoding (RLE) format
910
+ if return_coco_annotation:
911
+ segmentation = convert_segmentation_to_rle(segmentation)
912
+
913
+ results.append({"segmentation": segmentation, "segments_info": segments})
914
+ return results
915
+
916
+ # Adapted from transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessor.post_process_panoptic_segmentation
917
+ def post_process_panoptic_segmentation(
918
+ self,
919
+ outputs,
920
+ threshold: float = 0.5,
921
+ mask_threshold: float = 0.5,
922
+ overlap_mask_area_threshold: float = 0.8,
923
+ label_ids_to_fuse: set[int] | None = None,
924
+ target_sizes: list[tuple[int, int]] | None = None,
925
+ ) -> list[dict]:
926
+ """
927
+ Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into image panoptic segmentation
928
+ predictions. Only supports PyTorch.
929
+
930
+ Args:
931
+ outputs ([`MaskFormerForInstanceSegmentationOutput`]):
932
+ The outputs from [`MaskFormerForInstanceSegmentation`].
933
+ threshold (`float`, *optional*, defaults to 0.5):
934
+ The probability score threshold to keep predicted instance masks.
935
+ mask_threshold (`float`, *optional*, defaults to 0.5):
936
+ Threshold to use when turning the predicted masks into binary values.
937
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
938
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
939
+ instance mask.
940
+ label_ids_to_fuse (`Set[int]`, *optional*):
941
+ The labels in this state will have all their instances be fused together. For instance we could say
942
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
943
+ set, but not the one for person.
944
+ target_sizes (`list[Tuple]`, *optional*):
945
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
946
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
947
+ resized.
948
+
949
+ Returns:
950
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
951
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
952
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
953
+ to the corresponding `target_sizes` entry.
954
+ - **segments_info** -- A dictionary that contains additional information on each segment.
955
+ - **id** -- an integer representing the `segment_id`.
956
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
957
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
958
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
959
+ - **score** -- Prediction score of segment with `segment_id`.
960
+ """
961
+
962
+ if label_ids_to_fuse is None:
963
+ logger.warning("`label_ids_to_fuse` unset. No instance will be fused.")
964
+ label_ids_to_fuse = set()
965
+
966
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
967
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
968
+
969
+ batch_size = class_queries_logits.shape[0]
970
+ num_labels = class_queries_logits.shape[-1] - 1
971
+
972
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
973
+
974
+ # Predicted label and score of each query (batch_size, num_queries)
975
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
976
+
977
+ # Loop over items in batch size
978
+ results: list[dict[str, TensorType]] = []
979
+
980
+ for i in range(batch_size):
981
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
982
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
983
+ )
984
+
985
+ # No mask found
986
+ if mask_probs_item.shape[0] <= 0:
987
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
988
+ segmentation = torch.zeros((height, width)) - 1
989
+ results.append({"segmentation": segmentation, "segments_info": []})
990
+ continue
991
+
992
+ # Get segmentation map and segment information of batch item
993
+ target_size = target_sizes[i] if target_sizes is not None else None
994
+ segmentation, segments = compute_segments(
995
+ mask_probs=mask_probs_item,
996
+ pred_scores=pred_scores_item,
997
+ pred_labels=pred_labels_item,
998
+ mask_threshold=mask_threshold,
999
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
1000
+ label_ids_to_fuse=label_ids_to_fuse,
1001
+ target_size=target_size,
1002
+ )
1003
+
1004
+ results.append({"segmentation": segmentation, "segments_info": segments})
1005
+ return results
1006
+
1007
+
1008
+ __all__ = ["OneFormerImageProcessorPil"]
lib/python3.11/site-packages/transformers/models/oneformer/modeling_oneformer.py ADDED
The diff for this file is too large to render. See raw diff
 
lib/python3.11/site-packages/transformers/models/oneformer/processing_oneformer.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 SHI Labs 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
+ """
15
+ Image/Text processor class for OneFormer
16
+ """
17
+
18
+ from ...processing_utils import ProcessorMixin
19
+ from ...utils import auto_docstring, is_torch_available
20
+
21
+
22
+ if is_torch_available():
23
+ import torch
24
+
25
+
26
+ @auto_docstring
27
+ class OneFormerProcessor(ProcessorMixin):
28
+ def __init__(
29
+ self, image_processor=None, tokenizer=None, max_seq_length: int = 77, task_seq_length: int = 77, **kwargs
30
+ ):
31
+ r"""
32
+ max_seq_length (`int`, *optional*, defaults to `77`):
33
+ Maximum sequence length for encoding class names and text inputs. This parameter controls the
34
+ maximum number of tokens used when tokenizing class names and other text inputs for the model.
35
+ task_seq_length (`int`, *optional*, defaults to `77`):
36
+ Maximum sequence length specifically for encoding task descriptions. Task descriptions (e.g.,
37
+ "the task is semantic") are tokenized with this length limit, which may differ from the general
38
+ text sequence length.
39
+ """
40
+ self.max_seq_length = max_seq_length
41
+ self.task_seq_length = task_seq_length
42
+
43
+ super().__init__(image_processor, tokenizer)
44
+
45
+ def _preprocess_text(self, text_list=None, max_length=77):
46
+ if text_list is None:
47
+ raise ValueError("tokens cannot be None.")
48
+
49
+ tokens = self.tokenizer(text_list, padding="max_length", max_length=max_length, truncation=True)
50
+
51
+ attention_masks, input_ids = tokens["attention_mask"], tokens["input_ids"]
52
+
53
+ token_inputs = []
54
+ for attn_mask, input_id in zip(attention_masks, input_ids):
55
+ token = torch.tensor(attn_mask) * torch.tensor(input_id)
56
+ token_inputs.append(token.unsqueeze(0))
57
+
58
+ token_inputs = torch.cat(token_inputs, dim=0)
59
+ return token_inputs
60
+
61
+ @auto_docstring
62
+ def __call__(self, images=None, task_inputs=None, segmentation_maps=None, **kwargs):
63
+ r"""
64
+ task_inputs (`str` or `list[str]`, *required*):
65
+ The task type(s) for segmentation. Must be one or more of `"semantic"`, `"instance"`, or `"panoptic"`.
66
+ Can be a single string for a single image, or a list of strings (one per image) for batch processing.
67
+ The task type determines which type of segmentation the model will perform on the input images.
68
+ segmentation_maps (`ImageInput`, *optional*):
69
+ The corresponding semantic segmentation maps with the pixel-wise annotations.
70
+
71
+ (`bool`, *optional*, defaults to `True`):
72
+ Whether or not to pad images up to the largest image in a batch and create a pixel mask.
73
+
74
+ If left to the default, will return a pixel mask that is:
75
+
76
+ - 1 for pixels that are real (i.e. **not masked**),
77
+ - 0 for pixels that are padding (i.e. **masked**).
78
+
79
+ Returns:
80
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
81
+ - **task_inputs** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
82
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
83
+ """
84
+
85
+ if task_inputs is None:
86
+ raise ValueError("You have to specify the task_input. Found None.")
87
+ elif images is None:
88
+ raise ValueError("You have to specify the image. Found None.")
89
+
90
+ if not all(task in ["semantic", "instance", "panoptic"] for task in task_inputs):
91
+ raise ValueError("task_inputs must be semantic, instance, or panoptic.")
92
+
93
+ encoded_inputs = self.image_processor(images, task_inputs, segmentation_maps, **kwargs)
94
+
95
+ if isinstance(task_inputs, str):
96
+ task_inputs = [task_inputs]
97
+
98
+ if isinstance(task_inputs, list) and all(isinstance(task_input, str) for task_input in task_inputs):
99
+ task_token_inputs = []
100
+ for task in task_inputs:
101
+ task_input = f"the task is {task}"
102
+ task_token_inputs.append(task_input)
103
+ encoded_inputs["task_inputs"] = self._preprocess_text(task_token_inputs, max_length=self.task_seq_length)
104
+ else:
105
+ raise TypeError("Task Inputs should be a string or a list of strings.")
106
+
107
+ if hasattr(encoded_inputs, "text_inputs"):
108
+ texts_list = encoded_inputs.text_inputs
109
+
110
+ text_inputs = []
111
+ for texts in texts_list:
112
+ text_input_list = self._preprocess_text(texts, max_length=self.max_seq_length)
113
+ text_inputs.append(text_input_list.unsqueeze(0))
114
+
115
+ encoded_inputs["text_inputs"] = torch.cat(text_inputs, dim=0)
116
+
117
+ return encoded_inputs
118
+
119
+ def encode_inputs(self, images=None, task_inputs=None, segmentation_maps=None, **kwargs):
120
+ """
121
+ This method forwards all its arguments to [`OneFormerImageProcessor.encode_inputs`] and then tokenizes the
122
+ task_inputs. Please refer to the docstring of this method for more information.
123
+ """
124
+
125
+ if task_inputs is None:
126
+ raise ValueError("You have to specify the task_input. Found None.")
127
+ elif images is None:
128
+ raise ValueError("You have to specify the image. Found None.")
129
+
130
+ if not all(task in ["semantic", "instance", "panoptic"] for task in task_inputs):
131
+ raise ValueError("task_inputs must be semantic, instance, or panoptic.")
132
+
133
+ encoded_inputs = self.image_processor.encode_inputs(images, task_inputs, segmentation_maps, **kwargs)
134
+
135
+ if isinstance(task_inputs, str):
136
+ task_inputs = [task_inputs]
137
+
138
+ if isinstance(task_inputs, list) and all(isinstance(task_input, str) for task_input in task_inputs):
139
+ task_token_inputs = []
140
+ for task in task_inputs:
141
+ task_input = f"the task is {task}"
142
+ task_token_inputs.append(task_input)
143
+ encoded_inputs["task_inputs"] = self._preprocess_text(task_token_inputs, max_length=self.task_seq_length)
144
+ else:
145
+ raise TypeError("Task Inputs should be a string or a list of strings.")
146
+
147
+ if hasattr(encoded_inputs, "text_inputs"):
148
+ texts_list = encoded_inputs.text_inputs
149
+
150
+ text_inputs = []
151
+ for texts in texts_list:
152
+ text_input_list = self._preprocess_text(texts, max_length=self.max_seq_length)
153
+ text_inputs.append(text_input_list.unsqueeze(0))
154
+
155
+ encoded_inputs["text_inputs"] = torch.cat(text_inputs, dim=0)
156
+
157
+ return encoded_inputs
158
+
159
+ def post_process_semantic_segmentation(self, *args, **kwargs):
160
+ """
161
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_semantic_segmentation`].
162
+ Please refer to the docstring of this method for more information.
163
+ """
164
+ return self.image_processor.post_process_semantic_segmentation(*args, **kwargs)
165
+
166
+ def post_process_instance_segmentation(self, *args, **kwargs):
167
+ """
168
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_instance_segmentation`].
169
+ Please refer to the docstring of this method for more information.
170
+ """
171
+ return self.image_processor.post_process_instance_segmentation(*args, **kwargs)
172
+
173
+ def post_process_panoptic_segmentation(self, *args, **kwargs):
174
+ """
175
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_panoptic_segmentation`].
176
+ Please refer to the docstring of this method for more information.
177
+ """
178
+ return self.image_processor.post_process_panoptic_segmentation(*args, **kwargs)
179
+
180
+
181
+ __all__ = ["OneFormerProcessor"]
lib/python3.11/site-packages/transformers/models/openai/__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_openai import *
22
+ from .modeling_openai import *
23
+ from .tokenization_openai 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__)
lib/python3.11/site-packages/transformers/models/openai/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (819 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/openai/__pycache__/configuration_openai.cpython-311.pyc ADDED
Binary file (4.86 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai/__pycache__/modeling_openai.cpython-311.pyc ADDED
Binary file (39 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai/__pycache__/tokenization_openai.cpython-311.pyc ADDED
Binary file (4.05 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai/configuration_openai.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """OpenAI GPT configuration"""
16
+
17
+ from huggingface_hub.dataclasses import strict
18
+
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="openai-community/openai-gpt")
24
+ @strict
25
+ class OpenAIGPTConfig(PreTrainedConfig):
26
+ r"""
27
+ afn (`str` or `Callable`, *optional*, defaults to `"gelu"`):
28
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
29
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
30
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
31
+ The epsilon to use in the layer normalization layers
32
+ summary_type (`str`, *optional*, defaults to `"cls_index"`):
33
+ Argument used when doing sequence summary, used in the models [`OpenAIGPTDoubleHeadsModel`] and
34
+ [`OpenAIGPTDoubleHeadsModel`].
35
+ Has to be one of the following options:
36
+ - `"last"`: Take the last token hidden state (like XLNet).
37
+ - `"first"`: Take the first token hidden state (like BERT).
38
+ - `"mean"`: Take the mean of all tokens hidden states.
39
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
40
+ - `"attn"`: Not implemented now, use multi-head attention.
41
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
42
+ Argument used when doing sequence summary, used in the models [`OpenAIGPTDoubleHeadsModel`] and
43
+ [`OpenAIGPTDoubleHeadsModel`].
44
+ Whether or not to add a projection after the vector extraction.
45
+ summary_activation (`str`, *optional*):
46
+ Argument used when doing sequence summary, used in the models [`OpenAIGPTDoubleHeadsModel`] and
47
+ [`OpenAIGPTDoubleHeadsModel`].
48
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
49
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
50
+ Argument used when doing sequence summary, used in the models [`OpenAIGPTDoubleHeadsModel`] and
51
+ [`OpenAIGPTDoubleHeadsModel`].
52
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
53
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
54
+ Argument used when doing sequence summary, used in the models [`OpenAIGPTDoubleHeadsModel`] and
55
+ [`OpenAIGPTDoubleHeadsModel`].
56
+ The dropout ratio to be used after the projection and activation.
57
+
58
+ Examples:
59
+
60
+ ```python
61
+ >>> from transformers import OpenAIGPTConfig, OpenAIGPTModel
62
+
63
+ >>> # Initializing a GPT configuration
64
+ >>> configuration = OpenAIGPTConfig()
65
+
66
+ >>> # Initializing a model (with random weights) from the configuration
67
+ >>> model = OpenAIGPTModel(configuration)
68
+
69
+ >>> # Accessing the model configuration
70
+ >>> configuration = model.config
71
+ ```"""
72
+
73
+ model_type = "openai-gpt"
74
+ attribute_map = {
75
+ "max_position_embeddings": "n_positions",
76
+ "hidden_size": "n_embd",
77
+ "num_attention_heads": "n_head",
78
+ "num_hidden_layers": "n_layer",
79
+ }
80
+
81
+ vocab_size: int = 40478
82
+ n_positions: int = 512
83
+ n_embd: int = 768
84
+ n_layer: int = 12
85
+ n_head: int = 12
86
+ afn: str = "gelu"
87
+ resid_pdrop: float | int = 0.1
88
+ embd_pdrop: float | int = 0.1
89
+ attn_pdrop: float | int = 0.1
90
+ layer_norm_epsilon: float = 1e-5
91
+ initializer_range: float = 0.02
92
+ summary_type: str = "cls_index"
93
+ summary_use_proj: bool = True
94
+ summary_activation: str | None = None
95
+ summary_proj_to_labels: bool = True
96
+ summary_first_dropout: float | int = 0.1
97
+ pad_token_id: int | None = None
98
+ bos_token_id: int | None = None
99
+ eos_token_id: int | list[int] | None = None
100
+ tie_word_embeddings: bool = True
101
+
102
+
103
+ __all__ = ["OpenAIGPTConfig"]
lib/python3.11/site-packages/transformers/models/openai/modeling_openai.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch OpenAI GPT model."""
16
+
17
+ import math
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+ import torch
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ... import initialization as init
27
+ from ...activations import gelu_new, get_activation, silu
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
30
+ from ...modeling_utils import PreTrainedModel
31
+ from ...pytorch_utils import Conv1D
32
+ from ...utils import (
33
+ ModelOutput,
34
+ auto_docstring,
35
+ logging,
36
+ )
37
+ from .configuration_openai import OpenAIGPTConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ ACT_FNS = {"relu": nn.ReLU(), "silu": silu, "gelu": gelu_new, "swish": silu}
44
+
45
+
46
+ class Attention(nn.Module):
47
+ def __init__(self, nx, n_positions, config, scale=False):
48
+ super().__init__()
49
+ self.n_positions = n_positions
50
+ n_state = nx # in Attention: n_state=768 (nx=n_embd)
51
+ if n_state % config.n_head != 0:
52
+ raise ValueError(f"Attention n_state shape: {n_state} must be divisible by config.n_head {config.n_head}")
53
+ self.register_buffer(
54
+ "bias",
55
+ torch.tril(torch.ones(n_positions, n_positions)).view(1, 1, n_positions, n_positions),
56
+ persistent=False,
57
+ )
58
+ self.n_head = config.n_head
59
+ self.split_size = n_state
60
+ self.scale = scale
61
+
62
+ self.c_attn = Conv1D(n_state * 3, nx)
63
+ self.c_proj = Conv1D(n_state, nx)
64
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
65
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
66
+
67
+ def _attn(self, q, k, v, attention_mask=None, output_attentions=False):
68
+ w = torch.matmul(q, k)
69
+ if self.scale:
70
+ w = w / math.sqrt(v.size(-1))
71
+ # XD: self.b may be larger than w, so we need to crop it
72
+ b = self.bias[:, :, : w.size(-2), : w.size(-1)]
73
+ w = w * b + -1e4 * (1 - b)
74
+
75
+ if attention_mask is not None:
76
+ # Apply the attention mask
77
+ w = w + attention_mask
78
+
79
+ w = nn.functional.softmax(w, dim=-1)
80
+ w = self.attn_dropout(w)
81
+
82
+ outputs = [torch.matmul(w, v)]
83
+ if output_attentions:
84
+ outputs.append(w)
85
+ return outputs
86
+
87
+ def merge_heads(self, x):
88
+ x = x.permute(0, 2, 1, 3).contiguous()
89
+ new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
90
+ return x.view(*new_x_shape)
91
+
92
+ def split_heads(self, x, k=False):
93
+ new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)
94
+ x = x.view(*new_x_shape)
95
+ if k:
96
+ return x.permute(0, 2, 3, 1)
97
+ else:
98
+ return x.permute(0, 2, 1, 3)
99
+
100
+ def forward(self, x, attention_mask=None, output_attentions=False):
101
+ x = self.c_attn(x)
102
+ query, key, value = x.split(self.split_size, dim=2)
103
+ query = self.split_heads(query)
104
+ key = self.split_heads(key, k=True)
105
+ value = self.split_heads(value)
106
+
107
+ attn_outputs = self._attn(query, key, value, attention_mask, output_attentions)
108
+ a = attn_outputs[0]
109
+
110
+ a = self.merge_heads(a)
111
+ a = self.c_proj(a)
112
+ a = self.resid_dropout(a)
113
+
114
+ outputs = [a] + attn_outputs[1:]
115
+ return outputs # a, (attentions)
116
+
117
+
118
+ class MLP(nn.Module):
119
+ def __init__(self, n_state, config): # in MLP: n_state=3072 (4 * n_embd)
120
+ super().__init__()
121
+ nx = config.n_embd
122
+ self.c_fc = Conv1D(n_state, nx)
123
+ self.c_proj = Conv1D(nx, n_state)
124
+ self.act = ACT_FNS[config.afn]
125
+ self.dropout = nn.Dropout(config.resid_pdrop)
126
+
127
+ def forward(self, x):
128
+ h = self.act(self.c_fc(x))
129
+ h2 = self.c_proj(h)
130
+ return self.dropout(h2)
131
+
132
+
133
+ class Block(nn.Module):
134
+ def __init__(self, n_positions, config, scale=False):
135
+ super().__init__()
136
+ nx = config.n_embd
137
+ self.attn = Attention(nx, n_positions, config, scale)
138
+ self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
139
+ self.mlp = MLP(4 * nx, config)
140
+ self.ln_2 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
141
+
142
+ def forward(self, x, attention_mask=None, output_attentions=False):
143
+ attn_outputs = self.attn(
144
+ x,
145
+ attention_mask=attention_mask,
146
+ output_attentions=output_attentions,
147
+ )
148
+ a = attn_outputs[0]
149
+
150
+ n = self.ln_1(x + a)
151
+ m = self.mlp(n)
152
+ h = self.ln_2(n + m)
153
+
154
+ outputs = [h] + attn_outputs[1:]
155
+ return outputs
156
+
157
+
158
+ # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->OpenAIGPT
159
+ class OpenAIGPTSequenceSummary(nn.Module):
160
+ r"""
161
+ Compute a single vector summary of a sequence hidden states.
162
+
163
+ Args:
164
+ config ([`OpenAIGPTConfig`]):
165
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
166
+ config class of your model for the default values it uses):
167
+
168
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
169
+
170
+ - `"last"` -- Take the last token hidden state (like XLNet)
171
+ - `"first"` -- Take the first token hidden state (like Bert)
172
+ - `"mean"` -- Take the mean of all tokens hidden states
173
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
174
+ - `"attn"` -- Not implemented now, use multi-head attention
175
+
176
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
177
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
178
+ (otherwise to `config.hidden_size`).
179
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
180
+ another string or `None` will add no activation.
181
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
182
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
183
+ """
184
+
185
+ def __init__(self, config: OpenAIGPTConfig):
186
+ super().__init__()
187
+
188
+ self.summary_type = getattr(config, "summary_type", "last")
189
+ if self.summary_type == "attn":
190
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
191
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
192
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
193
+ raise NotImplementedError
194
+
195
+ self.summary = nn.Identity()
196
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
197
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
198
+ num_classes = config.num_labels
199
+ else:
200
+ num_classes = config.hidden_size
201
+ self.summary = nn.Linear(config.hidden_size, num_classes)
202
+
203
+ activation_string = getattr(config, "summary_activation", None)
204
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
205
+
206
+ self.first_dropout = nn.Identity()
207
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
208
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
209
+
210
+ self.last_dropout = nn.Identity()
211
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
212
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
213
+
214
+ def forward(
215
+ self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
216
+ ) -> torch.FloatTensor:
217
+ """
218
+ Compute a single vector summary of a sequence hidden states.
219
+
220
+ Args:
221
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
222
+ The hidden states of the last layer.
223
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
224
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
225
+
226
+ Returns:
227
+ `torch.FloatTensor`: The summary of the sequence hidden states.
228
+ """
229
+ if self.summary_type == "last":
230
+ output = hidden_states[:, -1]
231
+ elif self.summary_type == "first":
232
+ output = hidden_states[:, 0]
233
+ elif self.summary_type == "mean":
234
+ output = hidden_states.mean(dim=1)
235
+ elif self.summary_type == "cls_index":
236
+ if cls_index is None:
237
+ cls_index = torch.full_like(
238
+ hidden_states[..., :1, :],
239
+ hidden_states.shape[-2] - 1,
240
+ dtype=torch.long,
241
+ )
242
+ else:
243
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
244
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
245
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
246
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
247
+ elif self.summary_type == "attn":
248
+ raise NotImplementedError
249
+
250
+ output = self.first_dropout(output)
251
+ output = self.summary(output)
252
+ output = self.activation(output)
253
+ output = self.last_dropout(output)
254
+
255
+ return output
256
+
257
+
258
+ @auto_docstring
259
+ class OpenAIGPTPreTrainedModel(PreTrainedModel):
260
+ config: OpenAIGPTConfig
261
+ base_model_prefix = "transformer"
262
+
263
+ def _init_weights(self, module):
264
+ super()._init_weights(module)
265
+ if isinstance(module, Attention):
266
+ n_positions = module.n_positions
267
+ init.copy_(
268
+ module.bias, torch.tril(torch.ones(n_positions, n_positions)).view(1, 1, n_positions, n_positions)
269
+ )
270
+ elif isinstance(module, OpenAIGPTModel):
271
+ init.copy_(module.position_ids, torch.arange(module.config.n_positions))
272
+
273
+
274
+ @auto_docstring(
275
+ custom_intro="""
276
+ Base class for outputs of models predicting if two sentences are consecutive or not.
277
+ """
278
+ )
279
+ @dataclass
280
+ class OpenAIGPTDoubleHeadsModelOutput(ModelOutput):
281
+ r"""
282
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
283
+ Language modeling loss.
284
+ mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
285
+ Multiple choice classification loss.
286
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
287
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
288
+ mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
289
+ Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
290
+ """
291
+
292
+ loss: torch.FloatTensor | None = None
293
+ mc_loss: torch.FloatTensor | None = None
294
+ logits: torch.FloatTensor | None = None
295
+ mc_logits: torch.FloatTensor | None = None
296
+ hidden_states: tuple[torch.FloatTensor] | None = None
297
+ attentions: tuple[torch.FloatTensor] | None = None
298
+
299
+
300
+ @auto_docstring
301
+ class OpenAIGPTModel(OpenAIGPTPreTrainedModel):
302
+ def __init__(self, config):
303
+ super().__init__(config)
304
+
305
+ self.tokens_embed = nn.Embedding(config.vocab_size, config.n_embd)
306
+ self.positions_embed = nn.Embedding(config.n_positions, config.n_embd)
307
+ self.drop = nn.Dropout(config.embd_pdrop)
308
+ self.h = nn.ModuleList([Block(config.n_positions, config, scale=True) for _ in range(config.n_layer)])
309
+
310
+ self.register_buffer("position_ids", torch.arange(config.n_positions), persistent=False)
311
+ # Initialize weights and apply final processing
312
+ self.post_init()
313
+
314
+ def get_input_embeddings(self):
315
+ return self.tokens_embed
316
+
317
+ def set_input_embeddings(self, new_embeddings):
318
+ self.tokens_embed = new_embeddings
319
+
320
+ @auto_docstring
321
+ def forward(
322
+ self,
323
+ input_ids: torch.LongTensor | None = None,
324
+ attention_mask: torch.FloatTensor | None = None,
325
+ token_type_ids: torch.LongTensor | None = None,
326
+ position_ids: torch.LongTensor | None = None,
327
+ inputs_embeds: torch.FloatTensor | None = None,
328
+ output_attentions: bool | None = None,
329
+ output_hidden_states: bool | None = None,
330
+ return_dict: bool | None = None,
331
+ **kwargs,
332
+ ) -> tuple[torch.Tensor] | BaseModelOutput:
333
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
334
+ output_hidden_states = (
335
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
336
+ )
337
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
338
+
339
+ if input_ids is not None and inputs_embeds is not None:
340
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
341
+ elif input_ids is not None:
342
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
343
+ input_shape = input_ids.size()
344
+ input_ids = input_ids.view(-1, input_shape[-1])
345
+ elif inputs_embeds is not None:
346
+ input_shape = inputs_embeds.size()[:-1]
347
+ else:
348
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
349
+
350
+ if position_ids is None:
351
+ # Code is different from when we had a single embedding matrix from position and token embeddings
352
+ position_ids = self.position_ids[None, : input_shape[-1]]
353
+
354
+ # Attention mask.
355
+ if attention_mask is not None:
356
+ # We create a 3D attention mask from a 2D tensor mask.
357
+ # Sizes are [batch_size, 1, 1, to_seq_length]
358
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
359
+ # this attention mask is more simple than the triangular masking of causal attention
360
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
361
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
362
+
363
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
364
+ # masked positions, this operation will create a tensor which is 0.0 for
365
+ # positions we want to attend and the dtype's smallest value for masked positions.
366
+ # Since we are adding it to the raw scores before the softmax, this is
367
+ # effectively the same as removing these entirely.
368
+ attention_mask = attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
369
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
370
+
371
+ if inputs_embeds is None:
372
+ inputs_embeds = self.tokens_embed(input_ids)
373
+ position_embeds = self.positions_embed(position_ids)
374
+ if token_type_ids is not None:
375
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1))
376
+ token_type_embeds = self.tokens_embed(token_type_ids)
377
+ else:
378
+ token_type_embeds = 0
379
+ hidden_states = inputs_embeds + position_embeds + token_type_embeds
380
+ hidden_states = self.drop(hidden_states)
381
+
382
+ output_shape = input_shape + (hidden_states.size(-1),)
383
+
384
+ all_attentions = () if output_attentions else None
385
+ all_hidden_states = () if output_hidden_states else None
386
+ for i, block in enumerate(self.h):
387
+ if output_hidden_states:
388
+ all_hidden_states = all_hidden_states + (hidden_states,)
389
+
390
+ outputs = block(hidden_states, attention_mask, output_attentions=output_attentions)
391
+ hidden_states = outputs[0]
392
+ if output_attentions:
393
+ all_attentions = all_attentions + (outputs[1],)
394
+
395
+ hidden_states = hidden_states.view(*output_shape)
396
+ # Add last layer
397
+ if output_hidden_states:
398
+ all_hidden_states = all_hidden_states + (hidden_states,)
399
+
400
+ if not return_dict:
401
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
402
+
403
+ return BaseModelOutput(
404
+ last_hidden_state=hidden_states,
405
+ hidden_states=all_hidden_states,
406
+ attentions=all_attentions,
407
+ )
408
+
409
+
410
+ @auto_docstring(
411
+ custom_intro="""
412
+ OpenAI GPT Model transformer with a language modeling head on top (linear layer with weights tied to the input
413
+ embeddings).
414
+ """
415
+ )
416
+ class OpenAIGPTLMHeadModel(OpenAIGPTPreTrainedModel, GenerationMixin):
417
+ _tied_weights_keys = {"lm_head.weight": "transformer.tokens_embed.weight"}
418
+
419
+ def __init__(self, config):
420
+ super().__init__(config)
421
+ self.transformer = OpenAIGPTModel(config)
422
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
423
+
424
+ # Initialize weights and apply final processing
425
+ self.post_init()
426
+
427
+ @auto_docstring
428
+ def forward(
429
+ self,
430
+ input_ids: torch.LongTensor | None = None,
431
+ attention_mask: torch.FloatTensor | None = None,
432
+ token_type_ids: torch.LongTensor | None = None,
433
+ position_ids: torch.LongTensor | None = None,
434
+ inputs_embeds: torch.FloatTensor | None = None,
435
+ labels: torch.LongTensor | None = None,
436
+ output_attentions: bool | None = None,
437
+ output_hidden_states: bool | None = None,
438
+ return_dict: bool | None = None,
439
+ logits_to_keep: int | torch.Tensor = 0,
440
+ **kwargs,
441
+ ) -> tuple[torch.Tensor] | CausalLMOutput:
442
+ r"""
443
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
444
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
445
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
446
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
447
+ """
448
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
449
+
450
+ transformer_outputs = self.transformer(
451
+ input_ids,
452
+ attention_mask=attention_mask,
453
+ token_type_ids=token_type_ids,
454
+ position_ids=position_ids,
455
+ inputs_embeds=inputs_embeds,
456
+ output_attentions=output_attentions,
457
+ output_hidden_states=output_hidden_states,
458
+ return_dict=return_dict,
459
+ )
460
+
461
+ hidden_states = transformer_outputs[0]
462
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
463
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
464
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
465
+
466
+ loss = None
467
+ if labels is not None:
468
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
469
+
470
+ if not return_dict:
471
+ output = (logits,) + transformer_outputs[1:]
472
+ return ((loss,) + output) if loss is not None else output
473
+
474
+ return CausalLMOutput(
475
+ loss=loss,
476
+ logits=logits,
477
+ hidden_states=transformer_outputs.hidden_states,
478
+ attentions=transformer_outputs.attentions,
479
+ )
480
+
481
+ def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs) -> dict[str, Any]:
482
+ # Overwritten -- old model with reduced inputs
483
+ model_inputs = {"input_ids": input_ids}
484
+
485
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
486
+ for key, value in kwargs.items():
487
+ if key not in model_inputs:
488
+ model_inputs[key] = value
489
+
490
+ return model_inputs
491
+
492
+
493
+ @auto_docstring(
494
+ custom_intro="""
495
+ OpenAI GPT Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
496
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
497
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
498
+ input sequence).
499
+ """
500
+ )
501
+ class OpenAIGPTDoubleHeadsModel(OpenAIGPTPreTrainedModel):
502
+ _tied_weights_keys = {"transformer.tokens_embed.weight": "lm_head.weight"}
503
+
504
+ def __init__(self, config):
505
+ super().__init__(config)
506
+
507
+ config.num_labels = 1
508
+ self.transformer = OpenAIGPTModel(config)
509
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
510
+ self.multiple_choice_head = OpenAIGPTSequenceSummary(config)
511
+
512
+ # Initialize weights and apply final processing
513
+ self.post_init()
514
+
515
+ @auto_docstring
516
+ def forward(
517
+ self,
518
+ input_ids: torch.LongTensor | None = None,
519
+ attention_mask: torch.FloatTensor | None = None,
520
+ token_type_ids: torch.LongTensor | None = None,
521
+ position_ids: torch.LongTensor | None = None,
522
+ inputs_embeds: torch.FloatTensor | None = None,
523
+ mc_token_ids: torch.LongTensor | None = None,
524
+ labels: torch.LongTensor | None = None,
525
+ mc_labels: torch.LongTensor | None = None,
526
+ output_attentions: bool | None = None,
527
+ output_hidden_states: bool | None = None,
528
+ return_dict: bool | None = None,
529
+ **kwargs,
530
+ ) -> tuple[torch.Tensor] | OpenAIGPTDoubleHeadsModelOutput:
531
+ r"""
532
+ mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
533
+ Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
534
+ 1]`.
535
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
536
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
537
+ `labels = input_ids` Indices are selected in `[-1, 0, ..., config.vocab_size]` All labels set to `-100` are
538
+ ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
539
+ mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
540
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
541
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
542
+
543
+ Examples:
544
+
545
+ ```python
546
+ >>> from transformers import AutoTokenizer, OpenAIGPTDoubleHeadsModel
547
+ >>> import torch
548
+
549
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/openai-gpt")
550
+ >>> model = OpenAIGPTDoubleHeadsModel.from_pretrained("openai-community/openai-gpt")
551
+ >>> tokenizer.add_special_tokens(
552
+ ... {"cls_token": "[CLS]"}
553
+ ... ) # Add a [CLS] to the vocabulary (we should train it also!)
554
+ >>> model.resize_token_embeddings(len(tokenizer))
555
+
556
+ >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
557
+ >>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices
558
+ >>> mc_token_ids = torch.tensor([input_ids.size(-1) - 1, input_ids.size(-1) - 1]).unsqueeze(0) # Batch size 1
559
+
560
+ >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
561
+ >>> lm_logits = outputs.logits
562
+ >>> mc_logits = outputs.mc_logits
563
+ ```"""
564
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
565
+
566
+ transformer_outputs = self.transformer(
567
+ input_ids,
568
+ attention_mask=attention_mask,
569
+ token_type_ids=token_type_ids,
570
+ position_ids=position_ids,
571
+ inputs_embeds=inputs_embeds,
572
+ output_attentions=output_attentions,
573
+ output_hidden_states=output_hidden_states,
574
+ return_dict=return_dict,
575
+ )
576
+ hidden_states = transformer_outputs[0]
577
+
578
+ lm_logits = self.lm_head(hidden_states)
579
+ mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
580
+
581
+ lm_loss, mc_loss = None, None
582
+ if mc_labels is not None:
583
+ loss_fct = CrossEntropyLoss()
584
+ mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
585
+ if labels is not None:
586
+ shift_logits = lm_logits[..., :-1, :].contiguous()
587
+ shift_labels = labels[..., 1:].contiguous()
588
+ loss_fct = CrossEntropyLoss()
589
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
590
+
591
+ if not return_dict:
592
+ output = (lm_logits, mc_logits) + transformer_outputs[1:]
593
+ if mc_loss is not None:
594
+ output = (mc_loss,) + output
595
+ return ((lm_loss,) + output) if lm_loss is not None else output
596
+
597
+ return OpenAIGPTDoubleHeadsModelOutput(
598
+ loss=lm_loss,
599
+ mc_loss=mc_loss,
600
+ logits=lm_logits,
601
+ mc_logits=mc_logits,
602
+ hidden_states=transformer_outputs.hidden_states,
603
+ attentions=transformer_outputs.attentions,
604
+ )
605
+
606
+
607
+ @auto_docstring(
608
+ custom_intro="""
609
+ The Original OpenAI GPT Model transformer with a sequence classification head on top (linear layer).
610
+ [`OpenAIGPTForSequenceClassification`] uses the last token in order to do the classification, as other causal
611
+ models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the
612
+ last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding
613
+ token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since
614
+ it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take
615
+ the last value in each row of the batch).
616
+ """
617
+ )
618
+ class OpenAIGPTForSequenceClassification(OpenAIGPTPreTrainedModel):
619
+ def __init__(self, config):
620
+ super().__init__(config)
621
+ self.num_labels = config.num_labels
622
+ self.transformer = OpenAIGPTModel(config)
623
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
624
+
625
+ # Initialize weights and apply final processing
626
+ self.post_init()
627
+
628
+ @auto_docstring
629
+ def forward(
630
+ self,
631
+ input_ids: torch.LongTensor | None = None,
632
+ attention_mask: torch.FloatTensor | None = None,
633
+ token_type_ids: torch.LongTensor | None = None,
634
+ position_ids: torch.LongTensor | None = None,
635
+ inputs_embeds: torch.FloatTensor | None = None,
636
+ labels: torch.LongTensor | None = None,
637
+ output_attentions: bool | None = None,
638
+ output_hidden_states: bool | None = None,
639
+ return_dict: bool | None = None,
640
+ **kwargs,
641
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
642
+ r"""
643
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
644
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
645
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
646
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
647
+ """
648
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
649
+
650
+ transformer_outputs = self.transformer(
651
+ input_ids,
652
+ attention_mask=attention_mask,
653
+ token_type_ids=token_type_ids,
654
+ position_ids=position_ids,
655
+ inputs_embeds=inputs_embeds,
656
+ output_attentions=output_attentions,
657
+ output_hidden_states=output_hidden_states,
658
+ return_dict=return_dict,
659
+ )
660
+
661
+ hidden_states = transformer_outputs[0]
662
+ logits = self.score(hidden_states)
663
+
664
+ if input_ids is not None:
665
+ batch_size, sequence_length = input_ids.shape[:2]
666
+ else:
667
+ batch_size, sequence_length = inputs_embeds.shape[:2]
668
+
669
+ # Ensure the batch size is > 1 if there is no padding.
670
+ if self.config.pad_token_id is None and batch_size != 1:
671
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
672
+ if self.config.pad_token_id is None:
673
+ last_non_pad_token = -1
674
+ elif input_ids is not None:
675
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
676
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
677
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
678
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
679
+ else:
680
+ last_non_pad_token = -1
681
+ logger.warning_once(
682
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
683
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
684
+ )
685
+
686
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
687
+
688
+ loss = None
689
+ if labels is not None:
690
+ if self.config.problem_type is None:
691
+ if self.num_labels == 1:
692
+ self.config.problem_type = "regression"
693
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
694
+ self.config.problem_type = "single_label_classification"
695
+ else:
696
+ self.config.problem_type = "multi_label_classification"
697
+
698
+ if self.config.problem_type == "regression":
699
+ loss_fct = MSELoss()
700
+ if self.num_labels == 1:
701
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
702
+ else:
703
+ loss = loss_fct(pooled_logits, labels)
704
+ elif self.config.problem_type == "single_label_classification":
705
+ loss_fct = CrossEntropyLoss()
706
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
707
+ elif self.config.problem_type == "multi_label_classification":
708
+ loss_fct = BCEWithLogitsLoss()
709
+ loss = loss_fct(pooled_logits, labels)
710
+ if not return_dict:
711
+ output = (pooled_logits,) + transformer_outputs[1:]
712
+ return ((loss,) + output) if loss is not None else output
713
+
714
+ return SequenceClassifierOutput(
715
+ loss=loss,
716
+ logits=pooled_logits,
717
+ hidden_states=transformer_outputs.hidden_states,
718
+ attentions=transformer_outputs.attentions,
719
+ )
720
+
721
+
722
+ __all__ = [
723
+ "OpenAIGPTDoubleHeadsModel",
724
+ "OpenAIGPTForSequenceClassification",
725
+ "OpenAIGPTLMHeadModel",
726
+ "OpenAIGPTModel",
727
+ "OpenAIGPTPreTrainedModel",
728
+ ]
lib/python3.11/site-packages/transformers/models/openai/tokenization_openai.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes for OpenAI GPT."""
15
+
16
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers
17
+ from tokenizers.models import BPE
18
+
19
+ from ...tokenization_utils_tokenizers import TokenizersBackend
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
26
+
27
+
28
+ class OpenAIGPTTokenizer(TokenizersBackend):
29
+ """
30
+ Construct a GPT Tokenizer (backed by HuggingFace's *tokenizers* library). Based on Byte-Pair-Encoding with
31
+ the following peculiarities:
32
+
33
+ - lower case all inputs
34
+ - uses BERT's BasicTokenizer for pre-BPE tokenization
35
+
36
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
37
+ refer to this superclass for more information regarding those methods.
38
+
39
+ Args:
40
+ vocab_file (`str`, *optional*):
41
+ Path to the vocabulary file.
42
+ merges_file (`str`, *optional*):
43
+ Path to the merges file.
44
+ tokenizer_file (`str`, *optional*):
45
+ Path to a tokenizers JSON file containing the serialization of a tokenizer.
46
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
47
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
48
+ token instead.
49
+ vocab (`str` or `dict[str, int]`, *optional*):
50
+ Custom vocabulary dictionary. If not provided, a blank vocabulary is initialized.
51
+ merges (`str` or `list[str]`, *optional*):
52
+ Custom merges list. If not provided, an empty list is used.
53
+ """
54
+
55
+ vocab_files_names = VOCAB_FILES_NAMES
56
+ model_input_names = ["input_ids", "attention_mask"]
57
+ model = BPE
58
+
59
+ def __init__(
60
+ self,
61
+ vocab: str | dict[str, int] | None = None,
62
+ merges: str | list[str] | None = None,
63
+ unk_token: str = "<unk>",
64
+ **kwargs,
65
+ ):
66
+ self._vocab = vocab if vocab is not None else {str(unk_token): 0}
67
+ self._merges = merges or []
68
+
69
+ self._tokenizer = Tokenizer(
70
+ BPE(
71
+ vocab=self._vocab,
72
+ merges=self._merges,
73
+ dropout=None,
74
+ continuing_subword_prefix="",
75
+ end_of_word_suffix="</w>",
76
+ fuse_unk=False,
77
+ unk_token=str(unk_token),
78
+ )
79
+ )
80
+
81
+ # Set normalizer and pre-tokenizer to mimic OpenAI GPT behavior
82
+ # OpenAI GPT uses BERT BasicTokenizer with lower_case=True
83
+ self._tokenizer.normalizer = normalizers.BertNormalizer(lowercase=True)
84
+
85
+ self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
86
+ self._tokenizer.decoder = decoders.BPEDecoder(suffix="</w>")
87
+
88
+ super().__init__(
89
+ unk_token=unk_token,
90
+ **kwargs,
91
+ )
92
+
93
+ @property
94
+ def do_lower_case(self):
95
+ return True
96
+
97
+
98
+ __all__ = ["OpenAIGPTTokenizer"]
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ 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_openai_privacy_filter import *
22
+ from .modeling_openai_privacy_filter import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (823 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/configuration_openai_privacy_filter.cpython-311.pyc ADDED
Binary file (5.1 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/modeling_openai_privacy_filter.cpython-311.pyc ADDED
Binary file (32.4 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/__pycache__/modular_openai_privacy_filter.cpython-311.pyc ADDED
Binary file (22.3 kB). View file
 
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/configuration_openai_privacy_filter.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/openai_privacy_filter/modular_openai_privacy_filter.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_openai_privacy_filter.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from huggingface_hub.dataclasses import strict
21
+
22
+ from ...configuration_utils import PreTrainedConfig
23
+ from ...utils import auto_docstring
24
+
25
+
26
+ OPENAI_PRIVACY_FILTER_SPAN_LABELS = (
27
+ "O",
28
+ "account_number",
29
+ "private_address",
30
+ "private_date",
31
+ "private_email",
32
+ "private_person",
33
+ "private_phone",
34
+ "private_url",
35
+ "secret",
36
+ )
37
+
38
+ OPENAI_PRIVACY_FILTER_NER_LABELS = ("O",) + tuple(
39
+ f"{prefix}-{label}"
40
+ for label in OPENAI_PRIVACY_FILTER_SPAN_LABELS
41
+ if label != "O"
42
+ for prefix in ("B", "I", "E", "S")
43
+ )
44
+
45
+
46
+ @auto_docstring(checkpoint="openai/privacy-filter")
47
+ @strict
48
+ class OpenAIPrivacyFilterConfig(PreTrainedConfig):
49
+ model_type = "openai_privacy_filter"
50
+ attribute_map = {
51
+ "num_experts": "num_local_experts",
52
+ }
53
+ default_theta = 150000.0
54
+ base_model_pp_plan = {
55
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
56
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
57
+ "norm": (["hidden_states"], ["hidden_states"]),
58
+ }
59
+ base_model_ep_plan = {
60
+ "layers.*.mlp.router": "ep_router",
61
+ "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",
62
+ "layers.*.mlp.experts.gate_up_proj_bias": "grouped_gemm",
63
+ "layers.*.mlp.experts.down_proj": "grouped_gemm",
64
+ "layers.*.mlp.experts.down_proj_bias": "grouped_gemm",
65
+ "layers.*.mlp.experts": "moe_tp_experts",
66
+ }
67
+ num_hidden_layers: int = 8
68
+ num_local_experts: int = 128
69
+ vocab_size: int = 200064
70
+ hidden_size: int = 640
71
+ intermediate_size: int = 640
72
+ head_dim: int = 64
73
+ num_attention_heads: int = 14
74
+ num_key_value_heads: int = 2
75
+ sliding_window: int = 128
76
+ tie_word_embeddings: bool = False
77
+ initializer_range: float = 0.02
78
+ max_position_embeddings: int = 131072
79
+ rms_norm_eps: float = 1e-5
80
+ rope_parameters: dict | None = None
81
+ attention_dropout: float | int = 0.0
82
+ num_experts_per_tok: int = 4
83
+ router_aux_loss_coef: float = 0.001
84
+ output_router_logits: bool = False
85
+ use_cache: bool = True
86
+ pad_token_id: int | None = 199999
87
+ bos_token_id: int | None = None
88
+ eos_token_id: int | list[int] | None = 199999
89
+ attention_bias: bool = True
90
+ classifier_dropout: float = 0.0
91
+
92
+ def __post_init__(self, **kwargs):
93
+ if self.num_key_value_heads is None:
94
+ self.num_key_value_heads = self.num_attention_heads
95
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
96
+
97
+ if self.rope_parameters is None:
98
+ self.rope_parameters = {
99
+ "rope_type": "yarn",
100
+ "factor": 32.0,
101
+ "beta_fast": 32.0,
102
+ "beta_slow": 1.0,
103
+ "truncate": False,
104
+ "original_max_position_embeddings": 4096,
105
+ }
106
+
107
+ requested_num_labels = kwargs.pop("num_labels", len(OPENAI_PRIVACY_FILTER_NER_LABELS))
108
+ if self.id2label is None and requested_num_labels == len(OPENAI_PRIVACY_FILTER_NER_LABELS):
109
+ self.id2label = dict(enumerate(OPENAI_PRIVACY_FILTER_NER_LABELS))
110
+ elif self.id2label is None:
111
+ self.num_labels = requested_num_labels
112
+ if self.label2id is None and self.id2label is not None:
113
+ self.label2id = {label: idx for idx, label in self.id2label.items()}
114
+
115
+ super().__post_init__(**kwargs)
116
+
117
+
118
+ __all__ = ["OpenAIPrivacyFilterConfig"]
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/modeling_openai_privacy_filter.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/openai_privacy_filter/modular_openai_privacy_filter.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_openai_privacy_filter.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+ from typing import Optional
23
+
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import functional as F
27
+
28
+ from ... import initialization as init
29
+ from ...integrations import (
30
+ use_experts_implementation,
31
+ use_kernel_forward_from_hub,
32
+ use_kernel_func_from_hub,
33
+ use_kernelized_func,
34
+ )
35
+ from ...masking_utils import create_bidirectional_sliding_window_mask
36
+ from ...modeling_layers import GenericForTokenClassification, GradientCheckpointingLayer
37
+ from ...modeling_outputs import BaseModelOutput
38
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
39
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from ...processing_utils import Unpack
41
+ from ...utils import TransformersKwargs, auto_docstring
42
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
43
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
44
+ from .configuration_openai_privacy_filter import OpenAIPrivacyFilterConfig
45
+
46
+
47
+ @use_kernel_forward_from_hub("RMSNorm")
48
+ class OpenAIPrivacyFilterRMSNorm(nn.Module):
49
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
50
+ """
51
+ OpenAIPrivacyFilterRMSNorm is equivalent to T5LayerNorm
52
+ """
53
+ super().__init__()
54
+ self.weight = nn.Parameter(torch.ones(hidden_size))
55
+ self.variance_epsilon = eps
56
+
57
+ def forward(self, hidden_states) -> torch.Tensor:
58
+ input_dtype = hidden_states.dtype
59
+ hidden_states = hidden_states.to(torch.float32)
60
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
61
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
62
+ return (self.weight * hidden_states).to(input_dtype) # main diff with Llama
63
+
64
+ def extra_repr(self):
65
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
66
+
67
+
68
+ class OpenAIPrivacyFilterRotaryEmbedding(nn.Module):
69
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
70
+
71
+ def __init__(self, config: OpenAIPrivacyFilterConfig, device=None):
72
+ super().__init__()
73
+ self.max_seq_len_cached = config.max_position_embeddings
74
+ self.original_max_seq_len = config.max_position_embeddings
75
+
76
+ self.config = config
77
+
78
+ self.rope_type = self.config.rope_parameters["rope_type"]
79
+ rope_init_fn: Callable = self.compute_default_rope_parameters
80
+ if self.rope_type != "default":
81
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
82
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
83
+
84
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
85
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
86
+
87
+ @staticmethod
88
+ def compute_default_rope_parameters(
89
+ config: OpenAIPrivacyFilterConfig | None = None,
90
+ device: Optional["torch.device"] = None,
91
+ seq_len: int | None = None,
92
+ ) -> tuple["torch.Tensor", float]:
93
+ """
94
+ Computes the inverse frequencies according to the original RoPE implementation
95
+ Args:
96
+ config ([`~transformers.PreTrainedConfig`]):
97
+ The model configuration.
98
+ device (`torch.device`):
99
+ The device to use for initialization of the inverse frequencies.
100
+ seq_len (`int`, *optional*):
101
+ The current sequence length. Unused for this type of RoPE.
102
+ Returns:
103
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
104
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
105
+ """
106
+ base = config.rope_parameters["rope_theta"]
107
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
108
+
109
+ attention_factor = 1.0 # Unused in this type of RoPE
110
+
111
+ # Compute the inverse frequencies
112
+ inv_freq = 1.0 / (
113
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
114
+ )
115
+ return inv_freq, attention_factor
116
+
117
+ @torch.no_grad()
118
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
119
+ def forward(self, x, position_ids):
120
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
121
+ position_ids_expanded = position_ids[:, None, :].float()
122
+
123
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
124
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
125
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
126
+ emb = freqs
127
+ cos = emb.cos() * self.attention_scaling
128
+ sin = emb.sin() * self.attention_scaling
129
+
130
+ return cos.to(x.dtype), sin.to(x.dtype)
131
+
132
+
133
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
134
+ """
135
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
136
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
137
+ """
138
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
139
+ if n_rep == 1:
140
+ return hidden_states
141
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
142
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
143
+
144
+
145
+ @use_kernel_func_from_hub("rotary_pos_emb")
146
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
147
+ cos = cos.unsqueeze(unsqueeze_dim)
148
+ sin = sin.unsqueeze(unsqueeze_dim)
149
+ q_embed = _apply_rotary_emb(q, cos, sin)
150
+ k_embed = _apply_rotary_emb(k, cos, sin)
151
+ return q_embed, k_embed
152
+
153
+
154
+ def _apply_rotary_emb(
155
+ x: torch.Tensor,
156
+ cos: torch.Tensor,
157
+ sin: torch.Tensor,
158
+ ) -> torch.Tensor:
159
+ # Interleaving layout instead of concatenated
160
+ first_half, second_half = x[..., ::2], x[..., 1::2]
161
+ first_ = first_half * cos - second_half * sin
162
+ second_ = second_half * cos + first_half * sin
163
+ return torch.stack((first_, second_), dim=-1).flatten(-2)
164
+
165
+
166
+ def eager_attention_forward(
167
+ module: nn.Module,
168
+ query: torch.Tensor,
169
+ key: torch.Tensor,
170
+ value: torch.Tensor,
171
+ attention_mask: torch.Tensor | None,
172
+ scaling: float,
173
+ dropout: float | int = 0.0,
174
+ **kwargs,
175
+ ):
176
+ key_states = repeat_kv(key, module.num_key_value_groups)
177
+ value_states = repeat_kv(value, module.num_key_value_groups)
178
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
179
+ if attention_mask is not None:
180
+ attn_weights = attn_weights + attention_mask
181
+
182
+ sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
183
+ combined_logits = torch.cat([attn_weights, sinks], dim=-1)
184
+
185
+ # This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
186
+ # when training with bsz>1 we clamp max values.
187
+
188
+ combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
189
+ probs = nn.functional.softmax(combined_logits, dim=-1, dtype=torch.float32) # Softmax in fp32
190
+ scores = probs[..., :-1] # we drop the sink here
191
+ attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training).to(value_states.dtype)
192
+ attn_output = torch.matmul(attn_weights, value_states)
193
+ attn_output = attn_output.transpose(1, 2).contiguous()
194
+ return attn_output, attn_weights
195
+
196
+
197
+ @use_kernelized_func(apply_rotary_pos_emb)
198
+ class OpenAIPrivacyFilterAttention(nn.Module):
199
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
200
+
201
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
202
+ super().__init__()
203
+ self.config = config
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = config.head_dim**-0.25
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = False
209
+ self.q_proj = nn.Linear(
210
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
211
+ )
212
+ self.k_proj = nn.Linear(
213
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
214
+ )
215
+ self.v_proj = nn.Linear(
216
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
217
+ )
218
+ self.o_proj = nn.Linear(
219
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
220
+ )
221
+ self.sliding_window = config.sliding_window + 1 # Account for FA symmetry using -1
222
+ self.sinks = nn.Parameter(torch.empty(config.num_attention_heads))
223
+
224
+ def forward(
225
+ self,
226
+ hidden_states: torch.Tensor,
227
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
228
+ attention_mask: torch.Tensor | None = None,
229
+ **kwargs: Unpack[TransformersKwargs],
230
+ ) -> tuple[torch.Tensor, None]:
231
+ input_shape = hidden_states.shape[:-1]
232
+ hidden_shape = (*input_shape, -1, self.head_dim)
233
+
234
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
235
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
236
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
237
+
238
+ cos, sin = position_embeddings
239
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
240
+
241
+ # Unique: applying scale individually to each Q and K
242
+ query_states = query_states * self.scaling
243
+ key_states = key_states * self.scaling
244
+
245
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
246
+ self.config._attn_implementation, eager_attention_forward
247
+ )
248
+
249
+ attn_output, attn_weights = attention_interface(
250
+ self,
251
+ query_states,
252
+ key_states,
253
+ value_states,
254
+ attention_mask,
255
+ dropout=0.0 if not self.training else self.attention_dropout,
256
+ scaling=1.0, # scaling applied before
257
+ sliding_window=self.sliding_window,
258
+ s_aux=self.sinks,
259
+ **kwargs,
260
+ )
261
+
262
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
263
+ attn_output = self.o_proj(attn_output)
264
+ return attn_output, attn_weights
265
+
266
+
267
+ @use_experts_implementation(is_transposed=True, has_bias=True)
268
+ class OpenAIPrivacyFilterExperts(nn.Module):
269
+ def __init__(self, config):
270
+ super().__init__()
271
+ self.intermediate_size = config.intermediate_size
272
+ self.num_experts = config.num_local_experts
273
+ self.hidden_size = config.hidden_size
274
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.intermediate_size))
275
+ self.gate_up_proj_bias = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_size))
276
+ self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.intermediate_size, self.hidden_size)))
277
+ self.down_proj_bias = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
278
+ self.alpha = 1.702
279
+ self.limit = 7.0
280
+
281
+ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
282
+ # Concatenated layout instead of interleaving
283
+ gate, up = gate_up.chunk(2, dim=-1)
284
+ gate = gate.clamp(min=None, max=self.limit)
285
+ up = up.clamp(min=-self.limit, max=self.limit)
286
+ glu = gate * torch.sigmoid(gate * self.alpha)
287
+ gated_output = (up + 1) * glu
288
+ return gated_output
289
+
290
+ def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor:
291
+ original_dtype = hidden_states.dtype
292
+
293
+ # Accumulate over fp32
294
+ next_states = torch.zeros_like(hidden_states, dtype=torch.float32, device=hidden_states.device)
295
+ with torch.no_grad():
296
+ expert_mask = torch.nn.functional.one_hot(
297
+ router_indices, num_classes=self.num_experts
298
+ ) # masking is also a class
299
+ expert_mask = expert_mask.permute(2, 1, 0)
300
+ # we sum on the top_k and on the sequence length to get which experts
301
+ # are hit this time around
302
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
303
+
304
+ # Key change to original gpt oss is to stay in fp32 precision for all linear projections / muls
305
+ for expert_idx in expert_hit:
306
+ # expert_idx only have 1 element, so we can use scale for fast indexing
307
+ expert_idx = expert_idx[0]
308
+ # skip masking index
309
+ if expert_idx == self.num_experts:
310
+ continue
311
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
312
+ current_state = hidden_states[token_idx]
313
+ gate_up = (
314
+ current_state.float() @ self.gate_up_proj[expert_idx].float()
315
+ + self.gate_up_proj_bias[expert_idx].float()
316
+ )
317
+ gated_output = self._apply_gate(gate_up).float()
318
+ out = gated_output.float() @ self.down_proj[expert_idx].float() + self.down_proj_bias[expert_idx].float()
319
+ weighted_output = out * routing_weights[token_idx, top_k_pos, None].float()
320
+ next_states.index_add_(0, token_idx, weighted_output)
321
+
322
+ return next_states.to(original_dtype)
323
+
324
+
325
+ class OpenAIPrivacyFilterTopKRouter(nn.Module):
326
+ def __init__(self, config):
327
+ super().__init__()
328
+ self.top_k = config.num_experts_per_tok
329
+ self.num_experts = config.num_local_experts
330
+ self.hidden_dim = config.hidden_size
331
+ self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim))
332
+ self.bias = nn.Parameter(torch.zeros(self.num_experts))
333
+
334
+ def forward(self, hidden_states):
335
+ # Force fp32
336
+ router_logits = F.linear(
337
+ hidden_states.float(), self.weight.float(), self.bias.float()
338
+ ) # (num_tokens, num_experts)
339
+ router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (num_tokens, top_k)
340
+ router_scores = torch.nn.functional.softmax(router_top_value, dim=1, dtype=router_top_value.dtype)
341
+ # Additional scaling
342
+ router_scores = router_scores / self.top_k
343
+ return router_logits, router_scores, router_indices
344
+
345
+
346
+ class OpenAIPrivacyFilterMLP(nn.Module):
347
+ """Similar to GPT Oss but with FP32 focus + added experts scaling"""
348
+
349
+ def __init__(self, config):
350
+ super().__init__()
351
+ self.router = OpenAIPrivacyFilterTopKRouter(config)
352
+ self.num_experts = config.num_experts_per_tok
353
+ self.experts = OpenAIPrivacyFilterExperts(config)
354
+
355
+ def forward(self, hidden_states):
356
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
357
+ hidden_states = hidden_states.reshape(-1, hidden_dim)
358
+ _, router_scores, router_indices = self.router(hidden_states)
359
+ hidden_states = self.experts(hidden_states, router_indices, router_scores)
360
+ # Additional scaling
361
+ hidden_states = hidden_states * self.num_experts
362
+ hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
363
+ return hidden_states, router_scores
364
+
365
+
366
+ class OpenAIPrivacyFilterEncoderLayer(GradientCheckpointingLayer):
367
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
368
+ super().__init__()
369
+ self.hidden_size = config.hidden_size
370
+ self.self_attn = OpenAIPrivacyFilterAttention(config)
371
+ self.mlp = OpenAIPrivacyFilterMLP(config)
372
+ self.input_layernorm = OpenAIPrivacyFilterRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
373
+ self.post_attention_layernorm = OpenAIPrivacyFilterRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
374
+
375
+ def forward(
376
+ self,
377
+ hidden_states: torch.Tensor,
378
+ attention_mask: torch.Tensor | None = None,
379
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
380
+ **kwargs: Unpack[TransformersKwargs],
381
+ ) -> torch.Tensor:
382
+ residual = hidden_states
383
+ hidden_states = self.input_layernorm(hidden_states)
384
+ # Self Attention
385
+ hidden_states, _ = self.self_attn(
386
+ hidden_states=hidden_states,
387
+ position_embeddings=position_embeddings,
388
+ attention_mask=attention_mask,
389
+ **kwargs,
390
+ )
391
+ hidden_states = residual + hidden_states
392
+
393
+ # Fully Connected
394
+ residual = hidden_states
395
+ hidden_states = self.post_attention_layernorm(hidden_states)
396
+ hidden_states, _ = self.mlp(hidden_states)
397
+ hidden_states = residual + hidden_states
398
+
399
+ return hidden_states
400
+
401
+
402
+ @auto_docstring
403
+ class OpenAIPrivacyFilterPreTrainedModel(PreTrainedModel):
404
+ config: OpenAIPrivacyFilterConfig
405
+ base_model_prefix = "model"
406
+ supports_gradient_checkpointing = True
407
+ _no_split_modules = ["OpenAIPrivacyFilterEncoderLayer"]
408
+ _skip_keys_device_placement = None # No cache
409
+ _supports_flash_attn = True
410
+ _supports_sdpa = False
411
+ _supports_flex_attn = True
412
+
413
+ _can_compile_fullgraph = True
414
+ _supports_attention_backend = True
415
+
416
+ _can_record_outputs = {
417
+ "router_logits": OutputRecorder(OpenAIPrivacyFilterTopKRouter, index=0),
418
+ "hidden_states": OpenAIPrivacyFilterEncoderLayer,
419
+ "attentions": OpenAIPrivacyFilterAttention,
420
+ }
421
+ _keep_in_fp32_modules = []
422
+ _compatible_flash_implementations = ["kernels-community/vllm-flash-attn3", "flash_attention_4"]
423
+ _keep_in_fp32_modules_strict = ["sinks"]
424
+
425
+ @torch.no_grad()
426
+ def _init_weights(self, module):
427
+ super()._init_weights(module)
428
+ std = self.config.initializer_range
429
+ if isinstance(module, OpenAIPrivacyFilterExperts):
430
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
431
+ init.zeros_(module.gate_up_proj_bias)
432
+ init.normal_(module.down_proj, mean=0.0, std=std)
433
+ init.zeros_(module.down_proj_bias)
434
+ elif isinstance(module, OpenAIPrivacyFilterAttention):
435
+ init.normal_(module.sinks, mean=0.0, std=std)
436
+ elif isinstance(module, OpenAIPrivacyFilterTopKRouter):
437
+ init.normal_(module.weight, mean=0.0, std=std)
438
+ init.normal_(module.bias, mean=0.0, std=std)
439
+
440
+ def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
441
+ """The model is very sensitive to accumulation orders, hence we default to `eager` instead"""
442
+ requested_experts = "eager" if requested_experts is None else requested_experts
443
+ return super().get_correct_experts_implementation(requested_experts)
444
+
445
+
446
+ @auto_docstring
447
+ class OpenAIPrivacyFilterModel(OpenAIPrivacyFilterPreTrainedModel):
448
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
449
+ super().__init__(config)
450
+ self.padding_idx = config.pad_token_id
451
+ self.vocab_size = config.vocab_size
452
+
453
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
454
+ self.layers = nn.ModuleList([OpenAIPrivacyFilterEncoderLayer(config) for _ in range(config.num_hidden_layers)])
455
+ self.norm = OpenAIPrivacyFilterRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
456
+ self.rotary_emb = OpenAIPrivacyFilterRotaryEmbedding(config=config)
457
+ self.gradient_checkpointing = False
458
+
459
+ # Initialize weights and apply final processing
460
+ self.post_init()
461
+
462
+ @merge_with_config_defaults
463
+ @capture_outputs
464
+ @auto_docstring
465
+ def forward(
466
+ self,
467
+ input_ids: torch.LongTensor | None = None,
468
+ attention_mask: torch.Tensor | None = None,
469
+ position_ids: torch.LongTensor | None = None,
470
+ inputs_embeds: torch.FloatTensor | None = None,
471
+ **kwargs: Unpack[TransformersKwargs],
472
+ ) -> BaseModelOutput:
473
+ if (input_ids is None) ^ (inputs_embeds is not None):
474
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
475
+
476
+ if inputs_embeds is None:
477
+ inputs_embeds = self.embed_tokens(input_ids)
478
+ hidden_states = inputs_embeds
479
+
480
+ if position_ids is None:
481
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
482
+ position_ids = position_ids.unsqueeze(0)
483
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
484
+
485
+ attention_mask = create_bidirectional_sliding_window_mask(
486
+ config=self.config,
487
+ inputs_embeds=hidden_states,
488
+ attention_mask=attention_mask,
489
+ )
490
+
491
+ for encoder_layer in self.layers:
492
+ hidden_states = encoder_layer(
493
+ hidden_states,
494
+ position_embeddings=position_embeddings,
495
+ attention_mask=attention_mask,
496
+ position_ids=position_ids,
497
+ **kwargs,
498
+ )
499
+
500
+ hidden_states = self.norm(hidden_states)
501
+
502
+ return BaseModelOutput(last_hidden_state=hidden_states)
503
+
504
+
505
+ class OpenAIPrivacyFilterForTokenClassification(GenericForTokenClassification, OpenAIPrivacyFilterPreTrainedModel): ...
506
+
507
+
508
+ __all__ = [
509
+ "OpenAIPrivacyFilterForTokenClassification",
510
+ "OpenAIPrivacyFilterModel",
511
+ "OpenAIPrivacyFilterPreTrainedModel",
512
+ ]
lib/python3.11/site-packages/transformers/models/openai_privacy_filter/modular_openai_privacy_filter.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch Privacy Filter model."""
15
+
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ from huggingface_hub.dataclasses import strict
20
+ from torch import nn
21
+ from torch.nn import functional as F
22
+
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...integrations import use_experts_implementation
25
+ from ...masking_utils import create_bidirectional_sliding_window_mask
26
+ from ...modeling_layers import GenericForTokenClassification
27
+ from ...modeling_outputs import BaseModelOutput
28
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
29
+ from ...processing_utils import Unpack
30
+ from ...utils import TransformersKwargs, auto_docstring, logging
31
+ from ...utils.generic import merge_with_config_defaults
32
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
33
+ from ..gpt_oss.configuration_gpt_oss import GptOssConfig
34
+ from ..gpt_oss.modeling_gpt_oss import (
35
+ GptOssAttention,
36
+ GptOssDecoderLayer,
37
+ GptOssExperts,
38
+ GptOssModel,
39
+ GptOssPreTrainedModel,
40
+ GptOssRMSNorm,
41
+ GptOssRotaryEmbedding,
42
+ GptOssTopKRouter,
43
+ apply_rotary_pos_emb,
44
+ repeat_kv,
45
+ )
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ OPENAI_PRIVACY_FILTER_SPAN_LABELS = (
52
+ "O",
53
+ "account_number",
54
+ "private_address",
55
+ "private_date",
56
+ "private_email",
57
+ "private_person",
58
+ "private_phone",
59
+ "private_url",
60
+ "secret",
61
+ )
62
+
63
+ OPENAI_PRIVACY_FILTER_NER_LABELS = ("O",) + tuple(
64
+ f"{prefix}-{label}"
65
+ for label in OPENAI_PRIVACY_FILTER_SPAN_LABELS
66
+ if label != "O"
67
+ for prefix in ("B", "I", "E", "S")
68
+ )
69
+
70
+
71
+ @auto_docstring(checkpoint="openai/privacy-filter")
72
+ @strict
73
+ class OpenAIPrivacyFilterConfig(GptOssConfig):
74
+ model_type = "openai_privacy_filter"
75
+ vocab_size: int = 200064
76
+ hidden_size: int = 640
77
+ intermediate_size: int = 640
78
+ num_hidden_layers: int = 8
79
+ num_attention_heads: int = 14
80
+ num_key_value_heads: int = 2
81
+ sliding_window: int = 128
82
+ classifier_dropout: float = 0.0
83
+ pad_token_id: int | None = 199999
84
+ eos_token_id: int | list[int] | None = 199999
85
+ layer_types = AttributeError() # SWA only
86
+ hidden_act = AttributeError() # Not used as it's expert MLPs only
87
+
88
+ def __post_init__(self, **kwargs):
89
+ if self.num_key_value_heads is None:
90
+ self.num_key_value_heads = self.num_attention_heads
91
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
92
+
93
+ if self.rope_parameters is None:
94
+ self.rope_parameters = {
95
+ "rope_type": "yarn",
96
+ "factor": 32.0,
97
+ "beta_fast": 32.0,
98
+ "beta_slow": 1.0,
99
+ "truncate": False,
100
+ "original_max_position_embeddings": 4096,
101
+ }
102
+
103
+ requested_num_labels = kwargs.pop("num_labels", len(OPENAI_PRIVACY_FILTER_NER_LABELS))
104
+ if self.id2label is None and requested_num_labels == len(OPENAI_PRIVACY_FILTER_NER_LABELS):
105
+ self.id2label = dict(enumerate(OPENAI_PRIVACY_FILTER_NER_LABELS))
106
+ elif self.id2label is None:
107
+ self.num_labels = requested_num_labels
108
+ if self.label2id is None and self.id2label is not None:
109
+ self.label2id = {label: idx for idx, label in self.id2label.items()}
110
+
111
+ PreTrainedConfig.__post_init__(self, **kwargs)
112
+
113
+
114
+ class OpenAIPrivacyFilterRMSNorm(GptOssRMSNorm):
115
+ pass
116
+
117
+
118
+ class OpenAIPrivacyFilterRotaryEmbedding(GptOssRotaryEmbedding):
119
+ pass
120
+
121
+
122
+ def _apply_rotary_emb(
123
+ x: torch.Tensor,
124
+ cos: torch.Tensor,
125
+ sin: torch.Tensor,
126
+ ) -> torch.Tensor:
127
+ # Interleaving layout instead of concatenated
128
+ first_half, second_half = x[..., ::2], x[..., 1::2]
129
+ first_ = first_half * cos - second_half * sin
130
+ second_ = second_half * cos + first_half * sin
131
+ return torch.stack((first_, second_), dim=-1).flatten(-2)
132
+
133
+
134
+ def eager_attention_forward(
135
+ module: nn.Module,
136
+ query: torch.Tensor,
137
+ key: torch.Tensor,
138
+ value: torch.Tensor,
139
+ attention_mask: torch.Tensor | None,
140
+ scaling: float,
141
+ dropout: float | int = 0.0,
142
+ **kwargs,
143
+ ):
144
+ key_states = repeat_kv(key, module.num_key_value_groups)
145
+ value_states = repeat_kv(value, module.num_key_value_groups)
146
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
147
+ if attention_mask is not None:
148
+ attn_weights = attn_weights + attention_mask
149
+
150
+ sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
151
+ combined_logits = torch.cat([attn_weights, sinks], dim=-1)
152
+
153
+ # This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
154
+ # when training with bsz>1 we clamp max values.
155
+
156
+ combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
157
+ probs = nn.functional.softmax(combined_logits, dim=-1, dtype=torch.float32) # Softmax in fp32
158
+ scores = probs[..., :-1] # we drop the sink here
159
+ attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training).to(value_states.dtype)
160
+ attn_output = torch.matmul(attn_weights, value_states)
161
+ attn_output = attn_output.transpose(1, 2).contiguous()
162
+ return attn_output, attn_weights
163
+
164
+
165
+ class OpenAIPrivacyFilterAttention(GptOssAttention):
166
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
167
+ super().__init__(config)
168
+ del self.layer_idx # Only for caching
169
+ del self.layer_type # SWA only
170
+ self.is_causal = False
171
+ self.sliding_window = config.sliding_window + 1 # Account for FA symmetry using -1
172
+ self.scaling = config.head_dim**-0.25
173
+
174
+ def forward(
175
+ self,
176
+ hidden_states: torch.Tensor,
177
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
178
+ attention_mask: torch.Tensor | None = None,
179
+ **kwargs: Unpack[TransformersKwargs],
180
+ ) -> tuple[torch.Tensor, None]:
181
+ input_shape = hidden_states.shape[:-1]
182
+ hidden_shape = (*input_shape, -1, self.head_dim)
183
+
184
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
185
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
186
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
187
+
188
+ cos, sin = position_embeddings
189
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
190
+
191
+ # Unique: applying scale individually to each Q and K
192
+ query_states = query_states * self.scaling
193
+ key_states = key_states * self.scaling
194
+
195
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
196
+ self.config._attn_implementation, eager_attention_forward
197
+ )
198
+
199
+ attn_output, attn_weights = attention_interface(
200
+ self,
201
+ query_states,
202
+ key_states,
203
+ value_states,
204
+ attention_mask,
205
+ dropout=0.0 if not self.training else self.attention_dropout,
206
+ scaling=1.0, # scaling applied before
207
+ sliding_window=self.sliding_window,
208
+ s_aux=self.sinks,
209
+ **kwargs,
210
+ )
211
+
212
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
213
+ attn_output = self.o_proj(attn_output)
214
+ return attn_output, attn_weights
215
+
216
+
217
+ @use_experts_implementation(is_transposed=True, has_bias=True)
218
+ class OpenAIPrivacyFilterExperts(GptOssExperts):
219
+ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
220
+ # Concatenated layout instead of interleaving
221
+ gate, up = gate_up.chunk(2, dim=-1)
222
+ gate = gate.clamp(min=None, max=self.limit)
223
+ up = up.clamp(min=-self.limit, max=self.limit)
224
+ glu = gate * torch.sigmoid(gate * self.alpha)
225
+ gated_output = (up + 1) * glu
226
+ return gated_output
227
+
228
+ def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor:
229
+ original_dtype = hidden_states.dtype
230
+
231
+ # Accumulate over fp32
232
+ next_states = torch.zeros_like(hidden_states, dtype=torch.float32, device=hidden_states.device)
233
+ with torch.no_grad():
234
+ expert_mask = torch.nn.functional.one_hot(
235
+ router_indices, num_classes=self.num_experts
236
+ ) # masking is also a class
237
+ expert_mask = expert_mask.permute(2, 1, 0)
238
+ # we sum on the top_k and on the sequence length to get which experts
239
+ # are hit this time around
240
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
241
+
242
+ # Key change to original gpt oss is to stay in fp32 precision for all linear projections / muls
243
+ for expert_idx in expert_hit:
244
+ # expert_idx only have 1 element, so we can use scale for fast indexing
245
+ expert_idx = expert_idx[0]
246
+ # skip masking index
247
+ if expert_idx == self.num_experts:
248
+ continue
249
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
250
+ current_state = hidden_states[token_idx]
251
+ gate_up = (
252
+ current_state.float() @ self.gate_up_proj[expert_idx].float()
253
+ + self.gate_up_proj_bias[expert_idx].float()
254
+ )
255
+ gated_output = self._apply_gate(gate_up).float()
256
+ out = gated_output.float() @ self.down_proj[expert_idx].float() + self.down_proj_bias[expert_idx].float()
257
+ weighted_output = out * routing_weights[token_idx, top_k_pos, None].float()
258
+ next_states.index_add_(0, token_idx, weighted_output)
259
+
260
+ return next_states.to(original_dtype)
261
+
262
+
263
+ class OpenAIPrivacyFilterTopKRouter(GptOssTopKRouter):
264
+ def forward(self, hidden_states):
265
+ # Force fp32
266
+ router_logits = F.linear(
267
+ hidden_states.float(), self.weight.float(), self.bias.float()
268
+ ) # (num_tokens, num_experts)
269
+ router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (num_tokens, top_k)
270
+ router_scores = torch.nn.functional.softmax(router_top_value, dim=1, dtype=router_top_value.dtype)
271
+ # Additional scaling
272
+ router_scores = router_scores / self.top_k
273
+ return router_logits, router_scores, router_indices
274
+
275
+
276
+ class OpenAIPrivacyFilterMLP(nn.Module):
277
+ """Similar to GPT Oss but with FP32 focus + added experts scaling"""
278
+
279
+ def __init__(self, config):
280
+ super().__init__()
281
+ self.router = OpenAIPrivacyFilterTopKRouter(config)
282
+ self.num_experts = config.num_experts_per_tok
283
+ self.experts = OpenAIPrivacyFilterExperts(config)
284
+
285
+ def forward(self, hidden_states):
286
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
287
+ hidden_states = hidden_states.reshape(-1, hidden_dim)
288
+ _, router_scores, router_indices = self.router(hidden_states)
289
+ hidden_states = self.experts(hidden_states, router_indices, router_scores)
290
+ # Additional scaling
291
+ hidden_states = hidden_states * self.num_experts
292
+ hidden_states = hidden_states.reshape(batch_size, sequence_length, hidden_dim)
293
+ return hidden_states, router_scores
294
+
295
+
296
+ class OpenAIPrivacyFilterEncoderLayer(GptOssDecoderLayer):
297
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
298
+ super().__init__(config)
299
+ self.self_attn = OpenAIPrivacyFilterAttention(config)
300
+
301
+ def forward(
302
+ self,
303
+ hidden_states: torch.Tensor,
304
+ attention_mask: torch.Tensor | None = None,
305
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
306
+ **kwargs: Unpack[TransformersKwargs],
307
+ ) -> torch.Tensor:
308
+ residual = hidden_states
309
+ hidden_states = self.input_layernorm(hidden_states)
310
+ # Self Attention
311
+ hidden_states, _ = self.self_attn(
312
+ hidden_states=hidden_states,
313
+ position_embeddings=position_embeddings,
314
+ attention_mask=attention_mask,
315
+ **kwargs,
316
+ )
317
+ hidden_states = residual + hidden_states
318
+
319
+ # Fully Connected
320
+ residual = hidden_states
321
+ hidden_states = self.post_attention_layernorm(hidden_states)
322
+ hidden_states, _ = self.mlp(hidden_states)
323
+ hidden_states = residual + hidden_states
324
+
325
+ return hidden_states
326
+
327
+
328
+ class OpenAIPrivacyFilterPreTrainedModel(GptOssPreTrainedModel):
329
+ config: OpenAIPrivacyFilterConfig
330
+ _no_split_modules = ["OpenAIPrivacyFilterEncoderLayer"]
331
+ _skip_keys_device_placement = None # No cache
332
+ _keep_in_fp32_modules = []
333
+ _keep_in_fp32_modules_strict = ["sinks"]
334
+
335
+ _can_record_outputs = {
336
+ "router_logits": OutputRecorder(OpenAIPrivacyFilterTopKRouter, index=0),
337
+ "hidden_states": OpenAIPrivacyFilterEncoderLayer,
338
+ "attentions": OpenAIPrivacyFilterAttention,
339
+ }
340
+
341
+ def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
342
+ """The model is very sensitive to accumulation orders, hence we default to `eager` instead"""
343
+ requested_experts = "eager" if requested_experts is None else requested_experts
344
+ return PreTrainedModel.get_correct_experts_implementation(self, requested_experts)
345
+
346
+
347
+ @auto_docstring
348
+ class OpenAIPrivacyFilterModel(GptOssModel):
349
+ def __init__(self, config: OpenAIPrivacyFilterConfig):
350
+ super().__init__(config)
351
+ self.layers = nn.ModuleList([OpenAIPrivacyFilterEncoderLayer(config) for _ in range(config.num_hidden_layers)])
352
+
353
+ @merge_with_config_defaults
354
+ @capture_outputs
355
+ @auto_docstring
356
+ def forward(
357
+ self,
358
+ input_ids: torch.LongTensor | None = None,
359
+ attention_mask: torch.Tensor | None = None,
360
+ position_ids: torch.LongTensor | None = None,
361
+ inputs_embeds: torch.FloatTensor | None = None,
362
+ **kwargs: Unpack[TransformersKwargs],
363
+ ) -> BaseModelOutput:
364
+ if (input_ids is None) ^ (inputs_embeds is not None):
365
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
366
+
367
+ if inputs_embeds is None:
368
+ inputs_embeds = self.embed_tokens(input_ids)
369
+ hidden_states = inputs_embeds
370
+
371
+ if position_ids is None:
372
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
373
+ position_ids = position_ids.unsqueeze(0)
374
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
375
+
376
+ attention_mask = create_bidirectional_sliding_window_mask(
377
+ config=self.config,
378
+ inputs_embeds=hidden_states,
379
+ attention_mask=attention_mask,
380
+ )
381
+
382
+ for encoder_layer in self.layers:
383
+ hidden_states = encoder_layer(
384
+ hidden_states,
385
+ position_embeddings=position_embeddings,
386
+ attention_mask=attention_mask,
387
+ position_ids=position_ids,
388
+ **kwargs,
389
+ )
390
+
391
+ hidden_states = self.norm(hidden_states)
392
+
393
+ return BaseModelOutput(last_hidden_state=hidden_states)
394
+
395
+
396
+ class OpenAIPrivacyFilterForTokenClassification(GenericForTokenClassification, OpenAIPrivacyFilterPreTrainedModel): ...
397
+
398
+
399
+ __all__ = [
400
+ "OpenAIPrivacyFilterForTokenClassification",
401
+ "OpenAIPrivacyFilterModel",
402
+ "OpenAIPrivacyFilterPreTrainedModel",
403
+ "OpenAIPrivacyFilterConfig",
404
+ ]
lib/python3.11/site-packages/transformers/models/opt/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_opt import *
22
+ from .modeling_opt import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.11/site-packages/transformers/models/opt/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (769 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/opt/__pycache__/configuration_opt.cpython-311.pyc ADDED
Binary file (3.73 kB). View file
 
lib/python3.11/site-packages/transformers/models/opt/__pycache__/modeling_opt.cpython-311.pyc ADDED
Binary file (35.2 kB). View file
 
lib/python3.11/site-packages/transformers/models/opt/configuration_opt.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Metaseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """OPT model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="facebook/opt-350m")
23
+ @strict
24
+ class OPTConfig(PreTrainedConfig):
25
+ r"""
26
+ do_layer_norm_before (`bool`, *optional*, defaults to `True`):
27
+ Whether to perform layer normalization before the attention block.
28
+ word_embed_proj_dim (`int`, *optional*):
29
+ `word_embed_proj_dim` can be set to down-project word embeddings, *e.g.* `opt-350m`. Defaults to
30
+ `hidden_size`.
31
+ enable_bias (`bool`, *optional*, defaults to `True`):
32
+ Whether or not if the linear layers in the attention blocks should use the bias term.
33
+ layer_norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
34
+ Whether or not if the layer norms should have learnable parameters.
35
+
36
+ Example:
37
+
38
+ ```python
39
+ >>> from transformers import OPTConfig, OPTModel
40
+
41
+ >>> # Initializing a OPT facebook/opt-large style configuration
42
+ >>> configuration = OPTConfig()
43
+
44
+ >>> # Initializing a model (with random weights) from the facebook/opt-large style configuration
45
+ >>> model = OPTModel(configuration)
46
+
47
+ >>> # Accessing the model configuration
48
+ >>> configuration = model.config
49
+ ```"""
50
+
51
+ model_type = "opt"
52
+ keys_to_ignore_at_inference = ["past_key_values"]
53
+
54
+ vocab_size: int = 50272
55
+ hidden_size: int = 768
56
+ num_hidden_layers: int = 12
57
+ ffn_dim: int = 3072
58
+ max_position_embeddings: int = 2048
59
+ do_layer_norm_before: bool = True
60
+ _remove_final_layer_norm: bool = False
61
+ word_embed_proj_dim: int | None = None
62
+ dropout: float | int = 0.1
63
+ attention_dropout: float | int = 0.0
64
+ num_attention_heads: int = 12
65
+ activation_function: str = "relu"
66
+ layerdrop: float | int = 0.0
67
+ init_std: float = 0.02
68
+ use_cache: bool = True
69
+ pad_token_id: int | None = 1
70
+ bos_token_id: int | None = 2
71
+ eos_token_id: int | list[int] | None = 2
72
+ enable_bias: bool = True
73
+ layer_norm_elementwise_affine: bool = True
74
+ tie_word_embeddings: bool = True
75
+
76
+ def __post_init__(self, **kwargs):
77
+ self.word_embed_proj_dim = (
78
+ self.word_embed_proj_dim if self.word_embed_proj_dim is not None else self.hidden_size
79
+ )
80
+ super().__post_init__(**kwargs)
81
+
82
+
83
+ __all__ = ["OPTConfig"]
lib/python3.11/site-packages/transformers/models/opt/modeling_opt.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch OPT model."""
15
+
16
+ from collections.abc import Callable
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ...activations import ACT2FN
23
+ from ...cache_utils import Cache, DynamicCache
24
+ from ...generation import GenerationMixin
25
+ from ...masking_utils import create_causal_mask
26
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithPast,
30
+ CausalLMOutputWithPast,
31
+ QuestionAnsweringModelOutput,
32
+ SequenceClassifierOutputWithPast,
33
+ )
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
35
+ from ...processing_utils import Unpack
36
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
37
+ from ...utils.generic import merge_with_config_defaults
38
+ from ...utils.output_capturing import capture_outputs
39
+ from .configuration_opt import OPTConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class OPTLearnedPositionalEmbedding(nn.Embedding):
46
+ """
47
+ This module learns positional embeddings up to a fixed maximum size.
48
+ """
49
+
50
+ def __init__(self, num_embeddings: int, embedding_dim: int):
51
+ # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2
52
+ # and adjust num_embeddings appropriately. Other models don't have this hack
53
+ self.offset = 2
54
+ super().__init__(num_embeddings + self.offset, embedding_dim)
55
+
56
+ def forward(
57
+ self,
58
+ attention_mask: torch.LongTensor,
59
+ past_key_values_length: int = 0,
60
+ position_ids: torch.LongTensor | None = None,
61
+ ):
62
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
63
+
64
+ if position_ids is None:
65
+ position_ids = torch.cumsum(attention_mask, dim=1)
66
+ position_ids = (position_ids * attention_mask - 1).long()
67
+ # cut positions if `past_key_values_length` is > 0
68
+ position_ids = position_ids[:, past_key_values_length:]
69
+
70
+ return super().forward(position_ids + self.offset)
71
+
72
+
73
+ # Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward
74
+ def eager_attention_forward(
75
+ module: nn.Module,
76
+ query: torch.Tensor,
77
+ key: torch.Tensor,
78
+ value: torch.Tensor,
79
+ attention_mask: torch.Tensor | None,
80
+ scaling: float,
81
+ dropout: float = 0.0,
82
+ **kwargs,
83
+ ):
84
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
85
+ if attention_mask is not None:
86
+ attn_weights = attn_weights + attention_mask
87
+
88
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
89
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
90
+
91
+ attn_output = torch.matmul(attn_weights, value)
92
+ attn_output = attn_output.transpose(1, 2).contiguous()
93
+
94
+ return attn_output, attn_weights
95
+
96
+
97
+ class OPTAttention(nn.Module):
98
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
99
+
100
+ def __init__(
101
+ self,
102
+ config: OPTConfig,
103
+ layer_idx: int | None = None,
104
+ **kwargs,
105
+ ):
106
+ super().__init__()
107
+ self.config = config
108
+ self.embed_dim = config.hidden_size
109
+ self.num_heads = config.num_attention_heads
110
+ self.dropout = config.attention_dropout
111
+ self.enable_bias = config.enable_bias
112
+ self.layer_idx = layer_idx
113
+ if layer_idx is None:
114
+ logger.warning_once(
115
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
116
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
117
+ "when creating this class."
118
+ )
119
+
120
+ self.head_dim = self.embed_dim // self.num_heads
121
+ self.is_causal = True
122
+
123
+ if (self.head_dim * self.num_heads) != self.embed_dim:
124
+ raise ValueError(
125
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
126
+ f" and `num_heads`: {self.num_heads})."
127
+ )
128
+ self.scaling = self.head_dim**-0.5
129
+
130
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=self.enable_bias)
131
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=self.enable_bias)
132
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=self.enable_bias)
133
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=self.enable_bias)
134
+
135
+ def forward(
136
+ self,
137
+ hidden_states: torch.Tensor,
138
+ past_key_values: Cache | None = None,
139
+ attention_mask: torch.Tensor | None = None,
140
+ output_attentions: bool = False,
141
+ **kwargs,
142
+ ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]:
143
+ """Input shape: Batch x Time x Channel"""
144
+ bsz, tgt_len, _ = hidden_states.size()
145
+
146
+ # Scaling is susceptible to floating point arithmetics' inprecisions
147
+ # which can lead to different results (this is dependent from model
148
+ # to model, e.g. whisper is one such case). We therefore keep the
149
+ # original order of scaling to follow the original implementation
150
+ # and enforce no scaling (1.0) in the attention call below.
151
+ query_states = self.q_proj(hidden_states) * self.scaling
152
+ query_states = query_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
153
+
154
+ key_states = self.k_proj(hidden_states)
155
+ value_states = self.v_proj(hidden_states)
156
+ key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
157
+ value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
158
+
159
+ if past_key_values is not None:
160
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
161
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
162
+
163
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
164
+ self.config._attn_implementation, eager_attention_forward
165
+ )
166
+
167
+ attn_output, attn_weights = attention_interface(
168
+ self,
169
+ query_states,
170
+ key_states,
171
+ value_states,
172
+ attention_mask,
173
+ dropout=0.0 if not self.training else self.dropout,
174
+ scaling=1.0,
175
+ **kwargs,
176
+ )
177
+
178
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
179
+ attn_output = self.out_proj(attn_output)
180
+
181
+ return attn_output, attn_weights
182
+
183
+
184
+ class OPTDecoderLayer(GradientCheckpointingLayer):
185
+ def __init__(self, config: OPTConfig, layer_idx: int | None = None):
186
+ super().__init__()
187
+ self.embed_dim = config.hidden_size
188
+
189
+ self.self_attn = OPTAttention(config=config, layer_idx=layer_idx)
190
+
191
+ self.do_layer_norm_before = config.do_layer_norm_before
192
+ self.dropout = config.dropout
193
+ self.activation_fn = ACT2FN[config.activation_function]
194
+
195
+ self.self_attn_layer_norm = nn.LayerNorm(
196
+ self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine
197
+ )
198
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=config.enable_bias)
199
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=config.enable_bias)
200
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine)
201
+
202
+ def forward(
203
+ self,
204
+ hidden_states: torch.Tensor,
205
+ attention_mask: torch.Tensor | None = None,
206
+ past_key_values: Cache | None = None,
207
+ use_cache: bool | None = False,
208
+ position_ids: torch.LongTensor | None = None,
209
+ **kwargs: Unpack[FlashAttentionKwargs],
210
+ ) -> torch.Tensor:
211
+ residual = hidden_states
212
+
213
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
214
+ if self.do_layer_norm_before:
215
+ hidden_states = self.self_attn_layer_norm(hidden_states)
216
+
217
+ # Self Attention
218
+ hidden_states, _ = self.self_attn(
219
+ hidden_states=hidden_states,
220
+ past_key_values=past_key_values,
221
+ position_ids=position_ids,
222
+ attention_mask=attention_mask,
223
+ **kwargs,
224
+ )
225
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
226
+ hidden_states = residual + hidden_states
227
+
228
+ # 350m applies layer norm AFTER attention
229
+ if not self.do_layer_norm_before:
230
+ hidden_states = self.self_attn_layer_norm(hidden_states)
231
+
232
+ # Fully Connected
233
+ hidden_states_shape = hidden_states.shape
234
+ hidden_states = hidden_states.reshape(-1, hidden_states.size(-1))
235
+ residual = hidden_states
236
+
237
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
238
+ if self.do_layer_norm_before:
239
+ hidden_states = self.final_layer_norm(hidden_states)
240
+
241
+ hidden_states = self.fc1(hidden_states)
242
+ hidden_states = self.activation_fn(hidden_states)
243
+
244
+ hidden_states = self.fc2(hidden_states)
245
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
246
+
247
+ hidden_states = (residual + hidden_states).view(hidden_states_shape)
248
+
249
+ # 350m applies layer norm AFTER attention
250
+ if not self.do_layer_norm_before:
251
+ hidden_states = self.final_layer_norm(hidden_states)
252
+
253
+ return hidden_states
254
+
255
+
256
+ @auto_docstring
257
+ class OPTPreTrainedModel(PreTrainedModel):
258
+ config: OPTConfig
259
+ base_model_prefix = "model"
260
+ supports_gradient_checkpointing = True
261
+ _no_split_modules = ["OPTDecoderLayer"]
262
+ _supports_attention_backend = True
263
+ _supports_flash_attn = True
264
+ _supports_sdpa = True
265
+ _supports_flex_attn = True
266
+ _can_compile_fullgraph = True
267
+ _can_record_outputs = {
268
+ "hidden_states": OPTDecoderLayer,
269
+ "attentions": OPTAttention,
270
+ }
271
+
272
+
273
+ class OPTDecoder(OPTPreTrainedModel):
274
+ """
275
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`]
276
+
277
+ Args:
278
+ config: OPTConfig
279
+ """
280
+
281
+ def __init__(self, config: OPTConfig):
282
+ super().__init__(config)
283
+ self.dropout = config.dropout
284
+ self.layerdrop = config.layerdrop
285
+ self.padding_idx = config.pad_token_id
286
+ self.max_target_positions = config.max_position_embeddings
287
+ self.vocab_size = config.vocab_size
288
+
289
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx)
290
+ self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size)
291
+
292
+ if config.word_embed_proj_dim != config.hidden_size:
293
+ self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False)
294
+ else:
295
+ self.project_out = None
296
+
297
+ if config.word_embed_proj_dim != config.hidden_size:
298
+ self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False)
299
+ else:
300
+ self.project_in = None
301
+
302
+ # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
303
+ # with checkpoints that have been fine-tuned before transformers v4.20.1
304
+ # see https://github.com/facebookresearch/metaseq/pull/164
305
+ if config.do_layer_norm_before and not config._remove_final_layer_norm:
306
+ self.final_layer_norm = nn.LayerNorm(
307
+ config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine
308
+ )
309
+ else:
310
+ self.final_layer_norm = None
311
+
312
+ self.layers = nn.ModuleList([OPTDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
313
+
314
+ self.gradient_checkpointing = False
315
+ # Initialize weights and apply final processing
316
+ self.post_init()
317
+
318
+ @merge_with_config_defaults
319
+ @capture_outputs
320
+ @auto_docstring
321
+ def forward(
322
+ self,
323
+ input_ids: torch.LongTensor | None = None,
324
+ attention_mask: torch.Tensor | None = None,
325
+ past_key_values: Cache | None = None,
326
+ inputs_embeds: torch.FloatTensor | None = None,
327
+ use_cache: bool | None = None,
328
+ position_ids: torch.LongTensor | None = None,
329
+ **kwargs: Unpack[TransformersKwargs],
330
+ ) -> BaseModelOutputWithPast:
331
+ if (input_ids is None) ^ (inputs_embeds is not None):
332
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
333
+
334
+ if input_ids is not None:
335
+ input_ids = input_ids.view(-1, input_ids.shape[-1])
336
+
337
+ if inputs_embeds is None:
338
+ inputs_embeds = self.embed_tokens(input_ids)
339
+
340
+ if use_cache and past_key_values is None:
341
+ past_key_values = DynamicCache(config=self.config)
342
+
343
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
344
+
345
+ if attention_mask is None:
346
+ seq_length = past_seen_tokens + inputs_embeds.shape[1]
347
+ attention_mask = torch.ones(inputs_embeds.shape[0], seq_length, device=inputs_embeds.device)
348
+
349
+ # embed positions
350
+ if position_ids is None:
351
+ position_ids = torch.cumsum(attention_mask, dim=1)
352
+ position_ids = (position_ids * attention_mask - 1).long()
353
+ # cut positions if `past_seen_tokens` is > 0
354
+ position_ids = position_ids[:, past_seen_tokens:]
355
+
356
+ causal_mask = create_causal_mask(
357
+ config=self.config,
358
+ inputs_embeds=inputs_embeds,
359
+ attention_mask=attention_mask,
360
+ past_key_values=past_key_values,
361
+ )
362
+
363
+ pos_embeds = self.embed_positions(attention_mask, past_seen_tokens, position_ids=position_ids)
364
+
365
+ if self.project_in is not None:
366
+ inputs_embeds = self.project_in(inputs_embeds)
367
+
368
+ hidden_states = inputs_embeds + pos_embeds.to(inputs_embeds.device)
369
+
370
+ # decoder layers
371
+ for idx, decoder_layer in enumerate(self.layers):
372
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
373
+ if self.training:
374
+ dropout_probability = torch.rand([])
375
+ if dropout_probability < self.layerdrop:
376
+ continue
377
+
378
+ hidden_states = decoder_layer(
379
+ hidden_states,
380
+ attention_mask=causal_mask,
381
+ position_ids=position_ids,
382
+ past_key_values=past_key_values,
383
+ use_cache=use_cache,
384
+ **kwargs,
385
+ )
386
+
387
+ if self.final_layer_norm is not None:
388
+ hidden_states = self.final_layer_norm(hidden_states)
389
+
390
+ if self.project_out is not None:
391
+ hidden_states = self.project_out(hidden_states)
392
+
393
+ return BaseModelOutputWithPast(
394
+ last_hidden_state=hidden_states,
395
+ past_key_values=past_key_values,
396
+ )
397
+
398
+
399
+ @auto_docstring
400
+ class OPTModel(OPTPreTrainedModel):
401
+ def __init__(self, config: OPTConfig):
402
+ super().__init__(config)
403
+ self.decoder = OPTDecoder(config)
404
+ # Initialize weights and apply final processing
405
+ self.post_init()
406
+
407
+ def get_input_embeddings(self):
408
+ return self.decoder.embed_tokens
409
+
410
+ def set_input_embeddings(self, value):
411
+ self.decoder.embed_tokens = value
412
+
413
+ @can_return_tuple
414
+ @auto_docstring
415
+ def forward(
416
+ self,
417
+ input_ids: torch.LongTensor | None = None,
418
+ attention_mask: torch.Tensor | None = None,
419
+ past_key_values: Cache | None = None,
420
+ inputs_embeds: torch.FloatTensor | None = None,
421
+ use_cache: bool | None = None,
422
+ position_ids: torch.LongTensor | None = None,
423
+ **kwargs: Unpack[TransformersKwargs],
424
+ ) -> BaseModelOutputWithPast:
425
+ decoder_outputs: BaseModelOutputWithPast = self.decoder(
426
+ input_ids=input_ids,
427
+ attention_mask=attention_mask,
428
+ position_ids=position_ids,
429
+ past_key_values=past_key_values,
430
+ inputs_embeds=inputs_embeds,
431
+ use_cache=use_cache,
432
+ **kwargs,
433
+ )
434
+
435
+ return BaseModelOutputWithPast(
436
+ last_hidden_state=decoder_outputs.last_hidden_state,
437
+ past_key_values=decoder_outputs.past_key_values,
438
+ hidden_states=decoder_outputs.hidden_states,
439
+ attentions=decoder_outputs.attentions,
440
+ )
441
+
442
+
443
+ class OPTForCausalLM(OPTPreTrainedModel, GenerationMixin):
444
+ _tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
445
+
446
+ def __init__(self, config):
447
+ super().__init__(config)
448
+ self.model = OPTModel(config)
449
+
450
+ # the lm_head weight is automatically tied to the embed tokens weight
451
+ self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False)
452
+
453
+ # Initialize weights and apply final processing
454
+ self.post_init()
455
+
456
+ def get_input_embeddings(self):
457
+ return self.model.decoder.embed_tokens
458
+
459
+ def set_input_embeddings(self, value):
460
+ self.model.decoder.embed_tokens = value
461
+
462
+ @can_return_tuple
463
+ @auto_docstring
464
+ def forward(
465
+ self,
466
+ input_ids: torch.LongTensor | None = None,
467
+ attention_mask: torch.Tensor | None = None,
468
+ past_key_values: Cache | None = None,
469
+ inputs_embeds: torch.FloatTensor | None = None,
470
+ labels: torch.LongTensor | None = None,
471
+ use_cache: bool | None = None,
472
+ position_ids: torch.LongTensor | None = None,
473
+ logits_to_keep: int | torch.Tensor = 0,
474
+ **kwargs: Unpack[TransformersKwargs],
475
+ ) -> tuple | CausalLMOutputWithPast:
476
+ r"""
477
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
478
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
479
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
480
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
481
+
482
+ Example:
483
+
484
+ ```python
485
+ >>> from transformers import AutoTokenizer, OPTForCausalLM
486
+
487
+ >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m")
488
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
489
+
490
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
491
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
492
+
493
+ >>> # Generate
494
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
495
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
496
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo."
497
+ ```"""
498
+
499
+ outputs: BaseModelOutputWithPast = self.model.decoder(
500
+ input_ids=input_ids,
501
+ attention_mask=attention_mask,
502
+ position_ids=position_ids,
503
+ past_key_values=past_key_values,
504
+ inputs_embeds=inputs_embeds,
505
+ use_cache=use_cache,
506
+ **kwargs,
507
+ )
508
+
509
+ hidden_states = outputs.last_hidden_state
510
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
511
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
512
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).contiguous()
513
+
514
+ loss = None
515
+ if labels is not None:
516
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
517
+
518
+ return CausalLMOutputWithPast(
519
+ loss=loss,
520
+ logits=logits,
521
+ past_key_values=outputs.past_key_values,
522
+ hidden_states=outputs.hidden_states,
523
+ attentions=outputs.attentions,
524
+ )
525
+
526
+
527
+ @auto_docstring(
528
+ custom_intro="""
529
+ The OPT Model transformer with a sequence classification head on top (linear layer).
530
+
531
+ [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models
532
+ (e.g. GPT-2) do.
533
+
534
+ Since it does classification on the last token, it requires to know the position of the last token. If a
535
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
536
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
537
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
538
+ each row of the batch).
539
+ """
540
+ )
541
+ class OPTForSequenceClassification(OPTPreTrainedModel):
542
+ def __init__(self, config: OPTConfig):
543
+ super().__init__(config)
544
+ self.num_labels = config.num_labels
545
+ self.model = OPTModel(config)
546
+ self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False)
547
+
548
+ # Initialize weights and apply final processing
549
+ self.post_init()
550
+
551
+ @can_return_tuple
552
+ @auto_docstring
553
+ def forward(
554
+ self,
555
+ input_ids: torch.LongTensor | None = None,
556
+ attention_mask: torch.FloatTensor | None = None,
557
+ past_key_values: Cache | None = None,
558
+ inputs_embeds: torch.FloatTensor | None = None,
559
+ labels: torch.LongTensor | None = None,
560
+ use_cache: bool | None = None,
561
+ position_ids: torch.LongTensor | None = None,
562
+ **kwargs: Unpack[TransformersKwargs],
563
+ ) -> tuple | SequenceClassifierOutputWithPast:
564
+ r"""
565
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
566
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
567
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
568
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
569
+ """
570
+ transformer_outputs: BaseModelOutputWithPast = self.model(
571
+ input_ids,
572
+ past_key_values=past_key_values,
573
+ attention_mask=attention_mask,
574
+ position_ids=position_ids,
575
+ inputs_embeds=inputs_embeds,
576
+ use_cache=use_cache,
577
+ **kwargs,
578
+ )
579
+ hidden_states = transformer_outputs.last_hidden_state
580
+ logits = self.score(hidden_states)
581
+
582
+ if input_ids is not None:
583
+ batch_size, sequence_length = input_ids.shape[:2]
584
+ else:
585
+ batch_size, sequence_length = inputs_embeds.shape[:2]
586
+
587
+ if self.config.pad_token_id is None and batch_size != 1:
588
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
589
+ if self.config.pad_token_id is None:
590
+ last_non_pad_token = -1
591
+ elif input_ids is not None:
592
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
593
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
594
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
595
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
596
+ else:
597
+ last_non_pad_token = -1
598
+ logger.warning_once(
599
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
600
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
601
+ )
602
+
603
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
604
+
605
+ loss = None
606
+ if labels is not None:
607
+ if self.config.problem_type is None:
608
+ if self.num_labels == 1:
609
+ self.config.problem_type = "regression"
610
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
611
+ self.config.problem_type = "single_label_classification"
612
+ else:
613
+ self.config.problem_type = "multi_label_classification"
614
+
615
+ if self.config.problem_type == "regression":
616
+ loss_fct = MSELoss()
617
+ if self.num_labels == 1:
618
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
619
+ else:
620
+ loss = loss_fct(pooled_logits, labels)
621
+ elif self.config.problem_type == "single_label_classification":
622
+ loss_fct = CrossEntropyLoss()
623
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
624
+ elif self.config.problem_type == "multi_label_classification":
625
+ loss_fct = BCEWithLogitsLoss()
626
+ loss = loss_fct(pooled_logits, labels)
627
+
628
+ return SequenceClassifierOutputWithPast(
629
+ loss=loss,
630
+ logits=pooled_logits,
631
+ past_key_values=transformer_outputs.past_key_values,
632
+ hidden_states=transformer_outputs.hidden_states,
633
+ attentions=transformer_outputs.attentions,
634
+ )
635
+
636
+ def get_input_embeddings(self):
637
+ return self.model.decoder.embed_tokens
638
+
639
+ def set_input_embeddings(self, value):
640
+ self.model.decoder.embed_tokens = value
641
+
642
+
643
+ @auto_docstring
644
+ class OPTForQuestionAnswering(OPTPreTrainedModel):
645
+ def __init__(self, config: OPTConfig):
646
+ super().__init__(config)
647
+ self.model = OPTModel(config)
648
+ self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2)
649
+
650
+ # Initialize weights and apply final processing
651
+ self.post_init()
652
+
653
+ @can_return_tuple
654
+ @auto_docstring
655
+ def forward(
656
+ self,
657
+ input_ids: torch.LongTensor | None = None,
658
+ attention_mask: torch.FloatTensor | None = None,
659
+ past_key_values: Cache | None = None,
660
+ inputs_embeds: torch.FloatTensor | None = None,
661
+ start_positions: torch.LongTensor | None = None,
662
+ end_positions: torch.LongTensor | None = None,
663
+ use_cache: bool | None = None,
664
+ position_ids: torch.LongTensor | None = None,
665
+ **kwargs: Unpack[TransformersKwargs],
666
+ ) -> tuple | QuestionAnsweringModelOutput:
667
+ r"""
668
+ Example:
669
+
670
+ ```python
671
+ >>> from transformers import AutoTokenizer, OPTForQuestionAnswering
672
+ >>> import torch
673
+
674
+ >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT
675
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
676
+
677
+ >>> # note: we are loading a OPTForQuestionAnswering from the hub here,
678
+ >>> # so the head will be randomly initialized, hence the predictions will be random
679
+ >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m")
680
+
681
+ >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
682
+
683
+ >>> inputs = tokenizer(question, text, return_tensors="pt")
684
+ >>> with torch.no_grad():
685
+ ... outputs = model(**inputs)
686
+
687
+ >>> answer_start_index = outputs.start_logits.argmax()
688
+ >>> answer_end_index = outputs.end_logits.argmax()
689
+
690
+ >>> answer_offset = len(tokenizer(question)[0])
691
+
692
+ >>> predict_answer_tokens = inputs.input_ids[
693
+ ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1
694
+ ... ]
695
+ >>> predicted = tokenizer.decode(predict_answer_tokens)
696
+ >>> predicted
697
+ ' a nice puppet'
698
+ ```"""
699
+ transformer_outputs: BaseModelOutputWithPast = self.model(
700
+ input_ids,
701
+ past_key_values=past_key_values,
702
+ attention_mask=attention_mask,
703
+ position_ids=position_ids,
704
+ inputs_embeds=inputs_embeds,
705
+ use_cache=use_cache,
706
+ **kwargs,
707
+ )
708
+ hidden_states = transformer_outputs.last_hidden_state
709
+
710
+ logits = self.qa_outputs(hidden_states)
711
+ start_logits, end_logits = logits.split(1, dim=-1)
712
+ start_logits = start_logits.squeeze(-1).contiguous()
713
+ end_logits = end_logits.squeeze(-1).contiguous()
714
+
715
+ total_loss = None
716
+ if start_positions is not None and end_positions is not None:
717
+ if len(start_positions.size()) > 1:
718
+ start_positions = start_positions.squeeze(-1)
719
+ if len(end_positions.size()) > 1:
720
+ end_positions = end_positions.squeeze(-1)
721
+ ignored_index = start_logits.size(1)
722
+ start_positions = start_positions.clamp(0, ignored_index).to(logits.device)
723
+ end_positions = end_positions.clamp(0, ignored_index).to(logits.device)
724
+
725
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
726
+ start_loss = loss_fct(start_logits, start_positions)
727
+ end_loss = loss_fct(end_logits, end_positions)
728
+ total_loss = (start_loss + end_loss) / 2
729
+
730
+ return QuestionAnsweringModelOutput(
731
+ loss=total_loss,
732
+ start_logits=start_logits,
733
+ end_logits=end_logits,
734
+ hidden_states=transformer_outputs.hidden_states,
735
+ attentions=transformer_outputs.attentions,
736
+ )
737
+
738
+ def get_input_embeddings(self):
739
+ return self.model.decoder.embed_tokens
740
+
741
+ def set_input_embeddings(self, value):
742
+ self.model.decoder.embed_tokens = value
743
+
744
+
745
+ __all__ = [
746
+ "OPTForCausalLM",
747
+ "OPTModel",
748
+ "OPTPreTrainedModel",
749
+ "OPTForSequenceClassification",
750
+ "OPTForQuestionAnswering",
751
+ ]
lib/python3.11/site-packages/transformers/models/ovis2/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_ovis2 import *
23
+ from .image_processing_ovis2 import *
24
+ from .image_processing_pil_ovis2 import *
25
+ from .modeling_ovis2 import *
26
+ from .processing_ovis2 import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (905 Bytes). View file
 
lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/configuration_ovis2.cpython-311.pyc ADDED
Binary file (4.89 kB). View file
 
lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/image_processing_ovis2.cpython-311.pyc ADDED
Binary file (16.9 kB). View file
 
lib/python3.11/site-packages/transformers/models/ovis2/__pycache__/image_processing_pil_ovis2.cpython-311.pyc ADDED
Binary file (14.1 kB). View file