diff --git a/docs/packed-prefill-design.md b/docs/packed-prefill-design.md new file mode 100644 index 000000000..bf20c45c5 --- /dev/null +++ b/docs/packed-prefill-design.md @@ -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. diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index e8211498c..b44bc4f76 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -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. @@ -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; @@ -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 diff --git a/helios/manifest.md b/helios/manifest.md index adb4cb468..d02c6bd79 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -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 diff --git a/helios/model-contract.md b/helios/model-contract.md index 3722a9e6d..988272c5e 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -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, diff --git a/helios/src/execution.rs b/helios/src/execution.rs index bf7544175..abafe2d9b 100644 --- a/helios/src/execution.rs +++ b/helios/src/execution.rs @@ -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; diff --git a/helios/src/execution/manifest.rs b/helios/src/execution/manifest.rs index b540202ee..b56b1ad80 100644 --- a/helios/src/execution/manifest.rs +++ b/helios/src/execution/manifest.rs @@ -446,6 +446,27 @@ pub struct ExecutionManifest { pub persistent_workers: Vec, } +/// Shared geometry check for Contract 3 packed multi-request prefill (`Prefill` / `TerminalPrefill`, +/// `batch >= 2`). Enforces `2 <= batch <= max_batch`, `1 <= width <= packed`, 64-aligned `packed` +/// within `[max(64, batch), min(batch * width, i32::MAX)]`, and optional `packed <= max_chunk`. +pub(crate) fn valid_packed_prefill_geometry( + batch: usize, + width: usize, + packed: usize, + max_batch: usize, + max_chunk: Option, +) -> bool { + (2..=max_batch).contains(&batch) + && width > 0 + && width <= packed + && packed >= batch + && packed <= batch.saturating_mul(width) + && packed >= 64 + && packed.is_multiple_of(64) + && packed <= i32::MAX as usize + && max_chunk.is_none_or(|chunk| packed <= chunk) +} + impl ExecutionManifest { fn validate_persistent_workers(&self) -> Result<()> { if self.persistent_workers.len() > 1 { @@ -850,13 +871,32 @@ impl ExecutionManifest { for graph in &self.graphs { if graph.kind == GraphKind::Speculative { if graph.packed_token_capacity < graph.batch_capacity - || graph.packed_token_capacity > graph.batch_capacity.saturating_mul(graph.token_capacity) + || graph.packed_token_capacity + > graph.batch_capacity.saturating_mul(graph.token_capacity) || graph.draft_tokens > self.completion_token_capacity - 1 - || (graph.token_capacity == 1 && graph.draft_tokens != 0) { + || (graph.token_capacity == 1 && graph.draft_tokens != 0) + { return Err("speculative B/D/W/P geometry is invalid".into()); } + } else if matches!(graph.kind, GraphKind::Prefill | GraphKind::TerminalPrefill) + && graph.batch_capacity >= 2 + { + if graph.draft_tokens != 0 + || !valid_packed_prefill_geometry( + graph.batch_capacity, + graph.token_capacity, + graph.packed_token_capacity, + self.request_capacity(), + None, + ) + { + return Err("packed prefill B/W/P geometry is invalid".into()); + } } else if graph.packed_token_capacity != 0 || graph.draft_tokens != 0 { - return Err("draft depth and target rows require a speculative operation".into()); + return Err( + "draft depth and target rows require a speculative or packed prefill operation" + .into(), + ); } if graph.confidence_width > 0 { let confidence = self.buffer("proposal_confidence")?; @@ -893,7 +933,17 @@ impl ExecutionManifest { (1..=self.request_capacity()).contains(&graph.batch_capacity) && (1..=self.completion_token_capacity).contains(&graph.token_capacity) } - GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => { + GraphKind::Prefill | GraphKind::TerminalPrefill => { + if graph.batch_capacity == 1 { + [1, 16].contains(&graph.token_capacity) + || (graph.token_capacity >= 64 + && graph.token_capacity.is_multiple_of(64)) + } else { + // `batch_capacity >= 2` packed prefill geometry was validated above. + graph.batch_capacity >= 2 + } + } + GraphKind::ScoredPrefill => { graph.batch_capacity == 1 && ([1, 16].contains(&graph.token_capacity) || (graph.token_capacity >= 64 diff --git a/helios/src/execution/tests.rs b/helios/src/execution/tests.rs index cf9bcb772..91c471d64 100644 --- a/helios/src/execution/tests.rs +++ b/helios/src/execution/tests.rs @@ -1402,3 +1402,42 @@ fn persistent_worker_manifest_validation_enforces_handles_alignment_and_cardinal ); } } + +#[test] +fn packed_prefill_manifest_validation_enforces_geometry_and_excludes_scored_prefill() { + for kind in [GraphKind::Prefill, GraphKind::TerminalPrefill] { + for (batch, width, packed) in [(2, 128, 128), (4, 128, 512), (4, 256, 512)] { + let mut value = manifest(); + value.graphs[0].kind = kind; + value.graphs[0].batch_capacity = batch; + value.graphs[0].token_capacity = width; + value.graphs[0].packed_token_capacity = packed; + value.graphs[0].draft_tokens = 0; + value.validate().unwrap(); + assert_eq!(value.graphs[0].packed_tokens(), packed); + } + } + let bad_cases = [ + (GraphKind::Prefill, 1, 128, 128, 0), // B == 1 forbids nonzero packed_token_capacity + (GraphKind::TerminalPrefill, 1, 128, 128, 0), // B == 1 forbids nonzero packed_token_capacity + (GraphKind::Prefill, 4, 128, 0, 0), // B >= 2 requires explicit P + (GraphKind::Prefill, 4, 128, 96, 0), // P must be 64-aligned + (GraphKind::Prefill, 4, 128, 32, 0), // P < 64 + (GraphKind::Prefill, 4, 256, 128, 0), // W > P + (GraphKind::Prefill, 4, 64, 320, 0), // P > B * W + (GraphKind::Prefill, 4, 128, 512, 1), // draft_tokens must be 0 + (GraphKind::ScoredPrefill, 4, 128, 512, 0), // ScoredPrefill stays B == 1 + ]; + for (kind, batch, width, packed, drafts) in bad_cases { + let mut value = manifest(); + value.graphs[0].kind = kind; + value.graphs[0].batch_capacity = batch; + value.graphs[0].token_capacity = width; + value.graphs[0].packed_token_capacity = packed; + value.graphs[0].draft_tokens = drafts; + assert!( + value.validate().is_err(), + "expected invalid packed prefill ({kind:?}, B={batch}, W={width}, P={packed}, D={drafts}) to fail" + ); + } +} diff --git a/helios/src/model/catalog.rs b/helios/src/model/catalog.rs index 53b395e1c..e1e1f3f7a 100644 --- a/helios/src/model/catalog.rs +++ b/helios/src/model/catalog.rs @@ -263,8 +263,25 @@ pub fn select_shape_with_drafts( speculative_shape(config, batch, tokens) } } - GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => { + GraphKind::Prefill | GraphKind::TerminalPrefill => { + if batch == 1 { + packed == 0 + && tokens > 0 + && tokens <= config.limits.prefill_chunk_size + && tokens.is_multiple_of(64) + } else { + crate::execution::valid_packed_prefill_geometry( + batch, + tokens, + packed, + usize::MAX, + Some(config.limits.prefill_chunk_size), + ) + } + } + GraphKind::ScoredPrefill => { batch == 1 + && packed == 0 && tokens > 0 && tokens <= config.limits.prefill_chunk_size && tokens.is_multiple_of(64) diff --git a/helios/src/model/packing.rs b/helios/src/model/packing.rs index 217909f76..7fc7b36f4 100644 --- a/helios/src/model/packing.rs +++ b/helios/src/model/packing.rs @@ -111,15 +111,19 @@ impl Inputs { } LiveRows | PrefillRow => binding.indexing == Scalar, ImageFeatureSlot => binding.indexing == Scalar && elements == 1 - && matches!(graph.kind, GraphKind::Vision | GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill | GraphKind::Mixed), + && (matches!(graph.kind, GraphKind::Vision | GraphKind::Mixed) + || (graph.kind.is_prefill() && graph.batch_capacity == 1)), PageTable | LiveStateRows => binding.indexing == RequestRow, PromptToken | PromptTargetToken | PromptLookaheadToken | PromptAndPendingToken - | PromptPosition - | ImageFeatureIndex + | PromptPosition => binding.indexing == PackedToken, + ImageFeatureIndex | ImageLeftContext - | ImageRightContext => binding.indexing == PackedToken, + | ImageRightContext => { + binding.indexing == PackedToken + && !(graph.kind.is_prefill() && graph.batch_capacity >= 2) + } PendingToken => matches!(binding.indexing, SubmissionRow | PackedToken), Constant => binding.indexing != PackedToken, RequestSlot | RequestGeneration if graph.kind == GraphKind::Vision => { @@ -166,6 +170,8 @@ impl Inputs { let rows = if graph.kind == GraphKind::Mixed { graph.prefill_capacity + (graph.batch_capacity - 1) * graph.token_capacity + } else if graph.packed_token_capacity != 0 { + graph.packed_token_capacity } else if graph.kind.is_prefill() { graph.token_capacity } else { @@ -413,6 +419,24 @@ impl Inputs { && g.prefill == frame.step.prefill_capacity() }) .ok_or("submission has no resolved packing plan")?; + if graph.kind.is_prefill() && graph.batch >= 2 { + let mut total_tokens = 0usize; + for lane in &frame.step.lanes { + if lane.tokens > graph.tokens { + return Err("packed prefill lane exceeds per-request token capacity".into()); + } + let live = frame.scheduler.request(lane.request)?; + if live.image_slot.is_some() { + return Err("packed prefill graph does not support image-conditioned lanes".into()); + } + total_tokens = total_tokens + .checked_add(lane.tokens) + .ok_or("packed prefill token sum overflow")?; + } + if total_tokens > graph.packed_tokens { + return Err("packed prefill lanes exceed packed token capacity".into()); + } + } self.staging.clear(); // Only retain cached bytes while this graph treats the same registered // buffer as a read-only mask input. Other bindings, graph state writes, diff --git a/helios/src/model/testing.rs b/helios/src/model/testing.rs index eb85bf0b0..785b1a3f3 100644 --- a/helios/src/model/testing.rs +++ b/helios/src/model/testing.rs @@ -181,9 +181,13 @@ pub fn metadata() -> PreparedContract { inputs.extend([ binding("token_ids", PromptToken, PackedToken, 0, 0), binding("prefill_positions", PromptPosition, PackedToken, 0, 0), - binding("vision_token_indices", ImageFeatureIndex, PackedToken, 0, 0), - binding("vision_feature_slot", ImageFeatureSlot, Scalar, 0, -1), ]); + if batch == 1 { + inputs.extend([ + binding("vision_token_indices", ImageFeatureIndex, PackedToken, 0, 0), + binding("vision_feature_slot", ImageFeatureSlot, Scalar, 0, -1), + ]); + } } graphs.push(GraphContract { tuned_bindings: vec![], graph: format!("{kind:?}-{batch}-{width}"), @@ -357,16 +361,27 @@ pub fn manifest(config: &ModelConfig) -> ExecutionManifest { GraphOperation::Speculative => GraphKind::Speculative, _ => unreachable!(), }; - GraphDescriptor { tuned_bindings: vec![], confidence_width: 0, draft_tokens: if kind == GraphKind::Speculative { fields[2].parse::().unwrap() - 1 } else { 0 }, packed_token_capacity: if kind == GraphKind::Speculative { fields[1].parse::().unwrap() * fields[2].parse::().unwrap() } else { 0 }, + let batch_capacity: usize = fields[1].parse().unwrap(); + let width: usize = fields[2].parse().unwrap(); + let packed_token_capacity = if kind == GraphKind::Speculative { + batch_capacity * width + } else if matches!(kind, GraphKind::Prefill | GraphKind::TerminalPrefill) + && batch_capacity >= 2 + { + config.limits.prefill_chunk_size + } else { + 0 + }; + GraphDescriptor { tuned_bindings: vec![], confidence_width: 0, draft_tokens: if kind == GraphKind::Speculative { width - 1 } else { 0 }, packed_token_capacity, name: g.graph.clone(), kind, sampling_mode: SamplingMode::General, handle: 1, - batch_capacity: fields[1].parse().unwrap(), + batch_capacity, token_capacity: if kind == GraphKind::Prefill { config.limits.prefill_chunk_size } else { - fields[2].parse().unwrap() + width }, prefill_capacity: 0, estimated_duration_ns: 1000, diff --git a/helios/src/model/tests.rs b/helios/src/model/tests.rs index 46b5d4d1a..f4cf5a7ca 100644 --- a/helios/src/model/tests.rs +++ b/helios/src/model/tests.rs @@ -2579,3 +2579,286 @@ fn continuation_prompt_validation_permits_decoded_in_vocab_image_and_span_tokens }; assert!(validate_continuation_prompt_data(&cfg, &span_tokens, &bad_span_end, 6).is_err()); } + +#[test] +fn packed_prefill_contract_validation_and_multi_lane_packing() { + let mut cfg = config(); + cfg.limits.max_active = 4; + cfg.limits.request_slots = 4; + cfg.limits.prefill_chunk_size = 512; + cfg.speculative_widths.clear(); + cfg.speculative_token_capacity = 0; + + // Build a valid base catalog (B == 1 prefill + decode + lifecycle), then add packed + // TerminalPrefill (B=4, W=128, P=512). + let mut m = testing::manifest(&cfg); + m.graphs.retain(|g| { + !matches!(g.kind, GraphKind::Speculative | GraphKind::Mixed | GraphKind::Vision) + && (g.kind != GraphKind::Prefill || g.batch_capacity == 1) + }); + cfg.contract + .graphs + .retain(|g| m.graphs.iter().any(|mg| mg.name == g.graph)); + + let base_prefill_graph = m + .graphs + .iter() + .find(|g| g.kind == GraphKind::Prefill && g.batch_capacity == 1) + .unwrap() + .clone(); + let base_prefill_contract = cfg + .contract + .graphs + .iter() + .find(|g| g.graph == base_prefill_graph.name) + .unwrap() + .clone(); + + // Add packed TerminalPrefill (B=4, W=128, P=512) without vision bindings. + let mut packed_graph = base_prefill_graph.clone(); + packed_graph.name = "terminal-prefill-b4-w128-p512".into(); + packed_graph.kind = GraphKind::TerminalPrefill; + packed_graph.handle = m.graphs.iter().map(|g| g.handle).max().unwrap_or(0) + 1; + packed_graph.batch_capacity = 4; + packed_graph.token_capacity = 128; + packed_graph.packed_token_capacity = 512; + packed_graph.input_bindings.retain(|b| { + !matches!( + b.buffer_name.as_str(), + "vision_token_indices" | "vision_feature_slot" + ) + }); + m.graphs.push(packed_graph.clone()); + // Also register a tight packed shape (B=4, W=128, P=256 < B*W) to verify aggregate P caps. + let mut tight_packed_graph = packed_graph.clone(); + tight_packed_graph.name = "terminal-prefill-b4-w128-p256".into(); + tight_packed_graph.packed_token_capacity = 256; + m.graphs.push(tight_packed_graph.clone()); + for (index, graph) in m.graphs.iter_mut().enumerate() { + graph.handle = index + 1; + } + + let mut packed_contract = base_prefill_contract.clone(); + packed_contract.graph = packed_graph.name.clone(); + packed_contract.kind = GraphOperation::TerminalPrefill; + packed_contract.inputs.retain(|i| { + !matches!( + i.source, + ValueSource::ImageFeatureIndex + | ValueSource::ImageFeatureSlot + | ValueSource::ImageLeftContext + | ValueSource::ImageRightContext + ) + }); + cfg.contract.graphs.push(packed_contract.clone()); + let mut tight_packed_contract = packed_contract.clone(); + tight_packed_contract.graph = tight_packed_graph.name.clone(); + cfg.contract.graphs.push(tight_packed_contract); + + catalog::validate(&cfg, &m).unwrap(); + + // Reject vision bindings on B >= 2 packed prefill graphs. + for bad_binding in [ + testing::binding( + "vision_feature_slot", + ValueSource::ImageFeatureSlot, + InputIndexing::Scalar, + 0, + -1, + ), + testing::binding( + "vision_token_indices", + ValueSource::ImageFeatureIndex, + InputIndexing::PackedToken, + 0, + 0, + ), + ] { + let mut bad_cfg = cfg.clone(); + let mut bad_m = m.clone(); + let g = bad_cfg + .contract + .graphs + .iter_mut() + .find(|g| g.graph == packed_graph.name) + .unwrap(); + g.inputs.push(bad_binding.clone()); + let buf = bad_m + .buffers + .iter() + .find(|b| b.name == bad_binding.buffer) + .unwrap() + .clone(); + bad_m + .graphs + .iter_mut() + .find(|g| g.name == packed_graph.name) + .unwrap() + .input_bindings + .push(crate::execution::InputBinding { + buffer_name: buf.name, + host_offset: 0, + nbytes: buf.nbytes, + }); + assert!( + Inputs::new(&bad_cfg, &bad_m).is_err(), + "expected {:?} on B>=2 packed prefill to be rejected", + bad_binding.source + ); + } + + // Reject P > prefill_chunk_size in catalog::validate. + { + let mut over_m = m.clone(); + over_m + .graphs + .iter_mut() + .find(|g| g.name == packed_graph.name) + .unwrap() + .packed_token_capacity = 576; + assert!(catalog::validate(&cfg, &over_m).is_err()); + } + + // Pack 3 active lanes (finishing 64, continuing 100/200, finishing 32) + 1 inactive row. + let mut inputs = Inputs::new(&cfg, &m).unwrap(); + let mut caps = scheduler_capabilities(&cfg); + caps.vision.feature_slots = 4; + caps.vision.features_per_request = 16; + caps.vision.max_images = 1; + caps.vision.patches_per_feature = 4; + caps.vision.patch_capacities = vec![4]; + let mut scheduler = RequestScheduler::new(cfg.identity, cfg.limits, caps).unwrap(); + scheduler + .prefill_graphs(&[cfg.limits.prefill_chunk_size]) + .unwrap(); + scheduler + .packed_prefill_graphs(&[ + (GraphKind::TerminalPrefill, 4, 128, 256), + (GraphKind::TerminalPrefill, 4, 128, 512), + ]) + .unwrap(); + scheduler.measured_graph_durations(&m.graphs).unwrap(); + + let mut admissions: [Option; 4] = std::array::from_fn(|_| None); + let mut admit = |start_tok: u32, len: usize| { + let prompt: Vec = (start_tok..start_tok + len as u32).collect(); + let h = scheduler + .admit(RequestSpec { + prompt: prompt.clone(), + message_boundaries: vec![], + conditioning: vec![], + max_new_tokens: 16, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + preserve_message_anchor: false, + }) + .unwrap(); + admissions[h.slot as usize] = Some(Admission { + handle: h, + sampling: SamplingParameters::default(), + core_parameters: Default::default(), + max_new_tokens: 16, + prompt, + data: PromptData { + positions: (0..len).map(|p| [p as i64; 3]).collect(), + vision_token_indices: vec![-1; len], + ..Default::default() + }, + grammar_mask: None, + ignore_eos: false, + prompt_logprobs: false, + }); + h + }; + let h0 = admit(1000, 64); + let h1 = admit(2000, 200); + let h2 = admit(3000, 32); + let h3 = admit(4000, 128); + drop(admit); + + let step = crate::scheduler::ScheduledStep { + draft_tokens: 0, + kind: GraphKind::TerminalPrefill, + batch_capacity: 4, + token_capacity: 128, + packed_token_capacity: 512, + mixed: None, + lanes: vec![ + crate::scheduler::ScheduledLane { request: h0, start_position: 0, tokens: 64 }, + crate::scheduler::ScheduledLane { request: h1, start_position: 0, tokens: 100 }, + crate::scheduler::ScheduledLane { request: h2, start_position: 0, tokens: 32 }, + ], + requires_feedback: true, + }; + pack_inputs(&mut inputs, &cfg, &scheduler, &step, &admissions).unwrap(); + let ups = inputs.uploads(); + let read_i32 = |name: &str| -> Vec { + ups.iter() + .find(|u| u.buffer == name) + .unwrap() + .bytes + .chunks_exact(4) + .map(|c| i32::from_le_bytes(c.try_into().unwrap())) + .collect() + }; + let read_i64 = |name: &str| -> Vec { + let mut out = Vec::new(); + for u in ups.iter().filter(|u| u.buffer == name) { + out.extend( + u.bytes + .chunks_exact(8) + .map(|c| i64::from_le_bytes(c.try_into().unwrap())), + ); + } + out + }; + assert_eq!(read_i32("live_rows"), vec![3]); + assert_eq!(read_i32("query_lengths"), vec![64, 100, 32, 0]); + assert_eq!(read_i32("sample_enabled"), vec![1, 0, 1, 0]); + assert_eq!( + read_i32("row_slot_ids"), + vec![h0.slot as i32, h1.slot as i32, h2.slot as i32, -1] + ); + let expected_tokens: Vec = (1000i64..1064) + .chain(2000i64..2100) + .chain(3000i64..3032) + .collect(); + assert_eq!(read_i64("token_ids"), expected_tokens); + + // Reject a lane exceeding W_req (128). + let mut bad_lane = step.clone(); + bad_lane.lanes[1].tokens = 129; + assert!(pack_inputs(&mut inputs, &cfg, &scheduler, &bad_lane, &admissions).is_err()); + + // Reject aggregate packed tokens exceeding P (256) even when every lane fits W_req (128). + let over_p = crate::scheduler::ScheduledStep { + packed_token_capacity: 256, + lanes: vec![ + crate::scheduler::ScheduledLane { request: h0, start_position: 0, tokens: 64 }, + crate::scheduler::ScheduledLane { request: h1, start_position: 0, tokens: 128 }, + crate::scheduler::ScheduledLane { request: h3, start_position: 0, tokens: 128 }, + ], + ..step.clone() + }; + over_p + .validate_mixed() + .expect_err("packed prefill must enforce aggregate packed token capacity"); + let err = pack_inputs(&mut inputs, &cfg, &scheduler, &over_p, &admissions) + .expect_err("packed prefill must enforce aggregate packed token capacity"); + assert!( + err.to_string() + .contains("packed prefill lanes exceed their captured geometry"), + "unexpected error: {err}" + ); + + // Reject an image-conditioned lane submitted to a B >= 2 packed prefill graph. + scheduler.set_vision_images(h2, &[4]).unwrap(); + let err = pack_inputs(&mut inputs, &cfg, &scheduler, &step, &admissions) + .expect_err("packed prefill must reject image-conditioned lanes"); + assert!( + err.to_string() + .contains("packed prefill graph does not support image-conditioned lanes"), + "unexpected error: {err}" + ); +} diff --git a/helios/src/runtime_core/selection.rs b/helios/src/runtime_core/selection.rs index cc9bf23f1..f2966881b 100644 --- a/helios/src/runtime_core/selection.rs +++ b/helios/src/runtime_core/selection.rs @@ -277,7 +277,30 @@ impl LoadOptions { && graph.prefill_capacity <= config["prefill_chunk_size"].as_u64().unwrap_or(0) && graph.speculation_enabled.is_some() && if speculative { (1..=crate::execution::resolve_completion_token_capacity(execution.completion_token_capacity) as u64).contains(&graph.token_capacity) } else { graph.token_capacity == 1 }, - GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill | GraphKind::Vision => graph.batch_capacity == 1 && graph.token_capacity > 0, + GraphKind::Prefill | GraphKind::TerminalPrefill => { + let max_chunk = config["prefill_chunk_size"].as_u64().unwrap_or(0); + if graph.batch_capacity == 1 { + graph.token_capacity > 0 && graph.packed_token_capacity == 0 + } else { + usize::try_from(graph.batch_capacity) + .ok() + .zip(usize::try_from(graph.token_capacity).ok()) + .zip(usize::try_from(graph.packed_token_capacity).ok()) + .zip(usize::try_from(max_chunk).ok()) + .is_some_and(|(((b, w), p), chunk)| { + crate::execution::valid_packed_prefill_geometry( + b, + w, + p, + REQUEST_LANES, + Some(chunk), + ) + }) + } + } + GraphKind::ScoredPrefill | GraphKind::Vision => { + graph.batch_capacity == 1 && graph.token_capacity > 0 + } GraphKind::Speculative => (1..=REQUEST_LANES as u64).contains(&graph.batch_capacity) && (1..=crate::execution::resolve_completion_token_capacity(execution.completion_token_capacity) as u64).contains(&graph.token_capacity), _ => (1..=REQUEST_LANES as u64).contains(&graph.batch_capacity) && graph.token_capacity == 1, }; @@ -285,7 +308,8 @@ impl LoadOptions { || (kind != GraphKind::Mixed && graph.prefill_capacity != 0) || (kind == GraphKind::Speculative && (graph.packed_token_capacity < graph.batch_capacity || graph.packed_token_capacity > graph.batch_capacity.saturating_mul(graph.token_capacity))) - || (kind != GraphKind::Speculative && graph.packed_token_capacity != 0) + || (!matches!(kind, GraphKind::Speculative | GraphKind::Prefill | GraphKind::TerminalPrefill) + && graph.packed_token_capacity != 0) || (graph.confidence_width > 0 && (kind != GraphKind::Speculative || graph.draft_tokens != Some(graph.confidence_width))) || (kind == GraphKind::Speculative && graph.speculation_enabled == Some(false)) @@ -340,7 +364,14 @@ impl LoadOptions { .min() .unwrap_or(active as u64); execution.graphs.retain(|graph| { - let limit = if graph.kind == "mixed" && active < 2 { 0 } else { max_batch }; + let packed_prefill = + matches!(graph.kind.as_str(), "prefill" | "terminal_prefill") + && graph.batch_capacity >= 2; + let limit = if (graph.kind == "mixed" || packed_prefill) && active < 2 { + 0 + } else { + max_batch + }; graph.batch_capacity <= limit && graph.speculation_enabled.is_none_or(|value| value == enabled) && (graph.kind != "decode" || !enabled) @@ -2068,6 +2099,155 @@ mod tests { assert!(error.contains("no captured speculative width fits"), "{error}"); } + #[test] + fn packed_prefill_selection_validates_geometry_and_filters_by_max_concurrency() { + let make_core = |packed_graphs: &[(u64, u64, u64, &str)]| { + let mut core = host_wide_round_core(); + core.execution.as_mut().unwrap().max_active = 8; + let graphs = &mut core.execution.as_mut().unwrap().graphs; + for batch in [4u64, 8] { + for kind in ["init", "restore", "snapshot", "resume", "decode"] { + if graphs.iter().any(|g| g.kind == kind && g.batch_capacity == batch) { + continue; + } + let mut g = graphs + .iter() + .find(|g| g.kind == kind && g.batch_capacity == 1) + .unwrap() + .clone(); + g.name = format!("{kind}-b{batch}"); + g.batch_capacity = batch; + graphs.push(g); + } + } + let base_prefill = graphs + .iter() + .find(|g| g.kind == "prefill" && g.batch_capacity == 1) + .cloned() + .unwrap_or_else(|| { + let mut g = graphs + .iter() + .find(|g| g.kind == "decode" && g.batch_capacity == 1) + .unwrap() + .clone(); + g.name = "prefill-b1-w1024".into(); + g.kind = "prefill".into(); + g.batch_capacity = 1; + g.token_capacity = 1024; + g.packed_token_capacity = 0; + g.speculation_enabled = None; + g.draft_tokens = None; + g.verify_tokens = None; + g.draft_source = 0; + graphs.push(g.clone()); + g + }); + for &(batch, width, packed, kind) in packed_graphs { + let mut g = base_prefill.clone(); + g.name = format!("{kind}-b{batch}-w{width}-p{packed}"); + g.kind = kind.into(); + g.batch_capacity = batch; + g.token_capacity = width; + g.packed_token_capacity = packed; + graphs.push(g); + } + refresh_graph_resources(&mut core); + core + }; + + let valid_specs = [ + (4, 128, 512, "terminal_prefill"), + (8, 128, 1024, "terminal_prefill"), + (4, 128, 512, "prefill"), + ]; + + let make_cfg = || { + serde_json::json!({ + "prefill_chunk_size": 1024, + "speculative_widths": [1, 8], + "speculative_token_capacity": 24 + }) + }; + + // max_concurrency=8 retains all packed prefill graphs. + let mut cores_c8 = [make_core(&valid_specs)]; + let mut cfg = make_cfg(); + LoadOptions { + max_concurrency: Some(8), + mtp_draft_tokens: Some(0), + ..Default::default() + } + .select(&mut cores_c8, &mut cfg) + .unwrap(); + + // max_concurrency=4 retains B=4 packed prefill and drops B=8. + let mut cores_c4 = [make_core(&valid_specs)]; + let mut cfg_c4 = make_cfg(); + LoadOptions { + max_concurrency: Some(4), + mtp_draft_tokens: Some(0), + ..Default::default() + } + .select(&mut cores_c4, &mut cfg_c4) + .unwrap(); + let kept_c4: Vec<_> = cores_c4[0] + .execution + .as_ref() + .unwrap() + .graphs + .iter() + .filter(|g| { + matches!(g.kind.as_str(), "prefill" | "terminal_prefill") && g.batch_capacity >= 2 + }) + .map(|g| (g.kind.as_str(), g.batch_capacity, g.packed_token_capacity)) + .collect(); + assert_eq!( + kept_c4, + vec![("terminal_prefill", 4, 512), ("prefill", 4, 512)] + ); + + // max_concurrency=1 drops all B >= 2 packed prefill graphs while keeping B == 1 prefill. + let mut cores_c1 = [make_core(&valid_specs)]; + let mut cfg_c1 = make_cfg(); + LoadOptions { + max_concurrency: Some(1), + mtp_draft_tokens: Some(0), + ..Default::default() + } + .select(&mut cores_c1, &mut cfg_c1) + .unwrap(); + assert!(cores_c1[0].execution.as_ref().unwrap().graphs.iter().all(|g| { + !(matches!(g.kind.as_str(), "prefill" | "terminal_prefill") && g.batch_capacity >= 2) + })); + assert!(cores_c1[0] + .execution + .as_ref() + .unwrap() + .graphs + .iter() + .any(|g| g.kind == "prefill" && g.batch_capacity == 1)); + + // Malformed packed prefill geometry (unaligned P, P > prefill_chunk_size, W > P) fails. + for bad in [ + (4, 128, 96, "terminal_prefill"), + (4, 512, 2048, "terminal_prefill"), + (4, 256, 128, "prefill"), + ] { + let bad_core = make_core(&[bad]); + let mut bad_cfg = make_cfg(); + assert!( + LoadOptions { + max_concurrency: Some(8), + mtp_draft_tokens: Some(0), + ..Default::default() + } + .select(&mut [bad_core], &mut bad_cfg) + .is_err(), + "expected malformed packed prefill {bad:?} to be rejected" + ); + } + } + } diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 9cd3a4bf9..b0bf901cd 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -433,9 +433,40 @@ impl ScheduledStep { } else if self.draft_tokens != 0 { return Err("proposal depth belongs only to speculative steps".into()); } - if self.packed_token_capacity != 0 && (self.kind != GraphKind::Speculative - || self.packed_token_capacity < self.batch_capacity - || self.packed_token_capacity > self.batch_capacity.saturating_mul(self.token_capacity)) { + if matches!(self.kind, GraphKind::Prefill | GraphKind::TerminalPrefill) + && self.batch_capacity >= 2 + { + if !crate::execution::valid_packed_prefill_geometry( + self.batch_capacity, + self.token_capacity, + self.packed_token_capacity, + REQUEST_LANES, + None, + ) || self.lanes.is_empty() + || self.lanes.len() > self.batch_capacity + || self + .lanes + .iter() + .any(|lane| lane.tokens == 0 || lane.tokens > self.token_capacity) + || self + .lanes + .iter() + .try_fold(0usize, |sum, lane| sum.checked_add(lane.tokens)) + .is_none_or(|sum| sum > self.packed_token_capacity) + || self.lanes.iter().enumerate().any(|(i, lane)| { + self.lanes[..i] + .iter() + .any(|other| other.request.slot == lane.request.slot) + }) + { + return Err("packed prefill lanes exceed their captured geometry".into()); + } + } else if self.packed_token_capacity != 0 + && (self.kind != GraphKind::Speculative + || self.packed_token_capacity < self.batch_capacity + || self.packed_token_capacity + > self.batch_capacity.saturating_mul(self.token_capacity)) + { return Err("speculative physical token capacity is invalid".into()); } match &self.mixed { @@ -667,6 +698,7 @@ pub struct RequestScheduler { terminal_prefill_catalog: Vec, terminal_prefill_window: usize, scored_prefill_catalog: Vec, + packed_prefill_catalog: Vec<(GraphKind, usize, usize, usize)>, mixed_catalog: Vec<(usize, usize, usize)>, forecasts: rounds::Forecasts, costs: cost::ActionCosts, @@ -764,6 +796,7 @@ impl RequestScheduler { terminal_prefill_catalog: Vec::new(), terminal_prefill_window: 0, scored_prefill_catalog: Vec::new(), + packed_prefill_catalog: Vec::new(), mixed_catalog: Vec::new(), forecasts, costs: cost::ActionCosts::default(), @@ -853,6 +886,37 @@ impl RequestScheduler { Ok(()) } + pub fn packed_prefill_graphs( + &mut self, + shapes: &[(GraphKind, usize, usize, usize)], + ) -> Result<()> { + if self.submitted != Fence(0) || self.slots.iter().any(|s| s.request.is_some()) { + return Err("packed prefill graphs must be selected before admission".into()); + } + let mut catalog = shapes.to_vec(); + catalog.sort_unstable_by_key(|&(kind, batch, width, packed)| { + (kind as u8, batch, width, packed) + }); + if catalog.iter().any(|&(kind, batch, width, packed)| { + !matches!(kind, GraphKind::Prefill | GraphKind::TerminalPrefill) + || !crate::execution::valid_packed_prefill_geometry( + batch, + width, + packed, + self.limits.request_slots, + Some(self.limits.prefill_chunk_size), + ) + }) || catalog.windows(2).any(|pair| pair[0] == pair[1]) + { + return Err( + "packed prefill shapes must be distinct aligned multi-request capacities within the chunk size" + .into(), + ); + } + self.packed_prefill_catalog = catalog; + Ok(()) + } + fn recompute_terminal_prefill_window(&mut self) { self.terminal_prefill_window = if self.terminal_prefill_catalog.is_empty() { 0 @@ -870,6 +934,27 @@ impl RequestScheduler { kind == GraphKind::Prefill && self.terminal_prefill_catalog.binary_search(&capacity).is_ok() } + pub(super) fn is_non_terminal_prefill_step( + &self, + kind: GraphKind, + batch: usize, + capacity: usize, + packed: usize, + ) -> bool { + if batch <= 1 { + self.is_non_terminal_prefill(kind, capacity) + } else { + kind == GraphKind::Prefill + && self + .packed_prefill_catalog + .binary_search_by_key( + &(GraphKind::TerminalPrefill as u8, batch, capacity, packed), + |&(k, b, w, p)| (k as u8, b, w, p), + ) + .is_ok() + } + } + pub(super) fn terminal_prefill_window(&self) -> usize { self.terminal_prefill_window } @@ -2527,6 +2612,9 @@ impl RequestScheduler { return Err("execution plan has stale request state".into()); } } + if step.lanes.len() > step.batch_capacity { + return Err("scheduled step exceeds batch capacity".into()); + } let mut needed = Vec::new(); for lane in &step.lanes { let request = self.request(lane.request)?; @@ -2579,7 +2667,12 @@ impl RequestScheduler { for lane in &step.lanes { self.promote_request_anchor(lane.request)?; } self.commit_checkpoint_plans(&plan.checkpoint_plans)?; self.commit_checkpoint_copies(step)?; - let non_terminal_prefill = self.is_non_terminal_prefill(step.kind, step.token_capacity); + let non_terminal_prefill = self.is_non_terminal_prefill_step( + step.kind, + step.batch_capacity, + step.token_capacity, + step.packed_token_capacity, + ); for (handle, pages, next_consumed_ceiling) in needed { let request = self.request_mut(handle)?; let allocated: Vec<_> = (0..pages) diff --git a/helios/src/scheduler/checkpoints.rs b/helios/src/scheduler/checkpoints.rs index a50770f60..bc5470bdf 100644 --- a/helios/src/scheduler/checkpoints.rs +++ b/helios/src/scheduler/checkpoints.rs @@ -922,9 +922,18 @@ impl RequestScheduler { .find(|cut| cut.role == RetentionRole::Anchor) .map_or_else(|| request.checkpoint_anchor(), |cut| cut.endpoint); let end = lane.start_position as usize + lane.tokens; - let deferred_after = (request.deferred_prefill - || self.is_non_terminal_prefill(kind, step.token_capacity)) - && kind != GraphKind::TerminalPrefill; + let non_terminal = if step.kind == GraphKind::Mixed { + self.is_non_terminal_prefill(kind, step.prefill_capacity()) + } else { + self.is_non_terminal_prefill_step( + kind, + step.batch_capacity, + step.token_capacity, + step.packed_token_capacity, + ) + }; + let deferred_after = + (request.deferred_prefill || non_terminal) && kind != GraphKind::TerminalPrefill; let cut = accounting .cuts .iter() diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 2e7211b17..6a7c25238 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -578,7 +578,7 @@ impl ActionCosts { } estimate.observed_at_ns = self.now_ns; self.refresh_packed_durations(); - if key.kind.is_prefill() { + if key.kind.is_prefill() && key.batch == 1 { self.refresh_prefill_context_slopes(); } } @@ -603,7 +603,8 @@ impl ActionCosts { Estimate { nanos: 0, replays: ReplayTimes::default(), - prefill: key.kind.is_prefill().then(|| PrefillCostModel::new(key.tokens)), + prefill: (key.kind.is_prefill() && key.batch == 1) + .then(|| PrefillCostModel::new(key.tokens)), observed_at_ns: 0, last_attempt_ns: 0, }, @@ -640,6 +641,23 @@ impl ActionCosts { self.shape_duration(kind, batch, tokens, 0) } + pub fn packed_prefill_duration( + &self, + kind: GraphKind, + batch: usize, + width: usize, + packed: usize, + ) -> Option { + self.duration_key(Key { + drafts: 0, + kind, + batch, + tokens: width, + prefill: 0, + packed, + }) + } + pub fn prefill_duration( &self, kind: GraphKind, @@ -948,7 +966,7 @@ impl ActionCosts { } estimate.observed_at_ns = self.now_ns; self.refresh_packed_durations(); - if key.kind.is_prefill() { + if key.kind.is_prefill() && key.batch == 1 { self.refresh_prefill_context_slopes(); } } diff --git a/helios/src/scheduler/lifecycle_tests.rs b/helios/src/scheduler/lifecycle_tests.rs index c4d8743e7..694b0ea52 100644 --- a/helios/src/scheduler/lifecycle_tests.rs +++ b/helios/src/scheduler/lifecycle_tests.rs @@ -61,6 +61,132 @@ fn completion_records(scheduler: &RequestScheduler, fence: Fence) -> Vec Self { + use crate::execution::{GraphDescriptor, SamplingMode}; + + let mut scheduler = tests::scheduler(2, 64, 16); + scheduler.prefill_graphs(&[64, 128, 256, 512]).unwrap(); + scheduler + .terminal_prefill_graphs(&[64, 128, 256, 512]) + .unwrap(); + scheduler + .packed_prefill_graphs(&[ + (GraphKind::Prefill, 2, 256, 512), + (GraphKind::TerminalPrefill, 2, 256, 512), + ]) + .unwrap(); + let mut graphs = tests::duration_graphs(2); + for kind in [GraphKind::Prefill, GraphKind::TerminalPrefill] { + for cap in [64usize, 128, 256, 512] { + if !graphs.iter().any(|g| { + g.kind == kind + && g.batch_capacity == 1 + && g.token_capacity == cap + && g.packed_token_capacity == 0 + }) { + graphs.push(GraphDescriptor { + name: format!("{kind:?}-1-{cap}"), + kind, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: 1, + token_capacity: cap, + prefill_capacity: 0, + packed_token_capacity: 0, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + } + graphs.push(GraphDescriptor { + name: format!("{kind:?}-2-256-512"), + kind, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: 2, + token_capacity: 256, + prefill_capacity: 0, + packed_token_capacity: 512, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + scheduler.measured_graph_durations(&graphs).unwrap(); + for kind in [GraphKind::Prefill, GraphKind::TerminalPrefill] { + for cap in [64usize, 128, 256, 512] { + let solo = ScheduledStep { + draft_tokens: 0, + kind, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![], + requires_feedback: kind == GraphKind::TerminalPrefill, + }; + scheduler + .costs + .set_measured(&solo, (cap as u64 / 64) * 5_000_000); + } + let packed = ScheduledStep { + draft_tokens: 0, + kind, + batch_capacity: 2, + token_capacity: 256, + packed_token_capacity: 512, + mixed: None, + lanes: vec![], + requires_feedback: kind == GraphKind::TerminalPrefill, + }; + // Non-terminal packed Prefill skips LM head / sampling and is faster than TerminalPrefill. + let packed_ns = if kind == GraphKind::Prefill { + 20_000_000 + } else { + 25_000_000 + }; + scheduler.costs.set_measured(&packed, packed_ns); + } + // 768-token prompts exceed the 512-token single-chunk solo limit so step 1 uses + // pipelined non-terminal packed Prefill (barrier = 0) and subsequent steps exercise + // feedback-exclusive packed TerminalPrefill (barrier = 1). + for slot in 0..2 { + let mut spec = tests::spec(768, 32); + spec.prompt[0] = 200 + slot as u32; + assert_eq!(scheduler.admit(spec).unwrap().slot as usize, slot); + } + for _ in 0..8 { + if scheduler + .slots + .iter() + .all(|slot| slot.request.as_ref().unwrap().phase == RequestPhase::Prefill) + { + let fence_origin = scheduler.submitted.0; + assert_eq!(scheduler.completed.0, fence_origin); + return Self { + scheduler, + fence_origin, + last_plan: None, + }; + } + let plan = scheduler + .plan() + .expect("packed-prefill warmup must complete Init"); + let fence = Fence(scheduler.submitted.0 + 1); + scheduler.commit(&plan, fence).unwrap(); + let records = completion_records(&scheduler, fence); + scheduler + .complete(fence, &records, Default::default()) + .unwrap(); + } + panic!("packed-prefill warmup did not reach two prefill requests"); + } + fn new() -> Self { let mut scheduler = tests::scheduler(2, 64, 16); for slot in 0..2 { @@ -719,3 +845,102 @@ fn scheduler_matches_lifecycle_model() { edges.len() ); } + +#[test] +fn packed_prefill_scheduler_matches_lifecycle_model() { + const PACKED_MAX_DEPTH: usize = 7; + let mut pending = VecDeque::from([Vec::::new()]); + let mut visited = HashSet::new(); + let mut edges = BTreeSet::new(); + let mut coverage = Coverage::default(); + let mut packed_non_terminal = false; + let mut packed_terminal = false; + let mut cancel_during_packed = false; + let mut stale_packed_plan = false; + + while let Some(path) = pending.pop_front() { + let mut fixture = Fixture::new_packed_prefill(); + for action in &path { + fixture.apply(*action); + } + if !visited.insert(fixture.state_key()) { + continue; + } + fixture.assert_ownership(); + check_rejections(&mut fixture, &mut coverage); + if path.len() == PACKED_MAX_DEPTH { + continue; + } + let before = fixture.projection(); + for action in fixture.actions() { + let mut candidate = Fixture::new_packed_prefill(); + for previous in &path { + candidate.apply(*previous); + } + let planned = (action[0] == 2 || action[0] == 4) + .then(|| candidate.scheduler.plan()) + .flatten(); + if action[0] == 2 + && let Some(plan) = &planned + && plan.batch_capacity >= 2 + && plan.lanes.len() >= 2 + { + if plan.kind == GraphKind::Prefill && action[2] == 0 { + packed_non_terminal = true; + } else if plan.kind == GraphKind::TerminalPrefill && action[2] == 1 { + packed_terminal = true; + } + } + if action[0] == 4 + && candidate.scheduler.submissions.values().any(|sub| { + sub.step.kind.is_prefill() + && sub.step.batch_capacity >= 2 + && sub + .lanes + .iter() + .any(|lane| u64::from(lane.request.slot) == action[1]) + }) + { + cancel_during_packed = true; + } + let stale_plan = (action[0] == 4) + .then_some(planned) + .flatten() + .filter(|plan| { + plan.lanes + .iter() + .any(|lane| u64::from(lane.request.slot) == action[1]) + }); + candidate.apply(action); + let after = candidate.projection(); + if let Some(plan) = stale_plan { + let state = candidate.state_key(); + let fence = Fence(candidate.scheduler.submitted.0 + 1); + assert!( + candidate.scheduler.commit(&plan, fence).is_err(), + "cancelled packed-prefill request plan accepted" + ); + assert_eq!(candidate.state_key(), state); + if plan.kind.is_prefill() && plan.batch_capacity >= 2 { + stale_packed_plan = true; + } + } + edges.insert((before, action, after)); + let mut successor = path.clone(); + successor.push(action); + pending.push_back(successor); + } + } + assert!( + packed_non_terminal && packed_terminal && cancel_during_packed && stale_packed_plan, + "missing packed-prefill lifecycle coverage: non_terminal={packed_non_terminal} terminal={packed_terminal} cancel_during_packed={cancel_during_packed} stale_packed_plan={stale_packed_plan}" + ); + for (before, action, after) in &edges { + println!("LIFECYCLE_EDGE [{before:?}, {action:?}, {after:?}]"); + } + println!( + "PACKED_PREFILL_LIFECYCLE_COVERAGE states={} edges={} depth={PACKED_MAX_DEPTH}", + visited.len(), + edges.len() + ); +} diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index 21d0b8fcd..f3bb4c071 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -11,6 +11,24 @@ use super::{ *, }; +pub(super) struct PackedCohort { + pub(super) mask: u64, + pub(super) promoted_mask: u64, + pub(super) lengths: [usize; REQUEST_LANES], + pub(super) total_work: usize, + pub(super) total_value: f64, +} + +impl PackedCohort { + pub(super) fn selected(&self) -> usize { + self.mask.count_ones() as usize + } + + pub(super) fn promoted_count(&self) -> usize { + self.promoted_mask.count_ones() as usize + } +} + #[derive(Clone, Copy, Debug)] pub struct PolicyConfig { pub output_token_value: f64, @@ -167,7 +185,7 @@ impl RequestScheduler { return short == long; } if smaller.kind.is_prefill() { - return smaller.work == larger.work; + return smaller.work == larger.work && smaller.host_lengths == larger.host_lengths; } if smaller.capacity == larger.capacity && smaller.prefill_capacity == larger.prefill_capacity { return true; @@ -1126,28 +1144,15 @@ impl RequestScheduler { let mut value = self.lane_value_for_tokens(request, following, work, horizon, values[slot]); let mut selected = 1u64 << slot; - if capacity > 1 { - let mut finishing = [(0usize, 0.0); REQUEST_LANES]; - let mut f = 0; - for (other_slot, other_entry) in self.slots.iter().enumerate() { - if other_slot == slot || mask & (1 << other_slot) == 0 { - continue; - } - if other_entry.request.as_ref().is_some_and(terminal_cleanup) { - finishing[f] = (other_slot, values[other_slot].finish(first_ms, total_ms)); - f += 1; - } - } - if f > 0 { - let extra = best_cohort::(&finishing[..f], capacity - 1); - selected |= extra; - value += finishing[..f] - .iter() - .filter(|(s, _)| extra & (1 << s) != 0) - .map(|(_, v)| *v) - .sum::(); - } - } + self.fill_finishing_lanes( + mask, + &mut selected, + &mut value, + capacity.saturating_sub(1), + first_ms, + total_ms, + values, + ); let rate = ValueRate::new(horizon, value, age_price); if best.is_none_or(|(_, old)| rate.compare(old).is_gt()) { best = Some((fill(selected), rate)); @@ -1297,6 +1302,50 @@ impl RequestScheduler { for &(batch, width, prefill) in &self.mixed_catalog { consider(GraphKind::Mixed, batch, width, prefill); } + drop(consider); + for &(following, batch, width, packed) in &self.packed_prefill_catalog { + let Some(ns) = self.costs.packed_prefill_duration(following, batch, width, packed) else { + continue; + }; + let horizon = if ns == 0 || duration_ns == 0 { + 0 + } else { + ns.saturating_add(duration_ns) + }; + let non_terminal = self.is_non_terminal_prefill_step(following, batch, width, packed); + let (offers, n) = self.packed_prefill_offers( + following, + width, + non_terminal, + horizon, + values, + age_price, + &mut prefill_plans, + Some((mask, kind)), + ); + let Some(choice) = + Self::select_packed_prefill_cohort(&offers[..n], batch, packed, Some(capacity)) + else { + continue; + }; + let total_ms = horizon as f64 / 1e6; + let first_ms = duration_ns as f64 / 1e6; + let mut selected = choice.promoted_mask; + let mut value = choice.total_value; + self.fill_finishing_lanes( + mask, + &mut selected, + &mut value, + capacity.saturating_sub(choice.promoted_count()), + first_ms, + total_ms, + values, + ); + let rate = ValueRate::new(horizon, value, age_price); + if best.is_none_or(|(_, old)| rate.compare(old).is_gt()) { + best = Some((fill(selected), rate)); + } + } let mut terminal = [(0, 0.0); REQUEST_LANES]; let mut count = 0; for slot in @@ -1455,6 +1504,299 @@ impl RequestScheduler { }); } + fn is_text_only_prefill_request(r: &LiveRequest) -> bool { + !r.prompt_logprobs + && r.image_slot.is_none() + && r.vision_patches.is_empty() + && r.conditioned_windows.is_empty() + } + + /// Select the highest-value packed prefill cohort of `2..=batch` lanes whose aggregate token + /// work fits within `packed`. When `promoted_limit` is `Some(cap)`, at least one promoted lane + /// (and at most `cap` promoted lanes) is reserved before ready lanes can fill the remaining + /// slots, matching two-stage continuation semantics. + pub(super) fn select_packed_prefill_cohort( + offers: &[(usize, usize, f64, bool)], + batch: usize, + packed: usize, + promoted_limit: Option, + ) -> Option { + let count = offers.len(); + if count < 2 || promoted_limit == Some(0) { + return None; + } + let mut best: Option = None; + for by_density in [false, true] { + let mut order = [0usize; REQUEST_LANES]; + for (i, item) in order[..count].iter_mut().enumerate() { + *item = i; + } + order[..count].sort_unstable_by(|&a, &b| { + let (sa, wa, va, _) = offers[a]; + let (sb, wb, vb, _) = offers[b]; + let primary = if by_density { + (vb / wb as f64) + .total_cmp(&(va / wa as f64)) + .then_with(|| vb.total_cmp(&va)) + } else { + vb.total_cmp(&va) + }; + primary.then_with(|| wa.cmp(&wb)).then_with(|| sa.cmp(&sb)) + }); + let mut mask = 0u64; + let mut promoted_mask = 0u64; + let mut lengths = [0usize; REQUEST_LANES]; + let mut total_work = 0usize; + let mut total_value = 0.0f64; + + // In continuation valuation, seed the best fitting promoted lane first so ready lanes + // cannot crowd out all promoted lanes and spuriously reject a valid cohort. + let mut seeded: Option = None; + if promoted_limit.is_some() { + if let Some(&idx) = order[..count] + .iter() + .find(|&&i| offers[i].3 && offers[i].1 <= packed) + { + let (slot, work, val, _) = offers[idx]; + mask |= 1u64 << slot; + promoted_mask |= 1u64 << slot; + lengths[slot] = work; + total_work = work; + total_value = val; + seeded = Some(idx); + } else { + continue; + } + } + for &idx in &order[..count] { + if mask.count_ones() as usize == batch { + break; + } + if seeded == Some(idx) { + continue; + } + let (slot, work, val, promoted) = offers[idx]; + if total_work + work > packed { + continue; + } + if promoted + && promoted_limit.is_some_and(|cap| promoted_mask.count_ones() as usize == cap) + { + continue; + } + mask |= 1u64 << slot; + lengths[slot] = work; + total_work += work; + total_value += val; + if promoted { + promoted_mask |= 1u64 << slot; + } + } + if mask.count_ones() < 2 { + continue; + } + let candidate = PackedCohort { + mask, + promoted_mask, + lengths, + total_work, + total_value, + }; + let better = best.as_ref().is_none_or(|prev| { + candidate + .total_value + .total_cmp(&prev.total_value) + .then_with(|| candidate.selected().cmp(&prev.selected())) + .then_with(|| candidate.total_work.cmp(&prev.total_work)) + .then_with(|| prev.mask.cmp(&candidate.mask)) + .is_gt() + }); + if better { + best = Some(candidate); + } + } + best + } + + #[allow(clippy::too_many_arguments)] + fn fill_finishing_lanes( + &self, + mask: u64, + selected: &mut u64, + value: &mut f64, + remaining_capacity: usize, + first_ms: f64, + total_ms: f64, + values: &[LaneValue; REQUEST_LANES], + ) { + if remaining_capacity == 0 { + return; + } + let mut finishing = [(0usize, 0.0); REQUEST_LANES]; + let mut f = 0; + for (other_slot, other_entry) in self.slots.iter().enumerate() { + if mask & (1 << other_slot) == 0 || *selected & (1 << other_slot) != 0 { + continue; + } + if other_entry.request.as_ref().is_some_and(terminal_cleanup) { + finishing[f] = (other_slot, values[other_slot].finish(first_ms, total_ms)); + f += 1; + } + } + if f > 0 { + let extra = best_cohort::(&finishing[..f], remaining_capacity); + *selected |= extra; + *value += finishing[..f] + .iter() + .filter(|(s, _)| extra & (1 << s) != 0) + .map(|(_, v)| *v) + .sum::(); + } + } + + #[allow(clippy::too_many_arguments)] + fn packed_prefill_offers( + &self, + kind: GraphKind, + width: usize, + non_terminal: bool, + horizon: u64, + values: &[LaneValue; REQUEST_LANES], + age_price: f64, + prefill_plans: &mut [PrefillSlotPlan; REQUEST_LANES], + continuation: Option<(u64, GraphKind)>, + ) -> ([(usize, usize, f64, bool); REQUEST_LANES], usize) { + let mut offers = [(0usize, 0usize, 0.0f64, false); REQUEST_LANES]; + let mut count = 0usize; + for (slot, entry) in self.slots.iter().enumerate() { + let Some(request) = entry.request.as_ref() else { + continue; + }; + if !Self::is_text_only_prefill_request(request) { + continue; + } + let promoted = match continuation { + Some((mask, current_kind)) => { + let offered = mask & (1 << slot) != 0; + let promoted = offered + && !terminal_cleanup(request) + && self.following_kind(request, current_kind) == Some(GraphKind::Prefill); + let ready = !offered + && self.eligible(request) + && self.request_kind(request) == Some(GraphKind::Prefill); + if !promoted && !ready { + continue; + } + promoted + } + None => { + if !self.eligible(request) + || self.request_kind(request) != Some(GraphKind::Prefill) + { + continue; + } + false + } + }; + let (cut, terminal_only) = + self.prefill_slot_state(&mut prefill_plans[slot], request, age_price); + let work = self.prefill_work_through(request, width, cut); + if work == 0 + || !self.packed_prefill_lane_compatible( + request, + kind, + non_terminal, + terminal_only, + work, + cut, + ) + { + continue; + } + let val = self.lane_value_for_tokens(request, kind, work, horizon, values[slot]); + offers[count] = (slot, work, val, promoted); + count += 1; + } + (offers, count) + } + + fn packed_prefill_lane_compatible( + &self, + r: &LiveRequest, + kind: GraphKind, + non_terminal: bool, + terminal_only: bool, + work: usize, + cut: Option, + ) -> bool { + if kind == GraphKind::TerminalPrefill { + return true; + } + if r.deferred_prefill { + return false; + } + if !non_terminal { + return true; + } + if terminal_only { + return false; + } + let start = Self::prefill_cursor(r); + let next_stop = cut + .unwrap_or(r.prompt_tokens) + .min(r.prefill_limit()) + .min(r.prompt_tokens); + let end = start.saturating_add(work); + let window = self.terminal_prefill_window(); + !(end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window)) + } + + fn packed_prefill_candidates( + &self, + output: &mut Vec, + values: &[LaneValue; REQUEST_LANES], + age_price: f64, + prefill_plans: &mut [PrefillSlotPlan; REQUEST_LANES], + ) { + for &(kind, batch, width, packed) in &self.packed_prefill_catalog { + let Some(duration_ns) = self.costs.packed_prefill_duration(kind, batch, width, packed) + else { + continue; + }; + let non_terminal = self.is_non_terminal_prefill_step(kind, batch, width, packed); + let (offers, count) = self.packed_prefill_offers( + kind, + width, + non_terminal, + duration_ns, + values, + age_price, + prefill_plans, + None, + ); + let Some(choice) = + Self::select_packed_prefill_cohort(&offers[..count], batch, packed, None) + else { + continue; + }; + output.push(Candidate { + host_lengths: Some(choice.lengths), + draft_tokens: 0, + packed_token_capacity: packed, + kind, + mask: choice.mask, + batch, + capacity: width, + prefill_capacity: 0, + prefill_slot: None, + work: choice.total_work, + duration_ns, + rate: ValueRate::new(duration_ns, choice.total_value, age_price), + feedback: !kind.pipelines(), + }); + } + } + fn add_candidate( &self, output: &mut Vec, @@ -1533,6 +1875,7 @@ impl RequestScheduler { self.mixed_candidates(output, values, age_price, false); self.packed_round_candidates(output, values, age_price, false); let mut prefill_plans = [PrefillSlotPlan::default(); REQUEST_LANES]; + self.packed_prefill_candidates(output, values, age_price, &mut prefill_plans); for kind in [ GraphKind::Prefill, GraphKind::TerminalPrefill, @@ -1734,17 +2077,49 @@ impl RequestScheduler { return false; } if candidate.kind == GraphKind::Prefill { - let slot = bits(candidate.mask).next().unwrap(); - let request = self.slots[slot].request.as_ref().unwrap(); - let cut = self.checkpoint_cut(request); - let work = self.prefill_work_through(request, candidate.capacity, cut); - if self.resolve_prefill_kind(request, candidate.capacity, work, cut) - != GraphKind::Prefill - || self.prefill_requires_terminal_completion_for_age( - request, cut, age_price, - ) - { - return false; + if candidate.batch == 1 { + let slot = bits(candidate.mask).next().unwrap(); + let request = self.slots[slot].request.as_ref().unwrap(); + let cut = self.checkpoint_cut(request); + let work = self.prefill_work_through(request, candidate.capacity, cut); + if self.resolve_prefill_kind(request, candidate.capacity, work, cut) + != GraphKind::Prefill + || self.prefill_requires_terminal_completion_for_age( + request, cut, age_price, + ) + { + return false; + } + } else { + let non_terminal = self.is_non_terminal_prefill_step( + candidate.kind, + candidate.batch, + candidate.capacity, + candidate.packed_token_capacity, + ); + for slot in bits(candidate.mask) { + let request = self.slots[slot].request.as_ref().unwrap(); + let cut = self.checkpoint_cut(request); + let terminal_only = self + .prefill_requires_terminal_completion_for_age( + request, cut, age_price, + ); + let work = candidate + .host_lengths + .map_or(0, |lengths| lengths[slot]); + if work == 0 + || !self.packed_prefill_lane_compatible( + request, + candidate.kind, + non_terminal, + terminal_only, + work, + cut, + ) + { + return false; + } + } } } true @@ -1775,7 +2150,8 @@ impl RequestScheduler { log_scale: f64, mut origin: PlanOrigin, ) -> Option { - if (candidate.kind.is_prefill() || candidate.prefill_slot.is_some()) + if ((candidate.kind.is_prefill() && candidate.batch == 1) + || candidate.prefill_slot.is_some()) && matches!(origin, PlanOrigin::Ordinary | PlanOrigin::Discovery) { let slot = candidate.prefill_slot.unwrap_or_else(|| bits(candidate.mask).next().unwrap()); @@ -1905,7 +2281,9 @@ impl RequestScheduler { lanes.push(ScheduledLane { request: r.handle, start_position: r.scheduled_consumed, - tokens: if kind.is_prefill() { + tokens: if let Some(ref host) = lengths { + host[slot] + } else if kind.is_prefill() { let capacity = if candidate.kind == GraphKind::Mixed { candidate.prefill_capacity } else { @@ -1914,9 +2292,7 @@ impl RequestScheduler { let cut = self.checkpoint_cut(r); self.prefill_work_through(r, capacity, cut) } else { - if candidate.packed_token_capacity != 0 { - lengths.as_ref().unwrap()[slot] - } else { self.lane_tokens(r, kind, candidate.capacity) } + self.lane_tokens(r, kind, candidate.capacity) }, }); } diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 19944eae7..9ec0834bb 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -9506,3 +9506,331 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() ); } } + +#[test] +fn packed_prefill_burst_beats_solo_preserves_isolation_and_respects_budget() { + use crate::execution::GraphDescriptor; + let limits = SchedulerLimits { + max_active: 8, + request_slots: 8, + max_sequence_tokens: 4096, + prefill_chunk_size: 1024, + pages: 2048, + snapshots: 64, + }; + let caps = SchedulerCapabilities { + completion_token_capacity: 8, + vocabulary: 32000, + page_tokens: 64, + vision: crate::model::VisionCapabilities { + feature_slots: 4, + features_per_request: 256, + max_images: 4, + patches_per_feature: 1, + patch_capacities: vec![64], + }, + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: Some(1), + }; + let mut graphs = vec![]; + for batch in [1usize, 4, 8] { + for kind in [ + GraphKind::Init, + GraphKind::Restore, + GraphKind::Snapshot, + GraphKind::Resume, + GraphKind::Decode, + ] { + graphs.push(GraphDescriptor { + name: format!("{kind:?}-{batch}"), + kind, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: batch, + token_capacity: 1, + prefill_capacity: 0, + packed_token_capacity: 0, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + } + for cap in [128usize, 256, 512, 1024] { + for kind in [GraphKind::Prefill, GraphKind::TerminalPrefill, GraphKind::ScoredPrefill] { + graphs.push(GraphDescriptor { + name: format!("{kind:?}-1-{cap}"), + kind, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: 1, + token_capacity: cap, + prefill_capacity: 0, + packed_token_capacity: 0, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + } + graphs.push(GraphDescriptor { + name: "vision-1-64".into(), + kind: GraphKind::Vision, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: 1, + token_capacity: 64, + prefill_capacity: 0, + packed_token_capacity: 0, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + let packed_shapes = [ + (GraphKind::TerminalPrefill, 4, 128, 512), + (GraphKind::TerminalPrefill, 4, 256, 512), + (GraphKind::TerminalPrefill, 8, 128, 1024), + ]; + for (kind, batch, width, packed) in packed_shapes { + graphs.push(GraphDescriptor { + name: format!("{kind:?}-{batch}-{width}-{packed}"), + kind, + sampling_mode: SamplingMode::General, + handle: 1, + batch_capacity: batch, + token_capacity: width, + prefill_capacity: 0, + packed_token_capacity: packed, + draft_tokens: 0, + confidence_width: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + + let make = || { + let mut s = RequestScheduler::new([0; 32], limits, caps.clone()).unwrap(); + s.prefill_graphs(&[128, 256, 512, 1024]).unwrap(); + s.terminal_prefill_graphs(&[128, 256, 512, 1024]).unwrap(); + s.scored_prefill_graphs(&[128, 256, 512, 1024]).unwrap(); + s.packed_prefill_graphs(&packed_shapes).unwrap(); + s.measured_graph_durations(&graphs).unwrap(); + for batch in [1, 4, 8] { + for kind in [ + GraphKind::Init, + GraphKind::Restore, + GraphKind::Snapshot, + GraphKind::Resume, + GraphKind::Decode, + ] { + set_cost(&mut s, kind, batch, 1, MS); + } + } + set_cost(&mut s, GraphKind::Vision, 1, 64, 2 * MS); + for cap in [128, 256, 512, 1024] { + let ns = (cap as u64 / 128) * 5 * MS; + set_cost(&mut s, GraphKind::Prefill, 1, cap, ns); + set_cost(&mut s, GraphKind::TerminalPrefill, 1, cap, ns); + set_cost(&mut s, GraphKind::ScoredPrefill, 1, cap, ns); + } + for &(kind, batch, width, packed) in &packed_shapes { + let step = ScheduledStep { + draft_tokens: 0, + kind, + batch_capacity: batch, + token_capacity: width, + packed_token_capacity: packed, + mixed: None, + lanes: vec![], + requires_feedback: true, + }; + s.costs.set_measured(&step, 7 * MS); + } + s + }; + + // 1. Solo prompt stays on B == 1 even when packed shapes are faster per token. + { + let mut s = make(); + let h = add(&mut s, 1, 96, 16); + initialize(&mut s, h); + let plan = s.plan().unwrap(); + assert_eq!(plan.batch_capacity, 1); + assert_eq!(plan.packed_token_capacity, 0); + assert_eq!(plan.lanes.len(), 1); + } + + // 2. Concurrent burst of 4 short prompts packs into TerminalPrefill(4, 128, 512), + // and Init(4) batches them first via continuation valuation. + { + let mut s = make(); + let handles: Vec<_> = (0..4).map(|i| add(&mut s, 10 + i, 96, 16)).collect(); + let init_plan = s.plan().unwrap(); + assert_eq!(init_plan.kind, GraphKind::Init); + assert_eq!(init_plan.lanes.len(), 4); + let f1 = Fence(s.submitted.0 + 1); + s.commit(&init_plan, f1).unwrap(); + let r1 = completion_records(&s, &init_plan, f1, 0); + s.complete(f1, &r1, gpu_time(MS)).unwrap(); + + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert_eq!(plan.batch_capacity, 4); + assert_eq!(plan.token_capacity, 128); + assert_eq!(plan.packed_token_capacity, 512); + assert_eq!(plan.lanes.len(), 4); + assert!(plan.lanes.iter().all(|l| l.tokens == 96)); + + let f2 = Fence(s.submitted.0 + 1); + s.commit(&plan, f2).unwrap(); + let r2 = completion_records(&s, &plan, f2, 77); + let tokens = s.complete(f2, &r2, gpu_time(7 * MS)).unwrap(); + assert_eq!(tokens.len(), 4); + for h in handles { + let req = s.request(h).unwrap(); + assert!( + matches!(req.phase, RequestPhase::Decode | RequestPhase::Snapshot), + "unexpected phase {:?} after packed terminal prefill", + req.phase + ); + assert_eq!(req.consumed_tokens, 96); + } + } + + // 3. Mixed finishing + continuing lanes: lanes 0 (64) & 2 (96) finish while lane 1 (300) + // advances to 256 in (4, 256, 512) and remains in Prefill. + { + let mut s = make(); + let h0 = add(&mut s, 20, 64, 16); + let h1 = add(&mut s, 21, 300, 16); + let h2 = add(&mut s, 22, 96, 16); + for h in [h0, h1, h2] { + initialize(&mut s, h); + } + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert_eq!(plan.batch_capacity, 4); + assert_eq!(plan.token_capacity, 256); + assert_eq!(plan.packed_token_capacity, 512); + assert_eq!(plan.lanes.len(), 3); + let by_handle = |h| plan.lanes.iter().find(|l| l.request == h).unwrap().tokens; + assert_eq!((by_handle(h0), by_handle(h1), by_handle(h2)), (64, 256, 96)); + + let f = Fence(s.submitted.0 + 1); + s.commit(&plan, f).unwrap(); + let mut recs = completion_records(&s, &plan, f, 42); + // Lane 1 did not reach prompt_tokens (256 < 300), so no generated token. + recs[h1.slot as usize].generated_tokens = 0; + recs[h1.slot as usize].token_id = -1; + let tokens = s.complete(f, &recs, gpu_time(7 * MS)).unwrap(); + assert_eq!(tokens.len(), 2); + assert!(matches!( + s.request(h0).unwrap().phase, + RequestPhase::Decode | RequestPhase::Snapshot + )); + assert_eq!(s.request(h1).unwrap().phase, RequestPhase::Prefill); + assert_eq!(s.request(h1).unwrap().consumed_tokens, 256); + assert!(matches!( + s.request(h2).unwrap().phase, + RequestPhase::Decode | RequestPhase::Snapshot + )); + } + + // 4. Budget constraint B*W > P: 4 prompts of 200 tokens with (4, 256, 512) must keep sum <= 512. + { + let mut s = make(); + for i in 0..4 { + let h = add(&mut s, 30 + i, 200, 16); + initialize(&mut s, h); + } + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert!(plan.batch_capacity >= 2); + let sum: usize = plan.lanes.iter().map(|l| l.tokens).sum(); + assert!(sum <= plan.packed_token_capacity); + assert!(plan.lanes.iter().all(|l| l.tokens <= plan.token_capacity)); + } + + // 5. Vision and prompt_logprobs requests are excluded from B >= 2 packed prefill. + { + let mut s = make(); + let t0 = add(&mut s, 40, 96, 16); + let t1 = add(&mut s, 41, 96, 16); + let scored = s + .admit(RequestSpec { + prompt: (1..=96).collect(), + message_boundaries: vec![], + conditioning: vec![], + max_new_tokens: 16, + grammar_constrained: false, + prompt_logprobs: true, + growable_output: false, + preserve_message_anchor: false, + }) + .unwrap(); + let vision = add(&mut s, 42, 96, 16); + for h in [t0, t1, scored, vision] { + initialize(&mut s, h); + } + s.request_mut(vision).unwrap().image_slot = Some(0); + + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert_eq!(plan.batch_capacity, 4); + assert_eq!(plan.lanes.len(), 2); + assert!(plan.lanes.iter().all(|l| l.request == t0 || l.request == t1)); + } + + // 6. Unmeasured discovery: prune_padding drops oversized (8, 128, 1024) in favor of (4, 128, 512) + // when 4 short prompts fit cleanly in (4, 128, 512). + { + let mut s = RequestScheduler::new([0; 32], limits, caps.clone()).unwrap(); + s.prefill_graphs(&[128, 256, 512, 1024]).unwrap(); + s.terminal_prefill_graphs(&[128, 256, 512, 1024]).unwrap(); + s.packed_prefill_graphs(&packed_shapes).unwrap(); + s.measured_graph_durations(&graphs).unwrap(); + for batch in [1, 4, 8] { + set_cost(&mut s, GraphKind::Init, batch, 1, MS); + set_cost(&mut s, GraphKind::Decode, batch, 1, MS); + } + for cap in [128, 256, 512, 1024] { + set_cost(&mut s, GraphKind::Prefill, 1, cap, 5 * MS); + set_cost(&mut s, GraphKind::TerminalPrefill, 1, cap, 5 * MS); + } + for i in 0..4 { + let h = add(&mut s, 60 + i, 96, 16); + initialize(&mut s, h); + } + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert_eq!(plan.batch_capacity, 4); + assert_eq!(plan.token_capacity, 128); + assert_eq!(plan.packed_token_capacity, 512); + assert_eq!(plan.lanes.len(), 4); + } + + // 7. Continuation cohort selection reserves a promoted lane so higher-value ready lanes + // cannot crowd out promoted lanes and spuriously drop the packed continuation. + { + let offers = [ + (0, 64, 500.0, false), + (1, 64, 400.0, false), + (2, 64, 100.0, true), + ]; + let choice = RequestScheduler::select_packed_prefill_cohort(&offers, 2, 128, Some(1)) + .expect("promoted lane must be reserved instead of crowded out by ready lanes"); + assert_eq!(choice.promoted_count(), 1); + assert_eq!(choice.promoted_mask, 1u64 << 2); + assert_eq!(choice.mask, (1u64 << 0) | (1u64 << 2)); + assert_eq!(choice.selected(), 2); + } +} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 1e5cad1f1..d5d9328d7 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -846,19 +846,31 @@ impl ModelRuntime { ) }) .and_then(|()| { - scheduler.scored_prefill_graphs(&executor.manifest().graphs.iter() - .filter(|g| g.kind == GraphKind::ScoredPrefill).map(|g| g.token_capacity).collect::>())?; - scheduler.terminal_prefill_graphs(&executor.manifest().graphs.iter() - .filter(|g| g.kind == GraphKind::TerminalPrefill).map(|g| g.token_capacity).collect::>())?; - scheduler.prefill_graphs( - &executor - .manifest() - .graphs - .iter() - .filter(|graph| graph.kind == crate::execution::GraphKind::Prefill) - .map(|graph| graph.token_capacity) - .collect::>(), - ) + let mut scored = Vec::new(); + let mut terminal = Vec::new(); + let mut prefill = Vec::new(); + let mut packed = Vec::new(); + for graph in &executor.manifest().graphs { + match (graph.kind, graph.batch_capacity) { + (GraphKind::ScoredPrefill, 1) => scored.push(graph.token_capacity), + (GraphKind::TerminalPrefill, 1) => { + terminal.push(graph.token_capacity) + } + (GraphKind::Prefill, 1) => prefill.push(graph.token_capacity), + (GraphKind::Prefill | GraphKind::TerminalPrefill, 2..) => packed + .push(( + graph.kind, + graph.batch_capacity, + graph.token_capacity, + graph.packed_token_capacity, + )), + _ => {} + } + } + scheduler.scored_prefill_graphs(&scored)?; + scheduler.terminal_prefill_graphs(&terminal)?; + scheduler.prefill_graphs(&prefill)?; + scheduler.packed_prefill_graphs(&packed) }) .and_then(|()| { scheduler.speculative_graphs( diff --git a/ignition/cli/serve.py b/ignition/cli/serve.py index 2cdfa863e..a4d350206 100644 --- a/ignition/cli/serve.py +++ b/ignition/cli/serve.py @@ -462,7 +462,9 @@ def debug_serve(args) -> int: **preparation_options) if plan.speculation is not None and plan.speculation.packed_verification: local_model = prepared.model if hasattr(prepared, "model") else prepared - if not any(signature.packed_token_capacity for signature in local_model.signatures.values()): + if not any( + signature.kind == "speculative" and signature.packed_token_capacity + for signature in local_model.signatures.values()): prepared.close() raise UsageError("this prepared recipe does not declare packed verification capacities") if plan.speculation.draft_prefix_selection == "gpu" and not any( diff --git a/ignition/direct/scheduler.py b/ignition/direct/scheduler.py index 2c17bf0ee..b9d425354 100644 --- a/ignition/direct/scheduler.py +++ b/ignition/direct/scheduler.py @@ -197,6 +197,8 @@ def of(cls, model): key = (signature.kind, signature.batch_capacity, signature.token_capacity) if signature.kind == "speculative": key += (signature.packed_token_capacity, signature.draft_tokens) + elif signature.kind in ("prefill", "terminal_prefill") and signature.batch_capacity >= 2: + key += (signature.packed_token_capacity,) graphs[key] = name return cls(capacity=buffers["row_slot_ids"].numel(), max_active=model.max_active, context=config["max_sequence_tokens"], page_tokens=config["model_contract"]["cache"]["page_tokens"], @@ -286,7 +288,7 @@ def snapshot_row(self, snapshot): def capacities(self, kind, *, width=None): """Prepared capacities of one graph kind: token capacities for prefill, batch capacities otherwise.""" if kind in ("prefill", "terminal_prefill"): - return sorted({key[2] for key in self.graphs if key[0] == kind}) + return sorted({key[2] for key in self.graphs if len(key) == 3 and key[0] == kind and key[1] == 1}) return sorted({key[1] for key in self.graphs if len(key) == 3 and key[0] == kind and (width is None or key[2] == width)}) diff --git a/ignition/preparation/execution.py b/ignition/preparation/execution.py index 238c214dc..19f93283b 100644 --- a/ignition/preparation/execution.py +++ b/ignition/preparation/execution.py @@ -75,9 +75,24 @@ def __post_init__(self): raise ValueError("draft depth requires a speculation-enabled graph") elif self.prefill_capacity: raise ValueError("only mixed graphs declare a separate prefill capacity") - if (type(self.packed_token_capacity) is not int or self.packed_token_capacity < 0 - or (self.packed_token_capacity and (self.kind != "speculative" - or not self.batch_capacity <= self.packed_token_capacity <= self.batch_capacity * self.token_capacity))): + if type(self.packed_token_capacity) is not int or self.packed_token_capacity < 0: + raise ValueError("packed token capacity must be a nonnegative integer") + if self.kind in ("prefill", "terminal_prefill") and self.batch_capacity >= 2: + if (not 2 <= self.batch_capacity <= MAX_CONCURRENCY + or self.packed_token_capacity < 64 + or self.packed_token_capacity % 64 + or self.packed_token_capacity >= 1 << 31 + or self.token_capacity > self.packed_token_capacity + or not self.batch_capacity <= self.packed_token_capacity <= self.batch_capacity * self.token_capacity): + raise ValueError( + "packed prefill graphs require aligned total token capacity within the batch and per-request bounds" + ) + if any(name in self.inputs for name in ( + "vision_token_indices", "vision_feature_slot", "vision_left", "vision_right")): + raise ValueError("packed prefill graphs do not support vision inputs") + elif self.packed_token_capacity and ( + self.kind != "speculative" + or not self.batch_capacity <= self.packed_token_capacity <= self.batch_capacity * self.token_capacity): raise ValueError("packed verification capacity must fit the batch and per-request prefix bounds") if self.kind == "speculative": if "speculative_prefix_limits" in self.inputs and ( diff --git a/ignition/preparation/model.py b/ignition/preparation/model.py index 4ae9e0bfe..d3bd85c33 100644 --- a/ignition/preparation/model.py +++ b/ignition/preparation/model.py @@ -29,6 +29,14 @@ def __init__(self, *, server_config, memory_report, session, close_resources=(), if forwards is not None and set(forwards) != set(self.serving_graphs): raise ValueError("retained forwards must cover exactly the captured graphs") self.server_config = dict(server_config) + prefill_chunk = self.server_config.get("prefill_chunk_size") + for name, signature in self.signatures.items(): + if signature.kind in ("prefill", "terminal_prefill") and signature.batch_capacity >= 2: + if prefill_chunk is None or signature.packed_token_capacity > prefill_chunk: + raise ValueError( + f"packed prefill graph {name!r} packed_token_capacity " + f"({signature.packed_token_capacity}) exceeds prefill_chunk_size ({prefill_chunk})" + ) if self.tuned_bindings: contract = dict(self.server_config["model_contract"]) contract["graphs"] = [dict(graph, tuned_bindings=[dict(buffer=value.buffer, tuning_graph=value.tuning_graph) diff --git a/scripts/scheduling_sim/learning_policy.py b/scripts/scheduling_sim/learning_policy.py index af99086aa..655b8db53 100644 --- a/scripts/scheduling_sim/learning_policy.py +++ b/scripts/scheduling_sim/learning_policy.py @@ -165,7 +165,8 @@ def _means(self, now_ms: float) -> dict[str, float | None]: def _graph(self, spec: GraphSpec, duration: float | None) -> Graph: # Unknown descriptors carry geometry only; their placeholder never enters a rate. return Graph(spec.name, duration if duration is not None else 1.0, - spec.prefill_capacity, spec.decode_capacity, spec.width) + spec.prefill_capacity, spec.decode_capacity, spec.width, + spec.prefill_batch_capacity, spec.packed_token_capacity) def _unknown_lane_value(self, lane: Lane) -> float: value = self.utility.lane_value(lane) @@ -185,10 +186,11 @@ def _actions(self, views: list[View], costs: dict[str, float | None], result = [] for action in actions: graph = action.graph - if costs[graph.name] is None and graph.prefill_capacity: + if costs[graph.name] is None and graph.prefill_capacity and graph.prefill_batch_capacity == 1: prompt = next((lane for lane in action.lanes if lane.prefill), None) remaining = next((v.remaining_prefill for v in views if prompt and v.name == prompt.name), 0) - if any(g.prefill_capacity and g.prefill_capacity < graph.prefill_capacity + if any(g.prefill_capacity and g.prefill_batch_capacity == 1 + and g.prefill_capacity < graph.prefill_capacity and g.decode_capacity == graph.decode_capacity and g.width == graph.width and (prompt is None or min(remaining, g.prefill_capacity) == prompt.prefill) for g in self.catalog): @@ -199,14 +201,14 @@ def _actions(self, views: list[View], costs: dict[str, float | None], def _natural_fit_prefill_capacity(self, remaining: int) -> int | None: best = None for graph in self.catalog: - if graph.prefill_capacity and not graph.decode_capacity: + if graph.prefill_capacity and not graph.decode_capacity and graph.prefill_batch_capacity == 1: work = min(remaining, graph.prefill_capacity) if work and (best is None or work > best[0] or (work == best[0] and graph.prefill_capacity < best[1])): best = (work, graph.prefill_capacity) return best[1] if best is not None else None def _interpolated_prefill_duration(self, target: GraphSpec, means: dict[str, float | None]) -> float | None: - if not target.prefill_capacity or target.decode_capacity: + if not target.prefill_capacity or target.decode_capacity or target.prefill_batch_capacity >= 2: return None lo = hi = decode_floor = None for graph in self.catalog: @@ -216,7 +218,9 @@ def _interpolated_prefill_duration(self, target: GraphSpec, means: dict[str, flo if graph.decode_capacity and not graph.prefill_capacity: decode_floor = duration if decode_floor is None else min(decode_floor, duration) continue - if not graph.prefill_capacity or graph.decode_capacity or graph.prefill_capacity == target.prefill_capacity: + if (not graph.prefill_capacity or graph.decode_capacity + or graph.prefill_batch_capacity >= 2 + or graph.prefill_capacity == target.prefill_capacity): continue cap = graph.prefill_capacity if cap > target.prefill_capacity: @@ -240,13 +244,15 @@ def _interpolated_prefill_duration(self, target: GraphSpec, means: dict[str, flo def _rank_key(self, action: Action, clocks: dict[str, float]): return (-self.utility.score(action), action.graph.duration_ms, min(clocks[lane.name] for lane in action.lanes), - action.graph.prefill_capacity + action.graph.decode_capacity * action.graph.width, + (action.graph.packed_token_capacity or action.graph.prefill_capacity) + + action.graph.decode_capacity * action.graph.width, action.graph.name, tuple(lane.name for lane in action.lanes)) def _bootstrap_key(self, action: Action, clocks: dict[str, float]): return (-sum(self._unknown_lane_value(lane) for lane in action.lanes), min(clocks[lane.name] for lane in action.lanes), - action.graph.prefill_capacity + action.graph.decode_capacity * action.graph.width, + (action.graph.packed_token_capacity or action.graph.prefill_capacity) + + action.graph.decode_capacity * action.graph.width, action.graph.name, tuple(lane.name for lane in action.lanes)) def _ensure_estimates(self, names: set[str], means: dict[str, float | None], @@ -307,13 +313,15 @@ def choose(self, views: list[View], now_ms: float) -> Decision: for v in views if v.remaining_prefill} raw_native_names = {a.graph.name for a in raw_native} for graph in self.catalog: - if graph.name in raw_native_names and graph.prefill_capacity and not graph.decode_capacity: + if (graph.name in raw_native_names and graph.prefill_capacity + and not graph.decode_capacity and graph.prefill_batch_capacity == 1): estimate = self._interpolated_prefill_duration(graph, means) if estimate is not None: interpolated[graph.name] = estimate for action in raw_native: graph = action.graph - if graph.prefill_capacity and not graph.decode_capacity: + if (graph.prefill_capacity and not graph.decode_capacity + and graph.prefill_batch_capacity == 1): if graph.name in interpolated: continue if graph.prefill_capacity != nat_fit.get(action.lanes[0].name): diff --git a/scripts/scheduling_sim/model.py b/scripts/scheduling_sim/model.py index de2547cf0..5d53b74dc 100644 --- a/scripts/scheduling_sim/model.py +++ b/scripts/scheduling_sim/model.py @@ -27,16 +27,28 @@ class Graph: prefill_capacity: int = 0 decode_capacity: int = 0 width: int = 1 + prefill_batch_capacity: int = 1 + packed_token_capacity: int = 0 def __post_init__(self): if not self.name or not isfinite(self.duration_ms) or self.duration_ms <= 0: raise ValueError("graphs require a name and a positive finite duration") - if min(self.prefill_capacity, self.decode_capacity) < 0 or self.width < 1: + if (min(self.prefill_capacity, self.decode_capacity, self.packed_token_capacity) < 0 + or self.width < 1 or self.prefill_batch_capacity < 1): raise ValueError("invalid graph capacities") if not self.prefill_capacity and not self.decode_capacity: raise ValueError("a graph must have a prefill or decode lane") if not self.decode_capacity and self.width != 1: raise ValueError("prefill-only graphs cannot have speculative lanes") + if self.prefill_batch_capacity >= 2: + if not self.prefill_capacity or self.decode_capacity or self.width != 1: + raise ValueError("packed prefill graphs must be prefill-only with width 1") + if not (max(self.prefill_batch_capacity, self.prefill_capacity) + <= self.packed_token_capacity + <= self.prefill_batch_capacity * self.prefill_capacity): + raise ValueError("invalid packed prefill token capacity") + elif self.packed_token_capacity != 0: + raise ValueError("packed_token_capacity requires prefill_batch_capacity >= 2") @dataclass(frozen=True) diff --git a/scripts/scheduling_sim/scheduler.py b/scripts/scheduling_sim/scheduler.py index 6b2208c27..104d2f22d 100644 --- a/scripts/scheduling_sim/scheduler.py +++ b/scripts/scheduling_sim/scheduler.py @@ -8,6 +8,56 @@ from .model import Action, Graph, Lane, Value, View, expected_output +def _select_packed_prefill_lanes( + prefills: list[View], + graph: Graph, + reward: Callable[[Lane, Graph], float], +) -> tuple[Lane, ...] | None: + """Two-order greedy cohort selection mirroring Helios select_packed_prefill_cohort.""" + if len(prefills) < 2: + return None + offers = [] + for view in prefills: + tokens = min(view.remaining_prefill, graph.prefill_capacity) + if tokens <= 0: + continue + emitted = float(tokens == view.remaining_prefill) + lane = Lane(view.name, tokens, 0, emitted, view.weight) + offers.append((view, lane, reward(lane, graph))) + if len(offers) < 2: + return None + best: tuple[float, int, int, tuple[str, ...], tuple[Lane, ...]] | None = None + for by_density in (False, True): + ordered = sorted( + offers, + key=lambda item: ( + -(item[2] / item[1].prefill) if by_density else -item[2], + -item[2], + item[1].prefill, + item[0].last_service_ms, + item[0].name, + ), + ) + chosen: list[Lane] = [] + total_tokens = 0 + total_val = 0.0 + for _, lane, val in ordered: + if len(chosen) == graph.prefill_batch_capacity: + break + if total_tokens + lane.prefill > graph.packed_token_capacity: + continue + chosen.append(lane) + total_tokens += lane.prefill + total_val += val + if len(chosen) < 2: + continue + names = tuple(lane.name for lane in chosen) + key = (total_val, len(chosen), total_tokens, tuple(reversed(names))) + if best is None or key[:3] > best[:3] or (key[:3] == best[:3] and names < best[3]): + best = (total_val, len(chosen), total_tokens, names, tuple(chosen)) + return None if best is None else best[4] + + def candidates(views: list[View], catalog: tuple[Graph, ...], value: Value, *, lane_value: Callable[[Lane, Graph], float] | None = None) -> list[Action]: if len({v.name for v in views}) != len(views): @@ -17,6 +67,11 @@ def candidates(views: list[View], catalog: tuple[Graph, ...], value: Value, actions = [] reward = lane_value if lane_value is not None else lambda lane, graph: lane.useful_work(value) for graph in catalog: + if graph.prefill_batch_capacity >= 2: + chosen = _select_packed_prefill_lanes(prefills, graph, reward) + if chosen: + actions.append(Action(graph, chosen)) + continue rows = [] if graph.decode_capacity: for view in decodes: @@ -43,7 +98,8 @@ def rank(views: list[View], catalog: tuple[Graph, ...], value: Value) -> list[Ac return sorted(candidates(views, catalog, value), key=lambda a: ( -a.score(value), a.graph.duration_ms, min(clocks[lane.name] for lane in a.lanes), - a.graph.prefill_capacity + a.graph.decode_capacity * a.graph.width, + (a.graph.packed_token_capacity or a.graph.prefill_capacity) + + a.graph.decode_capacity * a.graph.width, a.graph.name, tuple(lane.name for lane in a.lanes), )) diff --git a/scripts/scheduling_sim/simulator.py b/scripts/scheduling_sim/simulator.py index 1dd8bb599..bf005a537 100644 --- a/scripts/scheduling_sim/simulator.py +++ b/scripts/scheduling_sim/simulator.py @@ -88,6 +88,8 @@ def run(requests: list[Request], catalog: tuple[Graph, ...], value: Value, events.append({"start_ms": now, "end_ms": end, "graph": action.graph.name, "duration_ms": action.graph.duration_ms, "prefill_capacity": action.graph.prefill_capacity, + "prefill_batch_capacity": action.graph.prefill_batch_capacity, + "packed_token_capacity": action.graph.packed_token_capacity, "decode_capacity": action.graph.decode_capacity, "verification_width": action.graph.width, "expected_work": action.expected_work(value), "score": action.score(value), diff --git a/scripts/scheduling_sim/timing.py b/scripts/scheduling_sim/timing.py index bad8ddefe..1f17fe4a8 100644 --- a/scripts/scheduling_sim/timing.py +++ b/scripts/scheduling_sim/timing.py @@ -17,25 +17,42 @@ class GraphSpec: prefill_capacity: int = 0 decode_capacity: int = 0 width: int = 1 + prefill_batch_capacity: int = 1 + packed_token_capacity: int = 0 def __post_init__(self): if not isinstance(self.name, str) or not self.name: raise ValueError("a graph requires a name") - if any(type(v) is not int for v in (self.prefill_capacity, self.decode_capacity, self.width)): + if any(type(v) is not int for v in ( + self.prefill_capacity, self.decode_capacity, self.width, + self.prefill_batch_capacity, self.packed_token_capacity)): raise ValueError("graph capacities and width must be integers") - if min(self.prefill_capacity, self.decode_capacity) < 0 or self.width < 1: + if (min(self.prefill_capacity, self.decode_capacity, self.packed_token_capacity) < 0 + or self.width < 1 or self.prefill_batch_capacity < 1): raise ValueError("invalid graph capacities") if not self.prefill_capacity and not self.decode_capacity: raise ValueError("a graph must have a prefill or decode lane") if not self.decode_capacity and self.width != 1: raise ValueError("prefill-only graphs cannot have speculative lanes") + if self.prefill_batch_capacity >= 2: + if not self.prefill_capacity or self.decode_capacity or self.width != 1: + raise ValueError("packed prefill graphs must be prefill-only with width 1") + if not (max(self.prefill_batch_capacity, self.prefill_capacity) + <= self.packed_token_capacity + <= self.prefill_batch_capacity * self.prefill_capacity): + raise ValueError("invalid packed prefill token capacity") + elif self.packed_token_capacity != 0: + raise ValueError("packed_token_capacity requires prefill_batch_capacity >= 2") @classmethod def from_graph(cls, graph: Graph) -> "GraphSpec": - return cls(graph.name, graph.prefill_capacity, graph.decode_capacity, graph.width) + return cls(graph.name, graph.prefill_capacity, graph.decode_capacity, graph.width, + graph.prefill_batch_capacity, graph.packed_token_capacity) @property def family(self) -> str: + if self.prefill_batch_capacity >= 2: + return "packed_prefill" if self.prefill_capacity and self.decode_capacity: return "mixed" return "prefill" if self.prefill_capacity else "decode" diff --git a/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index 006954276..0cdd0a6ef 100644 --- a/scripts/scheduling_sim/utility.py +++ b/scripts/scheduling_sim/utility.py @@ -306,7 +306,8 @@ def choose(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = actions = candidates(views, catalog, self.value, lane_value=self.action_lane_value) return min(actions, key=lambda a: ( -self.score(a), a.graph.duration_ms, min(clocks[lane.name] for lane in a.lanes), - a.graph.prefill_capacity + a.graph.decode_capacity * a.graph.width, + (a.graph.packed_token_capacity or a.graph.prefill_capacity) + + a.graph.decode_capacity * a.graph.width, a.graph.name, tuple(lane.name for lane in a.lanes))) def observe(self, duration_ms: float, committed: list[dict]): diff --git a/scripts/scheduling_sim/workloads.py b/scripts/scheduling_sim/workloads.py index b2ae84d83..436c8e088 100644 --- a/scripts/scheduling_sim/workloads.py +++ b/scripts/scheduling_sim/workloads.py @@ -6,9 +6,16 @@ from .model import Graph, Request -def catalog(*, mixed: bool = False) -> tuple[Graph, ...]: +def catalog(*, mixed: bool = False, packed_prefill: bool = False) -> tuple[Graph, ...]: graphs = [Graph(f"prefill-{p}", 2 + p / 64, prefill_capacity=p) for p in (64, 128, 256, 512, 1024, 2048, 4096)] + if packed_prefill: + for batch, width, packed in ((2, 512, 1024), (2, 1024, 2048), (4, 512, 2048), (4, 1024, 4096)): + graphs.append(Graph(f"packed-prefill-b{batch}-w{width}-p{packed}", + 2 + packed / 64, + prefill_capacity=width, + prefill_batch_capacity=batch, + packed_token_capacity=packed)) for batch in (1, 2, 4, 8, 16): for width, singleton_ms in ((1, 15.0), (3, 17.3), (8, 30.0)): decode_ms = singleton_ms + 2 * (batch - 1) diff --git a/tests/preparation/test_execution.py b/tests/preparation/test_execution.py index d5ce02ec5..31e37c1e3 100644 --- a/tests/preparation/test_execution.py +++ b/tests/preparation/test_execution.py @@ -404,3 +404,70 @@ def test_async_transfer_channel_rejects_external_extents_alignment_above_contain extent_directory="/tmp/ext.dir", extent_segments=("/tmp/ext.seg",), ) + + +def test_packed_prefill_signature_validates_geometry_and_rejects_vision(monkeypatch): + for kind in ("prefill", "terminal_prefill"): + sig = GraphSignature(kind, 4, 128, ("tokens",), packed_token_capacity=512) + assert (sig.batch_capacity, sig.token_capacity, sig.packed_token_capacity) == (4, 128, 512) + partial = GraphSignature(kind, 8, 256, ("tokens",), packed_token_capacity=1024) + assert partial.packed_token_capacity == 1024 + execution = _execution(graphs={f"{kind}_b4": object()}, signatures={f"{kind}_b4": sig}) + spans = [(4096, 4), (8192, 8), (12288, 2048), (16384, 128), (20480, 1)] + monkeypatch.setattr(execution, "_validate_resources", lambda: (9, [11], spans)) + graph = execution.manifest()["graphs"][0] + assert (graph["batch_capacity"], graph["token_capacity"], graph["packed_token_capacity"]) == (4, 128, 512) + + for bad in ( + dict(kind="prefill", batch_capacity=1, token_capacity=128, packed_token_capacity=128), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=0), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=96), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=256, packed_token_capacity=128), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=64, packed_token_capacity=320), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=512, + draft_tokens=1), + dict(kind="terminal_prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=512, + inputs=("token_ids", "vision_feature_slot")), + dict(kind="prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=512, + inputs=("token_ids", "vision_token_indices")), + dict(kind="scored_prefill", batch_capacity=4, token_capacity=128, packed_token_capacity=512, + inputs=("prompt_target_tokens",)), + ): + with pytest.raises((ValueError, TypeError)): + GraphSignature(**bad) + + +def test_prepared_model_rejects_packed_prefill_exceeding_prefill_chunk_size(): + from ignition.preparation.model import PreparedModel + + sig = GraphSignature("terminal_prefill", 4, 256, ("tokens",), packed_token_capacity=1024) + ok = _execution( + model_class=PreparedModel, + graphs={"tp_b4": object()}, + signatures={"tp_b4": sig}, + max_active=4, + server_config={"prefill_chunk_size": 1024}, + memory_report={}, + session=None, + ) + assert ok.server_config["prefill_chunk_size"] == 1024 + with pytest.raises(ValueError, match="exceeds prefill_chunk_size"): + _execution( + model_class=PreparedModel, + graphs={"tp_b4": object()}, + signatures={"tp_b4": sig}, + max_active=4, + server_config={"prefill_chunk_size": 512}, + memory_report={}, + session=None, + ) + with pytest.raises(ValueError, match="exceeds prefill_chunk_size"): + _execution( + model_class=PreparedModel, + graphs={"tp_b4": object()}, + signatures={"tp_b4": sig}, + max_active=4, + server_config={}, + memory_report={}, + session=None, + ) diff --git a/tests/test_scheduling_sim.py b/tests/test_scheduling_sim.py index 200e51b79..1e929f438 100644 --- a/tests/test_scheduling_sim.py +++ b/tests/test_scheduling_sim.py @@ -319,3 +319,34 @@ def test_cli_writes_scores_and_request_metrics(tmp_path): trace = [json.loads(line) for line in (tmp_path / "trace.jsonl").read_text().splitlines()] assert trace[0]["graph"] == "prefill-64" assert (tmp_path / "requests.csv").exists() + + +def test_packed_prefill_packs_burst_and_respects_lane_and_token_budgets(): + solo = catalog(packed_prefill=False) + packed = catalog(packed_prefill=True) + burst = [Request(f"p{i}", 512, 1) for i in range(4)] + + solo_res = run(burst, solo, Value(64), horizon_ms=5000) + packed_res = run(burst, packed, Value(64), horizon_ms=5000) + assert solo_res.summary["unfinished"] == 0 + assert packed_res.summary["unfinished"] == 0 + assert any(e["graph"].startswith("packed-prefill-") for e in packed_res.trace) + assert packed_res.summary["elapsed_ms"] < solo_res.summary["elapsed_ms"] + for event in packed_res.trace: + prefill_lanes = [lane for lane in event["lanes"] if lane["prefill"]] + assert len(prefill_lanes) <= event["prefill_batch_capacity"] + assert all(lane["prefill"] <= event["prefill_capacity"] for lane in prefill_lanes) + budget = event["packed_token_capacity"] or event["prefill_capacity"] + assert sum(lane["prefill"] for lane in prefill_lanes) <= budget + + # Solo prompt never uses B >= 2 packed prefill. + solo_choice = choose([prefill(512)], packed, Value(64)) + assert solo_choice.graph.prefill_batch_capacity == 1 + assert len(solo_choice.lanes) == 1 + + # Packed token budget caps aggregate work across lanes. + tight = (Graph("packed-b4-w512-p1024", 10.0, prefill_capacity=512, + prefill_batch_capacity=4, packed_token_capacity=1024),) + tight_choice = choose([prefill(512, f"r{i}") for i in range(4)], tight, Value(64)) + assert len(tight_choice.lanes) == 2 + assert sum(lane.prefill for lane in tight_choice.lanes) == 1024 diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index fa97626b3..3961f9565 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -15,7 +15,7 @@ MODEL = Path(__file__).resolve().parent ROOT = MODEL.parent.parent PRINT_LOCK = threading.Lock() -TEST = "scheduler::lifecycle_tests::scheduler_matches_lifecycle_model" +TEST = "scheduler::lifecycle_tests::" RANK_TEST = "execution::threaded::protocol_tests::rank_coordinator_matches_model" DISPATCH_RING_TEST = "execution::threaded::tests::dispatch_ring_matches_model_edges" DISPATCH_RING_SUITE = "execution::threaded::tests::" @@ -182,7 +182,7 @@ def check_observations(output, directory, java, jar, module, prefix, width, *, j def run_observed_checks(test_bin, directory, java, jar, jobs): def run_rust(check): module, test, prefix, width = check - exact = ["--exact"] if test == TEST else [] + exact = ["--exact"] if test == TEST and not test.endswith("::") else [] output = run([str(test_bin), test] + exact + ["--nocapture"]) return module, parse_observations(output, module, prefix, width) @@ -252,7 +252,7 @@ def check_mutations(cargo, source, test, mutations): raise RuntimeError(f"update the {name} mutation for {source}") source.write_text(original.replace(needle, replacement, 1)) try: - run(cargo + [test, "--"] + (["--exact"] if test == TEST else [])) + run(cargo + [test, "--"] + (["--exact"] if test == TEST and not test.endswith("::") else [])) except subprocess.CalledProcessError as failure: if expected not in failure.output: raise RuntimeError(f"{name} failed for an unexpected reason") from failure @@ -745,6 +745,60 @@ def run_aux(test): " op.faulted = true;\n if let Some(slot) = op.bounce_slot.take() { self.free_bounce_slots.push(slot); }\n let completion_slot = op.completion_slot;", "faulted DMA must retain inflight and bounce ownership"), ]) + check_mutations( + cargo, + ROOT / "helios/src/model/packing.rs", + "model::tests::packed_prefill_contract_validation_and_multi_lane_packing", + [ + ("packed prefill image lane bypass", + " if live.image_slot.is_some() {\n" + " return Err(\"packed prefill graph does not support image-conditioned lanes\".into());\n" + " }", + " if false {\n" + " return Err(\"packed prefill graph does not support image-conditioned lanes\".into());\n" + " }", + "packed prefill must reject image-conditioned lanes"), + ], + ) + check_mutations( + cargo, + ROOT / "helios/src/scheduler.rs", + "model::tests::packed_prefill_contract_validation_and_multi_lane_packing", + [ + ("packed prefill aggregate token cap bypass", + " .try_fold(0usize, |sum, lane| sum.checked_add(lane.tokens))\n" + " .is_none_or(|sum| sum > self.packed_token_capacity)", + " .try_fold(0usize, |sum, lane| sum.checked_add(lane.tokens))\n" + " .is_none()", + "packed prefill must enforce aggregate packed token capacity"), + ], + ) + check_mutations( + cargo, + ROOT / "helios/src/scheduler.rs", + "scheduler::lifecycle_tests::packed_prefill_scheduler_matches_lifecycle_model", + [ + ("packed prefill non-terminal classification bypass", + " if batch <= 1 {\n" + " self.is_non_terminal_prefill(kind, capacity)\n" + " } else {\n" + " kind == GraphKind::Prefill\n" + " && self\n" + " .packed_prefill_catalog\n" + " .binary_search_by_key(\n" + " &(GraphKind::TerminalPrefill as u8, batch, capacity, packed),\n" + " |&(k, b, w, p)| (k as u8, b, w, p),\n" + " )\n" + " .is_ok()\n" + " }", + " if batch <= 1 {\n" + " self.is_non_terminal_prefill(kind, capacity)\n" + " } else {\n" + " false\n" + " }", + "missing packed-prefill lifecycle coverage"), + ], + ) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs)