From 04f7b29cb8612d03c7831b7897c2821f3461a4c6 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 00:44:12 +0800 Subject: [PATCH 01/12] test(ascend): check fixed-depth device lookahead per loop Signed-off-by: KrystalRay --- tests/test_npu_async.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/test_npu_async.py b/tests/test_npu_async.py index 52ba27de..97919be1 100644 --- a/tests/test_npu_async.py +++ b/tests/test_npu_async.py @@ -121,10 +121,11 @@ def synchronize(self): assert request.generated_token_ids == [] engine.step() assert engine.last_schedule.phase == RequestPhase.PRELUDE - engine.step() - assert engine.last_schedule.phase == RequestPhase.RECURRENT - assert request.loops_done == 4 - assert request.generated_token_ids == [] + for depth in range(1, 5): + engine.step() + assert engine.last_schedule.phase == RequestPhase.RECURRENT + assert request.loops_done == depth + assert request.generated_token_ids == [] assert ticket.device_values.device.type == "npu" finally: ticket.event = real_event From d92154e2ca5162e0aaec9674fc19735b934f2dd6 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 00:44:32 +0800 Subject: [PATCH 02/12] feat(ascend): enable adaptive Ouro decode Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 30 +++++++++--- tests/test_npu_async.py | 84 ++++++++++++++++++++++++++++++++- vllm_rlt/engine/stage_engine.py | 6 +-- 3 files changed, 107 insertions(+), 13 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 3a14d870..29c2b65e 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -1,9 +1,10 @@ # Ouro on Ascend -Run Ouro-1.4B on one Ascend NPU with BF16, greedy decoding and four recurrent -loops. The Python runtime uses Torch's `scaled_dot_product_attention` through -the `ascend_eager` backend, matching HF's SDPA entry point. Torch-NPU selects -the device kernel according to the input shape, mask and hardware. +Run Ouro-1.4B on one Ascend NPU with BF16 and greedy decoding. Decode uses four +recurrent loops by default. The Python runtime uses Torch's +`scaled_dot_product_attention` through the `ascend_eager` backend, matching HF's +SDPA entry point. Torch-NPU selects the device kernel according to the input +shape, mask and hardware. The example enables the optional asynchronous engine plan. ## Prepare the environment and model @@ -88,8 +89,24 @@ curl --fail http://127.0.0.1:8123/v1/completions \ -d '{"model":"ouro","prompt":"The capital of France is","max_tokens":8,"temperature":0,"min_loops":4,"max_loops":4,"exit_threshold":1}' ``` +### Adaptive decode depth + +Ouro on Ascend uses the shared CUDA and ROCm exit policies. Use `--exit-mode ouro` +with synchronous scheduling for the original gate. Use `--exit-mode ouro_delayed` +for the one-round delayed policy, which also supports `--async-scheduling`. +The first output uses all four prefill loops. For subsequent tokens, specify +`min_loops`, `max_loops` and an `exit_threshold` below `1` to +enable the adaptive gate. Decode depth can also be capped with `max_loops` from +`1` to `4`, subject to `min_loops <= max_loops`. Omit `max_loops` to use the +model depth. Keep `temperature=0` on Ascend. + +For example, send `"min_loops": 2, "max_loops": 4, "exit_threshold": 0.5` in +the completion request. Threshold `1` disables gate-driven exits and retains +the requested decode cap. The [shared runtime guide](../runtime.md#reusing-the-trained-ouro-gate-ouro_delayed) +describes how the two policies interpret the gate score. + -## Fixed-depth asynchronous engine plan +## Asynchronous engine plan - **Scheduling.** Stream events track completion and protect buffer and request lifetimes. Decode PRELUDE and each recurrent loop are separate submissions, @@ -107,8 +124,7 @@ curl --fail http://127.0.0.1:8123/v1/completions \ The example uses private, fully reserved `last_exited` KV. Keep graphs, static buffers, padding, prefix caching, incremental KV allocation, preemption, speculation and prefill/decode disaggregation disabled in this configuration. -Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs -and adaptive exit. +Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. ## Performance and correctness diff --git a/tests/test_npu_async.py b/tests/test_npu_async.py index 97919be1..5854066b 100644 --- a/tests/test_npu_async.py +++ b/tests/test_npu_async.py @@ -25,7 +25,7 @@ def test_fixed_depth_decode_keeps_each_loop_schedulable(): assert request.phase == RequestPhase.CODA -def make_engine(model, asynchronous, multi_stream): +def make_engine(model, asynchronous, multi_stream, *, exit_mode=None): return StageEngine( model, attention_backend="ascend_eager", @@ -41,7 +41,7 @@ def make_engine(model, asynchronous, multi_stream): use_uva=False, cuda_graphs=False, ), - exit_config=ExitConfig("ouro_delayed" if asynchronous else "ouro"), + exit_config=ExitConfig(exit_mode or ("ouro_delayed" if asynchronous else "ouro")), ) @@ -93,6 +93,86 @@ def forbidden(*args, **kwargs): engine.close() +@pytest.mark.npu +@pytest.mark.parametrize( + "exit_mode, async_schedule, multi_stream", + [("ouro", False, False), ("ouro_delayed", True, False), ("ouro_delayed", True, True)], + ids=["ouro-sync", "delayed-async-single", "delayed-async-multi"], +) +@torch.inference_mode() +def test_npu_adaptive_exit_then_deeper_decode(monkeypatch, exit_mode, async_schedule, multi_stream): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + recurrent = model.recurrent_prepared + + def alternate_gate(hidden, batch, cache, **kwargs): + hidden, gate = recurrent(hidden, batch, cache, **kwargs) + if gate is not None: + # Decode starts at position 15. Walk into the next page at full + # depth, which needs the KV copied from the earlier exit. + gate = batch.position_ids.remainder(2).to(gate.dtype) * 20 - 10 + return hidden, gate + + monkeypatch.setattr(model, "recurrent_prepared", alternate_gate) + adaptive = SamplingParams(max_tokens=5, min_loops=2, exit_threshold=0.9, ignore_eos=True) + fixed = SamplingParams(max_tokens=5, ignore_eos=True) + capped = SamplingParams(max_tokens=5, min_loops=1, max_loops=1, ignore_eos=True) + early = 2 if exit_mode == "ouro" else 3 + + def run(asynchronous, use_multi_stream): + engine = make_engine(model, asynchronous, use_multi_stream, exit_mode=exit_mode) + try: + with pytest.raises(ValueError, match="exceed the model's supported depth"): + engine.add_request("invalid", [3], SamplingParams(max_loops=5)) + with pytest.raises(ValueError, match="require greedy sampling"): + engine.add_request("invalid", [3], SamplingParams(temperature=0.5)) + engine.add_request("adaptive", [3, 7, 11] * 5, adaptive) + for _ in range(30): + if any(out.token_ids for out in engine.step()): + break + else: + pytest.fail("adaptive request did not produce its first token") + engine.add_request("fixed", [13, 17, 19], fixed) + engine.add_request("capped", [3, 5, 7], capped) + return drain(engine) + finally: + engine.close() + + expected = run(False, False) + assert expected["adaptive"][1] == [4, early, 4, early, 4] + assert expected["fixed"][1] == [4] * 5 + assert expected["capped"][1] == [4, 1, 1, 1, 1] + if async_schedule: + assert run(True, multi_stream) == expected + + +@pytest.mark.npu +@torch.inference_mode() +def test_npu_adaptive_abort_discards_pending_gate_before_request_id_reuse(): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + model.model.early_exit_gate.weight.zero_() + model.model.early_exit_gate.bias.fill_(10) + params = SamplingParams(max_tokens=4, min_loops=2, exit_threshold=0.9, ignore_eos=True) + engine = make_engine(model, True, True) + try: + engine.add_request("a", [3, 7, 11], params) + for _ in range(30): + engine.step() + if "a" in engine._pending_exit_signals: + break + else: + pytest.fail("adaptive request did not retain a gate result") + engine.abort_request("a") + assert "a" not in engine._pending_exit_signals + engine.add_request("a", [13, 17, 19], params) + assert drain(engine)["a"][1] == [4, 3, 3, 3] + finally: + engine.close() + + @pytest.mark.npu @torch.inference_mode() def test_npu_delayed_delivery_consumes_device_token_before_host_result(): diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index a8006977..f25c9f13 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -457,10 +457,8 @@ def _add_request(self, request_id, prompt_token_ids, sampling_params, *, trace_i raise ValueError("prompt token IDs must be integers within the model vocabulary") fixed_loop_count = getattr(self.model, "fixed_loop_count", False) target_loops, max_loops = self._resolve_loop_bounds(params) - if next(self.model.parameters()).device.type == "npu" and ( - max_loops != 4 or params.exit_threshold != 1.0 or params.temperature != 0 - ): - raise ValueError("NPU Ouro requests require four loops, exit_threshold=1 and greedy") + if next(self.model.parameters()).device.type == "npu" and params.temperature != 0: + raise ValueError("NPU Ouro requests require greedy sampling") if self.speculative_config is not None and ( max_loops != self.speculative_config.target_loops or params.exit_threshold != 1.0 ): From b609b4858d4ed4539359eaf186db0e96cfb800d8 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 01:18:39 +0800 Subject: [PATCH 03/12] feat(ascend): reuse full-depth Ouro prompt KV pages Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 13 ++++++-- tests/test_prefix_growth.py | 57 ++++++++++++++++++++++++++++++++- vllm_rlt/engine/stage_engine.py | 3 +- 3 files changed, 68 insertions(+), 5 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 29c2b65e..cd9259f2 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -122,10 +122,19 @@ describes how the two policies interpret the gate score. The Ascend backend gathers the visible KV rows for Torch SDPA. The example uses private, fully reserved `last_exited` KV. Keep graphs, -static buffers, padding, prefix caching, incremental KV allocation, preemption, -speculation and prefill/decode disaggregation disabled in this configuration. +static buffers, padding, preemption, speculation and prefill/decode +disaggregation disabled in this configuration. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. +### Prompt reuse and KV growth + +Use `--enable-prefix-caching` to reuse completed prompt pages at every +recurrent depth. The engine computes at least the last prompt token to obtain +the first output. Use `--incremental-kv` to allocate pages as requests grow. +Both options use the shared `last_exited` cache and work with synchronous +or asynchronous eager execution. Use `--wavefront-chunked-prefill` to group +ready prompt chunks by depth. + ## Performance and correctness diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 9fe717c6..708023c9 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -2,9 +2,12 @@ import torch from tests.helpers import tiny_ouro_config -from vllm_rlt import CacheConfig, ExecutionConfig, SamplingParams, SchedulerConfig +from tests.test_ascend import make_npu_model +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig from vllm_rlt.core.kv_cache_manager import KVCacheManager +from vllm_rlt.device import resolve_device from vllm_rlt.engine.llm_engine import LLMEngine +from vllm_rlt.engine.stage_engine import StageEngine from vllm_rlt.models import OuroForCausalLM from vllm_rlt.request import RequestPhase @@ -66,6 +69,58 @@ def test_prefix_refcounts_and_eviction(): assert c.num_free_blocks == 12 +@pytest.mark.npu +@pytest.mark.parametrize( + "asynchronous,multi_stream,wavefront", + [(False, False, False), (True, False, True), (True, True, True)], + ids=["sync", "async-wavefront-single", "async-wavefront-multi"], +) +@torch.inference_mode() +def test_npu_prefix_reuses_full_depth_pages_with_incremental_growth( + asynchronous, multi_stream, wavefront +): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + prefix = [3, 7, 11, 13] * 8 + prompts = {"a": prefix + [5, 17], "b": prefix + [19]} + params = SamplingParams(max_tokens=4, min_loops=2, exit_threshold=0.2, ignore_eos=True) + results = [] + for enabled in (False, True): + engine = StageEngine( + model, + attention_backend="ascend_eager", + cache_config=CacheConfig( + 96, 16, enable_prefix_caching=enabled, incremental_allocation=enabled + ), + scheduler_config=SchedulerConfig( + max_num_seqs=2, + max_num_batched_tokens=48, + prefill_chunk_size=16, + wavefront_chunked_prefill=wavefront, + ), + exit_config=ExitConfig("ouro_delayed"), + execution_config=ExecutionConfig( + async_scheduling=asynchronous, multi_stream=multi_stream, use_uva=False + ), + ) + try: + engine.add_request("seed", prefix + [23], SamplingParams(max_tokens=1)) + assert finish(engine)["seed"].exit_depths == [4] + cache = engine.cache_manager + assert len(cache.lookup_prefix(prompts["a"])) == (2 if enabled else 0) + for request_id, prompt in prompts.items(): + engine.add_request(request_id, prompt, params) + outputs = finish(engine) + assert len(outputs) == len(prompts) + results.append({key: (out.token_ids, out.exit_depths) for key, out in outputs.items()}) + assert cache.prefix_hits == (2 * len(prefix) if enabled else 0) + assert cache.num_used_blocks == 0 + finally: + engine.close() + assert results[0] == results[1] + + def test_incremental_growth_matches_reserved_generation(): m = model() p = SamplingParams(max_tokens=9, exit_threshold=0, ignore_eos=True) diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index f25c9f13..bf9f085e 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -88,13 +88,12 @@ def __init__( or speculative_config is not None or self.stage_config.role != "prefill_decode" or scheduler_config.enable_preemption - or cache_config.enable_prefix_caching or cache_config.layout != "last_exited" or self.exit_config.mode not in ("ouro", "ouro_delayed") ): raise ValueError( "NPU Ouro requires local execution, ouro/ouro_delayed exit mode and " - "last_exited KV without speculation, graphs, preemption or prefix caching" + "last_exited KV without speculation, graphs or preemption" ) staged_prefill = requires_staged_prefill( scheduler_config, produces_tokens=self.stage_config.produces_tokens From fb0163c5bc88ffc799986e29dde024c40b1da718 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Mon, 23 Nov 2026 10:17:26 +0800 Subject: [PATCH 04/12] feat(ascend): select attention automatically on NPU Prefer ascend_eager for compatible NPU attention and let the serving CLI default to auto on NPU. Keep backend capabilities and explicit choices on the shared selection path. (cherry picked from commit 0b772e24f31d6db3fb01ff42e255af164cf18100) --- docs/recipes/ouro_ascend.md | 6 +++++- tests/test_ascend_serving.py | 10 +++++----- tests/test_backend_selection.py | 25 +++++++++++++++++++++++++ tests/test_device.py | 6 +++--- vllm_rlt/attention/backend.py | 19 ++++++++++--------- vllm_rlt/entrypoints/serve.py | 4 +++- 6 files changed, 51 insertions(+), 19 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index cd9259f2..934f8be5 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -65,11 +65,15 @@ sequence lengths, resident request count and available device memory. For whole-cohort prefill, the chunk size must fit each prompt and the batched token budget must fit the sum of prompt lengths in the cohort. +The serving CLI defaults to `--attention-backend auto` on NPU. It prefers +`ascend_eager` for compatible BF16 execution. Use `--attention-backend torch` +for an explicit Torch reference run. + ```bash TASK_QUEUE_ENABLE=2 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \ python -m vllm_rlt.entrypoints.serve \ --model "$MODEL" --tokenizer "$MODEL" --served-model-name ouro \ - --device npu --dtype bfloat16 --attention-backend ascend_eager \ + --device npu --dtype bfloat16 \ --mode refill --exit-mode ouro_delayed \ --async-scheduling --single-stream --no-uva \ --block-size 16 --num-blocks 2064 --max-num-seqs 32 \ diff --git a/tests/test_ascend_serving.py b/tests/test_ascend_serving.py index f1edbd09..bedffd5a 100644 --- a/tests/test_ascend_serving.py +++ b/tests/test_ascend_serving.py @@ -17,8 +17,8 @@ @pytest.mark.parametrize( ("backend", "asynchronous"), - [("torch", False), ("ascend_eager", False), ("ascend_eager", True)], - ids=["torch-sync", "ascend-sync", "ascend-async"], + [("torch", False), ("ascend_eager", False), ("ascend_eager", True), (None, True)], + ids=["torch-sync", "ascend-sync", "ascend-async", "ascend-default-async"], ) def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, asynchronous): import aiohttp @@ -26,7 +26,7 @@ def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, as source = os.environ.get("VLLM_RLT_OURO_CHECKPOINT") if not source: pytest.skip("set VLLM_RLT_OURO_CHECKPOINT to the pinned local Ouro-1.4B checkpoint") - mode = backend + ("-async" if asynchronous else "-sync") + mode = (backend or "default") + ("-async" if asynchronous else "-sync") folder = Path(os.environ.get("VLLM_RLT_ASCEND_RESULTS", tmp_path)) / mode folder.mkdir(parents=True, exist_ok=True) with socket.socket() as listener: @@ -44,8 +44,6 @@ def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, as "npu", "--dtype", "bfloat16", - "--attention-backend", - backend, "--num-blocks", "64", "--max-num-seqs", @@ -55,6 +53,8 @@ def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, as "--port", str(port), ] + if backend is not None: + command.extend(["--attention-backend", backend]) if asynchronous: command.extend(["--async-scheduling", "--exit-mode", "ouro_delayed", "--single-stream"]) with (folder / "service.log").open("w") as log: diff --git a/tests/test_backend_selection.py b/tests/test_backend_selection.py index cc90cf90..5ecb98ab 100644 --- a/tests/test_backend_selection.py +++ b/tests/test_backend_selection.py @@ -64,6 +64,31 @@ def test_cpu_auto_reports_torch_and_runs_reference_attention(caplog): torch.testing.assert_close(selected(q, k, v, table, lengths), explicit(q, k, v, table, lengths)) +def test_npu_auto_selects_ascend_with_required_execution_capabilities(): + device = SimpleNamespace(type="npu") + required = BackendCapabilities(packed_prefill=True, async_scheduling=True) + selected = create_backend( + "auto", device, torch.bfloat16, 128, 16, required_capabilities=required + ) + assert selected.info["requested_backend"] == "auto" + assert selected.info["selected_backend"] == "ascend_eager" + assert selected.capabilities.packed_prefill and selected.capabilities.async_scheduling + explicit = create_backend("torch", device, torch.bfloat16, 128, 16) + assert explicit.info["selected_backend"] == "torch" + fallback = create_backend("auto", device, torch.float32, 128, 16) + assert fallback.info["selected_backend"] == "torch" + assert "BF16" in fallback.info["selection_reason"] + with pytest.raises(ValueError, match="no compatible attention backend.*cuda_graphs"): + create_backend( + "auto", + device, + torch.bfloat16, + 128, + 16, + required_capabilities=BackendCapabilities(cuda_graphs=True), + ) + + @pytest.mark.parametrize( "sm,dtype,head_dim,supported", [ diff --git a/tests/test_device.py b/tests/test_device.py index c33f8282..2e9265b9 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -67,9 +67,9 @@ def test_npu_does_not_use_cpu_default_memory_budget(): assert blocks == 17 and info["source"] == "blocks" -@pytest.mark.parametrize("backend", ["auto", "triton", "flash_attn_4"]) -def test_npu_requires_explicit_torch_before_allocation(backend): - with pytest.raises(ValueError, match="explicit attention_backend='torch'"): +@pytest.mark.parametrize("backend", ["triton", "flash_attn_4"]) +def test_npu_rejects_incompatible_attention_before_allocation(backend): + with pytest.raises(ValueError, match="NPU attention requires"): StageEngine(npu_model_stub(), attention_backend=backend) diff --git a/vllm_rlt/attention/backend.py b/vllm_rlt/attention/backend.py index c5ebdbfa..e9c5e4a1 100644 --- a/vllm_rlt/attention/backend.py +++ b/vllm_rlt/attention/backend.py @@ -118,10 +118,8 @@ def backend_capabilities(implementation) -> BackendCapabilities: 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 device_type == "npu" and backend not in ("auto", "torch", "ascend_eager"): + raise ValueError("NPU attention requires 'auto', 'ascend_eager' or 'torch'") if backend not in {"auto", "torch", "triton", "ascend_eager", *FLASH_BACKENDS}: raise ValueError("unknown attention backend") @@ -186,7 +184,7 @@ 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. + """Choose a compatible attention backend in device-specific priority order. Each candidate validates hardware/configuration and imports its implementation. Only compatibility and import failures permit auto to try the next candidate; @@ -201,9 +199,12 @@ def create_backend( validate_backend_name(backend, device_type=device.type) candidates = _AUTO_PRIORITY if backend == "auto" else (backend,) skipped = [] - if backend == "auto" and device.type != "cuda": - candidates = ("torch",) - skipped.append(f"{device.type.upper()} uses Torch reference attention") + if backend == "auto": + if device.type == "npu": + candidates = ("ascend_eager", "torch") + elif device.type != "cuda": + candidates = ("torch",) + skipped.append(f"{device.type.upper()} uses Torch reference attention") for candidate in candidates: try: implementation = _create_explicit( @@ -254,7 +255,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" + f"first compatible candidate in {' > '.join(candidates)} priority" if backend == "auto" else f"explicitly requested {backend}" ) diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index c7fc3c84..e1b8f49a 100644 --- a/vllm_rlt/entrypoints/serve.py +++ b/vllm_rlt/entrypoints/serve.py @@ -98,7 +98,7 @@ def main(): "flash_attn_3", "flash_attn_4", ], - default="triton", + help="Defaults to auto on NPU and Triton otherwise", ) parser.add_argument("--mode", choices=["refill", "no_refill", "mixed"], default="refill") parser.add_argument("--num-blocks", type=int, help="Override automatic KV sizing") @@ -116,6 +116,8 @@ def main(): add_runtime_args(parser) args = parser.parse_args() + if args.attention_backend is None: + args.attention_backend = "auto" if args.device == "npu" else "triton" limits = ServingLimits(**{name: getattr(args, name) for name in defaults}) if args.device == "cpu" and args.attention_backend not in ("auto", "torch"): parser.error("CPU execution requires --attention-backend torch or auto") From 80b4dd9e1c90a09a1604657d9b8af7c3a003697a Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 01:22:07 +0800 Subject: [PATCH 05/12] feat(ascend): qualify Ouro priority preemption and KV restore Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 10 +++++- tests/test_device.py | 3 +- tests/test_prefix_growth.py | 61 +++++++++++++++++++++++++++++++++ vllm_rlt/engine/preemption.py | 12 ++++--- vllm_rlt/engine/stage_engine.py | 3 +- 5 files changed, 80 insertions(+), 9 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 934f8be5..c01d2480 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -126,7 +126,7 @@ describes how the two policies interpret the gate score. The Ascend backend gathers the visible KV rows for Torch SDPA. The example uses private, fully reserved `last_exited` KV. Keep graphs, -static buffers, padding, preemption, speculation and prefill/decode +static buffers, padding, speculation and prefill/decode disaggregation disabled in this configuration. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. @@ -139,6 +139,14 @@ Both options use the shared `last_exited` cache and work with synchronous or asynchronous eager execution. Use `--wavefront-chunked-prefill` to group ready prompt chunks by depth. +### Priority preemption + +Use `--scheduling-policy priority --enable-preemption`. Lower priority +numbers are admitted first. A suspended request retains its KV pages when +there is room. Under capacity pressure, the engine copies those pages to the +host and restores them before resuming the request. Both synchronous and +asynchronous eager execution use the same suspension and restoration path. + ## Performance and correctness diff --git a/tests/test_device.py b/tests/test_device.py index 2e9265b9..cb640193 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -37,8 +37,7 @@ def npu_model_stub(**overrides): "options", [ dict(execution_config=ExecutionConfig(cuda_graphs=True)), - dict(cache_config=CacheConfig(num_blocks=32, enable_prefix_caching=True)), - dict(scheduler_config=SchedulerConfig(enable_preemption=True)), + dict(execution_config=ExecutionConfig(async_scheduling=True, static_buffers=True)), dict(exit_config=ExitConfig(mode="random_lookahead")), ], ) diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 708023c9..9fe8b018 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -290,6 +290,67 @@ def test_priority_preempts_at_safe_boundary(): assert e.preemption.preemptions == 1 +@pytest.mark.npu +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async-multi"]) +@pytest.mark.parametrize("offload", [False, True], ids=["resident", "offload"]) +@torch.inference_mode() +def test_npu_preemption_restores_adaptive_decode(asynchronous, offload): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + prompt = [3, 7, 11] * 5 + params = SamplingParams(max_tokens=6, priority=10, exit_threshold=0.2, ignore_eos=True) + configs = dict( + attention_backend="ascend_eager", + cache_config=CacheConfig(8 if offload else 32, 16), + scheduler_config=SchedulerConfig(max_num_seqs=1, policy="priority", enable_preemption=True), + exit_config=ExitConfig("ouro_delayed"), + execution_config=ExecutionConfig( + async_scheduling=asynchronous, multi_stream=asynchronous, use_uva=False + ), + ) + reference = StageEngine(model, **configs) + try: + reference.add_request("low", prompt, params) + expected = finish(reference)["low"] + finally: + reference.close() + + engine = StageEngine(model, **configs) + try: + engine.add_request("low", prompt, params) + request = engine.scheduler.requests["low"] + for _ in range(40): + engine.step() + if ( + request.phase is RequestPhase.RECURRENT + and request.loops_done == 1 + and not request.num_output_placeholders + ): + break + else: + pytest.fail("did not reach the recurrent preemption point") + engine.add_request("high", [13] * 15, SamplingParams(max_tokens=3, ignore_eos=True)) + for _ in range(40): + engine.step() + if "low" in engine.preemption.snapshots: + break + else: + pytest.fail("priority request did not suspend the resident") + snapshot = engine.preemption.snapshots["low"] + assert (snapshot["kv"] is not None) == offload + assert snapshot["phase"] is RequestPhase.RECURRENT + completed = finish(engine) + assert list(completed) == ["high", "low"] + assert completed["low"].token_ids == expected.token_ids + assert completed["low"].exit_depths == expected.exit_depths + assert engine.preemption.preemptions == engine.preemption.resumptions == 1 + assert not engine.preemption.snapshots + assert engine.cache_manager.num_used_blocks == 0 + finally: + engine.close() + + @pytest.mark.gpu @pytest.mark.parametrize("use_uva", [False, True]) def test_packed_prefill_metadata_matches_reference_and_waits_for_consumer(use_uva): diff --git a/vllm_rlt/engine/preemption.py b/vllm_rlt/engine/preemption.py index f8be4a75..31c22954 100644 --- a/vllm_rlt/engine/preemption.py +++ b/vllm_rlt/engine/preemption.py @@ -9,6 +9,8 @@ import torch +from vllm_rlt.device import stream_module + class PreemptionManager: def __init__(self, engine): @@ -52,10 +54,11 @@ def suspend(self, victim, *, offload_kv=True): hidden=None if hidden is None else hidden.to(device).clone(), token=None if token is None else token.to(device).clone(), ) - if not offload_kv and cache.device.type == "cuda": + device_ops = stream_module(cache.device) + if not offload_kv and device_ops is not None: # Clones can borrow runner-owned rows. Finish reading them before # another stream reuses the released runner slot. - torch.cuda.current_stream(cache.device).synchronize() + device_ops.current_stream(cache.device).synchronize() if previous is None: if runner is not None: runner.release(victim) @@ -87,8 +90,9 @@ def resume(self, request): self.engine.speculative_runner.restore_pipeline(request, state.get("pipeline")) # Resident copies completed before suspension released their runner slot. # Restored CPU buffers must be visible to every stream before resumption. - if kv is not None and cache.device.type == "cuda": - torch.cuda.current_stream(cache.device).synchronize() + device_ops = stream_module(cache.device) + if kv is not None and device_ops is not None: + device_ops.current_stream(cache.device).synchronize() del self.snapshots[request.request_id] self.resumptions += 1 return state["phase"] diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index bf9f085e..32c09967 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -87,13 +87,12 @@ def __init__( or (self.execution_config.async_scheduling and self.execution_config.static_buffers) or speculative_config is not None or self.stage_config.role != "prefill_decode" - or scheduler_config.enable_preemption or cache_config.layout != "last_exited" or self.exit_config.mode not in ("ouro", "ouro_delayed") ): raise ValueError( "NPU Ouro requires local execution, ouro/ouro_delayed exit mode and " - "last_exited KV without speculation, graphs or preemption" + "last_exited KV without speculation or graphs" ) staged_prefill = requires_staged_prefill( scheduler_config, produces_tokens=self.stage_config.produces_tokens From afe9ebc5119a79efe778aac1f2595ead769abbba Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 01:26:08 +0800 Subject: [PATCH 06/12] feat(ascend): support synchronous Ouro self-speculation Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 11 ++++++++-- tests/test_device.py | 11 +++++++++- tests/test_speculative.py | 37 +++++++++++++++++++++++++++++++++ vllm_rlt/engine/stage_engine.py | 3 +-- vllm_rlt/worker/speculative.py | 24 +++++++++++---------- 5 files changed, 70 insertions(+), 16 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index c01d2480..a35512b7 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -126,8 +126,8 @@ describes how the two policies interpret the gate score. The Ascend backend gathers the visible KV rows for Torch SDPA. The example uses private, fully reserved `last_exited` KV. Keep graphs, -static buffers, padding, speculation and prefill/decode -disaggregation disabled in this configuration. +static buffers, padding and prefill/decode disaggregation disabled in this +configuration. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. ### Prompt reuse and KV growth @@ -147,6 +147,13 @@ there is room. Under capacity pressure, the engine copies those pages to the host and restores them before resuming the request. Both synchronous and asynchronous eager execution use the same suspension and restoration path. +### Synchronous self-speculation + +Run with `--exit-mode ouro --speculative-tokens 3 --draft-loops 2 --target-loops 4` +and select `--speculative-mode block` or `--speculative-mode pipeline`. +Use synchronous scheduling and fixed four-loop greedy requests. The engine +verifies candidate tokens at the target depth. + ## Performance and correctness diff --git a/tests/test_device.py b/tests/test_device.py index cb640193..d6d21832 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -7,7 +7,7 @@ import torch from tests.helpers import tiny_ouro_config -from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SchedulerConfig +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SchedulerConfig, SpeculativeConfig from vllm_rlt.core.memory import plan_cache from vllm_rlt.device import resolve_device, stream_module from vllm_rlt.engine.stage_engine import StageEngine @@ -80,3 +80,12 @@ def test_builtin_profiler_does_not_mislabel_npu_as_cpu_only(tmp_path): def test_npu_async_requires_explicit_delayed_exit_policy(): with pytest.raises(ValueError, match="async scheduling requires ouro_delayed"): StageEngine(npu_model_stub(), execution_config=ExecutionConfig(async_scheduling=True)) + + +def test_npu_rejects_async_self_speculation_before_allocation(): + with pytest.raises(ValueError, match="async speculative decoding requires CUDA"): + StageEngine( + npu_model_stub(), + speculative_config=SpeculativeConfig(2), + execution_config=ExecutionConfig(async_scheduling=True), + ) diff --git a/tests/test_speculative.py b/tests/test_speculative.py index 7efb6992..5480868b 100644 --- a/tests/test_speculative.py +++ b/tests/test_speculative.py @@ -9,6 +9,7 @@ from tests.helpers import LocalLLM as LLM from tests.helpers import tiny_ouro_config from tests.reference import dense_reference +from tests.test_ascend import make_npu_model from vllm_rlt import ( CacheConfig, ExecutionConfig, @@ -17,6 +18,7 @@ SpeculativeConfig, ) from vllm_rlt.core.scheduler import ScheduledRequest, SchedulerOutput +from vllm_rlt.device import resolve_device from vllm_rlt.engine.llm_engine import LLMEngine from vllm_rlt.models import OuroForCausalLM from vllm_rlt.request import Request, RequestPhase @@ -138,6 +140,41 @@ def test_greedy_matches_native_with_ragged_rounds_and_limits(k, budget): assert llm.engine.cache_manager.num_used_blocks == 0 +@pytest.mark.npu +@pytest.mark.parametrize("mode", ["block", "pipeline"]) +@torch.inference_mode() +def test_npu_sync_self_speculation_matches_greedy_across_kv_pages(mode): + device = resolve_device("npu:0") + torch.npu.set_device(device) + m = make_npu_model(device) + prompts = [[3, 5, 7] * 5, [11, 13, 17] * 6] + params = [SamplingParams(max_tokens=n, ignore_eos=True) for n in (8, 5)] + outputs = [] + for speculation in (None, SpeculativeConfig(3, mode=mode)): + e = LLMEngine( + m, + attention_backend="ascend_eager", + cache_config=CacheConfig(64, 16), + speculative_config=speculation, + execution_config=ExecutionConfig(multi_stream=True, use_uva=False), + ) + try: + for index, (prompt, options) in enumerate(zip(prompts, params, strict=True)): + e.add_request(str(index), prompt, options) + completed = drain(e) + outputs.append( + {key: (out.token_ids, out.exit_depths) for key, out in completed.items()} + ) + assert all(out.finish_reason == "length" for out in completed.values()) + assert e.cache_manager.num_used_blocks == 0 + if speculation: + stats = e.speculative_runner.stats + assert stats.drafted_tokens > 0 and stats.verified_rows > 0 + finally: + e.close() + assert outputs[0] == outputs[1] + + @pytest.mark.parametrize( "device,backend", [ diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index 32c09967..71f87113 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -85,14 +85,13 @@ def __init__( if ( self.execution_config.cuda_graphs or (self.execution_config.async_scheduling and self.execution_config.static_buffers) - or speculative_config is not None or self.stage_config.role != "prefill_decode" or cache_config.layout != "last_exited" or self.exit_config.mode not in ("ouro", "ouro_delayed") ): raise ValueError( "NPU Ouro requires local execution, ouro/ouro_delayed exit mode and " - "last_exited KV without speculation or graphs" + "last_exited KV without graphs" ) staged_prefill = requires_staged_prefill( scheduler_config, produces_tokens=self.stage_config.produces_tokens diff --git a/vllm_rlt/worker/speculative.py b/vllm_rlt/worker/speculative.py index d292e422..dd97aee8 100644 --- a/vllm_rlt/worker/speculative.py +++ b/vllm_rlt/worker/speculative.py @@ -18,6 +18,7 @@ import torch from vllm_rlt.core.scheduler import SchedulerOutput +from vllm_rlt.device import stream_module from vllm_rlt.request import Operation, Request from vllm_rlt.worker.buffers import stage_metadata from vllm_rlt.worker.cuda_graph import CodaGraphs, RecurrentGraphs @@ -95,7 +96,7 @@ def collect(self) -> ModelRunnerOutput: if self.event is not None: self.event.synchronize() stream = self.runner.compute_stream - with torch.cuda.stream(stream) if stream is not None else nullcontext(): + with self.runner.device_ops.stream(stream) if stream is not None else nullcontext(): self.cached = ModelRunnerOutput( speculative=( self.runner._collect_pipeline(self) @@ -203,6 +204,7 @@ def __init__( self.runtime = runtime if runtime is not None else ModelRuntime(model, cache) self.pipeline_states: dict[str, PipelineState] = {} self.device = next(model.parameters()).device + self.device_ops = stream_module(self.device) self.compute_stream = compute_stream self.submissions = SubmissionQueue() self.input_buffers = { @@ -349,9 +351,9 @@ def submit(self, batch): self.submissions.begin() try: if self.compute_stream is not None: - self.compute_stream.wait_stream(torch.cuda.current_stream(self.device)) + self.compute_stream.wait_stream(self.device_ops.current_stream(self.device)) with ( - torch.cuda.stream(self.compute_stream) + self.device_ops.stream(self.compute_stream) if self.compute_stream is not None else nullcontext() ): @@ -363,8 +365,8 @@ def submit(self, batch): return submission except Exception: # Failed submissions may not have recorded a completion event. - if self.device.type == "cuda": - (self.compute_stream or torch.cuda.current_stream(self.device)).synchronize() + if self.device_ops is not None: + (self.compute_stream or self.device_ops.current_stream(self.device)).synchronize() self.submissions.drain() raise @@ -465,9 +467,9 @@ def _submit_pipeline(self, batch): ) decisions = choices event = None - if self.device.type == "cuda": - event = torch.cuda.Event() - event.record(torch.cuda.current_stream(self.device)) + if self.device_ops is not None: + event = self.device_ops.Event() + event.record(self.device_ops.current_stream(self.device)) self.stats.rounds += len(states) return SpeculativeSubmission( self, @@ -562,9 +564,9 @@ def _submit_round(self, batch, prepared): ) logits = self._coda(hidden, self._boundary(layouts, prepared.target, Operation.CODA)) event = None - if self.device.type == "cuda": - event = torch.cuda.Event() - event.record(torch.cuda.current_stream(self.device)) + if self.device_ops is not None: + event = self.device_ops.Event() + event.record(self.device_ops.current_stream(self.device)) self.stats.rounds += len(scheduled_requests) self.stats.drafted_tokens += sum(len(rows) for rows, _ in drafted) self.stats.verified_rows += sum(span.token_count for span in scheduled_requests) From 0cb173d038bb26fac47b54fe5111fc364f7cdd07 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Mon, 23 Nov 2026 01:26:23 +0800 Subject: [PATCH 07/12] test(ascend): cover matched chunked prefill parity Check exact packed versus per-query logits with real Ouro weights at aligned and unaligned chunk boundaries. Document why cross-chunk BF16 tests use a separate comparison. (cherry picked from commit 0bffe84b5e71b0d8929fd9b03d8eac15dbff5389) --- docs/recipes/ouro_ascend.md | 8 +++++ tests/test_ascend_checkpoint.py | 63 ++++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index a35512b7..acc5b788 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -154,6 +154,14 @@ and select `--speculative-mode block` or `--speculative-mode pipeline`. Use synchronous scheduling and fixed four-loop greedy requests. The engine verifies candidate tokens at the target depth. +For chunked-prefill parity checks, compare against HF SDPA using the same token +IDs, chunk boundaries, and batch shapes. On Ascend 910B3, changing the number of +rows in a BF16 `Linear` can change the projection even when the input rows and +weights are identical. Compare full prefill with chunked prefill separately to +measure sensitivity to chunk shape. The real-checkpoint regression checks exact +logits and greedy tokens with packed and per-query metadata under identical +127- and 128-token chunk boundaries. + ## Performance and correctness diff --git a/tests/test_ascend_checkpoint.py b/tests/test_ascend_checkpoint.py index c26e8fe8..7255f6c3 100644 --- a/tests/test_ascend_checkpoint.py +++ b/tests/test_ascend_checkpoint.py @@ -7,10 +7,11 @@ import torch from tests.test_ascend import assert_bf16_close, recurrent_states -from vllm_rlt import CacheConfig, SamplingParams, SchedulerConfig +from vllm_rlt import CacheConfig, ExecutionConfig, SamplingParams, SchedulerConfig from vllm_rlt.device import resolve_device from vllm_rlt.engine.stage_engine import StageEngine from vllm_rlt.models import OuroForCausalLM, load_tokenizer +from vllm_rlt.request import RequestPhase pytestmark = pytest.mark.npu @@ -53,6 +54,66 @@ def test_checkpoint_incremental_pages_preserve_hidden_logits_and_kv(checkpoint): torch.testing.assert_close(a, b, atol=0, rtol=0) +@pytest.mark.parametrize("chunk_size", [127, 128]) +@torch.inference_mode() +def test_checkpoint_chunked_prefill_packed_matches_per_query(checkpoint, chunk_size): + model, tokenizer = checkpoint + prompt = tokenizer.encode( + "The capital of France is Paris. The capital of Japan is Tokyo. " * 20, + add_special_tokens=False, + )[:145] + assert len(prompt) == 145 + expected_chunks = [(0, chunk_size), (chunk_size, len(prompt) - chunk_size)] + loops = model.config.total_ut_steps + params = SamplingParams( + max_tokens=4, temperature=0, min_loops=loops, max_loops=loops, ignore_eos=True + ) + + def run(packed_prefill): + engine = StageEngine( + model, + attention_backend="ascend_eager", + cache_config=CacheConfig(num_blocks=64, block_size=16), + scheduler_config=SchedulerConfig( + max_num_seqs=1, max_num_batched_tokens=len(prompt), prefill_chunk_size=chunk_size + ), + execution_config=ExecutionConfig(packed_prefill=packed_prefill, use_uva=False), + ) + logits, chunks = [], [] + + def capture_logits(_module, _inputs, output): + logits.append(output[0].detach().cpu()) + + try: + with model.lm_head.register_forward_hook(capture_logits): + engine.add_request("chunked", prompt, params) + for _ in range(64): + outputs = engine.step() + batch = engine.last_schedule + if batch is not None and batch.phase == RequestPhase.PREFILL: + chunks.extend( + (item.token_start, item.token_count) for item in batch.requests + ) + for output in outputs: + if output.finished: + assert chunks == expected_chunks + assert output.finish_reason == "length" + assert output.exit_depths == [loops] * params.max_tokens + assert len(logits) == params.max_tokens + assert engine.cache_manager.num_used_blocks == 0 + return output.token_ids, torch.stack(logits) + pytest.fail("chunked request did not finish") + finally: + engine.close() + + # Hold the projection shapes fixed so this checks packing and cached KV, + # independent of BF16 differences across different Linear row counts. + expected_ids, expected_logits = run(False) + actual_ids, actual_logits = run(True) + assert actual_ids == expected_ids + torch.testing.assert_close(actual_logits, expected_logits, atol=0, rtol=0) + + @pytest.mark.parametrize("backend", ["torch", "ascend_eager"]) @torch.inference_mode() def test_checkpoint_greedy_replay_and_request_cleanup(checkpoint, backend): From afbe511aa71dae93206b06a7a281f5881f37f2bb Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 01:37:55 +0800 Subject: [PATCH 08/12] feat(ascend): enable eager workspace reuse and padding Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 25 +++++++++-------- tests/test_ascend_serving.py | 50 ++++++++++++++++++++++++++++----- tests/test_device.py | 1 - tests/test_npu_async.py | 26 +++++++++++++---- tests/test_prefix_growth.py | 5 +++- vllm_rlt/engine/stage_engine.py | 1 - 6 files changed, 81 insertions(+), 27 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index acc5b788..906a315b 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -1,6 +1,6 @@ # Ouro on Ascend -Run Ouro-1.4B on one Ascend NPU with BF16 and greedy decoding. Decode uses four +Run Ouro-1.4B or Ouro-2.6B on one Ascend NPU with BF16 and greedy decoding. Decode uses four recurrent loops by default. The Python runtime uses Torch's `scaled_dot_product_attention` through the `ascend_eager` backend, matching HF's SDPA entry point. Torch-NPU selects the device kernel according to the input @@ -115,6 +115,8 @@ describes how the two policies interpret the gate score. - **Scheduling.** Stream events track completion and protect buffer and request lifetimes. Decode PRELUDE and each recurrent loop are separate submissions, so the scheduler can select a new batch at each boundary. +- **Buffers.** `--static-buffers` opts into reusable eager workspaces. + Add `--pad-to-power-of-two` to bucket the submitted row counts. - **Reuse and batching.** Ascend uses the shared packed-prefill metadata by default with `ascend_eager`. Use `--no-packed-prefill` to select the per-query layout. Greedy sampling and compatible prefill are batched. Full prefill @@ -125,9 +127,8 @@ describes how the two policies interpret the gate score. assignment using its own block table. The Ascend backend gathers the visible KV rows for Torch SDPA. -The example uses private, fully reserved `last_exited` KV. Keep graphs, -static buffers, padding and prefill/decode disaggregation disabled in this -configuration. +The example uses private, fully reserved `last_exited` KV. Graphs and +prefill/decode disaggregation require separate platform support. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. ### Prompt reuse and KV growth @@ -139,6 +140,14 @@ Both options use the shared `last_exited` cache and work with synchronous or asynchronous eager execution. Use `--wavefront-chunked-prefill` to group ready prompt chunks by depth. +For chunked-prefill parity checks, compare against HF SDPA using the same token +IDs, chunk boundaries, and batch shapes. On Ascend 910B3, changing the number of +rows in a BF16 `Linear` can change the projection even when the input rows and +weights are identical. Compare full prefill with chunked prefill separately to +measure sensitivity to chunk shape. The real-checkpoint regression checks exact +logits and greedy tokens with packed and per-query metadata under identical +127- and 128-token chunk boundaries. + ### Priority preemption Use `--scheduling-policy priority --enable-preemption`. Lower priority @@ -154,14 +163,6 @@ and select `--speculative-mode block` or `--speculative-mode pipeline`. Use synchronous scheduling and fixed four-loop greedy requests. The engine verifies candidate tokens at the target depth. -For chunked-prefill parity checks, compare against HF SDPA using the same token -IDs, chunk boundaries, and batch shapes. On Ascend 910B3, changing the number of -rows in a BF16 `Linear` can change the projection even when the input rows and -weights are identical. Compare full prefill with chunked prefill separately to -measure sensitivity to chunk shape. The real-checkpoint regression checks exact -logits and greedy tokens with packed and per-query metadata under identical -127- and 128-token chunk boundaries. - ## Performance and correctness diff --git a/tests/test_ascend_serving.py b/tests/test_ascend_serving.py index bedffd5a..f51e825b 100644 --- a/tests/test_ascend_serving.py +++ b/tests/test_ascend_serving.py @@ -16,17 +16,33 @@ @pytest.mark.parametrize( - ("backend", "asynchronous"), - [("torch", False), ("ascend_eager", False), ("ascend_eager", True), (None, True)], - ids=["torch-sync", "ascend-sync", "ascend-async", "ascend-default-async"], + ("backend", "asynchronous", "reuse_and_preemption"), + [ + ("torch", False, False), + ("ascend_eager", False, False), + ("ascend_eager", True, False), + (None, True, False), + (None, True, True), + ], + ids=[ + "torch-sync", + "ascend-sync", + "ascend-async", + "ascend-default-async", + "ascend-default-async-multi-kv", + ], ) -def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, asynchronous): +def test_checkpoint_http_completions_stream_and_disconnect( + tmp_path, backend, asynchronous, reuse_and_preemption +): import aiohttp source = os.environ.get("VLLM_RLT_OURO_CHECKPOINT") if not source: pytest.skip("set VLLM_RLT_OURO_CHECKPOINT to the pinned local Ouro-1.4B checkpoint") mode = (backend or "default") + ("-async" if asynchronous else "-sync") + if reuse_and_preemption: + mode += "-multi-kv" folder = Path(os.environ.get("VLLM_RLT_ASCEND_RESULTS", tmp_path)) / mode folder.mkdir(parents=True, exist_ok=True) with socket.socket() as listener: @@ -56,7 +72,24 @@ def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, as if backend is not None: command.extend(["--attention-backend", backend]) if asynchronous: - command.extend(["--async-scheduling", "--exit-mode", "ouro_delayed", "--single-stream"]) + command.extend(["--async-scheduling", "--exit-mode", "ouro_delayed"]) + if not reuse_and_preemption: + command.append("--single-stream") + if reuse_and_preemption: + command.extend( + [ + "--enable-prefix-caching", + "--incremental-kv", + "--static-buffers", + "--pad-to-power-of-two", + "--wavefront-chunked-prefill", + "--prefill-chunk-size", + "16", + "--scheduling-policy", + "priority", + "--enable-preemption", + ] + ) with (folder / "service.log").open("w") as log: process = subprocess.Popen( command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True @@ -83,9 +116,9 @@ def body(prompt, **extra): prompt=prompt, max_tokens=4, temperature=0, - min_loops=4, + min_loops=2 if reuse_and_preemption else 4, max_loops=4, - exit_threshold=1, + exit_threshold=0.2 if reuse_and_preemption else 1, ignore_eos=True, **extra, ) @@ -98,6 +131,9 @@ async def complete(prompt): return result prompts = ["The capital of France is", "One plus one equals"] + if reuse_and_preemption: + prefix = "Paris is the capital of France and is known for its museums. " * 3 + prompts = [prefix + prompt for prompt in prompts] normal = await asyncio.gather(*(complete(prompt) for prompt in prompts)) events = [] async with client.post( diff --git a/tests/test_device.py b/tests/test_device.py index d6d21832..9ea1fa45 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -37,7 +37,6 @@ def npu_model_stub(**overrides): "options", [ dict(execution_config=ExecutionConfig(cuda_graphs=True)), - dict(execution_config=ExecutionConfig(async_scheduling=True, static_buffers=True)), dict(exit_config=ExitConfig(mode="random_lookahead")), ], ) diff --git a/tests/test_npu_async.py b/tests/test_npu_async.py index 5854066b..a4cea22b 100644 --- a/tests/test_npu_async.py +++ b/tests/test_npu_async.py @@ -25,7 +25,9 @@ def test_fixed_depth_decode_keeps_each_loop_schedulable(): assert request.phase == RequestPhase.CODA -def make_engine(model, asynchronous, multi_stream, *, exit_mode=None): +def make_engine( + model, asynchronous, multi_stream, *, exit_mode=None, static_buffers=False, pad=False +): return StageEngine( model, attention_backend="ascend_eager", @@ -36,8 +38,8 @@ def make_engine(model, asynchronous, multi_stream, *, exit_mode=None): execution_config=ExecutionConfig( async_scheduling=asynchronous, multi_stream=multi_stream, - static_buffers=False, - pad_to_power_of_two=False, + static_buffers=static_buffers, + pad_to_power_of_two=pad, use_uva=False, cuda_graphs=False, ), @@ -63,8 +65,15 @@ def drain(engine): @pytest.mark.npu @pytest.mark.parametrize("multi_stream", [False, True]) +@pytest.mark.parametrize( + "static_buffers,pad", + [(False, False), (True, False), (True, True)], + ids=["dynamic", "static", "static-padded"], +) @torch.inference_mode() -def test_async_npu_matches_sync_without_device_barriers(monkeypatch, multi_stream): +def test_async_npu_matches_sync_without_device_barriers( + monkeypatch, multi_stream, static_buffers, pad +): resolve_device("npu") torch.npu.set_device(0) model = make_npu_model(torch.device("npu:0")) @@ -72,8 +81,15 @@ def test_async_npu_matches_sync_without_device_barriers(monkeypatch, multi_strea params = SamplingParams(max_tokens=4, min_loops=4, max_loops=4, ignore_eos=True) reference = None for asynchronous in (False, True): - engine = make_engine(model, asynchronous, multi_stream) + engine = make_engine( + model, + asynchronous, + multi_stream, + static_buffers=asynchronous and static_buffers, + pad=asynchronous and pad, + ) try: + assert bool(engine.model_runner.requestspaces) == (asynchronous and static_buffers) for repeat in range(2): for i, prompt in enumerate(prompts): engine.add_request(str(i), prompt, params) diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 9fe8b018..c60aa7ad 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -306,7 +306,10 @@ def test_npu_preemption_restores_adaptive_decode(asynchronous, offload): scheduler_config=SchedulerConfig(max_num_seqs=1, policy="priority", enable_preemption=True), exit_config=ExitConfig("ouro_delayed"), execution_config=ExecutionConfig( - async_scheduling=asynchronous, multi_stream=asynchronous, use_uva=False + async_scheduling=asynchronous, + multi_stream=asynchronous, + static_buffers=asynchronous, + use_uva=False, ), ) reference = StageEngine(model, **configs) diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index 71f87113..2e043b4c 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -84,7 +84,6 @@ def __init__( raise ValueError("NPU Ouro requires BF16 KV cache") if ( self.execution_config.cuda_graphs - or (self.execution_config.async_scheduling and self.execution_config.static_buffers) or self.stage_config.role != "prefill_decode" or cache_config.layout != "last_exited" or self.exit_config.mode not in ("ouro", "ouro_delayed") From 5e1d8ed6a7d62dfc9e07ecd2946fb3295a045bd6 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 01:38:59 +0800 Subject: [PATCH 09/12] docs(ascend): record Ouro 2.6B platform qualification Signed-off-by: KrystalRay --- README.md | 4 ++-- docs/recipes/ouro_ascend.md | 22 ++++++++++++++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cde38840..b30d9f66 100644 --- a/README.md +++ b/README.md @@ -143,8 +143,8 @@ a fixed scale at startup. See the | 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-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 | Native Ouro | [CUDA](docs/launching.md)
[Ascend](docs/recipes/ouro_ascend.md) | Ascend BF16 greedy eager serving with paged KV and synchronous or asynchronous decode. | +| Ouro-2.6B | Shared Ouro | [CUDA](docs/launching.md)
[Ascend](docs/recipes/ouro_ascend.md) | Ascend BF16 real-checkpoint generation with fixed and adaptive decode. Quality evidence covers the GSM8K-87 screen. | | [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 | | Nanbeige4.2-3B | Native Nanbeige | [CUDA](docs/launching.md) | Fixed two-loop inference. [CUDA PD validation](https://github.com/InferMatrixLab/vllm-rlt/pull/77) | diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 906a315b..0bd95e2f 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -1,7 +1,7 @@ # Ouro on Ascend -Run Ouro-1.4B or Ouro-2.6B on one Ascend NPU with BF16 and greedy decoding. Decode uses four -recurrent loops by default. The Python runtime uses Torch's +Run Ouro-1.4B or Ouro-2.6B on one Ascend NPU with BF16 and greedy decoding. +Decode uses four recurrent loops by default. The Python runtime uses Torch's `scaled_dot_product_attention` through the `ascend_eager` backend, matching HF's SDPA entry point. Torch-NPU selects the device kernel according to the input shape, mask and hardware. @@ -169,6 +169,24 @@ verifies candidate tokens at the target depth. A higher prefill quota lets more requests reach decode together and can delay decode for existing requests. The scheduler default is 1. +### Ouro-2.6B accuracy screen + +On Ascend 910B3 with CANN 9.0 and Torch-NPU 2.10, a BF16 greedy run used the +[GSM8K-87 question IDs](../../benchmarks/fixtures/gsm8k-87.json), three +demonstrations, and the strict answer scorer. Each run used cohorts of up to +eight requests and a 1,024-token output limit. Adaptive runs used +`min_loops=2` and `max_loops=4`. + +| Mode | Threshold | Correct | Mean decode loops | +| --- | ---: | ---: | ---: | +| Fixed four loops | 1.0 | 61/87 | 4.00 | +| Synchronous `ouro` | 0.2 | 59/87 | 2.09 | +| Asynchronous multi-stream `ouro_delayed` | 0.2 | 67/87 | 3.10 | + +The paired result against fixed depth was four losses and two gains for +`ouro`, and zero losses and six gains for `ouro_delayed`. These scores cover +the fixed regression cohort. + ### Full unified W1-W7 validation This historical run used the C++ host executor and explicit eager attention From 32424ea9eb9849ab56d70a915de5b02dfe4c0386 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Tue, 24 Nov 2026 11:55:17 +0800 Subject: [PATCH 10/12] fix(ascend): leave prefix cache enablement to RFC 172 follow-up Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 14 ++++++-------- tests/test_ascend_serving.py | 21 ++++++++++----------- tests/test_device.py | 1 + tests/test_prefix_growth.py | 24 +++++++++--------------- vllm_rlt/engine/stage_engine.py | 3 ++- 5 files changed, 28 insertions(+), 35 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 0bd95e2f..77f49eb8 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -131,14 +131,12 @@ The example uses private, fully reserved `last_exited` KV. Graphs and prefill/decode disaggregation require separate platform support. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. -### Prompt reuse and KV growth - -Use `--enable-prefix-caching` to reuse completed prompt pages at every -recurrent depth. The engine computes at least the last prompt token to obtain -the first output. Use `--incremental-kv` to allocate pages as requests grow. -Both options use the shared `last_exited` cache and work with synchronous -or asynchronous eager execution. Use `--wavefront-chunked-prefill` to group -ready prompt chunks by depth. +### Incremental KV and chunked prefill + +Use `--incremental-kv` to allocate pages as requests grow with the shared +`last_exited` cache. The option works with synchronous or asynchronous eager +execution. Use `--wavefront-chunked-prefill` to group ready prompt chunks by +depth. For chunked-prefill parity checks, compare against HF SDPA using the same token IDs, chunk boundaries, and batch shapes. On Ascend 910B3, changing the number of diff --git a/tests/test_ascend_serving.py b/tests/test_ascend_serving.py index f51e825b..92fdad90 100644 --- a/tests/test_ascend_serving.py +++ b/tests/test_ascend_serving.py @@ -16,7 +16,7 @@ @pytest.mark.parametrize( - ("backend", "asynchronous", "reuse_and_preemption"), + ("backend", "asynchronous", "combined_execution"), [ ("torch", False, False), ("ascend_eager", False, False), @@ -33,7 +33,7 @@ ], ) def test_checkpoint_http_completions_stream_and_disconnect( - tmp_path, backend, asynchronous, reuse_and_preemption + tmp_path, backend, asynchronous, combined_execution ): import aiohttp @@ -41,7 +41,7 @@ def test_checkpoint_http_completions_stream_and_disconnect( if not source: pytest.skip("set VLLM_RLT_OURO_CHECKPOINT to the pinned local Ouro-1.4B checkpoint") mode = (backend or "default") + ("-async" if asynchronous else "-sync") - if reuse_and_preemption: + if combined_execution: mode += "-multi-kv" folder = Path(os.environ.get("VLLM_RLT_ASCEND_RESULTS", tmp_path)) / mode folder.mkdir(parents=True, exist_ok=True) @@ -73,12 +73,11 @@ def test_checkpoint_http_completions_stream_and_disconnect( command.extend(["--attention-backend", backend]) if asynchronous: command.extend(["--async-scheduling", "--exit-mode", "ouro_delayed"]) - if not reuse_and_preemption: + if not combined_execution: command.append("--single-stream") - if reuse_and_preemption: + if combined_execution: command.extend( [ - "--enable-prefix-caching", "--incremental-kv", "--static-buffers", "--pad-to-power-of-two", @@ -116,9 +115,9 @@ def body(prompt, **extra): prompt=prompt, max_tokens=4, temperature=0, - min_loops=2 if reuse_and_preemption else 4, + min_loops=2 if combined_execution else 4, max_loops=4, - exit_threshold=0.2 if reuse_and_preemption else 1, + exit_threshold=0.2 if combined_execution else 1, ignore_eos=True, **extra, ) @@ -131,9 +130,9 @@ async def complete(prompt): return result prompts = ["The capital of France is", "One plus one equals"] - if reuse_and_preemption: - prefix = "Paris is the capital of France and is known for its museums. " * 3 - prompts = [prefix + prompt for prompt in prompts] + if combined_execution: + context = "Paris is the capital of France and is known for its museums. " * 3 + prompts = [context + prompt for prompt in prompts] normal = await asyncio.gather(*(complete(prompt) for prompt in prompts)) events = [] async with client.post( diff --git a/tests/test_device.py b/tests/test_device.py index 9ea1fa45..39065f8e 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -37,6 +37,7 @@ def npu_model_stub(**overrides): "options", [ dict(execution_config=ExecutionConfig(cuda_graphs=True)), + dict(cache_config=CacheConfig(num_blocks=32, enable_prefix_caching=True)), dict(exit_config=ExitConfig(mode="random_lookahead")), ], ) diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index c60aa7ad..94546fb5 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -76,23 +76,18 @@ def test_prefix_refcounts_and_eviction(): ids=["sync", "async-wavefront-single", "async-wavefront-multi"], ) @torch.inference_mode() -def test_npu_prefix_reuses_full_depth_pages_with_incremental_growth( - asynchronous, multi_stream, wavefront -): +def test_npu_incremental_growth_matches_reserved_generation(asynchronous, multi_stream, wavefront): device = resolve_device("npu:0") torch.npu.set_device(device) model = make_npu_model(device) - prefix = [3, 7, 11, 13] * 8 - prompts = {"a": prefix + [5, 17], "b": prefix + [19]} + prompts = {"a": [3, 7, 11] * 5, "b": [13, 17, 19] * 6} params = SamplingParams(max_tokens=4, min_loops=2, exit_threshold=0.2, ignore_eos=True) results = [] - for enabled in (False, True): + for incremental in (False, True): engine = StageEngine( model, attention_backend="ascend_eager", - cache_config=CacheConfig( - 96, 16, enable_prefix_caching=enabled, incremental_allocation=enabled - ), + cache_config=CacheConfig(96, 16, incremental_allocation=incremental), scheduler_config=SchedulerConfig( max_num_seqs=2, max_num_batched_tokens=48, @@ -105,16 +100,15 @@ def test_npu_prefix_reuses_full_depth_pages_with_incremental_growth( ), ) try: - engine.add_request("seed", prefix + [23], SamplingParams(max_tokens=1)) - assert finish(engine)["seed"].exit_depths == [4] - cache = engine.cache_manager - assert len(cache.lookup_prefix(prompts["a"])) == (2 if enabled else 0) for request_id, prompt in prompts.items(): engine.add_request(request_id, prompt, params) + engine.step() + cache = engine.cache_manager + assert cache.allocated_blocks("a") == (4 if incremental else 8) outputs = finish(engine) - assert len(outputs) == len(prompts) + assert outputs.keys() == prompts.keys() + assert all(len(out.token_ids) == params.max_tokens for out in outputs.values()) results.append({key: (out.token_ids, out.exit_depths) for key, out in outputs.items()}) - assert cache.prefix_hits == (2 * len(prefix) if enabled else 0) assert cache.num_used_blocks == 0 finally: engine.close() diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index 2e043b4c..0acff2d4 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -85,12 +85,13 @@ def __init__( if ( self.execution_config.cuda_graphs or self.stage_config.role != "prefill_decode" + or cache_config.enable_prefix_caching or cache_config.layout != "last_exited" or self.exit_config.mode not in ("ouro", "ouro_delayed") ): raise ValueError( "NPU Ouro requires local execution, ouro/ouro_delayed exit mode and " - "last_exited KV without graphs" + "last_exited KV without graphs or prefix caching" ) staged_prefill = requires_staged_prefill( scheduler_config, produces_tokens=self.stage_config.produces_tokens From e2fe1075d9cd781142a7a09ed218fdf9f4945a73 Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Wed, 25 Nov 2026 11:45:51 +0800 Subject: [PATCH 11/12] fix(ascend): retire workspace and exit-signal readbacks safely Reuse runner completion events for workspaces and retain pending adaptive exit scores without pinning readback slots across preemption. Cover real NPU scheduling and HTTP priority admission, and document eager workspace costs. Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 12 ++++-- tests/test_ascend_serving.py | 73 ++++++++++++++++++++++++++------- tests/test_input_preparation.py | 11 +++-- tests/test_npu_async.py | 68 ++++++++++++++++++++++++++---- tests/test_prefix_growth.py | 53 ++++++++++++++++++++++++ vllm_rlt/engine/preemption.py | 4 ++ vllm_rlt/entrypoints/serve.py | 15 ++++--- vllm_rlt/worker/buffers.py | 15 ++++--- vllm_rlt/worker/model_runner.py | 16 +++++--- 9 files changed, 222 insertions(+), 45 deletions(-) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 77f49eb8..43820b85 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -116,7 +116,13 @@ describes how the two policies interpret the gate score. lifetimes. Decode PRELUDE and each recurrent loop are separate submissions, so the scheduler can select a new batch at each boundary. - **Buffers.** `--static-buffers` opts into reusable eager workspaces. - Add `--pad-to-power-of-two` to bucket the submitted row counts. + Add `--pad-to-power-of-two` to bucket the submitted row counts. The workspace + pool sizes its four page tables by the batch-token budget and the model's + maximum context. With 8,192 batch tokens, a 65,536-token context, and + 16-token pages, the tables alone reserve 512 MiB on the NPU and 1.5 GiB + on the host, including 1 GiB of pinned staging. Each recurrent submission + copies the full table width for its submitted rows. Budget this storage + separately from `--num-blocks`. - **Reuse and batching.** Ascend uses the shared packed-prefill metadata by default with `ascend_eager`. Use `--no-packed-prefill` to select the per-query layout. Greedy sampling and compatible prefill are batched. Full prefill @@ -127,8 +133,8 @@ describes how the two policies interpret the gate score. assignment using its own block table. The Ascend backend gathers the visible KV rows for Torch SDPA. -The example uses private, fully reserved `last_exited` KV. Graphs and -prefill/decode disaggregation require separate platform support. +The example uses private, fully reserved `last_exited` KV. Prefix caching, +graphs, and prefill/decode disaggregation require separate platform support. Greedy parity remains unqualified for arbitrary chunked or mixed-length inputs. ### Incremental KV and chunked prefill diff --git a/tests/test_ascend_serving.py b/tests/test_ascend_serving.py index 92fdad90..03feedc6 100644 --- a/tests/test_ascend_serving.py +++ b/tests/test_ascend_serving.py @@ -63,7 +63,7 @@ def test_checkpoint_http_completions_stream_and_disconnect( "--num-blocks", "64", "--max-num-seqs", - "2", + "3" if combined_execution else "2", "--max-num-batched-tokens", "32", "--port", @@ -110,23 +110,26 @@ async def exercise(): await asyncio.sleep(0.25) def body(prompt, **extra): - return dict( - model="ouro-ascend", - prompt=prompt, - max_tokens=4, - temperature=0, - min_loops=2 if combined_execution else 4, - max_loops=4, - exit_threshold=0.2 if combined_execution else 1, - ignore_eos=True, - **extra, + return ( + dict( + model="ouro-ascend", + prompt=prompt, + max_tokens=4, + temperature=0, + min_loops=2 if combined_execution else 4, + max_loops=4, + exit_threshold=0.2 if combined_execution else 1, + ignore_eos=True, + ) + | extra ) - async def complete(prompt): - async with client.post(url + "/v1/completions", json=body(prompt)) as response: + async def complete(prompt, **extra): + payload = body(prompt, **extra) + async with client.post(url + "/v1/completions", json=payload) as response: result = await response.json() assert response.status == 200, result - assert result["usage"]["completion_tokens"] == 4 + assert result["usage"]["completion_tokens"] == payload["max_tokens"] return result prompts = ["The capital of France is", "One plus one equals"] @@ -163,7 +166,47 @@ async def complete(prompt): await response.content.readline() after_disconnect = await complete(prompts[1]) assert after_disconnect["choices"][0]["text"] == normal[1]["choices"][0]["text"] - return dict(normal=normal, stream=events, after_disconnect=after_disconnect) + result = dict(normal=normal, stream=events, after_disconnect=after_disconnect) + if combined_execution: + ready = [asyncio.Event() for _ in range(3)] + finish_order = [] + + async def resident(started): + payload = body( + prompts[0], + priority=10, + max_tokens=16, + stream=True, + stream_options={"include_usage": True}, + ) + usage = None + async with client.post(url + "/v1/completions", json=payload) as response: + assert response.status == 200 + async for line in response.content: + if not line.startswith(b"data: "): + continue + data = line[6:].strip() + if data == b"[DONE]": + break + event = json.loads(data) + if event.get("choices"): + started.set() + if event.get("usage"): + usage = event["usage"] + assert usage is not None and usage["completion_tokens"] == 16 + finish_order.append("resident") + + async def priority(): + await asyncio.wait_for( + asyncio.gather(*(started.wait() for started in ready)), timeout=30 + ) + await complete("One plus one equals", priority=-10, max_tokens=1) + finish_order.append("priority") + + await asyncio.gather(*(resident(started) for started in ready), priority()) + assert finish_order == ["priority", "resident", "resident", "resident"] + result["priority_finish_order"] = finish_order + return result try: result = asyncio.run(exercise()) diff --git a/tests/test_input_preparation.py b/tests/test_input_preparation.py index 23e315ab..de23597f 100644 --- a/tests/test_input_preparation.py +++ b/tests/test_input_preparation.py @@ -461,7 +461,7 @@ def test_prelude_workspace_owned_once_across_gpu_prepare_and_forward( attention_backend="triton" if device == "cuda" else "torch", ) runner = e.model_runner - acquired, recorded, forwarded = [], [], [] + acquired, recorded, forwarded, completion_events = [], [], [], [] for workspace in runner.requestspaces["boundary"]: acquire, record_done = workspace.acquire, workspace.record_done @@ -469,9 +469,10 @@ def track_acquire(workspace=workspace, acquire=acquire): acquired.append(workspace) return acquire() - def track_done(workspace=workspace, record_done=record_done): + def track_done(event=None, *, workspace=workspace, record_done=record_done): recorded.append(workspace) - return record_done() + completion_events.append(event) + return record_done(event) monkeypatch.setattr(workspace, "acquire", track_acquire) monkeypatch.setattr(workspace, "record_done", track_done) @@ -508,6 +509,10 @@ def execute(scheduled, prepared): assert forwarded[0].cpu().tolist() == [7] assert len(acquired) == 1 assert recorded == acquired + if device == "cuda" and not fail_preparation: + assert completion_events == [runner.submissions.events[-1]] + else: + assert completion_events == [None] monkeypatch.setattr(runner, "prepare_on_gpu", original_prepare) runner.submit(batch=batch).collect() assert len(acquired) == 2 diff --git a/tests/test_npu_async.py b/tests/test_npu_async.py index a4cea22b..792a42c3 100644 --- a/tests/test_npu_async.py +++ b/tests/test_npu_async.py @@ -63,6 +63,28 @@ def drain(engine): pytest.fail("NPU async engine did not drain") +@pytest.mark.npu +def test_npu_workspace_retires_its_consumer_before_reuse(): + from vllm_rlt.worker.buffers import Workspace + + device = resolve_device("npu:0") + torch.npu.set_device(device) + workspace = Workspace(4, 4, 8, device, torch.bfloat16, use_uva=False) + consumer = torch.npu.Stream(device=device) + consumer.wait_stream(torch.npu.current_stream(device)) + workspace.acquire() + with torch.npu.stream(consumer): + workspace.hidden.fill_(7) + observed = workspace.hidden.clone() + workspace.record_done() + (event,) = workspace.submissions.events + workspace.acquire() + assert event.query() + assert not workspace.submissions.events + workspace.hidden.fill_(9) + assert observed.cpu().tolist() == [[7.0] * 8] * 4 + + @pytest.mark.npu @pytest.mark.parametrize("multi_stream", [False, True]) @pytest.mark.parametrize( @@ -77,6 +99,14 @@ def test_async_npu_matches_sync_without_device_barriers( resolve_device("npu") torch.npu.set_device(0) model = make_npu_model(torch.device("npu:0")) + recurrent = model.recurrent_prepared + row_shapes = set() + + def observe_rows(hidden, batch, cache, **kwargs): + row_shapes.add((len(batch.rows), len(hidden))) + return recurrent(hidden, batch, cache, **kwargs) + + monkeypatch.setattr(model, "recurrent_prepared", observe_rows) prompts = [[3, 5, 7] * 7, [2, 11, 17], [13, 19] * 9] params = SamplingParams(max_tokens=4, min_loops=4, max_loops=4, ignore_eos=True) reference = None @@ -89,6 +119,7 @@ def test_async_npu_matches_sync_without_device_barriers( pad=asynchronous and pad, ) try: + row_shapes.clear() assert bool(engine.model_runner.requestspaces) == (asynchronous and static_buffers) for repeat in range(2): for i, prompt in enumerate(prompts): @@ -105,18 +136,34 @@ def forbidden(*args, **kwargs): reference = actual else: assert actual == reference + if asynchronous: + assert (3, 4 if pad else 3) in row_shapes finally: engine.close() @pytest.mark.npu @pytest.mark.parametrize( - "exit_mode, async_schedule, multi_stream", - [("ouro", False, False), ("ouro_delayed", True, False), ("ouro_delayed", True, True)], - ids=["ouro-sync", "delayed-async-single", "delayed-async-multi"], + "exit_mode, async_schedule, multi_stream, pad", + [ + ("ouro", False, False, False), + ("ouro", False, True, False), + ("ouro_delayed", True, False, False), + ("ouro_delayed", True, True, False), + ("ouro_delayed", True, True, True), + ], + ids=[ + "ouro-sync", + "ouro-sync-multi", + "delayed-async-single", + "delayed-async-multi", + "delayed-async-padded", + ], ) @torch.inference_mode() -def test_npu_adaptive_exit_then_deeper_decode(monkeypatch, exit_mode, async_schedule, multi_stream): +def test_npu_adaptive_exit_then_deeper_decode( + monkeypatch, exit_mode, async_schedule, multi_stream, pad +): device = resolve_device("npu:0") torch.npu.set_device(device) model = make_npu_model(device) @@ -137,7 +184,14 @@ def alternate_gate(hidden, batch, cache, **kwargs): early = 2 if exit_mode == "ouro" else 3 def run(asynchronous, use_multi_stream): - engine = make_engine(model, asynchronous, use_multi_stream, exit_mode=exit_mode) + engine = make_engine( + model, + asynchronous, + use_multi_stream, + exit_mode=exit_mode, + static_buffers=asynchronous and pad, + pad=asynchronous and pad, + ) try: with pytest.raises(ValueError, match="exceed the model's supported depth"): engine.add_request("invalid", [3], SamplingParams(max_loops=5)) @@ -159,8 +213,8 @@ def run(asynchronous, use_multi_stream): assert expected["adaptive"][1] == [4, early, 4, early, 4] assert expected["fixed"][1] == [4] * 5 assert expected["capped"][1] == [4, 1, 1, 1, 1] - if async_schedule: - assert run(True, multi_stream) == expected + if async_schedule or multi_stream: + assert run(async_schedule, multi_stream) == expected @pytest.mark.npu diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 94546fb5..a70518d1 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -327,6 +327,10 @@ def test_npu_preemption_restores_adaptive_decode(asynchronous, offload): break else: pytest.fail("did not reach the recurrent preemption point") + if asynchronous: + signal = engine._pending_exit_signals["low"] + slot = signal.ticket.slot + assert slot is not None and slot.leased engine.add_request("high", [13] * 15, SamplingParams(max_tokens=3, ignore_eos=True)) for _ in range(40): engine.step() @@ -337,6 +341,9 @@ def test_npu_preemption_restores_adaptive_decode(asynchronous, offload): snapshot = engine.preemption.snapshots["low"] assert (snapshot["kv"] is not None) == offload assert snapshot["phase"] is RequestPhase.RECURRENT + if asynchronous: + assert engine._pending_exit_signals["low"] is signal + assert not slot.leased and signal.ticket.slot is None completed = finish(engine) assert list(completed) == ["high", "low"] assert completed["low"].token_ids == expected.token_ids @@ -348,6 +355,52 @@ def test_npu_preemption_restores_adaptive_decode(asynchronous, offload): engine.close() +@pytest.mark.npu +@torch.inference_mode() +def test_npu_preempted_gates_release_slots_for_more_than_one_pool(): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + model.model.early_exit_gate.weight.zero_() + model.model.early_exit_gate.bias.fill_(10) + engine = StageEngine( + model, + attention_backend="ascend_eager", + cache_config=CacheConfig(128, 16), + scheduler_config=SchedulerConfig(max_num_seqs=1, policy="priority", enable_preemption=True), + exit_config=ExitConfig("ouro_delayed"), + execution_config=ExecutionConfig(async_scheduling=True, use_uva=False), + ) + try: + slots = [ + slot + for slot in engine.model_runner.readback_slots + if slot.storage.dtype == torch.float32 + ] + for priority in range(len(slots) + 2, 0, -1): + request_id = str(priority) + params = SamplingParams( + max_tokens=4, priority=priority, min_loops=2, exit_threshold=0.9, ignore_eos=True + ) + engine.add_request(request_id, [3, 7, 11], params) + for _ in range(40): + engine.step() + if request_id in engine._pending_exit_signals: + break + else: + pytest.fail("request did not reach the recurrent preemption point") + assert engine.preemption.preemptions > len(slots) + assert sum(slot.leased for slot in slots) == 1 + completed = finish(engine) + assert len(completed) == len(slots) + 2 + assert all(out.exit_depths == [4, 3, 3, 3] for out in completed.values()) + assert engine.preemption.resumptions == engine.preemption.preemptions + assert not any(slot.leased for slot in slots) + assert engine.cache_manager.num_used_blocks == 0 + finally: + engine.close() + + @pytest.mark.gpu @pytest.mark.parametrize("use_uva", [False, True]) def test_packed_prefill_metadata_matches_reference_and_waits_for_consumer(use_uva): diff --git a/vllm_rlt/engine/preemption.py b/vllm_rlt/engine/preemption.py index 31c22954..1779c184 100644 --- a/vllm_rlt/engine/preemption.py +++ b/vllm_rlt/engine/preemption.py @@ -33,6 +33,10 @@ def suspend(self, victim, *, offload_kv=True): previous = self.snapshots.get(victim.request_id) if previous is None: e.model_runner.synchronize() + signal = e._pending_exit_signals.get(victim.request_id) + if signal is not None: + # Keep the score for resumption while releasing the pinned slot. + signal.ticket.collect() e._rewind_split_prefill(victim) phase, hidden, token = victim.phase, victim.hidden_state, victim.input_token_tensor else: diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index e1b8f49a..a2057063 100644 --- a/vllm_rlt/entrypoints/serve.py +++ b/vllm_rlt/entrypoints/serve.py @@ -23,6 +23,12 @@ ) +def _attention_backend(args): + if args.attention_backend is not None: + return args.attention_backend + return "auto" if args.device == "npu" else "triton" + + def load_engine(args): from tokenizers.decoders import ByteLevel @@ -62,7 +68,7 @@ def load_engine(args): max_admission_bypasses=getattr(args, "max_admission_bypasses", 8), min_coda_batch_size=getattr(args, "min_coda_batch_size", 1), ), - attention_backend=args.attention_backend, + attention_backend=_attention_backend(args), ) if profiling is not None: engine.start_profile(profiling, scheduled=True) @@ -116,13 +122,12 @@ def main(): add_runtime_args(parser) args = parser.parse_args() - if args.attention_backend is None: - args.attention_backend = "auto" if args.device == "npu" else "triton" + backend = _attention_backend(args) limits = ServingLimits(**{name: getattr(args, name) for name in defaults}) - if args.device == "cpu" and args.attention_backend not in ("auto", "torch"): + if args.device == "cpu" and backend not in ("auto", "torch"): parser.error("CPU execution requires --attention-backend torch or auto") try: - validate_backend_name(args.attention_backend, device_type=args.device) + validate_backend_name(backend, device_type=args.device) except ValueError as exc: parser.error(str(exc)) torch.set_num_threads(args.cpu_threads) diff --git a/vllm_rlt/worker/buffers.py b/vllm_rlt/worker/buffers.py index 621e1715..71cbe329 100644 --- a/vllm_rlt/worker/buffers.py +++ b/vllm_rlt/worker/buffers.py @@ -5,6 +5,7 @@ import torch +from vllm_rlt.device import stream_module from vllm_rlt.worker.metadata import KVLayout, KVMetadata from vllm_rlt.worker.submission_queue import MAX_CONCURRENT_SUBMISSIONS, SubmissionQueue from vllm_rlt.worker.tensors import UvaBackedTensor, copy_tensor, use_uva_on @@ -66,8 +67,10 @@ class Workspace: def __init__(self, rows, width, hidden_size, device, dtype, *, use_uva=True): self.hidden = torch.empty((rows, hidden_size), device=device, dtype=dtype) self.device = device + self.device_ops = stream_module(device) self.use_uva = use_uva - self.submissions = SubmissionQueue() + # Host snapshots rotate, but the hidden and device buffers have one owner. + self.submissions = SubmissionQueue(max_pending=1) specs = { "tokens": ((rows,), torch.int64), "positions": ((rows,), torch.int64), @@ -86,12 +89,12 @@ def acquire(self): # Protect pinned snapshots until the previous workspace consumer retires. self.submissions.begin() - def record_done(self): + def record_done(self, event=None): """Record the last GPU consumer without waiting or freeing storage.""" - if self.device.type == "cuda": - event = torch.cuda.Event() - event.record(torch.cuda.current_stream(self.device)) - self.submissions.complete(event) + if event is None and self.device_ops is not None: + event = self.device_ops.Event() + event.record(self.device_ops.current_stream(self.device)) + self.submissions.complete(event) def store_metadata(self, layout: KVLayout, size): """Fill fixed host buffers from a storage-independent layout.""" diff --git a/vllm_rlt/worker/model_runner.py b/vllm_rlt/worker/model_runner.py index 3ba410ea..e0829f26 100644 --- a/vllm_rlt/worker/model_runner.py +++ b/vllm_rlt/worker/model_runner.py @@ -1219,6 +1219,7 @@ def submit(self, scheduled_batch: SchedulerOutput | None = None, *, batch: Execu prepared = None routing_finish_attempted = False slot = None + compute_done = None try: if self.submissions.begin() and split_prefill: self.split_prefill_submission_waits += 1 @@ -1262,12 +1263,12 @@ def submit(self, scheduled_batch: SchedulerOutput | None = None, *, batch: Execu ): result = None device_values = result - event = compute_done = None + event = None if self.device_ops is not None: compute_stream = self.device_ops.current_stream(self.device) - compute_done = self.device_ops.Event() - compute_done.record(compute_stream) - event = compute_done + event = self.device_ops.Event() + event.record(compute_stream) + compute_done = event if result is not None: slot = self._readback_slot(result) readback_stream = self.readback_stream or compute_stream @@ -1317,8 +1318,11 @@ def submit(self, scheduled_batch: SchedulerOutput | None = None, *, batch: Execu raise finally: if prepared is not None and prepared.workspace is not None: - with self.device_ops.stream(stream) if stream is not None else nullcontext(): - prepared.workspace.record_done() + if compute_done is None and stream is not None: + with self.device_ops.stream(stream): + prepared.workspace.record_done() + else: + prepared.workspace.record_done(compute_done) def finalize_many(self, requests): if not requests: From e1fb5b16e915f1acf14026f5dbed8fc76c9a109b Mon Sep 17 00:00:00 2001 From: KrystalRay Date: Wed, 25 Nov 2026 16:51:53 +0800 Subject: [PATCH 12/12] docs(ascend): note BF16 parity limits for block verification Signed-off-by: KrystalRay --- docs/recipes/ouro_ascend.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/recipes/ouro_ascend.md b/docs/recipes/ouro_ascend.md index 43820b85..05bf2cbe 100644 --- a/docs/recipes/ouro_ascend.md +++ b/docs/recipes/ouro_ascend.md @@ -167,6 +167,10 @@ and select `--speculative-mode block` or `--speculative-mode pipeline`. Use synchronous scheduling and fixed four-loop greedy requests. The engine verifies candidate tokens at the target depth. +With BF16 checkpoints on 910B3, block verification can use a different +`Linear` row count from serial decode. A one-ULP change can flip the +greedy token when the top logits are nearly tied. + ## Performance and correctness