22
vllm_ascend/_310p/quantization/__init__.py
Normal file
22
vllm_ascend/_310p/quantization/__init__.py
Normal file
@@ -0,0 +1,22 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from vllm_ascend._310p.quantization.modelslim_config import AscendModelSlimConfig310
|
||||
|
||||
__all__ = [
|
||||
"AscendModelSlimConfig310",
|
||||
]
|
||||
23
vllm_ascend/_310p/quantization/methods/__init__.py
Normal file
23
vllm_ascend/_310p/quantization/methods/__init__.py
Normal file
@@ -0,0 +1,23 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from . import (
|
||||
w8a8_dynamic, # noqa: F401
|
||||
w8a8_static, # noqa: F401
|
||||
w8a8s, # noqa: F401
|
||||
w8a8sc, # noqa: F401
|
||||
)
|
||||
41
vllm_ascend/_310p/quantization/methods/registry.py
Normal file
41
vllm_ascend/_310p/quantization/methods/registry.py
Normal file
@@ -0,0 +1,41 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 310P-local registry: maps (quant_type, layer_type) -> SchemeClass
|
||||
_SCHEME_REGISTRY: dict[tuple[str, str], type[Any]] = {}
|
||||
|
||||
|
||||
def register_scheme(quant_type: str, layer_type: str):
|
||||
"""Decorator to register a 310P quantization scheme."""
|
||||
|
||||
def decorator(cls: type[Any]) -> type[Any]:
|
||||
key = (quant_type, layer_type)
|
||||
if key in _SCHEME_REGISTRY:
|
||||
raise ValueError(
|
||||
f"[310P] Scheme already registered for {quant_type}/{layer_type}: {_SCHEME_REGISTRY[key].__name__}"
|
||||
)
|
||||
_SCHEME_REGISTRY[key] = cls
|
||||
return cls
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_scheme_class(quant_type: str, layer_type: str) -> type[Any] | None:
|
||||
"""Get 310P scheme class for given quant_type and layer_type."""
|
||||
return _SCHEME_REGISTRY.get((quant_type, layer_type))
|
||||
44
vllm_ascend/_310p/quantization/methods/w8a8_base.py
Normal file
44
vllm_ascend/_310p/quantization/methods/w8a8_base.py
Normal file
@@ -0,0 +1,44 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_ascend.quantization.methods.base import AscendLinearScheme
|
||||
|
||||
|
||||
class AscendW8A8Linear310pScheme(AscendLinearScheme):
|
||||
def get_weight(
|
||||
self,
|
||||
input_size: int,
|
||||
output_size: int,
|
||||
params_dtype: torch.dtype = torch.float16,
|
||||
) -> dict[str, Any]:
|
||||
return {"weight": torch.empty(output_size, input_size, dtype=torch.int8)}
|
||||
|
||||
def get_pertensor_param(self, params_dtype: torch.dtype, **kwargs: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"input_scale": torch.empty(1, dtype=params_dtype),
|
||||
"input_offset": torch.empty(1, dtype=torch.int8),
|
||||
}
|
||||
|
||||
def get_perchannel_param(self, output_size: int, params_dtype: torch.dtype) -> dict[str, Any]:
|
||||
return {
|
||||
"quant_bias": torch.empty(output_size, dtype=torch.int32),
|
||||
"deq_scale": torch.empty(output_size, dtype=torch.int64),
|
||||
}
|
||||
218
vllm_ascend/_310p/quantization/methods/w8a8_dynamic.py
Normal file
218
vllm_ascend/_310p/quantization/methods/w8a8_dynamic.py
Normal file
@@ -0,0 +1,218 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.distributed import get_ep_group
|
||||
|
||||
from vllm_ascend._310p.fused_moe.experts_selector import select_experts
|
||||
from vllm_ascend.ascend_forward_context import _EXTRA_CTX
|
||||
from vllm_ascend.ops.fused_moe.experts_selector import zero_experts_compute
|
||||
from vllm_ascend.ops.fused_moe.moe_runtime_args import build_fused_experts_input
|
||||
from vllm_ascend.quantization.methods.base import AscendMoEScheme, QuantType
|
||||
from vllm_ascend.utils import maybe_trans_nz
|
||||
|
||||
from .registry import register_scheme
|
||||
from .w8a8_base import AscendW8A8Linear310pScheme
|
||||
|
||||
|
||||
@register_scheme("W8A8_DYNAMIC", "moe")
|
||||
class AscendW8A8DynamicFusedMoEMethod310(AscendMoEScheme):
|
||||
"""310P-only FusedMoE method for Ascend W8A8_DYNAMIC.
|
||||
|
||||
Notes:
|
||||
- This scheme is discovered via 310P local registry.
|
||||
"""
|
||||
|
||||
# Declare the quantization type for this scheme
|
||||
quant_type: QuantType = QuantType.W8A8
|
||||
|
||||
def __init__(self):
|
||||
self.ep_group = get_ep_group()
|
||||
vllm_config = get_current_vllm_config()
|
||||
self.in_dtype = vllm_config.model_config.dtype
|
||||
|
||||
def get_weight(
|
||||
self, num_experts: int, intermediate_size_per_partition: int, hidden_sizes: int, params_dtype: torch.dtype
|
||||
) -> dict[str, Any]:
|
||||
param_dict = {}
|
||||
# Fused gate_up_proj (column parallel)
|
||||
param_dict["w13_weight"] = torch.empty(
|
||||
num_experts, 2 * intermediate_size_per_partition, hidden_sizes, dtype=torch.int8
|
||||
)
|
||||
# down_proj (row parallel)
|
||||
param_dict["w2_weight"] = torch.empty(
|
||||
num_experts, hidden_sizes, intermediate_size_per_partition, dtype=torch.int8
|
||||
)
|
||||
return param_dict
|
||||
|
||||
def get_dynamic_quant_param(
|
||||
self, num_experts: int, intermediate_size_per_partition: int, hidden_sizes: int, params_dtype: torch.dtype
|
||||
) -> dict[str, Any]:
|
||||
param_dict = {}
|
||||
param_dict["w13_weight_scale"] = torch.empty(
|
||||
num_experts, 2 * intermediate_size_per_partition, 1, dtype=torch.float32
|
||||
)
|
||||
param_dict["w13_weight_offset"] = torch.empty(
|
||||
num_experts, 2 * intermediate_size_per_partition, 1, dtype=params_dtype
|
||||
)
|
||||
param_dict["w2_weight_scale"] = torch.empty(num_experts, hidden_sizes, 1, dtype=torch.float32)
|
||||
param_dict["w2_weight_offset"] = torch.empty(num_experts, hidden_sizes, 1, dtype=params_dtype)
|
||||
return param_dict
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
router_logits: torch.Tensor,
|
||||
top_k: int,
|
||||
renormalize: bool,
|
||||
use_grouped_topk: bool = False,
|
||||
num_experts: int = -1,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
topk_group: int | None = None,
|
||||
num_expert_group: int | None = None,
|
||||
custom_routing_function: Callable | None = None,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0,
|
||||
e_score_correction_bias: torch.Tensor | None = None,
|
||||
is_prefill: bool = True,
|
||||
enable_force_load_balance: bool = False,
|
||||
log2phy: torch.Tensor | None = None,
|
||||
global_redundant_expert_num: int = 0,
|
||||
pertoken_scale: Any | None = None,
|
||||
activation: str = "silu",
|
||||
apply_router_weight_on_input: bool = False,
|
||||
mc2_mask: torch.Tensor | None = None,
|
||||
tid2eid: Any | None = None,
|
||||
) -> torch.Tensor:
|
||||
zero_expert_num = getattr(layer, "zero_expert_num", 0)
|
||||
zero_expert_type = getattr(layer, "zero_expert_type", None)
|
||||
|
||||
topk_weights, topk_ids = select_experts(
|
||||
hidden_states=x,
|
||||
router_logits=router_logits,
|
||||
top_k=top_k,
|
||||
use_grouped_topk=use_grouped_topk,
|
||||
renormalize=renormalize,
|
||||
topk_group=topk_group,
|
||||
num_expert_group=num_expert_group,
|
||||
custom_routing_function=custom_routing_function,
|
||||
scoring_func=scoring_func,
|
||||
routed_scaling_factor=routed_scaling_factor,
|
||||
e_score_correction_bias=e_score_correction_bias,
|
||||
global_num_experts=num_experts,
|
||||
)
|
||||
|
||||
if zero_expert_num > 0 and zero_expert_type is not None:
|
||||
topk_ids, topk_weights, zero_expert_result = zero_experts_compute(
|
||||
expert_indices=topk_ids,
|
||||
expert_scales=topk_weights,
|
||||
num_experts=num_experts,
|
||||
zero_expert_type=zero_expert_type,
|
||||
hidden_states=x,
|
||||
)
|
||||
|
||||
topk_weights = topk_weights.to(self.in_dtype)
|
||||
|
||||
moe_comm_method = _EXTRA_CTX.moe_comm_method
|
||||
|
||||
final_hidden_states = moe_comm_method.fused_experts(
|
||||
fused_experts_input=build_fused_experts_input(
|
||||
hidden_states=x,
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
w1=layer.w13_weight,
|
||||
w2=layer.w2_weight,
|
||||
quant_type=self.quant_type,
|
||||
dynamic_eplb=False,
|
||||
expert_map=expert_map,
|
||||
apply_router_weight_on_input=apply_router_weight_on_input,
|
||||
w1_scale=layer.w13_weight_scale,
|
||||
w2_scale=layer.w2_weight_scale,
|
||||
),
|
||||
)
|
||||
if zero_expert_num > 0 and zero_expert_type is not None:
|
||||
final_hidden_states += zero_expert_result
|
||||
return final_hidden_states
|
||||
|
||||
def process_weights_after_loading(self, layer):
|
||||
layer.w13_weight.data = maybe_trans_nz(layer.w13_weight.data)
|
||||
layer.w2_weight.data = maybe_trans_nz(layer.w2_weight.data)
|
||||
layer.w13_weight_scale.data = layer.w13_weight_scale.data.view(layer.w13_weight_scale.data.shape[0], -1)
|
||||
layer.w13_weight_offset.data = layer.w13_weight_offset.data.view(layer.w13_weight_offset.data.shape[0], -1)
|
||||
layer.w2_weight_scale.data = layer.w2_weight_scale.data.view(layer.w2_weight_scale.data.shape[0], -1)
|
||||
layer.w2_weight_offset.data = layer.w2_weight_offset.data.view(layer.w2_weight_offset.data.shape[0], -1)
|
||||
|
||||
|
||||
@register_scheme("W8A8_DYNAMIC", "linear")
|
||||
class AscendW8A8DynamicLinearMethod310(AscendW8A8Linear310pScheme):
|
||||
"""310P-only W8A8 dynamic linear scheme.
|
||||
|
||||
Notes:
|
||||
- This scheme is discovered via 310P local registry.
|
||||
"""
|
||||
|
||||
def get_perchannel_param(
|
||||
self,
|
||||
output_size: int,
|
||||
params_dtype: torch.dtype,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {}
|
||||
params["weight_scale"] = torch.empty(output_size, 1, dtype=torch.float32)
|
||||
params["weight_offset"] = torch.empty(output_size, 1, dtype=torch.float32)
|
||||
return params
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
tp_rank: int | None = 0,
|
||||
) -> torch.Tensor:
|
||||
# NOTE(310P):
|
||||
# - There is an accuracy issue currently, which is expected to be fixed in the next version.
|
||||
quantized_x, pertoken_scale = torch_npu.npu_dynamic_quant(x)
|
||||
need_unsqz = False
|
||||
if pertoken_scale.dim() == 2:
|
||||
need_unsqz = True
|
||||
quantized_x = quantized_x.squeeze(dim=1)
|
||||
pertoken_scale = pertoken_scale.squeeze(dim=1)
|
||||
|
||||
# NOTE(310P):
|
||||
# - Currently, W8A8 dynamic quantization supports only symmetric quantization.
|
||||
output = torch_npu.npu_quant_matmul(
|
||||
quantized_x,
|
||||
layer.weight.data,
|
||||
layer.weight_scale,
|
||||
pertoken_scale=pertoken_scale,
|
||||
bias=bias,
|
||||
output_dtype=x.dtype,
|
||||
)
|
||||
if need_unsqz:
|
||||
output = output.unsqueeze(dim=1)
|
||||
return output
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
# cast quantized weight tensors in NZ format for higher inference speed
|
||||
layer.weight.data = maybe_trans_nz(layer.weight.data).transpose(0, 1)
|
||||
layer.weight_scale.data = layer.weight_scale.data.flatten()
|
||||
layer.weight_offset.data = layer.weight_offset.data.flatten()
|
||||
98
vllm_ascend/_310p/quantization/methods/w8a8_static.py
Normal file
98
vllm_ascend/_310p/quantization/methods/w8a8_static.py
Normal file
@@ -0,0 +1,98 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
from vllm_ascend.utils import maybe_trans_nz
|
||||
|
||||
from .registry import register_scheme
|
||||
from .w8a8_base import AscendW8A8Linear310pScheme
|
||||
|
||||
|
||||
@register_scheme("W8A8", "linear")
|
||||
class AscendW8A8LinearMethod310(AscendW8A8Linear310pScheme):
|
||||
"""310P-only W8A8 static linear scheme.
|
||||
|
||||
Notes:
|
||||
- This scheme is discovered via 310P local registry.
|
||||
"""
|
||||
|
||||
def get_perchannel_param(self, output_size: int, params_dtype: torch.dtype) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {}
|
||||
params["quant_bias"] = torch.empty(output_size, dtype=torch.int32)
|
||||
params["deq_scale"] = torch.empty(output_size, dtype=torch.int64)
|
||||
params["weight_scale"] = torch.empty(output_size, 1, dtype=params_dtype)
|
||||
params["weight_offset"] = torch.empty(output_size, 1, dtype=params_dtype)
|
||||
return params
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
tp_rank: int | None = 0,
|
||||
) -> torch.Tensor:
|
||||
if x.dtype != torch.int8:
|
||||
x = torch.ops.vllm.quantize(
|
||||
x,
|
||||
layer.aclnn_input_scale,
|
||||
layer.aclnn_input_scale_reciprocal,
|
||||
layer.aclnn_input_offset,
|
||||
)
|
||||
|
||||
quant_bias = layer.quant_bias if tp_rank == 0 else None
|
||||
|
||||
# NOTE(310P):
|
||||
# - Current torch_npu.npu_quant_matmul on Ascend 310P expects the weight layout in a transposed form
|
||||
# for correct/efficient execution, so we pass `layer.weight.T` here.
|
||||
# - This is a temporary workaround. The planned replacement quant-matmul op will accept the
|
||||
# canonical (non-transposed) weight layout directly, so this explicit transpose will be removed
|
||||
# once that op is enabled on 310P.
|
||||
return torch_npu.npu_quant_matmul(
|
||||
x,
|
||||
layer.weight.data,
|
||||
layer.deq_scale,
|
||||
bias=quant_bias,
|
||||
output_dtype=layer.params_dtype,
|
||||
)
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
expanding_factor = layer.weight.data.shape[1]
|
||||
|
||||
# ---- quant stage tensors ----
|
||||
layer.aclnn_input_scale = torch.nn.Parameter(
|
||||
layer.input_scale.data.repeat(expanding_factor),
|
||||
requires_grad=False,
|
||||
)
|
||||
layer.aclnn_input_scale_reciprocal = torch.nn.Parameter(
|
||||
1.0 / layer.aclnn_input_scale.data,
|
||||
requires_grad=False,
|
||||
)
|
||||
layer.aclnn_input_offset = torch.nn.Parameter(
|
||||
layer.input_offset.data.repeat(expanding_factor),
|
||||
requires_grad=False,
|
||||
).to(layer.aclnn_input_scale.dtype)
|
||||
|
||||
# ---- matmul stage tensor ----
|
||||
layer.weight.data = maybe_trans_nz(layer.weight.data).transpose(0, 1)
|
||||
|
||||
# ---- dequant stage tensors ----
|
||||
layer.weight_scale.data = torch.flatten(layer.weight_scale.data)
|
||||
layer.weight_offset.data = torch.flatten(layer.weight_offset.data)
|
||||
66
vllm_ascend/_310p/quantization/methods/w8a8s.py
Normal file
66
vllm_ascend/_310p/quantization/methods/w8a8s.py
Normal file
@@ -0,0 +1,66 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
from vllm_ascend.utils import maybe_trans_nz
|
||||
|
||||
from .registry import register_scheme
|
||||
from .w8a8_base import AscendW8A8Linear310pScheme
|
||||
|
||||
|
||||
@register_scheme("W8A8S", "linear")
|
||||
class AscendW8A8SLinearMethod310(AscendW8A8Linear310pScheme):
|
||||
"""310P-only W8A8S Sparse linear scheme.
|
||||
|
||||
Notes:
|
||||
- This scheme is discovered via 310P local registry.
|
||||
"""
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
tp_rank: int | None = 0,
|
||||
) -> torch.Tensor:
|
||||
if x.dtype != torch.int8:
|
||||
x = torch.ops.vllm.quantize(
|
||||
x,
|
||||
layer.aclnn_input_scale,
|
||||
layer.aclnn_input_scale_reciprocal,
|
||||
layer.aclnn_input_offset,
|
||||
)
|
||||
|
||||
quant_bias = layer.quant_bias if tp_rank == 0 else None
|
||||
|
||||
return torch_npu.npu_quant_matmul(
|
||||
x,
|
||||
layer.weight.data.transpose(0, 1),
|
||||
layer.deq_scale,
|
||||
bias=quant_bias,
|
||||
output_dtype=layer.params_dtype,
|
||||
)
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
expanding_factor = layer.weight.data.shape[1]
|
||||
layer.aclnn_input_scale = layer.input_scale.data.repeat(expanding_factor)
|
||||
layer.aclnn_input_scale_reciprocal = 1.0 / layer.aclnn_input_scale.data
|
||||
layer.aclnn_input_offset = layer.input_offset.data.repeat(expanding_factor).to(layer.aclnn_input_scale.dtype)
|
||||
layer.weight.data = maybe_trans_nz(layer.weight.data)
|
||||
104
vllm_ascend/_310p/quantization/methods/w8a8sc.py
Normal file
104
vllm_ascend/_310p/quantization/methods/w8a8sc.py
Normal file
@@ -0,0 +1,104 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
from vllm.distributed import get_tensor_model_parallel_rank
|
||||
|
||||
from vllm_ascend.ops.linear import AscendRowParallelLinear
|
||||
|
||||
from .registry import register_scheme
|
||||
from .w8a8_base import AscendW8A8Linear310pScheme
|
||||
|
||||
|
||||
@register_scheme("W8A8SC", "linear")
|
||||
class AscendW8A8SCLinearMethod310(AscendW8A8Linear310pScheme):
|
||||
"""310P-only W8A8SC static linear scheme.
|
||||
|
||||
Notes:
|
||||
- This scheme is discovered via 310P local registry.
|
||||
"""
|
||||
|
||||
def get_weight(
|
||||
self,
|
||||
input_size: int,
|
||||
output_size: int,
|
||||
params_dtype: torch.dtype = torch.float16,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Get the weight tensors for the W8A8SC quantization scheme.
|
||||
|
||||
Args:
|
||||
input_size: Size of the input dimension (k)
|
||||
output_size: Size of the output dimension (n)
|
||||
params_dtype: Data type for parameters, default is torch.float16
|
||||
|
||||
Returns:
|
||||
A dictionary containing:
|
||||
- "weight": The compressed weight tensor with shape [c], where c is greater than 0
|
||||
and not larger than k * n
|
||||
- "index": Compression index generated simultaneously with compressed weights,
|
||||
with shape [x], where x = k_index * n_index * 8, k_index = ceil(k1 / tilingK),
|
||||
n_index = ceil(n1 / tilingN), k1 = k / 32, n1 = n / 16
|
||||
- "info": Compression information with length 5, containing compression block
|
||||
information tilingN, tilingK, original shape of the pre-compression x2 matrix,
|
||||
and identifier for the compression block traversal direction
|
||||
"""
|
||||
self.input_size = input_size
|
||||
index_len = math.ceil(input_size / 256) * math.ceil(output_size / 128) * 8
|
||||
return {
|
||||
"weight": torch.empty(input_size * output_size, dtype=torch.int8),
|
||||
"index": torch.empty(index_len, dtype=torch.int8),
|
||||
"info": torch.empty(5, dtype=torch.int64),
|
||||
}
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
tp_rank: int | None = 0,
|
||||
) -> torch.Tensor:
|
||||
if x.dtype != torch.int8:
|
||||
x = torch.ops.vllm.quantize(
|
||||
x,
|
||||
layer.aclnn_input_scale,
|
||||
layer.aclnn_input_scale_reciprocal,
|
||||
layer.aclnn_input_offset,
|
||||
)
|
||||
|
||||
return torch_npu.npu_matmul_compress_dequant(
|
||||
x,
|
||||
layer.weight,
|
||||
layer.index,
|
||||
layer.quant_bias,
|
||||
layer.deq_scale,
|
||||
)
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
layer.aclnn_input_scale = layer.input_scale.data.repeat(self.input_size)
|
||||
layer.aclnn_input_scale_reciprocal = 1.0 / layer.aclnn_input_scale.data
|
||||
layer.aclnn_input_offset = layer.input_offset.data.repeat(self.input_size).to(layer.aclnn_input_scale.dtype)
|
||||
layer.deq_scale.data = layer.deq_scale.data.unsqueeze(0).to(torch.uint64)
|
||||
layer.quant_bias.data = layer.quant_bias.data.unsqueeze(0)
|
||||
# Only apply bias on row_parallel_linear when tp_rank is 0.
|
||||
# torch_npu.npu_matmul_compress_dequant's quant_bias cannot be None.
|
||||
if isinstance(layer, AscendRowParallelLinear) and get_tensor_model_parallel_rank() != 0:
|
||||
layer.quant_bias.data = torch.zeros_like(layer.quant_bias)
|
||||
151
vllm_ascend/_310p/quantization/modelslim_config.py
Normal file
151
vllm_ascend/_310p/quantization/modelslim_config.py
Normal file
@@ -0,0 +1,151 @@
|
||||
#
|
||||
# Copyright (c) 2026 Huawei Technologies Co., Ltd. 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.
|
||||
# This file is a part of the vllm-ascend project.
|
||||
#
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import logger
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization import register_quantization_config
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
|
||||
from vllm_ascend._310p.quantization.methods.registry import (
|
||||
get_scheme_class,
|
||||
)
|
||||
from vllm_ascend.quantization.method_adapters import AscendFusedMoEMethod, AscendLinearMethod
|
||||
from vllm_ascend.quantization.modelslim_config import (
|
||||
AscendModelSlimConfig,
|
||||
get_quant_type_for_layer,
|
||||
packed_modules_model_mapping,
|
||||
)
|
||||
from vllm_ascend.utils import ASCEND_QUANTIZATION_METHOD, vllm_version_is
|
||||
|
||||
if vllm_version_is("0.23.0"):
|
||||
from vllm.model_executor.layers.fused_moe import FusedMoE
|
||||
else:
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner, RoutedExperts
|
||||
|
||||
|
||||
def _is_fused_moe_layer(layer: torch.nn.Module) -> bool:
|
||||
if vllm_version_is("0.23.0"):
|
||||
return isinstance(layer, FusedMoE)
|
||||
else:
|
||||
return isinstance(layer, (MoERunner, RoutedExperts))
|
||||
|
||||
|
||||
def create_scheme_for_layer(
|
||||
quant_description: dict[str, Any],
|
||||
prefix: str,
|
||||
layer_type: str,
|
||||
packed_modules_mapping: dict[str, Any] | None = None,
|
||||
):
|
||||
"""Create a quantization scheme instance for a layer.
|
||||
|
||||
Args:
|
||||
quant_description: The quantization description dictionary.
|
||||
prefix: The layer prefix.
|
||||
layer_type: The type of layer ("linear", "moe", "attention").
|
||||
packed_modules_mapping: Mapping for packed/fused modules.
|
||||
|
||||
Returns:
|
||||
An instance of the appropriate quantization scheme class.
|
||||
"""
|
||||
logger.info_once("Using vLLM Ascend ModelSlim quantization.")
|
||||
quant_type = get_quant_type_for_layer(quant_description, prefix, layer_type, packed_modules_mapping)
|
||||
|
||||
if quant_type is None:
|
||||
err_msg = f"Could not determine quantization type for layer {prefix} (layer_type={layer_type})."
|
||||
logger.error(err_msg)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
# Use registry to get scheme class
|
||||
scheme_cls = get_scheme_class(quant_type, layer_type)
|
||||
if scheme_cls is not None:
|
||||
return scheme_cls()
|
||||
|
||||
err_msg = f"Unsupported quant_type={quant_type} for layer_type={layer_type}."
|
||||
logger.error(err_msg)
|
||||
raise NotImplementedError(err_msg)
|
||||
|
||||
|
||||
@register_quantization_config(ASCEND_QUANTIZATION_METHOD)
|
||||
class AscendModelSlimConfig310(AscendModelSlimConfig):
|
||||
"""310P override for ModelSlim quantization config.
|
||||
|
||||
- Uses 310P-local scheme registry to create scheme by (quant_type, layer_type).
|
||||
- MUST keep packed_modules_mapping behavior consistent with base, otherwise
|
||||
fused modules (qkv_proj / gate_up_proj) will miss and fallback to base,
|
||||
causing NZ/transpose issues on 310P.
|
||||
"""
|
||||
|
||||
def get_quant_method(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
prefix: str,
|
||||
tid2eid: Any = None,
|
||||
) -> QuantizeMethodBase | None:
|
||||
vllm_config = get_current_vllm_config()
|
||||
model_type = vllm_config.model_config.hf_config.model_type
|
||||
|
||||
if model_type in packed_modules_model_mapping:
|
||||
self.packed_modules_mapping = packed_modules_model_mapping[model_type]
|
||||
|
||||
prefix = self.quant_prefix_mapper(model_type, prefix)
|
||||
|
||||
if isinstance(layer, LinearBase):
|
||||
packed = getattr(self, "packed_modules_mapping", {})
|
||||
if self.is_layer_skipped_ascend(prefix, packed):
|
||||
from vllm_ascend.ops.linear import AscendUnquantizedLinearMethod
|
||||
|
||||
logger.debug("Select AscendUnquantizedLinearMethod for %s (layer=%s)", prefix, "LinearBase")
|
||||
return AscendUnquantizedLinearMethod()
|
||||
|
||||
scheme = create_scheme_for_layer(
|
||||
quant_description=self.quant_description,
|
||||
prefix=prefix,
|
||||
layer_type="linear",
|
||||
packed_modules_mapping=packed,
|
||||
)
|
||||
logger.debug("Select AscendLinearMethod for %s (layer=%s)", prefix, "LinearBase")
|
||||
return AscendLinearMethod(scheme)
|
||||
|
||||
elif _is_fused_moe_layer(layer):
|
||||
if self.is_layer_skipped_ascend(prefix, self.packed_modules_mapping):
|
||||
from vllm_ascend._310p.fused_moe.fused_moe import AscendUnquantizedFusedMoEMethod310
|
||||
|
||||
logger.debug("Select AscendUnquantizedFusedMoEMethod310 for %s (layer=%s)", prefix, "FusedMoE")
|
||||
return AscendUnquantizedFusedMoEMethod310(layer.moe_config)
|
||||
scheme = create_scheme_for_layer(self.quant_description, prefix, "moe", self.packed_modules_mapping)
|
||||
logger.debug("Select AscendFusedMoEMethod for %s (layer=%s)", prefix, "FusedMoE")
|
||||
return AscendFusedMoEMethod(scheme, layer.moe_config)
|
||||
|
||||
elif isinstance(layer, VocabParallelEmbedding):
|
||||
from vllm_ascend._310p.ops.vocab_parallel_embedding import AscendUnquantizedEmbeddingMethod310
|
||||
|
||||
logger.debug(
|
||||
"Select AscendUnquantizedEmbeddingMethod310 for %s (layer=%s)", prefix, "VocabParallelEmbedding"
|
||||
)
|
||||
return AscendUnquantizedEmbeddingMethod310()
|
||||
|
||||
logger.debug("No quant method matched for %s, falling back to base", prefix)
|
||||
return super().get_quant_method(layer, prefix)
|
||||
Reference in New Issue
Block a user