import torch

from typing import List, Optional
from transformers import Qwen2Config as Qwen3Config
from vllm.attention import AttentionMetadata
from vllm.config import CacheConfig
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm_mlu.model_executor.layers.feed_forward import FeedForward
from vllm_mlu.mlu_hijack_utils import MluHijackObject
from vllm.logger import init_logger

from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding
from vllm.model_executor.models.qwen3 import Qwen3Attention, Qwen3DecoderLayer, Qwen3Model
from vllm.sequence import IntermediateTensors
from vllm_mlu.model_executor.models.layer_utils import (
    decoder_layer_forward_base, decoder_model_forward_base_pp,
    is_per_tensor_smoothquant, is_per_token_smoothquant,
    quant_fusion_with_rmsnorm)

logger = init_logger(__name__)


def vllm__module_executor__models__qwen3__Qwen3Attention__forward(
    self,
    positions: torch.Tensor,
    hidden_states: torch.Tensor,
    kv_cache: torch.Tensor,
    attn_metadata: AttentionMetadata,
    residual: Optional[torch.Tensor] = None,
    smooth_quant_scale: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    qkv, _ = self.qkv_proj(hidden_states, smooth_quant_scale)
    q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)

    '''
    =============================
    Modify by vllm_mlu for Qwen3
    =============================
    @brief: Apply QK normalization (Qwen3 specific)
    Reference: Qwen2 MLU implementation style
    '''
    # Make q and k contiguous before reshape/view operations
    q = q.contiguous()
    k = k.contiguous()

    # Apply QK normalization before rotary embedding
    q_shape = q.shape
    k_shape = k.shape
    q_by_head = q.view(*q_shape[:-1], self.num_heads, self.head_dim)
    q_by_head = self.q_norm(q_by_head)
    q = q_by_head.view(q_shape)

    k_by_head = k.view(*k_shape[:-1], self.num_kv_heads, self.head_dim)
    k_by_head = self.k_norm(k_by_head)
    k = k_by_head.view(k_shape)
    '''
    ==================
    End of QK Norm
    ==================
    '''

    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: pack q & k to fit tmo.apply_rotary
    Reference: Qwen2 MLU implementation
    '''
    # Pack q and k for MLU rotary embedding optimization
    # Ensure qk is contiguous for view operation
    qk = torch.cat([q, k], dim=-1).contiguous()
    self.rotary_emb(positions, qk.view(-1, self.num_heads + self.num_kv_heads, self.head_dim))
    # Split back after rotary
    q, k = qk.split([self.q_size, self.kv_size], dim=-1)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''

    attn_output = self.attn(q, k, v, kv_cache, attn_metadata)

    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: add residual
    '''
    output, _ = self.o_proj(attn_output, residual)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''
    return output


def vllm__module_executor__models__qwen3__Qwen3DecoderLayer____init__(
    self,
    config: Qwen3Config,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
) -> None:
    super(Qwen3DecoderLayer, self).__init__()
    self.hidden_size = config.hidden_size
    # Requires transformers > 4.32.0
    rope_theta = getattr(config, "rope_theta", 1000000)
    rope_scaling = getattr(config, "rope_scaling", None)
    self.self_attn = Qwen3Attention(
        hidden_size=self.hidden_size,
        num_heads=config.num_attention_heads,
        max_position_embeddings=config.max_position_embeddings,
        num_kv_heads=config.num_key_value_heads,
        rope_theta=rope_theta,
        cache_config=cache_config,
        quant_config=quant_config,
        rope_scaling=rope_scaling,
        rms_norm_eps=config.rms_norm_eps,
        qkv_bias=getattr(config, "attention_bias", False),
        head_dim=getattr(config, "head_dim", None),
        prefix=f"{prefix}.self_attn",
    )
    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: use FeedForward instead of MLP
    '''
    self.mlp = FeedForward(hidden_size=config.hidden_size,
                            intermediate_size=config.intermediate_size,
                            hidden_act='silu',
                            up_proj_name='gate_up_proj',
                            is_gated=True,
                            down_proj_name='down_proj',
                            bias=False,
                            quant_config=quant_config,
                            prefix=f"{prefix}.mlp")
    '''
    ==================
    End of MLU Hijack
    ==================
    '''
    self.input_layernorm = RMSNorm(config.hidden_size,
                                    eps=config.rms_norm_eps)
    self.post_attention_layernorm = RMSNorm(config.hidden_size,
                                            eps=config.rms_norm_eps)
    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: prepare to perf per-tensor sq cases if suitable
    '''
    self.is_per_tesnor_sq_perf_cases = is_per_tensor_smoothquant(quant_config)
    self.is_per_token_sq_perf_cases = is_per_token_smoothquant(quant_config)
    if self.is_per_tesnor_sq_perf_cases or self.is_per_token_sq_perf_cases:
        self.self_attn.qkv_proj.quant_method.skip_quant_input = True
        self.mlp.gate_up_proj.quant_method.skip_quant_input = True
        self.quant_fusion_attn_layernorm = None
        self.quant_fusion_mlp_layernorm = None
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


def vllm__module_executor__models__qwen3__Qwen3DecoderLayer__forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        kv_cache: torch.Tensor,
        attn_metadata: AttentionMetadata,
    ) -> torch.Tensor:
    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: perf model by:
    1) add residual in matmul;
    2) fuse quantization in layernorm in per-tensor sq case;
    '''
    attn_layernorm = self.input_layernorm
    mlp_layernorm = self.post_attention_layernorm
    if self.is_per_tesnor_sq_perf_cases or self.is_per_token_sq_perf_cases:
        if self.quant_fusion_attn_layernorm is None:
            if self.is_per_token_sq_perf_cases:
                attn_quant_scale = self.self_attn.qkv_proj.smooth
                mlp_quant_scale = self.mlp.gate_up_proj.smooth
            else:
                attn_quant_scale = self.self_attn.qkv_proj.scale_to_int
                mlp_quant_scale = self.mlp.gate_up_proj.scale_to_int
            self.quant_fusion_attn_layernorm = quant_fusion_with_rmsnorm(
                self.input_layernorm, attn_quant_scale,
                dynamic_quant=self.is_per_token_sq_perf_cases)
            self.quant_fusion_mlp_layernorm = quant_fusion_with_rmsnorm(
                self.post_attention_layernorm, mlp_quant_scale,
                dynamic_quant=self.is_per_token_sq_perf_cases)
        attn_layernorm = self.quant_fusion_attn_layernorm
        mlp_layernorm = self.quant_fusion_mlp_layernorm

    return decoder_layer_forward_base(positions=positions,
                                      hidden_states=hidden_states,
                                      kv_cache=kv_cache,
                                      attn_metadata=attn_metadata,
                                      input_layernorm=attn_layernorm,
                                      self_attn=self.self_attn,
                                      post_layernorm=mlp_layernorm,
                                      mlp=self.mlp,
                                      input_norm_fuse_en=self.is_per_token_sq_perf_cases,
                                      post_norm_fuse_en=self.is_per_token_sq_perf_cases)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


def vllm__module_executor__models__qwen3__Qwen3Model__forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        kv_caches: List[torch.Tensor],
        attn_metadata: AttentionMetadata,
        intermediate_tensors: Optional[IntermediateTensors] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
    '''
    =============================
    Modify by vllm_mlu
    =============================
    '''
    return decoder_model_forward_base_pp(input_ids=input_ids,
                                         positions=positions,
                                         kv_caches=kv_caches,
                                         attn_metadata=attn_metadata,
                                         intermediate_tensors=intermediate_tensors,
                                         layers=self.layers,
                                         start_layer=self.start_layer,
                                         end_layer=self.end_layer,
                                         get_input_embeddings=self.embed_tokens,
                                         norm=self.norm,
                                         inputs_embeds=inputs_embeds)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


# Apply hijacks
MluHijackObject.apply_hijack(Qwen3Attention,
                             Qwen3Attention.forward,
                             vllm__module_executor__models__qwen3__Qwen3Attention__forward)
MluHijackObject.apply_hijack(Qwen3DecoderLayer,
                             Qwen3DecoderLayer.__init__,
                             vllm__module_executor__models__qwen3__Qwen3DecoderLayer____init__)
MluHijackObject.apply_hijack(Qwen3DecoderLayer,
                             Qwen3DecoderLayer.forward,
                             vllm__module_executor__models__qwen3__Qwen3DecoderLayer__forward)
MluHijackObject.apply_hijack(Qwen3Model,
                             Qwen3Model.forward,
                             vllm__module_executor__models__qwen3__Qwen3Model__forward)
