assassinlike commited on
Commit
d481db7
·
verified ·
1 Parent(s): 740b865

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. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/__init__.py +28 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/configuration_bamba.py +210 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/modeling_bamba.py +1504 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/modular_bamba.py +1222 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/__init__.py +28 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py +127 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py +880 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py +177 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/__init__.py +30 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/configuration_big_bird.py +176 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/modeling_big_bird.py +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/modeling_flax_big_bird.py +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/tokenization_big_bird.py +303 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/tokenization_big_bird_fast.py +198 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/__init__.py +33 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/configuration_blip.py +317 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py +297 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip_fast.py +36 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py +1308 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_blip_text.py +968 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip.py +1709 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip_text.py +1122 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/processing_blip.py +125 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/__init__.py +28 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/configuration_convnextv2.py +118 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_convnextv2.py +447 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_tf_convnextv2.py +681 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/__init__.py +29 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/configuration_edgetam_video.py +435 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/modeling_edgetam_video.py +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/modular_edgetam_video.py +1243 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/__init__.py +30 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/configuration_gemma3.py +340 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/image_processing_gemma3.py +409 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/image_processing_gemma3_fast.py +258 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/modeling_gemma3.py +1341 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/modular_gemma3.py +1221 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/processing_gemma3.py +187 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/__init__.py +27 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/configuration_glm.py +152 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/modeling_glm.py +512 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/modular_glm.py +114 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/__init__.py +28 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/configuration_gpt_neox.py +206 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/modeling_gpt_neox.py +828 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/modular_gpt_neox.py +699 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/tokenization_gpt_neox_fast.py +224 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__init__.py +28 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py +167 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +755 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_bamba import *
22
+ from .modeling_bamba import *
23
+ from .processing_bamba 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/configuration_bamba.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 IBM and the HuggingFace Inc. team. 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
+ """Bamba model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class BambaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`BambaModel`]. It is used to instantiate a
27
+ BambaModel model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with defaults taken from [ibm-fms/Bamba-9.8b-2.2T-hf](https://huggingface.co/ibm-fms/Bamba-9.8b-2.2T-hf).
29
+
30
+ The BambaModel is a hybrid [mamba2](https://github.com/state-spaces/mamba) architecture with SwiGLU.
31
+ The checkpoints are jointly trained by IBM, Princeton, and UIUC.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 128000):
38
+ Vocabulary size of the Bamba model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`BambaModel`]
40
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
41
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
42
+ model has an output word embedding layer.
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 14336):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 8):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details, check out [this
57
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
68
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
69
+ integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
70
+ logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
71
+ sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
72
+ significantly.
73
+ pad_token_id (`int`, *optional*, defaults to 0):
74
+ The id of the padding token.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ The id of the "beginning-of-sequence" token.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ The id of the "end-of-sequence" token.
79
+ max_position_embeddings (`int`, *optional*, defaults to 262144):
80
+ Max cached sequence length for the model
81
+ attention_dropout (`float`, *optional*, defaults to 0.0):
82
+ The dropout ratio for the attention probabilities.
83
+ attn_layer_indices (`list`, *optional*):
84
+ Specifies the layer indices that will have full attention. Must contain values at most num_hidden_layers.
85
+ mamba_n_heads (`int`, *optional*, defaults to 128):
86
+ The number of mamba heads used in the v2 implementation.
87
+ mamba_d_head (`int`, *optional*, defaults to `"auto"`):
88
+ Head embedding dimension size
89
+ mamba_n_groups (`int`, *optional*, defaults to 1):
90
+ The number of the mamba groups used in the v2 implementation.
91
+ mamba_d_state (`int`, *optional*, defaults to 256):
92
+ The dimension the mamba state space latents
93
+ mamba_d_conv (`int`, *optional*, defaults to 4):
94
+ The size of the mamba convolution kernel
95
+ mamba_expand (`int`, *optional*, defaults to 2):
96
+ Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
97
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
98
+ The chunks in which to break the sequence when doing prefill/training
99
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
100
+ Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
101
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
102
+ Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
103
+ z_loss_coefficient (`float`, *optional*, defaults to 0.0):
104
+ Coefficient for auxiliary z-loss used to control logit growth during training
105
+
106
+ """
107
+
108
+ model_type = "bamba"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=128000,
114
+ tie_word_embeddings=False,
115
+ hidden_size=4096,
116
+ intermediate_size=14336,
117
+ num_hidden_layers=32,
118
+ num_attention_heads=32,
119
+ num_key_value_heads=8,
120
+ hidden_act="silu",
121
+ initializer_range=0.02,
122
+ rms_norm_eps=1e-5,
123
+ use_cache=True,
124
+ num_logits_to_keep=1,
125
+ pad_token_id=0,
126
+ bos_token_id=1,
127
+ eos_token_id=2,
128
+ max_position_embeddings=262144,
129
+ attention_dropout=0.0,
130
+ attn_layer_indices=None,
131
+ mamba_n_heads=128,
132
+ mamba_d_head="auto",
133
+ mamba_n_groups=1,
134
+ mamba_d_state=256,
135
+ mamba_d_conv=4,
136
+ mamba_expand=2,
137
+ mamba_chunk_size=256,
138
+ mamba_conv_bias=True,
139
+ mamba_proj_bias=False,
140
+ z_loss_coefficient=0.0,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.tie_word_embeddings = tie_word_embeddings
145
+ self.hidden_size = hidden_size
146
+ self.intermediate_size = intermediate_size
147
+ self.num_hidden_layers = num_hidden_layers
148
+ self.num_attention_heads = num_attention_heads
149
+ self.max_position_embeddings = max_position_embeddings
150
+ self.attention_dropout = attention_dropout
151
+ self.attention_bias = False
152
+ self.mlp_bias = False
153
+
154
+ # for backward compatibility
155
+ if num_key_value_heads is None:
156
+ num_key_value_heads = num_attention_heads
157
+
158
+ self.num_key_value_heads = num_key_value_heads
159
+ self.hidden_act = hidden_act
160
+ self.initializer_range = initializer_range
161
+ self.rms_norm_eps = rms_norm_eps
162
+
163
+ self.use_cache = use_cache
164
+ self.num_logits_to_keep = num_logits_to_keep
165
+
166
+ self.attn_layer_indices = attn_layer_indices
167
+ self.rope_theta = 10000.0
168
+ self.rope_scaling = None
169
+ self.partial_rotary_factor = 0.5
170
+
171
+ mamba_intermediate = mamba_expand * hidden_size
172
+
173
+ if mamba_intermediate % mamba_n_heads != 0:
174
+ raise ValueError("mamba_n_heads must divide mamba_expand * hidden_size")
175
+
176
+ # for the mamba_v2, must satisfy the following
177
+ if mamba_d_head == "auto":
178
+ mamba_d_head = mamba_intermediate // mamba_n_heads
179
+
180
+ if mamba_d_head * mamba_n_heads != mamba_intermediate:
181
+ raise ValueError("The dimensions for the Mamba head state do not match the model intermediate_size")
182
+
183
+ self.mamba_n_heads = mamba_n_heads
184
+ self.mamba_d_head = mamba_d_head
185
+ self.mamba_n_groups = mamba_n_groups
186
+ self.mamba_d_state = mamba_d_state
187
+ self.mamba_d_conv = mamba_d_conv
188
+ self.mamba_expand = mamba_expand
189
+ self.mamba_chunk_size = mamba_chunk_size
190
+ self.mamba_conv_bias = mamba_conv_bias
191
+ self.mamba_proj_bias = mamba_proj_bias
192
+ self.z_loss_coefficient = z_loss_coefficient
193
+
194
+ super().__init__(
195
+ pad_token_id=pad_token_id,
196
+ bos_token_id=bos_token_id,
197
+ eos_token_id=eos_token_id,
198
+ tie_word_embeddings=tie_word_embeddings,
199
+ **kwargs,
200
+ )
201
+
202
+ @property
203
+ def layers_block_type(self):
204
+ return [
205
+ "attention" if (self.attn_layer_indices and i in self.attn_layer_indices) else "mamba"
206
+ for i in range(self.num_hidden_layers)
207
+ ]
208
+
209
+
210
+ __all__ = ["BambaConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/modeling_bamba.py ADDED
@@ -0,0 +1,1504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/bamba/modular_bamba.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_bamba.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+
27
+ from typing import Any, Callable, Optional, TypedDict, Union
28
+
29
+ import torch
30
+ from torch import nn
31
+
32
+ from transformers.activations import ACT2FN
33
+
34
+ from ...cache_utils import Cache
35
+ from ...generation import GenerationMixin
36
+ from ...integrations import use_kernel_forward_from_hub
37
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
38
+ from ...modeling_layers import GradientCheckpointingLayer
39
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
44
+ from ...utils.deprecation import deprecate_kwarg
45
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_2_ssm_available
46
+ from .configuration_bamba import BambaConfig
47
+
48
+
49
+ if is_mamba_2_ssm_available():
50
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
51
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
52
+ else:
53
+ selective_state_update = None
54
+
55
+ if is_causal_conv1d_available():
56
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
57
+ else:
58
+ causal_conv1d_update, causal_conv1d_fn = None, None
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+
64
+ class BambaFlashAttentionKwargs(TypedDict, total=False):
65
+ """
66
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
67
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
68
+
69
+ Attributes:
70
+ cu_seq_lens_q (`torch.LongTensor`)
71
+ Gets cumulative sequence length for query state.
72
+ cu_seq_lens_k (`torch.LongTensor`)
73
+ Gets cumulative sequence length for key state.
74
+ max_length_q (`int`):
75
+ Maximum sequence length for query state.
76
+ max_length_k (`int`):
77
+ Maximum sequence length for key state.
78
+ seq_idx (`torch.IntTensor):
79
+ Index of each packed sequence.
80
+ """
81
+
82
+ cu_seq_lens_q: torch.LongTensor
83
+ cu_seq_lens_k: torch.LongTensor
84
+ max_length_q: int
85
+ max_length_k: int
86
+ seq_idx: torch.IntTensor
87
+
88
+
89
+ class HybridMambaAttentionDynamicCache:
90
+ """
91
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
92
+ (which has a constant shape regardless of seq_len).
93
+
94
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
95
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
96
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
97
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
98
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
99
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
100
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
101
+ """
102
+
103
+ is_compileable = False
104
+
105
+ def __init__(self, config: BambaConfig, batch_size, dtype=torch.float16, device=None):
106
+ self.layers_block_type = config.layers_block_type
107
+ self.has_previous_state = False # only used by mamba
108
+ conv_kernel_size = config.mamba_d_conv
109
+ ssm_state_size = config.mamba_d_state
110
+
111
+ self.conv_states = []
112
+ self.ssm_states = []
113
+ self.transformer_layers = []
114
+ for i in range(config.num_hidden_layers):
115
+ if self.layers_block_type[i] == "mamba":
116
+ self.conv_states += [
117
+ torch.zeros(
118
+ batch_size,
119
+ (config.mamba_expand * config.hidden_size + 2 * config.mamba_n_groups * ssm_state_size),
120
+ conv_kernel_size,
121
+ device=device,
122
+ dtype=dtype,
123
+ )
124
+ ]
125
+ self.ssm_states += [
126
+ torch.zeros(
127
+ batch_size,
128
+ config.mamba_n_heads,
129
+ config.mamba_d_head,
130
+ ssm_state_size,
131
+ device=device,
132
+ dtype=dtype,
133
+ )
134
+ ]
135
+ else:
136
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
137
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
138
+ self.transformer_layers.append(i)
139
+
140
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
141
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
142
+
143
+ def update(
144
+ self,
145
+ key_states: torch.Tensor,
146
+ value_states: torch.Tensor,
147
+ layer_idx: int,
148
+ cache_kwargs: Optional[dict[str, Any]] = None,
149
+ ) -> tuple[torch.Tensor, torch.Tensor]:
150
+ # Update the cache
151
+ if self.key_cache[layer_idx].shape[-1] == 0:
152
+ self.key_cache[layer_idx] = key_states
153
+ self.value_cache[layer_idx] = value_states
154
+ else:
155
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
156
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
157
+
158
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
159
+
160
+ def reorder_cache(self, beam_idx: torch.LongTensor):
161
+ """Reorders the cache for beam search, given the selected beam indices."""
162
+ for layer_idx in range(len(self.key_cache)):
163
+ device = self.key_cache[layer_idx].device
164
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
165
+ device = self.value_cache[layer_idx].device
166
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
167
+
168
+ device = self.conv_states[layer_idx].device
169
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
170
+ device = self.ssm_states[layer_idx].device
171
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
172
+
173
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
174
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
175
+ # take any layer that contains cache and not empty tensor
176
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
177
+ if len(self.key_cache) <= layer_idx:
178
+ return 0
179
+ return self.key_cache[layer_idx].shape[-2]
180
+
181
+
182
+ class BambaRotaryEmbedding(nn.Module):
183
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
184
+
185
+ def __init__(self, config: BambaConfig, device=None):
186
+ super().__init__()
187
+ # BC: "rope_type" was originally "type"
188
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
189
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
190
+ else:
191
+ self.rope_type = "default"
192
+ self.max_seq_len_cached = config.max_position_embeddings
193
+ self.original_max_seq_len = config.max_position_embeddings
194
+
195
+ self.config = config
196
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
197
+
198
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
199
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
200
+ self.original_inv_freq = self.inv_freq
201
+
202
+ @torch.no_grad()
203
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
204
+ def forward(self, x, position_ids):
205
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
206
+ position_ids_expanded = position_ids[:, None, :].float()
207
+
208
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+ cos = emb.cos() * self.attention_scaling
213
+ sin = emb.sin() * self.attention_scaling
214
+
215
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
216
+
217
+
218
+ def rotate_half(x):
219
+ """Rotates half the hidden dims of the input."""
220
+ x1 = x[..., : x.shape[-1] // 2]
221
+ x2 = x[..., x.shape[-1] // 2 :]
222
+ return torch.cat((-x2, x1), dim=-1)
223
+
224
+
225
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
226
+ """
227
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
228
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
229
+ """
230
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
231
+ if n_rep == 1:
232
+ return hidden_states
233
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
234
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
235
+
236
+
237
+ def eager_attention_forward(
238
+ module: nn.Module,
239
+ query: torch.Tensor,
240
+ key: torch.Tensor,
241
+ value: torch.Tensor,
242
+ attention_mask: Optional[torch.Tensor],
243
+ scaling: float,
244
+ dropout: float = 0.0,
245
+ **kwargs: Unpack[TransformersKwargs],
246
+ ):
247
+ key_states = repeat_kv(key, module.num_key_value_groups)
248
+ value_states = repeat_kv(value, module.num_key_value_groups)
249
+
250
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
251
+ if attention_mask is not None:
252
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
253
+ attn_weights = attn_weights + causal_mask
254
+
255
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
256
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
257
+ attn_output = torch.matmul(attn_weights, value_states)
258
+ attn_output = attn_output.transpose(1, 2).contiguous()
259
+
260
+ return attn_output, attn_weights
261
+
262
+
263
+ # Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_emb
264
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
265
+ """Applies Rotary Position Embedding to the query and key tensors.
266
+
267
+ Removes the interleaving of cos and sin from GLM
268
+
269
+ Args:
270
+ q (`torch.Tensor`): The query tensor.
271
+ k (`torch.Tensor`): The key tensor.
272
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
273
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
274
+ position_ids (`torch.Tensor`, *optional*):
275
+ Deprecated and unused.
276
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
277
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
278
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
279
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
280
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
281
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
282
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
283
+ Returns:
284
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
285
+ """
286
+ cos = cos.unsqueeze(unsqueeze_dim)
287
+ sin = sin.unsqueeze(unsqueeze_dim)
288
+
289
+ # Keep half or full tensor for later concatenation
290
+ rotary_dim = cos.shape[-1]
291
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
292
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
293
+
294
+ # Apply rotary embeddings on the first half or full tensor
295
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
296
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
297
+
298
+ # Concatenate back to full shape
299
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
300
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
301
+ return q_embed, k_embed
302
+
303
+
304
+ class BambaAttention(nn.Module):
305
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
306
+
307
+ def __init__(self, config: BambaConfig, layer_idx: int):
308
+ super().__init__()
309
+ self.config = config
310
+ self.layer_idx = layer_idx
311
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
312
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
313
+ self.scaling = self.head_dim**-0.5
314
+ self.attention_dropout = config.attention_dropout
315
+ self.is_causal = True
316
+
317
+ self.q_proj = nn.Linear(
318
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
319
+ )
320
+ self.k_proj = nn.Linear(
321
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
322
+ )
323
+ self.v_proj = nn.Linear(
324
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
325
+ )
326
+ self.o_proj = nn.Linear(
327
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
328
+ )
329
+
330
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
331
+ def forward(
332
+ self,
333
+ hidden_states: torch.Tensor,
334
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
335
+ attention_mask: Optional[torch.Tensor],
336
+ past_key_values: Optional[Cache] = None,
337
+ cache_position: Optional[torch.LongTensor] = None,
338
+ **kwargs: Unpack[TransformersKwargs],
339
+ ) -> tuple[torch.Tensor, torch.Tensor]:
340
+ input_shape = hidden_states.shape[:-1]
341
+ hidden_shape = (*input_shape, -1, self.head_dim)
342
+
343
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
344
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
345
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
346
+
347
+ cos, sin = position_embeddings
348
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
349
+
350
+ if past_key_values is not None:
351
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
352
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
353
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
354
+
355
+ attention_interface: Callable = eager_attention_forward
356
+ if self.config._attn_implementation != "eager":
357
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
358
+
359
+ attn_output, attn_weights = attention_interface(
360
+ self,
361
+ query_states,
362
+ key_states,
363
+ value_states,
364
+ attention_mask,
365
+ dropout=0.0 if not self.training else self.attention_dropout,
366
+ scaling=self.scaling,
367
+ **kwargs,
368
+ )
369
+
370
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
371
+ attn_output = self.o_proj(attn_output)
372
+ return attn_output, attn_weights
373
+
374
+
375
+ class BambaRMSNormGated(torch.nn.Module):
376
+ def __init__(self, hidden_size, eps=1e-6):
377
+ super().__init__()
378
+ self.weight = nn.Parameter(torch.ones(hidden_size))
379
+ self.variance_epsilon = eps
380
+
381
+ def forward(self, hidden_states, gate=None):
382
+ input_dtype = hidden_states.dtype
383
+ hidden_states = hidden_states.to(torch.float32)
384
+
385
+ if gate is not None:
386
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
387
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
388
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
389
+
390
+ return self.weight * hidden_states.to(input_dtype)
391
+
392
+
393
+ # Helper methods for segment sum computation
394
+
395
+
396
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
397
+ """
398
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
399
+
400
+ Assumes that we only have tensors of either size 4 or 3
401
+ """
402
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
403
+
404
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
405
+
406
+
407
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
408
+ """
409
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
410
+ simultaneously splitting it into chunk sequences.
411
+
412
+ Assumes that we only have tensors of either size 4 or 3
413
+ """
414
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
415
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
416
+
417
+ if len(input_tensor.shape) == 3:
418
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
419
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
420
+ else:
421
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
422
+ return input_tensor.reshape(
423
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
424
+ )
425
+
426
+
427
+ def segment_sum(input_tensor):
428
+ """
429
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
430
+ """
431
+ chunk_size = input_tensor.size(-1)
432
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
433
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
434
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
435
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
436
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
437
+ input_tensor = input_tensor.masked_fill(~mask, 0)
438
+ # 3. compute actual cumsum
439
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
440
+
441
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
442
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
443
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
444
+ return tensor_segsum
445
+
446
+
447
+ is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
448
+
449
+
450
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
451
+ """
452
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
453
+ """
454
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
455
+ dtype = hidden_states.dtype
456
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
457
+
458
+ return hidden_states
459
+
460
+
461
+ # Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
462
+ class BambaMixer(nn.Module):
463
+ """
464
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
465
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
466
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
467
+ and is why Mamba is called **selective** state spaces)
468
+
469
+ The are a few differences between this and Mamba2Mixer:
470
+ - The variable use_precomputed_states is slightly different due to the hybrid cache structure
471
+ - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
472
+ - Some extra variables that our layer doesn't need have been removed
473
+ - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
474
+ """
475
+
476
+ def __init__(self, config: BambaConfig, layer_idx: int):
477
+ super().__init__()
478
+ self.num_heads = config.mamba_n_heads
479
+ self.hidden_size = config.hidden_size
480
+ self.ssm_state_size = config.mamba_d_state
481
+ self.conv_kernel_size = config.mamba_d_conv
482
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
483
+ self.layer_idx = layer_idx
484
+ self.use_conv_bias = config.mamba_conv_bias
485
+ self.activation = config.hidden_act
486
+ self.act = ACT2FN[config.hidden_act]
487
+ self.use_bias = config.mamba_proj_bias
488
+
489
+ self.layer_norm_epsilon = config.rms_norm_eps
490
+
491
+ self.n_groups = config.mamba_n_groups
492
+ self.head_dim = config.mamba_d_head
493
+ self.chunk_size = config.mamba_chunk_size
494
+
495
+ # FIXME:
496
+ self.time_step_limit = (0.0, float("inf"))
497
+ self.time_step_min = 0.001
498
+ self.time_step_max = 0.1
499
+
500
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
501
+ self.conv1d = nn.Conv1d(
502
+ in_channels=self.conv_dim,
503
+ out_channels=self.conv_dim,
504
+ bias=config.mamba_conv_bias,
505
+ kernel_size=self.conv_kernel_size,
506
+ groups=self.conv_dim,
507
+ padding=self.conv_kernel_size - 1,
508
+ )
509
+
510
+ # projection of the input hidden states
511
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
512
+ self.in_proj = nn.Linear(
513
+ self.hidden_size,
514
+ projection_size,
515
+ bias=self.use_bias,
516
+ )
517
+ # selective projection used to make dt, B and C input dependent
518
+
519
+ # time step projection (discretization)
520
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
521
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
522
+
523
+ # S4D real initialization. These are not discretized!
524
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
525
+ A = torch.arange(1, self.num_heads + 1)
526
+ self.A_log = nn.Parameter(torch.log(A))
527
+ self.norm = BambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
528
+ self.D = nn.Parameter(torch.ones(self.num_heads))
529
+
530
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
531
+
532
+ if not is_fast_path_available:
533
+ logger.warning_once(
534
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
535
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
536
+ " https://github.com/Dao-AILab/causal-conv1d"
537
+ )
538
+ else:
539
+ logger.warning_once("The fast path for Bamba will be used when running the model on a GPU")
540
+
541
+ def cuda_kernels_forward(
542
+ self,
543
+ hidden_states: torch.Tensor,
544
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
545
+ cache_position: Optional[torch.LongTensor] = None,
546
+ attention_mask: Optional[torch.Tensor] = None,
547
+ seq_idx: Optional[torch.IntTensor] = None,
548
+ ):
549
+ # 1. Gated MLP's linear projection
550
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
551
+ projected_states = self.in_proj(hidden_states)
552
+
553
+ # Set up dimensions for reshapes later
554
+ batch_size, seq_len, _ = hidden_states.shape
555
+ groups_time_state_size = self.n_groups * self.ssm_state_size
556
+
557
+ use_precomputed_states = (
558
+ cache_params is not None
559
+ and cache_params.has_previous_state
560
+ and seq_len == 1
561
+ and cache_params.conv_states[self.layer_idx].shape[0]
562
+ == cache_params.ssm_states[self.layer_idx].shape[0]
563
+ == batch_size
564
+ and cache_position is not None
565
+ and cache_position[0] > 0
566
+ )
567
+
568
+ # getting projected states from cache if it exists
569
+ if use_precomputed_states:
570
+ gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
571
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
572
+ )
573
+
574
+ # 2. Convolution sequence transformation
575
+ hidden_states_B_C = causal_conv1d_update(
576
+ hidden_states_B_C,
577
+ cache_params.conv_states[self.layer_idx],
578
+ self.conv1d.weight.squeeze(1),
579
+ self.conv1d.bias,
580
+ self.activation,
581
+ )
582
+
583
+ hidden_states, B, C = torch.split(
584
+ hidden_states_B_C,
585
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
586
+ dim=-1,
587
+ )
588
+
589
+ # 3. SSM transformation
590
+ A = -torch.exp(self.A_log.float()) # (nheads,)
591
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
592
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
593
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
594
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
595
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
596
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
597
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
598
+ hidden_states = selective_state_update(
599
+ cache_params.ssm_states[self.layer_idx],
600
+ hidden_states_reshaped,
601
+ dt,
602
+ A,
603
+ B,
604
+ C,
605
+ D,
606
+ z=None,
607
+ dt_bias=dt_bias,
608
+ dt_softplus=True,
609
+ )
610
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
611
+ hidden_states = self.norm(hidden_states, gate)
612
+
613
+ # 4. Final linear projection
614
+ out = self.out_proj(hidden_states)[:, None, ...]
615
+ # Fused calculations or step by step if no initialized cache is found
616
+ else:
617
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
618
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
619
+
620
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
621
+ if self.training and cache_params is None:
622
+ out = mamba_split_conv1d_scan_combined(
623
+ projected_states,
624
+ self.conv1d.weight.squeeze(1),
625
+ self.conv1d.bias,
626
+ self.dt_bias,
627
+ A,
628
+ D=self.D,
629
+ chunk_size=self.chunk_size,
630
+ seq_idx=seq_idx,
631
+ activation=self.activation,
632
+ rmsnorm_weight=self.norm.weight,
633
+ rmsnorm_eps=self.norm.variance_epsilon,
634
+ outproj_weight=self.out_proj.weight,
635
+ outproj_bias=self.out_proj.bias,
636
+ headdim=self.head_dim,
637
+ ngroups=self.n_groups,
638
+ norm_before_gate=False,
639
+ return_final_states=False,
640
+ **dt_limit_kwargs,
641
+ )
642
+
643
+ else:
644
+ gate, hidden_states_B_C, dt = projected_states.split(
645
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
646
+ )
647
+
648
+ # 2. Convolution sequence transformation
649
+ # Init cache
650
+ if cache_params is not None:
651
+ # storing the states
652
+ # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv
653
+ # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise.
654
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
655
+ conv_states = nn.functional.pad(
656
+ hidden_states_B_C_transposed,
657
+ (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
658
+ )
659
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
660
+
661
+ if self.activation not in ["silu", "swish"]:
662
+ hidden_states_B_C = self.act(
663
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
664
+ )
665
+ else:
666
+ hidden_states_B_C = causal_conv1d_fn(
667
+ x=hidden_states_B_C.transpose(1, 2),
668
+ weight=self.conv1d.weight.squeeze(1),
669
+ bias=self.conv1d.bias,
670
+ activation=self.activation,
671
+ seq_idx=seq_idx,
672
+ ).transpose(1, 2)
673
+
674
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
675
+ hidden_states, B, C = torch.split(
676
+ hidden_states_B_C,
677
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
678
+ dim=-1,
679
+ )
680
+
681
+ # 3. SSM transformation
682
+ scan_output, ssm_state = mamba_chunk_scan_combined(
683
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
684
+ dt,
685
+ A,
686
+ B.view(batch_size, seq_len, self.n_groups, -1),
687
+ C.view(batch_size, seq_len, self.n_groups, -1),
688
+ chunk_size=self.chunk_size,
689
+ D=self.D,
690
+ z=None,
691
+ seq_idx=seq_idx,
692
+ return_final_states=True,
693
+ dt_bias=self.dt_bias,
694
+ dt_softplus=True,
695
+ **dt_limit_kwargs,
696
+ )
697
+
698
+ # Init cache
699
+ if ssm_state is not None and cache_params is not None:
700
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
701
+
702
+ scan_output = scan_output.view(batch_size, seq_len, -1)
703
+ # Multiply "gate" branch and apply extra normalization layer
704
+ scan_output = self.norm(scan_output, gate)
705
+
706
+ # 4. Final linear projection
707
+ out = self.out_proj(scan_output)
708
+ return out
709
+
710
+ # fmt: off
711
+ def torch_forward(
712
+ self,
713
+ input_states,
714
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
715
+ cache_position: Optional[torch.LongTensor] = None,
716
+ attention_mask: Optional[torch.Tensor] = None,
717
+ ):
718
+ batch_size, seq_len, _ = input_states.shape
719
+ dtype = input_states.dtype
720
+
721
+ # 1. Gated MLP's linear projection
722
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
723
+ projected_states = self.in_proj(input_states)
724
+ gate, hidden_states_B_C, dt = projected_states.split(
725
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
726
+ )
727
+
728
+ use_precomputed_states = (
729
+ cache_params is not None
730
+ and cache_params.has_previous_state
731
+ and seq_len == 1
732
+ and cache_params.conv_states[self.layer_idx].shape[0]
733
+ == cache_params.ssm_states[self.layer_idx].shape[0]
734
+ == batch_size
735
+ and cache_position is not None
736
+ and cache_position[0] > 0
737
+ )
738
+
739
+ # 2. Convolution sequence transformation
740
+ if use_precomputed_states:
741
+ cache_params.conv_states[self.layer_idx] = cache_params.conv_states[self.layer_idx].roll(shifts=-1, dims=-1)
742
+ cache_params.conv_states[self.layer_idx][:, :, -1] = hidden_states_B_C[:, 0, :].to(cache_params.conv_states[self.layer_idx].device)
743
+
744
+ # We need to guarantee that anything regarding the cache is on the same device
745
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
746
+
747
+ hidden_states_B_C = torch.sum(
748
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
749
+ )
750
+ if self.use_conv_bias:
751
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
752
+ hidden_states_B_C = self.act(hidden_states_B_C)
753
+ else:
754
+ # Init cache
755
+ if cache_params is not None:
756
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
757
+ conv_states = nn.functional.pad(
758
+ hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
759
+ )
760
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
761
+
762
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
763
+
764
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
765
+ hidden_states, B, C = torch.split(
766
+ hidden_states_B_C,
767
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
768
+ dim=-1
769
+ )
770
+
771
+ # 3. SSM transformation
772
+ A = -torch.exp(self.A_log.float()) # [num_heads]
773
+ if use_precomputed_states:
774
+ # We need to guarantee that anything regarding the cache is on the same device
775
+ cache_device = cache_params.ssm_states[self.layer_idx].device
776
+
777
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
778
+ # for batched generation
779
+ dt = dt[:, 0, :][:, None, ...]
780
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
781
+ # [num_heads] -> [num_heads, head_dim]
782
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
783
+
784
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
785
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
786
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
787
+ # [bsz, num_heads, head_dim, state_size]
788
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
789
+
790
+ # Discretize B
791
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
792
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
793
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
794
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
795
+ B = B.reshape(batch_size, -1, B.shape[-1])
796
+ # [bsz, num_heads, head_dim, state_size]
797
+ dB = dt[..., None] * B[..., None, :]
798
+
799
+ # Discretize x into dB
800
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
801
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
802
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
803
+
804
+ # State calculation
805
+ cache_params.ssm_states[self.layer_idx].copy_(
806
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
807
+ )
808
+
809
+ # Subsequent output
810
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
811
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
812
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
813
+ C = C.reshape(batch_size, -1, C.shape[-1])
814
+ # [bsz, num_heads, head_dim]
815
+
816
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
817
+ # Reshape ssm_states to merge the first two dimensions
818
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
819
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
820
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
821
+ y = y.view(batch_size, self.num_heads, self.head_dim)
822
+
823
+ # D skip connection
824
+ # [num_heads] -> [num_heads, head_dim]
825
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
826
+ y = (y + hidden_states * D).to(y.dtype)
827
+
828
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
829
+ y = y.reshape(batch_size, -1)[:, None, ...]
830
+ else:
831
+ # begin ssd naive implementation without einsums
832
+ dt = nn.functional.softplus(dt + self.dt_bias)
833
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
834
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
835
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
836
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
837
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
838
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
839
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
840
+
841
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
842
+
843
+ # Discretize x and A
844
+ hidden_states = hidden_states * dt[..., None]
845
+ A = A.to(hidden_states.dtype) * dt
846
+
847
+ # Rearrange into blocks/chunks
848
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
849
+
850
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
851
+ A = A.permute(0, 3, 1, 2)
852
+ A_cumsum = torch.cumsum(A, dim=-1)
853
+
854
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
855
+ # This is the analog of a causal mask
856
+ L = torch.exp(segment_sum(A))
857
+
858
+ # Contraction of C and B to get G (attention-weights like)
859
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
860
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
861
+
862
+ # Compute M, equivalent to applying attention mask to weights
863
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
864
+ M = M_intermediate.sum(dim=-1)
865
+
866
+ # Compute Y_diag (apply to values)
867
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
868
+
869
+ # 2. Compute the state for each intra-chunk
870
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
871
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
872
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
873
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
874
+
875
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
876
+ # (middle term of factorization of off-diag blocks; A terms)
877
+ if use_precomputed_states:
878
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
879
+ else:
880
+ previous_states = torch.zeros_like(states[:, :1])
881
+ states = torch.cat([previous_states, states], dim=1)
882
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
883
+ decay_chunk = decay_chunk.transpose(1, 3)
884
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
885
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
886
+
887
+ # 4. Compute state -> output conversion per chunk
888
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
889
+ state_decay_out = torch.exp(A_cumsum)
890
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
891
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
892
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
893
+
894
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
895
+ y = Y_diag + Y_off
896
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
897
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
898
+
899
+ y = y + D_residual
900
+ # Cutting off padded chunks
901
+ if pad_size > 0:
902
+ y = y[:, :seq_len, :, :]
903
+ y = y.reshape(batch_size, seq_len, -1)
904
+
905
+ # Init cache
906
+ if ssm_state is not None and cache_params is not None:
907
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
908
+
909
+ scan_output = self.norm(y, gate)
910
+
911
+ # end ssd naive
912
+
913
+ # 4. Final linear projection
914
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
915
+ return contextualized_states
916
+ # fmt: on
917
+
918
+ def forward(
919
+ self,
920
+ hidden_states,
921
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
922
+ cache_position: Optional[torch.LongTensor] = None,
923
+ attention_mask: Optional[torch.Tensor] = None,
924
+ seq_idx: Optional[torch.IntTensor] = None,
925
+ **kwargs,
926
+ ):
927
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
928
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, seq_idx)
929
+ if seq_idx is not None:
930
+ raise NotImplementedError(
931
+ "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`"
932
+ )
933
+ dtype = hidden_states.dtype
934
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
935
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
936
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
937
+
938
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
939
+
940
+
941
+ class BambaMLP(nn.Module):
942
+ def __init__(self, config):
943
+ super().__init__()
944
+ self.config = config
945
+ self.hidden_size = config.hidden_size
946
+ self.intermediate_size = config.intermediate_size
947
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
948
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
949
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
950
+ self.act_fn = ACT2FN[config.hidden_act]
951
+
952
+ def forward(self, x):
953
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
954
+ return down_proj
955
+
956
+
957
+ @use_kernel_forward_from_hub("RMSNorm")
958
+ class BambaRMSNorm(nn.Module):
959
+ def __init__(self, hidden_size, eps=1e-6):
960
+ """
961
+ BambaRMSNorm is equivalent to T5LayerNorm
962
+ """
963
+ super().__init__()
964
+ self.weight = nn.Parameter(torch.ones(hidden_size))
965
+ self.variance_epsilon = eps
966
+
967
+ def forward(self, hidden_states):
968
+ input_dtype = hidden_states.dtype
969
+ hidden_states = hidden_states.to(torch.float32)
970
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
971
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
972
+ return self.weight * hidden_states.to(input_dtype)
973
+
974
+ def extra_repr(self):
975
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
976
+
977
+
978
+ class BambaDecoderLayer(GradientCheckpointingLayer):
979
+ def __init__(self, config: BambaConfig, layer_idx: int, layer_type: str = "mamba"):
980
+ super().__init__()
981
+
982
+ num_experts = 1
983
+ ffn_layer_class = BambaMLP if num_experts == 1 else None
984
+ self.feed_forward = ffn_layer_class(config)
985
+ self.input_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
986
+ self.pre_ff_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
987
+
988
+ self.layer_type = layer_type
989
+ if layer_type == "mamba":
990
+ self.mamba = BambaMixer(config=config, layer_idx=layer_idx)
991
+ elif layer_type == "attention":
992
+ self.self_attn = BambaAttention(config, layer_idx)
993
+ else:
994
+ raise ValueError("Invalid layer_type")
995
+
996
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
997
+ def forward(
998
+ self,
999
+ hidden_states: torch.Tensor,
1000
+ attention_mask: Optional[torch.Tensor] = None,
1001
+ position_ids: Optional[torch.LongTensor] = None,
1002
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1003
+ output_attentions: Optional[bool] = False,
1004
+ use_cache: Optional[bool] = False,
1005
+ cache_position: Optional[torch.LongTensor] = None,
1006
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1007
+ **kwargs: Unpack[BambaFlashAttentionKwargs],
1008
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
1009
+ """
1010
+ Args:
1011
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1012
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1013
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1014
+ past_key_values (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
1015
+ output_attentions (`bool`, *optional*):
1016
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1017
+ returned tensors for more detail.
1018
+ use_cache (`bool`, *optional*):
1019
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1020
+ (see `past_key_values`).
1021
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1022
+ Indices depicting the position of the input sequence tokens in the sequence.
1023
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
1024
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
1025
+ with `head_dim` being the embedding dimension of each attention head.
1026
+ kwargs (`dict`, *optional*):
1027
+ Arbitrary kwargs. Can be used to provide `BambaFlashAttentionKwargs` for
1028
+ padding-free training and/or improve torch.compile performance.
1029
+ """
1030
+
1031
+ residual = hidden_states
1032
+
1033
+ hidden_states = self.input_layernorm(hidden_states)
1034
+
1035
+ # this is a hybrid decoder layer
1036
+ if self.layer_type == "mamba":
1037
+ hidden_states = self.mamba(
1038
+ hidden_states=hidden_states,
1039
+ cache_params=past_key_values,
1040
+ cache_position=cache_position,
1041
+ attention_mask=attention_mask,
1042
+ **kwargs,
1043
+ )
1044
+ self_attn_weights = None
1045
+ elif self.layer_type == "attention":
1046
+ hidden_states, self_attn_weights = self.self_attn(
1047
+ hidden_states=hidden_states,
1048
+ attention_mask=attention_mask,
1049
+ position_ids=position_ids,
1050
+ past_key_values=past_key_values,
1051
+ output_attentions=output_attentions,
1052
+ use_cache=use_cache,
1053
+ cache_position=cache_position,
1054
+ position_embeddings=position_embeddings,
1055
+ **kwargs,
1056
+ )
1057
+
1058
+ # residual connection after attention
1059
+ hidden_states = residual + hidden_states
1060
+
1061
+ # feed-forward
1062
+ residual = hidden_states
1063
+ hidden_states = self.pre_ff_layernorm(hidden_states)
1064
+ hidden_states = self.feed_forward(hidden_states)
1065
+ hidden_states = residual + hidden_states
1066
+
1067
+ outputs = (hidden_states,)
1068
+
1069
+ if output_attentions:
1070
+ outputs += (self_attn_weights,)
1071
+
1072
+ return outputs
1073
+
1074
+
1075
+ @auto_docstring
1076
+ class BambaPreTrainedModel(PreTrainedModel):
1077
+ config: BambaConfig
1078
+ base_model_prefix = "model"
1079
+ supports_gradient_checkpointing = True
1080
+ _no_split_modules = ["BambaDecoderLayer"]
1081
+ _skip_keys_device_placement = "past_key_values"
1082
+ _supports_flash_attn = True
1083
+ _supports_sdpa = True
1084
+ # Note: only supports HybridMambaAttentionDynamicCache
1085
+ _is_stateful = True
1086
+
1087
+ def _init_weights(self, module):
1088
+ super()._init_weights(module)
1089
+ if isinstance(module, BambaMixer):
1090
+ module.dt_bias.data.fill_(1.0)
1091
+ module.A_log.data = torch.log(torch.arange(1, module.num_heads + 1))
1092
+ module.D.data.fill_(1.0)
1093
+
1094
+
1095
+ @auto_docstring
1096
+ class BambaModel(BambaPreTrainedModel):
1097
+ def __init__(self, config: BambaConfig):
1098
+ super().__init__(config)
1099
+ self.padding_idx = config.pad_token_id
1100
+ self.vocab_size = config.vocab_size
1101
+
1102
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1103
+ decoder_layers = []
1104
+ for i in range(config.num_hidden_layers):
1105
+ decoder_layers.append(BambaDecoderLayer(config, layer_idx=i, layer_type=config.layers_block_type[i]))
1106
+ self.layers = nn.ModuleList(decoder_layers)
1107
+
1108
+ self._attn_implementation = config._attn_implementation
1109
+ self.final_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1110
+ self.rotary_emb = BambaRotaryEmbedding(config=config)
1111
+
1112
+ self.gradient_checkpointing = False
1113
+ # Initialize weights and apply final processing
1114
+ self.post_init()
1115
+
1116
+ @can_return_tuple
1117
+ @auto_docstring
1118
+ def forward(
1119
+ self,
1120
+ input_ids: Optional[torch.LongTensor] = None,
1121
+ attention_mask: Optional[torch.Tensor] = None,
1122
+ position_ids: Optional[torch.LongTensor] = None,
1123
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1124
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1125
+ use_cache: Optional[bool] = None,
1126
+ output_attentions: Optional[bool] = None,
1127
+ output_hidden_states: Optional[bool] = None,
1128
+ cache_position: Optional[torch.LongTensor] = None,
1129
+ **kwargs: Unpack[BambaFlashAttentionKwargs],
1130
+ ) -> BaseModelOutputWithPast:
1131
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1132
+ output_hidden_states = (
1133
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1134
+ )
1135
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1136
+
1137
+ if (input_ids is None) ^ (inputs_embeds is not None):
1138
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1139
+
1140
+ if self.gradient_checkpointing and self.training and use_cache:
1141
+ logger.warning_once(
1142
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1143
+ )
1144
+ use_cache = False
1145
+
1146
+ if inputs_embeds is None:
1147
+ inputs_embeds = self.embed_tokens(input_ids)
1148
+ hidden_states = inputs_embeds
1149
+
1150
+ if use_cache and past_key_values is None:
1151
+ logger.warning_once(
1152
+ "Bamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was "
1153
+ "provided, so no cache will be returned."
1154
+ )
1155
+
1156
+ if cache_position is None:
1157
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1158
+ if position_ids is None:
1159
+ position_ids = cache_position.unsqueeze(0)
1160
+
1161
+ causal_mask = self._update_causal_mask(
1162
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1163
+ )
1164
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1165
+
1166
+ # create position embeddings to be shared across the decoder layers
1167
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1168
+
1169
+ all_hidden_states = () if output_hidden_states else None
1170
+ all_self_attns = () if output_attentions else None
1171
+
1172
+ for decoder_layer in self.layers:
1173
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1174
+ layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask
1175
+
1176
+ if output_hidden_states:
1177
+ all_hidden_states += (hidden_states,)
1178
+
1179
+ layer_outputs = decoder_layer(
1180
+ hidden_states,
1181
+ attention_mask=layer_mask,
1182
+ position_ids=position_ids,
1183
+ past_key_values=past_key_values,
1184
+ output_attentions=output_attentions,
1185
+ use_cache=use_cache,
1186
+ cache_position=cache_position,
1187
+ position_embeddings=position_embeddings,
1188
+ **kwargs,
1189
+ )
1190
+
1191
+ hidden_states = layer_outputs[0]
1192
+
1193
+ if output_attentions:
1194
+ if layer_outputs[1] is not None:
1195
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1196
+ all_self_attns += (layer_outputs[1],)
1197
+
1198
+ hidden_states = self.final_layernorm(hidden_states)
1199
+
1200
+ # add hidden states from the last decoder layer
1201
+ if output_hidden_states:
1202
+ all_hidden_states += (hidden_states,)
1203
+
1204
+ if past_key_values and not past_key_values.has_previous_state:
1205
+ past_key_values.has_previous_state = True
1206
+
1207
+ next_cache = None if not use_cache else past_key_values
1208
+
1209
+ return BaseModelOutputWithPast(
1210
+ last_hidden_state=hidden_states,
1211
+ past_key_values=next_cache,
1212
+ hidden_states=all_hidden_states,
1213
+ attentions=all_self_attns,
1214
+ )
1215
+
1216
+ def _update_causal_mask(
1217
+ self,
1218
+ attention_mask: torch.Tensor,
1219
+ input_tensor: torch.Tensor,
1220
+ cache_position: torch.Tensor,
1221
+ past_key_values: HybridMambaAttentionDynamicCache,
1222
+ output_attentions: bool,
1223
+ ):
1224
+ if self.config._attn_implementation == "flash_attention_2":
1225
+ if attention_mask is not None and 0.0 in attention_mask:
1226
+ return attention_mask
1227
+ return None
1228
+
1229
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1230
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1231
+ # to infer the attention mask.
1232
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1233
+
1234
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1235
+ if self.config._attn_implementation == "sdpa" and not output_attentions:
1236
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1237
+ attention_mask,
1238
+ inputs_embeds=input_tensor,
1239
+ past_key_values_length=past_seen_tokens,
1240
+ is_training=self.training,
1241
+ ):
1242
+ return None
1243
+
1244
+ dtype = input_tensor.dtype
1245
+ sequence_length = input_tensor.shape[1]
1246
+ target_length = (
1247
+ attention_mask.shape[-1]
1248
+ if isinstance(attention_mask, torch.Tensor)
1249
+ else past_seen_tokens + sequence_length + 1
1250
+ )
1251
+
1252
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1253
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1254
+ attention_mask,
1255
+ sequence_length=sequence_length,
1256
+ target_length=target_length,
1257
+ dtype=dtype,
1258
+ cache_position=cache_position,
1259
+ batch_size=input_tensor.shape[0],
1260
+ )
1261
+
1262
+ if (
1263
+ self.config._attn_implementation == "sdpa"
1264
+ and attention_mask is not None
1265
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
1266
+ and not output_attentions
1267
+ ):
1268
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1269
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1270
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1271
+ min_dtype = torch.finfo(dtype).min
1272
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1273
+
1274
+ return causal_mask
1275
+
1276
+ @staticmethod
1277
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1278
+ attention_mask: torch.Tensor,
1279
+ sequence_length: int,
1280
+ target_length: int,
1281
+ dtype: torch.dtype,
1282
+ cache_position: torch.Tensor,
1283
+ batch_size: int,
1284
+ **kwargs,
1285
+ ):
1286
+ """
1287
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1288
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1289
+
1290
+ Args:
1291
+ attention_mask (`torch.Tensor`):
1292
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1293
+ `(batch_size, 1, query_length, key_value_length)`.
1294
+ sequence_length (`int`):
1295
+ The sequence length being processed.
1296
+ target_length (`int`):
1297
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1298
+ to account for the 0 padding, the part of the cache that is not filled yet.
1299
+ dtype (`torch.dtype`):
1300
+ The dtype to use for the 4D attention mask.
1301
+ cache_position (`torch.Tensor`):
1302
+ Indices depicting the position of the input sequence tokens in the sequence.
1303
+ batch_size (`torch.Tensor`):
1304
+ Batch size.
1305
+ """
1306
+ if attention_mask is not None and attention_mask.dim() == 4:
1307
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1308
+ causal_mask = attention_mask
1309
+ else:
1310
+ min_dtype = torch.finfo(dtype).min
1311
+ causal_mask = torch.full(
1312
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1313
+ )
1314
+ if sequence_length != 1:
1315
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1316
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
1317
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1318
+ if attention_mask is not None:
1319
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1320
+ mask_length = attention_mask.shape[-1]
1321
+ padding_attention_mask = (attention_mask[:, None, None, :] == attention_mask[:, None, :, None])[
1322
+ :, :, -sequence_length:, :
1323
+ ].to(dtype)
1324
+ padding_mask = causal_mask[:, :, :, :mask_length] + padding_attention_mask
1325
+ padding_mask = padding_mask == 0
1326
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1327
+ padding_mask, min_dtype
1328
+ )
1329
+
1330
+ return causal_mask
1331
+
1332
+ def _update_mamba_mask(self, attention_mask, cache_position):
1333
+ """
1334
+ No need for zeroing states when
1335
+ 1. Cached forward
1336
+ 2. Attending to all inputs
1337
+ """
1338
+ mamba_mask = attention_mask
1339
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1340
+ mamba_mask = None
1341
+ return mamba_mask
1342
+
1343
+
1344
+ @auto_docstring
1345
+ class BambaForCausalLM(BambaPreTrainedModel, GenerationMixin):
1346
+ _tied_weights_keys = ["lm_head.weight"]
1347
+ _tp_plan = {"lm_head": "colwise_rep"}
1348
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1349
+
1350
+ def __init__(self, config):
1351
+ super().__init__(config)
1352
+ self.model = BambaModel(config)
1353
+ self.vocab_size = config.vocab_size
1354
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1355
+ self.z_loss_coefficient = config.z_loss_coefficient
1356
+
1357
+ # Initialize weights and apply final processing
1358
+ self.post_init()
1359
+
1360
+ @can_return_tuple
1361
+ @auto_docstring
1362
+ def forward(
1363
+ self,
1364
+ input_ids: Optional[torch.LongTensor] = None,
1365
+ attention_mask: Optional[torch.Tensor] = None,
1366
+ position_ids: Optional[torch.LongTensor] = None,
1367
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1368
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1369
+ labels: Optional[torch.LongTensor] = None,
1370
+ use_cache: Optional[bool] = None,
1371
+ output_attentions: Optional[bool] = None,
1372
+ output_hidden_states: Optional[bool] = None,
1373
+ cache_position: Optional[torch.LongTensor] = None,
1374
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1375
+ **kwargs,
1376
+ ) -> CausalLMOutputWithPast:
1377
+ r"""
1378
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1379
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1380
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1381
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1382
+
1383
+ Example:
1384
+
1385
+ ```python
1386
+ >>> from transformers import AutoTokenizer, BambaForCausalLM
1387
+
1388
+ >>> model = BambaForCausalLM.from_pretrained("...")
1389
+ >>> tokenizer = AutoTokenizer.from_pretrained("...")
1390
+
1391
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1392
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1393
+
1394
+ >>> # Generate
1395
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1396
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1397
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1398
+ ```"""
1399
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1400
+ output_hidden_states = (
1401
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1402
+ )
1403
+
1404
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1405
+ outputs: BaseModelOutputWithPast = self.model(
1406
+ input_ids=input_ids,
1407
+ attention_mask=attention_mask,
1408
+ position_ids=position_ids,
1409
+ past_key_values=past_key_values,
1410
+ inputs_embeds=inputs_embeds,
1411
+ use_cache=use_cache,
1412
+ output_attentions=output_attentions,
1413
+ output_hidden_states=output_hidden_states,
1414
+ cache_position=cache_position,
1415
+ **kwargs,
1416
+ )
1417
+
1418
+ hidden_states = outputs.last_hidden_state
1419
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1420
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1421
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1422
+
1423
+ loss = None
1424
+ if labels is not None:
1425
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1426
+ if self.z_loss_coefficient > 0:
1427
+ # Type-match loss, but avoid upcasting large logits tensor until after it's been reduced on dim -1
1428
+ z_loss = logits.logsumexp(dim=-1).to(dtype=loss.dtype).pow(2).mean()
1429
+ loss = loss + self.z_loss_coefficient * z_loss
1430
+
1431
+ return CausalLMOutputWithPast(
1432
+ loss=loss,
1433
+ logits=logits,
1434
+ past_key_values=outputs.past_key_values,
1435
+ hidden_states=outputs.hidden_states,
1436
+ attentions=outputs.attentions,
1437
+ )
1438
+
1439
+ def prepare_inputs_for_generation(
1440
+ self,
1441
+ input_ids,
1442
+ past_key_values=None,
1443
+ attention_mask=None,
1444
+ inputs_embeds=None,
1445
+ cache_position=None,
1446
+ position_ids=None,
1447
+ use_cache=True,
1448
+ **kwargs,
1449
+ ):
1450
+ # Overwritten -- has a unique cache type, `HybridMambaAttentionDynamicCache`
1451
+
1452
+ empty_past_kv = past_key_values is None
1453
+
1454
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1455
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1456
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1457
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1458
+ # (we can't check exception 3 while compiling)
1459
+ if not empty_past_kv:
1460
+ if (
1461
+ inputs_embeds is not None # Exception 1
1462
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1463
+ ):
1464
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1465
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1466
+ input_ids = input_ids[:, cache_position]
1467
+ else:
1468
+ past_key_values = HybridMambaAttentionDynamicCache(
1469
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1470
+ )
1471
+
1472
+ if attention_mask is not None and position_ids is None:
1473
+ # create position_ids on the fly for batch generation
1474
+ position_ids = attention_mask.long().cumsum(-1) - 1
1475
+ position_ids.masked_fill_(attention_mask == 0, 1)
1476
+ if not empty_past_kv:
1477
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1478
+
1479
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1480
+ if inputs_embeds is not None and empty_past_kv:
1481
+ model_inputs = {"inputs_embeds": inputs_embeds}
1482
+ else:
1483
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1484
+
1485
+ model_inputs.update(
1486
+ {
1487
+ "position_ids": position_ids,
1488
+ "past_key_values": past_key_values,
1489
+ "use_cache": use_cache,
1490
+ "attention_mask": attention_mask,
1491
+ "logits_to_keep": self.config.num_logits_to_keep,
1492
+ "cache_position": cache_position,
1493
+ }
1494
+ )
1495
+
1496
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1497
+ for key, value in kwargs.items():
1498
+ if key not in model_inputs:
1499
+ model_inputs[key] = value
1500
+
1501
+ return model_inputs
1502
+
1503
+
1504
+ __all__ = ["BambaModel", "BambaForCausalLM", "BambaPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bamba/modular_bamba.py ADDED
@@ -0,0 +1,1222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """PyTorch Bamba model."""
21
+
22
+ from typing import Optional, TypedDict, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.models.jamba.modeling_jamba import HybridMambaAttentionDynamicCache, JambaAttentionDecoderLayer
29
+ from transformers.models.llama.modeling_llama import (
30
+ LlamaAttention,
31
+ LlamaForCausalLM,
32
+ LlamaMLP,
33
+ LlamaRMSNorm,
34
+ LlamaRotaryEmbedding,
35
+ rotate_half,
36
+ )
37
+ from transformers.models.mamba2.modeling_mamba2 import (
38
+ MambaRMSNormGated,
39
+ pad_tensor_by_size,
40
+ reshape_into_chunks,
41
+ segment_sum,
42
+ )
43
+
44
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
45
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
46
+ from ...modeling_utils import PreTrainedModel
47
+ from ...processing_utils import Unpack
48
+ from ...utils import (
49
+ auto_docstring,
50
+ can_return_tuple,
51
+ logging,
52
+ )
53
+ from ...utils.deprecation import deprecate_kwarg
54
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_2_ssm_available
55
+ from .configuration_bamba import BambaConfig
56
+
57
+
58
+ if is_mamba_2_ssm_available():
59
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
60
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
61
+ else:
62
+ selective_state_update = None
63
+
64
+ if is_causal_conv1d_available():
65
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
66
+ else:
67
+ causal_conv1d_update, causal_conv1d_fn = None, None
68
+
69
+ is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
70
+
71
+
72
+ logger = logging.get_logger(__name__)
73
+
74
+
75
+ class BambaFlashAttentionKwargs(TypedDict, total=False):
76
+ """
77
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
78
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
79
+
80
+ Attributes:
81
+ cu_seq_lens_q (`torch.LongTensor`)
82
+ Gets cumulative sequence length for query state.
83
+ cu_seq_lens_k (`torch.LongTensor`)
84
+ Gets cumulative sequence length for key state.
85
+ max_length_q (`int`):
86
+ Maximum sequence length for query state.
87
+ max_length_k (`int`):
88
+ Maximum sequence length for key state.
89
+ seq_idx (`torch.IntTensor):
90
+ Index of each packed sequence.
91
+ """
92
+
93
+ cu_seq_lens_q: torch.LongTensor
94
+ cu_seq_lens_k: torch.LongTensor
95
+ max_length_q: int
96
+ max_length_k: int
97
+ seq_idx: torch.IntTensor
98
+
99
+
100
+ # Adapted from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache for the v2 mixer
101
+ class HybridMambaAttentionDynamicCache(HybridMambaAttentionDynamicCache):
102
+ """
103
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
104
+ (which has a constant shape regardless of seq_len).
105
+
106
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
107
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
108
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
109
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
110
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
111
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
112
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
113
+ """
114
+
115
+ def __init__(self, config: BambaConfig, batch_size, dtype=torch.float16, device=None):
116
+ self.layers_block_type = config.layers_block_type
117
+ self.has_previous_state = False # only used by mamba
118
+ conv_kernel_size = config.mamba_d_conv
119
+ ssm_state_size = config.mamba_d_state
120
+
121
+ self.conv_states = []
122
+ self.ssm_states = []
123
+ self.transformer_layers = []
124
+ for i in range(config.num_hidden_layers):
125
+ if self.layers_block_type[i] == "mamba":
126
+ self.conv_states += [
127
+ torch.zeros(
128
+ batch_size,
129
+ (config.mamba_expand * config.hidden_size + 2 * config.mamba_n_groups * ssm_state_size),
130
+ conv_kernel_size,
131
+ device=device,
132
+ dtype=dtype,
133
+ )
134
+ ]
135
+ self.ssm_states += [
136
+ torch.zeros(
137
+ batch_size,
138
+ config.mamba_n_heads,
139
+ config.mamba_d_head,
140
+ ssm_state_size,
141
+ device=device,
142
+ dtype=dtype,
143
+ )
144
+ ]
145
+ else:
146
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
147
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
148
+ self.transformer_layers.append(i)
149
+
150
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
151
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
152
+
153
+
154
+ class BambaRotaryEmbedding(LlamaRotaryEmbedding):
155
+ pass
156
+
157
+
158
+ # Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_emb
159
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
160
+ """Applies Rotary Position Embedding to the query and key tensors.
161
+
162
+ Removes the interleaving of cos and sin from GLM
163
+
164
+ Args:
165
+ q (`torch.Tensor`): The query tensor.
166
+ k (`torch.Tensor`): The key tensor.
167
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
168
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
169
+ position_ids (`torch.Tensor`, *optional*):
170
+ Deprecated and unused.
171
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
172
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
173
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
174
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
175
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
176
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
177
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
178
+ Returns:
179
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
180
+ """
181
+ cos = cos.unsqueeze(unsqueeze_dim)
182
+ sin = sin.unsqueeze(unsqueeze_dim)
183
+
184
+ # Keep half or full tensor for later concatenation
185
+ rotary_dim = cos.shape[-1]
186
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
187
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
188
+
189
+ # Apply rotary embeddings on the first half or full tensor
190
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
191
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
192
+
193
+ # Concatenate back to full shape
194
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
195
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
196
+ return q_embed, k_embed
197
+
198
+
199
+ class BambaAttention(LlamaAttention):
200
+ pass
201
+
202
+
203
+ class BambaRMSNormGated(MambaRMSNormGated):
204
+ pass
205
+
206
+
207
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
208
+ """
209
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
210
+ """
211
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
212
+ dtype = hidden_states.dtype
213
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
214
+
215
+ return hidden_states
216
+
217
+
218
+ # Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
219
+ class BambaMixer(nn.Module):
220
+ """
221
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
222
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
223
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
224
+ and is why Mamba is called **selective** state spaces)
225
+
226
+ The are a few differences between this and Mamba2Mixer:
227
+ - The variable use_precomputed_states is slightly different due to the hybrid cache structure
228
+ - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
229
+ - Some extra variables that our layer doesn't need have been removed
230
+ - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
231
+ """
232
+
233
+ def __init__(self, config: BambaConfig, layer_idx: int):
234
+ super().__init__()
235
+ self.num_heads = config.mamba_n_heads
236
+ self.hidden_size = config.hidden_size
237
+ self.ssm_state_size = config.mamba_d_state
238
+ self.conv_kernel_size = config.mamba_d_conv
239
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
240
+ self.layer_idx = layer_idx
241
+ self.use_conv_bias = config.mamba_conv_bias
242
+ self.activation = config.hidden_act
243
+ self.act = ACT2FN[config.hidden_act]
244
+ self.use_bias = config.mamba_proj_bias
245
+
246
+ self.layer_norm_epsilon = config.rms_norm_eps
247
+
248
+ self.n_groups = config.mamba_n_groups
249
+ self.head_dim = config.mamba_d_head
250
+ self.chunk_size = config.mamba_chunk_size
251
+
252
+ # FIXME:
253
+ self.time_step_limit = (0.0, float("inf"))
254
+ self.time_step_min = 0.001
255
+ self.time_step_max = 0.1
256
+
257
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
258
+ self.conv1d = nn.Conv1d(
259
+ in_channels=self.conv_dim,
260
+ out_channels=self.conv_dim,
261
+ bias=config.mamba_conv_bias,
262
+ kernel_size=self.conv_kernel_size,
263
+ groups=self.conv_dim,
264
+ padding=self.conv_kernel_size - 1,
265
+ )
266
+
267
+ # projection of the input hidden states
268
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
269
+ self.in_proj = nn.Linear(
270
+ self.hidden_size,
271
+ projection_size,
272
+ bias=self.use_bias,
273
+ )
274
+ # selective projection used to make dt, B and C input dependent
275
+
276
+ # time step projection (discretization)
277
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
278
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
279
+
280
+ # S4D real initialization. These are not discretized!
281
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
282
+ A = torch.arange(1, self.num_heads + 1)
283
+ self.A_log = nn.Parameter(torch.log(A))
284
+ self.norm = BambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
285
+ self.D = nn.Parameter(torch.ones(self.num_heads))
286
+
287
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
288
+
289
+ if not is_fast_path_available:
290
+ logger.warning_once(
291
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
292
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
293
+ " https://github.com/Dao-AILab/causal-conv1d"
294
+ )
295
+ else:
296
+ logger.warning_once("The fast path for Bamba will be used when running the model on a GPU")
297
+
298
+ def cuda_kernels_forward(
299
+ self,
300
+ hidden_states: torch.Tensor,
301
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
302
+ cache_position: Optional[torch.LongTensor] = None,
303
+ attention_mask: Optional[torch.Tensor] = None,
304
+ seq_idx: Optional[torch.IntTensor] = None,
305
+ ):
306
+ # 1. Gated MLP's linear projection
307
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
308
+ projected_states = self.in_proj(hidden_states)
309
+
310
+ # Set up dimensions for reshapes later
311
+ batch_size, seq_len, _ = hidden_states.shape
312
+ groups_time_state_size = self.n_groups * self.ssm_state_size
313
+
314
+ use_precomputed_states = (
315
+ cache_params is not None
316
+ and cache_params.has_previous_state
317
+ and seq_len == 1
318
+ and cache_params.conv_states[self.layer_idx].shape[0]
319
+ == cache_params.ssm_states[self.layer_idx].shape[0]
320
+ == batch_size
321
+ and cache_position is not None
322
+ and cache_position[0] > 0
323
+ )
324
+
325
+ # getting projected states from cache if it exists
326
+ if use_precomputed_states:
327
+ gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
328
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
329
+ )
330
+
331
+ # 2. Convolution sequence transformation
332
+ hidden_states_B_C = causal_conv1d_update(
333
+ hidden_states_B_C,
334
+ cache_params.conv_states[self.layer_idx],
335
+ self.conv1d.weight.squeeze(1),
336
+ self.conv1d.bias,
337
+ self.activation,
338
+ )
339
+
340
+ hidden_states, B, C = torch.split(
341
+ hidden_states_B_C,
342
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
343
+ dim=-1,
344
+ )
345
+
346
+ # 3. SSM transformation
347
+ A = -torch.exp(self.A_log.float()) # (nheads,)
348
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
349
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
350
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
351
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
352
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
353
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
354
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
355
+ hidden_states = selective_state_update(
356
+ cache_params.ssm_states[self.layer_idx],
357
+ hidden_states_reshaped,
358
+ dt,
359
+ A,
360
+ B,
361
+ C,
362
+ D,
363
+ z=None,
364
+ dt_bias=dt_bias,
365
+ dt_softplus=True,
366
+ )
367
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
368
+ hidden_states = self.norm(hidden_states, gate)
369
+
370
+ # 4. Final linear projection
371
+ out = self.out_proj(hidden_states)[:, None, ...]
372
+ # Fused calculations or step by step if no initialized cache is found
373
+ else:
374
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
375
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
376
+
377
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
378
+ if self.training and cache_params is None:
379
+ out = mamba_split_conv1d_scan_combined(
380
+ projected_states,
381
+ self.conv1d.weight.squeeze(1),
382
+ self.conv1d.bias,
383
+ self.dt_bias,
384
+ A,
385
+ D=self.D,
386
+ chunk_size=self.chunk_size,
387
+ seq_idx=seq_idx,
388
+ activation=self.activation,
389
+ rmsnorm_weight=self.norm.weight,
390
+ rmsnorm_eps=self.norm.variance_epsilon,
391
+ outproj_weight=self.out_proj.weight,
392
+ outproj_bias=self.out_proj.bias,
393
+ headdim=self.head_dim,
394
+ ngroups=self.n_groups,
395
+ norm_before_gate=False,
396
+ return_final_states=False,
397
+ **dt_limit_kwargs,
398
+ )
399
+
400
+ else:
401
+ gate, hidden_states_B_C, dt = projected_states.split(
402
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
403
+ )
404
+
405
+ # 2. Convolution sequence transformation
406
+ # Init cache
407
+ if cache_params is not None:
408
+ # storing the states
409
+ # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv
410
+ # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise.
411
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
412
+ conv_states = nn.functional.pad(
413
+ hidden_states_B_C_transposed,
414
+ (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
415
+ )
416
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
417
+
418
+ if self.activation not in ["silu", "swish"]:
419
+ hidden_states_B_C = self.act(
420
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
421
+ )
422
+ else:
423
+ hidden_states_B_C = causal_conv1d_fn(
424
+ x=hidden_states_B_C.transpose(1, 2),
425
+ weight=self.conv1d.weight.squeeze(1),
426
+ bias=self.conv1d.bias,
427
+ activation=self.activation,
428
+ seq_idx=seq_idx,
429
+ ).transpose(1, 2)
430
+
431
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
432
+ hidden_states, B, C = torch.split(
433
+ hidden_states_B_C,
434
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
435
+ dim=-1,
436
+ )
437
+
438
+ # 3. SSM transformation
439
+ scan_output, ssm_state = mamba_chunk_scan_combined(
440
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
441
+ dt,
442
+ A,
443
+ B.view(batch_size, seq_len, self.n_groups, -1),
444
+ C.view(batch_size, seq_len, self.n_groups, -1),
445
+ chunk_size=self.chunk_size,
446
+ D=self.D,
447
+ z=None,
448
+ seq_idx=seq_idx,
449
+ return_final_states=True,
450
+ dt_bias=self.dt_bias,
451
+ dt_softplus=True,
452
+ **dt_limit_kwargs,
453
+ )
454
+
455
+ # Init cache
456
+ if ssm_state is not None and cache_params is not None:
457
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
458
+
459
+ scan_output = scan_output.view(batch_size, seq_len, -1)
460
+ # Multiply "gate" branch and apply extra normalization layer
461
+ scan_output = self.norm(scan_output, gate)
462
+
463
+ # 4. Final linear projection
464
+ out = self.out_proj(scan_output)
465
+ return out
466
+
467
+ # fmt: off
468
+ def torch_forward(
469
+ self,
470
+ input_states,
471
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
472
+ cache_position: Optional[torch.LongTensor] = None,
473
+ attention_mask: Optional[torch.Tensor] = None,
474
+ ):
475
+ batch_size, seq_len, _ = input_states.shape
476
+ dtype = input_states.dtype
477
+
478
+ # 1. Gated MLP's linear projection
479
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
480
+ projected_states = self.in_proj(input_states)
481
+ gate, hidden_states_B_C, dt = projected_states.split(
482
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
483
+ )
484
+
485
+ use_precomputed_states = (
486
+ cache_params is not None
487
+ and cache_params.has_previous_state
488
+ and seq_len == 1
489
+ and cache_params.conv_states[self.layer_idx].shape[0]
490
+ == cache_params.ssm_states[self.layer_idx].shape[0]
491
+ == batch_size
492
+ and cache_position is not None
493
+ and cache_position[0] > 0
494
+ )
495
+
496
+ # 2. Convolution sequence transformation
497
+ if use_precomputed_states:
498
+ cache_params.conv_states[self.layer_idx] = cache_params.conv_states[self.layer_idx].roll(shifts=-1, dims=-1)
499
+ cache_params.conv_states[self.layer_idx][:, :, -1] = hidden_states_B_C[:, 0, :].to(cache_params.conv_states[self.layer_idx].device)
500
+
501
+ # We need to guarantee that anything regarding the cache is on the same device
502
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
503
+
504
+ hidden_states_B_C = torch.sum(
505
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
506
+ )
507
+ if self.use_conv_bias:
508
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
509
+ hidden_states_B_C = self.act(hidden_states_B_C)
510
+ else:
511
+ # Init cache
512
+ if cache_params is not None:
513
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
514
+ conv_states = nn.functional.pad(
515
+ hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
516
+ )
517
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
518
+
519
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
520
+
521
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
522
+ hidden_states, B, C = torch.split(
523
+ hidden_states_B_C,
524
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
525
+ dim=-1
526
+ )
527
+
528
+ # 3. SSM transformation
529
+ A = -torch.exp(self.A_log.float()) # [num_heads]
530
+ if use_precomputed_states:
531
+ # We need to guarantee that anything regarding the cache is on the same device
532
+ cache_device = cache_params.ssm_states[self.layer_idx].device
533
+
534
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
535
+ # for batched generation
536
+ dt = dt[:, 0, :][:, None, ...]
537
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
538
+ # [num_heads] -> [num_heads, head_dim]
539
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
540
+
541
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
542
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
543
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
544
+ # [bsz, num_heads, head_dim, state_size]
545
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
546
+
547
+ # Discretize B
548
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
549
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
550
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
551
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
552
+ B = B.reshape(batch_size, -1, B.shape[-1])
553
+ # [bsz, num_heads, head_dim, state_size]
554
+ dB = dt[..., None] * B[..., None, :]
555
+
556
+ # Discretize x into dB
557
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
558
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
559
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
560
+
561
+ # State calculation
562
+ cache_params.ssm_states[self.layer_idx].copy_(
563
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
564
+ )
565
+
566
+ # Subsequent output
567
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
568
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
569
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
570
+ C = C.reshape(batch_size, -1, C.shape[-1])
571
+ # [bsz, num_heads, head_dim]
572
+
573
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
574
+ # Reshape ssm_states to merge the first two dimensions
575
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
576
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
577
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
578
+ y = y.view(batch_size, self.num_heads, self.head_dim)
579
+
580
+ # D skip connection
581
+ # [num_heads] -> [num_heads, head_dim]
582
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
583
+ y = (y + hidden_states * D).to(y.dtype)
584
+
585
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
586
+ y = y.reshape(batch_size, -1)[:, None, ...]
587
+ else:
588
+ # begin ssd naive implementation without einsums
589
+ dt = nn.functional.softplus(dt + self.dt_bias)
590
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
591
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
592
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
593
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
594
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
595
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
596
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
597
+
598
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
599
+
600
+ # Discretize x and A
601
+ hidden_states = hidden_states * dt[..., None]
602
+ A = A.to(hidden_states.dtype) * dt
603
+
604
+ # Rearrange into blocks/chunks
605
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
606
+
607
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
608
+ A = A.permute(0, 3, 1, 2)
609
+ A_cumsum = torch.cumsum(A, dim=-1)
610
+
611
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
612
+ # This is the analog of a causal mask
613
+ L = torch.exp(segment_sum(A))
614
+
615
+ # Contraction of C and B to get G (attention-weights like)
616
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
617
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
618
+
619
+ # Compute M, equivalent to applying attention mask to weights
620
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
621
+ M = M_intermediate.sum(dim=-1)
622
+
623
+ # Compute Y_diag (apply to values)
624
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
625
+
626
+ # 2. Compute the state for each intra-chunk
627
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
628
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
629
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
630
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
631
+
632
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
633
+ # (middle term of factorization of off-diag blocks; A terms)
634
+ if use_precomputed_states:
635
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
636
+ else:
637
+ previous_states = torch.zeros_like(states[:, :1])
638
+ states = torch.cat([previous_states, states], dim=1)
639
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
640
+ decay_chunk = decay_chunk.transpose(1, 3)
641
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
642
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
643
+
644
+ # 4. Compute state -> output conversion per chunk
645
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
646
+ state_decay_out = torch.exp(A_cumsum)
647
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
648
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
649
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
650
+
651
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
652
+ y = Y_diag + Y_off
653
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
654
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
655
+
656
+ y = y + D_residual
657
+ # Cutting off padded chunks
658
+ if pad_size > 0:
659
+ y = y[:, :seq_len, :, :]
660
+ y = y.reshape(batch_size, seq_len, -1)
661
+
662
+ # Init cache
663
+ if ssm_state is not None and cache_params is not None:
664
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
665
+
666
+ scan_output = self.norm(y, gate)
667
+
668
+ # end ssd naive
669
+
670
+ # 4. Final linear projection
671
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
672
+ return contextualized_states
673
+ # fmt: on
674
+
675
+ def forward(
676
+ self,
677
+ hidden_states,
678
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
679
+ cache_position: Optional[torch.LongTensor] = None,
680
+ attention_mask: Optional[torch.Tensor] = None,
681
+ seq_idx: Optional[torch.IntTensor] = None,
682
+ **kwargs,
683
+ ):
684
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
685
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, seq_idx)
686
+ if seq_idx is not None:
687
+ raise NotImplementedError(
688
+ "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`"
689
+ )
690
+ dtype = hidden_states.dtype
691
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
692
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
693
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
694
+
695
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
696
+
697
+
698
+ class BambaMLP(LlamaMLP):
699
+ pass
700
+
701
+
702
+ class BambaRMSNorm(LlamaRMSNorm):
703
+ pass
704
+
705
+
706
+ class BambaDecoderLayer(JambaAttentionDecoderLayer):
707
+ def __init__(self, config: BambaConfig, layer_idx: int, layer_type: str = "mamba"):
708
+ super().__init__(config, layer_idx)
709
+
710
+ del self.self_attn
711
+
712
+ num_experts = 1
713
+ ffn_layer_class = BambaMLP if num_experts == 1 else None
714
+ self.feed_forward = ffn_layer_class(config)
715
+
716
+ self.layer_type = layer_type
717
+ if layer_type == "mamba":
718
+ self.mamba = BambaMixer(config=config, layer_idx=layer_idx)
719
+ elif layer_type == "attention":
720
+ self.self_attn = BambaAttention(config, layer_idx)
721
+ else:
722
+ raise ValueError("Invalid layer_type")
723
+
724
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
725
+ def forward(
726
+ self,
727
+ hidden_states: torch.Tensor,
728
+ attention_mask: Optional[torch.Tensor] = None,
729
+ position_ids: Optional[torch.LongTensor] = None,
730
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
731
+ output_attentions: Optional[bool] = False,
732
+ use_cache: Optional[bool] = False,
733
+ cache_position: Optional[torch.LongTensor] = None,
734
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
735
+ **kwargs: Unpack[BambaFlashAttentionKwargs],
736
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
737
+ """
738
+ Args:
739
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
740
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
741
+ `(batch, sequence_length)` where padding elements are indicated by 0.
742
+ past_key_values (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
743
+ output_attentions (`bool`, *optional*):
744
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
745
+ returned tensors for more detail.
746
+ use_cache (`bool`, *optional*):
747
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
748
+ (see `past_key_values`).
749
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
750
+ Indices depicting the position of the input sequence tokens in the sequence.
751
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
752
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
753
+ with `head_dim` being the embedding dimension of each attention head.
754
+ kwargs (`dict`, *optional*):
755
+ Arbitrary kwargs. Can be used to provide `BambaFlashAttentionKwargs` for
756
+ padding-free training and/or improve torch.compile performance.
757
+ """
758
+
759
+ residual = hidden_states
760
+
761
+ hidden_states = self.input_layernorm(hidden_states)
762
+
763
+ # this is a hybrid decoder layer
764
+ if self.layer_type == "mamba":
765
+ hidden_states = self.mamba(
766
+ hidden_states=hidden_states,
767
+ cache_params=past_key_values,
768
+ cache_position=cache_position,
769
+ attention_mask=attention_mask,
770
+ **kwargs,
771
+ )
772
+ self_attn_weights = None
773
+ elif self.layer_type == "attention":
774
+ hidden_states, self_attn_weights = self.self_attn(
775
+ hidden_states=hidden_states,
776
+ attention_mask=attention_mask,
777
+ position_ids=position_ids,
778
+ past_key_values=past_key_values,
779
+ output_attentions=output_attentions,
780
+ use_cache=use_cache,
781
+ cache_position=cache_position,
782
+ position_embeddings=position_embeddings,
783
+ **kwargs,
784
+ )
785
+
786
+ # residual connection after attention
787
+ hidden_states = residual + hidden_states
788
+
789
+ # feed-forward
790
+ residual = hidden_states
791
+ hidden_states = self.pre_ff_layernorm(hidden_states)
792
+ hidden_states = self.feed_forward(hidden_states)
793
+ hidden_states = residual + hidden_states
794
+
795
+ outputs = (hidden_states,)
796
+
797
+ if output_attentions:
798
+ outputs += (self_attn_weights,)
799
+
800
+ return outputs
801
+
802
+
803
+ @auto_docstring
804
+ class BambaPreTrainedModel(PreTrainedModel):
805
+ config: BambaConfig
806
+ base_model_prefix = "model"
807
+ supports_gradient_checkpointing = True
808
+ _no_split_modules = ["BambaDecoderLayer"]
809
+ _skip_keys_device_placement = "past_key_values"
810
+ _supports_flash_attn = True
811
+ _supports_sdpa = True
812
+ # Note: only supports HybridMambaAttentionDynamicCache
813
+ _is_stateful = True
814
+
815
+ def _init_weights(self, module):
816
+ super()._init_weights(module)
817
+ if isinstance(module, BambaMixer):
818
+ module.dt_bias.data.fill_(1.0)
819
+ module.A_log.data = torch.log(torch.arange(1, module.num_heads + 1))
820
+ module.D.data.fill_(1.0)
821
+
822
+
823
+ @auto_docstring
824
+ class BambaModel(BambaPreTrainedModel):
825
+ def __init__(self, config: BambaConfig):
826
+ super().__init__(config)
827
+ self.padding_idx = config.pad_token_id
828
+ self.vocab_size = config.vocab_size
829
+
830
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+ decoder_layers = []
832
+ for i in range(config.num_hidden_layers):
833
+ decoder_layers.append(BambaDecoderLayer(config, layer_idx=i, layer_type=config.layers_block_type[i]))
834
+ self.layers = nn.ModuleList(decoder_layers)
835
+
836
+ self._attn_implementation = config._attn_implementation
837
+ self.final_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
838
+ self.rotary_emb = BambaRotaryEmbedding(config=config)
839
+
840
+ self.gradient_checkpointing = False
841
+ # Initialize weights and apply final processing
842
+ self.post_init()
843
+
844
+ @can_return_tuple
845
+ @auto_docstring
846
+ def forward(
847
+ self,
848
+ input_ids: Optional[torch.LongTensor] = None,
849
+ attention_mask: Optional[torch.Tensor] = None,
850
+ position_ids: Optional[torch.LongTensor] = None,
851
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
852
+ inputs_embeds: Optional[torch.FloatTensor] = None,
853
+ use_cache: Optional[bool] = None,
854
+ output_attentions: Optional[bool] = None,
855
+ output_hidden_states: Optional[bool] = None,
856
+ cache_position: Optional[torch.LongTensor] = None,
857
+ **kwargs: Unpack[BambaFlashAttentionKwargs],
858
+ ) -> BaseModelOutputWithPast:
859
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
860
+ output_hidden_states = (
861
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
862
+ )
863
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
864
+
865
+ if (input_ids is None) ^ (inputs_embeds is not None):
866
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
867
+
868
+ if self.gradient_checkpointing and self.training and use_cache:
869
+ logger.warning_once(
870
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
871
+ )
872
+ use_cache = False
873
+
874
+ if inputs_embeds is None:
875
+ inputs_embeds = self.embed_tokens(input_ids)
876
+ hidden_states = inputs_embeds
877
+
878
+ if use_cache and past_key_values is None:
879
+ logger.warning_once(
880
+ "Bamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was "
881
+ "provided, so no cache will be returned."
882
+ )
883
+
884
+ if cache_position is None:
885
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
886
+ if position_ids is None:
887
+ position_ids = cache_position.unsqueeze(0)
888
+
889
+ causal_mask = self._update_causal_mask(
890
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
891
+ )
892
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
893
+
894
+ # create position embeddings to be shared across the decoder layers
895
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
896
+
897
+ all_hidden_states = () if output_hidden_states else None
898
+ all_self_attns = () if output_attentions else None
899
+
900
+ for decoder_layer in self.layers:
901
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
902
+ layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask
903
+
904
+ if output_hidden_states:
905
+ all_hidden_states += (hidden_states,)
906
+
907
+ layer_outputs = decoder_layer(
908
+ hidden_states,
909
+ attention_mask=layer_mask,
910
+ position_ids=position_ids,
911
+ past_key_values=past_key_values,
912
+ output_attentions=output_attentions,
913
+ use_cache=use_cache,
914
+ cache_position=cache_position,
915
+ position_embeddings=position_embeddings,
916
+ **kwargs,
917
+ )
918
+
919
+ hidden_states = layer_outputs[0]
920
+
921
+ if output_attentions:
922
+ if layer_outputs[1] is not None:
923
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
924
+ all_self_attns += (layer_outputs[1],)
925
+
926
+ hidden_states = self.final_layernorm(hidden_states)
927
+
928
+ # add hidden states from the last decoder layer
929
+ if output_hidden_states:
930
+ all_hidden_states += (hidden_states,)
931
+
932
+ if past_key_values and not past_key_values.has_previous_state:
933
+ past_key_values.has_previous_state = True
934
+
935
+ next_cache = None if not use_cache else past_key_values
936
+
937
+ return BaseModelOutputWithPast(
938
+ last_hidden_state=hidden_states,
939
+ past_key_values=next_cache,
940
+ hidden_states=all_hidden_states,
941
+ attentions=all_self_attns,
942
+ )
943
+
944
+ def _update_causal_mask(
945
+ self,
946
+ attention_mask: torch.Tensor,
947
+ input_tensor: torch.Tensor,
948
+ cache_position: torch.Tensor,
949
+ past_key_values: HybridMambaAttentionDynamicCache,
950
+ output_attentions: bool,
951
+ ):
952
+ if self.config._attn_implementation == "flash_attention_2":
953
+ if attention_mask is not None and 0.0 in attention_mask:
954
+ return attention_mask
955
+ return None
956
+
957
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
958
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
959
+ # to infer the attention mask.
960
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
961
+
962
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
963
+ if self.config._attn_implementation == "sdpa" and not output_attentions:
964
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
965
+ attention_mask,
966
+ inputs_embeds=input_tensor,
967
+ past_key_values_length=past_seen_tokens,
968
+ is_training=self.training,
969
+ ):
970
+ return None
971
+
972
+ dtype = input_tensor.dtype
973
+ sequence_length = input_tensor.shape[1]
974
+ target_length = (
975
+ attention_mask.shape[-1]
976
+ if isinstance(attention_mask, torch.Tensor)
977
+ else past_seen_tokens + sequence_length + 1
978
+ )
979
+
980
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
981
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
982
+ attention_mask,
983
+ sequence_length=sequence_length,
984
+ target_length=target_length,
985
+ dtype=dtype,
986
+ cache_position=cache_position,
987
+ batch_size=input_tensor.shape[0],
988
+ )
989
+
990
+ if (
991
+ self.config._attn_implementation == "sdpa"
992
+ and attention_mask is not None
993
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
994
+ and not output_attentions
995
+ ):
996
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
997
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
998
+ # Details: https://github.com/pytorch/pytorch/issues/110213
999
+ min_dtype = torch.finfo(dtype).min
1000
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1001
+
1002
+ return causal_mask
1003
+
1004
+ @staticmethod
1005
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1006
+ attention_mask: torch.Tensor,
1007
+ sequence_length: int,
1008
+ target_length: int,
1009
+ dtype: torch.dtype,
1010
+ cache_position: torch.Tensor,
1011
+ batch_size: int,
1012
+ **kwargs,
1013
+ ):
1014
+ """
1015
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1016
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1017
+
1018
+ Args:
1019
+ attention_mask (`torch.Tensor`):
1020
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1021
+ `(batch_size, 1, query_length, key_value_length)`.
1022
+ sequence_length (`int`):
1023
+ The sequence length being processed.
1024
+ target_length (`int`):
1025
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1026
+ to account for the 0 padding, the part of the cache that is not filled yet.
1027
+ dtype (`torch.dtype`):
1028
+ The dtype to use for the 4D attention mask.
1029
+ cache_position (`torch.Tensor`):
1030
+ Indices depicting the position of the input sequence tokens in the sequence.
1031
+ batch_size (`torch.Tensor`):
1032
+ Batch size.
1033
+ """
1034
+ if attention_mask is not None and attention_mask.dim() == 4:
1035
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1036
+ causal_mask = attention_mask
1037
+ else:
1038
+ min_dtype = torch.finfo(dtype).min
1039
+ causal_mask = torch.full(
1040
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1041
+ )
1042
+ if sequence_length != 1:
1043
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1044
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
1045
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1046
+ if attention_mask is not None:
1047
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1048
+ mask_length = attention_mask.shape[-1]
1049
+ padding_attention_mask = (attention_mask[:, None, None, :] == attention_mask[:, None, :, None])[
1050
+ :, :, -sequence_length:, :
1051
+ ].to(dtype)
1052
+ padding_mask = causal_mask[:, :, :, :mask_length] + padding_attention_mask
1053
+ padding_mask = padding_mask == 0
1054
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1055
+ padding_mask, min_dtype
1056
+ )
1057
+
1058
+ return causal_mask
1059
+
1060
+ def _update_mamba_mask(self, attention_mask, cache_position):
1061
+ """
1062
+ No need for zeroing states when
1063
+ 1. Cached forward
1064
+ 2. Attending to all inputs
1065
+ """
1066
+ mamba_mask = attention_mask
1067
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1068
+ mamba_mask = None
1069
+ return mamba_mask
1070
+
1071
+
1072
+ class BambaForCausalLM(LlamaForCausalLM):
1073
+ def __init__(self, config):
1074
+ super().__init__(config)
1075
+ self.z_loss_coefficient = config.z_loss_coefficient
1076
+
1077
+ # Initialize weights and apply final processing
1078
+ self.post_init()
1079
+
1080
+ def forward(
1081
+ self,
1082
+ input_ids: Optional[torch.LongTensor] = None,
1083
+ attention_mask: Optional[torch.Tensor] = None,
1084
+ position_ids: Optional[torch.LongTensor] = None,
1085
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1086
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1087
+ labels: Optional[torch.LongTensor] = None,
1088
+ use_cache: Optional[bool] = None,
1089
+ output_attentions: Optional[bool] = None,
1090
+ output_hidden_states: Optional[bool] = None,
1091
+ cache_position: Optional[torch.LongTensor] = None,
1092
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1093
+ **kwargs,
1094
+ ) -> CausalLMOutputWithPast:
1095
+ r"""
1096
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1097
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1098
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1099
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1100
+
1101
+ Example:
1102
+
1103
+ ```python
1104
+ >>> from transformers import AutoTokenizer, BambaForCausalLM
1105
+
1106
+ >>> model = BambaForCausalLM.from_pretrained("...")
1107
+ >>> tokenizer = AutoTokenizer.from_pretrained("...")
1108
+
1109
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1110
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1111
+
1112
+ >>> # Generate
1113
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1114
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1115
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1116
+ ```"""
1117
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1118
+ output_hidden_states = (
1119
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1120
+ )
1121
+
1122
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1123
+ outputs: BaseModelOutputWithPast = self.model(
1124
+ input_ids=input_ids,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_values=past_key_values,
1128
+ inputs_embeds=inputs_embeds,
1129
+ use_cache=use_cache,
1130
+ output_attentions=output_attentions,
1131
+ output_hidden_states=output_hidden_states,
1132
+ cache_position=cache_position,
1133
+ **kwargs,
1134
+ )
1135
+
1136
+ hidden_states = outputs.last_hidden_state
1137
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1138
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1139
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1140
+
1141
+ loss = None
1142
+ if labels is not None:
1143
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1144
+ if self.z_loss_coefficient > 0:
1145
+ # Type-match loss, but avoid upcasting large logits tensor until after it's been reduced on dim -1
1146
+ z_loss = logits.logsumexp(dim=-1).to(dtype=loss.dtype).pow(2).mean()
1147
+ loss = loss + self.z_loss_coefficient * z_loss
1148
+
1149
+ return CausalLMOutputWithPast(
1150
+ loss=loss,
1151
+ logits=logits,
1152
+ past_key_values=outputs.past_key_values,
1153
+ hidden_states=outputs.hidden_states,
1154
+ attentions=outputs.attentions,
1155
+ )
1156
+
1157
+ def prepare_inputs_for_generation(
1158
+ self,
1159
+ input_ids,
1160
+ past_key_values=None,
1161
+ attention_mask=None,
1162
+ inputs_embeds=None,
1163
+ cache_position=None,
1164
+ position_ids=None,
1165
+ use_cache=True,
1166
+ **kwargs,
1167
+ ):
1168
+ # Overwritten -- has a unique cache type, `HybridMambaAttentionDynamicCache`
1169
+
1170
+ empty_past_kv = past_key_values is None
1171
+
1172
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1173
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1174
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1175
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1176
+ # (we can't check exception 3 while compiling)
1177
+ if not empty_past_kv:
1178
+ if (
1179
+ inputs_embeds is not None # Exception 1
1180
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1181
+ ):
1182
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1183
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1184
+ input_ids = input_ids[:, cache_position]
1185
+ else:
1186
+ past_key_values = HybridMambaAttentionDynamicCache(
1187
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1188
+ )
1189
+
1190
+ if attention_mask is not None and position_ids is None:
1191
+ # create position_ids on the fly for batch generation
1192
+ position_ids = attention_mask.long().cumsum(-1) - 1
1193
+ position_ids.masked_fill_(attention_mask == 0, 1)
1194
+ if not empty_past_kv:
1195
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1196
+
1197
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1198
+ if inputs_embeds is not None and empty_past_kv:
1199
+ model_inputs = {"inputs_embeds": inputs_embeds}
1200
+ else:
1201
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1202
+
1203
+ model_inputs.update(
1204
+ {
1205
+ "position_ids": position_ids,
1206
+ "past_key_values": past_key_values,
1207
+ "use_cache": use_cache,
1208
+ "attention_mask": attention_mask,
1209
+ "logits_to_keep": self.config.num_logits_to_keep,
1210
+ "cache_position": cache_position,
1211
+ }
1212
+ )
1213
+
1214
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1215
+ for key, value in kwargs.items():
1216
+ if key not in model_inputs:
1217
+ model_inputs[key] = value
1218
+
1219
+ return model_inputs
1220
+
1221
+
1222
+ __all__ = ["BambaModel", "BambaForCausalLM", "BambaPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/__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_bert_generation import *
22
+ from .modeling_bert_generation import *
23
+ from .tokenization_bert_generation 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
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
+ """BertGeneration model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+
19
+
20
+ class BertGenerationConfig(PretrainedConfig):
21
+ r"""
22
+ This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to
23
+ instantiate a BertGeneration model according to the specified arguments, defining the model architecture.
24
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the BertGeneration
25
+ [google/bert_for_seq_generation_L-24_bbc_encoder](https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder)
26
+ architecture.
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information.
30
+
31
+ Args:
32
+ vocab_size (`int`, *optional*, defaults to 50358):
33
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
34
+ `inputs_ids` passed when calling [`BertGeneration`].
35
+ hidden_size (`int`, *optional*, defaults to 1024):
36
+ Dimensionality of the encoder layers and the pooler layer.
37
+ num_hidden_layers (`int`, *optional*, defaults to 24):
38
+ Number of hidden layers in the Transformer encoder.
39
+ num_attention_heads (`int`, *optional*, defaults to 16):
40
+ Number of attention heads for each attention layer in the Transformer encoder.
41
+ intermediate_size (`int`, *optional*, defaults to 4096):
42
+ Dimensionality of the "intermediate" (often called feed-forward) layer in the Transformer encoder.
43
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
44
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
45
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
46
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
47
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
48
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
49
+ The dropout ratio for the attention probabilities.
50
+ max_position_embeddings (`int`, *optional*, defaults to 512):
51
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
52
+ just in case (e.g., 512 or 1024 or 2048).
53
+ initializer_range (`float`, *optional*, defaults to 0.02):
54
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
55
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
56
+ The epsilon used by the layer normalization layers.
57
+ pad_token_id (`int`, *optional*, defaults to 0):
58
+ Padding token id.
59
+ bos_token_id (`int`, *optional*, defaults to 2):
60
+ Beginning of stream token id.
61
+ eos_token_id (`int`, *optional*, defaults to 1):
62
+ End of stream token id.
63
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
64
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
65
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
66
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
67
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
68
+ with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+
73
+ Examples:
74
+
75
+ ```python
76
+ >>> from transformers import BertGenerationConfig, BertGenerationEncoder
77
+
78
+ >>> # Initializing a BertGeneration config
79
+ >>> configuration = BertGenerationConfig()
80
+
81
+ >>> # Initializing a model (with random weights) from the config
82
+ >>> model = BertGenerationEncoder(configuration)
83
+
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+
88
+ model_type = "bert-generation"
89
+
90
+ def __init__(
91
+ self,
92
+ vocab_size=50358,
93
+ hidden_size=1024,
94
+ num_hidden_layers=24,
95
+ num_attention_heads=16,
96
+ intermediate_size=4096,
97
+ hidden_act="gelu",
98
+ hidden_dropout_prob=0.1,
99
+ attention_probs_dropout_prob=0.1,
100
+ max_position_embeddings=512,
101
+ initializer_range=0.02,
102
+ layer_norm_eps=1e-12,
103
+ pad_token_id=0,
104
+ bos_token_id=2,
105
+ eos_token_id=1,
106
+ position_embedding_type="absolute",
107
+ use_cache=True,
108
+ **kwargs,
109
+ ):
110
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
111
+
112
+ self.vocab_size = vocab_size
113
+ self.hidden_size = hidden_size
114
+ self.num_hidden_layers = num_hidden_layers
115
+ self.num_attention_heads = num_attention_heads
116
+ self.hidden_act = hidden_act
117
+ self.intermediate_size = intermediate_size
118
+ self.hidden_dropout_prob = hidden_dropout_prob
119
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
120
+ self.max_position_embeddings = max_position_embeddings
121
+ self.initializer_range = initializer_range
122
+ self.layer_norm_eps = layer_norm_eps
123
+ self.position_embedding_type = position_embedding_type
124
+ self.use_cache = use_cache
125
+
126
+
127
+ __all__ = ["BertGenerationConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py ADDED
@@ -0,0 +1,880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
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 BERT model specific for generation."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
30
+ from ...utils import auto_docstring, logging
31
+ from ...utils.deprecation import deprecate_kwarg
32
+ from .configuration_bert_generation import BertGenerationConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BertGeneration
39
+ class BertGenerationSelfOutput(nn.Module):
40
+ def __init__(self, config):
41
+ super().__init__()
42
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
43
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
44
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
45
+
46
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
47
+ hidden_states = self.dense(hidden_states)
48
+ hidden_states = self.dropout(hidden_states)
49
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
50
+ return hidden_states
51
+
52
+
53
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->BertGeneration
54
+ class BertGenerationSelfAttention(nn.Module):
55
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
56
+ super().__init__()
57
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
58
+ raise ValueError(
59
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
60
+ f"heads ({config.num_attention_heads})"
61
+ )
62
+
63
+ self.num_attention_heads = config.num_attention_heads
64
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
65
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
66
+
67
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
68
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
69
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
70
+
71
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
72
+ self.position_embedding_type = position_embedding_type or getattr(
73
+ config, "position_embedding_type", "absolute"
74
+ )
75
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
76
+ self.max_position_embeddings = config.max_position_embeddings
77
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
78
+
79
+ self.is_decoder = config.is_decoder
80
+ self.layer_idx = layer_idx
81
+
82
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
83
+ def forward(
84
+ self,
85
+ hidden_states: torch.Tensor,
86
+ attention_mask: Optional[torch.FloatTensor] = None,
87
+ head_mask: Optional[torch.FloatTensor] = None,
88
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
89
+ past_key_values: Optional[Cache] = None,
90
+ output_attentions: Optional[bool] = False,
91
+ cache_position: Optional[torch.Tensor] = None,
92
+ ) -> tuple[torch.Tensor]:
93
+ batch_size, seq_length, _ = hidden_states.shape
94
+ query_layer = self.query(hidden_states)
95
+ query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
96
+ 1, 2
97
+ )
98
+
99
+ is_updated = False
100
+ is_cross_attention = encoder_hidden_states is not None
101
+ if past_key_values is not None:
102
+ if isinstance(past_key_values, EncoderDecoderCache):
103
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
104
+ if is_cross_attention:
105
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
106
+ curr_past_key_value = past_key_values.cross_attention_cache
107
+ else:
108
+ curr_past_key_value = past_key_values.self_attention_cache
109
+ else:
110
+ curr_past_key_value = past_key_values
111
+
112
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
113
+ if is_cross_attention and past_key_values is not None and is_updated:
114
+ # reuse k,v, cross_attentions
115
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
116
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
117
+ else:
118
+ key_layer = self.key(current_states)
119
+ key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
120
+ 1, 2
121
+ )
122
+ value_layer = self.value(current_states)
123
+ value_layer = value_layer.view(
124
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
125
+ ).transpose(1, 2)
126
+
127
+ if past_key_values is not None:
128
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
129
+ cache_position = cache_position if not is_cross_attention else None
130
+ key_layer, value_layer = curr_past_key_value.update(
131
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
132
+ )
133
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
134
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
135
+ past_key_values.is_updated[self.layer_idx] = True
136
+
137
+ # Take the dot product between "query" and "key" to get the raw attention scores.
138
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
139
+
140
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
141
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
142
+ if past_key_values is not None:
143
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
144
+ -1, 1
145
+ )
146
+ else:
147
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
148
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
149
+ distance = position_ids_l - position_ids_r
150
+
151
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
152
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
153
+
154
+ if self.position_embedding_type == "relative_key":
155
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
156
+ attention_scores = attention_scores + relative_position_scores
157
+ elif self.position_embedding_type == "relative_key_query":
158
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
159
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
160
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
161
+
162
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
163
+ if attention_mask is not None:
164
+ # Apply the attention mask is (precomputed for all layers in BertGenerationModel forward() function)
165
+ attention_scores = attention_scores + attention_mask
166
+
167
+ # Normalize the attention scores to probabilities.
168
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
169
+
170
+ # This is actually dropping out entire tokens to attend to, which might
171
+ # seem a bit unusual, but is taken from the original Transformer paper.
172
+ attention_probs = self.dropout(attention_probs)
173
+
174
+ # Mask heads if we want to
175
+ if head_mask is not None:
176
+ attention_probs = attention_probs * head_mask
177
+
178
+ context_layer = torch.matmul(attention_probs, value_layer)
179
+
180
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
181
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
182
+ context_layer = context_layer.view(new_context_layer_shape)
183
+
184
+ return context_layer, attention_probs
185
+
186
+
187
+ BERT_GENERATION_SELF_ATTENTION_CLASSES = {
188
+ "eager": BertGenerationSelfAttention,
189
+ }
190
+
191
+
192
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BertGeneration,BERT->BERT_GENERATION
193
+ class BertGenerationAttention(nn.Module):
194
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
195
+ super().__init__()
196
+ self.self = BERT_GENERATION_SELF_ATTENTION_CLASSES[config._attn_implementation](
197
+ config,
198
+ position_embedding_type=position_embedding_type,
199
+ layer_idx=layer_idx,
200
+ )
201
+ self.output = BertGenerationSelfOutput(config)
202
+ self.pruned_heads = set()
203
+
204
+ def prune_heads(self, heads):
205
+ if len(heads) == 0:
206
+ return
207
+ heads, index = find_pruneable_heads_and_indices(
208
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
209
+ )
210
+
211
+ # Prune linear layers
212
+ self.self.query = prune_linear_layer(self.self.query, index)
213
+ self.self.key = prune_linear_layer(self.self.key, index)
214
+ self.self.value = prune_linear_layer(self.self.value, index)
215
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
216
+
217
+ # Update hyper params and store pruned heads
218
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
219
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
220
+ self.pruned_heads = self.pruned_heads.union(heads)
221
+
222
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
223
+ def forward(
224
+ self,
225
+ hidden_states: torch.Tensor,
226
+ attention_mask: Optional[torch.FloatTensor] = None,
227
+ head_mask: Optional[torch.FloatTensor] = None,
228
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
229
+ past_key_values: Optional[Cache] = None,
230
+ output_attentions: Optional[bool] = False,
231
+ cache_position: Optional[torch.Tensor] = None,
232
+ ) -> tuple[torch.Tensor]:
233
+ self_outputs = self.self(
234
+ hidden_states,
235
+ attention_mask=attention_mask,
236
+ head_mask=head_mask,
237
+ encoder_hidden_states=encoder_hidden_states,
238
+ past_key_values=past_key_values,
239
+ output_attentions=output_attentions,
240
+ cache_position=cache_position,
241
+ )
242
+ attention_output = self.output(self_outputs[0], hidden_states)
243
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
244
+ return outputs
245
+
246
+
247
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BertGeneration
248
+ class BertGenerationIntermediate(nn.Module):
249
+ def __init__(self, config):
250
+ super().__init__()
251
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
252
+ if isinstance(config.hidden_act, str):
253
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
254
+ else:
255
+ self.intermediate_act_fn = config.hidden_act
256
+
257
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
258
+ hidden_states = self.dense(hidden_states)
259
+ hidden_states = self.intermediate_act_fn(hidden_states)
260
+ return hidden_states
261
+
262
+
263
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
264
+ class BertGenerationOutput(nn.Module):
265
+ def __init__(self, config):
266
+ super().__init__()
267
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
268
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
269
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
270
+
271
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
272
+ hidden_states = self.dense(hidden_states)
273
+ hidden_states = self.dropout(hidden_states)
274
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
275
+ return hidden_states
276
+
277
+
278
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->BertGeneration
279
+ class BertGenerationLayer(GradientCheckpointingLayer):
280
+ def __init__(self, config, layer_idx=None):
281
+ super().__init__()
282
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
283
+ self.seq_len_dim = 1
284
+ self.attention = BertGenerationAttention(config, layer_idx=layer_idx)
285
+ self.is_decoder = config.is_decoder
286
+ self.add_cross_attention = config.add_cross_attention
287
+ if self.add_cross_attention:
288
+ if not self.is_decoder:
289
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
290
+ self.crossattention = BertGenerationAttention(
291
+ config, position_embedding_type="absolute", layer_idx=layer_idx
292
+ )
293
+ self.intermediate = BertGenerationIntermediate(config)
294
+ self.output = BertGenerationOutput(config)
295
+
296
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ attention_mask: Optional[torch.FloatTensor] = None,
301
+ head_mask: Optional[torch.FloatTensor] = None,
302
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
303
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
304
+ past_key_values: Optional[Cache] = None,
305
+ output_attentions: Optional[bool] = False,
306
+ cache_position: Optional[torch.Tensor] = None,
307
+ ) -> tuple[torch.Tensor]:
308
+ self_attention_outputs = self.attention(
309
+ hidden_states,
310
+ attention_mask=attention_mask,
311
+ head_mask=head_mask,
312
+ output_attentions=output_attentions,
313
+ past_key_values=past_key_values,
314
+ cache_position=cache_position,
315
+ )
316
+ attention_output = self_attention_outputs[0]
317
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
318
+
319
+ if self.is_decoder and encoder_hidden_states is not None:
320
+ if not hasattr(self, "crossattention"):
321
+ raise ValueError(
322
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
323
+ " by setting `config.add_cross_attention=True`"
324
+ )
325
+
326
+ cross_attention_outputs = self.crossattention(
327
+ attention_output,
328
+ attention_mask=encoder_attention_mask,
329
+ head_mask=head_mask,
330
+ encoder_hidden_states=encoder_hidden_states,
331
+ past_key_values=past_key_values,
332
+ output_attentions=output_attentions,
333
+ cache_position=cache_position,
334
+ )
335
+ attention_output = cross_attention_outputs[0]
336
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
337
+
338
+ layer_output = apply_chunking_to_forward(
339
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
340
+ )
341
+ outputs = (layer_output,) + outputs
342
+
343
+ return outputs
344
+
345
+ def feed_forward_chunk(self, attention_output):
346
+ intermediate_output = self.intermediate(attention_output)
347
+ layer_output = self.output(intermediate_output, attention_output)
348
+ return layer_output
349
+
350
+
351
+ class BertEncoder(nn.Module):
352
+ def __init__(self, config, layer_idx=None):
353
+ super().__init__()
354
+ self.config = config
355
+ self.layer = nn.ModuleList([BertGenerationLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
356
+ self.gradient_checkpointing = False
357
+
358
+ def forward(
359
+ self,
360
+ hidden_states: torch.Tensor,
361
+ attention_mask: Optional[torch.FloatTensor] = None,
362
+ head_mask: Optional[torch.FloatTensor] = None,
363
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
364
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
365
+ past_key_values: Optional[Cache] = None,
366
+ use_cache: Optional[bool] = None,
367
+ output_attentions: Optional[bool] = False,
368
+ output_hidden_states: Optional[bool] = False,
369
+ return_dict: Optional[bool] = True,
370
+ cache_position: Optional[torch.Tensor] = None,
371
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
372
+ all_hidden_states = () if output_hidden_states else None
373
+ all_self_attentions = () if output_attentions else None
374
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
375
+
376
+ if self.gradient_checkpointing and self.training:
377
+ if use_cache:
378
+ logger.warning_once(
379
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
380
+ )
381
+ use_cache = False
382
+
383
+ if use_cache and past_key_values is None:
384
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
385
+ if use_cache and isinstance(past_key_values, tuple):
386
+ logger.warning_once(
387
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
388
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
389
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
390
+ )
391
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
392
+
393
+ for i, layer_module in enumerate(self.layer):
394
+ if output_hidden_states:
395
+ all_hidden_states = all_hidden_states + (hidden_states,)
396
+
397
+ layer_head_mask = head_mask[i] if head_mask is not None else None
398
+
399
+ layer_outputs = layer_module(
400
+ hidden_states,
401
+ attention_mask,
402
+ layer_head_mask,
403
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
404
+ encoder_attention_mask=encoder_attention_mask,
405
+ past_key_values=past_key_values,
406
+ output_attentions=output_attentions,
407
+ cache_position=cache_position,
408
+ )
409
+
410
+ hidden_states = layer_outputs[0]
411
+ if output_attentions:
412
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
413
+ if self.config.add_cross_attention:
414
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
415
+
416
+ if output_hidden_states:
417
+ all_hidden_states = all_hidden_states + (hidden_states,)
418
+
419
+ if not return_dict:
420
+ return tuple(
421
+ v
422
+ for v in [
423
+ hidden_states,
424
+ past_key_values,
425
+ all_hidden_states,
426
+ all_self_attentions,
427
+ all_cross_attentions,
428
+ ]
429
+ if v is not None
430
+ )
431
+ return BaseModelOutputWithPastAndCrossAttentions(
432
+ last_hidden_state=hidden_states,
433
+ past_key_values=past_key_values,
434
+ hidden_states=all_hidden_states,
435
+ attentions=all_self_attentions,
436
+ cross_attentions=all_cross_attentions,
437
+ )
438
+
439
+
440
+ def load_tf_weights_in_bert_generation(
441
+ model, tf_hub_path, model_class, is_encoder_named_decoder=False, is_encoder=False
442
+ ):
443
+ try:
444
+ import numpy as np
445
+ import tensorflow.compat.v1 as tf
446
+ import tensorflow_hub as hub
447
+ import tensorflow_text # noqa: F401
448
+
449
+ tf.disable_eager_execution()
450
+ except ImportError:
451
+ logger.error(
452
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
453
+ "https://www.tensorflow.org/install/ for installation instructions."
454
+ )
455
+ raise
456
+ tf_model = hub.Module(tf_hub_path)
457
+ init = tf.global_variables_initializer()
458
+ with tf.Session() as sess:
459
+ init.run()
460
+ all_variables = tf_model.variable_map
461
+ keep_track_variables = all_variables.copy()
462
+ for key in list(all_variables.keys()):
463
+ if "global" in key:
464
+ logger.info(f"Skipping {key}...")
465
+ continue
466
+ if not is_encoder:
467
+ model_pointer = getattr(model, model_class)
468
+ else:
469
+ model_pointer = model
470
+ is_embedding = False
471
+ logger.info(f"Trying to match {key}...")
472
+ # remove start_string = "module/bert/"
473
+ sub_layers = key.split("/")[2:]
474
+ if is_encoder_named_decoder and sub_layers[0] == "encoder":
475
+ logger.info(f"Skipping encoder layer {key} for decoder")
476
+ continue
477
+ if is_encoder and sub_layers[0] == "decoder":
478
+ logger.info(f"Skipping decoder layer {key} for encoder")
479
+ continue
480
+ for i, sub_layer in enumerate(sub_layers):
481
+ if sub_layer == "embeddings":
482
+ is_embedding = True
483
+ elif sub_layer == "LayerNorm":
484
+ is_embedding = False
485
+ if "layer" in sub_layer:
486
+ model_pointer = model_pointer.layer[int(sub_layer.split("_")[-1])]
487
+ elif sub_layer in ["kernel", "gamma"]:
488
+ model_pointer = model_pointer.weight
489
+ elif sub_layer == "beta":
490
+ model_pointer = model_pointer.bias
491
+ elif sub_layer == "encdec":
492
+ model_pointer = model_pointer.crossattention.self
493
+ elif sub_layer == "encdec_output":
494
+ model_pointer = model_pointer.crossattention.output
495
+ elif is_encoder_named_decoder and sub_layer == "decoder":
496
+ model_pointer = model_pointer.encoder
497
+ else:
498
+ if sub_layer == "attention" and "encdec" in sub_layers[i + 1]:
499
+ continue
500
+ try:
501
+ model_pointer = getattr(model_pointer, sub_layer)
502
+ except AttributeError:
503
+ logger.info(f"Skipping to initialize {key} at {sub_layer}...")
504
+ raise AttributeError
505
+
506
+ array = np.asarray(sess.run(all_variables[key]))
507
+ if not is_embedding:
508
+ logger.info(f"Transposing numpy weight of shape {array.shape} for {key}")
509
+ array = np.transpose(array)
510
+ else:
511
+ model_pointer = model_pointer.weight
512
+
513
+ if model_pointer.shape != array.shape:
514
+ raise ValueError(f"Pointer shape {model_pointer.shape} and array shape {array.shape} mismatched")
515
+ logger.info(f"Initialize PyTorch weight {key}")
516
+
517
+ model_pointer.data = torch.from_numpy(array.astype(np.float32))
518
+ keep_track_variables.pop(key, None)
519
+
520
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(keep_track_variables.keys())}")
521
+ return model
522
+
523
+
524
+ class BertGenerationEmbeddings(nn.Module):
525
+ """Construct the embeddings from word and position embeddings."""
526
+
527
+ def __init__(self, config):
528
+ super().__init__()
529
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
530
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
531
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
532
+ # any TensorFlow checkpoint file
533
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
534
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
535
+
536
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
537
+ self.register_buffer(
538
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
539
+ )
540
+
541
+ def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
542
+ if input_ids is not None:
543
+ input_shape = input_ids.size()
544
+ else:
545
+ input_shape = inputs_embeds.size()[:-1]
546
+
547
+ seq_length = input_shape[1]
548
+
549
+ if position_ids is None:
550
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
551
+
552
+ if inputs_embeds is None:
553
+ inputs_embeds = self.word_embeddings(input_ids)
554
+ position_embeddings = self.position_embeddings(position_ids)
555
+
556
+ embeddings = inputs_embeds + position_embeddings
557
+ embeddings = self.LayerNorm(embeddings)
558
+ embeddings = self.dropout(embeddings)
559
+ return embeddings
560
+
561
+
562
+ @auto_docstring
563
+ class BertGenerationPreTrainedModel(PreTrainedModel):
564
+ config: BertGenerationConfig
565
+ base_model_prefix = "bert"
566
+ supports_gradient_checkpointing = True
567
+
568
+ def _init_weights(self, module):
569
+ """Initialize the weights"""
570
+ if isinstance(module, nn.Linear):
571
+ # Slightly different from the TF version which uses truncated_normal for initialization
572
+ # cf https://github.com/pytorch/pytorch/pull/5617
573
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
574
+ if module.bias is not None:
575
+ module.bias.data.zero_()
576
+ elif isinstance(module, nn.Embedding):
577
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
578
+ if module.padding_idx is not None:
579
+ module.weight.data[module.padding_idx].zero_()
580
+ elif isinstance(module, nn.LayerNorm):
581
+ module.bias.data.zero_()
582
+ module.weight.data.fill_(1.0)
583
+ elif isinstance(module, BertGenerationOnlyLMHead):
584
+ module.bias.data.zero_()
585
+
586
+
587
+ @auto_docstring(
588
+ custom_intro="""
589
+ The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.
590
+ """
591
+ )
592
+ class BertGenerationEncoder(BertGenerationPreTrainedModel):
593
+ """
594
+
595
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
596
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
597
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
598
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
599
+
600
+ This model should be used when leveraging Bert or Roberta checkpoints for the [`EncoderDecoderModel`] class as
601
+ described in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461)
602
+ by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
603
+
604
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
605
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
606
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
607
+ """
608
+
609
+ def __init__(self, config):
610
+ super().__init__(config)
611
+ self.config = config
612
+
613
+ self.embeddings = BertGenerationEmbeddings(config)
614
+ self.encoder = BertEncoder(config)
615
+
616
+ # Initialize weights and apply final processing
617
+ self.post_init()
618
+
619
+ def get_input_embeddings(self):
620
+ return self.embeddings.word_embeddings
621
+
622
+ def set_input_embeddings(self, value):
623
+ self.embeddings.word_embeddings = value
624
+
625
+ def _prune_heads(self, heads_to_prune):
626
+ """
627
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
628
+ class PreTrainedModel
629
+ """
630
+ for layer, heads in heads_to_prune.items():
631
+ self.encoder.layer[layer].attention.prune_heads(heads)
632
+
633
+ @auto_docstring
634
+ def forward(
635
+ self,
636
+ input_ids: Optional[torch.Tensor] = None,
637
+ attention_mask: Optional[torch.Tensor] = None,
638
+ position_ids: Optional[torch.Tensor] = None,
639
+ head_mask: Optional[torch.Tensor] = None,
640
+ inputs_embeds: Optional[torch.Tensor] = None,
641
+ encoder_hidden_states: Optional[torch.Tensor] = None,
642
+ encoder_attention_mask: Optional[torch.Tensor] = None,
643
+ past_key_values: Optional[Cache] = None,
644
+ use_cache: Optional[bool] = None,
645
+ output_attentions: Optional[bool] = None,
646
+ output_hidden_states: Optional[bool] = None,
647
+ return_dict: Optional[bool] = None,
648
+ **kwargs, # NOOP kwargs, for now
649
+ ) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]:
650
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
651
+ output_hidden_states = (
652
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
653
+ )
654
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
655
+
656
+ if self.config.is_decoder:
657
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
658
+ else:
659
+ use_cache = False
660
+
661
+ if input_ids is not None and inputs_embeds is not None:
662
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
663
+ elif input_ids is not None:
664
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
665
+ input_shape = input_ids.size()
666
+ elif inputs_embeds is not None:
667
+ input_shape = inputs_embeds.size()[:-1]
668
+ else:
669
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
670
+
671
+ batch_size, seq_length = input_shape
672
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
673
+
674
+ past_key_values_length = 0
675
+ if past_key_values is not None:
676
+ past_key_values_length = (
677
+ past_key_values[0][0].shape[-2]
678
+ if not isinstance(past_key_values, Cache)
679
+ else past_key_values.get_seq_length()
680
+ )
681
+
682
+ if attention_mask is None:
683
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
684
+
685
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
686
+ # ourselves in which case we just need to make it broadcastable to all heads.
687
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
688
+
689
+ # If a 2D or 3D attention mask is provided for the cross-attention
690
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
691
+ if self.config.is_decoder and encoder_hidden_states is not None:
692
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
693
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
694
+ if encoder_attention_mask is None:
695
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
696
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
697
+ else:
698
+ encoder_extended_attention_mask = None
699
+
700
+ # Prepare head mask if needed
701
+ # 1.0 in head_mask indicate we keep the head
702
+ # attention_probs has shape bsz x n_heads x N x N
703
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
704
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
705
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
706
+
707
+ embedding_output = self.embeddings(
708
+ input_ids=input_ids,
709
+ position_ids=position_ids,
710
+ inputs_embeds=inputs_embeds,
711
+ past_key_values_length=past_key_values_length,
712
+ )
713
+
714
+ encoder_outputs = self.encoder(
715
+ embedding_output,
716
+ attention_mask=extended_attention_mask,
717
+ head_mask=head_mask,
718
+ encoder_hidden_states=encoder_hidden_states,
719
+ encoder_attention_mask=encoder_extended_attention_mask,
720
+ past_key_values=past_key_values,
721
+ use_cache=use_cache,
722
+ output_attentions=output_attentions,
723
+ output_hidden_states=output_hidden_states,
724
+ return_dict=return_dict,
725
+ )
726
+ sequence_output = encoder_outputs[0]
727
+
728
+ if not return_dict:
729
+ return (sequence_output,) + encoder_outputs[1:]
730
+
731
+ return BaseModelOutputWithPastAndCrossAttentions(
732
+ last_hidden_state=sequence_output,
733
+ past_key_values=encoder_outputs.past_key_values,
734
+ hidden_states=encoder_outputs.hidden_states,
735
+ attentions=encoder_outputs.attentions,
736
+ cross_attentions=encoder_outputs.cross_attentions,
737
+ )
738
+
739
+
740
+ class BertGenerationOnlyLMHead(nn.Module):
741
+ def __init__(self, config):
742
+ super().__init__()
743
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
744
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
745
+ self.decoder.bias = self.bias
746
+
747
+ def forward(self, hidden_states):
748
+ logits = self.decoder(hidden_states)
749
+ return logits
750
+
751
+ def _tie_weights(self):
752
+ # For accelerate compatibility and to not break backward compatibility
753
+ if self.decoder.bias.device.type == "meta":
754
+ self.decoder.bias = self.bias
755
+ else:
756
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
757
+ self.bias = self.decoder.bias
758
+
759
+
760
+ @auto_docstring(
761
+ custom_intro="""
762
+ BertGeneration Model with a `language modeling` head on top for CLM fine-tuning.
763
+ """
764
+ )
765
+ class BertGenerationDecoder(BertGenerationPreTrainedModel, GenerationMixin):
766
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
767
+
768
+ def __init__(self, config):
769
+ super().__init__(config)
770
+
771
+ if not config.is_decoder:
772
+ logger.warning("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
773
+
774
+ self.bert = BertGenerationEncoder(config)
775
+ self.lm_head = BertGenerationOnlyLMHead(config)
776
+
777
+ # Initialize weights and apply final processing
778
+ self.post_init()
779
+
780
+ def get_output_embeddings(self):
781
+ return self.lm_head.decoder
782
+
783
+ def set_output_embeddings(self, new_embeddings):
784
+ self.lm_head.decoder = new_embeddings
785
+ self.lm_head.bias = new_embeddings.bias
786
+
787
+ @auto_docstring
788
+ def forward(
789
+ self,
790
+ input_ids: Optional[torch.Tensor] = None,
791
+ attention_mask: Optional[torch.Tensor] = None,
792
+ position_ids: Optional[torch.Tensor] = None,
793
+ head_mask: Optional[torch.Tensor] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ encoder_hidden_states: Optional[torch.Tensor] = None,
796
+ encoder_attention_mask: Optional[torch.Tensor] = None,
797
+ labels: Optional[torch.Tensor] = None,
798
+ past_key_values: Optional[Cache] = None,
799
+ use_cache: Optional[bool] = None,
800
+ output_attentions: Optional[bool] = None,
801
+ output_hidden_states: Optional[bool] = None,
802
+ return_dict: Optional[bool] = None,
803
+ **kwargs,
804
+ ) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
805
+ r"""
806
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
807
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
808
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
809
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
810
+
811
+ Example:
812
+
813
+ ```python
814
+ >>> from transformers import AutoTokenizer, BertGenerationDecoder, BertGenerationConfig
815
+ >>> import torch
816
+
817
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
818
+ >>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
819
+ >>> config.is_decoder = True
820
+ >>> model = BertGenerationDecoder.from_pretrained(
821
+ ... "google/bert_for_seq_generation_L-24_bbc_encoder", config=config
822
+ ... )
823
+
824
+ >>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
825
+ >>> outputs = model(**inputs)
826
+
827
+ >>> prediction_logits = outputs.logits
828
+ ```"""
829
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
830
+ if labels is not None:
831
+ use_cache = False
832
+
833
+ outputs = self.bert(
834
+ input_ids,
835
+ attention_mask=attention_mask,
836
+ position_ids=position_ids,
837
+ head_mask=head_mask,
838
+ inputs_embeds=inputs_embeds,
839
+ encoder_hidden_states=encoder_hidden_states,
840
+ encoder_attention_mask=encoder_attention_mask,
841
+ past_key_values=past_key_values,
842
+ use_cache=use_cache,
843
+ output_attentions=output_attentions,
844
+ output_hidden_states=output_hidden_states,
845
+ return_dict=return_dict,
846
+ **kwargs,
847
+ )
848
+
849
+ sequence_output = outputs[0]
850
+ prediction_scores = self.lm_head(sequence_output)
851
+
852
+ lm_loss = None
853
+ if labels is not None:
854
+ lm_loss = self.loss_function(
855
+ prediction_scores,
856
+ labels,
857
+ vocab_size=self.config.vocab_size,
858
+ **kwargs,
859
+ )
860
+
861
+ if not return_dict:
862
+ output = (prediction_scores,) + outputs[1:]
863
+ return ((lm_loss,) + output) if lm_loss is not None else output
864
+
865
+ return CausalLMOutputWithCrossAttentions(
866
+ loss=lm_loss,
867
+ logits=prediction_scores,
868
+ past_key_values=outputs.past_key_values,
869
+ hidden_states=outputs.hidden_states,
870
+ attentions=outputs.attentions,
871
+ cross_attentions=outputs.cross_attentions,
872
+ )
873
+
874
+
875
+ __all__ = [
876
+ "BertGenerationDecoder",
877
+ "BertGenerationEncoder",
878
+ "BertGenerationPreTrainedModel",
879
+ "load_tf_weights_in_bert_generation",
880
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, 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
+ """Tokenization class for model BertGeneration."""
16
+
17
+ import os
18
+ from shutil import copyfile
19
+ from typing import Any, Optional
20
+
21
+ import sentencepiece as spm
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+ from ...utils.import_utils import requires
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
31
+
32
+
33
+ @requires(backends=("sentencepiece",))
34
+ class BertGenerationTokenizer(PreTrainedTokenizer):
35
+ """
36
+ Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
37
+
38
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
39
+ this superclass for more information regarding those methods.
40
+
41
+ Args:
42
+ vocab_file (`str`):
43
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
44
+ contains the vocabulary necessary to instantiate a tokenizer.
45
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
46
+ The begin of sequence token.
47
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
48
+ The end of sequence token.
49
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
50
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
51
+ token instead.
52
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
53
+ The token used for padding, for example when batching sequences of different lengths.
54
+ sep_token (`str`, *optional*, defaults to `"<::::>"`):
55
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
56
+ sequence classification or for a text and a question for question answering. It is also used as the last
57
+ token of a sequence built with special tokens.
58
+ sp_model_kwargs (`dict`, *optional*):
59
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
60
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
61
+ to set:
62
+
63
+ - `enable_sampling`: Enable subword regularization.
64
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
65
+
66
+ - `nbest_size = {0,1}`: No sampling is performed.
67
+ - `nbest_size > 1`: samples from the nbest_size results.
68
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
69
+ using forward-filtering-and-backward-sampling algorithm.
70
+
71
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
72
+ BPE-dropout.
73
+ """
74
+
75
+ vocab_files_names = VOCAB_FILES_NAMES
76
+ prefix_tokens: list[int] = []
77
+ model_input_names = ["input_ids", "attention_mask"]
78
+
79
+ def __init__(
80
+ self,
81
+ vocab_file,
82
+ bos_token="<s>",
83
+ eos_token="</s>",
84
+ unk_token="<unk>",
85
+ pad_token="<pad>",
86
+ sep_token="<::::>",
87
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
88
+ **kwargs,
89
+ ) -> None:
90
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
91
+
92
+ self.vocab_file = vocab_file
93
+
94
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
95
+ self.sp_model.Load(vocab_file)
96
+
97
+ # Add extra_ids to the special token list
98
+ super().__init__(
99
+ bos_token=bos_token,
100
+ eos_token=eos_token,
101
+ unk_token=unk_token,
102
+ pad_token=pad_token,
103
+ sep_token=sep_token,
104
+ sp_model_kwargs=self.sp_model_kwargs,
105
+ **kwargs,
106
+ )
107
+
108
+ @property
109
+ def vocab_size(self):
110
+ return self.sp_model.get_piece_size()
111
+
112
+ def get_vocab(self):
113
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
114
+ vocab.update(self.added_tokens_encoder)
115
+ return vocab
116
+
117
+ def __getstate__(self):
118
+ state = self.__dict__.copy()
119
+ state["sp_model"] = None
120
+ return state
121
+
122
+ def __setstate__(self, d):
123
+ self.__dict__ = d
124
+
125
+ # for backward compatibility
126
+ if not hasattr(self, "sp_model_kwargs"):
127
+ self.sp_model_kwargs = {}
128
+
129
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
130
+ self.sp_model.Load(self.vocab_file)
131
+
132
+ def _tokenize(self, text: str) -> list[str]:
133
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
134
+ return self.sp_model.encode(text, out_type=str)
135
+
136
+ def _convert_token_to_id(self, token):
137
+ """Converts a token (str) in an id using the vocab."""
138
+ return self.sp_model.piece_to_id(token)
139
+
140
+ def _convert_id_to_token(self, index):
141
+ """Converts an index (integer) in a token (str) using the vocab."""
142
+ token = self.sp_model.IdToPiece(index)
143
+ return token
144
+
145
+ def convert_tokens_to_string(self, tokens):
146
+ """Converts a sequence of tokens (string) in a single string."""
147
+ current_sub_tokens = []
148
+ out_string = ""
149
+ for token in tokens:
150
+ # make sure that special tokens are not decoded using sentencepiece model
151
+ if token in self.all_special_tokens:
152
+ out_string += self.sp_model.decode(current_sub_tokens) + token
153
+ current_sub_tokens = []
154
+ else:
155
+ current_sub_tokens.append(token)
156
+ out_string += self.sp_model.decode(current_sub_tokens)
157
+ return out_string.strip()
158
+
159
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
160
+ if not os.path.isdir(save_directory):
161
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
162
+ return
163
+ out_vocab_file = os.path.join(
164
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
165
+ )
166
+
167
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
168
+ copyfile(self.vocab_file, out_vocab_file)
169
+ elif not os.path.isfile(self.vocab_file):
170
+ with open(out_vocab_file, "wb") as fi:
171
+ content_spiece_model = self.sp_model.serialized_model_proto()
172
+ fi.write(content_spiece_model)
173
+
174
+ return (out_vocab_file,)
175
+
176
+
177
+ __all__ = ["BertGenerationTokenizer"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/__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_big_bird import *
22
+ from .modeling_big_bird import *
23
+ from .modeling_flax_big_bird import *
24
+ from .tokenization_big_bird import *
25
+ from .tokenization_big_bird_fast 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/configuration_big_bird.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research and The HuggingFace Inc. team. 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
+ """BigBird model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from collections.abc import Mapping
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...onnx import OnnxConfig
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class BigBirdConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`BigBirdModel`]. It is used to instantiate an
31
+ BigBird model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of the BigBird
33
+ [google/bigbird-roberta-base](https://huggingface.co/google/bigbird-roberta-base) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 50358):
41
+ Vocabulary size of the BigBird model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`BigBirdModel`].
43
+ hidden_size (`int`, *optional*, defaults to 768):
44
+ Dimension of the encoder layers and the pooler layer.
45
+ num_hidden_layers (`int`, *optional*, defaults to 12):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 12):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ intermediate_size (`int`, *optional*, defaults to 3072):
50
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
51
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
52
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
53
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
54
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
55
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
56
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
57
+ The dropout ratio for the attention probabilities.
58
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
59
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
60
+ just in case (e.g., 1024 or 2048 or 4096).
61
+ type_vocab_size (`int`, *optional*, defaults to 2):
62
+ The vocabulary size of the `token_type_ids` passed when calling [`BigBirdModel`].
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
66
+ The epsilon used by the layer normalization layers.
67
+ is_decoder (`bool`, *optional*, defaults to `False`):
68
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ attention_type (`str`, *optional*, defaults to `"block_sparse"`)
73
+ Whether to use block sparse attention (with n complexity) as introduced in paper or original attention
74
+ layer (with n^2 complexity). Possible values are `"original_full"` and `"block_sparse"`.
75
+ use_bias (`bool`, *optional*, defaults to `True`)
76
+ Whether to use bias in query, key, value.
77
+ rescale_embeddings (`bool`, *optional*, defaults to `False`)
78
+ Whether to rescale embeddings with (hidden_size ** 0.5).
79
+ block_size (`int`, *optional*, defaults to 64)
80
+ Size of each block. Useful only when `attention_type == "block_sparse"`.
81
+ num_random_blocks (`int`, *optional*, defaults to 3)
82
+ Each query is going to attend these many number of random blocks. Useful only when `attention_type ==
83
+ "block_sparse"`.
84
+ classifier_dropout (`float`, *optional*):
85
+ The dropout ratio for the classification head.
86
+
87
+ Example:
88
+
89
+ ```python
90
+ >>> from transformers import BigBirdConfig, BigBirdModel
91
+
92
+ >>> # Initializing a BigBird google/bigbird-roberta-base style configuration
93
+ >>> configuration = BigBirdConfig()
94
+
95
+ >>> # Initializing a model (with random weights) from the google/bigbird-roberta-base style configuration
96
+ >>> model = BigBirdModel(configuration)
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "big_bird"
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=50358,
107
+ hidden_size=768,
108
+ num_hidden_layers=12,
109
+ num_attention_heads=12,
110
+ intermediate_size=3072,
111
+ hidden_act="gelu_new",
112
+ hidden_dropout_prob=0.1,
113
+ attention_probs_dropout_prob=0.1,
114
+ max_position_embeddings=4096,
115
+ type_vocab_size=2,
116
+ initializer_range=0.02,
117
+ layer_norm_eps=1e-12,
118
+ use_cache=True,
119
+ pad_token_id=0,
120
+ bos_token_id=1,
121
+ eos_token_id=2,
122
+ sep_token_id=66,
123
+ attention_type="block_sparse",
124
+ use_bias=True,
125
+ rescale_embeddings=False,
126
+ block_size=64,
127
+ num_random_blocks=3,
128
+ classifier_dropout=None,
129
+ **kwargs,
130
+ ):
131
+ super().__init__(
132
+ pad_token_id=pad_token_id,
133
+ bos_token_id=bos_token_id,
134
+ eos_token_id=eos_token_id,
135
+ sep_token_id=sep_token_id,
136
+ **kwargs,
137
+ )
138
+
139
+ self.vocab_size = vocab_size
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.hidden_size = hidden_size
142
+ self.num_hidden_layers = num_hidden_layers
143
+ self.num_attention_heads = num_attention_heads
144
+ self.intermediate_size = intermediate_size
145
+ self.hidden_act = hidden_act
146
+ self.hidden_dropout_prob = hidden_dropout_prob
147
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
148
+ self.initializer_range = initializer_range
149
+ self.type_vocab_size = type_vocab_size
150
+ self.layer_norm_eps = layer_norm_eps
151
+ self.use_cache = use_cache
152
+
153
+ self.rescale_embeddings = rescale_embeddings
154
+ self.attention_type = attention_type
155
+ self.use_bias = use_bias
156
+ self.block_size = block_size
157
+ self.num_random_blocks = num_random_blocks
158
+ self.classifier_dropout = classifier_dropout
159
+
160
+
161
+ class BigBirdOnnxConfig(OnnxConfig):
162
+ @property
163
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
164
+ if self.task == "multiple-choice":
165
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
166
+ else:
167
+ dynamic_axis = {0: "batch", 1: "sequence"}
168
+ return OrderedDict(
169
+ [
170
+ ("input_ids", dynamic_axis),
171
+ ("attention_mask", dynamic_axis),
172
+ ]
173
+ )
174
+
175
+
176
+ __all__ = ["BigBirdConfig", "BigBirdOnnxConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/modeling_big_bird.py ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/modeling_flax_big_bird.py ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/tokenization_big_bird.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research and The HuggingFace Inc. team. 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
+ """Tokenization classes for BigBird."""
16
+
17
+ import os
18
+ import re
19
+ from shutil import copyfile
20
+ from typing import Any, Optional
21
+
22
+ import sentencepiece as spm
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+ from ...utils.import_utils import requires
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
32
+
33
+
34
+ @requires(backends=("sentencepiece",))
35
+ class BigBirdTokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct a BigBird tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
38
+
39
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
40
+ this superclass for more information regarding those methods.
41
+
42
+ Args:
43
+ vocab_file (`str`):
44
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
45
+ contains the vocabulary necessary to instantiate 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
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
50
+ The begin of sequence token.
51
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
52
+ The end of sequence token.
53
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
54
+ The token used for padding, for example when batching sequences of different lengths.
55
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
56
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
57
+ sequence classification or for a text and a question for question answering. It is also used as the last
58
+ token of a sequence built with special tokens.
59
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
60
+ The token used for masking values. This is the token used when training this model with masked language
61
+ modeling. This is the token which the model will try to predict.
62
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
63
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
64
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
65
+ sp_model_kwargs (`dict`, *optional*):
66
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
67
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
68
+ to set:
69
+
70
+ - `enable_sampling`: Enable subword regularization.
71
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
72
+
73
+ - `nbest_size = {0,1}`: No sampling is performed.
74
+ - `nbest_size > 1`: samples from the nbest_size results.
75
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
76
+ using forward-filtering-and-backward-sampling algorithm.
77
+
78
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
79
+ BPE-dropout.
80
+ """
81
+
82
+ vocab_files_names = VOCAB_FILES_NAMES
83
+ model_input_names = ["input_ids", "attention_mask"]
84
+ prefix_tokens: list[int] = []
85
+
86
+ def __init__(
87
+ self,
88
+ vocab_file,
89
+ unk_token="<unk>",
90
+ bos_token="<s>",
91
+ eos_token="</s>",
92
+ pad_token="<pad>",
93
+ sep_token="[SEP]",
94
+ mask_token="[MASK]",
95
+ cls_token="[CLS]",
96
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
97
+ **kwargs,
98
+ ) -> None:
99
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
100
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
101
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
102
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
103
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
104
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
105
+
106
+ # Mask token behave like a normal word, i.e. include the space before it
107
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
108
+
109
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
110
+
111
+ self.vocab_file = vocab_file
112
+
113
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
114
+ self.sp_model.Load(vocab_file)
115
+
116
+ super().__init__(
117
+ bos_token=bos_token,
118
+ eos_token=eos_token,
119
+ unk_token=unk_token,
120
+ pad_token=pad_token,
121
+ sep_token=sep_token,
122
+ mask_token=mask_token,
123
+ cls_token=cls_token,
124
+ sp_model_kwargs=self.sp_model_kwargs,
125
+ **kwargs,
126
+ )
127
+
128
+ @property
129
+ def vocab_size(self):
130
+ return self.sp_model.get_piece_size()
131
+
132
+ def get_vocab(self):
133
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
134
+ vocab.update(self.added_tokens_encoder)
135
+ return vocab
136
+
137
+ def __getstate__(self):
138
+ state = self.__dict__.copy()
139
+ state["sp_model"] = None
140
+ return state
141
+
142
+ def __setstate__(self, d):
143
+ self.__dict__ = d
144
+
145
+ # for backward compatibility
146
+ if not hasattr(self, "sp_model_kwargs"):
147
+ self.sp_model_kwargs = {}
148
+
149
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
150
+ self.sp_model.Load(self.vocab_file)
151
+
152
+ def _tokenize(self, text: str) -> list[str]:
153
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
154
+ return self.sp_model.encode(text, out_type=str)
155
+
156
+ def _convert_token_to_id(self, token):
157
+ """Converts a token (str) in an id using the vocab."""
158
+ return self.sp_model.piece_to_id(token)
159
+
160
+ def _convert_id_to_token(self, index):
161
+ """Converts an index (integer) in a token (str) using the vocab."""
162
+ token = self.sp_model.IdToPiece(index)
163
+ return token
164
+
165
+ # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
166
+ def convert_tokens_to_string(self, tokens):
167
+ """Converts a sequence of tokens (string) in a single string."""
168
+ current_sub_tokens = []
169
+ out_string = ""
170
+ prev_is_special = False
171
+ for token in tokens:
172
+ # make sure that special tokens are not decoded using sentencepiece model
173
+ if token in self.all_special_tokens:
174
+ if not prev_is_special:
175
+ out_string += " "
176
+ out_string += self.sp_model.decode(current_sub_tokens) + token
177
+ prev_is_special = True
178
+ current_sub_tokens = []
179
+ else:
180
+ current_sub_tokens.append(token)
181
+ prev_is_special = False
182
+ out_string += self.sp_model.decode(current_sub_tokens)
183
+ return out_string.strip()
184
+
185
+ def _decode(
186
+ self,
187
+ token_ids: list[int],
188
+ skip_special_tokens: bool = False,
189
+ clean_up_tokenization_spaces: Optional[bool] = None,
190
+ spaces_between_special_tokens: bool = True,
191
+ **kwargs,
192
+ ) -> str:
193
+ self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
194
+
195
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
196
+
197
+ # To avoid mixing byte-level and unicode for byte-level BPT
198
+ # we need to build string separately for added tokens and byte-level tokens
199
+ # cf. https://github.com/huggingface/transformers/issues/1133
200
+ sub_texts = []
201
+ current_sub_text = []
202
+ for token in filtered_tokens:
203
+ if skip_special_tokens and token in self.all_special_ids:
204
+ continue
205
+ if token in self.added_tokens_encoder:
206
+ if current_sub_text:
207
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
208
+ current_sub_text = []
209
+ sub_texts.append(token)
210
+ else:
211
+ current_sub_text.append(token)
212
+ if current_sub_text:
213
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
214
+
215
+ # Mimic the behavior of the Rust tokenizer:
216
+ # No space before [MASK] and [SEP]
217
+ if spaces_between_special_tokens:
218
+ text = re.sub(r" (\[(MASK|SEP)\])", r"\1", " ".join(sub_texts))
219
+ else:
220
+ text = "".join(sub_texts)
221
+
222
+ clean_up_tokenization_spaces = (
223
+ clean_up_tokenization_spaces
224
+ if clean_up_tokenization_spaces is not None
225
+ else self.clean_up_tokenization_spaces
226
+ )
227
+ if clean_up_tokenization_spaces:
228
+ clean_text = self.clean_up_tokenization(text)
229
+ return clean_text
230
+ else:
231
+ return text
232
+
233
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
234
+ if not os.path.isdir(save_directory):
235
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
236
+ return
237
+ out_vocab_file = os.path.join(
238
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
239
+ )
240
+
241
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
242
+ copyfile(self.vocab_file, out_vocab_file)
243
+ elif not os.path.isfile(self.vocab_file):
244
+ with open(out_vocab_file, "wb") as fi:
245
+ content_spiece_model = self.sp_model.serialized_model_proto()
246
+ fi.write(content_spiece_model)
247
+
248
+ return (out_vocab_file,)
249
+
250
+ def build_inputs_with_special_tokens(
251
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
252
+ ) -> list[int]:
253
+ """
254
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
255
+ adding special tokens. A Big Bird sequence has the following format:
256
+
257
+ - single sequence: `[CLS] X [SEP]`
258
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
259
+
260
+ Args:
261
+ token_ids_0 (`List[int]`):
262
+ List of IDs to which the special tokens will be added.
263
+ token_ids_1 (`List[int]`, *optional*):
264
+ Optional second list of IDs for sequence pairs.
265
+
266
+ Returns:
267
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
268
+ """
269
+ if token_ids_1 is None:
270
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
271
+ cls = [self.cls_token_id]
272
+ sep = [self.sep_token_id]
273
+ return cls + token_ids_0 + sep + token_ids_1 + sep
274
+
275
+ def get_special_tokens_mask(
276
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
277
+ ) -> list[int]:
278
+ """
279
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
280
+ special tokens using the tokenizer `prepare_for_model` method.
281
+
282
+ Args:
283
+ token_ids_0 (`List[int]`):
284
+ List of IDs.
285
+ token_ids_1 (`List[int]`, *optional*):
286
+ Optional second list of IDs for sequence pairs.
287
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
288
+ Whether or not the token list is already formatted with special tokens for the model.
289
+
290
+ Returns:
291
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
292
+ """
293
+ if already_has_special_tokens:
294
+ return super().get_special_tokens_mask(
295
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
296
+ )
297
+
298
+ if token_ids_1 is None:
299
+ return [1] + ([0] * len(token_ids_0)) + [1]
300
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
301
+
302
+
303
+ __all__ = ["BigBirdTokenizer"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/big_bird/tokenization_big_bird_fast.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
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
+ """Tokenization classes for Big Bird model."""
16
+
17
+ import os
18
+ from shutil import copyfile
19
+ from typing import Optional
20
+
21
+ from ...tokenization_utils import AddedToken
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import is_sentencepiece_available, logging
24
+
25
+
26
+ if is_sentencepiece_available():
27
+ from .tokenization_big_bird import BigBirdTokenizer
28
+ else:
29
+ BigBirdTokenizer = None
30
+
31
+ logger = logging.get_logger(__name__)
32
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
33
+
34
+
35
+ SPIECE_UNDERLINE = "▁"
36
+
37
+
38
+ class BigBirdTokenizerFast(PreTrainedTokenizerFast):
39
+ """
40
+ Construct a "fast" BigBird tokenizer (backed by HuggingFace's *tokenizers* library). Based on
41
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
42
+ tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
43
+ this superclass for more information regarding those methods
44
+
45
+ Args:
46
+ vocab_file (`str`):
47
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
48
+ contains the vocabulary necessary to instantiate a tokenizer.
49
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
50
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
51
+
52
+ <Tip>
53
+
54
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
55
+ sequence. The token used is the `cls_token`.
56
+
57
+ </Tip>
58
+
59
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
60
+ The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
61
+ that is used for the end of sequence. The token used is the `sep_token`.
62
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
63
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
64
+ token instead.
65
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
66
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
67
+ sequence classification or for a text and a question for question answering. It is also used as the last
68
+ token of a sequence built with special tokens.
69
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
70
+ The token used for padding, for example when batching sequences of different lengths.
71
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
72
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
73
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
74
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
75
+ The token used for masking values. This is the token used when training this model with masked language
76
+ modeling. This is the token which the model will try to predict.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ slow_tokenizer_class = BigBirdTokenizer
81
+ model_input_names = ["input_ids", "attention_mask"]
82
+ prefix_tokens: list[int] = []
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_file=None,
87
+ tokenizer_file=None,
88
+ unk_token="<unk>",
89
+ bos_token="<s>",
90
+ eos_token="</s>",
91
+ pad_token="<pad>",
92
+ sep_token="[SEP]",
93
+ mask_token="[MASK]",
94
+ cls_token="[CLS]",
95
+ **kwargs,
96
+ ):
97
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
98
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
99
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
100
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
101
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
102
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
103
+
104
+ # Mask token behave like a normal word, i.e. include the space before it
105
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
106
+
107
+ super().__init__(
108
+ vocab_file,
109
+ tokenizer_file=tokenizer_file,
110
+ bos_token=bos_token,
111
+ eos_token=eos_token,
112
+ unk_token=unk_token,
113
+ sep_token=sep_token,
114
+ pad_token=pad_token,
115
+ cls_token=cls_token,
116
+ mask_token=mask_token,
117
+ **kwargs,
118
+ )
119
+
120
+ self.vocab_file = vocab_file
121
+
122
+ def build_inputs_with_special_tokens(
123
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
124
+ ) -> list[int]:
125
+ """
126
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
127
+ adding special tokens. An BigBird sequence has the following format:
128
+
129
+ - single sequence: `[CLS] X [SEP]`
130
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
131
+
132
+ Args:
133
+ token_ids_0 (`List[int]`):
134
+ List of IDs to which the special tokens will be added
135
+ token_ids_1 (`List[int]`, *optional*):
136
+ Optional second list of IDs for sequence pairs.
137
+
138
+ Returns:
139
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
140
+ """
141
+ sep = [self.sep_token_id]
142
+ cls = [self.cls_token_id]
143
+ if token_ids_1 is None:
144
+ return cls + token_ids_0 + sep
145
+ return cls + token_ids_0 + sep + token_ids_1 + sep
146
+
147
+ def get_special_tokens_mask(
148
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
149
+ ) -> list[int]:
150
+ """
151
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
152
+ special tokens using the tokenizer `prepare_for_model` method.
153
+
154
+ Args:
155
+ token_ids_0 (`List[int]`):
156
+ List of ids.
157
+ token_ids_1 (`List[int]`, *optional*):
158
+ Optional second list of IDs for sequence pairs.
159
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
160
+ Set to True if the token list is already formatted with special tokens for the model
161
+
162
+ Returns:
163
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
164
+ """
165
+
166
+ if already_has_special_tokens:
167
+ if token_ids_1 is not None:
168
+ raise ValueError(
169
+ "You should not supply a second sequence if the provided sequence of "
170
+ "ids is already formatted with special tokens for the model."
171
+ )
172
+ return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_0]
173
+
174
+ if token_ids_1 is None:
175
+ return [1] + ([0] * len(token_ids_0)) + [1]
176
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
177
+
178
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
179
+ if not self.can_save_slow_tokenizer:
180
+ raise ValueError(
181
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
182
+ "tokenizer."
183
+ )
184
+
185
+ if not os.path.isdir(save_directory):
186
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
187
+ return
188
+ out_vocab_file = os.path.join(
189
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
190
+ )
191
+
192
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
193
+ copyfile(self.vocab_file, out_vocab_file)
194
+
195
+ return (out_vocab_file,)
196
+
197
+
198
+ __all__ = ["BigBirdTokenizerFast"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_blip import *
22
+ from .image_processing_blip import *
23
+ from .image_processing_blip_fast import *
24
+ from .modeling_blip import *
25
+ from .modeling_blip_text import *
26
+ from .modeling_tf_blip import *
27
+ from .modeling_tf_blip_text import *
28
+ from .processing_blip import *
29
+ else:
30
+ import sys
31
+
32
+ _file = globals()["__file__"]
33
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/configuration_blip.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Blip model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class BlipTextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`BlipTextModel`]. It is used to instantiate a BLIP
27
+ text model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the `BlipText` used by the [base
29
+ architectures](https://huggingface.co/Salesforce/blip-vqa-base).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30524):
37
+ Vocabulary size of the `Blip` text model. Defines the number of different tokens that can be represented by
38
+ the `inputs_ids` passed when calling [`BlipModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ encoder_hidden_size (`int`, *optional*, defaults to 768):
42
+ Dimensionality of the encoder layers from the vision model.
43
+ intermediate_size (`int`, *optional*, defaults to 3072):
44
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
45
+ num_hidden_layers (`int`, *optional*, defaults to 12):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 8):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ max_position_embeddings (`int`, *optional*, defaults to 512):
50
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
51
+ just in case (e.g., 512 or 1024 or 2048).
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
55
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
56
+ The epsilon used by the layer normalization layers.
57
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
58
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for the attention probabilities.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ bos_token_id (`int`, *optional*, defaults to 30522):
64
+ The id of the `beginning-of-sequence` token.
65
+ eos_token_id (`int`, *optional*, defaults to 2):
66
+ The id of the `end-of-sequence` token.
67
+ pad_token_id (`int`, *optional*, defaults to 0):
68
+ The id of the `padding` token.
69
+ sep_token_id (`int`, *optional*, defaults to 102):
70
+ The id of the `separator` token.
71
+ is_decoder (`bool`, *optional*, defaults to `True`):
72
+ Whether the model is used as a decoder.
73
+ use_cache (`bool`, *optional*, defaults to `True`):
74
+ Whether or not the model should return the last key/values attentions (not used by all models).
75
+ label_smoothing (float, *optional*):
76
+ A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
77
+ become a mixture of the original ground truth and a uniform distribution as described in
78
+ `Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
79
+
80
+ Example:
81
+
82
+ ```python
83
+ >>> from transformers import BlipTextConfig, BlipTextModel
84
+
85
+ >>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
86
+ >>> configuration = BlipTextConfig()
87
+
88
+ >>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
89
+ >>> model = BlipTextModel(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "blip_text_model"
96
+ base_config_key = "text_config"
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=30524,
101
+ hidden_size=768,
102
+ encoder_hidden_size=768,
103
+ intermediate_size=3072,
104
+ projection_dim=768,
105
+ num_hidden_layers=12,
106
+ num_attention_heads=8,
107
+ max_position_embeddings=512,
108
+ hidden_act="gelu",
109
+ layer_norm_eps=1e-12,
110
+ hidden_dropout_prob=0.0,
111
+ attention_probs_dropout_prob=0.0,
112
+ initializer_range=0.02,
113
+ bos_token_id=30522,
114
+ eos_token_id=2,
115
+ pad_token_id=0,
116
+ sep_token_id=102,
117
+ is_decoder=True,
118
+ use_cache=True,
119
+ label_smoothing=0.0,
120
+ **kwargs,
121
+ ):
122
+ super().__init__(
123
+ pad_token_id=pad_token_id,
124
+ bos_token_id=bos_token_id,
125
+ eos_token_id=eos_token_id,
126
+ sep_token_id=sep_token_id,
127
+ **kwargs,
128
+ )
129
+
130
+ self.vocab_size = vocab_size
131
+ self.hidden_size = hidden_size
132
+ self.encoder_hidden_size = encoder_hidden_size
133
+ self.intermediate_size = intermediate_size
134
+ self.projection_dim = projection_dim
135
+ self.hidden_dropout_prob = hidden_dropout_prob
136
+ self.num_hidden_layers = num_hidden_layers
137
+ self.num_attention_heads = num_attention_heads
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.layer_norm_eps = layer_norm_eps
140
+ self.hidden_act = hidden_act
141
+ self.initializer_range = initializer_range
142
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
143
+ self.is_decoder = is_decoder
144
+ self.use_cache = use_cache
145
+ self.label_smoothing = label_smoothing
146
+
147
+
148
+ class BlipVisionConfig(PretrainedConfig):
149
+ r"""
150
+ This is the configuration class to store the configuration of a [`BlipVisionModel`]. It is used to instantiate a
151
+ BLIP vision model according to the specified arguments, defining the model architecture. Instantiating a
152
+ configuration defaults will yield a similar configuration to that of the Blip-base
153
+ [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
154
+
155
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
156
+ documentation from [`PretrainedConfig`] for more information.
157
+
158
+
159
+ Args:
160
+ hidden_size (`int`, *optional*, defaults to 768):
161
+ Dimensionality of the encoder layers and the pooler layer.
162
+ intermediate_size (`int`, *optional*, defaults to 3072):
163
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
164
+ num_hidden_layers (`int`, *optional*, defaults to 12):
165
+ Number of hidden layers in the Transformer encoder.
166
+ num_attention_heads (`int`, *optional*, defaults to 12):
167
+ Number of attention heads for each attention layer in the Transformer encoder.
168
+ image_size (`int`, *optional*, defaults to 384):
169
+ The size (resolution) of each image.
170
+ patch_size (`int`, *optional*, defaults to 16):
171
+ The size (resolution) of each patch.
172
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
173
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
174
+ `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
175
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
176
+ The epsilon used by the layer normalization layers.
177
+ attention_dropout (`float`, *optional*, defaults to 0.0):
178
+ The dropout ratio for the attention probabilities.
179
+ initializer_range (`float`, *optional*, defaults to 1e-10):
180
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
181
+
182
+ Example:
183
+
184
+ ```python
185
+ >>> from transformers import BlipVisionConfig, BlipVisionModel
186
+
187
+ >>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
188
+ >>> configuration = BlipVisionConfig()
189
+
190
+ >>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
191
+ >>> model = BlipVisionModel(configuration)
192
+
193
+ >>> # Accessing the model configuration
194
+ >>> configuration = model.config
195
+ ```"""
196
+
197
+ model_type = "blip_vision_model"
198
+ base_config_key = "vision_config"
199
+
200
+ def __init__(
201
+ self,
202
+ hidden_size=768,
203
+ intermediate_size=3072,
204
+ projection_dim=512,
205
+ num_hidden_layers=12,
206
+ num_attention_heads=12,
207
+ image_size=384,
208
+ patch_size=16,
209
+ hidden_act="gelu",
210
+ layer_norm_eps=1e-5,
211
+ attention_dropout=0.0,
212
+ initializer_range=1e-10,
213
+ **kwargs,
214
+ ):
215
+ super().__init__(**kwargs)
216
+
217
+ self.hidden_size = hidden_size
218
+ self.intermediate_size = intermediate_size
219
+ self.projection_dim = projection_dim
220
+ self.num_hidden_layers = num_hidden_layers
221
+ self.num_attention_heads = num_attention_heads
222
+ self.patch_size = patch_size
223
+ self.image_size = image_size
224
+ self.initializer_range = initializer_range
225
+ self.attention_dropout = attention_dropout
226
+ self.layer_norm_eps = layer_norm_eps
227
+ self.hidden_act = hidden_act
228
+
229
+
230
+ class BlipConfig(PretrainedConfig):
231
+ r"""
232
+ [`BlipConfig`] is the configuration class to store the configuration of a [`BlipModel`]. It is used to instantiate
233
+ a BLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
234
+ a configuration with the defaults will yield a similar configuration to that of the BLIP-base
235
+ [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
236
+
237
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
238
+ documentation from [`PretrainedConfig`] for more information.
239
+
240
+ Args:
241
+ text_config (`dict`, *optional*):
242
+ Dictionary of configuration options used to initialize [`BlipTextConfig`].
243
+ vision_config (`dict`, *optional*):
244
+ Dictionary of configuration options used to initialize [`BlipVisionConfig`].
245
+ projection_dim (`int`, *optional*, defaults to 512):
246
+ Dimensionality of text and vision projection layers.
247
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
248
+ The initial value of the *logit_scale* parameter. Default is used as per the original BLIP implementation.
249
+ image_text_hidden_size (`int`, *optional*, defaults to 256):
250
+ Dimensionality of the hidden state of the image-text fusion layer.
251
+ label_smoothing (float, optional, *optional*, defaults to 0.0):
252
+ A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
253
+ become a mixture of the original ground truth and a uniform distribution as described in
254
+ `Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
255
+ kwargs (*optional*):
256
+ Dictionary of keyword arguments.
257
+
258
+ Example:
259
+
260
+ ```python
261
+ >>> from transformers import BlipConfig, BlipModel
262
+
263
+ >>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
264
+ >>> configuration = BlipConfig()
265
+
266
+ >>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
267
+ >>> model = BlipModel(configuration)
268
+
269
+ >>> # Accessing the model configuration
270
+ >>> configuration = model.config
271
+
272
+ >>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
273
+
274
+ >>> # Initializing a BLIPText and BLIPVision configuration
275
+ >>> config_text = BlipTextConfig()
276
+ >>> config_vision = BlipVisionConfig()
277
+
278
+ >>> config = BlipConfig.from_text_vision_configs(config_text, config_vision)
279
+ ```"""
280
+
281
+ model_type = "blip"
282
+ sub_configs = {"text_config": BlipTextConfig, "vision_config": BlipVisionConfig}
283
+
284
+ def __init__(
285
+ self,
286
+ text_config=None,
287
+ vision_config=None,
288
+ projection_dim=512,
289
+ logit_scale_init_value=2.6592,
290
+ image_text_hidden_size=256,
291
+ label_smoothing=0.0,
292
+ **kwargs,
293
+ ):
294
+ super().__init__(**kwargs)
295
+
296
+ if text_config is None:
297
+ text_config = {}
298
+ logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values.")
299
+
300
+ if vision_config is None:
301
+ vision_config = {}
302
+ logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.")
303
+
304
+ self.text_config = BlipTextConfig(**text_config)
305
+ self.vision_config = BlipVisionConfig(**vision_config)
306
+
307
+ self.text_config.encoder_hidden_size = self.vision_config.hidden_size
308
+
309
+ self.projection_dim = projection_dim
310
+ self.logit_scale_init_value = logit_scale_init_value
311
+ self.initializer_factor = 1.0
312
+ self.initializer_range = 0.02
313
+ self.image_text_hidden_size = image_text_hidden_size
314
+ self.label_smoothing = label_smoothing
315
+
316
+
317
+ __all__ = ["BlipConfig", "BlipTextConfig", "BlipVisionConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Image processor class for BLIP."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import convert_to_rgb, resize, to_channel_dimension_format
23
+ from ...image_utils import (
24
+ OPENAI_CLIP_MEAN,
25
+ OPENAI_CLIP_STD,
26
+ ChannelDimension,
27
+ ImageInput,
28
+ PILImageResampling,
29
+ infer_channel_dimension_format,
30
+ is_scaled_image,
31
+ make_flat_list_of_images,
32
+ to_numpy_array,
33
+ valid_images,
34
+ validate_preprocess_arguments,
35
+ )
36
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
37
+
38
+
39
+ if is_vision_available():
40
+ import PIL
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class BlipImageProcessor(BaseImageProcessor):
47
+ r"""
48
+ Constructs a BLIP image processor.
49
+
50
+ Args:
51
+ do_resize (`bool`, *optional*, defaults to `True`):
52
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
53
+ `do_resize` parameter in the `preprocess` method.
54
+ size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`):
55
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
56
+ method.
57
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
58
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
59
+ overridden by the `resample` parameter in the `preprocess` method.
60
+ do_rescale (`bool`, *optional*, defaults to `True`):
61
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
62
+ `do_rescale` parameter in the `preprocess` method.
63
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
64
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
65
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
66
+ do_normalize (`bool`, *optional*, defaults to `True`):
67
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
68
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
69
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
70
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
71
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
72
+ overridden by the `image_mean` parameter in the `preprocess` method.
73
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
74
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
75
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
76
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
77
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
78
+ Whether to convert the image to RGB.
79
+ """
80
+
81
+ model_input_names = ["pixel_values"]
82
+
83
+ def __init__(
84
+ self,
85
+ do_resize: bool = True,
86
+ size: Optional[dict[str, int]] = None,
87
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
88
+ do_rescale: bool = True,
89
+ rescale_factor: Union[int, float] = 1 / 255,
90
+ do_normalize: bool = True,
91
+ image_mean: Optional[Union[float, list[float]]] = None,
92
+ image_std: Optional[Union[float, list[float]]] = None,
93
+ do_convert_rgb: bool = True,
94
+ **kwargs,
95
+ ) -> None:
96
+ super().__init__(**kwargs)
97
+ size = size if size is not None else {"height": 384, "width": 384}
98
+ size = get_size_dict(size, default_to_square=True)
99
+
100
+ self.do_resize = do_resize
101
+ self.size = size
102
+ self.resample = resample
103
+ self.do_rescale = do_rescale
104
+ self.rescale_factor = rescale_factor
105
+ self.do_normalize = do_normalize
106
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
107
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
108
+ self.do_convert_rgb = do_convert_rgb
109
+
110
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
111
+ def resize(
112
+ self,
113
+ image: np.ndarray,
114
+ size: dict[str, int],
115
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
116
+ data_format: Optional[Union[str, ChannelDimension]] = None,
117
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
118
+ **kwargs,
119
+ ) -> np.ndarray:
120
+ """
121
+ Resize an image to `(size["height"], size["width"])`.
122
+
123
+ Args:
124
+ image (`np.ndarray`):
125
+ Image to resize.
126
+ size (`dict[str, int]`):
127
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
128
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
129
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
130
+ data_format (`ChannelDimension` or `str`, *optional*):
131
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
132
+ image is used. Can be one of:
133
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
134
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
135
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
136
+ input_data_format (`ChannelDimension` or `str`, *optional*):
137
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
138
+ from the input image. Can be one of:
139
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
140
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
141
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
142
+
143
+ Returns:
144
+ `np.ndarray`: The resized image.
145
+ """
146
+ size = get_size_dict(size)
147
+ if "height" not in size or "width" not in size:
148
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
149
+ output_size = (size["height"], size["width"])
150
+ return resize(
151
+ image,
152
+ size=output_size,
153
+ resample=resample,
154
+ data_format=data_format,
155
+ input_data_format=input_data_format,
156
+ **kwargs,
157
+ )
158
+
159
+ @filter_out_non_signature_kwargs()
160
+ def preprocess(
161
+ self,
162
+ images: ImageInput,
163
+ do_resize: Optional[bool] = None,
164
+ size: Optional[dict[str, int]] = None,
165
+ resample: Optional[PILImageResampling] = None,
166
+ do_rescale: Optional[bool] = None,
167
+ rescale_factor: Optional[float] = None,
168
+ do_normalize: Optional[bool] = None,
169
+ image_mean: Optional[Union[float, list[float]]] = None,
170
+ image_std: Optional[Union[float, list[float]]] = None,
171
+ return_tensors: Optional[Union[str, TensorType]] = None,
172
+ do_convert_rgb: Optional[bool] = None,
173
+ data_format: ChannelDimension = ChannelDimension.FIRST,
174
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
175
+ ) -> PIL.Image.Image:
176
+ """
177
+ Preprocess an image or batch of images.
178
+
179
+ Args:
180
+ images (`ImageInput`):
181
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
182
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
183
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
184
+ Whether to resize the image.
185
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
186
+ Controls the size of the image after `resize`. The shortest edge of the image is resized to
187
+ `size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
188
+ is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
189
+ edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
190
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
191
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
192
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
193
+ Whether to rescale the image values between [0 - 1].
194
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
195
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
196
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
197
+ Whether to normalize the image.
198
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
199
+ Image mean to normalize the image by if `do_normalize` is set to `True`.
200
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
201
+ Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
202
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
203
+ Whether to convert the image to RGB.
204
+ return_tensors (`str` or `TensorType`, *optional*):
205
+ The type of tensors to return. Can be one of:
206
+ - Unset: Return a list of `np.ndarray`.
207
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
208
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
209
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
210
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
211
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
212
+ The channel dimension format for the output image. Can be one of:
213
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
214
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
215
+ - Unset: Use the channel dimension format of the input image.
216
+ input_data_format (`ChannelDimension` or `str`, *optional*):
217
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
218
+ from the input image. Can be one of:
219
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
220
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
221
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
222
+ """
223
+ do_resize = do_resize if do_resize is not None else self.do_resize
224
+ resample = resample if resample is not None else self.resample
225
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
226
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
227
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
228
+ image_mean = image_mean if image_mean is not None else self.image_mean
229
+ image_std = image_std if image_std is not None else self.image_std
230
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
231
+
232
+ size = size if size is not None else self.size
233
+ size = get_size_dict(size, default_to_square=False)
234
+ images = self.fetch_images(images)
235
+ images = make_flat_list_of_images(images)
236
+
237
+ if not valid_images(images):
238
+ raise ValueError(
239
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
240
+ "torch.Tensor, tf.Tensor or jax.ndarray."
241
+ )
242
+
243
+ validate_preprocess_arguments(
244
+ do_rescale=do_rescale,
245
+ rescale_factor=rescale_factor,
246
+ do_normalize=do_normalize,
247
+ image_mean=image_mean,
248
+ image_std=image_std,
249
+ do_resize=do_resize,
250
+ size=size,
251
+ resample=resample,
252
+ )
253
+ # PIL RGBA images are converted to RGB
254
+ if do_convert_rgb:
255
+ images = [convert_to_rgb(image) for image in images]
256
+
257
+ # All transformations expect numpy arrays.
258
+ images = [to_numpy_array(image) for image in images]
259
+
260
+ if do_rescale and is_scaled_image(images[0]):
261
+ logger.warning_once(
262
+ "It looks like you are trying to rescale already rescaled images. If the input"
263
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
264
+ )
265
+
266
+ if input_data_format is None:
267
+ # We assume that all images have the same channel dimension format.
268
+ input_data_format = infer_channel_dimension_format(images[0])
269
+
270
+ if do_resize:
271
+ images = [
272
+ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
273
+ for image in images
274
+ ]
275
+
276
+ if do_rescale:
277
+ images = [
278
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
279
+ for image in images
280
+ ]
281
+
282
+ if do_normalize:
283
+ images = [
284
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
285
+ for image in images
286
+ ]
287
+
288
+ images = [
289
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
290
+ ]
291
+
292
+ encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
293
+
294
+ return encoded_outputs
295
+
296
+
297
+ __all__ = ["BlipImageProcessor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip_fast.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. 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
+ """Fast Image processor class for BLIP."""
16
+
17
+ from ...image_processing_utils_fast import BaseImageProcessorFast
18
+ from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring
23
+ class BlipImageProcessorFast(BaseImageProcessorFast):
24
+ # To be checked against the slow image processor
25
+ # None values left after checking can be removed
26
+ resample = PILImageResampling.BICUBIC
27
+ image_mean = OPENAI_CLIP_MEAN
28
+ image_std = OPENAI_CLIP_STD
29
+ size = {"height": 384, "width": 384}
30
+ do_resize = True
31
+ do_rescale = True
32
+ do_normalize = True
33
+ do_convert_rgb = True
34
+
35
+
36
+ __all__ = ["BlipImageProcessorFast"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py ADDED
@@ -0,0 +1,1308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. 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 BLIP model."""
16
+
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn.functional import normalize
24
+
25
+ from ...activations import ACT2FN
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...processing_utils import Unpack
31
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_int
32
+ from ...utils.generic import check_model_inputs
33
+ from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
34
+ from .modeling_blip_text import BlipTextLMHeadModel, BlipTextModel
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ # Copied from transformers.models.clip.modeling_clip.contrastive_loss
41
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
42
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
43
+
44
+
45
+ # Copied from transformers.models.clip.modeling_clip.clip_loss with clip->blip
46
+ def blip_loss(similarity: torch.Tensor) -> torch.Tensor:
47
+ caption_loss = contrastive_loss(similarity)
48
+ image_loss = contrastive_loss(similarity.t())
49
+ return (caption_loss + image_loss) / 2.0
50
+
51
+
52
+ @dataclass
53
+ @auto_docstring(
54
+ custom_intro="""
55
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
56
+ last hidden states. This class also adds the loss term from the text decoder.
57
+ """
58
+ )
59
+ class BlipForConditionalGenerationModelOutput(ModelOutput):
60
+ r"""
61
+ loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
62
+ Language modeling loss from the text decoder.
63
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
64
+ Prediction scores of the language modeling head of the text decoder model.
65
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*):
66
+ The image embeddings obtained after applying the Vision Transformer model to the input image.
67
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
68
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
69
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
70
+
71
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
72
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed):
73
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
74
+ sequence_length)`.
75
+
76
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
77
+ heads.
78
+ """
79
+
80
+ loss: Optional[tuple[torch.FloatTensor]] = None
81
+ logits: Optional[tuple[torch.FloatTensor]] = None
82
+ image_embeds: Optional[torch.FloatTensor] = None
83
+ last_hidden_state: Optional[torch.FloatTensor] = None
84
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
85
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
86
+
87
+ @property
88
+ def decoder_logits(self):
89
+ warnings.warn(
90
+ "`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
91
+ " Please use the `logits` attribute to retrieve the final output instead.",
92
+ FutureWarning,
93
+ )
94
+ return self.logits
95
+
96
+
97
+ @dataclass
98
+ @auto_docstring(
99
+ custom_intro="""
100
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
101
+ last hidden states. This class also adds the loss term from the text decoder.
102
+ """
103
+ )
104
+ class BlipTextVisionModelOutput(ModelOutput):
105
+ r"""
106
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
107
+ Language modeling loss from the text decoder.
108
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
109
+ The image embeddings obtained by applying the projection layer to the pooler_output.
110
+ """
111
+
112
+ loss: Optional[torch.FloatTensor] = None
113
+ image_embeds: Optional[torch.FloatTensor] = None
114
+ last_hidden_state: Optional[torch.FloatTensor] = None
115
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
116
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
117
+
118
+
119
+ @dataclass
120
+ @auto_docstring(
121
+ custom_intro="""
122
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
123
+ last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
124
+ scores.
125
+ """
126
+ )
127
+ class BlipImageTextMatchingModelOutput(ModelOutput):
128
+ r"""
129
+ itm_score (`torch.FloatTensor`):
130
+ The image-text similarity scores.
131
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
132
+ Language modeling loss from the text decoder.
133
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
134
+ The image embeddings obtained by applying the projection layer to the pooler_output.
135
+ vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
136
+ Last layer hidden-state of the vision of the vision-only branch of the model.
137
+ question_embeds (`torch.FloatTensor`):
138
+ The question embeddings obtained by the text projection layer.
139
+ """
140
+
141
+ itm_score: Optional[torch.FloatTensor] = None
142
+ loss: Optional[torch.FloatTensor] = None
143
+ image_embeds: Optional[torch.FloatTensor] = None
144
+ last_hidden_state: Optional[torch.FloatTensor] = None
145
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
146
+ vision_pooler_output: Optional[torch.FloatTensor] = None
147
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
148
+ question_embeds: Optional[tuple[torch.FloatTensor]] = None
149
+
150
+
151
+ @dataclass
152
+ @auto_docstring
153
+ class BlipOutput(ModelOutput):
154
+ r"""
155
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
156
+ Contrastive loss for image-text similarity.
157
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
158
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
159
+ similarity scores.
160
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
161
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
162
+ similarity scores.
163
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
164
+ The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
165
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
166
+ The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
167
+ text_model_output (`BaseModelOutputWithPooling`):
168
+ The output of the [`BlipTextModel`].
169
+ vision_model_output (`BaseModelOutputWithPooling`):
170
+ The output of the [`BlipVisionModel`].
171
+ """
172
+
173
+ loss: Optional[torch.FloatTensor] = None
174
+ logits_per_image: Optional[torch.FloatTensor] = None
175
+ logits_per_text: Optional[torch.FloatTensor] = None
176
+ text_embeds: Optional[torch.FloatTensor] = None
177
+ image_embeds: Optional[torch.FloatTensor] = None
178
+ text_model_output: BaseModelOutputWithPooling = None
179
+ vision_model_output: BaseModelOutputWithPooling = None
180
+
181
+ def to_tuple(self) -> tuple[Any]:
182
+ return tuple(
183
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
184
+ for k in self.keys()
185
+ )
186
+
187
+
188
+ class BlipVisionEmbeddings(nn.Module):
189
+ def __init__(self, config: BlipVisionConfig):
190
+ super().__init__()
191
+ self.config = config
192
+ self.embed_dim = config.hidden_size
193
+ self.image_size = config.image_size
194
+ self.patch_size = config.patch_size
195
+
196
+ self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
197
+
198
+ self.patch_embedding = nn.Conv2d(
199
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
200
+ )
201
+
202
+ self.num_patches = (self.image_size // self.patch_size) ** 2
203
+ self.num_positions = self.num_patches + 1
204
+
205
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
206
+
207
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
208
+ """
209
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
210
+ images. This method is also adapted to support torch.jit tracing.
211
+
212
+ Adapted from:
213
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
214
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
215
+ """
216
+
217
+ num_patches = embeddings.shape[1] - 1
218
+ num_positions = self.position_embedding.shape[1] - 1
219
+
220
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
221
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
222
+ return self.position_embedding
223
+
224
+ class_pos_embed = self.position_embedding[:, :1]
225
+ patch_pos_embed = self.position_embedding[:, 1:]
226
+
227
+ dim = embeddings.shape[-1]
228
+
229
+ new_height = height // self.patch_size
230
+ new_width = width // self.patch_size
231
+
232
+ sqrt_num_positions = torch_int(num_positions**0.5)
233
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
234
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
235
+
236
+ patch_pos_embed = nn.functional.interpolate(
237
+ patch_pos_embed,
238
+ size=(new_height, new_width),
239
+ mode="bicubic",
240
+ align_corners=False,
241
+ )
242
+
243
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
244
+
245
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
246
+
247
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
248
+ batch_size, _, height, width = pixel_values.shape
249
+ target_dtype = self.patch_embedding.weight.dtype
250
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
251
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
252
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
253
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
254
+ if interpolate_pos_encoding:
255
+ position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
256
+ else:
257
+ position_embedding = self.position_embedding
258
+ embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
259
+ return embeddings
260
+
261
+
262
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Blip
263
+ class BlipTextEmbeddings(nn.Module):
264
+ def __init__(self, config: BlipTextConfig):
265
+ super().__init__()
266
+ embed_dim = config.hidden_size
267
+
268
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
269
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
270
+
271
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
272
+ self.register_buffer(
273
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
274
+ )
275
+
276
+ def forward(
277
+ self,
278
+ input_ids: Optional[torch.LongTensor] = None,
279
+ position_ids: Optional[torch.LongTensor] = None,
280
+ inputs_embeds: Optional[torch.FloatTensor] = None,
281
+ ) -> torch.Tensor:
282
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
283
+ max_position_embedding = self.position_embedding.weight.shape[0]
284
+
285
+ if seq_length > max_position_embedding:
286
+ raise ValueError(
287
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
288
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
289
+ )
290
+
291
+ if position_ids is None:
292
+ position_ids = self.position_ids[:, :seq_length]
293
+
294
+ if inputs_embeds is None:
295
+ inputs_embeds = self.token_embedding(input_ids)
296
+
297
+ position_embeddings = self.position_embedding(position_ids)
298
+ embeddings = inputs_embeds + position_embeddings
299
+
300
+ return embeddings
301
+
302
+
303
+ class BlipAttention(nn.Module):
304
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
305
+
306
+ def __init__(self, config):
307
+ super().__init__()
308
+ self.config = config
309
+ self.embed_dim = config.hidden_size
310
+ self.num_heads = config.num_attention_heads
311
+ self.head_dim = self.embed_dim // self.num_heads
312
+ if self.head_dim * self.num_heads != self.embed_dim:
313
+ raise ValueError(
314
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
315
+ f" {self.num_heads})."
316
+ )
317
+ self.scale = self.head_dim**-0.5
318
+ self.dropout = nn.Dropout(config.attention_dropout)
319
+
320
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim)
321
+
322
+ self.projection = nn.Linear(self.embed_dim, self.embed_dim)
323
+
324
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
325
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
326
+
327
+ def forward(
328
+ self,
329
+ hidden_states: torch.Tensor,
330
+ head_mask: Optional[torch.Tensor] = None,
331
+ **kwargs: Unpack[TransformersKwargs],
332
+ ) -> tuple[torch.Tensor, torch.Tensor]:
333
+ """Input shape: Batch x Time x Channel"""
334
+
335
+ bsz, tgt_len, embed_dim = hidden_states.size()
336
+
337
+ mixed_qkv = (
338
+ self.qkv(hidden_states)
339
+ .reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads)
340
+ .permute(2, 0, 3, 1, 4)
341
+ )
342
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
343
+
344
+ # Take the dot product between "query" and "key" to get the raw attention scores.
345
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
346
+
347
+ attention_scores = attention_scores * self.scale
348
+
349
+ # Normalize the attention scores to probabilities.
350
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
351
+
352
+ # This is actually dropping out entire tokens to attend to, which might
353
+ # seem a bit unusual, but is taken from the original Transformer paper.
354
+ attention_probs = self.dropout(attention_probs)
355
+
356
+ # Mask heads if we want to
357
+ if head_mask is not None:
358
+ attention_probs = attention_probs * head_mask
359
+
360
+ context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
361
+
362
+ new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
363
+ context_layer = context_layer.reshape(new_context_layer_shape)
364
+
365
+ output = self.projection(context_layer)
366
+
367
+ return output, attention_probs
368
+
369
+
370
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Blip
371
+ class BlipMLP(nn.Module):
372
+ def __init__(self, config):
373
+ super().__init__()
374
+ self.config = config
375
+ self.activation_fn = ACT2FN[config.hidden_act]
376
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
377
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
378
+
379
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
380
+ hidden_states = self.fc1(hidden_states)
381
+ hidden_states = self.activation_fn(hidden_states)
382
+ hidden_states = self.fc2(hidden_states)
383
+ return hidden_states
384
+
385
+
386
+ class BlipEncoderLayer(GradientCheckpointingLayer):
387
+ def __init__(self, config: BlipConfig):
388
+ super().__init__()
389
+ self.embed_dim = config.hidden_size
390
+ self.self_attn = BlipAttention(config)
391
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
392
+ self.mlp = BlipMLP(config)
393
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
394
+
395
+ @auto_docstring
396
+ def forward(
397
+ self,
398
+ hidden_states: torch.Tensor,
399
+ attention_mask: torch.Tensor,
400
+ **kwargs: Unpack[TransformersKwargs],
401
+ ) -> torch.FloatTensor:
402
+ residual = hidden_states
403
+
404
+ hidden_states = self.layer_norm1(hidden_states)
405
+ hidden_states, _ = self.self_attn(
406
+ hidden_states=hidden_states,
407
+ head_mask=attention_mask,
408
+ **kwargs,
409
+ )
410
+ hidden_states = hidden_states + residual
411
+ residual = hidden_states
412
+ hidden_states = self.layer_norm2(hidden_states)
413
+ hidden_states = self.mlp(hidden_states)
414
+
415
+ hidden_states = hidden_states + residual
416
+
417
+ return hidden_states
418
+
419
+
420
+ @auto_docstring
421
+ class BlipPreTrainedModel(PreTrainedModel):
422
+ config: BlipConfig
423
+ base_model_prefix = "blip"
424
+ supports_gradient_checkpointing = True
425
+ _no_split_modules = ["BlipEncoderLayer", "BlipTextEmbeddings"]
426
+ _skip_keys_device_placement = ["past_key_values"]
427
+
428
+ def _init_weights(self, module):
429
+ """Initialize the weights"""
430
+ factor = self.config.initializer_range
431
+ if isinstance(module, (nn.Conv2d, nn.Embedding, nn.Linear)):
432
+ module.weight.data.normal_(mean=0.0, std=factor)
433
+ if hasattr(module, "bias") and module.bias is not None:
434
+ module.bias.data.zero_()
435
+
436
+ if isinstance(module, BlipVisionEmbeddings):
437
+ if hasattr(self.config, "vision_config"):
438
+ factor = self.config.vision_config.initializer_range
439
+ nn.init.trunc_normal_(
440
+ module.position_embedding,
441
+ mean=0.0,
442
+ std=factor,
443
+ )
444
+
445
+ nn.init.trunc_normal_(
446
+ module.class_embedding,
447
+ mean=0.0,
448
+ std=factor,
449
+ )
450
+
451
+ elif isinstance(module, nn.LayerNorm):
452
+ module.bias.data.zero_()
453
+ module.weight.data.fill_(1.0)
454
+ elif isinstance(module, nn.Linear) and module.bias is not None:
455
+ module.bias.data.zero_()
456
+
457
+
458
+ class BlipEncoder(nn.Module):
459
+ """
460
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
461
+ [`BlipEncoderLayer`].
462
+
463
+ Args:
464
+ config (`BlipConfig`):
465
+ The corresponding vision configuration for the `BlipEncoder`.
466
+ """
467
+
468
+ def __init__(self, config: BlipConfig):
469
+ super().__init__()
470
+ self.config = config
471
+ self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
472
+ self.gradient_checkpointing = False
473
+
474
+ @auto_docstring
475
+ def forward(
476
+ self,
477
+ inputs_embeds,
478
+ attention_mask: Optional[torch.Tensor] = None,
479
+ **kwargs: Unpack[TransformersKwargs],
480
+ ) -> Union[tuple, BaseModelOutput]:
481
+ hidden_states = inputs_embeds
482
+ for encoder_layer in self.layers:
483
+ hidden_states = encoder_layer(
484
+ hidden_states,
485
+ attention_mask=attention_mask,
486
+ **kwargs,
487
+ )
488
+
489
+ return BaseModelOutput(last_hidden_state=hidden_states)
490
+
491
+
492
+ class BlipVisionModel(BlipPreTrainedModel):
493
+ main_input_name = "pixel_values"
494
+ config: BlipVisionConfig
495
+ _can_record_outputs = {
496
+ "hidden_states": BlipEncoderLayer,
497
+ "attentions": BlipAttention,
498
+ }
499
+
500
+ def __init__(self, config: BlipVisionConfig):
501
+ super().__init__(config)
502
+ self.config = config
503
+ embed_dim = config.hidden_size
504
+
505
+ self.embeddings = BlipVisionEmbeddings(config)
506
+ self.encoder = BlipEncoder(config)
507
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
508
+
509
+ self.post_init()
510
+
511
+ @check_model_inputs(tie_last_hidden_states=False)
512
+ @auto_docstring
513
+ def forward(
514
+ self,
515
+ pixel_values: Optional[torch.FloatTensor] = None,
516
+ interpolate_pos_encoding: bool = False,
517
+ **kwargs: Unpack[TransformersKwargs],
518
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
519
+ if pixel_values is None:
520
+ raise ValueError("You have to specify pixel_values")
521
+
522
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
523
+
524
+ encoder_outputs: BaseModelOutput = self.encoder(
525
+ inputs_embeds=hidden_states,
526
+ **kwargs,
527
+ )
528
+
529
+ last_hidden_state = encoder_outputs.last_hidden_state
530
+ last_hidden_state = self.post_layernorm(last_hidden_state)
531
+
532
+ pooled_output = last_hidden_state[:, 0, :]
533
+ pooled_output = self.post_layernorm(pooled_output)
534
+
535
+ return BaseModelOutputWithPooling(
536
+ last_hidden_state=last_hidden_state,
537
+ pooler_output=pooled_output,
538
+ )
539
+
540
+ def get_input_embeddings(self):
541
+ return self.embeddings
542
+
543
+
544
+ @auto_docstring(
545
+ custom_intro="""
546
+ This model is going to be deprecated in future versions. Please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.
547
+ """
548
+ )
549
+ class BlipModel(BlipPreTrainedModel):
550
+ config: BlipConfig
551
+
552
+ def __init__(self, config: BlipConfig):
553
+ super().__init__(config)
554
+
555
+ if not isinstance(config.text_config, BlipTextConfig):
556
+ raise TypeError(
557
+ "config.text_config is expected to be of type BlipTextConfig but is of type"
558
+ f" {type(config.text_config)}."
559
+ )
560
+
561
+ if not isinstance(config.vision_config, BlipVisionConfig):
562
+ raise TypeError(
563
+ "config.vision_config is expected to be of type BlipVisionConfig but is of type"
564
+ f" {type(config.vision_config)}."
565
+ )
566
+
567
+ text_config = config.text_config
568
+ vision_config = config.vision_config
569
+
570
+ self.projection_dim = config.projection_dim
571
+ self.text_embed_dim = text_config.hidden_size
572
+ self.vision_embed_dim = vision_config.hidden_size
573
+
574
+ self.text_model = BlipTextModel(text_config)
575
+ self.vision_model = BlipVisionModel(vision_config)
576
+
577
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
578
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
579
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
580
+
581
+ logger.warning(
582
+ "`BlipModel` is going to be deprecated in future release, please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase."
583
+ )
584
+
585
+ # Initialize weights and apply final processing
586
+ self.post_init()
587
+
588
+ def get_input_embeddings(self):
589
+ return self.text_model.get_input_embeddings()
590
+
591
+ def set_input_embeddings(self, value):
592
+ self.text_model.set_input_embeddings(value)
593
+
594
+ @auto_docstring
595
+ def get_text_features(
596
+ self,
597
+ input_ids: Optional[torch.Tensor] = None,
598
+ attention_mask: Optional[torch.Tensor] = None,
599
+ position_ids: Optional[torch.Tensor] = None,
600
+ ) -> torch.FloatTensor:
601
+ r"""
602
+ Returns:
603
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
604
+ applying the projection layer to the pooled output of [`BlipTextModel`].
605
+
606
+ Examples:
607
+
608
+ ```python
609
+ >>> from transformers import AutoProcessor, BlipModel
610
+
611
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
612
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
613
+
614
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
615
+ >>> text_features = model.get_text_features(**inputs)
616
+ ```"""
617
+ text_outputs = self.text_model(
618
+ input_ids=input_ids,
619
+ attention_mask=attention_mask,
620
+ position_ids=position_ids,
621
+ )
622
+
623
+ pooled_output = text_outputs[1]
624
+ text_features = self.text_projection(pooled_output)
625
+
626
+ return text_features
627
+
628
+ @auto_docstring
629
+ def get_image_features(
630
+ self,
631
+ pixel_values: Optional[torch.FloatTensor] = None,
632
+ interpolate_pos_encoding: bool = False,
633
+ ) -> torch.FloatTensor:
634
+ r"""
635
+ Returns:
636
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
637
+ applying the projection layer to the pooled output of [`BlipVisionModel`].
638
+
639
+ Examples:
640
+
641
+ ```python
642
+ >>> from PIL import Image
643
+ >>> import requests
644
+ >>> from transformers import AutoProcessor, BlipModel
645
+
646
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
647
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
648
+
649
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
650
+ >>> image = Image.open(requests.get(url, stream=True).raw)
651
+
652
+ >>> inputs = processor(images=image, return_tensors="pt")
653
+
654
+ >>> image_features = model.get_image_features(**inputs)
655
+ ```"""
656
+
657
+ vision_outputs = self.vision_model(
658
+ pixel_values=pixel_values,
659
+ interpolate_pos_encoding=interpolate_pos_encoding,
660
+ )
661
+
662
+ pooled_output = vision_outputs[1] # pooled_output
663
+ image_features = self.visual_projection(pooled_output)
664
+
665
+ return image_features
666
+
667
+ @auto_docstring
668
+ def get_multimodal_features(
669
+ self,
670
+ input_ids: Optional[torch.LongTensor] = None,
671
+ pixel_values: Optional[torch.FloatTensor] = None,
672
+ attention_mask: Optional[torch.Tensor] = None,
673
+ interpolate_pos_encoding: bool = False,
674
+ ) -> torch.FloatTensor:
675
+ r"""
676
+ Returns:
677
+ multimodal_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The multimodal embeddings
678
+ obtained by applying the image embeddings to the text encoder using the cross-attention mechanism.
679
+
680
+ Examples:
681
+ ```python
682
+ >>> from PIL import Image
683
+ >>> import requests
684
+ >>> from transformers import AutoProcessor, BlipModel
685
+
686
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
687
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
688
+
689
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
690
+ >>> image = Image.open(requests.get(url, stream=True).raw)
691
+ >>> texts = ["a photo of a cat", "a photo of a dog"]
692
+ >>> inputs = processor(images=image, text=texts, padding=True, return_tensors="pt")
693
+
694
+ >>> multimodal_features = model.get_multimodal_features(**inputs)
695
+ ```"""
696
+ vision_outputs = self.vision_model(
697
+ pixel_values=pixel_values,
698
+ interpolate_pos_encoding=interpolate_pos_encoding,
699
+ )
700
+
701
+ image_embeds = vision_outputs[0]
702
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
703
+
704
+ text_outputs = self.text_model(
705
+ input_ids=input_ids,
706
+ attention_mask=attention_mask,
707
+ encoder_hidden_states=image_embeds,
708
+ encoder_attention_mask=image_atts,
709
+ )
710
+
711
+ pooled_output = text_outputs[1] # pooled_output
712
+ multimodal_features = self.text_projection(pooled_output)
713
+
714
+ return multimodal_features
715
+
716
+ @can_return_tuple
717
+ @auto_docstring
718
+ def forward(
719
+ self,
720
+ input_ids: Optional[torch.LongTensor] = None,
721
+ pixel_values: Optional[torch.FloatTensor] = None,
722
+ attention_mask: Optional[torch.Tensor] = None,
723
+ position_ids: Optional[torch.LongTensor] = None,
724
+ return_loss: Optional[bool] = None,
725
+ interpolate_pos_encoding: bool = False,
726
+ **kwargs: Unpack[TransformersKwargs],
727
+ ) -> Union[tuple, BlipOutput]:
728
+ r"""
729
+ return_loss (`bool`, *optional*):
730
+ Whether or not to return the contrastive loss.
731
+
732
+ Examples:
733
+
734
+ ```python
735
+ >>> from PIL import Image
736
+ >>> import requests
737
+ >>> from transformers import AutoProcessor, BlipModel
738
+
739
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
740
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
741
+
742
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
743
+ >>> image = Image.open(requests.get(url, stream=True).raw)
744
+
745
+ >>> inputs = processor(
746
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
747
+ ... )
748
+
749
+ >>> outputs = model(**inputs)
750
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
751
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
752
+ ```"""
753
+ vision_outputs = self.vision_model(
754
+ pixel_values=pixel_values,
755
+ interpolate_pos_encoding=interpolate_pos_encoding,
756
+ **kwargs,
757
+ )
758
+
759
+ text_outputs = self.text_model(
760
+ input_ids=input_ids,
761
+ attention_mask=attention_mask,
762
+ position_ids=position_ids,
763
+ **kwargs,
764
+ )
765
+
766
+ image_embeds = vision_outputs.pooler_output
767
+ image_embeds = self.visual_projection(image_embeds)
768
+
769
+ text_embeds = text_outputs.pooler_output
770
+ text_embeds = self.text_projection(text_embeds)
771
+
772
+ # normalized features
773
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
774
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
775
+
776
+ # cosine similarity as logits
777
+ logit_scale = self.logit_scale.exp().to(device=text_embeds.device)
778
+ image_embeds = image_embeds.to(device=text_embeds.device, dtype=text_embeds.dtype)
779
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
780
+ logits_per_image = logits_per_text.t()
781
+
782
+ loss = None
783
+ if return_loss:
784
+ loss = blip_loss(logits_per_text)
785
+
786
+ return BlipOutput(
787
+ loss=loss,
788
+ logits_per_image=logits_per_image,
789
+ logits_per_text=logits_per_text,
790
+ text_embeds=text_embeds,
791
+ image_embeds=image_embeds,
792
+ text_model_output=text_outputs,
793
+ vision_model_output=vision_outputs,
794
+ )
795
+
796
+
797
+ @auto_docstring(
798
+ custom_intro="""
799
+ BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
800
+ `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
801
+ the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
802
+ from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
803
+ """
804
+ )
805
+ class BlipForConditionalGeneration(BlipPreTrainedModel, GenerationMixin):
806
+ config: BlipConfig
807
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
808
+ main_input_name = "pixel_values"
809
+
810
+ def __init__(self, config: BlipConfig):
811
+ super().__init__(config)
812
+
813
+ self.vision_model = BlipVisionModel(config.vision_config)
814
+
815
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
816
+
817
+ self.decoder_input_ids = config.text_config.bos_token_id
818
+ self.decoder_pad_token_id = config.text_config.pad_token_id
819
+
820
+ # Initialize weights and apply final processing
821
+ self.post_init()
822
+
823
+ def get_input_embeddings(self):
824
+ return self.text_decoder.get_input_embeddings()
825
+
826
+ def set_input_embeddings(self, value):
827
+ self.text_decoder.set_input_embeddings(value)
828
+
829
+ @can_return_tuple
830
+ @auto_docstring
831
+ def forward(
832
+ self,
833
+ pixel_values: torch.FloatTensor,
834
+ input_ids: Optional[torch.LongTensor] = None,
835
+ attention_mask: Optional[torch.LongTensor] = None,
836
+ labels: Optional[torch.LongTensor] = None,
837
+ interpolate_pos_encoding: bool = False,
838
+ **kwargs: Unpack[TransformersKwargs],
839
+ ) -> Union[tuple, BlipForConditionalGenerationModelOutput]:
840
+ r"""
841
+ Examples:
842
+
843
+ ```python
844
+ >>> from PIL import Image
845
+ >>> import requests
846
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
847
+
848
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
849
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
850
+
851
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
852
+ >>> image = Image.open(requests.get(url, stream=True).raw)
853
+ >>> text = "A picture of"
854
+
855
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
856
+
857
+ >>> outputs = model(**inputs)
858
+ ```"""
859
+
860
+ vision_outputs = self.vision_model(
861
+ pixel_values=pixel_values,
862
+ interpolate_pos_encoding=interpolate_pos_encoding,
863
+ **kwargs,
864
+ )
865
+
866
+ image_embeds = vision_outputs.last_hidden_state
867
+
868
+ outputs = self.text_decoder(
869
+ input_ids=input_ids,
870
+ attention_mask=attention_mask,
871
+ encoder_hidden_states=image_embeds,
872
+ labels=labels,
873
+ reduction="mean",
874
+ **kwargs,
875
+ )
876
+
877
+ return BlipForConditionalGenerationModelOutput(
878
+ loss=outputs.loss,
879
+ logits=outputs.logits,
880
+ image_embeds=image_embeds,
881
+ last_hidden_state=vision_outputs.last_hidden_state,
882
+ hidden_states=vision_outputs.hidden_states,
883
+ attentions=vision_outputs.attentions,
884
+ )
885
+
886
+ @torch.no_grad()
887
+ def generate(
888
+ self,
889
+ pixel_values: torch.FloatTensor,
890
+ input_ids: Optional[torch.LongTensor] = None,
891
+ attention_mask: Optional[torch.LongTensor] = None,
892
+ interpolate_pos_encoding: bool = False,
893
+ **generate_kwargs,
894
+ ) -> torch.LongTensor:
895
+ r"""
896
+ Overrides *generate* function to be able to use the model as a conditional generator
897
+
898
+ Parameters:
899
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
900
+ Input image to be processed
901
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
902
+ The sequence used as a prompt for the generation.
903
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
904
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
905
+
906
+
907
+ Examples:
908
+ ```python
909
+ >>> from PIL import Image
910
+ >>> import requests
911
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
912
+
913
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
914
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
915
+
916
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
917
+ >>> image = Image.open(requests.get(url, stream=True).raw)
918
+
919
+ >>> inputs = processor(images=image, return_tensors="pt")
920
+
921
+ >>> outputs = model.generate(**inputs)
922
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
923
+ two cats sleeping on a couch
924
+ ```
925
+ """
926
+
927
+ batch_size = pixel_values.shape[0]
928
+ vision_outputs = self.vision_model(
929
+ pixel_values=pixel_values,
930
+ interpolate_pos_encoding=interpolate_pos_encoding,
931
+ )
932
+
933
+ image_embeds = vision_outputs[0]
934
+
935
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
936
+
937
+ if isinstance(input_ids, list):
938
+ input_ids = torch.LongTensor(input_ids)
939
+ elif input_ids is None:
940
+ input_ids = (
941
+ torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
942
+ .repeat(batch_size, 1)
943
+ .to(image_embeds.device)
944
+ )
945
+
946
+ input_ids[:, 0] = self.config.text_config.bos_token_id
947
+ attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
948
+
949
+ outputs = self.text_decoder.generate(
950
+ input_ids=input_ids[:, :-1],
951
+ eos_token_id=self.config.text_config.sep_token_id,
952
+ pad_token_id=self.config.text_config.pad_token_id,
953
+ attention_mask=attention_mask,
954
+ encoder_hidden_states=image_embeds,
955
+ encoder_attention_mask=image_attention_mask,
956
+ **generate_kwargs,
957
+ )
958
+
959
+ return outputs
960
+
961
+
962
+ @auto_docstring(
963
+ custom_intro="""
964
+ BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
965
+ decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
966
+ with the encoding of the image, and the text decoder will output the answer to the question.
967
+ """
968
+ )
969
+ class BlipForQuestionAnswering(BlipPreTrainedModel, GenerationMixin):
970
+ config: BlipConfig
971
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
972
+
973
+ def __init__(self, config: BlipConfig):
974
+ super().__init__(config)
975
+
976
+ self.vision_model = BlipVisionModel(config.vision_config)
977
+
978
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
979
+
980
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
981
+
982
+ self.decoder_pad_token_id = config.text_config.pad_token_id
983
+ self.decoder_start_token_id = config.text_config.bos_token_id
984
+
985
+ # Initialize weights and apply final processing
986
+ self.post_init()
987
+
988
+ def set_input_embeddings(self, value):
989
+ self.text_encoder.set_input_embeddings(value)
990
+
991
+ def get_input_embeddings(self):
992
+ # This will return shared embeddings if they are shared else specific to encoder.
993
+ return self.text_encoder.get_input_embeddings()
994
+
995
+ @can_return_tuple
996
+ @auto_docstring
997
+ def forward(
998
+ self,
999
+ input_ids: torch.LongTensor,
1000
+ pixel_values: torch.FloatTensor,
1001
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1002
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1003
+ attention_mask: Optional[torch.LongTensor] = None,
1004
+ labels: Optional[torch.LongTensor] = None,
1005
+ interpolate_pos_encoding: bool = False,
1006
+ **kwargs: Unpack[TransformersKwargs],
1007
+ ) -> Union[tuple, BlipTextVisionModelOutput]:
1008
+ r"""
1009
+ Examples:
1010
+
1011
+ ```python
1012
+ >>> from PIL import Image
1013
+ >>> import requests
1014
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1015
+
1016
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1017
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1018
+
1019
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1020
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1021
+
1022
+ >>> # training
1023
+ >>> text = "How many cats are in the picture?"
1024
+ >>> label = "2"
1025
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1026
+ >>> labels = processor(text=label, return_tensors="pt").input_ids
1027
+
1028
+ >>> inputs["labels"] = labels
1029
+ >>> outputs = model(**inputs)
1030
+ >>> loss = outputs.loss
1031
+ >>> loss.backward()
1032
+
1033
+ >>> # inference
1034
+ >>> text = "How many cats are in the picture?"
1035
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1036
+ >>> outputs = model.generate(**inputs)
1037
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1038
+ 2
1039
+ ```"""
1040
+ if labels is None and decoder_input_ids is None:
1041
+ raise ValueError(
1042
+ "Either `decoder_input_ids` or `labels` should be passed when calling `forward` with"
1043
+ " `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
1044
+ " are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
1045
+ )
1046
+
1047
+ vision_outputs = self.vision_model(
1048
+ pixel_values=pixel_values,
1049
+ interpolate_pos_encoding=interpolate_pos_encoding,
1050
+ **kwargs,
1051
+ )
1052
+
1053
+ image_embeds = vision_outputs.last_hidden_state
1054
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1055
+
1056
+ question_embeds = self.text_encoder(
1057
+ input_ids=input_ids,
1058
+ attention_mask=attention_mask,
1059
+ encoder_hidden_states=image_embeds,
1060
+ encoder_attention_mask=image_attention_mask,
1061
+ **kwargs,
1062
+ )
1063
+
1064
+ if labels is not None and decoder_input_ids is None:
1065
+ # labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
1066
+ decoder_input_ids = labels
1067
+
1068
+ question_embeds = question_embeds[0]
1069
+
1070
+ answer_output = self.text_decoder(
1071
+ input_ids=decoder_input_ids,
1072
+ attention_mask=decoder_attention_mask,
1073
+ encoder_hidden_states=question_embeds,
1074
+ encoder_attention_mask=attention_mask,
1075
+ labels=labels,
1076
+ reduction="mean",
1077
+ **kwargs,
1078
+ )
1079
+
1080
+ if labels is not None:
1081
+ decoder_loss = answer_output.loss.mean()
1082
+ else:
1083
+ decoder_loss = None
1084
+
1085
+ return BlipTextVisionModelOutput(
1086
+ loss=decoder_loss,
1087
+ image_embeds=image_embeds,
1088
+ last_hidden_state=vision_outputs.last_hidden_state,
1089
+ hidden_states=vision_outputs.hidden_states,
1090
+ attentions=vision_outputs.attentions,
1091
+ )
1092
+
1093
+ @torch.no_grad()
1094
+ def generate(
1095
+ self,
1096
+ input_ids: torch.LongTensor,
1097
+ pixel_values: torch.FloatTensor,
1098
+ attention_mask: Optional[torch.LongTensor] = None,
1099
+ interpolate_pos_encoding: bool = False,
1100
+ **generate_kwargs,
1101
+ ) -> torch.LongTensor:
1102
+ r"""
1103
+ Overrides *generate* function to be able to use the model as a conditional generator
1104
+
1105
+ Parameters:
1106
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
1107
+ The sequence used as a prompt for the generation.
1108
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
1109
+ Input image to be processed
1110
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1111
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
1112
+ tokens that are NOT MASKED, `0` for MASKED tokens.
1113
+ **generate_kwargs:
1114
+ Additional arguments passed to the *generate* function of the decoder
1115
+
1116
+
1117
+ Examples:
1118
+ ```python
1119
+ >>> from PIL import Image
1120
+ >>> import requests
1121
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1122
+
1123
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1124
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1125
+
1126
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1127
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1128
+ >>> text = "How many cats are in the picture?"
1129
+
1130
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1131
+
1132
+ >>> outputs = model.generate(**inputs)
1133
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1134
+ 2
1135
+ ```
1136
+ """
1137
+ vision_outputs = self.vision_model(
1138
+ pixel_values=pixel_values,
1139
+ interpolate_pos_encoding=interpolate_pos_encoding,
1140
+ )
1141
+
1142
+ image_embeds = vision_outputs[0]
1143
+
1144
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
1145
+
1146
+ if isinstance(input_ids, list):
1147
+ input_ids = torch.LongTensor(input_ids)
1148
+
1149
+ question_outputs = self.text_encoder(
1150
+ input_ids=input_ids,
1151
+ attention_mask=attention_mask,
1152
+ encoder_hidden_states=image_embeds,
1153
+ encoder_attention_mask=image_attention_mask,
1154
+ return_dict=False,
1155
+ )
1156
+
1157
+ question_embeds = question_outputs[0]
1158
+
1159
+ question_attention_mask = torch.ones(
1160
+ question_embeds.size()[:-1], dtype=torch.long, device=question_embeds.device
1161
+ )
1162
+
1163
+ bos_ids = torch.full(
1164
+ (question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device
1165
+ )
1166
+
1167
+ outputs = self.text_decoder.generate(
1168
+ input_ids=bos_ids,
1169
+ eos_token_id=self.config.text_config.sep_token_id,
1170
+ pad_token_id=self.config.text_config.pad_token_id,
1171
+ encoder_hidden_states=question_embeds,
1172
+ encoder_attention_mask=question_attention_mask,
1173
+ **generate_kwargs,
1174
+ )
1175
+
1176
+ return outputs
1177
+
1178
+
1179
+ @auto_docstring(
1180
+ custom_intro="""
1181
+ BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
1182
+ image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
1183
+ the image.
1184
+ """
1185
+ )
1186
+ class BlipForImageTextRetrieval(BlipPreTrainedModel):
1187
+ config: BlipConfig
1188
+
1189
+ def __init__(self, config: BlipConfig):
1190
+ super().__init__(config)
1191
+
1192
+ self.vision_model = BlipVisionModel(config.vision_config)
1193
+
1194
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
1195
+
1196
+ # vision projection layer
1197
+ self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
1198
+
1199
+ # text projection layer
1200
+ self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
1201
+
1202
+ # image text matching head
1203
+ self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
1204
+
1205
+ self.decoder_pad_token_id = (
1206
+ config.text_config.pad_token_id
1207
+ if not hasattr(config, "decoder_pad_token_id")
1208
+ else config.decoder_pad_token_id
1209
+ )
1210
+ self.decoder_start_token_id = (
1211
+ config.text_config.bos_token_id
1212
+ if not hasattr(config, "decoder_start_token_id")
1213
+ else config.decoder_start_token_id
1214
+ )
1215
+
1216
+ # Initialize weights and apply final processing
1217
+ self.post_init()
1218
+
1219
+ def get_input_embeddings(self):
1220
+ return self.text_encoder.get_input_embeddings()
1221
+
1222
+ def set_input_embeddings(self, value):
1223
+ self.text_encoder.set_input_embeddings(value)
1224
+
1225
+ @can_return_tuple
1226
+ @auto_docstring
1227
+ def forward(
1228
+ self,
1229
+ input_ids: torch.LongTensor,
1230
+ pixel_values: torch.FloatTensor,
1231
+ use_itm_head: Optional[bool] = True,
1232
+ attention_mask: Optional[torch.LongTensor] = None,
1233
+ interpolate_pos_encoding: bool = False,
1234
+ **kwargs: Unpack[TransformersKwargs],
1235
+ ) -> Union[tuple, BlipTextVisionModelOutput]:
1236
+ r"""
1237
+ use_itm_head (`bool`, *optional*, defaults to `True`):
1238
+ Whether or not to use the image-text matching head.
1239
+
1240
+ Examples:
1241
+
1242
+ ```python
1243
+ >>> from PIL import Image
1244
+ >>> import requests
1245
+ >>> from transformers import AutoProcessor, BlipForImageTextRetrieval
1246
+
1247
+ >>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
1248
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1249
+
1250
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1251
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1252
+ >>> text = "an image of a cat"
1253
+
1254
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1255
+ >>> outputs = model(**inputs)
1256
+ ```
1257
+ """
1258
+ vision_outputs = self.vision_model(
1259
+ pixel_values=pixel_values,
1260
+ interpolate_pos_encoding=interpolate_pos_encoding,
1261
+ **kwargs,
1262
+ )
1263
+
1264
+ image_embeds = vision_outputs.last_hidden_state
1265
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1266
+
1267
+ if use_itm_head:
1268
+ question_embeds = self.text_encoder(
1269
+ input_ids=input_ids,
1270
+ attention_mask=attention_mask,
1271
+ encoder_hidden_states=image_embeds,
1272
+ encoder_attention_mask=image_atts,
1273
+ **kwargs,
1274
+ )
1275
+ question_embeds = question_embeds.last_hidden_state
1276
+
1277
+ output = self.itm_head(question_embeds[:, 0, :])
1278
+ else:
1279
+ question_embeds = self.text_encoder(
1280
+ input_ids=input_ids,
1281
+ attention_mask=attention_mask,
1282
+ **kwargs,
1283
+ )
1284
+ question_embeds = question_embeds.last_hidden_state
1285
+
1286
+ image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
1287
+ text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
1288
+
1289
+ output = image_feat @ text_feat.t()
1290
+
1291
+ return BlipImageTextMatchingModelOutput(
1292
+ itm_score=output,
1293
+ last_hidden_state=vision_outputs.last_hidden_state,
1294
+ hidden_states=vision_outputs.hidden_states,
1295
+ attentions=vision_outputs.attentions,
1296
+ question_embeds=question_embeds,
1297
+ )
1298
+
1299
+
1300
+ __all__ = [
1301
+ "BlipModel",
1302
+ "BlipPreTrainedModel",
1303
+ "BlipForConditionalGeneration",
1304
+ "BlipForQuestionAnswering",
1305
+ "BlipVisionModel",
1306
+ "BlipTextModel",
1307
+ "BlipForImageTextRetrieval",
1308
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_blip_text.py ADDED
@@ -0,0 +1,968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the BSD-3-clause license (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
+ # https://opensource.org/licenses/BSD-3-Clause
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
+
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ from torch import Tensor, device, nn
22
+ from torch.nn import CrossEntropyLoss
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_layers import GradientCheckpointingLayer
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
35
+ from ...utils import logging
36
+ from ...utils.deprecation import deprecate_kwarg
37
+ from .configuration_blip import BlipTextConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
44
+ class BlipTextEmbeddings(nn.Module):
45
+ """Construct the embeddings from word and position embeddings."""
46
+
47
+ def __init__(self, config):
48
+ super().__init__()
49
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
50
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
51
+
52
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
53
+ # any TensorFlow checkpoint file
54
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
55
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
56
+
57
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
58
+ self.register_buffer(
59
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
60
+ )
61
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
62
+
63
+ self.config = config
64
+
65
+ def forward(
66
+ self,
67
+ input_ids: Optional[torch.LongTensor] = None,
68
+ position_ids: Optional[torch.LongTensor] = None,
69
+ inputs_embeds: Optional[torch.FloatTensor] = None,
70
+ past_key_values_length: int = 0,
71
+ ) -> torch.Tensor:
72
+ if input_ids is not None:
73
+ input_shape = input_ids.size()
74
+ else:
75
+ input_shape = inputs_embeds.size()[:-1]
76
+
77
+ seq_length = input_shape[1]
78
+
79
+ if position_ids is None:
80
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
81
+
82
+ if inputs_embeds is None:
83
+ inputs_embeds = self.word_embeddings(input_ids)
84
+
85
+ embeddings = inputs_embeds
86
+
87
+ if self.position_embedding_type == "absolute":
88
+ position_embeddings = self.position_embeddings(position_ids)
89
+ embeddings += position_embeddings
90
+ embeddings = self.LayerNorm(embeddings)
91
+ embeddings = self.dropout(embeddings)
92
+ return embeddings
93
+
94
+
95
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
96
+ class BlipTextSelfAttention(nn.Module):
97
+ def __init__(self, config, is_cross_attention, layer_idx=None):
98
+ super().__init__()
99
+ self.config = config
100
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
101
+ raise ValueError(
102
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
103
+ % (config.hidden_size, config.num_attention_heads)
104
+ )
105
+
106
+ self.num_attention_heads = config.num_attention_heads
107
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
108
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
109
+ self.layer_idx = layer_idx
110
+
111
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
112
+ if is_cross_attention:
113
+ self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
114
+ self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
115
+ else:
116
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
117
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
118
+
119
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
120
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
121
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
122
+ self.max_position_embeddings = config.max_position_embeddings
123
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
124
+
125
+ def save_attn_gradients(self, attn_gradients):
126
+ self.attn_gradients = attn_gradients
127
+
128
+ def get_attn_gradients(self):
129
+ return self.attn_gradients
130
+
131
+ def save_attention_map(self, attention_map):
132
+ self.attention_map = attention_map
133
+
134
+ def get_attention_map(self):
135
+ return self.attention_map
136
+
137
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
138
+ def forward(
139
+ self,
140
+ hidden_states: torch.Tensor,
141
+ attention_mask: Optional[torch.FloatTensor] = None,
142
+ head_mask: Optional[torch.FloatTensor] = None,
143
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
144
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
145
+ past_key_values: Optional[Cache] = None,
146
+ output_attentions: Optional[bool] = False,
147
+ cache_position: Optional[torch.Tensor] = None,
148
+ ) -> tuple[torch.Tensor]:
149
+ batch_size, seq_length, _ = hidden_states.shape
150
+ query_layer = (
151
+ self.query(hidden_states)
152
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
153
+ .transpose(1, 2)
154
+ )
155
+
156
+ # If this is instantiated as a cross-attention module, the keys
157
+ # and values come from an encoder; the attention mask needs to be
158
+ # such that the encoder's padding tokens are not attended to.
159
+ is_cross_attention = encoder_hidden_states is not None
160
+ attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
161
+
162
+ is_updated = False
163
+ if past_key_values is not None:
164
+ if isinstance(past_key_values, EncoderDecoderCache):
165
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
166
+ if is_cross_attention:
167
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
168
+ curr_past_key_value = past_key_values.cross_attention_cache
169
+ else:
170
+ curr_past_key_value = past_key_values.self_attention_cache
171
+ else:
172
+ curr_past_key_value = past_key_values
173
+
174
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
175
+ if is_cross_attention and past_key_values is not None and is_updated:
176
+ # reuse k,v, cross_attentions
177
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
178
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
179
+ else:
180
+ key_layer = (
181
+ self.key(current_states)
182
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
183
+ .transpose(1, 2)
184
+ )
185
+ value_layer = (
186
+ self.value(current_states)
187
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
188
+ .transpose(1, 2)
189
+ )
190
+
191
+ if past_key_values is not None:
192
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
193
+ cache_position = cache_position if not is_cross_attention else None
194
+ key_layer, value_layer = curr_past_key_value.update(
195
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
196
+ )
197
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
198
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
199
+ past_key_values.is_updated[self.layer_idx] = True
200
+
201
+ # Take the dot product between "query" and "key" to get the raw attention scores.
202
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
203
+
204
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
205
+ seq_length = hidden_states.size()[1]
206
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
207
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
208
+ distance = position_ids_l - position_ids_r
209
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
210
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
211
+
212
+ if self.position_embedding_type == "relative_key":
213
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
214
+ attention_scores = attention_scores + relative_position_scores
215
+ elif self.position_embedding_type == "relative_key_query":
216
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
217
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
218
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
219
+
220
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
221
+ if attention_mask is not None:
222
+ # Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
223
+ attention_scores = attention_scores + attention_mask.to(attention_scores.device)
224
+
225
+ # Normalize the attention scores to probabilities.
226
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
227
+
228
+ # This is actually dropping out entire tokens to attend to, which might
229
+ # seem a bit unusual, but is taken from the original Transformer paper.
230
+ attention_probs_dropped = self.dropout(attention_probs)
231
+
232
+ # Mask heads if we want to
233
+ if head_mask is not None:
234
+ attention_probs_dropped = attention_probs_dropped * head_mask
235
+
236
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
237
+
238
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
239
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
240
+ context_layer = context_layer.view(*new_context_layer_shape)
241
+
242
+ return context_layer, attention_probs
243
+
244
+
245
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert -> BlipText
246
+ class BlipTextSelfOutput(nn.Module):
247
+ def __init__(self, config):
248
+ super().__init__()
249
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
250
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
251
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
252
+
253
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
254
+ hidden_states = self.dense(hidden_states)
255
+ hidden_states = self.dropout(hidden_states)
256
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
257
+ return hidden_states
258
+
259
+
260
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
261
+ class BlipTextAttention(nn.Module):
262
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
263
+ super().__init__()
264
+ self.self = BlipTextSelfAttention(config, is_cross_attention, layer_idx=layer_idx)
265
+ self.output = BlipTextSelfOutput(config)
266
+ self.pruned_heads = set()
267
+
268
+ def prune_heads(self, heads):
269
+ if len(heads) == 0:
270
+ return
271
+ heads, index = find_pruneable_heads_and_indices(
272
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
273
+ )
274
+
275
+ # Prune linear layers
276
+ self.self.query = prune_linear_layer(self.self.query, index)
277
+ self.self.key = prune_linear_layer(self.self.key, index)
278
+ self.self.value = prune_linear_layer(self.self.value, index)
279
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
280
+
281
+ # Update hyper params and store pruned heads
282
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
283
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
284
+ self.pruned_heads = self.pruned_heads.union(heads)
285
+
286
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
287
+ def forward(
288
+ self,
289
+ hidden_states: torch.Tensor,
290
+ attention_mask: Optional[torch.FloatTensor] = None,
291
+ head_mask: Optional[torch.FloatTensor] = None,
292
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
293
+ past_key_values: Optional[Cache] = None,
294
+ output_attentions: Optional[bool] = False,
295
+ cache_position: Optional[torch.Tensor] = None,
296
+ ) -> tuple[torch.Tensor]:
297
+ self_outputs = self.self(
298
+ hidden_states,
299
+ attention_mask=attention_mask,
300
+ head_mask=head_mask,
301
+ encoder_hidden_states=encoder_hidden_states,
302
+ past_key_values=past_key_values,
303
+ output_attentions=output_attentions,
304
+ cache_position=cache_position,
305
+ )
306
+ attention_output = self.output(self_outputs[0], hidden_states)
307
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
308
+ return outputs
309
+
310
+
311
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert -> BlipText
312
+ class BlipTextIntermediate(nn.Module):
313
+ def __init__(self, config):
314
+ super().__init__()
315
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
316
+ if isinstance(config.hidden_act, str):
317
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
318
+ else:
319
+ self.intermediate_act_fn = config.hidden_act
320
+
321
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
322
+ hidden_states = self.dense(hidden_states)
323
+ hidden_states = self.intermediate_act_fn(hidden_states)
324
+ return hidden_states
325
+
326
+
327
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert -> BlipText
328
+ class BlipTextOutput(nn.Module):
329
+ def __init__(self, config):
330
+ super().__init__()
331
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
332
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
333
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
334
+
335
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
336
+ hidden_states = self.dense(hidden_states)
337
+ hidden_states = self.dropout(hidden_states)
338
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
339
+ return hidden_states
340
+
341
+
342
+ class BlipTextLayer(GradientCheckpointingLayer):
343
+ def __init__(self, config, layer_num):
344
+ super().__init__()
345
+ self.config = config
346
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
347
+ self.seq_len_dim = 1
348
+ self.attention = BlipTextAttention(config, layer_idx=layer_num)
349
+ self.layer_num = layer_num
350
+ if self.config.is_decoder:
351
+ self.crossattention = BlipTextAttention(
352
+ config, is_cross_attention=self.config.is_decoder, layer_idx=layer_num
353
+ )
354
+ self.intermediate = BlipTextIntermediate(config)
355
+ self.output = BlipTextOutput(config)
356
+
357
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
358
+ def forward(
359
+ self,
360
+ hidden_states: torch.Tensor,
361
+ attention_mask: Optional[torch.FloatTensor] = None,
362
+ head_mask: Optional[torch.FloatTensor] = None,
363
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
364
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
365
+ past_key_values: Optional[Cache] = None,
366
+ output_attentions: Optional[bool] = False,
367
+ cache_position: Optional[torch.Tensor] = None,
368
+ ) -> tuple[torch.Tensor]:
369
+ self_attention_outputs = self.attention(
370
+ hidden_states,
371
+ attention_mask=attention_mask,
372
+ head_mask=head_mask,
373
+ output_attentions=output_attentions,
374
+ past_key_values=past_key_values,
375
+ cache_position=cache_position,
376
+ )
377
+ attention_output = self_attention_outputs[0]
378
+ outputs = self_attention_outputs[1:]
379
+
380
+ if encoder_hidden_states is not None:
381
+ cross_attention_outputs = self.crossattention(
382
+ attention_output,
383
+ attention_mask=encoder_attention_mask,
384
+ head_mask=head_mask,
385
+ encoder_hidden_states=encoder_hidden_states,
386
+ past_key_values=past_key_values,
387
+ output_attentions=output_attentions,
388
+ cache_position=cache_position,
389
+ )
390
+ attention_output = cross_attention_outputs[0]
391
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
392
+ layer_output = apply_chunking_to_forward(
393
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
394
+ )
395
+ return (layer_output,) + outputs
396
+
397
+ def feed_forward_chunk(self, attention_output):
398
+ intermediate_output = self.intermediate(attention_output)
399
+ layer_output = self.output(intermediate_output, attention_output)
400
+ return layer_output
401
+
402
+
403
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
404
+ class BlipTextEncoder(nn.Module):
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.config = config
408
+ self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
409
+ self.gradient_checkpointing = False
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ attention_mask: Optional[torch.FloatTensor] = None,
415
+ head_mask: Optional[torch.FloatTensor] = None,
416
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
417
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
418
+ past_key_values: Optional[Cache] = None,
419
+ use_cache: Optional[bool] = None,
420
+ output_attentions: Optional[bool] = False,
421
+ output_hidden_states: Optional[bool] = False,
422
+ return_dict: Optional[bool] = True,
423
+ cache_position: Optional[torch.Tensor] = None,
424
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
425
+ if self.gradient_checkpointing and self.training:
426
+ if use_cache:
427
+ logger.warning(
428
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
429
+ )
430
+ use_cache = False
431
+
432
+ if use_cache:
433
+ if isinstance(past_key_values, tuple):
434
+ logger.warning_once(
435
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
436
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
437
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
438
+ )
439
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
440
+ # The model acts as encoder decoder but is not an encoder decoder. So we cast all cache objects to
441
+ # `EncoderDecoderCache` type assuming that the incoming cache is from `self_attention`
442
+ elif isinstance(past_key_values, DynamicCache):
443
+ past_key_values = EncoderDecoderCache(past_key_values, DynamicCache(config=self.config))
444
+ elif past_key_values is None:
445
+ past_key_values = EncoderDecoderCache(
446
+ DynamicCache(config=self.config), DynamicCache(config=self.config)
447
+ )
448
+
449
+ all_hidden_states = () if output_hidden_states else None
450
+ all_self_attentions = () if output_attentions else None
451
+ all_cross_attentions = () if output_attentions and encoder_hidden_states is not None else None
452
+
453
+ for i in range(self.config.num_hidden_layers):
454
+ layer_module = self.layer[i]
455
+ if output_hidden_states:
456
+ all_hidden_states = all_hidden_states + (hidden_states,)
457
+
458
+ layer_head_mask = head_mask[i] if head_mask is not None else None
459
+
460
+ layer_outputs = layer_module(
461
+ hidden_states,
462
+ attention_mask,
463
+ layer_head_mask,
464
+ encoder_hidden_states,
465
+ encoder_attention_mask,
466
+ past_key_values,
467
+ output_attentions,
468
+ cache_position,
469
+ )
470
+
471
+ hidden_states = layer_outputs[0]
472
+ if output_attentions:
473
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
474
+ if encoder_hidden_states is not None:
475
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
476
+
477
+ if output_hidden_states:
478
+ all_hidden_states = all_hidden_states + (hidden_states,)
479
+
480
+ if not return_dict:
481
+ return tuple(
482
+ v
483
+ for v in [
484
+ hidden_states,
485
+ past_key_values,
486
+ all_hidden_states,
487
+ all_self_attentions,
488
+ all_cross_attentions,
489
+ ]
490
+ if v is not None
491
+ )
492
+ return BaseModelOutputWithPastAndCrossAttentions(
493
+ last_hidden_state=hidden_states,
494
+ past_key_values=past_key_values,
495
+ hidden_states=all_hidden_states,
496
+ attentions=all_self_attentions,
497
+ cross_attentions=all_cross_attentions,
498
+ )
499
+
500
+
501
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BlipText
502
+ class BlipTextPooler(nn.Module):
503
+ def __init__(self, config):
504
+ super().__init__()
505
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
506
+ self.activation = nn.Tanh()
507
+
508
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
509
+ # We "pool" the model by simply taking the hidden state corresponding
510
+ # to the first token.
511
+ first_token_tensor = hidden_states[:, 0]
512
+ pooled_output = self.dense(first_token_tensor)
513
+ pooled_output = self.activation(pooled_output)
514
+ return pooled_output
515
+
516
+
517
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->BlipText
518
+ class BlipTextPredictionHeadTransform(nn.Module):
519
+ def __init__(self, config):
520
+ super().__init__()
521
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
522
+ if isinstance(config.hidden_act, str):
523
+ self.transform_act_fn = ACT2FN[config.hidden_act]
524
+ else:
525
+ self.transform_act_fn = config.hidden_act
526
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
527
+
528
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
529
+ hidden_states = self.dense(hidden_states)
530
+ hidden_states = self.transform_act_fn(hidden_states)
531
+ hidden_states = self.LayerNorm(hidden_states)
532
+ return hidden_states
533
+
534
+
535
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->BlipText
536
+ class BlipTextLMPredictionHead(nn.Module):
537
+ def __init__(self, config):
538
+ super().__init__()
539
+ self.transform = BlipTextPredictionHeadTransform(config)
540
+
541
+ # The output weights are the same as the input embeddings, but there is
542
+ # an output-only bias for each token.
543
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
544
+
545
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
546
+
547
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
548
+ self.decoder.bias = self.bias
549
+
550
+ def _tie_weights(self):
551
+ self.decoder.bias = self.bias
552
+
553
+ def forward(self, hidden_states):
554
+ hidden_states = self.transform(hidden_states)
555
+ hidden_states = self.decoder(hidden_states)
556
+ return hidden_states
557
+
558
+
559
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->BlipText
560
+ class BlipTextOnlyMLMHead(nn.Module):
561
+ def __init__(self, config):
562
+ super().__init__()
563
+ self.predictions = BlipTextLMPredictionHead(config)
564
+
565
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
566
+ prediction_scores = self.predictions(sequence_output)
567
+ return prediction_scores
568
+
569
+
570
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
571
+ class BlipTextPreTrainedModel(PreTrainedModel):
572
+ """
573
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
574
+ models.
575
+ """
576
+
577
+ config: BlipTextConfig
578
+ base_model_prefix = "bert"
579
+ _no_split_modules = []
580
+
581
+ def _init_weights(self, module):
582
+ """Initialize the weights"""
583
+ if isinstance(module, (nn.Linear, nn.Embedding)):
584
+ # Slightly different from the TF version which uses truncated_normal for initialization
585
+ # cf https://github.com/pytorch/pytorch/pull/5617
586
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
587
+ elif isinstance(module, nn.LayerNorm):
588
+ module.bias.data.zero_()
589
+ module.weight.data.fill_(1.0)
590
+ if isinstance(module, nn.Linear) and module.bias is not None:
591
+ module.bias.data.zero_()
592
+
593
+
594
+ # Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
595
+ class BlipTextModel(BlipTextPreTrainedModel):
596
+ """
597
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
598
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
599
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
600
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
601
+ `encoder_hidden_states` is then expected as an input to the forward pass.
602
+ """
603
+
604
+ def __init__(self, config, add_pooling_layer=True):
605
+ super().__init__(config)
606
+ self.config = config
607
+
608
+ self.embeddings = BlipTextEmbeddings(config)
609
+ self.encoder = BlipTextEncoder(config)
610
+ self.pooler = BlipTextPooler(config) if add_pooling_layer else None
611
+
612
+ self.post_init()
613
+
614
+ def get_input_embeddings(self):
615
+ return self.embeddings.word_embeddings
616
+
617
+ def set_input_embeddings(self, value):
618
+ self.embeddings.word_embeddings = value
619
+
620
+ # Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
621
+ def _prune_heads(self, heads_to_prune):
622
+ """
623
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
624
+ class PreTrainedModel
625
+ """
626
+ for layer, heads in heads_to_prune.items():
627
+ self.encoder.layer[layer].attention.prune_heads(heads)
628
+
629
+ def get_extended_attention_mask(
630
+ self, attention_mask: Tensor, input_shape: tuple[int], device: device, is_decoder: bool
631
+ ) -> Tensor:
632
+ """
633
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
634
+
635
+ Arguments:
636
+ attention_mask (`torch.Tensor`):
637
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
638
+ input_shape (`tuple[int]`):
639
+ The shape of the input to the model.
640
+ device (`torch.device`):
641
+ The device of the input to the model.
642
+
643
+ Returns:
644
+ `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
645
+ """
646
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
647
+ # ourselves in which case we just need to make it broadcastable to all heads.
648
+ if attention_mask.dim() == 3:
649
+ extended_attention_mask = attention_mask[:, None, :, :]
650
+ elif attention_mask.dim() == 2:
651
+ # Provided a padding mask of dimensions [batch_size, seq_length]
652
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
653
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
654
+ if is_decoder:
655
+ batch_size, seq_length = input_shape
656
+
657
+ seq_ids = torch.arange(seq_length, device=device)
658
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
659
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
660
+ causal_mask = causal_mask.to(attention_mask.dtype)
661
+
662
+ if causal_mask.shape[1] < attention_mask.shape[1]:
663
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
664
+ causal_mask = torch.cat(
665
+ [
666
+ torch.ones(
667
+ (batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype
668
+ ),
669
+ causal_mask,
670
+ ],
671
+ axis=-1,
672
+ )
673
+
674
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
675
+ else:
676
+ extended_attention_mask = attention_mask[:, None, None, :]
677
+ else:
678
+ raise ValueError(
679
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
680
+ )
681
+
682
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
683
+ # masked positions, this operation will create a tensor which is 0.0 for
684
+ # positions we want to attend and -10000.0 for masked positions.
685
+ # Since we are adding it to the raw scores before the softmax, this is
686
+ # effectively the same as removing these entirely.
687
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
688
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
689
+ return extended_attention_mask
690
+
691
+ def forward(
692
+ self,
693
+ input_ids: Optional[torch.Tensor] = None,
694
+ attention_mask: Optional[torch.Tensor] = None,
695
+ position_ids: Optional[torch.Tensor] = None,
696
+ head_mask: Optional[torch.Tensor] = None,
697
+ inputs_embeds: Optional[torch.Tensor] = None,
698
+ encoder_embeds: Optional[torch.Tensor] = None,
699
+ encoder_hidden_states: Optional[torch.Tensor] = None,
700
+ encoder_attention_mask: Optional[torch.Tensor] = None,
701
+ past_key_values: Optional[Cache] = None,
702
+ use_cache: Optional[bool] = None,
703
+ output_attentions: Optional[bool] = None,
704
+ output_hidden_states: Optional[bool] = None,
705
+ return_dict: Optional[bool] = None,
706
+ is_decoder: Optional[bool] = False,
707
+ cache_position: Optional[torch.Tensor] = None,
708
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
709
+ r"""
710
+ encoder_hidden_states (`torch.FloatTensor`, *optional*):
711
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
712
+ the model is configured as a decoder.
713
+ encoder_attention_mask (`torch.FloatTensor`, *optional*):
714
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
715
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
716
+ - 1 for tokens that are **not masked**,
717
+ - 0 for tokens that are **masked**.
718
+ past_key_values (`Cache`, *optional*):
719
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
720
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
721
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
722
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
723
+ use_cache (`bool`, *optional*):
724
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
725
+ `past_key_values`).
726
+ """
727
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
728
+ output_hidden_states = (
729
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
730
+ )
731
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
732
+
733
+ if is_decoder:
734
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
735
+ else:
736
+ use_cache = False
737
+
738
+ if input_ids is not None and inputs_embeds is not None:
739
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
740
+ elif input_ids is not None:
741
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
742
+ input_shape = input_ids.size()
743
+ batch_size, seq_length = input_shape
744
+ device = input_ids.device
745
+ elif inputs_embeds is not None:
746
+ input_shape = inputs_embeds.size()[:-1]
747
+ batch_size, seq_length = input_shape
748
+ device = inputs_embeds.device
749
+ elif encoder_embeds is not None:
750
+ input_shape = encoder_embeds.size()[:-1]
751
+ batch_size, seq_length = input_shape
752
+ device = encoder_embeds.device
753
+ else:
754
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
755
+
756
+ past_key_values_length = 0
757
+ if past_key_values is not None:
758
+ past_key_values_length = (
759
+ past_key_values[0][0].shape[-2]
760
+ if not isinstance(past_key_values, Cache)
761
+ else past_key_values.get_seq_length()
762
+ )
763
+
764
+ if attention_mask is None:
765
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length)).to(device)
766
+
767
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
768
+ # ourselves in which case we just need to make it broadcastable to all heads.
769
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
770
+ attention_mask, input_shape, device, is_decoder
771
+ )
772
+
773
+ # If a 2D or 3D attention mask is provided for the cross-attention
774
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
775
+ if encoder_hidden_states is not None:
776
+ if isinstance(encoder_hidden_states, list):
777
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
778
+ else:
779
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
780
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
781
+
782
+ if isinstance(encoder_attention_mask, list):
783
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
784
+ elif encoder_attention_mask is None:
785
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
786
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
787
+ else:
788
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
789
+ else:
790
+ encoder_extended_attention_mask = None
791
+
792
+ # Prepare head mask if needed
793
+ # 1.0 in head_mask indicate we keep the head
794
+ # attention_probs has shape bsz x n_heads x N x N
795
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
796
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
797
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
798
+
799
+ if encoder_embeds is None:
800
+ embedding_output = self.embeddings(
801
+ input_ids=input_ids,
802
+ position_ids=position_ids,
803
+ inputs_embeds=inputs_embeds,
804
+ past_key_values_length=past_key_values_length,
805
+ )
806
+ else:
807
+ embedding_output = encoder_embeds
808
+
809
+ encoder_outputs = self.encoder(
810
+ embedding_output,
811
+ attention_mask=extended_attention_mask,
812
+ head_mask=head_mask,
813
+ encoder_hidden_states=encoder_hidden_states,
814
+ encoder_attention_mask=encoder_extended_attention_mask,
815
+ past_key_values=past_key_values,
816
+ use_cache=use_cache,
817
+ output_attentions=output_attentions,
818
+ output_hidden_states=output_hidden_states,
819
+ return_dict=return_dict,
820
+ cache_position=cache_position,
821
+ )
822
+ sequence_output = encoder_outputs[0]
823
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
824
+
825
+ if not return_dict:
826
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
827
+
828
+ return BaseModelOutputWithPoolingAndCrossAttentions(
829
+ last_hidden_state=sequence_output,
830
+ pooler_output=pooled_output,
831
+ past_key_values=encoder_outputs.past_key_values,
832
+ hidden_states=encoder_outputs.hidden_states,
833
+ attentions=encoder_outputs.attentions,
834
+ cross_attentions=encoder_outputs.cross_attentions,
835
+ )
836
+
837
+
838
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
839
+ class BlipTextLMHeadModel(BlipTextPreTrainedModel, GenerationMixin):
840
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
841
+
842
+ def __init__(self, config):
843
+ super().__init__(config)
844
+
845
+ self.bert = BlipTextModel(config, add_pooling_layer=False)
846
+ self.cls = BlipTextOnlyMLMHead(config)
847
+ self.label_smoothing = config.label_smoothing
848
+
849
+ def get_input_embeddings(self):
850
+ return self.bert.get_input_embeddings()
851
+
852
+ def set_input_embeddings(self, new_embeddings):
853
+ self.bert.set_input_embeddings(new_embeddings)
854
+
855
+ def get_output_embeddings(self):
856
+ return self.cls.predictions.decoder
857
+
858
+ def set_output_embeddings(self, new_embeddings):
859
+ self.cls.predictions.decoder = new_embeddings
860
+ self.cls.predictions.bias = new_embeddings.bias
861
+
862
+ def forward(
863
+ self,
864
+ input_ids: Optional[torch.Tensor] = None,
865
+ attention_mask: Optional[torch.Tensor] = None,
866
+ position_ids: Optional[torch.Tensor] = None,
867
+ head_mask: Optional[torch.Tensor] = None,
868
+ inputs_embeds: Optional[torch.Tensor] = None,
869
+ encoder_hidden_states: Optional[torch.Tensor] = None,
870
+ encoder_attention_mask: Optional[torch.Tensor] = None,
871
+ labels: Optional[torch.Tensor] = None,
872
+ past_key_values: Optional[Cache] = None,
873
+ use_cache: Optional[bool] = None,
874
+ output_attentions: Optional[bool] = None,
875
+ output_hidden_states: Optional[bool] = None,
876
+ return_dict: Optional[bool] = None,
877
+ return_logits: Optional[bool] = False,
878
+ is_decoder: Optional[bool] = True,
879
+ reduction: Optional[str] = "mean",
880
+ cache_position: Optional[torch.Tensor] = None,
881
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
882
+ r"""
883
+ encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
884
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
885
+ configured as a decoder.
886
+ encoder_attention_mask (`torch.FloatTensor`, *optional*):
887
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
888
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
889
+ - 1 for tokens that are **not masked**,
890
+ - 0 for tokens that are **masked**.
891
+ labels (`torch.LongTensor`, *optional*):
892
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
893
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
894
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
895
+ past_key_values (`Cache`, *optional*):
896
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
897
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
898
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
899
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
900
+ use_cache (`bool`, *optional*):
901
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
902
+ `past_key_values`).
903
+ """
904
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
905
+ if labels is not None:
906
+ use_cache = False
907
+
908
+ outputs = self.bert(
909
+ input_ids,
910
+ attention_mask=attention_mask,
911
+ position_ids=position_ids,
912
+ head_mask=head_mask,
913
+ inputs_embeds=inputs_embeds,
914
+ encoder_hidden_states=encoder_hidden_states,
915
+ encoder_attention_mask=encoder_attention_mask,
916
+ past_key_values=past_key_values,
917
+ use_cache=use_cache,
918
+ output_attentions=output_attentions,
919
+ output_hidden_states=output_hidden_states,
920
+ return_dict=return_dict,
921
+ is_decoder=is_decoder,
922
+ cache_position=cache_position,
923
+ )
924
+
925
+ sequence_output = outputs[0]
926
+ prediction_scores = self.cls(sequence_output)
927
+
928
+ if return_logits:
929
+ return prediction_scores[:, :-1, :].contiguous()
930
+
931
+ lm_loss = None
932
+ if labels is not None:
933
+ # we are doing next-token prediction; shift prediction scores and input ids by one
934
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
935
+ labels = labels[:, 1:].contiguous().to(shifted_prediction_scores.device)
936
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=self.label_smoothing)
937
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
938
+ if reduction == "none":
939
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
940
+
941
+ if not return_dict:
942
+ output = (prediction_scores,) + outputs[2:]
943
+ return ((lm_loss,) + output) if lm_loss is not None else output
944
+
945
+ return CausalLMOutputWithCrossAttentions(
946
+ loss=lm_loss,
947
+ logits=prediction_scores,
948
+ past_key_values=outputs.past_key_values,
949
+ hidden_states=outputs.hidden_states,
950
+ attentions=outputs.attentions,
951
+ cross_attentions=outputs.cross_attentions,
952
+ )
953
+
954
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
955
+ # Overwrite -- hardcoded key return (`is_decoder=True`)
956
+
957
+ model_inputs = super().prepare_inputs_for_generation(
958
+ input_ids,
959
+ past_key_values=past_key_values,
960
+ attention_mask=attention_mask,
961
+ **model_kwargs,
962
+ )
963
+ model_inputs["is_decoder"] = True
964
+
965
+ return model_inputs
966
+
967
+
968
+ __all__ = ["BlipTextModel", "BlipTextLMHeadModel", "BlipTextPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip.py ADDED
@@ -0,0 +1,1709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Salesforce Team Authors and The HuggingFace Team. 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
+ """TensorFlow BLIP model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Any
22
+
23
+ import tensorflow as tf
24
+
25
+ from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling
26
+ from ...modeling_tf_utils import (
27
+ TFPreTrainedModel,
28
+ get_initializer,
29
+ get_tf_activation,
30
+ keras,
31
+ keras_serializable,
32
+ shape_list,
33
+ unpack_inputs,
34
+ )
35
+ from ...tf_utils import check_embeddings_within_bounds, stable_softmax
36
+ from ...utils import (
37
+ ModelOutput,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
44
+ from .modeling_tf_blip_text import BLIP_TEXT_INPUTS_DOCSTRING, TFBlipTextLMHeadModel, TFBlipTextModel
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
50
+
51
+
52
+ # Copied from transformers.models.clip.modeling_tf_clip.contrastive_loss
53
+ def contrastive_loss(logits: tf.Tensor) -> tf.Tensor:
54
+ return tf.math.reduce_mean(
55
+ keras.metrics.sparse_categorical_crossentropy(
56
+ y_true=tf.range(shape_list(logits)[0]), y_pred=logits, from_logits=True
57
+ )
58
+ )
59
+
60
+
61
+ # Copied from transformers.models.clip.modeling_tf_clip.clip_loss with clip->blip
62
+ def blip_loss(similarity: tf.Tensor) -> tf.Tensor:
63
+ caption_loss = contrastive_loss(similarity)
64
+ image_loss = contrastive_loss(tf.transpose(similarity))
65
+ return (caption_loss + image_loss) / 2.0
66
+
67
+
68
+ @dataclass
69
+ class TFBlipForConditionalGenerationModelOutput(ModelOutput):
70
+ """
71
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
72
+ last hidden states. This class also adds the loss term from the text decoder.
73
+
74
+ Args:
75
+ loss (`tf.Tensor`, *optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
76
+ Language modeling loss from the text decoder.
77
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
78
+ Prediction scores of the language modeling head of the text decoder model.
79
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)`, *optional*):
80
+ The image embeddings obtained after applying the Vision Transformer model to the input image.
81
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
82
+ Sequence of hidden-states at the output of the last layer of the model.
83
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True`):
84
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
85
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
86
+
87
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
88
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed):
89
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
90
+ sequence_length)`.
91
+
92
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
93
+ heads.`
94
+ """
95
+
96
+ loss: tuple[tf.Tensor] | None = None
97
+ logits: tuple[tf.Tensor] | None = None
98
+ image_embeds: tf.Tensor | None = None
99
+ last_hidden_state: tf.Tensor | None = None
100
+ hidden_states: tuple[tf.Tensor, ...] | None = None
101
+ attentions: tuple[tf.Tensor, ...] | None = None
102
+
103
+ @property
104
+ def decoder_logits(self):
105
+ warnings.warn(
106
+ "`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
107
+ " Please use the `logits` attribute to retrieve the final output instead.",
108
+ FutureWarning,
109
+ )
110
+ return self.logits
111
+
112
+
113
+ @dataclass
114
+ class TFBlipTextVisionModelOutput(ModelOutput):
115
+ """
116
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
117
+ last hidden states. This class also adds the loss term from the text decoder.
118
+
119
+ Args:
120
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
121
+ Language modeling loss from the text decoder.
122
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
123
+ The image embeddings obtained by applying the projection layer to the pooler_output.
124
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
125
+ Sequence of hidden-states at the output of the last layer of the model.
126
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
127
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
128
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
129
+
130
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
131
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
132
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
133
+ sequence_length)`.
134
+
135
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
136
+ heads.
137
+ """
138
+
139
+ loss: tf.Tensor | None = None
140
+ image_embeds: tf.Tensor | None = None
141
+ last_hidden_state: tf.Tensor | None = None
142
+ hidden_states: tuple[tf.Tensor, ...] | None = None
143
+ attentions: tuple[tf.Tensor, ...] | None = None
144
+
145
+
146
+ @dataclass
147
+ class TFBlipImageTextMatchingModelOutput(ModelOutput):
148
+ """
149
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
150
+ last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
151
+ scores.
152
+
153
+ Args:
154
+ itm_score (`tf.Tensor`):
155
+ The image-text similarity scores.
156
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
157
+ Language modeling loss from the text decoder.
158
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
159
+ The image embeddings obtained by applying the projection layer to the pooler_output.
160
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
161
+ Sequence of hidden-states at the output of the last layer of the model.
162
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
163
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
164
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
165
+
166
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
167
+ vision_pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`, *optional*):
168
+ Last layer hidden-state of the vision of the vision-only branch of the model.
169
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
170
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
171
+ sequence_length)`.
172
+
173
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
174
+ heads.
175
+ question_embeds (`tf.Tensor`):
176
+ The question embeddings obtained by the text projection layer.
177
+ """
178
+
179
+ itm_score: tf.Tensor | None = None
180
+ loss: tf.Tensor | None = None
181
+ image_embeds: tf.Tensor | None = None
182
+ last_hidden_state: tf.Tensor | None = None
183
+ hidden_states: tuple[tf.Tensor, ...] | None = None
184
+ vision_pooler_output: tf.Tensor | None = None
185
+ attentions: tuple[tf.Tensor, ...] | None = None
186
+ question_embeds: tuple[tf.Tensor] | None = None
187
+
188
+
189
+ @dataclass
190
+ class TFBlipOutput(ModelOutput):
191
+ """
192
+ Args:
193
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
194
+ Contrastive loss for image-text similarity.
195
+ logits_per_image:(`tf.Tensor` of shape `(image_batch_size, text_batch_size)`):
196
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
197
+ similarity scores.
198
+ logits_per_text:(`tf.Tensor` of shape `(text_batch_size, image_batch_size)`):
199
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
200
+ similarity scores.
201
+ text_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
202
+ The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
203
+ image_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
204
+ The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
205
+ text_model_output(`BaseModelOutputWithPooling`):
206
+ The output of the [`BlipTextModel`].
207
+ vision_model_output(`BaseModelOutputWithPooling`):
208
+ The output of the [`BlipVisionModel`].
209
+ """
210
+
211
+ loss: tf.Tensor | None = None
212
+ logits_per_image: tf.Tensor | None = None
213
+ logits_per_text: tf.Tensor | None = None
214
+ text_embeds: tf.Tensor | None = None
215
+ image_embeds: tf.Tensor | None = None
216
+ text_model_output: TFBaseModelOutputWithPooling = None
217
+ vision_model_output: TFBaseModelOutputWithPooling = None
218
+
219
+ def to_tuple(self) -> tuple[Any]:
220
+ return tuple(
221
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
222
+ for k in self.keys()
223
+ )
224
+
225
+
226
+ class TFBlipVisionEmbeddings(keras.layers.Layer):
227
+ def __init__(self, config: BlipVisionConfig, **kwargs):
228
+ super().__init__(**kwargs)
229
+ self.config = config
230
+ self.embed_dim = config.hidden_size
231
+ self.image_size = config.image_size
232
+ self.patch_size = config.patch_size
233
+
234
+ self.patch_embedding = keras.layers.Conv2D(
235
+ filters=self.embed_dim,
236
+ kernel_size=self.patch_size,
237
+ strides=self.patch_size,
238
+ kernel_initializer=get_initializer(self.config.initializer_range),
239
+ data_format="channels_last",
240
+ name="patch_embedding",
241
+ )
242
+
243
+ self.num_patches = (self.image_size // self.patch_size) ** 2
244
+ self.num_positions = self.num_patches + 1
245
+
246
+ def build(self, input_shape=None):
247
+ self.class_embedding = self.add_weight(
248
+ shape=(1, 1, self.embed_dim),
249
+ initializer=get_initializer(self.config.initializer_range),
250
+ trainable=True,
251
+ name="class_embedding",
252
+ )
253
+
254
+ self.position_embedding = self.add_weight(
255
+ shape=(1, self.num_positions, self.embed_dim),
256
+ initializer=get_initializer(self.config.initializer_range),
257
+ trainable=True,
258
+ name="position_embedding",
259
+ )
260
+
261
+ if self.built:
262
+ return
263
+ self.built = True
264
+ if getattr(self, "patch_embedding", None) is not None:
265
+ with tf.name_scope(self.patch_embedding.name):
266
+ self.patch_embedding.build([None, None, None, 3])
267
+
268
+ def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
269
+ # Input is channels-first, we transpose. PyTorch transposes after the conv because PyTorch
270
+ # likes channels-first convs.
271
+ batch_size = tf.shape(pixel_values)[0]
272
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
273
+ patch_embeds = self.patch_embedding(pixel_values)
274
+ patch_embeds = tf.reshape(patch_embeds, (batch_size, self.num_patches, -1))
275
+
276
+ class_embeds = tf.broadcast_to(self.class_embedding, (batch_size, 1, self.embed_dim))
277
+ embeddings = tf.concat([class_embeds, patch_embeds], axis=1)
278
+ embeddings = embeddings + self.position_embedding[:, : tf.shape(embeddings)[1], :]
279
+ return embeddings
280
+
281
+
282
+ # Copied from transformers.models.clip.modeling_tf_clip.TFCLIPTextEmbeddings with CLIP->Blip
283
+ class TFBlipTextEmbeddings(keras.layers.Layer):
284
+ def __init__(self, config: BlipTextConfig, **kwargs):
285
+ super().__init__(**kwargs)
286
+
287
+ self.embed_dim = config.hidden_size
288
+
289
+ self.config = config
290
+
291
+ def build(self, input_shape: tf.TensorShape = None):
292
+ with tf.name_scope("token_embedding"):
293
+ self.weight = self.add_weight(
294
+ shape=(self.config.vocab_size, self.embed_dim),
295
+ initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
296
+ trainable=True,
297
+ name="weight",
298
+ )
299
+
300
+ with tf.name_scope("position_embedding"):
301
+ self.position_embedding = self.add_weight(
302
+ shape=(self.config.max_position_embeddings, self.embed_dim),
303
+ initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
304
+ trainable=True,
305
+ name="embeddings",
306
+ )
307
+
308
+ super().build(input_shape)
309
+
310
+ def call(
311
+ self,
312
+ input_ids: tf.Tensor | None = None,
313
+ position_ids: tf.Tensor | None = None,
314
+ inputs_embeds: tf.Tensor | None = None,
315
+ ) -> tf.Tensor:
316
+ """
317
+ Applies embedding based on inputs tensor.
318
+
319
+ Returns:
320
+ final_embeddings (`tf.Tensor`): output embedding tensor.
321
+ """
322
+ if input_ids is None and inputs_embeds is None:
323
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
324
+
325
+ if inputs_embeds is None:
326
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
327
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
328
+
329
+ input_shape = shape_list(inputs_embeds)[:-1]
330
+
331
+ if position_ids is None:
332
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
333
+
334
+ position_embeds = tf.gather(params=self.position_embedding, indices=position_ids)
335
+ position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
336
+ final_embeddings = inputs_embeds + position_embeds
337
+
338
+ return final_embeddings
339
+
340
+
341
+ class TFBlipAttention(keras.layers.Layer):
342
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
343
+
344
+ def __init__(self, config, **kwargs):
345
+ super().__init__(**kwargs)
346
+ self.config = config
347
+ self.embed_dim = config.hidden_size
348
+ self.num_heads = config.num_attention_heads
349
+ self.head_dim = self.embed_dim // self.num_heads
350
+ if self.head_dim * self.num_heads != self.embed_dim:
351
+ raise ValueError(
352
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
353
+ f" {self.num_heads})."
354
+ )
355
+ self.scale = self.head_dim**-0.5
356
+ self.dropout = keras.layers.Dropout(config.attention_dropout, name="dropout")
357
+
358
+ self.qkv = keras.layers.Dense(
359
+ 3 * self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
360
+ )
361
+
362
+ self.projection = keras.layers.Dense(
363
+ self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
364
+ )
365
+
366
+ def call(
367
+ self,
368
+ hidden_states: tf.Tensor,
369
+ head_mask: tf.Tensor | None = None,
370
+ output_attentions: bool | None = False,
371
+ training: bool | None = None,
372
+ ) -> tuple[tf.Tensor, tf.Tensor | None, tuple[tf.Tensor] | None]:
373
+ """Input shape: Batch x Time x Channel"""
374
+
375
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
376
+
377
+ mixed_qkv = self.qkv(hidden_states)
378
+ mixed_qkv = tf.reshape(mixed_qkv, (bsz, tgt_len, 3, self.num_heads, self.head_dim))
379
+ mixed_qkv = tf.transpose(mixed_qkv, perm=(2, 0, 3, 1, 4))
380
+
381
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
382
+
383
+ # Take the dot product between "query" and "key" to get the raw attention scores.
384
+ attention_scores = query_states @ tf.transpose(key_states, (0, 1, 3, 2))
385
+
386
+ attention_scores = attention_scores * self.scale
387
+
388
+ # Normalize the attention scores to probabilities.
389
+ attention_probs = stable_softmax(attention_scores, axis=-1)
390
+
391
+ # This is actually dropping out entire tokens to attend to, which might
392
+ # seem a bit unusual, but is taken from the original Transformer paper.
393
+ attention_probs = self.dropout(attention_probs, training=training)
394
+
395
+ # Mask heads if we want to
396
+ if head_mask is not None:
397
+ attention_probs = attention_probs * head_mask
398
+
399
+ context_layer = tf.transpose(attention_probs @ value_states, perm=(0, 2, 1, 3))
400
+
401
+ new_context_layer_shape = shape_list(context_layer)[:-2] + [self.embed_dim]
402
+ context_layer = tf.reshape(context_layer, new_context_layer_shape)
403
+
404
+ output = self.projection(context_layer)
405
+
406
+ outputs = (output, attention_probs) if output_attentions else (output, None)
407
+
408
+ return outputs
409
+
410
+ def build(self, input_shape=None):
411
+ if self.built:
412
+ return
413
+ self.built = True
414
+ if getattr(self, "dropout", None) is not None:
415
+ with tf.name_scope(self.dropout.name):
416
+ self.dropout.build(None)
417
+ if getattr(self, "qkv", None) is not None:
418
+ with tf.name_scope(self.qkv.name):
419
+ self.qkv.build([None, None, self.embed_dim])
420
+ if getattr(self, "projection", None) is not None:
421
+ with tf.name_scope(self.projection.name):
422
+ self.projection.build([None, None, self.embed_dim])
423
+
424
+
425
+ class TFBlipMLP(keras.layers.Layer):
426
+ def __init__(self, config: BlipConfig, **kwargs):
427
+ super().__init__(**kwargs)
428
+
429
+ self.activation_fn = get_tf_activation(config.hidden_act)
430
+
431
+ in_proj_std = (config.hidden_size**-0.5) * ((2 * config.num_hidden_layers) ** -0.5)
432
+ fc_std = (2 * config.hidden_size) ** -0.5
433
+
434
+ self.fc1 = keras.layers.Dense(
435
+ units=config.intermediate_size, kernel_initializer=get_initializer(fc_std), name="fc1"
436
+ )
437
+ self.fc2 = keras.layers.Dense(
438
+ units=config.hidden_size, kernel_initializer=get_initializer(in_proj_std), name="fc2"
439
+ )
440
+ self.config = config
441
+
442
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
443
+ hidden_states = self.fc1(inputs=hidden_states)
444
+ hidden_states = self.activation_fn(hidden_states)
445
+ hidden_states = self.fc2(inputs=hidden_states)
446
+ return hidden_states
447
+
448
+ def build(self, input_shape=None):
449
+ if self.built:
450
+ return
451
+ self.built = True
452
+ if getattr(self, "fc1", None) is not None:
453
+ with tf.name_scope(self.fc1.name):
454
+ self.fc1.build([None, None, self.config.hidden_size])
455
+ if getattr(self, "fc2", None) is not None:
456
+ with tf.name_scope(self.fc2.name):
457
+ self.fc2.build([None, None, self.config.intermediate_size])
458
+
459
+
460
+ class TFBlipEncoderLayer(keras.layers.Layer):
461
+ def __init__(self, config: BlipConfig, **kwargs):
462
+ super().__init__(**kwargs)
463
+ self.embed_dim = config.hidden_size
464
+ self.self_attn = TFBlipAttention(config, name="self_attn")
465
+ self.layer_norm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm1")
466
+ self.mlp = TFBlipMLP(config, name="mlp")
467
+ self.layer_norm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm2")
468
+
469
+ def call(
470
+ self,
471
+ hidden_states: tf.Tensor,
472
+ attention_mask: tf.Tensor,
473
+ output_attentions: bool | None = False,
474
+ training: bool | None = None,
475
+ ) -> tuple[tf.Tensor]:
476
+ """
477
+ Args:
478
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
479
+ attention_mask (`tf.Tensor`): attention mask of size
480
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
481
+ `(config.encoder_attention_heads,)`.
482
+ output_attentions (`bool`, *optional*):
483
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
484
+ returned tensors for more detail.
485
+ """
486
+ residual = hidden_states
487
+
488
+ hidden_states = self.layer_norm1(hidden_states)
489
+ hidden_states, attn_weights = self.self_attn(
490
+ hidden_states=hidden_states,
491
+ head_mask=attention_mask,
492
+ output_attentions=output_attentions,
493
+ training=training,
494
+ )
495
+ hidden_states = hidden_states + residual
496
+ residual = hidden_states
497
+ hidden_states = self.layer_norm2(hidden_states)
498
+ hidden_states = self.mlp(hidden_states)
499
+
500
+ hidden_states = hidden_states + residual
501
+
502
+ outputs = (hidden_states,)
503
+
504
+ if output_attentions:
505
+ outputs += (attn_weights,)
506
+
507
+ return outputs
508
+
509
+ def build(self, input_shape=None):
510
+ if self.built:
511
+ return
512
+ self.built = True
513
+ if getattr(self, "self_attn", None) is not None:
514
+ with tf.name_scope(self.self_attn.name):
515
+ self.self_attn.build(None)
516
+ if getattr(self, "layer_norm1", None) is not None:
517
+ with tf.name_scope(self.layer_norm1.name):
518
+ self.layer_norm1.build([None, None, self.embed_dim])
519
+ if getattr(self, "mlp", None) is not None:
520
+ with tf.name_scope(self.mlp.name):
521
+ self.mlp.build(None)
522
+ if getattr(self, "layer_norm2", None) is not None:
523
+ with tf.name_scope(self.layer_norm2.name):
524
+ self.layer_norm2.build([None, None, self.embed_dim])
525
+
526
+
527
+ class TFBlipPreTrainedModel(TFPreTrainedModel):
528
+ """
529
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
530
+ models.
531
+ """
532
+
533
+ config_class = BlipConfig
534
+ base_model_prefix = "blip"
535
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
536
+
537
+
538
+ BLIP_START_DOCSTRING = r"""
539
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
540
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
541
+ etc.)
542
+
543
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
544
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
545
+ behavior.
546
+
547
+ Parameters:
548
+ config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
549
+ Initializing with a config file does not load the weights associated with the model, only the
550
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
551
+ """
552
+
553
+ BLIP_VISION_INPUTS_DOCSTRING = r"""
554
+ Args:
555
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
556
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
557
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
558
+ output_attentions (`bool`, *optional*):
559
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
560
+ tensors for more detail.
561
+ output_hidden_states (`bool`, *optional*):
562
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
563
+ more detail.
564
+ return_dict (`bool`, *optional*):
565
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
566
+ """
567
+
568
+ BLIP_INPUTS_DOCSTRING = r"""
569
+ Args:
570
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
571
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
572
+ it.
573
+
574
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
575
+
576
+ [What are input IDs?](../glossary#input-ids)
577
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
578
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
579
+
580
+ - 1 for tokens that are **not masked**,
581
+ - 0 for tokens that are **masked**.
582
+
583
+ [What are attention masks?](../glossary#attention-mask)
584
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
585
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
586
+ config.max_position_embeddings - 1]`.
587
+
588
+ [What are position IDs?](../glossary#position-ids)
589
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
590
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
591
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
592
+ return_loss (`bool`, *optional*):
593
+ Whether or not to return the contrastive loss.
594
+ output_attentions (`bool`, *optional*):
595
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
596
+ tensors for more detail.
597
+ output_hidden_states (`bool`, *optional*):
598
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
599
+ more detail.
600
+ return_dict (`bool`, *optional*):
601
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
602
+ """
603
+
604
+
605
+ @keras_serializable
606
+ class TFBlipEncoder(keras.layers.Layer):
607
+ config_class = BlipConfig
608
+ """
609
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
610
+ [`BlipEncoderLayer`].
611
+
612
+ Args:
613
+ config (`BlipConfig`):
614
+ The corresponding vision configuration for the `BlipEncoder`.
615
+ """
616
+
617
+ def __init__(self, config: BlipConfig, **kwargs):
618
+ super().__init__(**kwargs)
619
+ self.config = config
620
+ self.layers = [TFBlipEncoderLayer(config, name=f"layers_._{i}") for i in range(config.num_hidden_layers)]
621
+
622
+ @unpack_inputs
623
+ def call(
624
+ self,
625
+ inputs_embeds,
626
+ attention_mask: tf.Tensor | None = None,
627
+ output_attentions: bool | None = None,
628
+ output_hidden_states: bool | None = None,
629
+ return_dict: bool | None = None,
630
+ training: bool | None = None,
631
+ ) -> tuple | TFBaseModelOutput:
632
+ r"""
633
+ Args:
634
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
635
+ Embedded representation of the inputs. Should be float, not int tokens.
636
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
637
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
638
+
639
+ - 1 for tokens that are **not masked**,
640
+ - 0 for tokens that are **masked**.
641
+
642
+ [What are attention masks?](../glossary#attention-mask)
643
+ output_attentions (`bool`, *optional*):
644
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
645
+ returned tensors for more detail.
646
+ output_hidden_states (`bool`, *optional*):
647
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
648
+ for more detail.
649
+ return_dict (`bool`, *optional*):
650
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
651
+ """
652
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
653
+ output_hidden_states = (
654
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
655
+ )
656
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
657
+
658
+ encoder_states = () if output_hidden_states else None
659
+ all_attentions = () if output_attentions else None
660
+
661
+ hidden_states = inputs_embeds
662
+ for idx, encoder_layer in enumerate(self.layers):
663
+ if output_hidden_states:
664
+ encoder_states = encoder_states + (hidden_states,)
665
+ layer_outputs = encoder_layer(
666
+ hidden_states,
667
+ attention_mask,
668
+ output_attentions=output_attentions,
669
+ training=training,
670
+ )
671
+
672
+ hidden_states = layer_outputs[0]
673
+
674
+ if output_attentions:
675
+ all_attentions = all_attentions + (layer_outputs[1],)
676
+
677
+ if output_hidden_states:
678
+ encoder_states = encoder_states + (hidden_states,)
679
+
680
+ if not return_dict:
681
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
682
+ return TFBaseModelOutput(
683
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
684
+ )
685
+
686
+ def build(self, input_shape=None):
687
+ if self.built:
688
+ return
689
+ self.built = True
690
+ if getattr(self, "layers", None) is not None:
691
+ for layer in self.layers:
692
+ with tf.name_scope(layer.name):
693
+ layer.build(None)
694
+
695
+
696
+ class TFBlipVisionModel(TFBlipPreTrainedModel):
697
+ main_input_name = "pixel_values"
698
+ config_class = BlipVisionConfig
699
+
700
+ def __init__(self, config: BlipVisionConfig, *args, **kwargs):
701
+ super().__init__(config, *args, **kwargs)
702
+ self.config = config
703
+
704
+ self.embeddings = TFBlipVisionEmbeddings(config, name="embeddings")
705
+ self.encoder = TFBlipEncoder(config, name="encoder")
706
+ self.post_layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="post_layernorm")
707
+ self.embed_dim = config.hidden_size
708
+
709
+ def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOutputWithPooling:
710
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
711
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
712
+
713
+ return TFBaseModelOutputWithPooling(
714
+ last_hidden_state=output.last_hidden_state,
715
+ pooler_output=output.pooler_output,
716
+ hidden_states=hs,
717
+ attentions=attns,
718
+ )
719
+
720
+ @unpack_inputs
721
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
722
+ @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=BlipVisionConfig)
723
+ def call(
724
+ self,
725
+ pixel_values: tf.Tensor | None = None,
726
+ output_attentions: bool | None = None,
727
+ output_hidden_states: bool | None = None,
728
+ return_dict: bool | None = None,
729
+ training: bool | None = None,
730
+ ) -> tuple | TFBaseModelOutputWithPooling:
731
+ r"""
732
+ Returns:
733
+
734
+ """
735
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
736
+ output_hidden_states = (
737
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
738
+ )
739
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
740
+
741
+ if pixel_values is None:
742
+ raise ValueError("You have to specify pixel_values")
743
+
744
+ hidden_states = self.embeddings(pixel_values)
745
+
746
+ encoder_outputs = self.encoder(
747
+ inputs_embeds=hidden_states,
748
+ output_attentions=output_attentions,
749
+ output_hidden_states=output_hidden_states,
750
+ return_dict=return_dict,
751
+ training=training,
752
+ )
753
+
754
+ last_hidden_state = encoder_outputs[0]
755
+ last_hidden_state = self.post_layernorm(last_hidden_state)
756
+
757
+ pooled_output = last_hidden_state[:, 0, :]
758
+ # TF gets confused if we call the layer with inputs of different ranks, so insert a singleton dimension
759
+ pooled_output = self.post_layernorm(tf.expand_dims(pooled_output, 1))
760
+ pooled_output = tf.squeeze(pooled_output, 1)
761
+
762
+ if not return_dict:
763
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
764
+
765
+ return TFBaseModelOutputWithPooling(
766
+ last_hidden_state=last_hidden_state,
767
+ pooler_output=pooled_output,
768
+ hidden_states=encoder_outputs.hidden_states,
769
+ attentions=encoder_outputs.attentions,
770
+ )
771
+
772
+ def get_input_embeddings(self):
773
+ return self.embeddings
774
+
775
+ def build(self, input_shape=None):
776
+ if self.built:
777
+ return
778
+ self.built = True
779
+ if getattr(self, "embeddings", None) is not None:
780
+ with tf.name_scope(self.embeddings.name):
781
+ self.embeddings.build(None)
782
+ if getattr(self, "encoder", None) is not None:
783
+ with tf.name_scope(self.encoder.name):
784
+ self.encoder.build(None)
785
+ if getattr(self, "post_layernorm", None) is not None:
786
+ with tf.name_scope(self.post_layernorm.name):
787
+ self.post_layernorm.build([None, None, self.embed_dim])
788
+
789
+
790
+ class TFBlipMainLayer(keras.layers.Layer):
791
+ config_class = BlipConfig
792
+
793
+ def __init__(self, config: BlipConfig, *args, **kwargs):
794
+ super().__init__(*args, **kwargs)
795
+
796
+ if not isinstance(config.text_config, BlipTextConfig):
797
+ raise TypeError(
798
+ "config.text_config is expected to be of type BlipTextConfig but is of type"
799
+ f" {type(config.text_config)}."
800
+ )
801
+
802
+ if not isinstance(config.vision_config, BlipVisionConfig):
803
+ raise TypeError(
804
+ "config.vision_config is expected to be of type BlipVisionConfig but is of type"
805
+ f" {type(config.vision_config)}."
806
+ )
807
+
808
+ text_config = config.text_config
809
+ vision_config = config.vision_config
810
+
811
+ self.projection_dim = config.projection_dim
812
+ self.text_embed_dim = text_config.hidden_size
813
+ self.vision_embed_dim = vision_config.hidden_size
814
+
815
+ self.text_model = TFBlipTextModel(text_config, name="text_model")
816
+ self.vision_model = TFBlipVisionModel(vision_config, name="vision_model")
817
+
818
+ self.visual_projection = keras.layers.Dense(
819
+ self.projection_dim,
820
+ use_bias=False,
821
+ kernel_initializer=get_initializer(config.initializer_range),
822
+ name="visual_projection",
823
+ )
824
+ self.text_projection = keras.layers.Dense(
825
+ self.projection_dim,
826
+ use_bias=False,
827
+ kernel_initializer=get_initializer(config.initializer_range),
828
+ name="text_projection",
829
+ )
830
+
831
+ self.config = config
832
+
833
+ def build(self, input_shape=None):
834
+ self.logit_scale = self.add_weight(
835
+ name="logit_scale",
836
+ shape=[],
837
+ initializer=keras.initializers.Constant(self.config.logit_scale_init_value),
838
+ trainable=True,
839
+ )
840
+
841
+ if self.built:
842
+ return
843
+ self.built = True
844
+ if getattr(self, "text_model", None) is not None:
845
+ with tf.name_scope(self.text_model.name):
846
+ self.text_model.build(None)
847
+ if getattr(self, "vision_model", None) is not None:
848
+ with tf.name_scope(self.vision_model.name):
849
+ self.vision_model.build(None)
850
+ if getattr(self, "visual_projection", None) is not None:
851
+ with tf.name_scope(self.visual_projection.name):
852
+ self.visual_projection.build([None, None, self.vision_embed_dim])
853
+ if getattr(self, "text_projection", None) is not None:
854
+ with tf.name_scope(self.text_projection.name):
855
+ self.text_projection.build([None, None, self.text_embed_dim])
856
+
857
+ @unpack_inputs
858
+ def call(
859
+ self,
860
+ input_ids: tf.Tensor | None = None,
861
+ pixel_values: tf.Tensor | None = None,
862
+ attention_mask: tf.Tensor | None = None,
863
+ position_ids: tf.Tensor | None = None,
864
+ return_loss: bool | None = None,
865
+ output_attentions: bool | None = None,
866
+ output_hidden_states: bool | None = None,
867
+ return_dict: bool | None = None,
868
+ training: bool | None = None,
869
+ ) -> tuple | TFBlipOutput:
870
+ # Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
871
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
872
+ output_hidden_states = (
873
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
874
+ )
875
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
876
+
877
+ vision_outputs = self.vision_model(
878
+ pixel_values=pixel_values,
879
+ output_attentions=output_attentions,
880
+ output_hidden_states=output_hidden_states,
881
+ return_dict=return_dict,
882
+ training=training,
883
+ )
884
+
885
+ text_outputs = self.text_model(
886
+ input_ids=input_ids,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ output_attentions=output_attentions,
890
+ output_hidden_states=output_hidden_states,
891
+ return_dict=return_dict,
892
+ training=training,
893
+ )
894
+
895
+ image_embeds = vision_outputs[1]
896
+ image_embeds = self.visual_projection(image_embeds)
897
+
898
+ text_embeds = text_outputs[1]
899
+ text_embeds = self.text_projection(text_embeds)
900
+
901
+ # normalized features
902
+ image_embeds = image_embeds / tf.norm(image_embeds, ord=2, axis=-1, keepdims=True)
903
+ text_embeds = text_embeds / tf.norm(text_embeds, ord=2, axis=-1, keepdims=True)
904
+
905
+ # cosine similarity as logits
906
+ logit_scale = tf.exp(self.logit_scale)
907
+ logits_per_text = tf.matmul(text_embeds, image_embeds, transpose_b=True) * logit_scale
908
+ logits_per_image = tf.transpose(logits_per_text)
909
+
910
+ loss = None
911
+ if return_loss:
912
+ loss = blip_loss(logits_per_text)
913
+ loss = tf.reshape(loss, (1,))
914
+
915
+ if not return_dict:
916
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
917
+ return ((loss,) + output) if loss is not None else output
918
+
919
+ return TFBlipOutput(
920
+ loss=loss,
921
+ logits_per_image=logits_per_image,
922
+ logits_per_text=logits_per_text,
923
+ text_embeds=text_embeds,
924
+ image_embeds=image_embeds,
925
+ text_model_output=text_outputs,
926
+ vision_model_output=vision_outputs,
927
+ )
928
+
929
+
930
+ class TFBlipModel(TFBlipPreTrainedModel):
931
+ config_class = BlipConfig
932
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
933
+ main_input_name = "input_ids"
934
+
935
+ def __init__(self, config: BlipConfig, *inputs, **kwargs):
936
+ super().__init__(config, *inputs, **kwargs)
937
+
938
+ self.blip = TFBlipMainLayer(config, name="blip")
939
+
940
+ def serving_output(self, output: TFBlipOutput) -> TFBlipOutput:
941
+ return TFBlipOutput(
942
+ logits_per_image=output.logits_per_image,
943
+ logits_per_text=output.logits_per_text,
944
+ text_embeds=output.text_embeds,
945
+ image_embeds=output.image_embeds,
946
+ )
947
+
948
+ @unpack_inputs
949
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
950
+ @replace_return_docstrings(output_type=TFBlipOutput, config_class=BlipConfig)
951
+ def call(
952
+ self,
953
+ input_ids: tf.Tensor | None = None,
954
+ pixel_values: tf.Tensor | None = None,
955
+ attention_mask: tf.Tensor | None = None,
956
+ position_ids: tf.Tensor | None = None,
957
+ return_loss: bool | None = None,
958
+ output_attentions: bool | None = None,
959
+ output_hidden_states: bool | None = None,
960
+ return_dict: bool | None = None,
961
+ training: bool | None = None,
962
+ ) -> tuple | TFBlipOutput:
963
+ r"""
964
+ Returns:
965
+
966
+ Examples:
967
+
968
+ ```python
969
+ >>> from PIL import Image
970
+ >>> import requests
971
+ >>> from transformers import AutoProcessor, TFBlipModel
972
+
973
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
974
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
975
+
976
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
977
+ >>> image = Image.open(requests.get(url, stream=True).raw)
978
+
979
+ >>> inputs = processor(
980
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="tf", padding=True
981
+ ... )
982
+
983
+ >>> outputs = model(**inputs)
984
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
985
+ >>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities
986
+ ```"""
987
+ outputs = self.blip(
988
+ input_ids=input_ids,
989
+ pixel_values=pixel_values,
990
+ attention_mask=attention_mask,
991
+ position_ids=position_ids,
992
+ return_loss=return_loss,
993
+ output_attentions=output_attentions,
994
+ output_hidden_states=output_hidden_states,
995
+ return_dict=return_dict,
996
+ training=training,
997
+ )
998
+ return outputs
999
+
1000
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
1001
+ def get_text_features(
1002
+ self,
1003
+ input_ids: tf.Tensor | None = None,
1004
+ attention_mask: tf.Tensor | None = None,
1005
+ position_ids: tf.Tensor | None = None,
1006
+ return_dict: bool | None = None,
1007
+ ) -> tf.Tensor:
1008
+ r"""
1009
+ Returns:
1010
+ text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
1011
+ the projection layer to the pooled output of [`TFBlipTextModel`].
1012
+
1013
+ Examples:
1014
+
1015
+ ```python
1016
+ >>> from transformers import AutoProcessor, TFBlipModel
1017
+
1018
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
1019
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1020
+
1021
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
1022
+ >>> text_features = model.get_text_features(**inputs)
1023
+ ```"""
1024
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1025
+
1026
+ text_outputs = self.blip.text_model(
1027
+ input_ids=input_ids,
1028
+ attention_mask=attention_mask,
1029
+ position_ids=position_ids,
1030
+ return_dict=return_dict,
1031
+ )
1032
+
1033
+ pooled_output = text_outputs[1]
1034
+ text_features = self.blip.text_projection(pooled_output)
1035
+
1036
+ return text_features
1037
+
1038
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1039
+ def get_image_features(
1040
+ self,
1041
+ pixel_values: tf.Tensor | None = None,
1042
+ return_dict: bool | None = None,
1043
+ ) -> tf.Tensor:
1044
+ r"""
1045
+ Returns:
1046
+ image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
1047
+ the projection layer to the pooled output of [`TFBlipVisionModel`].
1048
+
1049
+ Examples:
1050
+
1051
+ ```python
1052
+ >>> from PIL import Image
1053
+ >>> import requests
1054
+ >>> from transformers import AutoProcessor, TFBlipModel
1055
+
1056
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
1057
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1058
+
1059
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1060
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1061
+
1062
+ >>> inputs = processor(images=image, return_tensors="tf")
1063
+
1064
+ >>> image_features = model.get_image_features(**inputs)
1065
+ ```"""
1066
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1067
+
1068
+ vision_outputs = self.blip.vision_model(pixel_values=pixel_values, return_dict=return_dict)
1069
+
1070
+ pooled_output = vision_outputs[1] # pooled_output
1071
+ image_features = self.blip.visual_projection(pooled_output)
1072
+
1073
+ return image_features
1074
+
1075
+ def build(self, input_shape=None):
1076
+ if self.built:
1077
+ return
1078
+ self.built = True
1079
+ if getattr(self, "blip", None) is not None:
1080
+ with tf.name_scope(self.blip.name):
1081
+ self.blip.build(None)
1082
+
1083
+
1084
+ @add_start_docstrings(
1085
+ """
1086
+ BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
1087
+ `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
1088
+ the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
1089
+ from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
1090
+ """,
1091
+ BLIP_START_DOCSTRING,
1092
+ )
1093
+ class TFBlipForConditionalGeneration(TFBlipPreTrainedModel):
1094
+ config_class = BlipConfig
1095
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
1096
+ main_input_name = "pixel_values"
1097
+
1098
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1099
+ super().__init__(config, *args, **kwargs)
1100
+
1101
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1102
+
1103
+ self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
1104
+
1105
+ self.decoder_input_ids = config.text_config.bos_token_id
1106
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1107
+
1108
+ def get_input_embeddings(self) -> keras.layers.Layer:
1109
+ return self.vision_model.embeddings.patch_embedding
1110
+
1111
+ @unpack_inputs
1112
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1113
+ @replace_return_docstrings(output_type=TFBlipForConditionalGenerationModelOutput, config_class=BlipConfig)
1114
+ def call(
1115
+ self,
1116
+ pixel_values: tf.Tensor,
1117
+ input_ids: tf.Tensor | None = None,
1118
+ attention_mask: tf.Tensor | None = None,
1119
+ output_attentions: bool | None = None,
1120
+ output_hidden_states: bool | None = None,
1121
+ labels: tf.Tensor | None = None,
1122
+ return_dict: bool | None = None,
1123
+ training: bool | None = None,
1124
+ ) -> tuple | TFBlipForConditionalGenerationModelOutput:
1125
+ r"""
1126
+ Returns:
1127
+
1128
+ Examples:
1129
+
1130
+ ```python
1131
+ >>> from PIL import Image
1132
+ >>> import requests
1133
+ >>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
1134
+
1135
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1136
+ >>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1137
+
1138
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1139
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1140
+ >>> text = "A picture of"
1141
+
1142
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1143
+
1144
+ >>> outputs = model(**inputs)
1145
+ ```"""
1146
+
1147
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1148
+ vision_outputs = self.vision_model(
1149
+ pixel_values=pixel_values,
1150
+ output_attentions=output_attentions,
1151
+ output_hidden_states=output_hidden_states,
1152
+ return_dict=return_dict,
1153
+ training=training,
1154
+ )
1155
+
1156
+ image_embeds = vision_outputs[0]
1157
+
1158
+ outputs = self.text_decoder(
1159
+ input_ids=input_ids,
1160
+ attention_mask=attention_mask,
1161
+ encoder_hidden_states=image_embeds,
1162
+ labels=labels,
1163
+ return_dict=False,
1164
+ training=training,
1165
+ )
1166
+
1167
+ if not return_dict:
1168
+ outputs = (outputs[0], outputs[1], image_embeds, vision_outputs[0]) + vision_outputs[2:]
1169
+ return tuple(output for output in outputs if output is not None)
1170
+
1171
+ if labels is not None:
1172
+ loss = outputs[0]
1173
+ logits = outputs[1]
1174
+ else:
1175
+ loss = None
1176
+ logits = outputs[0]
1177
+
1178
+ if loss is not None and loss.shape.rank == 0:
1179
+ loss = tf.reshape(loss, (1,))
1180
+
1181
+ return TFBlipForConditionalGenerationModelOutput(
1182
+ loss=loss,
1183
+ logits=logits,
1184
+ image_embeds=image_embeds,
1185
+ last_hidden_state=vision_outputs.last_hidden_state,
1186
+ hidden_states=vision_outputs.hidden_states,
1187
+ attentions=vision_outputs.attentions,
1188
+ )
1189
+
1190
+ def generate(
1191
+ self,
1192
+ pixel_values: tf.Tensor,
1193
+ input_ids: tf.Tensor | None = None,
1194
+ attention_mask: tf.Tensor | None = None,
1195
+ **generate_kwargs,
1196
+ ) -> tf.Tensor:
1197
+ r"""
1198
+ Overrides *generate* function to be able to use the model as a conditional generator
1199
+
1200
+ Parameters:
1201
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
1202
+ Input image to be processed
1203
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ The sequence used as a prompt for the generation.
1205
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1206
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1207
+
1208
+
1209
+ Examples:
1210
+ ```python
1211
+ >>> from PIL import Image
1212
+ >>> import requests
1213
+ >>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
1214
+
1215
+ >>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1216
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1217
+
1218
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1219
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1220
+
1221
+ >>> inputs = processor(images=image, return_tensors="tf")
1222
+
1223
+ >>> outputs = model.generate(**inputs)
1224
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1225
+ two cats sleeping on a couch
1226
+ ```
1227
+ """
1228
+
1229
+ batch_size = pixel_values.shape[0]
1230
+ vision_outputs = self.vision_model(pixel_values=pixel_values)
1231
+
1232
+ image_embeds = vision_outputs[0]
1233
+
1234
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
1235
+
1236
+ if isinstance(input_ids, list):
1237
+ input_ids = tf.convert_to_tensor(input_ids, dtype=tf.int32)
1238
+ elif input_ids is None:
1239
+ input_ids = tf.convert_to_tensor(
1240
+ [[self.decoder_input_ids, self.config.text_config.eos_token_id]], dtype=tf.int32
1241
+ )
1242
+
1243
+ input_ids = tf.tile(input_ids, (batch_size, 1))
1244
+
1245
+ # PyTorch: input_ids[:, 0] = self.config.text_config.bos_token_id
1246
+ input_ids = tf.concat(
1247
+ [tf.ones((batch_size, 1), dtype=tf.int32) * self.config.text_config.bos_token_id, input_ids[:, 1:]], axis=1
1248
+ )
1249
+ attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
1250
+
1251
+ outputs = self.text_decoder.generate(
1252
+ input_ids=input_ids[:, :-1],
1253
+ eos_token_id=self.config.text_config.sep_token_id,
1254
+ pad_token_id=self.config.text_config.pad_token_id,
1255
+ attention_mask=attention_mask,
1256
+ encoder_hidden_states=image_embeds,
1257
+ encoder_attention_mask=image_attention_mask,
1258
+ **generate_kwargs,
1259
+ )
1260
+
1261
+ return outputs
1262
+
1263
+ def build(self, input_shape=None):
1264
+ if self.built:
1265
+ return
1266
+ self.built = True
1267
+ if getattr(self, "vision_model", None) is not None:
1268
+ with tf.name_scope(self.vision_model.name):
1269
+ self.vision_model.build(None)
1270
+ if getattr(self, "text_decoder", None) is not None:
1271
+ with tf.name_scope(self.text_decoder.name):
1272
+ self.text_decoder.build(None)
1273
+
1274
+
1275
+ @add_start_docstrings(
1276
+ """
1277
+ BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
1278
+ decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
1279
+ with the encoding of the image, and the text decoder will output the answer to the question.
1280
+ """,
1281
+ BLIP_START_DOCSTRING,
1282
+ )
1283
+ class TFBlipForQuestionAnswering(TFBlipPreTrainedModel):
1284
+ config_class = BlipConfig
1285
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
1286
+
1287
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1288
+ super().__init__(config, *args, **kwargs)
1289
+
1290
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1291
+
1292
+ self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
1293
+
1294
+ self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
1295
+
1296
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1297
+ self.decoder_start_token_id = config.text_config.bos_token_id
1298
+
1299
+ def get_input_embeddings(self) -> keras.layers.Layer:
1300
+ return self.vision_model.embeddings.patch_embedding
1301
+
1302
+ # Adapted from transformers.models.t5.modeling_tf_t5.TFT5PreTrainedModel._shift_right
1303
+ def _shift_right(self, input_ids):
1304
+ decoder_start_token_id = self.decoder_start_token_id
1305
+ pad_token_id = self.decoder_pad_token_id
1306
+
1307
+ if decoder_start_token_id is None or pad_token_id is None:
1308
+ raise ValueError("decoder_start_token_id and pad_token_id must be defined!")
1309
+
1310
+ start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id)
1311
+ start_tokens = tf.cast(start_tokens, input_ids.dtype) # Ensure compatible dtypes for concatenation
1312
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
1313
+
1314
+ # replace possible -100 values in labels by `pad_token_id`
1315
+ shifted_input_ids = tf.where(
1316
+ shifted_input_ids == -100,
1317
+ tf.cast(tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids.dtype),
1318
+ shifted_input_ids,
1319
+ )
1320
+
1321
+ # "Verify that `labels` has only positive values and -100"
1322
+ tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=shifted_input_ids.dtype))
1323
+
1324
+ return shifted_input_ids
1325
+
1326
+ @unpack_inputs
1327
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1328
+ @replace_return_docstrings(output_type=TFBlipTextVisionModelOutput, config_class=BlipVisionConfig)
1329
+ def call(
1330
+ self,
1331
+ input_ids: tf.Tensor,
1332
+ pixel_values: tf.Tensor | None = None,
1333
+ decoder_input_ids: tf.Tensor | None = None,
1334
+ decoder_attention_mask: tf.Tensor | None = None,
1335
+ attention_mask: tf.Tensor | None = None,
1336
+ output_attentions: bool | None = None,
1337
+ output_hidden_states: bool | None = None,
1338
+ labels: tf.Tensor | None = None,
1339
+ return_dict: bool | None = None,
1340
+ training: bool | None = None,
1341
+ ) -> tuple | TFBlipTextVisionModelOutput:
1342
+ r"""
1343
+ Returns:
1344
+
1345
+ Examples:
1346
+
1347
+ ```python
1348
+ >>> from PIL import Image
1349
+ >>> import requests
1350
+ >>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
1351
+
1352
+ >>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1353
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1354
+
1355
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1356
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1357
+
1358
+ >>> # training
1359
+ >>> text = "How many cats are in the picture?"
1360
+ >>> label = "2"
1361
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1362
+ >>> labels = processor(text=label, return_tensors="tf").input_ids
1363
+
1364
+ >>> inputs["labels"] = labels
1365
+ >>> outputs = model(**inputs)
1366
+ >>> loss = outputs.loss
1367
+
1368
+ >>> # inference
1369
+ >>> text = "How many cats are in the picture?"
1370
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1371
+ >>> outputs = model.generate(**inputs)
1372
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1373
+ 2
1374
+ ```"""
1375
+ if labels is None and decoder_input_ids is None:
1376
+ raise ValueError(
1377
+ "Either `decoder_input_ids` or `labels` should be passed when calling"
1378
+ " `TFBlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
1379
+ " are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
1380
+ )
1381
+
1382
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1383
+
1384
+ vision_outputs = self.vision_model(
1385
+ pixel_values=pixel_values,
1386
+ output_attentions=output_attentions,
1387
+ output_hidden_states=output_hidden_states,
1388
+ return_dict=return_dict,
1389
+ training=training,
1390
+ )
1391
+
1392
+ image_embeds = vision_outputs[0]
1393
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
1394
+
1395
+ question_embeds = self.text_encoder(
1396
+ input_ids=input_ids,
1397
+ attention_mask=attention_mask,
1398
+ encoder_hidden_states=image_embeds,
1399
+ encoder_attention_mask=image_attention_mask,
1400
+ return_dict=return_dict,
1401
+ training=training,
1402
+ )
1403
+
1404
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1405
+
1406
+ if labels is not None and decoder_input_ids is None:
1407
+ # labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
1408
+ decoder_input_ids = labels
1409
+
1410
+ answer_output = self.text_decoder(
1411
+ input_ids=decoder_input_ids,
1412
+ attention_mask=decoder_attention_mask,
1413
+ encoder_hidden_states=question_embeds,
1414
+ encoder_attention_mask=attention_mask,
1415
+ labels=labels,
1416
+ return_dict=return_dict,
1417
+ training=training,
1418
+ )
1419
+
1420
+ if labels is not None:
1421
+ decoder_loss = tf.reduce_mean(answer_output.loss) if return_dict else tf.reduce_mean(answer_output[0])
1422
+ else:
1423
+ decoder_loss = None
1424
+
1425
+ if not return_dict:
1426
+ outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
1427
+ return tuple(output for output in outputs if output is not None)
1428
+
1429
+ return TFBlipTextVisionModelOutput(
1430
+ loss=decoder_loss,
1431
+ image_embeds=image_embeds,
1432
+ last_hidden_state=vision_outputs.last_hidden_state,
1433
+ hidden_states=vision_outputs.hidden_states,
1434
+ attentions=vision_outputs.attentions,
1435
+ )
1436
+
1437
+ def generate(
1438
+ self,
1439
+ input_ids: tf.Tensor,
1440
+ pixel_values: tf.Tensor,
1441
+ attention_mask: tf.Tensor | None = None,
1442
+ **generate_kwargs,
1443
+ ) -> tf.Tensor:
1444
+ r"""
1445
+ Overrides *generate* function to be able to use the model as a conditional generator
1446
+
1447
+ Parameters:
1448
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
1449
+ The sequence used as a prompt for the generation.
1450
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
1451
+ Input image to be processed
1452
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1453
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
1454
+ tokens that are NOT MASKED, `0` for MASKED tokens.
1455
+ generate_kwargs (dict, *optional*):
1456
+ Additional arguments passed to the `generate` function of the decoder
1457
+
1458
+
1459
+ Examples:
1460
+ ```python
1461
+ >>> from PIL import Image
1462
+ >>> import requests
1463
+ >>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
1464
+
1465
+ >>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1466
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1467
+
1468
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1469
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1470
+ >>> text = "How many cats are in the picture?"
1471
+
1472
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1473
+
1474
+ >>> outputs = model.generate(**inputs)
1475
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1476
+ 2
1477
+ ```
1478
+ """
1479
+ vision_outputs = self.vision_model(pixel_values=pixel_values)
1480
+
1481
+ image_embeds = vision_outputs[0]
1482
+
1483
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
1484
+
1485
+ if isinstance(input_ids, list):
1486
+ input_ids = tf.Tensor(input_ids)
1487
+
1488
+ question_outputs = self.text_encoder(
1489
+ input_ids=input_ids,
1490
+ attention_mask=attention_mask,
1491
+ encoder_hidden_states=image_embeds,
1492
+ encoder_attention_mask=image_attention_mask,
1493
+ return_dict=False,
1494
+ )
1495
+
1496
+ question_embeds = question_outputs[0]
1497
+
1498
+ question_attention_mask = tf.ones(shape_list(question_embeds)[:-1], dtype=tf.int32)
1499
+
1500
+ bos_ids = tf.fill(
1501
+ (tf.shape(question_embeds)[0], 1), value=tf.cast(self.decoder_start_token_id, input_ids.dtype)
1502
+ )
1503
+
1504
+ outputs = self.text_decoder.generate(
1505
+ input_ids=bos_ids,
1506
+ eos_token_id=self.config.text_config.sep_token_id,
1507
+ pad_token_id=self.config.text_config.pad_token_id,
1508
+ encoder_hidden_states=question_embeds,
1509
+ encoder_attention_mask=question_attention_mask,
1510
+ **generate_kwargs,
1511
+ )
1512
+
1513
+ return outputs
1514
+
1515
+ def build(self, input_shape=None):
1516
+ if self.built:
1517
+ return
1518
+ self.built = True
1519
+ if getattr(self, "vision_model", None) is not None:
1520
+ with tf.name_scope(self.vision_model.name):
1521
+ self.vision_model.build(None)
1522
+ if getattr(self, "text_encoder", None) is not None:
1523
+ with tf.name_scope(self.text_encoder.name):
1524
+ self.text_encoder.build(None)
1525
+ if getattr(self, "text_decoder", None) is not None:
1526
+ with tf.name_scope(self.text_decoder.name):
1527
+ self.text_decoder.build(None)
1528
+
1529
+
1530
+ @add_start_docstrings(
1531
+ """
1532
+ BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
1533
+ image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
1534
+ the image.
1535
+ """,
1536
+ BLIP_START_DOCSTRING,
1537
+ )
1538
+ class TFBlipForImageTextRetrieval(TFBlipPreTrainedModel):
1539
+ config_class = BlipConfig
1540
+
1541
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1542
+ super().__init__(config, *args, **kwargs)
1543
+
1544
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1545
+
1546
+ self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
1547
+
1548
+ # vision projection layer
1549
+ self.vision_proj = keras.layers.Dense(
1550
+ config.image_text_hidden_size,
1551
+ kernel_initializer=get_initializer(config.initializer_range),
1552
+ name="vision_proj",
1553
+ )
1554
+
1555
+ # text projection layer
1556
+ self.text_proj = keras.layers.Dense(
1557
+ config.image_text_hidden_size,
1558
+ kernel_initializer=get_initializer(config.initializer_range),
1559
+ name="text_proj",
1560
+ )
1561
+
1562
+ # image text matching head
1563
+ self.itm_head = keras.layers.Dense(
1564
+ 2, kernel_initializer=get_initializer(config.initializer_range), name="itm_head"
1565
+ )
1566
+
1567
+ self.decoder_pad_token_id = (
1568
+ config.text_config.pad_token_id
1569
+ if not hasattr(config, "decoder_pad_token_id")
1570
+ else config.decoder_pad_token_id
1571
+ )
1572
+ self.decoder_start_token_id = (
1573
+ config.text_config.bos_token_id
1574
+ if not hasattr(config, "decoder_start_token_id")
1575
+ else config.decoder_start_token_id
1576
+ )
1577
+ self.config = config
1578
+
1579
+ def get_input_embeddings(self) -> keras.layers.Layer:
1580
+ return self.vision_model.embeddings.patch_embedding
1581
+
1582
+ @unpack_inputs
1583
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1584
+ @replace_return_docstrings(output_type=TFBlipImageTextMatchingModelOutput, config_class=BlipVisionConfig)
1585
+ def call(
1586
+ self,
1587
+ input_ids: tf.Tensor,
1588
+ pixel_values: tf.Tensor | None = None,
1589
+ use_itm_head: bool | None = True,
1590
+ attention_mask: tf.Tensor | None = None,
1591
+ output_attentions: bool | None = None,
1592
+ output_hidden_states: bool | None = None,
1593
+ return_dict: bool | None = None,
1594
+ training: bool | None = None,
1595
+ ) -> tuple | TFBlipImageTextMatchingModelOutput:
1596
+ r"""
1597
+ Returns:
1598
+
1599
+ Examples:
1600
+
1601
+ ```python
1602
+ >>> from PIL import Image
1603
+ >>> import requests
1604
+ >>> from transformers import AutoProcessor, TFBlipForImageTextRetrieval
1605
+
1606
+ >>> model = TFBlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
1607
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1608
+
1609
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1610
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1611
+ >>> text = "an image of a cat"
1612
+
1613
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1614
+ >>> outputs = model(**inputs)
1615
+ ```
1616
+ """
1617
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1618
+
1619
+ vision_outputs = self.vision_model(
1620
+ pixel_values=pixel_values,
1621
+ output_attentions=output_attentions,
1622
+ output_hidden_states=output_hidden_states,
1623
+ return_dict=return_dict,
1624
+ training=training,
1625
+ )
1626
+
1627
+ image_embeds = vision_outputs[0]
1628
+ image_atts = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
1629
+
1630
+ # Matt: In PyTorch, only one path (itm/non-itm) is taken. However, in TensorFlow this can result in
1631
+ # some layers not being built! To avoid this, we always call both paths, then use an if statement to select
1632
+ # which output to pass to the final output. The unnecessary nodes will be pruned from the final graph, but
1633
+ # not before the layers have all been built correctly.
1634
+ itm_question_embeds = self.text_encoder(
1635
+ input_ids=input_ids,
1636
+ attention_mask=attention_mask,
1637
+ encoder_hidden_states=image_embeds,
1638
+ encoder_attention_mask=image_atts,
1639
+ return_dict=return_dict,
1640
+ training=training,
1641
+ )
1642
+ itm_question_embeds = itm_question_embeds[0] if not return_dict else itm_question_embeds.last_hidden_state
1643
+
1644
+ itm_output = self.itm_head(itm_question_embeds[:, 0, :])
1645
+
1646
+ no_itm_question_embeds = self.text_encoder(
1647
+ input_ids=input_ids,
1648
+ attention_mask=attention_mask,
1649
+ return_dict=return_dict,
1650
+ training=training,
1651
+ )
1652
+ no_itm_question_embeds = (
1653
+ no_itm_question_embeds[0] if not return_dict else no_itm_question_embeds.last_hidden_state
1654
+ )
1655
+
1656
+ image_feat, _ = tf.linalg.normalize(self.vision_proj(image_embeds[:, 0, :]), ord=2, axis=-1)
1657
+ text_feat, _ = tf.linalg.normalize(self.text_proj(no_itm_question_embeds[:, 0, :]), ord=2, axis=-1)
1658
+
1659
+ no_itm_output = tf.matmul(image_feat, text_feat, transpose_b=True)
1660
+
1661
+ if use_itm_head:
1662
+ output = itm_output
1663
+ question_embeds = itm_question_embeds
1664
+ else:
1665
+ output = no_itm_output
1666
+ question_embeds = no_itm_question_embeds
1667
+
1668
+ if not return_dict:
1669
+ outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
1670
+ return tuple(output for output in outputs if output is not None)
1671
+
1672
+ return TFBlipImageTextMatchingModelOutput(
1673
+ itm_score=output,
1674
+ last_hidden_state=vision_outputs.last_hidden_state,
1675
+ hidden_states=vision_outputs.hidden_states,
1676
+ attentions=vision_outputs.attentions,
1677
+ question_embeds=question_embeds,
1678
+ )
1679
+
1680
+ def build(self, input_shape=None):
1681
+ if self.built:
1682
+ return
1683
+ self.built = True
1684
+ if getattr(self, "vision_model", None) is not None:
1685
+ with tf.name_scope(self.vision_model.name):
1686
+ self.vision_model.build(None)
1687
+ if getattr(self, "text_encoder", None) is not None:
1688
+ with tf.name_scope(self.text_encoder.name):
1689
+ self.text_encoder.build(None)
1690
+ if getattr(self, "vision_proj", None) is not None:
1691
+ with tf.name_scope(self.vision_proj.name):
1692
+ self.vision_proj.build([None, None, self.config.vision_config.hidden_size])
1693
+ if getattr(self, "text_proj", None) is not None:
1694
+ with tf.name_scope(self.text_proj.name):
1695
+ self.text_proj.build([None, None, self.config.text_config.hidden_size])
1696
+ if getattr(self, "itm_head", None) is not None:
1697
+ with tf.name_scope(self.itm_head.name):
1698
+ self.itm_head.build([None, None, self.config.text_config.hidden_size])
1699
+
1700
+
1701
+ __all__ = [
1702
+ "TFBlipModel",
1703
+ "TFBlipPreTrainedModel",
1704
+ "TFBlipForConditionalGeneration",
1705
+ "TFBlipForQuestionAnswering",
1706
+ "TFBlipVisionModel",
1707
+ "TFBlipTextModel",
1708
+ "TFBlipForImageTextRetrieval",
1709
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip_text.py ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the BSD-3-clause license (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
+ # https://opensource.org/licenses/BSD-3-Clause
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
+
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+
21
+ import tensorflow as tf
22
+
23
+ from ...modeling_tf_outputs import (
24
+ TFBaseModelOutputWithPastAndCrossAttentions,
25
+ TFBaseModelOutputWithPoolingAndCrossAttentions,
26
+ TFCausalLMOutputWithCrossAttentions,
27
+ )
28
+ from ...modeling_tf_utils import (
29
+ TFModelInputType,
30
+ TFPreTrainedModel,
31
+ get_initializer,
32
+ get_tf_activation,
33
+ keras,
34
+ keras_serializable,
35
+ shape_list,
36
+ unpack_inputs,
37
+ )
38
+ from ...tf_utils import check_embeddings_within_bounds, invert_attention_mask, stable_softmax
39
+ from ...utils import add_start_docstrings_to_model_forward, logging
40
+ from .configuration_blip import BlipTextConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ BLIP_TEXT_INPUTS_DOCSTRING = r"""
46
+ Args:
47
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
48
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
49
+ it.
50
+
51
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
52
+
53
+ [What are input IDs?](../glossary#input-ids)
54
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
55
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
56
+
57
+ - 1 for tokens that are **not masked**,
58
+ - 0 for tokens that are **masked**.
59
+
60
+ [What are attention masks?](../glossary#attention-mask)
61
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
62
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
63
+ config.max_position_embeddings - 1]`.
64
+
65
+ [What are position IDs?](../glossary#position-ids)
66
+ output_attentions (`bool`, *optional*):
67
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
68
+ tensors for more detail.
69
+ output_hidden_states (`bool`, *optional*):
70
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
71
+ more detail.
72
+ return_dict (`bool`, *optional*):
73
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
74
+ """
75
+
76
+
77
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
78
+ class TFBlipTextEmbeddings(keras.layers.Layer):
79
+ """Construct the embeddings from word and position embeddings."""
80
+
81
+ def __init__(self, config, **kwargs):
82
+ super().__init__(**kwargs)
83
+ self.word_embeddings = keras.layers.Embedding(
84
+ config.vocab_size,
85
+ config.hidden_size,
86
+ embeddings_initializer=get_initializer(config.initializer_range),
87
+ name="word_embeddings",
88
+ )
89
+ self.position_embeddings = keras.layers.Embedding(
90
+ config.max_position_embeddings,
91
+ config.hidden_size,
92
+ embeddings_initializer=get_initializer(config.initializer_range),
93
+ name="position_embeddings",
94
+ )
95
+
96
+ # self.LayerNorm is not snake-cased to stick with PyTorch model variable name and be able to load
97
+ # any TensorFlow checkpoint file
98
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
99
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob, name="dropout")
100
+
101
+ self.position_ids = tf.expand_dims(tf.range(config.max_position_embeddings), 0)
102
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
103
+
104
+ self.config = config
105
+
106
+ def call(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0, training=None):
107
+ if input_ids is not None:
108
+ input_shape = tf.shape(input_ids)
109
+ else:
110
+ input_shape = tf.shape(inputs_embeds)[:-1]
111
+
112
+ seq_length = input_shape[1]
113
+
114
+ if position_ids is None:
115
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
116
+
117
+ if inputs_embeds is None:
118
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
119
+ inputs_embeds = self.word_embeddings(input_ids)
120
+
121
+ embeddings = inputs_embeds
122
+
123
+ if self.position_embedding_type == "absolute":
124
+ position_embeddings = self.position_embeddings(position_ids)
125
+ embeddings += position_embeddings
126
+ embeddings = self.LayerNorm(embeddings)
127
+ embeddings = self.dropout(embeddings, training=training)
128
+ return embeddings
129
+
130
+ def build(self, input_shape=None):
131
+ if self.built:
132
+ return
133
+ self.built = True
134
+ if getattr(self, "word_embeddings", None) is not None:
135
+ with tf.name_scope(self.word_embeddings.name):
136
+ self.word_embeddings.build(None)
137
+ if getattr(self, "position_embeddings", None) is not None:
138
+ with tf.name_scope(self.position_embeddings.name):
139
+ self.position_embeddings.build(None)
140
+ if getattr(self, "LayerNorm", None) is not None:
141
+ with tf.name_scope(self.LayerNorm.name):
142
+ self.LayerNorm.build([None, None, self.config.hidden_size])
143
+ if getattr(self, "dropout", None) is not None:
144
+ with tf.name_scope(self.dropout.name):
145
+ self.dropout.build(None)
146
+
147
+
148
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
149
+ class TFBlipTextSelfAttention(keras.layers.Layer):
150
+ def __init__(self, config, is_cross_attention, **kwargs):
151
+ super().__init__(**kwargs)
152
+ self.config = config
153
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
154
+ raise ValueError(
155
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
156
+ % (config.hidden_size, config.num_attention_heads)
157
+ )
158
+
159
+ self.num_attention_heads = config.num_attention_heads
160
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
161
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
162
+
163
+ self.query = keras.layers.Dense(
164
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
165
+ )
166
+ self.key = keras.layers.Dense(
167
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
168
+ )
169
+ self.value = keras.layers.Dense(
170
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
171
+ )
172
+
173
+ self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
174
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
175
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
176
+ self.max_position_embeddings = config.max_position_embeddings
177
+ self.distance_embedding = keras.layers.Embedding(
178
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
179
+ )
180
+ self.is_cross_attention = is_cross_attention
181
+
182
+ def transpose_for_scores(self, x):
183
+ new_x_shape = tf.concat(
184
+ [tf.shape(x)[:-1], tf.constant([self.num_attention_heads, self.attention_head_size], dtype=tf.int32)],
185
+ axis=0,
186
+ )
187
+ x = tf.reshape(x, new_x_shape)
188
+ return tf.transpose(x, perm=(0, 2, 1, 3))
189
+
190
+ def call(
191
+ self,
192
+ hidden_states,
193
+ attention_mask=None,
194
+ head_mask=None,
195
+ encoder_hidden_states=None,
196
+ encoder_attention_mask=None,
197
+ past_key_value=None,
198
+ output_attentions=False,
199
+ training=None,
200
+ ):
201
+ mixed_query_layer = self.query(hidden_states)
202
+
203
+ # If this is instantiated as a cross-attention module, the keys
204
+ # and values come from an encoder; the attention mask needs to be
205
+ # such that the encoder's padding tokens are not attended to.
206
+ is_cross_attention = encoder_hidden_states is not None
207
+
208
+ if is_cross_attention:
209
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
210
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
211
+ attention_mask = encoder_attention_mask
212
+ elif past_key_value is not None:
213
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
214
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
215
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
216
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
217
+ else:
218
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
219
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
220
+
221
+ query_layer = self.transpose_for_scores(mixed_query_layer)
222
+
223
+ past_key_value = (key_layer, value_layer)
224
+
225
+ # Take the dot product between "query" and "key" to get the raw attention scores.
226
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
227
+
228
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
229
+ seq_length = shape_list(hidden_states)[1]
230
+ position_ids_l = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 1)
231
+ position_ids_r = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 0)
232
+ distance = position_ids_l - position_ids_r
233
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
234
+ positional_embedding = tf.cast(positional_embedding, query_layer.dtype) # fp16 compatibility
235
+
236
+ if self.position_embedding_type == "relative_key":
237
+ relative_position_scores = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
238
+ attention_scores = attention_scores + relative_position_scores
239
+ elif self.position_embedding_type == "relative_key_query":
240
+ relative_position_scores_query = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
241
+ relative_position_scores_key = tf.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
242
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
243
+
244
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
245
+ if attention_mask is not None:
246
+ # Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
247
+ attention_scores = attention_scores + tf.cast(attention_mask, attention_scores.dtype)
248
+
249
+ # Normalize the attention scores to probabilities.
250
+ attention_probs = stable_softmax(attention_scores, axis=-1)
251
+
252
+ # This is actually dropping out entire tokens to attend to, which might
253
+ # seem a bit unusual, but is taken from the original Transformer paper.
254
+ attention_probs_dropped = self.dropout(attention_probs, training=training)
255
+
256
+ # Mask heads if we want to
257
+ if head_mask is not None:
258
+ attention_probs_dropped = attention_probs_dropped * head_mask
259
+
260
+ context_layer = attention_probs_dropped @ value_layer
261
+
262
+ context_layer = tf.transpose(context_layer, perm=(0, 2, 1, 3))
263
+ new_context_layer_shape = shape_list(context_layer)[:-2] + [self.all_head_size]
264
+ context_layer = tf.reshape(context_layer, new_context_layer_shape)
265
+
266
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
267
+
268
+ outputs = outputs + (past_key_value,)
269
+ return outputs
270
+
271
+ def build(self, input_shape=None):
272
+ if self.built:
273
+ return
274
+ self.built = True
275
+ if getattr(self, "query", None) is not None:
276
+ with tf.name_scope(self.query.name):
277
+ self.query.build([None, None, self.config.hidden_size])
278
+ if self.is_cross_attention:
279
+ if getattr(self, "key", None) is not None:
280
+ with tf.name_scope(self.key.name):
281
+ self.key.build([None, None, self.config.encoder_hidden_size])
282
+ if getattr(self, "value", None) is not None:
283
+ with tf.name_scope(self.value.name):
284
+ self.value.build([None, None, self.config.encoder_hidden_size])
285
+ else:
286
+ if getattr(self, "key", None) is not None:
287
+ with tf.name_scope(self.key.name):
288
+ self.key.build([None, None, self.config.hidden_size])
289
+ if getattr(self, "value", None) is not None:
290
+ with tf.name_scope(self.value.name):
291
+ self.value.build([None, None, self.config.hidden_size])
292
+
293
+
294
+ class TFBlipTextSelfOutput(keras.layers.Layer):
295
+ def __init__(self, config: BlipTextConfig, **kwargs):
296
+ super().__init__(**kwargs)
297
+
298
+ self.dense = keras.layers.Dense(
299
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
300
+ )
301
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
302
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
303
+ self.config = config
304
+
305
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool | None = None) -> tf.Tensor:
306
+ hidden_states = self.dense(inputs=hidden_states)
307
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
308
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
309
+
310
+ return hidden_states
311
+
312
+ def build(self, input_shape=None):
313
+ if self.built:
314
+ return
315
+ self.built = True
316
+ if getattr(self, "dense", None) is not None:
317
+ with tf.name_scope(self.dense.name):
318
+ self.dense.build([None, None, self.config.hidden_size])
319
+ if getattr(self, "LayerNorm", None) is not None:
320
+ with tf.name_scope(self.LayerNorm.name):
321
+ self.LayerNorm.build([None, None, self.config.hidden_size])
322
+
323
+
324
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
325
+ class TFBlipTextAttention(keras.layers.Layer):
326
+ def __init__(self, config, is_cross_attention=False, **kwargs):
327
+ super().__init__(**kwargs)
328
+ self.self = TFBlipTextSelfAttention(config, is_cross_attention, name="self")
329
+ # "output" is a protected attribute on TF models
330
+ self.self_output = TFBlipTextSelfOutput(config, name="output")
331
+
332
+ def call(
333
+ self,
334
+ hidden_states: tf.Tensor,
335
+ attention_mask: tf.Tensor | None = None,
336
+ head_mask: tf.Tensor | None = None,
337
+ encoder_hidden_states: tf.Tensor | None = None,
338
+ encoder_attention_mask: tf.Tensor | None = None,
339
+ past_key_value: tuple[tuple[tf.Tensor]] | None = None,
340
+ output_attentions: bool | None = False,
341
+ training: bool | None = None,
342
+ ):
343
+ self_outputs = self.self(
344
+ hidden_states,
345
+ attention_mask,
346
+ head_mask,
347
+ encoder_hidden_states,
348
+ encoder_attention_mask,
349
+ past_key_value,
350
+ output_attentions,
351
+ training=training,
352
+ )
353
+ attention_output = self.self_output(self_outputs[0], hidden_states, training=training)
354
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
355
+ return outputs
356
+
357
+ def build(self, input_shape=None):
358
+ if self.built:
359
+ return
360
+ self.built = True
361
+ if getattr(self, "self", None) is not None:
362
+ with tf.name_scope(self.self.name):
363
+ self.self.build(None)
364
+ if getattr(self, "self_output", None) is not None:
365
+ with tf.name_scope(self.self_output.name):
366
+ self.self_output.build(None)
367
+
368
+
369
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->BlipText
370
+ class TFBlipTextIntermediate(keras.layers.Layer):
371
+ def __init__(self, config: BlipTextConfig, **kwargs):
372
+ super().__init__(**kwargs)
373
+
374
+ self.dense = keras.layers.Dense(
375
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
376
+ )
377
+
378
+ if isinstance(config.hidden_act, str):
379
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
380
+ else:
381
+ self.intermediate_act_fn = config.hidden_act
382
+ self.config = config
383
+
384
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
385
+ hidden_states = self.dense(inputs=hidden_states)
386
+ hidden_states = self.intermediate_act_fn(hidden_states)
387
+
388
+ return hidden_states
389
+
390
+ def build(self, input_shape=None):
391
+ if self.built:
392
+ return
393
+ self.built = True
394
+ if getattr(self, "dense", None) is not None:
395
+ with tf.name_scope(self.dense.name):
396
+ self.dense.build([None, None, self.config.hidden_size])
397
+
398
+
399
+ class TFBlipTextOutput(keras.layers.Layer):
400
+ def __init__(self, config: BlipTextConfig, **kwargs):
401
+ super().__init__(**kwargs)
402
+
403
+ self.dense = keras.layers.Dense(
404
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
405
+ )
406
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
407
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
408
+ self.config = config
409
+
410
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
411
+ hidden_states = self.dense(inputs=hidden_states)
412
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
413
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
414
+
415
+ return hidden_states
416
+
417
+ def build(self, input_shape=None):
418
+ if self.built:
419
+ return
420
+ self.built = True
421
+ if getattr(self, "dense", None) is not None:
422
+ with tf.name_scope(self.dense.name):
423
+ self.dense.build([None, None, self.config.intermediate_size])
424
+ if getattr(self, "LayerNorm", None) is not None:
425
+ with tf.name_scope(self.LayerNorm.name):
426
+ self.LayerNorm.build([None, None, self.config.hidden_size])
427
+
428
+
429
+ class TFBlipTextLayer(keras.layers.Layer):
430
+ def __init__(self, config, **kwargs):
431
+ super().__init__(**kwargs)
432
+ self.config = config
433
+ self.attention = TFBlipTextAttention(config, name="attention")
434
+ if self.config.is_decoder:
435
+ self.crossattention = TFBlipTextAttention(
436
+ config, is_cross_attention=self.config.is_decoder, name="crossattention"
437
+ )
438
+ self.intermediate = TFBlipTextIntermediate(config, name="intermediate")
439
+ self.self_output = TFBlipTextOutput(config, name="output")
440
+
441
+ def call(
442
+ self,
443
+ hidden_states,
444
+ attention_mask=None,
445
+ head_mask=None,
446
+ encoder_hidden_states=None,
447
+ encoder_attention_mask=None,
448
+ past_key_value=None,
449
+ output_attentions=False,
450
+ training=None,
451
+ ):
452
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
453
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
454
+ self_attention_outputs = self.attention(
455
+ hidden_states,
456
+ attention_mask,
457
+ head_mask,
458
+ output_attentions=output_attentions,
459
+ past_key_value=self_attn_past_key_value,
460
+ training=training,
461
+ )
462
+ attention_output = self_attention_outputs[0]
463
+
464
+ outputs = self_attention_outputs[1:-1]
465
+ present_key_value = self_attention_outputs[-1]
466
+
467
+ if encoder_hidden_states is not None:
468
+ cross_attention_outputs = self.crossattention(
469
+ attention_output,
470
+ attention_mask,
471
+ head_mask,
472
+ encoder_hidden_states,
473
+ encoder_attention_mask,
474
+ output_attentions=output_attentions,
475
+ training=training,
476
+ )
477
+ attention_output = cross_attention_outputs[0]
478
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
479
+ intermediate_output = self.intermediate(attention_output)
480
+ layer_output = self.self_output(intermediate_output, attention_output, training=training)
481
+ outputs = (layer_output,) + outputs
482
+
483
+ outputs = outputs + (present_key_value,)
484
+
485
+ return outputs
486
+
487
+ def build(self, input_shape=None):
488
+ if self.built:
489
+ return
490
+ self.built = True
491
+ if getattr(self, "attention", None) is not None:
492
+ with tf.name_scope(self.attention.name):
493
+ self.attention.build(None)
494
+ if getattr(self, "intermediate", None) is not None:
495
+ with tf.name_scope(self.intermediate.name):
496
+ self.intermediate.build(None)
497
+ if getattr(self, "self_output", None) is not None:
498
+ with tf.name_scope(self.self_output.name):
499
+ self.self_output.build(None)
500
+ if getattr(self, "crossattention", None) is not None:
501
+ with tf.name_scope(self.crossattention.name):
502
+ self.crossattention.build(None)
503
+
504
+
505
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
506
+ @keras_serializable
507
+ class TFBlipTextEncoder(keras.layers.Layer):
508
+ config_class = BlipTextConfig
509
+
510
+ def __init__(self, config, name=None, **kwargs):
511
+ super().__init__(name=name, **kwargs)
512
+ self.config = config
513
+ self.layer = [TFBlipTextLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
514
+
515
+ @unpack_inputs
516
+ def call(
517
+ self,
518
+ hidden_states,
519
+ attention_mask=None,
520
+ head_mask=None,
521
+ encoder_hidden_states=None,
522
+ encoder_attention_mask=None,
523
+ past_key_values=None,
524
+ use_cache=None,
525
+ output_attentions=False,
526
+ output_hidden_states=False,
527
+ return_dict=True,
528
+ training=None,
529
+ ):
530
+ all_hidden_states = () if output_hidden_states else None
531
+ all_self_attentions = () if output_attentions else None
532
+ all_cross_attentions = () if output_attentions and self.config.is_decoder else None
533
+
534
+ next_decoder_cache = () if use_cache else None
535
+
536
+ for i in range(self.config.num_hidden_layers):
537
+ layer_module = self.layer[i]
538
+ if output_hidden_states:
539
+ all_hidden_states = all_hidden_states + (hidden_states,)
540
+
541
+ layer_head_mask = head_mask[i] if head_mask is not None else None
542
+ past_key_value = past_key_values[i] if past_key_values is not None else None
543
+
544
+ layer_outputs = layer_module(
545
+ hidden_states,
546
+ attention_mask,
547
+ layer_head_mask,
548
+ encoder_hidden_states,
549
+ encoder_attention_mask,
550
+ past_key_value,
551
+ output_attentions,
552
+ training=training,
553
+ )
554
+
555
+ hidden_states = layer_outputs[0]
556
+ if use_cache:
557
+ next_decoder_cache += (layer_outputs[-1],)
558
+ if output_attentions:
559
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
560
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
561
+
562
+ if output_hidden_states:
563
+ all_hidden_states = all_hidden_states + (hidden_states,)
564
+
565
+ if not return_dict:
566
+ return tuple(
567
+ v
568
+ for v in [
569
+ hidden_states,
570
+ next_decoder_cache,
571
+ all_hidden_states,
572
+ all_self_attentions,
573
+ all_cross_attentions,
574
+ ]
575
+ if v is not None
576
+ )
577
+ return TFBaseModelOutputWithPastAndCrossAttentions(
578
+ last_hidden_state=hidden_states,
579
+ past_key_values=next_decoder_cache,
580
+ hidden_states=all_hidden_states,
581
+ attentions=all_self_attentions,
582
+ cross_attentions=all_cross_attentions,
583
+ )
584
+
585
+ def build(self, input_shape=None):
586
+ if self.built:
587
+ return
588
+ self.built = True
589
+ if getattr(self, "layer", None) is not None:
590
+ for layer in self.layer:
591
+ with tf.name_scope(layer.name):
592
+ layer.build(None)
593
+
594
+
595
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->BlipText
596
+ class TFBlipTextPooler(keras.layers.Layer):
597
+ def __init__(self, config: BlipTextConfig, **kwargs):
598
+ super().__init__(**kwargs)
599
+
600
+ self.dense = keras.layers.Dense(
601
+ units=config.hidden_size,
602
+ kernel_initializer=get_initializer(config.initializer_range),
603
+ activation="tanh",
604
+ name="dense",
605
+ )
606
+ self.config = config
607
+
608
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
609
+ # We "pool" the model by simply taking the hidden state corresponding
610
+ # to the first token.
611
+ first_token_tensor = hidden_states[:, 0]
612
+ pooled_output = self.dense(inputs=first_token_tensor)
613
+
614
+ return pooled_output
615
+
616
+ def build(self, input_shape=None):
617
+ if self.built:
618
+ return
619
+ self.built = True
620
+ if getattr(self, "dense", None) is not None:
621
+ with tf.name_scope(self.dense.name):
622
+ self.dense.build([None, None, self.config.hidden_size])
623
+
624
+
625
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPredictionHeadTransform with Bert->BlipText
626
+ class TFBlipTextPredictionHeadTransform(keras.layers.Layer):
627
+ def __init__(self, config: BlipTextConfig, **kwargs):
628
+ super().__init__(**kwargs)
629
+
630
+ self.dense = keras.layers.Dense(
631
+ units=config.hidden_size,
632
+ kernel_initializer=get_initializer(config.initializer_range),
633
+ name="dense",
634
+ )
635
+
636
+ if isinstance(config.hidden_act, str):
637
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
638
+ else:
639
+ self.transform_act_fn = config.hidden_act
640
+
641
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
642
+ self.config = config
643
+
644
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
645
+ hidden_states = self.dense(inputs=hidden_states)
646
+ hidden_states = self.transform_act_fn(hidden_states)
647
+ hidden_states = self.LayerNorm(inputs=hidden_states)
648
+
649
+ return hidden_states
650
+
651
+ def build(self, input_shape=None):
652
+ if self.built:
653
+ return
654
+ self.built = True
655
+ if getattr(self, "dense", None) is not None:
656
+ with tf.name_scope(self.dense.name):
657
+ self.dense.build([None, None, self.config.hidden_size])
658
+ if getattr(self, "LayerNorm", None) is not None:
659
+ with tf.name_scope(self.LayerNorm.name):
660
+ self.LayerNorm.build([None, None, self.config.hidden_size])
661
+
662
+
663
+ class TFBlipTextLMPredictionHead(keras.layers.Layer):
664
+ def __init__(self, config, **kwargs):
665
+ super().__init__(**kwargs)
666
+ self.transform = TFBlipTextPredictionHeadTransform(config, name="transform")
667
+
668
+ # The output weights are the same as the input embeddings, but there is
669
+ # an output-only bias for each token.
670
+ self.decoder = keras.layers.Dense(
671
+ config.vocab_size,
672
+ kernel_initializer=get_initializer(config.initializer_range),
673
+ name="decoder",
674
+ use_bias=False,
675
+ )
676
+ self.config = config
677
+
678
+ def build(self, input_shape=None):
679
+ self.bias = self.add_weight(name="bias", shape=(self.config.vocab_size,), initializer="zeros", trainable=True)
680
+
681
+ if self.built:
682
+ return
683
+ self.built = True
684
+ if getattr(self, "transform", None) is not None:
685
+ with tf.name_scope(self.transform.name):
686
+ self.transform.build(None)
687
+ if getattr(self, "decoder", None) is not None:
688
+ with tf.name_scope(self.decoder.name):
689
+ self.decoder.build([None, None, self.config.hidden_size])
690
+
691
+ def call(self, hidden_states):
692
+ hidden_states = self.transform(hidden_states)
693
+ hidden_states = self.decoder(hidden_states) + self.bias
694
+ return hidden_states
695
+
696
+
697
+ class TFBlipTextOnlyMLMHead(keras.layers.Layer):
698
+ def __init__(self, config, **kwargs):
699
+ super().__init__(**kwargs)
700
+ self.predictions = TFBlipTextLMPredictionHead(config, name="predictions")
701
+
702
+ def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
703
+ prediction_scores = self.predictions(sequence_output)
704
+ return prediction_scores
705
+
706
+ def build(self, input_shape=None):
707
+ if self.built:
708
+ return
709
+ self.built = True
710
+ if getattr(self, "predictions", None) is not None:
711
+ with tf.name_scope(self.predictions.name):
712
+ self.predictions.build(None)
713
+
714
+
715
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
716
+ class TFBlipTextPreTrainedModel(TFPreTrainedModel):
717
+ """
718
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
719
+ models.
720
+ """
721
+
722
+ config_class = BlipTextConfig
723
+ base_model_prefix = "bert"
724
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
725
+
726
+
727
+ # Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
728
+ class TFBlipTextModel(TFBlipTextPreTrainedModel):
729
+ """
730
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
731
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
732
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
733
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
734
+ `encoder_hidden_states` is then expected as an input to the forward pass.
735
+ """
736
+
737
+ def __init__(self, config, add_pooling_layer=True, name=None, **kwargs):
738
+ super().__init__(config, name=name, **kwargs)
739
+ self.config = config
740
+
741
+ self.embeddings = TFBlipTextEmbeddings(config, name="embeddings")
742
+ self.encoder = TFBlipTextEncoder(config, name="encoder")
743
+ self.pooler = TFBlipTextPooler(config, name="pooler") if add_pooling_layer else None
744
+
745
+ def get_input_embeddings(self):
746
+ return self.embeddings.word_embeddings
747
+
748
+ def set_input_embeddings(self, value):
749
+ self.embeddings.word_embeddings = value
750
+
751
+ @tf.function
752
+ def get_extended_attention_mask(
753
+ self, attention_mask: tf.Tensor, input_shape: tuple[int], is_decoder: bool
754
+ ) -> tf.Tensor:
755
+ """
756
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
757
+
758
+ Arguments:
759
+ attention_mask (`tf.Tensor`):
760
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
761
+ input_shape (`tuple[int]`):
762
+ The shape of the input to the model.
763
+ is_decoder (`bool`):
764
+ Whether the model is used as a decoder.
765
+
766
+ Returns:
767
+ `tf.Tensor` The extended attention mask, with the same dtype as `attention_mask.dtype`.
768
+ """
769
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
770
+ # ourselves in which case we just need to make it broadcastable to all heads.
771
+ if not isinstance(attention_mask, tf.Tensor):
772
+ attention_mask = tf.convert_to_tensor(attention_mask) # Catches NumPy inputs that haven't been cast yet
773
+ if attention_mask.shape.rank == 3:
774
+ extended_attention_mask = attention_mask[:, None, :, :]
775
+ elif attention_mask.shape.rank == 2:
776
+ # Provided a padding mask of dimensions [batch_size, seq_length]
777
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
778
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
779
+ if is_decoder:
780
+ batch_size, seq_length = input_shape
781
+
782
+ seq_ids = tf.range(seq_length, dtype=attention_mask.dtype)
783
+ causal_mask = tf.broadcast_to(seq_ids, (batch_size, seq_length, seq_length)) <= seq_ids[None, :, None]
784
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
785
+
786
+ if shape_list(causal_mask)[1] < shape_list(attention_mask)[1]:
787
+ prefix_seq_len = tf.shape(attention_mask)[1] - tf.shape(causal_mask)[1]
788
+ causal_mask = tf.concat(
789
+ [
790
+ tf.ones((batch_size, seq_length, prefix_seq_len), dtype=causal_mask.dtype),
791
+ causal_mask,
792
+ ],
793
+ axis=-1,
794
+ )
795
+ extended_attention_mask = (
796
+ tf.cast(causal_mask[:, None, :, :], attention_mask.dtype) * attention_mask[:, None, None, :]
797
+ )
798
+ else:
799
+ extended_attention_mask = attention_mask[:, None, None, :]
800
+ else:
801
+ raise ValueError(
802
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
803
+ )
804
+
805
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
806
+ # masked positions, this operation will create a tensor which is 0.0 for
807
+ # positions we want to attend and -10000.0 for masked positions.
808
+ # Since we are adding it to the raw scores before the softmax, this is
809
+ # effectively the same as removing these entirely.
810
+ extended_attention_mask = tf.cast(extended_attention_mask, self.dtype) # fp16 compatibility
811
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
812
+ return extended_attention_mask
813
+
814
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
815
+ @unpack_inputs
816
+ def call(
817
+ self,
818
+ input_ids: TFModelInputType | None = None,
819
+ attention_mask: tf.Tensor | None = None,
820
+ position_ids: tf.Tensor | None = None,
821
+ head_mask: tf.Tensor | None = None,
822
+ inputs_embeds: tf.Tensor | None = None,
823
+ encoder_embeds: tf.Tensor | None = None,
824
+ encoder_hidden_states: tf.Tensor | None = None,
825
+ encoder_attention_mask: tf.Tensor | None = None,
826
+ past_key_values: tuple[tuple[tf.Tensor]] | None = None,
827
+ use_cache: bool | None = None,
828
+ output_attentions: bool | None = None,
829
+ output_hidden_states: bool | None = None,
830
+ return_dict: bool | None = None,
831
+ is_decoder: bool = False,
832
+ training: bool = False,
833
+ ) -> tuple[tf.Tensor] | TFBaseModelOutputWithPoolingAndCrossAttentions:
834
+ r"""
835
+ encoder_hidden_states (`tf.Tensor`, *optional*):
836
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
837
+ the model is configured as a decoder.
838
+ encoder_attention_mask (`tf.Tensor`, *optional*):
839
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
840
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
841
+ - 1 for tokens that are **not masked**,
842
+ - 0 for tokens that are **masked**.
843
+ past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
844
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
845
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
846
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
847
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
848
+ use_cache (`bool`, *optional*):
849
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
850
+ `past_key_values`).
851
+ """
852
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
853
+ output_hidden_states = (
854
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
855
+ )
856
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
857
+
858
+ if is_decoder:
859
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
860
+ else:
861
+ use_cache = False
862
+
863
+ if input_ids is not None and inputs_embeds is not None:
864
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
865
+ elif input_ids is not None:
866
+ input_shape = shape_list(input_ids)
867
+ batch_size, seq_length = input_shape
868
+ elif inputs_embeds is not None:
869
+ input_shape = shape_list(inputs_embeds)[:-1]
870
+ batch_size, seq_length = input_shape
871
+ elif encoder_embeds is not None:
872
+ input_shape = shape_list(encoder_embeds)[:-1]
873
+ batch_size, seq_length = input_shape
874
+ else:
875
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
876
+
877
+ # past_key_values_length
878
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
879
+
880
+ if attention_mask is None:
881
+ attention_mask = tf.ones((batch_size, seq_length + past_key_values_length))
882
+
883
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
884
+ # ourselves in which case we just need to make it broadcastable to all heads.
885
+ extended_attention_mask: tf.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, is_decoder)
886
+
887
+ # If a 2D or 3D attention mask is provided for the cross-attention
888
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
889
+ if encoder_hidden_states is not None:
890
+ if isinstance(encoder_hidden_states, list):
891
+ encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states[0])
892
+ else:
893
+ encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states)
894
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
895
+
896
+ if isinstance(encoder_attention_mask, list):
897
+ encoder_extended_attention_mask = [invert_attention_mask(mask) for mask in encoder_attention_mask]
898
+ elif encoder_attention_mask is None:
899
+ encoder_attention_mask = tf.ones(encoder_hidden_shape)
900
+ encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
901
+ else:
902
+ encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
903
+ else:
904
+ encoder_extended_attention_mask = None
905
+
906
+ # Prepare head mask if needed
907
+ # 1.0 in head_mask indicate we keep the head
908
+ # attention_probs has shape bsz x n_heads x N x N
909
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
910
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
911
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
912
+
913
+ if encoder_embeds is None:
914
+ embedding_output = self.embeddings(
915
+ input_ids=input_ids,
916
+ position_ids=position_ids,
917
+ inputs_embeds=inputs_embeds,
918
+ past_key_values_length=past_key_values_length,
919
+ )
920
+ else:
921
+ embedding_output = encoder_embeds
922
+
923
+ encoder_outputs = self.encoder(
924
+ embedding_output,
925
+ attention_mask=extended_attention_mask,
926
+ head_mask=head_mask,
927
+ encoder_hidden_states=encoder_hidden_states,
928
+ encoder_attention_mask=encoder_extended_attention_mask,
929
+ past_key_values=past_key_values,
930
+ use_cache=use_cache,
931
+ output_attentions=output_attentions,
932
+ output_hidden_states=output_hidden_states,
933
+ return_dict=return_dict,
934
+ training=training,
935
+ )
936
+ sequence_output = encoder_outputs[0]
937
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
938
+
939
+ if not return_dict:
940
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
941
+
942
+ return TFBaseModelOutputWithPoolingAndCrossAttentions(
943
+ last_hidden_state=sequence_output,
944
+ pooler_output=pooled_output,
945
+ past_key_values=encoder_outputs.past_key_values,
946
+ hidden_states=encoder_outputs.hidden_states,
947
+ attentions=encoder_outputs.attentions,
948
+ cross_attentions=encoder_outputs.cross_attentions,
949
+ )
950
+
951
+ def build(self, input_shape=None):
952
+ if self.built:
953
+ return
954
+ self.built = True
955
+ if getattr(self, "embeddings", None) is not None:
956
+ with tf.name_scope(self.embeddings.name):
957
+ self.embeddings.build(None)
958
+ if getattr(self, "encoder", None) is not None:
959
+ with tf.name_scope(self.encoder.name):
960
+ self.encoder.build(None)
961
+ if getattr(self, "pooler", None) is not None:
962
+ with tf.name_scope(self.pooler.name):
963
+ self.pooler.build(None)
964
+
965
+
966
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
967
+ class TFBlipTextLMHeadModel(TFBlipTextPreTrainedModel):
968
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
969
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
970
+
971
+ def __init__(self, config, **kwargs):
972
+ super().__init__(config, **kwargs)
973
+
974
+ self.bert = TFBlipTextModel(config, add_pooling_layer=False, name="bert")
975
+ self.cls = TFBlipTextOnlyMLMHead(config, name="cls")
976
+ self.label_smoothing = config.label_smoothing
977
+
978
+ def get_output_embeddings(self):
979
+ return self.cls.predictions.decoder
980
+
981
+ def set_output_embeddings(self, new_embeddings):
982
+ self.cls.predictions.decoder = new_embeddings
983
+
984
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
985
+ @unpack_inputs
986
+ def call(
987
+ self,
988
+ input_ids=None,
989
+ attention_mask=None,
990
+ position_ids=None,
991
+ head_mask=None,
992
+ inputs_embeds=None,
993
+ encoder_hidden_states=None,
994
+ encoder_attention_mask=None,
995
+ labels=None,
996
+ past_key_values=None,
997
+ use_cache=None,
998
+ output_attentions=None,
999
+ output_hidden_states=None,
1000
+ return_dict=None,
1001
+ return_logits=False,
1002
+ is_decoder=True,
1003
+ training=None,
1004
+ ):
1005
+ r"""
1006
+ encoder_hidden_states (`tf.Tensor`, *optional*): Sequence of
1007
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
1008
+ configured as a decoder.
1009
+ encoder_attention_mask (`tf.Tensor`, *optional*):
1010
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1011
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1012
+ - 1 for tokens that are **not masked**,
1013
+ - 0 for tokens that are **masked**.
1014
+ labels (`tf.Tensor`, *optional*):
1015
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1016
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1017
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1018
+ past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
1019
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1020
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1021
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1022
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1023
+ use_cache (`bool`, *optional*):
1024
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1025
+ `past_key_values`).
1026
+ """
1027
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1028
+ if labels is not None:
1029
+ use_cache = False
1030
+
1031
+ outputs = self.bert(
1032
+ input_ids,
1033
+ attention_mask=attention_mask,
1034
+ position_ids=position_ids,
1035
+ head_mask=head_mask,
1036
+ inputs_embeds=inputs_embeds,
1037
+ encoder_hidden_states=encoder_hidden_states,
1038
+ encoder_attention_mask=encoder_attention_mask,
1039
+ past_key_values=past_key_values,
1040
+ use_cache=use_cache,
1041
+ output_attentions=output_attentions,
1042
+ output_hidden_states=output_hidden_states,
1043
+ return_dict=return_dict,
1044
+ is_decoder=is_decoder,
1045
+ training=training,
1046
+ )
1047
+
1048
+ sequence_output = outputs[0]
1049
+ prediction_scores = self.cls(sequence_output)
1050
+
1051
+ if return_logits:
1052
+ return prediction_scores[:, :-1, :]
1053
+
1054
+ lm_loss = None
1055
+ if labels is not None:
1056
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1057
+ shifted_prediction_scores = prediction_scores[:, :-1, :]
1058
+ shifted_prediction_scores = tf.reshape(shifted_prediction_scores, (-1, self.config.vocab_size))
1059
+ labels = labels[:, 1:]
1060
+ labels = tf.reshape(labels, (-1,))
1061
+ # Keras won't give us label smoothing for sparse CE, so we de-sparsify things here
1062
+ # Use relu to clamp masked labels at 0 to avoid NaN (we will be zeroing those out later anyway)
1063
+ one_hot_labels = tf.one_hot(tf.nn.relu(labels), depth=self.config.vocab_size, dtype=tf.float32)
1064
+ loss_fct = keras.losses.CategoricalCrossentropy(
1065
+ from_logits=True, label_smoothing=self.label_smoothing, reduction="none"
1066
+ )
1067
+ masked_positions = tf.cast(tf.not_equal(labels, -100), dtype=tf.float32)
1068
+ lm_loss = loss_fct(one_hot_labels, shifted_prediction_scores)
1069
+ lm_loss *= masked_positions
1070
+ lm_loss = tf.reduce_sum(lm_loss, axis=0) / tf.math.count_nonzero(masked_positions, dtype=tf.float32)
1071
+
1072
+ if not return_dict:
1073
+ output = (prediction_scores,) + outputs[2:]
1074
+ return ((lm_loss,) + output) if lm_loss is not None else output
1075
+
1076
+ return TFCausalLMOutputWithCrossAttentions(
1077
+ loss=lm_loss,
1078
+ logits=prediction_scores,
1079
+ past_key_values=outputs.past_key_values,
1080
+ hidden_states=outputs.hidden_states,
1081
+ attentions=outputs.attentions,
1082
+ cross_attentions=outputs.cross_attentions,
1083
+ )
1084
+
1085
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1086
+ input_shape = input_ids.shape
1087
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1088
+ if attention_mask is None:
1089
+ attention_mask = input_ids.new_ones(input_shape)
1090
+
1091
+ # cut decoder_input_ids if past_key_values is used
1092
+ if past_key_values is not None:
1093
+ input_ids = input_ids[:, -1:]
1094
+
1095
+ return {
1096
+ "input_ids": input_ids,
1097
+ "attention_mask": attention_mask,
1098
+ "past_key_values": past_key_values,
1099
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states"),
1100
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask"),
1101
+ "is_decoder": True,
1102
+ }
1103
+
1104
+ def _reorder_cache(self, past_key_values, beam_idx):
1105
+ reordered_past = ()
1106
+ for layer_past in past_key_values:
1107
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1108
+ return reordered_past
1109
+
1110
+ def build(self, input_shape=None):
1111
+ if self.built:
1112
+ return
1113
+ self.built = True
1114
+ if getattr(self, "bert", None) is not None:
1115
+ with tf.name_scope(self.bert.name):
1116
+ self.bert.build(None)
1117
+ if getattr(self, "cls", None) is not None:
1118
+ with tf.name_scope(self.cls.name):
1119
+ self.cls.build(None)
1120
+
1121
+
1122
+ __all__ = ["TFBlipTextLMHeadModel", "TFBlipTextModel", "TFBlipTextPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/blip/processing_blip.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """
16
+ Processor class for Blip.
17
+ """
18
+
19
+ from typing import Optional, Union
20
+
21
+ from ...image_utils import ImageInput
22
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
23
+ from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
24
+
25
+
26
+ class BlipProcessorKwargs(ProcessingKwargs, total=False):
27
+ _defaults = {
28
+ "text_kwargs": {
29
+ "add_special_tokens": True,
30
+ "padding": False,
31
+ "stride": 0,
32
+ "return_overflowing_tokens": False,
33
+ "return_special_tokens_mask": False,
34
+ "return_offsets_mapping": False,
35
+ "return_token_type_ids": False,
36
+ "return_length": False,
37
+ "verbose": True,
38
+ },
39
+ "images_kwargs": {},
40
+ }
41
+
42
+
43
+ class BlipProcessor(ProcessorMixin):
44
+ r"""
45
+ Constructs a BLIP processor which wraps a BERT tokenizer and BLIP image processor into a single processor.
46
+
47
+ [`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`BertTokenizerFast`]. See the
48
+ docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
49
+
50
+ Args:
51
+ image_processor (`BlipImageProcessor`):
52
+ An instance of [`BlipImageProcessor`]. The image processor is a required input.
53
+ tokenizer (`BertTokenizerFast`):
54
+ An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
55
+ """
56
+
57
+ attributes = ["image_processor", "tokenizer"]
58
+ image_processor_class = ("BlipImageProcessor", "BlipImageProcessorFast")
59
+ tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
60
+
61
+ def __init__(self, image_processor, tokenizer, **kwargs):
62
+ tokenizer.return_token_type_ids = False
63
+ super().__init__(image_processor, tokenizer)
64
+ self.current_processor = self.image_processor
65
+
66
+ def __call__(
67
+ self,
68
+ images: Optional[ImageInput] = None,
69
+ text: Optional[Union[str, list[str], TextInput, PreTokenizedInput]] = None,
70
+ audio=None,
71
+ videos=None,
72
+ **kwargs: Unpack[BlipProcessorKwargs],
73
+ ) -> BatchEncoding:
74
+ """
75
+ This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
76
+ [`BertTokenizerFast.__call__`] to prepare text for the model.
77
+
78
+ Please refer to the docstring of the above two methods for more information.
79
+ Args:
80
+ images (`ImageInput`):
81
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
82
+ tensor. Both channels-first and channels-last formats are supported.
83
+ text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`):
84
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
85
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
86
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
87
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
88
+ If set, will return tensors of a particular framework. Acceptable values are:
89
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
90
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
91
+ - `'np'`: Return NumPy `np.ndarray` objects.
92
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
93
+ """
94
+ if images is None and text is None:
95
+ raise ValueError("You have to specify either images or text.")
96
+
97
+ text_encoding = None
98
+
99
+ # add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
100
+ # else, return the text encoding.
101
+ output_kwargs = self._merge_kwargs(
102
+ BlipProcessorKwargs,
103
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
104
+ **kwargs,
105
+ )
106
+ if text is not None:
107
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
108
+ if images is not None:
109
+ encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
110
+
111
+ if text_encoding is not None:
112
+ encoding_image_processor.update(text_encoding)
113
+ return encoding_image_processor
114
+
115
+ return text_encoding
116
+
117
+ @property
118
+ def model_input_names(self):
119
+ tokenizer_input_names = self.tokenizer.model_input_names
120
+ image_processor_input_names = self.image_processor.model_input_names
121
+ tokenizer_input_names = [name for name in tokenizer_input_names if name != "token_type_ids"]
122
+ return tokenizer_input_names + image_processor_input_names
123
+
124
+
125
+ __all__ = ["BlipProcessor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/__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_convnextv2 import *
22
+ from .modeling_convnextv2 import *
23
+ from .modeling_tf_convnextv2 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/configuration_convnextv2.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta Platforms, Inc. and The HuggingFace Inc. team. 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
+ """ConvNeXTV2 model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class ConvNextV2Config(BackboneConfigMixin, PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`ConvNextV2Model`]. It is used to instantiate an
28
+ ConvNeXTV2 model according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the ConvNeXTV2
30
+ [facebook/convnextv2-tiny-1k-224](https://huggingface.co/facebook/convnextv2-tiny-1k-224) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ num_channels (`int`, *optional*, defaults to 3):
37
+ The number of input channels.
38
+ patch_size (`int`, *optional*, defaults to 4):
39
+ Patch size to use in the patch embedding layer.
40
+ num_stages (`int`, *optional*, defaults to 4):
41
+ The number of stages in the model.
42
+ hidden_sizes (`list[int]`, *optional*, defaults to `[96, 192, 384, 768]`):
43
+ Dimensionality (hidden size) at each stage.
44
+ depths (`list[int]`, *optional*, defaults to `[3, 3, 9, 3]`):
45
+ Depth (number of blocks) for each stage.
46
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
47
+ The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
48
+ `"selu"` and `"gelu_new"` are supported.
49
+ initializer_range (`float`, *optional*, defaults to 0.02):
50
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
51
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
52
+ The epsilon used by the layer normalization layers.
53
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
54
+ The drop rate for stochastic depth.
55
+ image_size (`int`, *optional*, defaults to 224):
56
+ The size (resolution) of each image.
57
+ out_features (`list[str]`, *optional*):
58
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
59
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
60
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
61
+ same order as defined in the `stage_names` attribute.
62
+ out_indices (`list[int]`, *optional*):
63
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
64
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
65
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
66
+ same order as defined in the `stage_names` attribute.
67
+
68
+ Example:
69
+ ```python
70
+ >>> from transformers import ConvNeXTV2Config, ConvNextV2Model
71
+
72
+ >>> # Initializing a ConvNeXTV2 convnextv2-tiny-1k-224 style configuration
73
+ >>> configuration = ConvNeXTV2Config()
74
+
75
+ >>> # Initializing a model (with random weights) from the convnextv2-tiny-1k-224 style configuration
76
+ >>> model = ConvNextV2Model(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "convnextv2"
83
+
84
+ def __init__(
85
+ self,
86
+ num_channels=3,
87
+ patch_size=4,
88
+ num_stages=4,
89
+ hidden_sizes=None,
90
+ depths=None,
91
+ hidden_act="gelu",
92
+ initializer_range=0.02,
93
+ layer_norm_eps=1e-12,
94
+ drop_path_rate=0.0,
95
+ image_size=224,
96
+ out_features=None,
97
+ out_indices=None,
98
+ **kwargs,
99
+ ):
100
+ super().__init__(**kwargs)
101
+
102
+ self.num_channels = num_channels
103
+ self.patch_size = patch_size
104
+ self.num_stages = num_stages
105
+ self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
106
+ self.depths = [3, 3, 9, 3] if depths is None else depths
107
+ self.hidden_act = hidden_act
108
+ self.initializer_range = initializer_range
109
+ self.layer_norm_eps = layer_norm_eps
110
+ self.drop_path_rate = drop_path_rate
111
+ self.image_size = image_size
112
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
113
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
114
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
115
+ )
116
+
117
+
118
+ __all__ = ["ConvNextV2Config"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_convnextv2.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta Platforms, Inc. and The HuggingFace Inc. team. 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 ConvNextV2 model."""
16
+
17
+ from typing import Optional
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from ...activations import ACT2FN
23
+ from ...modeling_outputs import (
24
+ BackboneOutput,
25
+ BaseModelOutputWithNoAttention,
26
+ BaseModelOutputWithPoolingAndNoAttention,
27
+ ImageClassifierOutputWithNoAttention,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import auto_docstring, logging
31
+ from ...utils.backbone_utils import BackboneMixin
32
+ from ...utils.generic import can_return_tuple
33
+ from .configuration_convnextv2 import ConvNextV2Config
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ # Copied from transformers.models.beit.modeling_beit.drop_path
40
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
41
+ """
42
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
43
+
44
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
45
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
46
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
47
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
48
+ argument.
49
+ """
50
+ if drop_prob == 0.0 or not training:
51
+ return input
52
+ keep_prob = 1 - drop_prob
53
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
54
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
55
+ random_tensor.floor_() # binarize
56
+ output = input.div(keep_prob) * random_tensor
57
+ return output
58
+
59
+
60
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNextV2
61
+ class ConvNextV2DropPath(nn.Module):
62
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
63
+
64
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
65
+ super().__init__()
66
+ self.drop_prob = drop_prob
67
+
68
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
69
+ return drop_path(hidden_states, self.drop_prob, self.training)
70
+
71
+ def extra_repr(self) -> str:
72
+ return f"p={self.drop_prob}"
73
+
74
+
75
+ class ConvNextV2GRN(nn.Module):
76
+ """GRN (Global Response Normalization) layer"""
77
+
78
+ def __init__(self, dim: int):
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))
81
+ self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))
82
+
83
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
84
+ # Compute and normalize global spatial feature maps
85
+ global_features = torch.linalg.vector_norm(hidden_states, ord=2, dim=(1, 2), keepdim=True)
86
+ norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)
87
+ hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
88
+
89
+ return hidden_states
90
+
91
+
92
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2
93
+ class ConvNextV2LayerNorm(nn.LayerNorm):
94
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
95
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
96
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
97
+ """
98
+
99
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
100
+ super().__init__(normalized_shape, eps=eps, **kwargs)
101
+ if data_format not in ["channels_last", "channels_first"]:
102
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
103
+ self.data_format = data_format
104
+
105
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
106
+ """
107
+ Args:
108
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
109
+ """
110
+ if self.data_format == "channels_first":
111
+ features = features.permute(0, 2, 3, 1)
112
+ features = super().forward(features)
113
+ features = features.permute(0, 3, 1, 2)
114
+ else:
115
+ features = super().forward(features)
116
+ return features
117
+
118
+
119
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2
120
+ class ConvNextV2Embeddings(nn.Module):
121
+ """This class is comparable to (and inspired by) the SwinEmbeddings class
122
+ found in src/transformers/models/swin/modeling_swin.py.
123
+ """
124
+
125
+ def __init__(self, config):
126
+ super().__init__()
127
+ self.patch_embeddings = nn.Conv2d(
128
+ config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
129
+ )
130
+ self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
131
+ self.num_channels = config.num_channels
132
+
133
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
134
+ num_channels = pixel_values.shape[1]
135
+ if num_channels != self.num_channels:
136
+ raise ValueError(
137
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
138
+ )
139
+ embeddings = self.patch_embeddings(pixel_values)
140
+ embeddings = self.layernorm(embeddings)
141
+ return embeddings
142
+
143
+
144
+ class ConvNextV2Layer(nn.Module):
145
+ """This corresponds to the `Block` class in the original implementation.
146
+
147
+ There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
148
+ H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
149
+
150
+ The authors used (2) as they find it slightly faster in PyTorch.
151
+
152
+ Args:
153
+ config ([`ConvNextV2Config`]): Model configuration class.
154
+ dim (`int`): Number of input channels.
155
+ drop_path (`float`): Stochastic depth rate. Default: 0.0.
156
+ """
157
+
158
+ def __init__(self, config, dim, drop_path=0):
159
+ super().__init__()
160
+ # depthwise conv
161
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
162
+ self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)
163
+ # pointwise/1x1 convs, implemented with linear layers
164
+ self.pwconv1 = nn.Linear(dim, 4 * dim)
165
+ self.act = ACT2FN[config.hidden_act]
166
+ self.grn = ConvNextV2GRN(4 * dim)
167
+ self.pwconv2 = nn.Linear(4 * dim, dim)
168
+ self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
169
+
170
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
171
+ residual = features
172
+ features = self.dwconv(features)
173
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
174
+ features = features.permute(0, 2, 3, 1)
175
+ features = self.layernorm(features)
176
+ features = self.pwconv1(features)
177
+ features = self.act(features)
178
+ features = self.grn(features)
179
+ features = self.pwconv2(features)
180
+ # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
181
+ features = features.permute(0, 3, 1, 2)
182
+
183
+ features = residual + self.drop_path(features)
184
+ return features
185
+
186
+
187
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
188
+ class ConvNextV2Stage(nn.Module):
189
+ """ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
190
+
191
+ Args:
192
+ config ([`ConvNextV2Config`]): Model configuration class.
193
+ in_channels (`int`): Number of input channels.
194
+ out_channels (`int`): Number of output channels.
195
+ depth (`int`): Number of residual blocks.
196
+ drop_path_rates(`list[float]`): Stochastic depth rates for each layer.
197
+ """
198
+
199
+ def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
200
+ super().__init__()
201
+
202
+ if in_channels != out_channels or stride > 1:
203
+ self.downsampling_layer = nn.ModuleList(
204
+ [
205
+ ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
206
+ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
207
+ ]
208
+ )
209
+ else:
210
+ self.downsampling_layer = nn.ModuleList()
211
+ drop_path_rates = drop_path_rates or [0.0] * depth
212
+ self.layers = nn.ModuleList(
213
+ [ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
214
+ )
215
+
216
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
217
+ for layer in self.downsampling_layer:
218
+ features = layer(features)
219
+ for layer in self.layers:
220
+ features = layer(features)
221
+ return features
222
+
223
+
224
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with ConvNext->ConvNextV2
225
+ class ConvNextV2Encoder(nn.Module):
226
+ def __init__(self, config):
227
+ super().__init__()
228
+ self.stages = nn.ModuleList()
229
+ drop_path_rates = [
230
+ x.tolist()
231
+ for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
232
+ ]
233
+ prev_chs = config.hidden_sizes[0]
234
+ for i in range(config.num_stages):
235
+ out_chs = config.hidden_sizes[i]
236
+ stage = ConvNextV2Stage(
237
+ config,
238
+ in_channels=prev_chs,
239
+ out_channels=out_chs,
240
+ stride=2 if i > 0 else 1,
241
+ depth=config.depths[i],
242
+ drop_path_rates=drop_path_rates[i],
243
+ )
244
+ self.stages.append(stage)
245
+ prev_chs = out_chs
246
+
247
+ def forward(
248
+ self, hidden_states: torch.Tensor, output_hidden_states: Optional[bool] = False
249
+ ) -> BaseModelOutputWithNoAttention:
250
+ all_hidden_states = [hidden_states] if output_hidden_states else None
251
+
252
+ for layer_module in self.stages:
253
+ hidden_states = layer_module(hidden_states)
254
+ if all_hidden_states is not None:
255
+ all_hidden_states.append(hidden_states)
256
+
257
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
258
+
259
+
260
+ @auto_docstring
261
+ class ConvNextV2PreTrainedModel(PreTrainedModel):
262
+ config: ConvNextV2Config
263
+ base_model_prefix = "convnextv2"
264
+ main_input_name = "pixel_values"
265
+ _no_split_modules = ["ConvNextV2Layer"]
266
+
267
+ def _init_weights(self, module):
268
+ """Initialize the weights"""
269
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
270
+ # Slightly different from the TF version which uses truncated_normal for initialization
271
+ # cf https://github.com/pytorch/pytorch/pull/5617
272
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
273
+ if module.bias is not None:
274
+ module.bias.data.zero_()
275
+ elif isinstance(module, (nn.LayerNorm, ConvNextV2LayerNorm)):
276
+ module.bias.data.zero_()
277
+ module.weight.data.fill_(1.0)
278
+ elif isinstance(module, ConvNextV2GRN):
279
+ module.weight.data.zero_()
280
+ module.bias.data.zero_()
281
+
282
+
283
+ @auto_docstring
284
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
285
+ class ConvNextV2Model(ConvNextV2PreTrainedModel):
286
+ def __init__(self, config):
287
+ super().__init__(config)
288
+ self.config = config
289
+
290
+ self.embeddings = ConvNextV2Embeddings(config)
291
+ self.encoder = ConvNextV2Encoder(config)
292
+
293
+ # final layernorm layer
294
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
295
+
296
+ # Initialize weights and apply final processing
297
+ self.post_init()
298
+
299
+ @can_return_tuple
300
+ @auto_docstring
301
+ def forward(
302
+ self, pixel_values: Optional[torch.FloatTensor] = None, output_hidden_states: Optional[bool] = None
303
+ ) -> BaseModelOutputWithPoolingAndNoAttention:
304
+ if output_hidden_states is None:
305
+ output_hidden_states = self.config.output_hidden_states
306
+
307
+ if pixel_values is None:
308
+ raise ValueError("You have to specify pixel_values")
309
+
310
+ embedding_output = self.embeddings(pixel_values)
311
+ encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(
312
+ embedding_output, output_hidden_states=output_hidden_states
313
+ )
314
+ last_hidden_state = encoder_outputs.last_hidden_state
315
+
316
+ # global average pooling, (N, C, H, W) -> (N, C)
317
+ pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
318
+
319
+ return BaseModelOutputWithPoolingAndNoAttention(
320
+ last_hidden_state=last_hidden_state,
321
+ pooler_output=pooled_output,
322
+ hidden_states=encoder_outputs.hidden_states,
323
+ )
324
+
325
+
326
+ @auto_docstring(
327
+ custom_intro="""
328
+ ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
329
+ ImageNet.
330
+ """
331
+ )
332
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
333
+ class ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):
334
+ accepts_loss_kwargs = False
335
+
336
+ def __init__(self, config):
337
+ super().__init__(config)
338
+
339
+ self.num_labels = config.num_labels
340
+ self.convnextv2 = ConvNextV2Model(config)
341
+
342
+ # Classifier head
343
+ if config.num_labels > 0:
344
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
345
+ else:
346
+ self.classifier = nn.Identity()
347
+
348
+ # Initialize weights and apply final processing
349
+ self.post_init()
350
+
351
+ @can_return_tuple
352
+ @auto_docstring
353
+ def forward(
354
+ self, pixel_values: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, **kwargs
355
+ ) -> ImageClassifierOutputWithNoAttention:
356
+ r"""
357
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
358
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
359
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
360
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
361
+ """
362
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.convnextv2(pixel_values, **kwargs)
363
+ pooled_output = outputs.pooler_output
364
+ logits = self.classifier(pooled_output)
365
+
366
+ loss = None
367
+ if labels is not None:
368
+ loss = self.loss_function(labels=labels, pooled_logits=logits, config=self.config)
369
+
370
+ return ImageClassifierOutputWithNoAttention(
371
+ loss=loss,
372
+ logits=logits,
373
+ hidden_states=outputs.hidden_states,
374
+ )
375
+
376
+
377
+ @auto_docstring(
378
+ custom_intro="""
379
+ ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.
380
+ """
381
+ )
382
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224
383
+ class ConvNextV2Backbone(ConvNextV2PreTrainedModel, BackboneMixin):
384
+ has_attentions = False
385
+
386
+ def __init__(self, config):
387
+ super().__init__(config)
388
+ super()._init_backbone(config)
389
+
390
+ self.embeddings = ConvNextV2Embeddings(config)
391
+ self.encoder = ConvNextV2Encoder(config)
392
+ self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
393
+
394
+ # Add layer norms to hidden states of out_features
395
+ hidden_states_norms = {}
396
+ for stage, num_channels in zip(self._out_features, self.channels):
397
+ hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format="channels_first")
398
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
399
+
400
+ # initialize weights and apply final processing
401
+ self.post_init()
402
+
403
+ @can_return_tuple
404
+ @auto_docstring
405
+ def forward(
406
+ self,
407
+ pixel_values: torch.Tensor,
408
+ output_hidden_states: Optional[bool] = None,
409
+ ) -> BackboneOutput:
410
+ r"""
411
+ Examples:
412
+
413
+ ```python
414
+ >>> from transformers import AutoImageProcessor, AutoBackbone
415
+ >>> import torch
416
+ >>> from PIL import Image
417
+ >>> import requests
418
+
419
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
420
+ >>> image = Image.open(requests.get(url, stream=True).raw)
421
+
422
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224")
423
+ >>> model = AutoBackbone.from_pretrained("facebook/convnextv2-tiny-1k-224")
424
+
425
+ >>> inputs = processor(image, return_tensors="pt")
426
+ >>> outputs = model(**inputs)
427
+ ```"""
428
+ if output_hidden_states is None:
429
+ output_hidden_states = self.config.output_hidden_states
430
+
431
+ embedding_output = self.embeddings(pixel_values)
432
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.encoder(embedding_output, output_hidden_states=True)
433
+ hidden_states = outputs.hidden_states
434
+
435
+ feature_maps = []
436
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
437
+ if stage in self.out_features:
438
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
439
+ feature_maps.append(hidden_state)
440
+
441
+ return BackboneOutput(
442
+ feature_maps=tuple(feature_maps),
443
+ hidden_states=hidden_states if output_hidden_states else None,
444
+ )
445
+
446
+
447
+ __all__ = ["ConvNextV2ForImageClassification", "ConvNextV2Model", "ConvNextV2PreTrainedModel", "ConvNextV2Backbone"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_tf_convnextv2.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta Platforms Inc. and The HuggingFace Inc. team. 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
+ """TF 2.0 ConvNextV2 model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+ import tensorflow as tf
21
+
22
+ from ...activations_tf import get_tf_activation
23
+ from ...modeling_tf_outputs import (
24
+ TFBaseModelOutputWithNoAttention,
25
+ TFBaseModelOutputWithPooling,
26
+ TFBaseModelOutputWithPoolingAndNoAttention,
27
+ TFImageClassifierOutputWithNoAttention,
28
+ )
29
+ from ...modeling_tf_utils import (
30
+ TFModelInputType,
31
+ TFPreTrainedModel,
32
+ TFSequenceClassificationLoss,
33
+ get_initializer,
34
+ keras,
35
+ keras_serializable,
36
+ unpack_inputs,
37
+ )
38
+ from ...tf_utils import shape_list
39
+ from ...utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ )
45
+ from .configuration_convnextv2 import ConvNextV2Config
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ # General docstring
51
+ _CONFIG_FOR_DOC = "ConvNextV2Config"
52
+
53
+ # Base docstring
54
+ _CHECKPOINT_FOR_DOC = "facebook/convnextv2-tiny-1k-224"
55
+ _EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
56
+
57
+ # Image classification docstring
58
+ _IMAGE_CLASS_CHECKPOINT = "facebook/convnextv2-tiny-1k-224"
59
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
60
+
61
+
62
+ # Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextDropPath with ConvNext->ConvNextV2
63
+ class TFConvNextV2DropPath(keras.layers.Layer):
64
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
65
+ References:
66
+ (1) github.com:rwightman/pytorch-image-models
67
+ """
68
+
69
+ def __init__(self, drop_path: float, **kwargs):
70
+ super().__init__(**kwargs)
71
+ self.drop_path = drop_path
72
+
73
+ def call(self, x: tf.Tensor, training=None):
74
+ if training:
75
+ keep_prob = 1 - self.drop_path
76
+ shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
77
+ random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
78
+ random_tensor = tf.floor(random_tensor)
79
+ return (x / keep_prob) * random_tensor
80
+ return x
81
+
82
+
83
+ class TFConvNextV2GRN(keras.layers.Layer):
84
+ """GRN (Global Response Normalization) layer"""
85
+
86
+ def __init__(self, config: ConvNextV2Config, dim: int, **kwargs):
87
+ super().__init__(**kwargs)
88
+ self.dim = dim
89
+
90
+ def build(self, input_shape: tf.TensorShape = None):
91
+ # PT's `nn.Parameters` must be mapped to a TF layer weight to inherit the same name hierarchy (and vice-versa)
92
+ self.weight = self.add_weight(
93
+ name="weight",
94
+ shape=(1, 1, 1, self.dim),
95
+ initializer=keras.initializers.Zeros(),
96
+ )
97
+ self.bias = self.add_weight(
98
+ name="bias",
99
+ shape=(1, 1, 1, self.dim),
100
+ initializer=keras.initializers.Zeros(),
101
+ )
102
+ return super().build(input_shape)
103
+
104
+ def call(self, hidden_states: tf.Tensor):
105
+ global_features = tf.norm(hidden_states, ord="euclidean", axis=(1, 2), keepdims=True)
106
+ norm_features = global_features / (tf.reduce_mean(global_features, axis=-1, keepdims=True) + 1e-6)
107
+ hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
108
+ return hidden_states
109
+
110
+
111
+ # Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextEmbeddings with ConvNext->ConvNextV2
112
+ class TFConvNextV2Embeddings(keras.layers.Layer):
113
+ """This class is comparable to (and inspired by) the SwinEmbeddings class
114
+ found in src/transformers/models/swin/modeling_swin.py.
115
+ """
116
+
117
+ def __init__(self, config: ConvNextV2Config, **kwargs):
118
+ super().__init__(**kwargs)
119
+ self.patch_embeddings = keras.layers.Conv2D(
120
+ filters=config.hidden_sizes[0],
121
+ kernel_size=config.patch_size,
122
+ strides=config.patch_size,
123
+ name="patch_embeddings",
124
+ kernel_initializer=get_initializer(config.initializer_range),
125
+ bias_initializer=keras.initializers.Zeros(),
126
+ )
127
+ self.layernorm = keras.layers.LayerNormalization(epsilon=1e-6, name="layernorm")
128
+ self.num_channels = config.num_channels
129
+ self.config = config
130
+
131
+ def call(self, pixel_values):
132
+ if isinstance(pixel_values, dict):
133
+ pixel_values = pixel_values["pixel_values"]
134
+
135
+ tf.debugging.assert_equal(
136
+ shape_list(pixel_values)[1],
137
+ self.num_channels,
138
+ message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
139
+ )
140
+
141
+ # When running on CPU, `keras.layers.Conv2D` doesn't support `NCHW` format.
142
+ # So change the input format from `NCHW` to `NHWC`.
143
+ # shape = (batch_size, in_height, in_width, in_channels)
144
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
145
+
146
+ embeddings = self.patch_embeddings(pixel_values)
147
+ embeddings = self.layernorm(embeddings)
148
+ return embeddings
149
+
150
+ def build(self, input_shape=None):
151
+ if self.built:
152
+ return
153
+ self.built = True
154
+ if getattr(self, "patch_embeddings", None) is not None:
155
+ with tf.name_scope(self.patch_embeddings.name):
156
+ self.patch_embeddings.build([None, None, None, self.config.num_channels])
157
+ if getattr(self, "layernorm", None) is not None:
158
+ with tf.name_scope(self.layernorm.name):
159
+ self.layernorm.build([None, None, None, self.config.hidden_sizes[0]])
160
+
161
+
162
+ class TFConvNextV2Layer(keras.layers.Layer):
163
+ """This corresponds to the `Block` class in the original implementation.
164
+
165
+ There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
166
+ H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
167
+
168
+ The authors used (2) as they find it slightly faster in PyTorch. Since we already permuted the inputs to follow
169
+ NHWC ordering, we can just apply the operations straight-away without the permutation.
170
+
171
+ Args:
172
+ config (`ConvNextV2Config`):
173
+ Model configuration class.
174
+ dim (`int`):
175
+ Number of input channels.
176
+ drop_path (`float`, *optional*, defaults to 0.0):
177
+ Stochastic depth rate.
178
+ """
179
+
180
+ def __init__(self, config: ConvNextV2Config, dim: int, drop_path: float = 0.0, **kwargs):
181
+ super().__init__(**kwargs)
182
+ self.dim = dim
183
+ self.config = config
184
+ self.dwconv = keras.layers.Conv2D(
185
+ filters=dim,
186
+ kernel_size=7,
187
+ padding="same",
188
+ groups=dim,
189
+ kernel_initializer=get_initializer(config.initializer_range),
190
+ bias_initializer=keras.initializers.Zeros(),
191
+ name="dwconv",
192
+ ) # depthwise conv
193
+ self.layernorm = keras.layers.LayerNormalization(
194
+ epsilon=1e-6,
195
+ name="layernorm",
196
+ )
197
+ self.pwconv1 = keras.layers.Dense(
198
+ units=4 * dim,
199
+ kernel_initializer=get_initializer(config.initializer_range),
200
+ bias_initializer=keras.initializers.Zeros(),
201
+ name="pwconv1",
202
+ ) # pointwise/1x1 convs, implemented with linear layers
203
+ self.act = get_tf_activation(config.hidden_act)
204
+ self.grn = TFConvNextV2GRN(config, 4 * dim, dtype=tf.float32, name="grn")
205
+ self.pwconv2 = keras.layers.Dense(
206
+ units=dim,
207
+ kernel_initializer=get_initializer(config.initializer_range),
208
+ bias_initializer=keras.initializers.Zeros(),
209
+ name="pwconv2",
210
+ )
211
+ # Using `layers.Activation` instead of `tf.identity` to better control `training`
212
+ # behaviour.
213
+ self.drop_path = (
214
+ TFConvNextV2DropPath(drop_path, name="drop_path")
215
+ if drop_path > 0.0
216
+ else keras.layers.Activation("linear", name="drop_path")
217
+ )
218
+
219
+ def call(self, hidden_states, training=False):
220
+ input = hidden_states
221
+ x = self.dwconv(hidden_states)
222
+ x = self.layernorm(x)
223
+ x = self.pwconv1(x)
224
+ x = self.act(x)
225
+ x = self.grn(x)
226
+ x = self.pwconv2(x)
227
+ x = self.drop_path(x, training=training)
228
+ x = input + x
229
+ return x
230
+
231
+ def build(self, input_shape=None):
232
+ if self.built:
233
+ return
234
+ self.built = True
235
+ if getattr(self, "dwconv", None) is not None:
236
+ with tf.name_scope(self.dwconv.name):
237
+ self.dwconv.build([None, None, None, self.dim])
238
+ if getattr(self, "layernorm", None) is not None:
239
+ with tf.name_scope(self.layernorm.name):
240
+ self.layernorm.build([None, None, None, self.dim])
241
+ if getattr(self, "pwconv1", None) is not None:
242
+ with tf.name_scope(self.pwconv1.name):
243
+ self.pwconv1.build([None, None, self.dim])
244
+ if getattr(self, "grn", None) is not None:
245
+ with tf.name_scope(self.grn.name):
246
+ self.grn.build(None)
247
+ if getattr(self, "pwconv2", None) is not None:
248
+ with tf.name_scope(self.pwconv2.name):
249
+ self.pwconv2.build([None, None, 4 * self.dim])
250
+ if getattr(self, "drop_path", None) is not None:
251
+ with tf.name_scope(self.drop_path.name):
252
+ self.drop_path.build(None)
253
+
254
+
255
+ # Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextStage with ConvNext->ConvNextV2
256
+ class TFConvNextV2Stage(keras.layers.Layer):
257
+ """ConvNextV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
258
+
259
+ Args:
260
+ config (`ConvNextV2V2Config`):
261
+ Model configuration class.
262
+ in_channels (`int`):
263
+ Number of input channels.
264
+ out_channels (`int`):
265
+ Number of output channels.
266
+ depth (`int`):
267
+ Number of residual blocks.
268
+ drop_path_rates(`list[float]`):
269
+ Stochastic depth rates for each layer.
270
+ """
271
+
272
+ def __init__(
273
+ self,
274
+ config: ConvNextV2Config,
275
+ in_channels: int,
276
+ out_channels: int,
277
+ kernel_size: int = 2,
278
+ stride: int = 2,
279
+ depth: int = 2,
280
+ drop_path_rates: list[float] | None = None,
281
+ **kwargs,
282
+ ):
283
+ super().__init__(**kwargs)
284
+ if in_channels != out_channels or stride > 1:
285
+ self.downsampling_layer = [
286
+ keras.layers.LayerNormalization(
287
+ epsilon=1e-6,
288
+ name="downsampling_layer.0",
289
+ ),
290
+ # Inputs to this layer will follow NHWC format since we
291
+ # transposed the inputs from NCHW to NHWC in the `TFConvNextV2Embeddings`
292
+ # layer. All the outputs throughout the model will be in NHWC
293
+ # from this point on until the output where we again change to
294
+ # NCHW.
295
+ keras.layers.Conv2D(
296
+ filters=out_channels,
297
+ kernel_size=kernel_size,
298
+ strides=stride,
299
+ kernel_initializer=get_initializer(config.initializer_range),
300
+ bias_initializer=keras.initializers.Zeros(),
301
+ name="downsampling_layer.1",
302
+ ),
303
+ ]
304
+ else:
305
+ self.downsampling_layer = [tf.identity]
306
+
307
+ drop_path_rates = drop_path_rates or [0.0] * depth
308
+ self.layers = [
309
+ TFConvNextV2Layer(
310
+ config,
311
+ dim=out_channels,
312
+ drop_path=drop_path_rates[j],
313
+ name=f"layers.{j}",
314
+ )
315
+ for j in range(depth)
316
+ ]
317
+ self.in_channels = in_channels
318
+ self.out_channels = out_channels
319
+ self.stride = stride
320
+
321
+ def call(self, hidden_states):
322
+ for layer in self.downsampling_layer:
323
+ hidden_states = layer(hidden_states)
324
+ for layer in self.layers:
325
+ hidden_states = layer(hidden_states)
326
+ return hidden_states
327
+
328
+ def build(self, input_shape=None):
329
+ if self.built:
330
+ return
331
+ self.built = True
332
+ if getattr(self, "layers", None) is not None:
333
+ for layer in self.layers:
334
+ with tf.name_scope(layer.name):
335
+ layer.build(None)
336
+ if self.in_channels != self.out_channels or self.stride > 1:
337
+ with tf.name_scope(self.downsampling_layer[0].name):
338
+ self.downsampling_layer[0].build([None, None, None, self.in_channels])
339
+ with tf.name_scope(self.downsampling_layer[1].name):
340
+ self.downsampling_layer[1].build([None, None, None, self.in_channels])
341
+
342
+
343
+ class TFConvNextV2Encoder(keras.layers.Layer):
344
+ def __init__(self, config: ConvNextV2Config, **kwargs):
345
+ super().__init__(**kwargs)
346
+ self.stages = []
347
+ drop_path_rates = tf.linspace(0.0, config.drop_path_rate, sum(config.depths))
348
+ drop_path_rates = tf.split(drop_path_rates, config.depths)
349
+ drop_path_rates = [x.numpy().tolist() for x in drop_path_rates]
350
+ prev_chs = config.hidden_sizes[0]
351
+ for i in range(config.num_stages):
352
+ out_chs = config.hidden_sizes[i]
353
+ stage = TFConvNextV2Stage(
354
+ config,
355
+ in_channels=prev_chs,
356
+ out_channels=out_chs,
357
+ stride=2 if i > 0 else 1,
358
+ depth=config.depths[i],
359
+ drop_path_rates=drop_path_rates[i],
360
+ name=f"stages.{i}",
361
+ )
362
+ self.stages.append(stage)
363
+ prev_chs = out_chs
364
+
365
+ def call(
366
+ self,
367
+ hidden_states: tf.Tensor,
368
+ output_hidden_states: bool | None = False,
369
+ return_dict: bool | None = True,
370
+ ) -> tuple | TFBaseModelOutputWithNoAttention:
371
+ all_hidden_states = () if output_hidden_states else None
372
+
373
+ for i, layer_module in enumerate(self.stages):
374
+ if output_hidden_states:
375
+ all_hidden_states = all_hidden_states + (hidden_states,)
376
+
377
+ hidden_states = layer_module(hidden_states)
378
+
379
+ if output_hidden_states:
380
+ all_hidden_states = all_hidden_states + (hidden_states,)
381
+
382
+ if not return_dict:
383
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
384
+
385
+ return TFBaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
386
+
387
+ def build(self, input_shape=None):
388
+ for stage in self.stages:
389
+ with tf.name_scope(stage.name):
390
+ stage.build(None)
391
+
392
+
393
+ @keras_serializable
394
+ class TFConvNextV2MainLayer(keras.layers.Layer):
395
+ config_class = ConvNextV2Config
396
+
397
+ def __init__(self, config: ConvNextV2Config, **kwargs):
398
+ super().__init__(**kwargs)
399
+
400
+ self.config = config
401
+ self.embeddings = TFConvNextV2Embeddings(config, name="embeddings")
402
+ self.encoder = TFConvNextV2Encoder(config, name="encoder")
403
+ self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
404
+ # We are setting the `data_format` like so because from here on we will revert to the
405
+ # NCHW output format
406
+ self.pooler = keras.layers.GlobalAvgPool2D(data_format="channels_last")
407
+
408
+ @unpack_inputs
409
+ def call(
410
+ self,
411
+ pixel_values: TFModelInputType | None = None,
412
+ output_hidden_states: bool | None = None,
413
+ return_dict: bool | None = None,
414
+ training: bool = False,
415
+ ) -> TFBaseModelOutputWithPooling | tuple[tf.Tensor]:
416
+ output_hidden_states = (
417
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
418
+ )
419
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
420
+
421
+ if pixel_values is None:
422
+ raise ValueError("You have to specify pixel_values")
423
+
424
+ embedding_output = self.embeddings(pixel_values, training=training)
425
+
426
+ encoder_outputs = self.encoder(
427
+ embedding_output,
428
+ output_hidden_states=output_hidden_states,
429
+ return_dict=return_dict,
430
+ training=training,
431
+ )
432
+
433
+ last_hidden_state = encoder_outputs[0]
434
+
435
+ # Change to NCHW output format have uniformity in the modules
436
+ pooled_output = self.pooler(last_hidden_state)
437
+ last_hidden_state = tf.transpose(last_hidden_state, perm=(0, 3, 1, 2))
438
+ pooled_output = self.layernorm(pooled_output)
439
+
440
+ # Change the other hidden state outputs to NCHW as well
441
+ if output_hidden_states:
442
+ hidden_states = tuple(tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1])
443
+
444
+ if not return_dict:
445
+ hidden_states = hidden_states if output_hidden_states else ()
446
+ return (last_hidden_state, pooled_output) + hidden_states
447
+
448
+ return TFBaseModelOutputWithPoolingAndNoAttention(
449
+ last_hidden_state=last_hidden_state,
450
+ pooler_output=pooled_output,
451
+ hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
452
+ )
453
+
454
+ def build(self, input_shape=None):
455
+ if self.built:
456
+ return
457
+ self.built = True
458
+ if getattr(self, "embeddings", None) is not None:
459
+ with tf.name_scope(self.embeddings.name):
460
+ self.embeddings.build(None)
461
+ if getattr(self, "encoder", None) is not None:
462
+ with tf.name_scope(self.encoder.name):
463
+ self.encoder.build(None)
464
+ if getattr(self, "layernorm", None) is not None:
465
+ with tf.name_scope(self.layernorm.name):
466
+ self.layernorm.build([None, self.config.hidden_sizes[-1]])
467
+
468
+
469
+ class TFConvNextV2PreTrainedModel(TFPreTrainedModel):
470
+ """
471
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
472
+ models.
473
+ """
474
+
475
+ config_class = ConvNextV2Config
476
+ base_model_prefix = "convnextv2"
477
+ main_input_name = "pixel_values"
478
+
479
+
480
+ CONVNEXTV2_START_DOCSTRING = r"""
481
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
482
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
483
+ etc.)
484
+
485
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
486
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
487
+ behavior.
488
+
489
+ <Tip>
490
+
491
+ TensorFlow models and layers in `transformers` accept two formats as input:
492
+
493
+ - having all inputs as keyword arguments (like PyTorch models), or
494
+ - having all inputs as a list, tuple or dict in the first positional argument.
495
+
496
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
497
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
498
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
499
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
500
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
501
+ positional argument:
502
+
503
+ - a single Tensor with `pixel_values` only and nothing else: `model(pixel_values)`
504
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
505
+ `model([pixel_values, attention_mask])` or `model([pixel_values, attention_mask, token_type_ids])`
506
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
507
+ `model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})`
508
+
509
+ Note that when creating models and layers with
510
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
511
+ about any of this, as you can just pass inputs like you would to any other Python function!
512
+
513
+ </Tip>
514
+
515
+ Parameters:
516
+ config ([`ConvNextV2Config`]): Model configuration class with all the parameters of the model.
517
+ Initializing with a config file does not load the weights associated with the model, only the
518
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
519
+ """
520
+
521
+ CONVNEXTV2_INPUTS_DOCSTRING = r"""
522
+ Args:
523
+ pixel_values (`np.ndarray`, `tf.Tensor`, `list[tf.Tensor]`, `dict[str, tf.Tensor]` or `dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
524
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
525
+ [`ConvNextImageProcessor.__call__`] for details.
526
+
527
+ output_hidden_states (`bool`, *optional*):
528
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
529
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
530
+ used instead.
531
+ return_dict (`bool`, *optional*):
532
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
533
+ eager mode, in graph mode the value will always be set to `True`.
534
+ """
535
+
536
+
537
+ @add_start_docstrings(
538
+ "The bare ConvNextV2 model outputting raw features without any specific head on top.",
539
+ CONVNEXTV2_START_DOCSTRING,
540
+ )
541
+ class TFConvNextV2Model(TFConvNextV2PreTrainedModel):
542
+ def __init__(self, config: ConvNextV2Config, *inputs, **kwargs):
543
+ super().__init__(config, *inputs, **kwargs)
544
+ self.convnextv2 = TFConvNextV2MainLayer(config, name="convnextv2")
545
+
546
+ @unpack_inputs
547
+ @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
548
+ @add_code_sample_docstrings(
549
+ checkpoint=_CHECKPOINT_FOR_DOC,
550
+ output_type=TFBaseModelOutputWithPoolingAndNoAttention,
551
+ config_class=_CONFIG_FOR_DOC,
552
+ modality="vision",
553
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
554
+ )
555
+ def call(
556
+ self,
557
+ pixel_values: TFModelInputType | None = None,
558
+ output_hidden_states: bool | None = None,
559
+ return_dict: bool | None = None,
560
+ training: bool = False,
561
+ ) -> TFBaseModelOutputWithPoolingAndNoAttention | tuple[tf.Tensor]:
562
+ output_hidden_states = (
563
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
564
+ )
565
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
566
+
567
+ if pixel_values is None:
568
+ raise ValueError("You have to specify pixel_values")
569
+
570
+ outputs = self.convnextv2(
571
+ pixel_values=pixel_values,
572
+ output_hidden_states=output_hidden_states,
573
+ return_dict=return_dict,
574
+ training=training,
575
+ )
576
+
577
+ if not return_dict:
578
+ return outputs[:]
579
+
580
+ return TFBaseModelOutputWithPoolingAndNoAttention(
581
+ last_hidden_state=outputs.last_hidden_state,
582
+ pooler_output=outputs.pooler_output,
583
+ hidden_states=outputs.hidden_states,
584
+ )
585
+
586
+ def build(self, input_shape=None):
587
+ if self.built:
588
+ return
589
+ self.built = True
590
+ if getattr(self, "convnextv2", None) is not None:
591
+ with tf.name_scope(self.convnextv2.name):
592
+ self.convnextv2.build(None)
593
+
594
+
595
+ @add_start_docstrings(
596
+ """
597
+ ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
598
+ ImageNet.
599
+ """,
600
+ CONVNEXTV2_START_DOCSTRING,
601
+ )
602
+ class TFConvNextV2ForImageClassification(TFConvNextV2PreTrainedModel, TFSequenceClassificationLoss):
603
+ def __init__(self, config: ConvNextV2Config, *inputs, **kwargs):
604
+ super().__init__(config, *inputs, **kwargs)
605
+
606
+ self.num_labels = config.num_labels
607
+ self.convnextv2 = TFConvNextV2MainLayer(config, name="convnextv2")
608
+
609
+ # Classifier head
610
+ self.classifier = keras.layers.Dense(
611
+ units=config.num_labels,
612
+ kernel_initializer=get_initializer(config.initializer_range),
613
+ bias_initializer=keras.initializers.Zeros(),
614
+ name="classifier",
615
+ )
616
+
617
+ @unpack_inputs
618
+ @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
619
+ @add_code_sample_docstrings(
620
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
621
+ output_type=TFImageClassifierOutputWithNoAttention,
622
+ config_class=_CONFIG_FOR_DOC,
623
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
624
+ )
625
+ def call(
626
+ self,
627
+ pixel_values: TFModelInputType | None = None,
628
+ output_hidden_states: bool | None = None,
629
+ return_dict: bool | None = None,
630
+ labels: np.ndarray | tf.Tensor | None = None,
631
+ training: bool | None = False,
632
+ ) -> TFImageClassifierOutputWithNoAttention | tuple[tf.Tensor]:
633
+ r"""
634
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
635
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
636
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
637
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
638
+ """
639
+ output_hidden_states = (
640
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
641
+ )
642
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
643
+
644
+ if pixel_values is None:
645
+ raise ValueError("You have to specify pixel_values")
646
+
647
+ outputs = self.convnextv2(
648
+ pixel_values,
649
+ output_hidden_states=output_hidden_states,
650
+ return_dict=return_dict,
651
+ training=training,
652
+ )
653
+
654
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
655
+
656
+ logits = self.classifier(pooled_output)
657
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
658
+
659
+ if not return_dict:
660
+ output = (logits,) + outputs[2:]
661
+ return ((loss,) + output) if loss is not None else output
662
+
663
+ return TFImageClassifierOutputWithNoAttention(
664
+ loss=loss,
665
+ logits=logits,
666
+ hidden_states=outputs.hidden_states,
667
+ )
668
+
669
+ def build(self, input_shape=None):
670
+ if self.built:
671
+ return
672
+ self.built = True
673
+ if getattr(self, "convnextv2", None) is not None:
674
+ with tf.name_scope(self.convnextv2.name):
675
+ self.convnextv2.build(None)
676
+ if getattr(self, "classifier", None) is not None:
677
+ with tf.name_scope(self.classifier.name):
678
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
679
+
680
+
681
+ __all__ = ["TFConvNextV2ForImageClassification", "TFConvNextV2Model", "TFConvNextV2PreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 the HuggingFace Team. 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
+
16
+ from typing import TYPE_CHECKING
17
+
18
+ from ...utils import _LazyModule
19
+ from ...utils.import_utils import define_import_structure
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .configuration_edgetam_video import *
24
+ from .modeling_edgetam_video import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/configuration_edgetam_video.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/edgetam_video/modular_edgetam_video.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_edgetam_video.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 the HuggingFace Team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ..auto import CONFIG_MAPPING, AutoConfig
24
+
25
+
26
+ class EdgeTamVideoPromptEncoderConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`EdgeTamVideoPromptEncoder`]. The [`EdgeTamVideoPromptEncoder`]
29
+ module is used to encode the input 2D points and bounding boxes.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ hidden_size (`int`, *optional*, defaults to 256):
36
+ Dimensionality of the hidden states.
37
+ image_size (`int`, *optional*, defaults to 1024):
38
+ The expected output resolution of the image.
39
+ patch_size (`int`, *optional*, defaults to 16):
40
+ The size (resolution) of each patch.
41
+ mask_input_channels (`int`, *optional*, defaults to 16):
42
+ The number of channels to be fed to the `MaskDecoder` module.
43
+ num_point_embeddings (`int`, *optional*, defaults to 4):
44
+ The number of point embeddings to be used.
45
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function in the encoder and pooler.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
48
+ The epsilon used by the layer normalization layers.
49
+ scale (`float`, *optional*, defaults to 1):
50
+ The scale factor for the prompt encoder.
51
+ """
52
+
53
+ base_config_key = "prompt_encoder_config"
54
+
55
+ def __init__(
56
+ self,
57
+ hidden_size=256,
58
+ image_size=1024,
59
+ patch_size=16,
60
+ mask_input_channels=16,
61
+ num_point_embeddings=4,
62
+ hidden_act="gelu",
63
+ layer_norm_eps=1e-6,
64
+ scale=1,
65
+ **kwargs,
66
+ ):
67
+ super().__init__(**kwargs)
68
+ self.hidden_size = hidden_size
69
+ self.image_size = image_size
70
+ self.patch_size = patch_size
71
+ self.mask_input_channels = mask_input_channels
72
+ self.num_point_embeddings = num_point_embeddings
73
+ self.hidden_act = hidden_act
74
+ self.layer_norm_eps = layer_norm_eps
75
+ self.scale = scale
76
+
77
+
78
+ class EdgeTamVideoMaskDecoderConfig(PretrainedConfig):
79
+ r"""
80
+ This is the configuration class to store the configuration of a [`EdgeTamVideoMaskDecoder`]. It is used to instantiate a EDGETAM_VIDEO
81
+ memory encoder according to the specified arguments, defining the model architecture.
82
+
83
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
84
+ documentation from [`PretrainedConfig`] for more information.
85
+
86
+ Args:
87
+ hidden_size (`int`, *optional*, defaults to 256):
88
+ Dimensionality of the hidden states.
89
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
90
+ The non-linear activation function in the EDGETAM_VIDEO mask decoder.
91
+ mlp_dim (`int`, *optional*, defaults to 2048):
92
+ The dimension of the MLP in the two-way transformer.
93
+ num_hidden_layers (`int`, *optional*, defaults to 2):
94
+ The number of hidden layers in the two-way transformer.
95
+ num_attention_heads (`int`, *optional*, defaults to 8):
96
+ The number of attention heads in the two-way transformer.
97
+ attention_downsample_rate (`int`, *optional*, defaults to 2):
98
+ The downsample rate for the attention layers.
99
+ num_multimask_outputs (`int`, *optional*, defaults to 3):
100
+ The number of multimask outputs.
101
+ iou_head_depth (`int`, *optional*, defaults to 3):
102
+ The depth of the IoU head.
103
+ iou_head_hidden_dim (`int`, *optional*, defaults to 256):
104
+ The hidden dimension of the IoU head.
105
+ dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`):
106
+ Whether to use dynamic multimask via stability.
107
+ dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05):
108
+ The stability delta for the dynamic multimask.
109
+ dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98):
110
+ The stability threshold for the dynamic multimask.
111
+
112
+ """
113
+
114
+ base_config_key = "mask_decoder_config"
115
+
116
+ def __init__(
117
+ self,
118
+ hidden_size=256,
119
+ hidden_act="gelu",
120
+ mlp_dim=2048,
121
+ num_hidden_layers=2,
122
+ num_attention_heads=8,
123
+ attention_downsample_rate=2,
124
+ num_multimask_outputs=3,
125
+ iou_head_depth=3,
126
+ iou_head_hidden_dim=256,
127
+ dynamic_multimask_via_stability=True,
128
+ dynamic_multimask_stability_delta=0.05,
129
+ dynamic_multimask_stability_thresh=0.98,
130
+ **kwargs,
131
+ ):
132
+ super().__init__(**kwargs)
133
+
134
+ self.hidden_size = hidden_size
135
+ self.num_multimask_outputs = num_multimask_outputs
136
+ self.hidden_act = hidden_act
137
+ self.iou_head_depth = iou_head_depth
138
+ self.iou_head_hidden_dim = iou_head_hidden_dim
139
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
140
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
141
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
142
+
143
+ # TwoWayTransformer configuration
144
+ self.num_hidden_layers = num_hidden_layers
145
+ self.hidden_size = hidden_size
146
+ self.num_attention_heads = num_attention_heads
147
+ self.mlp_dim = mlp_dim
148
+ self.attention_downsample_rate = attention_downsample_rate
149
+
150
+
151
+ class EdgeTamVideoConfig(PretrainedConfig):
152
+ r"""
153
+ [`EdgeTamVideoConfig`] is the configuration class to store the configuration of a [`EdgeTamVideoModel`]. It is used to instantiate a
154
+ EDGETAM model according to the specified arguments, defining the memory attention, memory encoder, and image encoder
155
+ configs. Instantiating a configuration defaults will yield a similar configuration to that of the SAM 2.1 Hiera-tiny
156
+ [facebook/EdgeTAM](https://huggingface.co/facebook/EdgeTAM) architecture.
157
+
158
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
159
+ documentation from [`PretrainedConfig`] for more information.
160
+
161
+ Args:
162
+ vision_config (Union[`dict`, `EdgeTamVideoVisionConfig`], *optional*):
163
+ Dictionary of configuration options used to initialize [`EdgeTamVideoVisionConfig`].
164
+ prompt_encoder_config (Union[`dict`, `EdgeTamVideoPromptEncoderConfig`], *optional*):
165
+ Dictionary of configuration options used to initialize [`EdgeTamVideoPromptEncoderConfig`].
166
+ mask_decoder_config (Union[`dict`, `EdgeTamVideoMaskDecoderConfig`], *optional*):
167
+ Dictionary of configuration options used to initialize [`EdgeTamMaskDecoderConfig`].
168
+ initializer_range (`float`, *optional*, defaults to 0.02):
169
+ Standard deviation for parameter initialization.
170
+ num_maskmem (`int`, *optional*, defaults to 7):
171
+ The number of memory slots for the mask memory.
172
+ image_size (`int`, *optional*, defaults to 1024):
173
+ The size of the input images.
174
+ sigmoid_scale_for_mem_enc (`float`, *optional*, defaults to 20.0):
175
+ Scale factor for the sigmoid function in the memory encoder.
176
+ sigmoid_bias_for_mem_enc (`float`, *optional*, defaults to -10.0):
177
+ Bias for the sigmoid function in the memory encoder.
178
+ enable_occlusion_spatial_embedding (`bool`, *optional*, defaults to `True`):
179
+ Whether to enable spatial embedding for occlusions.
180
+ multimask_output_in_sam (`bool`, *optional*, defaults to `True`):
181
+ Whether to output multiple masks from the SAM head.
182
+ multimask_min_pt_num (`int`, *optional*, defaults to 0):
183
+ The minimum number of points to trigger multimask output.
184
+ multimask_max_pt_num (`int`, *optional*, defaults to 1):
185
+ The maximum number of points to trigger multimask output.
186
+ multimask_output_for_tracking (`bool`, *optional*, defaults to `True`):
187
+ Whether to use multimask output for tracking.
188
+ max_object_pointers_in_encoder (`int`, *optional*, defaults to 16):
189
+ The maximum number of object pointers in the encoder.
190
+ enable_temporal_pos_encoding_for_object_pointers (`bool`, *optional*, defaults to `True`):
191
+ Whether to enable temporal positional encoding for object pointers.
192
+ memory_attention_hidden_size (`int`, *optional*, defaults to 256):
193
+ Dimensionality of the memory attention hidden states.
194
+ memory_attention_num_layers (`int`, *optional*, defaults to 2):
195
+ The number of layers in the memory attention module.
196
+ memory_attention_num_attention_heads (`int`, *optional*, defaults to 1):
197
+ Number of attention heads for each attention layer in the memory attention.
198
+ memory_attention_downsample_rate (`int`, *optional*, defaults to 1):
199
+ The downsample rate for the attention layers.
200
+ memory_attention_mlp_hidden_size (`int`, *optional*, defaults to 2048):
201
+ The dimension of the feedforward network in the memory attention module.
202
+ memory_attention_mlp_hidden_act (`str`, *optional*, defaults to `"relu"`):
203
+ The non-linear activation function in the feedforward network in the memory attention module.
204
+ memory_attention_dropout (`float`, *optional*, defaults to 0.1):
205
+ The dropout rate for the memory attention module.
206
+ memory_attention_rope_theta (`float`, *optional*, defaults to 10000):
207
+ The Rope theta parameter.
208
+ memory_attention_rope_feat_sizes (`Tuple[int, int]`, *optional*, defaults to `[64, 64]`):
209
+ The feature sizes for the Rope positional encoding.
210
+ memory_attention_rope_k_sizes (`List[int]`, *optional*, defaults to `[16, 16]`):
211
+ The key feature sizes for the RoPE positional encoding in memory attention.
212
+ memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1):
213
+ The dropout rate for the Rope positional encoding.
214
+ perceiver_resampler_num_latents (`int`, *optional*, defaults to 256):
215
+ The number of 1D latent tokens in the perceiver resampler.
216
+ perceiver_resampler_num_latents_2d (`int`, *optional*, defaults to 256):
217
+ The number of 2D latent tokens in the perceiver resampler.
218
+ perceiver_resampler_hidden_size (`int`, *optional*, defaults to 64):
219
+ The hidden size of the perceiver resampler.
220
+ perceiver_resampler_mlp_intermediate_size (`int`, *optional*, defaults to 256):
221
+ The intermediate size of the feedforward network in the perceiver resampler.
222
+ perceiver_resampler_num_attention_heads (`int`, *optional*, defaults to 1):
223
+ The number of attention heads in the perceiver resampler.
224
+ perceiver_resampler_attention_head_dim (`int`, *optional*, defaults to 64):
225
+ The dimension of each attention head in the perceiver resampler.
226
+ perceiver_resampler_num_layers (`int`, *optional*, defaults to 2):
227
+ The number of layers in the perceiver resampler.
228
+ perceiver_resampler_hidden_dropout (`float`, *optional*, defaults to 0.0):
229
+ The dropout rate for the hidden layers in the perceiver resampler.
230
+ perceiver_resampler_attention_dropout (`float`, *optional*, defaults to 0.0):
231
+ The dropout rate for the attention layers in the perceiver resampler.
232
+ memory_encoder_hidden_size (`int`, *optional*, defaults to 256):
233
+ Dimensionality of the memory encoder hidden states.
234
+ memory_encoder_output_channels (`int`, *optional*, defaults to 64):
235
+ The number of output channels for the memory encoder.
236
+ mask_downsampler_embed_dim (`int`, *optional*, defaults to 256):
237
+ The dimension of the mask downsampler embedding.
238
+ memory_fuser_intermediate_dim (`int`, *optional*, defaults to 1024):
239
+ The intermediate dimension of the memory fuser feedforward network.
240
+ mask_downsampler_kernel_size (`int`, *optional*, defaults to 3):
241
+ The kernel size for the mask downsampler.
242
+ mask_downsampler_stride (`int`, *optional*, defaults to 2):
243
+ The stride for the mask downsampler.
244
+ mask_downsampler_padding (`int`, *optional*, defaults to 1):
245
+ The padding for the mask downsampler.
246
+ mask_downsampler_total_stride (`int`, *optional*, defaults to 16):
247
+ The total stride for the mask downsampler.
248
+ mask_downsampler_hidden_act (`str`, *optional*, defaults to `"gelu"`):
249
+ The non-linear activation function in the mask downsampler.
250
+ memory_fuser_num_layers (`int`, *optional*, defaults to 2):
251
+ The number of layers in the memory fuser.
252
+ memory_fuser_embed_dim (`int`, *optional*, defaults to 256):
253
+ The dimension of the memory fuser embedding.
254
+ memory_fuser_kernel_size (`int`, *optional*, defaults to 7):
255
+ The kernel size for the memory fuser.
256
+ memory_fuser_padding (`int`, *optional*, defaults to 3):
257
+ The padding for the memory fuser.
258
+ memory_fuser_layer_scale_init_value (`float`, *optional*, defaults to 1e-06):
259
+ The initial value for the layer scale in the memory fuser.
260
+ memory_fuser_hidden_act (`str`, *optional*, defaults to `"gelu"`):
261
+ The non-linear activation function in the memory fuser.
262
+
263
+ Example:
264
+
265
+ ```python
266
+ >>> from transformers import (
267
+ ... EdgeTamVisionConfig,
268
+ ... EdgeTamVideoPromptEncoderConfig,
269
+ ... EdgeTamVideoMaskDecoderConfig,
270
+ ... EdgeTamVideoModel,
271
+ ... EdgeTamVideoConfig,
272
+ ... )
273
+
274
+ >>> # Initializing a EdgeTamVideoConfig with `"facebook/edgetam.1_hiera_tiny"` style configuration
275
+ >>> configuration = EdgeTamVideoConfig()
276
+
277
+ >>> # Initializing a EdgeTamVideoModel (with random weights) from the `"facebook/edgetam.1_hiera_tiny"` style configuration
278
+ >>> model = EdgeTamVideoModel(configuration)
279
+
280
+ >>> # Accessing the model configuration
281
+ >>> configuration = model.config
282
+
283
+ >>> # We can also initialize a EdgeTamConfig from a EdgeTamVisionConfig, EdgeTamPromptEncoderConfig, and EdgeTamMaskDecoderConfig
284
+
285
+ >>> # Initializing EDGETAM vision encoder, memory attention, and memory encoder configurations
286
+ >>> vision_config = EdgeTamVisionConfig()
287
+ >>> prompt_encoder_config = EdgeTamVideoPromptEncoderConfig()
288
+ >>> mask_decoder_config = EdgeTamVideoMaskDecoderConfig()
289
+
290
+ >>> config = EdgeTamVideoConfig(vision_config, prompt_encoder_config, mask_decoder_config)
291
+ ```"""
292
+
293
+ model_type = "edgetam_video"
294
+ sub_configs = {
295
+ "vision_config": AutoConfig,
296
+ "prompt_encoder_config": EdgeTamVideoPromptEncoderConfig,
297
+ "mask_decoder_config": EdgeTamVideoMaskDecoderConfig,
298
+ }
299
+
300
+ def __init__(
301
+ self,
302
+ vision_config=None,
303
+ prompt_encoder_config=None,
304
+ mask_decoder_config=None,
305
+ initializer_range=0.02,
306
+ num_maskmem=7,
307
+ image_size=1024,
308
+ sigmoid_scale_for_mem_enc=20.0,
309
+ sigmoid_bias_for_mem_enc=-10.0,
310
+ enable_occlusion_spatial_embedding=True,
311
+ multimask_output_in_sam=True,
312
+ multimask_min_pt_num=0,
313
+ multimask_max_pt_num=1,
314
+ multimask_output_for_tracking=True,
315
+ max_object_pointers_in_encoder=16,
316
+ enable_temporal_pos_encoding_for_object_pointers=True,
317
+ # memory attention
318
+ memory_attention_hidden_size=256,
319
+ memory_attention_num_layers=2,
320
+ memory_attention_num_attention_heads=1,
321
+ memory_attention_downsample_rate=1,
322
+ memory_attention_mlp_hidden_size=2048,
323
+ memory_attention_mlp_hidden_act="relu",
324
+ memory_attention_dropout=0.1,
325
+ memory_attention_rope_theta=10000,
326
+ memory_attention_rope_feat_sizes=None,
327
+ memory_attention_rope_k_sizes=None,
328
+ memory_attention_rope_dropout=0.1,
329
+ # spatial perceiver resampler
330
+ perceiver_resampler_num_latents=256,
331
+ perceiver_resampler_num_latents_2d=256,
332
+ perceiver_resampler_hidden_size=64,
333
+ perceiver_resampler_mlp_intermediate_size=256,
334
+ perceiver_resampler_num_attention_heads=1,
335
+ perceiver_resampler_attention_head_dim=64,
336
+ perceiver_resampler_num_layers=2,
337
+ perceiver_resampler_hidden_dropout=0.0,
338
+ perceiver_resampler_attention_dropout=0.0,
339
+ # memory encoder
340
+ memory_encoder_hidden_size=256,
341
+ memory_encoder_output_channels=64,
342
+ mask_downsampler_embed_dim=256,
343
+ memory_fuser_intermediate_dim=1024,
344
+ mask_downsampler_kernel_size=3,
345
+ mask_downsampler_stride=2,
346
+ mask_downsampler_padding=1,
347
+ mask_downsampler_total_stride=16,
348
+ mask_downsampler_hidden_act="gelu",
349
+ memory_fuser_num_layers=2,
350
+ memory_fuser_embed_dim=256,
351
+ memory_fuser_kernel_size=7,
352
+ memory_fuser_padding=3,
353
+ memory_fuser_layer_scale_init_value=1e-6,
354
+ memory_fuser_hidden_act="gelu",
355
+ **kwargs,
356
+ ):
357
+ super().__init__(**kwargs)
358
+ vision_config = vision_config if vision_config is not None else {}
359
+ prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
360
+ mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
361
+ memory_attention_rope_feat_sizes = (
362
+ [64, 64] if memory_attention_rope_feat_sizes is None else memory_attention_rope_feat_sizes
363
+ )
364
+ memory_attention_rope_k_sizes = (
365
+ [16, 16] if memory_attention_rope_k_sizes is None else memory_attention_rope_k_sizes
366
+ )
367
+
368
+ if isinstance(vision_config, dict):
369
+ vision_config["model_type"] = vision_config.get("model_type", "sam2_vision_model")
370
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
371
+ if isinstance(prompt_encoder_config, EdgeTamVideoPromptEncoderConfig):
372
+ prompt_encoder_config = prompt_encoder_config.to_dict()
373
+ if isinstance(mask_decoder_config, EdgeTamVideoMaskDecoderConfig):
374
+ mask_decoder_config = mask_decoder_config.to_dict()
375
+
376
+ self.vision_config = vision_config
377
+ self.prompt_encoder_config = EdgeTamVideoPromptEncoderConfig(**prompt_encoder_config)
378
+ self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig(**mask_decoder_config)
379
+
380
+ self.initializer_range = initializer_range
381
+ self.num_maskmem = num_maskmem # default 1 input frame + 6 previous frames
382
+ self.image_size = image_size
383
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc # scale factor for mask sigmoid prob
384
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc # bias factor for mask sigmoid prob
385
+ self.enable_occlusion_spatial_embedding = enable_occlusion_spatial_embedding
386
+ self.multimask_output_in_sam = multimask_output_in_sam
387
+ self.multimask_min_pt_num = multimask_min_pt_num
388
+ self.multimask_max_pt_num = multimask_max_pt_num
389
+ self.multimask_output_for_tracking = multimask_output_for_tracking
390
+ self.max_object_pointers_in_encoder = max_object_pointers_in_encoder
391
+ self.enable_temporal_pos_encoding_for_object_pointers = enable_temporal_pos_encoding_for_object_pointers
392
+
393
+ # memory attention
394
+ self.memory_attention_hidden_size = memory_attention_hidden_size
395
+ self.memory_attention_num_layers = memory_attention_num_layers
396
+ self.memory_attention_num_attention_heads = memory_attention_num_attention_heads
397
+ self.memory_attention_downsample_rate = memory_attention_downsample_rate
398
+ self.memory_attention_mlp_hidden_size = memory_attention_mlp_hidden_size
399
+ self.memory_attention_mlp_hidden_act = memory_attention_mlp_hidden_act
400
+ self.memory_attention_dropout = memory_attention_dropout
401
+ self.memory_attention_rope_theta = memory_attention_rope_theta
402
+ self.memory_attention_rope_feat_sizes = memory_attention_rope_feat_sizes
403
+ self.memory_attention_rope_k_sizes = memory_attention_rope_k_sizes
404
+ self.memory_attention_rope_dropout = memory_attention_rope_dropout
405
+
406
+ # spatial perceiver resampler
407
+ self.perceiver_resampler_num_latents = perceiver_resampler_num_latents
408
+ self.perceiver_resampler_num_latents_2d = perceiver_resampler_num_latents_2d
409
+ self.perceiver_resampler_hidden_size = perceiver_resampler_hidden_size
410
+ self.perceiver_resampler_mlp_intermediate_size = perceiver_resampler_mlp_intermediate_size
411
+ self.perceiver_resampler_attention_head_dim = perceiver_resampler_attention_head_dim
412
+ self.perceiver_resampler_num_attention_heads = perceiver_resampler_num_attention_heads
413
+ self.perceiver_resampler_num_layers = perceiver_resampler_num_layers
414
+ self.perceiver_resampler_hidden_dropout = perceiver_resampler_hidden_dropout
415
+ self.perceiver_resampler_attention_dropout = perceiver_resampler_attention_dropout
416
+
417
+ # memory encoder
418
+ self.memory_encoder_hidden_size = memory_encoder_hidden_size
419
+ self.memory_encoder_output_channels = memory_encoder_output_channels
420
+ self.mask_downsampler_embed_dim = mask_downsampler_embed_dim
421
+ self.mask_downsampler_kernel_size = mask_downsampler_kernel_size
422
+ self.mask_downsampler_stride = mask_downsampler_stride
423
+ self.mask_downsampler_padding = mask_downsampler_padding
424
+ self.mask_downsampler_total_stride = mask_downsampler_total_stride
425
+ self.mask_downsampler_hidden_act = mask_downsampler_hidden_act
426
+ self.memory_fuser_num_layers = memory_fuser_num_layers
427
+ self.memory_fuser_embed_dim = memory_fuser_embed_dim
428
+ self.memory_fuser_intermediate_dim = memory_fuser_intermediate_dim
429
+ self.memory_fuser_kernel_size = memory_fuser_kernel_size
430
+ self.memory_fuser_padding = memory_fuser_padding
431
+ self.memory_fuser_layer_scale_init_value = memory_fuser_layer_scale_init_value
432
+ self.memory_fuser_hidden_act = memory_fuser_hidden_act
433
+
434
+
435
+ __all__ = ["EdgeTamVideoMaskDecoderConfig", "EdgeTamVideoPromptEncoderConfig", "EdgeTamVideoConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/modeling_edgetam_video.py ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/edgetam_video/modular_edgetam_video.py ADDED
@@ -0,0 +1,1243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 the HuggingFace Team. 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
+
16
+ import math
17
+ from typing import Callable, Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.utils.checkpoint
22
+ from torch import Tensor
23
+
24
+ from transformers.models.sam2.modeling_sam2 import (
25
+ eager_attention_forward,
26
+ window_partition,
27
+ )
28
+ from transformers.utils.generic import OutputRecorder
29
+
30
+ from ...activations import ACT2FN
31
+ from ...configuration_utils import PretrainedConfig
32
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
34
+ from ...processing_utils import Unpack
35
+ from ...pytorch_utils import compile_compatible_method_lru_cache
36
+ from ...utils import (
37
+ auto_docstring,
38
+ )
39
+ from ..auto import CONFIG_MAPPING, AutoConfig
40
+ from ..sam2_video.configuration_sam2_video import (
41
+ Sam2VideoConfig,
42
+ Sam2VideoMaskDecoderConfig,
43
+ Sam2VideoPromptEncoderConfig,
44
+ )
45
+ from ..sam2_video.modeling_sam2_video import (
46
+ Sam2VideoAttention,
47
+ Sam2VideoFeedForward,
48
+ Sam2VideoInferenceSession,
49
+ Sam2VideoLayerNorm,
50
+ Sam2VideoMemoryAttention,
51
+ Sam2VideoMemoryEncoder,
52
+ Sam2VideoMemoryFuserCXBlock,
53
+ Sam2VideoModel,
54
+ Sam2VideoPositionEmbeddingSine,
55
+ Sam2VideoPreTrainedModel,
56
+ Sam2VideoTwoWayAttentionBlock,
57
+ Sam2VideoVisionEncoderOutput,
58
+ Sam2VideoVisionRotaryEmbedding,
59
+ rotate_pairwise,
60
+ )
61
+
62
+
63
+ class EdgeTamVideoPromptEncoderConfig(Sam2VideoPromptEncoderConfig):
64
+ pass
65
+
66
+
67
+ class EdgeTamVideoMaskDecoderConfig(Sam2VideoMaskDecoderConfig):
68
+ pass
69
+
70
+
71
+ class EdgeTamVideoConfig(Sam2VideoConfig):
72
+ r"""
73
+ [`EdgeTamVideoConfig`] is the configuration class to store the configuration of a [`EdgeTamVideoModel`]. It is used to instantiate a
74
+ EDGETAM model according to the specified arguments, defining the memory attention, memory encoder, and image encoder
75
+ configs. Instantiating a configuration defaults will yield a similar configuration to that of the SAM 2.1 Hiera-tiny
76
+ [facebook/EdgeTAM](https://huggingface.co/facebook/EdgeTAM) architecture.
77
+
78
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
79
+ documentation from [`PretrainedConfig`] for more information.
80
+
81
+ Args:
82
+ vision_config (Union[`dict`, `EdgeTamVideoVisionConfig`], *optional*):
83
+ Dictionary of configuration options used to initialize [`EdgeTamVideoVisionConfig`].
84
+ prompt_encoder_config (Union[`dict`, `EdgeTamVideoPromptEncoderConfig`], *optional*):
85
+ Dictionary of configuration options used to initialize [`EdgeTamVideoPromptEncoderConfig`].
86
+ mask_decoder_config (Union[`dict`, `EdgeTamVideoMaskDecoderConfig`], *optional*):
87
+ Dictionary of configuration options used to initialize [`EdgeTamMaskDecoderConfig`].
88
+ initializer_range (`float`, *optional*, defaults to 0.02):
89
+ Standard deviation for parameter initialization.
90
+ num_maskmem (`int`, *optional*, defaults to 7):
91
+ The number of memory slots for the mask memory.
92
+ image_size (`int`, *optional*, defaults to 1024):
93
+ The size of the input images.
94
+ sigmoid_scale_for_mem_enc (`float`, *optional*, defaults to 20.0):
95
+ Scale factor for the sigmoid function in the memory encoder.
96
+ sigmoid_bias_for_mem_enc (`float`, *optional*, defaults to -10.0):
97
+ Bias for the sigmoid function in the memory encoder.
98
+ enable_occlusion_spatial_embedding (`bool`, *optional*, defaults to `True`):
99
+ Whether to enable spatial embedding for occlusions.
100
+ multimask_output_in_sam (`bool`, *optional*, defaults to `True`):
101
+ Whether to output multiple masks from the SAM head.
102
+ multimask_min_pt_num (`int`, *optional*, defaults to 0):
103
+ The minimum number of points to trigger multimask output.
104
+ multimask_max_pt_num (`int`, *optional*, defaults to 1):
105
+ The maximum number of points to trigger multimask output.
106
+ multimask_output_for_tracking (`bool`, *optional*, defaults to `True`):
107
+ Whether to use multimask output for tracking.
108
+ max_object_pointers_in_encoder (`int`, *optional*, defaults to 16):
109
+ The maximum number of object pointers in the encoder.
110
+ enable_temporal_pos_encoding_for_object_pointers (`bool`, *optional*, defaults to `True`):
111
+ Whether to enable temporal positional encoding for object pointers.
112
+ memory_attention_hidden_size (`int`, *optional*, defaults to 256):
113
+ Dimensionality of the memory attention hidden states.
114
+ memory_attention_num_layers (`int`, *optional*, defaults to 2):
115
+ The number of layers in the memory attention module.
116
+ memory_attention_num_attention_heads (`int`, *optional*, defaults to 1):
117
+ Number of attention heads for each attention layer in the memory attention.
118
+ memory_attention_downsample_rate (`int`, *optional*, defaults to 1):
119
+ The downsample rate for the attention layers.
120
+ memory_attention_mlp_hidden_size (`int`, *optional*, defaults to 2048):
121
+ The dimension of the feedforward network in the memory attention module.
122
+ memory_attention_mlp_hidden_act (`str`, *optional*, defaults to `"relu"`):
123
+ The non-linear activation function in the feedforward network in the memory attention module.
124
+ memory_attention_dropout (`float`, *optional*, defaults to 0.1):
125
+ The dropout rate for the memory attention module.
126
+ memory_attention_rope_theta (`float`, *optional*, defaults to 10000):
127
+ The Rope theta parameter.
128
+ memory_attention_rope_feat_sizes (`Tuple[int, int]`, *optional*, defaults to `[64, 64]`):
129
+ The feature sizes for the Rope positional encoding.
130
+ memory_attention_rope_k_sizes (`List[int]`, *optional*, defaults to `[16, 16]`):
131
+ The key feature sizes for the RoPE positional encoding in memory attention.
132
+ memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1):
133
+ The dropout rate for the Rope positional encoding.
134
+ perceiver_resampler_num_latents (`int`, *optional*, defaults to 256):
135
+ The number of 1D latent tokens in the perceiver resampler.
136
+ perceiver_resampler_num_latents_2d (`int`, *optional*, defaults to 256):
137
+ The number of 2D latent tokens in the perceiver resampler.
138
+ perceiver_resampler_hidden_size (`int`, *optional*, defaults to 64):
139
+ The hidden size of the perceiver resampler.
140
+ perceiver_resampler_mlp_intermediate_size (`int`, *optional*, defaults to 256):
141
+ The intermediate size of the feedforward network in the perceiver resampler.
142
+ perceiver_resampler_num_attention_heads (`int`, *optional*, defaults to 1):
143
+ The number of attention heads in the perceiver resampler.
144
+ perceiver_resampler_attention_head_dim (`int`, *optional*, defaults to 64):
145
+ The dimension of each attention head in the perceiver resampler.
146
+ perceiver_resampler_num_layers (`int`, *optional*, defaults to 2):
147
+ The number of layers in the perceiver resampler.
148
+ perceiver_resampler_hidden_dropout (`float`, *optional*, defaults to 0.0):
149
+ The dropout rate for the hidden layers in the perceiver resampler.
150
+ perceiver_resampler_attention_dropout (`float`, *optional*, defaults to 0.0):
151
+ The dropout rate for the attention layers in the perceiver resampler.
152
+ memory_encoder_hidden_size (`int`, *optional*, defaults to 256):
153
+ Dimensionality of the memory encoder hidden states.
154
+ memory_encoder_output_channels (`int`, *optional*, defaults to 64):
155
+ The number of output channels for the memory encoder.
156
+ mask_downsampler_embed_dim (`int`, *optional*, defaults to 256):
157
+ The dimension of the mask downsampler embedding.
158
+ memory_fuser_intermediate_dim (`int`, *optional*, defaults to 1024):
159
+ The intermediate dimension of the memory fuser feedforward network.
160
+ mask_downsampler_kernel_size (`int`, *optional*, defaults to 3):
161
+ The kernel size for the mask downsampler.
162
+ mask_downsampler_stride (`int`, *optional*, defaults to 2):
163
+ The stride for the mask downsampler.
164
+ mask_downsampler_padding (`int`, *optional*, defaults to 1):
165
+ The padding for the mask downsampler.
166
+ mask_downsampler_total_stride (`int`, *optional*, defaults to 16):
167
+ The total stride for the mask downsampler.
168
+ mask_downsampler_hidden_act (`str`, *optional*, defaults to `"gelu"`):
169
+ The non-linear activation function in the mask downsampler.
170
+ memory_fuser_num_layers (`int`, *optional*, defaults to 2):
171
+ The number of layers in the memory fuser.
172
+ memory_fuser_embed_dim (`int`, *optional*, defaults to 256):
173
+ The dimension of the memory fuser embedding.
174
+ memory_fuser_kernel_size (`int`, *optional*, defaults to 7):
175
+ The kernel size for the memory fuser.
176
+ memory_fuser_padding (`int`, *optional*, defaults to 3):
177
+ The padding for the memory fuser.
178
+ memory_fuser_layer_scale_init_value (`float`, *optional*, defaults to 1e-06):
179
+ The initial value for the layer scale in the memory fuser.
180
+ memory_fuser_hidden_act (`str`, *optional*, defaults to `"gelu"`):
181
+ The non-linear activation function in the memory fuser.
182
+
183
+ Example:
184
+
185
+ ```python
186
+ >>> from transformers import (
187
+ ... EdgeTamVisionConfig,
188
+ ... EdgeTamVideoPromptEncoderConfig,
189
+ ... EdgeTamVideoMaskDecoderConfig,
190
+ ... EdgeTamVideoModel,
191
+ ... EdgeTamVideoConfig,
192
+ ... )
193
+
194
+ >>> # Initializing a EdgeTamVideoConfig with `"facebook/edgetam.1_hiera_tiny"` style configuration
195
+ >>> configuration = EdgeTamVideoConfig()
196
+
197
+ >>> # Initializing a EdgeTamVideoModel (with random weights) from the `"facebook/edgetam.1_hiera_tiny"` style configuration
198
+ >>> model = EdgeTamVideoModel(configuration)
199
+
200
+ >>> # Accessing the model configuration
201
+ >>> configuration = model.config
202
+
203
+ >>> # We can also initialize a EdgeTamConfig from a EdgeTamVisionConfig, EdgeTamPromptEncoderConfig, and EdgeTamMaskDecoderConfig
204
+
205
+ >>> # Initializing EDGETAM vision encoder, memory attention, and memory encoder configurations
206
+ >>> vision_config = EdgeTamVisionConfig()
207
+ >>> prompt_encoder_config = EdgeTamVideoPromptEncoderConfig()
208
+ >>> mask_decoder_config = EdgeTamVideoMaskDecoderConfig()
209
+
210
+ >>> config = EdgeTamVideoConfig(vision_config, prompt_encoder_config, mask_decoder_config)
211
+ ```"""
212
+
213
+ model_type = "edgetam_video"
214
+ sub_configs = {
215
+ "vision_config": AutoConfig,
216
+ "prompt_encoder_config": EdgeTamVideoPromptEncoderConfig,
217
+ "mask_decoder_config": EdgeTamVideoMaskDecoderConfig,
218
+ }
219
+
220
+ def __init__(
221
+ self,
222
+ vision_config=None,
223
+ prompt_encoder_config=None,
224
+ mask_decoder_config=None,
225
+ initializer_range=0.02,
226
+ num_maskmem=7,
227
+ image_size=1024,
228
+ sigmoid_scale_for_mem_enc=20.0,
229
+ sigmoid_bias_for_mem_enc=-10.0,
230
+ enable_occlusion_spatial_embedding=True,
231
+ multimask_output_in_sam=True,
232
+ multimask_min_pt_num=0,
233
+ multimask_max_pt_num=1,
234
+ multimask_output_for_tracking=True,
235
+ max_object_pointers_in_encoder=16,
236
+ enable_temporal_pos_encoding_for_object_pointers=True,
237
+ # memory attention
238
+ memory_attention_hidden_size=256,
239
+ memory_attention_num_layers=2,
240
+ memory_attention_num_attention_heads=1,
241
+ memory_attention_downsample_rate=1,
242
+ memory_attention_mlp_hidden_size=2048,
243
+ memory_attention_mlp_hidden_act="relu",
244
+ memory_attention_dropout=0.1,
245
+ memory_attention_rope_theta=10000,
246
+ memory_attention_rope_feat_sizes=None,
247
+ memory_attention_rope_k_sizes=None,
248
+ memory_attention_rope_dropout=0.1,
249
+ # spatial perceiver resampler
250
+ perceiver_resampler_num_latents=256,
251
+ perceiver_resampler_num_latents_2d=256,
252
+ perceiver_resampler_hidden_size=64,
253
+ perceiver_resampler_mlp_intermediate_size=256,
254
+ perceiver_resampler_num_attention_heads=1,
255
+ perceiver_resampler_attention_head_dim=64,
256
+ perceiver_resampler_num_layers=2,
257
+ perceiver_resampler_hidden_dropout=0.0,
258
+ perceiver_resampler_attention_dropout=0.0,
259
+ # memory encoder
260
+ memory_encoder_hidden_size=256,
261
+ memory_encoder_output_channels=64,
262
+ mask_downsampler_embed_dim=256,
263
+ memory_fuser_intermediate_dim=1024,
264
+ mask_downsampler_kernel_size=3,
265
+ mask_downsampler_stride=2,
266
+ mask_downsampler_padding=1,
267
+ mask_downsampler_total_stride=16,
268
+ mask_downsampler_hidden_act="gelu",
269
+ memory_fuser_num_layers=2,
270
+ memory_fuser_embed_dim=256,
271
+ memory_fuser_kernel_size=7,
272
+ memory_fuser_padding=3,
273
+ memory_fuser_layer_scale_init_value=1e-6,
274
+ memory_fuser_hidden_act="gelu",
275
+ **kwargs,
276
+ ):
277
+ PretrainedConfig.__init__(**kwargs)
278
+ vision_config = vision_config if vision_config is not None else {}
279
+ prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
280
+ mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
281
+ memory_attention_rope_feat_sizes = (
282
+ [64, 64] if memory_attention_rope_feat_sizes is None else memory_attention_rope_feat_sizes
283
+ )
284
+ memory_attention_rope_k_sizes = (
285
+ [16, 16] if memory_attention_rope_k_sizes is None else memory_attention_rope_k_sizes
286
+ )
287
+
288
+ if isinstance(vision_config, dict):
289
+ vision_config["model_type"] = vision_config.get("model_type", "sam2_vision_model")
290
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
291
+ if isinstance(prompt_encoder_config, EdgeTamVideoPromptEncoderConfig):
292
+ prompt_encoder_config = prompt_encoder_config.to_dict()
293
+ if isinstance(mask_decoder_config, EdgeTamVideoMaskDecoderConfig):
294
+ mask_decoder_config = mask_decoder_config.to_dict()
295
+
296
+ self.vision_config = vision_config
297
+ self.prompt_encoder_config = EdgeTamVideoPromptEncoderConfig(**prompt_encoder_config)
298
+ self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig(**mask_decoder_config)
299
+
300
+ self.initializer_range = initializer_range
301
+ self.num_maskmem = num_maskmem # default 1 input frame + 6 previous frames
302
+ self.image_size = image_size
303
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc # scale factor for mask sigmoid prob
304
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc # bias factor for mask sigmoid prob
305
+ self.enable_occlusion_spatial_embedding = enable_occlusion_spatial_embedding
306
+ self.multimask_output_in_sam = multimask_output_in_sam
307
+ self.multimask_min_pt_num = multimask_min_pt_num
308
+ self.multimask_max_pt_num = multimask_max_pt_num
309
+ self.multimask_output_for_tracking = multimask_output_for_tracking
310
+ self.max_object_pointers_in_encoder = max_object_pointers_in_encoder
311
+ self.enable_temporal_pos_encoding_for_object_pointers = enable_temporal_pos_encoding_for_object_pointers
312
+
313
+ # memory attention
314
+ self.memory_attention_hidden_size = memory_attention_hidden_size
315
+ self.memory_attention_num_layers = memory_attention_num_layers
316
+ self.memory_attention_num_attention_heads = memory_attention_num_attention_heads
317
+ self.memory_attention_downsample_rate = memory_attention_downsample_rate
318
+ self.memory_attention_mlp_hidden_size = memory_attention_mlp_hidden_size
319
+ self.memory_attention_mlp_hidden_act = memory_attention_mlp_hidden_act
320
+ self.memory_attention_dropout = memory_attention_dropout
321
+ self.memory_attention_rope_theta = memory_attention_rope_theta
322
+ self.memory_attention_rope_feat_sizes = memory_attention_rope_feat_sizes
323
+ self.memory_attention_rope_k_sizes = memory_attention_rope_k_sizes
324
+ self.memory_attention_rope_dropout = memory_attention_rope_dropout
325
+
326
+ # spatial perceiver resampler
327
+ self.perceiver_resampler_num_latents = perceiver_resampler_num_latents
328
+ self.perceiver_resampler_num_latents_2d = perceiver_resampler_num_latents_2d
329
+ self.perceiver_resampler_hidden_size = perceiver_resampler_hidden_size
330
+ self.perceiver_resampler_mlp_intermediate_size = perceiver_resampler_mlp_intermediate_size
331
+ self.perceiver_resampler_attention_head_dim = perceiver_resampler_attention_head_dim
332
+ self.perceiver_resampler_num_attention_heads = perceiver_resampler_num_attention_heads
333
+ self.perceiver_resampler_num_layers = perceiver_resampler_num_layers
334
+ self.perceiver_resampler_hidden_dropout = perceiver_resampler_hidden_dropout
335
+ self.perceiver_resampler_attention_dropout = perceiver_resampler_attention_dropout
336
+
337
+ # memory encoder
338
+ self.memory_encoder_hidden_size = memory_encoder_hidden_size
339
+ self.memory_encoder_output_channels = memory_encoder_output_channels
340
+ self.mask_downsampler_embed_dim = mask_downsampler_embed_dim
341
+ self.mask_downsampler_kernel_size = mask_downsampler_kernel_size
342
+ self.mask_downsampler_stride = mask_downsampler_stride
343
+ self.mask_downsampler_padding = mask_downsampler_padding
344
+ self.mask_downsampler_total_stride = mask_downsampler_total_stride
345
+ self.mask_downsampler_hidden_act = mask_downsampler_hidden_act
346
+ self.memory_fuser_num_layers = memory_fuser_num_layers
347
+ self.memory_fuser_embed_dim = memory_fuser_embed_dim
348
+ self.memory_fuser_intermediate_dim = memory_fuser_intermediate_dim
349
+ self.memory_fuser_kernel_size = memory_fuser_kernel_size
350
+ self.memory_fuser_padding = memory_fuser_padding
351
+ self.memory_fuser_layer_scale_init_value = memory_fuser_layer_scale_init_value
352
+ self.memory_fuser_hidden_act = memory_fuser_hidden_act
353
+
354
+
355
+ class EdgeTamVideoLayerNorm(Sam2VideoLayerNorm):
356
+ pass
357
+
358
+
359
+ class EdgeTamVideoMemoryFuserCXBlock(Sam2VideoMemoryFuserCXBlock):
360
+ pass
361
+
362
+
363
+ class EdgeTamVideoVisionEncoderOutput(Sam2VideoVisionEncoderOutput):
364
+ pass
365
+
366
+
367
+ class EdgeTamVideoVisionRotaryEmbedding(Sam2VideoVisionRotaryEmbedding):
368
+ def __init__(self, config: EdgeTamVideoConfig, end_x: Optional[int] = None, end_y: Optional[int] = None):
369
+ nn.Module.__init__()
370
+ dim = config.memory_attention_hidden_size // (
371
+ config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads
372
+ )
373
+ # Ensure even dimension for proper axial splitting
374
+ if dim % 4 != 0:
375
+ raise ValueError("Dimension must be divisible by 4 for axial RoPE")
376
+ end_x, end_y = config.memory_attention_rope_feat_sizes if end_x is None else (end_x, end_y)
377
+ freqs = 1.0 / (config.memory_attention_rope_theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
378
+
379
+ # Generate 2D position indices for axial rotary embedding
380
+ flattened_indices = torch.arange(end_x * end_y, dtype=torch.long)
381
+ x_positions = flattened_indices % end_x
382
+ y_positions = torch.div(flattened_indices, end_x, rounding_mode="floor")
383
+ freqs_x = torch.outer(x_positions, freqs).float()
384
+ freqs_y = torch.outer(y_positions, freqs).float()
385
+ inv_freq = torch.cat([freqs_x, freqs_y], dim=-1)
386
+ inv_freq = inv_freq.repeat_interleave(2, dim=-1)
387
+ # directly register the cos and sin embeddings as we have a fixed feature shape
388
+ self.register_buffer("rope_embeddings_cos", inv_freq.cos(), persistent=False)
389
+ self.register_buffer("rope_embeddings_sin", inv_freq.sin(), persistent=False)
390
+
391
+
392
+ class EdgeTamVideoAttention(Sam2VideoAttention):
393
+ pass
394
+
395
+
396
+ def apply_rotary_pos_emb_2d_self_attn(
397
+ q: torch.Tensor,
398
+ k: torch.Tensor,
399
+ cos: torch.Tensor,
400
+ sin: torch.Tensor,
401
+ ) -> tuple[torch.Tensor, torch.Tensor]:
402
+ """
403
+ Apply rotary position embedding to query and key tensors for self-attention.
404
+
405
+ Args:
406
+ q: Query tensor of shape (..., seq_len, head_dim)
407
+ k: Key tensor of shape (..., seq_len, head_dim)
408
+ cos: Cosine position embedding of shape (seq_len, head_dim)
409
+ sin: Sine position embedding of shape (seq_len, head_dim)
410
+
411
+ Returns:
412
+ Rotated (q, k) tensors
413
+ """
414
+ # Apply RoPE to queries
415
+ q_embed = q.float() # force upscale to float32 as in the original implementation
416
+ q_embed = (q_embed * cos) + (rotate_pairwise(q_embed) * sin)
417
+
418
+ # Apply RoPE to keys (same embeddings as queries for self-attention)
419
+ k_embed = k.float() # force upscale to float32 as in the original implementation
420
+ k_embed = (k_embed * cos) + (rotate_pairwise(k_embed) * sin)
421
+
422
+ return q_embed.type_as(q), k_embed.type_as(k)
423
+
424
+
425
+ def apply_rotary_pos_emb_2d_cross_attn(
426
+ q: torch.Tensor,
427
+ k: torch.Tensor,
428
+ cos: torch.Tensor,
429
+ sin: torch.Tensor,
430
+ cos_k: torch.Tensor,
431
+ sin_k: torch.Tensor,
432
+ num_k_exclude_rope: int = 0,
433
+ repeat_freqs_k: int = 1,
434
+ ) -> tuple[torch.Tensor, torch.Tensor]:
435
+ """
436
+ Apply rotary position embedding to query and key tensors for cross-attention.
437
+
438
+ Args:
439
+ q: Query tensor of shape (..., seq_len, head_dim)
440
+ k: Key tensor of shape (..., seq_len, head_dim)
441
+ cos: Cosine position embedding of shape (seq_len, head_dim)
442
+ sin: Sine position embedding of shape (seq_len, head_dim)
443
+ cos_k: Cosine position embedding for keys of shape (seq_len, head_dim)
444
+ sin_k: Sine position embedding for keys of shape (seq_len, head_dim)
445
+ num_k_exclude_rope: Number of tokens at end of k to exclude from RoPE (e.g., object pointer tokens)
446
+ repeat_freqs_k: Frequency repetition for keys in cross-attention (e.g., for spatial memory tokens)
447
+
448
+ Returns:
449
+ Rotated (q, k) tensors
450
+ """
451
+ # Apply RoPE to queries (always straightforward)
452
+ q_embed = q.float()
453
+ q_embed = (q_embed * cos) + (rotate_pairwise(q_embed) * sin)
454
+
455
+ # Split keys: RoPE tokens and excluded tokens (e.g., object pointers)
456
+ num_total_k_tokens = k.shape[-2]
457
+ k_for_rope = k[..., : num_total_k_tokens - num_k_exclude_rope, :]
458
+ k_excluded = k[..., num_total_k_tokens - num_k_exclude_rope :, :]
459
+
460
+ # Early return if no keys need RoPE
461
+ if k_for_rope.shape[-2] == 0:
462
+ return q_embed.type_as(q), k_excluded
463
+
464
+ batch_size, num_heads, k_seq_len, channels_per_head = k_for_rope.shape
465
+
466
+ # Handle temporal/spatial token structure for memory
467
+ # Keys have temporal + spatial structure, only spatial tokens get RoPE
468
+ tokens_per_group = k_seq_len // repeat_freqs_k
469
+ spatial_tokens = cos_k.shape[-2]
470
+ temporal_tokens = tokens_per_group - spatial_tokens
471
+
472
+ # Reshape and separate temporal/spatial tokens
473
+ k_grouped = k_for_rope.view(batch_size, num_heads, repeat_freqs_k, tokens_per_group, channels_per_head)
474
+ k_temporal = k_grouped[..., :temporal_tokens, :].reshape(batch_size, num_heads, -1, channels_per_head)
475
+ k_spatial = k_grouped[..., temporal_tokens:, :].reshape(batch_size, num_heads, -1, channels_per_head)
476
+
477
+ # Only apply RoPE to spatial tokens
478
+ k_rope_input = k_spatial
479
+
480
+ # Prepare position embeddings for repeated groups
481
+ if repeat_freqs_k > 1:
482
+ cos_k = cos_k.repeat(1, 1, repeat_freqs_k, 1)
483
+ sin_k = sin_k.repeat(1, 1, repeat_freqs_k, 1)
484
+
485
+ # Apply RoPE to spatial tokens
486
+ k_spatial_embed = k_rope_input.float()
487
+ k_spatial_embed = (k_spatial_embed * cos_k) + (rotate_pairwise(k_spatial_embed) * sin_k)
488
+
489
+ # Reconstruct: temporal + spatial tokens back to original structure
490
+ k_spatial_reshaped = k_spatial_embed.view(batch_size, num_heads, repeat_freqs_k, -1, channels_per_head)
491
+ k_temporal_reshaped = k_temporal.view(batch_size, num_heads, repeat_freqs_k, -1, channels_per_head)
492
+ k_final = torch.cat([k_temporal_reshaped, k_spatial_reshaped], dim=3)
493
+ k_final = k_final.view(batch_size, num_heads, k_seq_len, channels_per_head)
494
+
495
+ # Combine RoPE-processed keys with excluded tokens
496
+ k_embed = torch.cat([k_final.type_as(k), k_excluded], dim=-2)
497
+ return q_embed.type_as(q), k_embed
498
+
499
+
500
+ class EdgeTamVideoRoPESelfAttention(nn.Module):
501
+ """Self-attention with rotary position encoding."""
502
+
503
+ def __init__(self, config: EdgeTamVideoConfig):
504
+ super().__init__()
505
+ self.config = config
506
+ self.hidden_size = config.memory_attention_hidden_size
507
+ self.internal_dim = self.hidden_size // config.memory_attention_downsample_rate
508
+ self.num_attention_heads = config.memory_attention_num_attention_heads
509
+ self.head_dim = self.internal_dim // config.memory_attention_num_attention_heads
510
+ self.scaling = self.head_dim**-0.5
511
+ self.is_causal = False
512
+
513
+ self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
514
+ self.k_proj = nn.Linear(self.hidden_size, self.internal_dim)
515
+ self.v_proj = nn.Linear(self.hidden_size, self.internal_dim)
516
+ self.o_proj = nn.Linear(self.internal_dim, self.hidden_size)
517
+ self.dropout_p = config.memory_attention_rope_dropout
518
+
519
+ def forward(
520
+ self,
521
+ query: torch.Tensor,
522
+ key: torch.Tensor,
523
+ value: torch.Tensor,
524
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
525
+ **kwargs: Unpack[FlashAttentionKwargs],
526
+ ) -> Tensor:
527
+ # Input projections
528
+ batch_size, point_batch_size = query.shape[:2]
529
+ new_shape = (batch_size * point_batch_size, -1, self.num_attention_heads, self.head_dim)
530
+
531
+ query = self.q_proj(query).view(*new_shape).transpose(1, 2)
532
+ key = self.k_proj(key).view(*new_shape).transpose(1, 2)
533
+ value = self.v_proj(value).view(*new_shape).transpose(1, 2)
534
+
535
+ cos, sin = position_embeddings
536
+ # Apply rotary position encoding for self-attention
537
+ query, key = apply_rotary_pos_emb_2d_self_attn(query, key, cos=cos, sin=sin)
538
+
539
+ attention_interface: Callable = eager_attention_forward
540
+ if self.config._attn_implementation != "eager":
541
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
542
+
543
+ attn_output, attn_weights = attention_interface(
544
+ self,
545
+ query,
546
+ key,
547
+ value,
548
+ attention_mask=None,
549
+ dropout=0.0 if not self.training else self.dropout_p,
550
+ scaling=self.scaling,
551
+ is_causal=self.is_causal,
552
+ **kwargs,
553
+ )
554
+ attn_output = attn_output.reshape(
555
+ batch_size, point_batch_size, -1, self.num_attention_heads * self.head_dim
556
+ ).contiguous()
557
+ attn_output = self.o_proj(attn_output)
558
+ return attn_output, attn_weights
559
+
560
+
561
+ class EdgeTamVideoRoPECrossAttention(nn.Module):
562
+ """Cross-attention with rotary position encoding."""
563
+
564
+ def __init__(self, config: EdgeTamVideoConfig, kv_in_dim: int):
565
+ super().__init__()
566
+ self.config = config
567
+ self.hidden_size = config.memory_attention_hidden_size
568
+ self.internal_dim = self.hidden_size // config.memory_attention_downsample_rate
569
+ self.num_attention_heads = config.memory_attention_num_attention_heads
570
+ self.head_dim = self.internal_dim // config.memory_attention_num_attention_heads
571
+ self.scaling = self.head_dim**-0.5
572
+ self.is_causal = False
573
+
574
+ self.kv_in_dim = kv_in_dim
575
+
576
+ self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
577
+ self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
578
+ self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
579
+ self.o_proj = nn.Linear(self.internal_dim, self.hidden_size)
580
+ self.dropout_p = config.memory_attention_rope_dropout
581
+
582
+ def forward(
583
+ self,
584
+ query: torch.Tensor,
585
+ key: torch.Tensor,
586
+ value: torch.Tensor,
587
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
588
+ position_embeddings_k: tuple[torch.Tensor, torch.Tensor],
589
+ num_k_exclude_rope: int = 0,
590
+ rope_k_repeat: int = 0,
591
+ **kwargs: Unpack[FlashAttentionKwargs],
592
+ ) -> Tensor:
593
+ # Input projections
594
+ batch_size, point_batch_size = query.shape[:2]
595
+ new_shape = (batch_size * point_batch_size, -1, self.num_attention_heads, self.head_dim)
596
+
597
+ query = self.q_proj(query).view(*new_shape).transpose(1, 2)
598
+ key = self.k_proj(key).view(*new_shape).transpose(1, 2)
599
+ value = self.v_proj(value).view(*new_shape).transpose(1, 2)
600
+
601
+ cos, sin = position_embeddings
602
+ cos_k, sin_k = position_embeddings_k
603
+ # Apply rotary position encoding for cross-attention
604
+ query, key = apply_rotary_pos_emb_2d_cross_attn(
605
+ query,
606
+ key,
607
+ cos=cos,
608
+ sin=sin,
609
+ cos_k=cos_k,
610
+ sin_k=sin_k,
611
+ repeat_freqs_k=rope_k_repeat,
612
+ num_k_exclude_rope=num_k_exclude_rope,
613
+ )
614
+
615
+ attention_interface: Callable = eager_attention_forward
616
+ if self.config._attn_implementation != "eager":
617
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
618
+
619
+ attn_output, attn_weights = attention_interface(
620
+ self,
621
+ query,
622
+ key,
623
+ value,
624
+ attention_mask=None,
625
+ dropout=0.0 if not self.training else self.dropout_p,
626
+ scaling=self.scaling,
627
+ is_causal=self.is_causal,
628
+ **kwargs,
629
+ )
630
+ attn_output = attn_output.reshape(
631
+ batch_size, point_batch_size, -1, self.num_attention_heads * self.head_dim
632
+ ).contiguous()
633
+ attn_output = self.o_proj(attn_output)
634
+ return attn_output, attn_weights
635
+
636
+
637
+ class EdgeTamVideoTwoWayAttentionBlock(Sam2VideoTwoWayAttentionBlock):
638
+ pass
639
+
640
+
641
+ class EdgeTamVideoPositionEmbeddingSine(Sam2VideoPositionEmbeddingSine):
642
+ # maxsize=2 because we need to cache the forward method for both memory encoder and perceiver resampler
643
+ @compile_compatible_method_lru_cache(maxsize=2)
644
+ def forward(self, **super_kwargs):
645
+ return super().forward(**super_kwargs)
646
+
647
+
648
+ class EdgeTamVideoMemoryEncoder(Sam2VideoMemoryEncoder):
649
+ pass
650
+
651
+
652
+ class EdgeTamVideoFeedForward(Sam2VideoFeedForward):
653
+ pass
654
+
655
+
656
+ class EdgeTamVideoPreTrainedModel(Sam2VideoPreTrainedModel):
657
+ pass
658
+
659
+
660
+ class EdgeTamVideoInferenceSession(Sam2VideoInferenceSession):
661
+ pass
662
+
663
+
664
+ class EdgeTamVideoMemoryAttentionMLP(nn.Module):
665
+ def __init__(self, config: EdgeTamVideoConfig):
666
+ super().__init__()
667
+ self.config = config
668
+ self.hidden_size = config.memory_attention_hidden_size
669
+ self.intermediate_size = config.memory_attention_mlp_hidden_size
670
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size)
671
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size)
672
+ self.dropout = nn.Dropout(config.memory_attention_dropout)
673
+ self.act_fn = ACT2FN[config.memory_attention_mlp_hidden_act]
674
+
675
+ def forward(self, x):
676
+ return self.down_proj(self.dropout(self.act_fn(self.up_proj(x))))
677
+
678
+
679
+ class EdgeTamVideoMemoryAttentionLayer(nn.Module):
680
+ def __init__(self, config: EdgeTamVideoConfig):
681
+ super().__init__()
682
+ hidden_size = config.memory_attention_hidden_size
683
+ self.self_attn = EdgeTamVideoRoPESelfAttention(config)
684
+ self.cross_attn_image = EdgeTamVideoRoPECrossAttention(config, kv_in_dim=64)
685
+
686
+ # MLP module
687
+ self.mlp = EdgeTamVideoMemoryAttentionMLP(config)
688
+
689
+ self.layer_norm1 = nn.LayerNorm(hidden_size)
690
+ self.layer_norm2 = nn.LayerNorm(hidden_size)
691
+ self.layer_norm3 = nn.LayerNorm(hidden_size)
692
+ self.dropout1 = nn.Dropout(config.memory_attention_dropout)
693
+ self.dropout2 = nn.Dropout(config.memory_attention_dropout)
694
+ self.dropout3 = nn.Dropout(config.memory_attention_dropout)
695
+
696
+ def forward(
697
+ self,
698
+ queries: Tensor,
699
+ keys: Tensor,
700
+ key_point_embedding: Tensor,
701
+ rope_position_embeddings: tuple[Tensor, Tensor],
702
+ rope_position_embeddings_k: Optional[tuple[Tensor, Tensor]] = None,
703
+ num_k_exclude_rope: int = 0,
704
+ rope_k_repeat: int = 0,
705
+ ) -> torch.Tensor:
706
+ # Self-Attention
707
+ query = self.layer_norm1(queries)
708
+ query, _ = self.self_attn(query=query, key=query, value=query, position_embeddings=rope_position_embeddings)
709
+ queries = queries + self.dropout1(query)
710
+
711
+ # Cross-Attention
712
+ query = self.layer_norm2(queries)
713
+ query, _ = self.cross_attn_image(
714
+ query=query,
715
+ key=keys + key_point_embedding,
716
+ value=keys,
717
+ position_embeddings=rope_position_embeddings,
718
+ position_embeddings_k=rope_position_embeddings_k,
719
+ num_k_exclude_rope=num_k_exclude_rope,
720
+ rope_k_repeat=rope_k_repeat,
721
+ )
722
+ queries = queries + self.dropout2(query)
723
+ # MLP
724
+ query = self.layer_norm3(queries)
725
+ query = self.mlp(query)
726
+ queries = queries + self.dropout3(query)
727
+ return queries
728
+
729
+
730
+ class EdgeTamVideoMemoryAttention(Sam2VideoMemoryAttention):
731
+ def __init__(self, config: EdgeTamVideoConfig):
732
+ super().__init__()
733
+ self.rotary_emb_k = EdgeTamVideoVisionRotaryEmbedding(
734
+ config, end_x=config.memory_attention_rope_k_sizes[0], end_y=config.memory_attention_rope_k_sizes[1]
735
+ )
736
+
737
+ def forward(
738
+ self,
739
+ current_vision_features: torch.Tensor,
740
+ memory: torch.Tensor,
741
+ current_vision_position_embeddings: Optional[Tensor] = None,
742
+ memory_posision_embeddings: Optional[Tensor] = None,
743
+ num_object_pointer_tokens: int = 0,
744
+ num_spatial_memory_tokens: int = -1,
745
+ ):
746
+ """
747
+ Args:
748
+ current_vision_features (`torch.FloatTensor`):
749
+ The current vision features used for self-attention.
750
+ memory (`torch.FloatTensor`):
751
+ The memory features used for cross-attention.
752
+ current_vision_position_embeddings (`torch.FloatTensor`, *optional*):
753
+ The position embeddings for the current vision features.
754
+ memory_posision_embeddings (`torch.FloatTensor`, *optional*):
755
+ The position embeddings for the memory features.
756
+ num_object_pointer_tokens (`int`, *optional*, defaults to 0):
757
+ The number of object pointer tokens.
758
+ """
759
+ output = current_vision_features
760
+ if current_vision_position_embeddings is not None:
761
+ output = output + 0.1 * current_vision_position_embeddings
762
+
763
+ # Convert to batch first
764
+ output = output.transpose(0, 1)
765
+ memory = memory.transpose(0, 1).unsqueeze(1)
766
+ memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1)
767
+ rope_position_embeddings = self.rotary_emb()
768
+ rope_position_embeddings_k = self.rotary_emb_k()
769
+ for layer in self.layers:
770
+ output = layer(
771
+ queries=output.unsqueeze(1) if output.ndim == 3 else output,
772
+ keys=memory,
773
+ key_point_embedding=memory_posision_embeddings,
774
+ rope_position_embeddings=rope_position_embeddings,
775
+ rope_position_embeddings_k=rope_position_embeddings_k,
776
+ num_k_exclude_rope=num_object_pointer_tokens,
777
+ rope_k_repeat=num_spatial_memory_tokens,
778
+ )
779
+
780
+ normed_output = self.layer_norm(output)
781
+
782
+ # Convert back to seq first
783
+ normed_output = normed_output.transpose(0, 1)
784
+
785
+ return normed_output
786
+
787
+
788
+ class EdgeTamVideoPerceiverMLP(nn.Module):
789
+ def __init__(self, config: EdgeTamVideoConfig):
790
+ super().__init__()
791
+ self.hidden_size = config.perceiver_resampler_hidden_size
792
+ self.intermediate_size = config.perceiver_resampler_mlp_intermediate_size
793
+
794
+ self.layer_norm = nn.LayerNorm(self.hidden_size)
795
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
796
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
797
+ self.act_fn = nn.GELU()
798
+
799
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
800
+ hidden_states = self.layer_norm(hidden_states)
801
+ hidden_states = self.down_proj(self.act_fn(self.up_proj(hidden_states)))
802
+ return hidden_states
803
+
804
+
805
+ class EdgeTamVideoPerceiverAttention(nn.Module):
806
+ def __init__(self, config: EdgeTamVideoConfig):
807
+ super().__init__()
808
+ self.config = config
809
+ self.hidden_size = config.perceiver_resampler_hidden_size
810
+ self.num_attention_heads = config.perceiver_resampler_num_attention_heads
811
+ self.head_dim = config.perceiver_resampler_attention_head_dim
812
+ self.attention_dropout = config.perceiver_resampler_attention_dropout
813
+
814
+ self.inner_dim = self.head_dim * self.num_attention_heads
815
+ self.scaling = self.head_dim**-0.5
816
+ self.is_causal = False
817
+
818
+ self.q_proj = nn.Linear(self.hidden_size, self.inner_dim, bias=False)
819
+ self.k_proj = nn.Linear(self.hidden_size, self.inner_dim, bias=False)
820
+ self.v_proj = nn.Linear(self.hidden_size, self.inner_dim, bias=False)
821
+ self.o_proj = nn.Linear(self.inner_dim, self.hidden_size, bias=False)
822
+
823
+ def forward(
824
+ self,
825
+ query: torch.Tensor,
826
+ key: torch.Tensor,
827
+ value: torch.Tensor,
828
+ positional_encoding: Optional[torch.Tensor] = None,
829
+ **kwargs,
830
+ ) -> torch.Tensor:
831
+ # Project queries, keys, and values
832
+ query = self.q_proj(query)
833
+ key = self.k_proj(key)
834
+ value = self.v_proj(value)
835
+
836
+ # Reshape for multi-head attention
837
+ batch_size, seq_len_q = query.shape[:2]
838
+ query = query.view(batch_size, seq_len_q, self.num_attention_heads, self.head_dim).transpose(1, 2)
839
+ seq_len_kv = key.shape[1]
840
+ key = key.view(batch_size, seq_len_kv, self.num_attention_heads, self.head_dim).transpose(1, 2)
841
+ value = value.view(batch_size, seq_len_kv, self.num_attention_heads, self.head_dim).transpose(1, 2)
842
+
843
+ # Add positional encoding if provided
844
+ if positional_encoding is not None:
845
+ pos_encoding = positional_encoding.view(
846
+ batch_size, seq_len_kv, self.num_attention_heads, self.head_dim
847
+ ).transpose(1, 2)
848
+ key = key + pos_encoding
849
+ value = value + pos_encoding
850
+
851
+ # Apply attention
852
+ attention_interface: Callable = eager_attention_forward
853
+ if self.config._attn_implementation != "eager":
854
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
855
+
856
+ attn_output, _ = attention_interface(
857
+ self,
858
+ query,
859
+ key,
860
+ value,
861
+ attention_mask=None,
862
+ dropout=0.0 if not self.training else self.attention_dropout,
863
+ scaling=self.scaling,
864
+ is_causal=self.is_causal,
865
+ **kwargs,
866
+ )
867
+
868
+ # Reshape output
869
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len_q, self.inner_dim)
870
+ return self.o_proj(attn_output)
871
+
872
+
873
+ class EdgeTamVideoPerceiverEncoderLayer(nn.Module):
874
+ def __init__(self, config: EdgeTamVideoConfig):
875
+ super().__init__()
876
+
877
+ self.cross_attention = EdgeTamVideoPerceiverAttention(config)
878
+ self.mlp = EdgeTamVideoPerceiverMLP(config)
879
+ self.dropout = nn.Dropout(config.perceiver_resampler_hidden_dropout)
880
+
881
+ self.self_attention = EdgeTamVideoPerceiverAttention(config)
882
+ self.self_mlp = EdgeTamVideoPerceiverMLP(config)
883
+
884
+ # Layer norms moved from attention classes to here
885
+ self.layer_norm_input = nn.LayerNorm(config.perceiver_resampler_hidden_size)
886
+ self.layer_norm_latents = nn.LayerNorm(config.perceiver_resampler_hidden_size)
887
+ self.layer_norm_self = nn.LayerNorm(config.perceiver_resampler_hidden_size)
888
+
889
+ def forward(
890
+ self,
891
+ latents: torch.Tensor,
892
+ input_features: torch.Tensor,
893
+ positional_encoding: Optional[torch.Tensor] = None,
894
+ ) -> torch.Tensor:
895
+ # Cross attention with layer norms
896
+ normalized_latents = self.layer_norm_latents(latents)
897
+ normalized_input = self.layer_norm_input(input_features)
898
+ cross_attention_output = self.cross_attention(
899
+ query=normalized_latents,
900
+ key=normalized_input,
901
+ value=normalized_input,
902
+ positional_encoding=positional_encoding,
903
+ )
904
+ latents = latents + self.dropout(cross_attention_output)
905
+
906
+ mlp_output = self.mlp(latents)
907
+ latents = latents + mlp_output
908
+
909
+ # Self attention with layer norm
910
+ normalized_latents_self = self.layer_norm_self(latents)
911
+ self_attention_output = self.self_attention(
912
+ query=normalized_latents_self, key=normalized_latents_self, value=normalized_latents_self
913
+ )
914
+ latents = latents + self_attention_output
915
+
916
+ self_mlp_output = self.self_mlp(latents)
917
+ latents = latents + self_mlp_output
918
+
919
+ return latents
920
+
921
+
922
+ class EdgeTamVideoPerceiverResampler(nn.Module):
923
+ def __init__(self, config: EdgeTamVideoConfig):
924
+ super().__init__()
925
+ self.config = config
926
+ self.hidden_size = config.perceiver_resampler_hidden_size
927
+ self.num_latents_1d = config.perceiver_resampler_num_latents
928
+ self.num_latents_2d = config.perceiver_resampler_num_latents_2d
929
+ self.num_layers = config.perceiver_resampler_num_layers
930
+
931
+ if self.num_latents_1d > 0:
932
+ self.latents_1d = nn.Parameter(torch.randn(self.num_latents_1d, self.hidden_size))
933
+ if self.num_latents_2d > 0:
934
+ self.latents_2d = nn.Parameter(torch.randn(self.num_latents_2d, self.hidden_size))
935
+
936
+ self.positional_encoding = EdgeTamVideoPositionEmbeddingSine(
937
+ num_pos_feats=self.hidden_size // 2, normalize=True
938
+ )
939
+
940
+ self.layers = nn.ModuleList([EdgeTamVideoPerceiverEncoderLayer(config) for _ in range(self.num_layers)])
941
+
942
+ self.layer_norm = nn.LayerNorm(self.hidden_size)
943
+
944
+ def forward(
945
+ self,
946
+ hidden_states: torch.Tensor,
947
+ positional_encoding: Optional[torch.Tensor] = None,
948
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
949
+ output_latents = []
950
+ output_positional_encodings = []
951
+
952
+ if self.num_latents_1d > 0:
953
+ latents_1d, pos_1d = self._forward_1d(hidden_states, positional_encoding)
954
+ output_latents.append(latents_1d)
955
+ output_positional_encodings.append(pos_1d)
956
+
957
+ if self.num_latents_2d > 0:
958
+ latents_2d, pos_2d = self._forward_2d(hidden_states)
959
+ output_latents.append(latents_2d)
960
+ output_positional_encodings.append(pos_2d)
961
+
962
+ combined_latents = torch.cat(output_latents, dim=1)
963
+
964
+ combined_positional_encoding = None
965
+ if positional_encoding is not None and output_positional_encodings:
966
+ combined_positional_encoding = torch.cat(output_positional_encodings, dim=1)
967
+
968
+ return combined_latents, combined_positional_encoding
969
+
970
+ def _forward_1d(
971
+ self,
972
+ hidden_states: torch.Tensor,
973
+ positional_encoding: Optional[torch.Tensor] = None,
974
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
975
+ batch_size = hidden_states.shape[0]
976
+
977
+ latents = self.latents_1d.unsqueeze(0).expand(batch_size, -1, -1)
978
+ flattened_features = hidden_states.permute(0, 2, 3, 1).flatten(1, 2)
979
+
980
+ positional_features = None
981
+ if positional_encoding is not None:
982
+ positional_features = positional_encoding.permute(0, 2, 3, 1).flatten(1, 2)
983
+
984
+ for layer in self.layers:
985
+ latents = layer(latents, flattened_features, positional_features)
986
+
987
+ latents = self.layer_norm(latents)
988
+
989
+ output_positional_encoding = None
990
+ if positional_encoding is not None:
991
+ output_positional_encoding = torch.zeros_like(latents)
992
+
993
+ return latents, output_positional_encoding
994
+
995
+ def _forward_2d(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
996
+ batch_size, channels, height, width = hidden_states.shape
997
+
998
+ latents_2d = self.latents_2d.unsqueeze(0).expand(batch_size, -1, -1).view(-1, 1, channels)
999
+
1000
+ num_windows_per_dim = int(math.sqrt(self.num_latents_2d))
1001
+ window_size = height // num_windows_per_dim
1002
+
1003
+ windowed_input = hidden_states.permute(0, 2, 3, 1)
1004
+ windowed_features, _ = window_partition(windowed_input, window_size)
1005
+ windowed_features = windowed_features.flatten(1, 2)
1006
+
1007
+ for layer in self.layers:
1008
+ latents_2d = layer(latents_2d, windowed_features, positional_encoding=None)
1009
+
1010
+ latents_2d = latents_2d.view(batch_size, num_windows_per_dim, num_windows_per_dim, channels).permute(
1011
+ 0, 3, 1, 2
1012
+ )
1013
+
1014
+ positional_encoding_2d = self.positional_encoding(latents_2d.shape, latents_2d.device, latents_2d.dtype).to(
1015
+ dtype=hidden_states.dtype
1016
+ )
1017
+ positional_encoding_2d = positional_encoding_2d.permute(0, 2, 3, 1).flatten(1, 2)
1018
+
1019
+ latents_2d = latents_2d.permute(0, 2, 3, 1).flatten(1, 2)
1020
+ latents_2d = self.layer_norm(latents_2d)
1021
+
1022
+ return latents_2d, positional_encoding_2d
1023
+
1024
+
1025
+ @auto_docstring
1026
+ class EdgeTamVideoModel(Sam2VideoModel):
1027
+ _tied_weights_keys = ["prompt_encoder.shared_embedding.positional_embedding"]
1028
+ # need to be ignored, as it's a buffer and will not be correctly detected as tied weight
1029
+ _keys_to_ignore_on_load_missing = ["prompt_encoder.shared_embedding.positional_embedding"]
1030
+ _keys_to_ignore_on_load_unexpected = []
1031
+ _can_record_outputs = {"mask_decoder_attentions": OutputRecorder(EdgeTamVideoTwoWayAttentionBlock, index=2)}
1032
+
1033
+ def __init__(self, config: EdgeTamVideoConfig):
1034
+ super().__init__(config)
1035
+ self.spatial_perceiver = EdgeTamVideoPerceiverResampler(config)
1036
+
1037
+ self.post_init()
1038
+
1039
+ def _build_memory_attention_inputs(
1040
+ self,
1041
+ temporal_positions_and_previous_outputs: list[tuple[int, dict]],
1042
+ device: torch.device,
1043
+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
1044
+ """
1045
+ Concatenate memory features and positional embeddings from previous frames.
1046
+
1047
+ Returns:
1048
+ Tuple of (memories_to_concatenate, memory_positional_embeddings_to_concatenate).
1049
+ """
1050
+ memories_to_concatenate = []
1051
+ memory_positional_embeddings_to_concatenate = []
1052
+
1053
+ for relative_temporal_offset, prev_output_data in temporal_positions_and_previous_outputs:
1054
+ if prev_output_data is None:
1055
+ continue # Skip if no output data for this temporal position (e.g., padding frames)
1056
+
1057
+ # Load memory features (potentially from CPU to GPU)
1058
+ # Features are flattened: (Batch, Channels, H, W) -> (H*W, Batch, Channels)
1059
+ memory_features = prev_output_data["maskmem_features"].to(device, non_blocking=True)
1060
+ memories_to_concatenate.append(memory_features.permute(1, 0, 2))
1061
+
1062
+ # Spatial positional encoding (potentially from CPU to GPU)
1063
+ spatial_memory_pos_embed = prev_output_data["maskmem_pos_enc"].to(device, non_blocking=True)
1064
+ spatial_memory_pos_embed = spatial_memory_pos_embed.squeeze(1).permute(1, 0, 2)
1065
+
1066
+ # Add temporal positional encoding
1067
+ # self.memory_temporal_positional_encoding shape: (NumMaskMem, 1, 1, MemDim)
1068
+ combined_memory_pos_embed = (
1069
+ spatial_memory_pos_embed + self.memory_temporal_positional_encoding[relative_temporal_offset - 1]
1070
+ )
1071
+ memory_positional_embeddings_to_concatenate.append(combined_memory_pos_embed)
1072
+
1073
+ return memories_to_concatenate, memory_positional_embeddings_to_concatenate
1074
+
1075
+ def _prepare_memory_conditioned_features(
1076
+ self,
1077
+ inference_session: EdgeTamVideoInferenceSession,
1078
+ frame_idx: int,
1079
+ obj_idx: int,
1080
+ is_initial_conditioning_frame: bool,
1081
+ current_vision_features: list[torch.Tensor],
1082
+ current_vision_positional_embeddings: list[torch.Tensor],
1083
+ num_total_frames: int,
1084
+ track_in_reverse_time: bool = False,
1085
+ streaming: bool = False,
1086
+ ) -> torch.Tensor:
1087
+ """
1088
+ Fuse current frame's visual features with memory from previous frames for enhanced object tracking.
1089
+
1090
+ This method conditions the current frame's visual features on temporal memory from previous frames,
1091
+ enabling consistent object tracking across video sequences. For initial conditioning frames, it uses
1092
+ no-memory embeddings. For subsequent frames, it retrieves and integrates memory features from both
1093
+ conditioning frames (user interactions) and non-conditioning frames (tracked results) via cross-attention.
1094
+
1095
+ Args:
1096
+ inference_session (`EdgeTamVideoInferenceSession`):
1097
+ The video inference session object.
1098
+ frame_idx (`int`):
1099
+ Index of the current frame being processed.
1100
+ obj_idx (`int`):
1101
+ Index of the object being processed.
1102
+ is_initial_conditioning_frame (`bool`):
1103
+ Whether this is an initial conditioning frame with user inputs (True) or a subsequent
1104
+ tracking frame (False).
1105
+ current_vision_features (`torch.Tensor`):
1106
+ Highest-level vision features of shape `(seq_len, batch_size, channels)`.
1107
+ current_vision_positional_embeddings (`torch.Tensor`):
1108
+ Positional embedding tensors corresponding to the highest-level vision features.
1109
+ num_total_frames (`int`):
1110
+ Total number of frames in the video sequence.
1111
+ track_in_reverse_time (`bool`, *optional*, defaults to `False`):
1112
+ Whether tracking is performed in reverse temporal order.
1113
+ streaming (`bool`, *optional*, defaults to `False`):
1114
+ Whether this is streaming inference mode.
1115
+
1116
+ Returns:
1117
+ `torch.Tensor`: Memory-conditioned feature tensor of shape `(batch_size, channels, height, width)`
1118
+ suitable for input to the SAM decoder.
1119
+ """
1120
+ # Get dimensions from the highest-level (lowest-resolution) feature map
1121
+ batch_size = current_vision_features.size(1)
1122
+ num_channels = self.hidden_dim
1123
+ height, width = self.backbone_feature_sizes[-1]
1124
+ device = current_vision_features.device
1125
+
1126
+ # If memory is disabled (e.g., for single image SAM), return current features directly.
1127
+ if self.num_maskmem == 0:
1128
+ # Permute (SeqLen, Batch, Channels) -> (Batch, Channels, SeqLen) then view as (Batch, Channels, Height, Width)
1129
+ # Assuming SeqLen = Height * Width for the last feature map
1130
+ current_feature_map = current_vision_features.permute(1, 2, 0).view(
1131
+ batch_size, num_channels, height, width
1132
+ )
1133
+ return current_feature_map
1134
+
1135
+ # Step 1: Handle initial conditioning frames
1136
+ if is_initial_conditioning_frame:
1137
+ # For initial conditioning frames, no prior memory is used directly in this block.
1138
+ # If configured, directly add a learnable "no memory" embedding.
1139
+ # current_vision_features has shape (SeqLen, Batch, Channels)
1140
+ conditioned_feature_map_flat = current_vision_features + self.no_memory_embedding
1141
+ # Reshape to (Batch, Channels, Height, Width)
1142
+ conditioned_feature_map = conditioned_feature_map_flat.permute(1, 2, 0).view(
1143
+ batch_size, num_channels, height, width
1144
+ )
1145
+ return conditioned_feature_map
1146
+
1147
+ # Step 2: Get memory frames and concatenate their features
1148
+ temporal_positions_and_previous_outputs = self._gather_memory_frame_outputs(
1149
+ inference_session, obj_idx, frame_idx, track_in_reverse_time
1150
+ )
1151
+
1152
+ memories_to_concatenate, memory_positional_embeddings_to_concatenate = self._build_memory_attention_inputs(
1153
+ temporal_positions_and_previous_outputs, device
1154
+ )
1155
+ num_spatial_memory_tokens = len(memories_to_concatenate)
1156
+
1157
+ # Step 3: Get and process object pointers
1158
+ temporal_offsets, pointer_tokens, max_object_pointers_to_use = self._get_object_pointers(
1159
+ inference_session, obj_idx, frame_idx, num_total_frames, device, track_in_reverse_time, streaming
1160
+ )
1161
+
1162
+ num_object_pointer_tokens = 0
1163
+ if pointer_tokens:
1164
+ object_pointers, object_pointers_pos_embed = self._process_object_pointers(
1165
+ temporal_offsets, pointer_tokens, max_object_pointers_to_use, batch_size, num_channels, device
1166
+ )
1167
+
1168
+ if object_pointers is not None:
1169
+ memories_to_concatenate.append(object_pointers)
1170
+ memory_positional_embeddings_to_concatenate.append(object_pointers_pos_embed)
1171
+ num_object_pointer_tokens = object_pointers.shape[0]
1172
+
1173
+ # Step 4: Concatenate all retrieved memories and their positional embeddings
1174
+ combined_memory = torch.cat(memories_to_concatenate, dim=0)
1175
+ combined_memory_positional_embeddings = torch.cat(memory_positional_embeddings_to_concatenate, dim=0)
1176
+
1177
+ # Step 5: Forward through the memory attention mechanism
1178
+ conditioned_feature_map_flat = self.memory_attention(
1179
+ current_vision_features=current_vision_features,
1180
+ current_vision_position_embeddings=current_vision_positional_embeddings,
1181
+ memory=combined_memory,
1182
+ memory_posision_embeddings=combined_memory_positional_embeddings, # Corrected typo from API
1183
+ num_object_pointer_tokens=num_object_pointer_tokens,
1184
+ num_spatial_memory_tokens=num_spatial_memory_tokens,
1185
+ )
1186
+
1187
+ # Reshape from (Batch, H*W, Channels) to (Batch, Channels, Height, Width)
1188
+ conditioned_feature_map = (
1189
+ conditioned_feature_map_flat.squeeze(1).permute(0, 2, 1).view(batch_size, num_channels, height, width)
1190
+ )
1191
+ return conditioned_feature_map
1192
+
1193
+ def _encode_new_memory(
1194
+ self,
1195
+ current_vision_feats: torch.Tensor,
1196
+ pred_masks_high_res: torch.Tensor,
1197
+ object_score_logits: torch.Tensor,
1198
+ is_mask_from_pts: bool,
1199
+ ) -> tuple[torch.Tensor, list[torch.Tensor]]:
1200
+ """Encode the current image and its prediction into a memory feature."""
1201
+ batch_size = current_vision_feats.size(1) # batch size on this frame
1202
+ channels = self.hidden_dim
1203
+ height, width = self.backbone_feature_sizes[-1] # top-level (lowest-resolution) feature size
1204
+ # top-level feature, (HW)BC => BCHW
1205
+ pix_feat = current_vision_feats.permute(1, 2, 0).view(batch_size, channels, height, width)
1206
+ if is_mask_from_pts and not self.training:
1207
+ # binarize the mask logits
1208
+ mask_for_mem = (pred_masks_high_res > 0).to(pred_masks_high_res.dtype)
1209
+ else:
1210
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
1211
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
1212
+ # apply scale and bias terms to the sigmoid probabilities
1213
+ mask_for_mem = mask_for_mem * self.config.sigmoid_scale_for_mem_enc
1214
+ mask_for_mem = mask_for_mem + self.config.sigmoid_bias_for_mem_enc
1215
+
1216
+ maskmem_features, maskmem_pos_enc = self.memory_encoder(
1217
+ pix_feat,
1218
+ mask_for_mem,
1219
+ )
1220
+ # add a no-object embedding to the spatial memory to indicate that the frame
1221
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
1222
+ if self.occlusion_spatial_embedding_parameter is not None:
1223
+ is_obj_appearing = (object_score_logits > 0).float()
1224
+ maskmem_features += (1 - is_obj_appearing[..., None]) * self.occlusion_spatial_embedding_parameter[
1225
+ ..., None, None
1226
+ ].expand(*maskmem_features.shape)
1227
+
1228
+ maskmem_pos_enc = maskmem_pos_enc.to(pred_masks_high_res.dtype)
1229
+ maskmem_features, maskmem_pos_enc = self.spatial_perceiver(maskmem_features, maskmem_pos_enc)
1230
+ maskmem_features = maskmem_features.to(pred_masks_high_res.dtype)
1231
+ maskmem_pos_enc = maskmem_pos_enc.to(pred_masks_high_res.dtype)
1232
+
1233
+ return maskmem_features, maskmem_pos_enc
1234
+
1235
+
1236
+ __all__ = [
1237
+ "EdgeTamVideoMaskDecoderConfig",
1238
+ "EdgeTamVideoPromptEncoderConfig",
1239
+ "EdgeTamVideoConfig",
1240
+ "EdgeTamVideoModel",
1241
+ "EdgeTamVideoInferenceSession",
1242
+ "EdgeTamVideoPreTrainedModel",
1243
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_gemma3 import *
22
+ from .image_processing_gemma3 import *
23
+ from .image_processing_gemma3_fast import *
24
+ from .modeling_gemma3 import *
25
+ from .processing_gemma3 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/configuration_gemma3.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma3/modular_gemma3.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_gemma3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Any, Optional, Union
23
+
24
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
25
+ from ...modeling_rope_utils import rope_config_validation
26
+ from ...utils import logging
27
+ from ..siglip import SiglipVisionConfig
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class Gemma3TextConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`Gemma3TextModel`]. It is used to instantiate an Gemma3Text
36
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
37
+ defaults will yield a similar configuration to that of the Gemma3Text-7B.
38
+ e.g. [google/gemma3_text-7b](https://huggingface.co/google/gemma3_text-7b)
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 262208):
43
+ Vocabulary size of the Gemma3Text model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Gemma3TextModel`]
45
+ hidden_size (`int`, *optional*, defaults to 2304):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 9216):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 26):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 8):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*, defaults to 4):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details, check out [this
59
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ head_dim (`int`, *optional*, defaults to 256):
62
+ The attention head dimension.
63
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
64
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
65
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
66
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
67
+ The maximum sequence length that this model might ever be used with.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
71
+ The epsilon used by the rms normalization layers.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`.
75
+ pad_token_id (`int`, *optional*, defaults to 0):
76
+ Padding token id.
77
+ eos_token_id (`int`, *optional*, defaults to 1):
78
+ End of stream token id.
79
+ bos_token_id (`int`, *optional*, defaults to 2):
80
+ Beginning of stream token id.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
84
+ The base period of the RoPE embeddings.
85
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
86
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
87
+ attention_dropout (`float`, *optional*, defaults to 0.0):
88
+ The dropout ratio for the attention probabilities.
89
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
90
+ Scaling factor used on the attention scores
91
+ sliding_window (`int`, *optional*, defaults to 4096):
92
+ In Gemma3Text, every other layer uses sliding window attention. This is the size of the sliding window.
93
+ layer_types (`list`, *optional*):
94
+ Attention pattern for each layer.
95
+ final_logit_softcapping (`float`, *optional*):
96
+ Scaling factor when applying tanh softcapping on the logits.
97
+ attn_logit_softcapping (`float`, *optional*):
98
+ Scaling factor when applying tanh softcapping on the attention scores.
99
+ rope_scaling (`Dict`, *optional*):
100
+ Dictionary containing the scaling configuration for the RoPE embeddings used in global attention. NOTE: if you apply new rope type
101
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
102
+ accordingly.
103
+ Expected contents:
104
+ `rope_type` (`str`):
105
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
106
+ 'llama3'], with 'default' being the original RoPE implementation.
107
+ `factor` (`float`, *optional*):
108
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
109
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
110
+ original maximum pre-trained length.
111
+ `original_max_position_embeddings` (`int`, *optional*):
112
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
113
+ pretraining.
114
+ `attention_factor` (`float`, *optional*):
115
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
116
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
117
+ `factor` field to infer the suggested value.
118
+ `beta_fast` (`float`, *optional*):
119
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
120
+ ramp function. If unspecified, it defaults to 32.
121
+ `beta_slow` (`float`, *optional*):
122
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
123
+ ramp function. If unspecified, it defaults to 1.
124
+ `short_factor` (`list[float]`, *optional*):
125
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
126
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
127
+ size divided by the number of attention heads divided by 2
128
+ `long_factor` (`list[float]`, *optional*):
129
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
130
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
131
+ size divided by the number of attention heads divided by 2
132
+ `low_freq_factor` (`float`, *optional*):
133
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
134
+ `high_freq_factor` (`float`, *optional*):
135
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
136
+ rope_local_base_freq (float, *optional*, defaults to 10000.0):
137
+ The base period of the RoPE embeddings for local attention.
138
+ use_bidirectional_attention (`bool`, *optional*, defaults to `False`): If True, the model will attend to all
139
+ text tokens instead of using a causal mask. This does not change behavior for vision tokens.
140
+
141
+ ```python
142
+ >>> from transformers import Gemma3TextModel, Gemma3TextConfig
143
+ >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
144
+ >>> configuration = Gemma3TextConfig()
145
+ >>> # Initializing a model from the gemma3_text-7b style configuration
146
+ >>> model = Gemma3TextModel(configuration)
147
+ >>> # Accessing the model configuration
148
+ >>> configuration = model.config
149
+ ```
150
+ """
151
+
152
+ model_type = "gemma3_text"
153
+ keys_to_ignore_at_inference = ["past_key_values"]
154
+ base_model_tp_plan = {
155
+ "layers.*.self_attn.q_proj": "colwise",
156
+ "layers.*.self_attn.k_proj": "colwise",
157
+ "layers.*.self_attn.v_proj": "colwise",
158
+ "layers.*.self_attn.o_proj": "rowwise",
159
+ "layers.*.mlp.gate_proj": "colwise",
160
+ "layers.*.mlp.up_proj": "colwise",
161
+ "layers.*.mlp.down_proj": "rowwise",
162
+ }
163
+ base_model_pp_plan = {
164
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
165
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
166
+ "norm": (["hidden_states"], ["hidden_states"]),
167
+ }
168
+
169
+ def __init__(
170
+ self,
171
+ vocab_size=262_208,
172
+ hidden_size=2304,
173
+ intermediate_size=9216,
174
+ num_hidden_layers=26,
175
+ num_attention_heads=8,
176
+ num_key_value_heads=4,
177
+ head_dim=256,
178
+ hidden_activation="gelu_pytorch_tanh",
179
+ max_position_embeddings=131_072,
180
+ initializer_range=0.02,
181
+ rms_norm_eps=1e-6,
182
+ use_cache=True,
183
+ pad_token_id=0,
184
+ eos_token_id=1,
185
+ bos_token_id=2,
186
+ tie_word_embeddings=True,
187
+ rope_theta=1_000_000.0,
188
+ attention_bias=False,
189
+ attention_dropout=0.0,
190
+ query_pre_attn_scalar=256,
191
+ sliding_window=4096,
192
+ layer_types=None,
193
+ final_logit_softcapping=None,
194
+ attn_logit_softcapping=None,
195
+ rope_scaling=None,
196
+ rope_local_base_freq=10_000.0,
197
+ use_bidirectional_attention=False,
198
+ **kwargs,
199
+ ):
200
+ super().__init__(
201
+ pad_token_id=pad_token_id,
202
+ bos_token_id=bos_token_id,
203
+ eos_token_id=eos_token_id,
204
+ tie_word_embeddings=tie_word_embeddings,
205
+ **kwargs,
206
+ )
207
+ self.vocab_size = vocab_size
208
+ self.max_position_embeddings = max_position_embeddings
209
+ self.hidden_size = hidden_size
210
+ self.intermediate_size = intermediate_size
211
+ self.num_hidden_layers = num_hidden_layers
212
+ self.num_attention_heads = num_attention_heads
213
+ self.head_dim = head_dim
214
+ self.num_key_value_heads = num_key_value_heads
215
+ self.initializer_range = initializer_range
216
+ self.rms_norm_eps = rms_norm_eps
217
+ self.use_cache = use_cache
218
+ self.rope_theta = rope_theta
219
+ self.attention_bias = attention_bias
220
+ self.attention_dropout = attention_dropout
221
+ self.hidden_activation = hidden_activation
222
+ self.query_pre_attn_scalar = query_pre_attn_scalar
223
+ self.sliding_window = sliding_window
224
+ self.final_logit_softcapping = final_logit_softcapping
225
+ self.attn_logit_softcapping = attn_logit_softcapping
226
+ self.layer_types = layer_types
227
+ self.use_bidirectional_attention = use_bidirectional_attention
228
+ if use_bidirectional_attention:
229
+ self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
230
+
231
+ self.rope_local_base_freq = rope_local_base_freq
232
+ self.rope_scaling = rope_scaling
233
+ rope_config_validation(self)
234
+
235
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
236
+ self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
237
+
238
+ if self.layer_types is None:
239
+ self.layer_types = [
240
+ "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
241
+ for i in range(self.num_hidden_layers)
242
+ ]
243
+ layer_type_validation(self.layer_types, self.num_hidden_layers)
244
+
245
+
246
+ class Gemma3Config(PretrainedConfig):
247
+ r"""
248
+ This is the configuration class to store the configuration of a [`Gemma3ForConditionalGeneration`]. It is used to instantiate an
249
+ Gemma3ForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration
250
+ with the defaults will yield a similar configuration to that of the PaliGemma-2B.
251
+
252
+ e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b)
253
+
254
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
255
+ documentation from [`PretrainedConfig`] for more information.
256
+
257
+ Args:
258
+ text_config (`Union[Gemma3TextConfig, dict]`, *optional*):
259
+ The config object of the text backbone.
260
+ vision_config (`Union[AutoConfig, dict]`, *optional*):
261
+ Custom vision config or dict.
262
+ mm_tokens_per_image (`int`, *optional*, defaults to 256):
263
+ The number of tokens per image embedding.
264
+ boi_token_index (`int`, *optional*, defaults to 255999):
265
+ The begin-of-image token index to wrap the image prompt.
266
+ eoi_token_index (`int`, *optional*, defaults to 256000):
267
+ The end-of-image token index to wrap the image prompt.
268
+ image_token_index (`int`, *optional*, defaults to 262144):
269
+ The image token index to encode the image prompt.
270
+ initializer_range (`float`, *optional*, defaults to 0.02):
271
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
272
+
273
+
274
+ Example:
275
+
276
+ ```python
277
+ >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig
278
+
279
+ >>> # Initializing a Siglip-like vision config
280
+ >>> vision_config = SiglipVisionConfig()
281
+
282
+ >>> # Initializing a Gemma3 Text config
283
+ >>> text_config = Gemma3TextConfig()
284
+
285
+ >>> # Initializing a Gemma3 gemma-3-4b style configuration
286
+ >>> configuration = Gemma3Config(vision_config, text_config)
287
+
288
+ >>> # Initializing a model from the gemma-3-4b style configuration
289
+ >>> model = Gemma3TextConfig(configuration)
290
+
291
+ >>> # Accessing the model configuration
292
+ >>> configuration = model.config
293
+ ```"""
294
+
295
+ model_type = "gemma3"
296
+ attribute_map = {
297
+ "image_token_id": "image_token_index",
298
+ "boi_token_id": "boi_token_index",
299
+ "eoi_token_id": "eoi_token_index",
300
+ }
301
+ sub_configs = {
302
+ "text_config": Gemma3TextConfig,
303
+ "vision_config": SiglipVisionConfig,
304
+ }
305
+
306
+ def __init__(
307
+ self,
308
+ text_config: Optional[Union[Gemma3TextConfig, dict[str, Any]]] = None,
309
+ vision_config: Optional[Union[SiglipVisionConfig, dict[str, Any]]] = None,
310
+ mm_tokens_per_image: int = 256,
311
+ boi_token_index: int = 255_999,
312
+ eoi_token_index: int = 256_000,
313
+ image_token_index: int = 262_144,
314
+ initializer_range: float = 0.02,
315
+ **kwargs,
316
+ ):
317
+ if text_config is None:
318
+ text_config = Gemma3TextConfig()
319
+ logger.info("text_config is None, using default Gemma3TextConfig text config.")
320
+ elif isinstance(text_config, dict):
321
+ text_config = Gemma3TextConfig(**text_config)
322
+
323
+ if isinstance(vision_config, dict):
324
+ vision_config = SiglipVisionConfig(**vision_config)
325
+ elif vision_config is None:
326
+ vision_config = SiglipVisionConfig()
327
+ logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
328
+
329
+ self.text_config = text_config
330
+ self.vision_config = vision_config
331
+ self.mm_tokens_per_image = mm_tokens_per_image
332
+ self.boi_token_index = boi_token_index
333
+ self.eoi_token_index = eoi_token_index
334
+ self.image_token_index = image_token_index
335
+ self.initializer_range = initializer_range
336
+
337
+ super().__init__(**kwargs)
338
+
339
+
340
+ __all__ = ["Gemma3Config", "Gemma3TextConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/image_processing_gemma3.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. 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
+ """Image processor class for Gemma3."""
16
+
17
+ import itertools
18
+ import math
19
+ from typing import Optional, Union
20
+
21
+ import numpy as np
22
+
23
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
24
+ from ...image_transforms import (
25
+ convert_to_rgb,
26
+ resize,
27
+ to_channel_dimension_format,
28
+ )
29
+ from ...image_utils import (
30
+ IMAGENET_STANDARD_MEAN,
31
+ IMAGENET_STANDARD_STD,
32
+ ChannelDimension,
33
+ ImageInput,
34
+ PILImageResampling,
35
+ get_image_size,
36
+ infer_channel_dimension_format,
37
+ is_scaled_image,
38
+ make_flat_list_of_images,
39
+ to_numpy_array,
40
+ valid_images,
41
+ validate_preprocess_arguments,
42
+ )
43
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ if is_vision_available():
50
+ import PIL
51
+
52
+
53
+ class Gemma3ImageProcessor(BaseImageProcessor):
54
+ r"""
55
+ Constructs a SigLIP image processor.
56
+
57
+ Args:
58
+ do_resize (`bool`, *optional*, defaults to `True`):
59
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
60
+ `do_resize` in the `preprocess` method.
61
+ size (`dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
62
+ Size of the image after resizing. Can be overridden by `size` in the `preprocess` method.
63
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
64
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
65
+ do_rescale (`bool`, *optional*, defaults to `True`):
66
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
67
+ the `preprocess` method.
68
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
69
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
70
+ method.
71
+ do_normalize (`bool`, *optional*, defaults to `True`):
72
+ Whether to normalize the image by the specified mean and standard deviation. Can be overridden by
73
+ `do_normalize` in the `preprocess` method.
74
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
75
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
76
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
77
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
78
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
79
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
80
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
81
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
82
+ Whether to convert the image to RGB.
83
+ do_pan_and_scan (`bool`, *optional*):
84
+ Whether to apply `pan_and_scan` to images.
85
+ pan_and_scan_min_crop_size (`int`, *optional*):
86
+ Minimum size of each crop in pan and scan.
87
+ pan_and_scan_max_num_crops (`int`, *optional*):
88
+ Maximum number of crops per image in pan and scan.
89
+ pan_and_scan_min_ratio_to_activate (`float`, *optional*):
90
+ Minimum aspect ratio to activate pan and scan.
91
+ """
92
+
93
+ model_input_names = ["pixel_values", "num_crops"]
94
+
95
+ def __init__(
96
+ self,
97
+ do_resize: bool = True,
98
+ size: Optional[dict[str, int]] = None,
99
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
100
+ do_rescale: bool = True,
101
+ rescale_factor: Union[int, float] = 1 / 255,
102
+ do_normalize: bool = True,
103
+ image_mean: Optional[Union[float, list[float]]] = None,
104
+ image_std: Optional[Union[float, list[float]]] = None,
105
+ do_convert_rgb: Optional[bool] = True,
106
+ do_pan_and_scan: Optional[bool] = None,
107
+ pan_and_scan_min_crop_size: Optional[int] = None,
108
+ pan_and_scan_max_num_crops: Optional[int] = None,
109
+ pan_and_scan_min_ratio_to_activate: Optional[float] = None,
110
+ **kwargs,
111
+ ) -> None:
112
+ super().__init__(**kwargs)
113
+ size = size if size is not None else {"height": 224, "width": 224}
114
+ size = get_size_dict(size, default_to_square=True)
115
+ image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
116
+ image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
117
+
118
+ self.do_resize = do_resize
119
+ self.size = size
120
+ self.resample = resample
121
+ self.do_rescale = do_rescale
122
+ self.rescale_factor = rescale_factor
123
+ self.do_normalize = do_normalize
124
+ self.image_mean = image_mean
125
+ self.image_std = image_std
126
+ self.do_convert_rgb = do_convert_rgb
127
+ self.do_pan_and_scan = do_pan_and_scan
128
+ self.pan_and_scan_min_crop_size = pan_and_scan_min_crop_size
129
+ self.pan_and_scan_max_num_crops = pan_and_scan_max_num_crops
130
+ self.pan_and_scan_min_ratio_to_activate = pan_and_scan_min_ratio_to_activate
131
+
132
+ def pan_and_scan(
133
+ self,
134
+ image: np.ndarray,
135
+ pan_and_scan_min_crop_size: int,
136
+ pan_and_scan_max_num_crops: int,
137
+ pan_and_scan_min_ratio_to_activate: float,
138
+ data_format: Optional[Union[str, ChannelDimension]] = None,
139
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
140
+ ):
141
+ """
142
+ Pan and Scan and image, by cropping into smaller images when the aspect ratio exceeds
143
+ minimum allowed ratio.
144
+
145
+ Args:
146
+ image (`np.ndarray`):
147
+ Image to resize.
148
+ pan_and_scan_min_crop_size (`int`, *optional*):
149
+ Minimum size of each crop in pan and scan.
150
+ pan_and_scan_max_num_crops (`int`, *optional*):
151
+ Maximum number of crops per image in pan and scan.
152
+ pan_and_scan_min_ratio_to_activate (`float`, *optional*):
153
+ Minimum aspect ratio to activate pan and scan.
154
+ data_format (`str` or `ChannelDimension`, *optional*):
155
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
156
+ input_data_format (`ChannelDimension` or `str`, *optional*):
157
+ The channel dimension format of the input image. If not provided, it will be inferred.
158
+ """
159
+ height, width = get_image_size(image)
160
+
161
+ # Square or landscape image.
162
+ if width >= height:
163
+ # Only apply PaS if the image is sufficiently exaggerated
164
+ if width / height < pan_and_scan_min_ratio_to_activate:
165
+ return []
166
+
167
+ # Select ideal number of crops close to the image aspect ratio and such that crop_size > min_crop_size.
168
+ num_crops_w = int(math.floor(width / height + 0.5)) # Half round up rounding.
169
+ num_crops_w = min(int(math.floor(width / pan_and_scan_min_crop_size)), num_crops_w)
170
+
171
+ # Make sure the number of crops is in range [2, pan_and_scan_max_num_crops].
172
+ num_crops_w = max(2, num_crops_w)
173
+ num_crops_w = min(pan_and_scan_max_num_crops, num_crops_w)
174
+ num_crops_h = 1
175
+
176
+ # Portrait image.
177
+ else:
178
+ # Only apply PaS if the image is sufficiently exaggerated
179
+ if height / width < pan_and_scan_min_ratio_to_activate:
180
+ return []
181
+
182
+ # Select ideal number of crops close to the image aspect ratio and such that crop_size > min_crop_size.
183
+ num_crops_h = int(math.floor(height / width + 0.5))
184
+ num_crops_h = min(int(math.floor(height / pan_and_scan_min_crop_size)), num_crops_h)
185
+
186
+ # Make sure the number of crops is in range [2, pan_and_scan_max_num_crops].
187
+ num_crops_h = max(2, num_crops_h)
188
+ num_crops_h = min(pan_and_scan_max_num_crops, num_crops_h)
189
+ num_crops_w = 1
190
+
191
+ crop_size_w = int(math.ceil(width / num_crops_w))
192
+ crop_size_h = int(math.ceil(height / num_crops_h))
193
+
194
+ # Don't apply PaS if crop size is too small.
195
+ if min(crop_size_w, crop_size_h) < pan_and_scan_min_crop_size:
196
+ return []
197
+
198
+ crop_positions_w = [crop_size_w * i for i in range(num_crops_w)]
199
+ crop_positions_h = [crop_size_h * i for i in range(num_crops_h)]
200
+
201
+ if input_data_format == ChannelDimension.LAST:
202
+ image_crops = [
203
+ image[pos_h : pos_h + crop_size_h, pos_w : pos_w + crop_size_w]
204
+ for pos_h, pos_w in itertools.product(crop_positions_h, crop_positions_w)
205
+ ]
206
+ else:
207
+ image_crops = [
208
+ image[:, pos_h : pos_h + crop_size_h, pos_w : pos_w + crop_size_w]
209
+ for pos_h, pos_w in itertools.product(crop_positions_h, crop_positions_w)
210
+ ]
211
+
212
+ return image_crops
213
+
214
+ def _process_images_for_pan_and_scan(
215
+ self,
216
+ images: list[np.ndarray],
217
+ do_pan_and_scan: bool,
218
+ pan_and_scan_min_crop_size: int,
219
+ pan_and_scan_max_num_crops: int,
220
+ pan_and_scan_min_ratio_to_activate: float,
221
+ data_format: Optional[Union[str, ChannelDimension]] = None,
222
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
223
+ ):
224
+ pas_images_list = []
225
+ num_crops = []
226
+ for image in images:
227
+ pas_images = self.pan_and_scan(
228
+ image=image,
229
+ pan_and_scan_min_crop_size=pan_and_scan_min_crop_size,
230
+ pan_and_scan_max_num_crops=pan_and_scan_max_num_crops,
231
+ pan_and_scan_min_ratio_to_activate=pan_and_scan_min_ratio_to_activate,
232
+ data_format=data_format,
233
+ input_data_format=input_data_format,
234
+ )
235
+ pas_images_list.extend([image] + pas_images)
236
+ num_crops.append(len(pas_images))
237
+ return pas_images_list, num_crops
238
+
239
+ @filter_out_non_signature_kwargs()
240
+ def preprocess(
241
+ self,
242
+ images: ImageInput,
243
+ do_resize: Optional[bool] = None,
244
+ size: Optional[dict[str, int]] = None,
245
+ resample: Optional[PILImageResampling] = None,
246
+ do_rescale: Optional[bool] = None,
247
+ rescale_factor: Optional[float] = None,
248
+ do_normalize: Optional[bool] = None,
249
+ image_mean: Optional[Union[float, list[float]]] = None,
250
+ image_std: Optional[Union[float, list[float]]] = None,
251
+ return_tensors: Optional[Union[str, TensorType]] = None,
252
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
253
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
254
+ do_convert_rgb: Optional[bool] = None,
255
+ do_pan_and_scan: Optional[bool] = None,
256
+ pan_and_scan_min_crop_size: Optional[int] = None,
257
+ pan_and_scan_max_num_crops: Optional[int] = None,
258
+ pan_and_scan_min_ratio_to_activate: Optional[float] = None,
259
+ ) -> PIL.Image.Image:
260
+ """
261
+ Preprocess an image or batch of images.
262
+
263
+ Args:
264
+ images (`ImageInput`):
265
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
266
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
267
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
268
+ Whether to resize the image.
269
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
270
+ Size of the image after resizing.
271
+ resample (`int`, *optional*, defaults to `self.resample`):
272
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
273
+ has an effect if `do_resize` is set to `True`.
274
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
275
+ Whether to rescale the image.
276
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
277
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
278
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
279
+ Whether to normalize the image.
280
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
281
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
282
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
283
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
284
+ `True`.
285
+ return_tensors (`str` or `TensorType`, *optional*):
286
+ The type of tensors to return. Can be one of:
287
+ - Unset: Return a list of `np.ndarray`.
288
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
289
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
290
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
291
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
292
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
293
+ The channel dimension format for the output image. Can be one of:
294
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
295
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
296
+ - Unset: Use the channel dimension format of the input image.
297
+ input_data_format (`ChannelDimension` or `str`, *optional*):
298
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
299
+ from the input image. Can be one of:
300
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
301
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
302
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
303
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
304
+ Whether to convert the image to RGB.
305
+ do_pan_and_scan (`bool`, *optional*, defaults to `self.do_pan_and_scan`):
306
+ Whether to apply `pan_and_scan` to images.
307
+ pan_and_scan_min_crop_size (`int`, *optional*, defaults to `self.pan_and_scan_min_crop_size`):
308
+ Minimum size of each crop in pan and scan.
309
+ pan_and_scan_max_num_crops (`int`, *optional*, defaults to `self.pan_and_scan_max_num_crops`):
310
+ Maximum number of crops per image in pan and scan.
311
+ pan_and_scan_min_ratio_to_activate (`float`, *optional*, defaults to `self.pan_and_scan_min_ratio_to_activate`):
312
+ Minimum aspect ratio to activate pan and scan.
313
+ """
314
+ do_resize = do_resize if do_resize is not None else self.do_resize
315
+ size = size if size is not None else self.size
316
+ size = get_size_dict(size, param_name="size", default_to_square=False)
317
+ resample = resample if resample is not None else self.resample
318
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
319
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
320
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
321
+ image_mean = image_mean if image_mean is not None else self.image_mean
322
+ image_std = image_std if image_std is not None else self.image_std
323
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
324
+ do_pan_and_scan = do_pan_and_scan if do_pan_and_scan is not None else self.do_pan_and_scan
325
+ pan_and_scan_min_crop_size = (
326
+ pan_and_scan_min_crop_size if pan_and_scan_min_crop_size is not None else self.pan_and_scan_min_crop_size
327
+ )
328
+ pan_and_scan_max_num_crops = (
329
+ pan_and_scan_max_num_crops if pan_and_scan_max_num_crops is not None else self.pan_and_scan_max_num_crops
330
+ )
331
+ pan_and_scan_min_ratio_to_activate = (
332
+ pan_and_scan_min_ratio_to_activate
333
+ if pan_and_scan_min_ratio_to_activate is not None
334
+ else self.pan_and_scan_min_ratio_to_activate
335
+ )
336
+
337
+ images = self.fetch_images(images)
338
+ images = make_flat_list_of_images(images)
339
+
340
+ if not valid_images(images):
341
+ raise ValueError(
342
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
343
+ "torch.Tensor, tf.Tensor or jax.ndarray."
344
+ )
345
+
346
+ validate_preprocess_arguments(
347
+ do_rescale=do_rescale,
348
+ rescale_factor=rescale_factor,
349
+ do_normalize=do_normalize,
350
+ image_mean=image_mean,
351
+ image_std=image_std,
352
+ do_resize=do_resize,
353
+ size=size,
354
+ resample=resample,
355
+ )
356
+ if do_convert_rgb:
357
+ images = [convert_to_rgb(image) for image in images]
358
+
359
+ # All transformations expect numpy arrays.
360
+ images = [to_numpy_array(image) for image in images]
361
+
362
+ if do_rescale and is_scaled_image(images[0]):
363
+ logger.warning_once(
364
+ "It looks like you are trying to rescale already rescaled images. If the input"
365
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
366
+ )
367
+
368
+ if input_data_format is None:
369
+ # We assume that all images have the same channel dimension format.
370
+ input_data_format = infer_channel_dimension_format(images[0])
371
+
372
+ if do_pan_and_scan:
373
+ images, num_crops = self._process_images_for_pan_and_scan(
374
+ images=images,
375
+ do_pan_and_scan=do_pan_and_scan,
376
+ pan_and_scan_min_crop_size=pan_and_scan_min_crop_size,
377
+ pan_and_scan_max_num_crops=pan_and_scan_max_num_crops,
378
+ pan_and_scan_min_ratio_to_activate=pan_and_scan_min_ratio_to_activate,
379
+ data_format=data_format,
380
+ input_data_format=input_data_format,
381
+ )
382
+
383
+ else:
384
+ num_crops = [0 for _ in images]
385
+
386
+ processed_images = []
387
+ for image in images:
388
+ if do_resize:
389
+ height, width = size["height"], size["width"]
390
+ image = resize(
391
+ image=image, size=(height, width), resample=resample, input_data_format=input_data_format
392
+ )
393
+
394
+ if do_rescale:
395
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
396
+
397
+ if do_normalize:
398
+ image = self.normalize(
399
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
400
+ )
401
+
402
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
403
+ processed_images.append(image)
404
+
405
+ data = {"pixel_values": processed_images, "num_crops": num_crops}
406
+ return BatchFeature(data=data, tensor_type=return_tensors)
407
+
408
+
409
+ __all__ = ["Gemma3ImageProcessor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/image_processing_gemma3_fast.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. 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
+ """Fast Image processor class for SigLIP."""
16
+
17
+ import itertools
18
+ import math
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ from torchvision.transforms.v2 import functional as F
23
+
24
+ from ...image_processing_utils_fast import (
25
+ BaseImageProcessorFast,
26
+ BatchFeature,
27
+ DefaultFastImageProcessorKwargs,
28
+ group_images_by_shape,
29
+ reorder_images,
30
+ )
31
+ from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageInput, PILImageResampling, SizeDict
32
+ from ...processing_utils import Unpack
33
+ from ...utils import (
34
+ TensorType,
35
+ auto_docstring,
36
+ logging,
37
+ )
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class Gemma3FastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
44
+ """
45
+ do_pan_and_scan (`bool`, *optional*):
46
+ Whether to apply `pan_and_scan` to images.
47
+ pan_and_scan_min_crop_size (`int`, *optional*):
48
+ Minimum size of each crop in pan and scan.
49
+ pan_and_scan_max_num_crops (`int`, *optional*):
50
+ Maximum number of crops per image in pan and scan.
51
+ pan_and_scan_min_ratio_to_activate (`float`, *optional*):
52
+ Minimum aspect ratio to activate pan and scan.
53
+ """
54
+
55
+ do_pan_and_scan: Optional[bool]
56
+ pan_and_scan_min_crop_size: Optional[int]
57
+ pan_and_scan_max_num_crops: Optional[int]
58
+ pan_and_scan_min_ratio_to_activate: Optional[float]
59
+
60
+
61
+ @auto_docstring
62
+ class Gemma3ImageProcessorFast(BaseImageProcessorFast):
63
+ resample = PILImageResampling.BILINEAR
64
+ image_mean = IMAGENET_STANDARD_MEAN
65
+ image_std = IMAGENET_STANDARD_STD
66
+ size = {"height": 224, "width": 224}
67
+ default_to_square = True
68
+ do_convert_rgb = True
69
+ do_resize = True
70
+ do_rescale = True
71
+ do_normalize = True
72
+ do_pan_and_scan = None
73
+ pan_and_scan_min_crop_size = None
74
+ pan_and_scan_max_num_crops = None
75
+ pan_and_scan_min_ratio_to_activate = None
76
+ valid_kwargs = Gemma3FastImageProcessorKwargs
77
+
78
+ def __init__(self, **kwargs: Unpack[Gemma3FastImageProcessorKwargs]):
79
+ super().__init__(**kwargs)
80
+
81
+ def pan_and_scan_batched(
82
+ self,
83
+ images: "torch.Tensor",
84
+ pan_and_scan_min_crop_size: int,
85
+ pan_and_scan_max_num_crops: int,
86
+ pan_and_scan_min_ratio_to_activate: float,
87
+ ):
88
+ """
89
+ Pan and Scan an image, by cropping into smaller images when the aspect ratio exceeds
90
+ minimum allowed ratio.
91
+
92
+ Args:
93
+ image (`torch.Tensor`):
94
+ Image to resize.
95
+ pan_and_scan_min_crop_size (`int`, *optional*):
96
+ Minimum size of each crop in pan and scan.
97
+ pan_and_scan_max_num_crops (`int`, *optional*):
98
+ Maximum number of crops per image in pan and scan.
99
+ pan_and_scan_min_ratio_to_activate (`float`, *optional*):
100
+ Minimum aspect ratio to activate pan and scan.
101
+ """
102
+ height, width = images.shape[-2:]
103
+
104
+ # Square or landscape image.
105
+ if width >= height:
106
+ # Only apply PaS if the image is sufficiently exaggerated
107
+ if width / height < pan_and_scan_min_ratio_to_activate:
108
+ return []
109
+
110
+ # Select ideal number of crops close to the image aspect ratio and such that crop_size > min_crop_size.
111
+ num_crops_w = int(math.floor(width / height + 0.5)) # Half round up rounding.
112
+ num_crops_w = min(int(math.floor(width / pan_and_scan_min_crop_size)), num_crops_w)
113
+
114
+ # Make sure the number of crops is in range [2, pan_and_scan_max_num_crops].
115
+ num_crops_w = max(2, num_crops_w)
116
+ num_crops_w = min(pan_and_scan_max_num_crops, num_crops_w)
117
+ num_crops_h = 1
118
+
119
+ # Portrait image.
120
+ else:
121
+ # Only apply PaS if the image is sufficiently exaggerated
122
+ if height / width < pan_and_scan_min_ratio_to_activate:
123
+ return []
124
+
125
+ # Select ideal number of crops close to the image aspect ratio and such that crop_size > min_crop_size.
126
+ num_crops_h = int(math.floor(height / width + 0.5))
127
+ num_crops_h = min(int(math.floor(height / pan_and_scan_min_crop_size)), num_crops_h)
128
+
129
+ # Make sure the number of crops is in range [2, pan_and_scan_max_num_crops].
130
+ num_crops_h = max(2, num_crops_h)
131
+ num_crops_h = min(pan_and_scan_max_num_crops, num_crops_h)
132
+ num_crops_w = 1
133
+
134
+ crop_size_w = int(math.ceil(width / num_crops_w))
135
+ crop_size_h = int(math.ceil(height / num_crops_h))
136
+
137
+ # Don't apply PaS if crop size is too small.
138
+ if min(crop_size_w, crop_size_h) < pan_and_scan_min_crop_size:
139
+ return []
140
+
141
+ crop_positions_w = [crop_size_w * i for i in range(num_crops_w)]
142
+ crop_positions_h = [crop_size_h * i for i in range(num_crops_h)]
143
+
144
+ return [
145
+ images[..., pos_h : pos_h + crop_size_h, pos_w : pos_w + crop_size_w]
146
+ for pos_h, pos_w in itertools.product(crop_positions_h, crop_positions_w)
147
+ ]
148
+
149
+ def _process_images_for_pan_and_scan(
150
+ self,
151
+ images: list["torch.Tensor"],
152
+ do_pan_and_scan: bool,
153
+ pan_and_scan_min_crop_size: int,
154
+ pan_and_scan_max_num_crops: int,
155
+ pan_and_scan_min_ratio_to_activate: float,
156
+ ):
157
+ pas_images = self.pan_and_scan_batched(
158
+ images=images,
159
+ pan_and_scan_min_crop_size=pan_and_scan_min_crop_size,
160
+ pan_and_scan_max_num_crops=pan_and_scan_max_num_crops,
161
+ pan_and_scan_min_ratio_to_activate=pan_and_scan_min_ratio_to_activate,
162
+ )
163
+ num_crops = [len(pas_images) for _ in images]
164
+ return pas_images, num_crops
165
+
166
+ @auto_docstring
167
+ def preprocess(
168
+ self,
169
+ images: ImageInput,
170
+ **kwargs: Unpack[Gemma3FastImageProcessorKwargs],
171
+ ) -> BatchFeature:
172
+ return super().preprocess(images, **kwargs)
173
+
174
+ def _preprocess(
175
+ self,
176
+ images: list[list["torch.Tensor"]],
177
+ do_resize: bool,
178
+ size: SizeDict,
179
+ do_pan_and_scan: Optional[bool],
180
+ pan_and_scan_min_crop_size: Optional[int],
181
+ pan_and_scan_max_num_crops: Optional[int],
182
+ pan_and_scan_min_ratio_to_activate: Optional[float],
183
+ interpolation: Optional["F.InterpolationMode"],
184
+ do_rescale: bool,
185
+ rescale_factor: float,
186
+ do_normalize: bool,
187
+ image_mean: Optional[Union[float, list[float]]],
188
+ image_std: Optional[Union[float, list[float]]],
189
+ disable_grouping: Optional[bool],
190
+ return_tensors: Optional[Union[str, TensorType]],
191
+ **kwargs,
192
+ ) -> BatchFeature:
193
+ # Group images by size for batched processing
194
+ processed_images_grouped = {}
195
+ num_crops_grouped = {}
196
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
197
+ for shape_images, stacked_images in grouped_images.items():
198
+ if do_pan_and_scan:
199
+ pas_images, num_crops = self._process_images_for_pan_and_scan(
200
+ images=stacked_images,
201
+ do_pan_and_scan=do_pan_and_scan,
202
+ pan_and_scan_min_crop_size=pan_and_scan_min_crop_size,
203
+ pan_and_scan_max_num_crops=pan_and_scan_max_num_crops,
204
+ pan_and_scan_min_ratio_to_activate=pan_and_scan_min_ratio_to_activate,
205
+ )
206
+ # Add the thumbnails to the image patches
207
+ stacked_images = [stacked_images] + pas_images
208
+ # Group images by size for batched resizing (this will typically group thumbnails together and cropped patches together)
209
+ processed_image_patches_grouped = {}
210
+ grouped_image_patches, grouped_image_patches_index = group_images_by_shape(
211
+ stacked_images, disable_grouping=disable_grouping
212
+ )
213
+ for shape, stacked_image_patches in grouped_image_patches.items():
214
+ stacked_image_patches = self.resize(
215
+ image=stacked_image_patches,
216
+ size=size,
217
+ interpolation=interpolation,
218
+ )
219
+ processed_image_patches_grouped[shape] = stacked_image_patches
220
+ processed_image_patches = reorder_images(processed_image_patches_grouped, grouped_image_patches_index)
221
+ # Transpose to have the thumbnails with their corresponding patches
222
+ stacked_images = torch.stack(processed_image_patches, dim=0).transpose(0, 1).contiguous()
223
+ else:
224
+ num_crops = [0 for _ in stacked_images]
225
+
226
+ if do_resize:
227
+ stacked_images = self.resize(
228
+ image=stacked_images,
229
+ size=size,
230
+ interpolation=interpolation,
231
+ )
232
+ num_crops_grouped[shape_images] = num_crops
233
+ processed_images_grouped[shape_images] = stacked_images
234
+ resized_images = reorder_images(processed_images_grouped, grouped_images_index)
235
+ # If pan and scan is enabled, we need to flatten the list of images
236
+ if do_pan_and_scan:
237
+ resized_images = [image for images_list in resized_images for image in images_list]
238
+ num_crops = reorder_images(num_crops_grouped, grouped_images_index)
239
+
240
+ # Group images by size for further processing
241
+ # Needed in case do_resize is False, or resize returns images with different sizes
242
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
243
+ processed_images_grouped = {}
244
+ for shape, stacked_images in grouped_images.items():
245
+ # Fused rescale and normalize
246
+ stacked_images = self.rescale_and_normalize(
247
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
248
+ )
249
+ processed_images_grouped[shape] = stacked_images
250
+
251
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
252
+ processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
253
+ return BatchFeature(
254
+ data={"pixel_values": processed_images, "num_crops": num_crops}, tensor_type=return_tensors
255
+ )
256
+
257
+
258
+ __all__ = ["Gemma3ImageProcessorFast"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/modeling_gemma3.py ADDED
@@ -0,0 +1,1341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma3/modular_gemma3.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_gemma3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ import copy
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass
25
+ from typing import Optional, Union
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+
30
+ from ...activations import ACT2FN
31
+ from ...cache_utils import Cache, DynamicCache
32
+ from ...configuration_utils import PretrainedConfig
33
+ from ...generation import GenerationMixin
34
+ from ...masking_utils import create_causal_mask, create_masks_for_generate, create_sliding_window_causal_mask
35
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
36
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
37
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
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 ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging
42
+ from ...utils.deprecation import deprecate_kwarg
43
+ from ...utils.generic import check_model_inputs
44
+ from ..auto import AutoModel
45
+ from .configuration_gemma3 import Gemma3Config, Gemma3TextConfig
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ @dataclass
52
+ @auto_docstring(
53
+ custom_intro="""
54
+ Base class for Gemma3 outputs, with hidden states and attentions.
55
+ """
56
+ )
57
+ class Gemma3ModelOutputWithPast(BaseModelOutputWithPast):
58
+ r"""
59
+ image_hidden_states (`torch.FloatTensor`, *optional*):
60
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
61
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
62
+ """
63
+
64
+ image_hidden_states: Optional[torch.FloatTensor] = None
65
+
66
+
67
+ @dataclass
68
+ @auto_docstring(
69
+ custom_intro="""
70
+ Base class for Gemma3 causal language model (or autoregressive) outputs.
71
+ """
72
+ )
73
+ class Gemma3CausalLMOutputWithPast(ModelOutput):
74
+ r"""
75
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
76
+ Language modeling loss (for next-token prediction).
77
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
78
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
79
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
80
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
81
+
82
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
83
+ `past_key_values` input) to speed up sequential decoding.
84
+ image_hidden_states (`torch.FloatTensor`, *optional*):
85
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
86
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
87
+ """
88
+
89
+ loss: Optional[torch.FloatTensor] = None
90
+ logits: Optional[torch.FloatTensor] = None
91
+ past_key_values: Optional[Cache] = None
92
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
93
+ attentions: Optional[tuple[torch.FloatTensor]] = None
94
+ image_hidden_states: Optional[torch.FloatTensor] = None
95
+
96
+
97
+ class Gemma3TextScaledWordEmbedding(nn.Embedding):
98
+ """
99
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
100
+ """
101
+
102
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
103
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
104
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
105
+
106
+ def forward(self, input_ids: torch.Tensor):
107
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
108
+
109
+
110
+ class Gemma3MLP(nn.Module):
111
+ def __init__(self, config: Gemma3TextConfig):
112
+ super().__init__()
113
+ self.config = config
114
+ self.hidden_size = config.hidden_size
115
+ self.intermediate_size = config.intermediate_size
116
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
117
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
118
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
119
+ self.act_fn = ACT2FN[config.hidden_activation]
120
+
121
+ def forward(self, x):
122
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
123
+ return down_proj
124
+
125
+
126
+ class Gemma3RMSNorm(nn.Module):
127
+ def __init__(self, dim: int, eps: float = 1e-6):
128
+ super().__init__()
129
+ self.eps = eps
130
+ self.weight = nn.Parameter(torch.zeros(dim))
131
+
132
+ def _norm(self, x):
133
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
134
+
135
+ def forward(self, x):
136
+ output = self._norm(x.float())
137
+ # Llama does x.to(float16) * w whilst Gemma3 is (x * w).to(float16)
138
+ # See https://github.com/huggingface/transformers/pull/29402
139
+ output = output * (1.0 + self.weight.float())
140
+ return output.type_as(x)
141
+
142
+ def extra_repr(self):
143
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
144
+
145
+
146
+ class Gemma3RotaryEmbedding(nn.Module):
147
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
148
+
149
+ def __init__(self, config: Gemma3TextConfig, device=None):
150
+ super().__init__()
151
+ # BC: "rope_type" was originally "type"
152
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
153
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
154
+ else:
155
+ self.rope_type = "default"
156
+ self.max_seq_len_cached = config.max_position_embeddings
157
+ self.original_max_seq_len = config.max_position_embeddings
158
+
159
+ self.config = config
160
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
161
+
162
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
163
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
164
+ self.original_inv_freq = self.inv_freq
165
+
166
+ @torch.no_grad()
167
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
168
+ def forward(self, x, position_ids):
169
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
170
+ position_ids_expanded = position_ids[:, None, :].float()
171
+
172
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
173
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
174
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
175
+ emb = torch.cat((freqs, freqs), dim=-1)
176
+ cos = emb.cos() * self.attention_scaling
177
+ sin = emb.sin() * self.attention_scaling
178
+
179
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
180
+
181
+
182
+ def rotate_half(x):
183
+ """Rotates half the hidden dims of the input."""
184
+ x1 = x[..., : x.shape[-1] // 2]
185
+ x2 = x[..., x.shape[-1] // 2 :]
186
+ return torch.cat((-x2, x1), dim=-1)
187
+
188
+
189
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
190
+ """Applies Rotary Position Embedding to the query and key tensors.
191
+
192
+ Args:
193
+ q (`torch.Tensor`): The query tensor.
194
+ k (`torch.Tensor`): The key tensor.
195
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
196
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
197
+ position_ids (`torch.Tensor`, *optional*):
198
+ Deprecated and unused.
199
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
200
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
201
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
202
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
203
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
204
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
205
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
206
+ Returns:
207
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
208
+ """
209
+ cos = cos.unsqueeze(unsqueeze_dim)
210
+ sin = sin.unsqueeze(unsqueeze_dim)
211
+ q_embed = (q * cos) + (rotate_half(q) * sin)
212
+ k_embed = (k * cos) + (rotate_half(k) * sin)
213
+ return q_embed, k_embed
214
+
215
+
216
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
217
+ """
218
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
219
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
220
+ """
221
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
222
+ if n_rep == 1:
223
+ return hidden_states
224
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
225
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
226
+
227
+
228
+ def eager_attention_forward(
229
+ module: nn.Module,
230
+ query: torch.Tensor,
231
+ key: torch.Tensor,
232
+ value: torch.Tensor,
233
+ attention_mask: Optional[torch.Tensor],
234
+ dropout: float = 0.0,
235
+ scaling: Optional[float] = None,
236
+ softcap: Optional[float] = None,
237
+ **kwargs,
238
+ ) -> tuple[torch.Tensor, torch.Tensor]:
239
+ if scaling is None:
240
+ scaling = module.head_dim**-0.5
241
+
242
+ key_states = repeat_kv(key, module.num_key_value_groups)
243
+ value_states = repeat_kv(value, module.num_key_value_groups)
244
+
245
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
246
+
247
+ if softcap is not None:
248
+ attn_weights = attn_weights / softcap
249
+ attn_weights = torch.tanh(attn_weights)
250
+ attn_weights = attn_weights * softcap
251
+ if attention_mask is not None: # no matter the length, we just slice it
252
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
253
+ attn_weights = attn_weights + causal_mask
254
+
255
+ # upcast attention to fp32
256
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
257
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
258
+ attn_output = torch.matmul(attn_weights, value_states)
259
+ attn_output = attn_output.transpose(1, 2).contiguous()
260
+ return attn_output, attn_weights
261
+
262
+
263
+ class Gemma3Attention(nn.Module):
264
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
265
+
266
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
267
+ super().__init__()
268
+ self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
269
+ self.config = config
270
+ self.layer_idx = layer_idx
271
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
272
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
273
+ self.scaling = config.query_pre_attn_scalar**-0.5
274
+ self.attention_dropout = self.config.attention_dropout
275
+ self.is_causal = not self.config.use_bidirectional_attention
276
+
277
+ self.q_proj = nn.Linear(
278
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
279
+ )
280
+ self.k_proj = nn.Linear(
281
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
282
+ )
283
+ self.v_proj = nn.Linear(
284
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
285
+ )
286
+ self.o_proj = nn.Linear(
287
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
288
+ )
289
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
290
+ self.sliding_window = config.sliding_window if self.is_sliding else None
291
+
292
+ self.q_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
293
+ self.k_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
294
+
295
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ position_embeddings: torch.Tensor,
300
+ attention_mask: Optional[torch.Tensor],
301
+ past_key_values: Optional[Cache] = None,
302
+ cache_position: Optional[torch.LongTensor] = None,
303
+ **kwargs: Unpack[FlashAttentionKwargs],
304
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
305
+ input_shape = hidden_states.shape[:-1]
306
+ hidden_shape = (*input_shape, -1, self.head_dim)
307
+
308
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
309
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
310
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
311
+
312
+ query_states = self.q_norm(query_states)
313
+ key_states = self.k_norm(key_states)
314
+
315
+ cos, sin = position_embeddings
316
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
317
+
318
+ if past_key_values is not None:
319
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
320
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
321
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
322
+
323
+ attention_interface: Callable = eager_attention_forward
324
+ if self.config._attn_implementation != "eager":
325
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
326
+
327
+ attn_output, attn_weights = attention_interface(
328
+ self,
329
+ query_states,
330
+ key_states,
331
+ value_states,
332
+ attention_mask,
333
+ dropout=self.attention_dropout if self.training else 0.0,
334
+ scaling=self.scaling,
335
+ sliding_window=self.sliding_window,
336
+ **kwargs,
337
+ )
338
+
339
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
340
+ attn_output = self.o_proj(attn_output)
341
+ return attn_output, attn_weights
342
+
343
+
344
+ class Gemma3DecoderLayer(GradientCheckpointingLayer):
345
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
346
+ super().__init__()
347
+ self.config = config
348
+ self.hidden_size = config.hidden_size
349
+ self.layer_idx = layer_idx
350
+ self.attention_type = config.layer_types[layer_idx]
351
+ self.self_attn = Gemma3Attention(config=config, layer_idx=layer_idx)
352
+ self.mlp = Gemma3MLP(config)
353
+ self.input_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
354
+ self.post_attention_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
355
+ self.pre_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
356
+ self.post_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
357
+
358
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
359
+ def forward(
360
+ self,
361
+ hidden_states: torch.Tensor,
362
+ position_embeddings_global: torch.Tensor,
363
+ position_embeddings_local: torch.Tensor,
364
+ attention_mask: Optional[torch.Tensor] = None,
365
+ position_ids: Optional[torch.LongTensor] = None,
366
+ past_key_values: Optional[Cache] = None,
367
+ output_attentions: Optional[bool] = False,
368
+ use_cache: Optional[bool] = False,
369
+ cache_position: Optional[torch.LongTensor] = None,
370
+ **kwargs,
371
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
372
+ residual = hidden_states
373
+
374
+ hidden_states = self.input_layernorm(hidden_states)
375
+
376
+ # apply global RoPE to non-sliding layer only
377
+ if self.self_attn.is_sliding:
378
+ position_embeddings = position_embeddings_local
379
+ else:
380
+ position_embeddings = position_embeddings_global
381
+
382
+ hidden_states, self_attn_weights = self.self_attn(
383
+ hidden_states=hidden_states,
384
+ position_embeddings=position_embeddings,
385
+ attention_mask=attention_mask,
386
+ position_ids=position_ids,
387
+ past_key_values=past_key_values,
388
+ output_attentions=output_attentions,
389
+ use_cache=use_cache,
390
+ cache_position=cache_position,
391
+ **kwargs,
392
+ )
393
+ hidden_states = self.post_attention_layernorm(hidden_states)
394
+ hidden_states = residual + hidden_states
395
+
396
+ residual = hidden_states
397
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
398
+ hidden_states = self.mlp(hidden_states)
399
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
400
+ hidden_states = residual + hidden_states
401
+
402
+ outputs = (hidden_states,)
403
+
404
+ if output_attentions:
405
+ outputs += (self_attn_weights,)
406
+
407
+ return outputs
408
+
409
+
410
+ @auto_docstring
411
+ class Gemma3PreTrainedModel(PreTrainedModel):
412
+ config: Gemma3Config
413
+ base_model_prefix = ""
414
+ supports_gradient_checkpointing = True
415
+ _no_split_modules = [
416
+ "Gemma3DecoderLayer",
417
+ "SiglipVisionEmbeddings",
418
+ "SiglipEncoderLayer",
419
+ "SiglipMultiheadAttentionPoolingHead",
420
+ ]
421
+ _skip_keys_device_placement = ["past_key_values"]
422
+ _supports_flash_attn = True
423
+ _supports_sdpa = True
424
+ _supports_flex_attn = True
425
+
426
+ _can_compile_fullgraph = True
427
+ _supports_attention_backend = True
428
+ _can_record_outputs = {
429
+ "hidden_states": Gemma3DecoderLayer,
430
+ "attentions": Gemma3Attention,
431
+ }
432
+
433
+ def _init_weights(self, module):
434
+ super()._init_weights(module)
435
+ if isinstance(module, Gemma3MultiModalProjector):
436
+ module.mm_input_projection_weight.data.zero_()
437
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
438
+ elif "RMSNorm" in module.__class__.__name__:
439
+ module.weight.data.zero_()
440
+
441
+
442
+ def _bidirectional_window_overlay(sliding_window: int) -> Callable[[int, int, int, int], bool]:
443
+ """
444
+ Enables a bidirectional mask within the sliding window.
445
+ """
446
+
447
+ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
448
+ """A token can attend to any other token if their absolute distance is within
449
+ the (exclusive) sliding window size (distance < sliding_window)."""
450
+ return abs(q_idx - kv_idx) < sliding_window
451
+
452
+ return inner_mask
453
+
454
+
455
+ @auto_docstring
456
+ class Gemma3TextModel(Gemma3PreTrainedModel):
457
+ config: Gemma3TextConfig
458
+
459
+ def __init__(self, config: Gemma3TextConfig):
460
+ super().__init__(config)
461
+ self.padding_idx = config.pad_token_id
462
+ self.vocab_size = config.vocab_size
463
+
464
+ # Gemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
465
+ self.embed_tokens = Gemma3TextScaledWordEmbedding(
466
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
467
+ )
468
+ self.layers = nn.ModuleList(
469
+ [Gemma3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
470
+ )
471
+ self.norm = Gemma3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
472
+ self.rotary_emb = Gemma3RotaryEmbedding(config=config)
473
+ self.gradient_checkpointing = False
474
+
475
+ # TODO: raushan fix this after RoPE refactor. For now we hack it by reassigning thetas
476
+ # when we want to create a local RoPE layer. Config defaults should hold values for global RoPE
477
+ config = copy.deepcopy(config)
478
+ config.rope_theta = config.rope_local_base_freq
479
+ config.rope_scaling = {"rope_type": "default"}
480
+ self.rotary_emb_local = Gemma3RotaryEmbedding(config=config)
481
+
482
+ # Initialize weights and apply final processing
483
+ self.post_init()
484
+
485
+ @check_model_inputs
486
+ @auto_docstring
487
+ def forward(
488
+ self,
489
+ input_ids: Optional[torch.LongTensor] = None,
490
+ attention_mask: Optional[torch.Tensor] = None,
491
+ position_ids: Optional[torch.LongTensor] = None,
492
+ past_key_values: Optional[Cache] = None,
493
+ inputs_embeds: Optional[torch.FloatTensor] = None,
494
+ use_cache: Optional[bool] = None,
495
+ output_attentions: Optional[bool] = None,
496
+ output_hidden_states: Optional[bool] = None,
497
+ cache_position: Optional[torch.LongTensor] = None,
498
+ **kwargs: Unpack[TransformersKwargs],
499
+ ) -> BaseModelOutputWithPast:
500
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
501
+ output_hidden_states = (
502
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
503
+ )
504
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
505
+
506
+ if (input_ids is None) ^ (inputs_embeds is not None):
507
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
508
+
509
+ if self.gradient_checkpointing and self.training and use_cache:
510
+ logger.warning_once(
511
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
512
+ )
513
+ use_cache = False
514
+
515
+ if inputs_embeds is None:
516
+ inputs_embeds = self.embed_tokens(input_ids)
517
+
518
+ if use_cache and past_key_values is None and not self.training:
519
+ past_key_values = DynamicCache(config=self.config)
520
+
521
+ if cache_position is None:
522
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
523
+ cache_position = torch.arange(
524
+ past_seen_tokens,
525
+ past_seen_tokens + inputs_embeds.shape[1],
526
+ device=inputs_embeds.device,
527
+ )
528
+
529
+ if position_ids is None:
530
+ position_ids = cache_position.unsqueeze(0)
531
+
532
+ # It may already have been prepared by e.g. `generate`
533
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
534
+ # Prepare mask arguments
535
+ mask_kwargs = {
536
+ "config": self.config,
537
+ "input_embeds": inputs_embeds,
538
+ "attention_mask": attention_mask,
539
+ "cache_position": cache_position,
540
+ "past_key_values": past_key_values,
541
+ "position_ids": position_ids,
542
+ }
543
+ sliding_mask_kwargs = mask_kwargs.copy()
544
+
545
+ if self.config.use_bidirectional_attention:
546
+ mask_kwargs["or_mask_function"] = lambda *args: torch.tensor(True, dtype=torch.bool)
547
+ sliding_mask_kwargs["or_mask_function"] = _bidirectional_window_overlay(self.config.sliding_window)
548
+
549
+ # Create the masks
550
+ causal_mask_mapping = {
551
+ "full_attention": create_causal_mask(**mask_kwargs),
552
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
553
+ }
554
+
555
+ # embed positions
556
+ hidden_states = inputs_embeds
557
+
558
+ # create position embeddings to be shared across the decoder layers
559
+ position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
560
+ position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
561
+
562
+ # decoder layers
563
+ all_hidden_states = () if output_hidden_states else None
564
+ all_self_attns = () if output_attentions else None
565
+
566
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
567
+ if output_hidden_states:
568
+ all_hidden_states += (hidden_states,)
569
+
570
+ layer_outputs = decoder_layer(
571
+ hidden_states,
572
+ position_embeddings_global=position_embeddings_global,
573
+ position_embeddings_local=position_embeddings_local,
574
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
575
+ position_ids=position_ids,
576
+ past_key_values=past_key_values,
577
+ output_attentions=output_attentions,
578
+ use_cache=use_cache,
579
+ cache_position=cache_position,
580
+ **kwargs,
581
+ )
582
+
583
+ hidden_states = layer_outputs[0]
584
+
585
+ if output_attentions:
586
+ all_self_attns += (layer_outputs[1],)
587
+
588
+ hidden_states = self.norm(hidden_states)
589
+
590
+ if output_hidden_states:
591
+ all_hidden_states += (hidden_states,)
592
+
593
+ return BaseModelOutputWithPast(
594
+ last_hidden_state=hidden_states,
595
+ past_key_values=past_key_values,
596
+ hidden_states=all_hidden_states,
597
+ attentions=all_self_attns,
598
+ )
599
+
600
+
601
+ @auto_docstring
602
+ class Gemma3ForCausalLM(Gemma3PreTrainedModel, GenerationMixin):
603
+ _tied_weights_keys = ["lm_head.weight"]
604
+ _tp_plan = {"lm_head": "colwise_rep"}
605
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
606
+ config: Gemma3TextConfig
607
+ base_model_prefix = "language_model"
608
+
609
+ def __init__(self, config: Gemma3TextConfig):
610
+ super().__init__(config)
611
+ self.model = Gemma3TextModel(config)
612
+ self.vocab_size = config.vocab_size
613
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
614
+
615
+ # Initialize weights and apply final processing
616
+ self.post_init()
617
+
618
+ @can_return_tuple
619
+ @auto_docstring
620
+ def forward(
621
+ self,
622
+ input_ids: Optional[torch.LongTensor] = None,
623
+ attention_mask: Optional[torch.Tensor] = None,
624
+ position_ids: Optional[torch.LongTensor] = None,
625
+ past_key_values: Optional[Cache] = None,
626
+ inputs_embeds: Optional[torch.FloatTensor] = None,
627
+ labels: Optional[torch.LongTensor] = None,
628
+ use_cache: Optional[bool] = None,
629
+ output_attentions: Optional[bool] = None,
630
+ output_hidden_states: Optional[bool] = None,
631
+ cache_position: Optional[torch.LongTensor] = None,
632
+ logits_to_keep: Union[int, torch.Tensor] = 0,
633
+ **kwargs,
634
+ ) -> CausalLMOutputWithPast:
635
+ r"""
636
+ Example:
637
+
638
+ ```python
639
+ >>> from transformers import AutoTokenizer, Gemma3ForCausalLM
640
+
641
+ >>> model = Gemma3ForCausalLM.from_pretrained("google/gemma-2-9b")
642
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
643
+
644
+ >>> prompt = "What is your favorite condiment?"
645
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
646
+
647
+ >>> # Generate
648
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
649
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
650
+ "What is your favorite condiment?"
651
+ ```"""
652
+
653
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
654
+ output_hidden_states = (
655
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
656
+ )
657
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
658
+ outputs: BaseModelOutputWithPast = self.model(
659
+ input_ids=input_ids,
660
+ attention_mask=attention_mask,
661
+ position_ids=position_ids,
662
+ past_key_values=past_key_values,
663
+ inputs_embeds=inputs_embeds,
664
+ use_cache=use_cache,
665
+ output_attentions=output_attentions,
666
+ output_hidden_states=output_hidden_states,
667
+ cache_position=cache_position,
668
+ **kwargs,
669
+ )
670
+
671
+ hidden_states = outputs.last_hidden_state
672
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
673
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
674
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
675
+ if self.config.final_logit_softcapping is not None:
676
+ logits = logits / self.config.final_logit_softcapping
677
+ logits = torch.tanh(logits)
678
+ logits = logits * self.config.final_logit_softcapping
679
+
680
+ loss = None
681
+ if labels is not None:
682
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
683
+
684
+ return CausalLMOutputWithPast(
685
+ loss=loss,
686
+ logits=logits,
687
+ past_key_values=outputs.past_key_values,
688
+ hidden_states=outputs.hidden_states,
689
+ attentions=outputs.attentions,
690
+ )
691
+
692
+
693
+ class Gemma3MultiModalProjector(nn.Module):
694
+ def __init__(self, config: Gemma3Config):
695
+ super().__init__()
696
+
697
+ self.mm_input_projection_weight = nn.Parameter(
698
+ torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
699
+ )
700
+
701
+ self.mm_soft_emb_norm = Gemma3RMSNorm(
702
+ config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
703
+ )
704
+
705
+ self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
706
+ self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
707
+ self.kernel_size = self.patches_per_image // self.tokens_per_side
708
+ self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
709
+
710
+ def forward(self, vision_outputs: torch.Tensor):
711
+ batch_size, _, seq_length = vision_outputs.shape
712
+
713
+ reshaped_vision_outputs = vision_outputs.transpose(1, 2)
714
+ reshaped_vision_outputs = reshaped_vision_outputs.reshape(
715
+ batch_size, seq_length, self.patches_per_image, self.patches_per_image
716
+ )
717
+ reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
718
+
719
+ pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
720
+ pooled_vision_outputs = pooled_vision_outputs.flatten(2)
721
+ pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
722
+
723
+ normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
724
+
725
+ projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
726
+ return projected_vision_outputs.type_as(vision_outputs)
727
+
728
+
729
+ def token_type_ids_mask_function(
730
+ token_type_ids: Optional[torch.Tensor],
731
+ image_group_ids: Optional[torch.Tensor],
732
+ tokens_per_image: int,
733
+ ) -> Optional[Callable]:
734
+ """
735
+ This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths,
736
+ not start and end indices.
737
+ """
738
+ # Do not return an additional mask in this case
739
+ if token_type_ids is None:
740
+ return None
741
+
742
+ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
743
+ # If it's 1 for both query and key/value, we are in an image block
744
+ # NOTE: static cache shape goes beyond input seq length, while token_type_ids.shape[1] == input seq length
745
+ # Since vmap doesn't support `if statement` we workaround it with `torch.where`
746
+ safe_idx = torch.where(kv_idx < token_type_ids.shape[1], kv_idx, 0)
747
+ token_type_ids_at_kv_idx = token_type_ids[batch_idx, safe_idx]
748
+ token_type_ids_at_kv_idx = torch.where(kv_idx < token_type_ids.shape[1], token_type_ids_at_kv_idx, 0)
749
+
750
+ image_group_ids_at_kv_idx = image_group_ids[batch_idx, safe_idx]
751
+ image_group_ids_at_kv_idx = torch.where(kv_idx < image_group_ids.shape[1], image_group_ids_at_kv_idx, -1)
752
+
753
+ is_image_block = (token_type_ids[batch_idx, q_idx] == 1) & (token_type_ids_at_kv_idx == 1)
754
+ same_image_block = image_group_ids[batch_idx, q_idx] == image_group_ids_at_kv_idx
755
+
756
+ # This is bidirectional attention whenever we are dealing with image tokens
757
+ return is_image_block & same_image_block
758
+
759
+ return inner_mask
760
+
761
+
762
+ @auto_docstring(
763
+ custom_intro="""
764
+ The Base Gemma3 model which consists of a vision backbone and a language model without language modeling head.,
765
+ """
766
+ )
767
+ class Gemma3Model(Gemma3PreTrainedModel):
768
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
769
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
770
+ accepts_loss_kwargs = False
771
+
772
+ def __init__(self, config: Gemma3Config):
773
+ super().__init__(config)
774
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
775
+ self.multi_modal_projector = Gemma3MultiModalProjector(config)
776
+ self.vocab_size = config.text_config.vocab_size
777
+
778
+ language_model = AutoModel.from_config(config=config.text_config)
779
+ self.language_model = language_model
780
+
781
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
782
+ self.post_init()
783
+
784
+ def get_input_embeddings(self):
785
+ return self.language_model.get_input_embeddings()
786
+
787
+ def set_input_embeddings(self, value):
788
+ self.language_model.set_input_embeddings(value)
789
+
790
+ def set_decoder(self, decoder):
791
+ self.language_model = decoder
792
+
793
+ def get_decoder(self):
794
+ return self.language_model
795
+
796
+ def get_image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
797
+ """
798
+ Projects the last hidden state from the vision model into language model space.
799
+
800
+ Args:
801
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
802
+ The tensors corresponding to the input images.
803
+ Returns:
804
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
805
+ """
806
+ vision_outputs = self.vision_tower(pixel_values=pixel_values).last_hidden_state
807
+ image_features = self.multi_modal_projector(vision_outputs)
808
+ return image_features
809
+
810
+ def get_placeholder_mask(
811
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
812
+ ):
813
+ """
814
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
815
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
816
+ """
817
+ if input_ids is None:
818
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
819
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
820
+ )
821
+ special_image_mask = special_image_mask.all(-1)
822
+ else:
823
+ special_image_mask = input_ids == self.config.image_token_id
824
+
825
+ n_image_tokens = special_image_mask.sum()
826
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
827
+ n_image_features = image_features.shape[0] * image_features.shape[1]
828
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
829
+ raise ValueError(
830
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
831
+ )
832
+ return special_image_mask
833
+
834
+ @can_return_tuple
835
+ @auto_docstring
836
+ def forward(
837
+ self,
838
+ input_ids: Optional[torch.LongTensor] = None,
839
+ pixel_values: Optional[torch.FloatTensor] = None,
840
+ attention_mask: Optional[torch.Tensor] = None,
841
+ position_ids: Optional[torch.LongTensor] = None,
842
+ past_key_values: Optional[Cache] = None,
843
+ token_type_ids: Optional[torch.LongTensor] = None,
844
+ cache_position: Optional[torch.LongTensor] = None,
845
+ inputs_embeds: Optional[torch.FloatTensor] = None,
846
+ labels: Optional[torch.LongTensor] = None,
847
+ use_cache: Optional[bool] = None,
848
+ output_attentions: Optional[bool] = None,
849
+ output_hidden_states: Optional[bool] = None,
850
+ return_dict: Optional[bool] = None,
851
+ **lm_kwargs,
852
+ ) -> Union[tuple, Gemma3ModelOutputWithPast]:
853
+ r"""
854
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
855
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
856
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
857
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
858
+
859
+ Example:
860
+
861
+ ```python
862
+ >>> from PIL import Image
863
+ >>> import requests
864
+ >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
865
+
866
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma32-3b-mix-224")
867
+ >>> processor = AutoProcessor.from_pretrained("google/gemma32-3b-mix-224")
868
+
869
+ >>> prompt = "Where is the cat standing?"
870
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
871
+ >>> image = Image.open(requests.get(url, stream=True).raw)
872
+
873
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
874
+
875
+ >>> # Generate
876
+ >>> generate_ids = model.generate(**inputs,)
877
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
878
+ "Where is the cat standing?\nsnow"
879
+ ```"""
880
+ if (input_ids is None) ^ (inputs_embeds is not None):
881
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
882
+
883
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
884
+ output_hidden_states = (
885
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
886
+ )
887
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
888
+
889
+ # Replace image id with PAD if the image token if OOV, to avoid index-errors
890
+ if input_ids is not None and self.config.image_token_id >= self.vocab_size:
891
+ special_image_mask = input_ids == self.config.image_token_id
892
+ llm_input_ids = input_ids.clone()
893
+ llm_input_ids[special_image_mask] = 0
894
+ else:
895
+ llm_input_ids = input_ids
896
+
897
+ if inputs_embeds is None:
898
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
899
+
900
+ if cache_position is None:
901
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
902
+ cache_position = torch.arange(
903
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
904
+ )
905
+
906
+ # Merge text and images
907
+ if pixel_values is not None:
908
+ image_features = self.get_image_features(pixel_values)
909
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
910
+ special_image_mask = self.get_placeholder_mask(
911
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
912
+ )
913
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
914
+
915
+ # It may already have been prepared by e.g. `generate`
916
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
917
+ # Prepare mask arguments
918
+ mask_kwargs = {
919
+ "config": self.config.get_text_config(),
920
+ "input_embeds": inputs_embeds,
921
+ "attention_mask": attention_mask,
922
+ "cache_position": cache_position,
923
+ "past_key_values": past_key_values,
924
+ "position_ids": position_ids,
925
+ }
926
+ # NOTE: this `is_prefill` logic is not flawless, it fails when we're using a cache eagerly initialized
927
+ # (e.g. compiled prefill) AND `pixel_values` are not provided. Determining prefill in that case requires
928
+ # checking data values, which is not compile-compatible.
929
+ is_prefill = (
930
+ not use_cache
931
+ or past_key_values is None
932
+ or not past_key_values.is_initialized
933
+ or pixel_values is not None
934
+ )
935
+ if token_type_ids is not None and is_prefill:
936
+ # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
937
+
938
+ # First find where a new image block starts: 1 if image and previous not image
939
+ # The images cannot attend to future images, but can attend to all prev images and to itself
940
+ # bidirectionally
941
+ is_image = (token_type_ids == 1).to(cache_position.device)
942
+ new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
943
+ image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
944
+ image_group_ids = torch.where(
945
+ is_image, image_group_ids, torch.full_like(token_type_ids, -1, device=is_image.device)
946
+ )
947
+ mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
948
+ token_type_ids.to(cache_position.device), image_group_ids, self.config.mm_tokens_per_image
949
+ )
950
+
951
+ # Create the masks
952
+ causal_mask_mapping = {
953
+ "full_attention": create_causal_mask(**mask_kwargs),
954
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
955
+ }
956
+
957
+ outputs = self.language_model(
958
+ attention_mask=causal_mask_mapping,
959
+ position_ids=position_ids,
960
+ past_key_values=past_key_values,
961
+ inputs_embeds=inputs_embeds,
962
+ use_cache=use_cache,
963
+ output_attentions=output_attentions,
964
+ output_hidden_states=output_hidden_states,
965
+ return_dict=True,
966
+ cache_position=cache_position,
967
+ **lm_kwargs,
968
+ )
969
+
970
+ return Gemma3ModelOutputWithPast(
971
+ last_hidden_state=outputs.last_hidden_state,
972
+ past_key_values=outputs.past_key_values if use_cache else None,
973
+ hidden_states=outputs.hidden_states,
974
+ attentions=outputs.attentions,
975
+ image_hidden_states=image_features if pixel_values is not None else None,
976
+ )
977
+
978
+
979
+ @auto_docstring(
980
+ custom_intro="""
981
+ The Base Gemma3 model which consists of a vision backbone and a language model without language modeling head.,
982
+ """
983
+ )
984
+ class Gemma3ForConditionalGeneration(Gemma3PreTrainedModel, GenerationMixin):
985
+ _checkpoint_conversion_mapping = {
986
+ "^language_model.model": "model.language_model",
987
+ "^vision_tower": "model.vision_tower",
988
+ "^multi_modal_projector": "model.multi_modal_projector",
989
+ "^language_model.lm_head": "lm_head",
990
+ }
991
+ _tied_weights_keys = ["lm_head.weight"]
992
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
993
+ # Fix: https://github.com/huggingface/transformers/issues/40564
994
+ accepts_loss_kwargs = False
995
+
996
+ def __init__(self, config: Gemma3Config):
997
+ super().__init__(config)
998
+ self.model = Gemma3Model(config)
999
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1000
+ self.post_init()
1001
+
1002
+ def get_input_embeddings(self):
1003
+ return self.model.get_input_embeddings()
1004
+
1005
+ def set_input_embeddings(self, value):
1006
+ self.model.set_input_embeddings(value)
1007
+
1008
+ def set_decoder(self, decoder):
1009
+ self.model.set_decoder(decoder)
1010
+
1011
+ def get_decoder(self):
1012
+ return self.model.get_decoder()
1013
+
1014
+ def get_image_features(self, pixel_values):
1015
+ return self.model.get_image_features(pixel_values)
1016
+
1017
+ # Make modules available through conditional class for BC
1018
+ @property
1019
+ def language_model(self):
1020
+ return self.model.language_model
1021
+
1022
+ @property
1023
+ def vision_tower(self):
1024
+ return self.model.vision_tower
1025
+
1026
+ @property
1027
+ def multi_modal_projector(self):
1028
+ return self.model.multi_modal_projector
1029
+
1030
+ @auto_docstring
1031
+ def forward(
1032
+ self,
1033
+ input_ids: Optional[torch.LongTensor] = None,
1034
+ pixel_values: Optional[torch.FloatTensor] = None,
1035
+ attention_mask: Optional[torch.Tensor] = None,
1036
+ position_ids: Optional[torch.LongTensor] = None,
1037
+ past_key_values: Optional[Cache] = None,
1038
+ token_type_ids: Optional[torch.LongTensor] = None,
1039
+ cache_position: Optional[torch.LongTensor] = None,
1040
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1041
+ labels: Optional[torch.LongTensor] = None,
1042
+ use_cache: Optional[bool] = None,
1043
+ output_attentions: Optional[bool] = None,
1044
+ output_hidden_states: Optional[bool] = None,
1045
+ return_dict: Optional[bool] = None,
1046
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1047
+ **lm_kwargs,
1048
+ ) -> Union[tuple, Gemma3CausalLMOutputWithPast]:
1049
+ r"""
1050
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1051
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1052
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1053
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
1054
+
1055
+ Example:
1056
+
1057
+ ```python
1058
+ >>> from PIL import Image
1059
+ >>> import requests
1060
+ >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
1061
+
1062
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
1063
+ >>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
1064
+
1065
+ >>> messages = [
1066
+ ... {
1067
+ ... "role": "system",
1068
+ ... "content": [
1069
+ ... {"type": "text", "text": "You are a helpful assistant."}
1070
+ ... ]
1071
+ ... },
1072
+ ... {
1073
+ ... "role": "user", "content": [
1074
+ ... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
1075
+ ... {"type": "text", "text": "Where is the cat standing?"},
1076
+ ... ]
1077
+ ... },
1078
+ ... ]
1079
+
1080
+ >>> inputs = processor.apply_chat_template(
1081
+ ... messages,
1082
+ ... tokenize=True,
1083
+ ... return_dict=True,
1084
+ ... return_tensors="pt",
1085
+ ... add_generation_prompt=True
1086
+ ... )
1087
+ >>> # Generate
1088
+ >>> generate_ids = model.generate(**inputs)
1089
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1090
+ "user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
1091
+ ```
1092
+ """
1093
+
1094
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1095
+ output_hidden_states = (
1096
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1097
+ )
1098
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1099
+
1100
+ outputs = self.model(
1101
+ input_ids=input_ids,
1102
+ pixel_values=pixel_values,
1103
+ token_type_ids=token_type_ids,
1104
+ attention_mask=attention_mask,
1105
+ position_ids=position_ids,
1106
+ past_key_values=past_key_values,
1107
+ inputs_embeds=inputs_embeds,
1108
+ use_cache=use_cache,
1109
+ labels=labels,
1110
+ output_attentions=output_attentions,
1111
+ output_hidden_states=output_hidden_states,
1112
+ return_dict=return_dict,
1113
+ cache_position=cache_position,
1114
+ **lm_kwargs,
1115
+ )
1116
+
1117
+ hidden_states = outputs[0]
1118
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1119
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1120
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1121
+
1122
+ loss = None
1123
+ if labels is not None:
1124
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1125
+ logits = logits.float()
1126
+ shift_logits = logits[..., :-1, :]
1127
+ shift_labels = labels[..., 1:]
1128
+ if attention_mask is not None:
1129
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
1130
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
1131
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
1132
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
1133
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
1134
+ else:
1135
+ shift_logits = shift_logits.contiguous()
1136
+ shift_labels = shift_labels.contiguous()
1137
+ # Flatten the tokens
1138
+ loss_fct = nn.CrossEntropyLoss()
1139
+
1140
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
1141
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
1142
+ loss = loss_fct(flat_logits, flat_labels)
1143
+
1144
+ if not return_dict:
1145
+ output = (logits,) + outputs[1:]
1146
+ return (loss,) + output if loss is not None else output
1147
+
1148
+ return Gemma3CausalLMOutputWithPast(
1149
+ loss=loss,
1150
+ logits=logits,
1151
+ past_key_values=outputs.past_key_values,
1152
+ hidden_states=outputs.hidden_states,
1153
+ attentions=outputs.attentions,
1154
+ image_hidden_states=outputs.image_hidden_states,
1155
+ )
1156
+
1157
+ def prepare_inputs_for_generation(
1158
+ self,
1159
+ input_ids,
1160
+ past_key_values=None,
1161
+ inputs_embeds=None,
1162
+ cache_position=None,
1163
+ position_ids=None,
1164
+ pixel_values=None,
1165
+ attention_mask=None,
1166
+ token_type_ids=None,
1167
+ use_cache=True,
1168
+ logits_to_keep=None,
1169
+ labels=None,
1170
+ **kwargs,
1171
+ ):
1172
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
1173
+ model_inputs = super().prepare_inputs_for_generation(
1174
+ input_ids,
1175
+ past_key_values=past_key_values,
1176
+ inputs_embeds=inputs_embeds,
1177
+ attention_mask=attention_mask,
1178
+ position_ids=position_ids,
1179
+ cache_position=cache_position,
1180
+ use_cache=use_cache,
1181
+ logits_to_keep=logits_to_keep,
1182
+ token_type_ids=token_type_ids,
1183
+ **kwargs,
1184
+ )
1185
+
1186
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
1187
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
1188
+ if cache_position[0] == 0:
1189
+ model_inputs["pixel_values"] = pixel_values
1190
+
1191
+ return model_inputs
1192
+
1193
+ @staticmethod
1194
+ def create_masks_for_generate(
1195
+ config: PretrainedConfig,
1196
+ input_embeds: torch.Tensor,
1197
+ attention_mask: Optional[torch.Tensor],
1198
+ cache_position: torch.Tensor,
1199
+ past_key_values: Optional[Cache],
1200
+ position_ids: Optional[torch.Tensor],
1201
+ token_type_ids: Optional[torch.Tensor] = None,
1202
+ **kwargs,
1203
+ ) -> dict:
1204
+ # Prepare mask arguments
1205
+ mask_kwargs = {
1206
+ "config": config.get_text_config(),
1207
+ "input_embeds": input_embeds,
1208
+ "attention_mask": attention_mask,
1209
+ "cache_position": cache_position,
1210
+ "past_key_values": past_key_values,
1211
+ "position_ids": position_ids,
1212
+ }
1213
+ # Add the token type ids mask for generate as well
1214
+ if token_type_ids is not None and input_embeds.shape[1] != 1:
1215
+ # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
1216
+
1217
+ # First find where a new image block starts: 1 if image and previous not image
1218
+ # The images cannot attend to future images, but can attend to all prev images and to itself bidirectionally
1219
+ is_image = (token_type_ids == 1).to(cache_position.device)
1220
+ new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
1221
+ image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
1222
+ image_group_ids = torch.where(is_image, image_group_ids, torch.full_like(token_type_ids, -1))
1223
+ mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
1224
+ token_type_ids.to(cache_position.device), image_group_ids, config.mm_tokens_per_image
1225
+ )
1226
+
1227
+ return create_masks_for_generate(**mask_kwargs)
1228
+
1229
+
1230
+ class Gemma3ForSequenceClassification(Gemma3PreTrainedModel):
1231
+ _checkpoint_conversion_mapping = {
1232
+ "^language_model.model": "model.language_model",
1233
+ "^vision_tower": "model.vision_tower",
1234
+ "^multi_modal_projector": "model.multi_modal_projector",
1235
+ }
1236
+
1237
+ def __init__(self, config):
1238
+ super().__init__(config)
1239
+ self.num_labels = config.num_labels
1240
+ self.model = Gemma3Model(config)
1241
+ self.score = nn.Linear(config.text_config.hidden_size, self.num_labels, bias=False)
1242
+
1243
+ # Initialize weights and apply final processing
1244
+ self.post_init()
1245
+
1246
+ def get_input_embeddings(self):
1247
+ return self.model.get_input_embeddings()
1248
+
1249
+ def set_input_embeddings(self, value):
1250
+ self.model.set_input_embeddings(value)
1251
+
1252
+ @can_return_tuple
1253
+ @auto_docstring
1254
+ def forward(
1255
+ self,
1256
+ input_ids: Optional[torch.LongTensor] = None,
1257
+ pixel_values: Optional[torch.FloatTensor] = None,
1258
+ attention_mask: Optional[torch.Tensor] = None,
1259
+ position_ids: Optional[torch.LongTensor] = None,
1260
+ past_key_values: Optional[Cache] = None,
1261
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1262
+ token_type_ids: Optional[torch.LongTensor] = None,
1263
+ labels: Optional[torch.LongTensor] = None,
1264
+ use_cache: Optional[bool] = None,
1265
+ **kwargs: Unpack[TransformersKwargs],
1266
+ ) -> SequenceClassifierOutputWithPast:
1267
+ r"""
1268
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1269
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1270
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1271
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1272
+ """
1273
+
1274
+ transformer_outputs = self.model(
1275
+ input_ids,
1276
+ attention_mask=attention_mask,
1277
+ pixel_values=pixel_values,
1278
+ position_ids=position_ids,
1279
+ past_key_values=past_key_values,
1280
+ inputs_embeds=inputs_embeds,
1281
+ token_type_ids=token_type_ids,
1282
+ use_cache=use_cache,
1283
+ **kwargs,
1284
+ )
1285
+ hidden_states = transformer_outputs.last_hidden_state
1286
+ logits = self.score(hidden_states)
1287
+
1288
+ if input_ids is not None:
1289
+ batch_size = input_ids.shape[0]
1290
+ else:
1291
+ batch_size = inputs_embeds.shape[0]
1292
+
1293
+ if self.config.text_config.pad_token_id is None and batch_size != 1:
1294
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1295
+ if self.config.text_config.pad_token_id is None:
1296
+ last_non_pad_token = -1
1297
+ elif input_ids is not None:
1298
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1299
+ non_pad_mask = (input_ids != self.config.text_config.pad_token_id).to(logits.device, torch.int32)
1300
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1301
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1302
+ else:
1303
+ last_non_pad_token = -1
1304
+ logger.warning_once(
1305
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1306
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1307
+ )
1308
+
1309
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1310
+
1311
+ loss = None
1312
+ if labels is not None:
1313
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1314
+
1315
+ return SequenceClassifierOutputWithPast(
1316
+ loss=loss,
1317
+ logits=pooled_logits,
1318
+ past_key_values=transformer_outputs.past_key_values,
1319
+ hidden_states=transformer_outputs.hidden_states,
1320
+ attentions=transformer_outputs.attentions,
1321
+ )
1322
+
1323
+
1324
+ class Gemma3TextForSequenceClassification(GenericForSequenceClassification, Gemma3PreTrainedModel):
1325
+ """
1326
+ Gemma3TextForSequenceClassification is a text-only sequence classification model that works with Gemma3TextConfig.
1327
+ It uses the generic sequence classification implementation for efficiency and consistency.
1328
+ """
1329
+
1330
+ config: Gemma3TextConfig
1331
+
1332
+
1333
+ __all__ = [
1334
+ "Gemma3PreTrainedModel",
1335
+ "Gemma3TextModel",
1336
+ "Gemma3ForCausalLM",
1337
+ "Gemma3ForConditionalGeneration",
1338
+ "Gemma3Model",
1339
+ "Gemma3ForSequenceClassification",
1340
+ "Gemma3TextForSequenceClassification",
1341
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/modular_gemma3.py ADDED
@@ -0,0 +1,1221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import copy
17
+ from collections.abc import Callable
18
+ from typing import Any, Optional, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+
23
+ from ...cache_utils import Cache, DynamicCache
24
+ from ...configuration_utils import PretrainedConfig, layer_type_validation
25
+ from ...masking_utils import create_causal_mask, create_masks_for_generate, create_sliding_window_causal_mask
26
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
28
+ from ...modeling_outputs import BaseModelOutputWithPast, SequenceClassifierOutputWithPast
29
+ from ...modeling_rope_utils import rope_config_validation
30
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
31
+ from ...processing_utils import Unpack
32
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
33
+ from ...utils.deprecation import deprecate_kwarg
34
+ from ..gemma2.configuration_gemma2 import Gemma2Config
35
+ from ..gemma2.modeling_gemma2 import (
36
+ Gemma2Attention,
37
+ Gemma2ForCausalLM,
38
+ Gemma2MLP,
39
+ Gemma2Model,
40
+ Gemma2PreTrainedModel,
41
+ Gemma2RMSNorm,
42
+ Gemma2RotaryEmbedding,
43
+ apply_rotary_pos_emb,
44
+ eager_attention_forward,
45
+ )
46
+ from ..paligemma.modeling_paligemma import (
47
+ PaligemmaCausalLMOutputWithPast,
48
+ PaliGemmaForConditionalGeneration,
49
+ PaliGemmaModel,
50
+ PaligemmaModelOutputWithPast,
51
+ )
52
+ from ..siglip import SiglipVisionConfig
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ class Gemma3TextConfig(Gemma2Config, PretrainedConfig):
59
+ r"""
60
+ This is the configuration class to store the configuration of a [`Gemma3TextModel`]. It is used to instantiate an Gemma3Text
61
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
62
+ defaults will yield a similar configuration to that of the Gemma3Text-7B.
63
+ e.g. [google/gemma3_text-7b](https://huggingface.co/google/gemma3_text-7b)
64
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
65
+ documentation from [`PretrainedConfig`] for more information.
66
+ Args:
67
+ vocab_size (`int`, *optional*, defaults to 262208):
68
+ Vocabulary size of the Gemma3Text model. Defines the number of different tokens that can be represented by the
69
+ `inputs_ids` passed when calling [`Gemma3TextModel`]
70
+ hidden_size (`int`, *optional*, defaults to 2304):
71
+ Dimension of the hidden representations.
72
+ intermediate_size (`int`, *optional*, defaults to 9216):
73
+ Dimension of the MLP representations.
74
+ num_hidden_layers (`int`, *optional*, defaults to 26):
75
+ Number of hidden layers in the Transformer decoder.
76
+ num_attention_heads (`int`, *optional*, defaults to 8):
77
+ Number of attention heads for each attention layer in the Transformer decoder.
78
+ num_key_value_heads (`int`, *optional*, defaults to 4):
79
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
80
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
81
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
82
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
83
+ by meanpooling all the original heads within that group. For more details, check out [this
84
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
85
+ `num_attention_heads`.
86
+ head_dim (`int`, *optional*, defaults to 256):
87
+ The attention head dimension.
88
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
89
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
90
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
91
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
92
+ The maximum sequence length that this model might ever be used with.
93
+ initializer_range (`float`, *optional*, defaults to 0.02):
94
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
95
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
96
+ The epsilon used by the rms normalization layers.
97
+ use_cache (`bool`, *optional*, defaults to `True`):
98
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
99
+ relevant if `config.is_decoder=True`.
100
+ pad_token_id (`int`, *optional*, defaults to 0):
101
+ Padding token id.
102
+ eos_token_id (`int`, *optional*, defaults to 1):
103
+ End of stream token id.
104
+ bos_token_id (`int`, *optional*, defaults to 2):
105
+ Beginning of stream token id.
106
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
107
+ Whether to tie weight embeddings
108
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
109
+ The base period of the RoPE embeddings.
110
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
111
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
112
+ attention_dropout (`float`, *optional*, defaults to 0.0):
113
+ The dropout ratio for the attention probabilities.
114
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
115
+ Scaling factor used on the attention scores
116
+ sliding_window (`int`, *optional*, defaults to 4096):
117
+ In Gemma3Text, every other layer uses sliding window attention. This is the size of the sliding window.
118
+ layer_types (`list`, *optional*):
119
+ Attention pattern for each layer.
120
+ final_logit_softcapping (`float`, *optional*):
121
+ Scaling factor when applying tanh softcapping on the logits.
122
+ attn_logit_softcapping (`float`, *optional*):
123
+ Scaling factor when applying tanh softcapping on the attention scores.
124
+ rope_scaling (`Dict`, *optional*):
125
+ Dictionary containing the scaling configuration for the RoPE embeddings used in global attention. NOTE: if you apply new rope type
126
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
127
+ accordingly.
128
+ Expected contents:
129
+ `rope_type` (`str`):
130
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
131
+ 'llama3'], with 'default' being the original RoPE implementation.
132
+ `factor` (`float`, *optional*):
133
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
134
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
135
+ original maximum pre-trained length.
136
+ `original_max_position_embeddings` (`int`, *optional*):
137
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
138
+ pretraining.
139
+ `attention_factor` (`float`, *optional*):
140
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
141
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
142
+ `factor` field to infer the suggested value.
143
+ `beta_fast` (`float`, *optional*):
144
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
145
+ ramp function. If unspecified, it defaults to 32.
146
+ `beta_slow` (`float`, *optional*):
147
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
148
+ ramp function. If unspecified, it defaults to 1.
149
+ `short_factor` (`list[float]`, *optional*):
150
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
151
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
152
+ size divided by the number of attention heads divided by 2
153
+ `long_factor` (`list[float]`, *optional*):
154
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
155
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
156
+ size divided by the number of attention heads divided by 2
157
+ `low_freq_factor` (`float`, *optional*):
158
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
159
+ `high_freq_factor` (`float`, *optional*):
160
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
161
+ rope_local_base_freq (float, *optional*, defaults to 10000.0):
162
+ The base period of the RoPE embeddings for local attention.
163
+ use_bidirectional_attention (`bool`, *optional*, defaults to `False`): If True, the model will attend to all
164
+ text tokens instead of using a causal mask. This does not change behavior for vision tokens.
165
+
166
+ ```python
167
+ >>> from transformers import Gemma3TextModel, Gemma3TextConfig
168
+ >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
169
+ >>> configuration = Gemma3TextConfig()
170
+ >>> # Initializing a model from the gemma3_text-7b style configuration
171
+ >>> model = Gemma3TextModel(configuration)
172
+ >>> # Accessing the model configuration
173
+ >>> configuration = model.config
174
+ ```
175
+ """
176
+
177
+ model_type = "gemma3_text"
178
+
179
+ def __init__(
180
+ self,
181
+ vocab_size=262_208,
182
+ hidden_size=2304,
183
+ intermediate_size=9216,
184
+ num_hidden_layers=26,
185
+ num_attention_heads=8,
186
+ num_key_value_heads=4,
187
+ head_dim=256,
188
+ hidden_activation="gelu_pytorch_tanh",
189
+ max_position_embeddings=131_072,
190
+ initializer_range=0.02,
191
+ rms_norm_eps=1e-6,
192
+ use_cache=True,
193
+ pad_token_id=0,
194
+ eos_token_id=1,
195
+ bos_token_id=2,
196
+ tie_word_embeddings=True,
197
+ rope_theta=1_000_000.0,
198
+ attention_bias=False,
199
+ attention_dropout=0.0,
200
+ query_pre_attn_scalar=256,
201
+ sliding_window=4096,
202
+ layer_types=None,
203
+ final_logit_softcapping=None,
204
+ attn_logit_softcapping=None,
205
+ rope_scaling=None,
206
+ rope_local_base_freq=10_000.0,
207
+ use_bidirectional_attention=False,
208
+ **kwargs,
209
+ ):
210
+ PretrainedConfig.__init__(
211
+ pad_token_id=pad_token_id,
212
+ bos_token_id=bos_token_id,
213
+ eos_token_id=eos_token_id,
214
+ tie_word_embeddings=tie_word_embeddings,
215
+ **kwargs,
216
+ )
217
+ self.vocab_size = vocab_size
218
+ self.max_position_embeddings = max_position_embeddings
219
+ self.hidden_size = hidden_size
220
+ self.intermediate_size = intermediate_size
221
+ self.num_hidden_layers = num_hidden_layers
222
+ self.num_attention_heads = num_attention_heads
223
+ self.head_dim = head_dim
224
+ self.num_key_value_heads = num_key_value_heads
225
+ self.initializer_range = initializer_range
226
+ self.rms_norm_eps = rms_norm_eps
227
+ self.use_cache = use_cache
228
+ self.rope_theta = rope_theta
229
+ self.attention_bias = attention_bias
230
+ self.attention_dropout = attention_dropout
231
+ self.hidden_activation = hidden_activation
232
+ self.query_pre_attn_scalar = query_pre_attn_scalar
233
+ self.sliding_window = sliding_window
234
+ self.final_logit_softcapping = final_logit_softcapping
235
+ self.attn_logit_softcapping = attn_logit_softcapping
236
+ self.layer_types = layer_types
237
+ self.use_bidirectional_attention = use_bidirectional_attention
238
+ if use_bidirectional_attention:
239
+ self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
240
+
241
+ self.rope_local_base_freq = rope_local_base_freq
242
+ self.rope_scaling = rope_scaling
243
+ rope_config_validation(self)
244
+
245
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
246
+ self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
247
+
248
+ if self.layer_types is None:
249
+ self.layer_types = [
250
+ "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
251
+ for i in range(self.num_hidden_layers)
252
+ ]
253
+ layer_type_validation(self.layer_types, self.num_hidden_layers)
254
+
255
+
256
+ class Gemma3Config(PretrainedConfig):
257
+ r"""
258
+ This is the configuration class to store the configuration of a [`Gemma3ForConditionalGeneration`]. It is used to instantiate an
259
+ Gemma3ForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration
260
+ with the defaults will yield a similar configuration to that of the PaliGemma-2B.
261
+
262
+ e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b)
263
+
264
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
265
+ documentation from [`PretrainedConfig`] for more information.
266
+
267
+ Args:
268
+ text_config (`Union[Gemma3TextConfig, dict]`, *optional*):
269
+ The config object of the text backbone.
270
+ vision_config (`Union[AutoConfig, dict]`, *optional*):
271
+ Custom vision config or dict.
272
+ mm_tokens_per_image (`int`, *optional*, defaults to 256):
273
+ The number of tokens per image embedding.
274
+ boi_token_index (`int`, *optional*, defaults to 255999):
275
+ The begin-of-image token index to wrap the image prompt.
276
+ eoi_token_index (`int`, *optional*, defaults to 256000):
277
+ The end-of-image token index to wrap the image prompt.
278
+ image_token_index (`int`, *optional*, defaults to 262144):
279
+ The image token index to encode the image prompt.
280
+ initializer_range (`float`, *optional*, defaults to 0.02):
281
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
282
+
283
+
284
+ Example:
285
+
286
+ ```python
287
+ >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig
288
+
289
+ >>> # Initializing a Siglip-like vision config
290
+ >>> vision_config = SiglipVisionConfig()
291
+
292
+ >>> # Initializing a Gemma3 Text config
293
+ >>> text_config = Gemma3TextConfig()
294
+
295
+ >>> # Initializing a Gemma3 gemma-3-4b style configuration
296
+ >>> configuration = Gemma3Config(vision_config, text_config)
297
+
298
+ >>> # Initializing a model from the gemma-3-4b style configuration
299
+ >>> model = Gemma3TextConfig(configuration)
300
+
301
+ >>> # Accessing the model configuration
302
+ >>> configuration = model.config
303
+ ```"""
304
+
305
+ model_type = "gemma3"
306
+ attribute_map = {
307
+ "image_token_id": "image_token_index",
308
+ "boi_token_id": "boi_token_index",
309
+ "eoi_token_id": "eoi_token_index",
310
+ }
311
+ sub_configs = {
312
+ "text_config": Gemma3TextConfig,
313
+ "vision_config": SiglipVisionConfig,
314
+ }
315
+
316
+ def __init__(
317
+ self,
318
+ text_config: Optional[Union[Gemma3TextConfig, dict[str, Any]]] = None,
319
+ vision_config: Optional[Union[SiglipVisionConfig, dict[str, Any]]] = None,
320
+ mm_tokens_per_image: int = 256,
321
+ boi_token_index: int = 255_999,
322
+ eoi_token_index: int = 256_000,
323
+ image_token_index: int = 262_144,
324
+ initializer_range: float = 0.02,
325
+ **kwargs,
326
+ ):
327
+ if text_config is None:
328
+ text_config = Gemma3TextConfig()
329
+ logger.info("text_config is None, using default Gemma3TextConfig text config.")
330
+ elif isinstance(text_config, dict):
331
+ text_config = Gemma3TextConfig(**text_config)
332
+
333
+ if isinstance(vision_config, dict):
334
+ vision_config = SiglipVisionConfig(**vision_config)
335
+ elif vision_config is None:
336
+ vision_config = SiglipVisionConfig()
337
+ logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
338
+
339
+ self.text_config = text_config
340
+ self.vision_config = vision_config
341
+ self.mm_tokens_per_image = mm_tokens_per_image
342
+ self.boi_token_index = boi_token_index
343
+ self.eoi_token_index = eoi_token_index
344
+ self.image_token_index = image_token_index
345
+ self.initializer_range = initializer_range
346
+
347
+ super().__init__(**kwargs)
348
+
349
+
350
+ class Gemma3ModelOutputWithPast(PaligemmaModelOutputWithPast):
351
+ pass
352
+
353
+
354
+ class Gemma3CausalLMOutputWithPast(PaligemmaCausalLMOutputWithPast):
355
+ pass
356
+
357
+
358
+ class Gemma3TextScaledWordEmbedding(nn.Embedding):
359
+ """
360
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
361
+ """
362
+
363
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
364
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
365
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
366
+
367
+ def forward(self, input_ids: torch.Tensor):
368
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
369
+
370
+
371
+ class Gemma3MLP(Gemma2MLP):
372
+ def __init__(self, config: Gemma3TextConfig):
373
+ super().__init__(config)
374
+
375
+
376
+ class Gemma3RMSNorm(Gemma2RMSNorm):
377
+ def __init__(self, dim: int, eps: float = 1e-6):
378
+ super().__init__(dim=dim, eps=eps)
379
+
380
+
381
+ class Gemma3RotaryEmbedding(Gemma2RotaryEmbedding):
382
+ def __init__(self, config: Gemma3TextConfig, device=None):
383
+ super().__init__(config)
384
+
385
+
386
+ # Weird way to inherit but otherwise the sliding window gets defined first and can't access `is_sliding`
387
+ class Gemma3Attention(Gemma2Attention):
388
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
389
+ self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
390
+
391
+ super().__init__(config, layer_idx)
392
+ self.sliding_window = config.sliding_window if self.is_sliding else None
393
+ self.is_causal = not self.config.use_bidirectional_attention
394
+
395
+ self.q_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
396
+ self.k_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
397
+
398
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
399
+ def forward(
400
+ self,
401
+ hidden_states: torch.Tensor,
402
+ position_embeddings: torch.Tensor,
403
+ attention_mask: Optional[torch.Tensor],
404
+ past_key_values: Optional[Cache] = None,
405
+ cache_position: Optional[torch.LongTensor] = None,
406
+ **kwargs: Unpack[FlashAttentionKwargs],
407
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
408
+ input_shape = hidden_states.shape[:-1]
409
+ hidden_shape = (*input_shape, -1, self.head_dim)
410
+
411
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
412
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
413
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
414
+
415
+ query_states = self.q_norm(query_states)
416
+ key_states = self.k_norm(key_states)
417
+
418
+ cos, sin = position_embeddings
419
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
420
+
421
+ if past_key_values is not None:
422
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
423
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
424
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
425
+
426
+ attention_interface: Callable = eager_attention_forward
427
+ if self.config._attn_implementation != "eager":
428
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
429
+
430
+ attn_output, attn_weights = attention_interface(
431
+ self,
432
+ query_states,
433
+ key_states,
434
+ value_states,
435
+ attention_mask,
436
+ dropout=self.attention_dropout if self.training else 0.0,
437
+ scaling=self.scaling,
438
+ sliding_window=self.sliding_window,
439
+ **kwargs,
440
+ )
441
+
442
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
443
+ attn_output = self.o_proj(attn_output)
444
+ return attn_output, attn_weights
445
+
446
+
447
+ class Gemma3DecoderLayer(GradientCheckpointingLayer):
448
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
449
+ super().__init__()
450
+ self.config = config
451
+ self.hidden_size = config.hidden_size
452
+ self.layer_idx = layer_idx
453
+ self.attention_type = config.layer_types[layer_idx]
454
+ self.self_attn = Gemma3Attention(config=config, layer_idx=layer_idx)
455
+ self.mlp = Gemma3MLP(config)
456
+ self.input_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
457
+ self.post_attention_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
458
+ self.pre_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
459
+ self.post_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
460
+
461
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
462
+ def forward(
463
+ self,
464
+ hidden_states: torch.Tensor,
465
+ position_embeddings_global: torch.Tensor,
466
+ position_embeddings_local: torch.Tensor,
467
+ attention_mask: Optional[torch.Tensor] = None,
468
+ position_ids: Optional[torch.LongTensor] = None,
469
+ past_key_values: Optional[Cache] = None,
470
+ output_attentions: Optional[bool] = False,
471
+ use_cache: Optional[bool] = False,
472
+ cache_position: Optional[torch.LongTensor] = None,
473
+ **kwargs,
474
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
475
+ residual = hidden_states
476
+
477
+ hidden_states = self.input_layernorm(hidden_states)
478
+
479
+ # apply global RoPE to non-sliding layer only
480
+ if self.self_attn.is_sliding:
481
+ position_embeddings = position_embeddings_local
482
+ else:
483
+ position_embeddings = position_embeddings_global
484
+
485
+ hidden_states, self_attn_weights = self.self_attn(
486
+ hidden_states=hidden_states,
487
+ position_embeddings=position_embeddings,
488
+ attention_mask=attention_mask,
489
+ position_ids=position_ids,
490
+ past_key_values=past_key_values,
491
+ output_attentions=output_attentions,
492
+ use_cache=use_cache,
493
+ cache_position=cache_position,
494
+ **kwargs,
495
+ )
496
+ hidden_states = self.post_attention_layernorm(hidden_states)
497
+ hidden_states = residual + hidden_states
498
+
499
+ residual = hidden_states
500
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
501
+ hidden_states = self.mlp(hidden_states)
502
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
503
+ hidden_states = residual + hidden_states
504
+
505
+ outputs = (hidden_states,)
506
+
507
+ if output_attentions:
508
+ outputs += (self_attn_weights,)
509
+
510
+ return outputs
511
+
512
+
513
+ GEMMA3_START_DOCSTRING = None
514
+
515
+
516
+ class Gemma3PreTrainedModel(Gemma2PreTrainedModel):
517
+ base_model_prefix = ""
518
+ _no_split_modules = [
519
+ "Gemma3DecoderLayer",
520
+ "SiglipVisionEmbeddings",
521
+ "SiglipEncoderLayer",
522
+ "SiglipMultiheadAttentionPoolingHead",
523
+ ]
524
+
525
+ def _init_weights(self, module):
526
+ PreTrainedModel._init_weights(self, module)
527
+ if isinstance(module, Gemma3MultiModalProjector):
528
+ module.mm_input_projection_weight.data.zero_()
529
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
530
+ elif "RMSNorm" in module.__class__.__name__:
531
+ module.weight.data.zero_()
532
+
533
+
534
+ def _bidirectional_window_overlay(sliding_window: int) -> Callable[[int, int, int, int], bool]:
535
+ """
536
+ Enables a bidirectional mask within the sliding window.
537
+ """
538
+
539
+ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
540
+ """A token can attend to any other token if their absolute distance is within
541
+ the (exclusive) sliding window size (distance < sliding_window)."""
542
+ return abs(q_idx - kv_idx) < sliding_window
543
+
544
+ return inner_mask
545
+
546
+
547
+ class Gemma3TextModel(Gemma2Model):
548
+ config: Gemma3TextConfig
549
+
550
+ def __init__(self, config: Gemma3TextConfig):
551
+ super().__init__(config)
552
+
553
+ # Gemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
554
+ self.embed_tokens = Gemma3TextScaledWordEmbedding(
555
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
556
+ )
557
+
558
+ # TODO: raushan fix this after RoPE refactor. For now we hack it by reassigning thetas
559
+ # when we want to create a local RoPE layer. Config defaults should hold values for global RoPE
560
+ config = copy.deepcopy(config)
561
+ config.rope_theta = config.rope_local_base_freq
562
+ config.rope_scaling = {"rope_type": "default"}
563
+ self.rotary_emb_local = Gemma3RotaryEmbedding(config=config)
564
+
565
+ def forward(
566
+ self,
567
+ input_ids: Optional[torch.LongTensor] = None,
568
+ attention_mask: Optional[torch.Tensor] = None,
569
+ position_ids: Optional[torch.LongTensor] = None,
570
+ past_key_values: Optional[Cache] = None,
571
+ inputs_embeds: Optional[torch.FloatTensor] = None,
572
+ use_cache: Optional[bool] = None,
573
+ output_attentions: Optional[bool] = None,
574
+ output_hidden_states: Optional[bool] = None,
575
+ cache_position: Optional[torch.LongTensor] = None,
576
+ **kwargs: Unpack[TransformersKwargs],
577
+ ) -> BaseModelOutputWithPast:
578
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
579
+ output_hidden_states = (
580
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
581
+ )
582
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
583
+
584
+ if (input_ids is None) ^ (inputs_embeds is not None):
585
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
586
+
587
+ if self.gradient_checkpointing and self.training and use_cache:
588
+ logger.warning_once(
589
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
590
+ )
591
+ use_cache = False
592
+
593
+ if inputs_embeds is None:
594
+ inputs_embeds = self.embed_tokens(input_ids)
595
+
596
+ if use_cache and past_key_values is None and not self.training:
597
+ past_key_values = DynamicCache(config=self.config)
598
+
599
+ if cache_position is None:
600
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
601
+ cache_position = torch.arange(
602
+ past_seen_tokens,
603
+ past_seen_tokens + inputs_embeds.shape[1],
604
+ device=inputs_embeds.device,
605
+ )
606
+
607
+ if position_ids is None:
608
+ position_ids = cache_position.unsqueeze(0)
609
+
610
+ # It may already have been prepared by e.g. `generate`
611
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
612
+ # Prepare mask arguments
613
+ mask_kwargs = {
614
+ "config": self.config,
615
+ "input_embeds": inputs_embeds,
616
+ "attention_mask": attention_mask,
617
+ "cache_position": cache_position,
618
+ "past_key_values": past_key_values,
619
+ "position_ids": position_ids,
620
+ }
621
+ sliding_mask_kwargs = mask_kwargs.copy()
622
+
623
+ if self.config.use_bidirectional_attention:
624
+ mask_kwargs["or_mask_function"] = lambda *args: torch.tensor(True, dtype=torch.bool)
625
+ sliding_mask_kwargs["or_mask_function"] = _bidirectional_window_overlay(self.config.sliding_window)
626
+
627
+ # Create the masks
628
+ causal_mask_mapping = {
629
+ "full_attention": create_causal_mask(**mask_kwargs),
630
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
631
+ }
632
+
633
+ # embed positions
634
+ hidden_states = inputs_embeds
635
+
636
+ # create position embeddings to be shared across the decoder layers
637
+ position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
638
+ position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
639
+
640
+ # decoder layers
641
+ all_hidden_states = () if output_hidden_states else None
642
+ all_self_attns = () if output_attentions else None
643
+
644
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
645
+ if output_hidden_states:
646
+ all_hidden_states += (hidden_states,)
647
+
648
+ layer_outputs = decoder_layer(
649
+ hidden_states,
650
+ position_embeddings_global=position_embeddings_global,
651
+ position_embeddings_local=position_embeddings_local,
652
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
653
+ position_ids=position_ids,
654
+ past_key_values=past_key_values,
655
+ output_attentions=output_attentions,
656
+ use_cache=use_cache,
657
+ cache_position=cache_position,
658
+ **kwargs,
659
+ )
660
+
661
+ hidden_states = layer_outputs[0]
662
+
663
+ if output_attentions:
664
+ all_self_attns += (layer_outputs[1],)
665
+
666
+ hidden_states = self.norm(hidden_states)
667
+
668
+ if output_hidden_states:
669
+ all_hidden_states += (hidden_states,)
670
+
671
+ return BaseModelOutputWithPast(
672
+ last_hidden_state=hidden_states,
673
+ past_key_values=past_key_values,
674
+ hidden_states=all_hidden_states,
675
+ attentions=all_self_attns,
676
+ )
677
+
678
+
679
+ class Gemma3ForCausalLM(Gemma2ForCausalLM):
680
+ config: Gemma3TextConfig
681
+ base_model_prefix = "language_model"
682
+
683
+ def __init__(self, config: Gemma3TextConfig):
684
+ super().__init__(config)
685
+ self.model = Gemma3TextModel(config)
686
+
687
+
688
+ class Gemma3MultiModalProjector(nn.Module):
689
+ def __init__(self, config: Gemma3Config):
690
+ super().__init__()
691
+
692
+ self.mm_input_projection_weight = nn.Parameter(
693
+ torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
694
+ )
695
+
696
+ self.mm_soft_emb_norm = Gemma3RMSNorm(
697
+ config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
698
+ )
699
+
700
+ self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
701
+ self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
702
+ self.kernel_size = self.patches_per_image // self.tokens_per_side
703
+ self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
704
+
705
+ def forward(self, vision_outputs: torch.Tensor):
706
+ batch_size, _, seq_length = vision_outputs.shape
707
+
708
+ reshaped_vision_outputs = vision_outputs.transpose(1, 2)
709
+ reshaped_vision_outputs = reshaped_vision_outputs.reshape(
710
+ batch_size, seq_length, self.patches_per_image, self.patches_per_image
711
+ )
712
+ reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
713
+
714
+ pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
715
+ pooled_vision_outputs = pooled_vision_outputs.flatten(2)
716
+ pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
717
+
718
+ normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
719
+
720
+ projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
721
+ return projected_vision_outputs.type_as(vision_outputs)
722
+
723
+
724
+ def token_type_ids_mask_function(
725
+ token_type_ids: Optional[torch.Tensor],
726
+ image_group_ids: Optional[torch.Tensor],
727
+ tokens_per_image: int,
728
+ ) -> Optional[Callable]:
729
+ """
730
+ This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths,
731
+ not start and end indices.
732
+ """
733
+ # Do not return an additional mask in this case
734
+ if token_type_ids is None:
735
+ return None
736
+
737
+ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
738
+ # If it's 1 for both query and key/value, we are in an image block
739
+ # NOTE: static cache shape goes beyond input seq length, while token_type_ids.shape[1] == input seq length
740
+ # Since vmap doesn't support `if statement` we workaround it with `torch.where`
741
+ safe_idx = torch.where(kv_idx < token_type_ids.shape[1], kv_idx, 0)
742
+ token_type_ids_at_kv_idx = token_type_ids[batch_idx, safe_idx]
743
+ token_type_ids_at_kv_idx = torch.where(kv_idx < token_type_ids.shape[1], token_type_ids_at_kv_idx, 0)
744
+
745
+ image_group_ids_at_kv_idx = image_group_ids[batch_idx, safe_idx]
746
+ image_group_ids_at_kv_idx = torch.where(kv_idx < image_group_ids.shape[1], image_group_ids_at_kv_idx, -1)
747
+
748
+ is_image_block = (token_type_ids[batch_idx, q_idx] == 1) & (token_type_ids_at_kv_idx == 1)
749
+ same_image_block = image_group_ids[batch_idx, q_idx] == image_group_ids_at_kv_idx
750
+
751
+ # This is bidirectional attention whenever we are dealing with image tokens
752
+ return is_image_block & same_image_block
753
+
754
+ return inner_mask
755
+
756
+
757
+ class Gemma3Model(PaliGemmaModel):
758
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
759
+ accepts_loss_kwargs = False
760
+
761
+ def __init__(self, config: Gemma3Config):
762
+ super().__init__(config)
763
+ del self.text_config_dtype
764
+
765
+ def get_image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
766
+ """
767
+ Projects the last hidden state from the vision model into language model space.
768
+
769
+ Args:
770
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
771
+ The tensors corresponding to the input images.
772
+ Returns:
773
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
774
+ """
775
+ vision_outputs = self.vision_tower(pixel_values=pixel_values).last_hidden_state
776
+ image_features = self.multi_modal_projector(vision_outputs)
777
+ return image_features
778
+
779
+ def _update_causal_mask(self, **super_kwargs):
780
+ raise AttributeError("We don't want to inherit it")
781
+
782
+ @can_return_tuple
783
+ @auto_docstring
784
+ def forward(
785
+ self,
786
+ input_ids: Optional[torch.LongTensor] = None,
787
+ pixel_values: Optional[torch.FloatTensor] = None,
788
+ attention_mask: Optional[torch.Tensor] = None,
789
+ position_ids: Optional[torch.LongTensor] = None,
790
+ past_key_values: Optional[Cache] = None,
791
+ token_type_ids: Optional[torch.LongTensor] = None,
792
+ cache_position: Optional[torch.LongTensor] = None,
793
+ inputs_embeds: Optional[torch.FloatTensor] = None,
794
+ labels: Optional[torch.LongTensor] = None,
795
+ use_cache: Optional[bool] = None,
796
+ output_attentions: Optional[bool] = None,
797
+ output_hidden_states: Optional[bool] = None,
798
+ return_dict: Optional[bool] = None,
799
+ **lm_kwargs,
800
+ ) -> Union[tuple, Gemma3ModelOutputWithPast]:
801
+ if (input_ids is None) ^ (inputs_embeds is not None):
802
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
803
+
804
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
805
+ output_hidden_states = (
806
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
807
+ )
808
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
809
+
810
+ # Replace image id with PAD if the image token if OOV, to avoid index-errors
811
+ if input_ids is not None and self.config.image_token_id >= self.vocab_size:
812
+ special_image_mask = input_ids == self.config.image_token_id
813
+ llm_input_ids = input_ids.clone()
814
+ llm_input_ids[special_image_mask] = 0
815
+ else:
816
+ llm_input_ids = input_ids
817
+
818
+ if inputs_embeds is None:
819
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
820
+
821
+ if cache_position is None:
822
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
823
+ cache_position = torch.arange(
824
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
825
+ )
826
+
827
+ # Merge text and images
828
+ if pixel_values is not None:
829
+ image_features = self.get_image_features(pixel_values)
830
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
831
+ special_image_mask = self.get_placeholder_mask(
832
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
833
+ )
834
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
835
+
836
+ # It may already have been prepared by e.g. `generate`
837
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
838
+ # Prepare mask arguments
839
+ mask_kwargs = {
840
+ "config": self.config.get_text_config(),
841
+ "input_embeds": inputs_embeds,
842
+ "attention_mask": attention_mask,
843
+ "cache_position": cache_position,
844
+ "past_key_values": past_key_values,
845
+ "position_ids": position_ids,
846
+ }
847
+ # NOTE: this `is_prefill` logic is not flawless, it fails when we're using a cache eagerly initialized
848
+ # (e.g. compiled prefill) AND `pixel_values` are not provided. Determining prefill in that case requires
849
+ # checking data values, which is not compile-compatible.
850
+ is_prefill = (
851
+ not use_cache
852
+ or past_key_values is None
853
+ or not past_key_values.is_initialized
854
+ or pixel_values is not None
855
+ )
856
+ if token_type_ids is not None and is_prefill:
857
+ # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
858
+
859
+ # First find where a new image block starts: 1 if image and previous not image
860
+ # The images cannot attend to future images, but can attend to all prev images and to itself
861
+ # bidirectionally
862
+ is_image = (token_type_ids == 1).to(cache_position.device)
863
+ new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
864
+ image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
865
+ image_group_ids = torch.where(
866
+ is_image, image_group_ids, torch.full_like(token_type_ids, -1, device=is_image.device)
867
+ )
868
+ mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
869
+ token_type_ids.to(cache_position.device), image_group_ids, self.config.mm_tokens_per_image
870
+ )
871
+
872
+ # Create the masks
873
+ causal_mask_mapping = {
874
+ "full_attention": create_causal_mask(**mask_kwargs),
875
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
876
+ }
877
+
878
+ outputs = self.language_model(
879
+ attention_mask=causal_mask_mapping,
880
+ position_ids=position_ids,
881
+ past_key_values=past_key_values,
882
+ inputs_embeds=inputs_embeds,
883
+ use_cache=use_cache,
884
+ output_attentions=output_attentions,
885
+ output_hidden_states=output_hidden_states,
886
+ return_dict=True,
887
+ cache_position=cache_position,
888
+ **lm_kwargs,
889
+ )
890
+
891
+ return Gemma3ModelOutputWithPast(
892
+ last_hidden_state=outputs.last_hidden_state,
893
+ past_key_values=outputs.past_key_values if use_cache else None,
894
+ hidden_states=outputs.hidden_states,
895
+ attentions=outputs.attentions,
896
+ image_hidden_states=image_features if pixel_values is not None else None,
897
+ )
898
+
899
+
900
+ class Gemma3ForConditionalGeneration(PaliGemmaForConditionalGeneration):
901
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
902
+ # Fix: https://github.com/huggingface/transformers/issues/40564
903
+ accepts_loss_kwargs = False
904
+
905
+ @auto_docstring
906
+ def forward(
907
+ self,
908
+ input_ids: Optional[torch.LongTensor] = None,
909
+ pixel_values: Optional[torch.FloatTensor] = None,
910
+ attention_mask: Optional[torch.Tensor] = None,
911
+ position_ids: Optional[torch.LongTensor] = None,
912
+ past_key_values: Optional[Cache] = None,
913
+ token_type_ids: Optional[torch.LongTensor] = None,
914
+ cache_position: Optional[torch.LongTensor] = None,
915
+ inputs_embeds: Optional[torch.FloatTensor] = None,
916
+ labels: Optional[torch.LongTensor] = None,
917
+ use_cache: Optional[bool] = None,
918
+ output_attentions: Optional[bool] = None,
919
+ output_hidden_states: Optional[bool] = None,
920
+ return_dict: Optional[bool] = None,
921
+ logits_to_keep: Union[int, torch.Tensor] = 0,
922
+ **lm_kwargs,
923
+ ) -> Union[tuple, Gemma3CausalLMOutputWithPast]:
924
+ r"""
925
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
926
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
927
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
928
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
929
+
930
+ Example:
931
+
932
+ ```python
933
+ >>> from PIL import Image
934
+ >>> import requests
935
+ >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
936
+
937
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
938
+ >>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
939
+
940
+ >>> messages = [
941
+ ... {
942
+ ... "role": "system",
943
+ ... "content": [
944
+ ... {"type": "text", "text": "You are a helpful assistant."}
945
+ ... ]
946
+ ... },
947
+ ... {
948
+ ... "role": "user", "content": [
949
+ ... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
950
+ ... {"type": "text", "text": "Where is the cat standing?"},
951
+ ... ]
952
+ ... },
953
+ ... ]
954
+
955
+ >>> inputs = processor.apply_chat_template(
956
+ ... messages,
957
+ ... tokenize=True,
958
+ ... return_dict=True,
959
+ ... return_tensors="pt",
960
+ ... add_generation_prompt=True
961
+ ... )
962
+ >>> # Generate
963
+ >>> generate_ids = model.generate(**inputs)
964
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
965
+ "user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
966
+ ```
967
+ """
968
+
969
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
970
+ output_hidden_states = (
971
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
972
+ )
973
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
974
+
975
+ outputs = self.model(
976
+ input_ids=input_ids,
977
+ pixel_values=pixel_values,
978
+ token_type_ids=token_type_ids,
979
+ attention_mask=attention_mask,
980
+ position_ids=position_ids,
981
+ past_key_values=past_key_values,
982
+ inputs_embeds=inputs_embeds,
983
+ use_cache=use_cache,
984
+ labels=labels,
985
+ output_attentions=output_attentions,
986
+ output_hidden_states=output_hidden_states,
987
+ return_dict=return_dict,
988
+ cache_position=cache_position,
989
+ **lm_kwargs,
990
+ )
991
+
992
+ hidden_states = outputs[0]
993
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
994
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
995
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
996
+
997
+ loss = None
998
+ if labels is not None:
999
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1000
+ logits = logits.float()
1001
+ shift_logits = logits[..., :-1, :]
1002
+ shift_labels = labels[..., 1:]
1003
+ if attention_mask is not None:
1004
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
1005
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
1006
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
1007
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
1008
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
1009
+ else:
1010
+ shift_logits = shift_logits.contiguous()
1011
+ shift_labels = shift_labels.contiguous()
1012
+ # Flatten the tokens
1013
+ loss_fct = nn.CrossEntropyLoss()
1014
+
1015
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
1016
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
1017
+ loss = loss_fct(flat_logits, flat_labels)
1018
+
1019
+ if not return_dict:
1020
+ output = (logits,) + outputs[1:]
1021
+ return (loss,) + output if loss is not None else output
1022
+
1023
+ return Gemma3CausalLMOutputWithPast(
1024
+ loss=loss,
1025
+ logits=logits,
1026
+ past_key_values=outputs.past_key_values,
1027
+ hidden_states=outputs.hidden_states,
1028
+ attentions=outputs.attentions,
1029
+ image_hidden_states=outputs.image_hidden_states,
1030
+ )
1031
+
1032
+ def prepare_inputs_for_generation(
1033
+ self,
1034
+ input_ids,
1035
+ past_key_values=None,
1036
+ inputs_embeds=None,
1037
+ cache_position=None,
1038
+ position_ids=None,
1039
+ pixel_values=None,
1040
+ attention_mask=None,
1041
+ token_type_ids=None,
1042
+ use_cache=True,
1043
+ logits_to_keep=None,
1044
+ labels=None,
1045
+ **kwargs,
1046
+ ):
1047
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
1048
+ model_inputs = super().prepare_inputs_for_generation(
1049
+ input_ids,
1050
+ past_key_values=past_key_values,
1051
+ inputs_embeds=inputs_embeds,
1052
+ attention_mask=attention_mask,
1053
+ position_ids=position_ids,
1054
+ cache_position=cache_position,
1055
+ use_cache=use_cache,
1056
+ logits_to_keep=logits_to_keep,
1057
+ token_type_ids=token_type_ids,
1058
+ **kwargs,
1059
+ )
1060
+
1061
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
1062
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
1063
+ if cache_position[0] == 0:
1064
+ model_inputs["pixel_values"] = pixel_values
1065
+
1066
+ return model_inputs
1067
+
1068
+ def _prepare_4d_causal_attention_mask_with_cache_position(self, **super_kwargs):
1069
+ raise AttributeError("We don't want to inherit it")
1070
+
1071
+ @staticmethod
1072
+ def create_masks_for_generate(
1073
+ config: PretrainedConfig,
1074
+ input_embeds: torch.Tensor,
1075
+ attention_mask: Optional[torch.Tensor],
1076
+ cache_position: torch.Tensor,
1077
+ past_key_values: Optional[Cache],
1078
+ position_ids: Optional[torch.Tensor],
1079
+ token_type_ids: Optional[torch.Tensor] = None,
1080
+ **kwargs,
1081
+ ) -> dict:
1082
+ # Prepare mask arguments
1083
+ mask_kwargs = {
1084
+ "config": config.get_text_config(),
1085
+ "input_embeds": input_embeds,
1086
+ "attention_mask": attention_mask,
1087
+ "cache_position": cache_position,
1088
+ "past_key_values": past_key_values,
1089
+ "position_ids": position_ids,
1090
+ }
1091
+ # Add the token type ids mask for generate as well
1092
+ if token_type_ids is not None and input_embeds.shape[1] != 1:
1093
+ # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
1094
+
1095
+ # First find where a new image block starts: 1 if image and previous not image
1096
+ # The images cannot attend to future images, but can attend to all prev images and to itself bidirectionally
1097
+ is_image = (token_type_ids == 1).to(cache_position.device)
1098
+ new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
1099
+ image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
1100
+ image_group_ids = torch.where(is_image, image_group_ids, torch.full_like(token_type_ids, -1))
1101
+ mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
1102
+ token_type_ids.to(cache_position.device), image_group_ids, config.mm_tokens_per_image
1103
+ )
1104
+
1105
+ return create_masks_for_generate(**mask_kwargs)
1106
+
1107
+
1108
+ class Gemma3ForSequenceClassification(Gemma3PreTrainedModel):
1109
+ _checkpoint_conversion_mapping = {
1110
+ "^language_model.model": "model.language_model",
1111
+ "^vision_tower": "model.vision_tower",
1112
+ "^multi_modal_projector": "model.multi_modal_projector",
1113
+ }
1114
+
1115
+ def __init__(self, config):
1116
+ super().__init__(config)
1117
+ self.num_labels = config.num_labels
1118
+ self.model = Gemma3Model(config)
1119
+ self.score = nn.Linear(config.text_config.hidden_size, self.num_labels, bias=False)
1120
+
1121
+ # Initialize weights and apply final processing
1122
+ self.post_init()
1123
+
1124
+ def get_input_embeddings(self):
1125
+ return self.model.get_input_embeddings()
1126
+
1127
+ def set_input_embeddings(self, value):
1128
+ self.model.set_input_embeddings(value)
1129
+
1130
+ @can_return_tuple
1131
+ @auto_docstring
1132
+ def forward(
1133
+ self,
1134
+ input_ids: Optional[torch.LongTensor] = None,
1135
+ pixel_values: Optional[torch.FloatTensor] = None,
1136
+ attention_mask: Optional[torch.Tensor] = None,
1137
+ position_ids: Optional[torch.LongTensor] = None,
1138
+ past_key_values: Optional[Cache] = None,
1139
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1140
+ token_type_ids: Optional[torch.LongTensor] = None,
1141
+ labels: Optional[torch.LongTensor] = None,
1142
+ use_cache: Optional[bool] = None,
1143
+ **kwargs: Unpack[TransformersKwargs],
1144
+ ) -> SequenceClassifierOutputWithPast:
1145
+ r"""
1146
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1147
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1148
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1149
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1150
+ """
1151
+
1152
+ transformer_outputs = self.model(
1153
+ input_ids,
1154
+ attention_mask=attention_mask,
1155
+ pixel_values=pixel_values,
1156
+ position_ids=position_ids,
1157
+ past_key_values=past_key_values,
1158
+ inputs_embeds=inputs_embeds,
1159
+ token_type_ids=token_type_ids,
1160
+ use_cache=use_cache,
1161
+ **kwargs,
1162
+ )
1163
+ hidden_states = transformer_outputs.last_hidden_state
1164
+ logits = self.score(hidden_states)
1165
+
1166
+ if input_ids is not None:
1167
+ batch_size = input_ids.shape[0]
1168
+ else:
1169
+ batch_size = inputs_embeds.shape[0]
1170
+
1171
+ if self.config.text_config.pad_token_id is None and batch_size != 1:
1172
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1173
+ if self.config.text_config.pad_token_id is None:
1174
+ last_non_pad_token = -1
1175
+ elif input_ids is not None:
1176
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1177
+ non_pad_mask = (input_ids != self.config.text_config.pad_token_id).to(logits.device, torch.int32)
1178
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1179
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1180
+ else:
1181
+ last_non_pad_token = -1
1182
+ logger.warning_once(
1183
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1184
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1185
+ )
1186
+
1187
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1188
+
1189
+ loss = None
1190
+ if labels is not None:
1191
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1192
+
1193
+ return SequenceClassifierOutputWithPast(
1194
+ loss=loss,
1195
+ logits=pooled_logits,
1196
+ past_key_values=transformer_outputs.past_key_values,
1197
+ hidden_states=transformer_outputs.hidden_states,
1198
+ attentions=transformer_outputs.attentions,
1199
+ )
1200
+
1201
+
1202
+ class Gemma3TextForSequenceClassification(GenericForSequenceClassification, Gemma3PreTrainedModel):
1203
+ """
1204
+ Gemma3TextForSequenceClassification is a text-only sequence classification model that works with Gemma3TextConfig.
1205
+ It uses the generic sequence classification implementation for efficiency and consistency.
1206
+ """
1207
+
1208
+ config: Gemma3TextConfig
1209
+
1210
+
1211
+ __all__ = [
1212
+ "Gemma3Config",
1213
+ "Gemma3TextConfig",
1214
+ "Gemma3PreTrainedModel",
1215
+ "Gemma3TextModel",
1216
+ "Gemma3ForCausalLM",
1217
+ "Gemma3ForConditionalGeneration",
1218
+ "Gemma3Model",
1219
+ "Gemma3ForSequenceClassification",
1220
+ "Gemma3TextForSequenceClassification",
1221
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gemma3/processing_gemma3.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import re
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...feature_extraction_utils import BatchFeature
22
+ from ...image_utils import ImageInput, make_nested_list_of_images
23
+ from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
24
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
25
+ from ...utils import to_py_obj
26
+
27
+
28
+ class Gemma3ImagesKwargs(ImagesKwargs):
29
+ do_pan_and_scan: Optional[bool]
30
+ pan_and_scan_min_crop_size: Optional[int]
31
+ pan_and_scan_max_num_crops: Optional[int]
32
+ pan_and_scan_min_ratio_to_activate: Optional[float]
33
+ do_convert_rgb: Optional[bool]
34
+
35
+
36
+ class Gemma3ProcessorKwargs(ProcessingKwargs, total=False):
37
+ images_kwargs: Gemma3ImagesKwargs
38
+ _defaults = {
39
+ "text_kwargs": {
40
+ "padding": False,
41
+ "return_mm_token_type_ids": True,
42
+ },
43
+ "images_kwargs": {
44
+ "do_convert_rgb": True,
45
+ "do_pan_and_scan": False,
46
+ "pan_and_scan_min_crop_size": 256,
47
+ "pan_and_scan_max_num_crops": 4,
48
+ "pan_and_scan_min_ratio_to_activate": 1.2,
49
+ },
50
+ }
51
+
52
+
53
+ class Gemma3Processor(ProcessorMixin):
54
+ attributes = ["image_processor", "tokenizer"]
55
+ image_processor_class = "AutoImageProcessor"
56
+ tokenizer_class = "AutoTokenizer"
57
+
58
+ def __init__(
59
+ self,
60
+ image_processor,
61
+ tokenizer,
62
+ chat_template=None,
63
+ image_seq_length: int = 256,
64
+ **kwargs,
65
+ ):
66
+ self.image_seq_length = image_seq_length
67
+ self.image_token_id = tokenizer.image_token_id
68
+ self.boi_token = tokenizer.boi_token
69
+ self.image_token = tokenizer.image_token
70
+ image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)
71
+ self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"
72
+
73
+ super().__init__(
74
+ image_processor=image_processor,
75
+ tokenizer=tokenizer,
76
+ chat_template=chat_template,
77
+ **kwargs,
78
+ )
79
+
80
+ def __call__(
81
+ self,
82
+ images: Optional[ImageInput] = None,
83
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
84
+ videos=None,
85
+ audio=None,
86
+ **kwargs: Unpack[Gemma3ProcessorKwargs],
87
+ ) -> BatchFeature:
88
+ if text is None and images is None:
89
+ raise ValueError("Provide at least one of `text` or `images`.")
90
+
91
+ output_kwargs = self._merge_kwargs(
92
+ Gemma3ProcessorKwargs,
93
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
94
+ **kwargs,
95
+ )
96
+
97
+ if isinstance(text, str):
98
+ text = [text]
99
+ elif not isinstance(text, list) and not isinstance(text[0], str):
100
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
101
+
102
+ image_inputs = {}
103
+ if images is not None:
104
+ images = self.image_processor.fetch_images(images)
105
+ batched_images = make_nested_list_of_images(images)
106
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
107
+
108
+ # Create empty text to be replaced with placeholders
109
+ if not text:
110
+ text = [" ".join([self.boi_token] * len(images)) for images in batched_images]
111
+
112
+ if len(batched_images) != len(text):
113
+ raise ValueError(
114
+ f"Received inconsistently sized batches of images ({len(batched_images)}) and text ({len(text)})."
115
+ )
116
+
117
+ # Replace image tokens by the full expanded sequence
118
+ num_crops = to_py_obj(image_inputs.pop("num_crops"))
119
+ batch_num_crops = [[num_crops.pop(0) for _ in range(len(images))] for images in batched_images]
120
+ for batch_idx, (prompt, images, num_crops) in enumerate(zip(text, batched_images, batch_num_crops)):
121
+ image_indexes = [m.start() for m in re.finditer(self.boi_token, prompt)]
122
+
123
+ if len(images) != len(image_indexes):
124
+ raise ValueError(
125
+ f"Prompt contained {len(image_indexes)} image tokens but received {len(images)} images."
126
+ )
127
+
128
+ # Insert additional image tokens for Pan-and-Scan crops
129
+ for num, idx in reversed(list(zip(num_crops, image_indexes))):
130
+ if num:
131
+ formatted_image_text = (
132
+ f"Here is the original image {self.boi_token} and here are some crops to help you see better "
133
+ + " ".join([self.boi_token] * num)
134
+ )
135
+ prompt = prompt[:idx] + formatted_image_text + prompt[idx + len(self.boi_token) :]
136
+ text[batch_idx] = prompt
137
+
138
+ # Expand placeholder image tokens to the full image token sequence
139
+ text = [prompt.replace(self.boi_token, self.full_image_sequence) for prompt in text]
140
+
141
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
142
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
143
+ text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
144
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
145
+
146
+ # Add token type ids manually, as tokenizer can't do arbitrary position token types
147
+ if return_mm_token_type_ids:
148
+ array_ids = np.array(text_inputs["input_ids"])
149
+ mm_token_type_ids = np.zeros_like(array_ids)
150
+ mm_token_type_ids[array_ids == self.image_token_id] = 1
151
+ text_inputs["token_type_ids"] = mm_token_type_ids.tolist()
152
+
153
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
154
+
155
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
156
+ """
157
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
158
+
159
+ Args:
160
+ image_sizes (`list[list[int]]`, *optional*):
161
+ The input sizes formatted as (height, width) per each image.
162
+
163
+ Returns:
164
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
165
+ input modalities, along with other useful data.
166
+ """
167
+
168
+ vision_data = {}
169
+ if image_sizes is not None:
170
+ # NOTE: no image cropping supported yet
171
+ num_image_tokens = [self.image_seq_length] * len(image_sizes)
172
+ num_image_patches = [1] * len(image_sizes)
173
+
174
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
175
+
176
+ return MultiModalData(**vision_data)
177
+
178
+ @property
179
+ def model_input_names(self):
180
+ tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids"]
181
+ image_processor_input_names = self.image_processor.model_input_names
182
+
183
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
184
+ return list(tokenizer_input_names + image_processor_input_names)
185
+
186
+
187
+ __all__ = ["Gemma3Processor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/__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_glm import *
22
+ from .modeling_glm 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/configuration_glm.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+
19
+
20
+ class GlmConfig(PretrainedConfig):
21
+ r"""
22
+ This is the configuration class to store the configuration of a [`GlmModel`]. It is used to instantiate an Glm
23
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
24
+ defaults will yield a similar configuration to that of the Glm-4-9b-chat.
25
+ e.g. [THUDM/glm-4-9b-chat](https://huggingface.co/THUDM/glm-4-9b-chat)
26
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
27
+ documentation from [`PretrainedConfig`] for more information.
28
+ Args:
29
+ vocab_size (`int`, *optional*, defaults to 151552):
30
+ Vocabulary size of the Glm model. Defines the number of different tokens that can be represented by the
31
+ `inputs_ids` passed when calling [`GlmModel`]
32
+ hidden_size (`int`, *optional*, defaults to 4096):
33
+ Dimension of the hidden representations.
34
+ intermediate_size (`int`, *optional*, defaults to 13696):
35
+ Dimension of the MLP representations.
36
+ num_hidden_layers (`int`, *optional*, defaults to 40):
37
+ Number of hidden layers in the Transformer decoder.
38
+ num_attention_heads (`int`, *optional*, defaults to 32):
39
+ Number of attention heads for each attention layer in the Transformer decoder.
40
+ num_key_value_heads (`int`, *optional*, defaults to 2):
41
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
42
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
43
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
44
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
45
+ by meanpooling all the original heads within that group. For more details, check out [this
46
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
47
+ `num_attention_heads`.
48
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5): The factor of the partial rotary position.
49
+ head_dim (`int`, *optional*, defaults to 128):
50
+ The attention head dimension.
51
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
52
+ The legacy activation function. It is overwritten by the `hidden_activation`.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
56
+ The maximum sequence length that this model might ever be used with.
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ rms_norm_eps (`float`, *optional*, defaults to 1.5625e-07):
60
+ The epsilon used by the rms normalization layers.
61
+ use_cache (`bool`, *optional*, defaults to `True`):
62
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
63
+ relevant if `config.is_decoder=True`.
64
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
65
+ Whether to tie weight embeddings
66
+ rope_theta (`float`, *optional*, defaults to 10000.0):
67
+ The base period of the RoPE embeddings.
68
+ pad_token_id (`int`, *optional*, defaults to 151329):
69
+ Padding token id.
70
+ eos_token_id (`int` | `list`, *optional*, defaults to `[151329, 151336, 151338]`):
71
+ End of stream token id.
72
+ bos_token_id (`int`, *optional*):
73
+ Beginning of stream token id.
74
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `True`):
75
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
76
+ ```python
77
+ >>> from transformers import GlmModel, GlmConfig
78
+ >>> # Initializing a Glm glm-4-9b-chat style configuration
79
+ >>> configuration = GlmConfig()
80
+ >>> # Initializing a model from the glm-4-9b-chat style configuration
81
+ >>> model = GlmModel(configuration)
82
+ >>> # Accessing the model configuration
83
+ >>> configuration = model.config
84
+ ```"""
85
+
86
+ model_type = "glm"
87
+ keys_to_ignore_at_inference = ["past_key_values"]
88
+ base_model_tp_plan = {
89
+ "layers.*.self_attn.q_proj": "colwise",
90
+ "layers.*.self_attn.k_proj": "colwise",
91
+ "layers.*.self_attn.v_proj": "colwise",
92
+ "layers.*.self_attn.o_proj": "rowwise",
93
+ "layers.*.mlp.gate_up_proj": "colwise_rep", # we need to replicate here due to the `chunk` operation
94
+ "layers.*.mlp.down_proj": "rowwise_rep", # we need to replicate here due to the `chunk` operation
95
+ }
96
+ base_model_pp_plan = {
97
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
98
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
99
+ "norm": (["hidden_states"], ["hidden_states"]),
100
+ }
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_size=151552,
105
+ hidden_size=4096,
106
+ intermediate_size=13696,
107
+ num_hidden_layers=40,
108
+ num_attention_heads=32,
109
+ num_key_value_heads=2,
110
+ partial_rotary_factor=0.5,
111
+ head_dim=128,
112
+ hidden_act="silu",
113
+ attention_dropout=0.0,
114
+ max_position_embeddings=131072,
115
+ initializer_range=0.02,
116
+ rms_norm_eps=0.00000015625,
117
+ use_cache=True,
118
+ tie_word_embeddings=False,
119
+ rope_theta=10000.0,
120
+ pad_token_id=151329,
121
+ eos_token_id=[151329, 151336, 151338],
122
+ bos_token_id=None,
123
+ attention_bias=True,
124
+ **kwargs,
125
+ ):
126
+ self.vocab_size = vocab_size
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.hidden_size = hidden_size
129
+ self.intermediate_size = intermediate_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.partial_rotary_factor = partial_rotary_factor
133
+ self.head_dim = head_dim
134
+ self.num_key_value_heads = num_key_value_heads
135
+ self.hidden_act = hidden_act
136
+ self.initializer_range = initializer_range
137
+ self.rms_norm_eps = rms_norm_eps
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.attention_bias = attention_bias
141
+ self.attention_dropout = attention_dropout
142
+
143
+ super().__init__(
144
+ pad_token_id=pad_token_id,
145
+ bos_token_id=bos_token_id,
146
+ eos_token_id=eos_token_id,
147
+ tie_word_embeddings=tie_word_embeddings,
148
+ **kwargs,
149
+ )
150
+
151
+
152
+ __all__ = ["GlmConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/modeling_glm.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/glm/modular_glm.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_glm.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Callable, Optional, Union
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationMixin
30
+ from ...integrations import use_kernel_forward_from_hub
31
+ from ...masking_utils import create_causal_mask
32
+ from ...modeling_layers import (
33
+ GenericForSequenceClassification,
34
+ GenericForTokenClassification,
35
+ GradientCheckpointingLayer,
36
+ )
37
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
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, can_return_tuple
42
+ from ...utils.deprecation import deprecate_kwarg
43
+ from ...utils.generic import check_model_inputs
44
+ from .configuration_glm import GlmConfig
45
+
46
+
47
+ class GlmMLP(nn.Module):
48
+ def __init__(self, config):
49
+ super().__init__()
50
+
51
+ self.config = config
52
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
53
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
54
+ self.activation_fn = ACT2FN[config.hidden_act]
55
+
56
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
57
+ up_states = self.gate_up_proj(hidden_states)
58
+
59
+ gate, up_states = up_states.chunk(2, dim=-1)
60
+ up_states = up_states * self.activation_fn(gate)
61
+
62
+ return self.down_proj(up_states)
63
+
64
+
65
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
66
+ """
67
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
68
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
69
+ """
70
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
71
+ if n_rep == 1:
72
+ return hidden_states
73
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
74
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
75
+
76
+
77
+ def eager_attention_forward(
78
+ module: nn.Module,
79
+ query: torch.Tensor,
80
+ key: torch.Tensor,
81
+ value: torch.Tensor,
82
+ attention_mask: Optional[torch.Tensor],
83
+ scaling: float,
84
+ dropout: float = 0.0,
85
+ **kwargs: Unpack[TransformersKwargs],
86
+ ):
87
+ key_states = repeat_kv(key, module.num_key_value_groups)
88
+ value_states = repeat_kv(value, module.num_key_value_groups)
89
+
90
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
91
+ if attention_mask is not None:
92
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
93
+ attn_weights = attn_weights + causal_mask
94
+
95
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
96
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
97
+ attn_output = torch.matmul(attn_weights, value_states)
98
+ attn_output = attn_output.transpose(1, 2).contiguous()
99
+
100
+ return attn_output, attn_weights
101
+
102
+
103
+ def rotate_half(x):
104
+ """Rotates half the hidden dims of the input."""
105
+ x1 = x[..., 0::2]
106
+ x2 = x[..., 1::2]
107
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
108
+
109
+
110
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
111
+ """Applies Rotary Position Embedding to the query and key tensors.
112
+
113
+ Args:
114
+ q (`torch.Tensor`): The query tensor.
115
+ k (`torch.Tensor`): The key tensor.
116
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
117
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
118
+ position_ids (`torch.Tensor`, *optional*):
119
+ Deprecated and unused.
120
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
121
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
122
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
123
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
124
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
125
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
126
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
127
+ Returns:
128
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
129
+ """
130
+ cos = cos.unsqueeze(unsqueeze_dim)
131
+ sin = sin.unsqueeze(unsqueeze_dim)
132
+
133
+ # Interleave them instead of usual shape
134
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
135
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
136
+
137
+ # Keep half or full tensor for later concatenation
138
+ rotary_dim = cos.shape[-1]
139
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
140
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
141
+
142
+ # Apply rotary embeddings on the first half or full tensor
143
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
144
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
145
+
146
+ # Concatenate back to full shape
147
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
148
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
149
+ return q_embed, k_embed
150
+
151
+
152
+ class GlmAttention(nn.Module):
153
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
154
+
155
+ def __init__(self, config: GlmConfig, layer_idx: Optional[int] = None):
156
+ super().__init__()
157
+ self.config = config
158
+ self.layer_idx = layer_idx
159
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
160
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
161
+ self.scaling = self.head_dim**-0.5
162
+ self.attention_dropout = config.attention_dropout
163
+ self.is_causal = True
164
+
165
+ self.q_proj = nn.Linear(
166
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
167
+ )
168
+ self.k_proj = nn.Linear(
169
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
170
+ )
171
+ self.v_proj = nn.Linear(
172
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
173
+ )
174
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
175
+
176
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
177
+ def forward(
178
+ self,
179
+ hidden_states: torch.Tensor,
180
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
181
+ attention_mask: Optional[torch.Tensor],
182
+ past_key_values: Optional[Cache] = None,
183
+ cache_position: Optional[torch.LongTensor] = None,
184
+ **kwargs: Unpack[TransformersKwargs],
185
+ ) -> tuple[torch.Tensor, torch.Tensor]:
186
+ input_shape = hidden_states.shape[:-1]
187
+ hidden_shape = (*input_shape, -1, self.head_dim)
188
+
189
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
190
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
191
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
192
+
193
+ cos, sin = position_embeddings
194
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
195
+
196
+ if past_key_values is not None:
197
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
198
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
199
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
200
+
201
+ attention_interface: Callable = eager_attention_forward
202
+ if self.config._attn_implementation != "eager":
203
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
204
+
205
+ attn_output, attn_weights = attention_interface(
206
+ self,
207
+ query_states,
208
+ key_states,
209
+ value_states,
210
+ attention_mask,
211
+ dropout=0.0 if not self.training else self.attention_dropout,
212
+ scaling=self.scaling,
213
+ **kwargs,
214
+ )
215
+
216
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
217
+ attn_output = self.o_proj(attn_output)
218
+ return attn_output, attn_weights
219
+
220
+
221
+ @use_kernel_forward_from_hub("RMSNorm")
222
+ class GlmRMSNorm(nn.Module):
223
+ def __init__(self, hidden_size, eps=1e-6):
224
+ """
225
+ GlmRMSNorm is equivalent to T5LayerNorm
226
+ """
227
+ super().__init__()
228
+ self.weight = nn.Parameter(torch.ones(hidden_size))
229
+ self.variance_epsilon = eps
230
+
231
+ def forward(self, hidden_states):
232
+ input_dtype = hidden_states.dtype
233
+ hidden_states = hidden_states.to(torch.float32)
234
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
235
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
236
+ return self.weight * hidden_states.to(input_dtype)
237
+
238
+ def extra_repr(self):
239
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
240
+
241
+
242
+ class GlmRotaryEmbedding(nn.Module):
243
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
244
+
245
+ def __init__(self, config: GlmConfig, device=None):
246
+ super().__init__()
247
+ # BC: "rope_type" was originally "type"
248
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
249
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
250
+ else:
251
+ self.rope_type = "default"
252
+ self.max_seq_len_cached = config.max_position_embeddings
253
+ self.original_max_seq_len = config.max_position_embeddings
254
+
255
+ self.config = config
256
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
257
+
258
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
259
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
260
+ self.original_inv_freq = self.inv_freq
261
+
262
+ @torch.no_grad()
263
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
264
+ def forward(self, x, position_ids):
265
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
266
+ position_ids_expanded = position_ids[:, None, :].float()
267
+
268
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
269
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
270
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
271
+ emb = torch.cat((freqs, freqs), dim=-1)
272
+ cos = emb.cos() * self.attention_scaling
273
+ sin = emb.sin() * self.attention_scaling
274
+
275
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
276
+
277
+
278
+ class GlmDecoderLayer(GradientCheckpointingLayer):
279
+ def __init__(self, config: GlmConfig, layer_idx: int):
280
+ super().__init__()
281
+ self.hidden_size = config.hidden_size
282
+
283
+ self.self_attn = GlmAttention(config=config, layer_idx=layer_idx)
284
+
285
+ self.mlp = GlmMLP(config)
286
+ self.input_layernorm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
287
+ self.post_attention_layernorm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
288
+
289
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
290
+ def forward(
291
+ self,
292
+ hidden_states: torch.Tensor,
293
+ attention_mask: Optional[torch.Tensor] = None,
294
+ position_ids: Optional[torch.LongTensor] = None,
295
+ past_key_values: Optional[Cache] = None,
296
+ use_cache: Optional[bool] = False,
297
+ cache_position: Optional[torch.LongTensor] = None,
298
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
299
+ **kwargs: Unpack[TransformersKwargs],
300
+ ) -> torch.Tensor:
301
+ residual = hidden_states
302
+ hidden_states = self.input_layernorm(hidden_states)
303
+ # Self Attention
304
+ hidden_states, _ = self.self_attn(
305
+ hidden_states=hidden_states,
306
+ attention_mask=attention_mask,
307
+ position_ids=position_ids,
308
+ past_key_values=past_key_values,
309
+ use_cache=use_cache,
310
+ cache_position=cache_position,
311
+ position_embeddings=position_embeddings,
312
+ **kwargs,
313
+ )
314
+ hidden_states = residual + hidden_states
315
+
316
+ # Fully Connected
317
+ residual = hidden_states
318
+ hidden_states = self.post_attention_layernorm(hidden_states)
319
+ hidden_states = self.mlp(hidden_states)
320
+ hidden_states = residual + hidden_states
321
+ return hidden_states
322
+
323
+
324
+ @auto_docstring
325
+ class GlmPreTrainedModel(PreTrainedModel):
326
+ config: GlmConfig
327
+ base_model_prefix = "model"
328
+ supports_gradient_checkpointing = True
329
+ _no_split_modules = ["GlmDecoderLayer"]
330
+ _skip_keys_device_placement = ["past_key_values"]
331
+ _supports_flash_attn = True
332
+ _supports_sdpa = True
333
+ _supports_flex_attn = True
334
+
335
+ _can_compile_fullgraph = True
336
+ _supports_attention_backend = True
337
+ _can_record_outputs = {
338
+ "hidden_states": GlmDecoderLayer,
339
+ "attentions": GlmAttention,
340
+ }
341
+
342
+
343
+ @auto_docstring
344
+ class GlmModel(GlmPreTrainedModel):
345
+ def __init__(self, config: GlmConfig):
346
+ super().__init__(config)
347
+ self.padding_idx = config.pad_token_id
348
+ self.vocab_size = config.vocab_size
349
+
350
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
351
+ self.layers = nn.ModuleList(
352
+ [GlmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
353
+ )
354
+ self.norm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
355
+ self.rotary_emb = GlmRotaryEmbedding(config=config)
356
+ self.gradient_checkpointing = False
357
+
358
+ # Initialize weights and apply final processing
359
+ self.post_init()
360
+
361
+ @check_model_inputs
362
+ @auto_docstring
363
+ def forward(
364
+ self,
365
+ input_ids: Optional[torch.LongTensor] = None,
366
+ attention_mask: Optional[torch.Tensor] = None,
367
+ position_ids: Optional[torch.LongTensor] = None,
368
+ past_key_values: Optional[Cache] = None,
369
+ inputs_embeds: Optional[torch.FloatTensor] = None,
370
+ cache_position: Optional[torch.LongTensor] = None,
371
+ use_cache: Optional[bool] = None,
372
+ **kwargs: Unpack[TransformersKwargs],
373
+ ) -> BaseModelOutputWithPast:
374
+ if (input_ids is None) ^ (inputs_embeds is not None):
375
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
376
+
377
+ if inputs_embeds is None:
378
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
379
+
380
+ if use_cache and past_key_values is None:
381
+ past_key_values = DynamicCache(config=self.config)
382
+
383
+ if cache_position is None:
384
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
385
+ cache_position: torch.Tensor = torch.arange(
386
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
387
+ )
388
+
389
+ if position_ids is None:
390
+ position_ids = cache_position.unsqueeze(0)
391
+
392
+ causal_mask = create_causal_mask(
393
+ config=self.config,
394
+ input_embeds=inputs_embeds,
395
+ attention_mask=attention_mask,
396
+ cache_position=cache_position,
397
+ past_key_values=past_key_values,
398
+ position_ids=position_ids,
399
+ )
400
+
401
+ hidden_states = inputs_embeds
402
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
403
+
404
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
405
+ hidden_states = decoder_layer(
406
+ hidden_states,
407
+ attention_mask=causal_mask,
408
+ position_ids=position_ids,
409
+ past_key_values=past_key_values,
410
+ cache_position=cache_position,
411
+ position_embeddings=position_embeddings,
412
+ **kwargs,
413
+ )
414
+
415
+ hidden_states = self.norm(hidden_states)
416
+ return BaseModelOutputWithPast(
417
+ last_hidden_state=hidden_states,
418
+ past_key_values=past_key_values,
419
+ )
420
+
421
+
422
+ @auto_docstring
423
+ class GlmForCausalLM(GlmPreTrainedModel, GenerationMixin):
424
+ _tied_weights_keys = ["lm_head.weight"]
425
+ _tp_plan = {"lm_head": "colwise_rep"}
426
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
427
+
428
+ def __init__(self, config):
429
+ super().__init__(config)
430
+ self.model = GlmModel(config)
431
+ self.vocab_size = config.vocab_size
432
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
433
+
434
+ # Initialize weights and apply final processing
435
+ self.post_init()
436
+
437
+ @can_return_tuple
438
+ @auto_docstring
439
+ def forward(
440
+ self,
441
+ input_ids: Optional[torch.LongTensor] = None,
442
+ attention_mask: Optional[torch.Tensor] = None,
443
+ position_ids: Optional[torch.LongTensor] = None,
444
+ past_key_values: Optional[Cache] = None,
445
+ inputs_embeds: Optional[torch.FloatTensor] = None,
446
+ labels: Optional[torch.LongTensor] = None,
447
+ use_cache: Optional[bool] = None,
448
+ cache_position: Optional[torch.LongTensor] = None,
449
+ logits_to_keep: Union[int, torch.Tensor] = 0,
450
+ **kwargs: Unpack[TransformersKwargs],
451
+ ) -> CausalLMOutputWithPast:
452
+ r"""
453
+ Example:
454
+
455
+ ```python
456
+ >>> from transformers import AutoTokenizer, GlmForCausalLM
457
+
458
+ >>> model = GlmForCausalLM.from_pretrained("meta-glm/Glm-2-7b-hf")
459
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-glm/Glm-2-7b-hf")
460
+
461
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
462
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
463
+
464
+ >>> # Generate
465
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
466
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
467
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
468
+ ```"""
469
+ outputs: BaseModelOutputWithPast = self.model(
470
+ input_ids=input_ids,
471
+ attention_mask=attention_mask,
472
+ position_ids=position_ids,
473
+ past_key_values=past_key_values,
474
+ inputs_embeds=inputs_embeds,
475
+ use_cache=use_cache,
476
+ cache_position=cache_position,
477
+ **kwargs,
478
+ )
479
+
480
+ hidden_states = outputs.last_hidden_state
481
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
482
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
483
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
484
+
485
+ loss = None
486
+ if labels is not None:
487
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
488
+
489
+ return CausalLMOutputWithPast(
490
+ loss=loss,
491
+ logits=logits,
492
+ past_key_values=outputs.past_key_values,
493
+ hidden_states=outputs.hidden_states,
494
+ attentions=outputs.attentions,
495
+ )
496
+
497
+
498
+ class GlmForSequenceClassification(GenericForSequenceClassification, GlmPreTrainedModel):
499
+ pass
500
+
501
+
502
+ class GlmForTokenClassification(GenericForTokenClassification, GlmPreTrainedModel):
503
+ pass
504
+
505
+
506
+ __all__ = [
507
+ "GlmPreTrainedModel",
508
+ "GlmModel",
509
+ "GlmForCausalLM",
510
+ "GlmForSequenceClassification",
511
+ "GlmForTokenClassification",
512
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm/modular_glm.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ...utils import logging
22
+ from ..llama.modeling_llama import (
23
+ LlamaAttention,
24
+ LlamaForCausalLM,
25
+ LlamaForSequenceClassification,
26
+ LlamaForTokenClassification,
27
+ )
28
+ from ..phi3.modeling_phi3 import Phi3MLP
29
+ from .configuration_glm import GlmConfig
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ _CHECKPOINT_FOR_DOC = "THUDM/glm-4-9b"
35
+
36
+
37
+ class GlmMLP(Phi3MLP):
38
+ pass
39
+
40
+
41
+ def rotate_half(x):
42
+ """Rotates half the hidden dims of the input."""
43
+ x1 = x[..., 0::2]
44
+ x2 = x[..., 1::2]
45
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
46
+
47
+
48
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
49
+ """Applies Rotary Position Embedding to the query and key tensors.
50
+
51
+ Args:
52
+ q (`torch.Tensor`): The query tensor.
53
+ k (`torch.Tensor`): The key tensor.
54
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
55
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
56
+ position_ids (`torch.Tensor`, *optional*):
57
+ Deprecated and unused.
58
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
59
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
60
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
61
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
62
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
63
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
64
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
65
+ Returns:
66
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
67
+ """
68
+ cos = cos.unsqueeze(unsqueeze_dim)
69
+ sin = sin.unsqueeze(unsqueeze_dim)
70
+
71
+ # Interleave them instead of usual shape
72
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
73
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
74
+
75
+ # Keep half or full tensor for later concatenation
76
+ rotary_dim = cos.shape[-1]
77
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
78
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
79
+
80
+ # Apply rotary embeddings on the first half or full tensor
81
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
82
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
83
+
84
+ # Concatenate back to full shape
85
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
86
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
87
+ return q_embed, k_embed
88
+
89
+
90
+ class GlmAttention(LlamaAttention):
91
+ def __init__(self, config: GlmConfig, layer_idx: Optional[int] = None):
92
+ super().__init__(config, layer_idx)
93
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
94
+
95
+
96
+ class GlmForCausalLM(LlamaForCausalLM):
97
+ pass
98
+
99
+
100
+ class GlmForSequenceClassification(LlamaForSequenceClassification):
101
+ pass
102
+
103
+
104
+ class GlmForTokenClassification(LlamaForTokenClassification):
105
+ pass
106
+
107
+
108
+ __all__ = [
109
+ "GlmPreTrainedModel", # noqa: F822
110
+ "GlmModel", # noqa: F822
111
+ "GlmForCausalLM",
112
+ "GlmForSequenceClassification",
113
+ "GlmForTokenClassification",
114
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/__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_gpt_neox import *
22
+ from .modeling_gpt_neox import *
23
+ from .tokenization_gpt_neox_fast 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/configuration_gpt_neox.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and The HuggingFace Inc. team. 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
+ """GPTNeoX model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class GPTNeoXConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`GPTNeoXModel`]. It is used to instantiate an
28
+ GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the GPTNeoX
30
+ [EleutherAI/gpt-neox-20b](https://huggingface.co/EleutherAI/gpt-neox-20b) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 50432):
38
+ Vocabulary size of the GPTNeoX model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`GPTNeoXModel`].
40
+ hidden_size (`int`, *optional*, defaults to 6144):
41
+ Dimension of the encoder layers and the pooler layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 44):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 64):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ intermediate_size (`int`, *optional*, defaults to 24576):
47
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
51
+ rotary_pct (`float`, *optional*, defaults to 0.25):
52
+ percentage of hidden dimensions to allocate to rotary embeddings
53
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
54
+ base for computing rotary embeddings frequency
55
+ attention_dropout (`float`, *optional*, defaults to 0.0):
56
+ The dropout ratio probability of the attention score.
57
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
58
+ The dropout ratio of (1) the word embeddings, (2) the post-attention hidden states, and (3) the post-mlp
59
+ hidden states.
60
+ classifier_dropout (`float`, *optional*, defaults to 0.1):
61
+ Argument used when doing token classification, used in the model [`GPTNeoXForTokenClassification`].
62
+
63
+ The dropout ratio for the hidden layer.
64
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
65
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
66
+ just in case (e.g., 512 or 1024 or 2048).
67
+ initializer_range (`float`, *optional*, defaults to 1e-5):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
70
+ The epsilon used by the layer normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
73
+ relevant if `config.is_decoder=True`.
74
+ use_parallel_residual (`bool`, *optional*, defaults to `True`):
75
+ Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
76
+ speedup at large scales (e.g. 20B).
77
+ rope_scaling (`Dict`, *optional*):
78
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
79
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
80
+ accordingly.
81
+ Expected contents:
82
+ `rope_type` (`str`):
83
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
84
+ 'llama3'], with 'default' being the original RoPE implementation.
85
+ `factor` (`float`, *optional*):
86
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
87
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
88
+ original maximum pre-trained length.
89
+ `original_max_position_embeddings` (`int`, *optional*):
90
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
91
+ pretraining.
92
+ `attention_factor` (`float`, *optional*):
93
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
94
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
95
+ `factor` field to infer the suggested value.
96
+ `beta_fast` (`float`, *optional*):
97
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
98
+ ramp function. If unspecified, it defaults to 32.
99
+ `beta_slow` (`float`, *optional*):
100
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
101
+ ramp function. If unspecified, it defaults to 1.
102
+ `short_factor` (`list[float]`, *optional*):
103
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
104
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
105
+ size divided by the number of attention heads divided by 2
106
+ `long_factor` (`list[float]`, *optional*):
107
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
108
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
109
+ size divided by the number of attention heads divided by 2
110
+ `low_freq_factor` (`float`, *optional*):
111
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
112
+ `high_freq_factor` (`float`, *optional*):
113
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
114
+ attention_bias (`bool`, *optional*, defaults to `True`):
115
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
116
+
117
+ Example:
118
+
119
+ ```python
120
+ >>> from transformers import GPTNeoXConfig, GPTNeoXModel
121
+
122
+ >>> # Initializing a GPTNeoX gpt-neox-20b style configuration
123
+ >>> configuration = GPTNeoXConfig()
124
+
125
+ >>> # Initializing a model (with random weights) from the gpt-neox-20b style configuration
126
+ >>> model = GPTNeoXModel(configuration) # doctest: +SKIP
127
+
128
+ >>> # Accessing the model configuration
129
+ >>> configuration = model.config # doctest: +SKIP
130
+ ```"""
131
+
132
+ model_type = "gpt_neox"
133
+ keys_to_ignore_at_inference = ["past_key_values"]
134
+ base_model_tp_plan = {
135
+ "layers.*.attention.query_key_value": "colwise",
136
+ "layers.*.attention.dense": "rowwise",
137
+ "layers.*.mlp.dense_h_to_4h": "colwise",
138
+ "layers.*.mlp.dense_4h_to_h": "rowwise",
139
+ }
140
+ base_model_pp_plan = {
141
+ "embed_in": (["input_ids"], ["inputs_embeds"]),
142
+ "emb_dropout": (["inputs_embeds"], ["hidden_states"]),
143
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
144
+ "final_layer_norm": (["hidden_states"], ["hidden_states"]),
145
+ }
146
+
147
+ def __init__(
148
+ self,
149
+ vocab_size=50432,
150
+ hidden_size=6144,
151
+ num_hidden_layers=44,
152
+ num_attention_heads=64,
153
+ intermediate_size=24576,
154
+ hidden_act="gelu",
155
+ rotary_pct=0.25,
156
+ rotary_emb_base=10000,
157
+ attention_dropout=0.0,
158
+ hidden_dropout=0.0,
159
+ classifier_dropout=0.1,
160
+ max_position_embeddings=2048,
161
+ initializer_range=0.02,
162
+ layer_norm_eps=1e-5,
163
+ use_cache=True,
164
+ bos_token_id=0,
165
+ eos_token_id=2,
166
+ tie_word_embeddings=False,
167
+ use_parallel_residual=True,
168
+ rope_scaling=None,
169
+ attention_bias=True,
170
+ **kwargs,
171
+ ):
172
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
173
+ self.vocab_size = vocab_size
174
+ self.max_position_embeddings = max_position_embeddings
175
+ self.hidden_size = hidden_size
176
+ self.num_hidden_layers = num_hidden_layers
177
+ self.num_attention_heads = num_attention_heads
178
+ self.intermediate_size = intermediate_size
179
+ self.hidden_act = hidden_act
180
+ self.rotary_pct = rotary_pct
181
+ self.partial_rotary_factor = rotary_pct
182
+ self.rotary_emb_base = rotary_emb_base
183
+ self.rope_theta = rotary_emb_base
184
+ self.attention_dropout = attention_dropout
185
+ self.hidden_dropout = hidden_dropout
186
+ self.classifier_dropout = classifier_dropout
187
+ self.initializer_range = initializer_range
188
+ self.layer_norm_eps = layer_norm_eps
189
+ self.use_cache = use_cache
190
+ self.tie_word_embeddings = tie_word_embeddings
191
+ self.use_parallel_residual = use_parallel_residual
192
+ self.rope_scaling = rope_scaling
193
+ self.attention_bias = attention_bias
194
+ # Validate the correctness of rotary position embeddings parameters
195
+ # BC: if there is a 'type' field, move it to 'rope_type'.
196
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
197
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
198
+ rope_config_validation(self)
199
+
200
+ if self.hidden_size % self.num_attention_heads != 0:
201
+ raise ValueError(
202
+ "The hidden size is not divisible by the number of attention heads! Make sure to update them!"
203
+ )
204
+
205
+
206
+ __all__ = ["GPTNeoXConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/modeling_gpt_neox.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gpt_neox/modular_gpt_neox.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_gpt_neox.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ from typing import Callable, Optional, Union
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from ...activations import ACT2FN
13
+ from ...cache_utils import Cache, DynamicCache
14
+ from ...generation import GenerationMixin
15
+ from ...integrations import use_kernel_forward_from_hub
16
+ from ...masking_utils import create_causal_mask
17
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
18
+ from ...modeling_layers import GradientCheckpointingLayer
19
+ from ...modeling_outputs import (
20
+ BaseModelOutputWithPast,
21
+ CausalLMOutputWithPast,
22
+ QuestionAnsweringModelOutput,
23
+ SequenceClassifierOutputWithPast,
24
+ TokenClassifierOutput,
25
+ )
26
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
27
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
28
+ from ...processing_utils import Unpack
29
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
30
+ from ...utils.deprecation import deprecate_kwarg
31
+ from ...utils.generic import check_model_inputs
32
+ from .configuration_gpt_neox import GPTNeoXConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class GPTNeoXMLP(nn.Module):
39
+ def __init__(self, config):
40
+ super().__init__()
41
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
42
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
43
+ self.act = ACT2FN[config.hidden_act]
44
+
45
+ def forward(self, hidden_states):
46
+ hidden_states = self.dense_h_to_4h(hidden_states)
47
+ hidden_states = self.act(hidden_states)
48
+ hidden_states = self.dense_4h_to_h(hidden_states)
49
+ return hidden_states
50
+
51
+
52
+ def rotate_half(x):
53
+ """Rotates half the hidden dims of the input."""
54
+ x1 = x[..., : x.shape[-1] // 2]
55
+ x2 = x[..., x.shape[-1] // 2 :]
56
+ return torch.cat((-x2, x1), dim=-1)
57
+
58
+
59
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
60
+ """Applies Rotary Position Embedding to the query and key tensors.
61
+
62
+ Args:
63
+ q (`torch.Tensor`): The query tensor.
64
+ k (`torch.Tensor`): The key tensor.
65
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
66
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
67
+ position_ids (`torch.Tensor`, *optional*):
68
+ Deprecated and unused.
69
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
70
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
71
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
72
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
73
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
74
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
75
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
76
+ Returns:
77
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
78
+ """
79
+ cos = cos.unsqueeze(unsqueeze_dim)
80
+ sin = sin.unsqueeze(unsqueeze_dim)
81
+
82
+ # Keep half or full tensor for later concatenation
83
+ rotary_dim = cos.shape[-1]
84
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
85
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
86
+
87
+ # Apply rotary embeddings on the first half or full tensor
88
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
89
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
90
+
91
+ # Concatenate back to full shape
92
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
93
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
94
+ return q_embed, k_embed
95
+
96
+
97
+ def eager_attention_forward(
98
+ module: nn.Module,
99
+ query: torch.Tensor,
100
+ key: torch.Tensor,
101
+ value: torch.Tensor,
102
+ attention_mask: torch.Tensor,
103
+ scaling: float,
104
+ dropout: float = 0.0,
105
+ head_mask: Optional[torch.Tensor] = None,
106
+ **kwargs,
107
+ ):
108
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
109
+
110
+ if attention_mask is not None: # no matter the length, we just slice it
111
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
112
+ attn_weights = attn_weights + causal_mask
113
+
114
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
115
+
116
+ # Mask heads if we want to
117
+ if head_mask is not None:
118
+ attn_weights = attn_weights * head_mask
119
+
120
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
121
+ attn_output = torch.matmul(attn_weights, value)
122
+
123
+ # Reshape outputs
124
+ attn_output = attn_output.transpose(1, 2).contiguous()
125
+
126
+ return attn_output, attn_weights
127
+
128
+
129
+ class GPTNeoXAttention(nn.Module):
130
+ def __init__(self, config, layer_idx=None):
131
+ super().__init__()
132
+ self.config = config
133
+ self.head_size = config.hidden_size // config.num_attention_heads
134
+ self.attention_dropout = config.attention_dropout
135
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
136
+ self.scaling = self.head_size**-0.5
137
+ self.is_causal = True
138
+ self.layer_idx = layer_idx
139
+
140
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.attention_bias)
141
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states: torch.FloatTensor,
146
+ attention_mask: torch.FloatTensor,
147
+ head_mask: Optional[torch.FloatTensor] = None,
148
+ layer_past: Optional[Cache] = None,
149
+ output_attentions: Optional[bool] = False,
150
+ cache_position: Optional[torch.LongTensor] = None,
151
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
152
+ **kwargs: Unpack[FlashAttentionKwargs],
153
+ ):
154
+ input_shape = hidden_states.shape[:-1]
155
+ hidden_shape = (*input_shape, -1, 3 * self.head_size)
156
+
157
+ qkv = self.query_key_value(hidden_states).view(hidden_shape).transpose(1, 2)
158
+ query_states, key_states, value_states = qkv.chunk(3, dim=-1)
159
+
160
+ cos, sin = position_embeddings
161
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
162
+
163
+ # Cache QKV values
164
+ if layer_past is not None:
165
+ cache_kwargs = {
166
+ "sin": sin,
167
+ "cos": cos,
168
+ "partial_rotation_size": self.rotary_ndims,
169
+ "cache_position": cache_position,
170
+ }
171
+ key_states, value_states = layer_past.update(key_states, value_states, self.layer_idx, cache_kwargs)
172
+
173
+ attention_interface: Callable = eager_attention_forward
174
+ if self.config._attn_implementation != "eager":
175
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
176
+
177
+ # Compute attention
178
+ attn_output, attn_weights = attention_interface(
179
+ self,
180
+ query_states,
181
+ key_states,
182
+ value_states,
183
+ attention_mask,
184
+ scaling=self.scaling,
185
+ dropout=0.0 if not self.training else self.attention_dropout,
186
+ head_mask=head_mask,
187
+ **kwargs,
188
+ )
189
+
190
+ # Reshape outputs and final projection
191
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
192
+ attn_output = self.dense(attn_output)
193
+
194
+ return attn_output, attn_weights
195
+
196
+
197
+ class GPTNeoXLayer(GradientCheckpointingLayer):
198
+ def __init__(self, config, layer_idx):
199
+ super().__init__()
200
+ self.use_parallel_residual = config.use_parallel_residual
201
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
202
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
203
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout)
204
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout)
205
+ self.attention = GPTNeoXAttention(config, layer_idx)
206
+ self.mlp = GPTNeoXMLP(config)
207
+
208
+ def forward(
209
+ self,
210
+ hidden_states: Optional[torch.FloatTensor],
211
+ attention_mask: Optional[torch.FloatTensor] = None,
212
+ position_ids: Optional[torch.LongTensor] = None,
213
+ head_mask: Optional[torch.FloatTensor] = None,
214
+ use_cache: Optional[bool] = False,
215
+ layer_past: Optional[Cache] = None,
216
+ output_attentions: Optional[bool] = False,
217
+ cache_position: Optional[torch.LongTensor] = None,
218
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
219
+ **kwargs: Unpack[FlashAttentionKwargs],
220
+ ):
221
+ attn_output, attn_weights = self.attention(
222
+ self.input_layernorm(hidden_states),
223
+ attention_mask=attention_mask,
224
+ position_ids=position_ids,
225
+ layer_past=layer_past,
226
+ head_mask=head_mask,
227
+ use_cache=use_cache,
228
+ output_attentions=output_attentions,
229
+ cache_position=cache_position,
230
+ position_embeddings=position_embeddings,
231
+ **kwargs,
232
+ )
233
+ attn_output = self.post_attention_dropout(attn_output)
234
+
235
+ if self.use_parallel_residual:
236
+ # pseudocode:
237
+ # x = x + attn(ln1(x)) + mlp(ln2(x))
238
+ mlp_output = self.mlp(self.post_attention_layernorm(hidden_states))
239
+ mlp_output = self.post_mlp_dropout(mlp_output)
240
+ hidden_states = mlp_output + attn_output + hidden_states
241
+ else:
242
+ # pseudocode:
243
+ # x = x + attn(ln1(x))
244
+ # x = x + mlp(ln2(x))
245
+ attn_output = attn_output + hidden_states
246
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
247
+ mlp_output = self.post_mlp_dropout(mlp_output)
248
+ hidden_states = mlp_output + attn_output
249
+
250
+ outputs = (hidden_states,)
251
+ if output_attentions:
252
+ outputs += (attn_weights,)
253
+
254
+ return outputs
255
+
256
+
257
+ class GPTNeoXRotaryEmbedding(nn.Module):
258
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
259
+
260
+ def __init__(self, config: GPTNeoXConfig, device=None):
261
+ super().__init__()
262
+ # BC: "rope_type" was originally "type"
263
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
264
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
265
+ else:
266
+ self.rope_type = "default"
267
+ self.max_seq_len_cached = config.max_position_embeddings
268
+ self.original_max_seq_len = config.max_position_embeddings
269
+
270
+ self.config = config
271
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
272
+
273
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
274
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
275
+ self.original_inv_freq = self.inv_freq
276
+
277
+ @torch.no_grad()
278
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
279
+ def forward(self, x, position_ids):
280
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
281
+ position_ids_expanded = position_ids[:, None, :].float()
282
+
283
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
284
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
285
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
286
+ emb = torch.cat((freqs, freqs), dim=-1)
287
+ cos = emb.cos() * self.attention_scaling
288
+ sin = emb.sin() * self.attention_scaling
289
+
290
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
291
+
292
+
293
+ @use_kernel_forward_from_hub("RMSNorm")
294
+ class GPTNeoXRMSNorm(nn.Module):
295
+ def __init__(self, hidden_size, eps=1e-6):
296
+ """
297
+ GPTNeoXRMSNorm is equivalent to T5LayerNorm
298
+ """
299
+ super().__init__()
300
+ self.weight = nn.Parameter(torch.ones(hidden_size))
301
+ self.variance_epsilon = eps
302
+
303
+ def forward(self, hidden_states):
304
+ input_dtype = hidden_states.dtype
305
+ hidden_states = hidden_states.to(torch.float32)
306
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
307
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
308
+ return self.weight * hidden_states.to(input_dtype)
309
+
310
+ def extra_repr(self):
311
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
312
+
313
+
314
+ class GPTNeoXDecoderLayer(GradientCheckpointingLayer):
315
+ def __init__(self, config: GPTNeoXConfig, layer_idx: int):
316
+ super().__init__()
317
+ self.hidden_size = config.hidden_size
318
+
319
+ self.self_attn = GPTNeoXAttention(config=config, layer_idx=layer_idx)
320
+
321
+ self.mlp = GPTNeoXMLP(config)
322
+ self.input_layernorm = GPTNeoXRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
323
+ self.post_attention_layernorm = GPTNeoXRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
324
+
325
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
326
+ def forward(
327
+ self,
328
+ hidden_states: torch.Tensor,
329
+ attention_mask: Optional[torch.Tensor] = None,
330
+ position_ids: Optional[torch.LongTensor] = None,
331
+ past_key_values: Optional[Cache] = None,
332
+ use_cache: Optional[bool] = False,
333
+ cache_position: Optional[torch.LongTensor] = None,
334
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
335
+ **kwargs: Unpack[TransformersKwargs],
336
+ ) -> torch.Tensor:
337
+ residual = hidden_states
338
+ hidden_states = self.input_layernorm(hidden_states)
339
+ # Self Attention
340
+ hidden_states, _ = self.self_attn(
341
+ hidden_states=hidden_states,
342
+ attention_mask=attention_mask,
343
+ position_ids=position_ids,
344
+ past_key_values=past_key_values,
345
+ use_cache=use_cache,
346
+ cache_position=cache_position,
347
+ position_embeddings=position_embeddings,
348
+ **kwargs,
349
+ )
350
+ hidden_states = residual + hidden_states
351
+
352
+ # Fully Connected
353
+ residual = hidden_states
354
+ hidden_states = self.post_attention_layernorm(hidden_states)
355
+ hidden_states = self.mlp(hidden_states)
356
+ hidden_states = residual + hidden_states
357
+ return hidden_states
358
+
359
+
360
+ @auto_docstring
361
+ class GPTNeoXPreTrainedModel(PreTrainedModel):
362
+ config: GPTNeoXConfig
363
+ base_model_prefix = "gpt_neox"
364
+ supports_gradient_checkpointing = True
365
+ _no_split_modules = ["GPTNeoXLayer"]
366
+ _skip_keys_device_placement = ["past_key_values"]
367
+ _supports_flash_attn = True
368
+ _supports_sdpa = True
369
+ _supports_flex_attn = True
370
+
371
+ _can_compile_fullgraph = True
372
+ _supports_attention_backend = True
373
+ _can_record_outputs = {
374
+ "hidden_states": GPTNeoXDecoderLayer,
375
+ "attentions": GPTNeoXAttention,
376
+ }
377
+ _keys_to_ignore_on_load_unexpected = [r"attention.bias", r"attention.masked_bias"]
378
+
379
+
380
+ @auto_docstring
381
+ class GPTNeoXModel(GPTNeoXPreTrainedModel):
382
+ def __init__(self, config):
383
+ super().__init__(config)
384
+ self.config = config
385
+
386
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
387
+ self.emb_dropout = nn.Dropout(config.hidden_dropout)
388
+ self.layers = nn.ModuleList([GPTNeoXLayer(config, i) for i in range(config.num_hidden_layers)])
389
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
390
+ self.rotary_emb = GPTNeoXRotaryEmbedding(config=config)
391
+ self.gradient_checkpointing = False
392
+
393
+ # Initialize weights and apply final processing
394
+ self.post_init()
395
+
396
+ @check_model_inputs
397
+ @auto_docstring
398
+ def forward(
399
+ self,
400
+ input_ids: Optional[torch.LongTensor] = None,
401
+ attention_mask: Optional[torch.FloatTensor] = None,
402
+ position_ids: Optional[torch.LongTensor] = None,
403
+ head_mask: Optional[torch.FloatTensor] = None,
404
+ inputs_embeds: Optional[torch.FloatTensor] = None,
405
+ past_key_values: Optional[Cache] = None,
406
+ use_cache: Optional[bool] = None,
407
+ output_attentions: Optional[bool] = None,
408
+ output_hidden_states: Optional[bool] = None,
409
+ cache_position: Optional[torch.LongTensor] = None,
410
+ **kwargs: Unpack[TransformersKwargs],
411
+ ) -> BaseModelOutputWithPast:
412
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
413
+ output_hidden_states = (
414
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
415
+ )
416
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
417
+
418
+ if (input_ids is None) ^ (inputs_embeds is not None):
419
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
420
+
421
+ if self.gradient_checkpointing and self.training:
422
+ if use_cache:
423
+ logger.warning_once(
424
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
425
+ )
426
+ use_cache = False
427
+
428
+ if inputs_embeds is None:
429
+ inputs_embeds = self.embed_in(input_ids)
430
+
431
+ if use_cache and past_key_values is None:
432
+ past_key_values = DynamicCache(config=self.config)
433
+
434
+ if cache_position is None:
435
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
436
+ cache_position = torch.arange(
437
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
438
+ )
439
+
440
+ if position_ids is None:
441
+ position_ids = cache_position.unsqueeze(0)
442
+
443
+ causal_mask = create_causal_mask(
444
+ config=self.config,
445
+ input_embeds=inputs_embeds,
446
+ attention_mask=attention_mask,
447
+ cache_position=cache_position,
448
+ past_key_values=past_key_values,
449
+ position_ids=position_ids,
450
+ )
451
+
452
+ # Prepare head mask if needed
453
+ # 1.0 in head_mask indicate we keep the head
454
+ # attention_probs has shape bsz x n_heads x N x N
455
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
456
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
457
+ converted_head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
458
+ # Flex Attention converts it to a separate mask
459
+ if head_mask is not None:
460
+ converted_head_mask = ~converted_head_mask.bool() * torch.finfo(inputs_embeds.dtype).min
461
+ converted_head_mask = converted_head_mask.to(dtype=self.dtype, device=self.device)
462
+ head_mask = converted_head_mask
463
+
464
+ hidden_states = self.emb_dropout(inputs_embeds)
465
+
466
+ # create position embeddings to be shared across the decoder layers
467
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
468
+
469
+ all_attentions = () if output_attentions else None
470
+ all_hidden_states = () if output_hidden_states else None
471
+ for i, layer in enumerate(self.layers):
472
+ if output_hidden_states:
473
+ all_hidden_states = all_hidden_states + (hidden_states,)
474
+
475
+ outputs = layer(
476
+ hidden_states,
477
+ attention_mask=causal_mask,
478
+ position_ids=position_ids,
479
+ head_mask=head_mask[i],
480
+ layer_past=past_key_values,
481
+ use_cache=use_cache,
482
+ output_attentions=output_attentions,
483
+ cache_position=cache_position,
484
+ position_embeddings=position_embeddings,
485
+ **kwargs,
486
+ )
487
+ hidden_states = outputs[0]
488
+
489
+ if output_attentions:
490
+ all_attentions = all_attentions + (outputs[1],)
491
+
492
+ hidden_states = self.final_layer_norm(hidden_states)
493
+ # Add last hidden state
494
+ if output_hidden_states:
495
+ all_hidden_states = all_hidden_states + (hidden_states,)
496
+
497
+ return BaseModelOutputWithPast(
498
+ last_hidden_state=hidden_states,
499
+ past_key_values=past_key_values,
500
+ hidden_states=all_hidden_states,
501
+ attentions=all_attentions,
502
+ )
503
+
504
+ def get_input_embeddings(self):
505
+ return self.embed_in
506
+
507
+ def set_input_embeddings(self, value):
508
+ self.embed_in = value
509
+
510
+
511
+ @auto_docstring(
512
+ custom_intro="""
513
+ GPTNeoX Model with a `language modeling` head on top for CLM fine-tuning.
514
+ """
515
+ )
516
+ class GPTNeoXForCausalLM(GPTNeoXPreTrainedModel, GenerationMixin):
517
+ _tied_weights_keys = ["embed_out.weight"]
518
+ _tp_plan = {"embed_out": "colwise_rep"}
519
+ _pp_plan = {"embed_out": (["hidden_states"], ["logits"])}
520
+
521
+ def __init__(self, config):
522
+ super().__init__(config)
523
+
524
+ self.gpt_neox = GPTNeoXModel(config)
525
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
526
+
527
+ # Initialize weights and apply final processing
528
+ self.post_init()
529
+
530
+ def get_output_embeddings(self):
531
+ return self.embed_out
532
+
533
+ def set_output_embeddings(self, new_embeddings):
534
+ self.embed_out = new_embeddings
535
+
536
+ @can_return_tuple
537
+ @auto_docstring
538
+ def forward(
539
+ self,
540
+ input_ids: Optional[torch.LongTensor] = None,
541
+ attention_mask: Optional[torch.FloatTensor] = None,
542
+ position_ids: Optional[torch.LongTensor] = None,
543
+ inputs_embeds: Optional[torch.FloatTensor] = None,
544
+ head_mask: Optional[torch.FloatTensor] = None,
545
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
546
+ labels: Optional[torch.LongTensor] = None,
547
+ use_cache: Optional[bool] = None,
548
+ output_attentions: Optional[bool] = None,
549
+ output_hidden_states: Optional[bool] = None,
550
+ cache_position: Optional[torch.LongTensor] = None,
551
+ logits_to_keep: Union[int, torch.Tensor] = 0,
552
+ **kwargs: Unpack[TransformersKwargs],
553
+ ) -> Union[tuple, CausalLMOutputWithPast]:
554
+ r"""
555
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
556
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
557
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
558
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
559
+
560
+ Example:
561
+
562
+ ```python
563
+ >>> from transformers import AutoTokenizer, GPTNeoXForCausalLM, GPTNeoXConfig
564
+ >>> import torch
565
+
566
+ >>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
567
+ >>> config = GPTNeoXConfig.from_pretrained("EleutherAI/gpt-neox-20b")
568
+ >>> config.is_decoder = True
569
+ >>> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", config=config)
570
+
571
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
572
+ >>> outputs = model(**inputs)
573
+
574
+ >>> prediction_logits = outputs.logits
575
+ ```"""
576
+
577
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
578
+ input_ids,
579
+ attention_mask=attention_mask,
580
+ position_ids=position_ids,
581
+ head_mask=head_mask,
582
+ inputs_embeds=inputs_embeds,
583
+ past_key_values=past_key_values,
584
+ use_cache=use_cache,
585
+ output_attentions=output_attentions,
586
+ output_hidden_states=output_hidden_states,
587
+ cache_position=cache_position,
588
+ **kwargs,
589
+ )
590
+
591
+ hidden_states = outputs.last_hidden_state
592
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
593
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
594
+ logits = self.embed_out(hidden_states[:, slice_indices, :])
595
+
596
+ loss = None
597
+ if labels is not None:
598
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
599
+
600
+ return CausalLMOutputWithPast(
601
+ loss=loss,
602
+ logits=logits,
603
+ past_key_values=outputs.past_key_values,
604
+ hidden_states=outputs.hidden_states,
605
+ attentions=outputs.attentions,
606
+ )
607
+
608
+
609
+ @auto_docstring(
610
+ custom_intro="""
611
+ The GPTNeoX Model transformer with a sequence classification head on top (linear layer).
612
+
613
+ [`GPTNeoXForSequenceClassification`] uses the last token in order to do the classification, as other causal models
614
+ (e.g. GPT-1) do.
615
+
616
+ Since it does classification on the last token, it requires to know the position of the last token. If a
617
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
618
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
619
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
620
+ each row of the batch).
621
+ """
622
+ )
623
+ class GPTNeoXForSequenceClassification(GPTNeoXPreTrainedModel):
624
+ def __init__(self, config):
625
+ super().__init__(config)
626
+ self.num_labels = config.num_labels
627
+ self.gpt_neox = GPTNeoXModel(config)
628
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
629
+
630
+ # Initialize weights and apply final processing
631
+ self.post_init()
632
+
633
+ @can_return_tuple
634
+ @auto_docstring
635
+ def forward(
636
+ self,
637
+ input_ids: Optional[torch.LongTensor] = None,
638
+ attention_mask: Optional[torch.FloatTensor] = None,
639
+ position_ids: Optional[torch.LongTensor] = None,
640
+ inputs_embeds: Optional[torch.FloatTensor] = None,
641
+ head_mask: Optional[torch.FloatTensor] = None,
642
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
643
+ labels: Optional[torch.LongTensor] = None,
644
+ use_cache: Optional[bool] = None,
645
+ output_attentions: Optional[bool] = None,
646
+ output_hidden_states: Optional[bool] = None,
647
+ ) -> SequenceClassifierOutputWithPast:
648
+ r"""
649
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
650
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
651
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
652
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
653
+ """
654
+
655
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
656
+ input_ids,
657
+ attention_mask=attention_mask,
658
+ position_ids=position_ids,
659
+ head_mask=head_mask,
660
+ inputs_embeds=inputs_embeds,
661
+ past_key_values=past_key_values,
662
+ use_cache=use_cache,
663
+ output_attentions=output_attentions,
664
+ output_hidden_states=output_hidden_states,
665
+ )
666
+ hidden_states = outputs.last_hidden_state
667
+ logits = self.score(hidden_states)
668
+
669
+ batch_size = logits.shape[0]
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
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
691
+
692
+ return SequenceClassifierOutputWithPast(
693
+ loss=loss,
694
+ logits=pooled_logits,
695
+ past_key_values=outputs.past_key_values,
696
+ hidden_states=outputs.hidden_states,
697
+ attentions=outputs.attentions,
698
+ )
699
+
700
+
701
+ class GPTNeoXForTokenClassification(GPTNeoXPreTrainedModel):
702
+ def __init__(self, config):
703
+ super().__init__(config)
704
+ self.num_labels = config.num_labels
705
+
706
+ self.gpt_neox = GPTNeoXModel(config)
707
+ self.dropout = nn.Dropout(config.classifier_dropout)
708
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
709
+
710
+ # Initialize weights and apply final processing
711
+ self.post_init()
712
+
713
+ @can_return_tuple
714
+ @auto_docstring
715
+ def forward(
716
+ self,
717
+ input_ids: Optional[torch.LongTensor] = None,
718
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.Tensor]]]] = None,
719
+ attention_mask: Optional[torch.FloatTensor] = None,
720
+ token_type_ids: Optional[torch.LongTensor] = None,
721
+ position_ids: Optional[torch.LongTensor] = None,
722
+ head_mask: Optional[torch.FloatTensor] = None,
723
+ inputs_embeds: Optional[torch.FloatTensor] = None,
724
+ labels: Optional[torch.LongTensor] = None,
725
+ use_cache: Optional[bool] = None,
726
+ output_attentions: Optional[bool] = None,
727
+ output_hidden_states: Optional[bool] = None,
728
+ ) -> TokenClassifierOutput:
729
+ r"""
730
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
731
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
732
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
733
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
734
+ """
735
+
736
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
737
+ input_ids,
738
+ past_key_values=past_key_values,
739
+ attention_mask=attention_mask,
740
+ position_ids=position_ids,
741
+ head_mask=head_mask,
742
+ inputs_embeds=inputs_embeds,
743
+ use_cache=use_cache,
744
+ output_attentions=output_attentions,
745
+ output_hidden_states=output_hidden_states,
746
+ )
747
+
748
+ hidden_states = outputs.last_hidden_state
749
+ hidden_states = self.dropout(hidden_states)
750
+ logits = self.classifier(hidden_states)
751
+
752
+ loss = None
753
+ if labels is not None:
754
+ loss = self.loss_function(logits, labels, self.config)
755
+
756
+ return TokenClassifierOutput(
757
+ loss=loss,
758
+ logits=logits,
759
+ hidden_states=outputs.hidden_states,
760
+ attentions=outputs.attentions,
761
+ )
762
+
763
+
764
+ @auto_docstring
765
+ class GPTNeoXForQuestionAnswering(GPTNeoXPreTrainedModel):
766
+ def __init__(self, config):
767
+ super().__init__(config)
768
+ self.num_labels = config.num_labels
769
+ self.gpt_neox = GPTNeoXModel(config)
770
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
771
+
772
+ # Initialize weights and apply final processing
773
+ self.post_init()
774
+
775
+ @can_return_tuple
776
+ @auto_docstring
777
+ def forward(
778
+ self,
779
+ input_ids: Optional[torch.LongTensor] = None,
780
+ attention_mask: Optional[torch.FloatTensor] = None,
781
+ token_type_ids: Optional[torch.LongTensor] = None,
782
+ position_ids: Optional[torch.LongTensor] = None,
783
+ head_mask: Optional[torch.FloatTensor] = None,
784
+ inputs_embeds: Optional[torch.FloatTensor] = None,
785
+ start_positions: Optional[torch.LongTensor] = None,
786
+ end_positions: Optional[torch.LongTensor] = None,
787
+ output_attentions: Optional[bool] = None,
788
+ output_hidden_states: Optional[bool] = None,
789
+ ) -> QuestionAnsweringModelOutput:
790
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
791
+ input_ids,
792
+ attention_mask=attention_mask,
793
+ position_ids=position_ids,
794
+ head_mask=head_mask,
795
+ inputs_embeds=inputs_embeds,
796
+ output_attentions=output_attentions,
797
+ output_hidden_states=output_hidden_states,
798
+ )
799
+
800
+ sequence_output = outputs.last_hidden_state
801
+
802
+ logits = self.qa_outputs(sequence_output)
803
+ start_logits, end_logits = logits.split(1, dim=-1)
804
+ start_logits = start_logits.squeeze(-1).contiguous()
805
+ end_logits = end_logits.squeeze(-1).contiguous()
806
+
807
+ loss = None
808
+ if start_positions is not None and end_positions is not None:
809
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions)
810
+
811
+ return QuestionAnsweringModelOutput(
812
+ loss=loss,
813
+ start_logits=start_logits,
814
+ end_logits=end_logits,
815
+ hidden_states=outputs.hidden_states,
816
+ attentions=outputs.attentions,
817
+ )
818
+
819
+
820
+ __all__ = [
821
+ "GPTNeoXForCausalLM",
822
+ "GPTNeoXForQuestionAnswering",
823
+ "GPTNeoXForSequenceClassification",
824
+ "GPTNeoXForTokenClassification",
825
+ "GPTNeoXLayer",
826
+ "GPTNeoXModel",
827
+ "GPTNeoXPreTrainedModel",
828
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/modular_gpt_neox.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from ...activations import ACT2FN
7
+ from ...cache_utils import Cache, DynamicCache
8
+ from ...generation import GenerationMixin
9
+ from ...masking_utils import create_causal_mask
10
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
11
+ from ...modeling_layers import GradientCheckpointingLayer
12
+ from ...modeling_outputs import (
13
+ BaseModelOutputWithPast,
14
+ CausalLMOutputWithPast,
15
+ QuestionAnsweringModelOutput,
16
+ SequenceClassifierOutputWithPast,
17
+ TokenClassifierOutput,
18
+ )
19
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
20
+ from ...processing_utils import Unpack
21
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
22
+ from ..llama.modeling_llama import LlamaModel, LlamaPreTrainedModel, LlamaRotaryEmbedding, rotate_half
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class GPTNeoXMLP(nn.Module):
29
+ def __init__(self, config):
30
+ super().__init__()
31
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
32
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
33
+ self.act = ACT2FN[config.hidden_act]
34
+
35
+ def forward(self, hidden_states):
36
+ hidden_states = self.dense_h_to_4h(hidden_states)
37
+ hidden_states = self.act(hidden_states)
38
+ hidden_states = self.dense_4h_to_h(hidden_states)
39
+ return hidden_states
40
+
41
+
42
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
43
+ """Applies Rotary Position Embedding to the query and key tensors.
44
+
45
+ Args:
46
+ q (`torch.Tensor`): The query tensor.
47
+ k (`torch.Tensor`): The key tensor.
48
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
49
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
50
+ position_ids (`torch.Tensor`, *optional*):
51
+ Deprecated and unused.
52
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
53
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
54
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
55
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
56
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
57
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
58
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
59
+ Returns:
60
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
61
+ """
62
+ cos = cos.unsqueeze(unsqueeze_dim)
63
+ sin = sin.unsqueeze(unsqueeze_dim)
64
+
65
+ # Keep half or full tensor for later concatenation
66
+ rotary_dim = cos.shape[-1]
67
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
68
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
69
+
70
+ # Apply rotary embeddings on the first half or full tensor
71
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
72
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
73
+
74
+ # Concatenate back to full shape
75
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
76
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
77
+ return q_embed, k_embed
78
+
79
+
80
+ def eager_attention_forward(
81
+ module: nn.Module,
82
+ query: torch.Tensor,
83
+ key: torch.Tensor,
84
+ value: torch.Tensor,
85
+ attention_mask: torch.Tensor,
86
+ scaling: float,
87
+ dropout: float = 0.0,
88
+ head_mask: Optional[torch.Tensor] = None,
89
+ **kwargs,
90
+ ):
91
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
92
+
93
+ if attention_mask is not None: # no matter the length, we just slice it
94
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
95
+ attn_weights = attn_weights + causal_mask
96
+
97
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
98
+
99
+ # Mask heads if we want to
100
+ if head_mask is not None:
101
+ attn_weights = attn_weights * head_mask
102
+
103
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
104
+ attn_output = torch.matmul(attn_weights, value)
105
+
106
+ # Reshape outputs
107
+ attn_output = attn_output.transpose(1, 2).contiguous()
108
+
109
+ return attn_output, attn_weights
110
+
111
+
112
+ class GPTNeoXAttention(nn.Module):
113
+ def __init__(self, config, layer_idx=None):
114
+ super().__init__()
115
+ self.config = config
116
+ self.head_size = config.hidden_size // config.num_attention_heads
117
+ self.attention_dropout = config.attention_dropout
118
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
119
+ self.scaling = self.head_size**-0.5
120
+ self.is_causal = True
121
+ self.layer_idx = layer_idx
122
+
123
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.attention_bias)
124
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
125
+
126
+ def forward(
127
+ self,
128
+ hidden_states: torch.FloatTensor,
129
+ attention_mask: torch.FloatTensor,
130
+ head_mask: Optional[torch.FloatTensor] = None,
131
+ layer_past: Optional[Cache] = None,
132
+ output_attentions: Optional[bool] = False,
133
+ cache_position: Optional[torch.LongTensor] = None,
134
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
135
+ **kwargs: Unpack[FlashAttentionKwargs],
136
+ ):
137
+ input_shape = hidden_states.shape[:-1]
138
+ hidden_shape = (*input_shape, -1, 3 * self.head_size)
139
+
140
+ qkv = self.query_key_value(hidden_states).view(hidden_shape).transpose(1, 2)
141
+ query_states, key_states, value_states = qkv.chunk(3, dim=-1)
142
+
143
+ cos, sin = position_embeddings
144
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
145
+
146
+ # Cache QKV values
147
+ if layer_past is not None:
148
+ cache_kwargs = {
149
+ "sin": sin,
150
+ "cos": cos,
151
+ "partial_rotation_size": self.rotary_ndims,
152
+ "cache_position": cache_position,
153
+ }
154
+ key_states, value_states = layer_past.update(key_states, value_states, self.layer_idx, cache_kwargs)
155
+
156
+ attention_interface: Callable = eager_attention_forward
157
+ if self.config._attn_implementation != "eager":
158
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
159
+
160
+ # Compute attention
161
+ attn_output, attn_weights = attention_interface(
162
+ self,
163
+ query_states,
164
+ key_states,
165
+ value_states,
166
+ attention_mask,
167
+ scaling=self.scaling,
168
+ dropout=0.0 if not self.training else self.attention_dropout,
169
+ head_mask=head_mask,
170
+ **kwargs,
171
+ )
172
+
173
+ # Reshape outputs and final projection
174
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
175
+ attn_output = self.dense(attn_output)
176
+
177
+ return attn_output, attn_weights
178
+
179
+
180
+ class GPTNeoXLayer(GradientCheckpointingLayer):
181
+ def __init__(self, config, layer_idx):
182
+ super().__init__()
183
+ self.use_parallel_residual = config.use_parallel_residual
184
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
185
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
186
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout)
187
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout)
188
+ self.attention = GPTNeoXAttention(config, layer_idx)
189
+ self.mlp = GPTNeoXMLP(config)
190
+
191
+ def forward(
192
+ self,
193
+ hidden_states: Optional[torch.FloatTensor],
194
+ attention_mask: Optional[torch.FloatTensor] = None,
195
+ position_ids: Optional[torch.LongTensor] = None,
196
+ head_mask: Optional[torch.FloatTensor] = None,
197
+ use_cache: Optional[bool] = False,
198
+ layer_past: Optional[Cache] = None,
199
+ output_attentions: Optional[bool] = False,
200
+ cache_position: Optional[torch.LongTensor] = None,
201
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
202
+ **kwargs: Unpack[FlashAttentionKwargs],
203
+ ):
204
+ attn_output, attn_weights = self.attention(
205
+ self.input_layernorm(hidden_states),
206
+ attention_mask=attention_mask,
207
+ position_ids=position_ids,
208
+ layer_past=layer_past,
209
+ head_mask=head_mask,
210
+ use_cache=use_cache,
211
+ output_attentions=output_attentions,
212
+ cache_position=cache_position,
213
+ position_embeddings=position_embeddings,
214
+ **kwargs,
215
+ )
216
+ attn_output = self.post_attention_dropout(attn_output)
217
+
218
+ if self.use_parallel_residual:
219
+ # pseudocode:
220
+ # x = x + attn(ln1(x)) + mlp(ln2(x))
221
+ mlp_output = self.mlp(self.post_attention_layernorm(hidden_states))
222
+ mlp_output = self.post_mlp_dropout(mlp_output)
223
+ hidden_states = mlp_output + attn_output + hidden_states
224
+ else:
225
+ # pseudocode:
226
+ # x = x + attn(ln1(x))
227
+ # x = x + mlp(ln2(x))
228
+ attn_output = attn_output + hidden_states
229
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
230
+ mlp_output = self.post_mlp_dropout(mlp_output)
231
+ hidden_states = mlp_output + attn_output
232
+
233
+ outputs = (hidden_states,)
234
+ if output_attentions:
235
+ outputs += (attn_weights,)
236
+
237
+ return outputs
238
+
239
+
240
+ class GPTNeoXRotaryEmbedding(LlamaRotaryEmbedding):
241
+ pass
242
+
243
+
244
+ class GPTNeoXPreTrainedModel(LlamaPreTrainedModel):
245
+ base_model_prefix = "gpt_neox"
246
+ _no_split_modules = ["GPTNeoXLayer"]
247
+ _keys_to_ignore_on_load_unexpected = [r"attention.bias", r"attention.masked_bias"]
248
+
249
+
250
+ GPT_NEOX_START_DOCSTRING = None # Will be picked up by modular
251
+ GPT_NEOX_INPUTS_DOCSTRING = None # Will be picked up by modular
252
+
253
+
254
+ class GPTNeoXModel(LlamaModel):
255
+ def __init__(self, config):
256
+ PreTrainedModel.__init__(self, config)
257
+ self.config = config
258
+
259
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
260
+ self.emb_dropout = nn.Dropout(config.hidden_dropout)
261
+ self.layers = nn.ModuleList([GPTNeoXLayer(config, i) for i in range(config.num_hidden_layers)])
262
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
263
+ self.rotary_emb = GPTNeoXRotaryEmbedding(config=config)
264
+ self.gradient_checkpointing = False
265
+
266
+ # Initialize weights and apply final processing
267
+ self.post_init()
268
+
269
+ def get_input_embeddings(self):
270
+ return self.embed_in
271
+
272
+ def set_input_embeddings(self, value):
273
+ self.embed_in = value
274
+
275
+ def forward(
276
+ self,
277
+ input_ids: Optional[torch.LongTensor] = None,
278
+ attention_mask: Optional[torch.FloatTensor] = None,
279
+ position_ids: Optional[torch.LongTensor] = None,
280
+ head_mask: Optional[torch.FloatTensor] = None,
281
+ inputs_embeds: Optional[torch.FloatTensor] = None,
282
+ past_key_values: Optional[Cache] = None,
283
+ use_cache: Optional[bool] = None,
284
+ output_attentions: Optional[bool] = None,
285
+ output_hidden_states: Optional[bool] = None,
286
+ cache_position: Optional[torch.LongTensor] = None,
287
+ **kwargs: Unpack[TransformersKwargs],
288
+ ) -> BaseModelOutputWithPast:
289
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
290
+ output_hidden_states = (
291
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
292
+ )
293
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
294
+
295
+ if (input_ids is None) ^ (inputs_embeds is not None):
296
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
297
+
298
+ if self.gradient_checkpointing and self.training:
299
+ if use_cache:
300
+ logger.warning_once(
301
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
302
+ )
303
+ use_cache = False
304
+
305
+ if inputs_embeds is None:
306
+ inputs_embeds = self.embed_in(input_ids)
307
+
308
+ if use_cache and past_key_values is None:
309
+ past_key_values = DynamicCache(config=self.config)
310
+
311
+ if cache_position is None:
312
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
313
+ cache_position = torch.arange(
314
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
315
+ )
316
+
317
+ if position_ids is None:
318
+ position_ids = cache_position.unsqueeze(0)
319
+
320
+ causal_mask = create_causal_mask(
321
+ config=self.config,
322
+ input_embeds=inputs_embeds,
323
+ attention_mask=attention_mask,
324
+ cache_position=cache_position,
325
+ past_key_values=past_key_values,
326
+ position_ids=position_ids,
327
+ )
328
+
329
+ # Prepare head mask if needed
330
+ # 1.0 in head_mask indicate we keep the head
331
+ # attention_probs has shape bsz x n_heads x N x N
332
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
333
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
334
+ converted_head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
335
+ # Flex Attention converts it to a separate mask
336
+ if head_mask is not None:
337
+ converted_head_mask = ~converted_head_mask.bool() * torch.finfo(inputs_embeds.dtype).min
338
+ converted_head_mask = converted_head_mask.to(dtype=self.dtype, device=self.device)
339
+ head_mask = converted_head_mask
340
+
341
+ hidden_states = self.emb_dropout(inputs_embeds)
342
+
343
+ # create position embeddings to be shared across the decoder layers
344
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
345
+
346
+ all_attentions = () if output_attentions else None
347
+ all_hidden_states = () if output_hidden_states else None
348
+ for i, layer in enumerate(self.layers):
349
+ if output_hidden_states:
350
+ all_hidden_states = all_hidden_states + (hidden_states,)
351
+
352
+ outputs = layer(
353
+ hidden_states,
354
+ attention_mask=causal_mask,
355
+ position_ids=position_ids,
356
+ head_mask=head_mask[i],
357
+ layer_past=past_key_values,
358
+ use_cache=use_cache,
359
+ output_attentions=output_attentions,
360
+ cache_position=cache_position,
361
+ position_embeddings=position_embeddings,
362
+ **kwargs,
363
+ )
364
+ hidden_states = outputs[0]
365
+
366
+ if output_attentions:
367
+ all_attentions = all_attentions + (outputs[1],)
368
+
369
+ hidden_states = self.final_layer_norm(hidden_states)
370
+ # Add last hidden state
371
+ if output_hidden_states:
372
+ all_hidden_states = all_hidden_states + (hidden_states,)
373
+
374
+ return BaseModelOutputWithPast(
375
+ last_hidden_state=hidden_states,
376
+ past_key_values=past_key_values,
377
+ hidden_states=all_hidden_states,
378
+ attentions=all_attentions,
379
+ )
380
+
381
+
382
+ @auto_docstring(
383
+ custom_intro="""
384
+ GPTNeoX Model with a `language modeling` head on top for CLM fine-tuning.
385
+ """
386
+ )
387
+ class GPTNeoXForCausalLM(GPTNeoXPreTrainedModel, GenerationMixin):
388
+ _tied_weights_keys = ["embed_out.weight"]
389
+ _tp_plan = {"embed_out": "colwise_rep"}
390
+ _pp_plan = {"embed_out": (["hidden_states"], ["logits"])}
391
+
392
+ def __init__(self, config):
393
+ super().__init__(config)
394
+
395
+ self.gpt_neox = GPTNeoXModel(config)
396
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
397
+
398
+ # Initialize weights and apply final processing
399
+ self.post_init()
400
+
401
+ def get_output_embeddings(self):
402
+ return self.embed_out
403
+
404
+ def set_output_embeddings(self, new_embeddings):
405
+ self.embed_out = new_embeddings
406
+
407
+ @can_return_tuple
408
+ @auto_docstring
409
+ def forward(
410
+ self,
411
+ input_ids: Optional[torch.LongTensor] = None,
412
+ attention_mask: Optional[torch.FloatTensor] = None,
413
+ position_ids: Optional[torch.LongTensor] = None,
414
+ inputs_embeds: Optional[torch.FloatTensor] = None,
415
+ head_mask: Optional[torch.FloatTensor] = None,
416
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
417
+ labels: Optional[torch.LongTensor] = None,
418
+ use_cache: Optional[bool] = None,
419
+ output_attentions: Optional[bool] = None,
420
+ output_hidden_states: Optional[bool] = None,
421
+ cache_position: Optional[torch.LongTensor] = None,
422
+ logits_to_keep: Union[int, torch.Tensor] = 0,
423
+ **kwargs: Unpack[TransformersKwargs],
424
+ ) -> Union[tuple, CausalLMOutputWithPast]:
425
+ r"""
426
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
427
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
428
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
429
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
430
+
431
+ Example:
432
+
433
+ ```python
434
+ >>> from transformers import AutoTokenizer, GPTNeoXForCausalLM, GPTNeoXConfig
435
+ >>> import torch
436
+
437
+ >>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
438
+ >>> config = GPTNeoXConfig.from_pretrained("EleutherAI/gpt-neox-20b")
439
+ >>> config.is_decoder = True
440
+ >>> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", config=config)
441
+
442
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
443
+ >>> outputs = model(**inputs)
444
+
445
+ >>> prediction_logits = outputs.logits
446
+ ```"""
447
+
448
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
449
+ input_ids,
450
+ attention_mask=attention_mask,
451
+ position_ids=position_ids,
452
+ head_mask=head_mask,
453
+ inputs_embeds=inputs_embeds,
454
+ past_key_values=past_key_values,
455
+ use_cache=use_cache,
456
+ output_attentions=output_attentions,
457
+ output_hidden_states=output_hidden_states,
458
+ cache_position=cache_position,
459
+ **kwargs,
460
+ )
461
+
462
+ hidden_states = outputs.last_hidden_state
463
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
464
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
465
+ logits = self.embed_out(hidden_states[:, slice_indices, :])
466
+
467
+ loss = None
468
+ if labels is not None:
469
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
470
+
471
+ return CausalLMOutputWithPast(
472
+ loss=loss,
473
+ logits=logits,
474
+ past_key_values=outputs.past_key_values,
475
+ hidden_states=outputs.hidden_states,
476
+ attentions=outputs.attentions,
477
+ )
478
+
479
+
480
+ @auto_docstring(
481
+ custom_intro="""
482
+ The GPTNeoX Model transformer with a sequence classification head on top (linear layer).
483
+
484
+ [`GPTNeoXForSequenceClassification`] uses the last token in order to do the classification, as other causal models
485
+ (e.g. GPT-1) do.
486
+
487
+ Since it does classification on the last token, it requires to know the position of the last token. If a
488
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
489
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
490
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
491
+ each row of the batch).
492
+ """
493
+ )
494
+ class GPTNeoXForSequenceClassification(GPTNeoXPreTrainedModel):
495
+ def __init__(self, config):
496
+ super().__init__(config)
497
+ self.num_labels = config.num_labels
498
+ self.gpt_neox = GPTNeoXModel(config)
499
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
500
+
501
+ # Initialize weights and apply final processing
502
+ self.post_init()
503
+
504
+ @can_return_tuple
505
+ @auto_docstring
506
+ def forward(
507
+ self,
508
+ input_ids: Optional[torch.LongTensor] = None,
509
+ attention_mask: Optional[torch.FloatTensor] = None,
510
+ position_ids: Optional[torch.LongTensor] = None,
511
+ inputs_embeds: Optional[torch.FloatTensor] = None,
512
+ head_mask: Optional[torch.FloatTensor] = None,
513
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
514
+ labels: Optional[torch.LongTensor] = None,
515
+ use_cache: Optional[bool] = None,
516
+ output_attentions: Optional[bool] = None,
517
+ output_hidden_states: Optional[bool] = None,
518
+ ) -> SequenceClassifierOutputWithPast:
519
+ r"""
520
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
521
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
522
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
523
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
524
+ """
525
+
526
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
527
+ input_ids,
528
+ attention_mask=attention_mask,
529
+ position_ids=position_ids,
530
+ head_mask=head_mask,
531
+ inputs_embeds=inputs_embeds,
532
+ past_key_values=past_key_values,
533
+ use_cache=use_cache,
534
+ output_attentions=output_attentions,
535
+ output_hidden_states=output_hidden_states,
536
+ )
537
+ hidden_states = outputs.last_hidden_state
538
+ logits = self.score(hidden_states)
539
+
540
+ batch_size = logits.shape[0]
541
+ if self.config.pad_token_id is None and batch_size != 1:
542
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
543
+ if self.config.pad_token_id is None:
544
+ last_non_pad_token = -1
545
+ elif input_ids is not None:
546
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
547
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
548
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
549
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
550
+ else:
551
+ last_non_pad_token = -1
552
+ logger.warning_once(
553
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
554
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
555
+ )
556
+
557
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
558
+
559
+ loss = None
560
+ if labels is not None:
561
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
562
+
563
+ return SequenceClassifierOutputWithPast(
564
+ loss=loss,
565
+ logits=pooled_logits,
566
+ past_key_values=outputs.past_key_values,
567
+ hidden_states=outputs.hidden_states,
568
+ attentions=outputs.attentions,
569
+ )
570
+
571
+
572
+ class GPTNeoXForTokenClassification(GPTNeoXPreTrainedModel):
573
+ def __init__(self, config):
574
+ super().__init__(config)
575
+ self.num_labels = config.num_labels
576
+
577
+ self.gpt_neox = GPTNeoXModel(config)
578
+ self.dropout = nn.Dropout(config.classifier_dropout)
579
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
580
+
581
+ # Initialize weights and apply final processing
582
+ self.post_init()
583
+
584
+ @can_return_tuple
585
+ @auto_docstring
586
+ def forward(
587
+ self,
588
+ input_ids: Optional[torch.LongTensor] = None,
589
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.Tensor]]]] = None,
590
+ attention_mask: Optional[torch.FloatTensor] = None,
591
+ token_type_ids: Optional[torch.LongTensor] = None,
592
+ position_ids: Optional[torch.LongTensor] = None,
593
+ head_mask: Optional[torch.FloatTensor] = None,
594
+ inputs_embeds: Optional[torch.FloatTensor] = None,
595
+ labels: Optional[torch.LongTensor] = None,
596
+ use_cache: Optional[bool] = None,
597
+ output_attentions: Optional[bool] = None,
598
+ output_hidden_states: Optional[bool] = None,
599
+ ) -> TokenClassifierOutput:
600
+ r"""
601
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
602
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
603
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
604
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
605
+ """
606
+
607
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
608
+ input_ids,
609
+ past_key_values=past_key_values,
610
+ attention_mask=attention_mask,
611
+ position_ids=position_ids,
612
+ head_mask=head_mask,
613
+ inputs_embeds=inputs_embeds,
614
+ use_cache=use_cache,
615
+ output_attentions=output_attentions,
616
+ output_hidden_states=output_hidden_states,
617
+ )
618
+
619
+ hidden_states = outputs.last_hidden_state
620
+ hidden_states = self.dropout(hidden_states)
621
+ logits = self.classifier(hidden_states)
622
+
623
+ loss = None
624
+ if labels is not None:
625
+ loss = self.loss_function(logits, labels, self.config)
626
+
627
+ return TokenClassifierOutput(
628
+ loss=loss,
629
+ logits=logits,
630
+ hidden_states=outputs.hidden_states,
631
+ attentions=outputs.attentions,
632
+ )
633
+
634
+
635
+ @auto_docstring
636
+ class GPTNeoXForQuestionAnswering(GPTNeoXPreTrainedModel):
637
+ def __init__(self, config):
638
+ super().__init__(config)
639
+ self.num_labels = config.num_labels
640
+ self.gpt_neox = GPTNeoXModel(config)
641
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
642
+
643
+ # Initialize weights and apply final processing
644
+ self.post_init()
645
+
646
+ @can_return_tuple
647
+ @auto_docstring
648
+ def forward(
649
+ self,
650
+ input_ids: Optional[torch.LongTensor] = None,
651
+ attention_mask: Optional[torch.FloatTensor] = None,
652
+ token_type_ids: Optional[torch.LongTensor] = None,
653
+ position_ids: Optional[torch.LongTensor] = None,
654
+ head_mask: Optional[torch.FloatTensor] = None,
655
+ inputs_embeds: Optional[torch.FloatTensor] = None,
656
+ start_positions: Optional[torch.LongTensor] = None,
657
+ end_positions: Optional[torch.LongTensor] = None,
658
+ output_attentions: Optional[bool] = None,
659
+ output_hidden_states: Optional[bool] = None,
660
+ ) -> QuestionAnsweringModelOutput:
661
+ outputs: BaseModelOutputWithPast = self.gpt_neox(
662
+ input_ids,
663
+ attention_mask=attention_mask,
664
+ position_ids=position_ids,
665
+ head_mask=head_mask,
666
+ inputs_embeds=inputs_embeds,
667
+ output_attentions=output_attentions,
668
+ output_hidden_states=output_hidden_states,
669
+ )
670
+
671
+ sequence_output = outputs.last_hidden_state
672
+
673
+ logits = self.qa_outputs(sequence_output)
674
+ start_logits, end_logits = logits.split(1, dim=-1)
675
+ start_logits = start_logits.squeeze(-1).contiguous()
676
+ end_logits = end_logits.squeeze(-1).contiguous()
677
+
678
+ loss = None
679
+ if start_positions is not None and end_positions is not None:
680
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions)
681
+
682
+ return QuestionAnsweringModelOutput(
683
+ loss=loss,
684
+ start_logits=start_logits,
685
+ end_logits=end_logits,
686
+ hidden_states=outputs.hidden_states,
687
+ attentions=outputs.attentions,
688
+ )
689
+
690
+
691
+ __all__ = [
692
+ "GPTNeoXForCausalLM",
693
+ "GPTNeoXForQuestionAnswering",
694
+ "GPTNeoXForSequenceClassification",
695
+ "GPTNeoXForTokenClassification",
696
+ "GPTNeoXLayer",
697
+ "GPTNeoXModel",
698
+ "GPTNeoXPreTrainedModel",
699
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox/tokenization_gpt_neox_fast.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and The HuggingFace Inc. team. 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
+ """Tokenization classes for GPTNeoX."""
16
+
17
+ from typing import Optional
18
+
19
+ from tokenizers import processors
20
+
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
28
+
29
+
30
+ class GPTNeoXTokenizerFast(PreTrainedTokenizerFast):
31
+ """
32
+ Construct a "fast" GPT-NeoX-20B tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
33
+ Byte-Pair-Encoding.
34
+
35
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
36
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
37
+
38
+ ```python
39
+ >>> from transformers import GPTNeoXTokenizerFast
40
+
41
+ >>> tokenizer = GPTNeoXTokenizerFast.from_pretrained("openai-community/gpt2")
42
+ >>> tokenizer("Hello world")["input_ids"]
43
+ [15496, 995]
44
+
45
+ >>> tokenizer(" Hello world")["input_ids"]
46
+ [18435, 995]
47
+ ```
48
+
49
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
50
+ the model was not pretrained this way, it might yield a decrease in performance.
51
+
52
+ <Tip>
53
+
54
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
55
+
56
+ </Tip>
57
+
58
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
59
+ refer to this superclass for more information regarding those methods.
60
+
61
+ Args:
62
+ vocab_file (`str`):
63
+ Path to the vocabulary file.
64
+ merges_file (`str`):
65
+ Path to the merges file.
66
+ errors (`str`, *optional*, defaults to `"replace"`):
67
+ Paradigm to follow when decoding bytes to UTF-8. See
68
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
69
+ unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
70
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
71
+ token instead.
72
+ bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
73
+ The beginning of sequence token.
74
+ eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
75
+ The end of sequence token.
76
+ pad_token (`str`, *optional*):
77
+ Token for padding a sequence.
78
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
79
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
80
+ other word. (GPTNeoX tokenizer detect beginning of words by the preceding space).
81
+ add_bos_token (`bool`, *optional*, defaults to `False`):
82
+ Whether or not to add a `bos_token` at the start of sequences.
83
+ add_eos_token (`bool`, *optional*, defaults to `False`):
84
+ Whether or not to add an `eos_token` at the end of sequences.
85
+ trim_offsets (`bool`, *optional*, defaults to `True`):
86
+ Whether or not the post-processing step should trim offsets to avoid including whitespaces.
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+ model_input_names = ["input_ids", "attention_mask"]
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_file=None,
95
+ merges_file=None,
96
+ tokenizer_file=None,
97
+ unk_token="<|endoftext|>",
98
+ bos_token="<|endoftext|>",
99
+ eos_token="<|endoftext|>",
100
+ pad_token=None,
101
+ add_bos_token=False,
102
+ add_eos_token=False,
103
+ add_prefix_space=False,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(
107
+ vocab_file=vocab_file,
108
+ merges_file=merges_file,
109
+ tokenizer_file=tokenizer_file,
110
+ unk_token=unk_token,
111
+ bos_token=bos_token,
112
+ eos_token=eos_token,
113
+ pad_token=pad_token,
114
+ add_bos_token=add_bos_token,
115
+ add_eos_token=add_eos_token,
116
+ add_prefix_space=add_prefix_space,
117
+ **kwargs,
118
+ )
119
+
120
+ self._add_bos_token = add_bos_token
121
+ self._add_eos_token = add_eos_token
122
+ self.update_post_processor()
123
+
124
+ @property
125
+ def add_eos_token(self):
126
+ return self._add_eos_token
127
+
128
+ @property
129
+ def add_bos_token(self):
130
+ return self._add_bos_token
131
+
132
+ @add_eos_token.setter
133
+ def add_eos_token(self, value):
134
+ self._add_eos_token = value
135
+ self.update_post_processor()
136
+
137
+ @add_bos_token.setter
138
+ def add_bos_token(self, value):
139
+ self._add_bos_token = value
140
+ self.update_post_processor()
141
+
142
+ # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.update_post_processor
143
+ def update_post_processor(self):
144
+ """
145
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
146
+ """
147
+ bos = self.bos_token
148
+ bos_token_id = self.bos_token_id
149
+ if bos is None and self.add_bos_token:
150
+ raise ValueError("add_bos_token = True but bos_token = None")
151
+
152
+ eos = self.eos_token
153
+ eos_token_id = self.eos_token_id
154
+ if eos is None and self.add_eos_token:
155
+ raise ValueError("add_eos_token = True but eos_token = None")
156
+
157
+ single = f"{(bos + ':0 ') if self.add_bos_token else ''}$A:0{(' ' + eos + ':0') if self.add_eos_token else ''}"
158
+ pair = f"{single}{(' ' + bos + ':1') if self.add_bos_token else ''} $B:1{(' ' + eos + ':1') if self.add_eos_token else ''}"
159
+
160
+ special_tokens = []
161
+ if self.add_bos_token:
162
+ special_tokens.append((bos, bos_token_id))
163
+ if self.add_eos_token:
164
+ special_tokens.append((eos, eos_token_id))
165
+ self._tokenizer.post_processor = processors.TemplateProcessing(
166
+ single=single, pair=pair, special_tokens=special_tokens
167
+ )
168
+
169
+ # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_special_tokens_mask
170
+ def get_special_tokens_mask(
171
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
172
+ ) -> list[int]:
173
+ """
174
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
175
+ special tokens using the tokenizer `prepare_for_model` method.
176
+
177
+ Args:
178
+ token_ids_0 (`list[int]`):
179
+ List of IDs.
180
+ token_ids_1 (`list[int]`, *optional*):
181
+ Optional second list of IDs for sequence pairs.
182
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
183
+ Whether or not the token list is already formatted with special tokens for the model.
184
+
185
+ Returns:
186
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
187
+ """
188
+ if already_has_special_tokens:
189
+ return super().get_special_tokens_mask(
190
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
191
+ )
192
+
193
+ bos_token_id = [1] if self.add_bos_token else []
194
+ eos_token_id = [1] if self.add_eos_token else []
195
+
196
+ if token_ids_1 is None:
197
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
198
+ return (
199
+ bos_token_id
200
+ + ([0] * len(token_ids_0))
201
+ + eos_token_id
202
+ + bos_token_id
203
+ + ([0] * len(token_ids_1))
204
+ + eos_token_id
205
+ )
206
+
207
+ # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.build_inputs_with_special_tokens
208
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
209
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
210
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
211
+
212
+ output = bos_token_id + token_ids_0 + eos_token_id
213
+
214
+ if token_ids_1 is not None:
215
+ output = output + bos_token_id + token_ids_1 + eos_token_id
216
+
217
+ return output
218
+
219
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
220
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
221
+ return tuple(files)
222
+
223
+
224
+ __all__ = ["GPTNeoXTokenizerFast"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__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_gpt_neox_japanese import *
22
+ from .modeling_gpt_neox_japanese import *
23
+ from .tokenization_gpt_neox_japanese 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__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 ABEJA, Inc. and The HuggingFace Inc. team. 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
+ """GPTNeoX Japanese model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class GPTNeoXJapaneseConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`GPTNeoXModelJapanese`]. It is used to instantiate
28
+ a GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the GPTNeoXJapanese
30
+ [abeja/gpt-neox-japanese-2.7b](https://huggingface.co/abeja/gpt-neox-japanese-2.7b) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information. Default configs is set as 2.7B model
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the GPTNeoXJapanese model. Defines the number of different tokens that can be
38
+ represented by the `inputs_ids` passed when calling [`GPTNeoXJapanese`].
39
+ hidden_size (`int`, *optional*, defaults to 2560):
40
+ Dimension of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 32):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 32):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_multiple_size (`int`, *optional*, defaults to 4):
46
+ Dimension of the "intermediate" layer in the Transformer encoder is calculated by hidden_size *
47
+ intermediate_multiple_size.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler.
50
+ rotary_pct (`float`, *optional*, defaults to 1.00):
51
+ percentage of hidden dimensions to allocate to rotary embeddings
52
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
53
+ base for computing rotary embeddings frequency
54
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
55
+ The maximum sequence length that this model might ever be used with.
56
+ initializer_range (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
59
+ The epsilon used by the layer normalization layers.
60
+ use_cache (`bool`, *optional*, defaults to `True`):
61
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
62
+ relevant if `config.is_decoder=True`.
63
+ rope_scaling (`Dict`, *optional*):
64
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
65
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
66
+ accordingly.
67
+ Expected contents:
68
+ `rope_type` (`str`):
69
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
70
+ 'llama3'], with 'default' being the original RoPE implementation.
71
+ `factor` (`float`, *optional*):
72
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
73
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
74
+ original maximum pre-trained length.
75
+ `original_max_position_embeddings` (`int`, *optional*):
76
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
77
+ pretraining.
78
+ `attention_factor` (`float`, *optional*):
79
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
80
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
81
+ `factor` field to infer the suggested value.
82
+ `beta_fast` (`float`, *optional*):
83
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
84
+ ramp function. If unspecified, it defaults to 32.
85
+ `beta_slow` (`float`, *optional*):
86
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
87
+ ramp function. If unspecified, it defaults to 1.
88
+ `short_factor` (`list[float]`, *optional*):
89
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
90
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
91
+ size divided by the number of attention heads divided by 2
92
+ `long_factor` (`list[float]`, *optional*):
93
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
94
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
95
+ size divided by the number of attention heads divided by 2
96
+ `low_freq_factor` (`float`, *optional*):
97
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
98
+ `high_freq_factor` (`float`, *optional*):
99
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
100
+ attention_dropout (`float`, *optional*, defaults to 0.1):
101
+ The dropout ratio for the attention.
102
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
103
+ The dropout ratio for the hidden layer.
104
+ Example:
105
+
106
+ ```python
107
+ >>> from transformers import GPTNeoXJapaneseConfig, GPTNeoXJapaneseModel
108
+
109
+ >>> # Initializing a GPTNeoXJapanese gpt-neox-japanese-2.7b style configuration
110
+ >>> configuration = GPTNeoXJapaneseConfig()
111
+
112
+ >>> # Initializing a model (with random weights) from the gpt-neox-japanese-2.7b style configuration
113
+ >>> model = GPTNeoXJapaneseModel(configuration)
114
+
115
+ >>> # Accessing the model configuration
116
+ >>> configuration = model.config
117
+ ```"""
118
+
119
+ model_type = "gpt_neox_japanese"
120
+
121
+ def __init__(
122
+ self,
123
+ vocab_size=32000,
124
+ hidden_size=2560,
125
+ num_hidden_layers=32,
126
+ num_attention_heads=32,
127
+ intermediate_multiple_size=4,
128
+ hidden_act="gelu",
129
+ rotary_pct=1.00,
130
+ rotary_emb_base=10000,
131
+ max_position_embeddings=2048,
132
+ initializer_range=0.02,
133
+ layer_norm_eps=1e-5,
134
+ use_cache=True,
135
+ bos_token_id=31996,
136
+ eos_token_id=31999,
137
+ rope_scaling=None,
138
+ attention_dropout=0.1,
139
+ hidden_dropout=0.0,
140
+ **kwargs,
141
+ ):
142
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
143
+ self.vocab_size = vocab_size
144
+ self.max_position_embeddings = max_position_embeddings
145
+ self.hidden_size = hidden_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+ self.intermediate_multiple_size = intermediate_multiple_size
149
+ self.hidden_act = hidden_act
150
+ self.rotary_pct = rotary_pct
151
+ self.partial_rotary_factor = rotary_pct
152
+ self.rotary_emb_base = rotary_emb_base
153
+ self.rope_theta = rotary_emb_base
154
+ self.initializer_range = initializer_range
155
+ self.layer_norm_eps = layer_norm_eps
156
+ self.use_cache = use_cache
157
+ self.rope_scaling = rope_scaling
158
+ self.attention_dropout = attention_dropout
159
+ self.hidden_dropout = hidden_dropout
160
+ # Validate the correctness of rotary position embeddings parameters
161
+ # BC: if there is a 'type' field, move it to 'rope_type'.
162
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
163
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
164
+ rope_config_validation(self)
165
+
166
+
167
+ __all__ = ["GPTNeoXJapaneseConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 ABEJA, Inc. and The HuggingFace Inc. team. 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 GPTNeoX model."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ from torch import Tensor, nn
22
+
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
27
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
28
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import auto_docstring, is_torch_flex_attn_available, logging
31
+ from .configuration_gpt_neox_japanese import GPTNeoXJapaneseConfig
32
+
33
+
34
+ if is_torch_flex_attn_available():
35
+ from torch.nn.attention.flex_attention import BlockMask
36
+
37
+ from ...integrations.flex_attention import make_flex_block_causal_mask
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ @auto_docstring
44
+ class GPTNeoXJapanesePreTrainedModel(PreTrainedModel):
45
+ config: GPTNeoXJapaneseConfig
46
+ base_model_prefix = "gpt_neox_japanese"
47
+ _no_split_modules = ["GPTNeoXJapaneseLayer"]
48
+ _skip_keys_device_placement = "past_key_values"
49
+
50
+ _can_compile_fullgraph = True
51
+
52
+ def _init_weights(self, module):
53
+ """Initialize the weights"""
54
+ if isinstance(module, nn.Linear):
55
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
56
+ if module.bias is not None:
57
+ module.bias.data.zero_()
58
+ elif isinstance(module, nn.Embedding):
59
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
60
+ if module.padding_idx is not None:
61
+ module.weight.data[module.padding_idx].zero_()
62
+ elif isinstance(module, nn.LayerNorm):
63
+ module.bias.data.zero_()
64
+ module.weight.data.fill_(1.0)
65
+ elif isinstance(module, GPTNeoXJapaneseAttention):
66
+ if module.dense_bias is not None:
67
+ module.dense_bias.data.zero_()
68
+
69
+
70
+ class GPTNeoXJapaneseAttention(nn.Module):
71
+ def __init__(self, config, use_bias=False, layer_idx=None):
72
+ super().__init__()
73
+ self.num_attention_heads = config.num_attention_heads
74
+ self.hidden_size = config.hidden_size
75
+ self.head_size = self.hidden_size // self.num_attention_heads
76
+ if layer_idx is None:
77
+ logger.warning_once(
78
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
79
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
80
+ "when creating this class."
81
+ )
82
+
83
+ self.layer_idx = layer_idx
84
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
85
+ self.rope_theta = config.rotary_emb_base
86
+ self.rotary_emb = GPTNeoXJapaneseRotaryEmbedding(config=config)
87
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
88
+ self.norm_factor = math.sqrt(self.head_size)
89
+
90
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=False)
91
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
92
+ # Activate bias if the last layer
93
+ self.use_bias = use_bias
94
+ self.dense_bias = nn.Parameter(torch.zeros(config.hidden_size)) if use_bias else None
95
+
96
+ def forward(
97
+ self,
98
+ hidden_states: torch.FloatTensor,
99
+ attention_mask: torch.FloatTensor,
100
+ position_ids: torch.LongTensor,
101
+ head_mask: Optional[torch.FloatTensor] = None,
102
+ layer_past: Optional[Cache] = None,
103
+ use_cache: Optional[bool] = False,
104
+ output_attentions: Optional[bool] = False,
105
+ cache_position: Optional[torch.LongTensor] = None,
106
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
107
+ ):
108
+ # Compute QKV
109
+ # Attention heads [batch, seq_len, hidden_size]
110
+ # --> [batch, seq_len, (np * 3 * head_size)]
111
+ qkv = self.query_key_value(hidden_states)
112
+
113
+ # [batch, seq_len, (num_heads * 3 * head_size)]
114
+ # --> [batch, seq_len, num_heads, 3 * head_size]
115
+ new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)
116
+ qkv = qkv.view(*new_qkv_shape)
117
+
118
+ # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
119
+ query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
120
+ key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)
121
+ value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)
122
+
123
+ # Compute rotary embeddings on rotary_ndims
124
+ query_rot = query[..., : self.rotary_ndims]
125
+ query_pass = query[..., self.rotary_ndims :]
126
+ key_rot = key[..., : self.rotary_ndims]
127
+ key_pass = key[..., self.rotary_ndims :]
128
+
129
+ cos, sin = position_embeddings
130
+ query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
131
+ query = torch.cat((query, query_pass), dim=-1).contiguous()
132
+ key = torch.cat((key, key_pass), dim=-1).contiguous()
133
+
134
+ # Cache QKV values
135
+ if layer_past is not None:
136
+ cache_kwargs = {
137
+ "sin": sin,
138
+ "cos": cos,
139
+ "partial_rotation_size": self.rotary_ndims,
140
+ "cache_position": cache_position,
141
+ }
142
+ key, value = layer_past.update(key, value, self.layer_idx, cache_kwargs)
143
+
144
+ # Compute attention
145
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
146
+
147
+ # Reshape outputs
148
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_size)
149
+ attn_output = self.dense(attn_output)
150
+
151
+ return attn_output, attn_weights, self.dense_bias
152
+
153
+ @classmethod
154
+ def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
155
+ """
156
+ Splits hidden dim into attn_head_size and num_attention_heads
157
+ """
158
+ # tensor: [bs, seq_len, hidden_size]
159
+ new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
160
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
161
+ tensor = tensor.view(new_shape)
162
+ # -> [bs, num_attention_heads, seq_len, attn_head_size]
163
+ tensor = tensor.permute(0, 2, 1, 3)
164
+ return tensor
165
+
166
+ @classmethod
167
+ def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
168
+ """
169
+ Merges attn_head_size dim and num_attn_heads dim into hidden dim
170
+ """
171
+ # tensor [bs, num_attention_heads, seq_len, attn_head_size]
172
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
173
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
174
+ tensor = tensor.view(tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size)
175
+ # -> [bs, seq_len, hidden_size]
176
+ return tensor
177
+
178
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
179
+ # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]
180
+ # compute causal mask from causal mask buffer
181
+ batch_size, num_attention_heads, query_length, attn_head_size = query.size()
182
+ key_length = key.size(-2)
183
+
184
+ query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)
185
+ key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)
186
+
187
+ # [batch_size * num_heads, q_length, kv_length]
188
+ attn_scores = torch.zeros(
189
+ batch_size * num_attention_heads,
190
+ query_length,
191
+ key_length,
192
+ dtype=query.dtype,
193
+ device=key.device,
194
+ )
195
+ attention_scores = torch.baddbmm(
196
+ attn_scores,
197
+ query,
198
+ key.transpose(1, 2),
199
+ beta=1.0,
200
+ alpha=1.0 / self.norm_factor,
201
+ )
202
+
203
+ attention_scores = attention_scores.view(batch_size, num_attention_heads, query_length, -1)
204
+ if attention_mask is not None: # no matter the length, we just slice it
205
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
206
+ attention_scores = attention_scores + causal_mask
207
+
208
+ attn_weights = nn.functional.softmax(attention_scores, dim=-1)
209
+ attn_weights = self.attention_dropout(attn_weights)
210
+ attn_weights = attn_weights.to(value.dtype)
211
+
212
+ # Mask heads if we want to
213
+ if head_mask is not None:
214
+ attn_weights = attn_weights * head_mask
215
+
216
+ attn_output = torch.matmul(attn_weights, value)
217
+ return attn_output, attn_weights
218
+
219
+
220
+ # Copied from transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXRotaryEmbedding with GPTNeoX->GPTNeoXJapanese
221
+ class GPTNeoXJapaneseRotaryEmbedding(nn.Module):
222
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
223
+
224
+ def __init__(self, config: GPTNeoXJapaneseConfig, device=None):
225
+ super().__init__()
226
+ # BC: "rope_type" was originally "type"
227
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
228
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
229
+ else:
230
+ self.rope_type = "default"
231
+ self.max_seq_len_cached = config.max_position_embeddings
232
+ self.original_max_seq_len = config.max_position_embeddings
233
+
234
+ self.config = config
235
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
236
+
237
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
238
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
239
+ self.original_inv_freq = self.inv_freq
240
+
241
+ @torch.no_grad()
242
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
243
+ def forward(self, x, position_ids):
244
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
245
+ position_ids_expanded = position_ids[:, None, :].float()
246
+
247
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
248
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
249
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
250
+ emb = torch.cat((freqs, freqs), dim=-1)
251
+ cos = emb.cos() * self.attention_scaling
252
+ sin = emb.sin() * self.attention_scaling
253
+
254
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
255
+
256
+
257
+ def rotate_half(x):
258
+ """Rotates half the hidden dims of the input."""
259
+ x1 = x[..., : x.shape[-1] // 2]
260
+ x2 = x[..., x.shape[-1] // 2 :]
261
+ return torch.cat((-x2, x1), dim=-1)
262
+
263
+
264
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
265
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
266
+ """Applies Rotary Position Embedding to the query and key tensors.
267
+
268
+ Args:
269
+ q (`torch.Tensor`): The query tensor.
270
+ k (`torch.Tensor`): The key tensor.
271
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
272
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
273
+ position_ids (`torch.Tensor`, *optional*):
274
+ Deprecated and unused.
275
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
276
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
277
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
278
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
279
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
280
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
281
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
282
+ Returns:
283
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
284
+ """
285
+ cos = cos.unsqueeze(unsqueeze_dim)
286
+ sin = sin.unsqueeze(unsqueeze_dim)
287
+ q_embed = (q * cos) + (rotate_half(q) * sin)
288
+ k_embed = (k * cos) + (rotate_half(k) * sin)
289
+ return q_embed, k_embed
290
+
291
+
292
+ def bias_dropout_add(x: Tensor, bias: Tensor, residual: Optional[Tensor], prob: float, training: bool) -> Tensor:
293
+ """add bias to x, apply dropout and residual connection
294
+
295
+ Args:
296
+ x (Tensor): main path of output
297
+ bias (Tensor): None or attn_bias of the last attention layer
298
+ residual (Optional[Tensor]): residual value
299
+ prob (float): dropout probability
300
+ training (bool): whether in training mode or not
301
+
302
+ Returns:
303
+ Tensor: dropout(x + bias) + residual
304
+ """
305
+ if bias is not None:
306
+ x = x + bias
307
+ out = torch.nn.functional.dropout(x, p=prob, training=training)
308
+ if residual is not None:
309
+ out = residual + out
310
+ return out
311
+
312
+
313
+ class GPTNeoXJapaneseMLP(nn.Module):
314
+ def __init__(self, config):
315
+ super().__init__()
316
+ intermediate_size = int(config.hidden_size * config.intermediate_multiple_size)
317
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, intermediate_size, bias=False)
318
+ # Project back to h.
319
+ self.dense_4h_to_h = nn.Linear(intermediate_size, config.hidden_size, bias=False)
320
+ self.act = ACT2FN[config.hidden_act]
321
+
322
+ def forward(self, hidden_states):
323
+ intermediate = self.dense_h_to_4h(hidden_states)
324
+ intermediate = self.act(intermediate)
325
+ output = self.dense_4h_to_h(intermediate)
326
+ return output
327
+
328
+
329
+ class GPTNeoXJapaneseLayer(nn.Module):
330
+ def __init__(self, config, layer_number):
331
+ super().__init__()
332
+ self.layer_number = layer_number
333
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
334
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
335
+ # activate bias only last layer
336
+ self.attention = GPTNeoXJapaneseAttention(
337
+ config=config, use_bias=layer_number == config.num_hidden_layers - 1, layer_idx=layer_number
338
+ )
339
+ self.mlp = GPTNeoXJapaneseMLP(config)
340
+ self.hidden_dropout = config.hidden_dropout
341
+
342
+ def forward(
343
+ self,
344
+ hidden_states: Optional[torch.FloatTensor],
345
+ attention_mask: Optional[torch.FloatTensor] = None,
346
+ position_ids: Optional[torch.LongTensor] = None,
347
+ head_mask: Optional[torch.FloatTensor] = None,
348
+ use_cache: Optional[bool] = False,
349
+ layer_past: Optional[Cache] = None,
350
+ output_attentions: Optional[bool] = False,
351
+ cache_position: Optional[torch.LongTensor] = None,
352
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
353
+ ):
354
+ residual = hidden_states
355
+ ln_out = self.input_layernorm(hidden_states)
356
+ attn_output, attn_weights, attn_bias = self.attention(
357
+ ln_out,
358
+ attention_mask=attention_mask,
359
+ layer_past=layer_past,
360
+ head_mask=head_mask,
361
+ use_cache=use_cache,
362
+ output_attentions=output_attentions,
363
+ position_ids=position_ids,
364
+ cache_position=cache_position,
365
+ position_embeddings=position_embeddings,
366
+ )
367
+
368
+ # attn_output = (atten_output + bias) + residual
369
+ attn_output = bias_dropout_add(
370
+ attn_output,
371
+ bias=attn_bias.expand_as(residual) if attn_bias is not None else attn_bias,
372
+ residual=residual,
373
+ prob=self.hidden_dropout,
374
+ training=self.training,
375
+ )
376
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
377
+
378
+ # attn_output = (mlp_output + mlp_bias) + atten_output
379
+ attn_output = bias_dropout_add(
380
+ mlp_output, bias=None, residual=attn_output, prob=self.hidden_dropout, training=self.training
381
+ )
382
+
383
+ return attn_output, attn_weights
384
+
385
+
386
+ @auto_docstring
387
+ class GPTNeoXJapaneseModel(GPTNeoXJapanesePreTrainedModel):
388
+ def __init__(self, config):
389
+ super().__init__(config)
390
+ self.config = config
391
+
392
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
393
+ self.layers = nn.ModuleList(
394
+ [GPTNeoXJapaneseLayer(config=config, layer_number=i) for i in range(config.num_hidden_layers)]
395
+ )
396
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
397
+ self.rotary_emb = GPTNeoXJapaneseRotaryEmbedding(config=config)
398
+
399
+ # Initialize weights and apply final processing
400
+ self.post_init()
401
+
402
+ def get_input_embeddings(self):
403
+ return self.embed_in
404
+
405
+ def set_input_embeddings(self, value):
406
+ self.embed_in = value
407
+
408
+ @auto_docstring
409
+ def forward(
410
+ self,
411
+ input_ids: Optional[torch.LongTensor] = None,
412
+ attention_mask: Optional[torch.FloatTensor] = None,
413
+ position_ids: Optional[torch.LongTensor] = None,
414
+ head_mask: Optional[torch.FloatTensor] = None,
415
+ inputs_embeds: Optional[torch.FloatTensor] = None,
416
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
417
+ use_cache: Optional[bool] = None,
418
+ output_attentions: Optional[bool] = None,
419
+ output_hidden_states: Optional[bool] = None,
420
+ return_dict: Optional[bool] = None,
421
+ cache_position: Optional[torch.LongTensor] = None,
422
+ ) -> Union[tuple, BaseModelOutputWithPast]:
423
+ r"""
424
+ Example:
425
+
426
+ ```python
427
+ >>> from transformers import AutoTokenizer, GPTNeoXJapaneseModel
428
+ >>> import torch
429
+
430
+ >>> tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
431
+ >>> model = GPTNeoXJapaneseModel.from_pretrained("abeja/gpt-neox-japanese-2.7b")
432
+
433
+ >>> inputs = tokenizer("日本語のGPT-neoxがHugging Faceで使えます😀", return_tensors="pt")
434
+ >>> outputs = model(**inputs)
435
+
436
+ >>> last_hidden_states = outputs.last_hidden_state
437
+ ```
438
+ """
439
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
440
+ output_hidden_states = (
441
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
442
+ )
443
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
444
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
445
+
446
+ if (input_ids is None) ^ (inputs_embeds is not None):
447
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
448
+
449
+ if inputs_embeds is None:
450
+ inputs_embeds = self.embed_in(input_ids)
451
+
452
+ if use_cache and past_key_values is None:
453
+ past_key_values = DynamicCache(config=self.config)
454
+
455
+ seq_length = inputs_embeds.shape[1]
456
+ if cache_position is None:
457
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
458
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + seq_length, device=inputs_embeds.device)
459
+
460
+ if position_ids is None:
461
+ position_ids = cache_position.unsqueeze(0)
462
+
463
+ causal_mask = self._update_causal_mask(
464
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
465
+ )
466
+
467
+ # Prepare head mask if needed
468
+ # 1.0 in head_mask indicate we keep the head
469
+ # attention_probs has shape bsz x n_heads x N x N
470
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
471
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
472
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
473
+ hidden_states = inputs_embeds
474
+
475
+ # create position embeddings to be shared across the decoder layers
476
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
477
+
478
+ all_attentions = () if output_attentions else None
479
+ all_hidden_states = () if output_hidden_states else None
480
+ for i, layer in enumerate(self.layers):
481
+ if output_hidden_states:
482
+ all_hidden_states = all_hidden_states + (hidden_states,)
483
+
484
+ outputs = layer(
485
+ hidden_states,
486
+ attention_mask=causal_mask,
487
+ position_ids=position_ids,
488
+ head_mask=head_mask[i],
489
+ layer_past=past_key_values,
490
+ use_cache=use_cache,
491
+ output_attentions=output_attentions,
492
+ cache_position=cache_position,
493
+ position_embeddings=position_embeddings,
494
+ )
495
+ hidden_states = outputs[0]
496
+ if output_attentions:
497
+ all_attentions = all_attentions + (outputs[1],)
498
+
499
+ hidden_states = self.final_layer_norm(hidden_states)
500
+ # Add last hidden state
501
+ if output_hidden_states:
502
+ all_hidden_states = all_hidden_states + (hidden_states,)
503
+
504
+ if not return_dict:
505
+ return tuple(
506
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_attentions] if v is not None
507
+ )
508
+
509
+ return BaseModelOutputWithPast(
510
+ last_hidden_state=hidden_states,
511
+ past_key_values=past_key_values,
512
+ hidden_states=all_hidden_states,
513
+ attentions=all_attentions,
514
+ )
515
+
516
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
517
+ def _update_causal_mask(
518
+ self,
519
+ attention_mask: Union[torch.Tensor, "BlockMask"],
520
+ input_tensor: torch.Tensor,
521
+ cache_position: torch.Tensor,
522
+ past_key_values: Cache,
523
+ output_attentions: bool = False,
524
+ ):
525
+ if self.config._attn_implementation == "flash_attention_2":
526
+ if attention_mask is not None and (attention_mask == 0.0).any():
527
+ return attention_mask
528
+ return None
529
+ if self.config._attn_implementation == "flex_attention":
530
+ if isinstance(attention_mask, torch.Tensor):
531
+ attention_mask = make_flex_block_causal_mask(attention_mask)
532
+ return attention_mask
533
+
534
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
535
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
536
+ # to infer the attention mask.
537
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
538
+ using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
539
+
540
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
541
+ if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
542
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
543
+ attention_mask,
544
+ inputs_embeds=input_tensor,
545
+ past_key_values_length=past_seen_tokens,
546
+ is_training=self.training,
547
+ ):
548
+ return None
549
+
550
+ dtype = input_tensor.dtype
551
+ sequence_length = input_tensor.shape[1]
552
+ if using_compilable_cache:
553
+ target_length = past_key_values.get_max_cache_shape()
554
+ else:
555
+ target_length = (
556
+ attention_mask.shape[-1]
557
+ if isinstance(attention_mask, torch.Tensor)
558
+ else past_seen_tokens + sequence_length + 1
559
+ )
560
+
561
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
562
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
563
+ attention_mask,
564
+ sequence_length=sequence_length,
565
+ target_length=target_length,
566
+ dtype=dtype,
567
+ cache_position=cache_position,
568
+ batch_size=input_tensor.shape[0],
569
+ )
570
+
571
+ if (
572
+ self.config._attn_implementation == "sdpa"
573
+ and attention_mask is not None
574
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
575
+ and not output_attentions
576
+ ):
577
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
578
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
579
+ # Details: https://github.com/pytorch/pytorch/issues/110213
580
+ min_dtype = torch.finfo(dtype).min
581
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
582
+
583
+ return causal_mask
584
+
585
+ @staticmethod
586
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
587
+ def _prepare_4d_causal_attention_mask_with_cache_position(
588
+ attention_mask: torch.Tensor,
589
+ sequence_length: int,
590
+ target_length: int,
591
+ dtype: torch.dtype,
592
+ cache_position: torch.Tensor,
593
+ batch_size: int,
594
+ **kwargs,
595
+ ):
596
+ """
597
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
598
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
599
+
600
+ Args:
601
+ attention_mask (`torch.Tensor`):
602
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
603
+ `(batch_size, 1, query_length, key_value_length)`.
604
+ sequence_length (`int`):
605
+ The sequence length being processed.
606
+ target_length (`int`):
607
+ The target length: when generating with static cache, the mask should be as long as the static cache,
608
+ to account for the 0 padding, the part of the cache that is not filled yet.
609
+ dtype (`torch.dtype`):
610
+ The dtype to use for the 4D attention mask.
611
+ cache_position (`torch.Tensor`):
612
+ Indices depicting the position of the input sequence tokens in the sequence.
613
+ batch_size (`torch.Tensor`):
614
+ Batch size.
615
+ """
616
+ if attention_mask is not None and attention_mask.dim() == 4:
617
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
618
+ causal_mask = attention_mask
619
+ else:
620
+ min_dtype = torch.finfo(dtype).min
621
+ causal_mask = torch.full(
622
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
623
+ )
624
+ if sequence_length != 1:
625
+ causal_mask = torch.triu(causal_mask, diagonal=1)
626
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
627
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
628
+ if attention_mask is not None:
629
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
630
+ mask_length = attention_mask.shape[-1]
631
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
632
+ causal_mask.device
633
+ )
634
+ padding_mask = padding_mask == 0
635
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
636
+ padding_mask, min_dtype
637
+ )
638
+
639
+ return causal_mask
640
+
641
+
642
+ @auto_docstring(
643
+ custom_intro="""
644
+ GPTNeoXJapanese Model with a `language modeling` head on top for Classifier Model fine-tuning.
645
+ """
646
+ )
647
+ class GPTNeoXJapaneseForCausalLM(GPTNeoXJapanesePreTrainedModel, GenerationMixin):
648
+ _tied_weights_keys = ["embed_out.weight"]
649
+
650
+ def __init__(self, config):
651
+ super().__init__(config)
652
+ self.config = config
653
+
654
+ self.gpt_neox_japanese = GPTNeoXJapaneseModel(config)
655
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
656
+
657
+ # Initialize weights and apply final processing
658
+ self.post_init()
659
+
660
+ def get_output_embeddings(self):
661
+ return self.embed_out
662
+
663
+ def set_output_embeddings(self, new_embeddings):
664
+ self.embed_out = new_embeddings
665
+
666
+ @auto_docstring
667
+ def forward(
668
+ self,
669
+ input_ids: Optional[torch.LongTensor] = None,
670
+ attention_mask: Optional[torch.FloatTensor] = None,
671
+ position_ids: Optional[torch.LongTensor] = None,
672
+ inputs_embeds: Optional[torch.FloatTensor] = None,
673
+ head_mask: Optional[torch.FloatTensor] = None,
674
+ past_key_values: Optional[Union[Cache, tuple[tuple[torch.FloatTensor]]]] = None,
675
+ labels: Optional[torch.LongTensor] = None,
676
+ use_cache: Optional[bool] = None,
677
+ output_attentions: Optional[bool] = None,
678
+ output_hidden_states: Optional[bool] = None,
679
+ return_dict: Optional[bool] = None,
680
+ cache_position: Optional[torch.LongTensor] = None,
681
+ **kwargs,
682
+ ) -> Union[tuple, CausalLMOutputWithPast]:
683
+ r"""
684
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
685
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
686
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
687
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
688
+
689
+ Example:
690
+
691
+ ```python
692
+ >>> from transformers import AutoTokenizer, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseConfig
693
+ >>> import torch
694
+
695
+ >>> tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
696
+ >>> config = GPTNeoXJapaneseConfig.from_pretrained("abeja/gpt-neox-japanese-2.7b")
697
+ >>> config.is_decoder = True
698
+ >>> model = GPTNeoXJapaneseForCausalLM.from_pretrained("abeja/gpt-neox-japanese-2.7b", config=config)
699
+
700
+ >>> inputs = tokenizer("日本語のGPT-neoxがHugging Faceで使えます😀", return_tensors="pt")
701
+ >>> outputs = model(**inputs)
702
+
703
+ >>> prediction_logits = outputs.logits
704
+ ```
705
+ """
706
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
707
+
708
+ outputs = self.gpt_neox_japanese(
709
+ input_ids,
710
+ attention_mask=attention_mask,
711
+ position_ids=position_ids,
712
+ head_mask=head_mask,
713
+ inputs_embeds=inputs_embeds,
714
+ past_key_values=past_key_values,
715
+ use_cache=use_cache,
716
+ output_attentions=output_attentions,
717
+ output_hidden_states=output_hidden_states,
718
+ return_dict=return_dict,
719
+ cache_position=cache_position,
720
+ )
721
+
722
+ hidden_states = outputs[0]
723
+ lm_logits = self.embed_out(hidden_states)
724
+
725
+ lm_loss = None
726
+ if labels is not None:
727
+ # move labels to correct device to enable model parallelism
728
+ labels = labels.to(lm_logits.device)
729
+
730
+ lm_loss = self.loss_function(
731
+ lm_logits,
732
+ labels,
733
+ vocab_size=self.config.vocab_size,
734
+ **kwargs,
735
+ )
736
+
737
+ if not return_dict:
738
+ output = (lm_logits,) + outputs[1:]
739
+ return ((lm_loss,) + output) if lm_loss is not None else output
740
+
741
+ return CausalLMOutputWithPast(
742
+ loss=lm_loss,
743
+ logits=lm_logits,
744
+ past_key_values=outputs.past_key_values,
745
+ hidden_states=outputs.hidden_states,
746
+ attentions=outputs.attentions,
747
+ )
748
+
749
+
750
+ __all__ = [
751
+ "GPTNeoXJapaneseForCausalLM",
752
+ "GPTNeoXJapaneseLayer",
753
+ "GPTNeoXJapaneseModel",
754
+ "GPTNeoXJapanesePreTrainedModel",
755
+ ]