diff --git a/README.md b/README.md index adfe3285..71225d41 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 3a14d870..05bf2cbe 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 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. The example enables the optional asynchronous engine plan. ## Prepare the environment and model @@ -64,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 \ @@ -88,12 +93,36 @@ 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, 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. 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 @@ -104,11 +133,43 @@ curl --fail http://127.0.0.1:8123/v1/completions \ 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, 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. +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 + +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 +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 +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. + +### 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. + +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 @@ -116,6 +177,24 @@ and adaptive exit. 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 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): diff --git a/tests/test_ascend_serving.py b/tests/test_ascend_serving.py index f1edbd09..03feedc6 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)], - ids=["torch-sync", "ascend-sync", "ascend-async"], + ("backend", "asynchronous", "combined_execution"), + [ + ("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, combined_execution +): 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 + ("-async" if asynchronous else "-sync") + mode = (backend or "default") + ("-async" if asynchronous else "-sync") + 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) with socket.socket() as listener: @@ -44,19 +60,35 @@ def test_checkpoint_http_completions_stream_and_disconnect(tmp_path, backend, as "npu", "--dtype", "bfloat16", - "--attention-backend", - backend, "--num-blocks", "64", "--max-num-seqs", - "2", + "3" if combined_execution else "2", "--max-num-batched-tokens", "32", "--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"]) + command.extend(["--async-scheduling", "--exit-mode", "ouro_delayed"]) + if not combined_execution: + command.append("--single-stream") + if combined_execution: + command.extend( + [ + "--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 @@ -78,26 +110,32 @@ 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=4, - max_loops=4, - exit_threshold=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"] + 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( @@ -128,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_backend_selection.py b/tests/test_backend_selection.py index 90df5655..e998d90a 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..39065f8e 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 @@ -38,7 +38,6 @@ def npu_model_stub(**overrides): [ 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(exit_config=ExitConfig(mode="random_lookahead")), ], ) @@ -67,9 +66,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) @@ -81,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_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 52ba27de..792a42c3 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): +def make_engine( + model, asynchronous, multi_stream, *, exit_mode=None, static_buffers=False, pad=False +): return StageEngine( model, attention_backend="ascend_eager", @@ -36,12 +38,12 @@ def make_engine(model, asynchronous, multi_stream): 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, ), - exit_config=ExitConfig("ouro_delayed" if asynchronous else "ouro"), + exit_config=ExitConfig(exit_mode or ("ouro_delayed" if asynchronous else "ouro")), ) @@ -61,19 +63,64 @@ 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( + "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")) + 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 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: + row_shapes.clear() + 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) @@ -89,10 +136,113 @@ 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, 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, pad +): + 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, + 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)) + 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 or multi_stream: + assert run(async_schedule, 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(): @@ -121,10 +271,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 diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 9fe717c6..a70518d1 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,52 @@ 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_incremental_growth_matches_reserved_generation(asynchronous, multi_stream, wavefront): + device = resolve_device("npu:0") + torch.npu.set_device(device) + model = make_npu_model(device) + 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 incremental in (False, True): + engine = StageEngine( + model, + attention_backend="ascend_eager", + cache_config=CacheConfig(96, 16, incremental_allocation=incremental), + 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: + 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 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.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) @@ -235,6 +284,123 @@ 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, + static_buffers=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") + 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() + 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 + 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 + 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.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/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/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/engine/preemption.py b/vllm_rlt/engine/preemption.py index f8be4a75..1779c184 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): @@ -31,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: @@ -52,10 +58,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 +94,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 3bf247da..57e3f624 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -102,17 +102,14 @@ 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 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 graphs or prefix caching" ) staged_prefill = requires_staged_prefill( scheduler_config, produces_tokens=self.stage_config.produces_tokens @@ -562,10 +559,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 ): diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index 3581f4c7..042b73be 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 @@ -67,7 +73,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) @@ -104,7 +110,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") @@ -122,11 +128,12 @@ def main(): add_runtime_args(parser) args = parser.parse_args() + 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 64775891..c1677a92 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, PackedKVRange from vllm_rlt.worker.submission_queue import MAX_CONCURRENT_SUBMISSIONS, SubmissionQueue from vllm_rlt.worker.tensors import UvaBackedTensor, copy_tensor, use_uva_on @@ -73,8 +74,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), @@ -93,12 +96,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 7e3846c5..5ab6d4db 100644 --- a/vllm_rlt/worker/model_runner.py +++ b/vllm_rlt/worker/model_runner.py @@ -1357,6 +1357,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 @@ -1400,12 +1401,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 @@ -1455,8 +1456,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: diff --git a/vllm_rlt/worker/speculative.py b/vllm_rlt/worker/speculative.py index 9f20f056..de6b3dd6 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) @@ -204,6 +205,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 = { @@ -355,9 +357,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() ): @@ -369,8 +371,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 @@ -484,9 +486,9 @@ def _submit_pipeline(self, batch): else: decisions = choices[0] if choices else hidden.new_empty(0, dtype=torch.long) 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, @@ -581,9 +583,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)