diff --git a/README.md b/README.md index adfe3285..cde38840 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,6 @@ a fixed scale at startup. See the | 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 | -| Inkling 2 Mini / TML-d24-varloop-research | Shared Inkling 2 Mini | [CUDA SM10x](docs/launching.md#inkling-2-mini) | Uses vLLM Inkling operators, with optional async scheduling, packed prefill, and separate KV and convolution history per pass | The broader model roadmap is in [RFC #69](https://github.com/InferMatrixLab/vllm-rlt/issues/69). diff --git a/docs/async-speculative.md b/docs/async-speculative.md index aeb674c1..6a003d1a 100644 --- a/docs/async-speculative.md +++ b/docs/async-speculative.md @@ -912,14 +912,8 @@ There is no cross-stage handoff for each speculative step. Prompt bootstrap uses the ordinary runner. Refill scheduling returns to the scheduler after each prompt chunk, where ready speculative work can be selected. -PD can import the completed prompt into the decode stage. The single-stage -native Inkling async token pipeline can also schedule mixed Core work. The -VarLoop checkpoint uses a server-wide pass count equal to the target depth. -A joined forward uses device-owned speculative addresses for the leading -single-query rows and host-planned packed metadata for the prompt rows. -Prompt progress uses the compute completion event. Speculative results keep -their independent tickets and readback stream. Packed bucket graphs can replay -the shared Core while attention uses the live query layout. +PD can import the completed prompt into the decode stage. These combinations do +not enable mixed scheduling of prompt rows with speculative verification rows. The synchronous runner reads the acceptance result before constructing the next @@ -992,9 +986,6 @@ token slots; the copy stream transfers compact results to pinned host storage. Collecting an older step never rewinds GPU state. Inactive slots have masked KV writes and zero attention lengths. Fixed-shape prelude/coda calls can include unused rows; this avoids a host dependency for selecting dynamic batch sizes. -On Inkling with native vLLM kernels, speculative steps and new-request -prefill share one compute stream because both use the same expert scratch. -Result readback still runs on its own stream when multi-stream execution is enabled. Pending steps cannot be preempted. Waiting admissions drain outstanding steps so Scheduler can select a victim at a completed step boundary. At that boundary, preemption saves hidden states, loop depths and candidates with the existing KV @@ -1008,16 +999,6 @@ comparing the two modes. `--speculative-tokens` bounds the reserved lookahead window in pipeline mode; a smaller scheduler token budget may discard descendants and reduce overlap. -With native Inkling and asynchronous CUDA Graphs, `--speculative-pipeline-graph transition` -pre-captures GPU acceptance and state updates for selected request counts. -`--speculative-pipeline-graph full` also captures an entire dense decode step -from prelude through the state update. Mixed prefill/decode and decode batches -outside the dense graph's shape or page-table capacity use the stage graphs. -Both modes capture before serving. Two leased input banks reuse unchanged page -tables and routing plans. Changed inputs are staged from pinned host memory -on the input stream when multi-stream execution is enabled. `--no-uva` uses -asynchronous CUDA copies from the same banks. - ### Accepted tokens ![Block and pipeline speculation at token granularity](diagrams/pipeline-token-batches.png) diff --git a/docs/launching.md b/docs/launching.md index 6986cd70..2aad2973 100644 --- a/docs/launching.md +++ b/docs/launching.md @@ -12,87 +12,6 @@ The release is for research/evaluation, not a production deployment guarantee. For Huawei Ascend NPU, follow the [Ascend setup](recipes/ouro_ascend.md) on `main`. -### Inkling 2 Mini - -The fixed and variable-loop checkpoints share one text implementation. The fixed -checkpoint uses three passes. The variable-loop checkpoint defaults to three and -accepts `--max-loops` to set the worker's depth in the CLI and server. For the -fixed checkpoint, an explicit `--max-loops` must match its depth. Both require -an NVIDIA SM10x GPU, a vLLM CUDA build with Inkling 2 operators, and its -FlashInfer dependencies. The tested vLLM source revision is `3146a9df4140`. - -```bash -python -m vllm_rlt.entrypoints.cli \ - --model thinkingmachines/Inkling-2-Mini --device cuda --num-blocks 96 \ - --prompt 'The capital of France is' --max-tokens 8 - -python -m vllm_rlt.entrypoints.cli \ - --model thinkingmachines/TML-d24-varloop-research --max-loops 2 \ - --device cuda --num-blocks 96 --prompt 'The capital of France is' --max-tokens 8 -``` - -Both examples use synchronous CUDA execution and BF16 KV. RLT loads the -checkpoint and schedules requests. The model uses native NVFP4 and MXFP8 -experts and the vLLM attention, short-convolution, and AttnRes operators. -The same checkpoint and pass arguments work with `vllm-rlt-serve` for text completions. - -Packed prefill is selected by default. Use `--packed-prefill` to require it or -`--no-packed-prefill` to select per-query prefill for comparison. Both use the -same chunk scheduler, relative position bias, attention sinks, BF16 KV, and -per-pass convolution history. Decode continues to use per-query attention. - -Use `--packed-prefill --cuda-graphs` to enable Graph execution. RLT captures decode -prelude, recurrent pass, and coda separately. Packed prefill has its own graph -entries for prelude, recurrent passes and KV-only coda, sized up to the -scheduler's query-token budget. Add -`--packed-graph-buckets` to round the query count up to the next vLLM throughput -bucket and share a graph memory pool. Each bucket is captured on first use by default. -Padding rows have no KV slots. Attention runs between graph segments with the -real query count and batch metadata. Token padding can change BF16 rounding -and the selected token when logits are close. - -`--mode mixed` lets Inkling combine staged prompt rows with decode rows in -one recurrent submission. The vLLM kernel path dispatches the leading decode -rows to relative decode attention and the remaining rows to packed FA4 when -the batch needs both. With `--packed-graph-buckets`, packed mixed batches use -the same token buckets as packed prefill. Otherwise, mixed batches within the -decode row limit use their own full-graph cache. Pure decode has a separate -full-graph cache. Each cache observes the configured entry limit. Uncached -batches beyond these limits run eagerly. Mixed uses the single-stage scheduler. - -Add `--async-scheduling` for either checkpoint, including in mixed mode. The -next decode prelude can use the Coda sample on the GPU while the CPU receives -the previous output. The scheduler checks the previous token for EOS before -sampling another token for the same request. Both attention and convolution -use the normal per-pass KV layout. The default scheduler is synchronous. - -Add `--cuda-graph-warmup` to compile FA4 attention variants and pre-capture a -bounded set of native Inkling decode and packed graphs before the worker becomes -ready. Warmup uses temporary KV pages and releases them before serving. The -token and row budgets and `--cuda-graph-max-graphs` bound startup coverage. -Once ready, the worker replays captured entries and executes unseen shapes eagerly. -For mixed mode, enabling `--packed-graph-buckets` lets small and large mixed -batches use the same pre-captured packed entries. - -Use `--wavefront-chunked-prefill` with mixed or refill scheduling to put ready -prompt chunks at different Core depths in the same batch. For Fixed with -mixed scheduling, the W7 C32 run used `--min-coda-batch-size 32` to let ready -Core work catch up to requests already waiting for Coda. Coda still runs below -the threshold when there is no ready decode Core work. - -With the native kernels, refill supports the greedy token pipeline -with `--speculative-mode pipeline --speculative-tokens 2 --draft-loops 1 --target-loops 3`. -Add `--async-scheduling` to submit ahead of CPU acceptance and output delivery. -For C32, a CUDA Graph row limit of 96 covers the pipeline's three slots per -request. The pipeline requires preemption to be disabled. - -Use `--mode mixed --async-scheduling` with that pipeline on a single worker -to run ready prompt and speculative rows in one Core forward. For VarLoop, -set `--max-loops` to the same value as `--target-loops`. This mode -uses packed prefill and supports `--wavefront-chunked-prefill`. Add -`--packed-graph-buckets --cuda-graph-warmup` to replay warmed packed Core -buckets for the shared forward. - ## 1. Check the machine Use Linux with Git, curl, [uv](https://docs.astral.sh/uv/getting-started/installation/), @@ -414,8 +333,8 @@ insert a depth boundary when decode work can join a prompt recurrent batch. `--wavefront-chunked-prefill` enables per-depth chunk regrouping. These are batching choices, not PD disaggregation. -Stage roles are `prefill`, `decode` and `prefill_decode`. Most speculative modes -use refill scheduling. Inkling with the native async token pipeline also -supports mixed recurrent batches. See the +Stage roles are `prefill`, `decode` and `prefill_decode`; `mixed` is a scheduling +mode, not a stage role. Speculation requires refill scheduling and cannot join +mixed recurrent batches. Model/backend restrictions still apply. See the [runtime guide](runtime.md#execution-batches-and-mixed-scheduling) before combining optional features. diff --git a/docs/runtime.md b/docs/runtime.md index 2445f7c5..c487ea37 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -159,9 +159,11 @@ for the selection order, shared budget and per-request progress. ### Wavefront chunked prefill `SchedulerConfig(wavefront_chunked_prefill=True)` opts into WCPB and requires -LAST_EXITED KV. It can run with refill or mixed scheduling. Speculation in -mixed mode is available for the single-stage native Inkling async token -pipeline. Asynchronous block speculation uses refill and rejects preemption. +LAST_EXITED KV. It can run with +refill or mixed scheduling. When combined with speculation, use refill mode; +asynchronous block speculation rejects preemption. Synchronous block and +pipeline modes have different support constraints; do not infer that every +combination is validated. The scheduler stages up to `total_ut_steps` chunks per request, then batches one ready chunk for each prompt depth. For four depths and chunk size two, recurrent diff --git a/docs/split-prefill-wavefront.md b/docs/split-prefill-wavefront.md index 1e62c577..5bbed969 100644 --- a/docs/split-prefill-wavefront.md +++ b/docs/split-prefill-wavefront.md @@ -37,8 +37,8 @@ batch still contains one operation type. WCPB is opt-in through `SchedulerConfig.wavefront_chunked_prefill` or the `--wavefront-chunked-prefill` CLI flag. `prefill_chunk_size` controls the prompt -chunk size. The option works with refill or mixed scheduling. The native -Inkling async token pipeline can also share recurrent work with prompt chunks. +chunk size. The option works with refill or mixed scheduling; mixed scheduling +does not support speculative work. ## Progress and dependencies @@ -93,9 +93,9 @@ per-depth frontiers; it does not introduce a generic `PrefillTask` registry. 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 and the -single-stage native Inkling mixed token pipeline. CUDA graph and asynchronous -paths use the existing runner machinery. +Speculative execution is supported with compatible refill scheduling; mixed +mode rejects speculative configuration. CUDA graph and asynchronous paths use +the existing runner machinery. `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_async_pipeline.py b/tests/test_async_pipeline.py index 64fb5077..76c5dc7c 100644 --- a/tests/test_async_pipeline.py +++ b/tests/test_async_pipeline.py @@ -83,23 +83,10 @@ def ready(ticket): assert not engine._pending_coda -@pytest.mark.parametrize( - ("device", "use_device_metadata"), - [ - ("cpu", False), - pytest.param("cuda", True, marks=pytest.mark.gpu), - pytest.param("cuda", False, marks=pytest.mark.gpu), - ], -) +@pytest.mark.parametrize("device", ["cpu", pytest.param("cuda", marks=pytest.mark.gpu)]) @pytest.mark.parametrize("multi_stream", [False, True]) -def test_prelude_consumes_device_sample_before_cpu_delivery( - monkeypatch, device, use_device_metadata, multi_stream -): - monkeypatch.setattr( - OuroForCausalLM, "supports_device_kv_metadata", use_device_metadata, raising=False - ) +def test_prelude_consumes_device_sample_before_cpu_delivery(monkeypatch, device, multi_stream): engine = make_engine(device=device, multi_stream=multi_stream) - assert (engine.model_runner.async_state is not None) == use_device_metadata engine.add_request("a", [2], SamplingParams(max_tokens=3, ignore_eos=True, exit_threshold=1)) engine.step() engine.step() diff --git a/tests/test_async_speculative.py b/tests/test_async_speculative.py index 29ef52fd..e777e967 100644 --- a/tests/test_async_speculative.py +++ b/tests/test_async_speculative.py @@ -359,8 +359,6 @@ def test_active_page_tables_are_contiguous_and_do_not_touch_inactive_storage(): leased=False, host_tables=torch.full((128,), -91, dtype=torch.int32), tables=torch.full((128,), -92, dtype=torch.int32), - table_versions=(), - table_shape=(), ) runner.buffers = [buffer] requests = [Request(rid, [2], SamplingParams()) for rid in ("short", "long")] @@ -385,20 +383,12 @@ def test_active_page_tables_are_contiguous_and_do_not_touch_inactive_storage(): assert (buffer.tables == -92).all() # CPU preparation does not upload. with pytest.raises(RuntimeError, match="exhausted"): runner._prepare_round(batch) - buffer.leased = False - same_width = SchedulerOutput( - RequestPhase.SPECULATIVE, - [ScheduledRequest(requests[0], 0, 1), batch.requests[1]], - ) - runner._prepare_round(same_width) - assert not buffer.tables_dirty # Simulate retirement, then shrink both dimensions using the same storage. buffer.leased = False before = buffer.host_tables.clone() smaller = SchedulerOutput(RequestPhase.SPECULATIVE, [ScheduledRequest(requests[0], 0, 1)]) _, _, host, device = runner._prepare_round(smaller) assert host.shape == device.shape == (1, 4, 1) - assert buffer.tables_dirty assert host.is_contiguous() and device.is_contiguous() assert torch.equal(buffer.host_tables[4:], before[4:]) diff --git a/tests/test_cuda_graph.py b/tests/test_cuda_graph.py index 95b779d3..a0f08c51 100644 --- a/tests/test_cuda_graph.py +++ b/tests/test_cuda_graph.py @@ -1,7 +1,6 @@ """Graph replay must update KV addresses, request identities and host progress.""" import gc -from types import SimpleNamespace import pytest import torch @@ -23,116 +22,6 @@ def test_cuda_graph_validation(): ) -def test_inkling_packed_graph_plan_tracks_decode_split_and_fa4_launch(monkeypatch): - from vllm_rlt.kernels import inkling2mini - - def plan_decode(_local, _requests, max_query, *_shape): - return 2 if max_query <= 2 else 0 - - def plan_prefill(local, _query, lengths, *_shape): - return (1 if local or max(lengths) < 32 else 2), False - - attention = SimpleNamespace( - plan_decode_attention=plan_decode, - plan_attention=plan_prefill, - bucket_max_seqlen_q=lambda max_query: max_query, - ) - monkeypatch.setattr(inkling2mini, "load_ops", lambda: SimpleNamespace(attention=attention)) - config = SimpleNamespace(window=32, rel_extent=64, num_attention_heads=8, num_key_value_heads=4) - - def plans(query, start=0): - rows = tuple( - (allocation, 0, position) - for allocation, count in zip((object(), object(), object()), query, strict=True) - for position in range(start, start + count) - ) - metadata = SimpleNamespace( - rows=rows, max_seqlen_q=max(query), write_blocks=rows, context_lengths=query - ) - return inkling2mini.packed_attention_plans(metadata, config) - - short = plans((1, 4, 3)) - assert short[0].decode_rows == 1 - assert short == plans((1, 4, 3), start=16) - assert plans((2, 4, 2))[0].decode_rows == 0 - long = plans((1, 4, 3), start=32) - assert short[0].prefill == (4, 1, False) - assert long[0].prefill == (4, 2, False) - assert long[1] == short[1] - - -def test_warmed_graph_cache_allows_hits_and_falls_back_on_misses(): - from vllm_rlt.worker.cuda_graph import _cache_full - - owner = SimpleNamespace(entries={2: object()}, execution=ExecutionConfig(), allow_capture=False) - assert not _cache_full(owner, 2) - assert _cache_full(owner, 3) - assert tuple(owner.entries) == (2,) - - -def test_packed_graph_capture_matches_vllm_throughput_grid(): - from vllm_rlt.worker.packed_graph import packed_capture_sizes - - sizes = ( - 1, - 2, - 4, - 8, - 16, - 24, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 160, - 192, - 224, - 256, - 320, - 384, - 448, - 512, - 640, - 768, - 896, - 1024, - ) - assert packed_capture_sizes(1024) == sizes - assert packed_capture_sizes(1000) == (*sizes[:-1], 1000) - assert packed_capture_sizes(1) == (1,) - - -@pytest.mark.gpu -@torch.inference_mode() -def test_packed_attention_segments_replay_with_live_inputs(): - from vllm_rlt.worker.packed_graph import _AttentionSegments - - static = torch.arange(4, device="cuda", dtype=torch.float32) - first = torch.ones_like(static) - second = torch.full_like(static, 7) - stream = torch.cuda.Stream() - stream.wait_stream(torch.cuda.current_stream()) - segments = _AttentionSegments() - with torch.cuda.stream(stream): - torch.add(static, first, out=torch.empty_like(static)) - stream.synchronize() - with segments.capture(first): - projected = static * 2 - attended = torch.empty_like(projected) - segments.attention(lambda batch: torch.add(projected, batch, out=attended)) - output = attended * 3 - torch.cuda.current_stream().wait_stream(stream) - torch.testing.assert_close(attended, static * 2 + first) - static.add_(4) - segments.replay(second) - torch.testing.assert_close(output, (static * 2 + second) * 3) - - @pytest.mark.gpu @pytest.mark.parametrize("backend", ["triton", "flash_attn"]) @pytest.mark.parametrize("mode", ["sync", "async", "multi"]) diff --git a/tests/test_prepared_kv.py b/tests/test_prepared_kv.py index 337ad837..e9609a6a 100644 --- a/tests/test_prepared_kv.py +++ b/tests/test_prepared_kv.py @@ -11,9 +11,6 @@ from vllm_rlt.attention import BackendCapabilities from vllm_rlt.core.kv_cache_manager import KVCacheManager from vllm_rlt.models import OuroForCausalLM -from vllm_rlt.request import ExecutionBatch, Operation, Request, StateSpan -from vllm_rlt.sampling_params import SamplingParams -from vllm_rlt.worker.buffers import stage_metadata @pytest.fixture(autouse=True) @@ -323,49 +320,3 @@ def test_depth_batches_share_depth_independent_metadata(packed): cache._prepare_batches(ids, [[0] * 5, [4] * 5], positions) with pytest.raises(ValueError, match="equal lengths"): cache._prepare_batches(ids, [[0] * 5, [1] * 4], positions) - - -def test_packed_spans_match_row_planning_across_depths(): - cache = make_cache(num_blocks=64) - cache.attention = SimpleNamespace(capabilities=BackendCapabilities(packed_prefill=True)) - a, b = (Request(name, [1], SamplingParams()) for name in ("a", "b")) - assert cache.allocate("a", 8) and cache.allocate("b", 6) - spans = (StateSpan(a, 1, 2, 0), StateSpan(a, 3, 4, 0), StateSpan(b, 4, 1, 1)) - ids, depths, positions = ExecutionBatch(Operation.RECURRENT, spans).addresses() - offsets = (0, 1, 2) - packed = cache.metadata_builder.build_packed(spans, offsets) - rows = cache.metadata_builder.build( - ids, [[depth + offset for depth in depths] for offset in offsets], positions, packed=True - ) - assert packed == rows - assert [len(layout.packed_ranges) for layout in packed] == [2] * len(offsets) - assert packed[0].attention.cu_seqlens_q == [0, 6, 7] - assert packed[0].attention.cu_seqlens_q is packed[-1].attention.cu_seqlens_q - with pytest.raises(ValueError, match="contiguous"): - cache.metadata_builder.build_packed((StateSpan(a, 0, 2, 0), spans[1]), (0,)) - - -def test_packed_external_kv_registration_preserves_holes_and_depths(): - cache = make_cache(num_blocks=64) - cache.attention = SimpleNamespace(capabilities=BackendCapabilities(packed_prefill=True)) - request = Request("r", [1], SamplingParams()) - assert cache.allocate("r", 8) - builder = cache.metadata_builder - late_layout = builder.build_packed((StateSpan(request, 2, 5, 1),), (0,)) - early_layout = builder.build_packed((StateSpan(request, 0, 2, 1),), (0,)) - late = stage_metadata(late_layout, cache._stage)[0] - early = stage_metadata(early_layout, cache._stage)[0] - allocation = late.packed_ranges[0].allocation - cache.record_external_kv(0, late) - with pytest.raises(RuntimeError, match="uninitialized KV history"): - cache._require_prefix(allocation, 0, 1, 7) - cache.record_external_kv(0, early) - cache._require_prefix(allocation, 0, 1, 7) - with pytest.raises(RuntimeError, match="uninitialized KV history"): - cache._require_prefix(allocation, 0, 0, 1) - with pytest.raises(RuntimeError, match="uninitialized KV history"): - cache._require_prefix(allocation, 1, 1, 1) - cache.free("r") - assert cache.allocate("r", 8) - with pytest.raises(RuntimeError, match="stale prepared KV batch"): - cache.record_external_kv(0, late) diff --git a/tests/test_split_prefill.py b/tests/test_split_prefill.py index bf3d921e..1080eaef 100644 --- a/tests/test_split_prefill.py +++ b/tests/test_split_prefill.py @@ -14,15 +14,7 @@ import torch from tests.helpers import make_prefill_engine, tiny_ouro_config, tiny_ouro_model -from vllm_rlt import ( - CacheConfig, - ExecutionConfig, - ExitConfig, - SamplingParams, - SchedulerConfig, - SpeculativeConfig, -) -from vllm_rlt.core.scheduler import Scheduler +from vllm_rlt import CacheConfig, ExecutionConfig, ExitConfig, SamplingParams, SchedulerConfig from vllm_rlt.core.scheduling_policy import ( MixedPolicy, NoRefillPolicy, @@ -1832,53 +1824,6 @@ def test_scheduling_policies_declare_their_prefill_stages(): ) -@pytest.mark.parametrize("wavefront", [False, True]) -def test_mixed_speculative_schedule_reserves_prompt_rows_under_the_shared_budget(wavefront): - engine = make_prefill_engine() - try: - scheduler = Scheduler( - SchedulerConfig( - mode="mixed", - max_num_seqs=3, - max_num_batched_tokens=4, - prefill_chunk_size=4, - wavefront_chunked_prefill=wavefront, - ), - engine.cache_manager, - SpeculativeConfig(2, 1, 3, "pipeline"), - total_ut_steps=3, - mixed_speculative=True, - ) - for request_id in ("decode-a", "decode-b"): - request = Request(request_id, [1], SamplingParams(max_tokens=8)) - scheduler.requests[request_id] = request - assert engine.cache_manager.allocate(request_id, 8) - scheduler.enqueue(request, RequestPhase.SPECULATIVE) - prompt = Request( - "prompt", - [1, 2, 3, 4], - SamplingParams(max_tokens=8), - num_preluded_tokens=4, - prefill_depth_ranges=Request.prefill_boundaries(4, 3), - ) - scheduler.requests[prompt.request_id] = prompt - assert engine.cache_manager.allocate(prompt.request_id, 4) - scheduler.enqueue(prompt, RequestPhase.PREFILLING_RECURRENT) - scheduler.policy.prefill_batches_since_recurrent = 1 - - batch = scheduler.schedule() - - assert batch.is_mixed and batch.loop_count == 1 and batch.num_tokens == 4 - assert [(batch.phase_for(span), span.token_count) for span in batch.requests] == [ - (RequestPhase.SPECULATIVE, 3), - (RequestPhase.PREFILLING_RECURRENT, 1), - ] - assert scheduler.policy.prefill_batches_since_recurrent == 0 - assert list(scheduler.queues[RequestPhase.SPECULATIVE]) == ["decode-b"] - finally: - engine.close() - - @pytest.mark.parametrize( ("label", "kwargs", "message"), [ diff --git a/vllm_rlt/attention/metadata.py b/vllm_rlt/attention/metadata.py index 5bd5e578..4043f696 100644 --- a/vllm_rlt/attention/metadata.py +++ b/vllm_rlt/attention/metadata.py @@ -61,6 +61,7 @@ def plan_attention_metadata( if packed_prefill and rows.sequence_keys is not None: if len(rows.sequence_keys) != len(rows.positions): raise ValueError("packed attention keys and positions must have equal lengths") + width = max((position // block_size + 1 for position in rows.positions), default=0) table_rows = range(len(rows.positions)) cumulative = None max_query = 1 @@ -82,33 +83,18 @@ def plan_attention_metadata( cumulative.append(index + 1) table_rows = ends max_query = max((b - a for a, b in zip(cumulative, cumulative[1:])), default=1) - return assemble_attention_metadata( - (rows.block_tables[index] for index in table_rows), - [rows.positions[index] + 1 for index in table_rows], - block_size=block_size, - cu_seqlens_q=cumulative, - max_seqlen_q=max_query, - ) - - -def assemble_attention_metadata( - block_tables, context_lengths, *, block_size, cu_seqlens_q=None, max_seqlen_q=1 -) -> AttentionMetadataValues: - """Serialize the tables of already grouped and validated queries.""" - max_length = max(context_lengths, default=0) - width = (max_length + block_size - 1) // block_size tables = [] - for blocks in block_tables: - table = blocks[:width] + for index in table_rows: + table = rows.block_tables[index][:width] tables.extend(table) tables.extend([-1] * (width - len(table))) return AttentionMetadataValues( block_tables=tables, - num_rows=len(context_lengths), + num_rows=len(table_rows), table_width=width, - context_lengths=context_lengths, - cu_seqlens_q=cu_seqlens_q, - max_seqlen_q=max_seqlen_q, + context_lengths=[rows.positions[index] + 1 for index in table_rows], + cu_seqlens_q=cumulative, + max_seqlen_q=max_query, ) diff --git a/vllm_rlt/config.py b/vllm_rlt/config.py index befeb6b2..7213adb0 100644 --- a/vllm_rlt/config.py +++ b/vllm_rlt/config.py @@ -160,10 +160,6 @@ class ExecutionConfig: # ordinary (non-staged) prefill. Sliding windows additionally require packed-window # support and compatible synchronous eager execution; off otherwise. packed_prefill: bool | None = None - # Opt in to the vLLM token grid for native Inkling packed CUDA Graphs. - packed_graph_buckets: bool = False - # Prepare native Inkling graphs before serving and keep the cache fixed. - cuda_graph_warmup: bool = False def __post_init__(self): if self.packed_prefill is not None and type(self.packed_prefill) is not bool: @@ -175,15 +171,11 @@ def __post_init__(self): "static_buffers", "pad_to_power_of_two", "cuda_graphs", - "packed_graph_buckets", - "cuda_graph_warmup", ): if type(getattr(self, name)) is not bool: raise ValueError(f"{name} must be a boolean") if self.cuda_graph_max_batch_size is not None: _positive("cuda_graph_max_batch_size", self.cuda_graph_max_batch_size) - if self.cuda_graph_warmup and not self.cuda_graphs: - raise ValueError("CUDA Graph warmup requires cuda_graphs") for name in ("cuda_graph_max_graphs", "cuda_graph_memory_reserve_bytes"): _positive(name, getattr(self, name)) if self.pad_to_power_of_two and not self.static_buffers: @@ -198,17 +190,12 @@ class SpeculativeConfig: draft_loops: int = 2 target_loops: int = 4 mode: str = "block" - pipeline_graph: str = "off" def __post_init__(self): for name in ("num_speculative_tokens", "draft_loops", "target_loops"): _positive(name, getattr(self, name)) if self.mode not in ("block", "pipeline"): raise ValueError("speculative mode must be block or pipeline") - if self.pipeline_graph not in ("off", "transition", "full"): - raise ValueError("pipeline_graph must be off, transition, or full") - if self.pipeline_graph != "off" and self.mode != "pipeline": - raise ValueError("pipeline_graph requires speculative pipeline mode") if self.mode == "pipeline" and self.target_loops % self.draft_loops: raise ValueError("pipeline draft_loops must divide target_loops") if self.draft_loops >= self.target_loops: diff --git a/vllm_rlt/core/kv_cache_manager.py b/vllm_rlt/core/kv_cache_manager.py index 77069894..c6187d77 100644 --- a/vllm_rlt/core/kv_cache_manager.py +++ b/vllm_rlt/core/kv_cache_manager.py @@ -31,12 +31,7 @@ from vllm_rlt.device import resolve_device from vllm_rlt.request import ExecutionBatch from vllm_rlt.worker.buffers import stage_metadata -from vllm_rlt.worker.metadata import ( - DeviceKVMetadata, - KVMetadata, - MetadataBuilder, - MixedRecurrentKVMetadata, -) +from vllm_rlt.worker.metadata import DeviceKVMetadata, KVMetadata, MetadataBuilder KV_CACHE_DTYPES = ("auto", "fp8_e4m3") FP8_E4M3_MAX = 448.0 @@ -199,8 +194,6 @@ def __init__( attention: AttentionBackend | None = None, kv_cache_dtype: str = "auto", fp8_scale: float | None = None, - auxiliary_width: int = 0, - interleaved_kv: bool = False, ): for name, value in ( ("num_layers", num_layers), @@ -267,24 +260,8 @@ def __init__( ) shape = (num_blocks, num_layers, block_size, num_kv_heads, head_dim) storage = torch.float8_e4m3fn if kv_cache_dtype == "fp8_e4m3" else dtype - if interleaved_kv: - # The relative decode kernel reads K and V from one row per head. - combined = torch.empty( - (num_layers, num_blocks, num_kv_heads, block_size, 2 * head_dim), - device=self.device, - dtype=storage, - ) - self.key_cache, self.value_cache = combined.permute(1, 0, 3, 2, 4).split( - head_dim, dim=-1 - ) - else: - self.key_cache = torch.empty(shape, device=self.device, dtype=storage) - self.value_cache = torch.empty_like(self.key_cache) - self.auxiliary_cache = ( - torch.empty((*shape[:3], auxiliary_width), device=self.device, dtype=dtype) - if auxiliary_width - else None - ) + self.key_cache = torch.empty(shape, device=self.device, dtype=storage) + self.value_cache = torch.empty_like(self.key_cache) # One scale per stored vector; None for an unquantized pool. self.key_scale = self.value_scale = None if kv_cache_dtype == "fp8_e4m3": @@ -338,7 +315,7 @@ def num_used_blocks(self) -> int: @property def bytes_per_block(self) -> int: - size = kv_bytes_per_block( + return kv_bytes_per_block( self.num_layers, self.block_size, self.num_kv_heads, @@ -346,9 +323,6 @@ def bytes_per_block(self) -> int: self.key_cache.element_size(), self.kv_cache_dtype, ) - if self.auxiliary_cache is not None: - size += self.auxiliary_cache.stride(0) * self.auxiliary_cache.element_size() - return size def required_blocks(self, max_tokens: int) -> int: if not isinstance(max_tokens, Integral) or isinstance(max_tokens, bool) or max_tokens <= 0: @@ -903,27 +877,7 @@ def _write_prepared( if not rows: return self._store_layer(layer, batch.write_blocks, batch.write_offsets, k[:rows], v[:rows]) - self._mark_prepared_write(layer, batch, coverage) - - def record_external_kv(self, layer, batch): - """Record host coverage after a fused backend has enqueued its KV writes.""" - self._validate_layer(layer) - coverage = self._require_live_batch(batch) - if isinstance(batch, MixedRecurrentKVMetadata): - batch = batch.prompt - coverage = self._require_live_batch(batch) - if isinstance(batch, DeviceKVMetadata): - return - if not batch.writable: - raise ValueError("a read-only prepared KV batch cannot be written") - self._mark_prepared_write(layer, batch, coverage) - - def _mark_prepared_write(self, layer, batch, coverage): - if batch.packed_ranges is not None: - for seq in batch.packed_ranges: - written = seq.allocation.written[self._plane(seq.depth)][layer] - written.add_range(seq.start, seq.end) - elif coverage is None: + if coverage is None: for allocation, depth, position in batch.rows: allocation.written[self._plane(depth)][layer].add(position) else: @@ -1046,10 +1000,7 @@ def _attend_prepared( ) if not batch.rows: return torch.empty_like(q) - if batch.packed_ranges is not None: - for seq in batch.packed_ranges: - self._require_prefix(seq.allocation, layer, seq.depth, seq.end) - elif coverage is None: + if coverage is None: for allocation, depth, position in batch.rows: self._require_prefix(allocation, layer, depth, position + 1) else: diff --git a/vllm_rlt/core/memory.py b/vllm_rlt/core/memory.py index 40f88f7c..1c52c16c 100644 --- a/vllm_rlt/core/memory.py +++ b/vllm_rlt/core/memory.py @@ -28,13 +28,9 @@ def graph_memory_reserve(model, scheduler, execution, speculative=None): if not execution.cuda_graphs: return 0 pools = 1 + bool(getattr(model, "requires_boundary_kv", False)) - if getattr(model, "supports_packed_prefill_graphs", False): - pools += (execution.packed_prefill is not False) + (scheduler.mode == "mixed") retained_logits = 0 if speculative is not None: pools += 2 - if execution.async_scheduling and getattr(model, "requires_ordered_pipeline_coda", False): - pools += 1 rows = min( cuda_graph_rows(execution), scheduler.max_num_seqs * (speculative.num_speculative_tokens + 1), @@ -56,13 +52,6 @@ def graph_memory_reserve(model, scheduler, execution, speculative=None): def _probe_forward(model, cache, tokens, ids, positions): count = len(ids) - if getattr(model, "interleaved_kv", False): - depth_sets = [[depth] * count for depth in range(model.config.total_ut_steps)] - metadata = cache._prepare_batches(ids, depth_sets, positions, packed_prefill=True) - hidden = model.prelude_prepared(tokens, metadata[0], cache) - for batch in metadata: - hidden, _ = model.recurrent_prepared(hidden, batch, cache) - return model.coda_prepared(hidden, metadata[0], cache) boundary = None if getattr(model, "requires_boundary_kv", False): boundary = cache._prepare_batch(ids, [0] * count, positions) @@ -160,8 +149,6 @@ def plan_cache( parameter.element_size(), cache.kv_cache_dtype, ) - auxiliary_width = getattr(config, "auxiliary_cache_width", 0) - per_block += kv_layers * cache.block_size * auxiliary_width * parameter.element_size() if cache.num_blocks is not None: return cache.num_blocks, {"source": "blocks", "bytes_per_block": per_block} if cache.kv_cache_memory_bytes is not None: @@ -205,8 +192,6 @@ def plan_cache( recurrent_layers=getattr(model, "recurrent_kv_layers", None), kv_cache_dtype=cache.kv_cache_dtype, fp8_scale=fp8_scale, - auxiliary_width=auxiliary_width, - interleaved_kv=getattr(model, "interleaved_kv", False), ) ids, positions = [], [] for index, length in enumerate(lengths): @@ -222,7 +207,7 @@ def plan_cache( # Profiling includes a conservative temporary KV allocation. Also budget for # long-context reference attention (Triton's online softmax has bounded scratch). context_scratch = 0 - if backend == "torch" and not auxiliary_width: + if backend == "torch": context_scratch = ( config.max_position_embeddings * config.num_attention_heads @@ -234,9 +219,8 @@ def plan_cache( scheduler, cache, execution, - torch.empty((), dtype=getattr(model, "state_dtype", parameter.dtype)).element_size(), + parameter.element_size(), staged_prefill=staged_prefill, - device_kv_metadata=getattr(model, "supports_device_kv_metadata", True), ) # Dynamic metadata at the largest supported context is small but not zero. metadata_width = math.ceil(config.max_position_embeddings / cache.block_size) diff --git a/vllm_rlt/core/scheduler.py b/vllm_rlt/core/scheduler.py index ea704070..9c9bce7f 100644 --- a/vllm_rlt/core/scheduler.py +++ b/vllm_rlt/core/scheduler.py @@ -140,8 +140,6 @@ def __init__( total_ut_steps: int | None = None, eos_token_id=(), exit_mode: str = "ouro", - mixed_speculative: bool = False, - prioritize_prefill_continuations: bool = False, ): self.config = config self.cache_manager = cache_manager @@ -169,16 +167,10 @@ def __init__( # recurrent batches. Other prompt chunks execute all depths atomically. self.wavefront_chunked_prefill = config.wavefront_chunked_prefill self.staged_prefill = requires_staged_prefill(config, produces_tokens=produces_tokens) - self.prioritize_prefill_continuations = ( - prioritize_prefill_continuations - and config.mode == "mixed" - and not self.wavefront_chunked_prefill - ) self.policy = create_scheduling_policy( config, speculative_config, produces_tokens=produces_tokens, - mixed_speculative=mixed_speculative, ) def add_request(self, request: Request): @@ -189,19 +181,7 @@ def add_request(self, request: Request): def enqueue(self, request: Request, phase: RequestPhase): request.phase = phase - queue = self.queues[phase] - if ( - self.prioritize_prefill_continuations - and request.num_prefilled_tokens > 0 - and phase in (RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT) - ): - # Continue prompts with a completed chunk first. Preserve queue - # order within each group. - for index, request_id in enumerate(queue): - if self.requests[request_id].num_prefilled_tokens == 0: - queue.insert(index, request.request_id) - return - queue.append(request.request_id) + self.queues[phase].append(request.request_id) def suspend_for_transfer(self, request): """Stop scheduling without freeing resources that a transfer still borrows.""" @@ -721,31 +701,29 @@ def has_ready(self, phase): def _take(self, phase: RequestPhase) -> SchedulerOutput | None: return self.take_phases((phase,)) - def take_phases(self, phases, *, eligible=None, reserve_for_later=0): + def take_phases(self, phases, *, eligible=None): """Select compatible requests across queues under one budget/reservation set.""" eligible = eligible if eligible is not None else self.execution_ready token_budget = self.config.max_num_batched_tokens scheduled_requests = [] selected: set[str] = set() - for index, phase in enumerate(phases): + for phase in phases: queue = self.queues[phase] - reserved = reserve_for_later if index == 0 else 0 - available = token_budget - reserved if self.wavefront_chunked_prefill and phase in ( RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT, ): - token_budget = reserved + self._take_wavefront_phase( + token_budget = self._take_wavefront_phase( phase, queue, - available, + token_budget, scheduled_requests, selected, eligible, ) continue remaining = len(queue) - while queue and available and len(selected) < self.config.max_num_seqs and remaining: + while queue and token_budget and len(selected) < self.config.max_num_seqs and remaining: remaining -= 1 request = self.requests[queue.popleft()] if eligible is not None and not eligible(request): @@ -762,7 +740,7 @@ def take_phases(self, phases, *, eligible=None, reserve_for_later=0): ): queue.append(request.request_id) continue - scheduled_request = self._make_scheduled_request(request, phase, available) + scheduled_request = self._make_scheduled_request(request, phase, token_budget) if ( phase in (RequestPhase.PREFILLING_PRELUDE, RequestPhase.PREFILLING_RECURRENT) and scheduled_request.token_count <= 0 @@ -784,7 +762,6 @@ def take_phases(self, phases, *, eligible=None, reserve_for_later=0): selected.add(request.request_id) scheduled_requests.append(replace(scheduled_request, phase=phase)) token_budget -= scheduled_request.token_count - available -= scheduled_request.token_count if not scheduled_requests: return None # Fairness follows the requests actually selected, including a mixed attempt @@ -792,9 +769,7 @@ def take_phases(self, phases, *, eligible=None, reserve_for_later=0): selected_phases = {scheduled_request.phase for scheduled_request in scheduled_requests} prompt_phases = selected_phases.intersection(self.policy.PREFILL_PHASES) recorded = ( - RequestPhase.SPECULATIVE - if RequestPhase.SPECULATIVE in selected_phases - else RequestPhase.RECURRENT + RequestPhase.RECURRENT if RequestPhase.RECURRENT in selected_phases else next(iter(prompt_phases)) if prompt_phases @@ -824,8 +799,6 @@ 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 phases == {RequestPhase.SPECULATIVE, RequestPhase.PREFILLING_RECURRENT}: - return 1 if RequestPhase.SPECULATIVE in phases or RequestPhase.CODA in phases: return 0 if RequestPhase.PRELUDE in phases: @@ -836,12 +809,7 @@ def _planned_loop_count(self, scheduled_requests): # 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. - if self.config.mode == "mixed" and ( - self.has_ready(RequestPhase.RECURRENT) - or ( - self.speculative_config is not None and self.has_ready(RequestPhase.SPECULATIVE) - ) - ): + if self.config.mode == "mixed" and self.has_ready(RequestPhase.RECURRENT): return 0 return self.total_ut_steps if RequestPhase.PREFILLING_RECURRENT in phases: @@ -1435,8 +1403,7 @@ def update_from_output( request.loops_done = 0 if request.request_id not in self.queues[RequestPhase.SPECULATIVE]: self.enqueue(request, RequestPhase.SPECULATIVE) - if emitted: - update.outputs.append(request) + update.outputs.append(request) return update def update_after_submission( diff --git a/vllm_rlt/core/scheduling_policy.py b/vllm_rlt/core/scheduling_policy.py index 561acf12..39b405ec 100644 --- a/vllm_rlt/core/scheduling_policy.py +++ b/vllm_rlt/core/scheduling_policy.py @@ -153,43 +153,6 @@ def schedule(self, scheduler, *, prefer_recurrent=False): return None -class MixedSpeculativePolicy(SpeculativePolicy): - """Share a core visit while keeping bootstrap and round results independent.""" - - def schedule(self, scheduler, *, prefer_recurrent=False): - if scheduler.has_ready(RequestPhase.CODA): - return scheduler._take(RequestPhase.CODA) - scheduler._admit() - if scheduler.has_ready(RequestPhase.CODA): - return scheduler._take(RequestPhase.CODA) - decode_ready = scheduler.has_ready(RequestPhase.SPECULATIVE) - if decode_ready and scheduler.has_ready(RequestPhase.PREFILLING_RECURRENT): - # Leave room for prompt rows even when all decode windows could - # fill the batch. For a one-row budget, decode_due caps the prompt streak. - budget = self.config.max_num_batched_tokens - reserved = ( - int(not self.decode_due) - if budget == 1 - else min(self.config.prefill_chunk_size, max(1, budget // 4)) - ) - batch = scheduler.take_phases( - (RequestPhase.SPECULATIVE, RequestPhase.PREFILLING_RECURRENT), - reserve_for_later=reserved, - ) - if batch is not None: - return batch - if decode_ready and self.decode_due: - batch = scheduler._take(RequestPhase.SPECULATIVE) - if batch is not None: - return batch - for phase in self.PREFILL_PHASES: - if scheduler.has_ready(phase): - batch = scheduler._take(phase) - if batch is not None: - return batch - return scheduler._take(RequestPhase.SPECULATIVE) if decode_ready else None - - class SplitPrefillPolicy(RefillPolicy): """Refill ordering for staged prompt work and recurrent depth boundaries.""" @@ -223,7 +186,6 @@ def create_scheduling_policy( speculative_config: SpeculativeConfig | None, *, produces_tokens: bool = True, - mixed_speculative: bool = False, ) -> SchedulingPolicy: """Pick one policy; reject combinations no policy implements yet. @@ -242,9 +204,7 @@ def create_scheduling_policy( # The remaining compatibility checks apply to generation scheduling. if scheduler_config.mode == "mixed": if speculative_config is not None: - if not mixed_speculative or speculative_config.mode != "pipeline": - raise ValueError("mixed scheduling requires a compatible speculative pipeline") - return MixedSpeculativePolicy(scheduler_config) + raise ValueError("mixed scheduling does not support speculative work") elif staged_prefill and speculative_config is None and scheduler_config.mode != "refill": raise ValueError("staged prefill currently implements refill or mixed scheduling") diff --git a/vllm_rlt/engine/llm_engine.py b/vllm_rlt/engine/llm_engine.py index 03bea9b5..8402b24a 100644 --- a/vllm_rlt/engine/llm_engine.py +++ b/vllm_rlt/engine/llm_engine.py @@ -32,7 +32,7 @@ def __init__( revision=None, model_config=None, seed=0, - startup_timeout=None, + startup_timeout=120, shutdown_timeout=30, stage_config=None, connector_factory=None, @@ -61,8 +61,7 @@ def __init__( self.trace_mode = getattr(engine_options.get("exit_config"), "mode", None) == "trace" self.closed = False self.failure = None - self.timeout = 120 if startup_timeout is None else startup_timeout - self.startup_timeout = 600 if startup_timeout is None else startup_timeout + self.timeout = startup_timeout self.shutdown_timeout = shutdown_timeout self.requests = {} # External ID -> unique execution generation, no Request copies. self.generations = {} @@ -93,7 +92,7 @@ def __init__( raise def wait_ready(self): - deadline = time.monotonic() + self.startup_timeout + deadline = time.monotonic() + self.timeout while not self.ready: remaining = deadline - time.monotonic() if remaining <= 0: diff --git a/vllm_rlt/engine/stage_engine.py b/vllm_rlt/engine/stage_engine.py index 7453612d..a8006977 100644 --- a/vllm_rlt/engine/stage_engine.py +++ b/vllm_rlt/engine/stage_engine.py @@ -14,7 +14,7 @@ ) from vllm_rlt.core.kv_cache_manager import KVCacheManager from vllm_rlt.core.memory import calibrate_fp8_scale, plan_cache -from vllm_rlt.core.scheduler import Scheduler, SchedulerOutput +from vllm_rlt.core.scheduler import Scheduler from vllm_rlt.core.scheduling_policy import requires_staged_prefill from vllm_rlt.engine.connector import StageConnector from vllm_rlt.engine.packed_prefill import packed_prefill_eligible @@ -65,7 +65,6 @@ def __init__( scheduler_config = scheduler_config or SchedulerConfig() parameter = next(model.parameters()) config = model.config - auxiliary_width = getattr(config, "auxiliary_cache_width", 0) if getattr(model, "requires_boundary_kv", False): required_layout = getattr(model, "kv_cache_layout", "last_exited") if cache_config.layout != required_layout: @@ -76,23 +75,6 @@ def __init__( self.execution_config = resolve_cuda_graph_rows( execution_config or ExecutionConfig(), scheduler_config, speculative_config ) - if self.execution_config.cuda_graph_warmup and not getattr(model, "interleaved_kv", False): - raise ValueError("CUDA Graph warmup requires native Inkling kernels") - if auxiliary_width: - if attention_backend not in ("auto", "torch", "triton"): - raise ValueError("Inkling 2 Mini requires the Triton KV backend") - # Inkling uses Triton for KV layout and vLLM for model attention. - attention_backend = "triton" - if ( - cache_config.kv_cache_dtype != "auto" - or scheduler_config.enable_preemption - or self.stage_config.role != "prefill_decode" - ): - raise ValueError( - "Inkling 2 Mini requires a single stage with BF16 KV, without preemption" - ) - if self.exit_config.mode != "ouro": - raise ValueError("Inkling 2 Mini runs the configured number of passes") if parameter.device.type == "npu": if config.to_dict()["model_type"] != "ouro" or config.total_ut_steps != 4: raise ValueError("NPU currently supports Ouro with four loops") @@ -128,35 +110,8 @@ def __init__( speculative=speculative_config is not None, preemption=scheduler_config.enable_preemption, ) - ordered_pipeline = ( - speculative_config is not None - and speculative_config.mode == "pipeline" - and getattr(model, "requires_ordered_pipeline_coda", False) - ) - device_boundary_pipeline = ordered_pipeline and getattr(model, "interleaved_kv", False) - mixed_speculative = scheduler_config.mode == "mixed" and speculative_config is not None - if mixed_speculative: - if not ( - device_boundary_pipeline - and getattr(model, "fixed_loop_count", False) - and self.execution_config.async_scheduling - and speculative_config.draft_loops == 1 - and self.stage_config.role == "prefill_decode" - ): - raise ValueError( - "mixed speculative decoding requires the async native Inkling pipeline" - ) - if self.execution_config.packed_prefill is False: - raise ValueError("mixed speculative decoding requires packed prefill") - self.execution_config = replace(self.execution_config, packed_prefill=True) - prefer_packed = True if getattr(model, "requires_boundary_kv", False): - prefill_capability = ( - "supports_wavefront_prefill" - if scheduler_config.wavefront_chunked_prefill - else "supports_mixed_prefill" - ) - if staged_prefill and not getattr(model, prefill_capability, False): + if staged_prefill: raise ValueError( "boundary-KV models do not support staged prefill required by this scheduler" ) @@ -165,14 +120,11 @@ def __init__( ): raise ValueError("boundary-KV models require synchronous scheduling") if speculative_config is not None: - if not ordered_pipeline and not getattr(model, "supports_self_speculation", False): + if not getattr(model, "supports_self_speculation", False): raise ValueError("boundary-KV speculative decoding is not yet supported") - if ordered_pipeline: - if self.execution_config.async_scheduling and not device_boundary_pipeline: - raise ValueError("async boundary pipeline requires interleaved KV") - if scheduler_config.enable_preemption: - raise ValueError("Inkling pipeline requires preemption to be disabled") - elif ( + # Qualified: synchronous eager rounds. Async rounds, Graph replay and + # resumable preemption of draft/target boundary state are separate work. + if ( self.execution_config.async_scheduling or self.execution_config.cuda_graphs or scheduler_config.enable_preemption @@ -189,14 +141,6 @@ def __init__( ) self.async_speculative = bool(speculative_config and self.execution_config.async_scheduling) if speculative_config is not None: - if speculative_config.pipeline_graph != "off" and not ( - device_boundary_pipeline - and self.async_speculative - and self.execution_config.cuda_graphs - ): - raise ValueError( - "pipeline_graph requires native Inkling, async scheduling and CUDA Graphs" - ) if cache_config.layout != "last_exited": raise ValueError("speculative decoding requires last_exited KV") if speculative_config.target_loops != config.total_ut_steps: @@ -205,7 +149,7 @@ def __init__( raise ValueError("speculative decoding requires fixed-depth ouro exit mode") if self.async_speculative and parameter.device.type != "cuda": raise ValueError("async speculative decoding requires CUDA") - if (scheduler_config.mode != "refill" and not mixed_speculative) or ( + if scheduler_config.mode != "refill" or ( self.async_speculative and not self.pipeline_speculative and scheduler_config.enable_preemption @@ -342,8 +286,6 @@ def __init__( recurrent_layers=getattr(model, "recurrent_kv_layers", None), kv_cache_dtype=cache_config.kv_cache_dtype, fp8_scale=fp8_scale, - auxiliary_width=auxiliary_width, - interleaved_kv=getattr(model, "interleaved_kv", False), ) self.scheduler = Scheduler( scheduler_config, @@ -353,13 +295,6 @@ def __init__( total_ut_steps=config.total_ut_steps, eos_token_id=config.eos_token_id, exit_mode=self.exit_config.mode, - mixed_speculative=mixed_speculative, - prioritize_prefill_continuations=( - getattr(model, "interleaved_kv", False) - and getattr(model, "fixed_loop_count", False) - and connector is None - and not scheduler_config.enable_preemption - ), ) self.connector = connector # One RNG registry per engine, shared by both runners: the CODA and @@ -380,29 +315,12 @@ def __init__( staged_prefill=self.scheduler.staged_prefill, rng=self.rng, ) - if device_boundary_pipeline and self.async_speculative: - # Speculative steps execute the boundary layers as well as Core. - # Their Inkling MoE scratch is shared with new-request prefill. - # Keep model work ordered and retain separate readback streams. - self.model_runner.boundary_stream = self.model_runner.core_stream - if mixed_speculative and self.model_runner.packed_graphs is not None: - self.model_runner.packed_graphs.enable_speculative_core() - self.graph_warmup = None - if self.execution_config.cuda_graph_warmup: - from vllm_rlt.worker.inkling_graph_warmup import warmup_inkling_graphs - - self.graph_warmup = warmup_inkling_graphs(self.model_runner, scheduler_config) - spec_execution = self.execution_config - if ordered_pipeline and not self.async_speculative: - # Boundary calls share the normal model's graph owners, including - # their keys, input buffers, and replay completion events. - spec_execution = replace(spec_execution, cuda_graphs=False, cuda_graph_warmup=False) self.speculative_runner = ( SpeculativeRunner( model, self.cache_manager, speculative_config, - spec_execution, + self.execution_config, rng=self.rng, runtime=self.model_runner.runtime, compute_stream=self.model_runner.core_stream, @@ -410,28 +328,6 @@ def __init__( if speculative_config is not None and not self.async_speculative else None ) - if ordered_pipeline and self.speculative_runner is not None: - self.speculative_runner.prelude_graphs = self.model_runner.prelude_graphs - self.speculative_runner.graphs = self.model_runner.graphs - self.speculative_runner.coda_graphs = self.model_runner.coda_graphs - if device_boundary_pipeline and self.execution_config.cuda_graphs: - assert speculative_config is not None - from vllm_rlt.worker.cuda_graph import ( - DeviceRecurrentGraphs, - speculative_capture_sizes, - ) - - graphs = DeviceRecurrentGraphs( - model, - self.cache_manager, - self.execution_config, - False, - capture_sizes=speculative_capture_sizes( - self.execution_config, scheduler_config, speculative_config - ), - ) - graphs.prepare() - self.speculative_runner.graphs = graphs if self.async_speculative: from vllm_rlt.worker.async_speculative import AsyncSpeculativeRunner @@ -638,21 +534,6 @@ def close(self): """Drain owned GPU work before serving teardown drops tensor owners.""" self.profiling.close() self.model_runner.synchronize() - if self.execution_config.cuda_graphs and getattr( - self.model.config, "auxiliary_cache_width", 0 - ): - names = ("prelude_graphs", "graphs", "mixed_graphs", "packed_graphs", "coda_graphs") - for name in names: - graph = getattr(self.model_runner, name) - if graph is None: - continue - logger.info( - "Inkling %s CUDA Graph captures=%d replays=%d fallbacks=%d", - name, - graph.captures, - graph.replays, - graph.fallbacks, - ) if self.async_speculative: cast("AsyncSpeculativeRunner", self.speculative_runner).synchronize() for rid in list(self.scheduler.requests): @@ -1017,26 +898,7 @@ def _step_async_speculative(self): batch = self._schedule() self.last_schedule = batch if batch is not None: - if batch.is_mixed: - speculative = SchedulerOutput( - RequestPhase.SPECULATIVE, - [item for item in batch.requests if item.phase == RequestPhase.SPECULATIVE], - loop_count=0, - ) - prompt = SchedulerOutput( - RequestPhase.PREFILLING_RECURRENT, - [ - item - for item in batch.requests - if item.phase == RequestPhase.PREFILLING_RECURRENT - ], - loop_count=batch.loop_count, - ) - ticket = self.executor.submit_mixed_speculative(speculative, prompt) - self._pending_speculative.append(ticket) - outputs.extend(self._update(prompt, None)) - self._apply_update(self.scheduler.update_after_submission(speculative)) - elif batch.is_speculative: + if batch.phase == RequestPhase.SPECULATIVE: ticket = self.executor.submit(batch) self._pending_speculative.append(ticket) self._apply_update(self.scheduler.update_after_submission(batch)) diff --git a/vllm_rlt/engine/worker.py b/vllm_rlt/engine/worker.py index 92a04cb1..80e98985 100644 --- a/vllm_rlt/engine/worker.py +++ b/vllm_rlt/engine/worker.py @@ -86,8 +86,6 @@ def __init__( ) if self.connector is not None: info.update(self.connector.startup_info()) - if self.engine.graph_warmup is not None: - info["graph_warmup"] = self.engine.graph_warmup self.send("ready", **info) def send(self, kind, **fields): diff --git a/vllm_rlt/entrypoints/cli.py b/vllm_rlt/entrypoints/cli.py index e34f832b..499cda14 100644 --- a/vllm_rlt/entrypoints/cli.py +++ b/vllm_rlt/entrypoints/cli.py @@ -81,11 +81,7 @@ def main(): ) parser.add_argument("--mode", choices=["refill", "no_refill", "mixed"], default="refill") parser.add_argument("--max-tokens", type=int, default=16) - parser.add_argument( - "--max-loops", - type=int, - help="Request loop limit. For Inkling VarLoop, also sets the instance depth.", - ) + parser.add_argument("--max-loops", type=int, default=None) parser.add_argument("--request-target-loops", type=int, default=None) parser.add_argument("--min-loops", type=int, default=None) parser.add_argument("--exit-threshold", type=float, default=1.0) @@ -126,7 +122,6 @@ def main(): llm = LLM( model, revision=args.revision, - max_loops=args.max_loops, device=args.device, dtype=getattr(torch, args.dtype), **runtime_configs(args), diff --git a/vllm_rlt/entrypoints/llm.py b/vllm_rlt/entrypoints/llm.py index 66865d40..55e46104 100644 --- a/vllm_rlt/entrypoints/llm.py +++ b/vllm_rlt/entrypoints/llm.py @@ -20,7 +20,6 @@ def __init__( *, tokenizer=None, revision=None, - max_loops=None, device=None, dtype=None, cache_config=None, @@ -32,7 +31,6 @@ def __init__( ): tokenizer_source = resolve_model_source(model) if isinstance(model, str) else None model, revision, model_config = prepare_model(model, revision=revision) - model_config = model_config.with_max_loops(max_loops) self._tokenizer_source = ( (tokenizer_source, revision) if tokenizer is None and tokenizer_source is not None diff --git a/vllm_rlt/entrypoints/runtime_args.py b/vllm_rlt/entrypoints/runtime_args.py index c02db413..679a198c 100644 --- a/vllm_rlt/entrypoints/runtime_args.py +++ b/vllm_rlt/entrypoints/runtime_args.py @@ -17,12 +17,6 @@ def add_runtime_args(parser): help="Enable fixed-loop self-speculation with K draft tokens", ) parser.add_argument("--speculative-mode", choices=["block", "pipeline"], default="block") - parser.add_argument( - "--speculative-pipeline-graph", - choices=["off", "transition", "full"], - default="off", - help="Pre-capture native asynchronous pipeline state updates or dense decode rounds", - ) parser.add_argument("--draft-loops", type=int, default=2) parser.add_argument("--target-loops", type=int, default=4) parser.add_argument("--enable-prefix-caching", action="store_true") @@ -81,16 +75,6 @@ def add_runtime_args(parser): help="Graph row limit; unset covers async speculative verification rows, else 128", ) parser.add_argument("--cuda-graph-max-graphs", type=int, default=16) - parser.add_argument( - "--cuda-graph-warmup", - action="store_true", - help="Prewarm native Inkling CUDA Graphs at startup and run unseen shapes eagerly", - ) - parser.add_argument( - "--packed-graph-buckets", - action="store_true", - help="Use vLLM token buckets and a shared graph pool for native Inkling packed CUDA Graphs", - ) parser.add_argument( "--cuda-graph-memory-reserve-bytes", type=int, @@ -121,15 +105,12 @@ def runtime_configs(args): parser = argparse.ArgumentParser(add_help=False) add_runtime_args(parser) args = SimpleNamespace(**(vars(parser.parse_args([])) | vars(args))) - if args.speculative_pipeline_graph != "off" and args.speculative_tokens is None: - raise ValueError("--speculative-pipeline-graph requires --speculative-tokens") return dict( speculative_config=SpeculativeConfig( num_speculative_tokens=args.speculative_tokens, draft_loops=args.draft_loops, target_loops=args.target_loops, mode=args.speculative_mode, - pipeline_graph=args.speculative_pipeline_graph, ) if args.speculative_tokens is not None else None, @@ -156,10 +137,8 @@ def runtime_configs(args): packed_prefill=args.packed_prefill, use_uva=args.use_uva, cuda_graphs=args.cuda_graphs, - cuda_graph_warmup=args.cuda_graph_warmup, cuda_graph_max_batch_size=args.cuda_graph_max_batch_size, cuda_graph_max_graphs=args.cuda_graph_max_graphs, - packed_graph_buckets=args.packed_graph_buckets, cuda_graph_memory_reserve_bytes=args.cuda_graph_memory_reserve_bytes, async_scheduling=args.async_scheduling, multi_stream=not args.single_stream, diff --git a/vllm_rlt/entrypoints/serve.py b/vllm_rlt/entrypoints/serve.py index 1a68f520..c7fc3c84 100644 --- a/vllm_rlt/entrypoints/serve.py +++ b/vllm_rlt/entrypoints/serve.py @@ -38,17 +38,13 @@ def load_engine(args): else (args.revision if args.tokenizer else revision) ), ) - model_type = config["model_type"].lower() - if model_type == "ouro": + if config["model_type"].lower() == "ouro": decoder = getattr(getattr(tokenizer, "backend_tokenizer", None), "decoder", None) if not isinstance(decoder, ByteLevel): raise ValueError("serving requires the Ouro byte-level tokenizer") - max_loops = getattr(args, "max_loops", None) - if max_loops is not None and model_type != "inkling2_loop": - raise ValueError("serve --max-loops sets the startup depth of an Inkling checkpoint") engine = StageClient( source, - model_config=ModelConfig.from_dict(config).with_max_loops(max_loops), + model_config=ModelConfig.from_dict(config), revision=revision, device=args.device, dtype=args.dtype, @@ -84,7 +80,6 @@ def main(): "--model", help="Local checkpoint path or HuggingFace repository ID", required=True ) parser.add_argument("--revision") - parser.add_argument("--max-loops", type=int, help="Startup depth for Inkling VarLoop") parser.add_argument("--tokenizer") parser.add_argument("--tokenizer-revision") parser.add_argument("--served-model-name") diff --git a/vllm_rlt/kernels/inkling2mini.py b/vllm_rlt/kernels/inkling2mini.py deleted file mode 100644 index 645ca14b..00000000 --- a/vllm_rlt/kernels/inkling2mini.py +++ /dev/null @@ -1,497 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Functional Inkling kernels from vLLM's SM10x path, called by the RLT model.""" - -from functools import cache -from types import SimpleNamespace -from typing import NamedTuple - -import numpy as np -import torch -from torch import nn - - -@cache -def load_ops(): - try: - from vllm.models.inkling.nvidia.ops.sconv import sconv_seq_metadata - from vllm.models.inkling2.nvidia.ops import ( - activation, - attention, - attn_res, - block_scales, - conv_mix, - linear, - loop, - moe, - norm, - sconv, - trtllm_bmm, - ) - except ImportError as error: - raise RuntimeError( - "Inkling's vllm kernels require a CUDA build of vLLM with Inkling 2 support " - "(tested source revision 3146a9df4140)" - ) from error - return SimpleNamespace( - activation=activation, - attention=attention, - attn_res=attn_res, - block_scales=block_scales, - conv_mix=conv_mix, - linear=linear, - loop=loop, - moe=moe, - norm=norm, - sconv=sconv, - sconv_seq_metadata=sconv_seq_metadata, - bmm=trtllm_bmm, - prefill=attention.Inkling2FA4RelAttentionKernel(), - ) - - -def warmup_fa4(config, cache, max_tokens, max_sequences): - """Compile reachable local and full relative-attention kernel variants.""" - from vllm.models.inkling.nvidia.ops.fa4_rel_attention import _num_warps_bucket - - ops = load_ops() - kernel = ops.prefill - heads, kv_heads = config.num_attention_heads, config.num_key_value_heads - warp_buckets = sorted({_num_warps_bucket(n) for n in range(1, max_sequences + 1)}) - query = 1 - while query <= ops.attention.bucket_max_seqlen_q(max_tokens): - if not ops.attention.plan_decode_attention( - False, 1, query, heads, kv_heads, config.rel_extent - ): - for local in (False, True): - variants = [(False, None)] - if not local: - variants.extend((True, warps) for warps in (None, *warp_buckets)) - for split, warps in variants: - kernel.compile( - kernel.CompileKey( - is_local=local, - num_heads=heads, - num_kv_heads=kv_heads, - head_dim=config.head_dim, - rel_extent=config.window if local else config.rel_extent, - dtype=cache.key_cache.dtype, - kv_dtype=cache.key_cache.dtype, - block_size=cache.block_size, - max_seqlen_q=query, - split_kv=split, - num_warps_bucket=warps, - large_num_reqs=max_sequences > 1024, - ) - ) - query *= 2 - - -class QuantizedExperts(nn.Module): - """RLT-owned weights and buffers for the upstream routing/quantized GEMM kernels.""" - - def __init__(self, config, read): - super().__init__() - self.ops = load_ops() - block_scales, moe, bmm = self.ops.block_scales, self.ops.moe, self.ops.bmm - self.router = nn.Parameter(read("gate.weight"), requires_grad=False) - self.bias = nn.Parameter(read("gate.bias"), requires_grad=False) - self.topk = config.experts_per_token - self.route_scale = config.route_scale - self.gate_cap = config.gate_softcap - self.up_cap = config.up_softcap - self.num_experts = len(self.router) - shapes = [] - for projection in ("w13", "w2"): - name = f"experts.{projection}_weight" - weight = read(name) - scale = read(f"{name}_scale") - nvfp4 = weight.dtype == torch.uint8 - shapes.append((weight.shape[1], weight.shape[2] * (2 if nvfp4 else 1))) - setattr(self, projection, nn.Parameter(block_scales.shuffle_rows(weight), False)) - scale = block_scales.swizzle_block_scales(block_scales.shuffle_rows(scale)) - setattr(self, f"{projection}_scale", nn.Parameter(scale, False)) - if nvfp4: - self.register_buffer(f"{projection}_amax", read(f"{name}_amax")) - self.register_buffer( - f"{projection}_denominator", read(f"{name}_outer_scale_denominator") - ) - self.nvfp4 = self.w13.dtype == torch.uint8 - self.shapes = tuple(shapes) - device = self.router.device - self.register_buffer( - "bounds", - torch.tensor([0, self.num_experts], device=device, dtype=torch.int32), - persistent=False, - ) - self.register_buffer( - "counters", - torch.zeros(moe.NUM_COUNTERS, device=device, dtype=torch.int32), - persistent=False, - ) - self.register_buffer( - "counts", - torch.zeros(self.num_experts, device=device, dtype=torch.int32), - persistent=False, - ) - self.register_buffer( - "ones", - torch.ones(self.num_experts, device=device, dtype=torch.float32), - persistent=False, - ) - bmm.load_kernels((self.w13, self.w2), (self.w13_scale, self.w2_scale), self.topk) - - def _scales(self, projection): - if not self.nvfp4: - return None, None - return getattr(self, f"{projection}_amax"), getattr(self, f"{projection}_denominator") - - def forward(self, hidden): - activation, moe, bmm = self.ops.activation, self.ops.moe, self.ops.bmm - hidden = hidden.contiguous() - plan = bmm.expert_plan(len(hidden), self.topk, self.num_experts, self.nvfp4, self.shapes) - routing, quantized = moe.route( - hidden, - self.router, - self.bias, - self.counters, - self.counts, - self.topk, - self.route_scale, - self.bounds, - plan, - *self._scales("w13"), - ) - inverse, gammas, rows, tiles = routing - gate_up = bmm.bmm(*quantized, self.w13, self.w13_scale, self.ones, tiles, plan, 0) - count = plan.max_ctas - quantized = activation.swiglu_quantize( - gate_up, - gammas, - self.gate_cap, - self.up_cap, - (rows, tiles[2 * count + 2 :], tiles[:count]), - plan.tile, - *self._scales("w2"), - ) - down = bmm.bmm(*quantized, self.w2, self.w2_scale, self.ones, tiles, plan, 1) - return moe.combine(down, inverse, self.topk, hidden.dtype) - - -def residual_stack(blocks): - stack = blocks.transpose(0, 1).contiguous() - _, tokens, width = stack.shape - return stack.as_strided(stack.shape, (tokens * width, width, 1)) - - -def attention_residual(blocks, queries): - stack = residual_stack(blocks) - queries = (queries.float() * stack.shape[-1] ** -0.5).contiguous() - mixed = load_ops().attn_res.attn_res(stack[:-1], stack[-1], None, queries, None, 0.0, True) - return mixed.transpose(0, 1) - - -def message_controller(dest, message, down, gain_forget, weight, eps, active=None): - ops = load_ops() - message = message.contiguous() - pair = ops.loop.pair_rms_norm(dest, message) - rank = torch.bmm(pair, down.transpose(1, 2)) - gains = torch.bmm(rank, gain_forget.transpose(1, 2), out_dtype=torch.float32) - mixed = ops.loop.blend_rms_norm(dest, message, gains, weight, eps) - if active is not None: - plain = torch.stack([rms_norm(x, w, eps) for x, w in zip(dest, weight, strict=True)]) - mixed = torch.where(active, mixed, plain) - return mixed - - -def rms_norm(hidden, weight, epsilon): - return load_ops().norm.rms_norm(hidden, weight, epsilon, out_dtype=weight.dtype) - - -class AttentionPlan(NamedTuple): - decode_reqs: int - decode_rows: int - max_decode_query: int - decode_splits: int - prefill: tuple[int, int, bool] | None - - -def packed_attention_plans(metadata, config): - """Return the launch parameters shared by all full or local layers.""" - from vllm_rlt.worker.metadata import MixedRecurrentKVMetadata - - mixed = isinstance(metadata, MixedRecurrentKVMetadata) - ranges = metadata.prompt.packed_ranges if mixed else getattr(metadata, "packed_ranges", None) - if ranges is not None: - lengths = [seq.end for seq in ranges] - query = [seq.end - seq.start for seq in ranges] - if mixed: - # Decode launch planning uses only the row count. A capacity bound - # is available if a shape instead requires all rows to use FA4. - capacity = metadata.block_tables.shape[1] * metadata.prompt.owner.block_size - lengths = [capacity] * metadata.decode_rows + lengths - query = [1] * metadata.decode_rows + query - else: - lengths, query = [], [] - previous = None - for allocation, depth, pos in metadata.rows: - key = id(allocation), depth - if key != previous: - lengths.append(pos + 1) - query.append(1) - previous = key - else: - if pos != lengths[-1]: - raise ValueError("packed Inkling rows must be contiguous within a sequence") - lengths[-1] = pos + 1 - query[-1] += 1 - leading_decode = next((i for i, count in enumerate(query) if count > 1), len(query)) - query = np.asarray(query, dtype=np.int64) - lengths = np.asarray(lengths, dtype=np.int64) - return tuple( - _attention_plan(config, local, metadata, packed=(leading_decode, query, lengths)) - for local in (False, True) - ) - - -def _attention_plan(config, local, metadata, *, packed=None): - ops = load_ops().attention - extent = config.window if local else config.rel_extent - tokens = len(metadata.write_blocks) - requests = len(metadata.context_lengths) - max_query = metadata.max_seqlen_q - - def decode_splits(reqs, query_rows): - return ops.plan_decode_attention( - local, reqs, query_rows, config.num_attention_heads, config.num_key_value_heads, extent - ) - - splits = decode_splits(requests, max_query) - if splits: - return AttentionPlan(requests, tokens, max_query, splits, None) - decode_reqs = 0 - if packed is None: - query = np.ones(tokens, dtype=np.int64) - lengths = np.asarray([pos + 1 for _, _, pos in metadata.rows], dtype=np.int64) - else: - leading_decode, query, lengths = packed - if 0 < leading_decode < requests: - splits = decode_splits(leading_decode, 1) - if splits: - decode_reqs = leading_decode - query = query[decode_reqs:] - prefill_splits, use_scheduler = ops.plan_attention( - local, query, lengths[decode_reqs:], config.num_attention_heads, config.num_key_value_heads - ) - prefill = ops.bucket_max_seqlen_q(int(query.max())), prefill_splits, use_scheduler - return AttentionPlan(decode_reqs, decode_reqs, 1, splits, prefill) - - -def _prepare_sconv_metadata(cu_seqlens, tokens): - """Build the per-token request index and query start for native kernels.""" - seq_idx = torch.empty(tokens, dtype=torch.int32, device=cu_seqlens.device) - query_start = torch.empty_like(seq_idx) - if tokens: - load_ops().sconv_seq_metadata(cu_seqlens, len(cu_seqlens) - 1, tokens, seq_idx, query_start) - return seq_idx, query_start - - -class KernelBatch: - """Translate RLT's prepared addresses into the functional kernel inputs.""" - - def __init__(self, cache, metadata, config, *, fused_sconv_metadata=False): - self.cache, self.metadata, self.config = cache, metadata, config - self.positions = metadata.position_ids[: len(metadata.write_blocks)] - self.slot_mapping = metadata.write_blocks * cache.block_size + metadata.write_offsets - mask = getattr(metadata, "write_mask", None) - if mask is not None: - self.slot_mapping = self.slot_mapping.masked_fill(~mask, -1) - self.seq_lens = metadata.context_lengths - self.block_table = metadata.block_tables - self.cu_seqlens = metadata.cu_seqlens_q - self.attention_segments = getattr(metadata, "attention_segments", None) - if self.cu_seqlens is None: - self.cu_seqlens = torch.arange( - len(self.positions) + 1, device=self.positions.device, dtype=torch.int32 - ) - self.seq_idx = self.query_start = self.cu_seqlens[:-1] - elif fused_sconv_metadata: - self.seq_idx, self.query_start = _prepare_sconv_metadata( - self.cu_seqlens, len(self.positions) - ) - else: - rows = torch.arange( - len(self.positions), device=self.positions.device, dtype=torch.int32 - ) - self.seq_idx = torch.searchsorted(self.cu_seqlens[1:], rows, right=True, out_int32=True) - if ( - self.attention_segments is not None - and getattr(metadata, "active_rows", None) is not None - ): - # The staged table ends in repeated offsets for inactive rows. - self.seq_idx.clamp_max_(len(self.cu_seqlens) - 2) - self.query_start = self.cu_seqlens[self.seq_idx] - self.attention_plans = getattr(metadata, "packed_attention_plan", None) - if self.attention_segments is not None: - return - if self.attention_plans is None and metadata.cu_seqlens_q is not None: - self.attention_plans = packed_attention_plans(metadata, config) - self.tau = load_ops().attention.compute_log_scaling_tau( - self.positions, config.log_scale_floor, config.log_scale_alpha - ) - - def conv_state(self, layer): - return ( - self.cache.auxiliary_cache[:, layer] - .unflatten(-1, (self.config.num_key_value_heads, -1)) - .transpose(1, 2) - ) - - def conv_mix( - self, - layer, - offset, - hidden, - weight, - out, - stack, - last, - queries, - norm, - *, - residual=None, - addend=None, - ): - cfg = self.config - return load_ops().conv_mix.conv_mix( - hidden, - weight, - self.conv_state(layer), - self.positions, - self.block_table, - self.seq_idx, - self.slot_mapping, - self.query_start, - offset, - cfg.width // cfg.num_key_value_heads, - out, - residual, - addend, - stack, - last, - queries, - norm, - cfg.rms_norm_eps, - ) - - def attend(self, layer, q, r, gate, sinks, k, v, k_dynamic, v_dynamic): - output = torch.empty_like(gate, memory_format=torch.contiguous_format) - if self.attention_segments is not None: - - def attend_live(batch, *projected): - count = len(batch.positions) - if count == len(projected[-1]): - batch._attend(layer, *projected) - else: - batch._attend( - layer, - *(tensor[:count] if tensor is not None else None for tensor in projected), - ) - projected[-1][count:].zero_() - - self.attention_segments.attention( - attend_live, q, r, gate, sinks, k, v, k_dynamic, v_dynamic, output - ) - else: - self._attend(layer, q, r, gate, sinks, k, v, k_dynamic, v_dynamic, output) - return output - - def _attend(self, layer, q, r, gate, sinks, k, v, k_dynamic, v_dynamic, output): - ops, cfg, md = load_ops(), self.config, self.metadata - tokens = len(q) - q = q.view(tokens, cfg.num_attention_heads, cfg.head_dim) - r = r.view(tokens, cfg.num_attention_heads, -1) - clipped_q = torch.empty_like(q, memory_format=torch.contiguous_format) - sheared_bias = q.new_empty( - (tokens + 128, cfg.num_attention_heads, layer.rel_basis.shape[-1] + 256) - ) - keys, values = self.cache.key_cache[:, layer.index], self.cache.value_cache[:, layer.index] - ops.sconv.attention_prologue( - q, - r, - k, - v, - layer.query_scale, - layer.rel_scale, - None if layer.local else self.tau, - layer.shifted_rel_proj, - layer.conv_k, - layer.conv_v, - k_dynamic, - v_dynamic, - self.conv_state(layer.index), - self.positions, - self.block_table, - self.seq_idx, - self.slot_mapping, - self.query_start, - keys, - values, - self.slot_mapping, - clipped_q, - sheared_bias, - self.cu_seqlens, - self.seq_lens, - clip_threshold=cfg.qk_clip, - rel_threshold=cfg.rel_clip, - norm_eps=cfg.rms_norm_eps, - ) - self.cache.record_external_kv(layer.index, md) - if self.attention_plans is None: - plan = _attention_plan(cfg, layer.local, md) - else: - plan = self.attention_plans[layer.local] - decode_reqs, decode_rows = plan.decode_reqs, plan.decode_rows - if decode_rows: - ops.attention.rel_decode_attention( - clipped_q[:decode_rows], - keys, - values, - sheared_bias, - gate[:decode_rows], - sinks[:decode_rows], - output[:decode_rows], - block_table=self.block_table[:decode_reqs], - cache_seqlens=self.seq_lens[:decode_reqs], - cu_seqlens_q=self.cu_seqlens[: decode_reqs + 1], - max_query_len=plan.max_decode_query, - num_actual_tokens=decode_rows, - softmax_scale=cfg.head_dim**-0.5, - is_local=layer.local, - num_splits=plan.decode_splits, - ) - if plan.prefill is not None: - max_query, splits, use_scheduler = plan.prefill - result = torch.empty_like(clipped_q[decode_rows:], dtype=torch.float32) - lse = q.new_empty((cfg.num_attention_heads, tokens - decode_rows), dtype=torch.float32) - cu = self.cu_seqlens[decode_reqs:] - if decode_reqs: - cu = cu - decode_rows - ops.prefill( - clipped_q[decode_rows:], - keys, - values, - block_table=self.block_table[decode_reqs:], - cache_seqlens=self.seq_lens[decode_reqs:], - cu_seqlens_q=cu, - max_seqlen_q=max_query, - softmax_scale=cfg.head_dim**-0.5, - window_size=(cfg.window - 1, 0) if layer.local else (-1, -1), - sheared_bias=sheared_bias[decode_rows:], - num_splits=splits, - use_scheduler=use_scheduler, - out=result, - lse=lse, - ) - ops.attention.gate_sink( - result, gate[decode_rows:], lse.t(), sinks[decode_rows:], output[decode_rows:] - ) diff --git a/vllm_rlt/models/__init__.py b/vllm_rlt/models/__init__.py index e1e597ef..af4b8c00 100644 --- a/vllm_rlt/models/__init__.py +++ b/vllm_rlt/models/__init__.py @@ -11,7 +11,6 @@ from .config import ModelConfig, prepare_model from .dory import DoryConfig, DoryForCausalLM from .huginn import HuginnConfig, HuginnForCausalLM -from .inkling2mini import Inkling2Config, Inkling2ForCausalLM from .nanbeige import NanbeigeConfig, NanbeigeForCausalLM from .ouro import OuroConfig, OuroForCausalLM @@ -20,7 +19,6 @@ "nanbeige": NanbeigeForCausalLM, "huginn_raven": HuginnForCausalLM, "dory": DoryForCausalLM, - "inkling2_loop": Inkling2ForCausalLM, } @@ -228,8 +226,6 @@ def from_pretrained( "HuginnForCausalLM", "DoryConfig", "DoryForCausalLM", - "Inkling2Config", - "Inkling2ForCausalLM", "AutoModelForCausalLM", "resolve_local_model_path", "resolve_model_source", diff --git a/vllm_rlt/models/config.py b/vllm_rlt/models/config.py index 8a15eb07..7d416da0 100644 --- a/vllm_rlt/models/config.py +++ b/vllm_rlt/models/config.py @@ -7,7 +7,6 @@ from .dory import DoryConfig from .huginn import HuginnConfig -from .inkling2mini import Inkling2Config from .nanbeige import NanbeigeConfig from .ouro import OuroConfig @@ -16,7 +15,6 @@ "nanbeige": NanbeigeConfig, "huginn_raven": HuginnConfig, "dory": DoryConfig, - "inkling2_loop": Inkling2Config, } @@ -28,7 +26,7 @@ class ModelConfig: limits remain properties of the concrete config rather than duplicated fields. """ - model_specific_config: OuroConfig | NanbeigeConfig | HuginnConfig | DoryConfig | Inkling2Config + model_specific_config: OuroConfig | NanbeigeConfig | HuginnConfig | DoryConfig def __post_init__(self): if type(self.model_specific_config) not in _CONFIG_TYPES.values(): @@ -57,21 +55,6 @@ def total_ut_steps(self): def max_position_embeddings(self): return self.model_specific_config.max_position_embeddings - def with_max_loops(self, max_loops): - """Set the Inkling instance depth. Other models use max_loops per request.""" - config = self.model_specific_config - if max_loops is None or not isinstance(config, Inkling2Config): - return self - if type(max_loops) is not int or max_loops < 1: - raise ValueError("max_loops must be a positive integer") - if max_loops == config.total_ut_steps: - return self - if not config.is_varloop: - raise ValueError( - f"max_loops must match the Fixed Inkling depth ({config.total_ut_steps})" - ) - return ModelConfig(config.with_loop_num_passes(max_loops)) - def prepare_model(model, *, revision=None, model_config=None): """Resolve a source once, before spawning; preserve its weight-source semantics.""" diff --git a/vllm_rlt/models/inkling2mini.py b/vllm_rlt/models/inkling2mini.py deleted file mode 100644 index 100ce24f..00000000 --- a/vllm_rlt/models/inkling2mini.py +++ /dev/null @@ -1,577 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Inkling 2 Mini text backbone with scheduler-visible loop passes.""" - -import json -from contextlib import ExitStack -from dataclasses import dataclass, replace -from pathlib import Path - -import torch -from safetensors import safe_open -from torch import nn -from torch.nn import functional as F - -from vllm_rlt.kernels.inkling2mini import ( - KernelBatch, - QuantizedExperts, - attention_residual, - load_ops, - message_controller, - packed_attention_plans, - residual_stack, - rms_norm, -) - - -@dataclass(frozen=True) -class Inkling2Config: - num_hidden_layers: int - num_attention_heads: int - num_key_value_heads: int - head_dim: int - vocab_size: int - padded_vocab_size: int - max_position_embeddings: int - eos_token_id: int - width: int - core_start: int - core_end: int - checkpoint_passes: int - is_varloop: bool - local_layers: tuple[int, ...] - window: int - rel_extent: int - block_layers: int - experts_per_token: int - route_scale: float - gate_softcap: float - up_softcap: float - logit_softcap: float - rms_norm_eps: float - qk_clip: float - rel_clip: float - log_scale_floor: int - log_scale_alpha: float - loop_num_passes: int | None = None - - @property - def total_ut_steps(self): - return self.checkpoint_passes if self.loop_num_passes is None else self.loop_num_passes - - @property - def hidden_size(self): - # Completed and partial prelude blocks, the core's message bank and a pass flag. - return (self.core_end // self.block_layers + 1) * self.width + 1 - - @property - def auxiliary_cache_width(self): - # Raw projections for the four short convolutions on every layer visit. - per_head = 2 * (self.head_dim + self.width // self.num_key_value_heads) - return self.num_key_value_heads * (1 << (per_head - 1).bit_length()) - - def with_loop_num_passes(self, passes): - if not self.is_varloop: - raise ValueError("loop_num_passes requires an Inkling 2 Mini variable-loop checkpoint") - if type(passes) is not int or passes < 1: - raise ValueError("loop_num_passes must be a positive integer") - return replace(self, loop_num_passes=passes) - - @classmethod - def from_dict(cls, values): - text = values["text_config"] - loop = text["loop_config"] - if type(loop["is_varloop"]) is not bool: - raise ValueError("Inkling 2 Mini loop_config.is_varloop must be a boolean") - if text.get("loop_share_cache", False): - raise ValueError("Inkling 2 Mini currently requires per-pass KV and convolution state") - for dim in ("head_dim", "num_attention_heads", "num_key_value_heads"): - if text[dim] != text[f"swa_{dim}"]: - raise ValueError("Inkling 2 Mini requires matching local and global head shapes") - config = cls( - num_hidden_layers=text["num_hidden_layers"], - num_attention_heads=text["num_attention_heads"], - num_key_value_heads=text["num_key_value_heads"], - head_dim=text["head_dim"], - vocab_size=text["unpadded_vocab_size"], - padded_vocab_size=text["vocab_size"], - max_position_embeddings=text["model_max_length"], - eos_token_id=values["eos_token_id"], - width=text["hidden_size"], - core_start=loop["core_start"], - core_end=loop["core_end"], - checkpoint_passes=loop["num_passes"], - is_varloop=loop["is_varloop"], - local_layers=tuple(text["local_layer_ids"]), - window=text["sliding_window_size"], - rel_extent=text["rel_extent"], - block_layers=text["n_layers_per_attn_res_block"], - experts_per_token=text["num_experts_per_tok"], - route_scale=text["route_scale"], - gate_softcap=text["mlp_gate_softcap"], - up_softcap=text["mlp_up_softcap"], - logit_softcap=text["final_logit_softcapping"], - rms_norm_eps=text["rms_norm_eps"], - qk_clip=text["qk_l2_clip_threshold"], - rel_clip=text["rel_l2_clip_threshold"], - log_scale_floor=text["log_scaling_n_floor"], - log_scale_alpha=text["log_scaling_alpha"], - ) - if ( - not 0 < config.core_start < config.core_end < config.num_hidden_layers - or config.core_start % config.block_layers - or config.core_end % config.block_layers - or type(config.checkpoint_passes) is not int - or config.checkpoint_passes < (1 if config.is_varloop else 2) - ): - raise ValueError("invalid Inkling 2 Mini loop configuration") - passes = text.get("loop_num_passes") - return config if passes is None else config.with_loop_num_passes(passes) - - def to_dict(self): - # Runtime model-family checks use this field; the checkpoint retains its JSON schema. - return {"model_type": "inkling2_loop"} - - -class _OrderedCodaBatch: - """Share independent projections while ordering each history write.""" - - def __init__(self, target, draft, target_rows): - self.segments = ( - (target, slice(0, target_rows)), - (draft, slice(target_rows, None)), - ) - - def attend(self, layer, *projected): - # Both scopes use their own position, mask and page-table views. - return torch.cat( - [ - batch.attend( - layer, *(part[rows] if part is not None else None for part in projected) - ) - for batch, rows in self.segments - ] - ) - - def conv_mix( - self, - layer, - offset, - hidden, - weight, - out, - stack, - last, - queries, - norm, - *, - residual=None, - addend=None, - ): - output = [] - for batch, rows in self.segments: - output.append( - batch.conv_mix( - layer, - offset, - hidden[rows], - weight, - out[rows], - stack[:, rows], - last[rows] if last is not None else None, - queries, - norm, - residual=residual[rows] if residual is not None else None, - addend=addend[rows] if addend is not None else None, - ) - ) - return torch.cat(output, dim=1) - - -class _Layer(nn.Module): - def __init__(self, config, index, read): - super().__init__() - self.index = index - self.local = index in config.local_layers - self.boundary = index % config.block_layers == 0 - self.is_core = config.core_start <= index < config.core_end - self.ops = load_ops() - - def param(name): - return nn.Parameter(read(name), requires_grad=False) - - for name, key in ( - ("query", "wq_du.weight"), - ("key", "wk_dv.weight"), - ("value", "wv_dv.weight"), - ("relative", "wr_du.weight"), - ("rel_basis", "rel_logits_proj.proj"), - ("query_scale", "q_l2_clip.scale"), - ("rel_scale", "rel_l2_clip.scale"), - ("sink", "attn_sink_proj.weight"), - ("output", "wo_ud.weight"), - ("output_gate", "gate_attn.weight"), - ): - setattr(self, name, param(f"attn.{key}")) - for name, key in ( - ("conv_k", "attn.k_sconv"), - ("conv_v", "attn.v_sconv"), - ("conv_attn", "attn_sconv"), - ("conv_mlp", "mlp_sconv"), - ): - weight = ( - read(f"{key}.static_w") - if not self.local and name in ("conv_k", "conv_v") - else read(f"{key}.weight").squeeze(1) - ) - setattr(self, name, nn.Parameter(weight, requires_grad=False)) - self._pack_attention_weights() - if not self.local: - self.dynamic_k = param("attn.k_sconv.weight_proj") - self.dynamic_v = param("attn.v_sconv.weight_proj") - names = ("attn_norm",) if self.local else ("q_input_norm", "k_input_norm", "v_input_norm") - self.input_norms = nn.ParameterList(param(f"{name}.weight") for name in names) - self.mlp_norm = param("mlp_norm.weight") - self.register_buffer("attn_norm_rows", torch.stack(tuple(self.input_norms))) - self.mlp = QuantizedExperts(config, lambda name: read(f"mlp.{name}")) - if self.is_core: - streams = ("attn", "k", "v", "mlp") - self.controller_down = nn.Parameter( - torch.stack([read(f"controllers.{stream}.down_weight") for stream in streams]), - requires_grad=False, - ) - self.controller_up = nn.Parameter( - torch.stack( - [ - torch.cat( - [ - read(f"controllers.{stream}.{gate}_weight") - for gate in ("gain", "forget") - ] - ) - for stream in streams - ] - ), - requires_grad=False, - ) - - def _pack_attention_weights(self): - weights = (self.query, self.relative, self.output_gate, self.sink, self.key, self.value) - self.projection_sizes = tuple(weight.shape[0] for weight in weights) - joined = torch.cat(weights) - padding = -len(joined) % 8 - if padding: - joined = F.pad(joined, (0, 0, 0, padding)) - self.qkvr = nn.Parameter(joined, requires_grad=False) - self.register_buffer( - "shifted_rel_proj", self.ops.sconv.shift_rel_proj(self.rel_basis, self.local) - ) - del self.query, self.relative, self.output_gate, self.sink, self.key, self.value - - def _attention(self, inputs, batch): - line = self.ops.linear.linear - q_input, k_input, v_input = inputs - sizes = self.projection_sizes - if self.local: - packed = line(q_input, self.qkvr) - q, r, gate, sinks, k, v = packed[:, : sum(sizes)].split(sizes, dim=-1) - k_dynamic = v_dynamic = None - else: - q_side = sum(sizes[:4]) - k_end = q_side + sizes[4] - projected = line(q_input, self.qkvr[: q_side + (-q_side % 8)]) - q, r, gate, sinks = projected[:, :q_side].split(sizes[:4], dim=-1) - k = line(k_input, self.qkvr[q_side:k_end]) - v = line(v_input, self.qkvr[k_end : k_end + sizes[5]]) - k_dynamic = F.linear(k_input, self.dynamic_k) - v_dynamic = F.linear(v_input, self.dynamic_v) - return line(batch.attend(self, q, r, gate, sinks, k, v, k_dynamic, v_dynamic), self.output) - - -class Inkling2ForCausalLM(nn.Module): - requires_boundary_kv = True - supports_async_scheduling = True - # Keep the per-pass attention and convolution page mapping on the host. - supports_device_kv_metadata = False - supports_packed_recurrent_graphs = True - supports_packed_prefill_graphs = True - supports_recurrent_gate = False - supports_mixed_prefill = True - supports_wavefront_prefill = True - requires_ordered_pipeline_coda = True - supports_cuda_graphs = True - # A VarLoop checkpoint selects its pass count when the engine starts. - fixed_loop_count = True - interleaved_kv = True - state_dtype = torch.bfloat16 - batch_type = KernelBatch - - def __init__(self, config: Inkling2Config, read=None): - super().__init__() - if read is None: - raise ValueError("Inkling 2 Mini requires a checkpoint") - self.config = config - self.embed = nn.Parameter(read("embed.weight"), requires_grad=False) - self.embed_norm = nn.Parameter(read("embed_norm.weight"), requires_grad=False) - self.norm = nn.Parameter(read("norm.weight"), requires_grad=False) - self.head = nn.Parameter(read("unembed.weight"), requires_grad=False) - self.prelude_kv_layers = tuple(range(config.core_start)) - self.recurrent_kv_layers = tuple(range(config.core_start, config.core_end)) - self.coda_kv_layers = tuple(range(config.core_end, config.num_hidden_layers)) - self.layers = nn.ModuleList( - [ - _Layer(config, index, lambda name: read(f"layers.{index}.{name}")) - for index in range(config.num_hidden_layers) - ] - ) - factor = config.width**-0.5 - self.attn_queries = nn.ParameterList( - nn.Parameter( - ( - read(f"attn_res.attn_queries.{i - 1}").view(-1, config.width).float() * factor - ).contiguous(), - requires_grad=False, - ) - for i in range(1, config.num_hidden_layers) - ) - mlp_queries = torch.stack( - [ - read(f"attn_res.mlp_queries.{i}").view(1, config.width) - for i in range(config.num_hidden_layers) - ] - ) - self.register_buffer("mlp_queries", mlp_queries.float() * factor) - self.register_buffer( - "output_query", read("attn_res.output_query").view(1, -1).float() * factor - ) - main = read("middle_cycle_cross_pass_queries").view(-1, 2, config.width) - kv = read("middle_cycle_cross_pass_kv_queries").view_as(main) - self.message_queries = nn.Parameter( - torch.cat((main[:, :1], kv, main[:, 1:]), dim=1), requires_grad=False - ) - self.prelude_blocks = config.core_start // config.block_layers + 1 - - def _run_layers(self, blocks, indices, batch, bank=None, has_message=None, *, final=False): - cfg = self.config - size = (cfg.num_hidden_layers + cfg.block_layers - 1) // cfg.block_layers + 1 - stack = blocks.new_empty(size, len(blocks), cfg.width) - num_blocks = blocks.shape[1] - 1 - stack[: num_blocks + 1].copy_(residual_stack(blocks)) - ops = load_ops() - inputs = None - for index in indices: - layer = self.layers[index] - partial = stack[num_blocks] - messages = ( - None - if bank is None - else attention_residual( - bank, self.message_queries[index - cfg.core_start] - ).transpose(0, 1) - ) - if inputs is None: - if index == 0: - inputs = rms_norm(partial, layer.input_norms[0], cfg.rms_norm_eps)[None] - else: - inputs = ops.attn_res.attn_res( - stack[:num_blocks], - partial, - None, - self.attn_queries[index - 1], - layer.attn_norm_rows if messages is None else None, - cfg.rms_norm_eps, - True, - ) - if layer.local: - inputs = inputs.expand(3, -1, -1) - if messages is not None: - inputs = message_controller( - inputs, - messages[:3], - layer.controller_down[:3], - layer.controller_up[:3], - layer.attn_norm_rows.expand(3, -1), - cfg.rms_norm_eps, - has_message, - ) - attn = layer._attention(inputs, batch) - attn_out = torch.empty_like(partial) - mlp_norm = layer.mlp_norm[None] - mlp_in = batch.conv_mix( - index, - 2 * cfg.head_dim, - attn, - layer.conv_attn, - attn_out, - stack[: num_blocks + layer.boundary], - None if layer.boundary else partial, - self.mlp_queries[index], - mlp_norm if messages is None else None, - ) - if messages is not None: - mlp_in = message_controller( - mlp_in, - messages[3:], - layer.controller_down[3:], - layer.controller_up[3:], - mlp_norm, - cfg.rms_norm_eps, - has_message, - ) - mlp = layer.mlp(mlp_in[0]) - num_blocks += layer.boundary - if index + 1 < cfg.num_hidden_layers: - query = self.attn_queries[index] - next_norm = self.layers[index + 1].attn_norm_rows if bank is None else None - else: - query, next_norm = self.output_query, self.norm[None] - inputs = batch.conv_mix( - index, - 2 * cfg.head_dim + cfg.width // cfg.num_key_value_heads, - mlp, - layer.conv_mlp, - stack[num_blocks], - stack[:num_blocks], - None, - query, - next_norm, - residual=None if layer.boundary else partial, - addend=attn_out, - ) - return inputs[0] if final else stack[: num_blocks + 1].transpose(0, 1) - - def recurrent_graph_variant(self, batch): - rows = getattr(batch, "rows", None) - if rows is None: - # A device-owned pipeline selects the first-pass path from hidden state. - return "mixed" - first = {depth == 0 for _, depth, _ in rows} - if len(first) != 1: - return "mixed" - return "first" if True in first else "later" - - def packed_recurrent_graph_plan(self, batch): - return packed_attention_plans(batch, self.config) - - def prelude_prepared(self, tokens, metadata, cache, *, generators=None): - batch = self.batch_type(cache, metadata, self.config) - embed = F.embedding(tokens, self.embed) - initial = rms_norm(embed, self.embed_norm, self.config.rms_norm_eps) - initial = initial.to(self.state_dtype).unsqueeze(1) - blocks = self._run_layers(initial, self.prelude_kv_layers, batch) - tail = blocks.new_zeros( - (len(tokens), self.config.hidden_size - blocks.shape[1] * blocks.shape[2]) - ) - return torch.cat((blocks.flatten(1), tail), dim=-1) - - def recurrent_prepared(self, hidden, metadata, cache, *, compute_gate=True): - batch = self.batch_type(cache, metadata, self.config) - rows = len(batch.positions) - packed = hidden[:rows, :-1].unflatten(-1, (-1, self.config.width)) - prelude, bank = packed[:, : self.prelude_blocks], packed[:, self.prelude_blocks :] - has_message = hidden[:rows, -1].view(1, -1, 1).ne(0) - variant = ( - metadata.graph_variant - if hasattr(metadata, "graph_variant") - else self.recurrent_graph_variant(metadata) - ) - if variant == "first": - bank = None - elif variant == "later": - has_message = None - blocks = self._run_layers(prelude, self.recurrent_kv_layers, batch, bank, has_message) - # The first completed core entry repeats the retained prelude partial. - result = torch.cat( - ( - packed[:, : self.prelude_blocks].flatten(1), - blocks[:, self.prelude_blocks :].flatten(1), - hidden.new_ones((rows, 1)), - ), - dim=-1, - ) - if rows < len(hidden): - result = F.pad(result, (0, 0, 0, len(hidden) - rows)) - return result, None - - def recurrent(self, hidden, request_ids, depths, positions, cache, *, compute_gate=True): - return self.recurrent_prepared( - hidden, - cache._prepare_batch(request_ids, depths, positions), - cache, - compute_gate=compute_gate, - ) - - def _coda_inputs(self, hidden, metadata, cache): - batch = self.batch_type(cache, metadata, self.config) - blocks = hidden[: len(batch.positions), :-1].unflatten(-1, (-1, self.config.width)) - return batch, blocks - - def coda_hidden_prepared(self, hidden, metadata, cache): - """Update the boundary history and return the normalized LM head input.""" - batch, blocks = self._coda_inputs(hidden, metadata, cache) - return self._run_layers(blocks, self.coda_kv_layers, batch, final=True) - - def project_coda(self, state): - logits = F.linear(state, self.head)[..., : self.config.vocab_size] - cap = self.config.logit_softcap - return (logits / cap).tanh() * cap - - def coda_prepared(self, hidden, metadata, cache, *, compute_logits=True): - if compute_logits: - return self.project_coda(self.coda_hidden_prepared(hidden, metadata, cache)) - batch, blocks = self._coda_inputs(hidden, metadata, cache) - self._run_layers(blocks, self.coda_kv_layers, batch) - return None - - def coda_pair(self, target_hidden, target_metadata, draft_hidden, draft_metadata, cache): - target, target_blocks = self._coda_inputs(target_hidden, target_metadata, cache) - draft, draft_blocks = self._coda_inputs(draft_hidden, draft_metadata, cache) - # Order attention and convolution writes before the draft reads target history. - batch = _OrderedCodaBatch(target, draft, len(target_blocks)) - blocks = torch.cat((target_blocks, draft_blocks)) - state = self._run_layers(blocks, self.coda_kv_layers, batch, final=True) - return self.project_coda(state).argmax(-1).view(2, -1) - - @classmethod - def from_pretrained( - cls, path, *, revision=None, device="cpu", dtype=torch.bfloat16, config=None - ): - if torch.device(device).type != "cuda" or dtype != torch.bfloat16: - raise ValueError("Inkling 2 Mini currently requires CUDA and BF16 model dtype") - folder = Path(path).expanduser() - if not folder.is_dir(): - from . import resolve_model_config - - source, _, _ = resolve_model_config(path, revision=revision) - folder = Path(source) - if config is None: - config = Inkling2Config.from_dict(json.loads((folder / "config.json").read_text())) - if torch.cuda.get_device_capability(device)[0] != 10: - raise ValueError("Inkling 2 Mini requires SM10x for the vLLM operators") - load_ops() - index_path = folder / "model.safetensors.index.json" - if index_path.is_file(): - index = json.loads(index_path.read_text())["weight_map"] - names = sorted({file for key, file in index.items() if key.startswith("model.llm.")}) - else: - names = ["model.safetensors"] - if not names or any( - Path(name).name != name or not name.endswith(".safetensors") for name in names - ): - raise ValueError( - "Inkling 2 Mini requires local safetensors entries in its checkpoint index" - ) - with ExitStack() as stack: - weights = {} - for name in names: - shard = stack.enter_context(safe_open(folder / name, framework="pt", device="cpu")) - weights.update( - {name: shard for name in shard.keys() if name.startswith("model.llm.")} - ) - - def read(name): - key = f"model.llm.{name}" - if key not in weights: - raise ValueError(f"Inkling 2 Mini checkpoint is missing {key}") - return weights[key].get_tensor(key).to(device) - - return cls(config, read).eval() diff --git a/vllm_rlt/worker/async_speculative.py b/vllm_rlt/worker/async_speculative.py index c08e38c9..8b18dfa2 100644 --- a/vllm_rlt/worker/async_speculative.py +++ b/vllm_rlt/worker/async_speculative.py @@ -15,26 +15,16 @@ import numpy as np import torch -from vllm_rlt.config import cuda_graph_rows from vllm_rlt.core.kv_cache_manager import _Allocation from vllm_rlt.core.scheduler import SchedulerOutput from vllm_rlt.request import Operation, Request from vllm_rlt.worker.cuda_graph import ( CodaGraphs, - CodaPairGraphs, DeviceRecurrentGraphs, - PreludeGraphs, - graph_capture_sizes, speculative_capture_sizes, ) from vllm_rlt.worker.executor import ForwardBatch from vllm_rlt.worker.output import ModelRunnerOutput, SpeculativeResult -from vllm_rlt.worker.pipeline_graph import ( - PipelineRoundGraph, - PipelineTransitionGraphs, - pipeline_transition, - publish_pipeline, -) from vllm_rlt.worker.sampler import RngRegistry from vllm_rlt.worker.speculative import ( PipelineState, @@ -48,7 +38,6 @@ categorical, speculative_accept, ) -from vllm_rlt.worker.tensors import copy_tensor, pinned_tensor # Float plan arrays travel in the int64 upload as float64 bit patterns. _FLOAT_UPLOADS = frozenset({"r_temperature", "r_top_p", "v_temperature", "v_top_p"}) @@ -235,22 +224,12 @@ class SpeculativeRequestState: class SpeculativeRoundBuffer: - def __init__(self, runner, scheduler, *, pipeline_capacity=0): + def __init__(self, runner, scheduler): cache = runner.cache width = math.ceil(runner.model.config.max_position_embeddings / cache.block_size) shape = (scheduler.max_num_seqs, cache.max_loops, width) - self.host_tables = pinned_tensor((math.prod(shape),), torch.int32, cache.device) - self.table_versions = () - self.table_shape = () - self.tables_dirty = False + self.host_tables = torch.empty(math.prod(shape), dtype=torch.int32, pin_memory=True) self.tables = torch.empty(math.prod(shape), dtype=torch.int32, device=cache.device) - self.plan_key = None - self.plan = None - if pipeline_capacity: - size = ((3 + 2 * pipeline_capacity) * scheduler.max_num_seqs,) - self.host_plan = pinned_tensor(size, torch.int64, cache.device) - self.device_plan = torch.empty(size, dtype=torch.int64, device=cache.device) - self.inputs_ready = None # Result capacity in int64 elements (not bytes), for one submission. # Block layout: [result token IDs for all verification rows, # accepted counts per request, next positions per request, @@ -378,7 +357,7 @@ def __init__( model, cache, config, - replace(execution, cuda_graphs=False, cuda_graph_warmup=False), + replace(execution, cuda_graphs=False), rng=rng, runtime=runtime, compute_stream=compute_stream, @@ -391,63 +370,16 @@ def __init__( ) self.coda_graphs = ( CodaGraphs(model, execution, bucketed=True, capture_sizes=sizes) - if execution.cuda_graphs and not self.ordered_pipeline_coda + if execution.cuda_graphs else None ) - self.coda_pair_graphs = None - if execution.cuda_graphs and self.ordered_pipeline_coda: - sizes = graph_capture_sizes(execution, preferred=(scheduler.max_num_seqs,)) - self.prelude_graphs = PreludeGraphs( - model, execution, cache, bucketed=True, capture_sizes=sizes - ) - self.coda_pair_graphs = CodaPairGraphs(model, cache, sizes) - self.prelude_graphs.prepare() - self.coda_pair_graphs.prepare() if self.graphs is not None: self.graphs.prepare() - if self.coda_graphs is not None: self.coda_graphs.prepare() self.compute_stream = compute_stream self.copy_stream = copy_stream - self.input_stream = ( - torch.cuda.Stream(device=self.device) if execution.multi_stream else compute_stream - ) - self.use_uva = execution.use_uva - self.pipeline_capacity = ( - min(config.num_speculative_tokens + 1, config.target_loops // config.draft_loops) - if config.mode == "pipeline" - else 0 - ) - self.pipeline_lanes = torch.arange(self.pipeline_capacity, device=self.device) - self.transition_graph = self.round_graph = None - if config.pipeline_graph != "off": - request_capacity = min( - scheduler.max_num_seqs, - scheduler.max_num_batched_tokens, - cuda_graph_rows(execution), - ) - request_sizes = graph_capture_sizes(execution, preferred=(request_capacity,)) - self.transition_graph = PipelineTransitionGraphs( - self.device, request_sizes, self.pipeline_capacity, config - ) - if config.pipeline_graph == "full": - dense_requests = min( - request_capacity, - scheduler.max_num_batched_tokens // self.pipeline_capacity, - cuda_graph_rows(execution) // self.pipeline_capacity, - ) - if dense_requests: - self.round_graph = PipelineRoundGraph( - model, cache, dense_requests, self.pipeline_capacity, config - ) self.compute_stream.wait_stream(torch.cuda.current_stream(self.device)) - self.buffers = [ - SpeculativeRoundBuffer(self, scheduler, pipeline_capacity=self.pipeline_capacity) - for _ in range(2) - ] - if self.input_stream is not self.compute_stream: - for buffer in self.buffers: - buffer.inputs_ready = torch.cuda.Event() + self.buffers = [SpeculativeRoundBuffer(self, scheduler) for _ in range(2)] self.states: dict[str, SpeculativeRequestState] = {} # Device (input token, next position) per live request. A round gathers # and scatters these rows in one operation each instead of per request. @@ -483,14 +415,17 @@ def _state(self, request, buffer): request, allocation, self.slot_values[slot, 0], self.slot_values[slot, 1], slot=slot ) if self.config.mode == "pipeline": - width = self.pipeline_capacity + width = min( + self.config.num_speculative_tokens + 1, + self.config.target_loops // self.config.draft_loops, + ) parameter = next(self.model.parameters()) state.pipeline = DevicePipelineState( state.token.expand(width).clone(), torch.zeros(width, dtype=torch.long, device=self.device), torch.zeros( (width, self.model.config.hidden_size), - dtype=getattr(self.model, "state_dtype", parameter.dtype), + dtype=parameter.dtype, device=self.device, ), torch.zeros(width, dtype=torch.long, device=self.device), @@ -511,9 +446,13 @@ def _grow_slots(self): for state in self.states.values(): state.token, state.position = new[state.slot, 0], new[state.slot, 1] - def _device_kv(self, positions, table, allocations, active): + def _execute_recurrent_step(self, hidden, positions, tables, depth, allocations, active=None): + if isinstance(depth, torch.Tensor): + table = tables.gather(1, depth[:, None, None].expand(-1, 1, tables.shape[2])).squeeze(1) + else: + table = tables[:, depth].contiguous() blocks = table.gather(1, (positions // self.cache.block_size)[:, None]).squeeze(1) - return self.metadata.prepare_device( + metadata = self.metadata.prepare_device( allocations=allocations, position_ids=positions, write_blocks=blocks.long(), @@ -524,28 +463,6 @@ def _device_kv(self, positions, table, allocations, active): ).int(), write_mask=active, ) - - def _execute_recurrent_step( - self, hidden, positions, tables, depth, allocations, active=None, *, prompt=None - ): - if isinstance(depth, torch.Tensor): - table = tables.gather(1, depth[:, None, None].expand(-1, 1, tables.shape[2])).squeeze(1) - else: - table = tables[:, depth].contiguous() - metadata = self._device_kv(positions, table, allocations, active) - if prompt is not None: - runner, prepared = prompt - prompt_forward = prepared.forwards[0].forward - decode_rows = len(hidden) - metadata = self.metadata.join_recurrent(metadata, prompt_forward.metadata[0]) - forward = ForwardBatch( - Operation.RECURRENT, - hidden=torch.cat((hidden, prompt_forward.hidden)), - metadata=(metadata,), - ) - result = self.runtime.forward(forward).hidden - runner.finish_mixed_recurrent(prepared, result[decode_rows:]) - return result[:decode_rows] forward = ForwardBatch( Operation.RECURRENT, hidden=hidden, metadata=(metadata,), graphs=self.graphs ) @@ -568,64 +485,29 @@ def _prepare_round(self, batch): ) for scheduled_request in scheduled_requests ) - width, versions = 0, [] + page_counts = [] for scheduled_request, (_, allocation) in zip(scheduled_requests, allocations): upper = scheduled_request.token_start + scheduled_request.token_count if upper > allocation.max_tokens or upper <= 0: raise ValueError("speculative round exceeds reserved context") pages = math.ceil(upper / self.cache.block_size) - version = allocation.block_tables - if any(len(table) < pages for table in version): + if any(len(table) < pages for table in allocation.block_tables): raise ValueError("speculative round has unallocated KV pages") - width = max(width, pages) - versions.append(version) + page_counts.append(pages) # A prefix of flat reusable storage provides contiguous active views even # as request count/page width change. The previous copy must be retired. - shape = (len(scheduled_requests), self.cache.max_loops, width) + shape = (len(scheduled_requests), self.cache.max_loops, max(page_counts)) size = math.prod(shape) host_tables = buffer.host_tables[:size].view(shape) tables = buffer.tables[:size].view(shape) - buffer.tables_dirty = buffer.table_shape != shape or any( - old is not new for old, new in zip(buffer.table_versions, versions, strict=True) - ) - if buffer.tables_dirty: - table_view = host_tables.numpy() - table_view.fill(0) - # Upload allocated pages through this batch's width. Device context - # lengths still limit each row. Advancing within these pages is free. - for i, version in enumerate(versions): - for depth, table in enumerate(version): - pages = min(width, len(table)) - table_view[i, depth, :pages] = table[:pages] - # Retain immutable tuples for identity checks, including across KV growth. - buffer.table_versions = tuple(versions) - buffer.table_shape = shape + table_view = host_tables.numpy() + table_view.fill(0) + for i, ((_, allocation), pages) in enumerate(zip(allocations, page_counts)): + for depth, table in enumerate(allocation.block_tables): + table_view[i, depth, :pages] = table[:pages] buffer.leased = True return buffer, allocations, host_tables, tables - def _stage_pipeline_plan(self, spans, buffer): - capacity = self.pipeline_capacity - widths = tuple(min(span.token_count, capacity) for span in spans) - limits = tuple( - len(span.request.prompt_token_ids) + span.request.sampling_params.max_tokens - 1 - for span in spans - ) - key = (widths, limits) - if key == buffer.plan_key: - return False - roots, rows, owners = [], [], [] - for index, width in enumerate(widths): - roots.append(len(rows)) - rows.extend(range(index * capacity, index * capacity + width)) - owners.extend([index] * width) - n, num_rows = len(widths), len(rows) - size = 3 * n + 2 * num_rows - host = buffer.host_plan[:size] - host.numpy()[:] = (*widths, *limits, *roots, *rows, *owners) - buffer.plan = buffer.device_plan[:size].split((n, n, n, num_rows, num_rows)) - buffer.plan_key = key - return True - def _round_plan(self, items, states, buffer): """Host-built gather/scatter indices for a round, uploaded in one copy. @@ -888,33 +770,14 @@ def _accept_and_update_state( return count @torch.inference_mode() - def submit(self, batch, *, prompt=None): + def submit(self, batch): # 1. Reserve a slot and prepare only the active CPU page tables. buffer, allocations, host_tables, tables = self._prepare_round(batch) scheduled_requests = batch.requests - plan_dirty = self.config.mode == "pipeline" and self._stage_pipeline_plan( - scheduled_requests, buffer - ) - upload = buffer.tables_dirty or plan_dirty - if upload: - # The ticket keeps this bank immutable through readback. Upload can - # overlap earlier compute and uses neither the compute nor D2H stream. - with torch.cuda.stream(self.input_stream): - if buffer.tables_dirty: - copy_tensor(host_tables, tables, use_uva=self.use_uva) - if plan_dirty: - size = sum(t.numel() for t in buffer.plan) - copy_tensor( - buffer.host_plan[:size], buffer.device_plan[:size], use_uva=self.use_uva - ) - if buffer.inputs_ready is not None: - buffer.inputs_ready.record(self.input_stream) # A partial submission may not record events. The engine drains both # owned streams before releasing allocations or recycling the slot. # 2. Submit computation; device state joins successive rounds. with torch.cuda.stream(self.compute_stream): - if upload and buffer.inputs_ready is not None: - self.compute_stream.wait_event(buffer.inputs_ready) states = tuple( self._state(scheduled_request.request, buffer) for scheduled_request in scheduled_requests @@ -922,14 +785,10 @@ def submit(self, batch, *, prompt=None): rounds = tuple(s.submitted for s in states) if any(s.submitted > s.delivered for s in states): self.submitted_before_collect += 1 + tables.copy_(host_tables, non_blocking=True) error_flags = False if self.config.mode == "pipeline": - args = (scheduled_requests, states, tables, allocations, buffer) - count = ( - self._pipeline_step(*args) - if prompt is None - else self._pipeline_step(*args, prompt=prompt) - ) + count = self._pipeline_step(scheduled_requests, states, tables, allocations, buffer) else: plan = self._round_plan(scheduled_requests, states, buffer) u = None if plan.random is None else self._uniforms(scheduled_requests, plan.random) @@ -969,111 +828,89 @@ def submit(self, batch, *, prompt=None): error_flags=error_flags, ) - def _pipeline_step(self, spans, states, tables, allocations, buffer, *, prompt=None): - graph = self.round_graph - if graph is not None and prompt is None and graph.supports(buffer.plan_key[0], tables): - graph.forward(states, tables, buffer) - for state in states: - state.submitted += 1 - return len(buffer.plan[3]) - - pipelines = [state.pipeline for state in states] - pipeline = DevicePipelineState( - torch.stack([state.tokens for state in pipelines]), - torch.stack([state.depths for state in pipelines]), - torch.stack([state.hidden for state in pipelines]), - torch.stack([state.candidates for state in pipelines]), - torch.stack([state.active for state in pipelines]), + def _pipeline_step(self, spans, states, tables, allocations, buffer): + widths = [ + min(span.token_count, len(state.pipeline.tokens)) for span, state in zip(spans, states) + ] + active = torch.cat([state.pipeline.active[:w] for state, w in zip(states, widths)]) + depths = torch.cat([state.pipeline.depths[:w] for state, w in zip(states, widths)]) + positions = torch.cat( + [ + state.position + torch.arange(w, device=self.device) + for state, w in zip(states, widths) + ] ) - num_requests = len(states) - widths, output_limits, roots, rows, owners = buffer.plan - num_rows = len(rows) - lanes = self.pipeline_lanes - valid = pipeline.active & (lanes < widths[:, None]) - lengths = valid.sum(1) - active = valid.flatten()[rows] - depths = pipeline.depths.flatten()[rows] - positions = torch.stack([state.position for state in states]) - row_positions = (positions[:, None] + lanes).flatten()[rows] # Padding never reads beyond the reserved context or writes live KV. - row_positions = torch.where(active, row_positions, 0) - tokens = pipeline.tokens.flatten()[rows] - retained = pipeline.hidden.flatten(0, 1)[rows] - if self.ordered_pipeline_coda: - tails = roots + (lengths - 1).clamp_min(0) - boundary_tables = tables[:, 0].contiguous() - draft_rows = active[tails] & (depths[tails] == 0) - prelude = self._prelude( - tokens[tails], - self._device_kv(row_positions[tails], boundary_tables, allocations, draft_rows), - ) - hidden = retained - hidden[tails] = torch.where(draft_rows[:, None], prelude, retained[tails]) - else: - prelude = self._prelude(tokens) - hidden = torch.where((depths == 0)[:, None], prelude, retained) - row_tables = tables[owners] + positions = torch.where(active, positions, 0) + tokens = torch.cat([state.pipeline.tokens[:w] for state, w in zip(states, widths)]) + retained = torch.cat([state.pipeline.hidden[:w] for state, w in zip(states, widths)]) + prelude = self.runtime.forward(ForwardBatch(Operation.PRELUDE, tokens=tokens)).hidden + hidden = torch.where((depths == 0)[:, None], prelude, retained) + row_tables = torch.cat([tables[i : i + 1].expand(w, -1, -1) for i, w in enumerate(widths)]) for offset in range(self.config.draft_loops): depth = torch.where(active, depths + offset, 0) hidden = self._execute_recurrent_step( - hidden, row_positions, row_tables, depth, allocations, active, prompt=prompt + hidden, positions, row_tables, depth, allocations, active ) - if self.ordered_pipeline_coda: - target_rows = active[roots] & ( - depths[roots] + self.config.draft_loops == self.config.target_loops - ) - # Write verified Coda history before the draft reads any earlier position. - target_kv = self._device_kv( - row_positions[roots], boundary_tables, allocations, target_rows - ) - draft_kv = self._device_kv( - row_positions[tails], boundary_tables, allocations, draft_rows - ) - if self.coda_pair_graphs is None: - target, draft = self.model.coda_pair( - hidden[roots], target_kv, hidden[tails], draft_kv, self.cache - ) - else: - target, draft = self.coda_pair_graphs.forward( - hidden[roots], target_kv, hidden[tails], draft_kv + choices = self._coda(hidden).argmax(-1) + start = 0 + for i, (span, state, w) in enumerate(zip(spans, states, widths)): + p = state.pipeline + ids = torch.arange(len(p.tokens), device=self.device) + # Budget reductions discard speculative descendants, never the root. + valid = p.active & (ids < w) + new_depths = p.depths + valid.long() * self.config.draft_loops + predictions = torch.zeros_like(p.tokens) + predictions[:w].copy_(choices[start : start + w]) + next_hidden = p.hidden.clone() + next_hidden[:w].copy_(hidden[start : start + w]) + drafted = valid & (new_depths == self.config.draft_loops) + candidates = torch.where(drafted, predictions, p.candidates) + emitted = valid[0] & (new_depths[0] == self.config.target_loops) + accepted = emitted & (candidates[0] == predictions[0]) + reject = emitted & ~accepted + state.token.copy_(torch.where(emitted, predictions[0], state.token)) + state.position.add_(emitted.long()) + # Shift only on target completion. All decisions remain stream-ordered tensors. + source = (ids + emitted.long()).clamp_max(len(ids) - 1) + remaining = valid.long().sum() - emitted.long() + surviving = (ids < remaining) & ~reject + p.tokens.copy_(p.tokens.gather(0, source)) + p.depths.copy_(new_depths.gather(0, source)) + p.hidden.copy_(next_hidden[source]) + p.candidates.copy_(candidates.gather(0, source)) + tail = (valid.long().sum() - 1).clamp_min(0) + append = drafted.gather(0, tail.reshape(1)).squeeze(0) & ~reject + newborn = (ids == remaining) & append + # A rejection (or a one-row budget) restarts from the corrected root. + restart = reject | (emitted & (remaining == 0)) + newborn = torch.where(restart, ids == 0, newborn) + limit = len(span.request.prompt_token_ids) + span.request.sampling_params.max_tokens - 1 + newborn &= (ids < w) & (state.position + ids < limit) + candidate = candidates.gather(0, tail.reshape(1)).squeeze(0) + token = torch.where(restart, state.token, candidate) + p.tokens.copy_(torch.where(newborn, token, p.tokens)) + p.depths.masked_fill_(newborn, 0) + p.active.copy_((surviving | newborn) & (state.position + ids < limit)) + # Per-request wire order matches SpeculativeRoundTicket.collect(): + # prediction, accepted, emitted, next_position, drafted, verified. + # A pipeline step verifies at most one token per request, so the + # verified count equals emitted (0 or 1). + buffer.result[6 * i : 6 * i + 6].copy_( + torch.stack( + ( + predictions[0], + accepted.long(), + emitted.long(), + state.position, + drafted.long().sum(), + emitted.long(), + ) ) - choices = torch.zeros_like(tokens) - choices[roots] = target - choices[tails] = torch.where(draft_rows, draft, choices[tails]) - else: - choices = self._coda(hidden).argmax(-1) - predictions = torch.zeros_like(pipeline.tokens) - predictions.flatten().index_copy_(0, rows, choices) - pipeline.hidden.flatten(0, 1).index_copy_(0, rows, hidden) - input_tokens = torch.stack([state.token for state in states]) - transition = self.transition_graph - if transition is not None and num_requests in transition.entries: - update = transition.forward( - pipeline, predictions, valid, widths, positions, output_limits, input_tokens - ) - else: - update = pipeline_transition( - pipeline.tokens, - pipeline.depths, - pipeline.candidates, - predictions, - valid, - widths, - positions, - output_limits, - input_tokens, - lanes, - lengths, - self.config.draft_loops, - self.config.target_loops, ) - shifted_hidden = pipeline.hidden.gather( - 1, update.source[:, :, None].expand(-1, -1, pipeline.hidden.shape[2]) - ) - publish_pipeline(states, shifted_hidden, update, buffer) - for state in states: state.submitted += 1 - return num_rows + start += w + return start def snapshot_pipeline(self, request, device): state = self.states.get(request.request_id) @@ -1177,11 +1014,7 @@ def discard_buffers(self): for buffer in self.buffers: buffer.keepalive.clear() buffer.leased = False - buffer.table_shape = () - buffer.plan_key = None def synchronize(self): - if self.input_stream is not self.compute_stream: - self.input_stream.synchronize() self.compute_stream.synchronize() self.copy_stream.synchronize() diff --git a/vllm_rlt/worker/buffers.py b/vllm_rlt/worker/buffers.py index 64775891..621e1715 100644 --- a/vllm_rlt/worker/buffers.py +++ b/vllm_rlt/worker/buffers.py @@ -5,7 +5,7 @@ import torch -from vllm_rlt.worker.metadata import KVLayout, KVMetadata, PackedKVRange +from vllm_rlt.worker.metadata import KVLayout, KVMetadata from vllm_rlt.worker.submission_queue import MAX_CONCURRENT_SUBMISSIONS, SubmissionQueue from vllm_rlt.worker.tensors import UvaBackedTensor, copy_tensor, use_uva_on @@ -26,14 +26,7 @@ def prefill_stage_rows(config, scheduler, *, staged_prefill=None) -> int: def execution_buffer_bytes( - config, - scheduler, - cache, - execution, - element_size, - *, - staged_prefill=None, - device_kv_metadata=True, + config, scheduler, cache, execution, element_size, *, staged_prefill=None ): rows = scheduler.max_num_batched_tokens if execution.pad_to_power_of_two: @@ -44,7 +37,7 @@ def execution_buffer_bytes( if execution.static_buffers: # Existing prefill/eager workspaces remain separate from async buffer sets. total += 4 * rows * (hidden + 4 * width + 36) - if execution.async_scheduling and device_kv_metadata: + if execution.async_scheduling: planes = config.total_ut_steps if cache.layout == "last_exited" else 1 # Four routing buffer sets, including capacity for an H2D descriptor fallback. total += 4 * rows * (hidden + 4 * width + 68) @@ -203,7 +196,6 @@ def stage_metadata(layouts, stage, *, padded_rows=None): else None ), max_seqlen_q=attention.max_seqlen_q, - packed_ranges=layout.packed_ranges, ) ) return tuple(batches) @@ -218,7 +210,6 @@ class PackedLayout: """ rows: tuple - packed_ranges: tuple[PackedKVRange, ...] | None writable: bool sequence_start: int lengths_start: int @@ -274,7 +265,6 @@ def store(self, metadata, tokens=()): layouts.append( PackedLayout( rows=item.rows, - packed_ranges=item.packed_ranges, writable=item.writable, sequence_start=sequence_start, lengths_start=lengths_start, @@ -357,7 +347,6 @@ def upload(self): layout.cumulative_start : layout.cumulative_start + q + 1 ], max_seqlen_q=layout.max_query, - packed_ranges=layout.packed_ranges, ) ) return self.targets[torch.int64][: self.token_count], tuple(metadata) diff --git a/vllm_rlt/worker/cuda_graph.py b/vllm_rlt/worker/cuda_graph.py index 69cbdf27..d3cd05c0 100644 --- a/vllm_rlt/worker/cuda_graph.py +++ b/vllm_rlt/worker/cuda_graph.py @@ -19,20 +19,6 @@ def _query_count(batch): return len(batch.position_ids) if isinstance(batch, DeviceKVMetadata) else len(batch.rows) -def _empty_device_batch(cache): - """Capture with zero live rows and keep all KV writes masked.""" - device = cache.device - positions = torch.empty(0, device=device, dtype=torch.long) - return DeviceKVMetadata( - allocations=(), - position_ids=positions, - write_blocks=positions, - write_offsets=positions, - context_lengths=torch.empty(0, device=device, dtype=torch.int32), - block_tables=torch.empty((0, 1), device=device, dtype=torch.int32), - ) - - def graph_capture_sizes(execution, preferred=()): """Prefer full-batch shapes, then spend remaining entries on smaller rows. @@ -65,11 +51,7 @@ def _bucket_size(sizes, count): def _cache_full(owner, key): - if key in owner.entries: - return False - if not getattr(owner, "allow_capture", True): - return True - full = len(owner.entries) >= owner.execution.cuda_graph_max_graphs + full = key not in owner.entries and len(owner.entries) >= owner.execution.cuda_graph_max_graphs if full and not owner.warned_cache_full: logger.warning( "%s cache is full (%d shapes); unseen shapes will run eager. " @@ -97,8 +79,7 @@ def _capture(hidden, stream, pool, run, *, startup=False): run() stream.synchronize() # Preserve main's cleanup of old engine cycles before entering capture. - if not startup or gc.isenabled(): - gc.collect() + gc.collect() graph = torch.cuda.CUDAGraph() # Collecting an unreachable old CUDAGraph here calls cudaGraphExecDestroy, # which is forbidden during capture and invalidates the new graph. @@ -123,18 +104,10 @@ class _DeviceCache: def __init__(self, cache): self.cache = cache - self.block_size = cache.key_cache.shape[2] - self.key_cache = cache.key_cache - self.value_cache = cache.value_cache - self.auxiliary_cache = getattr(cache, "auxiliary_cache", None) - - def record_external_kv(self, layer, batch): - # The graph owners advance host coverage after replay. - pass def _write_prepared(self, layer, batch, k, v): cache = self.cache - if getattr(cache, "key_scale", None) is not None: + if cache.key_scale is not None: # FP8 pools: one fused quantizing writer that honors the same row masks. cache._store_layer( layer, @@ -196,27 +169,11 @@ def _attend_prepared(self, layer, batch, q, *, window=None): def _graph_entry( - hidden, - batch, - cache, - max_position_embeddings, - *, - count=None, - packed=None, - bucketed=False, - table_count=None, - masked=False, - block_tables=None, + hidden, batch, cache, max_position_embeddings, *, count=None, packed=None, bucketed=False ): count = _query_count(batch) if count is None else count packed = batch.cu_seqlens_q is not None if packed is None else packed - tables = ( - table_count - if table_count is not None - else count - if bucketed - else len(batch.context_lengths) - ) + tables = count if bucketed else len(batch.context_lengths) width = math.ceil(max_position_embeddings / cache.block_size) return SimpleNamespace( hidden=hidden.new_empty((count, *hidden.shape[1:])), @@ -227,11 +184,7 @@ def _graph_entry( position_ids=torch.empty(count, device=cache.device, dtype=torch.long), write_blocks=torch.empty(count, device=cache.device, dtype=torch.long), write_offsets=torch.empty(count, device=cache.device, dtype=torch.long), - block_tables=( - torch.zeros((tables, width), device=cache.device, dtype=torch.int32) - if block_tables is None - else block_tables - ), + block_tables=torch.zeros((tables, width), device=cache.device, dtype=torch.int32), context_lengths=torch.empty(tables, device=cache.device, dtype=torch.int32), cu_seqlens_q=( torch.empty(tables + 1, device=cache.device, dtype=torch.int32) if packed else None @@ -239,14 +192,14 @@ def _graph_entry( max_seqlen_q=batch.max_seqlen_q if packed else 1, write_mask=( torch.empty(count, device=cache.device, dtype=torch.bool) - if bucketed or masked or getattr(batch, "write_mask", None) is not None + if bucketed or getattr(batch, "write_mask", None) is not None else None ), ), ) -def _copy_graph_inputs(entry, hidden, batch, *, count=None, copy_tables=True): +def _copy_graph_inputs(entry, hidden, batch, *, count=None): count = _query_count(batch) if count is None else count metadata = entry.metadata if metadata.active_rows is not None: @@ -257,7 +210,7 @@ def _copy_graph_inputs(entry, hidden, batch, *, count=None, copy_tables=True): metadata.write_offsets[count:].zero_() # Padding has zero context, so attention never reads its (stale) table # rows, and active rows read only pages they cover; no table reset. - metadata.context_lengths[len(batch.context_lengths) :].zero_() + metadata.context_lengths[count:].zero_() entry.hidden[:count].copy_(hidden[:count]) metadata.position_ids[:count].copy_(batch.position_ids[:count]) metadata.write_blocks[:count].copy_(batch.write_blocks[:count]) @@ -271,12 +224,8 @@ def _copy_graph_inputs(entry, hidden, batch, *, count=None, copy_tables=True): tables = len(batch.context_lengths) metadata.context_lengths[:tables].copy_(batch.context_lengths) if metadata.cu_seqlens_q is not None: - metadata.cu_seqlens_q[: tables + 1].copy_(batch.cu_seqlens_q) - if len(metadata.cu_seqlens_q) > tables + 1: - # searchsorted over a fixed capacity still maps the actual query rows. - metadata.cu_seqlens_q[tables + 1 :].fill_(count) - if copy_tables: - metadata.block_tables[:tables, : batch.block_tables.shape[1]].copy_(batch.block_tables) + metadata.cu_seqlens_q.copy_(batch.cu_seqlens_q) + metadata.block_tables[:tables, : batch.block_tables.shape[1]].copy_(batch.block_tables) @dataclass @@ -309,34 +258,29 @@ def select(self, hidden, batch): context_lengths=batch.context_lengths[:count], block_tables=batch.block_tables[:count], ) - if not count or count > cuda_graph_rows(self.execution): - self.fallbacks += 1 - return PreparedGraph(batch) - frontier = {} - ranges = getattr(batch, "packed_ranges", None) - host_rows = () if ranges is not None or isinstance(batch, DeviceKVMetadata) else batch.rows - for allocation, depth, pos in host_rows: - row_key = (id(allocation), depth) - previous = frontier.get(row_key) - if previous is not None and pos != previous + 1: - self.fallbacks += 1 - return PreparedGraph(batch) - frontier[row_key] = pos - variant_of = getattr(self.model, "recurrent_graph_variant", None) - variant = variant_of(batch) if variant_of is not None else None - # A plan can freeze launch dimensions and tensor slices selected from host layout. - plan_for = getattr(self.model, "packed_recurrent_graph_plan", None) - plan = plan_for(batch) if packed and plan_for is not None else None key = ( count, len(batch.context_lengths), batch.max_seqlen_q if packed else 1, packed, getattr(batch, "write_mask", None) is not None, - variant, - plan, ) - if _cache_full(self, key): + frontier = {} + contiguous = True + host_rows = () if isinstance(batch, DeviceKVMetadata) else batch.rows + for allocation, depth, pos in host_rows: + row_key = (id(allocation), depth) + previous = frontier.get(row_key) + if previous is not None and pos != previous + 1: + contiguous = False + break + frontier[row_key] = pos + if ( + not count + or count > cuda_graph_rows(self.execution) + or not contiguous + or _cache_full(self, key) + ): self.fallbacks += 1 return PreparedGraph(batch) entry = self.entries.get(key) @@ -344,14 +288,12 @@ def select(self, hidden, batch): entry = _graph_entry( hidden, batch, self.cache, self.model.config.max_position_embeddings ) - entry.metadata.graph_variant = variant - entry.metadata.packed_attention_plan = plan entry.graph = None self.entries[key] = entry return PreparedGraph(batch, entry) @torch.inference_mode() - def prepare_inputs(self, call, hidden, *, startup=False): + def prepare_inputs(self, call, hidden): batch, entry = call.metadata, call.entry if entry is not None: cache = self.cache @@ -361,11 +303,7 @@ def prepare_inputs(self, call, hidden, *, startup=False): seen = set() # Device-owned progress is ordered by the runner's stream. The CPU # written frontier intentionally lags in-flight speculative rounds. - ranges = getattr(batch, "packed_ranges", None) - if ranges is not None: - host_rows = ((seq.allocation, seq.depth, seq.start) for seq in ranges) - else: - host_rows = () if isinstance(batch, DeviceKVMetadata) else batch.rows + host_rows = () if isinstance(batch, DeviceKVMetadata) else batch.rows for allocation, depth, pos in host_rows: key = (id(allocation), depth) if key not in seen: @@ -385,7 +323,6 @@ def prepare_inputs(self, call, hidden, *, startup=False): lambda: self.model.recurrent_prepared( entry.hidden, entry.metadata, proxy, compute_gate=self.compute_gate ), - startup=startup, ) self.captures += 1 call.inputs_ready = True @@ -406,14 +343,10 @@ def execute(self, call, hidden): ) self.last_event = torch.cuda.Event() self.last_event.record(torch.cuda.current_stream(self.cache.device)) - if getattr(batch, "packed_ranges", None) is not None: + host_rows = () if isinstance(batch, DeviceKVMetadata) else batch.rows + for allocation, depth, pos in host_rows: for layer in self.cache.recurrent_layers: - self.cache._mark_prepared_write(layer, batch, None) - else: - host_rows = () if isinstance(batch, DeviceKVMetadata) else batch.rows - for allocation, depth, pos in host_rows: - for layer in self.cache.recurrent_layers: - allocation.written[self.cache._plane(depth)][layer].add(pos) + allocation.written[self.cache._plane(depth)][layer].add(pos) self.replays += 1 return output @@ -434,7 +367,14 @@ def prepare(self): """Capture the finite bucket set before any serving requests exist.""" parameter = next(self.model.parameters()) hidden = parameter.new_empty((0, self.model.config.hidden_size)) - batch = _empty_device_batch(self.cache) + batch = SimpleNamespace( + position_ids=torch.empty(0, device=self.cache.device, dtype=torch.long), + write_blocks=torch.empty(0, device=self.cache.device, dtype=torch.long), + write_offsets=torch.empty(0, device=self.cache.device, dtype=torch.long), + context_lengths=torch.empty(0, device=self.cache.device, dtype=torch.int32), + block_tables=torch.empty((0, 1), device=self.cache.device, dtype=torch.int32), + cu_seqlens_q=None, + ) proxy = _DeviceCache(self.cache) for size in self.capture_sizes: entry = _graph_entry( @@ -488,6 +428,8 @@ def __init__(self, model, execution, cache=None, *, bucketed=False, capture_size self.cache = cache # The boundary layers whose KV one replay reads and writes. self.kv_layers = getattr(model, "coda_kv_layers", ()) if cache is not None else () + if bucketed and cache is not None: + raise ValueError("bucketed coda graphs require a row-independent Ouro head") self.capture_sizes = (capture_sizes or graph_capture_sizes(execution)) if bucketed else None self.entries = {} self.pool = torch.cuda.graph_pool_handle() @@ -500,25 +442,6 @@ def __init__(self, model, execution, cache=None, *, bucketed=False, capture_size def prepare(self): if self.capture_sizes is None: return - if self.cache is not None: - batch = _empty_device_batch(self.cache) - hidden = self._empty_input() - for size in self.capture_sizes: - entry = _graph_entry( - hidden, - batch, - self.cache, - self.model.config.max_position_embeddings, - count=size, - bucketed=True, - ) - _copy_graph_inputs(entry, hidden, batch, count=0) - entry.graph, entry.output = _capture( - entry.hidden, self.stream, self.pool, lambda: self._run(entry), startup=True - ) - self.entries[size] = entry - self.captures += 1 - return parameter = next(self.model.parameters()) for size in self.capture_sizes: hidden = parameter.new_zeros((size, self.model.config.hidden_size)) @@ -531,18 +454,12 @@ def prepare(self): call.inputs_ready = False self.replays = 0 - def _empty_input(self): - parameter = next(self.model.parameters()) - dtype = getattr(self.model, "state_dtype", parameter.dtype) - return torch.empty((0, self.model.config.hidden_size), device=parameter.device, dtype=dtype) - def select(self, hidden, batch=None): count = len(hidden) - device_owned = isinstance(batch, DeviceKVMetadata) if self.cache is not None and ( batch is None - or (not device_owned and not batch.writable) - or _query_count(batch) != count + or not batch.writable + or len(batch.rows) != count or batch.cu_seqlens_q is not None ): raise ValueError("coda graphs require matching decode rows and KV metadata") @@ -554,14 +471,7 @@ def select(self, hidden, batch=None): entry = self.entries.get(capacity) if entry is None: entry = ( - _graph_entry( - hidden, - batch, - self.cache, - self.model.config.max_position_embeddings, - count=capacity, - bucketed=self.capture_sizes is not None, - ) + _graph_entry(hidden, batch, self.cache, self.model.config.max_position_embeddings) if self.cache is not None else SimpleNamespace(hidden=hidden.new_empty((capacity, *hidden.shape[1:]))) ) @@ -574,10 +484,9 @@ def prepare_inputs(self, call, hidden, *, startup=False): batch, entry = call.metadata, call.entry if self.cache is not None: self.cache._require_live_batch(batch) - if not isinstance(batch, DeviceKVMetadata): - for allocation, depth, position in batch.rows: - for layer in self.kv_layers: - self.cache._require_prefix(allocation, layer, depth, position) + for allocation, depth, position in batch.rows: + for layer in self.kv_layers: + self.cache._require_prefix(allocation, layer, depth, position) if entry is not None: stream = torch.cuda.current_stream(hidden.device) if self.last_event is not None: @@ -616,7 +525,7 @@ def execute(self, call, hidden): output = entry.output[: len(hidden)].clone() self.last_event = torch.cuda.Event() self.last_event.record(torch.cuda.current_stream(hidden.device)) - if self.cache is not None and not isinstance(batch, DeviceKVMetadata): + if self.cache is not None: for allocation, depth, position in batch.rows: for layer in self.kv_layers: allocation.written[self.cache._plane(depth)][layer].add(position) @@ -624,92 +533,16 @@ def execute(self, call, hidden): return output -class CodaPairGraphs: - """Replay the ordered pair on the speculative runner's single compute stream. - - Returned tokens borrow graph storage. The runner enqueues all consumers on - that same stream before another replay can overwrite them. - """ - - def __init__(self, model, cache, capture_sizes): - self.model, self.cache = model, cache - self.capture_sizes = capture_sizes - self.stream = torch.cuda.Stream(device=cache.device) - self.pool = torch.cuda.graph_pool_handle() - self.entries = {} - self.replays = self.fallbacks = 0 - - @torch.inference_mode() - def prepare(self): - model, cache = self.model, self.cache - parameter = next(model.parameters()) - hidden = torch.empty( - (0, model.config.hidden_size), - dtype=getattr(model, "state_dtype", parameter.dtype), - device=cache.device, - ) - empty = _empty_device_batch(cache) - proxy = _DeviceCache(cache) - for size in self.capture_sizes: - target = _graph_entry( - hidden, - empty, - cache, - model.config.max_position_embeddings, - count=size, - bucketed=True, - ) - draft = _graph_entry( - hidden, - empty, - cache, - model.config.max_position_embeddings, - count=size, - bucketed=True, - block_tables=target.metadata.block_tables, - ) - for entry in (target, draft): - _copy_graph_inputs(entry, hidden, empty, count=0) - - def run(): - return model.coda_pair( - target.hidden, target.metadata, draft.hidden, draft.metadata, proxy - ) - - graph, tokens = _capture(target.hidden, self.stream, self.pool, run, startup=True) - self.entries[size] = (target, draft, graph, tokens) - - def forward(self, target_hidden, target_kv, draft_hidden, draft_kv): - self.cache._require_live_batch(target_kv) - self.cache._require_live_batch(draft_kv) - count = len(target_hidden) - capacity = _bucket_size(self.capture_sizes, count) - if capacity not in self.entries or target_kv.block_tables is not draft_kv.block_tables: - self.fallbacks += 1 - return self.model.coda_pair( - target_hidden, target_kv, draft_hidden, draft_kv, self.cache - ) - target, draft, graph, tokens = self.entries[capacity] - _copy_graph_inputs(target, target_hidden, target_kv) - _copy_graph_inputs(draft, draft_hidden, draft_kv, copy_tables=False) - graph.replay() - self.replays += 1 - return tokens[:, :count] - - class PreludeGraphs(CodaGraphs): """Decode-token input stage of a boundary-KV model: tokens in, carried state out. Prompt prefill stays eager; its row count follows the prompt, not the batch. """ - def __init__(self, model, execution, cache, *, bucketed=False, capture_sizes=None): - super().__init__(model, execution, cache, bucketed=bucketed, capture_sizes=capture_sizes) + def __init__(self, model, execution, cache): + super().__init__(model, execution, cache) self.kv_layers = model.prelude_kv_layers - def _empty_input(self): - return torch.empty(0, device=self.cache.device, dtype=torch.long) - def _run(self, entry): return self.model.prelude_prepared(entry.hidden, entry.metadata, _DeviceCache(self.cache)) diff --git a/vllm_rlt/worker/executor.py b/vllm_rlt/worker/executor.py index 547d70e1..70404371 100644 --- a/vllm_rlt/worker/executor.py +++ b/vllm_rlt/worker/executor.py @@ -103,12 +103,6 @@ def submit(self, scheduled_batch): batch = build_execution_batch(scheduled_batch, self.runner.model.config.total_ut_steps) return self.runner.submit(scheduled_batch, batch=batch) - @torch.inference_mode() - def submit_mixed_speculative(self, speculative, prompt): - batch = build_execution_batch(prompt, self.runner.model.config.total_ut_steps) - with self.runner.prepare_mixed_recurrent(batch) as prepared: - return self.speculation.submit(speculative, prompt=(self.runner, prepared)) - @dataclass(frozen=True) class ForwardBatch: @@ -145,13 +139,9 @@ class ForwardResult: class ModelRuntime: - def __init__(self, model, cache, *, packed_graphs=None): + def __init__(self, model, cache): self.model = model self.cache = cache - self.packed_graphs = packed_graphs - - def _has_packed_graphs(self, metadata): - return self.packed_graphs is not None and metadata.cu_seqlens_q is not None def prepare(self, batch: ForwardBatch) -> ForwardBatch: """Choose graph/fallback for every call before execution. @@ -188,13 +178,12 @@ def forward(self, batch: ForwardBatch) -> ForwardResult: if batch.graphs is not None: logits = batch.graphs.execute(batch.graph_calls[0], hidden) elif batch.prelude_coda_kv_metadata is not None: - kv = batch.prelude_coda_kv_metadata - if not batch.compute_logits and self._has_packed_graphs(kv): - logits = self.packed_graphs.forward(Operation.CODA, hidden, kv) - else: - logits = self.model.coda_prepared( - hidden, kv, self.cache, compute_logits=batch.compute_logits - ) + logits = self.model.coda_prepared( + hidden, + batch.prelude_coda_kv_metadata, + self.cache, + compute_logits=batch.compute_logits, + ) else: logits = self.model.coda(hidden) if batch.compute_logits else None return ForwardResult(hidden=hidden, logits=logits) @@ -204,16 +193,12 @@ def forward(self, batch: ForwardBatch) -> ForwardResult: if batch.graphs is not None: return ForwardResult(batch.graphs.execute(batch.graph_calls[0], batch.tokens)) if batch.prelude_coda_kv_metadata is not None: - kv = batch.prelude_coda_kv_metadata - tokens = batch.tokens[: len(kv.position_ids)] - if self._has_packed_graphs(kv): - hidden = self.packed_graphs.forward( - Operation.PRELUDE, tokens, kv, generators=batch.generators - ) - else: - hidden = self.model.prelude_prepared( - tokens, kv, self.cache, generators=batch.generators - ) + hidden = self.model.prelude_prepared( + batch.tokens[: len(batch.prelude_coda_kv_metadata.position_ids)], + batch.prelude_coda_kv_metadata, + self.cache, + generators=batch.generators, + ) if batch.hidden_buffer is not None: batch.hidden_buffer.zero_() batch.hidden_buffer[: len(hidden)].copy_(hidden) @@ -230,10 +215,6 @@ def forward(self, batch: ForwardBatch) -> ForwardResult: if not call.inputs_ready: batch.graphs.prepare_inputs(call, hidden) hidden, gate = batch.graphs.execute(call, hidden) - elif self._has_packed_graphs(kv): - hidden, gate = self.packed_graphs.forward( - Operation.RECURRENT, hidden, kv, compute_gate=batch.compute_gate - ) else: hidden, gate = self.model.recurrent_prepared( hidden, kv, self.cache, compute_gate=batch.compute_gate diff --git a/vllm_rlt/worker/inkling_graph_warmup.py b/vllm_rlt/worker/inkling_graph_warmup.py deleted file mode 100644 index 012548ce..00000000 --- a/vllm_rlt/worker/inkling_graph_warmup.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Warm native Inkling kernels and graph entries before serving requests.""" - -import gc -import logging -import time - -import torch - -from vllm_rlt.config import cuda_graph_rows -from vllm_rlt.kernels.inkling2mini import warmup_fa4 -from vllm_rlt.request import Operation -from vllm_rlt.worker.packed_graph import packed_capture_sizes - -logger = logging.getLogger(__name__) - - -def _run_graph(owner, inputs, metadata): - call = owner.select(inputs, metadata) - owner.prepare_inputs(call, inputs, startup=True) - return owner.execute(call, inputs) - - -def _warm_decode(runner, ids, budget): - cache = runner.cache_manager - model = runner.model - limit = len(ids) - sizes = sorted(range(1, limit + 1), key=lambda size: (size != limit, size != 1, -size)) - positions = [0] * limit - tokens = torch.zeros(limit, device=cache.device, dtype=torch.long) - hidden = torch.zeros( - (limit, model.config.hidden_size), device=cache.device, dtype=runner.state_dtype - ) - multi_pass = model.config.total_ut_steps > 1 - uniform_depths = (0, 1) if multi_pass else (0,) - for size in sizes[:budget]: - batch = cache._prepare_batch(ids[:size], positions[:size], positions[:size]) - _run_graph(runner.prelude_graphs, tokens[:size], batch) - _run_graph(runner.coda_graphs, hidden[:size], batch) - for depth in uniform_depths: - if len(runner.graphs.entries) >= budget: - break - metadata = cache._prepare_batch(ids[:size], [depth] * size, positions[:size]) - _run_graph(runner.graphs, hidden[:size], metadata) - if multi_pass: - for size in sizes: - if len(runner.graphs.entries) >= budget: - break - if size > 1: - metadata = cache._prepare_batch( - ids[:size], [1] + [0] * (size - 1), positions[:size] - ) - _run_graph(runner.graphs, hidden[:size], metadata) - - -def _warm_packed(runner, scheduler, ids, limit, budget): - owner = runner.packed_graphs - cache = runner.cache_manager - model = runner.model - sizes = sorted( - packed_capture_sizes(limit), - key=lambda size: (size != limit, bool(size & (size - 1)), -size), - ) - tokens = torch.zeros(limit, device=cache.device, dtype=torch.long) - hidden = torch.zeros( - (limit, model.config.hidden_size), device=cache.device, dtype=runner.state_dtype - ) - positions = list(range(limit)) - all_prompt = [ids[0]] * limit - multi_pass = model.config.total_ut_steps > 1 - mixed = scheduler.mode == "mixed" - compute_gate = mixed and not owner.speculative_core - for size in sizes: - if size < owner.min_rows or len(owner.entries) >= budget: - continue - first = cache._prepare_batch( - all_prompt[:size], [0] * size, positions[:size], packed_prefill=True - ) - owner.forward(Operation.PRELUDE, tokens[:size], first, startup=True) - if len(owner.entries) < budget: - owner.forward( - Operation.RECURRENT, hidden[:size], first, compute_gate=compute_gate, startup=True - ) - if multi_pass and len(owner.entries) < budget: - later = cache._prepare_batch( - all_prompt[:size], [1] * size, positions[:size], packed_prefill=True - ) - owner.forward( - Operation.RECURRENT, hidden[:size], later, compute_gate=compute_gate, startup=True - ) - if mixed and multi_pass and size > 1 and len(ids) > 1 and len(owner.entries) < budget: - staggered = cache._prepare_batch( - [ids[1], *all_prompt[: size - 1]], - [1] + [0] * (size - 1), - [0, *positions[: size - 1]], - packed_prefill=True, - ) - owner.forward( - Operation.RECURRENT, - hidden[:size], - staggered, - compute_gate=compute_gate, - startup=True, - ) - if len(owner.entries) < budget: - owner.forward(Operation.CODA, hidden[:size], first, startup=True) - - -@torch.inference_mode() -def warmup_inkling_graphs(runner, scheduler): - """Capture a bounded set of graphs using temporary, valid KV allocations.""" - cache = runner.cache_manager - execution = runner.execution_config - available = cache.num_blocks // cache.storage_depths - if available == 0: - raise ValueError("Inkling CUDA Graph warmup needs KV pages for one request") - decode_rows = min( - cuda_graph_rows(execution), - scheduler.max_num_seqs, - scheduler.max_num_batched_tokens, - available, - ) - packed_rows = min( - runner.model.config.max_position_embeddings, - scheduler.max_num_batched_tokens, - (available - decode_rows + 1) * cache.block_size, - ) - budget = execution.cuda_graph_max_graphs - ids = [f"__inkling_warmup_{i}__" for i in range(decode_rows)] - prefix_queries, prefix_hits = cache.prefix_queries, cache.prefix_hits - allocated = [] - start = time.monotonic() - if runner.packed_graphs is not None: - logger.info("Compiling Inkling FA4 variants before serving") - with torch.cuda.device(cache.device): - warmup_fa4( - runner.model.config, cache, scheduler.max_num_batched_tokens, scheduler.max_num_seqs - ) - logger.info("Capturing Inkling startup CUDA Graphs") - gc.collect() - gc_enabled = gc.isenabled() - gc.disable() - try: - for i, request_id in enumerate(ids): - if not cache.allocate(request_id, packed_rows if i == 0 else 1): - raise RuntimeError("cannot allocate temporary Inkling warmup KV pages") - allocated.append(request_id) - _warm_decode(runner, ids, budget) - if runner.packed_graphs is not None: - _warm_packed(runner, scheduler, ids, packed_rows, budget) - finally: - try: - torch.cuda.synchronize(cache.device) - finally: - for request_id in allocated: - cache.free(request_id) - cache.prefix_queries, cache.prefix_hits = prefix_queries, prefix_hits - if gc_enabled: - gc.enable() - - owners = { - "prelude": runner.prelude_graphs, - "core": runner.graphs, - "coda": runner.coda_graphs, - "mixed": runner.mixed_graphs, - "packed": runner.packed_graphs, - } - for owner in owners.values(): - if owner is not None: - owner.allow_capture = False - owner.replays = owner.fallbacks = 0 - return dict( - elapsed_seconds=time.monotonic() - start, - entries={name: len(owner.entries) for name, owner in owners.items() if owner is not None}, - ) diff --git a/vllm_rlt/worker/metadata.py b/vllm_rlt/worker/metadata.py index 54040c2d..95fde7bb 100644 --- a/vllm_rlt/worker/metadata.py +++ b/vllm_rlt/worker/metadata.py @@ -13,19 +13,9 @@ import torch from vllm_rlt.attention import AttentionMetadataValues, AttentionRows, plan_attention_metadata -from vllm_rlt.attention.metadata import assemble_attention_metadata if TYPE_CHECKING: from vllm_rlt.core.kv_cache_manager import KVCacheManager, _Allocation - from vllm_rlt.request import StateSpan - - -@dataclass(frozen=True) -class PackedKVRange: - allocation: _Allocation - depth: int - start: int - end: int @dataclass(frozen=True, eq=False) @@ -49,7 +39,6 @@ class KVMetadata: writable: bool cu_seqlens_q: torch.Tensor | None = None max_seqlen_q: int = 1 - packed_ranges: tuple[PackedKVRange, ...] | None = None @dataclass(frozen=True, eq=False) @@ -79,14 +68,6 @@ class DeviceKVMetadata: max_seqlen_q: int = 1 -@dataclass(frozen=True, eq=False, kw_only=True) -class MixedRecurrentKVMetadata(DeviceKVMetadata): - """Speculative single-query rows followed by host-planned prompt ranges.""" - - decode_rows: int - prompt: KVMetadata - - @dataclass(frozen=True) class KVLayout: """Host values for one depth assignment, independent of destination storage. @@ -103,54 +84,12 @@ class KVLayout: write_offsets: list[int] attention: AttentionMetadataValues writable: bool - packed_ranges: tuple[PackedKVRange, ...] | None = None - - -def _packed_ranges(rows, cumulative): - if cumulative is None: - return None - return tuple( - PackedKVRange(*rows[start], rows[end - 1][2] + 1) - for start, end in zip(cumulative, cumulative[1:]) - ) class MetadataBuilder: def __init__(self, cache): self.cache = cache - def join_recurrent(self, decode, prompt): - """Join device-owned decode addresses and packed prompt addresses on-stream.""" - decode_rows = len(decode.position_ids) - prompt_rows = len(prompt.rows) - decode_width = decode.block_tables.shape[1] - prompt_width = prompt.block_tables.shape[1] - tables = decode.block_tables.new_zeros( - (decode_rows + len(prompt.context_lengths), max(decode_width, prompt_width)) - ) - tables[:decode_rows, :decode_width].copy_(decode.block_tables) - tables[decode_rows:, :prompt_width].copy_(prompt.block_tables) - cu_seqlens = torch.cat( - ( - torch.arange(decode_rows, device=tables.device, dtype=torch.int32), - prompt.cu_seqlens_q + decode_rows, - ) - ) - mask = torch.cat((decode.write_mask, decode.write_mask.new_ones(prompt_rows))) - return MixedRecurrentKVMetadata( - allocations=decode.allocations + prompt.allocations, - position_ids=torch.cat((decode.position_ids, prompt.position_ids[:prompt_rows])), - write_blocks=torch.cat((decode.write_blocks, prompt.write_blocks)), - write_offsets=torch.cat((decode.write_offsets, prompt.write_offsets)), - block_tables=tables, - context_lengths=torch.cat((decode.context_lengths, prompt.context_lengths)), - write_mask=mask, - cu_seqlens_q=cu_seqlens, - max_seqlen_q=prompt.max_seqlen_q, - decode_rows=decode_rows, - prompt=prompt, - ) - def prepare_device( self, *, @@ -230,89 +169,6 @@ def resolve_rows(self, ids, depths, positions): self._write_addresses(rows) return rows - def build_packed( - self, spans: Sequence[StateSpan], loop_offsets: Sequence[int], *, for_write=True - ) -> tuple[KVLayout, ...]: - """Plan packed ranges once and resolve physical pages for each core visit.""" - cache = self.cache - if not loop_offsets: - raise ValueError("at least one depth assignment is required") - if cache.layout != "last_exited" or not cache.attention_capabilities.packed_prefill: - raise ValueError("packed queries require a compatible attention backend and KV layout") - allocations, seen, ranges = {}, set(), [] - cumulative = [0] - previous = None - for span in spans: - request_id = span.request.request_id - allocation = allocations.get(request_id) - if allocation is None: - allocation = allocations[request_id] = cache._get_allocation(request_id) - start, end = span.token_start, span.token_start + span.token_count - if end <= start: - raise ValueError("packed queries require nonempty ranges") - cache._validate_depth(span.depth) - cache._validate_position(allocation, start) - cache._validate_position(allocation, end - 1) - key = (request_id, span.depth) - if key == previous: - if start != ranges[-1].end: - raise ValueError("packed prefill positions must be contiguous") - ranges[-1] = replace(ranges[-1], end=end) - cumulative[-1] += span.token_count - else: - if key in seen: - raise ValueError("packed prefill request/depth must form one sequence") - seen.add(key) - ranges.append(PackedKVRange(allocation, span.depth, start, end)) - cumulative.append(cumulative[-1] + span.token_count) - previous = key - - block_size = cache.block_size - positions = [position for seq in ranges for position in range(seq.start, seq.end)] - offsets = [position % block_size for position in positions] - lengths = [seq.end for seq in ranges] - max_query = max((seq.end - seq.start for seq in ranges), default=1) - owners = tuple(allocations.items()) - layouts = [] - for offset in loop_offsets: - depth_ranges, tables, blocks = [], [], [] - for seq in ranges: - depth = seq.depth + offset - cache._validate_depth(depth) - depth_ranges.append(replace(seq, depth=depth) if offset else seq) - table = seq.allocation.block_tables[cache._plane(depth)] - tables.append(table) - for page in range(seq.start // block_size, (seq.end - 1) // block_size + 1): - start = max(seq.start, page * block_size) - end = min(seq.end, (page + 1) * block_size) - blocks.extend([table[page]] * (end - start)) - if for_write and len(set(zip(blocks, offsets))) != len(positions): - raise ValueError("duplicate KV write addresses for request/depth/position rows") - layouts.append( - KVLayout( - owner=cache, - rows=tuple( - (seq.allocation, seq.depth, position) - for seq in depth_ranges - for position in range(seq.start, seq.end) - ), - allocations=owners, - positions=positions, - write_blocks=blocks, - write_offsets=offsets, - attention=assemble_attention_metadata( - tables, - lengths, - block_size=block_size, - cu_seqlens_q=cumulative, - max_seqlen_q=max_query, - ), - writable=for_write, - packed_ranges=tuple(depth_ranges), - ) - ) - return tuple(layouts) - def build( self, request_ids: Sequence[str], @@ -368,7 +224,6 @@ def build( write_offsets=offsets, attention=attention, writable=for_write, - packed_ranges=_packed_ranges(rows, attention.cu_seqlens_q), ) ) return tuple(layouts) @@ -417,7 +272,6 @@ def select_rows(layout, rows, *, packed=False): write_offsets=[layout.write_offsets[row] for row in rows], attention=attention, writable=layout.writable, - packed_ranges=_packed_ranges(selected, attention.cu_seqlens_q), ) @staticmethod diff --git a/vllm_rlt/worker/model_runner.py b/vllm_rlt/worker/model_runner.py index 7e3846c5..3ba410ea 100644 --- a/vllm_rlt/worker/model_runner.py +++ b/vllm_rlt/worker/model_runner.py @@ -1,13 +1,13 @@ """Request-phase execution, random lookahead signals and event-owned CUDA submissions.""" import math -from contextlib import contextmanager, nullcontext +from contextlib import nullcontext from dataclasses import dataclass, replace from typing import NamedTuple import torch -from vllm_rlt.config import ExecutionConfig, ExitConfig, SchedulerConfig, cuda_graph_rows +from vllm_rlt.config import ExecutionConfig, ExitConfig, SchedulerConfig from vllm_rlt.core.scheduler import SchedulerOutput from vllm_rlt.device import stream_module from vllm_rlt.request import ExecutionBatch, Operation, Request @@ -20,7 +20,6 @@ from vllm_rlt.worker.cuda_graph import CodaGraphs, PreludeGraphs, RecurrentGraphs from vllm_rlt.worker.executor import ForwardBatch, ModelRuntime from vllm_rlt.worker.output import ModelRunnerOutput -from vllm_rlt.worker.packed_graph import PackedGraphs from vllm_rlt.worker.sampler import RngRegistry, Sampler from vllm_rlt.worker.submission_queue import MAX_CONCURRENT_SUBMISSIONS, SubmissionQueue from vllm_rlt.worker.tensors import StagedInputTensor, TensorTransfer, UvaBuffer, pinned_tensor @@ -166,8 +165,8 @@ def __init__( self.model = model.eval() self.cache_manager = cache_manager self.metadata = cache_manager.metadata_builder + self.runtime = ModelRuntime(self.model, cache_manager) parameter = next(model.parameters()) - self.state_dtype = getattr(model, "state_dtype", parameter.dtype) self.device = parameter.device self.device_ops = stream_module(self.device) self.sampler = Sampler() @@ -176,11 +175,7 @@ def __init__( self.rng = rng if rng is not None else RngRegistry() self.exit_config = exit_config or ExitConfig() self.execution_config = execution_config or ExecutionConfig() - use_async_state = ( - self.execution_config.async_scheduling - and self.device.type == "cuda" - and getattr(model, "supports_device_kv_metadata", True) - ) + use_async_state = self.execution_config.async_scheduling and self.device.type == "cuda" scheduler = scheduler_config or SchedulerConfig() self.graphs = ( RecurrentGraphs( @@ -202,21 +197,6 @@ def __init__( if self.coda_graphs is not None and hasattr(model, "prelude_kv_layers") else None ) - self.mixed_graphs = ( - RecurrentGraphs(model, cache_manager, self.execution_config, self.graphs.compute_gate) - if self.graphs is not None - and scheduler.mode == "mixed" - and getattr(model, "supports_packed_recurrent_graphs", False) - else None - ) - self.packed_graphs = ( - PackedGraphs(model, cache_manager, self.execution_config, scheduler) - if self.graphs is not None - and self.execution_config.packed_prefill is not False - and getattr(model, "supports_packed_prefill_graphs", False) - else None - ) - self.runtime = ModelRuntime(self.model, cache_manager, packed_graphs=self.packed_graphs) self.input_buffers: dict[torch.dtype, StagedInputTensor] = { dtype: StagedInputTensor(dtype, self.device, use_uva=self.execution_config.use_uva) for dtype in (torch.int64, torch.int32) @@ -294,7 +274,7 @@ def __init__( torch.empty( (scheduler.max_num_seqs, stage_rows, model.config.hidden_size), device=self.device, - dtype=self.state_dtype, + dtype=parameter.dtype, ) if self.staged_prefill else None @@ -306,7 +286,7 @@ def __init__( torch.empty( (prefill_rows, model.config.hidden_size), device=self.device, - dtype=self.state_dtype, + dtype=parameter.dtype, ) if self.staged_prefill else None @@ -319,7 +299,7 @@ def __init__( else scheduler.max_num_seqs, max(scheduler.max_num_batched_tokens, scheduler.prefill_chunk_size), self.device, - self.state_dtype, + parameter.dtype, use_uva=self.execution_config.use_uva, ) for _ in range(MAX_CONCURRENT_SUBMISSIONS) @@ -352,7 +332,7 @@ def __init__( width, model.config.hidden_size, self.device, - self.state_dtype, + parameter.dtype, use_uva=self.execution_config.use_uva, ) for _ in range(2) @@ -361,7 +341,7 @@ def __init__( self.states = torch.empty( (scheduler.max_num_seqs, model.config.hidden_size), device=self.device, - dtype=self.state_dtype, + dtype=parameter.dtype, ) # Buffers allocated after stream creation must be visible there too. for stream in (self.core_stream, self.boundary_stream): @@ -648,16 +628,13 @@ def _gather(self, requests, workspace, size): hidden[row].copy_(request.hidden_state) return hidden - def _prepare_prefill_coda( - self, ids, positions, requests, kv=None, *, packed=None, eligible=None - ): + def _prepare_prefill_coda(self, ids, positions, requests, kv=None, *, packed=None): if not getattr(self.model, "requires_boundary_kv", False): return None, None rows = [ row for row, (position, request) in enumerate(zip(positions, requests)) - if (eligible is None or row in eligible) - and position < len(request.prompt_token_ids) - 1 + if position < len(request.prompt_token_ids) - 1 ] if not rows: return None, None @@ -677,32 +654,6 @@ def _prepare_prefill_coda( Operation.CODA, prelude_coda_kv_metadata=kv_metadata, compute_logits=False ), index - def _prepare_packed_prefill_coda(self, spans, *, loops=None): - if not getattr(self.model, "requires_boundary_kv", False): - return None, None - selected, rows = [], [] - offset = 0 - for span in spans: - if loops is None or ( - span.chunk_start is not None - and span.depth + loops == self.model.config.total_ut_steps - ): - # The last prompt row is consumed by the logits-producing CODA. - count = min( - span.token_count, len(span.request.prompt_token_ids) - 1 - span.token_start - ) - if count > 0: - selected.append(replace(span, token_count=count, depth=0)) - rows.extend(range(offset, offset + count)) - offset += span.token_count - if not rows: - return None, None - layout = self.metadata.build_packed(selected, (0,)) - kv = stage_metadata(layout, self._append_input)[0] - index = self.input_buffers[torch.int64].append(rows) - forward = ForwardBatch(Operation.CODA, prelude_coda_kv_metadata=kv, compute_logits=False) - return forward, index - def _prepare_shared_loop_inputs(self, batch): cache = self.cache_manager spans = sorted(batch.spans, key=lambda span: span.token_count, reverse=True) @@ -791,37 +742,35 @@ def _prepare_loop_inputs(self, batch, packed_metadata=None): cache = self.cache_manager if cache.layout == "shared": return self._prepare_shared_loop_inputs(batch) + ids, positions, tokens, requests, outputs, depths = [], [], [], [], [], [] + for span in batch.spans: + count, request = span.token_count, span.request + ids.extend([request.request_id] * count) + depths.extend([span.depth] * count) + positions.extend(range(span.token_start, span.token_start + count)) + tokens.extend(span.input_tokens) + requests.extend([request] * count) + outputs.append((len(tokens) - 1, request)) packed = cache.attention_capabilities.packed_prefill and ( not cache.attention_capabilities.packed_sliding_window or all(len(span.request.prompt_token_ids) > 64 for span in batch.spans) ) - tokens, requests, outputs = [], [], [] - for span in batch.spans: - tokens.extend(span.input_tokens) - requests.extend([span.request] * span.token_count) - outputs.append((len(tokens) - 1, span.request)) - loop_offsets = range(batch.loop_count) - if packed: - layouts = self.metadata.build_packed(batch.spans, loop_offsets) - if packed_metadata is not None: - packed_metadata.store(layouts, tokens) - tensor, metadata = None, () - else: - tensor = self.input_buffers[torch.int64].append(tokens) - metadata = stage_metadata(layouts, self._append_input) - coda, coda_rows = self._prepare_packed_prefill_coda(batch.spans) + size = len(tokens) if packed else self._size(len(tokens)) + depth_sets = [[depth + offset for depth in depths] for offset in range(batch.loop_count)] + if packed_metadata is not None: + layouts = self.metadata.build(ids, depth_sets, positions, packed=True) + packed_metadata.store(layouts, tokens) + tensor, metadata = None, () else: - ids, depths, positions = batch.addresses() - size = self._size(len(tokens)) tensor = self.input_buffers[torch.int64].append(tokens + [0] * (size - len(tokens))) - depth_sets = [[depth + offset for depth in depths] for offset in loop_offsets] metadata = self._stage_metadata( ids, depth_sets, positions, + packed=packed, padded_rows=size, ) - coda, coda_rows = self._prepare_prefill_coda(ids, positions, requests, packed=False) + coda, coda_rows = self._prepare_prefill_coda(ids, positions, requests, packed=packed) forwards = [ PreparedForward( ForwardBatch(Operation.PRELUDE, tokens=tensor, metadata=metadata), @@ -884,7 +833,7 @@ def input_view(tensor): storage = torch.empty( (capacity, self.model.config.hidden_size), device=self.device, - dtype=self.state_dtype, + dtype=next(self.model.parameters()).dtype, ) self.loop_hidden[slot] = storage hidden_buffer = storage[:size] @@ -907,55 +856,27 @@ def prepare_on_cpu(self, batch: ExecutionBatch): if batch.operation == Operation.PRELUDE and batch.loop_count: return prepared metadata, boundary_metadata = (), None - followups = () - boundary_kv = getattr(self.model, "requires_boundary_kv", False) - packed = batch.has_chunks and self.cache_manager.attention_capabilities.packed_prefill if batch.operation == Operation.RECURRENT: start = 1 if prepared.kv is not None else 0 - if not packed and (start < batch.loop_count or (boundary_kv and batch.has_chunks)): - ids, depths, positions = batch.addresses() if start < batch.loop_count: - offsets = range(start, batch.loop_count) - if packed: - layouts = self.metadata.build_packed(batch.spans, offsets) - metadata = stage_metadata(layouts, self._append_input) - else: - metadata = self._stage_metadata( - ids, [[depth + offset for depth in depths] for offset in offsets], positions - ) - if packed: - coda, rows = self._prepare_packed_prefill_coda(batch.spans, loops=batch.loop_count) - if coda is not None: - followups = (PreparedForward(coda, outputs=(), hidden_rows=rows),) - elif boundary_kv and batch.has_chunks: - complete, requests = set(), [] - row = 0 - for span in batch.spans: - end = row + span.token_count - if ( - span.chunk_start is not None - and span.depth + batch.loop_count == self.model.config.total_ut_steps - ): - complete.update(range(row, end)) - requests.extend([span.request] * span.token_count) - row = end - if complete: - coda, rows = self._prepare_prefill_coda( - ids, positions, requests, packed=packed, eligible=complete - ) - if coda is not None: - followups = (PreparedForward(coda, outputs=(), hidden_rows=rows),) - elif boundary_kv: - if packed: - layouts = self.metadata.build_packed(batch.spans, (0,)) - boundary_metadata = stage_metadata(layouts, self._append_input)[0] - else: ids, depths, positions = batch.addresses() - boundary_metadata = self._stage_metadata(ids, (depths,), positions)[0] + metadata = self._stage_metadata( + ids, + [ + [depth + offset for depth in depths] + for offset in range(start, batch.loop_count) + ], + positions, + packed=batch.has_chunks + and self.cache_manager.attention_capabilities.packed_prefill, + ) + elif getattr(self.model, "requires_boundary_kv", False): + ids, depths, positions = batch.addresses() + boundary_metadata = self._stage_metadata(ids, (depths,), positions)[0] forward = ForwardBatch( batch.operation, metadata=metadata, prelude_coda_kv_metadata=boundary_metadata ) - return replace(prepared, forwards=(PreparedForward(forward), *followups)) + return replace(prepared, forwards=(PreparedForward(forward),)) def _prepare_cpu_inputs(self, batch: ExecutionBatch): """Snapshot request inputs and acquire the storage used by this submission.""" @@ -1094,45 +1015,28 @@ def _prepare_forward(self, 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 - followups = prepared.forwards[1:] metadata = inputs.metadata kv_metadata = inputs.prelude_coda_kv_metadata if metadata or kv_metadata is not None or prepared.gate_indices is not None: uploaded = {dtype: buffer.upload() for dtype, buffer in self.input_buffers.items()} - - def input_view(indices): - return uploaded[indices.dtype].as_strided( - indices.shape, indices.stride(), indices.storage_offset() - ) - if prepared.gate_indices is not None: + indices = prepared.gate_indices prepared = replace( prepared, - gate_indices=input_view(prepared.gate_indices), + gate_indices=uploaded[indices.dtype].as_strided( + indices.shape, indices.stride(), indices.storage_offset() + ), ) metadata = tuple(self.metadata.bind(kv, uploaded) for kv in metadata) if kv_metadata is not None: kv_metadata = self.metadata.bind(kv_metadata, uploaded) - followups = tuple( - replace( - entry, - forward=replace( - entry.forward, - prelude_coda_kv_metadata=self.metadata.bind( - entry.forward.prelude_coda_kv_metadata, uploaded - ), - ), - hidden_rows=input_view(entry.hidden_rows), - ) - for entry in followups - ) if batch.operation == Operation.PRELUDE: forward = ForwardBatch( Operation.PRELUDE, tokens=prepared.token_ids, prelude_coda_kv_metadata=kv_metadata, generators=self._prepare_generators(requests) if kv_metadata else None, - graphs=self.prelude_graphs if kv_metadata and not batch.has_chunks else None, + graphs=self.prelude_graphs if kv_metadata else None, ) return replace(prepared, forwards=(PreparedForward(self.runtime.prepare(forward)),)) hidden = self._load_hidden(batch, prepared, workspace, size) @@ -1144,24 +1048,10 @@ def input_view(indices): graphs=self.coda_graphs if kv_metadata else None, ) return replace(prepared, forwards=(PreparedForward(self.runtime.prepare(forward)),)) - boundary_kv = getattr(self.model, "requires_boundary_kv", False) - supports_packed_graphs = getattr(self.model, "supports_packed_recurrent_graphs", False) - graph_eligible = supports_packed_graphs or not (boundary_kv and batch.has_chunks) - graphs = self.graphs if batch.emit_gate and graph_eligible else None + graphs = self.graphs if batch.emit_gate else None kv = prepared.kv if kv is not None: metadata = (kv,) + metadata - if graphs is not None and batch.has_chunks: - graphs = self.mixed_graphs or graphs - if ( - self.packed_graphs is not None - and ( - self.packed_graphs.bucketed - or batch.num_rows > cuda_graph_rows(self.execution_config) - ) - and metadata[0].cu_seqlens_q is not None - ): - graphs = None forward = ForwardBatch( Operation.RECURRENT, hidden=hidden[: batch.num_rows] @@ -1172,9 +1062,7 @@ def input_view(indices): compute_gate=batch.emit_gate and self.exit_config.mode in ("ouro", "ouro_delayed"), ) return replace( - prepared, - kv=metadata[0], - forwards=(PreparedForward(self.runtime.prepare(forward)), *followups), + prepared, kv=metadata[0], forwards=(PreparedForward(self.runtime.prepare(forward)),) ) def _load_hidden(self, batch, prepared, workspace, size): @@ -1316,32 +1204,6 @@ def _wait_for_requests(self, batch, stream): if span.request.hidden_state is not None: span.request.hidden_state.record_stream(stream) - @contextmanager - def prepare_mixed_recurrent(self, batch): - """Lease the regular prompt inputs until the joined Core finishes reading them.""" - stream = self.core_stream - if self.submissions.begin(): - self.split_prefill_submission_waits += 1 - prepared = self.prepare_on_cpu(batch) - source_stream = torch.cuda.current_stream(self.device) - with torch.cuda.stream(stream): - if source_stream != stream: - stream.wait_stream(source_stream) - self._wait_for_requests(batch, stream) - yield self.prepare_on_gpu(prepared) - event = torch.cuda.Event() - event.record(stream) - for span in batch.spans: - self.events[span.request.request_id] = event - self.submissions.complete(event) - self.split_prefill_submissions += 1 - - def finish_mixed_recurrent(self, prepared, hidden): - """Save the prompt slice and enqueue the ordinary KV-only Coda follows.""" - self._store_hidden(prepared.batch, hidden, prepared) - for entry in prepared.forwards[1:]: - self.runtime.forward(replace(entry.forward, hidden=hidden[entry.hidden_rows])) - @torch.inference_mode() def submit(self, scheduled_batch: SchedulerOutput | None = None, *, batch: ExecutionBatch): """Submit model computation and return its result/completion ownership. diff --git a/vllm_rlt/worker/packed_graph.py b/vllm_rlt/worker/packed_graph.py deleted file mode 100644 index a3080e9e..00000000 --- a/vllm_rlt/worker/packed_graph.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Packed Inkling graphs with eager, batch-dependent native attention.""" - -import gc -import math -from contextlib import contextmanager - -import torch - -from vllm_rlt.config import cuda_graph_rows -from vllm_rlt.request import Operation -from vllm_rlt.worker.cuda_graph import ( - _bucket_size, - _cache_full, - _copy_graph_inputs, - _DeviceCache, - _graph_entry, - _query_count, -) -from vllm_rlt.worker.metadata import MixedRecurrentKVMetadata - - -def packed_capture_sizes(limit): - """Use the vLLM throughput grid for prefill and mixed token counts.""" - sizes = [] - size = 1 - while size < limit: - sizes.append(size) - step = min(size, max(8, size / 4), 0.07 * max(size, 4096)) - stride = 1 << math.floor(math.log2(step)) - size = (size // stride + 1) * stride - return (*sizes, limit) - - -class _AttentionSegments: - """Capture model segments around in-place attention calls.""" - - def __init__(self, pool=None): - self.segments = [] - self.shared_pool = pool is not None - self.pool = torch.cuda.graph_pool_handle() if pool is None else pool - self.current = None - self.batch = None - - def _begin(self): - self.current = torch.cuda.CUDAGraph() - self.current.capture_begin(pool=self.pool) - - def _finish(self): - graph, self.current = self.current, None - graph.capture_end() - return graph - - @contextmanager - def capture(self, batch): - self.batch = batch - try: - self._begin() - yield - finally: - try: - if self.current is not None: - self.segments.append((self._finish(), None)) - finally: - self.batch = None - - def attention(self, run, *tensors): - graph = self._finish() - # The eager break reads real queries and writes live KV during capture. - graph.replay() - run(self.batch, *tensors) - # Graphs own the device addresses. Non-owning aliases let the allocator - # reuse transient allocations when capturing the next bucket. - if self.shared_pool: - tensors = tuple(_borrow_graph_tensor(tensor) for tensor in tensors) - self.segments.append((graph, (run, tensors))) - self._begin() - - def replay(self, batch): - for graph, attention in self.segments: - graph.replay() - if attention is not None: - run, tensors = attention - run(batch, *tensors) - - -def _borrow_graph_tensor(tensor): - return None if tensor is None else torch.ops._C.weak_ref_tensor(tensor) - - -class PackedGraphs: - """Own packed prelude, core and KV-only coda graphs apart from decode.""" - - def __init__(self, model, cache, execution, scheduler): - self.model, self.cache = model, cache - self.execution = execution - self.max_rows = scheduler.max_num_batched_tokens - self.max_sequences = scheduler.max_num_seqs - self.speculative_core = False - self.bucketed = execution.packed_graph_buckets - self.min_rows = ( - 1 - if self.bucketed - else min(scheduler.prefill_chunk_size, 1 + cuda_graph_rows(execution)) - ) - self.capture_sizes = packed_capture_sizes(self.max_rows) if self.bucketed else () - self.pool = torch.cuda.graph_pool_handle() if self.bucketed else None - self.entries = {} - self.stream = torch.cuda.Stream(device=cache.device) - self.proxy = _DeviceCache(cache) - self.last_event = None - self.captures = self.replays = self.fallbacks = 0 - self.warned_cache_full = False - self.key_layers = { - Operation.PRELUDE: model.prelude_kv_layers, - Operation.RECURRENT: model.recurrent_kv_layers, - Operation.CODA: model.coda_kv_layers, - } - - def enable_speculative_core(self): - self.speculative_core = True - - def _forward(self, operation, inputs, metadata, cache, *, generators=None, compute_gate=False): - if operation == Operation.PRELUDE: - return self.model.prelude_prepared(inputs, metadata, cache, generators=generators) - if operation == Operation.RECURRENT: - return self.model.recurrent_prepared(inputs, metadata, cache, compute_gate=compute_gate) - return self.model.coda_prepared(inputs, metadata, cache, compute_logits=False) - - def _capture_pieces(self, entry, live, warm, run, *, startup=False): - # As with a lazy full capture, drain existing consumers of the live KV pages. - if startup: - self.stream.wait_stream(torch.cuda.current_stream(self.cache.device)) - else: - torch.cuda.synchronize(self.cache.device) - try: - with torch.cuda.stream(self.stream): - warm() - self.stream.synchronize() - if not startup or gc.isenabled(): - gc.collect() - enabled = gc.isenabled() - gc.disable() - try: - entry.metadata.attention_segments = entry.segments - with entry.segments.capture(live): - return run() - finally: - if enabled: - gc.enable() - finally: - self.stream.synchronize() - - @torch.inference_mode() - def forward( - self, operation, inputs, batch, *, generators=None, compute_gate=False, startup=False - ): - # Inkling uses the same recurrent forward with either caller gate flag. - compute_gate = compute_gate and getattr(self.model, "supports_recurrent_gate", True) - count = _query_count(batch) - sequences = len(batch.context_lengths) - host_batch = batch.prompt if isinstance(batch, MixedRecurrentKVMetadata) else batch - masked = self.speculative_core and operation == Operation.RECURRENT - max_sequences = ( - min(self.max_rows, self.max_sequences * self.model.config.total_ut_steps) - if masked - else self.max_sequences - ) - layers = self.key_layers[operation] - variant = ( - self.model.recurrent_graph_variant(batch) if operation == Operation.RECURRENT else None - ) - size = _bucket_size(self.capture_sizes, count) - key = (operation, size, variant, compute_gate) - if ( - not self.min_rows <= count <= self.max_rows - or sequences > max_sequences - or host_batch.packed_ranges is None - or not host_batch.writable - or _cache_full(self, key) - ): - self.fallbacks += 1 - return self._forward( - operation, - inputs, - batch, - self.cache, - generators=generators, - compute_gate=compute_gate, - ) - - self.cache._require_live_batch(batch) - for seq in host_batch.packed_ranges: - for layer in layers: - self.cache._require_prefix(seq.allocation, layer, seq.depth, seq.start) - entry = self.entries.get(key) - if entry is None: - entry = _graph_entry( - inputs, - batch, - self.cache, - self.model.config.max_position_embeddings, - count=size, - bucketed=self.bucketed, - table_count=min(size, max_sequences), - masked=masked, - ) - entry.metadata.graph_variant = variant - entry.graph = None - entry.segments = _AttentionSegments(self.pool) - stream = torch.cuda.current_stream(inputs.device) - if self.last_event is not None: - stream.wait_event(self.last_event) - _copy_graph_inputs(entry, inputs, batch) - # Live attention between existing graph segments uses the fused - # row mapping. Capture uses the staged query table and pad mask. - live = self.model.batch_type( - self.proxy, - batch, - self.model.config, - fused_sconv_metadata=entry.graph is not None and not startup, - ) - if entry.graph is None: - - def run(): - return self._forward( - operation, entry.hidden, entry.metadata, self.proxy, compute_gate=compute_gate - ) - - def warm(): - return self._forward( - operation, inputs, batch, self.proxy, compute_gate=compute_gate - ) - - entry.output = self._capture_pieces(entry, live, warm, run, startup=startup) - entry.graph = entry.segments - if self.bucketed: - if isinstance(entry.output, tuple): - entry.output = tuple(_borrow_graph_tensor(value) for value in entry.output) - else: - entry.output = _borrow_graph_tensor(entry.output) - self.entries[key] = entry - self.captures += 1 - entry.graph.replay(live) - output = entry.output - if isinstance(output, tuple): - output = tuple(value[:count].clone() if value is not None else None for value in output) - elif output is not None: - output = output[:count].clone() - self.last_event = torch.cuda.Event() - self.last_event.record(stream) - for layer in layers: - self.cache._mark_prepared_write(layer, host_batch, None) - self.replays += 1 - return output diff --git a/vllm_rlt/worker/pipeline_graph.py b/vllm_rlt/worker/pipeline_graph.py deleted file mode 100644 index bd041121..00000000 --- a/vllm_rlt/worker/pipeline_graph.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Pre-captured CUDA work for native Inkling's device-owned speculative pipeline.""" - -import math -from typing import NamedTuple - -import torch - -from vllm_rlt.worker.cuda_graph import _capture, _DeviceCache -from vllm_rlt.worker.metadata import DeviceKVMetadata - - -class PipelineUpdate(NamedTuple): - token: torch.Tensor - position: torch.Tensor - tokens: torch.Tensor - depths: torch.Tensor - candidates: torch.Tensor - active: torch.Tensor - source: torch.Tensor - wire: torch.Tensor - - -def pipeline_transition( - tokens, - depths, - previous_candidates, - predictions, - valid, - widths, - positions, - output_limits, - input_tokens, - lanes, - lengths, - draft_loops, - target_loops, -): - new_depths = depths + valid.long() * draft_loops - drafted = valid & (new_depths == draft_loops) - candidates = torch.where(drafted, predictions, previous_candidates) - emitted = valid[:, 0] & (new_depths[:, 0] == target_loops) - accepted = emitted & (candidates[:, 0] == predictions[:, 0]) - reject = emitted & ~accepted - committed = emitted.long() - next_tokens = torch.where(emitted, predictions[:, 0], input_tokens) - next_positions = positions + committed - source = (lanes + committed[:, None]).clamp_max(tokens.shape[1] - 1) - remaining = lengths - committed - # Shift after target completion and discard descendants on rejection. - surviving = (lanes < remaining[:, None]) & ~reject[:, None] - tail = (lengths - 1).clamp_min(0)[:, None] - append = drafted.gather(1, tail).squeeze(1) & ~reject - restart = reject | (emitted & (remaining == 0)) - newborn = (lanes == remaining[:, None]) & append[:, None] - newborn = torch.where(restart[:, None], lanes == 0, newborn) - within_limit = next_positions[:, None] + lanes < output_limits[:, None] - newborn &= (lanes < widths[:, None]) & within_limit - candidate = candidates.gather(1, tail).squeeze(1) - newborn_tokens = torch.where(restart, next_tokens, candidate) - # Wire layout consumed by SpeculativeRoundTicket.collect(). - wire = torch.stack( - (predictions[:, 0], accepted.long(), committed, next_positions, drafted.sum(1), committed), - dim=1, - ) - return PipelineUpdate( - next_tokens, - next_positions, - torch.where(newborn, newborn_tokens[:, None], tokens.gather(1, source)), - new_depths.gather(1, source).masked_fill_(newborn, 0), - candidates.gather(1, source), - (surviving | newborn) & within_limit, - source, - wire, - ) - - -def publish_pipeline(states, hidden, update, buffer): - """Commit before the next compute submission and stage compact D2H output.""" - count = len(states) - for name in ("token", "position"): - torch._foreach_copy_( - [getattr(state, name) for state in states], getattr(update, name)[:count].unbind() - ) - for name in ("tokens", "depths", "candidates", "active", "hidden"): - values = hidden if name == "hidden" else getattr(update, name) - torch._foreach_copy_( - [getattr(state.pipeline, name) for state in states], values[:count].unbind() - ) - buffer.result[: 6 * count].view(count, 6).copy_(update.wire[:count]) - - -class PipelineTransitionGraphs: - """Capture integer state updates by request count on the pipeline's compute stream.""" - - def __init__(self, device, sizes, capacity, config): - self.lanes = torch.arange(capacity, device=device) - self.entries = {} - self.replays = 0 - stream = torch.cuda.Stream(device=device) - pool = torch.cuda.graph_pool_handle() - for count in sizes: - self._prepare(device, count, capacity, config, stream, pool) - - def _prepare(self, device, count, capacity, config, stream, pool): - rows = torch.zeros((5, count, capacity), device=device, dtype=torch.long) - requests = torch.zeros((4, count), device=device, dtype=torch.long) - - def run(): - tokens, depths, candidates, predictions, visible = rows.unbind() - widths, positions, limits, input_tokens = requests.unbind() - valid = visible.bool() - return pipeline_transition( - tokens, - depths, - candidates, - predictions, - valid, - widths, - positions, - limits, - input_tokens, - self.lanes, - valid.sum(1), - config.draft_loops, - config.target_loops, - ) - - graph, update = _capture(rows, stream, pool, run, startup=True) - self.entries[count] = (rows, requests, graph, update) - - def forward(self, pipeline, predictions, valid, widths, positions, limits, input_tokens): - rows, requests, graph, update = self.entries[len(widths)] - torch.stack( - (pipeline.tokens, pipeline.depths, pipeline.candidates, predictions, valid), out=rows - ) - torch.stack((widths, positions, limits, input_tokens), out=requests) - graph.replay() - self.replays += 1 - # The caller enqueues every output consumer on this stream before reuse. - return update - - -class PipelineRoundGraph: - """One dense decode bucket. Mixed rounds and sparse reservations use stage graphs.""" - - @torch.inference_mode() - def __init__(self, model, cache, requests, capacity, config): - self.model = model - self.cache = _DeviceCache(cache) - self.requests = requests - self.capacity = capacity - self.config = config - self.pages = min(512, math.ceil(model.config.max_position_embeddings / cache.block_size)) - self.replays = 0 - self._table_versions = () - self._table_shape = () - self._limits = () - device = cache.device - shape = (requests, capacity) - self.tokens = torch.zeros(shape, dtype=torch.long, device=device) - self.depths = torch.zeros_like(self.tokens) - self.candidates = torch.zeros_like(self.tokens) - self.active = torch.zeros(shape, dtype=torch.bool, device=device) - dtype = getattr(model, "state_dtype", next(model.parameters()).dtype) - self.hidden = torch.zeros((*shape, model.config.hidden_size), dtype=dtype, device=device) - self.positions = torch.zeros(requests, dtype=torch.long, device=device) - self.input_tokens = torch.zeros_like(self.positions) - self.output_limits = torch.zeros_like(self.positions) - self.tables = torch.zeros( - (requests, cache.max_loops, self.pages), dtype=torch.int32, device=device - ) - self.roots = capacity * torch.arange(requests, device=device) - self.owners = torch.arange(requests, device=device).repeat_interleave(capacity) - self.lanes = torch.arange(capacity, device=device) - self.widths = torch.full_like(self.positions, capacity) - stream = torch.cuda.Stream(device=device) - self.graph, self.result = _capture( - self.hidden, stream, torch.cuda.graph_pool_handle(), self._run, startup=True - ) - - def supports(self, widths, tables): - count = len(widths) - return ( - self.requests * 3 <= count * 4 <= self.requests * 4 - and tables.shape[-1] <= self.pages - and all(width == self.capacity for width in widths) - ) - - def _kv(self, positions, tables, active): - block_size = self.cache.block_size - blocks = tables.gather(1, (positions // block_size)[:, None]).squeeze(1) - return DeviceKVMetadata( - allocations=(), - position_ids=positions, - write_blocks=blocks.long(), - write_offsets=positions % block_size, - block_tables=tables, - context_lengths=torch.where(active, positions + 1, 0).int(), - write_mask=active, - ) - - def _run(self): - draft_loops, target_loops = self.config.draft_loops, self.config.target_loops - lengths = self.active.sum(1) - active = self.active.flatten() - depths = self.depths.flatten() - positions = (self.positions[:, None] + self.lanes).flatten() - positions = torch.where(active, positions, 0) - tails = self.roots + (lengths - 1).clamp_min(0) - draft_rows = active[tails] & (depths[tails] == 0) - boundary = self.tables[:, 0].contiguous() - draft_kv = self._kv(positions[tails], boundary, draft_rows) - prelude = self.model.prelude_prepared(self.tokens.flatten()[tails], draft_kv, self.cache) - hidden = self.hidden.flatten(0, 1).clone() - hidden[tails] = torch.where(draft_rows[:, None], prelude, hidden[tails]) - for offset in range(draft_loops): - planes = torch.where(active, depths + offset, 0) - tables = self.tables[self.owners, planes].contiguous() - hidden, _ = self.model.recurrent_prepared( - hidden, self._kv(positions, tables, active), self.cache, compute_gate=False - ) - target_rows = active[self.roots] & (depths[self.roots] + draft_loops == target_loops) - target_kv = self._kv(positions[self.roots], boundary, target_rows) - target, draft = self.model.coda_pair( - hidden[self.roots], target_kv, hidden[tails], draft_kv, self.cache - ) - predictions = torch.zeros_like(self.tokens) - predictions.flatten()[self.roots] = target - predictions.flatten()[tails] = torch.where(draft_rows, draft, predictions.flatten()[tails]) - update = pipeline_transition( - self.tokens, - self.depths, - self.candidates, - predictions, - self.active, - self.widths, - self.positions, - self.output_limits, - self.input_tokens, - self.lanes, - lengths, - draft_loops, - target_loops, - ) - hidden = hidden.reshape_as(self.hidden).gather( - 1, update.source[:, :, None].expand(-1, -1, self.hidden.shape[2]) - ) - return hidden, update - - def forward(self, states, tables, buffer): - count = len(states) - if count < self.requests: - self.active[count:].zero_() - if self._table_shape != buffer.table_shape or any( - old is not new - for old, new in zip(self._table_versions, buffer.table_versions, strict=True) - ): - self.tables[:count, :, : tables.shape[-1]].copy_(tables) - self._table_shape = buffer.table_shape - self._table_versions = buffer.table_versions - pipes = [state.pipeline for state in states] - for name in ("tokens", "depths", "candidates", "active", "hidden"): - torch.stack([getattr(pipe, name) for pipe in pipes], out=getattr(self, name)[:count]) - torch.stack([state.position for state in states], out=self.positions[:count]) - torch.stack([state.token for state in states], out=self.input_tokens[:count]) - limits = buffer.plan_key[1] - if self._limits != limits: - self.output_limits[:count].copy_(buffer.plan[1]) - self._limits = limits - self.graph.replay() - hidden, update = self.result - publish_pipeline(states, hidden, update, buffer) - self.replays += 1 diff --git a/vllm_rlt/worker/speculative.py b/vllm_rlt/worker/speculative.py index 9f20f056..d292e422 100644 --- a/vllm_rlt/worker/speculative.py +++ b/vllm_rlt/worker/speculative.py @@ -197,7 +197,6 @@ def __init__( ): self.model, self.cache, self.config = model, cache, config self.boundary_kv = getattr(model, "requires_boundary_kv", False) - self.ordered_pipeline_coda = getattr(model, "requires_ordered_pipeline_coda", False) # Windowed attention needs one query row per token. self.row_queries = getattr(model, "requires_sliding_window", False) self.metadata = cache.metadata_builder @@ -214,7 +213,6 @@ def __init__( # each request's RNG slot. self.rng = rng if rng is not None else RngRegistry() self.stats = SpeculativeStats() - self.prelude_graphs = None self.graphs = ( RecurrentGraphs(model, cache, execution, False) if execution.cuda_graphs else None ) @@ -316,13 +314,9 @@ def _prepare_inputs(self, batch): ) def _prelude(self, tokens, boundary=None): - forward = ForwardBatch( - Operation.PRELUDE, - tokens=tokens, - prelude_coda_kv_metadata=boundary, - graphs=self.prelude_graphs, - ) - return self.runtime.forward(self.runtime.prepare(forward)).hidden + return self.runtime.forward( + ForwardBatch(Operation.PRELUDE, tokens=tokens, prelude_coda_kv_metadata=boundary) + ).hidden def _recurrent(self, hidden, metadata): forward = ForwardBatch( @@ -440,23 +434,13 @@ def _submit_pipeline(self, batch): endpoints = [ i for i, t in enumerate(tokens) if t.depth + draft in (draft, self.config.target_loops) ] - coda_batches = [endpoints] if endpoints else [] - if self.ordered_pipeline_coda: - # Commit the target history before evaluating the later draft. - # Each short-conv call gets at most one position per request. - target = [i for i in endpoints if tokens[i].depth + draft == self.config.target_loops] - proposal = [i for i in endpoints if tokens[i].depth == 0] - coda_batches = [rows for rows in (target, proposal) if rows] - endpoints = [i for rows in coda_batches for i in rows] if self.boundary_kv: # Boundary history lives at depth 0. A request's rows stay ordered by # position and every row stores before any row attends, so a draft # row reads the target KV its predecessor stores in the same call. # PRELUDE runs for new rows only; CODA reads the endpoint rows. views[Operation.PRELUDE] = self._view(source, new, (draft,), layouts) - views[Operation.CODA] = tuple( - self._view(source, rows, (draft,), layouts)[0] for rows in coda_batches - ) + views[Operation.CODA] = self._view(source, endpoints, (draft,), layouts) uploaded = {dtype: buffer.upload() for dtype, buffer in self.input_buffers.items()} layouts = tuple(self.metadata.bind(metadata, uploaded) for _, metadata in layouts.values()) if new: @@ -474,15 +458,12 @@ def _submit_pipeline(self, batch): token.hidden = row token.depth += self.config.draft_loops # Synchronous execution reads decisions in collect(), before the next step. - coda_layouts = views.get(Operation.CODA, ()) - choices = [ - self._coda(hidden[rows], layouts[coda_layouts[i]] if coda_layouts else None).argmax(-1) - for i, rows in enumerate(coda_batches) - ] - if len(choices) > 1: - decisions = torch.cat(choices) - else: - decisions = choices[0] if choices else hidden.new_empty(0, dtype=torch.long) + choices = ( + self._coda(hidden[endpoints], self._boundary(layouts, views, Operation.CODA)).argmax(-1) + if endpoints + else hidden.new_empty(0, dtype=torch.long) + ) + decisions = choices event = None if self.device.type == "cuda": event = torch.cuda.Event()