#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/embedding_gemma2/modular_embedding_gemma2.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_embedding_gemma2.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, SubConfigSpec
from ...utils import (
    auto_docstring,
    logging,
)
from ..auto import AutoConfig


logger = logging.get_logger(__name__)


@auto_docstring(checkpoint="google/embeddinggemma-2")
@strict
class EmbeddingGemma2TextConfig(PreTrainedConfig):
    r"""
    sliding_window (`int`, *optional*, defaults to 512):
        Inclusive radius of the bidirectional sliding window: a `sliding_attention` layer attends to
        every position with `abs(q_idx - kv_idx) <= sliding_window`. It is a radius and not the
        one-sided width the causal Gemma models configure, because the mask here is symmetric, so
        the default is half of the 1024-wide window the reference implementation states.
    hidden_size_per_layer_input (`int`, *optional*, defaults to 512):
        Dimensionality of the per-layer (PLE) residual signal. EmbeddingGemma 2 uses
        *projection-only* PLE: the signal is derived from `inputs_embeds` alone, with no
        auxiliary token lookup table.
    embedding_dim (`int`, *optional*, defaults to 768):
        Dimensionality of the sentence embedding produced by `embedding_projection`.
    """

    model_type = "embedding_gemma2_text"
    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.v_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_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 = 512
    intermediate_size: int = 2048
    num_hidden_layers: int = 24
    num_attention_heads: int = 4
    num_key_value_heads: int = 2
    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
    pad_token_id: int | None = 0
    eos_token_id: int | list[int] | None = 1
    bos_token_id: int | None = 2
    rope_parameters: dict | None = None
    attention_bias: bool = False
    attention_dropout: int | float | None = 0.0
    sliding_window: int = 512
    layer_types: list[str] | None = None
    hidden_size_per_layer_input: int = 512
    embedding_dim: int = 768

    def __post_init__(self, **kwargs):
        # `sliding_window_pattern`, `global_head_dim` and `num_global_key_value_heads` are builder-only
        # kwargs, as in Gemma 4: they shape `layer_types` and `per_layer_config` and are not kept on
        # the config, which exposes the derived values instead.
        sliding_window_pattern = kwargs.pop("sliding_window_pattern", 6)
        if sliding_window_pattern < 1:
            raise ValueError(f"`sliding_window_pattern` must be a positive integer, got {sliding_window_pattern}.")

        if self.layer_types is None:
            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": "default", "rope_theta": 1_000_000.0},
        }
        if self.rope_parameters is None:
            self.rope_parameters = default_rope_params

        # Full-attention layers are wider, hence the separate head dimension and kv head count.
        global_head_dim = kwargs.pop("global_head_dim", 512)
        num_global_key_value_heads = kwargs.pop("num_global_key_value_heads", 1)
        if "per_layer_config" not in kwargs:
            kwargs["per_layer_config"] = {
                layer_idx: {"head_dim": global_head_dim, "num_key_value_heads": num_global_key_value_heads}
                for layer_idx, layer_type in enumerate(self.layer_types)
                if layer_type == "full_attention"
            }

        super().__post_init__(**kwargs)

    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/embeddinggemma-2")
@strict
class EmbeddingGemma2Config(PreTrainedConfig):
    r"""
    text_config (`EmbeddingGemma2TextConfig`, *optional*):
        Configuration of the text backbone.
    vision_config (`PreTrainedConfig` or `dict`, *optional*):
        Configuration of the vision tower. Reused verbatim from Gemma 4; the tower itself is
        resolved at runtime through `AutoModel`.
    audio_config (`PreTrainedConfig` or `dict`, *optional*):
        Configuration of the audio tower. Reused verbatim from Gemma 4; the tower itself is
        resolved at runtime through `AutoModel`.
    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.
    """

    model_type = "embedding_gemma2"
    sub_configs_defaults = {
        "vision_config": SubConfigSpec(config_class=AutoConfig, model_type="gemma4_vision", optional=True),
        "text_config": SubConfigSpec(config_class=EmbeddingGemma2TextConfig),
        "audio_config": SubConfigSpec(config_class=AutoConfig, model_type="gemma4_audio", optional=True),
    }

    text_config: EmbeddingGemma2TextConfig | dict[str, Any] | None = None
    vision_config: PreTrainedConfig | dict[str, Any] | None = None
    audio_config: PreTrainedConfig | 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


__all__ = ["EmbeddingGemma2Config", "EmbeddingGemma2TextConfig"]
