Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)<br>[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)<br>[RTX 5090 XQA recipe](docs/recipes/ouro_xqa_sm120.md)<br>[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 |
Expand Down
58 changes: 46 additions & 12 deletions benchmarks/gsm8k.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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"],
Expand Down Expand Up @@ -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",
Expand All @@ -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)
Expand Down
25 changes: 21 additions & 4 deletions benchmarks/gsm8k_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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)
Expand Down
161 changes: 161 additions & 0 deletions benchmarks/ouro_xqa_throughput.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
27 changes: 26 additions & 1 deletion docs/accuracy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading