import torch
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging

logger = logging.get_logger(__name__)


class MotifConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`MotifModel`]. It is used to instantiate a
    Motif model according to the specified arguments, defining the model architecture.
    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.
    Args:
        vocab_size (`int`, *optional*, defaults to 151936):
            Vocabulary size of the Motif model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`MotifModel`]
        hidden_size (`int`, *optional*, defaults to 4096):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 22016):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 32):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer encoder.
        num_key_value_heads (`int`, *optional*, defaults to 32):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
            by meanpooling all the original heads within that group. For more details checkout [this
            paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 32768):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether the model's input and output word embeddings should be tied.
        rope_theta (`float`, *optional*, defaults to 1000000.0):
            The base period of the RoPE embeddings.
        rope_scaling (`Dict`, *optional*):
            Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
            and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
            accordingly.
            Expected contents:
                `rope_type` (`str`):
                    The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
                    'llama3'], with 'default' being the original RoPE implementation.
                `factor` (`float`, *optional*):
                    Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
                    most scaling types, a `factor` of x will enable the model to handle sequences of length x *
                    original maximum pre-trained length.
                `original_max_position_embeddings` (`int`, *optional*):
                    Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
                    pretraining.
                `attention_factor` (`float`, *optional*):
                    Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
                    computation. If unspecified, it defaults to value recommended by the implementation, using the
                    `factor` field to infer the suggested value.
                `beta_fast` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
                    ramp function. If unspecified, it defaults to 32.
                `beta_slow` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
                    ramp function. If unspecified, it defaults to 1.
                `short_factor` (`List[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to short contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `long_factor` (`List[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to long contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `low_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
                `high_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
        use_sliding_window (`bool`, *optional*, defaults to `False`):
            Whether to use sliding window attention.
        sliding_window (`int`, *optional*, defaults to 4096):
            Sliding window attention (SWA) window size. If not specified, will default to `4096`.
        max_window_layers (`int`, *optional*, defaults to 28):
            The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
    ```python
    >>> from transformers import MotifModel, MotifConfig
    >>> # Initializing a Motif style configuration
    >>> configuration = MotifConfig()
    >>> # Initializing a model from the Motif-102B style configuration
    >>> model = MotifModel(configuration)
    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""

    model_type = "Motif"
    keys_to_ignore_at_inference = ["past_key_values"]

    base_model_tp_plan = {
        # Attention
        "layers.*.self_attn.q_proj": "colwise",
        "layers.*.self_attn.k_proj": "colwise",
        "layers.*.self_attn.v_proj": "colwise",
        "layers.*.self_attn.o_proj": "rowwise",
        # Dense MLP
        "layers.*.mlp.gate_proj": "colwise",
        "layers.*.mlp.up_proj": "colwise",
        "layers.*.mlp.down_proj": "rowwise",
        # MoE experts (fused gate+up)
        "layers.*.moe.experts.gate_up_proj": "packed_colwise",
        "layers.*.moe.experts.down_proj": "rowwise",
        # Shared experts
        "layers.*.moe.shared_experts.gate_proj": "colwise",
        "layers.*.moe.shared_experts.up_proj": "colwise",
        "layers.*.moe.shared_experts.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"]),
    }

    def __init__(
        self,
        vocab_size=151936,
        hidden_size=4096,
        intermediate_size=22016,
        num_hidden_layers=32,
        num_attention_heads=32,
        num_key_value_heads=32,
        hidden_act="silu",
        max_position_embeddings=32768,
        initializer_range=0.02,
        rms_norm_eps=1e-6,
        use_cache=True,
        tie_word_embeddings=False,
        rope_theta=1000000.0,
        rope_scaling=None,
        use_sliding_window=False,
        sliding_window=4096,
        max_window_layers=28,
        sliding_window_pattern="interleave",
        sliding_window_period=2,
        attention_dropout=0.0,
        # Differential Attention parameters
        head_dim=None,
        num_noise_heads=0,
        k_ratio=1,
        # MoE parameters
        num_experts=0,
        experts_top_k=2,
        num_shared_experts=0,
        interleave_moe_layer_step=0,
        moe_intermediate_size=None,
        score_func="softmax",
        route_norm=False,
        route_scale=1.0,
        load_balance_coeff=None,
        score_before_experts=False,
        _debug_force_load_balance=False,
        output_router_logits=False,
        router_aux_loss_coef=0.0,
        # MHC (Manifold-constrained Hyper-Connections) parameters
        mhc_enabled=False,
        mhc_expansion_rate=4,
        mhc_identity_init=False,
        mhc_sinkhorn_iters=20,
        # DiffAttention V2 / Attention class
        diff_v2=False,
        attention_cls="basic",
        # GDLA (Grouped Differential Latent Attention) parameters
        q_lora_rank=0,
        kv_lora_rank=0,
        qk_rope_head_dim=None,
        v_head_dim=None,
        original_seq_len=32768,
        rope_factor=1.0,
        mscale=1.0,
        swa_rope_theta=None,
        # Attention output gating
        headwise_attn_output_gate=False,
        elementwise_attn_output_gate=False,
        # MoE: first N layers always dense (no MoE), regardless of interleave schedule
        n_dense_first_layers=0,
        # MTP (Multi-Token Prediction) speculative decoding
        num_nextn_predict_layers=0,
        **kwargs,
    ):
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.use_sliding_window = use_sliding_window
        self.sliding_window = sliding_window if use_sliding_window else None
        self.max_window_layers = max_window_layers
        self.sliding_window_pattern = sliding_window_pattern
        self.sliding_window_period = sliding_window_period

        # for backward compatibility
        if num_key_value_heads is None:
            num_key_value_heads = num_attention_heads

        self.num_key_value_heads = num_key_value_heads
        self.hidden_act = hidden_act
        self.initializer_range = initializer_range
        self.rms_norm_eps = rms_norm_eps
        self.use_cache = use_cache
        self.rope_theta = rope_theta
        self.rope_scaling = rope_scaling
        self.attention_dropout = attention_dropout

        # Differential Attention configuration
        self.head_dim = head_dim
        self.num_noise_heads = num_noise_heads
        self.k_ratio = k_ratio

        # MoE configuration
        self.num_experts = num_experts
        self.experts_top_k = experts_top_k
        self.num_shared_experts = num_shared_experts
        self.interleave_moe_layer_step = interleave_moe_layer_step
        self.moe_intermediate_size = moe_intermediate_size if moe_intermediate_size is not None else intermediate_size
        self.score_func = score_func
        self.route_norm = route_norm
        self.route_scale = route_scale
        self.load_balance_coeff = load_balance_coeff
        self.score_before_experts = score_before_experts
        self._debug_force_load_balance = _debug_force_load_balance
        self.output_router_logits = output_router_logits
        self.router_aux_loss_coef = router_aux_loss_coef

        # MHC configuration
        self.mhc_enabled = mhc_enabled
        self.mhc_expansion_rate = mhc_expansion_rate
        self.mhc_identity_init = mhc_identity_init
        self.mhc_sinkhorn_iters = mhc_sinkhorn_iters

        # DiffAttention V2 / Attention class
        self.diff_v2 = diff_v2
        self.attention_cls = attention_cls

        # GDLA parameters
        self.q_lora_rank = q_lora_rank
        self.kv_lora_rank = kv_lora_rank
        self.qk_rope_head_dim = qk_rope_head_dim
        self.v_head_dim = v_head_dim
        self.original_seq_len = original_seq_len
        self.rope_factor = rope_factor
        self.mscale = mscale
        self.swa_rope_theta = swa_rope_theta

        # Attention output gating
        self.headwise_attn_output_gate = headwise_attn_output_gate
        self.elementwise_attn_output_gate = elementwise_attn_output_gate

        # MoE dense-first layers
        self.n_dense_first_layers = n_dense_first_layers

        # MTP speculative decoding
        self.num_nextn_predict_layers = num_nextn_predict_layers

        # Validate the correctness of rotary position embeddings parameters
        # BC: if there is a 'type' field, move it to 'rope_type'.
        if self.rope_scaling is not None and "type" in self.rope_scaling:
            self.rope_scaling["rope_type"] = self.rope_scaling["type"]
        # Motif applies the YaRN mscale on the attention softmax scale
        # (DeepSeek-style, full-attention layers only), never on the cos/sin table.
        # Default attention_factor=1.0 so transformers' YaRN rope init does not ALSO
        # scale cos/sin (which would double-apply mscale); apply_yarn_scaling=False
        # makes that intent explicit for the modeling code (MotifRotaryEmbedding).
        if self.rope_scaling is not None and self.rope_scaling.get("rope_type") == "yarn":
            self.rope_scaling.setdefault("attention_factor", 1.0)
            self.rope_scaling.setdefault("apply_yarn_scaling", False)
        if callable(getattr(type(self), "validate_rope", None)):
            self.validate_rope()

        # The per-expert PolyNorm activation (GroupedPolyNorm) is only correct via
        # the EAGER experts loop: the grouped_mm / batched_mm interfaces call
        # _apply_gate once over all expert-sorted tokens with no per-expert index,
        # so they cannot apply per-expert coefficients. Force eager dispatch for
        # MoE Motif models unless the caller explicitly overrides it. (This also
        # covers ROCm, where torch._grouped_mm has no runtime kernel.)
        if self.num_experts > 0 and "experts_implementation" not in kwargs:
            kwargs["experts_implementation"] = "eager"

        super().__init__(
            tie_word_embeddings=tie_word_embeddings,
            **kwargs,
        )
        logger.info(f" kwargs : {kwargs}")
