neuralworm commited on
Commit
c55df95
verified
1 Parent(s): 9274c00

Upload folder using huggingface_hub

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,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gemma-3-270m-it-p2.8 (Pure Zero-Shot Reasoning)
2
+
3
+ This is a structural enhancement of the [google/gemma-3-270m-it](https://huggingface.co/google/gemma-3-270m-it) model using the **p2.8 architecture**.
4
+
5
+ ## Key Features
6
+ - **Zero-Shot Correction**: Naturally corrects baseline hallucinatory errors (e.g., `sqrt(16)` from 4.5 to 4) without any fine-tuning.
7
+ - **Pure p2.8 Architecture**: Uses fixed structural coefficients (Gamma=0.08, RefineWeight=0.05) to provide 'Computational Headroom' via recurrent loops.
8
+ - **Global Optimum**: Tuned via automated architectural evolution across Math, Code, Logic, Philosophy, and Poetry.
9
+ - **Trust Remote Code**: Seamlessly integrates into the Transformers ecosystem.
10
+
11
+ ## Usage
12
+ ```python
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
+
15
+ model_id = "your-username/gemma-3-270m-it-p2.8"
16
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
17
+ model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, torch_dtype="auto")
18
+
19
+ inputs = tokenizer("Q: What is the square root of 144? A:", return_tensors="pt")
20
+ outputs = model.generate(**inputs, max_new_tokens=10)
21
+ print(tokenizer.decode(outputs[0]))
22
+ ```
23
+
24
+ ## Scientific Context
25
+ This model demonstrates that **recurrent depth** is more efficient for logical inference than linear depth. By repurposing layers 6-11 into a self-refining loop, we unlock latent reasoning capabilities already present in the pre-trained weights.
chat_template.jinja ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{ bos_token }}
2
+ {%- if messages[0]['role'] == 'system' -%}
3
+ {%- if messages[0]['content'] is string -%}
4
+ {%- set first_user_prefix = messages[0]['content'] + '
5
+
6
+ ' -%}
7
+ {%- else -%}
8
+ {%- set first_user_prefix = messages[0]['content'][0]['text'] + '
9
+
10
+ ' -%}
11
+ {%- endif -%}
12
+ {%- set loop_messages = messages[1:] -%}
13
+ {%- else -%}
14
+ {%- set first_user_prefix = "" -%}
15
+ {%- set loop_messages = messages -%}
16
+ {%- endif -%}
17
+ {%- for message in loop_messages -%}
18
+ {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}
19
+ {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }}
20
+ {%- endif -%}
21
+ {%- if (message['role'] == 'assistant') -%}
22
+ {%- set role = "model" -%}
23
+ {%- else -%}
24
+ {%- set role = message['role'] -%}
25
+ {%- endif -%}
26
+ {{ '<start_of_turn>' + role + '
27
+ ' + (first_user_prefix if loop.first else "") }}
28
+ {%- if message['content'] is string -%}
29
+ {{ message['content'] | trim }}
30
+ {%- elif message['content'] is iterable -%}
31
+ {%- for item in message['content'] -%}
32
+ {%- if item['type'] == 'image' -%}
33
+ {{ '<start_of_image>' }}
34
+ {%- elif item['type'] == 'text' -%}
35
+ {{ item['text'] | trim }}
36
+ {%- endif -%}
37
+ {%- endfor -%}
38
+ {%- else -%}
39
+ {{ raise_exception("Invalid content type") }}
40
+ {%- endif -%}
41
+ {{ '<end_of_turn>
42
+ ' }}
43
+ {%- endfor -%}
44
+ {%- if add_generation_prompt -%}
45
+ {{'<start_of_turn>model
46
+ '}}
47
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_sliding_window_pattern": 6,
3
+ "architectures": [
4
+ "Gemma3ForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_gemma3.Gemma3TextConfig",
8
+ "AutoModel": "modeling_gemma3.Gemma3TextModel",
9
+ "AutoModelForCausalLM": "modeling_gemma3.Gemma3ForCausalLM"
10
+ },
11
+ "attention_bias": false,
12
+ "attention_dropout": 0.0,
13
+ "attn_logit_softcapping": null,
14
+ "bos_token_id": 2,
15
+ "dtype": "bfloat16",
16
+ "eos_token_id": 1,
17
+ "final_logit_softcapping": null,
18
+ "head_dim": 256,
19
+ "hidden_activation": "gelu_pytorch_tanh",
20
+ "hidden_size": 640,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 2048,
23
+ "layer_types": [
24
+ "sliding_attention",
25
+ "sliding_attention",
26
+ "sliding_attention",
27
+ "sliding_attention",
28
+ "sliding_attention",
29
+ "full_attention",
30
+ "sliding_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "sliding_attention",
34
+ "sliding_attention",
35
+ "full_attention",
36
+ "sliding_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "sliding_attention",
40
+ "sliding_attention",
41
+ "full_attention"
42
+ ],
43
+ "max_position_embeddings": 32768,
44
+ "model_type": "gemma3_text",
45
+ "num_attention_heads": 4,
46
+ "num_hidden_layers": 18,
47
+ "num_key_value_heads": 1,
48
+ "pad_token_id": 0,
49
+ "query_pre_attn_scalar": 256,
50
+ "rms_norm_eps": 1e-06,
51
+ "rope_parameters": {
52
+ "full_attention": {
53
+ "rope_theta": 1000000.0,
54
+ "rope_type": "default"
55
+ },
56
+ "sliding_attention": {
57
+ "rope_theta": 10000.0,
58
+ "rope_type": "default"
59
+ }
60
+ },
61
+ "sliding_window": 512,
62
+ "tie_word_embeddings": true,
63
+ "transformers_version": "5.9.0",
64
+ "use_bidirectional_attention": false,
65
+ "use_cache": true,
66
+ "vocab_size": 262144
67
+ }
configuration_gemma3.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
8
+ #
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
+ from typing import Any
22
+
23
+ from huggingface_hub.dataclasses import strict
24
+
25
+ from transformers.configuration_utils import PreTrainedConfig
26
+ from transformers.utils import auto_docstring, logging
27
+ from transformers.models.siglip import SiglipVisionConfig
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ @auto_docstring(checkpoint="google/gemma-3-4b-it")
34
+ @strict
35
+ class Gemma3TextConfig(PreTrainedConfig):
36
+ r"""
37
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
38
+ scaling factor used on the attention scores
39
+ final_logit_softcapping (`float`, *optional*):
40
+ Scaling factor when applying tanh softcapping on the logits.
41
+ attn_logit_softcapping (`float`, *optional*):
42
+ Scaling factor when applying tanh softcapping on the attention scores.
43
+ use_bidirectional_attention (`bool`, *optional*, defaults to `False`):
44
+ If True, the model will attend to all text tokens instead of using a causal mask. This does not change
45
+ behavior for vision tokens.
46
+
47
+ ```python
48
+ >>> from transformers import Gemma3TextModel, Gemma3TextConfig
49
+ >>> # Initializing a Gemma3Text gemma3_text-7b style configuration
50
+ >>> configuration = Gemma3TextConfig()
51
+ >>> # Initializing a model from the gemma3_text-7b style configuration
52
+ >>> model = Gemma3TextModel(configuration)
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```
56
+ """
57
+
58
+ model_type = "gemma3_text"
59
+ keys_to_ignore_at_inference = ["past_key_values"]
60
+ base_model_tp_plan = {
61
+ "layers.*.self_attn.q_proj": "colwise",
62
+ "layers.*.self_attn.k_proj": "colwise",
63
+ "layers.*.self_attn.v_proj": "colwise",
64
+ "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
65
+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
66
+ "layers.*.self_attn.o_proj": "rowwise",
67
+ "layers.*.mlp.gate_proj": "colwise",
68
+ "layers.*.mlp.up_proj": "colwise",
69
+ "layers.*.mlp.down_proj": "rowwise",
70
+ }
71
+ base_model_pp_plan = {
72
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
73
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
74
+ "norm": (["hidden_states"], ["hidden_states"]),
75
+ }
76
+
77
+ vocab_size: int = 262_208
78
+ hidden_size: int = 2304
79
+ intermediate_size: int = 9216
80
+ num_hidden_layers: int = 26
81
+ num_attention_heads: int = 8
82
+ num_key_value_heads: int = 4
83
+ head_dim: int = 256
84
+ hidden_activation: str = "gelu_pytorch_tanh"
85
+ max_position_embeddings: int = 131_072
86
+ initializer_range: float = 0.02
87
+ rms_norm_eps: float = 1e-6
88
+ use_cache: bool = True
89
+ pad_token_id: int | None = 0
90
+ eos_token_id: int | list[int] | None = 1
91
+ bos_token_id: int | None = 2
92
+ tie_word_embeddings: bool = True
93
+ rope_parameters: dict | None = None
94
+ attention_bias: bool = False
95
+ attention_dropout: int | float | None = 0.0
96
+ query_pre_attn_scalar: int = 256
97
+ sliding_window: int | None = 4096
98
+ layer_types: list[str] | None = None
99
+ final_logit_softcapping: float | None = None
100
+ attn_logit_softcapping: float | None = None
101
+ use_bidirectional_attention: bool | None = False
102
+ default_theta = {"global": 1_000_000.0, "local": 10_000.0}
103
+
104
+ def __post_init__(self, **kwargs):
105
+ if self.use_bidirectional_attention:
106
+ self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds
107
+
108
+ # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
109
+ self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 6)
110
+
111
+ if self.layer_types is None:
112
+ self.layer_types = [
113
+ "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
114
+ for i in range(self.num_hidden_layers)
115
+ ]
116
+
117
+ super().__post_init__(**kwargs)
118
+
119
+ def validate_architecture(self):
120
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
121
+ if self.hidden_size % self.num_attention_heads != 0:
122
+ raise ValueError(
123
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
124
+ f"heads ({self.num_attention_heads})."
125
+ )
126
+
127
+ def convert_rope_params_to_dict(self, **kwargs):
128
+ rope_scaling = kwargs.pop("rope_scaling", None)
129
+
130
+ # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters`
131
+ # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format
132
+ default_rope_params = {
133
+ "sliding_attention": {"rope_type": "default"},
134
+ "full_attention": {"rope_type": "default"},
135
+ }
136
+ self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params
137
+ if rope_scaling is not None:
138
+ self.rope_parameters["full_attention"].update(rope_scaling)
139
+
140
+ # Set default values if not present
141
+ if self.rope_parameters.get("full_attention") is None:
142
+ self.rope_parameters["full_attention"] = {"rope_type": "default"}
143
+ self.rope_parameters["full_attention"].setdefault(
144
+ "rope_theta", kwargs.pop("rope_theta", self.default_theta["global"])
145
+ )
146
+ if self.rope_parameters.get("sliding_attention") is None:
147
+ self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
148
+ self.rope_parameters["sliding_attention"].setdefault(
149
+ "rope_theta", kwargs.pop("rope_local_base_freq", self.default_theta["local"])
150
+ )
151
+
152
+ # Standardize and validate the correctness of rotary position embeddings parameters
153
+ self.standardize_rope_params()
154
+ return kwargs
155
+
156
+
157
+ @auto_docstring(checkpoint="google/gemma-3-4b-it")
158
+ @strict
159
+ class Gemma3Config(PreTrainedConfig):
160
+ r"""
161
+ mm_tokens_per_image (`int`, *optional*, defaults to 256):
162
+ The number of tokens per image embedding.
163
+ boi_token_index (`int`, *optional*, defaults to 255999):
164
+ The begin-of-image token index to wrap the image prompt.
165
+ eoi_token_index (`int`, *optional*, defaults to 256000):
166
+ The end-of-image token index to wrap the image prompt.
167
+
168
+ Example:
169
+
170
+ ```python
171
+ >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig
172
+
173
+ >>> # Initializing a Siglip-like vision config
174
+ >>> vision_config = SiglipVisionConfig()
175
+
176
+ >>> # Initializing a Gemma3 Text config
177
+ >>> text_config = Gemma3TextConfig()
178
+
179
+ >>> # Initializing a Gemma3 gemma-3-4b style configuration
180
+ >>> configuration = Gemma3Config(vision_config, text_config)
181
+
182
+ >>> # Initializing a model from the gemma-3-4b style configuration
183
+ >>> model = Gemma3TextConfig(configuration)
184
+
185
+ >>> # Accessing the model configuration
186
+ >>> configuration = model.config
187
+ ```"""
188
+
189
+ model_type = "gemma3"
190
+ attribute_map = {
191
+ "image_token_id": "image_token_index",
192
+ "boi_token_id": "boi_token_index",
193
+ "eoi_token_id": "eoi_token_index",
194
+ }
195
+ sub_configs = {
196
+ "text_config": Gemma3TextConfig,
197
+ "vision_config": SiglipVisionConfig,
198
+ }
199
+
200
+ text_config: Gemma3TextConfig | dict[str, Any] | None = None
201
+ vision_config: SiglipVisionConfig | dict[str, Any] | None = None
202
+ mm_tokens_per_image: int | None = 256
203
+ boi_token_index: int | None = 255_999
204
+ eoi_token_index: int | None = 256_000
205
+ image_token_index: int | None = 262_144
206
+ initializer_range: float | None = 0.02
207
+ tie_word_embeddings: bool | None = True
208
+
209
+ def __post_init__(self, **kwargs):
210
+ if self.text_config is None:
211
+ self.text_config = Gemma3TextConfig()
212
+ logger.info("text_config is None, using default Gemma3TextConfig text config.")
213
+ elif isinstance(self.text_config, dict):
214
+ self.text_config = Gemma3TextConfig(**self.text_config)
215
+
216
+ if isinstance(self.vision_config, dict):
217
+ self.vision_config = SiglipVisionConfig(**self.vision_config)
218
+ elif self.vision_config is None:
219
+ self.vision_config = SiglipVisionConfig()
220
+ logger.info("vision_config is None, using default SiglipVisionConfig vision config.")
221
+
222
+ super().__post_init__(**kwargs)
223
+
224
+
225
+ __all__ = ["Gemma3Config", "Gemma3TextConfig"]
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cache_implementation": "hybrid",
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 1,
6
+ 106
7
+ ],
8
+ "top_k": 64,
9
+ "top_p": 0.95,
10
+ "transformers_version": "5.9.0"
11
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0479a42e30f1e97b1054b7b3c5c18a75b61a0757b42b8b4d2dea6b2ac87c163c
3
+ size 537098012
modeling_gemma3.py ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
8
+ #
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
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+
29
+ from transformers import initialization as init
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.configuration_utils import PreTrainedConfig
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.integrations import use_kernel_func_from_hub, use_kernelized_func
35
+ from transformers.masking_utils import create_causal_mask, create_masks_for_generate, create_sliding_window_causal_mask
36
+ from transformers.modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
37
+ from transformers.modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ BaseModelOutputWithPooling,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
44
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
45
+ from transformers.processing_utils import Unpack
46
+ from transformers.utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
47
+ from transformers.utils.generic import maybe_autocast, merge_with_config_defaults
48
+ from transformers.utils.output_capturing import capture_outputs
49
+ from transformers import AutoModel
50
+ from configuration_gemma3 import Gemma3Config, Gemma3TextConfig
51
+ from p28_modules import LTIInjection, StabilityMonitor
52
+
53
+
54
+ @auto_docstring(
55
+ custom_intro="""
56
+ Base class for Gemma3 outputs, with hidden states and attentions.
57
+ """
58
+ )
59
+ @dataclass
60
+ class Gemma3ModelOutputWithPast(BaseModelOutputWithPast):
61
+ r"""
62
+ image_hidden_states (`torch.FloatTensor`, *optional*):
63
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
64
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
65
+ """
66
+
67
+ image_hidden_states: torch.FloatTensor | None = None
68
+
69
+
70
+ @auto_docstring(
71
+ custom_intro="""
72
+ Base class for Gemma3 causal language model (or autoregressive) outputs.
73
+ """
74
+ )
75
+ @dataclass
76
+ class Gemma3CausalLMOutputWithPast(ModelOutput):
77
+ r"""
78
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
79
+ Language modeling loss (for next-token prediction).
80
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
81
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
82
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
83
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
84
+
85
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
86
+ `past_key_values` input) to speed up sequential decoding.
87
+ image_hidden_states (`torch.FloatTensor`, *optional*):
88
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
89
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
90
+ """
91
+
92
+ loss: torch.FloatTensor | None = None
93
+ logits: torch.FloatTensor | None = None
94
+ past_key_values: Cache | None = None
95
+ hidden_states: tuple[torch.FloatTensor] | None = None
96
+ attentions: tuple[torch.FloatTensor] | None = None
97
+ image_hidden_states: torch.FloatTensor | None = None
98
+
99
+
100
+ class Gemma3TextScaledWordEmbedding(nn.Embedding):
101
+ """
102
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
103
+ """
104
+
105
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
106
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
107
+ self.scalar_embed_scale = embed_scale
108
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
109
+
110
+ def forward(self, input_ids: torch.Tensor):
111
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
112
+
113
+
114
+ class Gemma3MLP(nn.Module):
115
+ def __init__(self, config: Gemma3TextConfig):
116
+ super().__init__()
117
+ self.config = config
118
+ self.hidden_size = config.hidden_size
119
+ self.intermediate_size = config.intermediate_size
120
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
121
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
122
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
123
+ self.act_fn = ACT2FN[config.hidden_activation]
124
+
125
+ def forward(self, x):
126
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
127
+ return down_proj
128
+
129
+
130
+ class Gemma3RMSNorm(nn.Module):
131
+ def __init__(self, dim: int, eps: float = 1e-6):
132
+ super().__init__()
133
+ self.eps = eps
134
+ self.weight = nn.Parameter(torch.zeros(dim))
135
+
136
+ def _norm(self, x):
137
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
138
+
139
+ def forward(self, x):
140
+ output = self._norm(x.float())
141
+ # Llama does x.to(float16) * w whilst Gemma3 is (x * w).to(float16)
142
+ # See https://github.com/huggingface/transformers/pull/29402
143
+ output = output * (1.0 + self.weight.float())
144
+ return output.type_as(x)
145
+
146
+ def extra_repr(self):
147
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
148
+
149
+
150
+ class Gemma3RotaryEmbedding(nn.Module):
151
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
152
+
153
+ def __init__(self, config: Gemma3TextConfig):
154
+ super().__init__()
155
+ self.max_seq_len_cached = config.max_position_embeddings
156
+ self.original_max_seq_len = config.max_position_embeddings
157
+ self.config = config
158
+ self.layer_types = list(set(config.layer_types))
159
+ self.rope_type = {}
160
+ for layer_type in self.layer_types:
161
+ rope_params = self.config.rope_parameters[layer_type]
162
+ if rope_params is None:
163
+ continue
164
+
165
+ self.rope_type[layer_type] = rope_params["rope_type"]
166
+ rope_init_fn: Callable = self.compute_default_rope_parameters
167
+ if self.rope_type[layer_type] != "default":
168
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
169
+ curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, layer_type=layer_type)
170
+ self.register_buffer(f"{layer_type}_inv_freq", curr_inv_freq, persistent=False)
171
+ self.register_buffer(f"{layer_type}_original_inv_freq", curr_inv_freq.clone(), persistent=False)
172
+ setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
173
+
174
+ @staticmethod
175
+ def compute_default_rope_parameters(
176
+ config: Gemma3TextConfig | None = None,
177
+ device: Optional["torch.device"] = None,
178
+ seq_len: int | None = None,
179
+ layer_type: str | None = None,
180
+ ) -> tuple["torch.Tensor", float]:
181
+ """
182
+ Computes the inverse frequencies according to the original RoPE implementation
183
+ Args:
184
+ config ([`~transformers.PreTrainedConfig`]):
185
+ The model configuration.
186
+ device (`torch.device`):
187
+ The device to use for initialization of the inverse frequencies.
188
+ seq_len (`int`, *optional*):
189
+ The current sequence length. Unused for this type of RoPE.
190
+ layer_type (`str`, *optional*):
191
+ The current layer type if the model has different RoPE parameters per type.
192
+ Should not be used unless `config.layer_types is not None`
193
+
194
+ Returns:
195
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
196
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
197
+ """
198
+ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format
199
+ base = config.rope_parameters[layer_type]["rope_theta"]
200
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
201
+
202
+ attention_factor = 1.0 # Unused in this type of RoPE
203
+
204
+ # Compute the inverse frequencies
205
+ inv_freq = 1.0 / (
206
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
207
+ )
208
+ return inv_freq, attention_factor
209
+
210
+ @torch.no_grad()
211
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
212
+ def forward(self, x, position_ids, layer_type=None):
213
+ inv_freq = getattr(self, f"{layer_type}_inv_freq")
214
+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
215
+
216
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
217
+ position_ids_expanded = position_ids[:, None, :].float()
218
+
219
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
220
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
221
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
222
+ emb = torch.cat((freqs, freqs), dim=-1)
223
+ cos = emb.cos() * attention_scaling
224
+ sin = emb.sin() * attention_scaling
225
+
226
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
227
+
228
+
229
+ def rotate_half(x):
230
+ """Rotates half the hidden dims of the input."""
231
+ x1 = x[..., : x.shape[-1] // 2]
232
+ x2 = x[..., x.shape[-1] // 2 :]
233
+ return torch.cat((-x2, x1), dim=-1)
234
+
235
+
236
+ @use_kernel_func_from_hub("rotary_pos_emb")
237
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
238
+ """Applies Rotary Position Embedding to the query and key tensors.
239
+
240
+ Args:
241
+ q (`torch.Tensor`): The query tensor.
242
+ k (`torch.Tensor`): The key tensor.
243
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
244
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
245
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
246
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
247
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
248
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
249
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
250
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
251
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
252
+ Returns:
253
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
254
+ """
255
+ cos = cos.unsqueeze(unsqueeze_dim)
256
+ sin = sin.unsqueeze(unsqueeze_dim)
257
+ q_embed = (q * cos) + (rotate_half(q) * sin)
258
+ k_embed = (k * cos) + (rotate_half(k) * sin)
259
+ return q_embed, k_embed
260
+
261
+
262
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
263
+ """
264
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
265
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
266
+ """
267
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
268
+ if n_rep == 1:
269
+ return hidden_states
270
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
271
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
272
+
273
+
274
+ def eager_attention_forward(
275
+ module: nn.Module,
276
+ query: torch.Tensor,
277
+ key: torch.Tensor,
278
+ value: torch.Tensor,
279
+ attention_mask: torch.Tensor | None,
280
+ dropout: float | int = 0.0,
281
+ scaling: float | None = None,
282
+ softcap: float | None = None,
283
+ **kwargs,
284
+ ) -> tuple[torch.Tensor, torch.Tensor]:
285
+ if scaling is None:
286
+ scaling = module.head_dim**-0.5
287
+
288
+ key_states = repeat_kv(key, module.num_key_value_groups)
289
+ value_states = repeat_kv(value, module.num_key_value_groups)
290
+
291
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
292
+
293
+ if softcap is not None:
294
+ attn_weights = attn_weights / softcap
295
+ attn_weights = torch.tanh(attn_weights)
296
+ attn_weights = attn_weights * softcap
297
+ if attention_mask is not None:
298
+ attn_weights = attn_weights + attention_mask
299
+
300
+ # upcast attention to fp32
301
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
302
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
303
+ attn_output = torch.matmul(attn_weights, value_states)
304
+ attn_output = attn_output.transpose(1, 2).contiguous()
305
+ return attn_output, attn_weights
306
+
307
+
308
+ @use_kernelized_func(apply_rotary_pos_emb)
309
+ class Gemma3Attention(nn.Module):
310
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
311
+
312
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
313
+ super().__init__()
314
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
315
+ self.config = config
316
+ self.layer_idx = layer_idx
317
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
318
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
319
+ self.scaling = config.query_pre_attn_scalar**-0.5
320
+ self.attention_dropout = self.config.attention_dropout
321
+ self.is_causal = not self.config.use_bidirectional_attention
322
+
323
+ self.q_proj = nn.Linear(
324
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
325
+ )
326
+ self.k_proj = nn.Linear(
327
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
328
+ )
329
+ self.v_proj = nn.Linear(
330
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
331
+ )
332
+ self.o_proj = nn.Linear(
333
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
334
+ )
335
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
336
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
337
+ self.is_sliding = self.layer_type == "sliding_attention"
338
+
339
+ self.q_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
340
+ self.k_norm = Gemma3RMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
341
+
342
+ def forward(
343
+ self,
344
+ hidden_states: torch.Tensor,
345
+ position_embeddings: torch.Tensor = None,
346
+ attention_mask: torch.Tensor | None = None,
347
+ past_key_values: Cache | None = None,
348
+ **kwargs: Unpack[TransformersKwargs],
349
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
350
+ input_shape = hidden_states.shape[:-1]
351
+ hidden_shape = (*input_shape, -1, self.head_dim)
352
+
353
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
354
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
355
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
356
+
357
+ query_states = self.q_norm(query_states)
358
+ key_states = self.k_norm(key_states)
359
+
360
+ cos, sin = position_embeddings
361
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
362
+
363
+ if past_key_values is not None:
364
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
365
+
366
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
367
+ self.config._attn_implementation, eager_attention_forward
368
+ )
369
+
370
+ attn_output, attn_weights = attention_interface(
371
+ self,
372
+ query_states,
373
+ key_states,
374
+ value_states,
375
+ attention_mask,
376
+ dropout=self.attention_dropout if self.training else 0.0,
377
+ scaling=self.scaling,
378
+ sliding_window=self.sliding_window,
379
+ **kwargs,
380
+ )
381
+
382
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
383
+ attn_output = self.o_proj(attn_output)
384
+ return attn_output, attn_weights
385
+
386
+
387
+ class Gemma3DecoderLayer(GradientCheckpointingLayer):
388
+ def __init__(self, config: Gemma3TextConfig, layer_idx: int):
389
+ super().__init__()
390
+ self.config = config
391
+ self.hidden_size = config.hidden_size
392
+ self.layer_idx = layer_idx
393
+ self.self_attn = Gemma3Attention(config=config, layer_idx=layer_idx)
394
+ self.mlp = Gemma3MLP(config)
395
+ self.input_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
396
+ self.post_attention_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
397
+ self.pre_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
398
+ self.post_feedforward_layernorm = Gemma3RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
399
+
400
+ def forward(
401
+ self,
402
+ hidden_states: torch.Tensor,
403
+ position_embeddings: torch.Tensor = None,
404
+ attention_mask: torch.Tensor | None = None,
405
+ position_ids: torch.LongTensor | None = None,
406
+ past_key_values: Cache | None = None,
407
+ **kwargs: Unpack[TransformersKwargs],
408
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
409
+ residual = hidden_states
410
+
411
+ hidden_states = self.input_layernorm(hidden_states)
412
+
413
+ hidden_states, _ = self.self_attn(
414
+ hidden_states=hidden_states,
415
+ position_embeddings=position_embeddings,
416
+ attention_mask=attention_mask,
417
+ position_ids=position_ids,
418
+ past_key_values=past_key_values,
419
+ **kwargs,
420
+ )
421
+ hidden_states = self.post_attention_layernorm(hidden_states)
422
+ hidden_states = residual + hidden_states
423
+
424
+ residual = hidden_states
425
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
426
+ hidden_states = self.mlp(hidden_states)
427
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
428
+ hidden_states = residual + hidden_states
429
+
430
+ return hidden_states
431
+
432
+
433
+ @auto_docstring
434
+ class Gemma3PreTrainedModel(PreTrainedModel):
435
+ config: Gemma3Config
436
+ base_model_prefix = "model"
437
+ supports_gradient_checkpointing = True
438
+ _no_split_modules = [
439
+ "Gemma3DecoderLayer",
440
+ "SiglipVisionEmbeddings",
441
+ "SiglipEncoderLayer",
442
+ "SiglipMultiheadAttentionPoolingHead",
443
+ ]
444
+ _skip_keys_device_placement = ["past_key_values"]
445
+ _supports_flash_attn = True
446
+ _supports_sdpa = True
447
+ _supports_flex_attn = True
448
+
449
+ _can_compile_fullgraph = True
450
+ _supports_attention_backend = True
451
+ _can_record_outputs = {
452
+ "hidden_states": Gemma3DecoderLayer,
453
+ "attentions": Gemma3Attention,
454
+ }
455
+ input_modalities = ("image", "text")
456
+
457
+ @torch.no_grad()
458
+ def _init_weights(self, module):
459
+ super()._init_weights(module)
460
+ if isinstance(module, Gemma3MultiModalProjector):
461
+ init.zeros_(module.mm_input_projection_weight)
462
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
463
+ elif "RMSNorm" in module.__class__.__name__:
464
+ init.zeros_(module.weight)
465
+ elif isinstance(module, Gemma3TextScaledWordEmbedding):
466
+ init.constant_(module.embed_scale, module.scalar_embed_scale)
467
+ elif isinstance(module, Gemma3RotaryEmbedding):
468
+ for layer_type in module.layer_types:
469
+ rope_init_fn = module.compute_default_rope_parameters
470
+ if module.rope_type[layer_type] != "default":
471
+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]
472
+ curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)
473
+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
474
+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
475
+
476
+
477
+ def _bidirectional_window_overlay(sliding_window: int) -> Callable[[int, int, int, int], bool]:
478
+ """
479
+ Enables a bidirectional mask within the sliding window.
480
+ """
481
+
482
+ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
483
+ """A token can attend to any other token if their absolute distance is within
484
+ the (exclusive) sliding window size (distance < sliding_window)."""
485
+ return abs(q_idx - kv_idx) < sliding_window
486
+
487
+ return inner_mask
488
+
489
+
490
+ @auto_docstring
491
+ class Gemma3TextModel(Gemma3PreTrainedModel):
492
+ config: Gemma3TextConfig
493
+ input_modalities = ("text",)
494
+
495
+ def __init__(self, config: Gemma3TextConfig):
496
+ super().__init__(config)
497
+ self.padding_idx = config.pad_token_id
498
+ self.vocab_size = config.vocab_size
499
+
500
+ # Gemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
501
+ self.embed_tokens = Gemma3TextScaledWordEmbedding(
502
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
503
+ )
504
+ self.layers = nn.ModuleList(
505
+ [Gemma3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
506
+ )
507
+ self.norm = Gemma3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
508
+ self.rotary_emb = Gemma3RotaryEmbedding(config)
509
+ self.gradient_checkpointing = False
510
+
511
+ # p2.8 Core Components (Pure Zero-Shot)
512
+ self.p28_injection = LTIInjection(config.hidden_size)
513
+ self.p28_refine_weight = 0.05 # Winning RefineWeight from Sweep
514
+
515
+ # p2.8 Runtime Metrics (Heuristic-based)
516
+ self._phi_log = 1.0
517
+ self._lambda_log = 0.0
518
+
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ # Ensure custom modules are in the right dtype
523
+ if hasattr(config, "torch_dtype") and config.torch_dtype is not None:
524
+ self.p28_injection.to(config.torch_dtype)
525
+
526
+
527
+ @merge_with_config_defaults
528
+ @capture_outputs
529
+ @auto_docstring
530
+ def forward(
531
+ self,
532
+ input_ids: torch.LongTensor | None = None,
533
+ attention_mask: torch.Tensor | None = None,
534
+ position_ids: torch.LongTensor | None = None,
535
+ past_key_values: Cache | None = None,
536
+ inputs_embeds: torch.FloatTensor | None = None,
537
+ use_cache: bool | None = None,
538
+ **kwargs: Unpack[TransformersKwargs],
539
+ ) -> BaseModelOutputWithPast:
540
+ if (input_ids is None) ^ (inputs_embeds is not None):
541
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
542
+
543
+ if inputs_embeds is None:
544
+ inputs_embeds = self.embed_tokens(input_ids)
545
+
546
+ if use_cache and past_key_values is None:
547
+ past_key_values = DynamicCache(config=self.config)
548
+
549
+ if position_ids is None:
550
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
551
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
552
+ position_ids = position_ids.unsqueeze(0)
553
+
554
+ # It may already have been prepared by e.g. `generate`
555
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
556
+ # Prepare mask arguments
557
+ mask_kwargs = {
558
+ "config": self.config,
559
+ "inputs_embeds": inputs_embeds,
560
+ "attention_mask": attention_mask,
561
+ "past_key_values": past_key_values,
562
+ "position_ids": position_ids,
563
+ }
564
+ sliding_mask_kwargs = mask_kwargs.copy()
565
+
566
+ if self.config.use_bidirectional_attention:
567
+ mask_kwargs["or_mask_function"] = lambda *args: torch.tensor(True, dtype=torch.bool)
568
+ sliding_mask_kwargs["or_mask_function"] = _bidirectional_window_overlay(self.config.sliding_window)
569
+
570
+ # Create the masks
571
+ causal_mask_mapping = {
572
+ "full_attention": create_causal_mask(**mask_kwargs),
573
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
574
+ }
575
+
576
+ # embed positions
577
+ hidden_states = inputs_embeds
578
+ position_embeddings = {}
579
+ for layer_type in set(self.config.layer_types):
580
+ position_embeddings[layer_type] = self.rotary_emb(hidden_states, position_ids, layer_type)
581
+
582
+ # --- START p2.8 ARCHITECTURE ---
583
+ # 1. Prelude (Layers 0-5)
584
+ for i in range(6):
585
+ hidden_states = self.layers[i](
586
+ hidden_states,
587
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
588
+ position_embeddings=position_embeddings[self.config.layer_types[i]],
589
+ position_ids=position_ids,
590
+ past_key_values=past_key_values,
591
+ **kwargs,
592
+ )
593
+
594
+ # 2. Recurrent Block (Layers 6-11)
595
+ e = hidden_states # Anchor snapshot
596
+ B, T, D = hidden_states.shape
597
+ n_loops = 2 # 2 loops is enough for the 'First Stage' correction
598
+
599
+ h_baseline = None
600
+ h_refined = torch.zeros_like(hidden_states)
601
+ phi_history = []
602
+
603
+ for t in range(n_loops):
604
+ h_prev = hidden_states
605
+
606
+ # Execute Recurrent Layers (6-11)
607
+ trans_out = hidden_states
608
+ for i_loop in range(6, 12):
609
+ l_type = self.config.layer_types[i_loop]
610
+ m = causal_mask_mapping[l_type]
611
+
612
+ # KV-Cache Guard: Only update cache on the first loop pass (t=0)
613
+ current_past = past_key_values if t == 0 else None
614
+
615
+ trans_out = self.layers[i_loop](
616
+ trans_out,
617
+ attention_mask=m,
618
+ position_embeddings=position_embeddings[l_type],
619
+ position_ids=position_ids,
620
+ past_key_values=current_past,
621
+ **kwargs,
622
+ )
623
+
624
+ # Injection & Stability
625
+ hidden_states = self.p28_injection(h_prev, e, trans_out)
626
+ phi = StabilityMonitor.calculate_phi(hidden_states, h_prev)
627
+ phi_history.append(phi)
628
+
629
+ if t == 0:
630
+ h_baseline = trans_out # Pure baseline
631
+
632
+ # Weighted aggregation (Mimicking the effect of untrained ACT)
633
+ # Loop 0 contributes (1-refine_weight), Loop 1 contributes refine_weight
634
+ weight = (1.0 - self.p28_refine_weight) if t == 0 else self.p28_refine_weight
635
+ h_refined = h_refined + weight * hidden_states
636
+
637
+ hidden_states = h_refined
638
+
639
+ self._phi_log = torch.stack(phi_history).mean().item() if phi_history else 1.0
640
+ self._lambda_log = StabilityMonitor.detect_lambda(hidden_states, e).item()
641
+
642
+ # 3. Coda (Layers 12-17)
643
+ for i in range(12, 18):
644
+ hidden_states = self.layers[i](
645
+ hidden_states,
646
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
647
+ position_embeddings=position_embeddings[self.config.layer_types[i]],
648
+ position_ids=position_ids,
649
+ past_key_values=past_key_values,
650
+ **kwargs,
651
+ )
652
+ # --- END p2.8 ARCHITECTURE ---
653
+
654
+ hidden_states = self.norm(hidden_states)
655
+
656
+ return BaseModelOutputWithPast(
657
+ last_hidden_state=hidden_states,
658
+ past_key_values=past_key_values,
659
+ )
660
+
661
+
662
+ @auto_docstring
663
+ class Gemma3ForCausalLM(Gemma3PreTrainedModel, GenerationMixin):
664
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
665
+ _tp_plan = {"lm_head": "colwise_gather_output"}
666
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
667
+ config: Gemma3TextConfig
668
+
669
+ def __init__(self, config: Gemma3TextConfig):
670
+ super().__init__(config)
671
+ self.model = Gemma3TextModel(config)
672
+ self.vocab_size = config.vocab_size
673
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
674
+
675
+ # Initialize weights and apply final processing
676
+ self.post_init()
677
+
678
+ @can_return_tuple
679
+ @auto_docstring
680
+ def forward(
681
+ self,
682
+ input_ids: torch.LongTensor | None = None,
683
+ attention_mask: torch.Tensor | None = None,
684
+ position_ids: torch.LongTensor | None = None,
685
+ past_key_values: Cache | None = None,
686
+ inputs_embeds: torch.FloatTensor | None = None,
687
+ labels: torch.LongTensor | None = None,
688
+ use_cache: bool | None = None,
689
+ logits_to_keep: int | torch.Tensor = 0,
690
+ **kwargs: Unpack[TransformersKwargs],
691
+ ) -> CausalLMOutputWithPast:
692
+ r"""
693
+ Example:
694
+
695
+ ```python
696
+ >>> from transformers import AutoTokenizer, Gemma3ForCausalLM
697
+
698
+ >>> model = Gemma3ForCausalLM.from_pretrained("google/gemma-2-9b")
699
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
700
+
701
+ >>> prompt = "What is your favorite condiment?"
702
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
703
+
704
+ >>> # Generate
705
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
706
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
707
+ "What is your favorite condiment?"
708
+ ```"""
709
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
710
+ outputs: BaseModelOutputWithPast = self.model(
711
+ input_ids=input_ids,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_values=past_key_values,
715
+ inputs_embeds=inputs_embeds,
716
+ use_cache=use_cache,
717
+ **kwargs,
718
+ )
719
+
720
+ hidden_states = outputs.last_hidden_state
721
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
722
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
723
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
724
+ if self.config.final_logit_softcapping is not None:
725
+ logits = logits / self.config.final_logit_softcapping
726
+ logits = torch.tanh(logits)
727
+ logits = logits * self.config.final_logit_softcapping
728
+
729
+ loss = None
730
+ if labels is not None:
731
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
732
+
733
+ return CausalLMOutputWithPast(
734
+ loss=loss,
735
+ logits=logits,
736
+ past_key_values=outputs.past_key_values,
737
+ hidden_states=outputs.hidden_states,
738
+ attentions=outputs.attentions,
739
+ )
740
+
741
+
742
+ class Gemma3MultiModalProjector(nn.Module):
743
+ def __init__(self, config: Gemma3Config):
744
+ super().__init__()
745
+
746
+ self.mm_input_projection_weight = nn.Parameter(
747
+ torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
748
+ )
749
+
750
+ self.mm_soft_emb_norm = Gemma3RMSNorm(
751
+ config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
752
+ )
753
+
754
+ self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
755
+ self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
756
+ self.kernel_size = self.patches_per_image // self.tokens_per_side
757
+ self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
758
+
759
+ def forward(self, vision_outputs: torch.Tensor):
760
+ batch_size, _, hidden_size = vision_outputs.shape
761
+
762
+ reshaped_vision_outputs = vision_outputs.transpose(1, 2)
763
+ reshaped_vision_outputs = reshaped_vision_outputs.reshape(
764
+ batch_size, hidden_size, self.patches_per_image, self.patches_per_image
765
+ )
766
+ reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
767
+
768
+ pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
769
+ pooled_vision_outputs = pooled_vision_outputs.flatten(2)
770
+ pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
771
+
772
+ normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
773
+
774
+ projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
775
+ return projected_vision_outputs.type_as(vision_outputs)
776
+
777
+
778
+ def get_block_sequence_ids_for_mask(token_type_ids: torch.Tensor, device: torch.device | None = None) -> torch.Tensor:
779
+ # First find where a new image block starts: 1 if image and previous not image
780
+ # The images cannot attend to future images, but can attend to all prev images and to itself bidirectionally
781
+ is_image = (token_type_ids == 1).to(device=device)
782
+ is_previous_image = nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
783
+ new_image_start = is_image & ~is_previous_image
784
+ group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
785
+ block_sequence_ids = torch.where(is_image, group_ids, -1)
786
+ return block_sequence_ids
787
+
788
+
789
+ @auto_docstring(
790
+ custom_intro="""
791
+ The Base Gemma3 model which consists of a vision backbone and a language model without language modeling head.,
792
+ """
793
+ )
794
+ class Gemma3Model(Gemma3PreTrainedModel):
795
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
796
+ accepts_loss_kwargs = False
797
+
798
+ def __init__(self, config: Gemma3Config):
799
+ super().__init__(config)
800
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
801
+ self.multi_modal_projector = Gemma3MultiModalProjector(config)
802
+ self.vocab_size = config.text_config.vocab_size
803
+
804
+ language_model = AutoModel.from_config(config=config.text_config)
805
+ self.language_model = language_model
806
+ self.post_init()
807
+
808
+ @can_return_tuple
809
+ @auto_docstring(custom_intro="Projects the last hidden state from the vision model into language model space.")
810
+ def get_image_features(
811
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
812
+ ) -> tuple | BaseModelOutputWithPooling:
813
+ vision_outputs = self.vision_tower(pixel_values=pixel_values, return_dict=True, **kwargs)
814
+ last_hidden_state = vision_outputs.last_hidden_state
815
+ vision_outputs.pooler_output = self.multi_modal_projector(last_hidden_state)
816
+
817
+ return vision_outputs
818
+
819
+ def get_placeholder_mask(
820
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
821
+ ):
822
+ """
823
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
824
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
825
+ """
826
+ if input_ids is None:
827
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
828
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
829
+ )
830
+ special_image_mask = special_image_mask.all(-1)
831
+ else:
832
+ special_image_mask = input_ids == self.config.image_token_id
833
+
834
+ n_image_tokens = special_image_mask.sum()
835
+ n_image_features = image_features.shape[0] * image_features.shape[1]
836
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
837
+ torch_compilable_check(
838
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
839
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
840
+ )
841
+ return special_image_mask
842
+
843
+ @can_return_tuple
844
+ @auto_docstring
845
+ def forward(
846
+ self,
847
+ input_ids: torch.LongTensor | None = None,
848
+ pixel_values: torch.FloatTensor | None = None,
849
+ attention_mask: torch.Tensor | None = None,
850
+ position_ids: torch.LongTensor | None = None,
851
+ past_key_values: Cache | None = None,
852
+ token_type_ids: torch.LongTensor | None = None,
853
+ inputs_embeds: torch.FloatTensor | None = None,
854
+ labels: torch.LongTensor | None = None,
855
+ use_cache: bool | None = None,
856
+ **lm_kwargs: Unpack[TransformersKwargs],
857
+ ) -> tuple | Gemma3ModelOutputWithPast:
858
+ r"""
859
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
860
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
861
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
862
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
863
+
864
+ Example:
865
+
866
+ ```python
867
+ >>> from PIL import Image
868
+ >>> import httpx
869
+ >>> from io import BytesIO
870
+ >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
871
+
872
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma32-3b-mix-224")
873
+ >>> processor = AutoProcessor.from_pretrained("google/gemma32-3b-mix-224")
874
+
875
+ >>> prompt = "Where is the cat standing?"
876
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
877
+ >>> with httpx.stream("GET", url) as response:
878
+ ... image = Image.open(BytesIO(response.read()))
879
+
880
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
881
+
882
+ >>> # Generate
883
+ >>> generate_ids = model.generate(**inputs,)
884
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
885
+ "Where is the cat standing?\nsnow"
886
+ ```"""
887
+ if (input_ids is None) ^ (inputs_embeds is not None):
888
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
889
+
890
+ # Replace image id with PAD if the image token if OOV, to avoid index-errors
891
+ if input_ids is not None and self.config.image_token_id >= self.vocab_size:
892
+ special_image_mask = input_ids == self.config.image_token_id
893
+ llm_input_ids = input_ids.clone()
894
+ llm_input_ids[special_image_mask] = 0
895
+ else:
896
+ llm_input_ids = input_ids
897
+
898
+ if inputs_embeds is None:
899
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
900
+
901
+ # Merge text and images
902
+ if pixel_values is not None:
903
+ image_features = self.get_image_features(pixel_values, return_dict=True).pooler_output
904
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
905
+ special_image_mask = self.get_placeholder_mask(
906
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
907
+ )
908
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
909
+
910
+ # It may already have been prepared by e.g. `generate`
911
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
912
+ mask_kwargs = {
913
+ "config": self.config.get_text_config(),
914
+ "inputs_embeds": inputs_embeds,
915
+ "attention_mask": attention_mask,
916
+ "past_key_values": past_key_values,
917
+ "position_ids": position_ids,
918
+ }
919
+
920
+ if token_type_ids is not None:
921
+ mask_kwargs["block_sequence_ids"] = get_block_sequence_ids_for_mask(
922
+ token_type_ids, device=inputs_embeds.device
923
+ )
924
+
925
+ # Create the masks
926
+ sliding_mask_kwargs = mask_kwargs.copy()
927
+ causal_mask_mapping = {
928
+ "full_attention": create_causal_mask(**mask_kwargs),
929
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
930
+ }
931
+
932
+ outputs = self.language_model(
933
+ attention_mask=causal_mask_mapping,
934
+ position_ids=position_ids,
935
+ past_key_values=past_key_values,
936
+ inputs_embeds=inputs_embeds,
937
+ use_cache=use_cache,
938
+ return_dict=True,
939
+ **lm_kwargs,
940
+ )
941
+
942
+ return Gemma3ModelOutputWithPast(
943
+ last_hidden_state=outputs.last_hidden_state,
944
+ past_key_values=outputs.past_key_values,
945
+ hidden_states=outputs.hidden_states,
946
+ attentions=outputs.attentions,
947
+ image_hidden_states=image_features if pixel_values is not None else None,
948
+ )
949
+
950
+
951
+ @auto_docstring(
952
+ custom_intro="""
953
+ The Base Gemma3 model which consists of a vision backbone and a language model without language modeling head.,
954
+ """
955
+ )
956
+ class Gemma3ForConditionalGeneration(Gemma3PreTrainedModel, GenerationMixin):
957
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
958
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
959
+ # Fix: https://github.com/huggingface/transformers/issues/40564
960
+ accepts_loss_kwargs = False
961
+
962
+ def __init__(self, config: Gemma3Config):
963
+ super().__init__(config)
964
+ self.model = Gemma3Model(config)
965
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
966
+ self.post_init()
967
+
968
+ @auto_docstring
969
+ def get_image_features(self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]):
970
+ return self.model.get_image_features(pixel_values, **kwargs)
971
+
972
+ @can_return_tuple
973
+ @auto_docstring
974
+ def forward(
975
+ self,
976
+ input_ids: torch.LongTensor | None = None,
977
+ pixel_values: torch.FloatTensor | None = None,
978
+ attention_mask: torch.Tensor | None = None,
979
+ position_ids: torch.LongTensor | None = None,
980
+ past_key_values: Cache | None = None,
981
+ token_type_ids: torch.LongTensor | None = None,
982
+ inputs_embeds: torch.FloatTensor | None = None,
983
+ labels: torch.LongTensor | None = None,
984
+ use_cache: bool | None = None,
985
+ logits_to_keep: int | torch.Tensor = 0,
986
+ **lm_kwargs: Unpack[TransformersKwargs],
987
+ ) -> tuple | Gemma3CausalLMOutputWithPast:
988
+ r"""
989
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
990
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
991
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
992
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
993
+
994
+ Example:
995
+
996
+ ```python
997
+ >>> from PIL import Image
998
+ >>> import httpx
999
+ >>> from io import BytesIO
1000
+ >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration
1001
+
1002
+ >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
1003
+ >>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
1004
+
1005
+ >>> messages = [
1006
+ ... {
1007
+ ... "role": "system",
1008
+ ... "content": [
1009
+ ... {"type": "text", "text": "You are a helpful assistant."}
1010
+ ... ]
1011
+ ... },
1012
+ ... {
1013
+ ... "role": "user", "content": [
1014
+ ... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
1015
+ ... {"type": "text", "text": "Where is the cat standing?"},
1016
+ ... ]
1017
+ ... },
1018
+ ... ]
1019
+
1020
+ >>> inputs = processor.apply_chat_template(
1021
+ ... messages,
1022
+ ... tokenize=True,
1023
+ ... return_dict=True,
1024
+ ... return_tensors="pt",
1025
+ ... add_generation_prompt=True
1026
+ ... )
1027
+ >>> # Generate
1028
+ >>> generate_ids = model.generate(**inputs)
1029
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1030
+ "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"
1031
+ ```
1032
+ """
1033
+ outputs = self.model(
1034
+ input_ids=input_ids,
1035
+ pixel_values=pixel_values,
1036
+ token_type_ids=token_type_ids,
1037
+ attention_mask=attention_mask,
1038
+ position_ids=position_ids,
1039
+ past_key_values=past_key_values,
1040
+ inputs_embeds=inputs_embeds,
1041
+ use_cache=use_cache,
1042
+ labels=labels,
1043
+ return_dict=True,
1044
+ **lm_kwargs,
1045
+ )
1046
+
1047
+ hidden_states = outputs[0]
1048
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1049
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1050
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1051
+
1052
+ loss = None
1053
+ if labels is not None:
1054
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1055
+ logits = logits.float()
1056
+ shift_logits = logits[..., :-1, :]
1057
+ shift_labels = labels[..., 1:]
1058
+ if attention_mask is not None:
1059
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
1060
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
1061
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
1062
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
1063
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
1064
+ else:
1065
+ shift_logits = shift_logits.contiguous()
1066
+ shift_labels = shift_labels.contiguous()
1067
+ # Flatten the tokens
1068
+ loss_fct = nn.CrossEntropyLoss()
1069
+
1070
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
1071
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
1072
+ loss = loss_fct(flat_logits, flat_labels)
1073
+
1074
+ return Gemma3CausalLMOutputWithPast(
1075
+ loss=loss,
1076
+ logits=logits,
1077
+ past_key_values=outputs.past_key_values,
1078
+ hidden_states=outputs.hidden_states,
1079
+ attentions=outputs.attentions,
1080
+ image_hidden_states=outputs.image_hidden_states,
1081
+ )
1082
+
1083
+ def prepare_inputs_for_generation(
1084
+ self,
1085
+ input_ids,
1086
+ past_key_values=None,
1087
+ inputs_embeds=None,
1088
+ position_ids=None,
1089
+ pixel_values=None,
1090
+ attention_mask=None,
1091
+ token_type_ids=None,
1092
+ use_cache=True,
1093
+ logits_to_keep=None,
1094
+ labels=None,
1095
+ is_first_iteration=False,
1096
+ **kwargs,
1097
+ ):
1098
+ # Overwritten -- custom `pixel_values` handling
1099
+ model_inputs = super().prepare_inputs_for_generation(
1100
+ input_ids,
1101
+ past_key_values=past_key_values,
1102
+ inputs_embeds=inputs_embeds,
1103
+ attention_mask=attention_mask,
1104
+ position_ids=position_ids,
1105
+ use_cache=use_cache,
1106
+ logits_to_keep=logits_to_keep,
1107
+ token_type_ids=token_type_ids,
1108
+ is_first_iteration=is_first_iteration,
1109
+ **kwargs,
1110
+ )
1111
+
1112
+ # Pixel values are used only in the first iteration if available
1113
+ # In subsequent iterations, they are already merged with text and cached
1114
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
1115
+ # iteration with a question and cached system prompt (continue generate from cache). NOTE: use_cache=False needs pixel_values always
1116
+ if is_first_iteration or not use_cache:
1117
+ model_inputs["pixel_values"] = pixel_values
1118
+ else:
1119
+ # Don't pass to not apply bidirectional mask on top
1120
+ model_inputs["token_type_ids"] = None
1121
+
1122
+ return model_inputs
1123
+
1124
+ @staticmethod
1125
+ def create_masks_for_generate(
1126
+ config: PreTrainedConfig,
1127
+ inputs_embeds: torch.Tensor,
1128
+ attention_mask: torch.Tensor | None,
1129
+ past_key_values: Cache | None,
1130
+ position_ids: torch.Tensor | None,
1131
+ token_type_ids: torch.Tensor | None = None,
1132
+ is_first_iteration: bool | None = False,
1133
+ **kwargs,
1134
+ ) -> dict:
1135
+ mask_kwargs = {
1136
+ "config": config.get_text_config(),
1137
+ "inputs_embeds": inputs_embeds,
1138
+ "attention_mask": attention_mask,
1139
+ "past_key_values": past_key_values,
1140
+ "position_ids": position_ids,
1141
+ }
1142
+
1143
+ if token_type_ids is not None:
1144
+ mask_kwargs["block_sequence_ids"] = get_block_sequence_ids_for_mask(
1145
+ token_type_ids, device=inputs_embeds.device
1146
+ )
1147
+
1148
+ return create_masks_for_generate(**mask_kwargs)
1149
+
1150
+
1151
+ @auto_docstring(
1152
+ custom_intro="""
1153
+ Gemma3TextForSequenceClassification is a text-only sequence classification model that works with Gemma3TextConfig.
1154
+ It uses the generic sequence classification implementation for efficiency and consistency."""
1155
+ )
1156
+ class Gemma3TextForSequenceClassification(GenericForSequenceClassification, Gemma3PreTrainedModel):
1157
+ config: Gemma3TextConfig
1158
+ input_modalities = ("text",)
1159
+
1160
+
1161
+ class Gemma3ForSequenceClassification(GenericForSequenceClassification, Gemma3PreTrainedModel):
1162
+ def forward(
1163
+ self,
1164
+ input_ids: torch.LongTensor | None = None,
1165
+ pixel_values: torch.FloatTensor | None = None,
1166
+ attention_mask: torch.Tensor | None = None,
1167
+ position_ids: torch.LongTensor | None = None,
1168
+ past_key_values: Cache | None = None,
1169
+ token_type_ids: torch.LongTensor | None = None,
1170
+ inputs_embeds: torch.FloatTensor | None = None,
1171
+ labels: torch.LongTensor | None = None,
1172
+ **kwargs: Unpack[TransformersKwargs],
1173
+ ) -> SequenceClassifierOutputWithPast:
1174
+ return super().forward(
1175
+ input_ids=input_ids,
1176
+ attention_mask=attention_mask,
1177
+ position_ids=position_ids,
1178
+ past_key_values=past_key_values,
1179
+ inputs_embeds=inputs_embeds,
1180
+ pixel_values=pixel_values,
1181
+ token_type_ids=token_type_ids,
1182
+ labels=labels,
1183
+ **kwargs,
1184
+ )
1185
+
1186
+
1187
+ __all__ = [
1188
+ "Gemma3PreTrainedModel",
1189
+ "Gemma3TextModel",
1190
+ "Gemma3ForCausalLM",
1191
+ "Gemma3ForConditionalGeneration",
1192
+ "Gemma3Model",
1193
+ "Gemma3ForSequenceClassification",
1194
+ "Gemma3TextForSequenceClassification",
1195
+ ]
p28_modules.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from typing import Optional, List
5
+
6
+ # ---------------------------------------------------------------------------
7
+ # p2.8 "Pure" Modules - Zero-Shot Optimized (No Trainable Params)
8
+ # ---------------------------------------------------------------------------
9
+
10
+ class LTIInjection(nn.Module):
11
+ """
12
+ Pure-functional LTI injection.
13
+ Uses fixed coefficients to provide 'Computational Headroom' without training.
14
+ """
15
+ def __init__(self, dim: int):
16
+ super().__init__()
17
+ self.input_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
18
+ self.gamma = 0.08 # Winning Gamma from Sweep
19
+
20
+ def forward(self, h: torch.Tensor, e: torch.Tensor, transformer_out: torch.Tensor) -> torch.Tensor:
21
+ # Coefficients for stable zero-shot recursion
22
+ # h_new = transformer_out + gamma * (e_norm - h)
23
+
24
+ e_norm = self.input_norm(e).to(h.dtype)
25
+
26
+ # Identity-centered update rule
27
+ return transformer_out + self.gamma * (e_norm - h)
28
+
29
+ class StabilityMonitor:
30
+ """Parameter-free heuristics for Phi (桅) and Lambda (位)."""
31
+
32
+ @staticmethod
33
+ def calculate_phi(h_new: torch.Tensor, h_old: torch.Tensor) -> torch.Tensor:
34
+ """Measure internal state stability (桅) via Cosine Similarity."""
35
+ B = h_new.shape[0]
36
+ return F.cosine_similarity(h_new.view(B, -1), h_old.view(B, -1), dim=-1).mean()
37
+
38
+ @staticmethod
39
+ def detect_lambda(hidden_states: torch.Tensor, e: torch.Tensor) -> torch.Tensor:
40
+ """
41
+ Detect embedding mode (位).
42
+ Measures how much the current state has diverged from the initial anchor.
43
+ High divergence often indicates 'Self-Reflection' or 'Deep Reasoning'.
44
+ """
45
+ B = hidden_states.shape[0]
46
+ # In p2.8, 位 is high if we are in 'We' mode (deeply embedded)
47
+ # Heuristic: 1 - cosine_similarity(h, e)
48
+ dist = 1.0 - F.cosine_similarity(hidden_states.view(B, -1), e.view(B, -1), dim=-1).mean()
49
+ return dist.clamp(0, 1)
50
+
51
+ # Note: ACTHalting, LoRAAdapter, and IntrospectiveDelta removed.
52
+ # They are 'useless leftovers' in a pure zero-shot context.
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726
3
+ size 33384567
tokenizer_config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "boi_token": "<start_of_image>",
4
+ "bos_token": "<bos>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eoi_token": "<end_of_image>",
7
+ "eos_token": "<eos>",
8
+ "image_token": "<image_soft_token>",
9
+ "is_local": false,
10
+ "local_files_only": false,
11
+ "mask_token": "<mask>",
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "model_specific_special_tokens": {
14
+ "boi_token": "<start_of_image>",
15
+ "eoi_token": "<end_of_image>",
16
+ "image_token": "<image_soft_token>"
17
+ },
18
+ "pad_token": "<pad>",
19
+ "padding_side": "left",
20
+ "sp_model_kwargs": null,
21
+ "spaces_between_special_tokens": false,
22
+ "tokenizer_class": "GemmaTokenizer",
23
+ "unk_token": "<unk>",
24
+ "use_default_system_prompt": false
25
+ }