From f2ce6725846e8a6773d8236d0d442eb473fd270e Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:35:16 +0800 Subject: [PATCH 1/9] feat: add FlashInfer attention backend for SM120 decode Register FlashInfer (flashinfer-python >= 0.7.0, XQA kernels) as a paged decode backend through the attention contract layer: - explicit "flashinfer" selection plus an auto slot between FlashAttention-2 and Triton; the SM gate keeps auto away from it on SM8/9/10, so it is only reached where every FlashAttention generation is rejected (SM 12.x) - capabilities declare CUDA graphs and async scheduling; packed prefill stays FA4-only because the adapter leaves the kernel without a prefill entry point - validation rejects unsupported setups explicitly (float16 unvalidated on SM120, page sizes outside the compiled XQA variants, head_dim not divisible by 16); the workspace allocates lazily on first execution so backend selection performs no device allocations - empty batches return early because the kernel host-dispatch SIGFPEs on batch 0; padded block-table columns are clamped non-negative and the kernel bounds reads by seq_lens, so -1/zero/stale padding stays invisible - requires CUDA_HOME with nvcc >= 12.9 and that toolkit's lib directory on LD_LIBRARY_PATH for the just-in-time compiled modules --- docs/flashinfer.md | 97 ++++++++++ pyproject.toml | 1 + tests/test_backend_selection.py | 33 +++- tests/test_flashinfer_attention.py | 216 +++++++++++++++++++++++ vllm_rlt/attention/backend.py | 13 +- vllm_rlt/entrypoints/cli.py | 1 + vllm_rlt/entrypoints/serve.py | 1 + vllm_rlt/kernels/flashinfer_attention.py | 115 ++++++++++++ 8 files changed, 465 insertions(+), 12 deletions(-) create mode 100644 docs/flashinfer.md create mode 100644 tests/test_flashinfer_attention.py create mode 100644 vllm_rlt/kernels/flashinfer_attention.py diff --git a/docs/flashinfer.md b/docs/flashinfer.md new file mode 100644 index 00000000..cc6fc1a1 --- /dev/null +++ b/docs/flashinfer.md @@ -0,0 +1,97 @@ +# FlashInfer Attention Backend + +The `flashinfer` backend runs paged decode attention through FlashInfer's XQA +kernels (`flashinfer-python >= 0.7.0`, `trtllm_batch_decode_with_kv_cache`, +`backend="auto"`). It is the validated attention path for NVIDIA consumer +Blackwell (SM120, e.g. RTX 5090), where the pinned FlashAttention releases +reject paged KV. + +## Scope + +- Decode and per-token prefill, identical semantics to the Triton path, + including CUDA Graph capture and asynchronous scheduling. +- No packed prefill: the engine keeps the FA4-only packed path closed, so + prefill runs per token exactly as with Triton. +- No prefill/decode disaggregation; PD entrypoints reject the backend + explicitly. +- `bfloat16` only. `float16` is rejected at startup: the kernels compute + correctly, but flashinfer-python 0.7.0.post1 crashes the process (host + SIGFPE) while building the f16 JIT module on first in-process use. +- `--block-size` must be one of `16, 32, 64, 128` (compiled XQA page-size + variants) and `head_dim` must be divisible by 16 within `[16, 512]`. + +## Installation and runtime requirements + +```bash +pip install -e ".[flashinfer]" +``` + +The XQA kernels are compiled just in time on first use, which imposes two +environment requirements beyond the package install: + +1. **A CUDA toolkit with `nvcc >= 12.9` reachable via `CUDA_HOME`.** SM120 + kernels are built for the `compute_120f` architecture family, which needs + CUDA 12.9 or newer. Without `nvcc`, startup falls back to comparing against + the CUDA version PyTorch was built with, and SM 12.x devices are rejected + with `SM 12.x requires CUDA >= 12.9`. +2. **That toolkit's `lib` directory on `LD_LIBRARY_PATH`.** The compiled + modules link `libcudart.so.13`; pip-installed toolkits keep it outside the + default loader path. With the pip toolkit layout + (`nvidia-cuda-nvcc`/`nvidia-cuda-runtime`/`nvidia-cuda-cccl`/...), the + unified tree lives under `site-packages/nvidia/cu13` and may need + `lib64/libcudart.so` and `lib64/stubs/libcuda.so` developer symlinks, which + the wheels do not ship. + +The first call on a machine compiles for a few seconds and caches under +`~/.cache/flashinfer///`; later calls, including CUDA +Graph capture warmups, reuse the cache. + +## Running + +```bash +vllm-rlt --model --revision \ + --device cuda --dtype bfloat16 --attention-backend flashinfer +``` + +The adapter holds one 128 MiB zero-initialized workspace for the kernel's +scratch and softmax statistics; it is allocated once at startup and reused, so +graph capture performs no new allocations. Padded block-table columns are +clamped non-negative before the call: the engine produces `-1` padding on the +synchronous path, `0` on the asynchronous path, and stale-but-valid ids in +CUDA Graph replay beyond the current width. The kernel bounds reads by +`seq_lens`, so all three padding states stay invisible. + +## Choosing between Triton and FlashInfer + +SM120 is the only validated target for this backend; on it, FlashInfer decodes +noticeably faster at low concurrency (single-request decode measured ~2x +against the Triton kernel at 256-token contexts) because the XQA kernel +parallelizes a single query row across KV chunks, while the Triton kernel +spawns one program per (row, head). At high concurrency with long contexts the +two are comparable; choose Triton when its determinism properties matter more +and FlashInfer for single-user or low-batch latency. SM9/SM10 devices are +accepted but unvalidated — prefer FlashAttention there until validated +configurations are recorded. + +## Validation status + +Validated on RTX 5090 (SM120, 32 GB) with Ouro-1.4B BF16, `block_size=16`, +fixed four-loop decode: oracle parity against the reference paged attention, +token/exit-depth equality against the Triton backend across synchronous, +asynchronous, and multi-stream execution with static buffers and graph replay, +and end-to-end greedy generation. + +## Accuracy note (GSM8K-87, single greedy pass) + +On the frozen GSM8K-87 protocol (HF baseline 59/87), a fixed four-loop greedy +pass scores 58/87 with FlashInfer versus 61/87 with Triton. 64 of 87 +generations are token-identical between the two backends; the remaining 23 +diverge at scattered positions with unchanged exit depths, and the net +correct-answer flips are 3 against, 0 for. Kernel-level comparison against a +float32 oracle at 352-1024 token contexts shows the Triton kernel is +near-exact (max deviation up to 5e-4) while XQA's split reductions deviate by +up to 4e-3 — within normal BF16 kernel variation, but enough to flip +near-tied greedy argmax decisions during long chain-of-thought decoding. +Triton remains the default backend; treat this note as the expected greedy +variation when opting into FlashInfer on SM120. + diff --git a/pyproject.toml b/pyproject.toml index 93a60a77..b79c36d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ pd = ["nixl==1.4.1"] serve = [] flash-attn = ["flash-attn>=2.8.3"] flash-attn4 = ["flash-attn-4==4.0.0b30"] +flashinfer = ["flashinfer-python>=0.7.0"] triton = [] dev = ["pytest>=8", "ruff>=0.9"] diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index f8624beb..5824d950 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -15,9 +15,15 @@ @pytest.fixture def packages(monkeypatch): - from vllm_rlt.kernels import flash_attention - - installed = {"flash_attn", "flash_attn_3.flash_attn_interface", "flash_attn.cute", "triton"} + from vllm_rlt.kernels import flash_attention, flashinfer_attention + + installed = { + "flash_attn", + "flash_attn_3.flash_attn_interface", + "flash_attn.cute", + "triton", + "flashinfer", + } original_import = flash_attention.importlib.import_module def import_module(name): @@ -32,10 +38,17 @@ def import_module(name): flash_attn_with_kvcache=lambda *args, **kwargs: None, flash_attn_varlen_func=lambda *args, **kwargs: None, ) + if name == "flashinfer.decode": + if "flashinfer" not in installed: + raise ImportError("flashinfer is not installed") + return SimpleNamespace( + trtllm_batch_decode_with_kv_cache=lambda *args, **kwargs: None + ) return original_import(name) monkeypatch.setattr(flash_attention.importlib, "import_module", import_module) monkeypatch.setattr(flash_attention, "version", lambda name: "test") + monkeypatch.setattr(flashinfer_attention, "version", lambda name: "test") monkeypatch.setattr(torch.version, "hip", None) return installed @@ -74,7 +87,8 @@ def test_cpu_auto_reports_torch_and_runs_reference_attention(caplog): "flash_attn_2", ), ((10, 0), torch.bfloat16, 128, 16, (), "flash_attn_4"), - ((12, 0), torch.bfloat16, 128, 16, (), "triton"), + ((12, 0), torch.bfloat16, 128, 16, (), "flashinfer"), + ((12, 0), torch.bfloat16, 128, 16, ("flashinfer",), "triton"), ((7, 5), torch.float16, 128, 256, (), "torch"), ], ) @@ -109,12 +123,15 @@ def test_auto_reports_missing_packages_and_configuration(packages, monkeypatch): assert "multiple of 256" in reason and "triton" in reason -@pytest.mark.parametrize("backend", ["flash_attn_2", "triton"]) -def test_explicit_missing_package_never_falls_back(packages, monkeypatch, backend): - monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (8, 9)) +@pytest.mark.parametrize( + "backend,sm,block_size", + [("flash_attn_2", (8, 9), 256), ("triton", (8, 9), 256), ("flashinfer", (12, 0), 16)], +) +def test_explicit_missing_package_never_falls_back(packages, monkeypatch, backend, sm, block_size): + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: sm) packages.clear() with pytest.raises(ImportError): - create_backend(backend, torch.device("cuda"), torch.bfloat16, 128, 256) + create_backend(backend, torch.device("cuda"), torch.bfloat16, 128, block_size) def test_explicit_flash_incompatibility_is_not_overridden(packages, monkeypatch): diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py new file mode 100644 index 00000000..af8300b9 --- /dev/null +++ b/tests/test_flashinfer_attention.py @@ -0,0 +1,216 @@ +"""FlashInfer paged attention: gates, padding states, graphs and mixed depths.""" + +import pytest +import torch + +from tests.helpers import tiny_ouro_config +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig +from vllm_rlt.engine.llm_engine import LLMEngine +from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention +from vllm_rlt.kernels.paged_attention import torch_paged_attention +from vllm_rlt.models import OuroForCausalLM + + +def _cuda_like(monkeypatch, sm): + monkeypatch.setattr(torch.version, "hip", None) + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: sm) + + +def test_unsupported_architecture_rejected_before_import(monkeypatch): + from vllm_rlt.kernels import flashinfer_attention + + _cuda_like(monkeypatch, (7, 5)) + + def unexpected_import(name): + pytest.fail(f"unsupported architecture reached dependency import: {name}") + + monkeypatch.setattr(flashinfer_attention.importlib, "import_module", unexpected_import) + with pytest.raises(ValueError, match="not supported on SM75"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + + +@pytest.mark.parametrize( + "dtype", [torch.float16, torch.float32, torch.complex64], ids=["fp16", "fp32", "complex"] +) +def test_unvalidated_dtypes_rejected(monkeypatch, dtype): + _cuda_like(monkeypatch, (12, 0)) + with pytest.raises(ValueError): + FlashInferPagedAttention(torch.device("cuda"), dtype, 128, 16) + + +def test_geometry_and_page_size_rejections(monkeypatch): + _cuda_like(monkeypatch, (12, 0)) + with pytest.raises(ValueError, match="divisible by 16"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 100, 16) + with pytest.raises(ValueError, match="divisible by 16"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 8, 16) + with pytest.raises(ValueError, match="page-size variants"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 17) + with pytest.raises(ValueError, match="NVIDIA"): + FlashInferPagedAttention(torch.device("cpu"), torch.bfloat16, 128, 16) + + +def test_missing_package_raises_import_error_without_fallback(monkeypatch): + from importlib.metadata import PackageNotFoundError + + from vllm_rlt.kernels import flashinfer_attention + + _cuda_like(monkeypatch, (12, 0)) + + def missing(name): + raise PackageNotFoundError(name) + + monkeypatch.setattr(flashinfer_attention, "version", missing) + with pytest.raises(ImportError, match="install flashinfer"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + + +@pytest.mark.gpu +def test_backend_contract_anchors(): + attention = FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + assert attention.info["backend"] == "flashinfer" + assert attention.info["package"] == "flashinfer-python" + assert attention.info["page_size"] == 16 + assert attention.info["kernel"] == "xqa" + assert attention.capabilities.packed_prefill is False + assert attention.capabilities.cuda_graphs is True + assert attention.capabilities.async_scheduling is True + # Absence is the contract: the FA4 packed-prefill gates in the engine and + # model runner key off a missing generation attribute staying missing. + assert not hasattr(attention, "generation") + assert not hasattr(attention, "prefill") + + +@pytest.mark.gpu +@pytest.mark.parametrize("heads", [2, 4]) +def test_ragged_strided_paged_attention_with_zero_length_row(heads): + torch.manual_seed(9) + # Layer slicing leaves a non-contiguous block stride, as in the real cache. + keys = torch.randn(12, 3, 16, 2, 128, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(12, 3, 16, 2, 128, device="cuda", dtype=torch.bfloat16)[:, 1] + q = torch.randn(4, heads, 128, device="cuda", dtype=torch.bfloat16) + tables = torch.tensor( + [[7, 2, 9], [3, 0, 0], [1, 8, 6], [0, 0, 0]], device="cuda", dtype=torch.int32 + ) + lengths = torch.tensor([35, 1, 47, 0], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 128, 16) + expected = torch_paged_attention(q, keys, values, tables, lengths) + actual = attention(q, keys, values, tables, lengths) + torch.testing.assert_close(actual, expected, atol=0.015, rtol=0.02) + assert torch.isfinite(actual).all() + # Zero-length rows are async padding rows; they must read as exact zeros, + # not small garbage, so downstream masking stays optional. + assert torch.count_nonzero(actual[-1]) == 0 + + +@pytest.mark.gpu +def test_padding_states_are_invisible(): + torch.manual_seed(11) + keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + q = torch.randn(3, 2, 64, device="cuda", dtype=torch.bfloat16) + lengths = torch.tensor([16, 31, 20], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 64, 16) + outputs = [] + for fill in (-1, 0, 19): # sync pad, async pad, stale-but-valid replay id + tables = torch.full((3, 4), fill, device="cuda", dtype=torch.int32) + for row in range(3): + tables[row, :2] = torch.arange(row * 2, row * 2 + 2, device="cuda") + outputs.append(attention(q, keys, values, tables, lengths)) + assert torch.equal(outputs[0], outputs[1]) + assert torch.equal(outputs[0], outputs[2]) + + +@pytest.mark.gpu +def test_flashinfer_decode_same_queries_match_across_batch_sizes(): + generator = torch.Generator(device="cuda").manual_seed(1234) + dtype = torch.bfloat16 + # Ouro geometry and long enough prefixes to exercise any KV split selection. + keys = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] + values = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] + q = torch.randn(4, 16, 128, generator=generator, device="cuda", dtype=dtype) + tables = torch.arange(260, device="cuda", dtype=torch.int32).view(4, 65) + lengths = torch.tensor([1025, 1029, 1025, 1031], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, dtype, 128, 16) + together = attention(q, keys, values, tables, lengths) + for rows in ([2, 3], [3, 0], [1]): + separate = attention(q[rows], keys, values, tables[rows], lengths[rows]) + torch.testing.assert_close(separate, together[rows], rtol=0, atol=0) + + +@pytest.mark.gpu +def test_graph_replay_updates_buffers(): + torch.manual_seed(5) + keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + rows, width = 4, 4 + q = torch.randn(rows, 2, 64, device="cuda", dtype=torch.bfloat16) + static_tables = torch.zeros(rows, width, device="cuda", dtype=torch.int32) + static_lengths = torch.full((rows,), 16, device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 64, 16) + # Warm JIT modules and workspace outside the capture region. + attention(q, keys, values, static_tables, static_lengths) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = attention(q, keys, values, static_tables, static_lengths) + generator = torch.Generator().manual_seed(21) + for trial in range(3): + for row in range(rows): + start = (row * 3 + trial * 5) % 16 + static_tables[row] = torch.arange(start, start + width, dtype=torch.int32) + static_lengths.copy_( + torch.randint(1, width * 16, (rows,), generator=generator, dtype=torch.int32) + ) + graph.replay() + expected = torch_paged_attention(q, keys, values, static_tables, static_lengths) + torch.testing.assert_close(out, expected, atol=0.015, rtol=0.02) + + +@pytest.mark.gpu +@pytest.mark.parametrize("layout", ["last_exited", "shared"]) +@pytest.mark.parametrize("static", [False, True]) +def test_flashinfer_sync_async_mixed_depths(layout, static): + torch.manual_seed(123) + config = tiny_ouro_config(head_dim=64) + model = OuroForCausalLM(config).to(device="cuda", dtype=torch.bfloat16) + traces = {str(i): [4, 2 + i % 3, 4, 2, 3, 4] for i in range(3)} + outputs = [] + for backend, asynchronous, multi in [ + ("triton", False, False), + ("flashinfer", False, False), + ("flashinfer", True, False), + ("flashinfer", True, True), + ]: + engine = LLMEngine( + model, + cache_config=CacheConfig(num_blocks=48, block_size=16, layout=layout), + scheduler_config=SchedulerConfig( + max_num_seqs=3, max_num_batched_tokens=8, prefill_chunk_size=4 + ), + execution_config=ExecutionConfig( + async_scheduling=asynchronous, + multi_stream=multi, + static_buffers=static, + pad_to_power_of_two=static, + ), + exit_config=ExitConfig("trace", depths_by_request=traces), + attention_backend=backend, + ) + for i in range(3): + engine.add_request( + str(i), + [2, 3, 4, 5] * (i + 1), + SamplingParams(max_tokens=6, min_loops=1, ignore_eos=True), + ) + finished = {} + for _ in range(300): + if not engine.has_unfinished_requests(): + break + for out in engine.step(): + if out.finished: + finished[out.request_id] = (out.token_ids, out.exit_depths) + assert len(finished) == 3 + assert engine.cache_manager.num_used_blocks == 0 + outputs.append(finished) + assert all(value == outputs[0] for value in outputs) diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index 15bde763..2e2005a9 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -8,6 +8,7 @@ import torch from vllm_rlt.kernels.flash_attention import FLASH_BACKENDS, FlashPagedAttention +from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention from vllm_rlt.kernels.paged_attention import torch_paged_attention, triton_paged_attention @@ -47,7 +48,8 @@ def generation(self): 3: BackendCapabilities(cuda_graphs=True, async_scheduling=True), 4: BackendCapabilities(packed_prefill=True, cuda_graphs=True, async_scheduling=True), } -_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "triton", "torch") +_FLASHINFER_CAPABILITIES = BackendCapabilities(cuda_graphs=True, async_scheduling=True) +_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "flashinfer", "triton", "torch") def backend_capabilities(implementation) -> BackendCapabilities: @@ -55,7 +57,7 @@ def backend_capabilities(implementation) -> BackendCapabilities: def validate_backend_name(backend: str) -> None: - if backend not in {"auto", "torch", "triton", *FLASH_BACKENDS}: + if backend not in {"auto", "torch", "triton", "flashinfer", *FLASH_BACKENDS}: raise ValueError("unknown attention backend") @@ -70,6 +72,9 @@ def _create_explicit(backend, device, dtype, head_dim, block_size): # Probe the actual module, including its dependency imports, before selection. importlib.import_module("vllm_rlt.kernels.triton_attention") return AttentionBackend(triton_paged_attention, _TRITON_CAPABILITIES, {"backend": backend}) + if backend == "flashinfer": + kernel = FlashInferPagedAttention(device, dtype, head_dim, block_size) + return AttentionBackend(kernel, _FLASHINFER_CAPABILITIES, dict(kernel.info)) if backend in FLASH_BACKENDS: kernel = FlashPagedAttention(device, dtype, head_dim, block_size, backend) return AttentionBackend(kernel, _FLASH_CAPABILITIES[kernel.generation], dict(kernel.info)) @@ -85,7 +90,7 @@ def create_backend( *, required_capabilities: BackendCapabilities = BackendCapabilities(), ) -> AttentionBackend: - """Explicit choices fail without fallback; auto tries FA4/3/2, Triton, then Torch. + """Explicit choices fail without fallback; auto tries FA4/3/2, FlashInfer, Triton, then Torch. Each candidate validates hardware/configuration and imports its implementation. Only compatibility and import failures permit auto to try the next candidate; @@ -118,7 +123,7 @@ def create_backend( f"flash_attn_{implementation.generation}" if candidate in FLASH_BACKENDS else candidate ) reason = ( - "first compatible candidate in FA4 > FA3 > FA2 > Triton > Torch priority" + "first compatible candidate in FA4 > FA3 > FA2 > FlashInfer > Triton > Torch priority" if backend == "auto" else f"explicitly requested {backend}" ) diff --git a/vllm_rlt/entrypoints/cli.py b/vllm_rlt/entrypoints/cli.py index b7c53c82..706baab6 100644 --- a/vllm_rlt/entrypoints/cli.py +++ b/vllm_rlt/entrypoints/cli.py @@ -70,6 +70,7 @@ def main(): "auto", "torch", "triton", + "flashinfer", "flash_attn", "flash_attn_2", "flash_attn_3", diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index 0563433c..3e5e45db 100644 --- a/vllm_rlt/entrypoints/serve.py +++ b/vllm_rlt/entrypoints/serve.py @@ -92,6 +92,7 @@ def main(): "auto", "torch", "triton", + "flashinfer", "flash_attn", "flash_attn_2", "flash_attn_3", diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py new file mode 100644 index 00000000..2b4cae71 --- /dev/null +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -0,0 +1,115 @@ +"""FlashInfer XQA paged decode kernels; no packed prefill in this backend. + +Decode uses independent single-query rows, exactly like the Triton path. +SM120 (RTX 50) is the validated target; other supported majors are accepted +but unvalidated. Requires a CUDA toolkit with nvcc >= 12.9 visible through +CUDA_HOME for the just-in-time compiled kernels, and that toolkit's lib +directory on LD_LIBRARY_PATH. +""" + +import importlib +import logging +from importlib.metadata import PackageNotFoundError, version +from types import SimpleNamespace + +import torch + +FLASHINFER_PAGE_SIZES = (16, 32, 64, 128) +FLASHINFER_WORKSPACE_BYTES = 128 * 1024 * 1024 + + +class FlashInferPagedAttention: + def __init__(self, device, dtype, head_dim, block_size): + if device.type != "cuda" or torch.version.hip: + raise ValueError("flashinfer currently requires an NVIDIA CUDA device") + # float16 kernels compute correctly, but flashinfer-python 0.7.0.post1 + # crashes the process (host SIGFPE) while building the f16 JIT module + # on first in-process use; reject instead of shipping that. + if dtype is torch.float16: + raise ValueError( + "the flashinfer backend is not validated with float16; use bfloat16" + ) + if dtype is not torch.bfloat16: + raise ValueError("flashinfer requires bfloat16") + # The XQA JIT module generator rejects anything else at first call; + # validate here so the failure is an explicit startup error instead. + if head_dim % 16 or not 16 <= head_dim <= 512: + raise ValueError( + "flashinfer requires head_dim divisible by 16 and in [16, 512] (XQA kernels)" + ) + # XQA kernels are compiled per page size and only these variants ship. + if block_size not in FLASHINFER_PAGE_SIZES: + raise ValueError( + "flashinfer requires --block-size one of " + f"{FLASHINFER_PAGE_SIZES} (XQA page-size variants)" + ) + major, minor = torch.cuda.get_device_capability(device) + if major not in (9, 10, 12): + raise ValueError(f"flashinfer is not supported on SM{major}{minor}") + try: + package_version = version("flashinfer-python") + self.kernel = getattr( + importlib.import_module("flashinfer.decode"), + "trtllm_batch_decode_with_kv_cache", + ) + except (ImportError, AttributeError, PackageNotFoundError) as error: + raise ImportError( + "install flashinfer with: pip install 'flashinfer-python>=0.7.0' " + "(a CUDA toolkit with nvcc >= 12.9 must be reachable via CUDA_HOME, " + "and its lib directory on LD_LIBRARY_PATH for the JIT modules). " + "No backend fallback was performed." + ) from error + if major != 12: + logging.getLogger(__name__).warning( + "flashinfer attention is validated on SM120 only; SM%d%d is unvalidated", + major, + minor, + ) + # Persistent, pre-zeroed scratch shared by every call. Allocated on the + # first execution rather than here so backend selection stays free of + # device allocations: engines always profile before CUDA-graph capture, + # so the workspace exists by the time any graph is recorded. + self.workspace = None + self.info = dict( + backend="flashinfer", + package="flashinfer-python", + version=package_version, + kernel="xqa", + page_size=block_size, + ) + # Mirrors the capability names of the attention contract so a later + # migration only touches registration, not this kernel adapter. + self.capabilities = SimpleNamespace( + packed_prefill=False, cuda_graphs=True, async_scheduling=True + ) + logging.getLogger(__name__).warning("Attention implementation: %s", self.info) + + def __call__(self, q, key_cache, value_cache, block_tables, context_lengths): + # An empty batch host-crashes (SIGFPE, not an exception) inside the + # FlashInfer dispatch; return the same empty shape the other backends do. + if q.shape[0] == 0: + return torch.empty_like(q) + if self.workspace is None: + self.workspace = torch.zeros( + FLASHINFER_WORKSPACE_BYTES, dtype=torch.uint8, device=q.device + ) + out = torch.empty_like(q) + self.kernel( + q, + (key_cache, value_cache), + self.workspace, + # Padding columns hold -1 (synchronous), 0 (async), or stale valid + # ids (graph replay beyond the current width). The kernel bounds + # reads by seq_lens, and clamped ids keep any full-width access on + # allocated memory regardless. + block_tables=block_tables.clamp_min(0), + seq_lens=context_lengths.to(torch.uint32), + max_seq_len=block_tables.shape[1] * key_cache.shape[1], + bmm1_scale=q.shape[-1] ** -0.5, + out=out, + q_len_per_req=1, + # The engine pool is [blocks, page, heads, dim]; the API default is + # HND and silently misreads NHD data. + kv_layout="NHD", + ) + return out From 0a560976247080eadda2c25abf64ca795c5315a1 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:35:16 +0800 Subject: [PATCH 2/9] bench: parameterize the GSM8K native attention backend The run subcommand accepts --attention-backend (torch/triton/flashinfer, default triton), records it in the run metadata, and passes it through Generator to the engine instead of the hardcoded Triton selection. --- benchmarks/gsm8k.py | 12 +++++++++++- benchmarks/gsm8k_backends.py | 6 ++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/benchmarks/gsm8k.py b/benchmarks/gsm8k.py index 862a6752..226ac1b2 100644 --- a/benchmarks/gsm8k.py +++ b/benchmarks/gsm8k.py @@ -439,6 +439,7 @@ def run(args): output.mkdir(parents=True, exist_ok=False) metadata = { "backend": args.backend, + "attention_backend": args.attention_backend, "protocol_sha256": file_digest(args.protocol), "source": source(), "cuda_visible_devices": os.environ["CUDA_VISIBLE_DEVICES"], @@ -456,7 +457,10 @@ def run(args): tokenizer = AutoTokenizer.from_pretrained(model, local_files_only=True) task = make_task(protocol["task_config"]) start = time.monotonic() - generator = Generator(args.backend, str(model), tokenizer, protocol["max_length"], exit_policy) + generator = Generator( + args.backend, str(model), tokenizer, protocol["max_length"], exit_policy, + attention_backend=args.attention_backend, + ) load_seconds = time.monotonic() - start rows = [] with (output / "samples.jsonl").open("x", buffering=1) as stream: @@ -619,6 +623,12 @@ def main(): p.add_argument("--backend", choices=["transformers", "native"], required=True) p.add_argument("--protocol", required=True) p.add_argument("--output", required=True) + p.add_argument( + "--attention-backend", + choices=["torch", "triton", "flashinfer"], + default="triton", + help="Native engine attention kernel; recorded in the run metadata", + ) p.add_argument("--exit-mode", choices=["ouro", "ouro_delayed"], default="ouro") p.add_argument( "--exit-threshold", diff --git a/benchmarks/gsm8k_backends.py b/benchmarks/gsm8k_backends.py index 4c038aa8..bf0fad81 100644 --- a/benchmarks/gsm8k_backends.py +++ b/benchmarks/gsm8k_backends.py @@ -80,7 +80,9 @@ def _after_model(self, module, inputs, output): class Generator: - def __init__(self, backend, model_path, tokenizer, max_length, exit_policy): + def __init__( + self, backend, model_path, tokenizer, max_length, exit_policy, attention_backend="triton" + ): self.backend, self.tokenizer, self.exit = backend, tokenizer, exit_policy # Full depth, taken from the protocol (the checkpoint's total_ut_steps). loops = exit_policy["max_loops"] @@ -113,7 +115,7 @@ def __init__(self, backend, model_path, tokenizer, max_length, exit_policy): model_path, device="cuda", dtype=torch.bfloat16, - attention_backend="triton", + attention_backend=attention_backend, # last_exited KV keeps one plane per loop. cache_config=CacheConfig(num_blocks=loops * ((max_length + 15) // 16)), scheduler_config=SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=128), From a224349c5ed1c5a32747874c42e91c6aabe6d039 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:35:16 +0800 Subject: [PATCH 3/9] docs: add FlashInfer backend guide with SM120 accuracy note Document installation and the two runtime requirements (CUDA_HOME with nvcc >= 12.9 for JIT kernels, the toolkit lib directory on LD_LIBRARY_PATH), scope and explicit rejections, backend selection guidance, and the GSM8K-87 greedy variation measured on RTX 5090. --- README.md | 6 +++--- docs/README.md | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2ff14ddb..be9e9f7b 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,9 @@ vLLM to be installed. See [Citation](#citation) for the paper's BibTeX entry. - **Depth-aware paged KV cache.** LAST-EXITED and SHARED layouts, automatic CUDA cache sizing, and optional prefix caching, incremental page allocation, priority scheduling, and preemption with CPU state snapshots. -- **Configurable GPU execution.** Triton and FlashAttention backends, asynchronous - scheduling, multiple CUDA streams, reusable buffers, and CUDA Graph capture - of decode recurrent cores. +- **Configurable GPU execution.** Triton, FlashAttention, and FlashInfer backends, + asynchronous scheduling, multiple CUDA streams, reusable buffers, and CUDA Graph + capture of decode recurrent cores. - **Offline and online inference.** A Python API, a command-line interface, and an OpenAI-compatible completions endpoint with streaming, greedy decoding, and seeded top-k/top-p sampling. diff --git a/docs/README.md b/docs/README.md index 3288f99e..9d0fb8ce 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ an environment to receiving the first generated response. The | [Runtime configuration](cdb_runtime.md) | Exit policies, KV layouts, execution options, and CUDA Graphs | | [Asynchronous scheduling](https://github.com/hsliuustc0106/vllm-rlt/pull/30) | CPU/GPU pipelining and single-stream or multi-stream execution | | [FlashAttention](https://github.com/hsliuustc0106/vllm-rlt/pull/30) | FA2/FA3/FA4 installation, hardware selection, and constraints | +| [FlashInfer](flashinfer.md) | XQA decode kernels for SM120: installation, environment, and scope | | [Cache and scheduling features](https://github.com/hsliuustc0106/vllm-rlt/pull/31) | Prefix reuse, incremental KV, priorities, and preemption | | [Prefill/decode disaggregation](https://github.com/hsliuustc0106/vllm-rlt/pull/31) | Single-host GPU worker pools and NIXL transfer | | [HTTP serving](serving.md) | Completions API, streaming, and service lifecycle | @@ -26,7 +27,8 @@ an environment to receiving the first generated response. The Current model support is limited to Ouro-1.4B. CPU execution provides a Torch reference backend. FlashAttention hardware validation is currently documented -for FA4 on B300; FA2/FA3 require validation on their target devices. Disaggregated +for FA4 on B300; FA2/FA3 require validation on their target devices. FlashInfer +decode is validated on RTX 5090 (SM120). Disaggregated serving currently targets multiple GPUs on a single host. `ouro_delayed` reuses the trained Ouro gate with a one-loop delay; it changes From 1a24e527005a5ace2de33b7c1e7f9e17bf9bc566 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:34:38 +0800 Subject: [PATCH 4/9] docs: record GSM8K attention-backend runs in the accuracy guide Document the --attention-backend flag on the native run command, the RTX 5090 Triton/FlashInfer scores on the frozen 87-question case, and the expected single-pass greedy variation between BF16 kernels. --- docs/accuracy.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/accuracy.md b/docs/accuracy.md index f0eccac3..60a2ff29 100644 --- a/docs/accuracy.md +++ b/docs/accuracy.md @@ -164,6 +164,25 @@ counts as `identical_context` when the two runs chose different depths for a pos whose preceding tokens were still identical. These fields are diagnostic; the accuracy gate does not use them. +## Attention-backend runs + +`run --backend native` selects the attention kernel with `--attention-backend` +(`triton` by default, recorded in the run metadata): + +```bash +python -m benchmarks.gsm8k run --backend native --attention-backend flashinfer \ + --protocol /path/to/gsm8k-87-protocol.json --output /path/to/native-flashinfer +``` + +On RTX 5090 (SM120) the frozen default case scored **Triton 61/87 and FlashInfer +58/87** against the stored HF baseline of 59/87: 64 of the 87 generations were +token-identical between the kernels, the divergent ones flipped near-tied greedy +choices at scattered positions, and exit depths never differed. This is the +expected single-pass greedy variation between BF16 kernels with different +accumulation orders — see the [FlashInfer accuracy +note](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass) before treating a +one-question delta from a backend swap as a regression. + Dataset: [GSM8K](https://huggingface.co/datasets/openai/gsm8k). The [Ouro evaluation settings](https://arxiv.org/html/2510.25741v5#A3.T16) do not pin the exact harness revision, demonstrations or token limits, so the settings From 549a709ba0b7f875c96bacda0ad510d917c7c0e2 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:05:48 +0800 Subject: [PATCH 5/9] fix: gate automatic FlashInfer selection to SM120 and dedupe capabilities Address review feedback on #112: - auto only considers the flashinfer candidate on SM 12.x, so SM90/SM100 keep their pre-FlashInfer fallback when every FlashAttention generation is unavailable; explicit --attention-backend flashinfer still opts in on other accepted architectures with the unvalidated-architecture warning - the capability declaration now lives only in the attention registration layer; the kernel adapter no longer carries a duplicate - regression rows for the SM90/SM100 fallbacks, an explicit-opt-in test, and the CUDA Graph matrix (replay, eager fallback, abort/cancellation, request reuse) now cover FlashInfer --- tests/test_backend_selection.py | 21 +++++++++++++++++++++ tests/test_cuda_graph.py | 7 ++++--- tests/test_flashinfer_attention.py | 13 ++++++++----- vllm_rlt/attention/backend.py | 22 +++++++++++++++++++++- vllm_rlt/kernels/flashinfer_attention.py | 6 ------ 5 files changed, 54 insertions(+), 15 deletions(-) diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index 5824d950..859b3053 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -87,6 +87,15 @@ def test_cpu_auto_reports_torch_and_runs_reference_attention(caplog): "flash_attn_2", ), ((10, 0), torch.bfloat16, 128, 16, (), "flash_attn_4"), + ( + (9, 0), + torch.bfloat16, + 128, + 16, + ("flash_attn.cute", "flash_attn_3.flash_attn_interface"), + "triton", + ), + ((10, 0), torch.bfloat16, 128, 16, ("flash_attn.cute",), "triton"), ((12, 0), torch.bfloat16, 128, 16, (), "flashinfer"), ((12, 0), torch.bfloat16, 128, 16, ("flashinfer",), "triton"), ((7, 5), torch.float16, 128, 256, (), "torch"), @@ -104,6 +113,18 @@ def test_auto_selection_constraints( assert backend_capabilities(selected).packed_prefill +def test_explicit_flashinfer_opt_in_outside_sm120(packages, monkeypatch, caplog): + import logging + + caplog.set_level(logging.WARNING, logger="vllm_rlt.kernels.flashinfer_attention") + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (9, 0)) + selected = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) + assert selected.info["selected_backend"] == "flashinfer" + assert selected.capabilities.cuda_graphs and selected.capabilities.async_scheduling + assert not selected.capabilities.packed_prefill + assert "unvalidated" in caplog.text + + def test_rocm_auto_uses_triton(packages, monkeypatch): monkeypatch.setattr(torch.version, "hip", "7.0") monkeypatch.setattr( diff --git a/tests/test_cuda_graph.py b/tests/test_cuda_graph.py index fb901c42..85f689b9 100644 --- a/tests/test_cuda_graph.py +++ b/tests/test_cuda_graph.py @@ -21,7 +21,7 @@ def test_cuda_graph_validation(): @pytest.mark.gpu -@pytest.mark.parametrize("backend", ["triton", "flash_attn"]) +@pytest.mark.parametrize("backend", ["triton", "flash_attn", "flashinfer"]) @pytest.mark.parametrize("mode", ["sync", "async", "multi"]) @pytest.mark.parametrize("layout", ["last_exited", "shared"]) @pytest.mark.parametrize("static", [False, True]) @@ -71,7 +71,8 @@ def test_graph_replay_matches_eager_and_reuses_requests(backend, mode, layout, s @pytest.mark.gpu -def test_graph_cache_limit_fallback_and_abort(): +@pytest.mark.parametrize("backend", ["triton", "flashinfer"]) +def test_graph_cache_limit_fallback_and_abort(backend): torch.manual_seed(19) model = OuroForCausalLM(tiny_ouro_config(head_dim=64)).to("cuda", torch.bfloat16) engine = LLMEngine( @@ -87,7 +88,7 @@ def test_graph_cache_limit_fallback_and_abort(): async_scheduling=True, ), exit_config=ExitConfig("ouro_delayed"), - attention_backend="triton", + attention_backend=backend, ) for count in [1, 2, 3]: for i in range(count): diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py index af8300b9..920c40ec 100644 --- a/tests/test_flashinfer_attention.py +++ b/tests/test_flashinfer_attention.py @@ -5,6 +5,7 @@ from tests.helpers import tiny_ouro_config from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig +from vllm_rlt.attention import BackendCapabilities, create_backend from vllm_rlt.engine.llm_engine import LLMEngine from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention from vllm_rlt.kernels.paged_attention import torch_paged_attention @@ -72,13 +73,15 @@ def test_backend_contract_anchors(): assert attention.info["package"] == "flashinfer-python" assert attention.info["page_size"] == 16 assert attention.info["kernel"] == "xqa" - assert attention.capabilities.packed_prefill is False - assert attention.capabilities.cuda_graphs is True - assert attention.capabilities.async_scheduling is True - # Absence is the contract: the FA4 packed-prefill gates in the engine and - # model runner key off a missing generation attribute staying missing. + # Absence is the contract: capability declarations live only in the + # attention registration layer, and the FA4 packed-prefill gates key off + # a missing generation attribute staying missing. + assert not hasattr(attention, "capabilities") assert not hasattr(attention, "generation") assert not hasattr(attention, "prefill") + wrapper = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) + assert wrapper.info["selected_backend"] == "flashinfer" + assert wrapper.capabilities == BackendCapabilities(cuda_graphs=True, async_scheduling=True) @pytest.mark.gpu diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index 2e2005a9..a0bdb664 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -56,6 +56,18 @@ def backend_capabilities(implementation) -> BackendCapabilities: return implementation.capabilities +def _auto_flashinfer_supported(device) -> bool: + """Gate automatic FlashInfer selection to the validated SM120 target. + + Other architectures the kernel accepts remain reachable through explicit + `--attention-backend flashinfer` opt-in; auto keeps its pre-FlashInfer + fallback behavior everywhere else. + """ + if device.type != "cuda" or torch.version.hip: + return False + return torch.cuda.get_device_capability(device)[0] == 12 + + def validate_backend_name(backend: str) -> None: if backend not in {"auto", "torch", "triton", "flashinfer", *FLASH_BACKENDS}: raise ValueError("unknown attention backend") @@ -90,7 +102,8 @@ def create_backend( *, required_capabilities: BackendCapabilities = BackendCapabilities(), ) -> AttentionBackend: - """Explicit choices fail without fallback; auto tries FA4/3/2, FlashInfer, Triton, then Torch. + """Explicit choices fail without fallback; auto tries FA4/3/2, FlashInfer + (SM120 only), Triton, then Torch. Each candidate validates hardware/configuration and imports its implementation. Only compatibility and import failures permit auto to try the next candidate; @@ -104,6 +117,13 @@ def create_backend( candidates = ("torch",) skipped.append(f"{device.type.upper()} uses Torch reference attention") for candidate in candidates: + if ( + backend == "auto" + and candidate == "flashinfer" + and not _auto_flashinfer_supported(device) + ): + skipped.append("flashinfer: automatic selection is validated on SM120 only") + continue try: implementation = _create_explicit(candidate, device, dtype, head_dim, block_size) missing = [ diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py index 2b4cae71..73a0a5a4 100644 --- a/vllm_rlt/kernels/flashinfer_attention.py +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -10,7 +10,6 @@ import importlib import logging from importlib.metadata import PackageNotFoundError, version -from types import SimpleNamespace import torch @@ -77,11 +76,6 @@ def __init__(self, device, dtype, head_dim, block_size): kernel="xqa", page_size=block_size, ) - # Mirrors the capability names of the attention contract so a later - # migration only touches registration, not this kernel adapter. - self.capabilities = SimpleNamespace( - packed_prefill=False, cuda_graphs=True, async_scheduling=True - ) logging.getLogger(__name__).warning("Attention implementation: %s", self.info) def __call__(self, q, key_cache, value_cache, block_tables, context_lengths): From 3dffae1110c1ce05a1702591128385553d6ab381 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:40:36 +0800 Subject: [PATCH 6/9] Integrate FlashInfer XQA paged attention on SM120 --- README.md | 2 + benchmarks/gsm8k.py | 12 +- benchmarks/gsm8k_backends.py | 6 +- docs/README.md | 1 + docs/accuracy.md | 19 ++ docs/flashinfer.md | 96 +++++++++ pyproject.toml | 1 + tests/test_backend_selection.py | 45 +++- tests/test_cuda_graph.py | 7 +- tests/test_flashinfer_attention.py | 261 +++++++++++++++++++++++ vllm_rlt/attention/backend.py | 33 ++- vllm_rlt/entrypoints/cli.py | 1 + vllm_rlt/entrypoints/serve.py | 1 + vllm_rlt/kernels/flashinfer_attention.py | 110 ++++++++++ 14 files changed, 579 insertions(+), 16 deletions(-) create mode 100644 docs/flashinfer.md create mode 100644 tests/test_flashinfer_attention.py create mode 100644 vllm_rlt/kernels/flashinfer_attention.py diff --git a/README.md b/README.md index 17502f55..59fa2a63 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,8 @@ including Dory sliding attention, uses `flash-attn-4==4.0.0b39` and calibrates a fixed scale at startup. See the [hardware and calibration requirements](docs/runtime.md#experimental-fa4-static-scale-adapter). +For the FlashInfer XQA backend, see the [FlashInfer guide](docs/flashinfer.md). + ## Model Support diff --git a/benchmarks/gsm8k.py b/benchmarks/gsm8k.py index d1ecc7f0..acc21a73 100644 --- a/benchmarks/gsm8k.py +++ b/benchmarks/gsm8k.py @@ -591,6 +591,7 @@ def run(args): output.mkdir(parents=True, exist_ok=False) metadata = { "backend": args.backend, + "attention_backend": args.attention_backend, "protocol_sha256": file_digest(args.protocol), "source": source(), "cuda_visible_devices": os.environ["CUDA_VISIBLE_DEVICES"], @@ -609,7 +610,10 @@ def run(args): close_id = thinking_close_id(tokenizer) if scorer == SCORER_THINKING else None task = make_task(protocol["task_config"]) start = time.monotonic() - generator = Generator(args.backend, str(model), tokenizer, protocol["max_length"], exit_policy) + generator = Generator( + args.backend, str(model), tokenizer, protocol["max_length"], exit_policy, + attention_backend=args.attention_backend, + ) load_seconds = time.monotonic() - start rows = [] try: @@ -787,6 +791,12 @@ def main(): p.add_argument("--backend", choices=["transformers", "native"], required=True) p.add_argument("--protocol", required=True) p.add_argument("--output", required=True) + p.add_argument( + "--attention-backend", + choices=["torch", "triton", "flashinfer"], + default="triton", + help="Native engine attention kernel; recorded in the run metadata", + ) p.add_argument("--exit-mode", choices=["ouro", "ouro_delayed"], default="ouro") p.add_argument( "--exit-threshold", diff --git a/benchmarks/gsm8k_backends.py b/benchmarks/gsm8k_backends.py index 15d57165..2d39b9e6 100644 --- a/benchmarks/gsm8k_backends.py +++ b/benchmarks/gsm8k_backends.py @@ -101,7 +101,9 @@ def _after_model(self, module, inputs, output): class Generator: - def __init__(self, backend, model_path, tokenizer, max_length, exit_policy): + def __init__( + self, backend, model_path, tokenizer, max_length, exit_policy, attention_backend="triton" + ): self.backend, self.tokenizer, self.exit = backend, tokenizer, exit_policy # Full depth, taken from the protocol (the checkpoint's total_ut_steps). loops = exit_policy["max_loops"] @@ -138,7 +140,7 @@ def __init__(self, backend, model_path, tokenizer, max_length, exit_policy): check_depth(self.model.config, loops) self.engine = StageEngine( self.model, - attention_backend="triton", + attention_backend=attention_backend, # last_exited KV keeps one plane per loop. cache_config=CacheConfig(num_blocks=loops * ((max_length + 15) // 16)), scheduler_config=SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=128), diff --git a/docs/README.md b/docs/README.md index 47adbd1d..05c886f5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ an environment to receiving the first generated response. The | [Self-speculation](async-speculative.md) | Cross-round asynchronous block execution, token pipelines, and acceptance/rejection timelines | | [Asynchronous scheduling](https://github.com/InferMatrixLab/vllm-rlt/pull/30) | CPU/GPU pipelining and single-stream or multi-stream execution | | [FlashAttention](https://github.com/InferMatrixLab/vllm-rlt/pull/30) | FA2/FA3/FA4 installation, hardware selection, and constraints | +| [FlashInfer](flashinfer.md) | XQA decode for SM120: installation, configuration and limitations | | [Cache and scheduling features](https://github.com/InferMatrixLab/vllm-rlt/pull/31) | Prefix reuse, incremental KV, priorities, and preemption | | [Prefill/decode disaggregation](https://github.com/InferMatrixLab/vllm-rlt/pull/31) | Single-host GPU worker pools and NIXL transfer | | [HTTP serving](serving.md) | Completions API, streaming, and service lifecycle | diff --git a/docs/accuracy.md b/docs/accuracy.md index fd1f9463..ca375a02 100644 --- a/docs/accuracy.md +++ b/docs/accuracy.md @@ -193,6 +193,25 @@ counts as `identical_context` when the two runs chose different depths for a pos whose preceding tokens were still identical. These fields are diagnostic; the accuracy gate does not use them. +## Attention-backend runs + +`run --backend native` selects the attention kernel with `--attention-backend` +(`triton` by default, recorded in the run metadata): + +```bash +python -m benchmarks.gsm8k run --backend native --attention-backend flashinfer \ + --protocol /path/to/gsm8k-87-protocol.json --output /path/to/native-flashinfer +``` + +On RTX 5090 (SM120) the frozen default case scored **Triton 61/87 and FlashInfer +58/87** against the stored HF baseline of 59/87: 64 of the 87 generations were +token-identical between the kernels, the divergent ones flipped near-tied greedy +choices at scattered positions, and exit depths never differed. This is the +expected single-pass greedy variation between BF16 kernels with different +accumulation orders — see the [FlashInfer accuracy +note](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass) before treating a +one-question delta from a backend swap as a regression. + Dataset: [GSM8K](https://huggingface.co/datasets/openai/gsm8k). The [Ouro evaluation settings](https://arxiv.org/html/2510.25741v5#A3.T16) do not pin the exact harness revision, demonstrations or token limits, so the settings diff --git a/docs/flashinfer.md b/docs/flashinfer.md new file mode 100644 index 00000000..427f6378 --- /dev/null +++ b/docs/flashinfer.md @@ -0,0 +1,96 @@ +# FlashInfer Attention Backend + +The `flashinfer` backend runs paged decode attention through FlashInfer's XQA +kernels (`flashinfer-python >= 0.7.0`, `trtllm_batch_decode_with_kv_cache`, +`backend="xqa"`). It is the validated attention path for NVIDIA consumer +Blackwell (SM120, e.g. RTX 5090), where the pinned FlashAttention releases +reject paged KV. + +## Scope + +- Decode and per-token prefill, identical semantics to the Triton path, + including CUDA Graph capture and asynchronous scheduling. +- No packed prefill: the engine keeps the FA4-only packed path closed, so + prefill runs per token exactly as with Triton. +- No prefill/decode disaggregation; PD entrypoints reject the backend + explicitly. +- `bfloat16` only. `float16` is rejected at startup: the kernels compute + correctly, but flashinfer-python 0.7.0.post1 crashes the process (host + SIGFPE) while building the f16 JIT module on first in-process use. +- `--block-size` must be one of `16, 32, 64, 128` (compiled XQA page-size + variants) and `head_dim` must be divisible by 16 within `[16, 512]`. + +## Installation and runtime requirements + +```bash +pip install -e ".[flashinfer]" +``` + +The XQA kernels are compiled just in time on first use, which imposes two +environment requirements beyond the package install: + +1. **A CUDA toolkit with `nvcc >= 12.9` reachable via `CUDA_HOME`.** SM120 + kernels are built for the `compute_120f` architecture family, which needs + CUDA 12.9 or newer. Without `nvcc`, startup falls back to comparing against + the CUDA version PyTorch was built with, and SM 12.x devices are rejected + with `SM 12.x requires CUDA >= 12.9`. +2. **That toolkit's `lib` directory on `LD_LIBRARY_PATH`.** The compiled + modules link `libcudart.so.13`; pip-installed toolkits keep it outside the + default loader path. With the pip toolkit layout + (`nvidia-cuda-nvcc`/`nvidia-cuda-runtime`/`nvidia-cuda-cccl`/...), the + unified tree lives under `site-packages/nvidia/cu13` and may need + `lib64/libcudart.so` and `lib64/stubs/libcuda.so` developer symlinks, which + the wheels do not ship. + +The first call on a machine compiles for a few seconds and caches under +`~/.cache/flashinfer///`; later calls, including CUDA +Graph capture warmups, reuse the cache. + +## Running + +```bash +vllm-rlt --model --revision \ + --device cuda --dtype bfloat16 --attention-backend flashinfer +``` + +The adapter holds one 128 MiB zero-initialized workspace for the kernel's +scratch and softmax statistics; it is allocated once at startup and reused, so +graph capture performs no new allocations. Padded block-table columns are +clamped non-negative before the call: the engine produces `-1` padding on the +synchronous path, `0` on the asynchronous path, and stale-but-valid ids in +CUDA Graph replay beyond the current width. The kernel bounds reads by +`seq_lens`, so all three padding states stay invisible. + +## Choosing between Triton and FlashInfer + +SM120 is the only validated target for this backend; on it, FlashInfer decodes +noticeably faster at low concurrency (single-request decode measured ~2x +against the Triton kernel at 256-token contexts) because the XQA kernel +parallelizes a single query row across KV chunks, while the Triton kernel +spawns one program per (row, head). At high concurrency with long contexts the +two are comparable; choose Triton when its determinism properties matter more +and FlashInfer for single-user or low-batch latency. SM9/SM10 devices are +accepted but unvalidated — prefer FlashAttention there until validated +configurations are recorded. + +## Validation status + +Validated on RTX 5090 (SM120, 32 GB) with Ouro-1.4B BF16, `block_size=16`, +fixed four-loop decode: oracle parity against the reference paged attention, +token/exit-depth equality against the Triton backend across synchronous, +asynchronous, and multi-stream execution with static buffers and graph replay, +and end-to-end greedy generation. + +## Accuracy note (GSM8K-87, single greedy pass) + +On the frozen GSM8K-87 protocol (HF baseline 59/87), a fixed four-loop greedy +pass scores 58/87 with FlashInfer versus 61/87 with Triton. 64 of 87 +generations are token-identical between the two backends; the remaining 23 +diverge at scattered positions with unchanged exit depths, and the net +correct-answer flips are 3 against, 0 for. Kernel-level comparison against a +float32 oracle at 352-1024 token contexts shows the Triton kernel is +near-exact (max deviation up to 5e-4) while XQA's split reductions deviate by +up to 4e-3 — within normal BF16 kernel variation, but enough to flip +near-tied greedy argmax decisions during long chain-of-thought decoding. +Triton remains the default backend; treat this note as the expected greedy +variation when opting into FlashInfer on SM120. diff --git a/pyproject.toml b/pyproject.toml index fa46c0c8..1a8d6d4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ pd = ["nixl==1.4.1"] serve = [] flash-attn = ["flash-attn>=2.8.3"] flash-attn4 = ["flash-attn-4==4.0.0b39"] +flashinfer = ["flashinfer-python>=0.7.0"] triton = [] dev = ["pytest>=8", "ruff>=0.9"] diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index cc90cf90..33ebb0d6 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -15,7 +15,7 @@ @pytest.fixture def packages(monkeypatch): - from vllm_rlt.kernels import flash_attention + from vllm_rlt.kernels import flash_attention, flashinfer_attention installed = { "flash_attn", @@ -23,6 +23,7 @@ def packages(monkeypatch): "flash_attn.cute", "TensorwiseScales", "triton", + "flashinfer", } original_import = flash_attention.importlib.import_module @@ -41,12 +42,19 @@ def import_module(name): if name == "flash_attn.cute" and "TensorwiseScales" in installed: result.TensorwiseScales = SimpleNamespace return result + if name == "flashinfer.decode": + if "flashinfer" not in installed: + raise ImportError("flashinfer is not installed") + return SimpleNamespace( + trtllm_batch_decode_with_kv_cache=lambda *args, **kwargs: None + ) return original_import(name) monkeypatch.setattr(flash_attention.importlib, "import_module", import_module) monkeypatch.setattr( flash_attention, "version", lambda name: "4.0.0b39" if name == "flash-attn-4" else "test" ) + monkeypatch.setattr(flashinfer_attention, "version", lambda name: "test") monkeypatch.setattr(torch.version, "hip", None) return installed @@ -173,7 +181,17 @@ def test_dory_requirements_select_native_fa4_and_reject_old_hd256(packages, monk "flash_attn_2", ), ((10, 0), torch.bfloat16, 128, 16, (), "flash_attn_4"), - ((12, 0), torch.bfloat16, 128, 16, (), "triton"), + ( + (9, 0), + torch.bfloat16, + 128, + 16, + ("flash_attn.cute", "flash_attn_3.flash_attn_interface"), + "triton", + ), + ((10, 0), torch.bfloat16, 128, 16, ("flash_attn.cute",), "triton"), + ((12, 0), torch.bfloat16, 128, 16, (), "flashinfer"), + ((12, 0), torch.bfloat16, 128, 16, ("flashinfer",), "triton"), ((7, 5), torch.float16, 128, 256, (), "torch"), ], ) @@ -189,6 +207,18 @@ def test_auto_selection_constraints( assert backend_capabilities(selected).packed_prefill +def test_explicit_flashinfer_opt_in_outside_sm120(packages, monkeypatch, caplog): + import logging + + caplog.set_level(logging.WARNING, logger="vllm_rlt.kernels.flashinfer_attention") + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (9, 0)) + selected = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) + assert selected.info["selected_backend"] == "flashinfer" + assert selected.capabilities.cuda_graphs and selected.capabilities.async_scheduling + assert not selected.capabilities.packed_prefill + assert "unvalidated" in caplog.text + + def test_rocm_auto_uses_triton(packages, monkeypatch): monkeypatch.setattr(torch.version, "hip", "7.0") monkeypatch.setattr( @@ -208,12 +238,15 @@ def test_auto_reports_missing_packages_and_configuration(packages, monkeypatch): assert "multiple of 256" in reason and "triton" in reason -@pytest.mark.parametrize("backend", ["flash_attn_2", "triton"]) -def test_explicit_missing_package_never_falls_back(packages, monkeypatch, backend): - monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (8, 9)) +@pytest.mark.parametrize( + "backend,sm,block_size", + [("flash_attn_2", (8, 9), 256), ("triton", (8, 9), 256), ("flashinfer", (12, 0), 16)], +) +def test_explicit_missing_package_never_falls_back(packages, monkeypatch, backend, sm, block_size): + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: sm) packages.clear() with pytest.raises(ImportError): - create_backend(backend, torch.device("cuda"), torch.bfloat16, 128, 256) + create_backend(backend, torch.device("cuda"), torch.bfloat16, 128, block_size) def test_explicit_flash_incompatibility_is_not_overridden(packages, monkeypatch): diff --git a/tests/test_cuda_graph.py b/tests/test_cuda_graph.py index a0f08c51..3c6e0599 100644 --- a/tests/test_cuda_graph.py +++ b/tests/test_cuda_graph.py @@ -23,7 +23,7 @@ def test_cuda_graph_validation(): @pytest.mark.gpu -@pytest.mark.parametrize("backend", ["triton", "flash_attn"]) +@pytest.mark.parametrize("backend", ["triton", "flash_attn", "flashinfer"]) @pytest.mark.parametrize("mode", ["sync", "async", "multi"]) @pytest.mark.parametrize("layout", ["last_exited", "shared"]) @pytest.mark.parametrize("static", [False, True]) @@ -73,7 +73,8 @@ def test_graph_replay_matches_eager_and_reuses_requests(backend, mode, layout, s @pytest.mark.gpu -def test_graph_cache_limit_fallback_and_abort(): +@pytest.mark.parametrize("backend", ["triton", "flashinfer"]) +def test_graph_cache_limit_fallback_and_abort(backend): torch.manual_seed(19) model = OuroForCausalLM(tiny_ouro_config(head_dim=64)).to("cuda", torch.bfloat16) engine = LLMEngine( @@ -89,7 +90,7 @@ def test_graph_cache_limit_fallback_and_abort(): async_scheduling=True, ), exit_config=ExitConfig("ouro_delayed"), - attention_backend="triton", + attention_backend=backend, ) for count in [1, 2, 3]: for i in range(count): diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py new file mode 100644 index 00000000..03eddb80 --- /dev/null +++ b/tests/test_flashinfer_attention.py @@ -0,0 +1,261 @@ +"""FlashInfer paged attention: gates, padding states, graphs and mixed depths.""" + +import pytest +import torch + +from tests.helpers import tiny_ouro_config +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig +from vllm_rlt.attention import BackendCapabilities, create_backend +from vllm_rlt.engine.llm_engine import LLMEngine +from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention +from vllm_rlt.kernels.paged_attention import torch_paged_attention +from vllm_rlt.models import OuroForCausalLM + + +def _cuda_like(monkeypatch, sm): + monkeypatch.setattr(torch.version, "hip", None) + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: sm) + + +def test_unsupported_architecture_rejected_before_import(monkeypatch): + from vllm_rlt.kernels import flashinfer_attention + + _cuda_like(monkeypatch, (7, 5)) + + def unexpected_import(name): + pytest.fail(f"unsupported architecture reached dependency import: {name}") + + monkeypatch.setattr(flashinfer_attention.importlib, "import_module", unexpected_import) + with pytest.raises(ValueError, match="not supported on SM75"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + + +@pytest.mark.parametrize( + "dtype", [torch.float16, torch.float32, torch.complex64], ids=["fp16", "fp32", "complex"] +) +def test_unvalidated_dtypes_rejected(monkeypatch, dtype): + _cuda_like(monkeypatch, (12, 0)) + with pytest.raises(ValueError): + FlashInferPagedAttention(torch.device("cuda"), dtype, 128, 16) + + +def test_geometry_and_page_size_rejections(monkeypatch): + _cuda_like(monkeypatch, (12, 0)) + with pytest.raises(ValueError, match="divisible by 16"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 100, 16) + with pytest.raises(ValueError, match="divisible by 16"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 8, 16) + with pytest.raises(ValueError, match="page-size variants"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 17) + with pytest.raises(ValueError, match="NVIDIA"): + FlashInferPagedAttention(torch.device("cpu"), torch.bfloat16, 128, 16) + + +def test_missing_package_raises_import_error_without_fallback(monkeypatch): + from importlib.metadata import PackageNotFoundError + + from vllm_rlt.kernels import flashinfer_attention + + _cuda_like(monkeypatch, (12, 0)) + + def missing(name): + raise PackageNotFoundError(name) + + monkeypatch.setattr(flashinfer_attention, "version", missing) + with pytest.raises(ImportError, match="install flashinfer"): + FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + + +def test_kernel_call_explicitly_selects_xqa(monkeypatch): + from types import SimpleNamespace + from unittest.mock import Mock + + output, workspace, uint32 = object(), object(), object() + empty_like = Mock(return_value=output) + fake_torch = SimpleNamespace(empty_like=empty_like, uint32=uint32) + monkeypatch.setitem(FlashInferPagedAttention.__call__.__globals__, "torch", fake_torch) + attention = FlashInferPagedAttention.__new__(FlashInferPagedAttention) + attention.workspace = workspace + attention.kernel = Mock() + q = SimpleNamespace(shape=(2, 4, 64)) + keys = SimpleNamespace(shape=(8, 16, 2, 64)) + values = SimpleNamespace(shape=(8, 16, 2, 64)) + tables = Mock(shape=(2, 3)) + lengths = Mock() + + for _ in range(2): + assert attention(q, keys, values, tables, lengths) is output + attention.kernel.assert_called_with( + q, + (keys, values), + workspace, + block_tables=tables.clamp_min.return_value, + seq_lens=lengths.to.return_value, + max_seq_len=48, + bmm1_scale=0.125, + out=output, + q_len_per_req=1, + kv_layout="NHD", + backend="xqa", + ) + assert attention.kernel.call_count == 2 + assert attention.workspace is workspace + tables.clamp_min.assert_called_with(0) + lengths.to.assert_called_with(uint32) + + attention.kernel.reset_mock() + assert attention(SimpleNamespace(shape=(0, 4, 64)), keys, values, tables, lengths) is output + attention.kernel.assert_not_called() + + +@pytest.mark.gpu +def test_backend_contract_anchors(): + attention = FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) + assert attention.info["backend"] == "flashinfer" + assert attention.info["package"] == "flashinfer-python" + assert attention.info["page_size"] == 16 + assert attention.info["kernel"] == "xqa" + # Absence is the contract: capability declarations live only in the + # attention registration layer, and the FA4 packed-prefill gates key off + # a missing generation attribute staying missing. + assert not hasattr(attention, "capabilities") + assert not hasattr(attention, "generation") + assert not hasattr(attention, "prefill") + wrapper = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) + assert wrapper.info["selected_backend"] == "flashinfer" + assert wrapper.capabilities == BackendCapabilities(cuda_graphs=True, async_scheduling=True) + + +@pytest.mark.gpu +@pytest.mark.parametrize("heads", [2, 4]) +def test_ragged_strided_paged_attention_with_zero_length_row(heads): + torch.manual_seed(9) + # Layer slicing leaves a non-contiguous block stride, as in the real cache. + keys = torch.randn(12, 3, 16, 2, 128, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(12, 3, 16, 2, 128, device="cuda", dtype=torch.bfloat16)[:, 1] + q = torch.randn(4, heads, 128, device="cuda", dtype=torch.bfloat16) + tables = torch.tensor( + [[7, 2, 9], [3, 0, 0], [1, 8, 6], [0, 0, 0]], device="cuda", dtype=torch.int32 + ) + lengths = torch.tensor([35, 1, 47, 0], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 128, 16) + expected = torch_paged_attention(q, keys, values, tables, lengths) + actual = attention(q, keys, values, tables, lengths) + torch.testing.assert_close(actual, expected, atol=0.015, rtol=0.02) + assert torch.isfinite(actual).all() + # Zero-length rows are async padding rows; they must read as exact zeros, + # not small garbage, so downstream masking stays optional. + assert torch.count_nonzero(actual[-1]) == 0 + + +@pytest.mark.gpu +def test_padding_states_are_invisible(): + torch.manual_seed(11) + keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + q = torch.randn(3, 2, 64, device="cuda", dtype=torch.bfloat16) + lengths = torch.tensor([16, 31, 20], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 64, 16) + outputs = [] + for fill in (-1, 0, 19): # sync pad, async pad, stale-but-valid replay id + tables = torch.full((3, 4), fill, device="cuda", dtype=torch.int32) + for row in range(3): + tables[row, :2] = torch.arange(row * 2, row * 2 + 2, device="cuda") + outputs.append(attention(q, keys, values, tables, lengths)) + assert torch.equal(outputs[0], outputs[1]) + assert torch.equal(outputs[0], outputs[2]) + + +@pytest.mark.gpu +def test_flashinfer_decode_same_queries_match_across_batch_sizes(): + generator = torch.Generator(device="cuda").manual_seed(1234) + dtype = torch.bfloat16 + # Ouro geometry and long enough prefixes to exercise any KV split selection. + keys = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] + values = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] + q = torch.randn(4, 16, 128, generator=generator, device="cuda", dtype=dtype) + tables = torch.arange(260, device="cuda", dtype=torch.int32).view(4, 65) + lengths = torch.tensor([1025, 1029, 1025, 1031], device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, dtype, 128, 16) + together = attention(q, keys, values, tables, lengths) + for rows in ([2, 3], [3, 0], [1]): + separate = attention(q[rows], keys, values, tables[rows], lengths[rows]) + torch.testing.assert_close(separate, together[rows], rtol=0, atol=0) + + +@pytest.mark.gpu +def test_graph_replay_updates_buffers(): + torch.manual_seed(5) + keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] + rows, width = 4, 4 + q = torch.randn(rows, 2, 64, device="cuda", dtype=torch.bfloat16) + static_tables = torch.zeros(rows, width, device="cuda", dtype=torch.int32) + static_lengths = torch.full((rows,), 16, device="cuda", dtype=torch.int32) + attention = FlashInferPagedAttention(q.device, torch.bfloat16, 64, 16) + # Warm JIT modules and workspace outside the capture region. + attention(q, keys, values, static_tables, static_lengths) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = attention(q, keys, values, static_tables, static_lengths) + generator = torch.Generator().manual_seed(21) + for trial in range(3): + for row in range(rows): + start = (row * 3 + trial * 5) % 16 + static_tables[row] = torch.arange(start, start + width, dtype=torch.int32) + static_lengths.copy_( + torch.randint(1, width * 16, (rows,), generator=generator, dtype=torch.int32) + ) + graph.replay() + expected = torch_paged_attention(q, keys, values, static_tables, static_lengths) + torch.testing.assert_close(out, expected, atol=0.015, rtol=0.02) + + +@pytest.mark.gpu +@pytest.mark.parametrize("layout", ["last_exited", "shared"]) +@pytest.mark.parametrize("static", [False, True]) +def test_flashinfer_sync_async_mixed_depths(layout, static): + torch.manual_seed(123) + config = tiny_ouro_config(head_dim=64) + model = OuroForCausalLM(config).to(device="cuda", dtype=torch.bfloat16) + traces = {str(i): [4, 2 + i % 3, 4, 2, 3, 4] for i in range(3)} + outputs = [] + for backend, asynchronous, multi in [ + ("triton", False, False), + ("flashinfer", False, False), + ("flashinfer", True, False), + ("flashinfer", True, True), + ]: + engine = LLMEngine( + model, + cache_config=CacheConfig(num_blocks=48, block_size=16, layout=layout), + scheduler_config=SchedulerConfig( + max_num_seqs=3, max_num_batched_tokens=8, prefill_chunk_size=4 + ), + execution_config=ExecutionConfig( + async_scheduling=asynchronous, + multi_stream=multi, + static_buffers=static, + pad_to_power_of_two=static, + ), + exit_config=ExitConfig("trace", depths_by_request=traces), + attention_backend=backend, + ) + for i in range(3): + engine.add_request( + str(i), + [2, 3, 4, 5] * (i + 1), + SamplingParams(max_tokens=6, min_loops=1, ignore_eos=True), + ) + finished = {} + for _ in range(300): + if not engine.has_unfinished_requests(): + break + for out in engine.step(): + if out.finished: + finished[out.request_id] = (out.token_ids, out.exit_depths) + assert len(finished) == 3 + assert engine.cache_manager.num_used_blocks == 0 + outputs.append(finished) + assert all(value == outputs[0] for value in outputs) diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index 6a1bf8bb..6c6bc858 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -8,6 +8,7 @@ import torch from vllm_rlt.kernels.flash_attention import FLASH_BACKENDS, FlashPagedAttention +from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention from vllm_rlt.kernels.paged_attention import ( PackedWindowShape, TorchPagedAttention, @@ -92,15 +93,28 @@ def generation(self): device_context_lengths=True, ), } -_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "triton", "torch") +_FLASHINFER_CAPABILITIES = BackendCapabilities(cuda_graphs=True, async_scheduling=True) +_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "flashinfer", "triton", "torch") def backend_capabilities(implementation) -> BackendCapabilities: return implementation.capabilities +def _auto_flashinfer_supported(device) -> bool: + """Gate automatic FlashInfer selection to the validated SM120 target. + + Other architectures the kernel accepts remain reachable through explicit + `--attention-backend flashinfer` opt-in; auto keeps its pre-FlashInfer + fallback behavior everywhere else. + """ + if device.type != "cuda" or torch.version.hip: + return False + return torch.cuda.get_device_capability(device)[0] == 12 + + def validate_backend_name(backend: str) -> None: - if backend not in {"auto", "torch", "triton", *FLASH_BACKENDS}: + if backend not in {"auto", "torch", "triton", "flashinfer", *FLASH_BACKENDS}: raise ValueError("unknown attention backend") @@ -133,6 +147,9 @@ def _create_explicit(backend, device, dtype, head_dim, block_size, *, packed, pa return AttentionBackend( kernel, capabilities, {"backend": backend, "packed_prefill_tile": tile} ) + if backend == "flashinfer": + kernel = FlashInferPagedAttention(device, dtype, head_dim, block_size) + return AttentionBackend(kernel, _FLASHINFER_CAPABILITIES, dict(kernel.info)) if backend in FLASH_BACKENDS: kernel = FlashPagedAttention(device, dtype, head_dim, block_size, backend) capabilities = replace( @@ -157,7 +174,8 @@ def create_backend( packed_window_shape: PackedWindowShape | None = None, allow_fp8_calibration: bool = False, ) -> AttentionBackend: - """Explicit choices fail without fallback; auto tries FA4/3/2, Triton, then Torch. + """Explicit choices fail without fallback; auto tries FA4/3/2, FlashInfer + (SM120 only), Triton, then Torch. Each candidate validates hardware/configuration and imports its implementation. Only compatibility and import failures permit auto to try the next candidate; @@ -176,6 +194,13 @@ def create_backend( candidates = ("torch",) skipped.append(f"{device.type.upper()} uses Torch reference attention") for candidate in candidates: + if ( + backend == "auto" + and candidate == "flashinfer" + and not _auto_flashinfer_supported(device) + ): + skipped.append("flashinfer: automatic selection is validated on SM120 only") + continue try: implementation = _create_explicit( candidate, @@ -225,7 +250,7 @@ def create_backend( f"flash_attn_{implementation.generation}" if candidate in FLASH_BACKENDS else candidate ) reason = ( - "first compatible candidate in FA4 > FA3 > FA2 > Triton > Torch priority" + "first compatible candidate in FA4 > FA3 > FA2 > FlashInfer > Triton > Torch priority" if backend == "auto" else f"explicitly requested {backend}" ) diff --git a/vllm_rlt/entrypoints/cli.py b/vllm_rlt/entrypoints/cli.py index a9b8025c..2dce6890 100644 --- a/vllm_rlt/entrypoints/cli.py +++ b/vllm_rlt/entrypoints/cli.py @@ -70,6 +70,7 @@ def main(): "auto", "torch", "triton", + "flashinfer", "flash_attn", "flash_attn_2", "flash_attn_3", diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index dc5eef6c..c518f69c 100644 --- a/vllm_rlt/entrypoints/serve.py +++ b/vllm_rlt/entrypoints/serve.py @@ -91,6 +91,7 @@ def main(): "auto", "torch", "triton", + "flashinfer", "flash_attn", "flash_attn_2", "flash_attn_3", diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py new file mode 100644 index 00000000..d1c3739f --- /dev/null +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -0,0 +1,110 @@ +"""FlashInfer XQA paged decode kernels; no packed prefill in this backend. + +Decode uses independent single-query rows, exactly like the Triton path. +SM120 (RTX 50) is the validated target; other supported majors are accepted +but unvalidated. Requires a CUDA toolkit with nvcc >= 12.9 visible through +CUDA_HOME for the just-in-time compiled kernels, and that toolkit's lib +directory on LD_LIBRARY_PATH. +""" + +import importlib +import logging +from importlib.metadata import PackageNotFoundError, version + +import torch + +FLASHINFER_PAGE_SIZES = (16, 32, 64, 128) +FLASHINFER_WORKSPACE_BYTES = 128 * 1024 * 1024 + + +class FlashInferPagedAttention: + def __init__(self, device, dtype, head_dim, block_size): + if device.type != "cuda" or torch.version.hip: + raise ValueError("flashinfer currently requires an NVIDIA CUDA device") + # float16 kernels compute correctly, but flashinfer-python 0.7.0.post1 + # crashes the process (host SIGFPE) while building the f16 JIT module + # on first in-process use; reject instead of shipping that. + if dtype is torch.float16: + raise ValueError( + "the flashinfer backend is not validated with float16; use bfloat16" + ) + if dtype is not torch.bfloat16: + raise ValueError("flashinfer requires bfloat16") + # The XQA JIT module generator rejects anything else at first call; + # validate here so the failure is an explicit startup error instead. + if head_dim % 16 or not 16 <= head_dim <= 512: + raise ValueError( + "flashinfer requires head_dim divisible by 16 and in [16, 512] (XQA kernels)" + ) + # XQA kernels are compiled per page size and only these variants ship. + if block_size not in FLASHINFER_PAGE_SIZES: + raise ValueError( + "flashinfer requires --block-size one of " + f"{FLASHINFER_PAGE_SIZES} (XQA page-size variants)" + ) + major, minor = torch.cuda.get_device_capability(device) + if major not in (9, 10, 12): + raise ValueError(f"flashinfer is not supported on SM{major}{minor}") + try: + package_version = version("flashinfer-python") + self.kernel = getattr( + importlib.import_module("flashinfer.decode"), + "trtllm_batch_decode_with_kv_cache", + ) + except (ImportError, AttributeError, PackageNotFoundError) as error: + raise ImportError( + "install flashinfer with: pip install 'flashinfer-python>=0.7.0' " + "(a CUDA toolkit with nvcc >= 12.9 must be reachable via CUDA_HOME, " + "and its lib directory on LD_LIBRARY_PATH for the JIT modules). " + "No backend fallback was performed." + ) from error + if major != 12: + logging.getLogger(__name__).warning( + "flashinfer attention is validated on SM120 only; SM%d%d is unvalidated", + major, + minor, + ) + # Persistent, pre-zeroed scratch shared by every call. Allocated on the + # first execution rather than here so backend selection stays free of + # device allocations: engines always profile before CUDA-graph capture, + # so the workspace exists by the time any graph is recorded. + self.workspace = None + self.info = dict( + backend="flashinfer", + package="flashinfer-python", + version=package_version, + kernel="xqa", + page_size=block_size, + ) + logging.getLogger(__name__).warning("Attention implementation: %s", self.info) + + def __call__(self, q, key_cache, value_cache, block_tables, context_lengths): + # An empty batch host-crashes (SIGFPE, not an exception) inside the + # FlashInfer dispatch; return the same empty shape the other backends do. + if q.shape[0] == 0: + return torch.empty_like(q) + if self.workspace is None: + self.workspace = torch.zeros( + FLASHINFER_WORKSPACE_BYTES, dtype=torch.uint8, device=q.device + ) + out = torch.empty_like(q) + self.kernel( + q, + (key_cache, value_cache), + self.workspace, + # Padding columns hold -1 (synchronous), 0 (async), or stale valid + # ids (graph replay beyond the current width). The kernel bounds + # reads by seq_lens, and clamped ids keep any full-width access on + # allocated memory regardless. + block_tables=block_tables.clamp_min(0), + seq_lens=context_lengths.to(torch.uint32), + max_seq_len=block_tables.shape[1] * key_cache.shape[1], + bmm1_scale=q.shape[-1] ** -0.5, + out=out, + q_len_per_req=1, + # The engine pool is [blocks, page, heads, dim]; the API default is + # HND and silently misreads NHD data. + kv_layout="NHD", + backend="xqa", + ) + return out From efd36af82c778594f57955bf8c9eb05f350e6e3f Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:40:36 +0800 Subject: [PATCH 7/9] Support fixed-scale E4M3 KV in FlashInfer XQA on SM120 --- docs/flashinfer.md | 4 ++- tests/test_backend_selection.py | 10 +++++++ tests/test_flashinfer_attention.py | 34 +++++++++++++++++++++--- vllm_rlt/attention/backend.py | 3 ++- vllm_rlt/kernels/flashinfer_attention.py | 30 +++++++++++++++++++-- 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/docs/flashinfer.md b/docs/flashinfer.md index 427f6378..4b600b19 100644 --- a/docs/flashinfer.md +++ b/docs/flashinfer.md @@ -14,7 +14,9 @@ reject paged KV. prefill runs per token exactly as with Triton. - No prefill/decode disaggregation; PD entrypoints reject the backend explicitly. -- `bfloat16` only. `float16` is rejected at startup: the kernels compute +- On SM120, `--kv-cache-dtype fp8_e4m3` selects E4M3 KV with a fixed + scale calibrated at startup. Query and output remain BF16. +- Model dtype is `bfloat16` only. `float16` is rejected at startup: the kernels compute correctly, but flashinfer-python 0.7.0.post1 crashes the process (host SIGFPE) while building the f16 JIT module on first in-process use. - `--block-size` must be one of `16, 32, 64, 128` (compiled XQA page-size diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index 33ebb0d6..c9275ab3 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -97,6 +97,16 @@ def test_fa4_static_fp8_selection(packages, monkeypatch, sm, dtype, head_dim, su assert selected.info["selected_backend"] == "flash_attn_4" +def test_xqa_static_fp8_selection(packages, monkeypatch): + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (12, 0)) + args = ("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) + required = BackendCapabilities(fp8_kv=True) + selected = create_backend(*args, required_capabilities=required, allow_fp8_calibration=True) + assert selected.capabilities.fp8_kv_static and not selected.capabilities.fp8_kv + with pytest.raises(ValueError, match="fp8_kv"): + create_backend(*args, required_capabilities=required) + + def test_fa4_static_fp8_requires_public_scale_api(packages, monkeypatch): monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (10, 3)) packages.remove("TensorwiseScales") diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py index 03eddb80..719a4d18 100644 --- a/tests/test_flashinfer_attention.py +++ b/tests/test_flashinfer_attention.py @@ -72,14 +72,14 @@ def test_kernel_call_explicitly_selects_xqa(monkeypatch): output, workspace, uint32 = object(), object(), object() empty_like = Mock(return_value=output) - fake_torch = SimpleNamespace(empty_like=empty_like, uint32=uint32) + fake_torch = SimpleNamespace(empty_like=empty_like, uint32=uint32, float8_e4m3fn=object()) monkeypatch.setitem(FlashInferPagedAttention.__call__.__globals__, "torch", fake_torch) attention = FlashInferPagedAttention.__new__(FlashInferPagedAttention) attention.workspace = workspace attention.kernel = Mock() q = SimpleNamespace(shape=(2, 4, 64)) - keys = SimpleNamespace(shape=(8, 16, 2, 64)) - values = SimpleNamespace(shape=(8, 16, 2, 64)) + keys = SimpleNamespace(shape=(8, 16, 2, 64), dtype=torch.bfloat16) + values = SimpleNamespace(shape=keys.shape, dtype=keys.dtype) tables = Mock(shape=(2, 3)) lengths = Mock() @@ -93,6 +93,7 @@ def test_kernel_call_explicitly_selects_xqa(monkeypatch): seq_lens=lengths.to.return_value, max_seq_len=48, bmm1_scale=0.125, + bmm2_scale=1.0, out=output, q_len_per_req=1, kv_layout="NHD", @@ -108,6 +109,28 @@ def test_kernel_call_explicitly_selects_xqa(monkeypatch): attention.kernel.assert_not_called() +def test_xqa_fixed_fp8_call_on_cpu(): + from unittest.mock import Mock + + attention = FlashInferPagedAttention.__new__(FlashInferPagedAttention) + attention.supports_fp8_static = True + attention.kernel = Mock() + attention.workspace = object() + q = torch.empty(1, 2, 64, dtype=torch.bfloat16) + k = torch.empty((1, 16, 2, 64), dtype=torch.float8_e4m3fn) + v = torch.empty_like(k) + table = torch.zeros((1, 1), dtype=torch.int32) + lengths = torch.ones(1, dtype=torch.int32) + scale = torch.tensor(0.25) + attention(q, k, v, table, lengths, key_scale=scale, value_scale=scale) + kwargs = attention.kernel.call_args.kwargs + torch.testing.assert_close(kwargs["bmm1_scale"], scale / 8) + assert kwargs["bmm2_scale"] is scale + assert kwargs["backend"] == "xqa" + with pytest.raises(ValueError, match="scalar FP32"): + attention(q, k, v, table, lengths, key_scale=scale.expand(2), value_scale=scale) + + @pytest.mark.gpu def test_backend_contract_anchors(): attention = FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) @@ -123,7 +146,10 @@ def test_backend_contract_anchors(): assert not hasattr(attention, "prefill") wrapper = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) assert wrapper.info["selected_backend"] == "flashinfer" - assert wrapper.capabilities == BackendCapabilities(cuda_graphs=True, async_scheduling=True) + assert wrapper.capabilities == BackendCapabilities( + cuda_graphs=True, async_scheduling=True, + fp8_kv_static=torch.cuda.get_device_capability() == (12, 0), + ) @pytest.mark.gpu diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index 6c6bc858..db0e9d71 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -149,7 +149,8 @@ def _create_explicit(backend, device, dtype, head_dim, block_size, *, packed, pa ) if backend == "flashinfer": kernel = FlashInferPagedAttention(device, dtype, head_dim, block_size) - return AttentionBackend(kernel, _FLASHINFER_CAPABILITIES, dict(kernel.info)) + capabilities = replace(_FLASHINFER_CAPABILITIES, fp8_kv_static=kernel.supports_fp8_static) + return AttentionBackend(kernel, capabilities, dict(kernel.info)) if backend in FLASH_BACKENDS: kernel = FlashPagedAttention(device, dtype, head_dim, block_size, backend) capabilities = replace( diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py index d1c3739f..553f6253 100644 --- a/vllm_rlt/kernels/flashinfer_attention.py +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -45,6 +45,7 @@ def __init__(self, device, dtype, head_dim, block_size): major, minor = torch.cuda.get_device_capability(device) if major not in (9, 10, 12): raise ValueError(f"flashinfer is not supported on SM{major}{minor}") + self.supports_fp8_static = (major, minor) == (12, 0) try: package_version = version("flashinfer-python") self.kernel = getattr( @@ -78,11 +79,35 @@ def __init__(self, device, dtype, head_dim, block_size): ) logging.getLogger(__name__).warning("Attention implementation: %s", self.info) - def __call__(self, q, key_cache, value_cache, block_tables, context_lengths): + def __call__( + self, q, key_cache, value_cache, block_tables, context_lengths, *, + key_scale=None, value_scale=None, + ): # An empty batch host-crashes (SIGFPE, not an exception) inside the # FlashInfer dispatch; return the same empty shape the other backends do. if q.shape[0] == 0: return torch.empty_like(q) + bmm1_scale = q.shape[-1] ** -0.5 + bmm2_scale = 1.0 + if key_cache.dtype != value_cache.dtype: + raise ValueError("XQA K and V cache dtypes must match") + if key_cache.dtype == torch.float8_e4m3fn: + if not self.supports_fp8_static: + raise ValueError("fixed-scale FP8 KV requires SM120") + for scale in (key_scale, value_scale): + if ( + scale is None + or scale.ndim != 0 + or scale.dtype != torch.float32 + or scale.device != q.device + ): + raise ValueError("XQA FP8 KV requires scalar FP32 scales on the query device") + # Descale K before softmax and V in the weighted sum. + bmm1_scale = key_scale * bmm1_scale + bmm2_scale = value_scale + elif key_scale is not None or value_scale is not None: + raise ValueError("XQA KV scales require an E4M3 cache") + if self.workspace is None: self.workspace = torch.zeros( FLASHINFER_WORKSPACE_BYTES, dtype=torch.uint8, device=q.device @@ -99,7 +124,8 @@ def __call__(self, q, key_cache, value_cache, block_tables, context_lengths): block_tables=block_tables.clamp_min(0), seq_lens=context_lengths.to(torch.uint32), max_seq_len=block_tables.shape[1] * key_cache.shape[1], - bmm1_scale=q.shape[-1] ** -0.5, + bmm1_scale=bmm1_scale, + bmm2_scale=bmm2_scale, out=out, q_len_per_req=1, # The engine pool is [blocks, page, heads, dim]; the API default is From 76422cc779b1ee97c2798e7d1a7e8f3711a54088 Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:10:51 +0800 Subject: [PATCH 8/9] fix: narrow XQA auto selection to SM120 and record GSM8K attention backends --- README.md | 3 +- benchmarks/gsm8k.py | 54 ++++++++++++----- benchmarks/gsm8k_backends.py | 23 ++++++-- docs/accuracy.md | 27 +++++---- docs/flashinfer.md | 75 ++++++++++++++---------- docs/launching.md | 4 +- docs/runtime.md | 3 + tests/test_backend_selection.py | 19 ++++-- tests/test_flashinfer_attention.py | 10 +--- tests/test_gsm8k_accuracy.py | 24 ++++++-- tests/test_gsm8k_backends.py | 8 ++- vllm_rlt/attention/backend.py | 10 +++- vllm_rlt/engine/stage_engine.py | 1 + vllm_rlt/kernels/flashinfer_attention.py | 23 ++++---- 14 files changed, 190 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 60ccb9f0..8df60c27 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,8 @@ including Dory sliding attention, uses `flash-attn-4==4.0.0b39` and calibrates a fixed scale at startup. See the [hardware and calibration requirements](docs/runtime.md#experimental-fa4-static-scale-adapter). -For the FlashInfer XQA backend, see the [FlashInfer guide](docs/flashinfer.md). +On SM120, FlashInfer XQA supports BF16 attention with BF16 KV or calibrated +fixed-scale E4M3 KV. See the [FlashInfer guide](docs/flashinfer.md). ## Model Support diff --git a/benchmarks/gsm8k.py b/benchmarks/gsm8k.py index acc21a73..f4027088 100644 --- a/benchmarks/gsm8k.py +++ b/benchmarks/gsm8k.py @@ -591,7 +591,6 @@ def run(args): output.mkdir(parents=True, exist_ok=False) metadata = { "backend": args.backend, - "attention_backend": args.attention_backend, "protocol_sha256": file_digest(args.protocol), "source": source(), "cuda_visible_devices": os.environ["CUDA_VISIBLE_DEVICES"], @@ -605,18 +604,30 @@ def run(args): "loops": loops, "exit": exit_policy, } - write_json(output / "metadata.json", metadata) tokenizer = AutoTokenizer.from_pretrained(model, local_files_only=True) close_id = thinking_close_id(tokenizer) if scorer == SCORER_THINKING else None task = make_task(protocol["task_config"]) start = time.monotonic() generator = Generator( - args.backend, str(model), tokenizer, protocol["max_length"], exit_policy, + args.backend, + str(model), + tokenizer, + protocol["max_length"], + exit_policy, attention_backend=args.attention_backend, + no_packed_prefill=args.no_packed_prefill, ) load_seconds = time.monotonic() - start rows = [] try: + metadata["attention_backend"] = generator.attention_backend + if args.backend == "native": + metadata["packed_prefill"] = generator.engine.execution_config.packed_prefill + if generator.attention_backend == "flashinfer": + metadata["attention_backend_version"] = generator.engine.cache_manager.attention_info[ + "version" + ] + write_json(output / "metadata.json", metadata) with (output / "samples.jsonl").open("x", buffering=1) as stream: for row in protocol["records"]: stops = row["generation_kwargs"]["until"] + [tokenizer.eos_token] @@ -664,6 +675,20 @@ def run(args): return summary +def comparison_run(summary): + # The release model always used eager, including older summaries that + # recorded the native CLI default. Native runs predating the option used Triton. + backend = summary["backend"] + attention = "eager" if backend == "transformers" else summary.get("attention_backend", "triton") + return { + "backend": backend, + "attention_backend": attention, + **{k: summary[k] for k in ("packed_prefill", "attention_backend_version") if k in summary}, + "exit": summary.get("exit", fixed_exit(4)), + "depth": summary.get("depth"), + } + + def compare(args): paths = [Path(args.transformers), Path(args.native)] summaries = [json.loads((p / "summary.json").read_text()) for p in paths] @@ -703,16 +728,8 @@ def compare(args): "split": a["split"], # Summaries written before exit options existed used the fixed recipe, and the # harness then accepted only four-loop checkpoints. - "reference": { - "backend": a["backend"], - "exit": a.get("exit", fixed_exit(4)), - "depth": a.get("depth"), - }, - "candidate": { - "backend": b["backend"], - "exit": b.get("exit", fixed_exit(4)), - "depth": b.get("depth"), - }, + "reference": comparison_run(a), + "candidate": comparison_run(b), "reference_accuracy_pct": 100 * a["accuracy"], "candidate_accuracy_pct": 100 * b["accuracy"], "reference_correct": a["correct"], @@ -794,8 +811,12 @@ def main(): p.add_argument( "--attention-backend", choices=["torch", "triton", "flashinfer"], - default="triton", - help="Native engine attention kernel; recorded in the run metadata", + help="Native engine attention kernel (default: triton)", + ) + p.add_argument( + "--no-packed-prefill", + action="store_true", + help="Use per-query rows for native prefill; useful for matched kernel comparisons", ) p.add_argument("--exit-mode", choices=["ouro", "ouro_delayed"], default="ouro") p.add_argument( @@ -811,6 +832,9 @@ def main(): p.add_argument("--native", "--candidate", dest="native", required=True) p.add_argument("--output", required=True) args = parser.parse_args() + if args.command == "run" and args.backend == "transformers": + if args.attention_backend is not None or args.no_packed_prefill: + parser.error("--attention-backend and --no-packed-prefill require --backend native") result = {"prepare": prepare, "run": run, "compare": compare}[args.command](args) if args.command == "compare" and not result["passes_observed_accuracy_gate"]: raise SystemExit(1) diff --git a/benchmarks/gsm8k_backends.py b/benchmarks/gsm8k_backends.py index 2d39b9e6..d038596c 100644 --- a/benchmarks/gsm8k_backends.py +++ b/benchmarks/gsm8k_backends.py @@ -102,19 +102,30 @@ def _after_model(self, module, inputs, output): class Generator: def __init__( - self, backend, model_path, tokenizer, max_length, exit_policy, attention_backend="triton" + self, + backend, + model_path, + tokenizer, + max_length, + exit_policy, + attention_backend=None, + *, + no_packed_prefill=False, ): self.backend, self.tokenizer, self.exit = backend, tokenizer, exit_policy # Full depth, taken from the protocol (the checkpoint's total_ut_steps). loops = exit_policy["max_loops"] if backend == "transformers": + if attention_backend is not None or no_packed_prefill: + raise ValueError("Attention and packed prefill options require --backend native") + self.attention_backend = "eager" self.model = ( AutoModelForCausalLM.from_pretrained( model_path, trust_remote_code=True, local_files_only=True, torch_dtype=torch.bfloat16, - attn_implementation="eager", + attn_implementation=self.attention_backend, ) .eval() .to("cuda") @@ -138,15 +149,19 @@ def __init__( model_path, device="cuda", dtype=torch.bfloat16 ).eval() check_depth(self.model.config, loops) + execution = {"async_scheduling": exit_policy["async_scheduling"]} + if no_packed_prefill: + execution["packed_prefill"] = False self.engine = StageEngine( self.model, - attention_backend=attention_backend, + attention_backend=attention_backend or "triton", # last_exited KV keeps one plane per loop. cache_config=CacheConfig(num_blocks=loops * ((max_length + 15) // 16)), scheduler_config=SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=128), exit_config=ExitConfig(exit_policy["mode"]), - execution_config=ExecutionConfig(async_scheduling=exit_policy["async_scheduling"]), + execution_config=ExecutionConfig(**execution), ) + self.attention_backend = self.engine.cache_manager.backend # Observe the existing sampling boundary without changing arithmetic. self._finite_hook = self.model.lm_head.register_forward_hook( lambda module, inputs, output: check_logits(output) diff --git a/docs/accuracy.md b/docs/accuracy.md index ca375a02..1f6e638a 100644 --- a/docs/accuracy.md +++ b/docs/accuracy.md @@ -34,7 +34,7 @@ attention and the standard Transformers `DynamicCache` with one slot per layer a loop (96 here), plus `exit_at_step = total_ut_steps - 1` (3) for last-loop logits. This cache setup accommodates the pinned release's older cache interface; the model source is not patched. -The candidate uses the existing native engine and Triton attention. Both use +The default native candidate uses Triton attention. Both use BF16 weights and activations, retaining each backend's existing FP32 reductions and other operations that need higher precision. The evaluator changes no inference arithmetic. @@ -196,21 +196,26 @@ gate does not use them. ## Attention-backend runs `run --backend native` selects the attention kernel with `--attention-backend` -(`triton` by default, recorded in the run metadata): +(default `triton`). The Transformers reference always uses eager attention. +Run metadata and comparison reports identify the attention implementation. +Native metadata also records the effective packed-prefill setting and, for XQA, +the FlashInfer version. + +Use the same frozen protocol and disable packed prefill for both native runs: ```bash +python -m benchmarks.gsm8k run --backend native --attention-backend triton \ + --no-packed-prefill --protocol "$PROTOCOL" --output "$RESULTS/triton" python -m benchmarks.gsm8k run --backend native --attention-backend flashinfer \ - --protocol /path/to/gsm8k-87-protocol.json --output /path/to/native-flashinfer + --no-packed-prefill --protocol "$PROTOCOL" --output "$RESULTS/flashinfer" +python -m benchmarks.gsm8k compare --reference "$RESULTS/triton" \ + --candidate "$RESULTS/flashinfer" --output "$RESULTS/comparison.json" ``` -On RTX 5090 (SM120) the frozen default case scored **Triton 61/87 and FlashInfer -58/87** against the stored HF baseline of 59/87: 64 of the 87 generations were -token-identical between the kernels, the divergent ones flipped near-tied greedy -choices at scattered positions, and exit depths never differed. This is the -expected single-pass greedy variation between BF16 kernels with different -accumulation orders — see the [FlashInfer accuracy -note](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass) before treating a -one-question delta from a backend swap as a regression. +On RTX 5090 the matched BF16 runs scored **Triton 62/87 and FlashInfer 58/87**. +The stored HF reference scored 59/87. The XQA run completed and failed the +one-percentage-point gate. Both `run` and `compare` write their results before +returning a failing gate status. See the [per-question results](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass). Dataset: [GSM8K](https://huggingface.co/datasets/openai/gsm8k). The [Ouro evaluation settings](https://arxiv.org/html/2510.25741v5#A3.T16) do not diff --git a/docs/flashinfer.md b/docs/flashinfer.md index 4b600b19..3e4fc2f0 100644 --- a/docs/flashinfer.md +++ b/docs/flashinfer.md @@ -8,10 +8,11 @@ reject paged KV. ## Scope -- Decode and per-token prefill, identical semantics to the Triton path, - including CUDA Graph capture and asynchronous scheduling. -- No packed prefill: the engine keeps the FA4-only packed path closed, so - prefill runs per token exactly as with Triton. +- XQA batches one query position per row for decode and prefill. Each row + attends to its own visible KV prefix. The backend supports CUDA Graph + capture and asynchronous scheduling. +- XQA declares `packed_prefill=False`. Triton can also run packed prefill. + Disable packing for both backends when comparing their single-query paths. - No prefill/decode disaggregation; PD entrypoints reject the backend explicitly. - On SM120, `--kv-cache-dtype fp8_e4m3` selects E4M3 KV with a fixed @@ -21,6 +22,7 @@ reject paged KV. SIGFPE) while building the f16 JIT module on first in-process use. - `--block-size` must be one of `16, 32, 64, 128` (compiled XQA page-size variants) and `head_dim` must be divisible by 16 within `[16, 512]`. + For `head_dim > 256`, XQA requires at most 16 query heads per KV head. ## Installation and runtime requirements @@ -51,13 +53,14 @@ Graph capture warmups, reuse the cache. ## Running ```bash -vllm-rlt --model --revision \ +vllm-rlt --model "$MODEL" --revision "$REVISION" --prompt "What is 2 + 2?" \ --device cuda --dtype bfloat16 --attention-backend flashinfer ``` The adapter holds one 128 MiB zero-initialized workspace for the kernel's -scratch and softmax statistics; it is allocated once at startup and reused, so -graph capture performs no new allocations. Padded block-table columns are +scratch and softmax statistics. The first nonempty call allocates it and later +calls reuse it. Each call still prepares an output tensor, page table and +sequence lengths. Padded block-table columns are clamped non-negative before the call: the engine produces `-1` padding on the synchronous path, `0` on the asynchronous path, and stale-but-valid ids in CUDA Graph replay beyond the current width. The kernel bounds reads by @@ -65,34 +68,42 @@ CUDA Graph replay beyond the current width. The kernel bounds reads by ## Choosing between Triton and FlashInfer -SM120 is the only validated target for this backend; on it, FlashInfer decodes -noticeably faster at low concurrency (single-request decode measured ~2x -against the Triton kernel at 256-token contexts) because the XQA kernel -parallelizes a single query row across KV chunks, while the Triton kernel -spawns one program per (row, head). At high concurrency with long contexts the -two are comparable; choose Triton when its determinism properties matter more -and FlashInfer for single-user or low-batch latency. SM9/SM10 devices are -accepted but unvalidated — prefer FlashAttention there until validated -configurations are recorded. +The inference CLI defaults to Torch. The HTTP server and native GSM8K harness +default to Triton. With `--attention-backend auto`, the engine considers +FlashInfer on SM120 (compute capability 12.0) ahead of Triton. Other devices +accepted by the adapter require explicit selection and log a validation warning. + +Both XQA and Triton can split a single query's KV prefix. Triton's single-query +kernel launches programs over rows, heads and KV splits, then reduces partial +outputs. Measure performance at the batch size and context length of interest. ## Validation status -Validated on RTX 5090 (SM120, 32 GB) with Ouro-1.4B BF16, `block_size=16`, -fixed four-loop decode: oracle parity against the reference paged attention, -token/exit-depth equality against the Triton backend across synchronous, -asynchronous, and multi-stream execution with static buffers and graph replay, -and end-to-end greedy generation. +The RTX 5090 GSM8K run below used the Ouro-1.4B checkpoint. The GPU regression +tests use a tiny Ouro model for cross-backend comparisons of tokens and +prescribed exit depths in synchronous, asynchronous and multi-stream runs. +The graph tests compare eager execution and replay within each backend. +Attention operator tests compare numerical outputs against a paged reference +with tolerances. ## Accuracy note (GSM8K-87, single greedy pass) -On the frozen GSM8K-87 protocol (HF baseline 59/87), a fixed four-loop greedy -pass scores 58/87 with FlashInfer versus 61/87 with Triton. 64 of 87 -generations are token-identical between the two backends; the remaining 23 -diverge at scattered positions with unchanged exit depths, and the net -correct-answer flips are 3 against, 0 for. Kernel-level comparison against a -float32 oracle at 352-1024 token contexts shows the Triton kernel is -near-exact (max deviation up to 5e-4) while XQA's split reductions deviate by -up to 4e-3 — within normal BF16 kernel variation, but enough to flip -near-tied greedy argmax decisions during long chain-of-thought decoding. -Triton remains the default backend; treat this note as the expected greedy -variation when opting into FlashInfer on SM120. +At commit `cd368ce` on RTX 5090, both native backends used Ouro-1.4B, +BF16 weights and KV, page size 16, four fixed loops, greedy decoding, per-row +prefill and the frozen strict scorer. FlashInfer `0.7.5.post1` scored **58/87** +and Triton **62/87**. The generated token sequences matched on **61/87**. +All generated tokens exited at depth four. + +| Question | XQA final answer | Triton final answer | Strict scoring | +| --- | --- | --- | --- | +| 203 | `27` | `31` | XQA gave the wrong value | +| 426 | `$11` | `11` | XQA amount was correct, extraction failed | +| 745 | `$1100` | `1100` | XQA amount was correct, extraction failed | +| 819 | `$6,250` | `6,250` | XQA amount was correct, extraction failed | + +At the first differing attention row on question 203, rounding the unnormalized +softmax weights to BF16 in both numerator and denominator reproduced all 2,048 +XQA output components. The Triton row matched the FP64 reference rounded to BF16. +This experiment identifies the rounding behavior at that row. The three +currency-format losses were established by replaying the scorer. +See the [matched benchmark commands and accuracy gate](accuracy.md#attention-backend-runs). diff --git a/docs/launching.md b/docs/launching.md index 2aad2973..817f459a 100644 --- a/docs/launching.md +++ b/docs/launching.md @@ -244,7 +244,7 @@ depths, and the finish reason. Use `--attention-backend auto` with the inference CLI or the local HTTP server to select a compatible implementation at startup. Auto tries FA4, FA3, FA2, -Triton, then Torch, checking hardware, dtype, head dimension, block size, installed +FlashInfer (SM120 only), Triton, then Torch, checking hardware, dtype, head dimension, block size, installed packages, and execution requirements. CPU uses Torch. For example, on an RTX 4090, the default 16-token block size rules out FA2's 256-token page requirement; auto selects Triton if it is installed. @@ -260,7 +260,7 @@ omitting both selects it automatically when supported. `--no-uva` independently selects copies instead of mapped host-memory reads. See the [packed-prefill selection rules](runtime.md#packed-prefill). -Explicit choices (`torch`, `triton`, `flash_attn`, or `flash_attn_2/3/4`) retain +Explicit choices (`torch`, `triton`, `flashinfer`, `flash_attn`, or `flash_attn_2/3/4`) retain their validation errors and never fall back. Existing defaults are unchanged: the inference CLI defaults to Torch and the local server defaults to Triton. The Python equivalent is `attention_backend="auto"`. Read the worker startup diff --git a/docs/runtime.md b/docs/runtime.md index c487ea37..2a1aee98 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -352,6 +352,9 @@ model dtype and leaves every existing path unchanged. token in FP8 as well. Accuracy should be checked per model and workload; adaptive exits can change where a token exits because the gate sees slightly different attention. +On SM120, the [FlashInfer XQA adapter](flashinfer.md#scope) also accepts E4M3 KV. +It uses a single calibrated scale for K and V and keeps Q and output in BF16. + ### Experimental FA4 static-scale adapter Use `--kv-cache-dtype fp8_e4m3 --attention-backend flash_attn_4` diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index c9275ab3..dd788885 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -45,9 +45,7 @@ def import_module(name): if name == "flashinfer.decode": if "flashinfer" not in installed: raise ImportError("flashinfer is not installed") - return SimpleNamespace( - trtllm_batch_decode_with_kv_cache=lambda *args, **kwargs: None - ) + return SimpleNamespace(trtllm_batch_decode_with_kv_cache=lambda *args, **kwargs: None) return original_import(name) monkeypatch.setattr(flash_attention.importlib, "import_module", import_module) @@ -201,6 +199,7 @@ def test_dory_requirements_select_native_fa4_and_reject_old_hd256(packages, monk ), ((10, 0), torch.bfloat16, 128, 16, ("flash_attn.cute",), "triton"), ((12, 0), torch.bfloat16, 128, 16, (), "flashinfer"), + ((12, 1), torch.bfloat16, 128, 16, (), "triton"), ((12, 0), torch.bfloat16, 128, 16, ("flashinfer",), "triton"), ((7, 5), torch.float16, 128, 256, (), "torch"), ], @@ -217,11 +216,19 @@ def test_auto_selection_constraints( assert backend_capabilities(selected).packed_prefill -def test_explicit_flashinfer_opt_in_outside_sm120(packages, monkeypatch, caplog): - import logging +def test_flashinfer_wide_head_group_limit(packages, monkeypatch): + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (12, 0)) + args = (torch.device("cuda"), torch.bfloat16, 512, 16) + assert create_backend("flashinfer", *args, head_group_ratio=16).info["kernel"] == "xqa" + with pytest.raises(ValueError, match="head_group_ratio <= 16"): + create_backend("flashinfer", *args, head_group_ratio=32) + assert create_backend("auto", *args, head_group_ratio=32).info["selected_backend"] == "torch" + +@pytest.mark.parametrize("sm", [(9, 0), (12, 1)]) +def test_explicit_flashinfer_opt_in_outside_sm120(packages, monkeypatch, caplog, sm): caplog.set_level(logging.WARNING, logger="vllm_rlt.kernels.flashinfer_attention") - monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (9, 0)) + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: sm) selected = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) assert selected.info["selected_backend"] == "flashinfer" assert selected.capabilities.cuda_graphs and selected.capabilities.async_scheduling diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py index 719a4d18..51c1f770 100644 --- a/tests/test_flashinfer_attention.py +++ b/tests/test_flashinfer_attention.py @@ -138,16 +138,12 @@ def test_backend_contract_anchors(): assert attention.info["package"] == "flashinfer-python" assert attention.info["page_size"] == 16 assert attention.info["kernel"] == "xqa" - # Absence is the contract: capability declarations live only in the - # attention registration layer, and the FA4 packed-prefill gates key off - # a missing generation attribute staying missing. - assert not hasattr(attention, "capabilities") - assert not hasattr(attention, "generation") - assert not hasattr(attention, "prefill") + # StageEngine selects packed prefill from the registered backend capabilities. wrapper = create_backend("flashinfer", torch.device("cuda"), torch.bfloat16, 128, 16) assert wrapper.info["selected_backend"] == "flashinfer" assert wrapper.capabilities == BackendCapabilities( - cuda_graphs=True, async_scheduling=True, + cuda_graphs=True, + async_scheduling=True, fp8_kv_static=torch.cuda.get_device_capability() == (12, 0), ) diff --git a/tests/test_gsm8k_accuracy.py b/tests/test_gsm8k_accuracy.py index c7da98b0..0c50be48 100644 --- a/tests/test_gsm8k_accuracy.py +++ b/tests/test_gsm8k_accuracy.py @@ -617,14 +617,24 @@ def test_compare_reports_exit_policies_between_native_runs(tmp_path): depth = depth_summary([{"exit_depths": [4, 2]}]) for backend, extra in ( ("transformers", {"backend": "native"}), - ("native", {"exit": adaptive, "depth": depth}), + ("native", {"exit": adaptive, "depth": depth, "attention_backend": "flashinfer"}), ): path = tmp_path / backend / "summary.json" path.write_text(json.dumps({**json.loads(path.read_text()), **extra})) result = compare(args) # A summary without exit settings predates them and used the fixed four-loop recipe. - assert result["reference"] == {"backend": "native", "exit": fixed_exit(4), "depth": None} - assert result["candidate"] == {"backend": "native", "exit": adaptive, "depth": depth} + assert result["reference"] == { + "backend": "native", + "attention_backend": "triton", + "exit": fixed_exit(4), + "depth": None, + } + assert result["candidate"] == { + "backend": "native", + "attention_backend": "flashinfer", + "exit": adaptive, + "depth": depth, + } assert (result["reference_correct"], result["candidate_correct"]) == (1, 1) # Backend-named keys would mislabel a native-vs-native comparison, so they are omitted. assert not any(key.startswith(("transformers_", "native_")) for key in result) @@ -632,7 +642,13 @@ def test_compare_reports_exit_policies_between_native_runs(tmp_path): def test_compare_keeps_backend_named_keys_for_hf_vs_native(tmp_path): - result = compare(comparison_fixture(tmp_path, native_correct=False)) + args = comparison_fixture(tmp_path, native_correct=False) + path = args.transformers / "summary.json" + summary = json.loads(path.read_text()) + # Legacy HF runs recorded the native CLI default even though the model used eager. + path.write_text(json.dumps({**summary, "attention_backend": "triton"})) + result = compare(args) + assert result["reference"]["attention_backend"] == "eager" assert result["reference_correct_candidate_wrong"] == 1 assert result["transformers_correct"] == result["reference_correct"] == 1 assert result["native_correct"] == result["candidate_correct"] == 0 diff --git a/tests/test_gsm8k_backends.py b/tests/test_gsm8k_backends.py index 29be03e7..67da0ade 100644 --- a/tests/test_gsm8k_backends.py +++ b/tests/test_gsm8k_backends.py @@ -147,7 +147,13 @@ def test_native_generator_owns_logits_check_and_releases_it(monkeypatch): engine = Mock() factory = Mock(return_value=engine) monkeypatch.setattr(backends, "StageEngine", factory) - generator = backends.Generator("native", "unused", None, 128, fixed_exit(4)) + engine.cache_manager.backend = "flashinfer" + generator = backends.Generator( + "native", "unused", None, 128, fixed_exit(4), "flashinfer", no_packed_prefill=True + ) + assert generator.attention_backend == "flashinfer" + assert factory.call_args.kwargs["attention_backend"] == "flashinfer" + assert factory.call_args.kwargs["execution_config"].packed_prefill is False assert factory.call_args.args == (model,) model.lm_head(torch.zeros(1, model.config.hidden_size)) with pytest.raises(FloatingPointError, match="Non-finite"): diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index 7aa0f555..a0b7c9c1 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -128,7 +128,7 @@ def _auto_flashinfer_supported(device) -> bool: """ if device.type != "cuda" or torch.version.hip: return False - return torch.cuda.get_device_capability(device)[0] == 12 + return torch.cuda.get_device_capability(device) == (12, 0) def validate_backend_name(backend: str, *, device_type: str | None = None) -> None: @@ -200,6 +200,7 @@ def create_backend( block_size: int, *, required_capabilities: BackendCapabilities = BackendCapabilities(), + head_group_ratio: int | None = None, prefer_packed_prefill: bool = False, packed_window_shape: PackedWindowShape | None = None, allow_fp8_calibration: bool = False, @@ -232,6 +233,13 @@ def create_backend( skipped.append("flashinfer: automatic selection is validated on SM120 only") continue try: + if ( + candidate == "flashinfer" + and head_dim > 256 + and head_group_ratio is not None + and head_group_ratio > 16 + ): + raise ValueError("XQA with head_dim > 256 requires head_group_ratio <= 16") implementation = _create_explicit( candidate, device, diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index a8006977..c5d252ed 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -241,6 +241,7 @@ def __init__( fp8_kv=cache_config.kv_cache_dtype == "fp8_e4m3", sliding_window=sliding_window, ), + head_group_ratio=config.num_attention_heads // config.num_key_value_heads, prefer_packed_prefill=prefer_packed and not sliding_window, packed_window_shape=packed_window_shape, allow_fp8_calibration=True, diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py index 553f6253..bbe24f4e 100644 --- a/vllm_rlt/kernels/flashinfer_attention.py +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -25,9 +25,7 @@ def __init__(self, device, dtype, head_dim, block_size): # crashes the process (host SIGFPE) while building the f16 JIT module # on first in-process use; reject instead of shipping that. if dtype is torch.float16: - raise ValueError( - "the flashinfer backend is not validated with float16; use bfloat16" - ) + raise ValueError("the flashinfer backend is not validated with float16; use bfloat16") if dtype is not torch.bfloat16: raise ValueError("flashinfer requires bfloat16") # The XQA JIT module generator rejects anything else at first call; @@ -59,16 +57,14 @@ def __init__(self, device, dtype, head_dim, block_size): "and its lib directory on LD_LIBRARY_PATH for the JIT modules). " "No backend fallback was performed." ) from error - if major != 12: + if (major, minor) != (12, 0): logging.getLogger(__name__).warning( "flashinfer attention is validated on SM120 only; SM%d%d is unvalidated", major, minor, ) - # Persistent, pre-zeroed scratch shared by every call. Allocated on the - # first execution rather than here so backend selection stays free of - # device allocations: engines always profile before CUDA-graph capture, - # so the workspace exists by the time any graph is recorded. + # Allocate scratch on the first nonempty call. Graph warmup initializes + # it before capture, including engines using an explicit KV capacity. self.workspace = None self.info = dict( backend="flashinfer", @@ -80,8 +76,15 @@ def __init__(self, device, dtype, head_dim, block_size): logging.getLogger(__name__).warning("Attention implementation: %s", self.info) def __call__( - self, q, key_cache, value_cache, block_tables, context_lengths, *, - key_scale=None, value_scale=None, + self, + q, + key_cache, + value_cache, + block_tables, + context_lengths, + *, + key_scale=None, + value_scale=None, ): # An empty batch host-crashes (SIGFPE, not an exception) inside the # FlashInfer dispatch; return the same empty shape the other backends do. From 170256d4493238229771c99938c9084b1bbf9b8f Mon Sep 17 00:00:00 2001 From: yanbao1217 <215131680+yanbao1217@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:54:24 +0800 Subject: [PATCH 9/9] fix: tighten XQA selection and validate Ouro on SM120 --- README.md | 2 +- benchmarks/ouro_xqa_throughput.py | 161 +++++++++++++++++++++++ docs/README.md | 2 +- docs/accuracy.md | 3 +- docs/flashinfer.md | 69 ++++++---- docs/launching.md | 6 +- docs/recipes/ouro_xqa_sm120.md | 63 +++++++++ tests/conftest.py | 15 +++ tests/test_backend_selection.py | 65 +++++++++ tests/test_cuda_graph.py | 12 +- tests/test_flashinfer_attention.py | 67 ++++++++-- vllm_rlt/attention/backend.py | 18 +-- vllm_rlt/entrypoints/runtime_args.py | 3 +- vllm_rlt/kernels/flashinfer_attention.py | 38 ++++-- 14 files changed, 460 insertions(+), 64 deletions(-) create mode 100644 benchmarks/ouro_xqa_throughput.py create mode 100644 docs/recipes/ouro_xqa_sm120.md diff --git a/README.md b/README.md index 8df60c27..0e7679e4 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ fixed-scale E4M3 KV. See the [FlashInfer guide](docs/flashinfer.md). | Checkpoint | Implementation | Platforms | Documented validation scope | | --- | --- | --- | --- | -| Ouro-1.4B | Native Ouro | [CUDA](docs/launching.md)
[Ascend](docs/recipes/ouro_ascend.md) | Ascend BF16 full prefill with eager Python execution, paged KV and optional fixed-depth async scheduling. Arbitrary chunked prefill remains unresolved. | +| Ouro-1.4B | Native Ouro | [CUDA](docs/launching.md)
[RTX 5090 XQA recipe](docs/recipes/ouro_xqa_sm120.md)
[Ascend](docs/recipes/ouro_ascend.md) | RTX 5090 XQA runs BF16 and calibrated E4M3 KV. The BF16 GSM8K-87 run is below the accuracy gate. Ascend BF16 full prefill with eager Python execution, paged KV and optional fixed-depth async scheduling. Arbitrary chunked prefill remains unresolved on Ascend. | | Ouro-2.6B | Shared Ouro | [CUDA](docs/launching.md) | Shares the Ouro implementation. [Separate quality and performance qualification](docs/recipes/ouro_thinking.md#6-evidence-and-limitations) remains open. | | [Ouro-1.4B-Thinking](docs/recipes/ouro_thinking.md) | Reuses Ouro | [CUDA](docs/launching.md) | Bounded BF16, fixed-four-loop synchronous basic integration | | [Ouro-2.6B-Thinking](docs/recipes/ouro_thinking.md) | Reuses Ouro | [CUDA](docs/launching.md) | Bounded BF16, fixed-four-loop synchronous basic integration | diff --git a/benchmarks/ouro_xqa_throughput.py b/benchmarks/ouro_xqa_throughput.py new file mode 100644 index 00000000..5bf1b50a --- /dev/null +++ b/benchmarks/ouro_xqa_throughput.py @@ -0,0 +1,161 @@ +"""Matched Ouro-1.4B BF16 eager throughput with per-row prefill on Triton and XQA.""" + +import argparse +import gc +import json +import statistics +import time +from importlib.metadata import version +from pathlib import Path + +import torch + +from benchmarks.preemption import checkpoint_identity +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig +from vllm_rlt.engine.stage_engine import StageEngine +from vllm_rlt.models import OuroForCausalLM + +PROMPT, OUTPUT, PAGE, LOOPS = 512, 128, 16, 4 + + +def drive(engine, prompts, concurrency, params): + """Time initial admission, continuous replacement, prefill and final drain.""" + pending = iter(enumerate(prompts)) + completed = {} + + def admit_next(): + item = next(pending, None) + if item is not None: + index, ids = item + engine.add_request(str(index), ids, params) + + torch.cuda.synchronize() + start = time.perf_counter() + for _ in range(concurrency): + admit_next() + while engine.has_unfinished_requests(): + for output in engine.step(): + if output.finished: + completed[output.request_id] = output + admit_next() + torch.cuda.synchronize() + elapsed = time.perf_counter() - start + if len(completed) != len(prompts) or engine.cache_manager.num_used_blocks: + raise RuntimeError("Incomplete drain or retained KV blocks") + for output in completed.values(): + if ( + len(output.token_ids) != OUTPUT + or output.exit_depths != [LOOPS] * OUTPUT + or output.finish_reason != "length" + ): + raise RuntimeError( + f"Unexpected token count, exit depth or stop for {output.request_id}" + ) + return elapsed + + +def measure(model, backend, concurrency, pair): + blocks = concurrency * LOOPS * ((PROMPT + OUTPUT + PAGE - 1) // PAGE) + engine = StageEngine( + model, + attention_backend=backend, + cache_config=CacheConfig(num_blocks=blocks, block_size=PAGE), + scheduler_config=SchedulerConfig( + max_num_seqs=concurrency, max_num_batched_tokens=PROMPT, prefill_chunk_size=PROMPT + ), + execution_config=ExecutionConfig(async_scheduling=False, packed_prefill=False), + exit_config=ExitConfig("ouro"), + ) + try: + cache = engine.cache_manager + if cache.backend != backend or cache.key_cache.dtype != torch.bfloat16: + raise RuntimeError("Unexpected attention backend or KV dtype") + params = SamplingParams( + max_tokens=OUTPUT, min_loops=LOOPS, max_loops=LOOPS, ignore_eos=True + ) + + def prompts(seed, count): + return torch.randint( + 3, + model.config.vocab_size, + (count, PROMPT), + generator=torch.Generator().manual_seed(seed), + ).tolist() + + drive(engine, prompts(9000, concurrency), concurrency, params) + tokens = 2 * concurrency * OUTPUT + elapsed = drive(engine, prompts(pair, 2 * concurrency), concurrency, params) + return dict( + pair=pair, + backend=backend, + attention=cache.attention_info, + concurrency=concurrency, + kv_blocks=blocks, + output_tokens=tokens, + seconds=elapsed, + output_tokens_per_second=tokens / elapsed, + ) + finally: + engine.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True, help="New result directory") + parser.add_argument("--concurrency", type=int, nargs="+", default=[1, 8, 32]) + parser.add_argument("--pairs", type=int, default=3) + args = parser.parse_args() + if min(args.pairs, *args.concurrency) < 1 or len(set(args.concurrency)) != len( + args.concurrency + ): + parser.error("use positive pair counts and distinct positive concurrency levels") + if torch.cuda.device_count() != 1: + parser.error("select one GPU with CUDA_VISIBLE_DEVICES") + model = OuroForCausalLM.from_pretrained( + str(args.model), device="cuda", dtype=torch.bfloat16 + ).eval() + args.output.mkdir(parents=True, exist_ok=False) + metadata = dict( + model=str(args.model.resolve()), + checkpoint=checkpoint_identity(args.model), + device=torch.cuda.get_device_name(0), + torch=torch.__version__, + cuda=torch.version.cuda, + triton=version("triton"), + flashinfer=version("flashinfer-python"), + input_tokens=PROMPT, + output_tokens=OUTPUT, + loops=LOOPS, + page_size=PAGE, + dtype=str(next(model.parameters()).dtype), + packed_prefill=False, + pairs=args.pairs, + concurrency=args.concurrency, + requests_per_trial="2x concurrency", + ) + (args.output / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n") + medians = [] + with (args.output / "trials.jsonl").open("x") as raw, torch.inference_mode(): + for concurrency in args.concurrency: + rates = {"triton": [], "flashinfer": []} + for pair in range(args.pairs): + order = ("triton", "flashinfer") if pair % 2 == 0 else ("flashinfer", "triton") + for backend in order: + row = measure(model, backend, concurrency, pair) + print(json.dumps(row), file=raw, flush=True) + rates[backend].append(row["output_tokens_per_second"]) + print( + f"C{concurrency} pair {pair} {backend}: {rates[backend][-1]:.1f} tok/s", + flush=True, + ) + gc.collect() + torch.cuda.empty_cache() + medians.append( + {"concurrency": concurrency, **{k: statistics.median(v) for k, v in rates.items()}} + ) + (args.output / "medians.json").write_text(json.dumps(medians, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/docs/README.md b/docs/README.md index 59e7f259..f5c1c291 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,7 +24,7 @@ setup on `v0.2.0`. The Ascend guide below uses `main`. | [Self-speculation](async-speculative.md) | Cross-round asynchronous block execution, token pipelines, and acceptance/rejection timelines | | [Asynchronous scheduling](https://github.com/InferMatrixLab/vllm-rlt/pull/30) | CPU/GPU pipelining and single-stream or multi-stream execution | | [FlashAttention](https://github.com/InferMatrixLab/vllm-rlt/pull/30) | FA2/FA3/FA4 installation, hardware selection, and constraints | -| [FlashInfer](flashinfer.md) | XQA decode for SM120: installation, configuration and limitations | +| [FlashInfer](flashinfer.md) | XQA installation, configuration and limitations, with an [Ouro-1.4B RTX 5090 recipe](recipes/ouro_xqa_sm120.md) | | [Cache and scheduling features](https://github.com/InferMatrixLab/vllm-rlt/pull/31) | Prefix reuse, incremental KV, priorities, and preemption | | [Prefill/decode disaggregation](https://github.com/InferMatrixLab/vllm-rlt/pull/31) | Single-host GPU worker pools and NIXL transfer | | [HTTP serving](serving.md) | Device setup, completions API, streaming, and service lifecycle | diff --git a/docs/accuracy.md b/docs/accuracy.md index 1f6e638a..12086add 100644 --- a/docs/accuracy.md +++ b/docs/accuracy.md @@ -215,7 +215,8 @@ python -m benchmarks.gsm8k compare --reference "$RESULTS/triton" \ On RTX 5090 the matched BF16 runs scored **Triton 62/87 and FlashInfer 58/87**. The stored HF reference scored 59/87. The XQA run completed and failed the one-percentage-point gate. Both `run` and `compare` write their results before -returning a failing gate status. See the [per-question results](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass). +returning a failing gate status. See the [per-question results](flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass) +and the [RTX 5090 recipe with matched throughput](recipes/ouro_xqa_sm120.md). Dataset: [GSM8K](https://huggingface.co/datasets/openai/gsm8k). The [Ouro evaluation settings](https://arxiv.org/html/2510.25741v5#A3.T16) do not diff --git a/docs/flashinfer.md b/docs/flashinfer.md index 3e4fc2f0..7d76cae5 100644 --- a/docs/flashinfer.md +++ b/docs/flashinfer.md @@ -2,9 +2,9 @@ The `flashinfer` backend runs paged decode attention through FlashInfer's XQA kernels (`flashinfer-python >= 0.7.0`, `trtllm_batch_decode_with_kv_cache`, -`backend="xqa"`). It is the validated attention path for NVIDIA consumer -Blackwell (SM120, e.g. RTX 5090), where the pinned FlashAttention releases -reject paged KV. +`backend="xqa"`). The RTX 5090 (SM120) runs this path with paged KV. +The [GSM8K-87 results](#accuracy-note-gsm8k-87-single-greedy-pass) give its +current model accuracy. ## Scope @@ -23,6 +23,7 @@ reject paged KV. - `--block-size` must be one of `16, 32, 64, 128` (compiled XQA page-size variants) and `head_dim` must be divisible by 16 within `[16, 512]`. For `head_dim > 256`, XQA requires at most 16 query heads per KV head. + Automatic selection skips XQA if the caller does not know that ratio. ## Installation and runtime requirements @@ -30,21 +31,20 @@ reject paged KV. pip install -e ".[flashinfer]" ``` -The XQA kernels are compiled just in time on first use, which imposes two -environment requirements beyond the package install: - -1. **A CUDA toolkit with `nvcc >= 12.9` reachable via `CUDA_HOME`.** SM120 - kernels are built for the `compute_120f` architecture family, which needs - CUDA 12.9 or newer. Without `nvcc`, startup falls back to comparing against - the CUDA version PyTorch was built with, and SM 12.x devices are rejected - with `SM 12.x requires CUDA >= 12.9`. -2. **That toolkit's `lib` directory on `LD_LIBRARY_PATH`.** The compiled - modules link `libcudart.so.13`; pip-installed toolkits keep it outside the - default loader path. With the pip toolkit layout - (`nvidia-cuda-nvcc`/`nvidia-cuda-runtime`/`nvidia-cuda-cccl`/...), the - unified tree lives under `site-packages/nvidia/cu13` and may need - `lib64/libcudart.so` and `lib64/stubs/libcuda.so` developer symlinks, which - the wheels do not ship. +Set `CUDA_HOME` to the toolkit that supplies `bin/nvcc` for the first JIT +build. The dynamic loader must be able to find that toolkit's CUDA runtime. +For a non-system toolkit, add its library directory to `LD_LIBRARY_PATH`. + +| FlashInfer on SM120 | CUDA toolkit used by the XQA JIT | +| --- | --- | +| `0.7.0.post1` | Selects `compute_120f`, which requires CUDA 12.9 or newer. | +| `0.7.5.post1` | Builds `sm_120a` with CUDA 12.8 and selects `compute_120f` with CUDA 12.9 or newer. The CUDA 12.8 build links `libcudart.so.12`. | + +At startup the adapter checks whether the installed FlashInfer compilation +context includes SM120 and whether the toolkit supports the selected target. +This also applies to explicit `FLASHINFER_CUDA_ARCH_LIST` overrides. +An incompatible target is reported immediately for +explicit selection. With `auto`, selection continues to the next backend. The first call on a machine compiles for a few seconds and caches under `~/.cache/flashinfer///`; later calls, including CUDA @@ -52,15 +52,15 @@ Graph capture warmups, reuse the cache. ## Running -```bash -vllm-rlt --model "$MODEL" --revision "$REVISION" --prompt "What is 2 + 2?" \ - --device cuda --dtype bfloat16 --attention-backend flashinfer -``` +The [Ouro-1.4B RTX 5090 recipe](recipes/ouro_xqa_sm120.md) covers the pinned +checkpoint, BF16 and calibrated E4M3 launch options, and the measured BF16 +accuracy and throughput. The adapter holds one 128 MiB zero-initialized workspace for the kernel's scratch and softmax statistics. The first nonempty call allocates it and later -calls reuse it. Each call still prepares an output tensor, page table and -sequence lengths. Padded block-table columns are +calls reuse it. The adapter makes a dense copy only when Q has non-contiguous +strides. Each call prepares an output tensor, page table and sequence lengths. +Padded block-table columns are clamped non-negative before the call: the engine produces `-1` padding on the synchronous path, `0` on the asynchronous path, and stale-but-valid ids in CUDA Graph replay beyond the current width. The kernel bounds reads by @@ -83,8 +83,12 @@ The RTX 5090 GSM8K run below used the Ouro-1.4B checkpoint. The GPU regression tests use a tiny Ouro model for cross-backend comparisons of tokens and prescribed exit depths in synchronous, asynchronous and multi-stream runs. The graph tests compare eager execution and replay within each backend. -Attention operator tests compare numerical outputs against a paged reference -with tolerances. +Operator tests compare XQA with FP32 paged attention and check identical +results under a permutation of rows. Ouro-1.4B has 16 Q heads, 16 KV heads +and head dimension 128. With page size 16 and 1,025–1,031 visible tokens, +reducing a four-row batch to two rows changed the XQA BF16 output by up to +`0.001953125` on the RTX 5090. XQA's KV split count depends on batch size. +The tests also cover a separate 16-Q/4-KV grouped-query configuration. ## Accuracy note (GSM8K-87, single greedy pass) @@ -92,7 +96,11 @@ At commit `cd368ce` on RTX 5090, both native backends used Ouro-1.4B, BF16 weights and KV, page size 16, four fixed loops, greedy decoding, per-row prefill and the frozen strict scorer. FlashInfer `0.7.5.post1` scored **58/87** and Triton **62/87**. The generated token sequences matched on **61/87**. -All generated tokens exited at depth four. +All generated tokens exited at depth four. On 2026-11-22 the same frozen run +with dense query normalization and the SM120 JIT selection fix reproduced +all 87 token sequences for each respective backend. The stored HF reference +scored 59/87. One question out of 87 exceeds the allowed one-percentage-point +regression, so XQA still fails the accuracy gate. | Question | XQA final answer | Triton final answer | Strict scoring | | --- | --- | --- | --- | @@ -104,6 +112,9 @@ All generated tokens exited at depth four. At the first differing attention row on question 203, rounding the unnormalized softmax weights to BF16 in both numerator and denominator reproduced all 2,048 XQA output components. The Triton row matched the FP64 reference rounded to BF16. -This experiment identifies the rounding behavior at that row. The three -currency-format losses were established by replaying the scorer. +All 1,632 XQA calls through the first divergent token used contiguous Q. +Forcing a single KV split in a diagnostic reproduced the same two-key row, +including its 151 differences from the BF16-rounded FP64 reference, and the +same fifteenth token (`5`). The three currency-format losses were established +by replaying the strict scorer. See the [matched benchmark commands and accuracy gate](accuracy.md#attention-backend-runs). diff --git a/docs/launching.md b/docs/launching.md index 817f459a..72b85ece 100644 --- a/docs/launching.md +++ b/docs/launching.md @@ -245,7 +245,11 @@ depths, and the finish reason. Use `--attention-backend auto` with the inference CLI or the local HTTP server to select a compatible implementation at startup. Auto tries FA4, FA3, FA2, FlashInfer (SM120 only), Triton, then Torch, checking hardware, dtype, head dimension, block size, installed -packages, and execution requirements. CPU uses Torch. For example, on an RTX +packages, and execution requirements. On SM120 the FlashInfer JIT must include +the device target. When `head_dim > 256`, automatic XQA selection also requires a +known ratio of at most 16 query heads per KV head. The +[Ouro-1.4B RTX 5090 recipe](recipes/ouro_xqa_sm120.md) includes a +four-loop launch and the matched benchmark configuration. CPU uses Torch. For example, on an RTX 4090, the default 16-token block size rules out FA2's 256-token page requirement; auto selects Triton if it is installed. diff --git a/docs/recipes/ouro_xqa_sm120.md b/docs/recipes/ouro_xqa_sm120.md new file mode 100644 index 00000000..ffac80aa --- /dev/null +++ b/docs/recipes/ouro_xqa_sm120.md @@ -0,0 +1,63 @@ +# Ouro-1.4B on RTX 5090 with FlashInfer XQA + +## Setup and launch + +Use one NVIDIA RTX 5090 (SM120), the BF16 Ouro-1.4B checkpoint and page size +16. FlashInfer `0.7.5.post1` supports SM120 with CUDA 12.8 or newer. +Set `CUDA_HOME` to the toolkit that will compile XQA. See the +[toolkit and JIT requirements](../flashinfer.md#installation-and-runtime-requirements). + +```bash +export CUDA_VISIBLE_DEVICES=0 +export MODEL=/path/to/Ouro-1.4B +export RESULTS=/path/to/results +mkdir -p "$RESULTS" +python -m pip install -e '.[flashinfer]' 'flashinfer-python==0.7.5.post1' +hf download ByteDance/Ouro-1.4B --revision 574fa66cb8bf5abdc979642d01cf2b79b16bfab1 \ + --local-dir "$MODEL" +vllm-rlt --model "$MODEL" --device cuda --dtype bfloat16 --attention-backend flashinfer \ + --block-size 16 --no-packed-prefill --min-loops 4 --max-loops 4 --max-tokens 16 \ + --prompt "What is 2 + 2?" +``` + +The startup record identifies the selected kernel as `xqa`, its FlashInfer +version and page size. To exercise the calibrated E4M3 KV cache, add +`--kv-cache-dtype fp8_e4m3`. Q and output stay BF16. The accuracy and +throughput runs below use BF16 KV. + +## Accuracy + +Use the [frozen GSM8K-87 protocol](../accuracy.md#prepare-and-run-the-default-case) +and the [matched native commands](../accuracy.md#attention-backend-runs). +Both backends use four loops, greedy generation, per-row prefill and the same +strict scorer. A failed gate writes the run summary and returns a nonzero exit +status. The [per-question results](../flashinfer.md#accuracy-note-gsm8k-87-single-greedy-pass) +record the numerical and answer-format losses. + +## Matched throughput + +```bash +python -m benchmarks.ouro_xqa_throughput --model "$MODEL" \ + --output "$RESULTS/throughput" --concurrency 1 8 32 --pairs 3 +``` + +Each trial processes twice the concurrency in closed-loop replacement, with +512 prompt tokens and 128 generated tokens per request, four loops, eager +execution and per-row prefill. One full wave at the measured concurrency warms +each backend before each timed trial. +Timing covers initial admission, prefill, replacement and drain. Backend order +alternates across pairs. The result directory contains the checkpoint hashes +and package versions in `metadata.json`, the individual timings and token counts +in `trials.jsonl` and median output tokens per second in `medians.json`. + +On 2026-11-22, the RTX 5090 ran PyTorch `2.13.0+cu130`, +Triton `3.7.1` and FlashInfer `0.7.5.post1` with NVIDIA driver +`580.76.05`. Values are median output tokens/s with the three-trial +range in parentheses. All 18 timed trials completed with the expected count +and exit depths, producing 62,976 output tokens in total. + +| Concurrent requests | Triton | FlashInfer XQA | XQA vs Triton | +| ---: | ---: | ---: | ---: | +| 1 | 15.9 (15.8–16.2) | 16.9 (16.7–16.9) | +6.2% | +| 8 | 108.2 (108.1–108.2) | 115.7 (112.2–116.1) | +6.9% | +| 32 | 317.3 (313.9–320.0) | 334.0 (330.6–334.3) | +5.3% | diff --git a/tests/conftest.py b/tests/conftest.py index 6981e499..421eff65 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,24 @@ import os +from importlib.metadata import PackageNotFoundError, version import pytest import torch +@pytest.fixture(scope="session") +def flashinfer_gpu(): + if ( + not torch.cuda.is_available() + or torch.version.hip + or torch.cuda.get_device_capability()[0] not in (9, 10, 12) + ): + pytest.skip("XQA requires NVIDIA SM9x, SM10x or SM12x") + try: + version("flashinfer-python") + except PackageNotFoundError: + pytest.skip("install the flashinfer extra to run XQA GPU tests") + + def pytest_addoption(parser): parser.addoption( "--run-gpu", action="store_true", help="Run CUDA tests on explicitly selected devices" diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index dd788885..0c98fb77 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -46,6 +46,12 @@ def import_module(name): if "flashinfer" not in installed: raise ImportError("flashinfer is not installed") return SimpleNamespace(trtllm_batch_decode_with_kv_cache=lambda *args, **kwargs: None) + if name == "flashinfer.compilation_context": + return SimpleNamespace( + CompilationContext=lambda: SimpleNamespace(TARGET_CUDA_ARCHS={(12, "0f")}) + ) + if name == "flashinfer.jit.cpp_ext": + return SimpleNamespace(is_cuda_version_at_least=lambda version: True) return original_import(name) monkeypatch.setattr(flash_attention.importlib, "import_module", import_module) @@ -219,12 +225,71 @@ def test_auto_selection_constraints( def test_flashinfer_wide_head_group_limit(packages, monkeypatch): monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (12, 0)) args = (torch.device("cuda"), torch.bfloat16, 512, 16) + assert create_backend("auto", *args).info["selected_backend"] == "torch" + assert create_backend("flashinfer", *args).info["selected_backend"] == "flashinfer" + assert ( + create_backend("auto", *args, head_group_ratio=16).info["selected_backend"] == "flashinfer" + ) + assert ( + create_backend("auto", args[0], args[1], 256, 16).info["selected_backend"] == "flashinfer" + ) assert create_backend("flashinfer", *args, head_group_ratio=16).info["kernel"] == "xqa" with pytest.raises(ValueError, match="head_group_ratio <= 16"): create_backend("flashinfer", *args, head_group_ratio=32) assert create_backend("auto", *args, head_group_ratio=32).info["selected_backend"] == "torch" +@pytest.mark.parametrize("targets", [set(), {(9, "0a"), (12, "1a")}, {(12, "0a")}]) +def test_flashinfer_selection_requires_a_jit_target_for_the_device(packages, monkeypatch, targets): + from vllm_rlt.kernels import flashinfer_attention + + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (12, 0)) + original_import = flashinfer_attention.importlib.import_module + + def import_module(name): + if name == "flashinfer.compilation_context": + return SimpleNamespace( + CompilationContext=lambda: SimpleNamespace(TARGET_CUDA_ARCHS=targets) + ) + return original_import(name) + + monkeypatch.setattr(flashinfer_attention.importlib, "import_module", import_module) + args = (torch.device("cuda"), torch.bfloat16, 128, 16) + selected = create_backend("auto", *args) + if (12, "0a") in targets: + assert selected.info["selected_backend"] == "flashinfer" + else: + assert selected.info["selected_backend"] == "triton" + assert "no XQA JIT target for SM120" in selected.info["selection_reason"] + with pytest.raises(ValueError, match="no XQA JIT target for SM120"): + create_backend("flashinfer", *args) + + +@pytest.mark.parametrize("reject_at_import", [True, False], ids=["import", "forced-120f"]) +def test_flashinfer_jit_toolkit_failure_before_first_launch( + packages, monkeypatch, reject_at_import +): + from vllm_rlt.kernels import flashinfer_attention + + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device: (12, 0)) + original_import = flashinfer_attention.importlib.import_module + + def import_module(name): + if name == "flashinfer.decode" and reject_at_import: + raise RuntimeError("SM 12.x requires CUDA >= 12.9") + if name == "flashinfer.jit.cpp_ext": + return SimpleNamespace(is_cuda_version_at_least=lambda minimum: minimum == "12.8") + return original_import(name) + + monkeypatch.setattr(flashinfer_attention.importlib, "import_module", import_module) + args = (torch.device("cuda"), torch.bfloat16, 128, 16) + selected = create_backend("auto", *args) + assert selected.info["selected_backend"] == "triton" + assert "CUDA >= 12.9" in selected.info["selection_reason"] + with pytest.raises(ValueError, match="CUDA >= 12.9"): + create_backend("flashinfer", *args) + + @pytest.mark.parametrize("sm", [(9, 0), (12, 1)]) def test_explicit_flashinfer_opt_in_outside_sm120(packages, monkeypatch, caplog, sm): caplog.set_level(logging.WARNING, logger="vllm_rlt.kernels.flashinfer_attention") diff --git a/tests/test_cuda_graph.py b/tests/test_cuda_graph.py index 3c6e0599..cb52be2c 100644 --- a/tests/test_cuda_graph.py +++ b/tests/test_cuda_graph.py @@ -11,6 +11,14 @@ from vllm_rlt.models import OuroForCausalLM +@pytest.fixture +def backend(request): + name = request.param + if name == "flashinfer": + request.getfixturevalue("flashinfer_gpu") + return name + + def test_cuda_graph_validation(): with pytest.raises(ValueError, match="positive"): ExecutionConfig(cuda_graph_max_graphs=0) @@ -23,7 +31,7 @@ def test_cuda_graph_validation(): @pytest.mark.gpu -@pytest.mark.parametrize("backend", ["triton", "flash_attn", "flashinfer"]) +@pytest.mark.parametrize("backend", ["triton", "flash_attn", "flashinfer"], indirect=True) @pytest.mark.parametrize("mode", ["sync", "async", "multi"]) @pytest.mark.parametrize("layout", ["last_exited", "shared"]) @pytest.mark.parametrize("static", [False, True]) @@ -73,7 +81,7 @@ def test_graph_replay_matches_eager_and_reuses_requests(backend, mode, layout, s @pytest.mark.gpu -@pytest.mark.parametrize("backend", ["triton", "flashinfer"]) +@pytest.mark.parametrize("backend", ["triton", "flashinfer"], indirect=True) def test_graph_cache_limit_fallback_and_abort(backend): torch.manual_seed(19) model = OuroForCausalLM(tiny_ouro_config(head_dim=64)).to("cuda", torch.bfloat16) diff --git a/tests/test_flashinfer_attention.py b/tests/test_flashinfer_attention.py index 51c1f770..37a14f99 100644 --- a/tests/test_flashinfer_attention.py +++ b/tests/test_flashinfer_attention.py @@ -6,6 +6,7 @@ from tests.helpers import tiny_ouro_config from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig from vllm_rlt.attention import BackendCapabilities, create_backend +from vllm_rlt.core.kv_cache_manager import KVCacheManager from vllm_rlt.engine.llm_engine import LLMEngine from vllm_rlt.kernels.flashinfer_attention import FlashInferPagedAttention from vllm_rlt.kernels.paged_attention import torch_paged_attention @@ -77,7 +78,7 @@ def test_kernel_call_explicitly_selects_xqa(monkeypatch): attention = FlashInferPagedAttention.__new__(FlashInferPagedAttention) attention.workspace = workspace attention.kernel = Mock() - q = SimpleNamespace(shape=(2, 4, 64)) + q = torch.empty(2, 4, 64) keys = SimpleNamespace(shape=(8, 16, 2, 64), dtype=torch.bfloat16) values = SimpleNamespace(shape=keys.shape, dtype=keys.dtype) tables = Mock(shape=(2, 3)) @@ -132,7 +133,7 @@ def test_xqa_fixed_fp8_call_on_cpu(): @pytest.mark.gpu -def test_backend_contract_anchors(): +def test_backend_contract_anchors(flashinfer_gpu): attention = FlashInferPagedAttention(torch.device("cuda"), torch.bfloat16, 128, 16) assert attention.info["backend"] == "flashinfer" assert attention.info["package"] == "flashinfer-python" @@ -150,7 +151,7 @@ def test_backend_contract_anchors(): @pytest.mark.gpu @pytest.mark.parametrize("heads", [2, 4]) -def test_ragged_strided_paged_attention_with_zero_length_row(heads): +def test_ragged_strided_paged_attention_with_zero_length_row(heads, flashinfer_gpu): torch.manual_seed(9) # Layer slicing leaves a non-contiguous block stride, as in the real cache. keys = torch.randn(12, 3, 16, 2, 128, device="cuda", dtype=torch.bfloat16)[:, 1] @@ -171,7 +172,35 @@ def test_ragged_strided_paged_attention_with_zero_length_row(heads): @pytest.mark.gpu -def test_padding_states_are_invisible(): +def test_cache_attend_accepts_strided_query_rows(flashinfer_gpu): + cache = KVCacheManager( + num_layers=1, + num_kv_heads=16, + head_dim=128, + num_blocks=2, + block_size=16, + max_loops=1, + device="cuda", + dtype=torch.bfloat16, + backend="flashinfer", + ) + for request in ("a", "b"): + assert cache.allocate(request, 2) + backing = torch.ones(4, 16, 128, dtype=torch.bfloat16, device="cuda") + backing[1::2].fill_(-1) + values = torch.zeros_like(backing) + values[1::2].fill_(1) + cache.write(0, ["a", "a", "b", "b"], [0] * 4, [0, 1, 0, 1], -backing, values) + q = backing[::2] + assert not q.is_contiguous() + dense = cache.attend(0, ["a", "b"], [0, 0], [1, 1], q.contiguous()) + from_view = cache.attend(0, ["a", "b"], [0, 0], [1, 1], q) + assert torch.equal(dense, torch.ones_like(dense)) + assert torch.equal(from_view, dense) + + +@pytest.mark.gpu +def test_padding_states_are_invisible(flashinfer_gpu): torch.manual_seed(11) keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] @@ -189,24 +218,40 @@ def test_padding_states_are_invisible(): @pytest.mark.gpu -def test_flashinfer_decode_same_queries_match_across_batch_sizes(): +@pytest.mark.parametrize("kv_heads", [4, 16], ids=["gqa", "ouro-1.4b"]) +def test_flashinfer_decode_same_queries_across_batch_sizes(kv_heads, flashinfer_gpu): generator = torch.Generator(device="cuda").manual_seed(1234) dtype = torch.bfloat16 - # Ouro geometry and long enough prefixes to exercise any KV split selection. - keys = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] - values = torch.randn(260, 2, 16, 4, 128, generator=generator, device="cuda", dtype=dtype)[:, 1] + # Keep the cache's layer stride. Ouro-1.4B uses 16 Q heads and 16 KV heads. + keys = torch.randn(260, 2, 16, kv_heads, 128, generator=generator, device="cuda", dtype=dtype)[ + :, 1 + ] + values = torch.randn( + 260, 2, 16, kv_heads, 128, generator=generator, device="cuda", dtype=dtype + )[:, 1] q = torch.randn(4, 16, 128, generator=generator, device="cuda", dtype=dtype) tables = torch.arange(260, device="cuda", dtype=torch.int32).view(4, 65) lengths = torch.tensor([1025, 1029, 1025, 1031], device="cuda", dtype=torch.int32) attention = FlashInferPagedAttention(q.device, dtype, 128, 16) together = attention(q, keys, values, tables, lengths) + reference = torch_paged_attention(q.float(), keys, values, tables, lengths) + # Same BF16 operator tolerances as the ragged paged-reference test above. + torch.testing.assert_close(together.float(), reference, atol=0.015, rtol=0.02) + assert torch.equal(attention(q, keys, values, tables, lengths), together) + perm = [3, 0, 2, 1] + assert torch.equal( + attention(q[perm], keys, values, tables[perm], lengths[perm]), together[perm] + ) for rows in ([2, 3], [3, 0], [1]): separate = attention(q[rows], keys, values, tables[rows], lengths[rows]) - torch.testing.assert_close(separate, together[rows], rtol=0, atol=0) + torch.testing.assert_close(separate.float(), reference[rows], atol=0.015, rtol=0.02) + if kv_heads == 4: + # The original GQA regression is bitwise stable for these inputs. + assert torch.equal(separate, together[rows]) @pytest.mark.gpu -def test_graph_replay_updates_buffers(): +def test_graph_replay_updates_buffers(flashinfer_gpu): torch.manual_seed(5) keys = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] values = torch.randn(24, 3, 16, 2, 64, device="cuda", dtype=torch.bfloat16)[:, 1] @@ -237,7 +282,7 @@ def test_graph_replay_updates_buffers(): @pytest.mark.gpu @pytest.mark.parametrize("layout", ["last_exited", "shared"]) @pytest.mark.parametrize("static", [False, True]) -def test_flashinfer_sync_async_mixed_depths(layout, static): +def test_flashinfer_sync_async_mixed_depths(layout, static, flashinfer_gpu): torch.manual_seed(123) config = tiny_ouro_config(head_dim=64) model = OuroForCausalLM(config).to(device="cuda", dtype=torch.bfloat16) diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index a0b7c9c1..f3e52dde 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -120,7 +120,7 @@ def backend_capabilities(implementation) -> BackendCapabilities: def _auto_flashinfer_supported(device) -> bool: - """Gate automatic FlashInfer selection to the validated SM120 target. + """Limit automatic FlashInfer selection to the tested SM120 target. Other architectures the kernel accepts remain reachable through explicit `--attention-backend flashinfer` opt-in; auto keeps its pre-FlashInfer @@ -230,16 +230,16 @@ def create_backend( and candidate == "flashinfer" and not _auto_flashinfer_supported(device) ): - skipped.append("flashinfer: automatic selection is validated on SM120 only") + skipped.append("flashinfer: automatic selection is limited to SM120") continue try: - if ( - candidate == "flashinfer" - and head_dim > 256 - and head_group_ratio is not None - and head_group_ratio > 16 - ): - raise ValueError("XQA with head_dim > 256 requires head_group_ratio <= 16") + if candidate == "flashinfer" and head_dim > 256: + if backend == "auto" and head_group_ratio is None: + raise ValueError( + "XQA auto selection needs a known head_group_ratio for head_dim > 256" + ) + if head_group_ratio is not None and head_group_ratio > 16: + raise ValueError("XQA with head_dim > 256 requires head_group_ratio <= 16") implementation = _create_explicit( candidate, device, diff --git a/vllm_rlt/entrypoints/runtime_args.py b/vllm_rlt/entrypoints/runtime_args.py index 679a198c..4e3d6987 100644 --- a/vllm_rlt/entrypoints/runtime_args.py +++ b/vllm_rlt/entrypoints/runtime_args.py @@ -49,7 +49,8 @@ def add_runtime_args(parser): "--kv-cache-dtype", choices=["auto", "fp8_e4m3"], default="auto", - help="FP8 KV: per-vector scales on Torch/Triton, startup calibration on FA4", + help="FP8 KV uses per-vector scales on Torch/Triton and a startup-calibrated " + "scale on supported FA4 configurations and FlashInfer XQA on SM120", ) parser.add_argument("--gpu-memory-utilization", type=float, default=0.9) parser.add_argument("--kv-cache-memory-bytes", type=int) diff --git a/vllm_rlt/kernels/flashinfer_attention.py b/vllm_rlt/kernels/flashinfer_attention.py index bbe24f4e..0b4a5348 100644 --- a/vllm_rlt/kernels/flashinfer_attention.py +++ b/vllm_rlt/kernels/flashinfer_attention.py @@ -1,10 +1,8 @@ """FlashInfer XQA paged decode kernels; no packed prefill in this backend. Decode uses independent single-query rows, exactly like the Triton path. -SM120 (RTX 50) is the validated target; other supported majors are accepted -but unvalidated. Requires a CUDA toolkit with nvcc >= 12.9 visible through -CUDA_HOME for the just-in-time compiled kernels, and that toolkit's lib -directory on LD_LIBRARY_PATH. +SM120 (RTX 50) is the tested target. The installed FlashInfer version and +CUDA toolkit determine which architectures the XQA JIT can build. """ import importlib @@ -17,6 +15,23 @@ FLASHINFER_WORKSPACE_BYTES = 128 * 1024 * 1024 +def _check_sm120_jit_target(package_version): + # Use the same architecture list as XQA's JIT. Older releases can import + # normally with an empty list when nvcc cannot target the current GPU. + context = importlib.import_module("flashinfer.compilation_context").CompilationContext() + targets = context.TARGET_CUDA_ARCHS + if not {(12, "0"), (12, "0a"), (12, "0f")}.intersection(targets): + raise ValueError( + f"FlashInfer {package_version} has no XQA JIT target for SM120 " + f"(targets: {sorted(targets)}). Check CUDA_HOME and FLASHINFER_CUDA_ARCH_LIST." + ) + # An explicitly suffixed FLASHINFER_CUDA_ARCH_LIST bypasses FlashInfer's + # toolkit check. All requested targets are passed to nvcc. + minimum = "12.9" if (12, "0f") in targets else "12.8" + if not importlib.import_module("flashinfer.jit.cpp_ext").is_cuda_version_at_least(minimum): + raise ValueError(f"Configured FlashInfer XQA target for SM120 requires CUDA >= {minimum}") + + class FlashInferPagedAttention: def __init__(self, device, dtype, head_dim, block_size): if device.type != "cuda" or torch.version.hip: @@ -50,16 +65,21 @@ def __init__(self, device, dtype, head_dim, block_size): importlib.import_module("flashinfer.decode"), "trtllm_batch_decode_with_kv_cache", ) + if (major, minor) == (12, 0): + _check_sm120_jit_target(package_version) except (ImportError, AttributeError, PackageNotFoundError) as error: raise ImportError( "install flashinfer with: pip install 'flashinfer-python>=0.7.0' " - "(a CUDA toolkit with nvcc >= 12.9 must be reachable via CUDA_HOME, " - "and its lib directory on LD_LIBRARY_PATH for the JIT modules). " - "No backend fallback was performed." + "and configure a compatible CUDA toolkit for its XQA JIT" + ) from error + except RuntimeError as error: + # FlashInfer can also initialize its compilation context at import. + raise ValueError( + f"FlashInfer XQA initialization on SM{major}{minor} failed: {error}" ) from error if (major, minor) != (12, 0): logging.getLogger(__name__).warning( - "flashinfer attention is validated on SM120 only; SM%d%d is unvalidated", + "flashinfer attention was tested on SM120; SM%d%d is unvalidated", major, minor, ) @@ -115,6 +135,8 @@ def __call__( self.workspace = torch.zeros( FLASHINFER_WORKSPACE_BYTES, dtype=torch.uint8, device=q.device ) + # XQA takes a raw query pointer and assumes dense [row, head, dim] strides. + q = q.contiguous() out = torch.empty_like(q) self.kernel( q,