Skip to content

[FEAT][Dory/Huginn] Add three-stage staged prefill and loop-level batching (2A phase 2/4) - #208

Open
LyxWxj wants to merge 2 commits into
InferMatrixLab:mainfrom
LyxWxj:dory/pr-2a-prefill-coda
Open

LyxWxj wants to merge 2 commits into
InferMatrixLab:mainfrom
LyxWxj:dory/pr-2a-prefill-coda

Conversation

@LyxWxj

@LyxWxj LyxWxj commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Required human contributor answers

The contributor has identified Dory adaptation as the primary objective. The
answers and necessity decision below are proposed wording for contributor
review
, informed by RFC #176 and the implementation; they do not by themselves
complete the human-contributor gate. The contributor must confirm them and
provide a precise, accessible source for the confirmed answers and decision
before submission.

1. What outcome are you trying to achieve?

Enable the new Dory model to use staged chunked prefill while preserving its
attention-bearing PRELUDE and CODA semantics, including prompt CODA KV. This
increment adds the execution and scheduling foundations for per-request fixed
loop counts, loop-level batching, WCPB, and continuous admission/completion.
The broader RFC #176 PR 2A goal also includes ordinary mixed prefill/decode;
automatic batching of prompt and decode CODA remains a follow-up, as does
heterogeneous-loop atomic prefill.

Supporting context: RFC #176 PR 2A and the scope of this increment below.

2. What is the highest-leverage variable for that outcome?

A candidate highest-leverage variable is the runtime's correctly
schedulable Dory prefill frontier
: whether each prompt chunk can advance
through PRELUDE, the requested recurrent depths, and CODA while retaining the
correct hidden and KV state. This is a prerequisite for safely admitting new
requests, batching compatible loop depths, and overlapping independent work.
The present evidence concerns correctness of those mechanisms; it does not
establish a throughput improvement.

Supporting context: RFC #176 PR 2A and the frontier and lifetime design
described below; the choice of variable needs contributor confirmation.

3. How will this work move that variable rather than create busywork?

The change moves that variable directly in the runtime rather than adding only
model metadata or documentation:

  • requires_prefill_coda makes the model's stage contract explicit for Dory
    and Huginn.
  • PREFILLING_CODA, separate recurrent/CODA frontiers, and chunk reclamation
    make the scheduler advance only after the required causal work is complete.
  • Per-request fixed loop boundaries let Dory requests with different target
    depths share weights and compatible recurrent batches.
  • WCPB reuses the existing depth-frontier and ring-slot machinery, while
    row-aligned logits masks avoid projecting unused prompt rows.
  • Submission-owned hidden scratch plus request events preserve state lifetime
    when independent recurrent and CODA work uses different CUDA streams.

The focused CPU and A100 tests exercise these transitions, mixed depths,
selected logits, cancellation, multi-stream execution, and a real Dory
checkpoint. No performance improvement is claimed until matched serving
benchmarks are completed.

Supporting context: implementation and validation described in this draft;
RFC #176 PR 2A.

4. Who is the customer or user, and what do they actually need?

The likely users are maintainers and operators serving Dory through the common
vllm-rlt engine, and their downstream inference users. They need the engine to
preserve Dory's PRELUDE/recurrent/CODA computation, support fixed per-request
loop targets and concurrent requests, and retain the correct attention KV and
hidden state as chunks are interleaved. Downstream users need correct prompt and
decode outputs without managing internal scheduler phases or hidden-state ring
slots. Huginn also benefits because it has an attention-bearing prompt CODA,
but Dory is the primary adaptation target.

Supporting context: RFC #176 PR 2A and the implementation's model scope;
the customer and their priorities need contributor confirmation.

PR necessity and bugfix evidence

Proposed decision: yes, a PR is needed; contributor confirmation is pending.
The base runtime cannot provide the required staged Dory behavior merely by
changing configuration: it lacks the prompt-CODA phase and its associated
frontiers and hidden-state lifecycle.

Observed capability gap, reproduced locally: using the same tiny Dory
configuration, per-loop KV and mode="mixed", constructing a StageEngine
at base ce200f0d2085fb041c66691245e29aef2a9ed714 raises:

ValueError: boundary-KV models do not support staged prefill required by this scheduler

At head 965ac96f09fa8bc0aa4d961a80e01fe0cd4d626d, the same construction
succeeds with staged_prefill=True. The local
reproducer and
captured base/head output record the code
snapshots and observed result; these Git-ignored artifacts must be published or
attached before submission. Construction alone is not inference-correctness
evidence: the staged-versus-atomic tests and real-checkpoint checks listed
below provide additional, separately scoped coverage.

