[Attention] Add trtllm diffusion attention backend with Skip-Softmax (#5283)
Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com>
This commit is contained in:
1 parent
4dd1b47f47
commit
7762d664d8
24 files changed
+1512
-52
No files matched your search
@@ -64,6 +64,7 @@ class DiffusionAttentionBackendEnum(Enum, metaclass=_DiffusionBackendEnumMeta):
|
||||
FLASHINFER_ATTN = "vllm_omni.diffusion.attention.backends.flashinfer_attn.FlashInferAttentionBackend"
|
||||
FLASH_ATTN_HUB = "vllm_omni.diffusion.attention.backends.flash_attn_hub.FlashAttentionHubBackend"
|
||||
FLASH_ATTN_3_HUB = "vllm_omni.diffusion.attention.backends.flash_attn_hub.FlashAttention3HubBackend"
|
||||
TRTLLM_ATTN = "vllm_omni.diffusion.attention.backends.trtllm_attn.TrtllmAttentionBackend"
|
||||
|
||||
def get_path(self, include_classname: bool = True) -> str:
|
||||
"""Get the class path for this backend (respects overrides).
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
AttentionBackend,
|
||||
AttentionImpl,
|
||||
AttentionMetadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _validate_control(value, name: str, lo: float, hi: float | None) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
v = float(value)
|
||||
if not math.isfinite(v) or v < lo or (hi is not None and v > hi):
|
||||
rng = f"in [{lo}, {hi}]" if hi is not None else f">= {lo}"
|
||||
raise ValueError(f"{name} must be finite and {rng}; got {value!r}.")
|
||||
return v
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkipSoftmaxConfig:
|
||||
threshold: float | None = None
|
||||
target_sparsity: float | None = None
|
||||
disabled_until_timestep: float = 0.0
|
||||
a: float | None = None
|
||||
b: float | None = None
|
||||
|
||||
@classmethod
|
||||
def from_backend_kwargs(cls, backend_kwargs: dict | None) -> "SkipSoftmaxConfig":
|
||||
bk = backend_kwargs or {}
|
||||
return cls(
|
||||
threshold=_validate_control(bk.get("skip_softmax_threshold"), "skip_softmax_threshold", 0.0, None),
|
||||
target_sparsity=_validate_control(bk.get("target_sparsity"), "target_sparsity", 0.0, 1.0),
|
||||
disabled_until_timestep=_validate_control(
|
||||
bk.get("disabled_until_timestep", 0.0), "disabled_until_timestep", 0.0, 1.0
|
||||
),
|
||||
)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.threshold is not None or (
|
||||
self.target_sparsity is not None and self.a is not None and self.b is not None
|
||||
)
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return self.threshold is not None or self.target_sparsity is not None
|
||||
|
||||
@property
|
||||
def gated(self) -> bool:
|
||||
return self.disabled_until_timestep > 0.0
|
||||
|
||||
def resolve_factor(self, seqlen: int, timestep: float | None) -> float | None:
|
||||
if self.threshold is not None:
|
||||
factor = self.threshold * seqlen
|
||||
elif self.target_sparsity is not None and self.a is not None and self.b is not None:
|
||||
factor = self.a * math.exp(self.b * self.target_sparsity)
|
||||
else:
|
||||
return None
|
||||
if self.gated and timestep is not None and timestep > self.disabled_until_timestep:
|
||||
return None
|
||||
return factor
|
||||
|
||||
|
||||
try:
|
||||
from flashinfer.prefill import trtllm_ragged_attention_deepseek
|
||||
|
||||
HAS_FLASHINFER = True
|
||||
except Exception as e: # pragma: no cover - import guard
|
||||
HAS_FLASHINFER = False
|
||||
logger.warning(
|
||||
"FlashInfer is unavailable; TRTLLM_ATTN backend will not work. Reason: %s",
|
||||
e,
|
||||
)
|
||||
|
||||
|
||||
def _workspace_bytes() -> int:
|
||||
import vllm.envs as envs
|
||||
|
||||
return getattr(envs, "VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", 394 * 1024 * 1024)
|
||||
|
||||
|
||||
class TrtllmAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
return [128]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "TRTLLM_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["TrtllmAttentionImpl"]:
|
||||
return TrtllmAttentionImpl
|
||||
|
||||
|
||||
class TrtllmAttentionImpl(AttentionImpl):
|
||||
_workspace: torch.Tensor | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
softmax_scale: float,
|
||||
causal: bool = False,
|
||||
num_kv_heads: int | None = None,
|
||||
prefix: str = "",
|
||||
qkv_layout: str | None = None,
|
||||
backend_kwargs: dict | None = None,
|
||||
**extra_impl_args,
|
||||
) -> None:
|
||||
self.num_heads = num_heads
|
||||
self.head_size = head_size
|
||||
self.softmax_scale = softmax_scale
|
||||
self.causal = causal
|
||||
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
||||
|
||||
self.skip = SkipSoftmaxConfig.from_backend_kwargs(backend_kwargs)
|
||||
self._warned_missing_timestep = False
|
||||
|
||||
def set_layer_calibration(self, a: float, b: float) -> None:
|
||||
self.skip = replace(self.skip, a=a, b=b)
|
||||
|
||||
def _resolve_skip_factor(self, seqlen: int) -> float | None:
|
||||
if not self.skip.enabled:
|
||||
return None
|
||||
|
||||
timestep = None
|
||||
if self.skip.gated:
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
|
||||
timestep = getattr(get_forward_context(), "denoise_timestep", None)
|
||||
if timestep is None:
|
||||
if not self._warned_missing_timestep:
|
||||
logger.warning(
|
||||
"TRTLLM skip: disabled_until_timestep=%s set but this pipeline does not "
|
||||
"publish denoise_timestep; staying dense. Have the pipeline call "
|
||||
"DenoiseProgressMixin.record_denoise_step to enable timestep gating.",
|
||||
self.skip.disabled_until_timestep,
|
||||
)
|
||||
self._warned_missing_timestep = True
|
||||
return None
|
||||
return self.skip.resolve_factor(seqlen, timestep)
|
||||
|
||||
@classmethod
|
||||
def _get_workspace(cls, device: torch.device) -> torch.Tensor:
|
||||
nbytes = _workspace_bytes()
|
||||
ws = cls._workspace
|
||||
if ws is None or ws.device != device or ws.numel() < nbytes:
|
||||
ws = torch.zeros(nbytes, dtype=torch.uint8, device=device)
|
||||
cls._workspace = ws
|
||||
return ws
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
attn_mask = getattr(attn_metadata, "attn_mask", None) if attn_metadata is not None else None
|
||||
if attn_mask is not None:
|
||||
raise ValueError(
|
||||
"TRTLLM_ATTN does not support attn_mask (Wan sets one only under SP with "
|
||||
"mask_sp_padding=True and a non-divisible seq len). Either set "
|
||||
"parallel_config.mask_sp_padding=False, or select a mask-capable backend "
|
||||
"(e.g. CUDNN_ATTN / TORCH_SDPA)."
|
||||
)
|
||||
|
||||
if not HAS_FLASHINFER:
|
||||
raise ImportError(
|
||||
"TRTLLM_ATTN backend requires flashinfer. Install it or select "
|
||||
"another backend via --diffusion-attention-backend."
|
||||
)
|
||||
|
||||
batch, q_len, num_q_heads, head_dim = query.shape
|
||||
kv_len, num_kv_heads = key.shape[1], key.shape[2]
|
||||
|
||||
device = query.device
|
||||
|
||||
q = query.reshape(batch * q_len, num_q_heads, head_dim).contiguous()
|
||||
k = key.reshape(batch * kv_len, num_kv_heads, head_dim).contiguous()
|
||||
v = value.reshape(batch * kv_len, num_kv_heads, head_dim).contiguous()
|
||||
|
||||
seq_lens = torch.full((batch,), kv_len, dtype=torch.int32, device=device)
|
||||
cu_seq_lens_q = torch.arange(0, (batch + 1) * q_len, step=q_len, dtype=torch.int32, device=device)
|
||||
cu_seq_lens_kv = torch.arange(0, (batch + 1) * kv_len, step=kv_len, dtype=torch.int32, device=device)
|
||||
workspace = self._get_workspace(device)
|
||||
|
||||
bmm1_scale = self.softmax_scale
|
||||
bmm2_scale = 1.0
|
||||
|
||||
_skip_factor = self._resolve_skip_factor(kv_len)
|
||||
|
||||
out = trtllm_ragged_attention_deepseek(
|
||||
query=q,
|
||||
key=k,
|
||||
value=v,
|
||||
workspace_buffer=workspace,
|
||||
seq_lens=seq_lens,
|
||||
max_q_len=q_len,
|
||||
max_kv_len=kv_len,
|
||||
bmm1_scale=bmm1_scale,
|
||||
bmm2_scale=bmm2_scale,
|
||||
o_sf_scale=-1.0,
|
||||
batch_size=batch,
|
||||
window_left=-1,
|
||||
cum_seq_lens_q=cu_seq_lens_q,
|
||||
cum_seq_lens_kv=cu_seq_lens_kv,
|
||||
enable_pdl=False,
|
||||
is_causal=self.causal,
|
||||
return_lse=False,
|
||||
skip_softmax_threshold_scale_factor=_skip_factor,
|
||||
)
|
||||
return out.reshape(batch, q_len, num_q_heads, head_dim)
|
||||
@@ -0,0 +1,152 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SUPPORTED_FORMULA = "a*exp(b*target_sparsity)"
|
||||
|
||||
|
||||
def parse_sparse_attention_config(sac: dict | None) -> dict | None:
|
||||
if not sac:
|
||||
return None
|
||||
group: dict = {}
|
||||
for g in (sac.get("config_groups") or {}).values():
|
||||
if isinstance(g, dict) and (g.get("algorithm") == "skip_softmax" or g.get("threshold_scale_factor")):
|
||||
group = g
|
||||
break
|
||||
tsf = group.get("threshold_scale_factor") or sac.get("threshold_scale_factor") or {}
|
||||
ab = tsf.get("coefficients") or tsf.get("prefill") or {}
|
||||
if "a" not in ab or "b" not in ab:
|
||||
return None
|
||||
|
||||
formula = (tsf.get("formula") or _SUPPORTED_FORMULA).replace(" ", "")
|
||||
if formula != _SUPPORTED_FORMULA:
|
||||
raise ValueError(
|
||||
f"unsupported skip-softmax formula {tsf.get('formula')!r}; this backend implements '{_SUPPORTED_FORMULA}'."
|
||||
)
|
||||
|
||||
return {"a": float(ab["a"]), "b": float(ab["b"]), "ignore": list(group.get("ignore") or [])}
|
||||
|
||||
|
||||
def parse_secondary_expert_calibration(model: str | None) -> dict | None:
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
if not model:
|
||||
return None
|
||||
try:
|
||||
cfg = get_hf_file_to_dict("transformer_2/config.json", model)
|
||||
return parse_sparse_attention_config(cfg.get("sparse_attention_config")) if cfg else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning(
|
||||
"Could not read transformer_2 skip-softmax calibration (%s); transformer_2 will stay uncalibrated (dense).",
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def propagate_skip_softmax_calibration(specs: list, model: str | None, tf_config: Any) -> None:
|
||||
calibration = parse_sparse_attention_config(
|
||||
tf_config.get("sparse_attention_config") if tf_config is not None else None
|
||||
)
|
||||
if calibration is not None:
|
||||
by_expert = {"transformer": calibration}
|
||||
ckpt2 = parse_secondary_expert_calibration(model)
|
||||
if ckpt2 is not None:
|
||||
by_expert["transformer_2"] = ckpt2
|
||||
calibration = {"by_expert": by_expert}
|
||||
|
||||
if calibration is None:
|
||||
for spec in specs:
|
||||
ss = spec.skip_softmax
|
||||
if ss is not None and ss.target_sparsity is not None and ss.threshold is None:
|
||||
raise ValueError(
|
||||
f"target_sparsity was requested but the checkpoint for model '{model}' carries no "
|
||||
f"skip-softmax calibration. Either set skip_softmax.threshold for the "
|
||||
f"calibration-free path or load a calibrated checkpoint."
|
||||
)
|
||||
return
|
||||
|
||||
for spec in specs:
|
||||
if spec.skip_calibration is None:
|
||||
spec.skip_calibration = calibration
|
||||
|
||||
experts = list(calibration["by_expert"])
|
||||
logger.info("Loaded skip-softmax calibration from checkpoint (%d curve(s): %s).", len(experts), ", ".join(experts))
|
||||
|
||||
|
||||
def apply_skip_softmax_calibration(attention_config: Any, model: Any) -> None:
|
||||
cfg = attention_config
|
||||
specs = getattr(cfg, "per_role", None)
|
||||
calibration = None
|
||||
for spec in (getattr(cfg, "default", None), *(specs.values() if specs else ())):
|
||||
calibration = calibration or getattr(spec, "skip_calibration", None)
|
||||
if not calibration:
|
||||
return
|
||||
|
||||
stamped = apply_to_pipeline(model, calibration)
|
||||
logger.info("Skip-softmax: stamped calibration onto %d attention layer(s).", stamped)
|
||||
|
||||
|
||||
_EXPERT_PREFIXES = ("transformer.", "transformer_2.")
|
||||
|
||||
|
||||
def layer_match_names(module_name: str) -> tuple[str, ...]:
|
||||
names = {module_name, module_name.replace("._orig_mod.", ".")}
|
||||
for name in tuple(names):
|
||||
for pfx in _EXPERT_PREFIXES:
|
||||
if name.startswith(pfx):
|
||||
names.add(name[len(pfx) :])
|
||||
return tuple(names)
|
||||
|
||||
|
||||
def is_ignored(module_name: str, ignore_patterns) -> bool:
|
||||
names = layer_match_names(module_name)
|
||||
for p in ignore_patterns or ():
|
||||
for n in names:
|
||||
if fnmatch.fnmatch(n, p) or fnmatch.fnmatch(n, p + ".*"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def select_expert(module_name: str, expert_keys) -> str | None:
|
||||
for key in sorted(expert_keys or (), key=len, reverse=True):
|
||||
if module_name == key or module_name.startswith(key + "."):
|
||||
return key
|
||||
return None
|
||||
|
||||
|
||||
def resolve_layer_calibration(module_name: str, calibration: dict) -> dict | None:
|
||||
if not calibration:
|
||||
return None
|
||||
by_expert = calibration.get("by_expert")
|
||||
if by_expert:
|
||||
key = select_expert(module_name, by_expert.keys())
|
||||
if key is None:
|
||||
return None
|
||||
entry = by_expert[key]
|
||||
else:
|
||||
entry = calibration
|
||||
if is_ignored(module_name, entry.get("ignore")):
|
||||
return None
|
||||
return {"a": entry.get("a"), "b": entry.get("b")}
|
||||
|
||||
|
||||
def apply_to_pipeline(pipeline, calibration: dict) -> int:
|
||||
if not calibration:
|
||||
return 0
|
||||
stamped = 0
|
||||
for name, module in pipeline.named_modules():
|
||||
impl = getattr(module, "attention", None)
|
||||
set_layer = getattr(impl, "set_layer_calibration", None)
|
||||
if set_layer is None:
|
||||
continue
|
||||
per = resolve_layer_calibration(name, calibration)
|
||||
if per and per.get("a") is not None and per.get("b") is not None:
|
||||
set_layer(per["a"], per["b"])
|
||||
stamped += 1
|
||||
return stamped
|
||||
@@ -77,14 +77,20 @@ class Attention(nn.Module):
|
||||
config = get_current_diffusion_config_or_none()
|
||||
attention_config = config.diffusion_attention_config if config is not None else None
|
||||
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
|
||||
model_class_name = getattr(config, "model_class_name", None) if config is not None else None
|
||||
allow_trtllm_default = get_diffusion_model_metadata(model_class_name).attention_mask_free
|
||||
|
||||
attn_backend_cls, spec = get_attn_backend_for_role(
|
||||
role=role,
|
||||
head_size=head_size,
|
||||
attention_config=attention_config,
|
||||
role_category=role_category,
|
||||
allow_trtllm_default=allow_trtllm_default,
|
||||
)
|
||||
if spec is not None:
|
||||
backend_kwargs = spec.extra or None
|
||||
backend_kwargs = spec.backend_kwargs()
|
||||
self.backend_pref = spec.backend
|
||||
logger.debug("Attention(role=%s) → backend=%s", role, spec.backend)
|
||||
else:
|
||||
@@ -99,6 +105,7 @@ class Attention(nn.Module):
|
||||
causal=causal,
|
||||
num_kv_heads=num_kv_heads,
|
||||
qkv_layout=qkv_layout,
|
||||
prefix=prefix,
|
||||
backend_kwargs=backend_kwargs,
|
||||
)
|
||||
# Instantiate fallback backend for float32 support
|
||||
@@ -310,6 +317,13 @@ class Attention(nn.Module):
|
||||
)
|
||||
|
||||
def _run_ring_attention(self, query, key, value, attn_metadata):
|
||||
skip = getattr(self.attention, "skip", None)
|
||||
if skip is not None and getattr(skip, "configured", False):
|
||||
raise NotImplementedError(
|
||||
"Skip-Softmax (TRTLLM_ATTN) is not supported with ring sequence parallelism: "
|
||||
"the ring path bypasses the backend, so the skip config would be silently ignored. "
|
||||
"Use Ulysses SP instead, or remove the skip_softmax config."
|
||||
)
|
||||
# Delegate to RingParallelAttention strategy if available
|
||||
if self.ring_runner is not None:
|
||||
return self.ring_runner.run_attention(
|
||||
|
||||
@@ -51,18 +51,20 @@ def _load_backend_cls(cls_path: str) -> type[AttentionBackend]:
|
||||
def _cached_get_backend_cls(
|
||||
backend_name: str | None,
|
||||
head_size: int,
|
||||
allow_trtllm_default: bool = True,
|
||||
) -> type[AttentionBackend]:
|
||||
"""Cache backend class resolution by (backend_name, head_size).
|
||||
"""Cache backend class resolution by (backend_name, head_size, allow_trtllm_default).
|
||||
|
||||
This ensures platform validation (compute capability checks, package
|
||||
availability, etc.) runs only once per unique (backend_name, head_size)
|
||||
combination, avoiding repeated log messages.
|
||||
availability, etc.) runs only once per unique combination, avoiding
|
||||
repeated log messages.
|
||||
"""
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
backend_cls_path = current_omni_platform.get_diffusion_attn_backend_cls(
|
||||
selected_backend=backend_name,
|
||||
head_size=head_size,
|
||||
allow_trtllm_default=allow_trtllm_default,
|
||||
)
|
||||
return _load_backend_cls(backend_cls_path)
|
||||
|
||||
@@ -97,6 +99,7 @@ def get_attn_backend_for_role(
|
||||
head_size: int,
|
||||
attention_config: AttentionConfig | None = None,
|
||||
role_category: str | None = None,
|
||||
allow_trtllm_default: bool = True,
|
||||
) -> tuple[type[AttentionBackend], AttentionSpec | None]:
|
||||
"""
|
||||
Get attention backend for a specific attention role.
|
||||
@@ -140,7 +143,7 @@ def get_attn_backend_for_role(
|
||||
return backend_cls, spec
|
||||
|
||||
# 2. Platform default
|
||||
backend_cls = _cached_get_backend_cls(None, head_size)
|
||||
backend_cls = _cached_get_backend_cls(None, head_size, allow_trtllm_default)
|
||||
_log_backend_resolution(
|
||||
role=role,
|
||||
role_category=role_category,
|
||||
|
||||
+80
-11
@@ -2,6 +2,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import copy
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
from collections.abc import Callable, Mapping
|
||||
@@ -1070,6 +1071,19 @@ class OmniDiffusionConfig:
|
||||
"""
|
||||
self.tf_model_config = tf_config
|
||||
self._propagate_quantization_from_tf_config(tf_config)
|
||||
self._propagate_skip_softmax_calibration(tf_config)
|
||||
|
||||
def _propagate_skip_softmax_calibration(self, tf_config: "TransformerConfig") -> None:
|
||||
cfg = getattr(self, "diffusion_attention_config", None)
|
||||
if not isinstance(cfg, AttentionConfig):
|
||||
return
|
||||
specs = [s for s in (cfg.default, *cfg.per_role.values()) if s is not None]
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.trtllm_calibration import (
|
||||
propagate_skip_softmax_calibration,
|
||||
)
|
||||
|
||||
propagate_skip_softmax_calibration(specs, self.model, tf_config)
|
||||
|
||||
def update_multimodal_support(self) -> None:
|
||||
# Resolve serving-visible multimodal behavior from shared metadata
|
||||
@@ -1323,23 +1337,78 @@ class DiffusionRequestAbortedError(RuntimeError):
|
||||
"""Raised when a diffusion request ends via user-visible abort."""
|
||||
|
||||
|
||||
def _in_range(value: Any, name: str, lo: float, hi: float | None) -> float | None:
|
||||
"""Validate an optional numeric control at config-parse time."""
|
||||
if value is None:
|
||||
return None
|
||||
x = float(value)
|
||||
if not math.isfinite(x) or x < lo or (hi is not None and x > hi):
|
||||
rng = f"in [{lo}, {hi}]" if hi is not None else f">= {lo}"
|
||||
raise ValueError(f"{name} must be finite and {rng}; got {value!r}.")
|
||||
return x
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkipSoftmaxSpec:
|
||||
"""User-facing skip-softmax controls for the TRTLLM_ATTN backend.
|
||||
|
||||
``target_sparsity`` uses the checkpoint's calibrated curve (a·exp(b·s)); ``threshold``
|
||||
is the calibration-free absolute skip threshold. They are mutually exclusive.
|
||||
"""
|
||||
|
||||
target_sparsity: float | None = None
|
||||
threshold: float | None = None
|
||||
disabled_until_timestep: float = 0.0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.target_sparsity = _in_range(self.target_sparsity, "skip_softmax.target_sparsity", 0.0, 1.0)
|
||||
self.threshold = _in_range(self.threshold, "skip_softmax.threshold", 0.0, None)
|
||||
self.disabled_until_timestep = (
|
||||
_in_range(self.disabled_until_timestep, "skip_softmax.disabled_until_timestep", 0.0, 1.0) or 0.0
|
||||
)
|
||||
if self.target_sparsity is not None and self.threshold is not None:
|
||||
raise ValueError("skip_softmax: set either target_sparsity or threshold, not both.")
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionSpec:
|
||||
"""Specifies a backend and its backend-specific parameters for one attention role."""
|
||||
"""Specifies a backend and its typed backend-specific config for one attention role."""
|
||||
|
||||
backend: str # registry name, e.g. "FLASH_ATTN"
|
||||
extra: dict[str, Any] = field(default_factory=dict) # backend-specific kwargs
|
||||
backend: str
|
||||
skip_softmax: SkipSoftmaxSpec | None = None
|
||||
skip_calibration: dict | None = field(default=None, repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.backend, str):
|
||||
raise TypeError(f"Expected str for AttentionSpec.backend, got {type(self.backend)!r}")
|
||||
self.skip_softmax = self._coerce_skip_softmax(self.skip_softmax)
|
||||
if self.skip_softmax is not None and self.backend.upper() != "TRTLLM_ATTN":
|
||||
raise ValueError(
|
||||
f"skip_softmax is only supported by the TRTLLM_ATTN backend, but backend={self.backend!r}. "
|
||||
f"Remove skip_softmax or set backend to TRTLLM_ATTN."
|
||||
)
|
||||
|
||||
if self.extra is None:
|
||||
self.extra = {}
|
||||
elif isinstance(self.extra, Mapping):
|
||||
self.extra = dict(self.extra)
|
||||
else:
|
||||
raise TypeError(f"Expected dict for AttentionSpec.extra, got {type(self.extra)!r}")
|
||||
@staticmethod
|
||||
def _coerce_skip_softmax(value: Any) -> SkipSoftmaxSpec | None:
|
||||
if value is None or isinstance(value, SkipSoftmaxSpec):
|
||||
return value
|
||||
if isinstance(value, Mapping):
|
||||
return SkipSoftmaxSpec(**dict(value))
|
||||
raise TypeError(f"Expected dict or SkipSoftmaxSpec for skip_softmax, got {type(value)!r}")
|
||||
|
||||
def backend_kwargs(self) -> dict[str, Any] | None:
|
||||
"""Serialize typed backend config into the kwargs dict the backend impl consumes."""
|
||||
if self.skip_softmax is None:
|
||||
return None
|
||||
ss = self.skip_softmax
|
||||
kw: dict[str, Any] = {}
|
||||
if ss.threshold is not None:
|
||||
kw["skip_softmax_threshold"] = ss.threshold
|
||||
if ss.target_sparsity is not None:
|
||||
kw["target_sparsity"] = ss.target_sparsity
|
||||
if ss.disabled_until_timestep:
|
||||
kw["disabled_until_timestep"] = ss.disabled_until_timestep
|
||||
return kw or None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -1408,13 +1477,13 @@ class AttentionConfig:
|
||||
normalized[role] = node
|
||||
return
|
||||
|
||||
spec_keys = {"backend", "extra"}
|
||||
spec_keys = {"backend", "skip_softmax"}
|
||||
node_dict = dict(node)
|
||||
node_keys = set(node_dict)
|
||||
if node_keys & spec_keys:
|
||||
if not node_keys <= spec_keys:
|
||||
raise ValueError(
|
||||
f"Invalid per_role entry for role {role!r}: cannot mix backend/extra with nested role keys."
|
||||
f"Invalid per_role entry for role {role!r}: cannot mix backend/skip_softmax with nested role keys."
|
||||
)
|
||||
normalized[role] = node_dict
|
||||
return
|
||||
|
||||
@@ -28,6 +28,7 @@ class ForwardContext:
|
||||
attn_metadata: dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None = None
|
||||
split_text_embed_in_sp: bool = False
|
||||
denoise_step_idx: int | None = None
|
||||
denoise_timestep: float | None = None
|
||||
# Per-request reference latent for img2img DiT models (e.g. Ming)
|
||||
ref_latent: torch.Tensor | None = None
|
||||
# whether to split the text embed in sequence parallel, if True, the text embed will be split in sequence parallel
|
||||
@@ -214,6 +215,21 @@ def set_forward_context_denoise_step_idx(step_idx: int | None) -> None:
|
||||
_forward_context.denoise_step_idx = step_idx
|
||||
|
||||
|
||||
class DenoiseProgressMixin:
|
||||
def record_denoise_step(
|
||||
self,
|
||||
step_idx: int | None,
|
||||
timestep=None,
|
||||
scheduler=None,
|
||||
) -> None:
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
if timestep is None or _forward_context is None:
|
||||
return
|
||||
scheduler = scheduler if scheduler is not None else getattr(self, "scheduler", None)
|
||||
ntt = getattr(getattr(scheduler, "config", None), "num_train_timesteps", None)
|
||||
_forward_context.denoise_timestep = float(timestep) / ntt if ntt else None
|
||||
|
||||
|
||||
def set_forward_context_ref_latent(ref_latent: torch.Tensor | None) -> None:
|
||||
"""Set the per-request reference latent on the active ForwardContext.
|
||||
|
||||
|
||||
@@ -378,6 +378,7 @@ class DiffusersPipelineLoader:
|
||||
model.to("cpu")
|
||||
logger.info("Quantization complete, offloaded model back to CPU")
|
||||
|
||||
self._apply_skip_softmax_calibration(model)
|
||||
return model.eval()
|
||||
|
||||
@staticmethod
|
||||
@@ -391,6 +392,14 @@ class DiffusersPipelineLoader:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _apply_skip_softmax_calibration(self, model: nn.Module) -> None:
|
||||
from vllm_omni.diffusion.attention.backends.trtllm_calibration import (
|
||||
apply_skip_softmax_calibration,
|
||||
)
|
||||
|
||||
cfg = getattr(self.od_config, "diffusion_attention_config", None)
|
||||
apply_skip_softmax_calibration(cfg, model)
|
||||
|
||||
def _process_weights_after_loading(self, model: nn.Module, target_device: torch.device) -> None:
|
||||
"""Process weights after loading for quantization methods.
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ class DiffusionModelMetadata:
|
||||
# config/model plumbing can read it without importing concrete pipelines.
|
||||
supports_multimodal_inputs: bool = False
|
||||
max_multimodal_image_inputs: int | None = None
|
||||
attention_mask_free: bool = False
|
||||
|
||||
|
||||
QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES = 4
|
||||
@@ -35,6 +36,10 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=BOOGU_IMAGE_MAX_INPUT_IMAGES,
|
||||
),
|
||||
"WanPipeline": DiffusionModelMetadata(attention_mask_free=True),
|
||||
"WanImageToVideoPipeline": DiffusionModelMetadata(attention_mask_free=True),
|
||||
"WanVACEPipeline": DiffusionModelMetadata(attention_mask_free=True),
|
||||
"WanS2VPipeline": DiffusionModelMetadata(attention_mask_free=True),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import Dist
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -264,6 +264,7 @@ class Wan22Pipeline(
|
||||
PipelineParallelMixin,
|
||||
CFGParallelMixin,
|
||||
ProgressBarMixin,
|
||||
DenoiseProgressMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
SupportsComponentDiscovery,
|
||||
):
|
||||
@@ -460,7 +461,7 @@ class Wan22Pipeline(
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
self.record_denoise_step(step_idx, t)
|
||||
|
||||
# Select model based on timestep and boundary_ratio
|
||||
# High noise stage (t >= boundary_timestep): use transformer
|
||||
|
||||
@@ -24,7 +24,7 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import Dist
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -144,6 +144,7 @@ class Wan22I2VPipeline(
|
||||
CFGParallelMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
DenoiseProgressMixin,
|
||||
SupportsComponentDiscovery,
|
||||
):
|
||||
"""
|
||||
@@ -354,7 +355,7 @@ class Wan22I2VPipeline(
|
||||
current_model = self.transformer_2
|
||||
current_guidance_scale = guidance_high
|
||||
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
self.record_denoise_step(step_idx, t)
|
||||
|
||||
# Prepare latent input
|
||||
if self.expand_timesteps:
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioInput, SupportImageInput
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
@@ -462,7 +463,13 @@ def _load_wan_t5_as_umt5(
|
||||
|
||||
|
||||
class Wan22S2VPipeline(
|
||||
nn.Module, SupportImageInput, SupportAudioInput, CFGParallelMixin, ProgressBarMixin, DiffusionPipelineProfilerMixin
|
||||
nn.Module,
|
||||
SupportImageInput,
|
||||
SupportAudioInput,
|
||||
CFGParallelMixin,
|
||||
DenoiseProgressMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
):
|
||||
"""
|
||||
Wan2.2 Speech-to-Video Pipeline.
|
||||
@@ -993,8 +1000,9 @@ class Wan22S2VPipeline(
|
||||
do_true_cfg = self.do_classifier_free_guidance and negative_prompt_embeds is not None
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
self.record_denoise_step(step_idx, t)
|
||||
|
||||
latent_model_input = [latents.to(device)]
|
||||
timestep = t.unsqueeze(0).to(device) if t.dim() == 0 else t.to(device)
|
||||
|
||||
@@ -25,7 +25,6 @@ from vllm.model_executor.layers.quantization.base_config import QuantizationConf
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
Wan22Pipeline,
|
||||
@@ -204,7 +203,7 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
self.record_denoise_step(step_idx, t)
|
||||
|
||||
if boundary_timestep is not None and t < boundary_timestep and self.transformer_2 is not None:
|
||||
current_model = self.transformer_2
|
||||
|
||||
Reference in new issue
Block a user