diff --git a/README.md b/README.md
index cde38840..0e7679e4 100644
--- a/README.md
+++ b/README.md
@@ -139,11 +139,14 @@ 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).
+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
| 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/gsm8k.py b/benchmarks/gsm8k.py
index d1ecc7f0..f4027088 100644
--- a/benchmarks/gsm8k.py
+++ b/benchmarks/gsm8k.py
@@ -604,15 +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)
+ generator = Generator(
+ 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]
@@ -660,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]
@@ -699,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"],
@@ -787,6 +808,16 @@ 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"],
+ 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(
"--exit-threshold",
@@ -801,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 15d57165..d038596c 100644
--- a/benchmarks/gsm8k_backends.py
+++ b/benchmarks/gsm8k_backends.py
@@ -101,18 +101,31 @@ 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=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")
@@ -136,15 +149,19 @@ def __init__(self, backend, model_path, tokenizer, max_length, exit_policy):
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="triton",
+ 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/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 1b933288..f5c1c291 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -24,6 +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 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 fd1f9463..12086add 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.
@@ -193,6 +193,31 @@ 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`
+(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 \
+ --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 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)
+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
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..7d76cae5
--- /dev/null
+++ b/docs/flashinfer.md
@@ -0,0 +1,120 @@
+# 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"`). 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
+
+- 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
+ 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
+ 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
+
+```bash
+pip install -e ".[flashinfer]"
+```
+
+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
+Graph capture warmups, reuse the cache.
+
+## Running
+
+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. 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
+`seq_lens`, so all three padding states stay invisible.
+
+## Choosing between Triton and FlashInfer
+
+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
+
+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.
+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)
+
+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. 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 |
+| --- | --- | --- | --- |
+| 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.
+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 2aad2973..72b85ece 100644
--- a/docs/launching.md
+++ b/docs/launching.md
@@ -244,8 +244,12 @@ 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
-packages, and execution requirements. CPU uses Torch. For example, on an RTX
+FlashInfer (SM120 only), Triton, then Torch, checking hardware, dtype, head dimension, block size, installed
+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.
@@ -260,7 +264,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/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/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/pyproject.toml b/pyproject.toml
index 067040f1..ea101847 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/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 cc90cf90..0c98fb77 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,23 @@ 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)
+ 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)
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
@@ -89,6 +101,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")
@@ -173,7 +195,18 @@ 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, 1), torch.bfloat16, 128, 16, (), "triton"),
+ ((12, 0), torch.bfloat16, 128, 16, ("flashinfer",), "triton"),
((7, 5), torch.float16, 128, 256, (), "torch"),
],
)
@@ -189,6 +222,85 @@ def test_auto_selection_constraints(
assert backend_capabilities(selected).packed_prefill
+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")
+ 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
+ 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 +320,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..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"])
+@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,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"], 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)
engine = LLMEngine(
@@ -89,7 +98,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..37a14f99
--- /dev/null
+++ b/tests/test_flashinfer_attention.py
@@ -0,0 +1,328 @@
+"""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.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
+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, float8_e4m3fn=object())
+ monkeypatch.setitem(FlashInferPagedAttention.__call__.__globals__, "torch", fake_torch)
+ attention = FlashInferPagedAttention.__new__(FlashInferPagedAttention)
+ attention.workspace = workspace
+ attention.kernel = Mock()
+ 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))
+ 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,
+ bmm2_scale=1.0,
+ 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()
+
+
+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(flashinfer_gpu):
+ 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"
+ # 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,
+ fp8_kv_static=torch.cuda.get_device_capability() == (12, 0),
+ )
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("heads", [2, 4])
+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]
+ 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_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]
+ 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
+@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
+ # 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.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(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]
+ 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, flashinfer_gpu):
+ 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/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 c5ebdbfa..f3e52dde 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,
@@ -110,19 +111,32 @@ 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:
+ """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
+ fallback behavior everywhere else.
+ """
+ if device.type != "cuda" or torch.version.hip:
+ return False
+ return torch.cuda.get_device_capability(device) == (12, 0)
+
+
def validate_backend_name(backend: str, *, device_type: str | None = None) -> None:
if device_type == "npu" and backend not in ("torch", "ascend_eager"):
raise ValueError(
"NPU execution requires explicit attention_backend='torch' or 'ascend_eager'"
)
- if backend not in {"auto", "torch", "triton", "ascend_eager", *FLASH_BACKENDS}:
+ if backend not in {"auto", "torch", "triton", "ascend_eager", "flashinfer", *FLASH_BACKENDS}:
raise ValueError("unknown attention backend")
@@ -162,6 +176,10 @@ 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)
+ 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(
@@ -182,11 +200,13 @@ 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,
) -> 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;
@@ -205,7 +225,21 @@ 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 limited to SM120")
+ continue
try:
+ 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,
@@ -254,7 +288,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/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/entrypoints/cli.py b/vllm_rlt/entrypoints/cli.py
index 499cda14..946cad12 100644
--- a/vllm_rlt/entrypoints/cli.py
+++ b/vllm_rlt/entrypoints/cli.py
@@ -72,6 +72,7 @@ def main():
"auto",
"torch",
"triton",
+ "flashinfer",
"flash_attn",
"flash_attn_2",
"flash_attn_3",
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/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py
index c7fc3c84..db9e9b38 100644
--- a/vllm_rlt/entrypoints/serve.py
+++ b/vllm_rlt/entrypoints/serve.py
@@ -93,6 +93,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..0b4a5348
--- /dev/null
+++ b/vllm_rlt/kernels/flashinfer_attention.py
@@ -0,0 +1,161 @@
+"""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 tested target. The installed FlashInfer version and
+CUDA toolkit determine which architectures the XQA JIT can build.
+"""
+
+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
+
+
+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:
+ 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}")
+ self.supports_fp8_static = (major, minor) == (12, 0)
+ try:
+ package_version = version("flashinfer-python")
+ self.kernel = getattr(
+ 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' "
+ "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 was tested on SM120; SM%d%d is unvalidated",
+ major,
+ minor,
+ )
+ # 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",
+ 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,
+ *,
+ 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
+ )
+ # XQA takes a raw query pointer and assumes dense [row, head, dim] strides.
+ q = q.contiguous()
+ 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=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
+ # HND and silently misreads NHD data.
+ kv_layout="NHD",
+ backend="xqa",
+ )
+ return out