This is a feature adaptation, not a regression fix to a previously
supported Dory staged-prefill path. The cross-stream scratch experiment in
artifacts/dory-pr2-a100/stream-scratch-20261123.log is supporting evidence for
why submission-owned hidden buffers are required: with an intentionally
injected delay, a counterfactual shared-buffer alias corrupts an independent
request's input, while the implementation's separate buffers do not. It is not
presented as an observed failure in a previously supported production path.

Purpose

Dory and Huginn have attention-bearing output stages. A prompt chunk is not
finished when its final recurrent loop finishes: its output-stage attention
must also populate the CODA KV for that chunk. This change introduces that
causal phase into staged prefill and makes it usable with the existing WCPB and
loop-level scheduling machinery, while keeping the scope to synchronous eager
generation with per-loop KV and retained history.

What this increment changes

  • Declare requires_prefill_coda for Dory and Huginn and add the
    PREFILLING_CODA runtime phase. Models such as Ouro, which do not declare the
    capability, continue to finish a prompt chunk at the final recurrent depth.
  • Run the prompt PRELUDE, each required recurrent depth, and prompt CODA at
    their respective causal frontiers. Dory retains the injection input alongside
    the recurrent state across the loop calls.
  • Reuse the existing WCPB and depth-frontier machinery for ready chunks and
    mixed recurrent depths. Compatible prefill/decode recurrent spans may share
    a model call, and WCPB can also batch compatible prelude work. Continuous
    admission and completion remain supported.
  • On staged Dory requests in non-trace mode, accept a request-local fixed
    target_loops between 1 and total_ut_steps; when omitted, it defaults to
    total_ut_steps. Different target depths share model weights. Trace mode
    retains its separate trace-driven exit semantics. Huginn retains its existing
    loop/exit policy; this PR does not turn Huginn into a fixed-loop model.
  • Add row-selective CODA logits and sampling support and protect staged hidden
    inputs across different execution streams and in-flight submissions.

Design decisions and reviewer questions

1. Who advances chunk frontiers, and who owns hidden state?

The scheduler owns request queues and logical progress; ModelRunner owns the
device-resident hidden-state storage, gather/scatter, execution streams, and
completion events. The scheduler distinguishes:

prefill_reclaimable_tokens <= num_prefilled_tokens
    <= num_recurrent_prefilled_tokens <= num_preluded_tokens <= prompt_length

For models requiring prompt CODA, num_recurrent_prefilled_tokens is the
contiguous final-recurrent-depth frontier and num_prefilled_tokens is the
contiguous CODA frontier. A chunk's prefill_reclaimable_tokens boundary moves
only when the whole chunk passes its final required stage. These are logical
frontiers; device consumers are ordered by events rather than assumed complete
merely because the host has submitted them.

2. Why a model capability instead of a per-model terminal-phase enum?

requires_prefill_coda expresses the model behavior that drives the extra
stage. The shared scheduler and executor use it to select the completion and
retention behavior; models do not each provide a separate prefill-terminal
phase. This also covers Huginn's existing attention-bearing CODA instead of
introducing a Dory-only path. Without the capability, final recurrent completion
remains the prompt-chunk completion boundary.

3. When are logits calculated, and what about mixed CODA?

All eligible prompt rows execute attention-bearing CODA so their KV history is
valid. Non-final prompt rows do not need logits or samples; the final prompt
row produces the first output token directly in PREFILLING_CODA. It does
not require a redundant ordinary CODA just to sample that token.

ForwardBatch.compute_logits accepts either a uniform boolean or a row-aligned
boolean mask. For a chunk-bearing CODA batch, only the last row of a final
prompt span and ordinary decode CODA rows are selected. Sparse results are
mapped back to the appropriate request spans. Tests exercise mixed
PREFILLING_CODA/CODA execution by explicitly selecting both phases;
automatic scheduling of those two phases into one batch is not implemented
and remains a later increment. Existing ordinary CODA behavior is preserved.

4. How are WCPB chunk offsets and hidden-state lifetime handled?

WCPB maps a logical chunk to a per-request ring slot relative to
prefill_window_origin:

chunk_index = (chunk_start - origin) // chunk_size
slot = chunk_index % len(request.prefill_depth_ranges)
hidden_row_offset = slot * chunk_size + (token_start - chunk_start)

