Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions docs/packed-prefill-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
# Packed Multi-Request Prefill

Packed multi-request prefill extends `GraphKind::Prefill` and
`GraphKind::TerminalPrefill` additively within `ModelContract` version 3 so
concurrent short or warm-prefix text prompts execute together in one CUDA graph
replay (`batch_capacity >= 2`). Single-request prefill graphs (`batch_capacity == 1`,
`packed_token_capacity == 0`) remain unchanged.

## 1. Problem

Solo prefill graphs (`batch_capacity == 1`) require one full forward replay per
request, regardless of how many uncached prompt tokens that request contributes.
`GraphKind::Mixed` overlaps one prefill request with decode lanes, but still
admits at most one prefill request per step.

On memory-bandwidth-bound hardware such as four NVIDIA GB10 GPUs running
DeepSeek V4.1 Flash at tensor-parallel degree 4 (TP4), reading MoE expert
weights dominates feed-forward layer latency up to roughly 512–1,024 tokens:

- **Conditions:** Single NVIDIA GB10 (SM121), DeepSeek V4.1 Flash layer 3 TP4
shard, uncompressed native-scale checkpoint, CUDA-graphed serial router plus
routed and shared experts, median of 7 interleaved timing passes.
- **Measurements:**
- `64` rows: `3,947.3 µs/layer` (`61.7 µs/token`)
- `128` rows: `5,000.0 µs/layer` (`39.1 µs/token`)
- `256` rows: `5,629.1 µs/layer` (`22.0 µs/token`)
- `512` rows: `6,619.4 µs/layer` (`12.9 µs/token`)
- `1,024` rows: `7,625.4 µs/layer` (`7.45 µs/token`)
- **Conclusion:** Processing 16 concurrent 64-token warm-prefix turns serially
in solo prefill graphs costs roughly `16 × 3.95 ms = 63.2 ms/layer` in
feed-forward execution alone, whereas packing the same 1,024 tokens into one
replay costs `7.63 ms/layer` (`8.3×` lower per-layer FFN latency). Across full
serving bursts of 4–16 concurrent short prompts or shared-prefix tool turns,
single-request prefill serialization inflates p95/p99 time to first token
(TTFT) by an estimated `3–6×` with no mathematical necessity.

## 2. Architecture Summary

| Layer | Location | Packed Prefill Behavior |
|---|---|---|
| Helios manifest & catalog | `helios/src/execution/manifest.rs`, `helios/src/model/catalog.rs`, `helios/src/runtime_core/selection.rs` | Accepts `GraphKind::Prefill` and `GraphKind::TerminalPrefill` with `B >= 2`, `1 <= W_req <= P`, 64-aligned `P` (`max(64, B) <= P <= B * W_req`, `P <= prefill_chunk_size`, `draft_tokens == 0`), keeping `ScoredPrefill` and `B == 1` prefill unchanged and dropping `B >= 2` graphs when `--max-concurrency 1`. |
| Helios input packing | `helios/src/model/packing.rs` | Rejects vision bindings (`ImageFeatureSlot`, `ImageFeatureIndex`, `ImageLeftContext`, `ImageRightContext`) on `B >= 2` prefill graphs, sizes `InputIndexing::PackedToken` inputs to `P`, enforces `lane.tokens <= W_req` and `sum(lane.tokens) <= P`, and packs per-lane `QueryLength` and `SampleEnabled`. |
| Helios scheduler & cost model | `helios/src/scheduler.rs`, `helios/src/scheduler/cost.rs`, `helios/src/scheduler/policy.rs`, `helios/src/scheduler/checkpoints.rs` | Indexes packed `(kind, B, W_req, P)` shapes with `ReplayTimes` cost tracking, packs two or more text-only prefill lanes greedily by marginal value rate (with `Init`/`Restore` continuation valuation and padding pruning), and tracks non-terminal vs. terminal packed steps across checkpoints. |
| Ignition graph signatures | `ignition/preparation/execution.py`, `ignition/direct/scheduler.py` | Validates `(B >= 2, W_req, P)` prefill and `terminal_prefill` signatures, forbids vision bindings on packed prefill signatures, and keeps direct-mode solo prefill catalogs isolated from `B >= 2` packed graphs. |
| Recipe batch & draft components | `hyperflare_recipes/components/paged_batch.py`, `hyperflare_recipes/components/dspark.py` | `PreparedBatch` and `RotaryBatch` validate and pack `B >= 2` text-only prefill rows (`0 < lengths[i] <= W_req`, `sum(lengths) <= P`) with per-row rotary offset commits; `PreparedFeedbackCapture` and `PreparedContext` retain all `P` rows when `rows > 1`. |
| DeepSeek V4.1 recipe (`local-inference-lab/hyperflare-recipes#153`) | `hyperflare_recipes/recipes/deepseek41/{recipe,bootstrap,decoder}.py` | Adds `--packed-prefill` / `--no-packed-prefill` preparing compact text-only `terminal_prefill` shapes (`W_req <= 256`, `P <= 2048`), executing all 40 layers without `PreparedDecoderSuffix` truncation and sizing DMA/RoCE gather buffers accordingly. |

