diff --git a/README.md b/README.md index cde38840..cece68c5 100644 --- a/README.md +++ b/README.md @@ -148,8 +148,8 @@ a fixed scale at startup. See the | [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) | -| Huginn-0125 | Native Huginn | [CUDA](docs/launching.md) | Synchronous fixed-depth, LAST_EXITED KV, CUDA Graph decode core and coda | -| [NVIDIA-Nemotron-Labs-Dory1.0-4B](docs/dory.md) | Native Dory | [CUDA](docs/launching.md) | Synchronous fixed-loop execution, boundary KV, per-loop and last-loop KV modes, Triton/Torch sliding-window masking, BF16 real-checkpoint agreement at 1/2/4 loops on A100; long context, Graphs/async and reclamation not qualified | +| Huginn-0125 | Native Huginn | [CUDA](docs/launching.md) | Synchronous fixed-depth, LAST_EXITED KV, eager mixed/WCPB prefill, CUDA Graph decode core and coda | +| [NVIDIA-Nemotron-Labs-Dory1.0-4B](docs/dory.md) | Native Dory | [CUDA](docs/launching.md) | Synchronous fixed-loop execution, per-loop and last-loop KV, eager staged prefill with per-loop KV, BF16 real-checkpoint checks on A100; long context, staged Graphs/async and reclamation not qualified | The broader model roadmap is in [RFC #69](https://github.com/InferMatrixLab/vllm-rlt/issues/69). @@ -157,16 +157,19 @@ Huginn uses native checkpoint loading and depth-aware KV for its recurrent core, with separate prelude and coda KV. It supports synchronous fixed-depth inference and CUDA Graphs for the recurrent core and decode coda. -Huginn does **not** currently support WCPB/mixed staged prefill, asynchronous -execution, self-speculation, or PD. Feature availability is not equivalent to -validation of every model/backend/workload combination. +Huginn supports synchronous eager WCPB and mixed staged prefill with per-loop KV. +Asynchronous staged execution, self-speculation, prefix reuse, and PD are not +supported. Feature availability is not equivalent to validation of every +model/backend/workload combination. Dory runs the native normalized-GPT stack with attention-bearing input and output stages, so its boundary stages own their own KV. Synchronous fixed-loop execution is supported for both `per_loop` and `last_loop` KV -modes. Sliding-window masking exists only in the Torch reference attention -backend, and WCPB, CUDA Graphs, asynchronous execution, self-speculation, -prefix reuse and PD are rejected. See the +modes. Sliding-window masking is available in Torch and supported GPU attention +backends. Synchronous eager WCPB and mixed staged prefill support per-request +fixed loop counts with per-loop KV. Ordinary Graphs, asynchronous execution and +synchronous self-speculation have separate configuration restrictions; staged +Graphs/async, prefix reuse and PD are not supported. See the [Dory baseline notes](docs/dory.md) for the exact qualified scope. ## Documentation diff --git a/docs/README.md b/docs/README.md index 1b933288..c57b455f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,15 +41,15 @@ Supported models are Ouro-1.4B, Nanbeige4.2-3B, Huginn-0125 and NVIDIA-Nemotron-Labs-Dory1.0-4B. See the [checkpoint support matrix](../README.md#model-support) and the [Thinking recipe](recipes/ouro_thinking.md) for model-specific coverage. -Huginn currently uses synchronous execution, LAST_EXITED KV, and fixed -recurrent depth; prefix caching, asynchronous execution, and speculative -decoding are rejected, as are mixed/WCPB staged prefill and PD. Its CUDA Graphs capture the recurrent decode core -and coda, including the LM head. -The [Dory baseline notes](dory.md) list the narrower scope qualified for Dory: -synchronous fixed-loop execution with boundary KV in both KV modes, sliding-window -masking on the Torch and Triton backends, and BF16 agreement with the pinned -checkpoint at 1/2/4 loops; Graphs, WCPB, async, speculation, prefix reuse and PD -remain out of scope. +Huginn supports synchronous fixed-depth execution, LAST_EXITED KV, and eager +mixed/WCPB staged prefill; prefix caching, asynchronous execution, speculative +decoding and PD are rejected. Its ordinary CUDA Graphs capture the recurrent +decode core and coda, including the LM head. +The [Dory notes](dory.md) describe the supported execution modes and their +validation scope. Eager staged prefill with per-request fixed depths is separate +from the already supported ordinary Graph, async and synchronous speculative +paths. Tiny-model CUDA regressions and a short real-checkpoint differential +check cover A100; broader staged qualification remains outstanding. CPU execution provides a Torch reference backend. FlashAttention hardware validation is currently documented for FA4 on B300; FA2/FA3 require validation on their target devices. Disaggregated serving currently targets multiple GPUs on a single host. diff --git a/docs/dory.md b/docs/dory.md index 46cfd8d6..3ae3ff98 100644 --- a/docs/dory.md +++ b/docs/dory.md @@ -69,6 +69,13 @@ layer id rather than their physical sublayer index. `gate_up_proj` fails loudly instead of loading approximately. - Synchronous eager execution: full-prompt prefill followed by ordinary token decoding, with the configured fixed loop count. +- Synchronous eager staged prefill with per-loop KV, including WCPB and mixed + prelude/recurrent batching. Each request may select a fixed target from one + through `total_ut_steps`, with the full model depth as the default. Prompt + CODA is a separate causal stage; its final prompt row produces the first token. + Tiny-model CPU and A100 CUDA regressions cover float32, BF16 and multi-stream + execution. A short BF16 real-checkpoint differential check is recorded below; + long-context and broader backend qualification remain outstanding. - `loops=` at load time to fix 1, 2 or 4 loops. - Greedy and sampled decoding, request seeds, EOS (`2`, `11`) and length stopping through the existing engine, covered by @@ -134,14 +141,15 @@ even with per-query attention. These fail fast rather than degrade silently: -- WCPB, mixed or staged prefill, and PD. +- Staged prefill with CUDA Graphs, asynchronous scheduling, preemption, + speculation, shared/last-loop KV, or PD. - Prefix caching. - Self-speculation combined with CUDA Graphs, asynchronous scheduling, preemption or `last_loop` KV, and sampled token-pipeline speculation. The synchronous eager form is supported; see below. -- Per-request loop counts other than the configured full depth: Dory has no - trained exit gate, so the runtime refuses to invent one, including via - `min_loops` with `exit_threshold=0`. +- Request loop counts below the configured full depth with ordinary atomic + prefill. Dory has no trained exit gate; its supported staged request target + is fixed rather than inferred from `exit_threshold`. Preemption and snapshots are **not qualified** rather than enforced: the generic KV snapshot mechanism copies every plane, so it may well work, but no @@ -248,6 +256,19 @@ path. ### Real checkpoint +For the staged prefill change, a separate BF16 differential test compares the +local `Dory1.0-4B-BF16` checkpoint on an A100 80GB PCIe (PyTorch 2.13.0+cu130, +Triton 3.7.1) against independent atomic-prefill runs of the same weights. The +two five- and ten-token prompts run together with fixed request depths 1 and 2, +chunk size 2, and three greedy output tokens. Both mixed and WCPB scheduling +match the atomic token IDs and depths. First-token top-20 overlap is 20/20 for +the shallow request and 19/20 for the full-depth request; the largest top-20 +logit deviation is 0.1500. This checks neither long contexts nor throughput, +and is a runtime-to-runtime differential, not an independent accuracy oracle. +The checkpoint's `model.safetensors` SHA-256 is +`207483664dfef54c4c4438863260d3ba423bf3d6009b43fe84264b281e9fda23`; its +revision was not independently verified for this run. + `tests/test_dory_real_checkpoint.py` runs the pinned snapshot `f6c832e6963ddb74f62c75813a3e8c74b1af67b1` on one `A100-SXM4-80GB` (torch 2.13.0+cu130, triton 3.7.1, Python 3.12.15) with the prompt diff --git a/docs/runtime.md b/docs/runtime.md index c487ea37..9111dee2 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -63,7 +63,15 @@ if __name__ == "__main__": The default exit mode remains `ouro`, with the original cumulative hazard policy. For random lookahead, sigmoid is a direct score for exiting after one more loop, not a hazard/CDF. `SamplingParams.exit_threshold` compares this score directly. Threshold 1 disables adaptive exit; `max_loops` always caps execution. Adaptive lookahead cannot exit before round 2, although an explicitly configured hard maximum of 1 is honored. All prompt tokens still run the model's full depth. -Fixed-loop models accept the request-level `SamplingParams.target_loops` field (offline CLI: `--request-target-loops`). An omitted target defaults to `total_ut_steps`; an explicit target must be between one and the model depth. If `max_loops` is provided, it must match the fixed target. For compatibility with the default, `min_loops=2` is accepted, as is `min_loops` equal to the target; the fixed target determines the exit depth. Targets below the model depth are rejected until per-request prompt prefill is enabled; they are never silently run at full prompt depth. Dynamic-exit models do not accept this field and retain their existing loop-bound and exit-threshold behavior. +Fixed-loop models accept the request-level `SamplingParams.target_loops` field (offline CLI: `--request-target-loops`). An omitted target defaults to `total_ut_steps`; an explicit target must be between one and the model depth. If `max_loops` is provided, it must match the fixed target. For compatibility with the default, `min_loops=2` is accepted, as is `min_loops` equal to the target; the fixed target determines the exit depth. Dory accepts shorter request targets for synchronous eager staged prefill with per-loop KV; ordinary atomic prefill still rejects shorter targets. Dynamic-exit models do not accept this field and retain their existing loop-bound and exit-threshold behavior. + +Huginn initializes its recurrent state one token at a time using the request's +generator. This keeps seeded state independent of chunk sizes and batch grouping, +including when prelude work is mixed with decoding. Relative to earlier versions +that initialized a whole span at once, the same seed can produce different +outputs; GPU performance of this per-token initialization has not been measured. +Some PyTorch implementations of truncated-normal initialization synchronize +the device during rejection sampling, making that cost potentially significant. For dynamic-exit models, ordinary asynchronous execution requires `ouro_delayed`, `random_lookahead` or `trace`; fixed-loop models do not need an exit signal. Speculative execution has the separate constraints below. Asynchronous execution automatically enables reusable static inputs to avoid blocking device metadata transfers. CPU supports the same scheduling state machine for tests, with immediately completed operations; it does not simulate GPU parallel execution. `multi_stream` is an independent CUDA execution feature: `False` uses one stream for core, boundary and copies; `True` separates those streams, with or without async scheduling. @@ -383,8 +391,8 @@ because the runtime window includes the current token. Full-attention layers keep their causal mask. Packed prompt chunks retain bottom-right alignment against an existing prefix. Both `per_loop` and `last_loop` KV modes, using their required layouts, support asynchronous scheduling and CUDA Graphs in -the input, recurrent and output stages. Dory's existing rejection of mixed -scheduling and boundary-KV prefix caching remains in effect. +the input, recurrent and output stages. Dory's staged path has separate +eager/per-loop restrictions, and boundary-KV prefix caching remains rejected. Validation on B300 with FA4 4.0.0b39 covers 69 GPU cases across kernel, end-to-end and regression checks: head dimensions 64/128/256, packed sliding diff --git a/docs/scheduler.md b/docs/scheduler.md index cb9c2a57..7c11892b 100644 --- a/docs/scheduler.md +++ b/docs/scheduler.md @@ -761,7 +761,10 @@ restrictions still apply. Speculative generation requires refill. chunk runs its prelude and all recurrent depths locally in one submission. Mixed mode inserts a boundary when ready decode work can join prompt recurrent work, and it returns after every depth in such a mixed batch. With no ready -decode work, the prompt batch can run through its remaining depths. WCPB always +decode work, a prompt batch can run through its remaining depths. Models with +attention-bearing prompt CODA stage the prelude separately and run CODA after +the required recurrent depths; their final prompt row also produces the first +sampled token. WCPB always returns after one depth to regroup ready chunks. Chunk size and loop submission size are distinct choices; WCPB retains up to one staged chunk per model depth. Ordinary prompt chunks already end at the scheduler's configured chunk boundary, diff --git a/docs/split-prefill-wavefront.md b/docs/split-prefill-wavefront.md index 5bbed969..2df2bc97 100644 --- a/docs/split-prefill-wavefront.md +++ b/docs/split-prefill-wavefront.md @@ -8,11 +8,11 @@ uneven, without making chunks larger and reducing scheduling opportunities. ![Split prefill compared with wavefront chunked prefill](assets/Split-prefill-vs-wavefront-chunked-prefill.png) -The current runner requires one operation per batch: PRELUDE ranges and RECURRENT -ranges are submitted separately. Ordinary prefill can also execute its selected range -through all recurrent depths in one plan. Actual submission counts depend on scheduler -mode, token budget, and ready work; the numbered batches in the figure should not be -read as measured latency or a fixed runtime schedule. +The current runner requires one operation per batch: PRELUDE, RECURRENT and +CODA ranges are submitted separately. Ordinary prefill can also execute its +selected range through all recurrent depths in one plan. Actual submission +counts depend on scheduler mode, token budget, and ready work; the numbered batches +in the figure should not be read as measured latency or a fixed runtime schedule. ## Execution model @@ -22,12 +22,24 @@ scheduler may choose a shorter execution boundary when ready decode work needs a depth decision. `ExecutionBatch.loop_count` records the recurrent work in that submission. -With `wavefront_chunked_prefill=True`, prompt work is scheduled in two phases: +With `wavefront_chunked_prefill=True`, prompt work uses these phases: | Phase | Work | Recurrent loops in the submission | | --- | --- | ---: | | `PREFILLING_PRELUDE` | Embed staged prompt ranges and prepare inputs | 0 | | `PREFILLING_RECURRENT` | Run ready prompt ranges at their selected recurrent depths | 1 | +| `PREFILLING_CODA` | Run attention-bearing output layers on ready prompt ranges, when required by the model | 0 | + +Huginn and Dory require the CODA phase to populate their output-attention KV. +All prompt rows run the output layers; only the last prompt row projects logits +and samples the first output. This phase is currently scheduled separately from +ordinary decode CODA. Ouro does not require prompt CODA. + +Staged CODA passes a row-aligned boolean `ForwardBatch.compute_logits` mask: +only a final prompt row or a mixed decode row is selected for projection and +sampling. Sparse samples are mapped back to their request spans. Uniform boolean +values remain supported for the existing atomic and CUDA Graph paths; automatic +mixing of prompt and decode CODA is a separate scheduling change. The scheduler can include several ranges from different chunks, requests, and depths in one recurrent batch. It obeys the shared token budget, request-owner @@ -52,22 +64,24 @@ Progress belongs to the request rather than to a persistent task table: - `num_preluded_tokens` tracks the prompt range whose prelude has been staged. - `prefill_depth_ranges` tracks the ready range at each recurrent depth. -- `num_prefilled_tokens` tracks prompt progress at the final depth, including - progress within a chunk. +- For attention-bearing CODA, `num_recurrent_prefilled_tokens` tracks the final + recurrent frontier; `num_prefilled_tokens` tracks completed prompt CODA. + For other models, `num_prefilled_tokens` tracks the final recurrent frontier. - `prefill_reclaimable_tokens` marks the oldest resident chunk boundary. It - advances only after that chunk completes its final depth and its ring slot - can be reused. + advances after the chunk's final required stage completes: CODA for Huginn and + Dory, otherwise the final recurrent depth. This separation prevents a prelude or partial chunk from advancing the -reclaimable boundary. Prefix publication, prompt completion, and CODA follow -the completed final-depth frontier. +reclaimable boundary. For models with prompt CODA, the CODA frontier cannot +overtake the final recurrent frontier and each chunk remains resident until +CODA consumes it. ## Hidden-state ring Each request reserves `prefill_chunk_size * total_ut_steps` rows for staged prompt hidden states. A chunk uses a ring slot derived from its index relative -to the cached-prefix origin. For a chunk-local offset `j` and slot `s`, its row -offset is: +to the cached-prefix origin and the request's prefill loop count. For a +chunk-local offset `j` and slot `s`, its row offset is: ```text prefill_hidden_row_offset = s * prefill_chunk_size + j @@ -75,9 +89,10 @@ prefill_hidden_row_offset = s * prefill_chunk_size + j `ScheduledRequest` and `StateSpan` carry this row offset. When it is `None`, the runner derives the row from `token_start - chunk_start`. Intermediate outputs -are scattered to the ring for later depths; after final-depth completion, the -chunk's intermediate state is no longer needed. Asynchronous submissions keep -the backing rows alive until dependent reads complete. +are scattered to the ring for later depths or prompt CODA. Batch-local gathered +hidden scratch rotates with the submission's input descriptors and is reused +only after its last device consumer. Request events also protect ring rows from +reuse before dependent reads finish. ## Scheduling and recovery @@ -94,8 +109,12 @@ Preemption rewinds staged work to the request's completed prompt frontier and recomputes unfinished work after resume. PD transfer progress is reported for completed chunks, and imported prompt state initializes the same frontiers. Speculative execution is supported with compatible refill scheduling; mixed -mode rejects speculative configuration. CUDA graph and asynchronous paths use -the existing runner machinery. +mode rejects speculative configuration. For Huginn and Dory, staged prefill +currently requires synchronous eager generation without preemption, speculation, +prefix reuse, or PD; the separate CUDA streams remain event-ordered. Tiny-model +CPU and A100 CUDA regressions cover these staged paths. A short real Dory +checkpoint check compares mixed and WCPB prefill with atomic prefill; longer +contexts and broader backend qualification remain outstanding. `SHARED` KV is rejected for WCPB. Its position-major dependencies do not permit the same cross-chunk/depth ordering as `LAST_EXITED` without a different diff --git a/tests/test_ascend_compatibility.py b/tests/test_ascend_compatibility.py index 9f264189..4a223778 100644 --- a/tests/test_ascend_compatibility.py +++ b/tests/test_ascend_compatibility.py @@ -2,17 +2,19 @@ import builtins from dataclasses import fields +from types import SimpleNamespace import pytest import torch from tests.helpers import tiny_ouro_model -from vllm_rlt import CacheConfig, SchedulerConfig +from vllm_rlt import CacheConfig, SamplingParams, SchedulerConfig from vllm_rlt.attention.backend import BackendCapabilities from vllm_rlt.device import stream_module from vllm_rlt.engine.stage_engine import StageEngine from vllm_rlt.layers.rotary_embedding import RotaryEmbedding -from vllm_rlt.worker.executor import ModelRuntime +from vllm_rlt.request import Operation +from vllm_rlt.worker.executor import ForwardBatch, ForwardResult, ModelRuntime from vllm_rlt.worker.model_runner import ModelRunner from vllm_rlt.worker.sampler import Sampler @@ -87,3 +89,33 @@ def guarded(name, *args, **kwargs): assert type(engine.model_runner.sampler) is Sampler finally: engine.close() + + +@pytest.mark.parametrize("compute_logits", [False, True]) +def test_npu_coda_uses_batched_sampling_only_for_materialized_logits(compute_logits): + logits = torch.tensor([[0.0, 1.0]]) if compute_logits else None + forward = ForwardBatch(Operation.CODA, compute_logits=torch.tensor([False, compute_logits])) + prepared = SimpleNamespace( + forwards=(SimpleNamespace(forward=forward, hidden_rows=None),), + sampling_params=(SamplingParams(),) if compute_logits else (), + sampling_generators=(None,) if compute_logits else (), + routing=None, + ) + calls = [] + + def sample_batch(values, params, generators): + calls.append((values, params, generators)) + return values.argmax(dim=-1) + + runner = SimpleNamespace( + runtime=SimpleNamespace(forward=lambda batch: ForwardResult(hidden=None, logits=logits)), + device=SimpleNamespace(type="npu"), + sampler=SimpleNamespace(sample_batch=sample_batch), + ) + actual = ModelRunner._execute_batch(runner, SimpleNamespace(), prepared) + if compute_logits: + assert actual.tolist() == [1] + assert len(calls) == 1 + else: + assert actual is None + assert not calls diff --git a/tests/test_dory_gpu.py b/tests/test_dory_gpu.py index 3a04240f..3a67d12d 100644 --- a/tests/test_dory_gpu.py +++ b/tests/test_dory_gpu.py @@ -245,6 +245,104 @@ def test_dory_execution_modes_match_cpu_oracle(mode, max_num_seqs): assert runner.prelude_graphs is None +@pytest.mark.parametrize("multi_stream", [False, True]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_staged_prefill_fixed_depths_match_cpu_oracle(multi_stream, wavefront, monkeypatch): + reference, model = reference_pair() + shallow = DoryForCausalLM(tiny_dory_config(n_recurrent_loops=1)).eval() + shallow.load_state_dict(reference.state_dict()) + engine = LLMEngine( + model, + attention_backend="triton", + cache_config=CacheConfig(num_blocks=256, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + execution_config=ExecutionConfig(multi_stream=multi_stream), + ) + runner = engine.model_runner + original_execute = runner._execute + scratch = set() + delayed = False + + def execute(batch, prepared): + nonlocal delayed + if prepared.batch_inputs is not None: + scratch.add(prepared.batch_inputs.buffers.hidden.data_ptr()) + if multi_stream and not delayed and prepared.batch.operation.value == "recurrent": + torch.cuda._sleep(20_000_000) + delayed = True + return original_execute(batch, prepared) + + monkeypatch.setattr(runner, "_execute", execute) + prompts = {"shallow": [4, 7, 9, 3, 12, 6, 5], "full": [8, 2, 10, 11, 4]} + for request_id, prompt in prompts.items(): + target = 1 if request_id == "shallow" else 2 + engine.add_request( + request_id, prompt, SamplingParams(max_tokens=3, target_loops=target, ignore_eos=True) + ) + try: + results = drain(engine) + assert results["shallow"].token_ids == greedy_reference(shallow, prompts["shallow"], 3) + assert results["full"].token_ids == greedy_reference(reference, prompts["full"], 3) + assert results["shallow"].exit_depths == [1] * 3 + assert results["full"].exit_depths == [2] * 3 + assert len(scratch) == 2 + assert delayed is multi_stream + assert engine.cache_manager.num_used_blocks == 0 + finally: + engine.close() + + +@pytest.mark.parametrize("multi_stream", [False, True]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_staged_bfloat16_prefill_matches_atomic_cuda(multi_stream, wavefront): + model = make_gpu_model().to(dtype=torch.bfloat16) + shallow = DoryForCausalLM(tiny_dory_config(n_recurrent_loops=1)).to( + device=DEVICE, dtype=torch.bfloat16 + ) + shallow.load_state_dict(model.state_dict()) + prompts = {"shallow": [4, 7, 9, 3, 12, 6, 5], "full": [8, 2, 10, 11, 4]} + targets = {"shallow": 1, "full": 2} + + def run(selected_model, selected, *, staged): + engine = LLMEngine( + selected_model, + attention_backend="triton", + cache_config=CacheConfig(num_blocks=256, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed" if staged else "refill", + wavefront_chunked_prefill=wavefront if staged else False, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + execution_config=ExecutionConfig(multi_stream=multi_stream), + ) + try: + for request_id in selected: + engine.add_request( + request_id, + prompts[request_id], + SamplingParams(max_tokens=3, target_loops=targets[request_id], ignore_eos=True), + ) + outputs = drain(engine) + assert engine.cache_manager.num_used_blocks == 0 + return { + request_id: (output.token_ids, output.exit_depths) + for request_id, output in outputs.items() + } + finally: + engine.close() + + expected = run(shallow, ("shallow",), staged=False) | run(model, ("full",), staged=False) + assert run(model, ("shallow", "full"), staged=True) == expected + + @pytest.mark.parametrize("mode", EXECUTION_MODES) @pytest.mark.parametrize("after", [0, 1, 3, 6, 9]) def test_dory_cancellation_releases_kv_in_every_execution_mode(mode, after): diff --git a/tests/test_dory_real_checkpoint.py b/tests/test_dory_real_checkpoint.py index e0864c22..387b80aa 100644 --- a/tests/test_dory_real_checkpoint.py +++ b/tests/test_dory_real_checkpoint.py @@ -26,6 +26,7 @@ from vllm_rlt.core.kv_cache_manager import KVCacheManager from vllm_rlt.engine.llm_engine import LLMEngine from vllm_rlt.models import DoryForCausalLM, load_tokenizer +from vllm_rlt.request import RequestPhase CHECKPOINT = os.environ.get("DORY_CHECKPOINT") @@ -223,3 +224,101 @@ def test_real_checkpoint_generation_stops_on_eos_or_limit(): finally: del model torch.cuda.empty_cache() + + +def test_real_checkpoint_staged_mixed_depths_match_atomic(): + tokens, _ = prompt_tokens() + prompts = {"shallow": tokens.tolist(), "full": tokens.tolist() * 2} + targets = {"shallow": 1, "full": 2} + shallow = load("cuda", torch.bfloat16, 1) + full = load("cuda", torch.bfloat16, 2) + + def run(model, request_ids, *, staged, wavefront=False): + engine = LLMEngine( + model, + attention_backend="triton", + cache_config=CacheConfig(num_blocks=64, block_size=16), + scheduler_config=SchedulerConfig( + mode="mixed" if staged else "refill", + wavefront_chunked_prefill=wavefront, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + ) + first_logits = {} + coda = model.coda_prepared + + def capture(hidden, batch, cache, *, compute_logits=True): + logits = coda(hidden, batch, cache, compute_logits=compute_logits) + if logits is not None: + scheduled = engine.last_schedule + producing = [ + item + for item in scheduled.requests + if scheduled.phase_for(item) == RequestPhase.CODA + or ( + scheduled.phase_for(item) == RequestPhase.PREFILLING_CODA + and item.completes_prompt + ) + ] + for item, row in zip(producing, logits): + first_logits.setdefault(item.request.request_id, row.detach().float().clone()) + return logits + + model.coda_prepared = capture + try: + for request_id in request_ids: + engine.add_request( + request_id, + prompts[request_id], + SamplingParams(max_tokens=3, target_loops=targets[request_id], ignore_eos=True), + ) + outputs = {} + mixed_depths = False + while engine.has_unfinished_requests(): + for output in engine.step(): + if output.finished: + outputs[output.request_id] = (output.token_ids, output.exit_depths) + batch = engine.last_schedule + if batch is not None: + recurrent = [ + item + for item in batch.requests + if batch.phase_for(item) == RequestPhase.PREFILLING_RECURRENT + ] + mixed_depths |= len({item.request.target_loops for item in recurrent}) > 1 + assert engine.cache_manager.num_used_blocks == 0 + assert set(first_logits) == set(request_ids) + return outputs, mixed_depths, first_logits + finally: + model.coda_prepared = coda + engine.close() + + try: + shallow_output, _, shallow_logits = run(shallow, ("shallow",), staged=False) + full_output, _, full_logits = run(full, ("full",), staged=False) + expected = shallow_output | full_output + expected_logits = shallow_logits | full_logits + for wavefront in (False, True): + actual, mixed_depths, logits = run( + full, ("shallow", "full"), staged=True, wavefront=wavefront + ) + assert mixed_depths + assert actual == expected + for request_id in prompts: + reference = expected_logits[request_id] + top_ids = reference.topk(TOP_K).indices + actual_top = logits[request_id].topk(TOP_K).indices + overlap = len(set(top_ids.tolist()) & set(actual_top.tolist())) + deviation = (logits[request_id][top_ids] - reference[top_ids]).abs().max().item() + print( + f"wavefront={wavefront} request={request_id} output={actual[request_id]} " + f"top{TOP_K}_overlap={overlap}/{TOP_K} max|dlogit|={deviation:.4f}", + flush=True, + ) + assert overlap >= TOP_K - 2 + assert deviation <= MAX_TOP_DEVIATION + finally: + del shallow, full + torch.cuda.empty_cache() diff --git a/tests/test_fa4_fp8.py b/tests/test_fa4_fp8.py index 18c347b2..3a105f21 100644 --- a/tests/test_fa4_fp8.py +++ b/tests/test_fa4_fp8.py @@ -420,19 +420,20 @@ def run(execution): assert actual == expected -def test_dory_fp8_preserves_mixed_scheduler_rejection(): +def test_dory_fp8_staged_prefill_rejects_graphs(): from tests.test_dory import tiny_dory_config - from vllm_rlt import SchedulerConfig + from vllm_rlt import ExecutionConfig, SchedulerConfig from vllm_rlt.engine.llm_engine import LLMEngine from vllm_rlt.models import DoryForCausalLM model = DoryForCausalLM(tiny_dory_config(head_dim=256)) - with pytest.raises(ValueError, match="boundary-KV models do not support staged prefill"): + with pytest.raises(ValueError, match="staged prefill requires synchronous eager"): LLMEngine( model, attention_backend="flash_attn_4", cache_config=CacheConfig(kv_cache_dtype="fp8_e4m3"), scheduler_config=SchedulerConfig(mode="mixed"), + execution_config=ExecutionConfig(cuda_graphs=True), ) diff --git a/tests/test_huginn.py b/tests/test_huginn.py index 2a606835..8129ae57 100644 --- a/tests/test_huginn.py +++ b/tests/test_huginn.py @@ -248,7 +248,12 @@ def test_prefill_populates_history_without_projecting_unused_logits(model, padde SchedulerConfig(), "prefix caching", ), - (CacheConfig(), ExecutionConfig(), SchedulerConfig(mode="mixed"), "staged prefill"), + ( + CacheConfig(), + ExecutionConfig(), + SchedulerConfig(mode="mixed", enable_preemption=True), + "staged prefill", + ), ( CacheConfig(), ExecutionConfig(async_scheduling=True), @@ -269,6 +274,54 @@ def test_unsupported_execution_rejected_before_cache_allocation( ) +@pytest.mark.gpu +@pytest.mark.parametrize("temperature", [0.0, 0.7]) +@pytest.mark.parametrize("multi_stream", [False, True]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_huginn_staged_prefill_matches_atomic_cuda(multi_stream, wavefront, temperature): + torch.manual_seed(42) + model = ( + HuginnForCausalLM(tiny_huginn_config(n_embd=384, n_heads=4, intermediate_size=768)) + .to(device="cuda", dtype=torch.bfloat16) + .eval() + ) + prompts = {"a": [4], "b": [8, 2, 10, 11, 4, 3, 9]} + + def run(selected, *, staged): + engine = LLMEngine( + model, + attention_backend="triton", + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed" if staged else "refill", + wavefront_chunked_prefill=wavefront if staged else False, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + execution_config=ExecutionConfig(multi_stream=multi_stream), + ) + try: + for request_id in selected: + engine.add_request( + request_id, + prompts[request_id], + SamplingParams(max_tokens=3, seed=17, ignore_eos=True, temperature=temperature), + ) + outputs = {} + while engine.has_unfinished_requests(): + for output in engine.step(): + if output.finished: + outputs[output.request_id] = (output.token_ids, output.exit_depths) + assert engine.cache_manager.num_used_blocks == 0 + return outputs + finally: + engine.close() + + expected = run(("a",), staged=False) | run(("b",), staged=False) + assert run(("a", "b"), staged=True) == expected + + @pytest.mark.gpu @pytest.mark.parametrize("max_graphs", [1, 16]) def test_huginn_graph_replay_matches_eager_with_reuse_and_fallback(max_graphs): diff --git a/tests/test_prefill_coda.py b/tests/test_prefill_coda.py new file mode 100644 index 00000000..408733ac --- /dev/null +++ b/tests/test_prefill_coda.py @@ -0,0 +1,568 @@ +"""Staged attention-bearing prefill and request-local recurrent depths.""" + +import pytest +import torch + +from tests.helpers import tiny_ouro_model +from tests.reference.dory import dense_dory_reference +from tests.test_dory import tiny_dory_config +from tests.test_huginn import tiny_huginn_config +from vllm_rlt import CacheConfig, ExecutionConfig, SamplingParams, SchedulerConfig +from vllm_rlt.engine.llm_engine import LLMEngine +from vllm_rlt.models import DoryForCausalLM, HuginnForCausalLM +from vllm_rlt.request import Operation, RequestPhase +from vllm_rlt.worker.executor import ForwardBatch, ModelRuntime +from vllm_rlt.worker.model_runner import ModelRunner + + +def make_model(kind, loops=None): + torch.manual_seed(42) + if kind == "dory": + return DoryForCausalLM(tiny_dory_config(n_recurrent_loops=loops or 2)).eval() + return HuginnForCausalLM(tiny_huginn_config()).eval() + + +def run_requests( + model, scheduler, prompts, targets=None, *, mix_coda=False, temperature=0.0, execution=None +): + engine = LLMEngine( + model, + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=scheduler, + execution_config=execution, + ) + phases = [] + schedule = engine.scheduler.schedule + + def record_schedule(**kwargs): + prompt = engine.scheduler.requests.get("1") + if ( + mix_coda == "final" + and engine.scheduler.has_ready(RequestPhase.CODA) + and prompt is not None + and prompt.phase + in ( + RequestPhase.PREFILLING_PRELUDE, + RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, + ) + ): + last_chunk = (len(prompt.prompt_token_ids) - 1) // scheduler.prefill_chunk_size + ready_final = ( + prompt.phase == RequestPhase.PREFILLING_CODA + and prompt.num_recurrent_prefilled_tokens == len(prompt.prompt_token_ids) + and prompt.num_prefilled_tokens // scheduler.prefill_chunk_size == last_chunk + ) + batch = engine.scheduler.take_phases( + (RequestPhase.CODA, RequestPhase.PREFILLING_CODA) + if ready_final + else (prompt.phase,) + ) + elif ( + mix_coda + and engine.scheduler.has_ready(RequestPhase.CODA) + and engine.scheduler.has_ready(RequestPhase.PREFILLING_CODA) + ): + batch = engine.scheduler.take_phases((RequestPhase.CODA, RequestPhase.PREFILLING_CODA)) + else: + batch = schedule(**kwargs) + if batch is not None: + for item in batch.requests: + if batch.phase_for(item) == RequestPhase.PREFILLING_CODA: + assert item.token_start == item.request.num_prefilled_tokens + assert ( + item.token_start + item.token_count + <= item.request.num_recurrent_prefilled_tokens + ) + phases.append(batch) + return batch + + engine.scheduler.schedule = record_schedule + for index, prompt in enumerate(prompts): + engine.add_request( + str(index), + prompt, + SamplingParams( + max_tokens=3, + ignore_eos=True, + temperature=temperature, + target_loops=None if targets is None else targets[index], + ), + ) + outputs = {} + for _ in range(300): + if not engine.has_unfinished_requests(): + break + if engine.scheduler.staged_prefill and model.requires_prefill_coda: + for request in engine.scheduler.requests.values(): + assert ( + request.prefill_reclaimable_tokens + <= request.num_prefilled_tokens + <= request.num_recurrent_prefilled_tokens + <= request.num_preluded_tokens + <= len(request.prompt_token_ids) + ) + for output in engine.step(): + if output.finished: + outputs[output.request_id] = output + else: + pytest.fail("staged prefill did not finish") + return engine, outputs, phases + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_staged_prefill_matches_atomic(kind, wavefront): + prompts = [[4, 7, 9, 3, 12, 6, 5], [8, 2, 10, 11, 4]] + model = make_model(kind) + config = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ) + engine, actual, phases = run_requests(model, config, prompts) + assert any(batch.phase == RequestPhase.PREFILLING_CODA for batch in phases) + assert set(actual) == {"0", "1"} + for index, prompt in enumerate(prompts): + _, expected, _ = run_requests( + make_model(kind), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=4, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + assert actual[str(index)].exit_depths == expected["0"].exit_depths + assert len(engine.model_runner.batch_input_buffers) == 2 + assert ( + engine.model_runner.batch_input_buffers[0].hidden.data_ptr() + != engine.model_runner.batch_input_buffers[1].hidden.data_ptr() + ) + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_staged_prefill_with_static_padded_buffers_matches_atomic(kind, wavefront): + prompts = [[4, 7, 9, 3, 12, 6, 5], [8, 2, 10, 11, 4], [6, 7, 3]] + config = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=3, + max_num_batched_tokens=6, + prefill_chunk_size=2, + ) + _, actual, _ = run_requests( + make_model(kind), + config, + prompts, + execution=ExecutionConfig(static_buffers=True, pad_to_power_of_two=True), + ) + for index, prompt in enumerate(prompts): + _, expected, _ = run_requests( + make_model(kind), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=4, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + assert actual[str(index)].exit_depths == expected["0"].exit_depths + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +def test_bfloat16_wavefront_matches_independent_atomic_requests(kind): + prompts = [[4, 7, 9, 3, 12, 6, 5], [8, 2, 10, 11, 4]] + targets = [1, 2] if kind == "dory" else None + _, actual, _ = run_requests( + make_model(kind).to(dtype=torch.bfloat16), + SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=True, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + prompts, + targets, + ) + for index, prompt in enumerate(prompts): + target = targets[index] if targets is not None else None + _, expected, _ = run_requests( + make_model(kind, target).to(dtype=torch.bfloat16), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=4, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + assert actual[str(index)].exit_depths == expected["0"].exit_depths + + +@pytest.mark.parametrize("wavefront", [False, True]) +def test_dory_staged_mixed_fixed_depths_match_independent_models(wavefront): + prompts = [[4, 7, 9, 3, 12, 6, 5], [8, 2, 10, 11, 4]] + targets = [1, 2] + config = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ) + _, actual, phases = run_requests(make_model("dory"), config, prompts, targets) + assert any( + len({item.request.target_loops for item in batch.requests}) > 1 + and batch.phase == RequestPhase.PREFILLING_RECURRENT + for batch in phases + ) + if wavefront: + assert any( + len({item.depth for item in batch.requests}) > 1 + and batch.phase == RequestPhase.PREFILLING_RECURRENT + for batch in phases + ) + for index, (prompt, target) in enumerate(zip(prompts, targets)): + _, expected, _ = run_requests( + make_model("dory", target), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=4, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + assert actual[str(index)].exit_depths == [target] * 3 + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_prefill_coda_projects_only_selected_rows_and_matches_atomic_logits(kind, wavefront): + prompt = [4, 7, 9, 3, 12, 6, 5] + actual_model = make_model(kind) + expected_model = make_model(kind) + + def capture(model): + results = [] + masks = [] + calls = [] + coda = model.coda_prepared + + def wrapped(hidden, batch, cache, *, compute_logits=True): + if isinstance(compute_logits, torch.Tensor): + masks.append(compute_logits.clone()) + logits = coda(hidden, batch, cache, compute_logits=compute_logits) + if logits is not None: + results.append(logits.detach().clone()) + return logits + + model.coda_prepared = wrapped + model.lm_head.register_forward_pre_hook( + lambda module, inputs: calls.append(inputs[0].shape) + ) + return results, masks, calls + + actual_logits, masks, head_calls = capture(actual_model) + expected_logits, _, _ = capture(expected_model) + staged = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=1, + max_num_batched_tokens=2, + prefill_chunk_size=2, + ) + atomic = SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=2, prefill_chunk_size=2) + _, actual, _ = run_requests(actual_model, staged, [prompt]) + _, expected, _ = run_requests(expected_model, atomic, [prompt]) + assert actual["0"].token_ids == expected["0"].token_ids + assert len(actual_logits) == len(expected_logits) == len(head_calls) == 3 + assert any(not mask.any() for mask in masks) + assert sum(mask.sum().item() for mask in masks) == 1 + assert all(shape[0] == 1 for shape in head_calls) + for actual_row, expected_row in zip(actual_logits, expected_logits): + torch.testing.assert_close(actual_row, expected_row, rtol=3e-5, atol=3e-6) + + +@pytest.mark.parametrize("target", [1, 2]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_dory_fixed_depth_prefill_logits_match_dense_reference(target, wavefront): + prompt = [4, 7, 9, 3, 12, 6, 5] + model = make_model("dory") + logits = [] + coda = model.coda_prepared + + def wrapped(hidden, batch, cache, *, compute_logits=True): + result = coda(hidden, batch, cache, compute_logits=compute_logits) + if result is not None: + logits.append(result.detach().clone()) + return result + + model.coda_prepared = wrapped + _, actual, _ = run_requests( + model, + SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=1, + max_num_batched_tokens=3, + prefill_chunk_size=2, + ), + [prompt], + [target], + ) + reference = make_model("dory", target) + tokens = list(prompt) + for row, token in zip(logits, actual["0"].token_ids): + expected = dense_dory_reference(reference, torch.tensor(tokens))["logits"][-1] + torch.testing.assert_close(row[0], expected, rtol=3e-5, atol=3e-6) + tokens.append(token) + + +@pytest.mark.parametrize("budget", [1, 3, 5]) +@pytest.mark.parametrize("wavefront", [False, True]) +def test_partial_chunks_and_three_fixed_depths(budget, wavefront): + prompts = [[4, 7, 9, 3, 12], [8, 2, 10], [11, 4, 3, 9, 6, 5, 2]] + targets = [1, 2, 3] + _, actual, _ = run_requests( + make_model("dory", 3), + SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=3, + max_num_batched_tokens=budget, + prefill_chunk_size=3, + ), + prompts, + targets, + ) + for index, (prompt, target) in enumerate(zip(prompts, targets)): + _, expected, _ = run_requests( + make_model("dory", target), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=3, prefill_chunk_size=3), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + assert actual[str(index)].exit_depths == [target] * 3 + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +def test_mixed_coda_execution_routes_sparse_results(kind, monkeypatch): + prompts = [[4], [8, 2, 10, 11, 4, 3, 9, 6]] + targets = [1, 2] if kind == "dory" else None + config = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=True, + max_num_seqs=2, + max_num_batched_tokens=3, + prefill_chunk_size=2, + ) + original = ModelRunner._mixed_hidden_sources + checked = [] + + def check_sources(runner, batch, buffers): + states = [span.request.hidden_state for span in batch.spans] + original(runner, batch, buffers) + if batch.operation == Operation.CODA: + assert all( + span.request.hidden_state is state for span, state in zip(batch.spans, states) + ) + checked.append(True) + + monkeypatch.setattr(ModelRunner, "_mixed_hidden_sources", check_sources) + _, actual, phases = run_requests(make_model(kind), config, prompts, targets, mix_coda=True) + assert checked + assert any( + {batch.phase_for(item) for item in batch.requests} + == {RequestPhase.CODA, RequestPhase.PREFILLING_CODA} + for batch in phases + ) + for index, prompt in enumerate(prompts): + target = targets[index] if targets is not None else None + _, expected, _ = run_requests( + make_model(kind, target), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=3, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + + +@pytest.mark.parametrize("temperature", [0.0, 0.7]) +def test_huginn_seed_is_invariant_to_chunking_and_mixed_prelude(temperature): + prompts = [[4], [8, 2, 10, 11, 4, 3, 9]] + _, actual, _ = run_requests( + make_model("huginn"), + SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=True, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ), + prompts, + mix_coda="final", + temperature=temperature, + ) + for index, prompt in enumerate(prompts): + _, expected, _ = run_requests( + make_model("huginn"), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=3, prefill_chunk_size=3), + [prompt], + temperature=temperature, + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +def test_mixed_coda_samples_final_prompt_and_decode_in_one_batch(kind): + prompts = [[4], [8, 2, 10, 11, 4, 3, 9]] + targets = [1, 2] if kind == "dory" else None + config = SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=True, + max_num_seqs=2, + max_num_batched_tokens=4, + prefill_chunk_size=2, + ) + _, actual, phases = run_requests(make_model(kind), config, prompts, targets, mix_coda="final") + assert any( + {batch.phase_for(item) for item in batch.requests} + == {RequestPhase.CODA, RequestPhase.PREFILLING_CODA} + and any(item.completes_prompt for item in batch.requests) + for batch in phases + ) + for index, prompt in enumerate(prompts): + target = targets[index] if targets is not None else None + _, expected, _ = run_requests( + make_model(kind, target), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=4, prefill_chunk_size=2), + [prompt], + ) + assert actual[str(index)].token_ids == expected["0"].token_ids + + +def test_sparse_logits_mask_for_models_without_coda_attention(): + model = tiny_ouro_model() + hidden = torch.randn(3, model.config.hidden_size) + runtime = ModelRuntime(model, None) + mask = torch.tensor([False, True, False]) + forward = ForwardBatch(Operation.CODA, hidden=hidden, compute_logits=mask, graphs=object()) + prepared = runtime.prepare(forward) + assert prepared.graphs is None + torch.testing.assert_close(runtime.forward(prepared).logits, model.coda(hidden[1:2])) + assert ( + runtime.forward( + ForwardBatch( + Operation.CODA, hidden=hidden, compute_logits=torch.zeros(3, dtype=torch.bool) + ) + ).logits + is None + ) + + +@pytest.mark.parametrize("kind", ["dory", "huginn"]) +@pytest.mark.parametrize("mask", [torch.ones(2), torch.ones(1, 3, dtype=torch.bool)]) +def test_coda_rejects_invalid_logits_mask_before_writing_kv(kind, mask): + model = make_model(kind) + hidden = torch.randn(3, model.config.hidden_size) + with pytest.raises(ValueError, match="boolean mask for every CODA row"): + model.coda_prepared(hidden, None, None, compute_logits=mask) + + +def test_first_prefill_sample_can_finish_without_decode_coda(): + model = make_model("dory") + + def force_eos(state): + logits = torch.full((len(state), model.config.vocab_size), -1.0, device=state.device) + logits[:, model.config.eos_token_id] = 1.0 + return logits + + model.logits = force_eos + engine = LLMEngine( + model, + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed", max_num_seqs=1, max_num_batched_tokens=2, prefill_chunk_size=2 + ), + ) + engine.add_request("request", [4, 7, 9], SamplingParams(max_tokens=3)) + outputs = [] + phases = [] + while engine.has_unfinished_requests(): + outputs.extend(engine.step()) + phases.append(engine.last_schedule.phase) + assert [output.token_ids for output in outputs] == [[model.config.eos_token_id[0]]] + assert outputs[0].finished + assert RequestPhase.PREFILLING_CODA in phases + assert RequestPhase.CODA not in phases + + +def test_staged_prefill_continuous_admission_and_completion(): + engine = LLMEngine( + make_model("dory"), + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=True, + max_num_seqs=2, + max_num_batched_tokens=2, + prefill_chunk_size=2, + ), + ) + params = SamplingParams(max_tokens=1, ignore_eos=True) + engine.add_request("long", [4, 7, 9, 3, 12, 6, 5, 2, 8, 11, 10], params) + engine.step() + engine.add_request("short", [4], params) + finished = [] + while engine.has_unfinished_requests(): + finished.extend(output.request_id for output in engine.step() if output.finished) + assert finished == ["short", "long"] + assert engine.cache_manager.num_used_blocks == 0 + + +@pytest.mark.parametrize("wavefront", [False, True]) +@pytest.mark.parametrize("complete_chunk", [False, True]) +def test_abort_around_prefill_coda_releases_request_state(wavefront, complete_chunk): + engine = LLMEngine( + make_model("dory"), + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=SchedulerConfig( + mode="mixed", + wavefront_chunked_prefill=wavefront, + max_num_seqs=1, + max_num_batched_tokens=2, + prefill_chunk_size=2, + ), + ) + params = SamplingParams(max_tokens=3, target_loops=1, ignore_eos=True) + engine.add_request("reused", [4, 7, 9, 3, 12], params) + request = engine.scheduler.requests["reused"] + for _ in range(30): + if request.phase == RequestPhase.PREFILLING_CODA: + break + engine.step() + else: + pytest.fail("request did not reach prefill CODA") + if complete_chunk: + engine.step() + assert request.num_prefilled_tokens == 2 + engine.abort_request("reused") + assert not engine.model_runner.state_slots + assert engine.cache_manager.num_used_blocks == 0 + + prompt = [5, 4, 3] + engine.add_request("reused", prompt, params) + actual = [] + while engine.has_unfinished_requests(): + actual.extend(output for output in engine.step() if output.finished) + _, expected, _ = run_requests( + make_model("dory", 1), + SchedulerConfig(max_num_seqs=1, max_num_batched_tokens=2, prefill_chunk_size=2), + [prompt], + ) + assert actual[0].token_ids == expected["0"].token_ids + assert actual[0].exit_depths == expected["0"].exit_depths + + +@pytest.mark.parametrize( + "execution", [ExecutionConfig(async_scheduling=True), ExecutionConfig(cuda_graphs=True)] +) +def test_boundary_staged_rejects_unqualified_execution(execution): + with pytest.raises(ValueError, match="staged prefill requires synchronous eager"): + LLMEngine( + make_model("dory"), + cache_config=CacheConfig(num_blocks=128, block_size=2), + scheduler_config=SchedulerConfig(mode="mixed"), + execution_config=execution, + ) diff --git a/tests/test_submission_queue.py b/tests/test_submission_queue.py index 80e31a43..996f8dc1 100644 --- a/tests/test_submission_queue.py +++ b/tests/test_submission_queue.py @@ -68,15 +68,21 @@ def test_failed_submission_gap_drains_before_slot_reuse(): def test_submission_slots_reuse_preallocated_prefill_storage(): - buffers = [BatchInputBuffers(2, 4, torch.device("cpu"), torch.float32) for _ in range(2)] + buffers = [ + BatchInputBuffers(2, 4, torch.device("cpu"), torch.float32, hidden_shape=(4, 8)) + for _ in range(2) + ] queue = SubmissionQueue() queue.begin() first = buffers[queue.slot] first_ptr = first.segments.cpu.data_ptr() + first_hidden_ptr = first.hidden.data_ptr() queue.begin() second = buffers[queue.slot] assert second.segments.cpu.data_ptr() != first_ptr + assert second.hidden.data_ptr() != first_hidden_ptr queue.begin() assert buffers[queue.slot] is first first.reset() assert first.segments.cpu.data_ptr() == first_ptr + assert first.hidden.data_ptr() == first_hidden_ptr diff --git a/vllm_rlt/core/scheduler.py b/vllm_rlt/core/scheduler.py index 9c9bce7f..1d87b4af 100644 --- a/vllm_rlt/core/scheduler.py +++ b/vllm_rlt/core/scheduler.py @@ -15,6 +15,7 @@ RequestPhase.PREFILL, RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, RequestPhase.SPECULATIVE, ) # Stages that must reserve KV capacity for that frontier before selection. @@ -138,12 +139,14 @@ def __init__( *, produces_tokens: bool = True, total_ut_steps: int | None = None, + requires_prefill_coda: bool = False, eos_token_id=(), exit_mode: str = "ouro", ): self.config = config self.cache_manager = cache_manager self.speculative_config = speculative_config + self.requires_prefill_coda = requires_prefill_coda self.total_ut_steps = ( total_ut_steps if total_ut_steps is not None else getattr(cache_manager, "max_loops", 1) ) @@ -172,6 +175,8 @@ def __init__( speculative_config, produces_tokens=produces_tokens, ) + if self.staged_prefill and self.requires_prefill_coda: + self.policy.PREFILL_PHASES += (RequestPhase.PREFILLING_CODA,) def add_request(self, request: Request): if request.request_id in self.requests: @@ -364,6 +369,7 @@ def _reserved_growth_blocks(self, *, reserve_outputs: bool) -> int: RequestPhase.PREFILL, RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, ) and not (reserve_outputs and has_allocation): continue tokens = len(request.prompt_token_ids) @@ -451,6 +457,7 @@ def _commit_admission(self, request: Request, plan: AdmissionPlan) -> bool: if not self._allocate(request, plan): return False request.num_prefilled_tokens = plan.cached_tokens + request.num_recurrent_prefilled_tokens = plan.cached_tokens # A reused prompt prefix is already prefilled at every depth, so the # staged window starts closed at that frontier and opens for the rest. request.num_preluded_tokens = plan.cached_tokens @@ -564,7 +571,7 @@ def _make_scheduled_request( token_budget, self.config.prefill_chunk_size, len(request.prompt_token_ids) - start ) return ScheduledRequest(request, start, count) - # The two split phases are unreachable while atomic prefill is enabled. + # Staged phases are unreachable while atomic prefill is enabled. if phase == RequestPhase.PREFILLING_PRELUDE: start = request.num_preluded_tokens count = min( @@ -574,7 +581,11 @@ def _make_scheduled_request( ) return ScheduledRequest(request, start, count, chunk_start=start) if phase == RequestPhase.PREFILLING_RECURRENT: - start = request.num_prefilled_tokens + start = ( + request.num_recurrent_prefilled_tokens + if self.requires_prefill_coda + else request.num_prefilled_tokens + ) if start >= request.num_preluded_tokens: return ScheduledRequest( request, start, 0, depth=0, chunk_start=request.prefill_reclaimable_tokens @@ -603,6 +614,28 @@ def _make_scheduled_request( and start + count == len(request.prompt_token_ids) ), ) + if phase == RequestPhase.PREFILLING_CODA: + start = request.num_prefilled_tokens + chunk_size = self.config.prefill_chunk_size + if self.wavefront_chunked_prefill: + origin = request.prefill_window_origin + chunk_start = origin + (start - origin) // chunk_size * chunk_size + slot = ((chunk_start - origin) // chunk_size) % len(request.prefill_depth_ranges) + offset = slot * chunk_size + start - chunk_start + chunk_end = min(len(request.prompt_token_ids), chunk_start + chunk_size) + else: + chunk_start = request.prefill_reclaimable_tokens + offset = start - chunk_start + chunk_end = request.num_preluded_tokens + end = min(start + token_budget, request.num_recurrent_prefilled_tokens, chunk_end) + return ScheduledRequest( + request, + start, + max(0, end - start), + chunk_start=chunk_start, + completes_prompt=end == len(request.prompt_token_ids), + prefill_hidden_row_offset=offset, + ) if phase == RequestPhase.SPECULATIVE: # K candidates plus one bonus distribution. At the output limit, # K=0 is an ordinary fixed-depth step and needs no extra KV slot. @@ -742,7 +775,12 @@ def take_phases(self, phases, *, eligible=None): continue scheduled_request = self._make_scheduled_request(request, phase, token_budget) if ( - phase in (RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT) + phase + in ( + RequestPhase.PREFILLING_PRELUDE, + RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, + ) and scheduled_request.token_count <= 0 ): queue.append(request.request_id) @@ -799,13 +837,17 @@ def _planned_loop_count(self, scheduled_requests): phases = {item.phase for item in scheduled_requests} if phases == {RequestPhase.PREFILL}: return self.total_ut_steps - if RequestPhase.SPECULATIVE in phases or RequestPhase.CODA in phases: + if phases.intersection( + (RequestPhase.SPECULATIVE, RequestPhase.CODA, RequestPhase.PREFILLING_CODA) + ): return 0 if RequestPhase.PRELUDE in phases: return 0 if self.wavefront_chunked_prefill: return 1 if RequestPhase.PREFILLING_RECURRENT in phases else 0 if RequestPhase.PREFILLING_PRELUDE in phases: + if self.requires_prefill_coda: + return 0 # In mixed mode, stage just the embeddings when recurrent decode work # is ready so the next depth can join that batch. Without a reason to # yield, PRELUDE can execute the full prompt depth in this submission. @@ -828,7 +870,14 @@ def _batch_loop_count(self, batch): phases = {batch.phase_for(item) for item in batch.requests} if RequestPhase.PREFILL in phases: return self.total_ut_steps - if phases.intersection((RequestPhase.PRELUDE, RequestPhase.CODA, RequestPhase.SPECULATIVE)): + if phases.intersection( + ( + RequestPhase.PRELUDE, + RequestPhase.CODA, + RequestPhase.PREFILLING_CODA, + RequestPhase.SPECULATIVE, + ) + ): return 0 if phases.intersection((RequestPhase.PREFILLING_RECURRENT, RequestPhase.RECURRENT)): return 1 @@ -847,11 +896,13 @@ def _max_contiguous_prefill_loops(self, scheduled_request): return max(1, loops) def _scheduled_prefill_completes(self, scheduled_request, loop_count): + if self.requires_prefill_coda: + return False phase = scheduled_request.phase depth = scheduled_request.depth if phase == RequestPhase.PREFILLING_RECURRENT else 0 return ( loop_count > 0 - and depth + loop_count == self.total_ut_steps + and depth + loop_count == len(scheduled_request.request.prefill_depth_ranges) and scheduled_request.token_start + scheduled_request.token_count == len(scheduled_request.request.prompt_token_ids) ) @@ -885,7 +936,7 @@ def _take_wavefront_phase( added = set() blocked = set() - total_depths = len(candidates[0].prefill_depth_ranges) + total_depths = max(len(request.prefill_depth_ranges) for request in candidates) def accept_task(request: Request, scheduled_request: ScheduledRequest) -> bool: """Reserve capacity and commit one wavefront task to this batch.""" @@ -917,6 +968,8 @@ def accept_task(request: Request, scheduled_request: ScheduledRequest) -> bool: assert prelude_cursors is not None start, end = prelude_cursors[request_id], len(request.prompt_token_ids) else: + if depth >= len(request.prefill_depth_ranges): + continue start, end = request.prefill_depth_ranges[depth] end = min(end, request.num_preluded_tokens) if start >= end: @@ -971,12 +1024,48 @@ def _advance_prefill_depth_frontier( ) -> bool: """Advance one submitted prompt span through one recurrent depth.""" request.prefill_depth_ranges[depth][0] = token_end - if depth + 1 < self.total_ut_steps: + if depth + 1 < len(request.prefill_depth_ranges): request.prefill_depth_ranges[depth + 1][1] = token_end return False - request.num_prefilled_tokens = token_end + if self.requires_prefill_coda: + request.num_recurrent_prefilled_tokens = token_end + else: + request.num_prefilled_tokens = token_end return True + def _apply_prefill_coda_progress(self, scheduled_request, *, event=None): + request = scheduled_request.request + start = scheduled_request.token_start + end = start + scheduled_request.token_count + if start != request.num_prefilled_tokens or end > request.num_recurrent_prefilled_tokens: + raise RuntimeError("prefill CODA crosses an incomplete causal frontier") + request.num_prefilled_tokens = end + if self.wavefront_chunked_prefill: + chunk_end = min( + len(request.prompt_token_ids), + scheduled_request.chunk_start + self.config.prefill_chunk_size, + ) + else: + chunk_end = request.num_preluded_tokens + chunk_complete = end == chunk_end + if chunk_complete: + if scheduled_request.chunk_start != request.prefill_reclaimable_tokens: + raise RuntimeError("prefill CODA completed chunks out of order") + request.prefill_reclaimable_tokens = end + self.cache_manager.publish_prefix( + request.request_id, request.prompt_token_ids, end, event + ) + prompt_complete = end == len(request.prompt_token_ids) + if prompt_complete: + request.loops_done = len(request.prefill_depth_ranges) + elif end < request.num_recurrent_prefilled_tokens: + self.enqueue(request, RequestPhase.PREFILLING_CODA) + elif self._prelude_window_open(request): + self.enqueue(request, RequestPhase.PREFILLING_PRELUDE) + else: + self.enqueue(request, RequestPhase.PREFILLING_RECURRENT) + return PrefillProgress(chunk_complete, prompt_complete) + def _apply_split_prefill_progress( self, scheduled_request: ScheduledRequest, @@ -991,7 +1080,9 @@ def _apply_split_prefill_progress( and consumers with that work; this transition does not wait for it. """ request = scheduled_request.request - total_depths = self.total_ut_steps + if phase == RequestPhase.PREFILLING_CODA: + return self._apply_prefill_coda_progress(scheduled_request, event=event) + total_depths = len(request.prefill_depth_ranges) start = scheduled_request.token_start end = start + scheduled_request.token_count if loop_count is None: @@ -1025,6 +1116,10 @@ def _apply_split_prefill_progress( token_end=end, ) + if self.requires_prefill_coda and final_depth_reached: + self.enqueue(request, RequestPhase.PREFILLING_CODA) + return PrefillProgress(False, False) + chunk_complete = final_depth_reached and end == request.num_preluded_tokens if not final_depth_reached or not chunk_complete: self.enqueue(request, RequestPhase.PREFILLING_RECURRENT) @@ -1126,6 +1221,9 @@ def _apply_wavefront_prefill_batch_progress( ): continue + if self.requires_prefill_coda: + continue + chunk_end = min( len(request.prompt_token_ids), item.chunk_start + self.config.prefill_chunk_size, @@ -1146,7 +1244,11 @@ def _apply_wavefront_prefill_batch_progress( request.num_prefilled_tokens, event, ) - if prompt_complete: + if self.requires_prefill_coda and ( + request.num_prefilled_tokens < request.num_recurrent_prefilled_tokens + ): + next_phase = RequestPhase.PREFILLING_CODA + elif prompt_complete: request.loops_done = self.total_ut_steps next_phase = self._prompt_destination(request) else: @@ -1213,6 +1315,7 @@ def _apply_prefill_phase_progress( RequestPhase.PREFILL, RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, ): event = ( request_events.get(request.request_id) @@ -1296,6 +1399,11 @@ def update_from_output( update = SchedulerUpdate() wavefront_groups = self._wavefront_prefill_groups(batch) loop_count = self._batch_loop_count(batch) + output_rows = ( + {batch_row: output_row for output_row, batch_row in enumerate(result.output_rows)} + if result.output_rows is not None + else None + ) for row, scheduled_request in enumerate(batch.requests): request = scheduled_request.request # Ignore results for a request that is no longer registered: it may @@ -1316,6 +1424,17 @@ def update_from_output( request_events=request_events, fallback_event=result.completion, ): + if phase == RequestPhase.PREFILLING_CODA and scheduled_request.completes_prompt: + output_row = output_rows.get(row) if output_rows is not None else row + if output_row is None or result.token_ids is None: + raise RuntimeError("final prefill CODA did not produce a token") + if self._record_token( + request, result.token_ids[output_row], request.loops_done + ): + update.finished.append(request) + else: + self.enqueue(request, RequestPhase.PRELUDE) + update.outputs.append(request) continue if phase == RequestPhase.PRELUDE: request.loops_done = 0 @@ -1347,6 +1466,7 @@ def update_from_output( update.exited.append(request) self.enqueue(request, RequestPhase.CODA if should_exit else RequestPhase.RECURRENT) elif phase == RequestPhase.CODA: + output_row = output_rows[row] if output_rows is not None else row if delivered: if not result.output_indices or result.output_indices[row] != len( request.generated_token_ids @@ -1356,7 +1476,7 @@ def update_from_output( raise RuntimeError("invalid pending output count") request.num_output_placeholders -= 1 depth = result.depths[row] if delivered else request.loops_done - if self._record_token(request, result.token_ids[row], depth): + if self._record_token(request, result.token_ids[output_row], depth): update.finished.append(request) elif not delivered: self.enqueue( diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index a8006977..ba0547b5 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -111,9 +111,16 @@ def __init__( preemption=scheduler_config.enable_preemption, ) if getattr(model, "requires_boundary_kv", False): - if staged_prefill: + if staged_prefill and ( + self.execution_config.async_scheduling + or self.execution_config.cuda_graphs + or scheduler_config.enable_preemption + or speculative_config is not None + or not self.stage_config.produces_tokens + ): raise ValueError( - "boundary-KV models do not support staged prefill required by this scheduler" + "boundary-KV staged prefill requires synchronous eager generation " + "without speculation or preemption" ) if self.execution_config.async_scheduling and not getattr( model, "supports_async_scheduling", False @@ -293,6 +300,7 @@ def __init__( speculative_config, produces_tokens=self.stage_config.produces_tokens, total_ut_steps=config.total_ut_steps, + requires_prefill_coda=getattr(model, "requires_prefill_coda", False), eos_token_id=config.eos_token_id, exit_mode=self.exit_config.mode, ) @@ -416,7 +424,10 @@ def _resolve_loop_bounds(self, params): "min_loops and max_loops must match the fixed target_loops when specified, " "except the min_loops default" ) - if target_loops != model_depth: + if target_loops != model_depth and not ( + self.scheduler.staged_prefill + and getattr(self.model, "requires_prefill_coda", False) + ): raise ValueError( "target_loops below total_ut_steps requires per-request prefill support" ) @@ -504,10 +515,13 @@ def _add_request(self, request_id, prompt_token_ids, sampling_params, *, trace_i list(prompt_token_ids), params, exit_trace=trace, - # Prefill always runs the model's full depth, whatever decode - # loop bound the request asks for. prefill_depth_ranges=Request.prefill_boundaries( - len(prompt_token_ids), config.total_ut_steps + len(prompt_token_ids), + target_loops + if fixed_loop_count + and self.scheduler.staged_prefill + and target_loops is not None + else config.total_ut_steps, ), _target_loops=( target_loops if fixed_loop_count and self.exit_config.mode != "trace" else None diff --git a/vllm_rlt/models/dory.py b/vllm_rlt/models/dory.py index 5f60482b..99b2fc42 100644 --- a/vllm_rlt/models/dory.py +++ b/vllm_rlt/models/dory.py @@ -480,6 +480,7 @@ class DoryForCausalLM(nn.Module): """Inference-only Dory with eager KV boundaries and a graphable recurrent core.""" requires_boundary_kv = True + requires_prefill_coda = True # No Ouro-style learned exit gate: a request uses one fixed target depth. fixed_loop_count = True # Fixed loops need no exit signal, so ordinary asynchronous scheduling can @@ -583,11 +584,23 @@ def recurrent_prepared(self, hidden, batch, cache, *, compute_gate: bool = True) ) return torch.cat((state, injection), dim=-1), gate - def coda_prepared(self, hidden, batch, cache, *, compute_logits: bool = True): + def coda_prepared(self, hidden, batch, cache, *, compute_logits: bool | torch.Tensor = True): """Run the attention-bearing output stage and the scaled LM head.""" + if isinstance(compute_logits, torch.Tensor) and ( + compute_logits.dtype != torch.bool + or compute_logits.ndim != 1 + or compute_logits.numel() != len(hidden) + ): + raise ValueError("compute_logits must be a boolean mask for every CODA row") state, _ = hidden.split(self.config.d_model, dim=-1) for index in self.backbone.output_layers: state = self.backbone.layers[index](state, batch.position_ids, batch, cache) + if isinstance(compute_logits, torch.Tensor): + rows = torch.nonzero(compute_logits, as_tuple=True)[0] + if not rows.numel(): + return None + state = state.index_select(0, rows.to(state.device)) + compute_logits = True return self.logits(state) if compute_logits else None def logits(self, state: torch.Tensor) -> torch.Tensor: diff --git a/vllm_rlt/models/huginn.py b/vllm_rlt/models/huginn.py index b7c4c117..27110272 100644 --- a/vllm_rlt/models/huginn.py +++ b/vllm_rlt/models/huginn.py @@ -202,6 +202,7 @@ class HuginnForCausalLM(nn.Module): """Huginn-0125 with eager KV boundaries and a graphable recurrent core.""" requires_boundary_kv = True + requires_prefill_coda = True def __init__(self, config: HuginnConfig) -> None: super().__init__() @@ -258,20 +259,15 @@ def prelude_prepared( for block in self.transformer.prelude: hidden = block(hidden, freqs, batch, cache) state = torch.empty_like(hidden) - start = 0 - while start < len(state): - end = start + 1 - generator = generators[start] if generators is not None else None - while end < len(state) and (generators is None or generators[end] is generator): - end += 1 + for row in range(len(state)): + generator = generators[row] if generators is not None else None torch.nn.init.trunc_normal_( - state[start:end], + state[row : row + 1], std=self.config.initializer_range, a=-3 * self.config.initializer_range, b=3 * self.config.initializer_range, generator=generator, ) - start = end state = state * math.sqrt(self.config.n_embd) return torch.cat((state, hidden), dim=-1) @@ -295,11 +291,23 @@ def recurrent(self, hidden, request_ids, depths, positions, cache, *, compute_ga def coda_prepared( self, hidden, batch: "KVMetadata", cache: "KVCacheManager", *, compute_logits=True ): + if isinstance(compute_logits, torch.Tensor) and ( + compute_logits.dtype != torch.bool + or compute_logits.ndim != 1 + or compute_logits.numel() != len(hidden) + ): + raise ValueError("compute_logits must be a boolean mask for every CODA row") state, _ = hidden.split(self.config.n_embd, dim=-1) state = self.transformer.ln_f(state) freqs = self._freqs(batch) for block in self.transformer.coda: state = block(state, freqs, batch, cache) + if isinstance(compute_logits, torch.Tensor): + rows = torch.nonzero(compute_logits, as_tuple=True)[0] + if not rows.numel(): + return None + state = state.index_select(0, rows.to(state.device)) + compute_logits = True return self.lm_head(self.transformer.ln_f(state)) if compute_logits else None @classmethod diff --git a/vllm_rlt/request.py b/vllm_rlt/request.py index 66322808..2fe649d7 100644 --- a/vllm_rlt/request.py +++ b/vllm_rlt/request.py @@ -15,6 +15,7 @@ class RequestPhase(str, Enum): PREFILL = "prefill" PREFILLING_PRELUDE = "prefilling_prelude" PREFILLING_RECURRENT = "prefilling_recurrent" + PREFILLING_CODA = "prefilling_coda" PRELUDE = "prelude" RECURRENT = "recurrent" SPECULATIVE = "speculative" @@ -47,6 +48,7 @@ class Request: num_speculative_rounds: int = 0 input_token_tensor: torch.Tensor | None = field(default=None, repr=False) num_prefilled_tokens: int = 0 + num_recurrent_prefilled_tokens: int = 0 # Split prefill: [num_prefilled_tokens, num_preluded_tokens) has resident # hidden states; wavefront keeps multiple chunks at distinct depths here. num_preluded_tokens: int = 0 @@ -55,7 +57,7 @@ class Request: # Wavefront chunk slots are assigned relative to this cached-prefix origin. prefill_window_origin: int = 0 # End of the completed prefix and start of the oldest resident chunk. Advance - # only after final-depth completion releases that chunk's hidden-state slot. + # only after its final required stage releases the hidden-state slot. prefill_reclaimable_tokens: int = 0 # Host-side decode progress; ModelRunner events track pending device work. loops_done: int = 0 @@ -147,6 +149,7 @@ class StateSpan: # Row offset in the request's prefill hidden-state buffer. None lets the runner # derive token_start - chunk_start. prefill_hidden_row_offset: int | None = None + compute_logits: bool = True @dataclass(frozen=True) diff --git a/vllm_rlt/worker/buffers.py b/vllm_rlt/worker/buffers.py index 621e1715..1fd79f3a 100644 --- a/vllm_rlt/worker/buffers.py +++ b/vllm_rlt/worker/buffers.py @@ -54,7 +54,7 @@ def execution_buffer_bytes( total += scheduler.max_num_seqs * stage_rows * hidden # Split recurrent batches gather staged rows into a contiguous model input. if stage_rows: - total += rows * hidden + total += MAX_CONCURRENT_SUBMISSIONS * rows * hidden span_capacity = rows if scheduler.wavefront_chunked_prefill else scheduler.max_num_seqs total += MAX_CONCURRENT_SUBMISSIONS * ( span_capacity * (5 + 4 * 8) * 8 + max(rows, scheduler.prefill_chunk_size) * 8 diff --git a/vllm_rlt/worker/executor.py b/vllm_rlt/worker/executor.py index 70404371..0ff5e0cb 100644 --- a/vllm_rlt/worker/executor.py +++ b/vllm_rlt/worker/executor.py @@ -13,7 +13,9 @@ from vllm_rlt.request import ExecutionBatch, Operation, RequestPhase, StateSpan -def build_execution_batch(scheduled_batch: SchedulerOutput, total_depths: int) -> ExecutionBatch: +def build_execution_batch( + scheduled_batch: SchedulerOutput, total_depths: int, *, requires_prefill_coda: bool = False +) -> ExecutionBatch: """Bind selected Request references to immutable operation/position/depth rows. This creates scalar execution descriptors, not new Requests or KV metadata. @@ -26,13 +28,18 @@ def build_execution_batch(scheduled_batch: SchedulerOutput, total_depths: int) - for scheduled_request in scheduled_batch.requests: phase = scheduled_batch.phase_for(scheduled_request) request = scheduled_request.request - chunk = phase in (RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT) + chunk = phase in ( + RequestPhase.PREFILLING_PRELUDE, + RequestPhase.PREFILLING_RECURRENT, + RequestPhase.PREFILLING_CODA, + ) prompt_input = phase in (RequestPhase.PREFILL, RequestPhase.PREFILLING_PRELUDE) operation = { RequestPhase.PREFILL: Operation.PRELUDE, RequestPhase.PREFILLING_PRELUDE: Operation.PRELUDE, RequestPhase.PRELUDE: Operation.PRELUDE, RequestPhase.PREFILLING_RECURRENT: Operation.RECURRENT, + RequestPhase.PREFILLING_CODA: Operation.CODA, RequestPhase.RECURRENT: Operation.RECURRENT, RequestPhase.CODA: Operation.CODA, }.get(phase) @@ -64,8 +71,19 @@ def build_execution_batch(scheduled_batch: SchedulerOutput, total_depths: int) - token_count=scheduled_request.token_count, depth=depth, chunk_start=scheduled_request.chunk_start if chunk else None, - retain_chunk=chunk and depth + execution_loops < total_depths, - retain_last=scheduled_request.completes_prompt if chunk else True, + retain_chunk=( + chunk + and operation != Operation.CODA + and ( + requires_prefill_coda + or depth + execution_loops < len(request.prefill_depth_ranges) + ) + ), + retain_last=( + scheduled_request.completes_prompt and not requires_prefill_coda + if chunk + else True + ), emit_gate=phase == RequestPhase.RECURRENT, input_tokens=tuple( request.prompt_token_ids[position : position + scheduled_request.token_count] @@ -75,6 +93,8 @@ def build_execution_batch(scheduled_batch: SchedulerOutput, total_depths: int) - prefill_hidden_row_offset=( scheduled_request.prefill_hidden_row_offset if chunk else None ), + compute_logits=phase != RequestPhase.PREFILLING_CODA + or scheduled_request.completes_prompt, ) ) operations.add(operation) @@ -100,7 +120,11 @@ def submit(self, scheduled_batch): if self.speculation is None: raise ValueError("speculative submission requires a configured round controller") return self.speculation.submit(scheduled_batch) - batch = build_execution_batch(scheduled_batch, self.runner.model.config.total_ut_steps) + batch = build_execution_batch( + scheduled_batch, + self.runner.model.config.total_ut_steps, + requires_prefill_coda=getattr(self.runner.model, "requires_prefill_coda", False), + ) return self.runner.submit(scheduled_batch, batch=batch) @@ -113,9 +137,10 @@ class ForwardBatch: both phases, rather than being reconstructed from a separate loop-input type. PRELUDE can include a sequence of RECURRENT views. RECURRENT starts from supplied hidden. - CODA projects supplied hidden. KV views carry allocation identity and may - use host-planned or device-owned positions. Graph executors must match the - operation and gate mode. All tensors/results are borrowed, not snapshots. + CODA consumes supplied hidden and optionally produces logits. KV views carry + allocation identity and may use host-planned or device-owned positions. + Graph executors must match the operation and gate mode. All tensors/results + are borrowed, not snapshots. """ operation: Operation @@ -128,7 +153,7 @@ class ForwardBatch: compute_gate: bool = False graphs: object = None graph_calls: tuple = () - compute_logits: bool = True + compute_logits: bool | torch.Tensor = True @dataclass(frozen=True) @@ -152,6 +177,10 @@ def prepare(self, batch: ForwardBatch) -> ForwardBatch: """ if batch.graphs is None: return batch + if batch.operation == Operation.CODA and ( + isinstance(batch.compute_logits, torch.Tensor) or not batch.compute_logits + ): + return replace(batch, graphs=None, graph_calls=()) if batch.operation == Operation.PRELUDE: # Graph buffers hold the query rows only; padding has no KV address. kv = batch.prelude_coda_kv_metadata @@ -184,6 +213,12 @@ def forward(self, batch: ForwardBatch) -> ForwardResult: self.cache, compute_logits=batch.compute_logits, ) + elif isinstance(batch.compute_logits, torch.Tensor): + mask = batch.compute_logits + if mask.dtype != torch.bool or mask.ndim != 1 or mask.numel() != len(hidden): + raise ValueError("compute_logits must be a boolean mask for every CODA row") + rows = torch.nonzero(mask, as_tuple=True)[0].to(hidden.device) + logits = self.model.coda(hidden.index_select(0, rows)) if rows.numel() else None else: logits = self.model.coda(hidden) if batch.compute_logits else None return ForwardResult(hidden=hidden, logits=logits) diff --git a/vllm_rlt/worker/model_runner.py b/vllm_rlt/worker/model_runner.py index 3ba410ea..783eb98f 100644 --- a/vllm_rlt/worker/model_runner.py +++ b/vllm_rlt/worker/model_runner.py @@ -35,7 +35,9 @@ class ReadbackSlot: class BatchInputBuffers: """One event-owned snapshot; source tensors survive until the final reader.""" - def __init__(self, max_seqs, max_tokens, device, hidden_dtype, *, use_uva=True): + def __init__( + self, max_seqs, max_tokens, device, hidden_dtype, *, use_uva=True, hidden_shape=None + ): self.segments = UvaBuffer((max_seqs, 5), torch.int64, device, use_uva=use_uva) self.segment_view = None self.token_input = pinned_tensor(max_tokens, torch.int64, device) @@ -44,6 +46,11 @@ def __init__(self, max_seqs, max_tokens, device, hidden_dtype, *, use_uva=True): self.hidden_gather = TensorTransfer(max_seqs, hidden_dtype, device, use_uva=use_uva) self.hidden_scatter = TensorTransfer(2 * max_seqs, hidden_dtype, device, use_uva=use_uva) self.hidden_outputs = [] + self.hidden = ( + torch.empty(hidden_shape, device=device, dtype=hidden_dtype) + if hidden_shape is not None + else None + ) def reset(self): self.token_transfers.reset() @@ -102,6 +109,8 @@ class PreparedExecution: packed_metadata: PackedMetadataBuffer | None = None sampling_params: tuple = () sampling_generators: tuple = () + sampling_spans: tuple[int, ...] = () + logits_mask: torch.Tensor | None = None @dataclass @@ -115,6 +124,7 @@ class Submission: depths: tuple[int, ...] = () positions: tuple[int, ...] = () output_indices: tuple[int, ...] = () + output_rows: tuple[int, ...] | None = None operation: Operation | None = None def __del__(self): @@ -142,6 +152,7 @@ def collect(self) -> ModelRunnerOutput: completion=self.event, depths=self.depths, output_indices=self.output_indices, + output_rows=self.output_rows, ) self.values = None if self.slot is not None: @@ -282,15 +293,6 @@ def __init__( prefill_rows = scheduler.max_num_batched_tokens if self.execution_config.pad_to_power_of_two: prefill_rows = 1 << (prefill_rows - 1).bit_length() - self.prefill_hidden = ( - torch.empty( - (prefill_rows, model.config.hidden_size), - device=self.device, - dtype=parameter.dtype, - ) - if self.staged_prefill - else None - ) self.batch_input_buffers = ( [ BatchInputBuffers( @@ -301,6 +303,7 @@ def __init__( self.device, parameter.dtype, use_uva=self.execution_config.use_uva, + hidden_shape=(prefill_rows, model.config.hidden_size), ) for _ in range(MAX_CONCURRENT_SUBMISSIONS) ] @@ -480,7 +483,7 @@ def _mixed_hidden_sources(self, batch, buffers): source = request.hidden_state source = None if source is None else source.reshape(1, -1) last = None - if span.retain_last: + if span.retain_last and batch.operation != Operation.CODA: if self.states is None: last = torch.empty( self.model.config.hidden_size, @@ -491,9 +494,7 @@ def _mixed_hidden_sources(self, batch, buffers): last = self.states[slot] request.hidden_state = last if source is not None: - buffers.hidden_gather.append( - source, self.prefill_hidden[row : row + span.token_count] - ) + buffers.hidden_gather.append(source, buffers.hidden[row : row + span.token_count]) buffers.hidden_outputs.append( ( row, @@ -519,7 +520,7 @@ def _mixed_hidden(self, hidden, prepared, *, scatter): def _gather_prefill(self, prepared): metadata = prepared.batch_inputs count = metadata.rows - hidden = self.prefill_hidden[:count] + hidden = metadata.buffers.hidden[:count] if metadata.mixed: self._mixed_hidden(hidden, prepared, scatter=False) return hidden @@ -906,7 +907,24 @@ def _prepare_cpu_inputs(self, batch: ExecutionBatch): prepared, gate_indices=self.input_buffers[torch.int64].append(gate_rows) ) if batch.operation == Operation.CODA: - prepared = replace(prepared, sampling_params=tuple(r.sampling_params for r in requests)) + sampling_spans = tuple( + index for index, span in enumerate(batch.spans) if span.compute_logits + ) + logits_mask = None + if batch.has_chunks: + mask = [False] * batch.num_rows + row = 0 + for span in batch.spans: + row += span.token_count + if span.compute_logits: + mask[row - 1] = True + logits_mask = torch.tensor(mask, dtype=torch.bool) + prepared = replace( + prepared, + sampling_spans=sampling_spans, + sampling_params=tuple(requests[index].sampling_params for index in sampling_spans), + logits_mask=logits_mask, + ) if batch.operation == Operation.PRELUDE and batch.loop_count: packed_metadata = ( self.packed_metadata_buffers[self.submissions.slot] @@ -978,8 +996,10 @@ def prepare_on_gpu(self, prepared): sampling_generators=tuple( None if params.temperature == 0 - else self.rng.acquire(span.request.request_id, params, self.device) - for span, params in zip(batch.spans, prepared.sampling_params) + else self.rng.acquire( + batch.spans[index].request.request_id, params, self.device + ) + for index, params in zip(prepared.sampling_spans, prepared.sampling_params) ), ) if prepared.routing is not None: @@ -1012,7 +1032,6 @@ def _prepare_forward(self, prepared): batch, workspace = prepared.batch, prepared.workspace if batch.operation == Operation.PRELUDE and batch.loop_count: return replace(prepared, forwards=self._prepare_loop_forwards(prepared)) - requests = [span.request for span in batch.spans] size = batch.num_rows if batch.has_chunks else self._size(batch.num_rows) inputs = prepared.forwards[0].forward metadata = inputs.metadata @@ -1035,7 +1054,13 @@ def _prepare_forward(self, prepared): Operation.PRELUDE, tokens=prepared.token_ids, prelude_coda_kv_metadata=kv_metadata, - generators=self._prepare_generators(requests) if kv_metadata else None, + generators=( + self._prepare_generators( + [span.request for span in batch.spans for _ in range(span.token_count)] + ) + if kv_metadata + else None + ), graphs=self.prelude_graphs if kv_metadata else None, ) return replace(prepared, forwards=(PreparedForward(self.runtime.prepare(forward)),)) @@ -1046,6 +1071,7 @@ def _prepare_forward(self, prepared): hidden=hidden[: batch.num_rows] if kv_metadata else hidden, prelude_coda_kv_metadata=kv_metadata, graphs=self.coda_graphs if kv_metadata else None, + compute_logits=prepared.logits_mask if prepared.logits_mask is not None else True, ) return replace(prepared, forwards=(PreparedForward(self.runtime.prepare(forward)),)) graphs = self.graphs if batch.emit_gate else None @@ -1147,7 +1173,7 @@ def _execute_batch(self, batch: ExecutionBatch, prepared): else logits[: len(batch.spans)] ) values = selected.float().sigmoid() - elif forward.compute_logits: + elif result.logits is not None: if self.device.type == "npu": values = self.sampler.sample_batch( result.logits, prepared.sampling_params, prepared.sampling_generators @@ -1295,6 +1321,7 @@ def submit(self, scheduled_batch: SchedulerOutput | None = None, *, batch: Execu depths=prepared.depths, positions=prepared.positions, output_indices=prepared.output_indices, + output_rows=prepared.sampling_spans if prepared.logits_mask is not None else None, operation=batch.operation, ) except Exception: diff --git a/vllm_rlt/worker/output.py b/vllm_rlt/worker/output.py index e0401f25..d65dc2c7 100644 --- a/vllm_rlt/worker/output.py +++ b/vllm_rlt/worker/output.py @@ -34,5 +34,6 @@ class ModelRunnerOutput: completion: object = None depths: tuple[int, ...] = () output_indices: tuple[int, ...] = () + output_rows: tuple[int, ...] | None = None speculative: list[SpeculativeResult] | None = None frontiers: list[int] | None = None