[CI] Select mirror_hardwares presets via MIRROR_HW (H100/B200) (#5543)
Signed-off-by: wangyu <410167048@qq.com> Signed-off-by: lishunyang12 <lishunyang12@163.com> Signed-off-by: [Your Name] <your.email@example.com> Signed-off-by: wangyu <53896905+yenuo26@users.noreply.github.com> Signed-off-by: Bo Li <22713281+bobboli@users.noreply.github.com> Co-authored-by: lishunyang12 <lishunyang12@163.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Bo Li <22713281+bobboli@users.noreply.github.com>
This commit is contained in:
77 files changed
+3470
-1077
No files matched your search
@@ -18,6 +18,7 @@ import torch
|
||||
|
||||
import vllm_omni.diffusion.attention.layer as layer_mod
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionBackend
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.config import (
|
||||
get_current_diffusion_config,
|
||||
@@ -73,6 +74,12 @@ class TestAttentionSpec:
|
||||
assert bk["dtype_vo"] == "fp8_e4m3"
|
||||
assert bk["flashinfer_backend"] == "trtllm-gen"
|
||||
|
||||
def test_quant_flashinfer_backend_serialized_without_dtype(self):
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN", quant={"flashinfer_backend": "fa2"})
|
||||
assert spec.quant is not None
|
||||
assert spec.quant.enabled is True
|
||||
assert spec.backend_kwargs() == {"quant": {"flashinfer_backend": "fa2"}}
|
||||
|
||||
def test_quant_and_skip_softmax_coexist(self):
|
||||
bk = AttentionSpec(
|
||||
backend="TRTLLM_ATTN", quant={"dtype_qk": "int8"}, skip_softmax={"target_sparsity": 0.5}
|
||||
@@ -150,8 +157,8 @@ class TestAttentionSpec:
|
||||
def test_block_sparse_precision_enum_input_normalized(self):
|
||||
"""RainFusionPrecision enum members must normalize to their string value.
|
||||
|
||||
Regression: the str,Enum members passed the value check but str() later
|
||||
produced "RainFusionPrecision.MIX" instead of "mix" (StrEnum fixes it).
|
||||
Regression: ``str(str, Enum)`` later produced ``RainFusionPrecision.MIX``
|
||||
instead of ``mix``. ``BlockSparseSpec`` stores ``member.value``.
|
||||
"""
|
||||
from vllm_omni.diffusion.attention.backends.rainfusion_attn import RainFusionConfig
|
||||
from vllm_omni.diffusion.data import RainFusionPrecision
|
||||
@@ -509,6 +516,49 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
|
||||
dense_flash.assert_not_called()
|
||||
sdpa.assert_called_once()
|
||||
|
||||
@pytest.mark.parametrize("fa4_available", [False, True])
|
||||
def test_paged_cuda_memory_profile_uses_sdpa_without_dense_fa4(self, monkeypatch, fa4_available):
|
||||
attention = Attention.__new__(Attention)
|
||||
attention._scheduler_paged_kv = True
|
||||
attention.paged_kv_cache_role = "primary"
|
||||
attention.backend_pref = "FLASH_ATTN"
|
||||
attention.attn_backend = SimpleNamespace(supports_piecewise_spans=True, get_name=lambda: "FLASH_ATTN")
|
||||
flash_output = torch.ones(1)
|
||||
sdpa_output = torch.zeros(1)
|
||||
dense_flash = Mock(return_value=flash_output)
|
||||
sdpa = Mock(return_value=sdpa_output)
|
||||
attention.attention = SimpleNamespace(forward=dense_flash)
|
||||
attention.sdpa_fallback = SimpleNamespace(forward=sdpa)
|
||||
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
layer_mod,
|
||||
"get_forward_context",
|
||||
lambda: SimpleNamespace(in_diffusion_kv_memory_profile=True),
|
||||
)
|
||||
monkeypatch.setattr(layer_mod.current_omni_platform, "is_npu", lambda: False)
|
||||
monkeypatch.setattr(layer_mod.current_omni_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
layer_mod.current_omni_platform,
|
||||
"supports_diffusion_dense_flash_attention",
|
||||
lambda: fa4_available,
|
||||
)
|
||||
|
||||
result = attention._run_local_attention(
|
||||
torch.zeros(1, dtype=torch.bfloat16),
|
||||
torch.zeros(1, dtype=torch.bfloat16),
|
||||
torch.zeros(1, dtype=torch.bfloat16),
|
||||
AttentionMetadata(),
|
||||
)
|
||||
|
||||
if fa4_available:
|
||||
assert result is flash_output
|
||||
dense_flash.assert_called_once()
|
||||
sdpa.assert_not_called()
|
||||
else:
|
||||
assert result is sdpa_output
|
||||
dense_flash.assert_not_called()
|
||||
sdpa.assert_called_once()
|
||||
|
||||
def test_dense_flash_import_error_is_not_reclassified(self, monkeypatch):
|
||||
attention = Attention.__new__(Attention)
|
||||
attention._scheduler_paged_kv = False
|
||||
@@ -579,7 +629,106 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
|
||||
|
||||
assert len(calls) == 1
|
||||
assert attention.attn_backend is _DenseBackend
|
||||
assert attention.backend_pref is None
|
||||
# Auto path records the resolved backend name for Ring/SP; it is not explicit.
|
||||
assert attention.backend_pref == _DenseBackend.get_name()
|
||||
assert attention.backend_explicit is False
|
||||
|
||||
def test_internal_paged_selector_does_not_require_dense_fa4(self, monkeypatch):
|
||||
"""Blackwell CUDNN default + marked paged layer must not act as explicit FLASH_ATTN."""
|
||||
|
||||
class _FakeAttentionImpl:
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
|
||||
def forward(self, query, key, value, attn_metadata=None):
|
||||
return query
|
||||
|
||||
class _CuDNNBackend:
|
||||
supports_paged_kv = False
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "CUDNN_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls():
|
||||
return _FakeAttentionImpl
|
||||
|
||||
def _fake_get_attn_backend_for_role(*args, attention_config=None, **kwargs):
|
||||
if attention_config is not None:
|
||||
spec, _ = attention_config.resolve_with_source(role="self", role_category=None)
|
||||
if spec is not None and spec.backend.upper() == "FLASH_ATTN":
|
||||
raise ValueError(
|
||||
"FLASH_ATTN was explicitly selected but is unsupported "
|
||||
"(Blackwell requires CuTe FlashAttention-4 "
|
||||
"(flash_attn.cute / vllm-omni[fa4]); FA2/FA3 kernels are Hopper-only). "
|
||||
"Select a compatible backend."
|
||||
)
|
||||
return _CuDNNBackend, None
|
||||
|
||||
monkeypatch.setattr(layer_mod, "get_attn_backend_for_role", _fake_get_attn_backend_for_role)
|
||||
monkeypatch.setattr(layer_mod.SDPABackend, "get_impl_cls", staticmethod(lambda: _FakeAttentionImpl))
|
||||
monkeypatch.setattr(FlashAttentionBackend, "get_impl_cls", staticmethod(lambda: _FakeAttentionImpl))
|
||||
monkeypatch.setattr(layer_mod, "build_parallel_attention_strategy", lambda **kwargs: object())
|
||||
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: False)
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(),
|
||||
diffusion_kv_mode=layer_mod.DiffusionKVCacheMode.PAGED_SCHEDULER,
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
diffusion_kv_cache_dtype=None,
|
||||
diffusion_kv_cache_skip_step_indices=None,
|
||||
diffusion_kv_cache_skip_layer_indices=None,
|
||||
)
|
||||
|
||||
with set_current_diffusion_config(od_config):
|
||||
attention = Attention(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
paged_kv_cache_role="primary",
|
||||
)
|
||||
|
||||
assert attention.attn_backend is FlashAttentionBackend
|
||||
assert attention.backend_pref == "FLASH_ATTN"
|
||||
assert attention.backend_explicit is False
|
||||
assert attention.attn_spec is None
|
||||
|
||||
def test_user_explicit_flash_attn_still_requires_dense_fa4(self, monkeypatch):
|
||||
def _fake_get_attn_backend_for_role(*args, attention_config=None, **kwargs):
|
||||
if attention_config is not None:
|
||||
spec, _ = attention_config.resolve_with_source(role="self", role_category=None)
|
||||
if spec is not None and spec.backend.upper() == "FLASH_ATTN":
|
||||
raise ValueError(
|
||||
"FLASH_ATTN was explicitly selected but is unsupported "
|
||||
"(Blackwell requires CuTe FlashAttention-4 "
|
||||
"(flash_attn.cute / vllm-omni[fa4]); FA2/FA3 kernels are Hopper-only). "
|
||||
"Select a compatible backend."
|
||||
)
|
||||
raise AssertionError("explicit FLASH_ATTN must not fall through to the platform default")
|
||||
|
||||
monkeypatch.setattr(layer_mod, "get_attn_backend_for_role", _fake_get_attn_backend_for_role)
|
||||
monkeypatch.setattr(layer_mod, "build_parallel_attention_strategy", lambda **kwargs: object())
|
||||
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: False)
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(default=AttentionSpec(backend="FLASH_ATTN")),
|
||||
diffusion_kv_mode=layer_mod.DiffusionKVCacheMode.PAGED_SCHEDULER,
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
diffusion_kv_cache_dtype=None,
|
||||
diffusion_kv_cache_skip_step_indices=None,
|
||||
diffusion_kv_cache_skip_layer_indices=None,
|
||||
)
|
||||
|
||||
with set_current_diffusion_config(od_config), pytest.raises(ValueError, match="explicitly selected"):
|
||||
Attention(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
paged_kv_cache_role="primary",
|
||||
)
|
||||
|
||||
def test_attention_init_uses_current_diffusion_config_without_forward_context(self, monkeypatch):
|
||||
class _FakeAttentionImpl:
|
||||
@@ -614,9 +763,10 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
|
||||
return _FakeBackend, AttentionSpec(backend="TRTLLM_ATTN", skip_softmax={"target_sparsity": 0.5})
|
||||
|
||||
class _FakeRingParallelAttention:
|
||||
def __init__(self, sp_group, attn_backend_pref=None):
|
||||
def __init__(self, sp_group, attn_backend_pref=None, attn_backend_explicit=False):
|
||||
self.sp_group = sp_group
|
||||
self.attn_backend_pref = attn_backend_pref
|
||||
self.attn_backend_explicit = attn_backend_explicit
|
||||
|
||||
monkeypatch.setattr(layer_mod, "get_attn_backend_for_role", _fake_get_attn_backend_for_role)
|
||||
monkeypatch.setattr(layer_mod.SDPABackend, "get_impl_cls", staticmethod(lambda: _FakeAttentionImpl))
|
||||
@@ -662,11 +812,134 @@ class TestAttentionInitUsesCurrentDiffusionConfig:
|
||||
assert attn.use_ring is True
|
||||
assert attn.ring_runner is not None
|
||||
assert attn.ring_runner.attn_backend_pref == "TRTLLM_ATTN"
|
||||
assert attn.ring_runner.attn_backend_explicit is True
|
||||
|
||||
def test_attention_init_forwards_flashinfer_backend_without_dtype(self, monkeypatch):
|
||||
class _FakeAttentionImpl:
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
|
||||
class _FakeBackend:
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls():
|
||||
return _FakeAttentionImpl
|
||||
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN", quant={"flashinfer_backend": "fa2"})
|
||||
|
||||
monkeypatch.setattr(layer_mod, "get_attn_backend_for_role", lambda **kwargs: (_FakeBackend, spec))
|
||||
monkeypatch.setattr(layer_mod.SDPABackend, "get_impl_cls", staticmethod(lambda: _FakeAttentionImpl))
|
||||
monkeypatch.setattr(layer_mod, "build_parallel_attention_strategy", lambda **kwargs: object())
|
||||
monkeypatch.setattr(layer_mod, "get_sp_group", lambda: None)
|
||||
monkeypatch.setattr(layer_mod, "is_forward_context_available", lambda: False)
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(default=spec),
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
diffusion_kv_cache_dtype=None,
|
||||
diffusion_kv_cache_skip_step_indices=None,
|
||||
diffusion_kv_cache_skip_layer_indices=None,
|
||||
)
|
||||
|
||||
with set_current_diffusion_config(od_config):
|
||||
attn = Attention(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
role="self",
|
||||
)
|
||||
|
||||
assert attn.backend_pref == "FLASHINFER_ATTN"
|
||||
assert attn.attention.kwargs["backend_kwargs"] == {"quant": {"flashinfer_backend": "fa2"}}
|
||||
assert attn.attention.kwargs["backend_explicit"] is True
|
||||
|
||||
def test_attention_init_propagates_ring_setup_failure(self, monkeypatch):
|
||||
class _FakeAttentionImpl:
|
||||
def __init__(self, **kwargs):
|
||||
pass
|
||||
|
||||
class _FakeBackend:
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "TORCH_SDPA"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls():
|
||||
return _FakeAttentionImpl
|
||||
|
||||
monkeypatch.setattr(
|
||||
layer_mod,
|
||||
"get_attn_backend_for_role",
|
||||
lambda **kwargs: (_FakeBackend, AttentionSpec(backend="TORCH_SDPA")),
|
||||
)
|
||||
monkeypatch.setattr(layer_mod.SDPABackend, "get_impl_cls", staticmethod(lambda: _FakeAttentionImpl))
|
||||
monkeypatch.setattr(
|
||||
layer_mod,
|
||||
"get_sp_group",
|
||||
lambda: (_ for _ in ()).throw(RuntimeError("SP group is not initialized")),
|
||||
)
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(default="TORCH_SDPA"),
|
||||
parallel_config=SimpleNamespace(ring_degree=2),
|
||||
)
|
||||
with set_current_diffusion_config(od_config):
|
||||
with pytest.raises(RuntimeError, match="SP group is not initialized"):
|
||||
Attention(num_heads=4, head_size=64, causal=False, softmax_scale=1.0)
|
||||
|
||||
def test_float32_main_dispatch_does_not_override_selected_backend(self):
|
||||
sentinel = torch.randn(1, 2, 4, 8)
|
||||
selected_calls = []
|
||||
|
||||
def _selected_forward(*args):
|
||||
selected_calls.append(args)
|
||||
return sentinel
|
||||
|
||||
fake_attention = SimpleNamespace(
|
||||
attention=SimpleNamespace(
|
||||
forward=_selected_forward,
|
||||
),
|
||||
sdpa_fallback=SimpleNamespace(
|
||||
forward=lambda *args: pytest.fail("unexpected SDPA fallback"),
|
||||
),
|
||||
_assert_metadata_compatible=lambda metadata: None,
|
||||
_scheduler_paged_kv=False,
|
||||
paged_kv_cache_role=None,
|
||||
)
|
||||
query = torch.randn(1, 2, 4, 8, dtype=torch.float32)
|
||||
|
||||
output = Attention._run_local_attention(fake_attention, query, query, query, None)
|
||||
|
||||
assert output is sentinel
|
||||
assert len(selected_calls) == 1
|
||||
|
||||
def test_unsupported_attention_mask_is_rejected_before_backend_call(self):
|
||||
fake_backend = SimpleNamespace(
|
||||
get_name=lambda: "NO_MASK_BACKEND",
|
||||
supports_attention_mask=lambda *args, **kwargs: False,
|
||||
)
|
||||
fake_attention = SimpleNamespace(attn_backend=fake_backend)
|
||||
metadata = AttentionMetadata(attn_mask=torch.ones(1, 2, dtype=torch.bool))
|
||||
|
||||
with pytest.raises(ValueError, match="does not support attn_mask"):
|
||||
Attention._assert_metadata_compatible(fake_attention, metadata)
|
||||
|
||||
def test_ring_attention_rejects_mask_instead_of_ignoring_it(self):
|
||||
fake_attention = SimpleNamespace(attention=SimpleNamespace(skip=None), ring_runner=None)
|
||||
query = torch.randn(1, 2, 4, 8)
|
||||
metadata = AttentionMetadata(attn_mask=torch.ones(1, 2, dtype=torch.bool))
|
||||
|
||||
with pytest.raises(ValueError, match="Ring attention does not support attn_mask"):
|
||||
Attention._run_ring_attention(fake_attention, query, query, query, metadata)
|
||||
|
||||
|
||||
class TestDiffusionKvCacheQuantization:
|
||||
@staticmethod
|
||||
def _install_attention_init_stubs(monkeypatch):
|
||||
def _install_attention_init_stubs(monkeypatch, *, supports_kv_cache_dtype=True):
|
||||
class _FakeAttentionImpl:
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
@@ -674,6 +947,10 @@ class TestDiffusionKvCacheQuantization:
|
||||
def forward(self, query, key, value, attn_metadata=None):
|
||||
return query
|
||||
|
||||
@staticmethod
|
||||
def supports_kv_cache_dtype(kv_cache_dtype, platform_key) -> bool:
|
||||
return supports_kv_cache_dtype
|
||||
|
||||
class _FakeBackend:
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
@@ -683,14 +960,11 @@ class TestDiffusionKvCacheQuantization:
|
||||
def get_impl_cls():
|
||||
return _FakeAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def supports_kv_cache_dtype(kv_cache_dtype, platform_key) -> bool:
|
||||
return True
|
||||
|
||||
class _FakeRingParallelAttention:
|
||||
def __init__(self, sp_group, attn_backend_pref=None):
|
||||
def __init__(self, sp_group, attn_backend_pref=None, attn_backend_explicit=False):
|
||||
self.sp_group = sp_group
|
||||
self.attn_backend_pref = attn_backend_pref
|
||||
self.attn_backend_explicit = attn_backend_explicit
|
||||
|
||||
monkeypatch.setattr(
|
||||
layer_mod,
|
||||
@@ -764,3 +1038,22 @@ class TestDiffusionKvCacheQuantization:
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
)
|
||||
|
||||
def test_explicit_unsupported_kv_cache_dtype_raises(self, monkeypatch):
|
||||
self._install_attention_init_stubs(monkeypatch, supports_kv_cache_dtype=False)
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(),
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
diffusion_kv_cache_dtype="fp8",
|
||||
diffusion_kv_cache_skip_step_indices=None,
|
||||
diffusion_kv_cache_skip_layer_indices=None,
|
||||
)
|
||||
|
||||
with set_current_diffusion_config(od_config):
|
||||
with pytest.raises(ValueError, match="does not support kv_cache_dtype='fp8'"):
|
||||
Attention(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
)
|
||||
@@ -0,0 +1,265 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import sys
|
||||
import types
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.registry import DiffusionAttentionBackendEnum
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.attention.selector import _cached_get_backend_cls
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import AttentionConfig
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
|
||||
# Importing CudaOmniPlatform pulls in vllm.platforms.cuda, which imports the
|
||||
# CUDA-only ``vllm._C_stable_libtorch`` extension at module top level. That
|
||||
# extension is absent on non-CUDA builds (e.g. Intel/XPU), so skip the whole
|
||||
# module there before the import can crash collection. ``is_cuda()`` resolves
|
||||
# the platform without importing cuda.py.
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip("CUDA-only diffusion backend selection tests", allow_module_level=True)
|
||||
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform # noqa: E402
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _blackwell_sm120(monkeypatch: pytest.MonkeyPatch, *, cudnn_version: int = 90500) -> None:
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(12, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_4", classmethod(lambda cls: False))
|
||||
monkeypatch.setattr(torch.backends.cudnn, "version", lambda: cudnn_version)
|
||||
|
||||
|
||||
def _install_dummy_flashinfer(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Top-level ``flashinfer`` only — no ``prefill`` wrapper (partial install)."""
|
||||
monkeypatch.setitem(sys.modules, "flashinfer", types.ModuleType("flashinfer"))
|
||||
# A previously imported real submodule must not satisfy the wrapper probe.
|
||||
monkeypatch.delitem(sys.modules, "flashinfer.prefill", raising=False)
|
||||
|
||||
|
||||
def _install_dummy_flashinfer_prefill(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""FlashInfer stub that exposes the prefill wrapper FLASHINFER_ATTN needs."""
|
||||
prefill = types.ModuleType("flashinfer.prefill")
|
||||
setattr(prefill, "BatchPrefillWithRaggedKVCacheWrapper", type("BatchPrefillWithRaggedKVCacheWrapper", (), {}))
|
||||
pkg = types.ModuleType("flashinfer")
|
||||
setattr(pkg, "prefill", prefill)
|
||||
monkeypatch.setitem(sys.modules, "flashinfer", pkg)
|
||||
monkeypatch.setitem(sys.modules, "flashinfer.prefill", prefill)
|
||||
|
||||
|
||||
def test_auto_selects_cudnn_for_supported_blackwell_head_size(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=128)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.CUDNN_ATTN.get_path()
|
||||
|
||||
|
||||
def test_auto_routes_incompatible_head_size_to_sdpa(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer(monkeypatch)
|
||||
|
||||
# 320 is outside cuDNN FMHA (<=256, multiple of 8) and FlashInfer {64,128,256}.
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=320)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
|
||||
|
||||
|
||||
def test_auto_routes_non_multiple_head_size_to_sdpa_without_flashinfer(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
monkeypatch.setitem(sys.modules, "flashinfer", None)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=12)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
|
||||
|
||||
|
||||
def test_auto_selects_flashinfer_when_cudnn_too_old(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch, cudnn_version=90499)
|
||||
_install_dummy_flashinfer_prefill(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=128)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.FLASHINFER_ATTN.get_path()
|
||||
|
||||
|
||||
def test_auto_skips_flashinfer_when_only_toplevel_package(monkeypatch: pytest.MonkeyPatch):
|
||||
"""A stub that only imports ``flashinfer`` must not be auto-selected."""
|
||||
_blackwell_sm120(monkeypatch, cudnn_version=90499)
|
||||
_install_dummy_flashinfer(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=128)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
|
||||
|
||||
|
||||
def test_explicit_flashinfer_raises_without_prefill_wrapper(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer(monkeypatch)
|
||||
|
||||
with pytest.raises(ValueError, match="BatchPrefillWithRaggedKVCacheWrapper"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASHINFER_ATTN", head_size=128)
|
||||
|
||||
|
||||
def test_auto_skips_flashinfer_for_unsupported_head_size_when_cudnn_too_old(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch, cudnn_version=90499)
|
||||
_install_dummy_flashinfer(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=72)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
|
||||
|
||||
|
||||
def test_explicit_cudnn_raises_for_incompatible_head_size(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
|
||||
with pytest.raises(ValueError, match="head_size=12 is unsupported"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("CUDNN_ATTN", head_size=12)
|
||||
|
||||
|
||||
def test_explicit_cudnn_accepts_supported_head_size(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls("CUDNN_ATTN", head_size=72)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.CUDNN_ATTN.get_path()
|
||||
|
||||
|
||||
def test_explicit_cudnn_skips_head_size_check_for_capability_probe(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls("CUDNN_ATTN", head_size=-1)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.CUDNN_ATTN.get_path()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head_size", [32, 320])
|
||||
def test_explicit_flashinfer_raises_for_unsupported_head_size(monkeypatch: pytest.MonkeyPatch, head_size: int):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer_prefill(monkeypatch)
|
||||
|
||||
with pytest.raises(ValueError, match=f"head_size={head_size} is unsupported"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASHINFER_ATTN", head_size=head_size)
|
||||
|
||||
|
||||
def test_explicit_flashinfer_accepts_supported_head_size(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer_prefill(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASHINFER_ATTN", head_size=128)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.FLASHINFER_ATTN.get_path()
|
||||
|
||||
|
||||
def test_explicit_flashinfer_skips_head_size_check_for_capability_probe(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer_prefill(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASHINFER_ATTN", head_size=-1)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.FLASHINFER_ATTN.get_path()
|
||||
|
||||
|
||||
def test_auto_selects_cudnn_for_unknown_head_size_probe(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_install_dummy_flashinfer_prefill(monkeypatch)
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=-1)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.CUDNN_ATTN.get_path()
|
||||
|
||||
|
||||
def test_explicit_flash_attn_rejects_blackwell_without_fa4(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": True})
|
||||
|
||||
with pytest.raises(ValueError, match="requires CuTe FlashAttention-4"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN", head_size=64)
|
||||
|
||||
|
||||
def test_explicit_flash_attn_accepts_blackwell_when_fa4_available(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_4", classmethod(lambda cls: True))
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN", head_size=64)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.FLASH_ATTN.get_path()
|
||||
|
||||
|
||||
def test_blackwell_dense_flash_capability_tracks_fa4(monkeypatch: pytest.MonkeyPatch):
|
||||
_blackwell_sm120(monkeypatch)
|
||||
|
||||
assert CudaOmniPlatform.supports_diffusion_dense_flash_attention() is False
|
||||
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_4", classmethod(lambda cls: True))
|
||||
|
||||
assert CudaOmniPlatform.supports_diffusion_dense_flash_attention() is True
|
||||
|
||||
|
||||
def test_hopper_dense_flash_capability_tracks_fa_package(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(9, 0)),
|
||||
)
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_package", classmethod(lambda cls: False))
|
||||
|
||||
assert CudaOmniPlatform.supports_diffusion_dense_flash_attention() is False
|
||||
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_package", classmethod(lambda cls: True))
|
||||
|
||||
assert CudaOmniPlatform.supports_diffusion_dense_flash_attention() is True
|
||||
|
||||
|
||||
def test_auto_selects_flash_attn_on_blackwell_when_cudnn_old_and_fa4_available(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
_blackwell_sm120(monkeypatch, cudnn_version=90499)
|
||||
monkeypatch.setitem(sys.modules, "flashinfer", None)
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_4", classmethod(lambda cls: True))
|
||||
|
||||
path = CudaOmniPlatform.get_diffusion_attn_backend_cls(None, head_size=128)
|
||||
|
||||
assert path == DiffusionAttentionBackendEnum.FLASH_ATTN.get_path()
|
||||
|
||||
|
||||
def test_marked_paged_layer_constructs_on_blackwell_cudnn_without_fa4(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Scheduler-paged remap must not require dense FA4 when CUDNN is the default."""
|
||||
_blackwell_sm120(monkeypatch)
|
||||
_cached_get_backend_cls.cache_clear()
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(),
|
||||
diffusion_kv_mode=DiffusionKVCacheMode.PAGED_SCHEDULER,
|
||||
parallel_config=SimpleNamespace(ring_degree=1, allgather_degree=1),
|
||||
diffusion_kv_cache_dtype=None,
|
||||
diffusion_kv_cache_skip_step_indices=None,
|
||||
diffusion_kv_cache_skip_layer_indices=None,
|
||||
model_class_name=None,
|
||||
)
|
||||
|
||||
with set_current_diffusion_config(od_config):
|
||||
attention = Attention(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
causal=False,
|
||||
softmax_scale=1.0,
|
||||
paged_kv_cache_role="primary",
|
||||
)
|
||||
|
||||
assert attention.attn_backend.get_name() == "FLASH_ATTN"
|
||||
assert attention.backend_pref == "FLASH_ATTN"
|
||||
assert attention.backend_explicit is False
|
||||
assert attention.attn_spec is None
|
||||
@@ -1,62 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from contextlib import nullcontext
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch.nn.attention import SDPBackend
|
||||
|
||||
import vllm_omni.diffusion.attention.backends.cudnn_attn as cudnn_backend
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.cudnn_attn import CuDNNAttentionImpl
|
||||
from vllm_omni.diffusion.attention.backends.cudnn_attn import CuDNNAttentionBackend, CuDNNAttentionImpl
|
||||
|
||||
pytestmark = [pytest.mark.diffusion, pytest.mark.cpu, pytest.mark.core_model]
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("query_sequence_length", "key_sequence_length", "expected_backend"),
|
||||
[
|
||||
(1, 1, SDPBackend.MATH),
|
||||
(8, 1, SDPBackend.MATH),
|
||||
(1, 8, SDPBackend.MATH),
|
||||
(8, 8, SDPBackend.CUDNN_ATTENTION),
|
||||
],
|
||||
)
|
||||
def test_cudnn_routes_single_token_attention_to_math(
|
||||
monkeypatch, query_sequence_length, key_sequence_length, expected_backend
|
||||
):
|
||||
def test_cudnn_backend_uses_math_for_kv_seq_len_one(monkeypatch):
|
||||
"""Automatic CUDNN_ATTN (platform default) may use MATH for singleton K/V."""
|
||||
selected_backends = []
|
||||
|
||||
@contextmanager
|
||||
def fake_sdpa_kernel(backends):
|
||||
selected_backends.append(backends)
|
||||
return nullcontext()
|
||||
selected_backends.append(tuple(backends))
|
||||
yield
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.diffusion.attention.backends.cudnn_attn.sdpa_kernel",
|
||||
fake_sdpa_kernel,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
torch.nn.functional,
|
||||
"scaled_dot_product_attention",
|
||||
lambda query, _key, _value, **_kwargs: query,
|
||||
)
|
||||
impl = CuDNNAttentionImpl(
|
||||
num_heads=2,
|
||||
head_size=4,
|
||||
softmax_scale=0.5,
|
||||
)
|
||||
query = torch.randn(1, query_sequence_length, 2, 4)
|
||||
key = torch.randn(1, key_sequence_length, 2, 4)
|
||||
value = torch.randn_like(key)
|
||||
def fake_sdpa(query, key, value, **kwargs):
|
||||
return query
|
||||
|
||||
output = impl.forward_cuda(query, key, value)
|
||||
monkeypatch.setattr(cudnn_backend, "sdpa_kernel", fake_sdpa_kernel)
|
||||
monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", fake_sdpa)
|
||||
|
||||
impl = CuDNNAttentionImpl(num_heads=2, head_size=8, softmax_scale=0.5)
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
singleton_kv = torch.randn(1, 1, 2, 8)
|
||||
|
||||
output = impl.forward_cuda(query, singleton_kv, singleton_kv)
|
||||
|
||||
assert output.shape == query.shape
|
||||
assert selected_backends == [[expected_backend]]
|
||||
assert selected_backends == [(SDPBackend.MATH,)]
|
||||
|
||||
|
||||
def test_explicit_cudnn_rejects_kv_seq_len_one():
|
||||
impl = CuDNNAttentionImpl(
|
||||
num_heads=2,
|
||||
head_size=8,
|
||||
softmax_scale=0.5,
|
||||
backend_explicit=True,
|
||||
)
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
singleton_kv = torch.randn(1, 1, 2, 8)
|
||||
|
||||
with pytest.raises(ValueError, match="explicitly selected.*sequence length 1"):
|
||||
impl.forward_cuda(query, singleton_kv, singleton_kv)
|
||||
|
||||
|
||||
def test_cudnn_backend_pins_cudnn_only_when_kv_seq_len_gt_one(monkeypatch):
|
||||
selected_backends = []
|
||||
|
||||
@contextmanager
|
||||
def fake_sdpa_kernel(backends):
|
||||
selected_backends.append(tuple(backends))
|
||||
yield
|
||||
|
||||
def reject_shape(*args, **kwargs):
|
||||
raise RuntimeError("No available kernel. Aborting execution.")
|
||||
|
||||
monkeypatch.setattr(cudnn_backend, "sdpa_kernel", fake_sdpa_kernel)
|
||||
monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", reject_shape)
|
||||
|
||||
impl = CuDNNAttentionImpl(num_heads=2, head_size=8, softmax_scale=0.5)
|
||||
tensors = torch.randn(1, 2, 2, 8)
|
||||
|
||||
with pytest.raises(RuntimeError, match="No available kernel"):
|
||||
impl.forward_cuda(tensors, tensors, tensors)
|
||||
|
||||
assert selected_backends == [(SDPBackend.CUDNN_ATTENTION,)]
|
||||
|
||||
|
||||
def test_cudnn_slices_valid_kv_prefix_without_padding_mask(monkeypatch):
|
||||
observed = {}
|
||||
observed: dict[str, Any] = {}
|
||||
|
||||
def fake_sdpa(query, key, value, **kwargs):
|
||||
observed.update(query=query, key=key, value=value, kwargs=kwargs)
|
||||
@@ -105,3 +127,15 @@ def test_cudnn_rejects_invalid_valid_kv_length():
|
||||
query,
|
||||
AttentionMetadata(extra={"valid_kv_length": 9}),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head_size", [8, 64, 128, 256])
|
||||
def test_cudnn_backend_accepts_blackwell_fmha_head_sizes(head_size):
|
||||
assert CuDNNAttentionBackend.supports_head_size(head_size)
|
||||
assert head_size in CuDNNAttentionBackend.get_supported_head_sizes()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head_size", [0, 7, 12, 320])
|
||||
def test_cudnn_backend_rejects_incompatible_head_sizes(head_size):
|
||||
assert not CuDNNAttentionBackend.supports_head_size(head_size)
|
||||
assert head_size not in CuDNNAttentionBackend.get_supported_head_sizes()
|
||||
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends import flashinfer_attn
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.flashinfer_attn import (
|
||||
FlashInferAttentionBackend,
|
||||
FlashInferAttentionImpl,
|
||||
)
|
||||
from vllm_omni.diffusion.data import AttentionSpec, AttnQuantSpec
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _impl(*, causal: bool = False, backend_explicit: bool = False):
|
||||
# Avoid CUDA/wrapper init; these tests only cover mask validation.
|
||||
obj = FlashInferAttentionImpl.__new__(FlashInferAttentionImpl)
|
||||
obj.causal = causal
|
||||
obj.softmax_scale = 0.5
|
||||
obj.flashinfer_backend = "fa2"
|
||||
obj.backend_explicit = backend_explicit
|
||||
obj._sdpa_fallback = None
|
||||
return obj
|
||||
|
||||
|
||||
def test_flashinfer_rejects_float_mask_instead_of_falling_back(monkeypatch):
|
||||
monkeypatch.setattr(flashinfer_attn, "HAS_FLASHINFER", True)
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
metadata = AttentionMetadata(attn_mask=torch.zeros(2, 2))
|
||||
|
||||
with pytest.raises(ValueError, match="boolean-only"):
|
||||
_impl(backend_explicit=True).forward_cuda(query, query, query, metadata)
|
||||
|
||||
|
||||
def test_flashinfer_rejects_causal_custom_mask_instead_of_falling_back(monkeypatch):
|
||||
monkeypatch.setattr(flashinfer_attn, "HAS_FLASHINFER", True)
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
metadata = AttentionMetadata(attn_mask=torch.tensor([[True, False], [True, True]]))
|
||||
|
||||
with pytest.raises(ValueError, match="causal=True"):
|
||||
_impl(causal=True, backend_explicit=True).forward_cuda(query, query, query, metadata)
|
||||
|
||||
|
||||
def test_explicit_cute_dsl_rejects_custom_mask_instead_of_falling_back(monkeypatch):
|
||||
monkeypatch.setattr(flashinfer_attn, "HAS_FLASHINFER", True)
|
||||
impl = _impl(backend_explicit=True)
|
||||
impl.flashinfer_backend = "cute-dsl"
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
metadata = AttentionMetadata(attn_mask=torch.tensor([[True, False], [True, True]]))
|
||||
|
||||
with pytest.raises(ValueError, match="cute-dsl"):
|
||||
impl.forward_cuda(query, query, query, metadata)
|
||||
|
||||
|
||||
def test_auto_cute_dsl_falls_back_to_sdpa_for_custom_mask(monkeypatch):
|
||||
monkeypatch.setattr(flashinfer_attn, "HAS_FLASHINFER", True)
|
||||
impl = _impl(backend_explicit=False)
|
||||
impl.flashinfer_backend = "cute-dsl"
|
||||
impl._run_batch_prefill = lambda *args, **kwargs: pytest.fail("unexpected cute-dsl prefill")
|
||||
query = torch.randn(1, 2, 2, 8)
|
||||
metadata = AttentionMetadata(attn_mask=torch.tensor([[True, False], [True, True]]))
|
||||
|
||||
output = impl.forward_cuda(query, query, query, metadata)
|
||||
|
||||
assert output.shape == query.shape
|
||||
|
||||
|
||||
def test_explicit_cute_dsl_is_not_mask_capable(monkeypatch):
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (10, 0))
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN")
|
||||
|
||||
assert FlashInferAttentionBackend.supports_attention_mask() is True
|
||||
assert FlashInferAttentionBackend.supports_attention_mask(spec) is False
|
||||
|
||||
|
||||
def test_explicit_fa2_flashinfer_is_mask_capable(monkeypatch):
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (10, 0))
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN", quant=AttnQuantSpec(flashinfer_backend="fa2"))
|
||||
|
||||
assert FlashInferAttentionBackend.supports_attention_mask(spec) is True
|
||||
|
||||
|
||||
def test_explicit_fa2_backend_kwargs_select_fa2_on_blackwell(monkeypatch):
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (10, 0))
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN", quant=AttnQuantSpec(flashinfer_backend="fa2"))
|
||||
kwargs = spec.backend_kwargs() or {}
|
||||
requested = (kwargs.get("quant") or {}).get("flashinfer_backend", "auto")
|
||||
|
||||
assert kwargs == {"quant": {"flashinfer_backend": "fa2"}}
|
||||
assert FlashInferAttentionImpl._select_backend(requested) == "fa2"
|
||||
assert FlashInferAttentionBackend.supports_attention_mask(spec) is True
|
||||
|
||||
|
||||
def test_auto_flashinfer_backend_kwargs_select_cute_dsl_on_blackwell(monkeypatch):
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (10, 0))
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN")
|
||||
kwargs = spec.backend_kwargs() or {}
|
||||
requested = (kwargs.get("quant") or {}).get("flashinfer_backend", "auto")
|
||||
|
||||
assert "quant" not in kwargs
|
||||
assert FlashInferAttentionImpl._select_backend(requested) == "cute-dsl"
|
||||
assert FlashInferAttentionBackend.supports_attention_mask(spec) is False
|
||||
|
||||
|
||||
def test_hopper_explicit_flashinfer_is_mask_capable(monkeypatch):
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (9, 0))
|
||||
spec = AttentionSpec(backend="FLASHINFER_ATTN")
|
||||
|
||||
assert FlashInferAttentionBackend.supports_attention_mask(spec) is True
|
||||
@@ -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
|
||||
|
||||
import sys
|
||||
import types
|
||||
@@ -9,18 +9,13 @@ import torch
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.registry import DiffusionAttentionBackendEnum
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPAImpl
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_kernels_hub_platform_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Test that when kernels package is not available, the platform fallback logic
|
||||
|
||||
routes to local FLASH_ATTN.
|
||||
"""
|
||||
def test_explicit_kernels_hub_selection_does_not_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
# Temporarily hide/remove kernels module if present
|
||||
@@ -38,19 +33,73 @@ def test_kernels_hub_platform_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": True})
|
||||
|
||||
# Test FLASH_ATTN_HUB falls back to FLASH_ATTN when kernels is unavailable
|
||||
backend_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_HUB", head_size=64)
|
||||
assert backend_path == DiffusionAttentionBackendEnum.FLASH_ATTN.get_path()
|
||||
with pytest.raises(ImportError, match="explicitly selected"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_HUB", head_size=64)
|
||||
with pytest.raises(ImportError, match="explicitly selected"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
|
||||
# Test FLASH_ATTN_3_HUB falls back to FLASH_ATTN when kernels is unavailable
|
||||
backend_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
assert backend_path == DiffusionAttentionBackendEnum.FLASH_ATTN.get_path()
|
||||
|
||||
# Test FLASH_ATTN_3_HUB falls back to FLASH_ATTN_HUB on pre-Hopper GPUs
|
||||
kernels_module = types.ModuleType("kernels")
|
||||
monkeypatch.setitem(sys.modules, "kernels", kernels_module)
|
||||
backend_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
assert backend_path == DiffusionAttentionBackendEnum.FLASH_ATTN_HUB.get_path()
|
||||
with pytest.raises(ValueError, match="require.*Hopper GPU"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(10, 3)),
|
||||
)
|
||||
with pytest.raises(ValueError, match="current FA2 kernels require"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_HUB", head_size=64)
|
||||
with pytest.raises(ValueError, match="require.*Hopper GPU"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN_3_HUB", head_size=64)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_flash_attention_unavailable_does_not_fallback(monkeypatch: pytest.MonkeyPatch):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(8, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
|
||||
with pytest.raises(ValueError, match="explicitly selected but is unsupported"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN", head_size=64)
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(10, 3)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": True})
|
||||
monkeypatch.setattr(CudaOmniPlatform, "has_flash_attn_4", classmethod(lambda cls: False))
|
||||
with pytest.raises(ValueError, match="requires CuTe FlashAttention-4"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("FLASH_ATTN", head_size=64)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu
|
||||
def test_explicit_sage_attention_unsupported_arch_does_not_reach_kernel(monkeypatch: pytest.MonkeyPatch):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(10, 3)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
|
||||
with pytest.raises(ValueError, match="does not provide a kernel for sm_103"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("SAGE_ATTN", head_size=64)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring import ring_globals, ring_kernels
|
||||
from vllm_omni.diffusion.attention.parallel import factory, ring
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_source_build_fa3_is_hopper_only(monkeypatch):
|
||||
fake_interface = SimpleNamespace(
|
||||
_flash_attn_forward=lambda *args, **kwargs: None,
|
||||
flash_attn_func=lambda *args, **kwargs: None,
|
||||
)
|
||||
try:
|
||||
with monkeypatch.context() as context:
|
||||
context.setitem(sys.modules, "flash_attn_interface", fake_interface)
|
||||
reloaded = importlib.reload(ring_globals)
|
||||
assert reloaded.HAS_FA3
|
||||
assert reloaded.FA3_SUPPORTED_CUDA_MAJORS == frozenset({9})
|
||||
finally:
|
||||
importlib.reload(ring_globals)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("capability", "expected"),
|
||||
[
|
||||
((8, 0), True),
|
||||
((8, 9), True),
|
||||
((9, 0), True),
|
||||
((10, 0), False),
|
||||
((10, 3), False),
|
||||
((12, 0), False),
|
||||
],
|
||||
)
|
||||
def test_can_use_fa3_checks_device_arch(monkeypatch, capability, expected):
|
||||
monkeypatch.setattr(ring, "HAS_FA3", True)
|
||||
monkeypatch.setattr(ring, "FA3_SUPPORTED_CUDA_MAJORS", frozenset({8, 9}))
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _device: capability)
|
||||
|
||||
assert ring._can_use_fa3(torch.device("cuda")) is expected
|
||||
|
||||
|
||||
def test_can_use_fa3_preserves_unknown_extension_contract(monkeypatch):
|
||||
monkeypatch.setattr(ring, "HAS_FA3", True)
|
||||
monkeypatch.setattr(ring, "FA3_SUPPORTED_CUDA_MAJORS", None)
|
||||
|
||||
assert ring._can_use_fa3(torch.device("cuda"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("capability", "expected"),
|
||||
[
|
||||
((8, 0), True),
|
||||
((9, 0), True),
|
||||
((10, 0), False),
|
||||
((10, 3), False),
|
||||
((12, 0), False),
|
||||
],
|
||||
)
|
||||
def test_can_use_fa2_checks_device_arch(monkeypatch, capability, expected):
|
||||
monkeypatch.setattr(ring, "HAS_FLASH_ATTN", True)
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _device: capability)
|
||||
|
||||
assert ring._can_use_fa2(torch.device("cuda")) is expected
|
||||
|
||||
|
||||
def test_ring_falls_back_to_sdpa_when_fa3_extension_has_no_device_kernel(monkeypatch):
|
||||
monkeypatch.setattr(ring, "HAS_FA3", True)
|
||||
monkeypatch.setattr(ring, "HAS_FA4", False)
|
||||
monkeypatch.setattr(ring, "HAS_FLASH_ATTN", False)
|
||||
monkeypatch.setattr(ring, "HAS_AITER", False)
|
||||
monkeypatch.setattr(ring, "_can_use_fa3", lambda _device: False)
|
||||
|
||||
expected = torch.randn(1, 2, 1, 8)
|
||||
|
||||
def fake_ring_sdpa(*args, **kwargs):
|
||||
return expected
|
||||
|
||||
module_name = "vllm_omni.diffusion.attention.backends.ring_pytorch_attn"
|
||||
monkeypatch.setitem(sys.modules, module_name, SimpleNamespace(ring_pytorch_attn_func=fake_ring_sdpa))
|
||||
|
||||
strategy = ring.RingParallelAttention(SimpleNamespace(ring_group=object()))
|
||||
query = torch.randn(1, 2, 1, 8, dtype=torch.bfloat16)
|
||||
actual = strategy.run_attention(query, query, query, attn_metadata=None)
|
||||
|
||||
assert actual is expected
|
||||
|
||||
|
||||
def test_explicit_ring_backend_does_not_fallback_to_sdpa(monkeypatch):
|
||||
monkeypatch.setattr(ring, "HAS_FA3", True)
|
||||
monkeypatch.setattr(ring, "HAS_FA4", False)
|
||||
monkeypatch.setattr(ring, "HAS_FLASH_ATTN", False)
|
||||
monkeypatch.setattr(ring, "HAS_AITER", False)
|
||||
monkeypatch.setattr(ring, "_can_use_fa3", lambda _device: False)
|
||||
|
||||
strategy = ring.RingParallelAttention(
|
||||
SimpleNamespace(ring_group=object()),
|
||||
attn_backend_pref="FLASH_ATTN",
|
||||
attn_backend_explicit=True,
|
||||
)
|
||||
query = torch.randn(1, 2, 1, 8, dtype=torch.bfloat16)
|
||||
|
||||
with pytest.raises(RuntimeError, match="explicitly selected"):
|
||||
strategy.run_attention(query, query, query, attn_metadata=None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_pref",
|
||||
[
|
||||
"CUDNN_ATTN",
|
||||
"FLASH_ATTN_HUB",
|
||||
"FLASH_ATTN_3_HUB",
|
||||
],
|
||||
)
|
||||
def test_explicit_non_ring_backend_is_rejected(monkeypatch, backend_pref):
|
||||
# Local FA is available so a missing rejection would silently run FA4/FA3/FA2
|
||||
# instead of the requested Hub/cuDNN backend.
|
||||
monkeypatch.setattr(ring, "HAS_FA4", True)
|
||||
monkeypatch.setattr(ring, "_can_use_fa4", lambda _device: True)
|
||||
module_name = "vllm_omni.diffusion.attention.backends.ring_pytorch_attn"
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
module_name,
|
||||
SimpleNamespace(ring_pytorch_attn_func=lambda *args, **kwargs: pytest.fail("unexpected SDPA fallback")),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"vllm_omni.diffusion.attention.backends.ring_flash_attn",
|
||||
SimpleNamespace(ring_flash_attn_func=lambda *args, **kwargs: pytest.fail("unexpected local FA ring")),
|
||||
)
|
||||
strategy = ring.RingParallelAttention(
|
||||
SimpleNamespace(ring_group=object()),
|
||||
attn_backend_pref=backend_pref,
|
||||
attn_backend_explicit=True,
|
||||
)
|
||||
query = torch.randn(1, 2, 1, 8, dtype=torch.bfloat16)
|
||||
|
||||
with pytest.raises(ValueError, match="ring sequence parallelism has no implementation"):
|
||||
strategy.run_attention(query, query, query, attn_metadata=None)
|
||||
|
||||
|
||||
def test_explicit_flash_ring_rejects_float32_instead_of_falling_back(monkeypatch):
|
||||
module_name = "vllm_omni.diffusion.attention.backends.ring_pytorch_attn"
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
module_name,
|
||||
SimpleNamespace(ring_pytorch_attn_func=lambda *args, **kwargs: pytest.fail("unexpected SDPA fallback")),
|
||||
)
|
||||
strategy = ring.RingParallelAttention(
|
||||
SimpleNamespace(ring_group=object()),
|
||||
attn_backend_pref="FLASH_ATTN",
|
||||
attn_backend_explicit=True,
|
||||
)
|
||||
query = torch.randn(1, 2, 1, 8, dtype=torch.float32)
|
||||
|
||||
with pytest.raises(ValueError, match="does not support float32"):
|
||||
strategy.run_attention(query, query, query, attn_metadata=None)
|
||||
|
||||
|
||||
def test_pytorch_ring_flash_op_rejects_float32():
|
||||
query = torch.randn(1, 2, 1, 8, dtype=torch.float32)
|
||||
|
||||
with pytest.raises(ValueError, match="does not support float32"):
|
||||
ring_kernels.pytorch_attn_forward(query, query, query, op_type="flash")
|
||||
|
||||
|
||||
def test_configured_sp_does_not_fallback_when_group_is_unavailable(monkeypatch):
|
||||
parallel_config = SimpleNamespace(ulysses_degree=2, ring_degree=1, allgather_degree=1)
|
||||
forward_context = SimpleNamespace(omni_diffusion_config=SimpleNamespace(parallel_config=parallel_config))
|
||||
monkeypatch.setattr(factory, "is_forward_context_available", lambda: True)
|
||||
monkeypatch.setattr(factory, "get_forward_context", lambda: forward_context)
|
||||
monkeypatch.setattr(
|
||||
factory,
|
||||
"get_sp_group",
|
||||
lambda: (_ for _ in ()).throw(RuntimeError("SP group is not initialized")),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="SP is configured"):
|
||||
factory.build_parallel_attention_strategy(scatter_idx=2, gather_idx=1, use_sync=False)
|
||||
|
||||
|
||||
def test_configured_sp_rejects_single_rank_group(monkeypatch):
|
||||
parallel_config = SimpleNamespace(ulysses_degree=2, ring_degree=1, allgather_degree=1)
|
||||
forward_context = SimpleNamespace(omni_diffusion_config=SimpleNamespace(parallel_config=parallel_config))
|
||||
monkeypatch.setattr(factory, "is_forward_context_available", lambda: True)
|
||||
monkeypatch.setattr(factory, "get_forward_context", lambda: forward_context)
|
||||
monkeypatch.setattr(factory, "get_sp_group", lambda: SimpleNamespace())
|
||||
monkeypatch.setattr(factory, "get_sequence_parallel_world_size", lambda: 1)
|
||||
|
||||
with pytest.raises(RuntimeError, match="world size is not greater than one"):
|
||||
factory.build_parallel_attention_strategy(scatter_idx=2, gather_idx=1, use_sync=False)
|
||||
@@ -72,3 +72,25 @@ def test_ring_prefers_fa4_on_blackwell(monkeypatch):
|
||||
|
||||
assert strategy.run_attention(query, "key", "value", None) == "output"
|
||||
assert captured["attn_type"] is AttnType.FA4
|
||||
|
||||
|
||||
def test_flashinfer_wrapper_canonicalizes_unbatched_lse_to_bhs(monkeypatch):
|
||||
seq_len = num_heads = 4
|
||||
query = torch.randn(1, seq_len, num_heads, 8)
|
||||
unbatched_out = torch.randn(seq_len, num_heads, 8)
|
||||
unbatched_lse = torch.arange(num_heads * seq_len, dtype=torch.float32).reshape(num_heads, seq_len)
|
||||
assert not torch.equal(unbatched_lse, unbatched_lse.transpose(0, 1))
|
||||
|
||||
def fake_prefill(_q, _k, _v, **_kwargs):
|
||||
return unbatched_out.clone(), unbatched_lse.clone()
|
||||
|
||||
monkeypatch.setattr(ring_kernels, "HAS_FLASHINFER", True)
|
||||
# FlashInfer symbols are only bound when HAS_FLASHINFER was true at import.
|
||||
monkeypatch.setattr(ring_kernels, "single_prefill_with_kv_cache", fake_prefill, raising=False)
|
||||
monkeypatch.setattr(ring_kernels, "_LOG2_E", 1.0, raising=False)
|
||||
|
||||
out, lse = ring_kernels.flashinfer_attn_forward(query, query, query, softmax_scale=0.1)
|
||||
|
||||
assert out.shape == query.shape
|
||||
assert lse.shape == (1, num_heads, seq_len)
|
||||
assert torch.equal(lse[0], unbatched_lse)
|
||||
@@ -0,0 +1,92 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import update_out_and_lse
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout", ["bhs", "bsh", "bhs_padded", "bhs1"])
|
||||
def test_ring_lse_known_layouts_are_normalized(layout):
|
||||
block_out = torch.randn(2, 5, 3, 4)
|
||||
canonical = torch.randn(2, 5, 3)
|
||||
if layout == "bhs":
|
||||
block_lse = canonical.transpose(1, 2)
|
||||
lse_layout = "bhs"
|
||||
elif layout == "bsh":
|
||||
block_lse = canonical
|
||||
lse_layout = "bsh"
|
||||
elif layout == "bhs_padded":
|
||||
block_lse = torch.cat([canonical.transpose(1, 2), torch.randn(2, 3, 2)], dim=2)
|
||||
lse_layout = "bhs"
|
||||
else:
|
||||
block_lse = canonical.transpose(1, 2).unsqueeze(-1)
|
||||
lse_layout = "bhs"
|
||||
|
||||
out, lse = update_out_and_lse(None, None, block_out, block_lse, lse_layout=lse_layout)
|
||||
|
||||
assert out.shape == block_out.shape
|
||||
assert out.dtype == torch.float32
|
||||
assert lse.shape == (2, 5, 3, 1)
|
||||
assert torch.equal(lse.squeeze(-1), canonical)
|
||||
|
||||
|
||||
def test_ring_lse_seq_len_equals_num_heads_keeps_asymmetric_values():
|
||||
batch, seq_len, num_heads, head_dim = 2, 4, 4, 8
|
||||
block_out = torch.randn(batch, seq_len, num_heads, head_dim)
|
||||
canonical = torch.arange(batch * seq_len * num_heads, dtype=torch.float32).reshape(batch, seq_len, num_heads)
|
||||
bhs = canonical.transpose(1, 2)
|
||||
|
||||
assert bhs.shape == canonical.shape
|
||||
assert not torch.equal(bhs, canonical)
|
||||
|
||||
_, lse_from_bhs = update_out_and_lse(None, None, block_out, bhs, lse_layout="bhs")
|
||||
_, lse_from_bsh = update_out_and_lse(None, None, block_out, canonical, lse_layout="bsh")
|
||||
|
||||
assert torch.equal(lse_from_bhs.squeeze(-1), canonical)
|
||||
assert torch.equal(lse_from_bsh.squeeze(-1), canonical)
|
||||
|
||||
_, lse_if_bsh_read_as_bhs = update_out_and_lse(None, None, block_out, canonical, lse_layout="bhs")
|
||||
assert not torch.equal(lse_if_bsh_read_as_bhs.squeeze(-1), canonical)
|
||||
assert torch.equal(lse_if_bsh_read_as_bhs.squeeze(-1), bhs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"invalid_lse",
|
||||
[
|
||||
torch.randn(2, 5),
|
||||
torch.randn(2, 4, 4),
|
||||
torch.randn(2, 3, 5, 2),
|
||||
],
|
||||
)
|
||||
def test_ring_lse_unknown_layout_is_rejected(invalid_lse):
|
||||
block_out = torch.randn(2, 5, 3, 4)
|
||||
|
||||
with pytest.raises(ValueError, match="Ring LSE"):
|
||||
update_out_and_lse(None, None, block_out, invalid_lse, lse_layout="bhs")
|
||||
|
||||
|
||||
def test_ring_accumulation_rejects_mismatched_block_output():
|
||||
out = torch.randn(2, 5, 3, 4)
|
||||
lse = torch.randn(2, 5, 3, 1)
|
||||
block_out = torch.randn(2, 6, 3, 4)
|
||||
block_lse = torch.randn(2, 3, 6)
|
||||
|
||||
with pytest.raises(ValueError, match="block output shape"):
|
||||
update_out_and_lse(out, lse, block_out, block_lse, lse_layout="bhs")
|
||||
|
||||
|
||||
def test_ring_accumulation_matches_logsumexp_weighting():
|
||||
first_out = torch.zeros(1, 2, 1, 1)
|
||||
second_out = torch.ones(1, 2, 1, 1)
|
||||
first_lse = torch.zeros(1, 1, 2)
|
||||
second_lse = torch.zeros(1, 1, 2)
|
||||
|
||||
out, lse = update_out_and_lse(None, None, first_out, first_lse, lse_layout="bhs")
|
||||
out, lse = update_out_and_lse(out, lse, second_out, second_lse, lse_layout="bhs")
|
||||
|
||||
assert torch.allclose(out, torch.full_like(out, 0.5))
|
||||
assert torch.allclose(lse, torch.full_like(lse, torch.log(torch.tensor(2.0))))
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_sage_attention_rejects_mask_instead_of_ignoring_it(monkeypatch):
|
||||
fake_package = types.ModuleType("sageattention")
|
||||
fake_package.sageattn = lambda *args, **kwargs: pytest.fail("unexpected Sage kernel call")
|
||||
monkeypatch.setitem(sys.modules, "sageattention", fake_package)
|
||||
module_name = "vllm_omni.diffusion.attention.backends.sage_attn"
|
||||
sys.modules.pop(module_name, None)
|
||||
try:
|
||||
backend_module = importlib.import_module(module_name)
|
||||
impl = backend_module.SageAttentionImpl(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
softmax_scale=1.0 / 8.0,
|
||||
causal=False,
|
||||
)
|
||||
query = torch.randn(1, 2, 4, 64)
|
||||
metadata = AttentionMetadata(attn_mask=torch.ones(1, 2, dtype=torch.bool))
|
||||
|
||||
with pytest.raises(ValueError, match="does not support attn_mask"):
|
||||
impl.forward_cuda(query, query, query, metadata)
|
||||
finally:
|
||||
sys.modules.pop(module_name, None)
|
||||
@@ -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
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
@@ -9,6 +9,8 @@ import pytest
|
||||
import torch
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion, pytest.mark.cpu]
|
||||
|
||||
|
||||
@@ -17,7 +19,7 @@ SAGE_ATTN3_MODULE = "vllm_omni.diffusion.attention.backends.sage_attn3"
|
||||
|
||||
def load_sage_attn3_module(monkeypatch: pytest.MonkeyPatch, kernel_impl):
|
||||
fake_module = types.ModuleType("sageattn3")
|
||||
fake_module.sageattn3_blackwell = kernel_impl
|
||||
setattr(fake_module, "sageattn3_blackwell", kernel_impl)
|
||||
monkeypatch.setitem(sys.modules, "sageattn3", fake_module)
|
||||
sys.modules.pop(SAGE_ATTN3_MODULE, None)
|
||||
return importlib.import_module(SAGE_ATTN3_MODULE)
|
||||
@@ -51,21 +53,11 @@ def test_sage_attn3_forward_uses_blackwell_layout(monkeypatch: pytest.MonkeyPatc
|
||||
assert torch.allclose(output, expected)
|
||||
|
||||
|
||||
def test_sage_attn3_falls_back_to_sdpa_for_gqa(monkeypatch: pytest.MonkeyPatch):
|
||||
def test_sage_attn3_rejects_gqa_instead_of_falling_back(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_kernel(*args, **kwargs):
|
||||
raise AssertionError("sageattn3_blackwell should not be used for GQA")
|
||||
|
||||
backend_module = load_sage_attn3_module(monkeypatch, fake_kernel)
|
||||
sdpa_calls = {}
|
||||
|
||||
def fake_sdpa(query, key, value, **kwargs):
|
||||
sdpa_calls["query_shape"] = query.shape
|
||||
sdpa_calls["key_shape"] = key.shape
|
||||
sdpa_calls["enable_gqa"] = kwargs["enable_gqa"]
|
||||
return query + 1
|
||||
|
||||
monkeypatch.setattr(backend_module.F, "scaled_dot_product_attention", fake_sdpa)
|
||||
|
||||
impl = backend_module.SageAttention3Impl(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
@@ -77,13 +69,38 @@ def test_sage_attn3_falls_back_to_sdpa_for_gqa(monkeypatch: pytest.MonkeyPatch):
|
||||
key = torch.randn(2, 8, 2, 64)
|
||||
value = torch.randn(2, 8, 2, 64)
|
||||
|
||||
output = impl.forward_cuda(query, key, value)
|
||||
with pytest.raises(NotImplementedError, match="does not support GQA/MQA"):
|
||||
impl.forward_cuda(query, key, value)
|
||||
|
||||
assert sdpa_calls["query_shape"] == (2, 4, 8, 64)
|
||||
assert sdpa_calls["key_shape"] == (2, 2, 8, 64)
|
||||
assert sdpa_calls["enable_gqa"] is True
|
||||
expected = (query.permute(0, 2, 1, 3) + 1).permute(0, 2, 1, 3)
|
||||
assert torch.allclose(output, expected)
|
||||
|
||||
def test_sage_attn3_rejects_mask_instead_of_ignoring_it(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_kernel(*args, **kwargs):
|
||||
raise AssertionError("sageattn3_blackwell should not run with an unsupported mask")
|
||||
|
||||
backend_module = load_sage_attn3_module(monkeypatch, fake_kernel)
|
||||
impl = backend_module.SageAttention3Impl(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
softmax_scale=1.0 / 8.0,
|
||||
causal=False,
|
||||
)
|
||||
query = torch.randn(2, 8, 4, 64)
|
||||
metadata = AttentionMetadata(attn_mask=torch.ones(2, 8, dtype=torch.bool))
|
||||
|
||||
with pytest.raises(ValueError, match="does not support attn_mask"):
|
||||
impl.forward_cuda(query, query, query, metadata)
|
||||
|
||||
|
||||
def test_sage_attn3_rejects_custom_softmax_scale(monkeypatch: pytest.MonkeyPatch):
|
||||
backend_module = load_sage_attn3_module(monkeypatch, lambda *args, **kwargs: None)
|
||||
|
||||
with pytest.raises(ValueError, match="does not expose a custom softmax scale"):
|
||||
backend_module.SageAttention3Impl(
|
||||
num_heads=4,
|
||||
head_size=64,
|
||||
softmax_scale=1.0,
|
||||
causal=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="sage_attn3 tests require CUDA platform")
|
||||
@@ -115,10 +132,39 @@ def test_cuda_platform_selects_sage_attn3_alias(monkeypatch: pytest.MonkeyPatch)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="sage_attn3 tests require CUDA platform")
|
||||
def test_cuda_platform_falls_back_when_sage_attn3_gpu_is_unsupported(monkeypatch: pytest.MonkeyPatch):
|
||||
@pytest.mark.parametrize("head_size", [32, 320])
|
||||
def test_cuda_platform_rejects_explicit_sage_attn3_unsupported_head_size(
|
||||
monkeypatch: pytest.MonkeyPatch, head_size: int
|
||||
):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda import platform as cuda_platform_module
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
original_import_module = importlib.import_module
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(10, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
monkeypatch.setattr(
|
||||
cuda_platform_module.importlib,
|
||||
"import_module",
|
||||
lambda module_name: object() if module_name == "sageattn3" else original_import_module(module_name),
|
||||
)
|
||||
load_sage_attn3_module(monkeypatch, lambda *args, **kwargs: None)
|
||||
|
||||
with pytest.raises(ValueError, match=f"head_size={head_size} is unsupported"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("SAGE_ATTN_3", head_size=head_size)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="sage_attn3 tests require CUDA platform")
|
||||
def test_cuda_platform_rejects_explicit_sage_attn3_on_unsupported_gpu(monkeypatch: pytest.MonkeyPatch):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.registry import DiffusionAttentionBackendEnum
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
@@ -129,6 +175,33 @@ def test_cuda_platform_falls_back_when_sage_attn3_gpu_is_unsupported(monkeypatch
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
|
||||
backend_path = CudaOmniPlatform.get_diffusion_attn_backend_cls("SAGE_ATTN_3", head_size=64)
|
||||
with pytest.raises(ValueError, match="explicitly selected"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("SAGE_ATTN_3", head_size=64)
|
||||
|
||||
assert backend_path == DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="sage_attn3 tests require CUDA platform")
|
||||
def test_cuda_platform_rejects_missing_explicit_sage_attn3(monkeypatch: pytest.MonkeyPatch):
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
from vllm_omni.diffusion.envs import PACKAGES_CHECKER
|
||||
from vllm_omni.platforms.cuda import platform as cuda_platform_module
|
||||
from vllm_omni.platforms.cuda.platform import CudaOmniPlatform
|
||||
|
||||
original_import_module = importlib.import_module
|
||||
|
||||
monkeypatch.setattr(
|
||||
CudaOmniPlatform,
|
||||
"get_device_capability",
|
||||
classmethod(lambda cls, device_id=0: DeviceCapability(10, 0)),
|
||||
)
|
||||
monkeypatch.setattr(PACKAGES_CHECKER, "get_packages_info", lambda: {"has_flash_attn": False})
|
||||
|
||||
def _missing_sageattn3(module_name):
|
||||
if module_name == "sageattn3":
|
||||
raise ImportError("sageattn3 not installed")
|
||||
return original_import_module(module_name)
|
||||
|
||||
monkeypatch.setattr(cuda_platform_module.importlib, "import_module", _missing_sageattn3)
|
||||
|
||||
with pytest.raises(ImportError, match="explicitly selected"):
|
||||
CudaOmniPlatform.get_diffusion_attn_backend_cls("SAGE_ATTN_3", head_size=64)
|
||||
@@ -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
|
||||
"""Unit tests for diffusion attention backend selection."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -100,9 +100,12 @@ def test_platform_default_used_without_resolved_spec(monkeypatch, attention_conf
|
||||
def test_backend_class_resolution_is_cached(monkeypatch):
|
||||
platform_calls = []
|
||||
load_calls = []
|
||||
fake_platform = SimpleNamespace(
|
||||
get_diffusion_attn_backend_cls=lambda **kwargs: (platform_calls.append(kwargs) or "fake.module.Backend")
|
||||
)
|
||||
|
||||
def fake_get_cls(**kwargs):
|
||||
platform_calls.append(kwargs)
|
||||
return "fake.module.Backend"
|
||||
|
||||
fake_platform = SimpleNamespace(get_diffusion_attn_backend_cls=fake_get_cls)
|
||||
|
||||
monkeypatch.setattr("vllm_omni.platforms.current_omni_platform", fake_platform)
|
||||
|
||||
@@ -126,6 +129,39 @@ def test_backend_class_resolution_is_cached(monkeypatch):
|
||||
assert load_calls == ["fake.module.Backend"]
|
||||
|
||||
|
||||
def test_capability_query_loads_explicit_cudnn_without_platform(monkeypatch):
|
||||
platform_calls = []
|
||||
|
||||
def fake_get_cls(**kwargs):
|
||||
platform_calls.append(kwargs)
|
||||
return "fake.module.MustNotBeCalled"
|
||||
|
||||
fake_platform = SimpleNamespace(get_diffusion_attn_backend_cls=fake_get_cls)
|
||||
monkeypatch.setattr("vllm_omni.platforms.current_omni_platform", fake_platform)
|
||||
|
||||
config = AttentionConfig(default=AttentionSpec(backend="CUDNN_ATTN"))
|
||||
backend = selector.get_attn_backend_for_capability(role="self", attention_config=config)
|
||||
|
||||
assert backend.get_name() == "CUDNN_ATTN"
|
||||
assert backend.supports_attention_mask()
|
||||
assert platform_calls == []
|
||||
|
||||
|
||||
def test_capability_query_uses_unknown_head_size_for_platform_default(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_get_backend(backend_name, head_size, allow_trtllm_default=True):
|
||||
calls.append((backend_name, head_size, allow_trtllm_default))
|
||||
return _PlatformBackend
|
||||
|
||||
monkeypatch.setattr(selector, "_cached_get_backend_cls", fake_get_backend)
|
||||
|
||||
backend = selector.get_attn_backend_for_capability(role="self", attention_config=AttentionConfig())
|
||||
|
||||
assert backend is _PlatformBackend
|
||||
assert calls == [(None, selector.HEAD_SIZE_UNKNOWN, True)]
|
||||
|
||||
|
||||
def test_load_backend_cls_reports_missing_module():
|
||||
with pytest.raises(ImportError, match="Failed to import module missing_attention_backend"):
|
||||
selector._load_backend_cls("missing_attention_backend.Backend")
|
||||
|
||||
+32
-17
@@ -6,7 +6,9 @@ Model specific tests for CacheDiT enablement.
|
||||
"""
|
||||
|
||||
import ast
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
@@ -17,7 +19,8 @@ from vllm.distributed import parallel_state
|
||||
import vllm_omni.diffusion.cache.cachedit as cd_backend
|
||||
import vllm_omni.diffusion.cache.cachedit.model_specific as cd_model_specific
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig, CacheDiTBackend, cache_summary
|
||||
from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import AttentionConfig, DiffusionCacheConfig
|
||||
from vllm_omni.diffusion.models.cosmos3.transformer_cosmos3 import Cosmos3VFMTransformer
|
||||
from vllm_omni.diffusion.models.helios.helios_transformer import HeliosTransformer3DModel
|
||||
from vllm_omni.diffusion.models.longcat_image.longcat_image_transformer import LongCatImageTransformer2DModel
|
||||
@@ -35,6 +38,17 @@ SEPARATE_CFG_TRANSFORMERS = [
|
||||
SAMPLE_CACHE_CONFIG = DiffusionCacheConfig()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _force_torch_sdpa():
|
||||
"""Pin TORCH_SDPA so CPU shape tests do not pick CUDA-only backends (FA3)."""
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(default="TORCH_SDPA"),
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
)
|
||||
with set_current_diffusion_config(od_config):
|
||||
yield
|
||||
|
||||
|
||||
def test_custom_cache_dit_enablers_are_registered_explicitly():
|
||||
expected_enablers = {
|
||||
"Wan22Pipeline": cd_model_specific.enable_cache_for_wan22,
|
||||
@@ -213,22 +227,23 @@ def test_ltx2_cache_dit_receives_audio_as_encoder(init_fake_tp_group):
|
||||
text_in = torch.full((1, seq_len, 16), 3.0)
|
||||
audio_text_in = torch.full((1, seq_len, 16), 4.0)
|
||||
|
||||
model = LTX2VideoTransformer3DModel(
|
||||
in_channels=16,
|
||||
out_channels=16,
|
||||
patch_size=1,
|
||||
patch_size_t=1,
|
||||
num_attention_heads=2,
|
||||
attention_head_dim=8,
|
||||
cross_attention_dim=16,
|
||||
audio_in_channels=16,
|
||||
audio_out_channels=16,
|
||||
audio_num_attention_heads=2,
|
||||
audio_attention_head_dim=8,
|
||||
audio_cross_attention_dim=16,
|
||||
num_layers=2,
|
||||
caption_channels=16,
|
||||
)
|
||||
with _force_torch_sdpa():
|
||||
model = LTX2VideoTransformer3DModel(
|
||||
in_channels=16,
|
||||
out_channels=16,
|
||||
patch_size=1,
|
||||
patch_size_t=1,
|
||||
num_attention_heads=2,
|
||||
attention_head_dim=8,
|
||||
cross_attention_dim=16,
|
||||
audio_in_channels=16,
|
||||
audio_out_channels=16,
|
||||
audio_num_attention_heads=2,
|
||||
audio_attention_head_dim=8,
|
||||
audio_cross_attention_dim=16,
|
||||
num_layers=2,
|
||||
caption_channels=16,
|
||||
)
|
||||
|
||||
# NOTE: This is currently using the LTX2 custom enabler, but the custom
|
||||
# enablers will be consolidated after
|
||||
|
||||
@@ -13,6 +13,8 @@ import vllm_omni.diffusion.data as diffusion_data
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.runtime import OmniServer, OmniServerParams, OnlineOmniClient, dummy_messages_from_mix_data
|
||||
from vllm_omni.diffusion.data import (
|
||||
AttentionConfig,
|
||||
AttentionSpec,
|
||||
DiffusionOutput,
|
||||
DiffusionParallelConfig,
|
||||
OmniDiffusionConfig,
|
||||
@@ -141,6 +143,84 @@ class TestPipelineArgumentsHandling:
|
||||
assert isinstance(output.output, MockPipelineOutput)
|
||||
assert output.output.image is stub_image
|
||||
|
||||
@staticmethod
|
||||
def _make_adapter(backend: str, set_attention_backend):
|
||||
adapter = DiffusersAdapterPipeline(
|
||||
od_config=_make_od_config(
|
||||
diffusion_attention_config=AttentionConfig(default=AttentionSpec(backend=backend)),
|
||||
)
|
||||
)
|
||||
adapter._pipeline = SimpleNamespace(
|
||||
transformer=SimpleNamespace(set_attention_backend=set_attention_backend),
|
||||
)
|
||||
return adapter
|
||||
|
||||
def test_explicit_unbound_backend_is_rejected(self):
|
||||
calls: list[str] = []
|
||||
adapter = self._make_adapter("CUDNN_ATTN", calls.append)
|
||||
|
||||
with pytest.raises(ValueError, match="do not provide a binding"):
|
||||
adapter._set_attention_backend()
|
||||
|
||||
assert calls == []
|
||||
|
||||
def test_failed_explicit_backend_does_not_fallback_to_native(self):
|
||||
calls: list[str] = []
|
||||
|
||||
def reject_backend(backend):
|
||||
calls.append(backend)
|
||||
raise RuntimeError(f"{backend} unavailable")
|
||||
|
||||
adapter = self._make_adapter("SAGE_ATTN", reject_backend)
|
||||
|
||||
with pytest.raises(RuntimeError, match="explicitly selected attention backend 'SAGE_ATTN'"):
|
||||
adapter._set_attention_backend()
|
||||
|
||||
assert calls == ["sage_hub", "sage", "sage_varlen"]
|
||||
assert "native" not in calls
|
||||
|
||||
def test_explicit_flash_attn_3_hub_does_not_fallback_to_fa2_or_local(self, monkeypatch):
|
||||
monkeypatch.setattr(DiffusersAdapterPipeline, "_is_blackwell_gpu", lambda self: False)
|
||||
calls: list[str] = []
|
||||
|
||||
def accept_later_backends(backend):
|
||||
calls.append(backend)
|
||||
if backend in ("flash_hub", "flash_varlen_hub", "flash", "flash_varlen", "_native_flash"):
|
||||
return
|
||||
raise RuntimeError(f"{backend} unavailable")
|
||||
|
||||
adapter = self._make_adapter("FLASH_ATTN_3_HUB", accept_later_backends)
|
||||
|
||||
with pytest.raises(RuntimeError, match="explicitly selected attention backend 'FLASH_ATTN_3_HUB'"):
|
||||
adapter._set_attention_backend()
|
||||
|
||||
assert calls == ["_flash_3_hub", "_flash_3_varlen_hub"]
|
||||
|
||||
def test_explicit_flash_attn_hub_does_not_fallback_to_local(self, monkeypatch):
|
||||
monkeypatch.setattr(DiffusersAdapterPipeline, "_is_blackwell_gpu", lambda self: False)
|
||||
calls: list[str] = []
|
||||
|
||||
def accept_local_flash(backend):
|
||||
calls.append(backend)
|
||||
if backend in ("flash", "flash_varlen", "_native_flash"):
|
||||
return
|
||||
raise RuntimeError(f"{backend} unavailable")
|
||||
|
||||
adapter = self._make_adapter("FLASH_ATTN_HUB", accept_local_flash)
|
||||
|
||||
with pytest.raises(RuntimeError, match="explicitly selected attention backend 'FLASH_ATTN_HUB'"):
|
||||
adapter._set_attention_backend()
|
||||
|
||||
assert calls == ["flash_hub", "flash_varlen_hub"]
|
||||
|
||||
def test_explicit_torch_sdpa_maps_to_diffusers_native(self):
|
||||
calls: list[str] = []
|
||||
adapter = self._make_adapter("TORCH_SDPA", calls.append)
|
||||
|
||||
adapter._set_attention_backend()
|
||||
|
||||
assert calls == ["native"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"feature_id",
|
||||
[
|
||||
|
||||
@@ -989,6 +989,89 @@ class TestDimensionValidation:
|
||||
# Since expected_dims=3 but tensor has 4 dims, should return original
|
||||
assert result.shape == tensor_4d.shape
|
||||
|
||||
def test_auto_pad_calls_attention_mask_capability(self, monkeypatch):
|
||||
from vllm_omni.diffusion.attention import selector
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelConfig
|
||||
from vllm_omni.diffusion.hooks.sequence_parallel import SequenceParallelSplitHook
|
||||
|
||||
class NoMaskBackend:
|
||||
@classmethod
|
||||
def supports_attention_mask(cls, attention_spec=None):
|
||||
del attention_spec
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_name():
|
||||
return "NO_MASK_BACKEND"
|
||||
|
||||
monkeypatch.setattr(parallel_state, "get_sequence_parallel_world_size", lambda: 2)
|
||||
monkeypatch.setattr(selector, "get_attn_backend_for_capability", lambda **kwargs: NoMaskBackend)
|
||||
|
||||
hook = SequenceParallelSplitHook(
|
||||
metadata={},
|
||||
config=SequenceParallelConfig(ulysses_degree=2, ring_degree=1),
|
||||
)
|
||||
tensor = torch.randn(1, 3, 8)
|
||||
|
||||
with pytest.raises(ValueError, match="does not support attention_mask"):
|
||||
hook._shard_with_auto_pad(tensor, dim=1)
|
||||
|
||||
def test_auto_pad_allows_explicit_cudnn(self, monkeypatch):
|
||||
from vllm_omni.diffusion.data import AttentionConfig, AttentionSpec, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelConfig
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.hooks.sequence_parallel import SequenceParallelSplitHook
|
||||
|
||||
monkeypatch.setattr(parallel_state, "get_sequence_parallel_world_size", lambda: 2)
|
||||
monkeypatch.setattr(parallel_state, "get_sequence_parallel_rank", lambda: 0)
|
||||
monkeypatch.setattr(parallel_state, "get_ring_parallel_world_size", lambda: 1)
|
||||
|
||||
hook = SequenceParallelSplitHook(
|
||||
metadata={},
|
||||
config=SequenceParallelConfig(ulysses_degree=2, ring_degree=1),
|
||||
)
|
||||
tensor = torch.randn(1, 3, 8)
|
||||
od_config = OmniDiffusionConfig(
|
||||
model="test",
|
||||
dtype=torch.float32,
|
||||
diffusion_attention_config=AttentionConfig(default=AttentionSpec(backend="CUDNN_ATTN")),
|
||||
)
|
||||
|
||||
with set_forward_context(omni_diffusion_config=od_config):
|
||||
result = hook._shard_with_auto_pad(tensor, dim=1)
|
||||
|
||||
# seq_len=3 padded to 4, then sharded by world_size=2 → rank 0 gets 2.
|
||||
assert result.shape == (1, 2, 8)
|
||||
|
||||
def test_auto_pad_rejects_explicit_flashinfer_cute_on_blackwell(self, monkeypatch):
|
||||
from vllm_omni.diffusion.data import AttentionConfig, AttentionSpec, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed import parallel_state
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelConfig
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.hooks.sequence_parallel import SequenceParallelSplitHook
|
||||
|
||||
monkeypatch.setattr(parallel_state, "get_sequence_parallel_world_size", lambda: 2)
|
||||
monkeypatch.setattr(parallel_state, "get_sequence_parallel_rank", lambda: 0)
|
||||
monkeypatch.setattr(parallel_state, "get_ring_parallel_world_size", lambda: 1)
|
||||
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *args, **kwargs: (10, 0))
|
||||
|
||||
hook = SequenceParallelSplitHook(
|
||||
metadata={},
|
||||
config=SequenceParallelConfig(ulysses_degree=2, ring_degree=1),
|
||||
)
|
||||
tensor = torch.randn(1, 3, 8)
|
||||
od_config = OmniDiffusionConfig(
|
||||
model="test",
|
||||
dtype=torch.float32,
|
||||
diffusion_attention_config=AttentionConfig(default=AttentionSpec(backend="FLASHINFER_ATTN")),
|
||||
)
|
||||
|
||||
with set_forward_context(omni_diffusion_config=od_config):
|
||||
with pytest.raises(ValueError, match="does not support attention_mask"):
|
||||
hook._shard_with_auto_pad(tensor, dim=1)
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
class TestStrictModeSplitValidation:
|
||||
|
||||
@@ -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
|
||||
|
||||
import logging
|
||||
import os
|
||||
@@ -63,6 +63,20 @@ def _force_default_gemm(monkeypatch):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _force_torch_sdpa():
|
||||
"""Pin TORCH_SDPA so CPU shape tests do not pick CUDA-only backends (FA3)."""
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import AttentionConfig
|
||||
|
||||
od_config = SimpleNamespace(
|
||||
diffusion_attention_config=AttentionConfig(default="TORCH_SDPA"),
|
||||
parallel_config=SimpleNamespace(ring_degree=1),
|
||||
)
|
||||
with set_current_diffusion_config(od_config):
|
||||
yield
|
||||
|
||||
|
||||
def _randomize_parameters(module: torch.nn.Module) -> None:
|
||||
"""Fill parameters with small random values.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -182,7 +182,8 @@ def _fake_ltx_parallel_attention():
|
||||
return "FLASH_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def supports_attention_mask():
|
||||
def supports_attention_mask(attention_spec=None):
|
||||
del attention_spec
|
||||
return True
|
||||
|
||||
def run(name):
|
||||
|
||||
Reference in new issue
Block a user