## 3. Shared Helios Contract

All runtime, packing, and scheduling behavior is derived strictly from declared
graph capacities and input bindings. No per-model Helios runtime flags,
capability booleans, or recipe allowlists are introduced.

### 3.1 Graph Descriptor Geometry

Reuse the three physical extent fields already defined in `helios/model-contract.md`
for packed speculative graphs:

- `batch_capacity` (`B`): maximum number of prefill requests packed into one
replay (`B >= 2`).
- `token_capacity` (`W_req`): maximum prompt tokens contributed by any single
active lane (`1 <= len_i <= W_req`).
- `packed_token_capacity` (`P`): aggregate packed prompt token rows across all
`B` lanes (`B <= P <= B * W_req`, 64-aligned).

Single-request prefill graphs (`B == 1`) retain their existing geometry
(`packed_token_capacity == 0`, `token_capacity == chunk_size`) without semantic
change.

### 3.2 Input Bindings and Binding-Derived Eligibility

- Packed prefill graphs (`B >= 2`) bind `ValueSource::PromptToken` and
`ValueSource::PromptPosition` with `InputIndexing::PackedToken` across `P`
rows, and bind `ValueSource::QueryLength`, `ValueSource::SampleEnabled`,
`ValueSource::RequestSlot`, `ValueSource::RequestGeneration`,
`ValueSource::LiveStateRows`, and `ValueSource::PageTable` per request or
submission row, matching the packing model used by `GraphKind::Mixed` and
`GraphKind::Speculative`.
- When `graph.kind.is_prefill()` and `graph.packed_token_capacity > 0`,
`helios/src/model/packing.rs` uses `graph.packed_token_capacity` as the
`InputIndexing::PackedToken` extent and enforces `lane.tokens <= graph.token_capacity`
per active lane and `sum(lane.tokens) <= graph.packed_token_capacity` across
the batch.
- Packed prefill graphs (`B >= 2`) omit `ValueSource::ImageFeatureSlot` and
other vision bindings. Helios derives text-only eligibility strictly from the
absence of vision bindings on the candidate graph: requests with pending image
features or prompt-logprob requirements continue using solo `B == 1` prefill
graphs without model-specific checks.
- `GraphKind::TerminalPrefill` with `B >= 2` emits one sampled output record per
lane with `SampleEnabled == 1`, matching `GraphKind::Decode` and
`GraphKind::Speculative` completion handling. Inactive lanes carry
`QueryLength == 0` and `SampleEnabled == 0` and do not mutate cache state.

### 3.3 Shared Scheduler Integration

- `helios/src/scheduler/cost.rs` and `helios/src/scheduler/policy.rs` index
packed prefill shapes `(kind, B, W_req, P)` discovered directly from the
loaded `ExecutionManifest`.
- When two or more admitted text-prefill requests are runnable (no unresolved
vision prerequisite and no prompt-logprobs requirement), the policy constructs
packed cohorts greedily by marginal value rate subject to `lane_work_i <= W_req`
and `sum(lane_work_i) <= P`.
- Packed prefill candidates compete on the same age-priced value-rate objective
against solo `Prefill(1, C)`, `Decode`/`Speculative`, and `Mixed` candidates.
Single long prompts continue selecting solo `B == 1` prefill chunks, while
concurrent short or warm-prefix bursts coalesce into packed `(B, W_req, P)`
replays.
- KV page reservation, continuation state-row reservation, prefix-cache lookup,
preemption, and partial cancellation apply identically across every
participating lane and every supported cache scheme.

## 4. Recipe Integration (DeepSeek V4.1)

