# SPDX-License-Identifier: Apache-2.0
from typing import Any, Callable, Dict, List, Optional

import torch
from torch.nn.parameter import Parameter
from vllm.distributed import get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size
from vllm.model_executor.layers.fused_moe import (FusedMoE, FusedMoEMethodBase,
                                                  FusedMoeWeightScaleSupported)
from vllm.model_executor.layers.linear import (LinearBase, LinearMethodBase,
                                               UnquantizedLinearMethod)
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig, QuantizeMethodBase)
#from vllm.model_executor.layers.fused_moe.optimus_moe import (  # noqa: F401
#    optimus_moe_int8)
from vllm.model_executor.utils import set_weight_attrs

class GroupwiseQuantConfig(QuantizationConfig):
    """Config class for Groupwise Quantization.
    """

    def __init__(
        self,
        weight_bits: int,
        group_size: int,
        symmetric: bool = False,
        bf16_blocks: Optional[list] = None,
        int8_blocks: Optional[list] = None,
        weight_dtype: Optional[
            str] = None,  # Literal["int8", "fp8_e4m3", "fp6", "int4"] = "int8",
        # FIXME: hack for mixed precision quantization
        extra_quant_configs: Optional[dict] = None,
    ) -> None:
        self.weight_bits = weight_bits
        self.group_size = group_size
        self.symmetric = symmetric
        self.bf16_blocks = bf16_blocks if bf16_blocks else []
        self.int8_blocks = int8_blocks if int8_blocks else []
        self.extra_quant_configs = extra_quant_configs

        if self.weight_bits == 4:
            self.pack_factor = 32 // self.weight_bits
        else:
            self.pack_factor = 1

        if not weight_dtype:
            if weight_bits == 8:
                self.weight_dtype = "int8"  # fp8e4m3 must explicitly set
            elif weight_bits == 6:
                self.weight_dtype = "fp6"
            elif weight_bits == 4:
                self.weight_dtype = "int4"
            else:
                raise ValueError(f"Unsupported weight bits: {weight_bits}")
        else:
            self.weight_dtype = weight_dtype

    def __repr__(self) -> str:
        return (f"GroupwiseQuantConfig(weight_bits={self.weight_bits}, "
                f"group_size={self.group_size})")

    @classmethod
    def get_name(cls) -> str:
        return "groupwise_quant"

    @classmethod
    def get_supported_act_dtypes(cls) -> List[torch.dtype]:
        return [torch.half, torch.bfloat16]

    @classmethod
    def get_min_capability(cls) -> int:
        # The Groupwise Quant kernel only supports Ampere or newer GPUs.
        return 80

    @classmethod
    def get_config_filenames(cls) -> List[str]:
        return [
            "quant_config.json",
        ]

    @classmethod
    def from_config(cls, config: Dict[str, Any]) -> "GroupwiseQuantConfig":
        weight_bits = cls.get_from_keys(config, ["w_bit", "bits"])
        group_size = cls.get_from_keys(config, ["q_group_size", "group_size"])
        bf16_blocks = config.get("bf16_blocks", [])
        int8_blocks = config.get("int8_blocks", [])
        weight_dtype = config.get("weight_type")
        extra_quant_configs = config.get("extra_quant_configs", {})
        return cls(weight_bits,
                   group_size,
                   bf16_blocks=bf16_blocks,
                   int8_blocks=int8_blocks,
                   weight_dtype=weight_dtype,
                   extra_quant_configs=extra_quant_configs)

    def get_quant_method(self,
                         layer: torch.nn.Module,
                         prefix: str = "") -> Optional["QuantizeMethodBase"]:
        if isinstance(layer, LinearBase):
            block_index = int(prefix.split("layers.")[1].split(".")[0])
            layer_name = prefix.split(".")[-1]

            if block_index in self.bf16_blocks:
                return UnquantizedLinearMethod()

            if self.extra_quant_configs:
                for config in self.extra_quant_configs:
                    if block_index in config[
                            "block_indices"] and layer_name in config[
                                "target_modules"]:
                        return GroupwiseQuantLinearMethod(
                            GroupwiseQuantConfig(
                                weight_bits=config["weight_bit"],
                                group_size=config["group_size"]
                                or self.group_size,
                                weight_dtype=config["weight_type"],
                                extra_quant_configs=self.extra_quant_configs))
                # no specific config for this layer means no quantization
                return UnquantizedLinearMethod()
            else:
                # Compatible with old config
                return GroupwiseQuantLinearMethod(self)
        elif isinstance(layer, FusedMoE):
            # For MoE layers, only support 8-bit quantization
            if self.weight_bits == 8:
                return GroupwiseInt8MoeMethod(self)
            else:
                raise ValueError(f"Unsupported weight bits for MoE: {self.weight_bits}. Only 8-bit is supported.")

        return None


