#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/axk2/modular_axk2.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_axk2.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 SK Telecom and the 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
from ...modeling_rope_utils import RotaryEmbeddingConfigMixin
from ...utils import auto_docstring


@auto_docstring(checkpoint="skt/A.X-K2")
@strict
class AXK2Config(PreTrainedConfig, RotaryEmbeddingConfigMixin):
    r"""
    n_group (`int`, *optional*):
        Number of expert groups for grouped routing, used by the larger A.X-K2 releases. `None` (the
        A.X-K2-Light default) routes over all experts without group restriction.
    topk_group (`int`, *optional*):
        Number of expert groups the top-k selection is restricted to when `n_group` is set.
    mlp_layer_types (`list`, *optional*):
        MLP type pattern for each layer (`"dense"` or `"sparse"`). Derived from the (legacy) kwargs
        `first_k_dense_replace` / `moe_layer_freq` when not provided.
    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 16):
        Number of heads for the indexer projections (DSA).
    gated_norm_rank (`int`, *optional*, defaults to 16):
        Bottleneck rank for the low-rank input-dependent gate used by `AXK2GatedRMSNorm`. The gate wraps
        `input_layernorm` on every layer and `post_attention_layernorm` on MoE layers.

    ```python
    >>> from transformers import AXK2Config, AXK2Model

    >>> # Initializing an A.X-K2 style configuration
    >>> configuration = AXK2Config()

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

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

    model_type = "axk2"
    keys_to_ignore_at_inference = ["past_key_values"]

    base_model_tp_plan = {
        "layers.*.self_attn.q_gate_proj": "colwise",
        "layers.*.self_attn.kv_a_proj_with_mqa": "mla_kv_a_proj",
        "layers.*.self_attn.kv_b_proj": "colwise",
        "layers.*.self_attn.o_proj": "rowwise",
        "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.gate": "ep_router",
        "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",
        "layers.*.mlp.experts.down_proj": "grouped_gemm",
        "layers.*.mlp.experts": "moe_tp_experts",
    }

    attribute_map = {"num_local_experts": "n_routed_experts"}

    vocab_size: int = 163840
    hidden_size: int = 2048
    intermediate_size: int = 5120
    moe_intermediate_size: int = 512
    num_hidden_layers: int = 48
    num_attention_heads: int = 32
    num_key_value_heads: int = 32
    n_shared_experts: int = 1
    n_routed_experts: int = 128
    routed_scaling_factor: float = 2.5
    kv_lora_rank: int = 128
    q_lora_rank: int = 384
    qk_rope_head_dim: int = 32
    v_head_dim: int = 64
    qk_nope_head_dim: int = 64
    # A.X-K2-Light routes without expert groups; the larger A.X-K2 releases set `n_group`/`topk_group`
    # for DeepSeek-V3-style grouped routing, so both modes are supported (`None` = non-grouped).
    n_group: int | None = None
    topk_group: int | None = None
    num_experts_per_tok: int = 8
    norm_topk_prob: bool = True
    hidden_act: str = "silu"
    max_position_embeddings: int = 131072
    initializer_range: float = 0.02
    rms_norm_eps: float = 1e-6
    use_cache: bool = True
    pad_token_id: int | None = None
    bos_token_id: int | None = 163691
    eos_token_id: int | list[int] | None = 163691
    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 = 16
    head_dim: int = 64
    layer_types: list[str] | None = None
    gated_norm_rank: int = 16

    def __post_init__(self, **kwargs):
        self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
        # RoPE applies only to the rope slice, so `head_dim` points at it (the inherited rotary embedding
        # reads `config.head_dim`).
        self.head_dim = self.qk_rope_head_dim

        # Convert from legacy args to mlp layer types
        if self.mlp_layer_types is None:
            first_k_dense_replace = kwargs.pop("first_k_dense_replace", 1)
            moe_layer_freq = kwargs.pop("moe_layer_freq", 1)
            self.mlp_layer_types = [
                "sparse" if i >= first_k_dense_replace and i % moe_layer_freq == 0 else "dense"
                for i in range(self.num_hidden_layers)
            ]

        # Indexer cache needed so DSA to indicate correct cache
        if self.layer_types is None:
            self.layer_types = ["deepseek_sparse_attention"] * self.num_hidden_layers

        super().__post_init__(**kwargs)

    def validate_architecture(self):
        super().validate_architecture()
        if self.q_lora_rank is None or self.q_lora_rank <= 0:
            raise ValueError(
                "A.X-K2 requires a positive `q_lora_rank` (the indexer and output gate read the query LoRA "
                f"bottleneck), got {self.q_lora_rank}."
            )
        if (self.n_group is None) != (self.topk_group is None):
            raise ValueError(
                f"`n_group` and `topk_group` must be set together (both `None` for non-grouped routing), got "
                f"n_group={self.n_group}, topk_group={self.topk_group}."
            )
        if self.n_group is not None:
            if self.n_routed_experts % self.n_group != 0:
                raise ValueError(
                    f"`n_routed_experts` ({self.n_routed_experts}) must be divisible by `n_group` ({self.n_group})."
                )
            if self.topk_group > self.n_group:
                raise ValueError(f"`topk_group` ({self.topk_group}) cannot exceed `n_group` ({self.n_group}).")


__all__ = ["AXK2Config"]
