[Hardware][Ascend] Add Wan2.2 MXFP4 UOS, Smooth and W4A8 fallback (#7210)
Signed-off-by: HAAZZZEEEE <wang-taicheng@qq.com>
This commit is contained in:
1 parent
4fab34c8f4
commit
becfefd440
20 files changed
+2435
-184
No files matched your search
@@ -446,6 +446,33 @@ def _disk_marks_serialized(qc_kwargs: dict[str, Any], quant_config: object) -> b
|
||||
return False
|
||||
|
||||
|
||||
_MXFP4_SERIALIZED_FLAGS = {
|
||||
"mxfp4": "is_checkpoint_mxfp4_serialized",
|
||||
"mxfp4_dualscale": "is_checkpoint_serialized",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_serialized_mxfp4_layer_policy(qc_method: str, qc_kwargs: dict[str, Any]) -> None:
|
||||
"""Canonicalize the BF16 layer policy owned by serialized MXFP4 metadata.
|
||||
|
||||
A serialized checkpoint config is a complete storage contract: an omitted
|
||||
layer list means no explicit BF16 layers. Method-only online metadata does
|
||||
not carry that contract and must leave caller-provided layer policy intact.
|
||||
"""
|
||||
method = _normalize_quant_method_alias(qc_method)
|
||||
if method is None:
|
||||
return
|
||||
serialized_flag = _MXFP4_SERIALIZED_FLAGS.get(method)
|
||||
if serialized_flag is None or not qc_kwargs.get(serialized_flag):
|
||||
return
|
||||
|
||||
ignored_layers = qc_kwargs.get("ignored_layers")
|
||||
if not ignored_layers:
|
||||
ignored_layers = qc_kwargs.get("modules_to_not_convert")
|
||||
qc_kwargs["ignored_layers"] = ignored_layers or []
|
||||
qc_kwargs.pop("modules_to_not_convert", None)
|
||||
|
||||
|
||||
def resolve_quant_config_from_disk(
|
||||
quant_config: QuantizationConfig | None,
|
||||
disk_qc: dict[str, Any] | str | None,
|
||||
@@ -460,22 +487,24 @@ def resolve_quant_config_from_disk(
|
||||
- quant_config is None: auto-detect from disk_qc (full build).
|
||||
- Methods mismatch: raise ValueError — prevents silent weight corruption.
|
||||
- Disk marks serialized but quant_config is online: rebuild from disk.
|
||||
- ignored_layers differ: rebuild from disk (per-transformer BF16 routing).
|
||||
- Serialized MXFP4 metadata owns the complete BF16 layer policy; omitted
|
||||
ignored_layers means the checkpoint default (no explicit BF16 layers).
|
||||
- Method-only metadata carries no storage policy and preserves caller
|
||||
ignored_layers and runtime fallback policies.
|
||||
"""
|
||||
if disk_qc is None:
|
||||
return quant_config
|
||||
|
||||
if isinstance(disk_qc, str):
|
||||
if quant_config is None:
|
||||
logger.info("Auto-detected quantization from config.json: method=%s", disk_qc)
|
||||
return build_quant_config(disk_qc)
|
||||
return quant_config
|
||||
qc_method = disk_qc
|
||||
qc_kwargs: dict[str, Any] = {}
|
||||
else:
|
||||
if not isinstance(disk_qc, Mapping) or "quant_method" not in disk_qc:
|
||||
return quant_config
|
||||
qc_method = disk_qc["quant_method"]
|
||||
qc_kwargs = {k: v for k, v in disk_qc.items() if k != "quant_method"}
|
||||
|
||||
if not isinstance(disk_qc, Mapping) or "quant_method" not in disk_qc:
|
||||
return quant_config
|
||||
|
||||
qc_method: str = disk_qc["quant_method"]
|
||||
qc_kwargs: dict[str, Any] = {k: v for k, v in disk_qc.items() if k != "quant_method"}
|
||||
_normalize_serialized_mxfp4_layer_policy(qc_method, qc_kwargs)
|
||||
|
||||
if quant_config is None:
|
||||
logger.info(
|
||||
@@ -494,6 +523,26 @@ def resolve_quant_config_from_disk(
|
||||
"Pass a matching --quantization flag or omit it for auto-detection."
|
||||
)
|
||||
|
||||
if isinstance(disk_qc, str):
|
||||
return quant_config
|
||||
|
||||
# Serialized checkpoint metadata owns storage and BF16 layer routing. The
|
||||
# active config owns runtime step/layer policies, including explicit empty
|
||||
# lists. Preserve them when each cascade transformer rebuilds from disk.
|
||||
for policy in ("w4a8_fallback_steps", "w4a8_fallback_layers"):
|
||||
if hasattr(quant_config, policy):
|
||||
qc_kwargs[policy] = list(getattr(quant_config, policy))
|
||||
if hasattr(quant_config, "mxfp4_scale_alg"):
|
||||
# Runtime activation policy is independent of how offline W4 was made.
|
||||
qc_kwargs["mxfp4_scale_alg"] = quant_config.mxfp4_scale_alg
|
||||
if hasattr(quant_config, "require_smooth_scale"):
|
||||
disk_requires_smooth = qc_kwargs.get("require_smooth_scale", False)
|
||||
if not isinstance(disk_requires_smooth, bool):
|
||||
raise ValueError("require_smooth_scale must be a boolean")
|
||||
# Either a calibrated checkpoint or an explicit caller can require
|
||||
# Smooth. Per-expert rebuilds must never weaken that requirement.
|
||||
qc_kwargs["require_smooth_scale"] = quant_config.require_smooth_scale or disk_requires_smooth
|
||||
|
||||
if _disk_marks_serialized(qc_kwargs, quant_config):
|
||||
logger.info(
|
||||
"config.json marks checkpoint as serialized; switching to offline %s mode.",
|
||||
@@ -501,6 +550,14 @@ def resolve_quant_config_from_disk(
|
||||
)
|
||||
return build_quant_config(qc_method, **qc_kwargs)
|
||||
|
||||
if (
|
||||
"require_smooth_scale" in qc_kwargs
|
||||
and hasattr(quant_config, "require_smooth_scale")
|
||||
and qc_kwargs["require_smooth_scale"] != quant_config.require_smooth_scale
|
||||
):
|
||||
logger.info("config.json Smooth requirement differs from active config; rebuilding quant_config.")
|
||||
return build_quant_config(qc_method, **qc_kwargs)
|
||||
|
||||
# AutoRound MXFP checkpoints use data_type="mx_fp" instead of
|
||||
# is_checkpoint_*_serialized; rebuild so the offline MXFP4/MXFP8 path is
|
||||
# selected according to the checkpoint's bit width.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""W4A4 MXFP4 (Microscaling FP4) online/offline quantization for diffusion transformers.
|
||||
|
||||
Architecture mirrors mxfp8_config.py:
|
||||
@@ -41,7 +41,7 @@ Dual-scale (W4A4_MXFP4_DUALSCALE):
|
||||
and npu_dual_level_quant_matmul. Weight stored in NZ hardware format via npu_format_cast.
|
||||
|
||||
Checkpoint tensor shapes for dual-scale:
|
||||
weight : (N, K) float8_e4m3fn – FP4 packed
|
||||
weight : (N, K) float8_e4m3fn – numeric FP4 values (packed after loading)
|
||||
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits)
|
||||
weight_dual_scale : (N, K//512, 1) float32 – coarse scale (extra dim avoids shape assert)
|
||||
mul_scale : (K,) float32 – per-input-channel activation pre-scale
|
||||
@@ -51,9 +51,9 @@ Reference: MindIE-SD W4A4MXFP4QuantLinear / W4A4MXFP4DualQuantLinear (mindiesd/q
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.logger import init_logger
|
||||
@@ -83,9 +83,54 @@ from vllm_omni.quantization.mxfp8_config import (
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _validate_w4a8_fallback_steps(steps: list[int] | None) -> list[int]:
|
||||
if steps is None:
|
||||
return []
|
||||
if not isinstance(steps, list) or any(type(step) is not int or step < 0 for step in steps):
|
||||
raise ValueError("w4a8_fallback_steps must be a list of non-negative integer denoise step indices.")
|
||||
return sorted(set(steps))
|
||||
|
||||
|
||||
def _validate_w4a8_fallback_layers(layers: list[str] | None) -> list[str]:
|
||||
"""Names are exact runtime Linear paths, not checkpoint aliases or patterns."""
|
||||
if layers is None:
|
||||
return []
|
||||
if not isinstance(layers, list) or any(
|
||||
not isinstance(name, str) or re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_0-9]+)*", name) is None
|
||||
for name in layers
|
||||
):
|
||||
raise ValueError("w4a8_fallback_layers must be a list of non-empty exact runtime Linear paths.")
|
||||
return sorted(set(layers))
|
||||
|
||||
|
||||
def _is_w4a8_fallback_step(steps: list[int]) -> bool:
|
||||
"""Read the request's zero-based denoise index; never keep state on a Linear."""
|
||||
if not steps:
|
||||
return False
|
||||
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
is_forward_context_available,
|
||||
)
|
||||
|
||||
step = get_forward_context().denoise_step_idx if is_forward_context_available() else None
|
||||
if step is None:
|
||||
raise RuntimeError("W4A8 step fallback requires a pipeline that publishes its denoise step in ForwardContext.")
|
||||
return step in steps
|
||||
|
||||
|
||||
def _validate_smooth_scale(scale: torch.Tensor) -> None:
|
||||
"""Reject malformed calibration before loading or activation dtype conversion."""
|
||||
if scale.ndim != 1 or not scale.is_floating_point():
|
||||
raise ValueError("MXFP4 mul_scale must be a one-dimensional floating-point Smooth tensor.")
|
||||
if not bool(torch.isfinite(scale).all()) or not bool((scale > 0).all()):
|
||||
raise ValueError("MXFP4 mul_scale must contain finite, strictly positive Smooth values.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -105,10 +150,24 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
self,
|
||||
is_checkpoint_mxfp4_serialized: bool = False,
|
||||
ignored_layers: list[str] | None = None,
|
||||
w4a8_fallback_steps: list[int] | None = None,
|
||||
require_smooth_scale: bool = False,
|
||||
w4a8_fallback_layers: list[str] | None = None,
|
||||
mxfp4_scale_alg: int = 0,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.is_checkpoint_mxfp4_serialized = is_checkpoint_mxfp4_serialized
|
||||
self.ignored_layers = ignored_layers or []
|
||||
self.w4a8_fallback_steps = _validate_w4a8_fallback_steps(w4a8_fallback_steps)
|
||||
self.w4a8_fallback_layers = _validate_w4a8_fallback_layers(w4a8_fallback_layers)
|
||||
if not isinstance(require_smooth_scale, bool):
|
||||
raise ValueError("require_smooth_scale must be a boolean")
|
||||
if require_smooth_scale and not self.is_checkpoint_mxfp4_serialized:
|
||||
raise ValueError("require_smooth_scale requires an offline MXFP4 checkpoint")
|
||||
self.require_smooth_scale = require_smooth_scale
|
||||
if type(mxfp4_scale_alg) is not int or mxfp4_scale_alg not in (0, 2):
|
||||
raise ValueError("mxfp4_scale_alg must be 0 (OCP MX) or 2 (UOS with dst_type_max=7.25).")
|
||||
self.mxfp4_scale_alg = mxfp4_scale_alg
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> QuantizationMethods:
|
||||
@@ -139,6 +198,10 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
return cls(
|
||||
is_checkpoint_mxfp4_serialized=is_serialized,
|
||||
ignored_layers=ignored_layers,
|
||||
w4a8_fallback_steps=config.get("w4a8_fallback_steps"),
|
||||
w4a8_fallback_layers=config.get("w4a8_fallback_layers"),
|
||||
require_smooth_scale=config.get("require_smooth_scale", False),
|
||||
mxfp4_scale_alg=config.get("mxfp4_scale_alg", 0),
|
||||
)
|
||||
|
||||
def get_quant_method(
|
||||
@@ -155,9 +218,15 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
return UnquantizedLinearMethod()
|
||||
if current_omni_platform.is_npu():
|
||||
if self.is_checkpoint_mxfp4_serialized:
|
||||
return NPUMxfp4LinearMethod(self)
|
||||
return NPUMxfp4OnlineLinearMethod(self)
|
||||
return NPUMxfp4LinearMethod(self, prefix=prefix)
|
||||
return NPUMxfp4OnlineLinearMethod(self, prefix=prefix)
|
||||
if current_omni_platform.is_rocm():
|
||||
if self.mxfp4_scale_alg != 0:
|
||||
raise NotImplementedError("MXFP4 UOS quantization is currently only supported on NPU (Ascend).")
|
||||
if self.w4a8_fallback_steps or self.w4a8_fallback_layers:
|
||||
raise NotImplementedError(
|
||||
"MXFP4 W4A8 step/layer fallback is currently only supported on NPU (Ascend)."
|
||||
)
|
||||
gcn_arch = torch.cuda.get_device_properties(torch.accelerator.current_device_index()).gcnArchName
|
||||
if "gfx950" not in gcn_arch:
|
||||
raise NotImplementedError(f"MXFP4 on ROCm requires gfx950 (MI355X). Detected: {gcn_arch}")
|
||||
@@ -176,6 +245,56 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _npu_quantize_mxfp4(x: torch.Tensor, scale_alg: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Quantize weight or activation using the same explicit FP4 algorithm."""
|
||||
import torch_npu
|
||||
|
||||
# Universal Optimal Scaling (Qmax=7.25), MXAttention Section 4.1:
|
||||
# https://arxiv.org/abs/2607.24377
|
||||
scale_kwargs = {"dst_type_max": 7.25} if scale_alg == 2 else {}
|
||||
return torch_npu.npu_dynamic_mx_quant(
|
||||
x,
|
||||
dst_type=torch_npu.float4_e2m1fn_x2,
|
||||
axis=-1,
|
||||
block_size=32,
|
||||
round_mode="rint",
|
||||
scale_alg=scale_alg,
|
||||
**scale_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _npu_w4a8_matmul(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
output_dtype: torch.dtype,
|
||||
) -> torch.Tensor:
|
||||
"""MXFP8 activations with prepared single-scale MXFP4 weights (N, K)."""
|
||||
import torch_npu
|
||||
|
||||
x_q, x_scale = torch_npu.npu_dynamic_mx_quant(
|
||||
x, dst_type=torch_npu.float8_e4m3fn, axis=-1, block_size=32, round_mode="rint", scale_alg=0
|
||||
)
|
||||
# Use the BF16 output/bias pair supported by the mixed FP8/FP4 kernel
|
||||
# in the target A5 runtime. Restore the caller's dtype afterwards.
|
||||
if bias is not None:
|
||||
bias = bias.to(torch.bfloat16).reshape(1, -1)
|
||||
output = torch_npu.npu_quant_matmul(
|
||||
x_q,
|
||||
weight.transpose(0, 1),
|
||||
weight_scale.transpose(0, 1),
|
||||
scale_dtype=torch_npu.float8_e8m0fnu,
|
||||
x2_dtype=torch_npu.float4_e2m1fn_x2,
|
||||
pertoken_scale=x_scale,
|
||||
pertoken_scale_dtype=torch_npu.float8_e8m0fnu,
|
||||
bias=bias,
|
||||
output_dtype=torch.bfloat16,
|
||||
group_sizes=[0, 0, 32],
|
||||
)
|
||||
return output.to(output_dtype)
|
||||
|
||||
|
||||
class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
"""NPU W4A4 MXFP4 offline linear method for pre-quantized checkpoints.
|
||||
|
||||
@@ -187,7 +306,8 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
NPUMxfp4OnlineLinearMethod normalizes to the same layout so apply() is shared.
|
||||
"""
|
||||
|
||||
def __init__(self, quant_config: DiffusionMXFP4Config) -> None:
|
||||
def __init__(self, quant_config: DiffusionMXFP4Config, *, prefix: str = "") -> None:
|
||||
self.is_w4a8_fallback_layer = prefix in quant_config.w4a8_fallback_layers
|
||||
self.quant_config = quant_config
|
||||
self.out_dtype = torch.get_default_dtype()
|
||||
|
||||
@@ -210,11 +330,14 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
layer.orig_dtype = params_dtype
|
||||
layer.weight_block_size = None
|
||||
|
||||
# BF16 placeholder; cast to float4_e2m1fn_x2 in process_weights.
|
||||
layer.register_parameter(
|
||||
"weight",
|
||||
ModelWeightParameter(
|
||||
data=torch.empty(output_size_per_partition, input_size_per_partition, dtype=params_dtype),
|
||||
data=torch.empty(
|
||||
output_size_per_partition,
|
||||
input_size_per_partition,
|
||||
dtype=params_dtype,
|
||||
),
|
||||
input_dim=1,
|
||||
output_dim=0,
|
||||
weight_loader=weight_loader,
|
||||
@@ -234,12 +357,42 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
),
|
||||
)
|
||||
|
||||
# Older single-scale checkpoints have no Smooth tensor. Keep their
|
||||
# identity transform while allowing calibrated checkpoints to load it.
|
||||
def smooth_weight_loader(
|
||||
param: ModelWeightParameter, loaded_weight: torch.Tensor, *args: Any, **kwargs: Any
|
||||
) -> None:
|
||||
_validate_smooth_scale(loaded_weight)
|
||||
if not callable(weight_loader):
|
||||
raise ValueError("Loading MXFP4 Smooth requires a callable weight_loader")
|
||||
weight_loader(param, loaded_weight, *args, **kwargs)
|
||||
|
||||
layer.register_parameter(
|
||||
"mul_scale",
|
||||
ModelWeightParameter(
|
||||
data=torch.ones(input_size_per_partition, dtype=torch.float32),
|
||||
input_dim=0,
|
||||
output_dim=None,
|
||||
weight_loader=smooth_weight_loader,
|
||||
),
|
||||
)
|
||||
setattr(layer.mul_scale, "ignore_warning", True)
|
||||
setattr(layer.mul_scale, "is_checkpoint_optional", not self.quant_config.require_smooth_scale)
|
||||
if self.quant_config.is_checkpoint_mxfp4_serialized:
|
||||
setattr(layer.weight_scale, "is_checkpoint_required", True)
|
||||
|
||||
def process_weights_after_loading(self, layer: Module) -> None:
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
return
|
||||
|
||||
import torch_npu
|
||||
|
||||
smooth_param = cast(torch.Tensor, layer.mul_scale)
|
||||
_validate_smooth_scale(smooth_param)
|
||||
smooth = smooth_param.data.to(dtype=cast(torch.dtype, layer.orig_dtype)).contiguous()
|
||||
# Finite FP32 values can overflow or underflow in the activation dtype.
|
||||
_validate_smooth_scale(smooth)
|
||||
|
||||
# NPU: cast to float4_e2m1fn_x2. Weight stays (N, K) — no pre-transpose.
|
||||
w = layer.weight
|
||||
if w.dtype != torch_npu.float4_e2m1fn_x2:
|
||||
@@ -258,15 +411,31 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
|
||||
replace_parameter(layer, "weight", w)
|
||||
replace_parameter(layer, "weight_scale", s)
|
||||
# Keep loader metadata while converting the calibration tensor once.
|
||||
layer.mul_scale.data = smooth.to(device=cast(torch.Tensor, w).device)
|
||||
layer._already_called_process_weights_after_loading = True
|
||||
|
||||
# --- NPU MXFP4 ops — shared with online path via inheritance ---
|
||||
|
||||
def _quantize_activation(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import torch_npu
|
||||
def _apply_inner(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
ori_dtype: torch.dtype,
|
||||
) -> torch.Tensor:
|
||||
# Online quantization has no calibrated Smooth tensor. For offline
|
||||
# weights the same pre-scale must precede both A4 and A8 quantization.
|
||||
if (mul_scale := getattr(layer, "mul_scale", None)) is not None:
|
||||
x = x * mul_scale.to(x.dtype)
|
||||
if self.is_w4a8_fallback_layer or _is_w4a8_fallback_step(self.quant_config.w4a8_fallback_steps):
|
||||
return _npu_w4a8_matmul(
|
||||
x, cast(torch.Tensor, layer.weight), cast(torch.Tensor, layer.weight_scale), bias, ori_dtype
|
||||
)
|
||||
return super()._apply_inner(layer, x, bias, ori_dtype)
|
||||
|
||||
# No dst_type: npu_dynamic_mx_quant defaults to float4_e2m1fn_x2.
|
||||
return torch_npu.npu_dynamic_mx_quant(x)
|
||||
def _quantize_activation(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return _npu_quantize_mxfp4(x, self.quant_config.mxfp4_scale_alg)
|
||||
|
||||
def _quant_matmul(
|
||||
self,
|
||||
@@ -318,8 +487,6 @@ class NPUMxfp4OnlineLinearMethod(_LazyWeightMixin, NPUMxfp4LinearMethod):
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
return
|
||||
|
||||
import torch_npu
|
||||
|
||||
if layer.weight.device == torch.device("meta"):
|
||||
weight = ModelWeightParameter(
|
||||
data=torch.empty_like(layer.weight, device=layer._load_device),
|
||||
@@ -331,8 +498,10 @@ class NPUMxfp4OnlineLinearMethod(_LazyWeightMixin, NPUMxfp4LinearMethod):
|
||||
layer.register_parameter("weight", weight)
|
||||
initialize_single_dummy_weight(layer.weight)
|
||||
|
||||
# NPU: quantize BF16/FP16 (N, K) → FP4. No dst_type → float4_e2m1fn_x2.
|
||||
weight_fp4, weight_scale_raw = torch_npu.npu_dynamic_mx_quant(layer.weight)
|
||||
# Prepare once; offline checkpoints keep their existing weight algorithm.
|
||||
weight_fp4, weight_scale_raw = _npu_quantize_mxfp4(
|
||||
cast(torch.Tensor, layer.weight), self.quant_config.mxfp4_scale_alg
|
||||
)
|
||||
|
||||
# Weight stays (N, K) — no pre-transpose for FP4 packed format.
|
||||
# Scale: (N, S) → (N, S/2, 2). Not pre-transposed; done inline in _quant_matmul.
|
||||
@@ -497,7 +666,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
"""NPU W4A4 MXFP4 dual-scale offline method for pre-quantized checkpoints.
|
||||
|
||||
Checkpoint tensors and their canonical post-load shapes:
|
||||
weight : (N, K) float8_e4m3fn – FP4 packed (2 values per byte)
|
||||
weight : (N, K) float8_e4m3fn – numeric FP4 values; packed into NZ after loading
|
||||
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits); reshaped to (N, K//64, 2)
|
||||
weight_dual_scale : (N, K//512, 1) float32 – coarse scale; transposed to (K//512, N)
|
||||
mul_scale : (K,) float32 – per-input-channel activation pre-scale (from calibration)
|
||||
@@ -509,7 +678,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
Reference: MindIE-SD W4A4MXFP4DualQuantLinear.
|
||||
"""
|
||||
|
||||
def __init__(self, quant_config: Any) -> None:
|
||||
def __init__(self, quant_config: DiffusionMXFP4DualScaleMixedConfig) -> None:
|
||||
self.quant_config = quant_config
|
||||
self.out_dtype = torch.get_default_dtype()
|
||||
|
||||
@@ -532,7 +701,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
layer.orig_dtype = params_dtype
|
||||
layer.weight_block_size = None
|
||||
|
||||
# FP4 packed: 2 values per float8_e4m3fn byte → checkpoint stores as float8_e4m3fn; register as BF16
|
||||
# Checkpoint FP4 values are stored numerically in FP8; BF16 preserves them exactly.
|
||||
layer.register_parameter(
|
||||
"weight",
|
||||
ModelWeightParameter(
|
||||
@@ -587,6 +756,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
),
|
||||
)
|
||||
setattr(layer.mul_scale, "ignore_warning", True)
|
||||
setattr(layer.weight_scale, "is_checkpoint_required", True)
|
||||
|
||||
def process_weights_after_loading(self, layer: Module) -> None:
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
@@ -594,7 +764,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
|
||||
import torch_npu
|
||||
|
||||
# float8_e4m3fn (FP4 packed) → float4_e2m1fn_x2 → NZ hardware format (format ID 29).
|
||||
# Numeric FP4 values → packed float4_e2m1fn_x2 → NZ hardware format (format ID 29).
|
||||
# NZ layout is required by npu_dual_level_quant_matmul for FP4 weight matrices.
|
||||
w = torch_npu.npu_dtype_cast(layer.weight.data.npu(), torch_npu.float4_e2m1fn_x2)
|
||||
w = torch_npu.npu_format_cast(w.view(torch.int8), 29, customize_dtype=torch.int8)
|
||||
@@ -631,7 +801,10 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
"""
|
||||
if ori_dtype not in (torch.bfloat16, torch.float16):
|
||||
x = x.to(torch.bfloat16)
|
||||
x_q, l0_scale, l1_scale = self._quantize_activation(x, layer.mul_scale)
|
||||
# The dual-level activation kernel requires x and Smooth to have the
|
||||
# same dtype. Prepared calibration scales are BF16, including online.
|
||||
smooth_scale = cast(torch.Tensor, layer.mul_scale).to(x.dtype)
|
||||
x_q, l0_scale, l1_scale = self._quantize_activation(x, smooth_scale)
|
||||
return self._quant_matmul(x_q, l0_scale, l1_scale, layer, bias, ori_dtype)
|
||||
|
||||
def _quantize_activation( # type: ignore[override]
|
||||
@@ -785,11 +958,20 @@ class DiffusionMXFP4DualScaleMixedConfig(QuantizationConfig):
|
||||
is_checkpoint_serialized: bool = False,
|
||||
ignored_layers: list[str] | None = None,
|
||||
num_bf16_fallback_layers: int = 5,
|
||||
w4a8_fallback_steps: list[int] | None = None,
|
||||
w4a8_fallback_layers: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.is_checkpoint_serialized = is_checkpoint_serialized
|
||||
self.ignored_layers = ignored_layers or []
|
||||
self.num_bf16_fallback_layers = num_bf16_fallback_layers
|
||||
self.w4a8_fallback_steps = _validate_w4a8_fallback_steps(w4a8_fallback_steps)
|
||||
self.w4a8_fallback_layers = _validate_w4a8_fallback_layers(w4a8_fallback_layers)
|
||||
if self.w4a8_fallback_steps or self.w4a8_fallback_layers:
|
||||
raise ValueError(
|
||||
"mxfp4_dualscale does not support W4A8 fallback. Use mxfp4 with single-scale weights; "
|
||||
"changing a DualScale checkpoint's method name does not convert its storage format."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> QuantizationMethods:
|
||||
@@ -822,6 +1004,8 @@ class DiffusionMXFP4DualScaleMixedConfig(QuantizationConfig):
|
||||
is_checkpoint_serialized=is_serialized,
|
||||
ignored_layers=ignored_layers,
|
||||
num_bf16_fallback_layers=num_bf16_fallback_layers,
|
||||
w4a8_fallback_steps=config.get("w4a8_fallback_steps"),
|
||||
w4a8_fallback_layers=config.get("w4a8_fallback_layers"),
|
||||
)
|
||||
|
||||
def get_quant_method(
|
||||
|
||||
Reference in new issue
Block a user