class GroupwiseQuantLinearMethod(LinearMethodBase):
    """Linear method for GroupwiseQuant.

    Args:
        quant_config: The groupwise_quant quantization config.
    """

    def __init__(self, quant_config: GroupwiseQuantConfig) -> None:
        self.quant_config = quant_config
        self.sm = torch.cuda.get_device_capability()

    def create_weights(self,
                       layer: torch.nn.Module,
                       input_size_per_partition: int,
                       output_partition_sizes: List[int],
                       input_size: int,
                       output_size: int,
                       params_dtype: torch.dtype,
                       num_experts: Optional[int] = None,
                       **extra_weight_attrs):
        assert input_size_per_partition % self.quant_config.group_size == 0
        output_size_per_partition = sum(output_partition_sizes)
        assert output_size_per_partition % self.quant_config.pack_factor == 0

        layer_keys = dir(layer)
        has_num_experts = any("num_experts" in name for name in layer_keys)
        if not has_num_experts:
            layer.register_parameter("num_experts", None)
        if self.quant_config.weight_bits == 8:
            assert input_size_per_partition % self.quant_config.group_size == 0
            if num_experts:
                weight_shape = [
                    num_experts, input_size_per_partition,
                    output_size_per_partition
                ]
                scale_shape = [
                    num_experts,
                    input_size_per_partition // self.quant_config.group_size,
                    output_size_per_partition,
                ]
            else:
                weight_shape = [
                    input_size_per_partition, output_size_per_partition
                ]
                scale_shape = [
                    input_size_per_partition // self.quant_config.group_size,
                    output_size_per_partition,
                ]
            qweight = Parameter(
                torch.empty(
                    *weight_shape,
                    device="cuda",
                    dtype=torch.int8,
                ),
                requires_grad=False,
            )

            scales = Parameter(
                torch.empty(
                    *scale_shape,
                    device="cuda",
                    dtype=params_dtype,
                ),
                requires_grad=False,
            )
            if num_experts:
                set_weight_attrs(qweight, {
                    "input_dim": 1,
                    "output_dim": 2,
                })
                set_weight_attrs(scales, {
                    "input_dim": 1,
                    "output_dim": 2,
                })
            else:
                set_weight_attrs(qweight, {
                    "input_dim": 0,
                    "output_dim": 1,
                })
                set_weight_attrs(scales, {
                    "input_dim": 0,
                    "output_dim": 1,
                })

            layer.register_parameter("qweight", qweight)
            set_weight_attrs(qweight, extra_weight_attrs)
            layer.register_parameter("scales", scales)
            set_weight_attrs(scales, extra_weight_attrs)
        else:
            raise NotImplementedError

    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
        if not hasattr(layer, "qweight"):
            return
        if self.quant_config.weight_bits == 8:
            num_experts = layer.num_experts
            qweight = layer.qweight
            if num_experts:
                for i in range(num_experts):
                    qweight[i].copy_(qweight[i].contiguous())
            else:
                qweight.copy_(qweight.contiguous())         
        else:
            raise NotImplementedError
        

    def apply(self,
            layer: torch.nn.Module,
            x: torch.Tensor,
            bias: Optional[torch.Tensor] = None,
            residual: Optional[torch.Tensor] = None,
            output: Optional[torch.Tensor] = None,
            expert_idx: Optional[int] = None) -> torch.Tensor:
        if self.quant_config.weight_bits == 8:
            qweight = layer.qweight
            scales = layer.scales
            num_experts = layer.num_experts

            if num_experts:
                assert expert_idx is not None, "expert_idx is None"
                qweight = qweight[expert_idx]
                scales = scales[expert_idx]

            group_size = self.quant_config.group_size
            input_size_per_partition = qweight.size(0)  
            output_size_per_partition = qweight.size(1)

            qweight = qweight.to(torch.float32) 
            scales = scales.to(torch.float32)

            scales_expanded = scales.repeat_interleave(group_size, dim=0)
            scales_expanded = scales_expanded[:input_size_per_partition]

            weight = qweight * scales_expanded

            weight = weight.to(x.dtype)
            if residual is not None:
                assert output is None or output is residual
                if get_tensor_model_parallel_world_size() > 1 and get_tensor_model_parallel_rank() != 0:
                    beta = 0.0
                else:
                    beta = 1.0
                if x.dim() == 2:
                    torch.addmm(residual, x, weight.t(), beta=beta, out=residual)
                elif x.dim() >= 3:
                    hx = x.size(-1)
                    hr = residual.size(-1)
                    torch.addmm(residual.view(-1, hr),
                                x.view(-1, hx),
                                weight.t(),
                                beta=beta,
                                out=residual.view(-1, hr))
                else:
                    raise AssertionError(f"unrecognized tensor dimensions: {x.dim()}")
                if bias is not None:
                    residual += bias
                return residual
            else:
                if output is not None:
                    if bias is not None:  # always separate bias add when output is provided
                        torch.matmul(x, weight.t(), out=output)
                        output.add_(bias)
                        return output
                    return torch.matmul(x, weight.t(), out=output)
                else:
                    return torch.nn.functional.linear(x, weight.t(), bias)
        else:
            raise NotImplementedError
        

class GroupwiseInt8MoeMethod(FusedMoEMethodBase):
    """MoE method for Groupwise INT8 quantization.
    
    Args:
        quant_config: The groupwise quantization config.
    """
    
    def __init__(self, quant_config: GroupwiseQuantConfig):
        self.quant_config = quant_config
        assert self.quant_config.weight_bits == 8, "Only 8-bit quantization is supported for GroupwiseInt8MoeMethod"
        
    def create_weights(self, layer: torch.nn.Module, num_experts: int, hidden_size: int,
                       intermediate_size_per_partition: int,
                       params_dtype: torch.dtype, **extra_weight_attrs):
        extra_weight_attrs.update({
            "is_transposed":
            True,
            "quant_method":
            FusedMoeWeightScaleSupported.GROUP.value,
        })
        # Create INT8 weights
        w13_weight = torch.nn.Parameter(torch.empty(
            num_experts,
            hidden_size,
            2 * intermediate_size_per_partition,
            dtype=torch.int8),
                                        requires_grad=False)
        layer.register_parameter("w13_weight", w13_weight)
        set_weight_attrs(w13_weight, {
            "input_dim": 1,
            "output_dim": 2,
        })
        set_weight_attrs(w13_weight, extra_weight_attrs)

        w2_weight = torch.nn.Parameter(torch.empty(
            num_experts,
            intermediate_size_per_partition,
            hidden_size,
            dtype=torch.int8),
                                       requires_grad=False)
        layer.register_parameter("w2_weight", w2_weight)
        set_weight_attrs(w2_weight, {
            "input_dim": 1,
            "output_dim": 2,
        })
        set_weight_attrs(w2_weight, extra_weight_attrs)

        # Create scales for groupwise quantization
        w13_weight_scale = torch.nn.Parameter(torch.empty(
            num_experts,
            hidden_size // self.quant_config.group_size,
            2 * intermediate_size_per_partition,
            dtype=params_dtype),
                                              requires_grad=False)
        layer.register_parameter("w13_weight_scale", w13_weight_scale)
        set_weight_attrs(w13_weight_scale, {
            "input_dim": 1,
            "output_dim": 2,
        })
        set_weight_attrs(w13_weight_scale, extra_weight_attrs)

        w2_weight_scale = torch.nn.Parameter(torch.empty(
            num_experts,
            intermediate_size_per_partition // self.quant_config.group_size,
            hidden_size,
            dtype=params_dtype),
                                             requires_grad=False)
        layer.register_parameter("w2_weight_scale", w2_weight_scale)
        set_weight_attrs(w2_weight_scale, {
            "input_dim": 1,
            "output_dim": 2,
        })
        set_weight_attrs(w2_weight_scale, extra_weight_attrs)

    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
        # Process weights similar to GroupwiseQuantLinearMethod for 8-bit case
        # num_experts = layer.w13_weight.shape[0]
        
        # for expert in range(num_experts):
        #     # Preprocess w13 weight (gate and up combined)
        #     layer.w13_weight[expert].copy_(
        #         torch.ops.Optimus.FpAIntBPreprocessWeightGPU(
        #             layer.w13_weight[expert].t().contiguous(), torch.int8))
            
        #     # Preprocess w2 weight (down)
        #     layer.w2_weight[expert].copy_(
        #         torch.ops.Optimus.FpAIntBPreprocessWeightGPU(
        #             layer.w2_weight[expert].t().contiguous(), torch.int8))
        pass
        
    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
        router_logits: torch.Tensor,
        top_k: int,
        renormalize: bool,
        use_grouped_topk: bool = False,
        topk_group: Optional[int] = None,
        num_expert_group: Optional[int] = None,
        global_num_experts: int = -1,
        expert_map: Optional[torch.Tensor] = None,
        custom_routing_function: Optional[Callable] = None,
        scoring_func: str = "softmax",
        e_score_correction_bias: Optional[torch.Tensor] = None,
        apply_router_weight_on_input: bool = False,
        enable_eplb: bool = False,
        expert_load_view: Optional[torch.Tensor] = None,
        activation: str = "silu",
        use_nn_moe: Optional[bool] = False,
        routed_scaling_factor: Optional[float] = None,
        use_fused_gate: Optional[bool] = False,
        logical_to_physical_map: Optional[torch.Tensor] = None,
        logical_replica_count: Optional[torch.Tensor] = None,
        **_            
    ) -> torch.Tensor:
        if enable_eplb:
            raise NotImplementedError(
                "EPLB not supported for `ExpertsInt8MoEMethod` yet.")

        from vllm.model_executor.layers.fused_moe.fused_moe_step3vw8a16 import fused_experts

        topk_weights, topk_ids = FusedMoE.select_experts(
            hidden_states=x,
            router_logits=router_logits,
            use_grouped_topk=use_grouped_topk,
            top_k=top_k,
            renormalize=renormalize,
            topk_group=topk_group,
            num_expert_group=num_expert_group,
            custom_routing_function=custom_routing_function,
            scoring_func=scoring_func,
            e_score_correction_bias=e_score_correction_bias)
#复用bf16 moe逻辑
        return fused_experts(
            x,
            layer.w13_weight,
            layer.w2_weight,
            topk_weights=topk_weights,
            topk_ids=topk_ids,
            inplace=True,
            activation=activation,
            use_nn_moe = True,
            global_num_experts=global_num_experts,
            apply_router_weight_on_input=apply_router_weight_on_input,
            expert_map=expert_map,
            w1_scale=layer.w13_weight_scale,
            w2_scale=layer.w2_weight_scale,
            use_step3v_w8a16 = True)


