TheoDB commited on
Commit
788ac17
·
verified ·
1 Parent(s): 2ffa0e1

Upload BidirLM-1B-Base

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - transformers
4
+ - bidirectional
5
+ - multilingual
6
+ license: apache-2.0
7
+ base_model: google/gemma-3-1b-pt
8
+ language:
9
+ - multilingual
10
+ - af
11
+ - am
12
+ - ar
13
+ - az
14
+ - be
15
+ - bg
16
+ - bn
17
+ - bs
18
+ - ca
19
+ - ceb
20
+ - cs
21
+ - cy
22
+ - da
23
+ - de
24
+ - el
25
+ - en
26
+ - es
27
+ - et
28
+ - eu
29
+ - fa
30
+ - fi
31
+ - fr
32
+ - ga
33
+ - gl
34
+ - gu
35
+ - ha
36
+ - he
37
+ - hi
38
+ - hr
39
+ - ht
40
+ - hu
41
+ - hy
42
+ - id
43
+ - ig
44
+ - is
45
+ - it
46
+ - ja
47
+ - jv
48
+ - ka
49
+ - kk
50
+ - kn
51
+ - ko
52
+ - ky
53
+ - lt
54
+ - lv
55
+ - mg
56
+ - mk
57
+ - ml
58
+ - mr
59
+ - ms
60
+ - mt
61
+ - my
62
+ - nb
63
+ - ne
64
+ - nl
65
+ - nso
66
+ - ny
67
+ - pa
68
+ - pl
69
+ - ps
70
+ - pt
71
+ - ro
72
+ - ru
73
+ - sd
74
+ - si
75
+ - sk
76
+ - sl
77
+ - sn
78
+ - so
79
+ - sq
80
+ - sr
81
+ - su
82
+ - sv
83
+ - sw
84
+ - ta
85
+ - te
86
+ - th
87
+ - tl
88
+ - tr
89
+ - uk
90
+ - ur
91
+ - vi
92
+ - wo
93
+ - xh
94
+ - yo
95
+ - zh
96
+ - zu
97
+ ---
98
+
99
+ # BidirLM-1B-Base
100
+
101
+ BidirLM-1B-Base is the intermediate MNTP-adapted checkpoint of the BidirLM family. It is obtained by converting [Gemma3-1B](https://huggingface.co/google/gemma-3-1b-pt) from causal to bidirectional attention and training with Masked Next Token Prediction (MNTP) on 30B tokens from a multi-domain corpus (FineWeb-Edu, FineWeb2-HQ, FineMath, Stack V2), then merged 50/50 with the original Gemma3-1B weights.
102
+
103
+ For general embeddings and downstream fine-tuning, use [BidirLM/BidirLM-1B-Embedding](https://huggingface.co/BidirLM/BidirLM-1B-Embedding) which adds contrastive training on top of this checkpoint.
104
+
105
+ ## Usage
106
+
107
+ ```python
108
+ from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM
109
+
110
+ tokenizer = AutoTokenizer.from_pretrained("BidirLM/BidirLM-1B-Base", trust_remote_code=True)
111
+
112
+ # Base encoder
113
+ model = AutoModel.from_pretrained("BidirLM/BidirLM-1B-Base", trust_remote_code=True)
114
+
115
+ # Masked language model
116
+ mlm = AutoModelForMaskedLM.from_pretrained("BidirLM/BidirLM-1B-Base", trust_remote_code=True)
117
+ ```
118
+
119
+ ## Requirements
120
+
121
+ ```
122
+ transformers>=4.57.6,<5.0.0
123
+ ```
124
+
125
+ This model requires `trust_remote_code=True`.
126
+
127
+ ## Citation
128
+
129
+ ```bibtex
130
+ @misc{boizard2026bidirlmtextomnimodalbidirectional,
131
+ title={BidirLM: From Text to Omnimodal Bidirectional Encoders by Adapting and Composing Causal LLMs},
132
+ author={Nicolas Boizard and Théo Deschamps-Berger and Hippolyte Gisserot-Boukhlef and Céline Hudelot and Pierre Colombo},
133
+ year={2026},
134
+ eprint={2604.02045},
135
+ archivePrefix={arXiv},
136
+ primaryClass={cs.CL},
137
+ url={https://arxiv.org/abs/2604.02045},
138
+ }
139
+ ```
config.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_sliding_window_pattern": 6,
3
+ "architectures": [
4
+ "BidirLMForMaskedLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "attn_logit_softcapping": null,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_bidirlm.BidirLMTextConfig",
11
+ "AutoModel": "modeling_bidirlm.BidirLMTextModel",
12
+ "AutoModelForMaskedLM": "modeling_bidirlm.BidirLMForMaskedLM",
13
+ "AutoModelForPreTraining": "modeling_bidirlm.BidirLMPreTrainedModel",
14
+ "AutoModelForSequenceClassification": "modeling_bidirlm.BidirLMForSequenceClassification",
15
+ "AutoModelForTokenClassification": "modeling_bidirlm.BidirLMForTokenClassification"
16
+ },
17
+ "bos_token_id": 2,
18
+ "classifier_pooling": "late",
19
+ "dtype": "float32",
20
+ "eos_token_id": 1,
21
+ "final_logit_softcapping": null,
22
+ "head_dim": 256,
23
+ "hidden_activation": "gelu_pytorch_tanh",
24
+ "hidden_size": 1152,
25
+ "initializer_range": 0.02,
26
+ "intermediate_size": 6912,
27
+ "layer_types": [
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "sliding_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "sliding_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "sliding_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "sliding_attention",
49
+ "sliding_attention",
50
+ "sliding_attention",
51
+ "full_attention",
52
+ "sliding_attention",
53
+ "sliding_attention"
54
+ ],
55
+ "max_position_embeddings": 32768,
56
+ "model_type": "bidirlm",
57
+ "num_attention_heads": 4,
58
+ "num_hidden_layers": 26,
59
+ "num_key_value_heads": 1,
60
+ "pad_token_id": 0,
61
+ "query_pre_attn_scalar": 256,
62
+ "rms_norm_eps": 1e-06,
63
+ "rope_local_base_freq": 10000,
64
+ "rope_scaling": null,
65
+ "rope_theta": 1000000,
66
+ "sliding_window": 512,
67
+ "sliding_window_pattern": 6,
68
+ "transformers_version": "4.57.3",
69
+ "use_bidirectional_attention": true,
70
+ "use_cache": true,
71
+ "vocab_size": 262144
72
+ }
configuration_bidirlm.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import transformers
25
+ _v = transformers.__version__
26
+ if _v < "4.57.6" or _v >= "5.0.0":
27
+ raise ImportError(
28
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
29
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
30
+ )
31
+
32
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
33
+ from transformers.modeling_rope_utils import rope_config_validation
34
+ from transformers.utils import logging
35
+ from transformers.models.siglip import SiglipVisionConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ class BidirLMConfig(PretrainedConfig):
42
+ r"""
43
+ This is the configuration class to store the configuration of a [`BidirLMModel`]. It is used to instantiate an Gemma3Text
44
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
45
+ defaults will yield a similar configuration to that of the Gemma3Text-7B.
46
+ e.g. [google/gemma3_text-7b](https://huggingface.co/google/gemma3_text-7b)
47
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
48
+ documentation from [`PretrainedConfig`] for more information.
49
+ Args:
50
+ vocab_size (`int`, *optional*, defaults to 262208):
51
+ Vocabulary size of the Gemma3Text model. Defines the number of different tokens that can be represented by the
52
+ `inputs_ids` passed when calling [`BidirLMModel`]
53
+ hidden_size (`int`, *optional*, defaults to 2304):
54
+ Dimension of the hidden representations.
55
+ intermediate_size (`int`, *optional*, defaults to 9216):
56
+ Dimension of the MLP representations.
57
+ num_hidden_layers (`int`, *optional*, defaults to 26):
58
+ Number of hidden layers in the Transformer decoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer decoder.
61
+ num_key_value_heads (`int`, *optional*, defaults to 4):
62
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
63
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
64
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
65
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
66
+ by meanpooling all the original heads within that group. For more details, check out [this
67
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
68
+ `num_attention_heads`.
69
+ head_dim (`int`, *optional*, defaults to 256):
70
+ The attention head dimension.
71
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
72
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
73
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
74
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
75
+ The maximum sequence length that this model might ever be used with.
76
+ initializer_range (`float`, *optional*, defaults to 0.02):
77
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
78
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
79
+ The epsilon used by the rms normalization layers.
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
82
+ relevant if `config.is_decoder=True`.
83
+ pad_token_id (`int`, *optional*, defaults to 0):
84
+ Padding token id.
85
+ eos_token_id (`int`, *optional*, defaults to 1):
86
+ End of stream token id.
87
+ bos_token_id (`int`, *optional*, defaults to 2):
88
+ Beginning of stream token id.
89
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
90
+ Whether to tie weight embeddings
91
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
92
+ The base period of the RoPE embeddings.
93
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
94
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
95
+ attention_dropout (`float`, *optional*, defaults to 0.0):
96
+ The dropout ratio for the attention probabilities.
97
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
98
+ Scaling factor used on the attention scores
99
+ sliding_window (`int`, *optional*, defaults to 4096):
100
+ In Gemma3Text, every other layer uses sliding window attention. This is the size of the sliding window.
101
+ layer_types (`list`, *optional*):
102
+ Attention pattern for each layer.
103
+ final_logit_softcapping (`float`, *optional*):
104
+ Scaling factor when applying tanh softcapping on the logits.
105
+ attn_logit_softcapping (`float`, *optional*):
106
+ Scaling factor when applying tanh softcapping on the attention scores.
107
+ rope_scaling (`Dict`, *optional*):
108
+ Dictionary containing the scaling configuration for the RoPE embeddings used in global attention. NOTE: if you apply new rope type
109
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
110
+ accordingly.
111
+ Expected contents:
112
+ `rope_type` (`str`):
113
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
114
+ 'llama3'], with 'default' being the original RoPE implementation.
115
+ `factor` (`float`, *optional*):
116
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
117
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
118
+ original maximum pre-trained length.
119
+ `original_max_position_embeddings` (`int`, *optional*):
120
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
121
+ pretraining.
122
+ `attention_factor` (`float`, *optional*):
123
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
124
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
125
+ `factor` field to infer the suggested value.
126
+ `beta_fast` (`float`, *optional*):
127
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
128
+ ramp function. If unspecified, it defaults to 32.
129
+ `beta_slow` (`float`, *optional*):
130
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
131
+ ramp function. If unspecified, it defaults to 1.
132
+ `short_factor` (`list[float]`, *optional*):
133
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
134
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
135
+ size divided by the number of attention heads divided by 2
136
+ `long_factor` (`list[float]`, *optional*):
137
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
138
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
139
+ size divided by the number of attention heads divided by 2
140
+ `low_freq_factor` (`float`, *optional*):
141
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
142
+ `high_freq_factor` (`float`, *optional*):
143
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
144
+ rope_local_base_freq (float, *optional*, defaults to 10000.0):
145
+ The base period of the RoPE embeddings for local attention.
146
+ use_bidirectional_attention (`bool`, *optional*, defaults to `False`): If True, the model will attend to all
147
+ text tokens instead of using a causal mask. This does not change behavior for vision tokens.
148
+
149
+ ```python
150
+ >>> from transformers import BidirLMModel, BidirLMConfig
151
+ >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
152
+ >>> configuration = BidirLMConfig()
153
+ >>> # Initializing a model from the gemma3_text-7b style configuration
154
+ >>> model = BidirLMModel(configuration)
155
+ >>> # Accessing the model configuration
156
+ >>> configuration = model.config
157
+ ```
158
+ """
159
+
160
+ model_type = "bidirlm"
161
+ keys_to_ignore_at_inference = ["past_key_values"]
162
+ base_model_tp_plan = {
163
+ "layers.*.self_attn.q_proj": "colwise",
164
+ "layers.*.self_attn.k_proj": "colwise",
165
+ "layers.*.self_attn.v_proj": "colwise",
166
+ "layers.*.self_attn.o_proj": "rowwise",
167
+ "layers.*.mlp.gate_proj": "colwise",
168
+ "layers.*.mlp.up_proj": "colwise",
169
+ "layers.*.mlp.down_proj": "rowwise",
170
+ }
171
+ base_model_pp_plan = {
172
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
173
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
174
+ "norm": (["hidden_states"], ["hidden_states"]),
175
+ }
176
+
177
+ def __init__(
178
+ self,
179
+ vocab_size=262_208,
180
+ hidden_size=2304,
181
+ intermediate_size=9216,
182
+ num_hidden_layers=26,
183
+ num_attention_heads=8,
184
+ num_key_value_heads=4,
185
+ head_dim=256,
186
+ hidden_activation="gelu_pytorch_tanh",
187
+ max_position_embeddings=131_072,
188
+ initializer_range=0.02,
189
+ rms_norm_eps=1e-6,
190
+ use_cache=True,
191
+ pad_token_id=0,
192
+ eos_token_id=1,
193
+ bos_token_id=2,
194
+ tie_word_embeddings=True,
195
+ rope_theta=1_000_000.0,
196
+ attention_bias=False,
197
+ attention_dropout=0.0,
198
+ query_pre_attn_scalar=256,
199
+ sliding_window=4096,
200
+ layer_types=None,
201
+ final_logit_softcapping=None,
202
+ attn_logit_softcapping=None,
203
+ rope_scaling=None,
204
+ rope_local_base_freq=10_000.0,
205
+ use_bidirectional_attention=True,
206
+ classifier_pooling="late",
207
+ **kwargs,
208
+ ):
209
+ super().__init__(
210
+ pad_token_id=pad_token_id,
211
+ bos_token_id=bos_token_id,
212
+ eos_token_id=eos_token_id,
213
+ tie_word_embeddings=tie_word_embeddings,
214
+ **kwargs,
215
+ )
216
+ self.vocab_size = vocab_size
217
+ self.max_position_embeddings = max_position_embeddings
218
+ self.hidden_size = hidden_size
219
+ self.intermediate_size = intermediate_size
220
+ self.num_hidden_layers = num_hidden_layers
221
+ self.num_attention_heads = num_attention_heads
222
+ self.head_dim = head_dim
223
+ self.num_key_value_heads = num_key_value_heads
224
+ self.initializer_range = initializer_range
225
+ self.rms_norm_eps = rms_norm_eps
226
+ self.use_cache = use_cache
227
+ self.rope_theta = rope_theta
228
+ self.attention_bias = attention_bias
229
+ self.attention_dropout = attention_dropout
230
+ self.hidden_activation = hidden_activation
231
+ self.query_pre_attn_scalar = query_pre_attn_scalar
232
+ self.sliding_window = sliding_window
233
+ self.final_logit_softcapping = final_logit_softcapping
234
+ self.attn_logit_softcapping = attn_logit_softcapping
235
+ self.layer_types = layer_types
236
+ self.use_bidirectional_attention = use_bidirectional_attention
237
+ self.classifier_pooling = classifier_pooling
238
+ if use_bidirectional_attention:
239
+ self.sliding_window = self.sliding_window // 2
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[BidirLMConfig, 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, BidirLMConfig
288
+
289
+ >>> # Initializing a Siglip-like vision config
290
+ >>> vision_config = SiglipVisionConfig()
291
+
292
+ >>> # Initializing a Gemma3 Text config
293
+ >>> text_config = BidirLMConfig()
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 = BidirLMConfig(configuration)
300
+
301
+ >>> # Accessing the model configuration
302
+ >>> configuration = model.config
303
+ ```"""
304
+
305
+ model_type = "bidirlm"
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": BidirLMConfig,
313
+ "vision_config": SiglipVisionConfig,
314
+ }
315
+
316
+ def __init__(
317
+ self,
318
+ text_config: Optional[Union[BidirLMConfig, 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 = BidirLMConfig()
329
+ logger.info("text_config is None, using default BidirLMConfig text config.")
330
+ elif isinstance(text_config, dict):
331
+ text_config = BidirLMConfig(**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
+ __all__ = ["Gemma3Config", "BidirLMConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0e6be7183b604eff83ce294b00f05108ff7ad33c904dc6624e5f6f65ddc78ec
3
+ size 1999811208
modeling_bidirlm.py ADDED
@@ -0,0 +1,1134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional
3
+
4
+ import transformers
5
+ _v = transformers.__version__
6
+ if _v < "4.57.6" or _v >= "5.0.0":
7
+ raise ImportError(
8
+ f"BidirLM requires transformers>=4.57.6,<5.0.0 (found {_v}). "
9
+ f"Install a compatible version: pip install 'transformers>=4.57.6,<5.0.0'"
10
+ )
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_layers import GradientCheckpointingLayer
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutput,
19
+ MaskedLMOutput,
20
+ SequenceClassifierOutput,
21
+ TokenClassifierOutput,
22
+ )
23
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
24
+ from transformers.modeling_utils import PreTrainedModel
25
+
26
+ from .configuration_bidirlm import Gemma3Config, BidirLMConfig
27
+
28
+ try:
29
+ import flash_attn
30
+
31
+ FLASH_ATTN_AVAILABLE = True
32
+ except ImportError:
33
+ FLASH_ATTN_AVAILABLE = False
34
+
35
+
36
+ def batch_input_to_cu_seqlens(x: torch.Tensor, attention_mask: torch.Tensor):
37
+ lengths = attention_mask.sum(dim=1)
38
+ max_seqlen = int(lengths.max().item())
39
+ cu_seqlens = torch.zeros(lengths.size(0) + 1, dtype=torch.int32, device=x.device)
40
+ cu_seqlens[1:] = torch.cumsum(lengths, dim=0)
41
+ x = x[attention_mask.bool()]
42
+ return x, cu_seqlens, max_seqlen
43
+
44
+
45
+ def cu_seqlens_to_batch_input(
46
+ x: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int
47
+ ):
48
+ B = cu_seqlens.size(0) - 1
49
+ D = x.size(1)
50
+ idx = torch.arange(max_seqlen, device=x.device).expand(B, max_seqlen)
51
+ lens = (cu_seqlens[1:] - cu_seqlens[:-1]).unsqueeze(1)
52
+ mask = idx < lens
53
+ base = cu_seqlens[:-1].unsqueeze(1)
54
+ gather_idx = (idx + base) * mask
55
+ out = torch.zeros(B, max_seqlen, D, device=x.device, dtype=x.dtype)
56
+ out[mask] = x[gather_idx[mask]]
57
+ return out
58
+
59
+
60
+ def cu_attention_weight_to_batch(hidden_states, cu_seqlens, max_seqlen):
61
+ H, T, _ = hidden_states.shape
62
+ device = hidden_states.device
63
+ cu_seqlens = cu_seqlens.to(device, dtype=torch.long)
64
+
65
+ B = cu_seqlens.numel() - 1
66
+ start = cu_seqlens[:-1]
67
+ end = cu_seqlens[1:]
68
+ L = end - start
69
+
70
+ p = torch.arange(max_seqlen, device=device)
71
+ valid = p.unsqueeze(0) < L.unsqueeze(1)
72
+
73
+ rel = p.unsqueeze(0)
74
+ abs_idx = start.unsqueeze(1) + rel
75
+ abs_idx = torch.where(valid, abs_idx, torch.zeros_like(abs_idx))
76
+
77
+ attn = hidden_states.unsqueeze(0).expand(B, -1, -1, -1)
78
+
79
+ row_index = abs_idx[:, None, :, None].expand(B, H, max_seqlen, T)
80
+ attn_rows = torch.gather(attn, dim=2, index=row_index)
81
+
82
+ col_index = abs_idx[:, None, None, :].expand(B, H, max_seqlen, max_seqlen)
83
+ attn_padded = torch.gather(attn_rows, dim=3, index=col_index)
84
+
85
+ mask = valid.to(attn_padded.dtype)
86
+ attn_padded = attn_padded * mask[:, None, :, None] * mask[:, None, None, :]
87
+
88
+ return attn_padded
89
+
90
+
91
+ class Gemma3Attention(nn.Module):
92
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
93
+
94
+ def __init__(self, config: BidirLMConfig, layer_idx: int):
95
+ super().__init__()
96
+ self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
97
+ self.config = config
98
+ self.layer_idx = layer_idx
99
+ self.head_dim = getattr(
100
+ config, "head_dim", config.hidden_size // config.num_attention_heads
101
+ )
102
+ self.num_key_value_groups = (
103
+ config.num_attention_heads // config.num_key_value_heads
104
+ )
105
+ self.scaling = config.query_pre_attn_scalar**-0.5
106
+ self.attention_dropout = self.config.attention_dropout
107
+
108
+ self.q_proj = nn.Linear(
109
+ config.hidden_size,
110
+ config.num_attention_heads * self.head_dim,
111
+ bias=config.attention_bias,
112
+ )
113
+ self.k_proj = nn.Linear(
114
+ config.hidden_size,
115
+ config.num_key_value_heads * self.head_dim,
116
+ bias=config.attention_bias,
117
+ )
118
+ self.v_proj = nn.Linear(
119
+ config.hidden_size,
120
+ config.num_key_value_heads * self.head_dim,
121
+ bias=config.attention_bias,
122
+ )
123
+ self.o_proj = nn.Linear(
124
+ config.num_attention_heads * self.head_dim,
125
+ config.hidden_size,
126
+ bias=config.attention_bias,
127
+ )
128
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
129
+ self.sliding_window = config.sliding_window if self.is_sliding else None
130
+
131
+ self.q_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
132
+ self.k_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
133
+
134
+ def forward(
135
+ self,
136
+ hidden_states,
137
+ position_embeddings,
138
+ attention_mask,
139
+ cu_seqlens: Optional[torch.Tensor],
140
+ max_seqlen: Optional[int],
141
+ window_size: Optional[tuple[int, int]] = None,
142
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
143
+ input_shape = hidden_states.shape[:-1]
144
+ hidden_shape = (*input_shape, -1, self.head_dim)
145
+
146
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(0, 1)
147
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(0, 1)
148
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(0, 1)
149
+
150
+ query_states = self.q_norm(query_states)
151
+ key_states = self.k_norm(key_states)
152
+
153
+ cos, sin = position_embeddings
154
+ query_states, key_states = apply_rotary_pos_emb(
155
+ query_states, key_states, cos, sin
156
+ )
157
+
158
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
159
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
160
+
161
+ if (
162
+ self.config._attn_implementation == "flash_attention_2"
163
+ and FLASH_ATTN_AVAILABLE
164
+ ):
165
+ attn_weights = None
166
+ attn_output = flash_attn.flash_attn_varlen_func(
167
+ query_states.transpose(0, 1),
168
+ key_states.transpose(0, 1),
169
+ value_states.transpose(0, 1),
170
+ cu_seqlens,
171
+ cu_seqlens,
172
+ max_seqlen_q=max_seqlen,
173
+ max_seqlen_k=max_seqlen,
174
+ dropout_p=self.attention_dropout if self.training else 0.0,
175
+ softmax_scale=self.scaling,
176
+ causal=not self.config.use_bidirectional_attention,
177
+ window_size=window_size,
178
+ )
179
+ else:
180
+ attn_output, attn_weights = sdpa_attention_forward(
181
+ query_states,
182
+ key_states,
183
+ value_states,
184
+ attention_mask=attention_mask,
185
+ scaling=self.scaling,
186
+ dropout=self.attention_dropout if self.training else 0.0,
187
+ softcap=self.attn_logit_softcapping,
188
+ )
189
+
190
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
191
+ attn_output = self.o_proj(attn_output)
192
+ return attn_output, attn_weights
193
+
194
+
195
+ def sdpa_attention_forward(
196
+ q,
197
+ k,
198
+ v,
199
+ attention_mask,
200
+ scaling,
201
+ dropout: float = 0.0,
202
+ softcap: Optional[float] = None,
203
+ ):
204
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) * scaling
205
+
206
+ if softcap is not None:
207
+ attn_weights = attn_weights / softcap
208
+ attn_weights = torch.tanh(attn_weights)
209
+ attn_weights = attn_weights * softcap
210
+
211
+ attn_weights = attn_weights + attention_mask
212
+
213
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
214
+ q.dtype
215
+ )
216
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout)
217
+
218
+ attn_output = torch.matmul(attn_weights, v)
219
+ attn_output = attn_output.transpose(0, 1).contiguous()
220
+
221
+ return attn_output, attn_weights
222
+
223
+
224
+ def create_packed_seqs_mask(
225
+ cu_seqlens: torch.Tensor,
226
+ causal: bool = True,
227
+ device: torch.device = torch.device("cpu"),
228
+ window_size: Optional[tuple[int, int]] = None,
229
+ ) -> torch.Tensor:
230
+ """
231
+ Builds a block-diagonal attention mask for packed sequences.
232
+ Returns shape [total_len, total_len] with 0.0 for attention and -inf for masked.
233
+ """
234
+ total_len = cu_seqlens[-1]
235
+ seq_lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).to(device)
236
+
237
+ seq_ids = torch.repeat_interleave(
238
+ torch.arange(len(seq_lengths), device=device),
239
+ seq_lengths
240
+ )
241
+
242
+ mask = seq_ids.unsqueeze(0) == seq_ids.unsqueeze(1)
243
+
244
+ if causal:
245
+ mask &= torch.tril(torch.ones(total_len, total_len, device=device, dtype=torch.bool))
246
+
247
+ if window_size is not None:
248
+ left, right = window_size
249
+ start_indices = torch.repeat_interleave(cu_seqlens[:-1].to(device), seq_lengths)
250
+ relative_pos = torch.arange(total_len, device=device) - start_indices
251
+
252
+ distance = relative_pos.unsqueeze(0) - relative_pos.unsqueeze(1)
253
+
254
+ if left >= 0:
255
+ mask &= (distance >= -left)
256
+ if right >= 0:
257
+ mask &= (distance <= right)
258
+
259
+ attn_mask = torch.full((total_len, total_len), float('-inf'), device=device)
260
+ attn_mask.masked_fill_(mask, 0.0)
261
+
262
+ return attn_mask
263
+
264
+
265
+ class Gemma3EncoderLayer(GradientCheckpointingLayer):
266
+ def __init__(self, config: BidirLMConfig, layer_idx: int):
267
+ super().__init__()
268
+ self.config = config
269
+ self.hidden_size = config.hidden_size
270
+ self.layer_idx = layer_idx
271
+ self.attention_type = config.layer_types[layer_idx]
272
+ self.self_attn = Gemma3Attention(config=config, layer_idx=layer_idx)
273
+ self.mlp = Gemma3MLP(config)
274
+ self.input_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
275
+ self.post_attention_layernorm = Gemma3RMSNorm(
276
+ self.hidden_size, eps=config.rms_norm_eps
277
+ )
278
+ self.pre_feedforward_layernorm = Gemma3RMSNorm(
279
+ self.hidden_size, eps=config.rms_norm_eps
280
+ )
281
+ self.post_feedforward_layernorm = Gemma3RMSNorm(
282
+ self.hidden_size, eps=config.rms_norm_eps
283
+ )
284
+
285
+ def forward(
286
+ self,
287
+ hidden_states: torch.Tensor,
288
+ position_embeddings_global: torch.Tensor,
289
+ position_embeddings_local: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ cu_seqlens: Optional[torch.Tensor] = None,
292
+ max_seqlen: Optional[int] = None,
293
+ window_size: Optional[tuple[int, int]] = None,
294
+ output_attentions: Optional[bool] = False,
295
+ ) -> tuple[
296
+ torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]
297
+ ]:
298
+ residual = hidden_states
299
+ hidden_states = self.input_layernorm(hidden_states)
300
+
301
+ if self.self_attn.is_sliding:
302
+ position_embeddings = position_embeddings_local
303
+ else:
304
+ position_embeddings = position_embeddings_global
305
+
306
+ hidden_states, self_attn_weights = self.self_attn(
307
+ hidden_states=hidden_states,
308
+ position_embeddings=position_embeddings,
309
+ attention_mask=attention_mask,
310
+ cu_seqlens=cu_seqlens,
311
+ max_seqlen=max_seqlen,
312
+ window_size=window_size,
313
+ )
314
+ hidden_states = self.post_attention_layernorm(hidden_states)
315
+ hidden_states = residual + hidden_states
316
+
317
+ residual = hidden_states
318
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
319
+ hidden_states = self.mlp(hidden_states)
320
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
321
+ hidden_states = residual + hidden_states
322
+
323
+ outputs = (hidden_states,)
324
+ if output_attentions:
325
+ outputs += (self_attn_weights,)
326
+
327
+ return outputs
328
+
329
+
330
+ class BidirLMPreTrainedModel(PreTrainedModel):
331
+ config: Gemma3Config
332
+ base_model_prefix = "model"
333
+ _supports_flash_attn = True
334
+
335
+ def _init_weights(self, module):
336
+ super()._init_weights(module)
337
+ # if isinstance(module, Gemma3MultiModalProjector):
338
+ # module.mm_input_projection_weight.data.zero_()
339
+ # # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
340
+ # elif "RMSNorm" in module.__class__.__name__:
341
+ # module.weight.data.zero_()
342
+ if "RMSNorm" in module.__class__.__name__:
343
+ module.weight.data.zero_()
344
+
345
+
346
+ class Gemma3TextScaledWordEmbedding(nn.Embedding):
347
+ """
348
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ num_embeddings: int,
354
+ embedding_dim: int,
355
+ padding_idx: int,
356
+ embed_scale: float = 1.0,
357
+ ):
358
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
359
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
360
+
361
+ def forward(self, input_ids: torch.Tensor):
362
+ return self.weight[input_ids, :] * self.embed_scale.to(self.weight.dtype)
363
+
364
+
365
+ class Gemma3MLP(nn.Module):
366
+ def __init__(self, config: BidirLMConfig):
367
+ super().__init__()
368
+ self.config = config
369
+ self.hidden_size = config.hidden_size
370
+ self.intermediate_size = config.intermediate_size
371
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
372
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
373
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
374
+ self.act_fn = ACT2FN[config.hidden_activation]
375
+
376
+ def forward(self, x):
377
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
378
+ return down_proj
379
+
380
+
381
+ class Gemma3RMSNorm(nn.Module):
382
+ def __init__(self, dim: int, eps: float = 1e-6):
383
+ super().__init__()
384
+ self.eps = eps
385
+ self.weight = nn.Parameter(torch.zeros(dim))
386
+
387
+ def _norm(self, x):
388
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
389
+
390
+ def forward(self, x):
391
+ output = self._norm(x.float())
392
+ # Llama does x.to(float16) * w whilst Gemma3 is (x * w).to(float16)
393
+ # See https://github.com/huggingface/transformers/pull/29402
394
+ output = output * (1.0 + self.weight.float())
395
+ return output.type_as(x)
396
+
397
+ def extra_repr(self):
398
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
399
+
400
+
401
+ class Gemma3RotaryEmbedding(nn.Module):
402
+ def __init__(self, config: BidirLMConfig, device=None):
403
+ super().__init__()
404
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
405
+ self.rope_type = config.rope_scaling.get(
406
+ "rope_type", config.rope_scaling.get("type")
407
+ )
408
+ else:
409
+ self.rope_type = "default"
410
+ self.max_seq_len_cached = config.max_position_embeddings
411
+ self.original_max_seq_len = config.max_position_embeddings
412
+
413
+ self.config = config
414
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
415
+
416
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
417
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
418
+ self.original_inv_freq = self.inv_freq
419
+
420
+ @torch.no_grad()
421
+ @dynamic_rope_update
422
+ def forward(self, x, position_ids):
423
+ inv_freq_expanded = self.inv_freq[:, None].float().to(x.device)
424
+ position_ids_expanded = position_ids[None, :].float()
425
+
426
+ device_type = (
427
+ x.device.type
428
+ if isinstance(x.device.type, str) and x.device.type != "mps"
429
+ else "cpu"
430
+ )
431
+ with torch.autocast(device_type=device_type, enabled=False):
432
+ freqs = (
433
+ inv_freq_expanded.float() @ position_ids_expanded.float()
434
+ ).transpose(0, 1)
435
+ emb = torch.cat((freqs, freqs), dim=-1)
436
+ cos = emb.cos() * self.attention_scaling
437
+ sin = emb.sin() * self.attention_scaling
438
+
439
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
440
+
441
+
442
+ def rotate_half(x):
443
+ """Rotates half the hidden dims of the input."""
444
+ x1 = x[..., : x.shape[-1] // 2]
445
+ x2 = x[..., x.shape[-1] // 2 :]
446
+ return torch.cat((-x2, x1), dim=-1)
447
+
448
+
449
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=0):
450
+ """Applies Rotary Position Embedding to the query and key tensors.
451
+
452
+ Args:
453
+ q (`torch.Tensor`): The query tensor.
454
+ k (`torch.Tensor`): The key tensor.
455
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
456
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
457
+ position_ids (`torch.Tensor`, *optional*):
458
+ Deprecated and unused.
459
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
460
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
461
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
462
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
463
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
464
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
465
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
466
+ Returns:
467
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
468
+ """
469
+ cos = cos.unsqueeze(unsqueeze_dim)
470
+ sin = sin.unsqueeze(unsqueeze_dim)
471
+ q_embed = (q * cos) + (rotate_half(q) * sin)
472
+ k_embed = (k * cos) + (rotate_half(k) * sin)
473
+ return q_embed, k_embed
474
+
475
+
476
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
477
+ """
478
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
479
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
480
+ """
481
+ num_key_value_heads, slen, head_dim = hidden_states.shape
482
+ if n_rep == 1:
483
+ return hidden_states
484
+ hidden_states = hidden_states[:, None, :, :].expand(
485
+ num_key_value_heads, n_rep, slen, head_dim
486
+ )
487
+ return hidden_states.reshape(num_key_value_heads * n_rep, slen, head_dim)
488
+
489
+
490
+ class BidirLMModel(BidirLMPreTrainedModel):
491
+ config: BidirLMConfig
492
+
493
+ def __init__(self, config: BidirLMConfig):
494
+ super().__init__(config)
495
+ self.padding_idx = config.pad_token_id
496
+ self.vocab_size = config.vocab_size
497
+
498
+ self.embed_tokens = Gemma3TextScaledWordEmbedding(
499
+ config.vocab_size,
500
+ config.hidden_size,
501
+ self.padding_idx,
502
+ embed_scale=self.config.hidden_size**0.5,
503
+ )
504
+ self.layers = nn.ModuleList(
505
+ [
506
+ Gemma3EncoderLayer(config, layer_idx)
507
+ for layer_idx in range(config.num_hidden_layers)
508
+ ]
509
+ )
510
+ self.norm = Gemma3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
511
+ self.rotary_emb = Gemma3RotaryEmbedding(config=config)
512
+ self.gradient_checkpointing = False
513
+
514
+ config = copy.deepcopy(config)
515
+ config.rope_theta = config.rope_local_base_freq
516
+ config.rope_scaling = {"rope_type": "default"}
517
+ self.rotary_emb_local = Gemma3RotaryEmbedding(config=config)
518
+
519
+ self.post_init()
520
+
521
+ def forward(
522
+ self,
523
+ input_ids: torch.LongTensor,
524
+ attention_mask: Optional[torch.Tensor] = None,
525
+ *,
526
+ cu_seqlens: Optional[torch.Tensor] = None,
527
+ max_seqlen: Optional[int] = None,
528
+ output_attentions: Optional[bool] = None,
529
+ output_hidden_states: Optional[bool] = None,
530
+ return_dict: Optional[bool] = None,
531
+ **kwargs,
532
+ ) -> tuple[torch.Tensor] | BaseModelOutput:
533
+ output_attentions = (
534
+ output_attentions
535
+ if output_attentions is not None
536
+ else self.config.output_attentions
537
+ )
538
+ output_hidden_states = (
539
+ output_hidden_states
540
+ if output_hidden_states is not None
541
+ else self.config.output_hidden_states
542
+ )
543
+ return_dict = (
544
+ return_dict if return_dict is not None else self.config.use_return_dict
545
+ )
546
+ all_hidden_states = () if output_hidden_states else None
547
+ all_self_attns = () if output_attentions else None
548
+
549
+ # For MNTP XP
550
+ batch_size, seq_len = input_ids.size()
551
+ new_input_ids = torch.empty((batch_size, seq_len + 1), dtype=input_ids.dtype, device=input_ids.device)
552
+ new_input_ids[:, 0] = 2
553
+ new_input_ids[:, 1:] = input_ids
554
+
555
+ if attention_mask is not None:
556
+ new_attention_mask = torch.empty((batch_size, seq_len + 1), dtype=attention_mask.dtype, device=attention_mask.device)
557
+ new_attention_mask[:, 0] = 1
558
+ new_attention_mask[:, 1:] = attention_mask
559
+ attention_mask = new_attention_mask
560
+ input_ids, cu_seqlens, max_seqlen = batch_input_to_cu_seqlens(new_input_ids, attention_mask)
561
+ else:
562
+ input_ids = new_input_ids
563
+
564
+ if cu_seqlens is None or max_seqlen is None:
565
+ cu_seqlens = torch.tensor(
566
+ [0, input_ids.size(0)], dtype=torch.int32, device=input_ids.device
567
+ )
568
+ max_seqlen = input_ids.size(0)
569
+
570
+ hidden_states = self.embed_tokens(input_ids)
571
+
572
+ position_ids = torch.arange(len(input_ids), device=hidden_states.device)
573
+ position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
574
+ position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
575
+
576
+ window_size = (
577
+ (
578
+ self.config.sliding_window,
579
+ self.config.sliding_window if self.config.use_bidirectional_attention else 0
580
+ )
581
+ if self.config.sliding_window is not None
582
+ else None
583
+ )
584
+ mask_mapping = {
585
+ "full_attention": create_packed_seqs_mask(cu_seqlens, causal=not self.config.use_bidirectional_attention, device=hidden_states.device),
586
+ "sliding_attention": create_packed_seqs_mask(cu_seqlens, causal=not self.config.use_bidirectional_attention, device=hidden_states.device, window_size=window_size)
587
+ }
588
+
589
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
590
+ if output_hidden_states:
591
+ if attention_mask is not None:
592
+ all_hidden_states += (
593
+ cu_seqlens_to_batch_input(
594
+ hidden_states, cu_seqlens, attention_mask.shape[-1]
595
+ )[0],
596
+ )
597
+ else:
598
+ all_hidden_states += (hidden_states,)
599
+
600
+ layer_outputs = encoder_layer(
601
+ hidden_states,
602
+ position_embeddings_global=position_embeddings_global,
603
+ position_embeddings_local=position_embeddings_local,
604
+ attention_mask=mask_mapping[encoder_layer.attention_type],
605
+ cu_seqlens=cu_seqlens,
606
+ max_seqlen=max_seqlen,
607
+ window_size=window_size if encoder_layer.attention_type == "sliding_attention" else (-1, -1),
608
+ )
609
+
610
+ hidden_states = layer_outputs[0]
611
+ if output_attentions:
612
+ if attention_mask is not None:
613
+ all_self_attns += (
614
+ cu_attention_weight_to_batch(
615
+ layer_outputs[1], cu_seqlens, attention_mask.shape[-1]
616
+ ),
617
+ )
618
+
619
+ else:
620
+ all_self_attns += (layer_outputs[1],)
621
+
622
+ hidden_states = self.norm(hidden_states)
623
+ if attention_mask is not None:
624
+ hidden_states = cu_seqlens_to_batch_input(
625
+ hidden_states, cu_seqlens, attention_mask.shape[-1]
626
+ )
627
+ if output_hidden_states:
628
+ all_hidden_states += (hidden_states,)
629
+
630
+ # For MNTP XP
631
+ output = BaseModelOutput(
632
+ last_hidden_state=hidden_states[:, :-1, :],
633
+ hidden_states=tuple(h[:, :-1, :] for h in all_hidden_states) if all_hidden_states is not None else None,
634
+ attentions=tuple(a[:, :, :-1, :-1] for a in all_self_attns) if all_self_attns is not None else None,
635
+ )
636
+ return output if return_dict else output.to_tuple()
637
+
638
+
639
+ class BidirLMForMaskedLM(BidirLMPreTrainedModel):
640
+ _tied_weights_keys = ["lm_head.weight"]
641
+ config: BidirLMConfig
642
+
643
+ def __init__(self, config):
644
+ super().__init__(config)
645
+ self.model = BidirLMModel(config)
646
+ self.vocab_size = config.vocab_size
647
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
648
+
649
+ self.post_init()
650
+
651
+ def forward(
652
+ self,
653
+ input_ids: torch.LongTensor,
654
+ *,
655
+ attention_mask: Optional[torch.Tensor] = None,
656
+ cu_seqlens: Optional[torch.Tensor] = None,
657
+ max_seqlen: Optional[int] = None,
658
+ labels: Optional[torch.LongTensor] = None,
659
+ output_attentions: Optional[bool] = None,
660
+ output_hidden_states: Optional[bool] = None,
661
+ return_dict: Optional[bool] = None,
662
+ **kwargs,
663
+ ) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
664
+ return_dict = (
665
+ return_dict if return_dict is not None else self.config.use_return_dict
666
+ )
667
+ encoder_output = self.model(
668
+ input_ids=input_ids,
669
+ attention_mask=attention_mask,
670
+ cu_seqlens=cu_seqlens,
671
+ max_seqlen=max_seqlen,
672
+ output_attentions=output_attentions,
673
+ output_hidden_states=output_hidden_states,
674
+ return_dict=return_dict,
675
+ )
676
+
677
+ logits = self.lm_head(encoder_output[0])
678
+ if self.config.final_logit_softcapping is not None:
679
+ logits = logits / self.config.final_logit_softcapping
680
+ logits = torch.tanh(logits)
681
+ logits = logits * self.config.final_logit_softcapping
682
+
683
+ loss = None
684
+ if labels is not None:
685
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size)
686
+
687
+ output = MaskedLMOutput(
688
+ loss=loss,
689
+ logits=logits,
690
+ hidden_states=encoder_output.hidden_states,
691
+ attentions=encoder_output.attentions,
692
+ )
693
+ return output if return_dict else output.to_tuple()
694
+
695
+
696
+ class BidirLMForSequenceClassification(BidirLMPreTrainedModel):
697
+ config: BidirLMConfig
698
+
699
+ def __init__(self, config):
700
+ super().__init__(config)
701
+ self.num_labels = config.num_labels
702
+ self.classifier_pooling = config.classifier_pooling
703
+
704
+ self.model = BidirLMModel(config)
705
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
706
+ self.activation = nn.GELU()
707
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
708
+ self.post_init()
709
+
710
+ def forward(
711
+ self,
712
+ input_ids: Optional[torch.LongTensor] = None,
713
+ attention_mask: Optional[torch.Tensor] = None,
714
+ labels: Optional[torch.LongTensor] = None,
715
+ output_attentions: Optional[bool] = None,
716
+ output_hidden_states: Optional[bool] = None,
717
+ return_dict: Optional[bool] = None,
718
+ **kwargs,
719
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
720
+ return_dict = (
721
+ return_dict if return_dict is not None else self.config.use_return_dict
722
+ )
723
+
724
+ encoder_output = self.model(
725
+ input_ids,
726
+ attention_mask=attention_mask,
727
+ output_attentions=output_attentions,
728
+ output_hidden_states=output_hidden_states,
729
+ return_dict=return_dict,
730
+ )
731
+ last_hidden_state = encoder_output[0]
732
+
733
+ if self.classifier_pooling in ["bos", "mean"]:
734
+ if self.classifier_pooling == "bos":
735
+ pooled_output = last_hidden_state[:, 0]
736
+
737
+ elif self.classifier_pooling == "mean":
738
+ if attention_mask is None:
739
+ pooled_output = last_hidden_state.mean(dim=1)
740
+ else:
741
+ pooled_output = (
742
+ last_hidden_state * attention_mask.unsqueeze(-1)
743
+ ).sum(dim=1)
744
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
745
+
746
+ pooled_output = self.dense(pooled_output)
747
+ pooled_output = self.activation(pooled_output)
748
+ logits = self.classifier(pooled_output)
749
+ elif self.classifier_pooling == "late":
750
+ x = self.dense(last_hidden_state)
751
+ x = self.activation(x)
752
+ logits = self.classifier(x)
753
+ if attention_mask is None:
754
+ logits = logits.mean(dim=1)
755
+ else:
756
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
757
+ logits /= attention_mask.sum(dim=1, keepdim=True)
758
+
759
+ loss = None
760
+ if labels is not None:
761
+ labels = labels.to(logits.device)
762
+ if self.config.problem_type is None:
763
+ if self.num_labels == 1:
764
+ self.config.problem_type = "regression"
765
+ elif self.num_labels > 1 and (
766
+ labels.dtype == torch.long or labels.dtype == torch.int
767
+ ):
768
+ self.config.problem_type = "single_label_classification"
769
+ else:
770
+ self.config.problem_type = "multi_label_classification"
771
+
772
+ if self.config.problem_type == "regression":
773
+ loss_fct = MSELoss()
774
+ if self.num_labels == 1:
775
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
776
+ else:
777
+ loss = loss_fct(logits, labels)
778
+ elif self.config.problem_type == "single_label_classification":
779
+ loss_fct = CrossEntropyLoss()
780
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
781
+ elif self.config.problem_type == "multi_label_classification":
782
+ loss_fct = BCEWithLogitsLoss()
783
+ loss = loss_fct(logits, labels)
784
+
785
+ output = SequenceClassifierOutput(
786
+ loss=loss,
787
+ logits=logits,
788
+ hidden_states=encoder_output.hidden_states,
789
+ attentions=encoder_output.attentions,
790
+ )
791
+ return output if return_dict else output.to_tuple()
792
+
793
+
794
+ class BidirLMForTokenClassification(BidirLMPreTrainedModel):
795
+ config: BidirLMConfig
796
+
797
+ def __init__(self, config):
798
+ super().__init__(config)
799
+ self.num_labels = config.num_labels
800
+
801
+ self.model = BidirLMModel(config)
802
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
803
+ self.post_init()
804
+
805
+ def forward(
806
+ self,
807
+ input_ids: Optional[torch.LongTensor] = None,
808
+ attention_mask: Optional[torch.Tensor] = None,
809
+ position_ids: Optional[torch.LongTensor] = None,
810
+ inputs_embeds: Optional[torch.FloatTensor] = None,
811
+ labels: Optional[torch.LongTensor] = None,
812
+ use_cache: Optional[bool] = None,
813
+ output_attentions: Optional[bool] = None,
814
+ output_hidden_states: Optional[bool] = None,
815
+ return_dict: Optional[bool] = None,
816
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
817
+ return_dict = (
818
+ return_dict if return_dict is not None else self.config.use_return_dict
819
+ )
820
+
821
+ outputs = self.model(
822
+ input_ids,
823
+ attention_mask=attention_mask,
824
+ position_ids=position_ids,
825
+ inputs_embeds=inputs_embeds,
826
+ use_cache=use_cache,
827
+ output_attentions=output_attentions,
828
+ output_hidden_states=output_hidden_states,
829
+ return_dict=return_dict,
830
+ )
831
+ sequence_output = outputs[0]
832
+ logits = self.classifier(sequence_output)
833
+
834
+ loss = None
835
+ if labels is not None:
836
+ loss_fct = CrossEntropyLoss()
837
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
838
+
839
+ if not return_dict:
840
+ output = (logits,) + outputs[2:]
841
+ return ((loss,) + output) if loss is not None else output
842
+
843
+ return TokenClassifierOutput(
844
+ loss=loss,
845
+ logits=logits,
846
+ hidden_states=outputs.hidden_states,
847
+ attentions=outputs.attentions,
848
+ )
849
+
850
+
851
+ # MultiModal
852
+ # class Gemma3Model(BidirLMPreTrainedModel):
853
+ # _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
854
+ # # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
855
+ # accepts_loss_kwargs = False
856
+
857
+ # def __init__(self, config: Gemma3Config):
858
+ # super().__init__(config)
859
+ # self.vision_tower = AutoModel.from_config(config=config.vision_config)
860
+ # self.multi_modal_projector = Gemma3MultiModalProjector(config)
861
+ # self.vocab_size = config.text_config.vocab_size
862
+
863
+ # language_model = AutoModel.from_config(config=config.text_config)
864
+ # self.language_model = language_model
865
+
866
+ # self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
867
+ # self.post_init()
868
+
869
+ # def get_input_embeddings(self):
870
+ # return self.language_model.get_input_embeddings()
871
+
872
+ # def set_input_embeddings(self, value):
873
+ # self.language_model.set_input_embeddings(value)
874
+
875
+ # def set_decoder(self, decoder):
876
+ # self.language_model = decoder
877
+
878
+ # def get_decoder(self):
879
+ # return self.language_model
880
+
881
+ # def get_image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
882
+ # """
883
+ # Projects the last hidden state from the vision model into language model space.
884
+
885
+ # Args:
886
+ # pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
887
+ # The tensors corresponding to the input images.
888
+ # Returns:
889
+ # image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
890
+ # """
891
+ # vision_outputs = self.vision_tower(pixel_values=pixel_values).last_hidden_state
892
+ # image_features = self.multi_modal_projector(vision_outputs)
893
+ # return image_features
894
+
895
+ # def get_placeholder_mask(
896
+ # self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
897
+ # ):
898
+ # """
899
+ # Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
900
+ # equal to the length of multimodal features. If the lengths are different, an error is raised.
901
+ # """
902
+ # if input_ids is None:
903
+ # special_image_mask = inputs_embeds == self.get_input_embeddings()(
904
+ # torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
905
+ # )
906
+ # special_image_mask = special_image_mask.all(-1)
907
+ # else:
908
+ # special_image_mask = input_ids == self.config.image_token_id
909
+
910
+ # n_image_tokens = special_image_mask.sum()
911
+ # special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
912
+ # n_image_features = image_features.shape[0] * image_features.shape[1]
913
+ # if inputs_embeds[special_image_mask].numel() != image_features.numel():
914
+ # raise ValueError(
915
+ # f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
916
+ # )
917
+ # return special_image_mask
918
+
919
+
920
+ # def forward(
921
+ # self,
922
+ # input_ids: Optional[torch.LongTensor] = None,
923
+ # pixel_values: Optional[torch.FloatTensor] = None,
924
+ # attention_mask: Optional[torch.Tensor] = None,
925
+ # position_ids: Optional[torch.LongTensor] = None,
926
+ # past_key_values: Optional[Cache] = None,
927
+ # token_type_ids: Optional[torch.LongTensor] = None,
928
+ # cache_position: Optional[torch.LongTensor] = None,
929
+ # inputs_embeds: Optional[torch.FloatTensor] = None,
930
+ # labels: Optional[torch.LongTensor] = None,
931
+ # use_cache: Optional[bool] = None,
932
+ # output_attentions: Optional[bool] = None,
933
+ # output_hidden_states: Optional[bool] = None,
934
+ # return_dict: Optional[bool] = None,
935
+ # **lm_kwargs,
936
+ # ) -> tuple:
937
+ # r"""
938
+ # labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
939
+ # Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
940
+ # config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
941
+ # (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
942
+
943
+ # Example:
944
+
945
+ # ```python
946
+ # >>> from PIL import Image
947
+ # >>> import requests
948
+ # >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
949
+
950
+ # >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma32-3b-mix-224")
951
+ # >>> processor = AutoProcessor.from_pretrained("google/gemma32-3b-mix-224")
952
+
953
+ # >>> prompt = "Where is the cat standing?"
954
+ # >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
955
+ # >>> image = Image.open(requests.get(url, stream=True).raw)
956
+
957
+ # >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
958
+
959
+ # >>> # Generate
960
+ # >>> generate_ids = model.generate(**inputs,)
961
+ # >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
962
+ # "Where is the cat standing?\nsnow"
963
+ # ```"""
964
+ # if (input_ids is None) ^ (inputs_embeds is not None):
965
+ # raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
966
+
967
+ # output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
968
+ # output_hidden_states = (
969
+ # output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
970
+ # )
971
+ # return_dict = return_dict if return_dict is not None else self.config.use_return_dict
972
+
973
+ # # Replace image id with PAD if the image token if OOV, to avoid index-errors
974
+ # if input_ids is not None and self.config.image_token_id >= self.vocab_size:
975
+ # special_image_mask = input_ids == self.config.image_token_id
976
+ # llm_input_ids = input_ids.clone()
977
+ # llm_input_ids[special_image_mask] = 0
978
+ # else:
979
+ # llm_input_ids = input_ids
980
+
981
+ # if inputs_embeds is None:
982
+ # inputs_embeds = self.get_input_embeddings()(llm_input_ids)
983
+
984
+ # if cache_position is None:
985
+ # past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
986
+ # cache_position = torch.arange(
987
+ # past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
988
+ # )
989
+
990
+ # # Merge text and images
991
+ # if pixel_values is not None:
992
+ # image_features = self.get_image_features(pixel_values)
993
+ # image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
994
+ # special_image_mask = self.get_placeholder_mask(
995
+ # input_ids, inputs_embeds=inputs_embeds, image_features=image_features
996
+ # )
997
+ # inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
998
+
999
+ # # It may already have been prepared by e.g. `generate`
1000
+ # if not isinstance(causal_mask_mapping := attention_mask, dict):
1001
+ # # Prepare mask arguments
1002
+ # mask_kwargs = {
1003
+ # "config": self.config.get_text_config(),
1004
+ # "input_embeds": inputs_embeds,
1005
+ # "attention_mask": attention_mask,
1006
+ # "cache_position": cache_position,
1007
+ # "past_key_values": past_key_values,
1008
+ # "position_ids": position_ids,
1009
+ # }
1010
+ # # NOTE: this `is_prefill` logic is not flawless, it fails when we're using a cache eagerly initialized
1011
+ # # (e.g. compiled prefill) AND `pixel_values` are not provided. Determining prefill in that case requires
1012
+ # # checking data values, which is not compile-compatible.
1013
+ # is_prefill = (
1014
+ # not use_cache
1015
+ # or past_key_values is None
1016
+ # or not past_key_values.is_initialized
1017
+ # or pixel_values is not None
1018
+ # )
1019
+ # if token_type_ids is not None and is_prefill:
1020
+ # # We need to pass an additional mask function to account for token type ids, and it needs to be an `or`
1021
+
1022
+ # # First find where a new image block starts: 1 if image and previous not image
1023
+ # # The images cannot attend to future images, but can attend to all prev images and to itself
1024
+ # # bidirectionally
1025
+ # is_image = (token_type_ids == 1).to(cache_position.device)
1026
+ # new_image_start = is_image & ~nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
1027
+ # image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
1028
+ # image_group_ids = torch.where(
1029
+ # is_image, image_group_ids, torch.full_like(token_type_ids, -1, device=is_image.device)
1030
+ # )
1031
+ # mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
1032
+ # token_type_ids.to(cache_position.device), image_group_ids, self.config.mm_tokens_per_image
1033
+ # )
1034
+
1035
+ # # Create the masks
1036
+ # causal_mask_mapping = {
1037
+ # "full_attention": create_causal_mask(**mask_kwargs),
1038
+ # "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
1039
+ # }
1040
+
1041
+ # outputs = self.language_model(
1042
+ # attention_mask=causal_mask_mapping,
1043
+ # position_ids=position_ids,
1044
+ # past_key_values=past_key_values,
1045
+ # inputs_embeds=inputs_embeds,
1046
+ # use_cache=use_cache,
1047
+ # output_attentions=output_attentions,
1048
+ # output_hidden_states=output_hidden_states,
1049
+ # return_dict=True,
1050
+ # cache_position=cache_position,
1051
+ # **lm_kwargs,
1052
+ # )
1053
+
1054
+ # return (
1055
+ # outputs,
1056
+ # image_features if pixel_values is not None else None,
1057
+ # )
1058
+
1059
+ # class Gemma3MultiModalProjector(nn.Module):
1060
+ # def __init__(self, config: Gemma3Config):
1061
+ # super().__init__()
1062
+
1063
+ # self.mm_input_projection_weight = nn.Parameter(
1064
+ # torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
1065
+ # )
1066
+
1067
+ # self.mm_soft_emb_norm = Gemma3RMSNorm(
1068
+ # config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
1069
+ # )
1070
+
1071
+ # self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
1072
+ # self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
1073
+ # self.kernel_size = self.patches_per_image // self.tokens_per_side
1074
+ # self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
1075
+
1076
+ # def forward(self, vision_outputs: torch.Tensor):
1077
+ # batch_size, _, seq_length = vision_outputs.shape
1078
+
1079
+ # reshaped_vision_outputs = vision_outputs.transpose(1, 2)
1080
+ # reshaped_vision_outputs = reshaped_vision_outputs.reshape(
1081
+ # batch_size, seq_length, self.patches_per_image, self.patches_per_image
1082
+ # )
1083
+ # reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
1084
+
1085
+ # pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
1086
+ # pooled_vision_outputs = pooled_vision_outputs.flatten(2)
1087
+ # pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
1088
+
1089
+ # normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
1090
+
1091
+ # projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
1092
+ # return projected_vision_outputs.type_as(vision_outputs)
1093
+
1094
+ # def token_type_ids_mask_function(
1095
+ # token_type_ids: Optional[torch.Tensor],
1096
+ # image_group_ids: Optional[torch.Tensor],
1097
+ # tokens_per_image: int,
1098
+ # ) -> Optional[Callable]:
1099
+ # """
1100
+ # This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths,
1101
+ # not start and end indices.
1102
+ # """
1103
+ # # Do not return an additional mask in this case
1104
+ # if token_type_ids is None:
1105
+ # return None
1106
+
1107
+ # def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
1108
+ # # If it's 1 for both query and key/value, we are in an image block
1109
+ # # NOTE: static cache shape goes beyond input seq length, while token_type_ids.shape[1] == input seq length
1110
+ # # Since vmap doesn't support `if statement` we workaround it with `torch.where`
1111
+ # safe_idx = torch.where(kv_idx < token_type_ids.shape[1], kv_idx, 0)
1112
+ # token_type_ids_at_kv_idx = token_type_ids[batch_idx, safe_idx]
1113
+ # token_type_ids_at_kv_idx = torch.where(kv_idx < token_type_ids.shape[1], token_type_ids_at_kv_idx, 0)
1114
+
1115
+ # image_group_ids_at_kv_idx = image_group_ids[batch_idx, safe_idx]
1116
+ # image_group_ids_at_kv_idx = torch.where(kv_idx < image_group_ids.shape[1], image_group_ids_at_kv_idx, -1)
1117
+
1118
+ # is_image_block = (token_type_ids[batch_idx, q_idx] == 1) & (token_type_ids_at_kv_idx == 1)
1119
+ # same_image_block = image_group_ids[batch_idx, q_idx] == image_group_ids_at_kv_idx
1120
+
1121
+ # # This is bidirectional attention whenever we are dealing with image tokens
1122
+ # return is_image_block & same_image_block
1123
+
1124
+ # return inner_mask
1125
+
1126
+
1127
+ __all__ = [
1128
+ "BidirLMPreTrainedModel",
1129
+ "BidirLMModel",
1130
+ "BidirLMForMaskedLM",
1131
+ "BidirLMForSequenceClassification",
1132
+ "BidirLMForTokenClassification",
1133
+ # "Gemma3Model",
1134
+ ]
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d4046bf0505a327dd5a0abbb427ecd4fc82f99c2ceaa170bc61ecde12809b0c
3
+ size 33384570
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c
3
+ size 4689074
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff