# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from src/transformers/models/gemma4_unified/modular_gemma4_unified.py. # Do NOT edit this file manually as any edits will be overwritten by the generation of # the file from the modular. If any change should be done, please apply the change to the # modular_gemma4_unified.py file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # Copyright 2026 the HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Literal from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig from ...utils import ( auto_docstring, logging, ) logger = logging.get_logger(__name__) @auto_docstring(checkpoint="google/gemma-4-12B-it") @strict class Gemma4UnifiedAudioConfig(PreTrainedConfig): r""" audio_embed_dim (`int`, defaults to 640): Dimension of audio features input to the multimodal embedder. Each audio soft token is a raw waveform frame of `audio_samples_per_token` samples, so `audio_embed_dim == audio_samples_per_token`. """ model_type = "gemma4_unified_audio" audio_embed_dim: int = 640 rms_norm_eps: float = 1e-6 initializer_range: float = 0.02 @property def hidden_size(self): """ Used by the MultimodalEmbedder to determine the input projection size. """ return self.audio_embed_dim @property def output_proj_dims(self): """ Output projection dimension (matches `hidden_size`). """ return self.audio_embed_dim @property def audio_samples_per_token(self): """ Number of raw audio samples per output soft token. At 16 kHz this equals 40ms of audio per token (16000 / 25 fps = 640). Same as `audio_embed_dim` """ return self.audio_embed_dim # Setters are setting the `audio_embed_dim` in each case as it's shared across @hidden_size.setter def hidden_size(self, value): self.audio_embed_dim = value @output_proj_dims.setter def output_proj_dims(self, value): self.audio_embed_dim = value @audio_samples_per_token.setter def audio_samples_per_token(self, value): self.audio_embed_dim = value @auto_docstring(checkpoint="google/gemma-4-12B-it") @strict class Gemma4UnifiedTextConfig(PreTrainedConfig): r""" use_bidirectional_attention (`str`, *optional*): Controls bidirectional attention behavior. When set to `"vision"`, vision tokens attend bidirectionally while text tokens use causal attention. When set to `"all"`, all tokens use bidirectional attention. attention_k_eq_v (`bool`, defaults to `False`): Whether keys and values share the same projection weights. When `True`, the key projection output is reused as the value projection. num_kv_shared_layers (`int`, defaults to 0): Number of consecutive decoder layers that share the same key-value projections. A value of 0 means no sharing (each layer has independent KV projections). use_double_wide_mlp (`bool`, defaults to `False`): Whether to use a double-width MLP with fused gate and up projections. """ model_type = "gemma4_unified_text" keys_to_ignore_at_inference = ["past_key_values"] base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce", "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_ep_plan = None # No MoE base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), } vocab_size: int = 262_144 hidden_size: int = 2304 intermediate_size: int = 9216 num_hidden_layers: int = 30 num_attention_heads: int = 8 num_key_value_heads: int = 4 head_dim: int = 256 hidden_activation: str = "gelu_pytorch_tanh" max_position_embeddings: int = 262_144 initializer_range: float = 0.02 rms_norm_eps: float = 1e-6 use_cache: bool = True pad_token_id: int | None = 0 eos_token_id: int | list[int] | None = 1 bos_token_id: int | None = 2 tie_word_embeddings: bool = True rope_parameters: dict | None = None attention_bias: bool = False attention_dropout: int | float | None = 0.0 sliding_window: int = 1024 layer_types: list[str] | None = None final_logit_softcapping: float | None = None use_bidirectional_attention: Literal["all", "vision"] | None = "vision" attention_k_eq_v: bool = False num_kv_shared_layers: int = 0 use_double_wide_mlp: bool = False def __post_init__(self, **kwargs): if self.use_bidirectional_attention == "all": self.is_causal = False self.sliding_window = (self.sliding_window // 2) + 1 # due to fa we set exclusive bounds if self.layer_types is None: sliding_window_pattern = 6 # by default 5:1 self.layer_types = [ "sliding_attention" if bool((i + 1) % sliding_window_pattern) else "full_attention" for i in range(self.num_hidden_layers) ] if self.layer_types and (last_layer_type := self.layer_types[-1]) != "full_attention": logger.warning( f"Last layer must use `full_attention`, but got `{last_layer_type}`. Forcing last layer to `full_attention`." ) self.layer_types[-1] = "full_attention" default_rope_params: dict[Literal["full_attention", "sliding_attention"] : dict[str, Any]] = { "sliding_attention": {"rope_type": "default", "rope_theta": 10_000.0}, "full_attention": {"rope_type": "proportional", "partial_rotary_factor": 0.25, "rope_theta": 1_000_000.0}, } if self.rope_parameters is None: self.rope_parameters = default_rope_params global_head_dim = kwargs.pop("global_head_dim", 512) num_global_key_value_heads = kwargs.pop("num_global_key_value_heads", None) if "per_layer_config" not in kwargs: layer_overrides: dict[str, Any] = {"head_dim": global_head_dim} # `attention_k_eq_v` gates the kv-head override for the models that declare it; # models that drop the attribute entirely are ungated, hence the `True` fallback. num_key_value_heads = num_global_key_value_heads if getattr(self, "attention_k_eq_v", True) else None if num_key_value_heads is not None: layer_overrides["num_key_value_heads"] = num_key_value_heads kwargs["per_layer_config"] = { layer_idx: layer_overrides for layer_idx, layer_type in enumerate(self.layer_types) if layer_type == "full_attention" } super().__post_init__(**kwargs) def to_dict(self) -> dict[str, Any]: output = super().to_dict() # Serialize the value `__post_init__` converted *from*, so that a reload converts once more # instead of halving the already-halved window. Configs that inherit this one without the # flag never convert, hence the `None` fallback. if getattr(self, "use_bidirectional_attention", None) == "all": output["sliding_window"] = (self.sliding_window - 1) * 2 return output def convert_rope_params_to_dict(self, **kwargs): # No need to handle BC for new models, because they have no old-format `rope_scaling` return kwargs @auto_docstring(checkpoint="google/gemma-4-12B-it") @strict class Gemma4UnifiedVisionConfig(PreTrainedConfig): r""" patch_size (`int`, defaults to 16): Size of the image patches in pixels. Images are first patchified at this resolution. pooling_kernel_size (`int`, defaults to 3): Kernel size for merging patches into model patches. A 3×3 merge produces model patches of size `patch_size * pooling_kernel_size = 48` pixels. mm_embed_dim (`int`, defaults to 3840): Hidden dimension for the patch embedding Dense projection (matches the text model `hidden_size`). mm_posemb_size (`int`, defaults to 1120): Size of the factorized 2D positional embedding table. The table has shape `(mm_posemb_size, 2, mm_embed_dim)` and is looked up per-axis. output_proj_dims (`int`, defaults to 3840): Output dimension of the multimodal embedder projection (maps to text hidden size). This is set by the composite config's text_config.hidden_size at runtime. """ model_type = "gemma4_unified_vision" patch_size: int = 16 pooling_kernel_size: int = 3 mm_embed_dim: int = 3840 mm_posemb_size: int = 1120 rms_norm_eps: float = 1e-6 output_proj_dims: int = 3840 initializer_range: float = 0.02 @property def model_patch_size(self): """ Size of the merged model patches in pixels. Each merged patch has `model_patch_size² * 3` raw pixel channels. """ return self.patch_size * self.pooling_kernel_size @model_patch_size.setter def model_patch_size(self, value): if value != self.patch_size * self.pooling_kernel_size: raise ValueError( f"`model_patch_size` needs to be equal to {self.patch_size = } * {self.pooling_kernel_size = }" ) @auto_docstring(checkpoint="google/gemma-4-12B-it") @strict class Gemma4UnifiedConfig(PreTrainedConfig): r""" boi_token_id (`int`, *optional*, defaults to 255999): The begin-of-image token index to wrap the image prompt. eoi_token_id (`int`, *optional*, defaults to 258882): The end-of-image token index to wrap the image prompt. boa_token_id (`int`, *optional*, defaults to 256000): The begin-of-audio token index to wrap the audio prompt. eoa_token_index (`int`, *optional*, defaults to 258883): The end-of-audio token index to wrap the audio prompt. Example: ```python >>> from transformers import ( >>> Gemma4UnifiedAudioConfig, >>> Gemma4UnifiedConfig, >>> Gemma4UnifiedForConditionalGeneration, >>> Gemma4UnifiedTextConfig, >>> Gemma4UnifiedVisionConfig, >>> ) >>> # Initializing a Gemma 4 Audio config. >>> audio_config = Gemma4UnifiedAudioConfig() >>> # Initializing a Gemma 4 Text config. >>> text_config = Gemma4UnifiedTextConfig() >>> # Initializing a Gemma 4 vision config. >>> vision_config = Gemma4UnifiedVisionConfig() >>> # Initializing a Gemma 4 config similar to google/gemma-4-e2b-it >>> configuration = Gemma4UnifiedConfig(text_config, vision_config, audio_config) >>> # Initializing a model from the google/gemma-4-e2b-it configuration >>> model = Gemma4UnifiedForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "gemma4_unified" sub_configs = { "text_config": Gemma4UnifiedTextConfig, "vision_config": Gemma4UnifiedVisionConfig, "audio_config": Gemma4UnifiedAudioConfig, } text_config: Gemma4UnifiedTextConfig | dict[str, Any] | None = None vision_config: Gemma4UnifiedVisionConfig | dict[str, Any] | None = None audio_config: Gemma4UnifiedAudioConfig | dict[str, Any] | None = None boi_token_id: int | None = 255_999 eoi_token_id: int | None = 258_882 image_token_id: int | None = 258_880 video_token_id: int | None = 258_884 boa_token_id: int | None = 256_000 eoa_token_index: int | None = 258_883 audio_token_id: int | None = 258_881 initializer_range: float | None = 0.02 tie_word_embeddings: bool = True def __post_init__(self, **kwargs): if self.text_config is None: self.text_config = Gemma4UnifiedTextConfig() logger.info("text_config is None. Using default Gemma4UnifiedTextConfig.") elif isinstance(self.text_config, dict): self.text_config = Gemma4UnifiedTextConfig(**self.text_config) if self.vision_config is None: logger.info("vision_config is None. Gemma4UnifiedModel.vision_tower will not be initialized.") if isinstance(self.vision_config, dict): self.vision_config = Gemma4UnifiedVisionConfig(**self.vision_config) if self.audio_config is None: logger.info("audio_config is None. Gemma4UnifiedModel.audio_tower will not be initialized.") if isinstance(self.audio_config, dict): self.audio_config = Gemma4UnifiedAudioConfig(**self.audio_config) super().__post_init__(**kwargs) __all__ = ["Gemma4UnifiedAudioConfig", "Gemma4UnifiedConfig", "Gemma4UnifiedTextConfig", "Gemma4UnifiedVisionConfig"]