- **Shared batch and draft components (`hyperflare_recipes/components/`):**
- `PreparedBatch` (`paged_batch.py`) supports `mode == "prefill"` with
`rows >= 2` for text-only packed graphs (`validate_prefill is None`),
validating per-lane `0 < lengths[i] <= W_req` and `sum(lengths) <= P` and
committing per-row rotary offsets in `RotaryBatch`.
- `PreparedFeedbackCapture` and `PreparedContext` (`dspark.py`) retain all
`P` rows directly when `rows > 1`, preserving per-lane feedback without
single-lane suffix truncation.
- **DeepSeek V4.1 (`hyperflare_recipes/recipes/deepseek41/`):**
- `PreparedCompressor`, `PreparedCompressedMLA` (`mode="extend"`),
`PreparedMXFP4Indexer` (`mode="prefill"`), `PreparedTableRequests`, and
`_commit_window` index per-lane rows from `starts.numel()`.
- Restricting packed `TerminalPrefill` shapes to `W_req <= 256` and
`P <= 2,048` executes all 40 layers directly without `PreparedDecoderSuffix`
bounded-replay approximation, preserving numerical parity with serial solo
prefill.
- Per-layer `window_cache` allocation scales as `(B, (128 + W_req) * 528)`
bytes (shared across layers via `layer_buffers.fork()`), requiring `2.16 MiB`
at `B = 16, W_req = 128`.
- Enabling `--packed-prefill` prepares up to six text-only `TerminalPrefill`
shapes filtered to the configured `max_concurrency` and `prefill_chunk_size`:
`(B=4, W_req=128, P=512)`, `(4, 256, 1024)`, `(8, 128, 1024)`,
`(8, 256, 2048)`, `(16, 128, 1024)`, and `(16, 128, 2048)` (or `(2, 128, 256)`
when `max_concurrency` is 2 or 3).

## 5. Compatibility and Validation

- **Additive `ModelContract` version 3:** Single-request prefill descriptors
(`B == 1`) retain `packed_token_capacity == 0`. Older runtimes reject
`batch_capacity != 1` prefill descriptors at catalog validation, and models
without `B >= 2` prefill graphs run single-request prefill unchanged.
- **Validation coverage:**
- Helios manifest, catalog, selection (`--max-concurrency` filtering), input
packing (vision binding rejection and multi-lane `QueryLength` /
`SampleEnabled` / `PackedToken` layout), and scheduler policy tests
(concurrent bursts, solo `B == 1` preservation, mixed finishing and
continuing lanes, `B * W_req > P` budget packing, vision and
`prompt_logprobs` isolation, unmeasured discovery, and padding pruning).
- Ignition `GraphSignature` validation and manifest serialization tests.
- Recipe parameter, catalog, `PreparedBatch` / `RotaryBatch` CUDA graph
validation, and NVIDIA GB10 multi-lane numerical parity tests against
serial solo prefill.
24 changes: 15 additions & 9 deletions docs/scheduling-runtime-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ only for decode rounds, and it estimates graph costs with a 7/8 moving average
that reverts to unmeasured after 30 seconds. The duration estimates, funded
refresh, and acceptance learning specified below describe Helios alone.

The native catalog contains prefill, terminal prefill, scored prefill, ordinary
decode, complete speculative generation, mixed prefill/generation, vision, and
state operations.
The native catalog contains solo and optional packed multi-request prefill,
terminal prefill, scored prefill, ordinary decode, complete speculative
generation, mixed prefill/generation, vision, and state operations (see
[`packed-prefill-design.md`](packed-prefill-design.md) for packed multi-request
prefill).
A complete speculative graph contains proposal generation, optional confidence
and prefix allocation, target verification, and accepted-state commit. Proposal
and verification are internal stages, not independently scheduled operations.
Expand Down Expand Up @@ -453,8 +455,9 @@ cancellation paths preserve fenced resource ownership regardless of utility.
Each prepared graph descriptor has one `estimated_duration_ns` field. Native
estimates start at zero, including descriptors supplied with a nonzero value.
Zero means indeterminate. Physical graph kind, batch capacity, token capacity,
proposal depth, mixed prefill capacity, and packed verification capacity identify
a cost entry; active row count does not change its identity.
proposal depth, mixed prefill capacity, and packed token capacity (packed
verification or packed multi-request prefill) identify a cost entry; active row
count does not change its identity.