CODA reads only rows that have passed the final recurrent frontier and does not
cross the chunk boundary. Partial chunks retain their slot until CODA consumes
the whole chunk. prefill_states is the cross-stage per-request store;
BatchInputBuffers.hidden is submission-local, contiguous model input gathered
from those rows and, for mixed batches, ordinary request.hidden_state rows.
Physical staged storage is currently reserved using
prefill_chunk_size * total_ut_steps rows per request; the ring's logical slot
count for fixed-depth Dory follows that request's target loop count. Although
the ring formula has an origin, boundary-KV prefix caching is still rejected.

5. Why does each in-flight batch own its hidden scratch?

With multi_stream=True, recurrent submissions use the core stream and prompt
CODA uses the boundary stream. For the same request, the next submission
waits for the preceding request event. For different requests, a CODA batch
and a recurrent batch may overlap; request-local dependencies do not protect a
single scratch tensor shared by both. Before this change, ordinary decode CODA
read request hidden state through its own gather/workspace path, not the
staged-prefill scratch.

The prior single ModelRunner.prefill_hidden is therefore replaced by
submission-owned BatchInputBuffers.hidden buffers. They rotate with the
existing two submission slots, and a slot is not reused until its consumer
event has retired. This preserves inter-request overlap without treating the
scratch buffer as long-lived request state. The additional allocated scratch
relative to the old single-buffer design is one batch-sized hidden tensor;
there is no throughput claim without a matched benchmark.

6. What happens when atomic prefill requests have different loop counts?

This increment supports differing request targets for staged Dory prefill.
Ordinary atomic prefill still rejects a Dory request target below the model's
configured full depth; it does not silently run all requests to the wrong
depth. Handling mixed request targets inside one atomic prefill batch remains a
follow-up. target_loops is not a general adaptive exit mechanism.

Scope and limitations

  • Qualified Dory/Huginn staged path: synchronous eager, per-loop KV, retained
    full history. Multi-stream execution is separate from asynchronous
    scheduling and remains event-ordered.
  • Boundary-KV staged prefill combined with CUDA Graphs, asynchronous scheduling,
    preemption, speculation, prefix reuse, shared/last-loop KV, or PD handoff is
    not qualified and is rejected where the runtime enforces that restriction.
    Ordinary non-staged capabilities are not claimed as coverage for these
    combinations.
  • Automatic mixing of prompt and decode CODA, heterogeneous target depths in
    atomic prefill, hybrid KV reclamation, complete-state prefix reuse, and
    long-context qualification remain outside this increment.
  • This is a functionality/correctness increment, not a demonstrated performance
    improvement. The required matched unprofiled serving benchmarks, ops-only and
    full profiles, bottleneck attribution, and post-implementation refactor
    review have not been completed.

Test Plan

vllm-rlt Version / Commit:

  • Head tested: 965ac96f09fa8bc0aa4d961a80e01fe0cd4d626d.
  • Base checked: ce200f0d2085fb041c66691245e29aef2a9ed714 (origin/main),
    fetched again on 2026-11-23; it is already an ancestor of the tested head.
  • Local CPU environment: Python 3.10 and PyTorch 2.14.0+cu130, project
    virtual environment, OMP_NUM_THREADS=1.
  • GPU environment: one A100 80GB PCIe, driver 590.48.01, Python 3.12.13,
    PyTorch 2.13.0+cu130, Triton 3.7.1; one explicitly selected device.

Commands run on the tested head:

export OMP_NUM_THREADS=1 PYTHONPATH="$PWD"
python -m ruff check .
pre-commit run --all-files
python -m pytest -q -m 'not gpu and not npu' \
  tests/test_prefill_coda.py tests/test_submission_queue.py tests/test_dory.py \
  tests/test_huginn.py tests/test_split_prefill.py

# Set CUDA_VISIBLE_DEVICES to the assigned device and DORY_CHECKPOINT to the
# local 4B BF16 checkpoint before running the GPU checks.
python -m pytest -q --run-gpu -s \
  tests/test_dory_gpu.py::test_staged_prefill_fixed_depths_match_cpu_oracle \
  tests/test_dory_gpu.py::test_staged_bfloat16_prefill_matches_atomic_cuda \
  tests/test_huginn.py::test_huginn_staged_prefill_matches_atomic_cuda \
  tests/test_dory_real_checkpoint.py::test_real_checkpoint_staged_mixed_depths_match_atomic

