Skip to content
Merged
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ 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).

Expand Down
23 changes: 21 additions & 2 deletions docs/async-speculative.md
Original file line number Diff line number Diff line change
Expand Up @@ -912,8 +912,14 @@ 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. These combinations do
not enable mixed scheduling of prompt rows with speculative verification rows.
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.


The synchronous runner reads the acceptance result before constructing the next
Expand Down Expand Up @@ -986,6 +992,9 @@ 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
Expand All @@ -999,6 +1008,16 @@ 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)
Expand Down
87 changes: 84 additions & 3 deletions docs/launching.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,87 @@ 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/),
Expand Down Expand Up @@ -333,8 +414,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`; `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
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
[runtime guide](runtime.md#execution-batches-and-mixed-scheduling) before
combining optional features.
8 changes: 3 additions & 5 deletions docs/runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,9 @@ 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. 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.
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.

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
Expand Down
10 changes: 5 additions & 5 deletions docs/split-prefill-wavefront.md
Original file line number Diff line number Diff line change
Expand Up @@ -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; mixed scheduling
does not support speculative work.
chunk size. The option works with refill or mixed scheduling. The native
Inkling async token pipeline can also share recurrent work with prompt chunks.

## Progress and dependencies

Expand Down Expand Up @@ -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; mixed
mode rejects speculative configuration. CUDA graph and asynchronous paths use
the existing runner machinery.
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.

`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
Expand Down
17 changes: 15 additions & 2 deletions tests/test_async_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,23 @@ def ready(ticket):
assert not engine._pending_coda


@pytest.mark.parametrize("device", ["cpu", pytest.param("cuda", marks=pytest.mark.gpu)])
@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("multi_stream", [False, True])
def test_prelude_consumes_device_sample_before_cpu_delivery(monkeypatch, device, multi_stream):
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
)
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()
Expand Down
10 changes: 10 additions & 0 deletions tests/test_async_speculative.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,8 @@ 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")]
Expand All @@ -383,12 +385,20 @@ 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:])

Expand Down
111 changes: 111 additions & 0 deletions tests/test_cuda_graph.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Graph replay must update KV addresses, request identities and host progress."""

import gc
from types import SimpleNamespace

import pytest
import torch
Expand All @@ -22,6 +23,116 @@ 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"])
Expand Down
Loading
Loading