[Model] Add Cosmos3 mixed W8A8/W8A16 and W4A4/W4A16 denoising (#6560)

Signed-off-by: Rahul Steiger <rsteiger@aws-cmh-slurm-1-vscode-04.cm.cluster>
Signed-off-by: Wojciech Kutak <wkutak@nvidia.com>
Co-authored-by: Rahul Steiger <rsteiger@nvidia.com>
This commit is contained in:
wkutakandRahul Steiger authored and GitHub committed 2026-09-10 23:51:09 +12:00
1 parent d8d4062547
commit 43a476c1e5
10 files changed
+1509 -4

No files matched your search

@@ -0,0 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Scheduled A16 execution for quantized Cosmos3 checkpoints."""
from .checkpoint import resolve_mixed_precision_config
from .config import Cosmos3MixedPrecisionConfig
from .runtime import Cosmos3MixedPrecisionRuntime
__all__ = [
"Cosmos3MixedPrecisionConfig",
"Cosmos3MixedPrecisionRuntime",
"resolve_mixed_precision_config",
]
@@ -0,0 +1,176 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Checkpoint discovery for the Cosmos3 diffusion-step precision policy."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Literal, cast
from .config import Cosmos3MixedPrecisionConfig, ReasonerPolicy, _non_negative_int
PolicySource = Literal[
"none",
"checkpoint",
"additional_config",
"additional_config_disabled",
]
_COMPONENT = "transformer"
_POLICY_FIELDS = frozenset(
{
"schema_version",
"type",
"index_space",
"scope",
"default_mode",
"first_steps",
"last_steps",
"overlap",
"reasoner",
}
)
_STEP_RANGE_FIELDS = frozenset({"count", "mode"})
_SUPPORTED_MODEL_OPT_CONFIGS = frozenset(
{
"modelopt",
"modelopt_fp4",
}
)
def resolve_mixed_precision_config(
od_config: object,
) -> tuple[Cosmos3MixedPrecisionConfig | None, PolicySource]:
"""Resolve an explicit runtime override before the checkpoint default."""
override_present, override = Cosmos3MixedPrecisionConfig.resolve_additional_config(
getattr(od_config, "additional_config", None)
)
if override_present:
if override is not None:
_validate_checkpoint_quantization(od_config)
source: PolicySource = "additional_config" if override is not None else "additional_config_disabled"
return override, source
checkpoint = read_checkpoint_policy(od_config)
if checkpoint is not None:
return checkpoint, "checkpoint"
return None, "none"
def read_checkpoint_policy(od_config: object) -> Cosmos3MixedPrecisionConfig | None:
"""Read and validate a policy from ``transformer/config.json``.
Missing metadata preserves ordinary checkpoint behavior. Metadata that is
present but malformed or incompatible fails closed.
"""
tf_config = getattr(od_config, "tf_model_config", None)
params = getattr(tf_config, "params", None)
if not isinstance(params, Mapping):
return None
disk_quant_config = params.get("quantization_config")
if not isinstance(disk_quant_config, Mapping):
return None
if "runtime" not in disk_quant_config:
return None
runtime_config = disk_quant_config["runtime"]
if not isinstance(runtime_config, Mapping):
raise TypeError("quantization_config.runtime must be a mapping")
if "diffusion_step_policy" not in runtime_config:
return None
raw_policy = runtime_config["diffusion_step_policy"]
if not isinstance(raw_policy, Mapping):
raise TypeError("quantization_config.runtime.diffusion_step_policy must be a mapping")
policy = _parse_policy(raw_policy)
if policy is None:
return None
_validate_checkpoint_quantization(od_config)
return policy
def _parse_policy(policy: Mapping[str, object]) -> Cosmos3MixedPrecisionConfig | None:
fields = set(policy)
unknown = fields - _POLICY_FIELDS
if unknown:
raise ValueError(f"Unknown diffusion_step_policy fields: {sorted(unknown)}")
missing = _POLICY_FIELDS - fields
if missing:
raise ValueError(f"Missing diffusion_step_policy fields: {sorted(missing)}")
schema_version = policy["schema_version"]
if not isinstance(schema_version, int) or isinstance(schema_version, bool) or schema_version != 1:
raise ValueError("diffusion_step_policy.schema_version must be the integer 1")
if policy["type"] != "first_last_n":
raise ValueError("diffusion_step_policy.type must be 'first_last_n'")
if policy["index_space"] != "denoising_loop_iteration":
raise ValueError("diffusion_step_policy.index_space must be 'denoising_loop_iteration'")
if policy["default_mode"] != "native":
raise ValueError("diffusion_step_policy.default_mode must be 'native'")
if policy["overlap"] != "a16":
raise ValueError("diffusion_step_policy.overlap must be 'a16'")
scope = policy["scope"]
if not isinstance(scope, list) or not scope or not all(isinstance(item, str) for item in scope):
raise TypeError("diffusion_step_policy.scope must be a non-empty list of strings")
first_steps = _parse_step_range(policy["first_steps"], "first_steps")
last_steps = _parse_step_range(policy["last_steps"], "last_steps")
reasoner = policy["reasoner"]
if reasoner not in {"native", "a16"}:
raise ValueError("diffusion_step_policy.reasoner must be 'native' or 'a16'")
if _COMPONENT not in scope:
return None
return Cosmos3MixedPrecisionConfig(
first_steps=first_steps,
last_steps=last_steps,
reasoner=cast(ReasonerPolicy, reasoner),
)
def _parse_step_range(value: object, name: str) -> int:
if not isinstance(value, Mapping):
raise TypeError(f"diffusion_step_policy.{name} must be a mapping")
fields = set(value)
unknown = fields - _STEP_RANGE_FIELDS
if unknown:
raise ValueError(f"Unknown diffusion_step_policy.{name} fields: {sorted(unknown)}")
missing = _STEP_RANGE_FIELDS - fields
if missing:
raise ValueError(f"Missing diffusion_step_policy.{name} fields: {sorted(missing)}")
if value["mode"] != "a16":
raise ValueError(f"diffusion_step_policy.{name}.mode must be 'a16'")
return _non_negative_int(value["count"], f"diffusion_step_policy.{name}.count")
def _validate_checkpoint_quantization(od_config: object) -> None:
# Match the effective quantization used to construct the transformer linears.
quant_config = getattr(od_config, "quantization_config", None)
if quant_config is None:
tf_config = getattr(od_config, "tf_model_config", None)
quant_config = getattr(tf_config, "quant_config", None)
get_name = getattr(quant_config, "get_name", None)
name = get_name() if callable(get_name) else None
if name not in _SUPPORTED_MODEL_OPT_CONFIGS:
raise ValueError(f"diffusion_step_policy requires a serialized ModelOpt FP8 or NVFP4 checkpoint, got {name!r}")
if name == "modelopt":
_require_serialized(quant_config, "is_checkpoint_fp8_serialized", "FP8")
return
if name == "modelopt_fp4":
if getattr(quant_config, "quant_method", "NVFP4") != "NVFP4":
raise ValueError("diffusion_step_policy requires checkpoint-native NVFP4 W4A4 linears")
_require_serialized(quant_config, "is_checkpoint_nvfp4_serialized", "NVFP4")
return
def _require_serialized(quant_config: object | None, flag: str, format_name: str) -> None:
if not bool(getattr(quant_config, flag, False)):
raise ValueError(f"diffusion_step_policy requires serialized ModelOpt {format_name} weights")
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Configuration parsing and denoising-step policy for mixed precision."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Literal, cast
ReasonerPolicy = Literal["native", "a16"]
_REASONER_POLICIES = frozenset({"native", "a16"})
_CONFIG_FIELDS = frozenset({"enabled", "first_steps", "last_steps", "reasoner"})
@dataclass(frozen=True)
class Cosmos3MixedPrecisionConfig:
"""Validated precision policy shared by every quantization strategy."""
first_steps: int = 3
last_steps: int = 3
reasoner: ReasonerPolicy = "a16"
@classmethod
def from_additional_config(
cls,
additional_config: Mapping[str, object] | None,
) -> Cosmos3MixedPrecisionConfig | None:
"""Parse Cosmos3 fields from vLLM-Omni's additional configuration."""
_, config = cls.resolve_additional_config(additional_config)
return config
@classmethod
def resolve_additional_config(
cls,
additional_config: Mapping[str, object] | None,
) -> tuple[bool, Cosmos3MixedPrecisionConfig | None]:
"""Return whether an override was supplied and its effective policy.
The separate presence bit distinguishes an absent runtime override from
an explicit disable. That distinction matters when a checkpoint owns a
default policy.
"""
if additional_config is not None and not isinstance(additional_config, Mapping):
raise TypeError("additional_config must be a mapping")
values = additional_config or {}
if "cosmos3_mixed_precision" not in values:
return False, None
raw_config = values["cosmos3_mixed_precision"]
if not isinstance(raw_config, Mapping):
raise TypeError("cosmos3_mixed_precision must be a mapping")
unknown = set(raw_config) - _CONFIG_FIELDS
if unknown:
raise ValueError(f"Unknown cosmos3_mixed_precision fields: {sorted(unknown)}")
enabled = raw_config.get("enabled", True)
if not isinstance(enabled, bool):
raise TypeError("cosmos3_mixed_precision.enabled must be a boolean")
if not enabled:
conflicting = set(raw_config) - {"enabled"}
if conflicting:
raise ValueError(
"cosmos3_mixed_precision.enabled=false cannot be combined with "
f"schedule fields: {sorted(conflicting)}"
)
return True, None
first_steps = _non_negative_int(
raw_config.get("first_steps", 3),
"cosmos3_mixed_precision.first_steps",
)
last_steps = _non_negative_int(
raw_config.get("last_steps", 3),
"cosmos3_mixed_precision.last_steps",
)
reasoner = str(raw_config.get("reasoner", "a16")).lower()
if reasoner not in _REASONER_POLICIES:
raise ValueError(
f"cosmos3_mixed_precision.reasoner must be one of {sorted(_REASONER_POLICIES)}, got {reasoner!r}"
)
config = cls(
first_steps=first_steps,
last_steps=last_steps,
reasoner=cast(ReasonerPolicy, reasoner),
)
if first_steps == 0 and last_steps == 0 and reasoner == "native":
return True, None
return True, config
def use_high_precision(self, step_index: int, num_steps: int) -> bool:
"""Select the high path for an actual scheduler-step index."""
if num_steps <= 0:
raise ValueError(f"num_steps must be positive, got {num_steps}")
if step_index < 0 or step_index >= num_steps:
raise IndexError(f"step_index must be in [0, {num_steps}), got {step_index}")
return step_index < self.first_steps or step_index >= num_steps - self.last_steps
def _non_negative_int(value: object, name: str) -> int:
"""Validate an integer configuration field without accepting booleans."""
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
raise TypeError(f"{name} must be a non-negative integer")
return value
@@ -0,0 +1,116 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Format-agnostic schedule state, linear discovery, and dispatch."""
from __future__ import annotations
from typing import Literal
import torch
from vllm.model_executor.layers.linear import LinearBase, LinearMethodBase
from .config import Cosmos3MixedPrecisionConfig
from .strategy import (
Cosmos3PrecisionStrategy,
Fp8W8A8W8A16Strategy,
Nvfp4W4A4W4A16Strategy,
)
PrecisionPath = Literal["reasoner", "generation"]
_STRATEGIES: tuple[Cosmos3PrecisionStrategy, ...] = (
Fp8W8A8W8A16Strategy(),
Nvfp4W4A4W4A16Strategy(),
)
def _strategy_for(method: object | None) -> Cosmos3PrecisionStrategy | None:
return next((strategy for strategy in _STRATEGIES if strategy.accepts(method)), None)
class Cosmos3MixedPrecisionLinearMethod(LinearMethodBase):
"""Dispatch between a checkpoint-native method and dense A16."""
def __init__(
self,
base_method: LinearMethodBase,
strategy: Cosmos3PrecisionStrategy,
runtime: Cosmos3MixedPrecisionRuntime,
module_name: str,
path: PrecisionPath,
) -> None:
self.base_method = base_method
self.strategy = strategy
self.runtime = runtime
self.module_name = module_name
self.path = path
def create_weights(self, *args, **kwargs) -> None:
self.base_method.create_weights(*args, **kwargs)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.strategy.validate_before_processing(
self.base_method,
layer,
self.module_name,
)
self.base_method.process_weights_after_loading(layer)
self.strategy.validate_after_processing(layer, self.module_name)
def apply(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
if not self.runtime.use_high_precision(self.path):
return self.base_method.apply(layer, x, bias)
return self.strategy.apply_high(layer, x, bias)
class Cosmos3MixedPrecisionRuntime:
"""Own one transformer's schedule state and wrapped linear inventory."""
def __init__(self, config: Cosmos3MixedPrecisionConfig) -> None:
self.config = config
# TODO: Make this request-local before Cosmos3 supports interleaved
# denoising requests on one transformer instance.
self._generation_high_precision = False
def install(self, transformer: torch.nn.Module) -> None:
components: dict[PrecisionPath, torch.nn.Module] = {
"generation": transformer.gen_layers,
}
if self.config.reasoner == "a16":
components["reasoner"] = transformer.language_model.layers
wrapped_count = 0
for path, component in components.items():
for local_name, layer in component.named_modules():
if not isinstance(layer, LinearBase):
continue
base_method = getattr(layer, "quant_method", None)
strategy = _strategy_for(base_method)
if strategy is None:
continue
module_name = getattr(layer, "prefix", None) or f"{path}.{local_name}"
layer.quant_method = Cosmos3MixedPrecisionLinearMethod(
base_method,
strategy,
self,
module_name,
path,
)
wrapped_count += 1
if not wrapped_count:
raise ValueError("Cosmos3 mixed precision found no compatible FP8 or NVFP4 ModelOpt linears")
def use_high_precision(self, path: PrecisionPath) -> bool:
return self.config.reasoner == "a16" if path == "reasoner" else self._generation_high_precision
def set_step(self, step_index: int, num_steps: int) -> None:
self._generation_high_precision = self.config.use_high_precision(step_index, num_steps)
def reset(self) -> None:
self._generation_high_precision = False
@@ -0,0 +1,218 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Format-specific live-weight validation and reference A16 materialization."""
from __future__ import annotations
import torch
import torch.nn.functional as F
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptFp8LinearMethod,
ModelOptNvFp4LinearMethod,
)
from vllm.model_executor.layers.quantization.utils import nvfp4_emulation_utils
_NVFP4_BLOCK_SIZE = 16
class Cosmos3PrecisionStrategy:
"""Quantization-format boundary behind the shared precision schedule."""
def accepts(self, method: object | None) -> bool:
"""Return whether this strategy owns a native linear method."""
raise NotImplementedError
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
"""Reject native transforms that cannot support live dequantization."""
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
"""Validate the live native weight representation."""
raise NotImplementedError
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
"""Materialize the live quantized weight as a dense BF16 matrix."""
raise NotImplementedError
def apply_high(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None,
) -> torch.Tensor:
"""Apply the reference dense A16 path."""
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
weight = self.materialize(layer)
expected_shape = (output_size, input_size)
if tuple(weight.shape) != expected_shape:
raise RuntimeError(f"Dense weight shape {tuple(weight.shape)} does not match {expected_shape}")
x_2d = x.reshape(-1, x.shape[-1])
if x_2d.shape[1] != input_size:
raise ValueError(f"Expected activation width {input_size}, got {x_2d.shape[1]}")
weight = weight.to(dtype=x.dtype)
if bias is not None and bias.dtype != x.dtype:
bias = bias.to(dtype=x.dtype)
output = F.linear(x_2d, weight, bias)
return output.view(*x.shape[:-1], output_size)
class Fp8W8A8W8A16Strategy(Cosmos3PrecisionStrategy):
"""Use native ModelOpt W8A8 or reference dense W8A16."""
def accepts(self, method: object | None) -> bool:
return isinstance(method, ModelOptFp8LinearMethod)
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
if hasattr(layer, "pre_quant_scale"):
raise ValueError(f"{module_name} uses unsupported SmoothQuant pre_quant_scale")
weight_scale = getattr(layer, "weight_scale", None)
if not isinstance(weight_scale, torch.Tensor) or weight_scale.numel() != 1:
raise ValueError(f"{module_name} requires serialized tensorwise FP8 weights")
fp8_kernel = getattr(method, "fp8_linear", None)
from vllm.model_executor.kernels.linear.scaled_mm.marlin import (
MarlinFP8ScaledMMLinearKernel,
)
if isinstance(fp8_kernel, MarlinFP8ScaledMMLinearKernel):
raise ValueError(
f"{module_name} selected Marlin FP8, which repacks the only weight copy; "
"use a backend that retains canonical FP8 weights"
)
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
weight = getattr(layer, "weight", None)
scale = getattr(layer, "weight_scale", None)
if not isinstance(weight, torch.Tensor) or weight.dtype != torch.float8_e4m3fn:
dtype = getattr(weight, "dtype", None)
raise TypeError(f"{module_name} requires a canonical FP8 weight, got {dtype}")
if weight.ndim != 2:
raise ValueError(f"{module_name} requires a rank-2 FP8 weight, got {tuple(weight.shape)}")
if not isinstance(scale, torch.Tensor):
raise ValueError(f"{module_name} has an FP8 weight but no weight_scale")
if scale.numel() != 1:
raise ValueError(f"{module_name} requires one live FP8 weight scale")
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
if weight.shape[0] < input_size or weight.shape[1] < output_size:
raise ValueError(
f"{module_name} live FP8 weight shape {tuple(weight.shape)} does not cover "
f"(K, N)=({input_size}, {output_size})"
)
_validate_positive_finite_scale(scale, module_name)
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
input_size = int(layer.input_size_per_partition)
output_size = int(layer.output_size_per_partition)
weight = layer.weight[:input_size, :output_size]
scale = layer.weight_scale.reshape(1).to(device=weight.device, dtype=torch.float32)
return (weight.to(torch.float32) * scale).t().to(torch.bfloat16)
class Nvfp4W4A4W4A16Strategy(Cosmos3PrecisionStrategy):
"""Use native ModelOpt W4A4 or reference dense W4A16."""
def accepts(self, method: object | None) -> bool:
return isinstance(method, ModelOptNvFp4LinearMethod)
def validate_before_processing(
self,
method: object,
layer: torch.nn.Module,
module_name: str,
) -> None:
kernel = getattr(method, "kernel", None)
from vllm.model_executor.kernels.linear.nvfp4.cutlass import (
CutlassNvFp4LinearKernel,
)
from vllm.model_executor.kernels.linear.nvfp4.flashinfer import (
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
)
compatible_kernels = (
CutlassNvFp4LinearKernel,
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
)
if not isinstance(kernel, compatible_kernels):
kernel_name = type(kernel).__name__ if kernel is not None else "none"
raise ValueError(
f"{module_name} selected unsupported NVFP4 backend {kernel_name}; "
"live W4A16 dequantization requires a CUTLASS-compatible layout"
)
global_scale = _nvfp4_global_scale(layer)
if global_scale is None or global_scale.numel() != 1:
raise ValueError(f"{module_name} is missing ModelOpt NVFP4 scales")
def validate_after_processing(
self,
layer: torch.nn.Module,
module_name: str,
) -> None:
packed = getattr(layer, "weight", None)
scale = getattr(layer, "weight_scale", None)
global_scale = getattr(layer, "weight_global_scale", None)
if not isinstance(packed, torch.Tensor) or packed.dtype != torch.uint8:
dtype = getattr(packed, "dtype", None)
raise TypeError(f"{module_name} requires a live packed NVFP4 weight, got {dtype}")
if not isinstance(scale, torch.Tensor) or not isinstance(global_scale, torch.Tensor):
raise ValueError(f"{module_name} is missing live NVFP4 scales")
output_size = int(layer.output_size_per_partition)
input_size = int(layer.input_size_per_partition)
if input_size % _NVFP4_BLOCK_SIZE != 0:
raise ValueError(f"{module_name} input size {input_size} is not divisible by {_NVFP4_BLOCK_SIZE}")
expected_weight = (output_size, input_size // 2)
if packed.shape[0] < expected_weight[0] or packed.shape[1] < expected_weight[1]:
raise ValueError(
f"{module_name} live NVFP4 weight shape {tuple(packed.shape)} does not cover {expected_weight}"
)
_validate_positive_finite_scale(global_scale, module_name)
lut_handle = nvfp4_emulation_utils.kE2M1ToFloat_handle
if lut_handle.val.device != packed.device:
lut_handle.val = lut_handle.val.to(packed.device)
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
output_size = int(layer.output_size_per_partition)
input_size = int(layer.input_size_per_partition)
packed = layer.weight[:output_size, : input_size // 2]
return nvfp4_emulation_utils.dequantize_to_dtype(
packed,
layer.weight_scale,
layer.weight_global_scale,
torch.bfloat16,
_NVFP4_BLOCK_SIZE,
True,
)
def _validate_positive_finite_scale(scale: torch.Tensor, module_name: str) -> None:
values = scale.detach().float()
if not torch.isfinite(values).all() or not (values > 0).all():
raise ValueError(f"{module_name} has a non-finite or non-positive weight scale")
def _nvfp4_global_scale(layer: torch.nn.Module) -> torch.Tensor | None:
for name in ("weight_scale_2", "weight_global_scale"):
value = getattr(layer, name, None)
if isinstance(value, torch.Tensor):
return value
return None