The CPU hook does not qualify CUDA/NPU paths. The focused GPU run uses an
isolated source snapshot of the tested commit; the shared host did not have the
gpu reservation utility, so the selected A100 was checked idle first.

Test Result

  • python -m ruff check .: passed.
  • pre-commit run --all-files: Ruff lint, Ruff format, and the CPU regression
    hook passed. GPU/NPU-marked tests were not enabled in that hook.
  • Focused CPU regression above: 178 passed, 43 deselected.
  • Focused A100 run above: 17 passed. It covers Dory and Huginn staged
    prefill, WCPB on/off, multi-stream variations, and the real-checkpoint mixed
    fixed-depth comparison.
  • An earlier broader regression on the same head recorded 1,343 CPU passed,
    35 skipped, 895 deselected
    , and 43 focused GPU passed. No Ascend/NPU
    hardware test was run.
  • Real checkpoint: local Dory1.0-4B-BF16, model.safetensors SHA-256
    207483664dfef54c4c4438863260d3ba423bf3d6009b43fe84264b281e9fda23;
    checkpoint revision was not independently verified. With five- and ten-token
    prompts, chunk size 2, target depths 1 and 2, and three greedy tokens, mixed
    and WCPB outputs/depths match independent atomic-chunk runs. Reference top-20
    logit overlap is 20/20 for the shallow request and 19/20 for the full
    request; the largest reported top-20 difference is 0.1500. This is a
    runtime-to-runtime comparison, not an independent quality benchmark.
  • Cross-stream scratch diagnostic: with tiny FP32 Dory and an intentionally
    delayed B recurrent submission, A's prompt-CODA gather completed while B was
    still in flight. The current separate buffers preserved B's input exactly;
    forcing the two scratch tensors to alias in the diagnostic changed B's input
    (maximum absolute difference 0.5827). This counterfactual is not a
    production configuration or a model-quality result.

The local run logs and the scratch diagnostic script are under the Git-ignored
artifacts/dory-pr2-a100/; the precision investigation and raw measurements
are under artifacts/dory-pr2-a100/numeric-investigation/. They must be made
accessible to reviewers before the PR is submitted.

Numerical precision investigation

The same local BF16 checkpoint was compared on A100 with chunk size 2. The
FP32 comparison converts the stored BF16 weights to FP32; it is not an original
FP32 checkpoint. Maximum differences below are on the reference top-20
logits
, not all vocabulary rows:

Prompt / comparison BF16 max top-20 difference FP32 max top-20 difference
10-token mixed staged vs atomic chunk 0.1500 0.0000076
41-token repeated-text mixed staged vs atomic chunk 0.4015 0.0000048

Both comparisons keep the first greedy token in this small diagnostic. For the
41-token BF16 case, however, full-vocabulary maximum difference is 0.5827
and softmax total variation is 0.0563; matching argmax is not distributional
equivalence. The existing automated 0.25 top-20 bound applies to its specific
10-token test and is not established as a universal tolerance.

In the 10-token mixed case, the first differing activation is a PRELUDE
o_proj output: input, weights, attention output and K/V for the inspected row
are equal, while changing only the BF16 matrix row count from 2 to 4 reproduces
991 differing output elements. Disabling reduced-precision BF16 reduction
improves that individual projection, but does not consistently improve the
final distribution across staged and WCPB cases; no global precision switch or
test-tolerance relaxation is proposed. This evidence explains a contribution to
the discrepancy, not all possible scheduling/KV errors.

Remaining before submission

  • The contributor must review and explicitly confirm the proposed answers and
    PR-necessity decision, and provide a precise, accessible source for them.
  • Attach or publish the local, Git-ignored raw test and diagnostic artifacts so
    reviewers can access them; reproduce on the final PR head if it changes.
  • Define and run a broader paired Dory precision/quality protocol, including
    multi-position teacher forcing and sliding-window boundaries; the 10-prompt
    smoke test is not a model-quality estimate.
  • Complete the required performance analysis and refactoring/code-quality
    review, or explicitly resolve their outstanding scope with the maintainers.

Signed-off-by: LyxWxj <yuxuanlou621@foxmail.com>
Signed-off-by: LyxWxj <yuxuanlou621@foxmail.com>
@LyxWxj LyxWxj changed the title [FEAT][Dory/Huginn] Add three-stage staged prefill and loop-level batching [FEAT][Dory/Huginn] Add three-stage staged prefill and loop-level batching (2A phase 2/4) Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant