[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
@@ -179,8 +179,36 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
|
||||
return {}
|
||||
|
||||
|
||||
def resolve_wan_transformer_quant_config(
|
||||
config: dict, quant_config: QuantizationConfig | None, component: str
|
||||
) -> QuantizationConfig | None:
|
||||
"""Resolve the expert before applying its checkpoint's storage contract."""
|
||||
from vllm_omni.quantization.component_config import ComponentQuantizationConfig
|
||||
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
|
||||
|
||||
# Wan experts are siblings: "transformer_2" must not inherit "transformer"
|
||||
# through the generic layer-prefix resolver. Select the whole expert name.
|
||||
component_quant_config = (
|
||||
quant_config.component_configs.get(component, quant_config.default_config)
|
||||
if isinstance(quant_config, ComponentQuantizationConfig)
|
||||
else quant_config
|
||||
)
|
||||
quantization_disabled = isinstance(quant_config, ComponentQuantizationConfig) and component_quant_config is None
|
||||
resolved_quant_config = resolve_quant_config_from_disk(component_quant_config, config.get("quantization_config"))
|
||||
if quantization_disabled and resolved_quant_config is not None:
|
||||
raise ValueError(
|
||||
f"Quantization is disabled for component {component!r}, but its checkpoint declares quantization. "
|
||||
"Use a BF16 checkpoint for this component or enable its matching quantization method."
|
||||
)
|
||||
return resolved_quant_config
|
||||
|
||||
|
||||
def create_transformer_from_config(
|
||||
config: dict, quant_config: QuantizationConfig | None = None, prefix: str = ""
|
||||
config: dict,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
*,
|
||||
component: str = "transformer",
|
||||
) -> WanTransformer3DModel:
|
||||
"""Create WanTransformer3DModel from config dict."""
|
||||
kwargs: dict = {}
|
||||
@@ -216,11 +244,7 @@ def create_transformer_from_config(
|
||||
if "pos_embed_seq_len" in config:
|
||||
kwargs["pos_embed_seq_len"] = config["pos_embed_seq_len"]
|
||||
|
||||
if "quantization_config" in config:
|
||||
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
|
||||
|
||||
quant_config = resolve_quant_config_from_disk(quant_config, config["quantization_config"])
|
||||
|
||||
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
|
||||
if quant_config is not None:
|
||||
kwargs["quant_config"] = quant_config
|
||||
if prefix:
|
||||
@@ -460,13 +484,13 @@ class Wan22Pipeline(
|
||||
# Initialize transformers with correct config (weights loaded via load_weights)
|
||||
if load_transformer:
|
||||
transformer_config = load_transformer_config(model, "transformer", local_files_only)
|
||||
self.transformer = self._create_transformer(transformer_config)
|
||||
self.transformer = self._create_transformer(transformer_config, component="transformer")
|
||||
else:
|
||||
self.transformer = None
|
||||
|
||||
if load_transformer_2:
|
||||
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
|
||||
else:
|
||||
self.transformer_2 = None
|
||||
|
||||
@@ -504,10 +528,17 @@ class Wan22Pipeline(
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler
|
||||
)
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
|
||||
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_transformer_from_config(
|
||||
config,
|
||||
quant_config=quant_config,
|
||||
component=component,
|
||||
)
|
||||
|
||||
@property
|
||||
def guidance_scale(self):
|
||||
|
||||
@@ -304,25 +304,10 @@ class Wan22I2VPipeline(
|
||||
# Transformers (weights loaded via load_weights)
|
||||
# Load config from model directory or HF Hub to get correct in_channels for I2V models
|
||||
transformer_config = load_transformer_config(model, "transformer", local_files_only)
|
||||
self.transformer = create_transformer_from_config(
|
||||
transformer_config,
|
||||
quant_config=od_config.quantization_config,
|
||||
)
|
||||
self.transformer = self._create_transformer(transformer_config, component="transformer")
|
||||
if self.has_transformer_2:
|
||||
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
|
||||
t2_quant = transformer_2_config.get("quantization_config")
|
||||
if isinstance(t2_quant, dict) and "quant_method" in t2_quant:
|
||||
from vllm_omni.quantization.factory import build_quant_config
|
||||
|
||||
method = t2_quant["quant_method"]
|
||||
kwargs = {k: v for k, v in t2_quant.items() if k != "quant_method"}
|
||||
t2_quant = build_quant_config(method, **kwargs)
|
||||
else:
|
||||
t2_quant = None
|
||||
self.transformer_2 = create_transformer_from_config(
|
||||
transformer_2_config,
|
||||
quant_config=t2_quant,
|
||||
)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
|
||||
else:
|
||||
self.transformer_2 = None
|
||||
|
||||
@@ -462,10 +447,13 @@ class Wan22I2VPipeline(
|
||||
image_embeds = self.image_encoder(pixel_values, output_hidden_states=True)
|
||||
return image_embeds.hidden_states[-2]
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
|
||||
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_transformer_from_config(config, quant_config=quant_config, component=component)
|
||||
|
||||
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
|
||||
sampling_params_list = req.sampling_params_list
|
||||
|
||||
@@ -28,6 +28,7 @@ from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
Wan22Pipeline,
|
||||
load_wan_weights_with_optional_gate,
|
||||
resolve_wan_transformer_quant_config,
|
||||
retrieve_latents,
|
||||
)
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
@@ -60,6 +61,8 @@ def create_vace_transformer_from_config(
|
||||
config: dict,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
*,
|
||||
component: str = "transformer",
|
||||
) -> WanVACETransformer3DModel:
|
||||
"""Create WanVACETransformer3DModel from config dict."""
|
||||
kwargs = {}
|
||||
@@ -97,6 +100,7 @@ def create_vace_transformer_from_config(
|
||||
kwargs["vace_layers"] = config["vace_layers"]
|
||||
if "vace_in_channels" in config:
|
||||
kwargs["vace_in_channels"] = config["vace_in_channels"]
|
||||
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
|
||||
if quant_config is not None:
|
||||
kwargs["quant_config"] = quant_config
|
||||
if prefix:
|
||||
@@ -205,10 +209,13 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanVACETransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanVACETransformer3DModel:
|
||||
"""Build VACE transformer. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_vace_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_vace_transformer_from_config(config, quant_config=quant_config, component=component)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
|
||||
@@ -18,7 +18,7 @@ from vllm.distributed import (
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.conv import Conv3dLayer
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, LinearBase, QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.utils import (
|
||||
@@ -45,6 +45,7 @@ from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
|
||||
from vllm_omni.diffusion.layers.norm import LayerNorm, RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingWan
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.quantization.mxfp4_config import NPUMxfp4LinearMethod
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -985,6 +986,68 @@ class WanTransformer3DModel(nn.Module):
|
||||
# ROPE helper
|
||||
self._cached_rope_emb = None
|
||||
self._cached_rope_resolution = None
|
||||
self._validate_w4a8_fallback_layers(quant_config)
|
||||
|
||||
def _validate_w4a8_fallback_layers(self, quant_config: QuantizationConfig | None) -> None:
|
||||
"""Reject checkpoint aliases/typos before loading weights or running inference."""
|
||||
requested = tuple(getattr(quant_config, "w4a8_fallback_layers", []))
|
||||
self._w4a8_fallback_layers = requested
|
||||
self._local_w4a8_fallback_layers: tuple[str, ...] = ()
|
||||
if not requested:
|
||||
return
|
||||
modules = dict(self.named_modules())
|
||||
missing_pp_prefixes = [name for name, module in modules.items() if isinstance(module, PPMissingLayer)]
|
||||
local_layers = [
|
||||
name for name in requested if not any(name.startswith(prefix + ".") for prefix in missing_pp_prefixes)
|
||||
]
|
||||
self._local_w4a8_fallback_layers = tuple(local_layers)
|
||||
invalid = [name for name in local_layers if not isinstance(modules.get(name), LinearBase)]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
"w4a8_fallback_layers requires exact runtime Linear paths relative to each Wan transformer; "
|
||||
f"unknown/non-Linear paths: {invalid}. Use attn1.to_qkv for fused self-attention, "
|
||||
"not checkpoint attn1.to_q/to_k/to_v names."
|
||||
)
|
||||
|
||||
def _log_w4a8_fallback_load_summary(self, component_name: str) -> None:
|
||||
"""Log post-load transforms/cache readiness, not numerical acceptance."""
|
||||
requested = self._w4a8_fallback_layers
|
||||
if not requested:
|
||||
return
|
||||
modules = dict(self.named_modules())
|
||||
local_layers = self._local_w4a8_fallback_layers
|
||||
selected_layers = [
|
||||
name for name in local_layers if getattr(modules[name].quant_method, "is_w4a8_fallback_layer", False)
|
||||
]
|
||||
bf16_overrides = [name for name in local_layers if name not in selected_layers]
|
||||
processed = [
|
||||
name
|
||||
for name in selected_layers
|
||||
if getattr(modules[name], "_already_called_process_weights_after_loading", False)
|
||||
]
|
||||
if not selected_layers:
|
||||
processing_state = "not-required"
|
||||
elif len(processed) == len(selected_layers):
|
||||
processing_state = "ready"
|
||||
else:
|
||||
processing_state = "not-ready"
|
||||
|
||||
def qualified(names: Iterable[str]) -> list[str]:
|
||||
return [f"{component_name}.{name}" for name in names]
|
||||
|
||||
logger.info(
|
||||
"Wan W4A8 post-load summary: component=%s; selected=%d %s; BF16 overrides=%d %s; "
|
||||
"weight/A8 processing state=%s (%d/%d selected layers processed); other PP ranks=%d",
|
||||
component_name,
|
||||
len(selected_layers),
|
||||
qualified(selected_layers),
|
||||
len(bf16_overrides),
|
||||
qualified(bf16_overrides),
|
||||
processing_state,
|
||||
len(processed),
|
||||
len(selected_layers),
|
||||
len(requested) - len(local_layers),
|
||||
)
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
@@ -1155,7 +1218,22 @@ class WanTransformer3DModel(nn.Module):
|
||||
}
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
single_scale_prefixes = {
|
||||
name
|
||||
for name, module in self.named_modules()
|
||||
if isinstance(getattr(module, "quant_method", None), NPUMxfp4LinearMethod)
|
||||
}
|
||||
|
||||
def reject_dualscale_tensor(name: str) -> None:
|
||||
if name.endswith(".weight_dual_scale") and name.rsplit(".", 1)[0] in single_scale_prefixes:
|
||||
raise ValueError(
|
||||
f"Single-scale mxfp4 cannot load DualScale tensor {name}; "
|
||||
"changing quant_method does not convert a checkpoint."
|
||||
)
|
||||
|
||||
loaded_params: set[str] = set()
|
||||
loaded_qkv_shards: dict[str, set[str]] = {}
|
||||
qkv_smooth_scales: dict[str, torch.Tensor] = {}
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
name = weight_name_remapping.get(name, name)
|
||||
@@ -1166,15 +1244,32 @@ class WanTransformer3DModel(nn.Module):
|
||||
# Pre-fused to_qkv tensors (from offline MXFP8 merged checkpoint) fall
|
||||
# through to the else branch and are loaded directly.
|
||||
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||
if weight_name not in original_name:
|
||||
if f"{weight_name}." not in original_name:
|
||||
continue
|
||||
lookup_name = original_name.replace(weight_name, param_name)
|
||||
lookup_name = original_name.replace(f"{weight_name}.", f"{param_name}.", 1)
|
||||
reject_dualscale_tensor(lookup_name)
|
||||
# Skip weights that belong to PP stages other than this one
|
||||
if is_pp_missing_parameter(lookup_name, self) or lookup_name not in params_dict:
|
||||
break
|
||||
param = params_dict[lookup_name]
|
||||
if lookup_name.endswith(".mul_scale"):
|
||||
previous_scale = qkv_smooth_scales.get(lookup_name)
|
||||
if previous_scale is not None and not torch.equal(previous_scale, loaded_weight):
|
||||
raise ValueError(f"Fused Q/K/V must share the same Smooth tensor: {lookup_name}")
|
||||
if previous_scale is None:
|
||||
qkv_smooth_scales[lookup_name] = loaded_weight.clone()
|
||||
weight_loader = param.weight_loader
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
loaded_params.add(original_name)
|
||||
if getattr(param, "output_dim", None) is None and not getattr(param, "needs_scalar_to_array", False):
|
||||
# Shared input-channel Smooth is a complete tensor even
|
||||
# when supplied under a single Q/K/V source name.
|
||||
loaded_params.add(lookup_name)
|
||||
else:
|
||||
shards = loaded_qkv_shards.setdefault(lookup_name, set())
|
||||
shards.add(shard_id)
|
||||
if shards == {"q", "k", "v"}:
|
||||
loaded_params.add(lookup_name)
|
||||
break
|
||||
else:
|
||||
# diffusers: ffn.net.0.proj.weight -> our: ffn.net_0.proj.weight
|
||||
@@ -1198,6 +1293,7 @@ class WanTransformer3DModel(nn.Module):
|
||||
if is_pp_missing_parameter(lookup_name, self):
|
||||
continue
|
||||
|
||||
reject_dualscale_tensor(lookup_name)
|
||||
if lookup_name not in params_dict:
|
||||
logger.warning(f"Skipping weight {original_name} -> {lookup_name}")
|
||||
continue
|
||||
@@ -1222,8 +1318,6 @@ class WanTransformer3DModel(nn.Module):
|
||||
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
|
||||
loaded_params.add(original_name)
|
||||
loaded_params.add(lookup_name)
|
||||
loaded_params.update((original_name, lookup_name))
|
||||
|
||||
return loaded_params
|
||||
Reference in new issue
Block a user