#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/inkling2/modular_inkling2.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_inkling2.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.

import copy

from huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig
from ...utils import auto_docstring


@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Small-MXFP8")
@strict
class Inkling2TextConfig(PreTrainedConfig):
    r"""
    unpadded_vocab_size (`int`, *optional*, defaults to 200058):
        Number of rows of the unembedding matrix that hold real tokens. Logits beyond it are dropped.
    swa_num_attention_heads (`int`, *optional*, defaults to 48):
        Number of attention heads in the sliding-window layers.
    swa_num_key_value_heads (`int`, *optional*, defaults to 8):
        Number of key/value heads in the sliding-window layers.
    swa_head_dim (`int`, *optional*, defaults to 128):
        Dimension of query and key heads in the sliding-window layers.
    sliding_window_size (`int`, *optional*, defaults to 1024):
        Size of the sliding attention window used by layers whose `layer_types` entry is `"hybrid_sliding"`.
    d_rel (`int`, *optional*, defaults to 16):
        Per-head dimension of the relative states that are mixed into the relative position bias.
    rel_extent (`int`, *optional*, defaults to 1024):
        Backward distance, in tokens, over which the relative position bias is applied in the full-attention layers.
    log_scaling_n_floor (`int`, *optional*, defaults to 128000):
        Position from which queries and relative states are scaled up logarithmically in the full-attention layers.
    log_scaling_alpha (`float`, *optional*, defaults to 0.1):
        Strength of the logarithmic scaling controlled by `log_scaling_n_floor`.
    qk_l2_clip_threshold (`float`, *optional*, defaults to 22.627416997969522):
        Maximum L2 norm of each query and key head vector. Longer vectors are scaled down to this norm.
    rel_l2_clip_threshold (`float`, *optional*, defaults to 8.0):
        Maximum L2 norm of each relative-state head vector.
    n_layers_per_attn_res_block (`int`, *optional*, defaults to 6):
        Number of decoder layers summed into one block before the block becomes a source of the attention residuals.
    mlp_gate_softcap (`float`, *optional*, defaults to 4.0):
        Softcap applied to the linear part of the experts' gate projection.
    mlp_up_softcap (`float`, *optional*, defaults to 25.0):
        Softcap applied to the experts' up projection.
    final_logit_softcapping (`float`, *optional*, defaults to 30.0):
        Softcap applied to the output logits.
    scoring_func (`str`, *optional*, defaults to `"sigmoid"`):
        Activation turning the router logits into expert scores.
    """

    model_type = "inkling2_text"
    base_config_key = "text_config"
    base_model_tp_plan = {
        "embed_tokens": "replicate",
        "layers.*.mlp.experts.gate_up_proj": "colwise",
        "layers.*.mlp.experts.down_proj": "rowwise",
        "layers.*.mlp.experts": "moe_tp_experts",
    }
    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 = {
        "sliding_window": "sliding_window_size",
        "num_local_experts": "n_routed_experts",
        "sconv_kernel_size": "conv_kernel_size",
        "model_max_length": "max_position_embeddings",
        "intermediate_size": "moe_intermediate_size",
        "routed_scaling_factor": "route_scale",
    }

    vocab_size: int = 201024

    unpadded_vocab_size: int = 200058
    hidden_size: int = 4608
    num_hidden_layers: int = 48
    num_attention_heads: int = 48
    num_key_value_heads: int = 8
    head_dim: int = 128
    swa_num_attention_heads: int = 48
    swa_num_key_value_heads: int = 8
    swa_head_dim: int = 128
    sliding_window_size: int = 1024
    d_rel: int = 16
    rel_extent: int = 1024
    log_scaling_n_floor: int = 128000
    log_scaling_alpha: float = 0.1
    layer_types: list[str] | None = None
    max_position_embeddings: int = 1048576
    rms_norm_eps: float = 1e-6
    conv_kernel_size: int = 4
    hidden_act: str = "silu"
    moe_intermediate_size: int = 2304
    n_routed_experts: int = 384
    num_experts_per_tok: int = 8
    route_scale: float = 8.0
    attention_dropout: float = 0.0
    initializer_range: float = 0.02
    pad_token_id: int | None = None
    bos_token_id: int | None = None
    eos_token_id: int | None = 200006
    qk_l2_clip_threshold: float = 22.627416997969522
    rel_l2_clip_threshold: float = 8.0
    n_layers_per_attn_res_block: int = 6
    mlp_gate_softcap: float = 4.0
    mlp_up_softcap: float = 25.0
    final_logit_softcapping: float = 30.0
    scoring_func: str = "sigmoid"
    use_cache: bool = True
    number_of_conv_states = 4

    def __post_init__(self, **kwargs):
        if self.layer_types is None:
            self.layer_types = [
                "hybrid" if (i + 1) % 6 == 0 else "hybrid_sliding" for i in range(self.num_hidden_layers)
            ]
        super().__post_init__(**kwargs)


