#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/mistral_large4/modular_mistral_large4.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_mistral_large4.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 HuggingFace Inc. 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 huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig, SubConfigSpec
from ...utils import auto_docstring
from ..auto import AutoConfig


@auto_docstring(checkpoint="mistralai/Mistral-Large-4-1T-A52B")
@strict
class MistralLarge4TextConfig(PreTrainedConfig):
    r"""
    n_group (`int`, *optional*, defaults to 1):
        Number of groups for routed experts.
    mlp_layer_types (`list`, *optional*):
        MLP type pattern for each layer (`"dense"` or `"sparse"`). Defaults to 1 dense + rest sparse.
    index_topk (`int`, *optional*, defaults to 2048):
        Number of top tokens selected by the indexer for sparse attention.
    index_head_dim (`int`, *optional*, defaults to 128):
        Head dimension for the indexer projections (DSA).
    index_n_heads (`int`, *optional*, defaults to 32):
        Number of heads for the indexer projections (DSA).
    first_k_dense_replace (`int`, *optional*, defaults to 1):
        Number of leading layers that use a dense MLP; the rest use the MoE block.
    indexer_types (`list[str]`, *optional*):
        Per-layer indexer mode (`"full"` runs the indexer, `"shared"` reuses the previous full
        layer's top-k). Defaults to the pattern derived from `index_topk_freq` /
        `index_skip_topk_offset` (or `index_topk_pattern`).
    no_rope_layers (`list[int]`, *optional*):
        List with at least the same length as the number of layers in the model.
        A `1` at an index position indicates that the corresponding layer will use RoPE,
        while a `0` indicates that it's a NoPE layer.
    kv_source_layers (`list[int]`, *optional*):
        For each layer, the index of the layer whose latent KV cache it attends to. A layer whose entry is its own
        index computes and caches its own latent KV; a layer pointing at an earlier layer has no `kv_a_proj_with_mqa`
        and reuses that layer's cache (the source layer must be its own source). Defaults to no sharing.

    ```python
    >>> from transformers import MistralLarge4TextConfig, MistralLarge4TextModel

    >>> # Initializing a Mistral Large 4 text configuration
    >>> configuration = MistralLarge4TextConfig()

    >>> # Initializing a model from the configuration
    >>> model = MistralLarge4TextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""

    model_type = "mistral_large4_text"
    keys_to_ignore_at_inference = ["past_key_values"]

    base_model_tp_plan = {
        "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
        "layers.*.mlp.experts.down_proj": "rowwise",
        "layers.*.mlp.experts": "moe_tp_experts",
        "layers.*.mlp.shared_experts.gate_proj": "colwise",
        "layers.*.mlp.shared_experts.up_proj": "colwise",
        "layers.*.mlp.shared_experts.down_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"]),
    }
    base_model_ep_plan = {
        "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",
        "layers.*.mlp.experts.down_proj": "grouped_gemm",
        "layers.*.mlp.experts": "ep_dispatch_experts",
    }

    attribute_map = {"num_local_experts": "n_routed_experts"}

    vocab_size: int = 204800
    hidden_size: int = 6144
    intermediate_size: int = 24576
    moe_intermediate_size: int = 6144
    num_hidden_layers: int = 72
    num_attention_heads: int = 64
    num_key_value_heads: int = 64
    n_shared_experts: int = 1
    n_routed_experts: int = 128
    output_router_logits: bool = False
    routed_scaling_factor: float = 1.0
    kv_lora_rank: int = 512
    qk_rope_head_dim: int = 64
    v_head_dim: int = 128
    qk_nope_head_dim: int = 64
    n_group: int = 1
    topk_group: int = 1
    num_experts_per_tok: int = 4
    hidden_act: str = "silu"
    max_position_embeddings: int = 1048576
    initializer_range: float = 0.02
    rms_norm_eps: float = 1e-5
    use_cache: bool = True
    pad_token_id: int | None = None
    bos_token_id: int | None = 1
    eos_token_id: int | list[int] | None = 2
    tie_word_embeddings: bool = False
    rope_parameters: dict | None = None
    mlp_layer_types: list[str] | None = None
    attention_bias: bool = False
    attention_dropout: float | int = 0.0
    index_topk: int = 2048
    index_head_dim: int = 128
    index_n_heads: int = 32
    head_dim: int = 64
    first_k_dense_replace: int = 1
    layer_types: list[str] | None = None
    # `"full"` runs the indexer, `"shared"` reuses the previous full layer's index mask.
    indexer_types: list[str] | None = None
    no_rope_layers: list[int] | None = None
    kv_source_layers: list[int] | None = None
    final_logit_softcapping: float = 30.0

    def __post_init__(self, **kwargs):
        # YaRN over a 512-token pretraining window, no magnitude scaling (attention_factor = 1.0) + LeRoPE
        if self.rope_parameters is None:
            self.rope_parameters = {
                "rope_type": "yarn",
                "rope_theta": 10000.0,
                "factor": 2048.0,
                "original_max_position_embeddings": 512,
                "beta_fast": 32.0,
                "beta_slow": 1.0,
                "attention_factor": 1.0,
            }
        # NoPE every `no_rope_layer_interval`-th layer (smollm3 convention: 1 == uses RoPE)
        if self.no_rope_layers is None:
            no_rope_layer_interval = kwargs.pop("no_rope_layer_interval", 4)
            self.no_rope_layers = [
                int((layer_idx + 1) % no_rope_layer_interval != 0) for layer_idx in range(self.num_hidden_layers)
            ]
        # KV sharing: by default every layer owns its latent KV cache
        if self.kv_source_layers is None:
            self.kv_source_layers = list(range(self.num_hidden_layers))
        # Per-layer indexer mode: a pattern (e.g. `"FSSF..."`) overrides the freq/offset schedule.
        if self.indexer_types is None:
            pattern = kwargs.get("index_topk_pattern")
            if pattern is not None:
                self.indexer_types = (
                    [{"F": "full", "S": "shared"}[c] for c in pattern] if isinstance(pattern, str) else list(pattern)
                )
            else:
                freq = max(kwargs.get("index_topk_freq", 1), 1)
                offset = kwargs.get("index_skip_topk_offset", 2)
                self.indexer_types = [
                    "full" if (max(i - offset + 1, 0) % freq) == 0 else "shared" for i in range(self.num_hidden_layers)
                ]
        self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
        # RoPE applies only to the rope slice, so point `head_dim` at it: the inherited (Llama) rotary
        # embedding reads `config.head_dim` and then computes the right frequencies with no override needed.
        self.head_dim = self.qk_rope_head_dim
        # MLP layer types: the first `first_k_dense_replace` layers are dense, the rest are MoE.
        if self.mlp_layer_types is None:
            n_dense = min(self.first_k_dense_replace, self.num_hidden_layers)
            self.mlp_layer_types = ["dense"] * n_dense + ["sparse"] * (self.num_hidden_layers - n_dense)
        # Every layer is DSA — drives cache-class dispatch.
        if self.layer_types is None:
            self.layer_types = ["indexed_attention"] * self.num_hidden_layers
        # BC: re-route `num_experts` to `n_routed_experts`
        if (num_experts := kwargs.get("num_experts")) is not None:
            self.n_routed_experts = num_experts
        super().__post_init__(**kwargs)

    def validate_architecture(self):
        # Validate KV sharing patterns
        if len(self.kv_source_layers) != self.num_hidden_layers:
            raise ValueError(
                f"`kv_source_layers` must have one entry per layer ({self.num_hidden_layers}), got {len(self.kv_source_layers)}."
            )
        for layer_idx, source in enumerate(self.kv_source_layers):
            if source > layer_idx or self.kv_source_layers[source] != source:
                raise ValueError(
                    f"Layer {layer_idx} must share KV with an earlier layer that owns its cache, got {source}."
                )
        super().validate_architecture()

    @property
    def kv_sharing_modes(self) -> list[str | None]:
        kv_sharing_modes = [None if i == self.kv_source_layers[i] else "reuse" for i in range(self.num_hidden_layers)]
        for i in range(self.num_hidden_layers):
            # These specific layers share the k/v part, but still need a cache for the indexer part - setting it to `reuse_but_indexer`
            # will still attribute them an IndexedLayer cache
            if kv_sharing_modes[i] == "reuse" and self.indexer_types[i] != "shared":
                kv_sharing_modes[i] = "reuse_but_indexer"
        # Find indices of layers that compute AND share their cache (i.e. their index appears at least twice in `kv_source_layers`)
        producers = [i for i in range(self.num_hidden_layers) if i in self.kv_source_layers[i + 1 :]]
        # Mark producers as such
        for producer_index in producers:
            kv_sharing_modes[producer_index] = "store"

        return kv_sharing_modes


@auto_docstring(checkpoint="mistralai/Mistral-Large-4-1T-A52B")
@strict
class MistralLarge4Config(PreTrainedConfig):
    r"""
    Example:

    ```python
    >>> from transformers import MistralLarge4ForConditionalGeneration, MistralLarge4Config, PixtralVisionConfig, MistralConfig

    >>> # Initializing a Pixtral-vision config
    >>> vision_config = PixtralVisionConfig()

    >>> # Initializing a Mistral config
    >>> text_config = MistralConfig()

    >>> # Initializing a MistralLarge4 configuration
    >>> configuration = MistralLarge4Config(vision_config, text_config)

    >>> # Initializing a model from the mistral_large4.1 configuration
    >>> model = MistralLarge4ForConditionalGeneration(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""

    model_type = "mistral_large4"
    attribute_map = {"image_token_id": "image_token_index"}
    sub_configs_defaults = {
        "text_config": MistralLarge4TextConfig,
        # Mistral Large 4 vision tower (same as Mistral Small 3.1: gated SiLU MLP, 1540 px images)
        "vision_config": SubConfigSpec(
            config_class=AutoConfig,
            model_type="pixtral",
            init_kwargs={
                "hidden_size": 2048,
                "intermediate_size": 6144,
                "num_hidden_layers": 30,
                "num_attention_heads": 16,
                "patch_size": 14,
                "image_size": 1540,
                "hidden_act": "silu",
            },
        ),
    }

    vision_config: dict | PreTrainedConfig | None = None
    text_config: dict | PreTrainedConfig | None = None
    image_token_index: int = 10
    projector_hidden_act: str = "gelu"
    vision_feature_layer: int | list[int] = -1
    multimodal_projector_bias: bool = False
    spatial_merge_size: int = 2

    tie_word_embeddings: bool = False


__all__ = ["MistralLarge4TextConfig", "MistralLarge4Config"]