Every selected complete speculative program enters the cost catalog with its
actual B/D/W/P. A smaller captured producer is a distinct physical program;
Expand All @@ -463,10 +466,13 @@ metadata must not relabel it as a deeper producer.
The first positive device observation sets the estimate. For non-prefill
graphs, further valid samples while fresh use the median of the last nine
replay observations, averaging the middle pair when fewer than nine samples give
an even count. For pure prefill graphs (`PREFILL`, `TERMINAL_PREFILL`, and
`SCORED_PREFILL`), samples are stratified across six fill-ratio and KV-context
depth buckets (`u <= 0.5` vs `u > 0.5` crossed with `< 4096`, `4096..32768`,
and `>= 32768` starting tokens), each retaining a nine-sample rolling median.
an even count. For solo (`batch == 1`) pure prefill graphs (`PREFILL`,
`TERMINAL_PREFILL`, and `SCORED_PREFILL`), samples are stratified across six
fill-ratio and KV-context depth buckets (`u <= 0.5` vs `u > 0.5` crossed with
`< 4096`, `4096..32768`, and `>= 32768` starting tokens), each retaining a
nine-sample rolling median. Packed multi-request prefill graphs (`batch >= 2`)
use the same flat nine-sample rolling median as non-prefill graphs rather than
single-lane context stratification.
Predictions fit a three-parameter nonnegative linear model
`theta_0 + theta_1 * u + theta_2 * u * (start_position / 4096)` by exact
relative-error-weighted nonnegative least squares over populated stratum
Expand Down
10 changes: 8 additions & 2 deletions helios/manifest.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,14 @@ A mixed graph has a batch capacity from 2 through the request
storage capacity, W from 1 through T, and a `prefill_capacity` that is a positive
multiple of 64. It binds the `int32[1]` `prefill_row` input. Every other kind
sets `prefill_capacity` to zero.
Prefill, terminal prefill, and scored prefill have batch capacity 1. Their token capacities are 1,
16, or a positive multiple of 64. The model configuration separately requires the captured
A `prefill` or `terminal_prefill` graph may optionally declare packed
multi-request execution with batch capacity B from 2 through the request storage
capacity, per-request token capacity W (`1 <= W <= P`), `draft_tokens == 0`, and
64-aligned `packed_token_capacity` P (`max(64, B) <= P <= B × W`,
`P <= prefill_chunk_size`). Single-request `prefill`, `terminal_prefill`, and
`scored_prefill` graphs have batch capacity 1, `packed_token_capacity == 0`, and
token capacities of 1, 16, or a positive multiple of 64. The model configuration
separately requires the captured
catalog for its `prefill_chunk_size`; transport validation does not infer a
scheduling policy or substitute a missing graph.
State operations
Expand Down
23 changes: 23 additions & 0 deletions helios/model-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,29 @@ smaller `PREFILL` graphs execute complete continuation state. When a model
declares no `TERMINAL_PREFILL` graphs, or omits a capacity from the terminal
catalog, Helios falls back to `PREFILL` with no contract version change.

### Optional packed multi-request prefill

Under contract version 3, a prepared model may additionally declare multi-request
`PREFILL` and `TERMINAL_PREFILL` graphs with `batch_capacity` B ≥ 2 (within the
prepared request capacity), per-request token capacity W (`1 <= W <= P`), and an
explicit 64-aligned `packed_token_capacity` P (`max(64, B) <= P <= B × W`,
`P <= prefill_chunk_size`, `draft_tokens == 0`). Single-request prefill graphs
(`B == 1`) retain `packed_token_capacity == 0`, and `SCORED_PREFILL` remains
`B == 1`.

Packed prefill graphs are text-only: shared contract validation forbids scalar
`IMAGE_FEATURE_SLOT` and packed `IMAGE_FEATURE_INDEX`, `IMAGE_LEFT_CONTEXT`, and
`IMAGE_RIGHT_CONTEXT` bindings when `B >= 2`. `PACKED_TOKEN` inputs cover P
rows. Shared packing populates per-lane `QUERY_LENGTH` and `SAMPLE_ENABLED`
(enabling sampling independently for each lane reaching the end of its prompt),
packs active lane prompt tokens and positions contiguously within P rows, and
rejects image-conditioned lanes or token sums exceeding P. Helios schedules
packed prefill through the shared value-rate policy whenever at least two
text-only prefill requests fit a prepared `(B, W, P)` shape; single-request
prompts, vision requests, and prompt-logprob requests remain on `B == 1` graphs.
When a model declares no `B >= 2` prefill graphs, Helios executes single-request
prefill with no contract version change.

### Complete speculative generation

`SPECULATIVE` is one complete captured generation operation: proposal generation,
Expand Down
1 change: 1 addition & 0 deletions helios/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! Fixed-capacity graph execution over two pinned transport frames.

mod manifest;
pub(crate) use manifest::valid_packed_prefill_geometry;
mod parallel;
mod rank_stream;
mod ranks;
Expand Down
Loading
Loading