import torch
import re
import torch.nn.functional as F
from typing import List, Optional, Tuple, Iterable
from transformers import PretrainedConfig
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.distributed import tensor_model_parallel_all_reduce
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.models.qwen2_moe import Qwen2MoeAttention, Qwen2MoeDecoderLayer, Qwen2MoeForCausalLM, Qwen2MoeModel
from vllm_mlu.model_executor.layers.sparse_moe_mlp import SparseMoeMlp
from vllm.utils import print_warning_once
from vllm.model_executor.models.utils import is_pp_missing_parameter
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)


class Qwen2MoeSparseMoeBlock(SparseMoeMlp):

    def __init__(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        super().__init__(num_experts=config.num_experts,
                         top_k=config.num_experts_per_tok,
                         hidden_size=config.hidden_size,
                         intermediate_size=config.moe_intermediate_size,
                         up_proj_name="gate_up_proj",
                         is_gated=True,
                         down_proj_name="down_proj",
                         has_bias=False,
                         skip_bias_add=False,
                         renormalize=config.norm_topk_prob,
                         hidden_act=config.hidden_act,
                         params_dtype=None,
                         quant_config=quant_config,
                         is_use_fused_moe=True)
        self.config = config
        self.shared_expert = None
        self.shared_expert_gate = None
        if config.shared_expert_intermediate_size > 0:
            self.shared_expert = FeedForward(hidden_size=config.hidden_size,
                                             intermediate_size=config.shared_expert_intermediate_size,
                                             hidden_act=config.hidden_act,
                                             up_proj_name='gate_up_proj',
                                             is_gated=True,
                                             down_proj_name='down_proj',
                                             bias=False,
                                             quant_config=quant_config,
                                             reduce_results=False)
            self.shared_expert_gate = ReplicatedLinear(config.hidden_size,
                                                       1,
                                                       bias=False,
                                                       params_dtype=self.params_dtype,
                                                       quant_config=None)


    def forward(self, hidden_states: torch.Tensor, residual: Optional[torch.Tensor] = None) -> torch.Tensor:
        num_tokens, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)
        shared_output = None
        if self.shared_expert is not None:
            shared_output = self.shared_expert(hidden_states)
            if self.shared_expert_gate is not None:
                gate_output = self.shared_expert_gate(hidden_states)
                shared_output = F.sigmoid(gate_output[0]) * shared_output

        # router_logits: (num_tokens, n_experts)
        router_logits, _ = self.gate(hidden_states)
        final_hidden_states = self.forward_experts(hidden_states, router_logits, residual)

        if shared_output is not None:
            final_hidden_states = final_hidden_states + shared_output
        if self.tp_size > 1:
            final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)

        return final_hidden_states.view(num_tokens, hidden_dim)


def vllm__module_executor__models__qwen2moe__Qwen2MoeAttention__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
    =============================
    @brief: pack q & k to fit tmo.apply_rotary
    '''
    qk, _ = qkv.split([self.q_size + self.kv_size, self.kv_size], dim=-1)
    self.rotary_emb(positions, qk.view(-1, self.num_heads + self.num_kv_heads, self.head_dim))
    '''
    ==================
    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__qwen2moe__Qwen2MoeDecoderLayer____init__(
    self,
    config: PretrainedConfig,
    layer_idx: int,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
) -> None:
    super(Qwen2MoeDecoderLayer, self).__init__()
    self.hidden_size = config.hidden_size
    rope_theta = getattr(config, "rope_theta", 10000)
    rope_scaling = getattr(config, "rope_scaling", None)
    max_position_embeddings = getattr(config, "max_position_embeddings",
                                        8192)
    self.self_attn = Qwen2MoeAttention(
        hidden_size=self.hidden_size,
        num_heads=config.num_attention_heads,
        num_kv_heads=config.num_key_value_heads,
        rope_theta=rope_theta,
        rope_scaling=rope_scaling,
        max_position_embeddings=max_position_embeddings,
        cache_config=cache_config,
        quant_config=quant_config,
    )

    # Note: Qwen/Qwen2-57B-A14B-Instruct does not have
    # `mlp_only_layers` in the config.
    mlp_only_layers = ([] if not hasattr(config, "mlp_only_layers") else
                        config.mlp_only_layers)
    if (layer_idx not in mlp_only_layers) and (
            config.num_experts > 0 and
        (layer_idx + 1) % config.decoder_sparse_step == 0):
        self.mlp = Qwen2MoeSparseMoeBlock(config=config,
                                            quant_config=quant_config)
    else:
        '''
        =============================
        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=config.hidden_act,
                               up_proj_name='gate_up_proj',
                               is_gated=True,
                               down_proj_name='down_proj',
                               bias=False,
                               quant_config=quant_config)
        '''
        ==================
        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. For moe
        model, we only do quant fusion in attn block.
    '''
    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.quant_fusion_attn_layernorm = None
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


def vllm__module_executor__models__qwen2moe__Qwen2MoeForCausalLM__load_weights(
        self,
        weights: Iterable[Tuple[str, torch.Tensor]]):
    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: pack params and cal start expert id
    '''
    for name, m in self.model.named_modules():
        if isinstance(m, SparseMoeMlp):
            m.pack_params()

    start_expert_id = 0
    '''
    ==================
    End of MLU Hijack
    ==================
    '''
    stacked_params_mapping = [
        # (param_name, shard_name, shard_id)
        ("qkv_proj", "q_proj", "q"),
        ("qkv_proj", "k_proj", "k"),
        ("qkv_proj", "v_proj", "v"),
        ("gate_up_proj", "gate_proj", 0),
        ("gate_up_proj", "up_proj", 1),
    ]

    '''
    =============================
    Modify by vllm_mlu
    =============================
    @brief: delete expert_params_mapping for no useless
    '''
    '''
    ==================
    End of MLU Hijack
    ==================
    '''

    params_dict = dict(self.named_parameters())
    for name, loaded_weight in weights:
        if "rotary_emb.inv_freq" in name:
            continue
        '''
        =============================
        Modify by vllm_mlu
        =============================
        @brief: replace expert_id in weight to named_expert_id in params_dict
        '''
        if start_expert_id > 0 and "mlp.experts." in name:
            expert_str = re.search(r'experts\.\d+', name).group(0)
            expert_id=int(expert_str.split(".")[1])
            named_expert_id = expert_id - start_expert_id
            old_expert_name = f"experts.{expert_id}"
            new_expert_name = f"experts.{named_expert_id}"
            name = name.replace(old_expert_name, new_expert_name)
        '''
        ==================
        End of MLU Hijack
        ==================
        '''
        for (param_name, weight_name, shard_id) in stacked_params_mapping:
            if weight_name not in name:
                continue
            '''
            =============================
            Modify by vllm_mlu
            =============================
            @brief: delete if "mlp.experts" in name: continue condition
            '''
            '''
            ==================
            End of MLU Hijack
            ==================
            '''
            name = name.replace(weight_name, param_name)
            # Skip loading extra bias for GPTQ models.
            if ((name.endswith(".bias") or name.endswith("_bias"))
                        and name not in params_dict):
                continue
            # Skip layers on other devices.
            if is_pp_missing_parameter(name, self):
                continue
            '''
            =============================
            Modify by vllm_mlu
            =============================
            @brief: add expert skiped condition and delete useless if name not in params_dict: continue condition
            '''
            # Skip experts that are not assigned to this worker.
            if (("mlp.experts." in name or "mlp.shared_expert." in name or "mlp.shared_expert_gate." in name)
                    and name not in params_dict):
                continue
            '''
            ==================
            End of MLU Hijack
            ==================
            '''
            param = params_dict[name]
            weight_loader = param.weight_loader
            weight_loader(param, loaded_weight, shard_id)
            break
        else:
            '''
            =============================
            Modify by vllm_mlu
            =============================
            @brief: delete for mapping in expert_params_mapping condition
            '''
            '''
            ==================
            End of MLU Hijack
            ==================
            '''
            # Skip loading extra bias for GPTQ models.
            if ((name.endswith(".bias") or name.endswith("_bias"))
                            and name not in params_dict):
                continue
            # Skip layers on other devices.
            if is_pp_missing_parameter(name, self):
                continue
            # Remapping the name of FP8 kv-scale.
            if name.endswith("kv_scale"):
                remapped_kv_scale_name = name.replace(
                    ".kv_scale", ".attn.kv_scale")
                if remapped_kv_scale_name not in params_dict:
                    print_warning_once(
                        "Found kv scale in the checkpoint "
                        f"(e.g. {name}), but not found the expected "
                        f"name in the model "
                        f"(e.g. {remapped_kv_scale_name}). "
                        "kv-scale is not loaded.")
                    continue
                else:
                    name = remapped_kv_scale_name
            '''
            =============================
            Modify by vllm_mlu
            =============================
            @brief: add expert skiped condition
            '''
            # Skip experts that are not assigned to this worker.
            if (("mlp.experts." in name or "mlp.shared_expert." in name or "mlp.shared_expert_gate." in name)
                    and name not in params_dict):
                continue
            '''
            ==================
            End of MLU Hijack
            ==================
            '''
            param = params_dict[name]
            weight_loader = getattr(param, "weight_loader",
                                    default_weight_loader)
            weight_loader(param, loaded_weight)


def vllm__module_executor__models__qwen2moe__Qwen2MoeDecoderLayer__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
    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
            else:
                attn_quant_scale = self.self_attn.qkv_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)
        attn_layernorm = self.quant_fusion_attn_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=self.post_attention_layernorm,
                                      mlp=self.mlp,
                                      input_norm_fuse_en=self.is_per_token_sq_perf_cases)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


def vllm__module_executor__models__qwen2moe__Qwen2MoeModel__forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        kv_caches: List[torch.Tensor],
        attn_metadata: AttentionMetadata,
        intermediate_tensors: Optional[IntermediateTensors] = 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)
    '''
    ==================
    End of MLU Hijack
    ==================
    '''


MluHijackObject.apply_hijack(Qwen2MoeAttention,
                             Qwen2MoeAttention.forward,
                             vllm__module_executor__models__qwen2moe__Qwen2MoeAttention__forward)
MluHijackObject.apply_hijack(Qwen2MoeDecoderLayer,
                             Qwen2MoeDecoderLayer.__init__,
                             vllm__module_executor__models__qwen2moe__Qwen2MoeDecoderLayer____init__)
MluHijackObject.apply_hijack(Qwen2MoeForCausalLM,
                             Qwen2MoeForCausalLM.load_weights,
                             vllm__module_executor__models__qwen2moe__Qwen2MoeForCausalLM__load_weights)
MluHijackObject.apply_hijack(Qwen2MoeDecoderLayer,
                             Qwen2MoeDecoderLayer.forward,
                             vllm__module_executor__models__qwen2moe__Qwen2MoeDecoderLayer__forward)
MluHijackObject.apply_hijack(Qwen2MoeModel,
                             Qwen2MoeModel.forward,
                             vllm__module_executor__models__qwen2moe__Qwen2MoeModel__forward)