@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Small-MXFP8")
@strict
class Inkling2VisionConfig(PreTrainedConfig):
    r"""
    spatial_merge_size (`int`, *optional*, defaults to 2):
        Side, in native patches, of the square of patch features concatenated into one language model token.
    posemb_grid_size (`int`, *optional*, defaults to 32):
        Side of the learned position embedding grid, interpolated to each image's native patch grid.
    projection_hidden_dim (`int`, *optional*, defaults to 4096):
        Hidden size of the MLP projecting merged patch features to the language model.
    projector_bias (`bool`, *optional*, defaults to `False`):
        Whether the projection MLP uses biases.
    text_hidden_size (`int`, *optional*, defaults to 4608):
        Hidden size of the language model the image features are projected to.
    """

    model_type = "inkling2_vision"
    base_config_key = "vision_config"

    hidden_size: int = 1024
    intermediate_size: int | None = None
    num_hidden_layers: int = 23
    num_attention_heads: int = 16
    num_channels: int = 3
    patch_size: int = 20
    hidden_act: str = "gelu"
    layer_norm_eps: float = 1e-5
    attention_dropout: float | int = 0.0
    default_rope_type = "axial"
    mlp_ratio: float = 4.0
    layer_scale_init_value: float = 0.1
    rope_parameters: dict | None = None
    attribute_map = {"native_patch_size": "patch_size", "adapter_merge_size": "spatial_merge_size"}
    spatial_merge_size: int = 2
    posemb_grid_size: int = 32
    projection_hidden_dim: int = 4096
    projector_bias: bool = False
    text_hidden_size: int = 4608
    initializer_range: float = 0.02

    def __post_init__(self, **kwargs):
        if self.intermediate_size is None:
            self.intermediate_size = int(self.hidden_size * self.mlp_ratio)
        super().__post_init__(**kwargs)


# Missing from the hub config: the routed experts are MXFP8 (e4m3, a ue8m0 scale per row and 32 values), the rest bf16
INKLING2_QUANTIZATION_CONFIG = {
    "quant_method": "fp8",
    "weight_block_size": [1, 32],
    "scale_fmt": "ue8m0",
    "modules_to_not_convert": ["lm_head", "model.vision_tower", "model.language_model.layers.*.self_attn"],
}


@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Small-MXFP8")
@strict
class Inkling2Config(PreTrainedConfig):
    r"""
    image_token_id (`int`, *optional*, defaults to 200054):
        Token index of the image placeholders, each replaced by one image feature.
    """

    model_type = "inkling2"
    sub_configs_defaults = {"text_config": Inkling2TextConfig, "vision_config": Inkling2VisionConfig}

    text_config: Inkling2TextConfig | dict | None = None
    vision_config: Inkling2VisionConfig | dict | None = None
    image_token_id: int = 200054

    @classmethod
    def from_dict(cls, config_dict: dict, **kwargs):
        # Quantization config is missing from the hub config: only added to an original checkpoint's config, not to
        # one saved by Transformers (which has its own, or none once dequantized)
        if "quantization_config" not in config_dict and "transformers_version" not in config_dict:
            config_dict = {**config_dict, "quantization_config": copy.deepcopy(INKLING2_QUANTIZATION_CONFIG)}
        return super().from_dict(config_dict, **kwargs)

    def validate_architecture(self):
        if self.vision_config.text_hidden_size != self.text_config.hidden_size:
            raise ValueError(
                f"`vision_config.text_hidden_size` ({self.vision_config.text_hidden_size}) must match "
                f"`text_config.hidden_size` ({self.text_config.hidden_size})."
            )


__all__ = ["Inkling2Config", "Inkling2TextConfig", "Inkling2VisionConfig"]
