diff --git a/docs/api.md b/docs/api.md index b4f24f621..3dd942dfe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -803,14 +803,17 @@ An output limit or user stop omits a strict call that began but did not finish; EOS inside such a call produces an error. A required or named tool choice still fails if no qualifying call completed. An active strict function tool attaches a request grammar for the entire -generation, including reasoning, prose, and tool calls. While generation is inside -an open reasoning region declared by the output envelope, tokens are validated on -the host without device masks so speculative widths and two-frame pipelining stay -active; once reasoning closes (or if a token violates the grammar), the runtime -transitions to device-masked decoding at MTP width one with one step in flight -for any decode batch containing it. Outside open reasoning—including prose when -`tool_choice: "auto"` produces only prose—device grammar enforcement applies -from the start. See the [native replay loop](core-design.md#native-replay-loop). +generation, including reasoning, prose, and tool calls. While generation is inside an open reasoning region declared by the output +envelope, tokens are validated on the host without per-step vocabulary mask +recomputation: non-speculative models keep one step in flight with an all-ones +mask and toggle the synced mask in place when reasoning closes, while +speculative models keep full speculative widths and two-frame pipelining active +and transition via in-place toggle or terminal-checkpoint restore (falling back +to rollback on burst overshoot or grammar rejection). Outside open +reasoning—including prose when `tool_choice: "auto"` produces only prose—device +grammar enforcement applies at MTP width one with one step in flight for any +decode batch containing it. See the +[native replay loop](core-design.md#native-replay-loop). Active strict tools on unsupported parsers, `strict: true` on custom or Messages tools, and invalid strict schemas return HTTP 400. Custom Lark answer grammars cannot be combined with active strict tools on DSML, Qwen diff --git a/docs/core-design.md b/docs/core-design.md index 3803ab21e..77ee7a33c 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1726,14 +1726,22 @@ ordinary function arguments. An active strict function tool constrains its call using the declared schema and the core's tool syntax. The output encoder holds the call until it has validated the complete arguments; a truncated strict call does not publish partial arguments. The composed request grammar validates the entire generation: reasoning, prose, -and tool calls. While generation is inside an open reasoning region declared by -the output envelope, the runtime validates emitted tokens on the host without -device grammar masks, allowing multi-token speculation and two-frame executor -pipelining; when reasoning closes or a token is rejected by the grammar, the -runtime truncates any burst overshoot, drains any queued frame, syncs the -grammar mask, and readmits the continuation with device grammar enforcement. -While device grammar masking is active (outside open reasoning, including prose -and tool calls), the request uses MTP width one and the +and tool calls. While generation is inside an open reasoning region declared by the output +envelope, the runtime validates emitted tokens on the host without recomputing +vocabulary masks. Non-speculative models keep one step in flight with device +`GrammarEnabled` active and a cached all-ones mask during open reasoning, then +toggle the synced vocabulary mask in place on the live slot when reasoning +closes or re-opens without thinking-budget expansion (or publish and restore a +terminal checkpoint when thinking-budget expansion applies). Speculative models run unmasked reasoning with multi-token +speculation and two-frame executor pipelining; when reasoning closes with no +overshoot and no pending frame or budget expansion, cores whose sampling graphs +bind `ValueSource::GrammarEnabled` toggle in place, while cores without +per-step `GrammarEnabled` bindings (or with one draining frame that does not +consume past the boundary) preserve KV and recurrent state by publishing a +terminal checkpoint and restoring it. Speculative burst overshoot or grammar +rejection falls back to cancelling the live slot and readmitting the truncated +prefix. While device grammar masking is active (outside open reasoning, +including prose and tool calls), the request uses MTP width one and the [native replay loop](#native-replay-loop) keeps one step in flight for any decode batch containing it. `tool_choice=required` requires a completed call to a declared tool; diff --git a/docs/mtp-design.md b/docs/mtp-design.md index b3eb1c0ee..56f7b481e 100644 --- a/docs/mtp-design.md +++ b/docs/mtp-design.md @@ -420,15 +420,37 @@ are ready. While a grammar-constrained request is inside an open reasoning region declared by its output envelope (including reasoning opened after a constrained recipient -or content-header frame), the runtime runs without device grammar masks so the -request uses full speculative widths and two-frame executor pipelining without a -feedback barrier. On completion, the runtime validates each emitted token -against the request grammar on the host without recomputing the full vocabulary -mask. When a token closes reasoning or is rejected by the grammar, the runtime -suppresses any trailing overshoot tokens in that burst, cancels the live slot so -any queued second frame drains without emitting output or publishing a terminal -snapshot, syncs the vocabulary mask at the exact boundary prefix, and readmits -the continuation with device grammar masking enabled. +or content-header frame), the runtime validates each emitted token against the +request grammar on the host without recomputing the full vocabulary mask. On +non-speculative models, the request keeps a step-level feedback barrier with +device `GrammarEnabled` active and a cached all-ones mask during open +reasoning, and toggles the synced vocabulary mask in place on the live slot +when reasoning closes or re-opens without thinking-budget expansion (or +publishes and restores a terminal checkpoint when thinking-budget expansion +applies). On speculative models, open reasoning runs +without device grammar masks so the request uses full speculative widths and +two-frame executor pipelining without a feedback barrier: + +- When a token closes reasoning (or re-opens reasoning) with no burst + overshoot, no queued second frame, and no thinking-budget expansion, cores + whose sampling graphs bind `ValueSource::GrammarEnabled` toggle the + scheduler's grammar constraint, device `GrammarEnabled`, and vocabulary mask + in place on the live slot. +- When reasoning closes or re-opens with no burst overshoot on a speculative + core whose sampling graphs do not bind `ValueSource::GrammarEnabled` (or when + a thinking-budget expansion applies or a single second frame is already in + flight), the runtime pauses further scheduling for that slot while any + in-flight frame drains. If the drained frame stays at or below the exact + boundary length (`consumed_tokens <= exact_len`), Helios publishes an + immutable terminal checkpoint (`Snapshot` -> `finish`) and readmits the + continuation via `Restore` (`Prefill(1)` or `Resume`) with the updated + grammar mode, preserving live KV and recurrent state. +- When a burst overshoots the boundary, a draining second frame consumes past + the boundary, or the host grammar rejects a token, the runtime suppresses any + trailing overshoot tokens, cancels the live slot so queued work drains + without publishing a terminal snapshot, syncs the vocabulary mask at the + exact boundary prefix, and readmits the continuation with device grammar + masking enabled. Host-evaluated custom stops (stop strings and stop token sequences) participate in multi-token speculative rounds and two-frame executor pipelining without a diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 68136f371..ba60c6db5 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -93,12 +93,19 @@ handshake rejects mismatched rank modes at startup, and multi-host `--rank` + `selene-manager` negotiates raw-only and excludes packed records for multi-process sessions): -- In `gpu` mode, new captures encode on GPU as `GKV1`, matrix-predictor and - large-page (>= 256 KiB) `GKV1` restores decode on GPU (falling back to the - bounded CPU pool if a background capture holds the GPU codec), and smaller - non-matrix `GKV1` and `ZKV1` restores decode on the bounded CPU worker pool - over async HtoD DMA so critical-path restores do not stall behind foreground - GPU saturation. All active offload tiers (`memory`, `disk`, `pool`) share one +- In `gpu` mode, new captures encode on GPU as `GKV1`, acquiring + `CopyEngineGate::enter_offload_batch` before locking the per-rank GPU codec + mutex so background captures blocked on active peer-copy graphs do not hold + the codec mutex. Matrix-predictor and large-page (>= 256 KiB) `GKV1` restores + partition windows into maximal GPU-batched, CPU-batched, and singleton runs + so leading or interleaved `Literal` and CPU-routed pages do not disable GPU + batching for subsequent `GKV1` pages. Foreground GPU restores non-blockingly + acquire the codec mutex and `CopyEngineGate::try_enter_offload_batch`, + falling back immediately to the bounded CPU pool without blocking or + consuming a gate wave token when a background capture holds the GPU codec or + a peer-copy graph blocks the gate. Smaller non-matrix `GKV1` and `ZKV1` + restores decode on the bounded CPU worker pool over async HtoD DMA so + critical-path restores do not stall behind foreground GPU saturation. All active offload tiers (`memory`, `disk`, `pool`) share one 3-buffer aliased per-rank `GpuRankCodec` workspace (~130 MiB per GPU on GLM-5.3-Flash TP4, ~32 MiB per GPU on DeepSeek-V4.1-Flash TP4, ~440 MiB on Qwen3.8-Flash-Next TP1) with no secondary CUDA primary context. Because `gpu` diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index f634ecfc6..2d470e51c 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -463,29 +463,42 @@ 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; 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. +The first positive device observation sets the estimate. For graphs without +variable prefill work, 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`) and mixed graphs (`MIXED`), samples +are stratified across six positive-fill and KV-context depth buckets +(`u <= 0.5` vs `u > 0.5` crossed with `< 4096`, `4096..32768`, and `>= 32768` +starting tokens), plus a zero-fill bucket for decode-only `MIXED` executions +(`work == 0`), each retaining a nine-sample rolling median. 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 -medians; when only a narrow fill regime (spread `< 0.15`) has been observed, -queries above `u_max` apply a bounded constant-throughput upward floor -`t_at_umax * min(u / u_max, 4)` to the base term (before adding `theta_2 * h`) -so partial fills cannot discount full-chunk cost estimates or lock out a large -capacity after TTL reset. When a smaller prefill capacity has no deep-context observations +medians; when only a narrow positive-fill regime (`pos_u_max > 0`, +`pos_u_max - pos_u_min < 0.15` across positive-fill strata) has been observed, +queries above `pos_u_max` apply a bounded constant-throughput upward floor +`pos_t_at_umax * min(u / pos_u_max, 4)` to the base term (before adding +`theta_2 * h`) so partial fills cannot discount full-chunk cost estimates or +lock out a large capacity after TTL reset, even after zero-fill `MIXED` samples +have been recorded. Decode-only `MIXED` queries (`work == 0`) use `theta_0` +only when a `zero_fill` sample anchors it and `theta_0 > 0`, falling back to +the lowest-fill observed median (`t_at_umin`) otherwise so positive-fill-only +fits never extrapolate decode-only latency toward zero. When a `MIXED` entry +has recorded only `zero_fill` samples (`pos_u_max == 0`), decode-only queries +use that observed median while positive-fill queries (`work > 0`) remain +unmeasured (`0`) until a positive-fill step executes, preventing decode-only +samples from under-pricing full-chunk prefills or inflating prefill service +rates. When a +smaller prefill capacity has no deep-context observations (`start_position >= 4096`), it borrows the per-token KV-context slope `theta_2 / peer_capacity` from the largest fresh strictly larger peer of the -same graph kind so deep prompts do not drift down onto stale shallow smaller -capacities. An entry becomes stale after 30 seconds -without a valid observation. Its measured cost remains available for selection -and service-rate normalization. The first valid observation of a stale entry -replaces its estimate directly (clearing all prefill strata); elapsed time alone -never makes a measured graph unknown. When multiple packed speculative shapes +same graph kind (and same `(batch, width)` for `MIXED`) so deep prompts do not +drift down onto stale shallow smaller capacities. An entry becomes stale after +30 seconds without a valid observation. Its measured cost remains available for +selection and service-rate normalization. The first valid observation of a stale +entry replaces its estimate directly (clearing all fill and context strata); +elapsed time alone never makes a measured graph unknown. When multiple packed speculative shapes cover a `(batch, width)` lookup for service-rate normalization or continuation pricing, Helios takes the minimum positive measured duration across matching shapes and returns zero only when every matching shape is unmeasured. diff --git a/helios/src/model.rs b/helios/src/model.rs index 2830ca32e..b47a9e370 100644 --- a/helios/src/model.rs +++ b/helios/src/model.rs @@ -21,7 +21,7 @@ use crate::{ execution::{CompletionRecord, ExecutionManifest, GraphKind}, scheduler::{SchedulerCapabilities, SchedulerLimits}, }; -pub use admission::Admission; +pub use admission::{Admission, AdmissionGrammar}; pub use contract::PreparedContract; pub use inputs::{InputStep, pack_inputs}; pub use packing::Inputs; diff --git a/helios/src/model/admission.rs b/helios/src/model/admission.rs index deefcbdd7..4e4a52104 100644 --- a/helios/src/model/admission.rs +++ b/helios/src/model/admission.rs @@ -56,6 +56,39 @@ impl PromptMetadataMut<'_> { } } +/// Device-side grammar masking state for an admitted request. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum AdmissionGrammar { + /// Device grammar masking is disabled (`GrammarEnabled = 0`, all-ones mask). + #[default] + Disabled, + /// Device grammar masking is enabled (`GrammarEnabled = 1`) with an all-ones mask + /// so non-speculative requests can toggle masks in place without `Restore`. + UnmaskedEnabled, + /// Device grammar masking is enabled (`GrammarEnabled = 1`) with an explicit mask. + Masked(Vec), +} + +impl AdmissionGrammar { + pub fn is_enabled(&self) -> bool { + !matches!(self, Self::Disabled) + } + + pub fn mask(&self) -> Option<&[i32]> { + match self { + Self::Masked(mask) => Some(mask.as_slice()), + Self::Disabled | Self::UnmaskedEnabled => None, + } + } + + pub fn mask_mut(&mut self) -> Option<&mut Vec> { + match self { + Self::Masked(mask) => Some(mask), + Self::Disabled | Self::UnmaskedEnabled => None, + } + } +} + pub struct Admission { pub handle: RequestHandle, pub sampling: SamplingParameters, @@ -63,7 +96,7 @@ pub struct Admission { pub max_new_tokens: u32, pub prompt: Vec, pub data: crate::model::PromptData, - pub grammar_mask: Option>, + pub grammar: AdmissionGrammar, pub ignore_eos: bool, pub prompt_logprobs: bool, } @@ -94,8 +127,8 @@ impl Admission { .iter() .any(|token| *token as usize >= config.contract.input_vocabulary) || self - .grammar_mask - .as_ref() + .grammar + .mask() .is_some_and(|mask| mask.len() != config.contract.vocabulary.div_ceil(32)) { return Err( @@ -112,12 +145,17 @@ impl Admission { #[cfg(feature = "server")] pub(crate) fn grammar_updated(&mut self, mask: &[i32]) { - self.grammar_mask - .as_mut() + self.grammar + .mask_mut() .expect("grammar admission has a mask") .copy_from_slice(mask); } + #[cfg(feature = "server")] + pub(crate) fn set_grammar(&mut self, grammar: AdmissionGrammar) { + self.grammar = grammar; + } + #[cfg(feature = "server")] pub fn from_prompt( config: &ModelConfig, @@ -133,18 +171,26 @@ impl Admission { prompt.tokens.len(), ignore_eos, grammar_constrained, + grammar_constrained, ) } #[cfg(feature = "server")] + #[allow(clippy::too_many_arguments)] pub fn from_continuation( config: &ModelConfig, handle: RequestHandle, prompt: &crate::server::Prompt, initial_prompt_tokens: usize, ignore_eos: bool, - grammar_constrained: bool, + grammar_mask_active: bool, + grammar_enabled: bool, ) -> Result { + let grammar = match prompt.grammar.as_ref() { + Some(grammar) if grammar_mask_active => AdmissionGrammar::Masked(grammar.mask().to_vec()), + Some(_) if grammar_enabled => AdmissionGrammar::UnmaskedEnabled, + _ => AdmissionGrammar::Disabled, + }; let admission = Self { handle, sampling: prompt.sampling.clone(), @@ -152,9 +198,7 @@ impl Admission { max_new_tokens: prompt.max_new_tokens, prompt: prompt.tokens.clone(), data: prompt.data.clone(), - grammar_mask: grammar_constrained - .then(|| prompt.grammar.as_ref().map(|grammar| grammar.mask().to_vec())) - .flatten(), + grammar, ignore_eos, prompt_logprobs: prompt.prompt_logprobs, }; diff --git a/helios/src/model/packed_round_tests.rs b/helios/src/model/packed_round_tests.rs index 165c7a329..171a20888 100644 --- a/helios/src/model/packed_round_tests.rs +++ b/helios/src/model/packed_round_tests.rs @@ -122,7 +122,7 @@ fn packed_combined_packing_preserves_sparse_slot_keys_and_ceiling_padding() { admissions[h.slot as usize] = Some(Admission { prompt_logprobs: false, handle: h, sampling: SamplingParameters::default(), core_parameters: Default::default(), max_new_tokens: 64, prompt, data: PromptData { positions: (0..64).map(|i| [i; 3]).collect(), - vision_token_indices: vec![-1; 64], ..Default::default() }, grammar_mask: None, ignore_eos: true }); + vision_token_indices: vec![-1; 64], ..Default::default() }, grammar: AdmissionGrammar::Disabled, ignore_eos: true }); handles.push(h); } scheduler.cancel(handles[1]).unwrap();admissions[handles[1].slot as usize] = None; diff --git a/helios/src/model/packing.rs b/helios/src/model/packing.rs index e482eafad..0b0d973f9 100644 --- a/helios/src/model/packing.rs +++ b/helios/src/model/packing.rs @@ -601,9 +601,9 @@ impl Inputs { // Grammar masks already contain packed i32 bit patterns. // Preserve those bytes without widening and validating every word. let count = admission - .grammar_mask - .as_ref() - .map_or(input.width, Vec::len); + .grammar + .mask() + .map_or(input.width, <[i32]>::len); if count == 0 { continue; } @@ -613,7 +613,7 @@ impl Inputs { { return Err("packed values exceed prepared input storage".into()); } - if let Some(mask) = &admission.grammar_mask { + if let Some(mask) = admission.grammar.mask() { // A constrained mask may overlap any unconstrained range of this buffer. self.unconstrained_masks.retain(|(name, _, _)| *name != binding.buffer); self.staging.i32( @@ -794,13 +794,13 @@ impl Inputs { } } GrammarMask => { - if let Some(mask) = &admission.grammar_mask { + if let Some(mask) = admission.grammar.mask() { values.extend(mask.iter().map(|v| *v as i64)); } else { values.resize(input.width, -1); } } - GrammarEnabled => values.push(i64::from(admission.grammar_mask.is_some())), + GrammarEnabled => values.push(i64::from(admission.grammar.is_enabled())), // Legacy copy-draft inputs in existing cores receive inactive sentinels. CopyTokenIds => values.resize(input.width, -1), CopyTokenCount | CopyGeneration | CopyGrammarCount => values.push(0), diff --git a/helios/src/model/tests.rs b/helios/src/model/tests.rs index 150125cfe..4d1470e0d 100644 --- a/helios/src/model/tests.rs +++ b/helios/src/model/tests.rs @@ -171,7 +171,7 @@ fn generic_core_parameters_resolve_pack_and_enforce_text_forward_contracts() { vision_token_indices: vec![-1; 4], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -420,7 +420,7 @@ fn core_parameters_pack_sparse_permuted_rows_and_preserve_prefix_values() { vision_token_indices: vec![-1; 4], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -549,7 +549,7 @@ fn admission_histogram_seed_and_partial_page_uploads_preserve_native_semantics() vision_token_indices: vec![-1; 65], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -697,7 +697,7 @@ fn large_prefill_uploads_preserve_token_position_and_image_indices_without_tail_ ..Default::default() }, prompt, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -1009,7 +1009,7 @@ fn packing_follows_value_bindings_after_buffers_and_model_are_renamed() { positions: (0..65).map(|p| [p; 3]).collect(), ..Default::default() }, - grammar_mask: Some(vec![i32::MIN; config.contract.vocabulary.div_ceil(32)]), + grammar: AdmissionGrammar::Masked(vec![i32::MIN; config.contract.vocabulary.div_ceil(32)]), ignore_eos: false, prompt_logprobs: false, }); @@ -1136,7 +1136,7 @@ fn legacy_copy_bindings_pack_neutral_sentinels_without_copy_proposals() { vision_token_indices: vec![-1; 65], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -1253,7 +1253,7 @@ fn mixed_native_uploads_pack_prompt_after_the_decode_extent_and_sample_only_elig vision_token_indices: vec![-1; count], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -1468,7 +1468,7 @@ fn state_transfer_and_resume_upload_fixture() { vision_token_indices: vec![-1; 64], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -1683,7 +1683,7 @@ fn grammar_packing_fixture() -> ( max_new_tokens: 512, prompt: vec![7; 66], data: PromptData::default(), - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, })); @@ -1737,16 +1737,16 @@ fn grammar_mask_packing_preserves_bits_row_layout_and_transitions() { expected.fill(0); } for (slot, admission) in admissions.iter_mut().enumerate() { - admission.as_mut().unwrap().grammar_mask = match (round, slot) { - (0, 1) | (1, 6) => Some( + admission.as_mut().unwrap().grammar = match (round, slot) { + (0, 1) | (1, 6) => AdmissionGrammar::Masked( (0..words) .map(|i| [i32::MIN, i32::MAX, 0, -1][i % 4]) .collect(), ), - (0, 6) => Some(vec![0; words]), - (1, 3) => Some(vec![1; words]), - (3, 1) => Some(vec![]), - _ => None, + (0, 6) => AdmissionGrammar::Masked(vec![0; words]), + (1, 3) => AdmissionGrammar::Masked(vec![1; words]), + (3, 1) => AdmissionGrammar::Masked(vec![]), + _ => AdmissionGrammar::Disabled, }; } pack_inputs(&mut inputs, &config, &scheduler, &step, &admissions).unwrap(); @@ -1768,9 +1768,9 @@ fn grammar_mask_packing_preserves_bits_row_layout_and_transitions() { for (row, lane) in step.lanes.iter().enumerate() { let slot = lane.request.slot as usize; let destination = if indexing == RequestRow { slot } else { row }; - let mask = admissions[slot].as_ref().unwrap().grammar_mask.as_ref(); + let mask = admissions[slot].as_ref().unwrap().grammar.mask(); // Empty masks leave the row untouched, including its padding. - if mask.is_some_and(Vec::is_empty) { + if mask.is_some_and(<[i32]>::is_empty) { continue; } for word in 0..words { @@ -1808,7 +1808,11 @@ fn grammar_mask_cache_survives_alternating_graph_indexing() { step.draft_tokens = if kind == GraphKind::Speculative { 5 } else { 0 }; step.packed_token_capacity = if kind == GraphKind::Speculative { 48 } else { 0 }; for admission in admissions.iter_mut().flatten() { - admission.grammar_mask = (kind == GraphKind::Speculative).then(|| vec![0; words]); + admission.grammar = if kind == GraphKind::Speculative { + AdmissionGrammar::Masked(vec![0; words]) + } else { + AdmissionGrammar::Disabled + }; } pack_inputs(&mut inputs, &config, &scheduler, &step, &admissions).unwrap(); for upload in inputs.uploads().into_iter().filter(|u| u.buffer == "sampling_grammar_mask") { @@ -1871,9 +1875,9 @@ fn grammar_mask_cache_discards_unsubmitted_rows_after_pack_error() { let words = config.contract.vocabulary.div_ceil(32); step.lanes = [0, 7].map(|slot| step.lanes[slot].clone()).into(); let mut inputs = Inputs::new(&config, &manifest).unwrap(); - admissions[7].as_mut().unwrap().grammar_mask = Some(vec![0; words + 1]); + admissions[7].as_mut().unwrap().grammar = AdmissionGrammar::Masked(vec![0; words + 1]); assert!(pack_inputs(&mut inputs, &config, &scheduler, &step, &admissions).is_err()); - admissions[7].as_mut().unwrap().grammar_mask = None; + admissions[7].as_mut().unwrap().grammar = AdmissionGrammar::Disabled; pack_inputs(&mut inputs, &config, &scheduler, &step, &admissions).unwrap(); let uploaded: usize = inputs.uploads().iter().filter(|u| u.buffer == "sampling_grammar_mask").map(|u| u.bytes.len()).sum(); assert_eq!(uploaded, 2 * words * 4, "the failed pack uploaded neither row"); @@ -1881,6 +1885,87 @@ fn grammar_mask_cache_discards_unsubmitted_rows_after_pack_error() { assert!(!inputs.uploads().iter().any(|u| u.buffer == "sampling_grammar_mask")); } +#[test] +fn grammar_enabled_unmasked_packs_enabled_with_cached_all_ones_mask_and_toggles_in_place() { + use crate::scheduler::{ScheduledLane, ScheduledStep}; + + let (config, manifest, scheduler, mut admissions, step) = grammar_packing_fixture(); + let words = config.contract.vocabulary.div_ceil(32); + let mut inputs = Inputs::new(&config, &manifest).unwrap(); + + // Non-speculative unmasked reasoning initializes `grammar_enabled = 1` with `grammar_mask = None` + // (all-ones mask) so `Init` sets GPU `grammar_enabled[slot] = 1` while `Decode` caches the + // all-ones mask and in-place mask toggling immediately enforces constraints. + let h = step.lanes[0].request; + let slot = h.slot as usize; + admissions[slot].as_mut().unwrap().grammar = AdmissionGrammar::UnmaskedEnabled; + let init = ScheduledStep { + draft_tokens: 0, + packed_token_capacity: 0, + kind: GraphKind::Init, + batch_capacity: 1, + token_capacity: 1, + mixed: None, + lanes: vec![ScheduledLane { + request: h, + start_position: 0, + tokens: 0, + }], + requires_feedback: true, + }; + pack_inputs(&mut inputs, &config, &scheduler, &init, &admissions).unwrap(); + let enabled_upload = inputs + .uploads() + .into_iter() + .find(|u| u.buffer == "admission_grammar_enabled") + .expect("Init must upload admission_grammar_enabled"); + assert_eq!(i32::from_le_bytes(enabled_upload.bytes[..4].try_into().unwrap()), 1); + let init_mask = inputs + .uploads() + .into_iter() + .find(|u| u.buffer == "admission_grammar_mask") + .expect("Init must upload all-ones admission_grammar_mask"); + assert_eq!(init_mask.bytes.len(), words * 4); + assert!(init_mask.bytes.iter().all(|&b| b == 0xff)); + + // Decode step caches all-ones mask on first pack, omits upload on second pack, and uploads + // exact constrained mask immediately when toggled in place. + let mut decode = step; + decode.lanes = vec![ScheduledLane { + request: h, + start_position: 1, + tokens: 1, + }]; + pack_inputs(&mut inputs, &config, &scheduler, &decode, &admissions).unwrap(); + assert!(inputs + .uploads() + .iter() + .any(|u| u.buffer == "sampling_grammar_mask" && u.bytes.iter().all(|&b| b == 0xff))); + pack_inputs(&mut inputs, &config, &scheduler, &decode, &admissions).unwrap(); + assert!(!inputs.uploads().iter().any(|u| u.buffer == "sampling_grammar_mask")); + + let mut constrained = vec![0i32; words]; + constrained[0] = 1 << 5; + admissions[slot].as_mut().unwrap().grammar = AdmissionGrammar::Masked(constrained); + pack_inputs(&mut inputs, &config, &scheduler, &decode, &admissions).unwrap(); + let mask_upload = inputs + .uploads() + .into_iter() + .find(|u| u.buffer == "sampling_grammar_mask") + .expect("in-place mask toggle must upload constrained mask"); + assert_eq!(i32::from_le_bytes(mask_upload.bytes[..4].try_into().unwrap()), 1 << 5); + + // Toggling back to unmasked reasoning re-uploads all-ones once and caches it again. + admissions[slot].as_mut().unwrap().grammar = AdmissionGrammar::UnmaskedEnabled; + pack_inputs(&mut inputs, &config, &scheduler, &decode, &admissions).unwrap(); + assert!(inputs + .uploads() + .iter() + .any(|u| u.buffer == "sampling_grammar_mask" && u.bytes.iter().all(|&b| b == 0xff))); + pack_inputs(&mut inputs, &config, &scheduler, &decode, &admissions).unwrap(); + assert!(!inputs.uploads().iter().any(|u| u.buffer == "sampling_grammar_mask")); +} + #[test] #[cfg(any(feature = "runtime-core", feature = "frontend"))] fn prefill_compacts_execution_feature_indices_and_preserves_admission_metadata() { @@ -1926,7 +2011,7 @@ fn prefill_compacts_execution_feature_indices_and_preserves_admission_metadata() vision_token_indices: canonical.clone(), ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -2023,7 +2108,7 @@ fn committed_generation_cursors_require_feedback_while_unused_prompt_positions_d max_new_tokens: 64, prompt: vec![7; 64], data: PromptData { positions: (0..64).map(|position| [position; 3]).collect(), vision_token_indices: vec![-1; 64], ..Default::default() - }, grammar_mask: None, ignore_eos: true, prompt_logprobs: false }); + }, grammar: AdmissionGrammar::Disabled, ignore_eos: true, prompt_logprobs: false }); let mut timing = ExecutionTiming::default(); timing.gpu_ns[0] = Some(1000); let mut sequence = 0; @@ -2290,7 +2375,7 @@ fn prompt_lookahead_packing_distributes_budget_across_single_multi_and_mixed_lan vision_token_indices: vec![-1; count], ..Default::default() }, - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -2516,7 +2601,7 @@ fn continuation_prompt_validation_permits_decoded_in_vocab_image_and_span_tokens max_new_tokens: 4, prompt: cont_tokens.clone(), data: cont_data.clone(), - grammar_mask: None, + grammar: AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }; diff --git a/helios/src/offload/copy_gate.rs b/helios/src/offload/copy_gate.rs index 1dbb63af6..1959d432d 100644 --- a/helios/src/offload/copy_gate.rs +++ b/helios/src/offload/copy_gate.rs @@ -168,30 +168,45 @@ impl CopyEngineGate { }) } + fn offload_must_wait(s: &State) -> bool { + s.peer_graphs_active > 0 + || (s.peer_graphs_waiting > 0 + && !(s.turn == Turn::Offload && s.offload_wave_remaining > 0)) + } + + fn take_offload_lease(&self, state: &mut State) -> OffloadBatchGuard<'_> { + if state.turn == Turn::Offload && state.offload_wave_remaining > 0 { + state.offload_wave_remaining -= 1; + if state.offload_wave_remaining == 0 { + state.turn = Turn::Peer; + } + } + state.offload_batches_active += 1; + OffloadBatchGuard { gate: self } + } + /// Wait until no peer-copy graph is active and this batch is permitted to run, /// returning the active offload batch lease. pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); - let must_wait = |s: &State| { - s.peer_graphs_active > 0 - || (s.peer_graphs_waiting > 0 - && !(s.turn == Turn::Offload && s.offload_wave_remaining > 0)) - }; - if must_wait(&state) { + if Self::offload_must_wait(&state) { state.offload_batches_waiting += 1; - while must_wait(&state) { + while Self::offload_must_wait(&state) { state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); } state.offload_batches_waiting = state.offload_batches_waiting.saturating_sub(1); } - if state.turn == Turn::Offload && state.offload_wave_remaining > 0 { - state.offload_wave_remaining -= 1; - if state.offload_wave_remaining == 0 { - state.turn = Turn::Peer; - } + self.take_offload_lease(&mut state) + } + + /// Acquire an active offload batch lease immediately when no peer-copy graph blocks + /// entry; returns `None` without waiting or mutating wait/wave counters otherwise. + pub fn try_enter_offload_batch(&self) -> Option> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if Self::offload_must_wait(&state) { + return None; } - state.offload_batches_active += 1; - OffloadBatchGuard { gate: self } + Some(self.take_offload_lease(&mut state)) } } @@ -642,4 +657,45 @@ mod tests { stop.store(true, Ordering::Release); peer.join().unwrap(); } + + #[test] + fn try_enter_offload_batch_returns_none_without_blocking_or_burning_wave_tokens() { + let gate = Arc::new(CopyEngineGate::new()); + + // Active peer-copy graph blocks immediate entry without mutating waiting/wave state. + let peer = gate.enter_peer_graph().unwrap(); + assert!( + gate.try_enter_offload_batch().is_none(), + "try_enter_offload_batch must return None while peer-copy graphs block entry" + ); + { + let state = gate.state.lock().unwrap(); + assert_eq!(state.offload_batches_active, 0); + assert_eq!(state.offload_batches_waiting, 0); + } + drop(peer); + + // Uncontended try-enter acquires and releases cleanly. + let lease = gate + .try_enter_offload_batch() + .expect("uncontended try_enter_offload_batch must succeed"); + assert_eq!(gate.state.lock().unwrap().offload_batches_active, 1); + drop(lease); + assert_eq!(gate.state.lock().unwrap().offload_batches_active, 0); + + // Waiting peer-copy graph (not in Turn::Offload wave) also rejects try-enter immediately. + { + let mut state = gate.state.lock().unwrap(); + state.peer_graphs_waiting = 1; + state.turn = Turn::Peer; + state.offload_wave_remaining = 0; + } + assert!(gate.try_enter_offload_batch().is_none()); + { + let mut state = gate.state.lock().unwrap(); + assert_eq!(state.offload_batches_active, 0); + assert_eq!(state.offload_batches_waiting, 0); + state.peer_graphs_waiting = 0; + } + } } diff --git a/helios/src/offload/transfer/codec.rs b/helios/src/offload/transfer/codec.rs index ad6d961af..45bb293f9 100644 --- a/helios/src/offload/transfer/codec.rs +++ b/helios/src/offload/transfer/codec.rs @@ -284,21 +284,22 @@ impl RankCodec { .iter() .map(|(u, s)| (u.as_slice(), s.as_slice())) .collect(); - let (stored_len, elapsed) = { - let mut guard = gpu.codec.lock().unwrap(); - let _ce = - copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); - let start = Instant::now(); - let res = guard.encode_pages_batches_with( - page_plan, - &batch_refs, - &self.gpu_profile, - stream, - event, - |unit, bytes| capture.push_slice(unit, bytes), - ); - (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) - }; + let (stored_len, elapsed) = + with_gpu_codec_locked(copy_gate, &gpu.codec, |guard| { + let start = Instant::now(); + let res = guard.encode_pages_batches_with( + page_plan, + &batch_refs, + &self.gpu_profile, + stream, + event, + |unit, bytes| capture.push_slice(unit, bytes), + ); + Ok(( + sync_on_err(stream, res).map_err(decode_error)?, + start.elapsed(), + )) + })?; stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; } @@ -312,26 +313,27 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let (stored_len, elapsed) = { - let mut guard = gpu.codec.lock().unwrap(); - let _ce = - copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); - let start = Instant::now(); - let res = guard.encode_from_device_with( - page_plan, - base_unit, - &self.gpu_profile, - &spans, - stream, - event, - |unit, bytes| { - let slen = unit.stored_length; - capture.push_slice(unit, bytes); - slen - }, - ); - (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) - }; + let (stored_len, elapsed) = + with_gpu_codec_locked(copy_gate, &gpu.codec, |guard| { + let start = Instant::now(); + let res = guard.encode_from_device_with( + page_plan, + base_unit, + &self.gpu_profile, + &spans, + stream, + event, + |unit, bytes| { + let slen = unit.stored_length; + capture.push_slice(unit, bytes); + slen + }, + ); + Ok(( + sync_on_err(stream, res).map_err(decode_error)?, + start.elapsed(), + )) + })?; stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += page_bytes as u64; @@ -346,26 +348,27 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let (stored_len, elapsed) = { - let mut guard = gpu.codec.lock().unwrap(); - let _ce = - copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); - let start = Instant::now(); - let res = guard.encode_from_device_with( - &self.cpu.gpu_row, - base_unit, - &self.gpu_profile, - &spans, - stream, - event, - |unit, bytes| { - let slen = unit.stored_length; - capture.push_slice(unit, bytes); - slen - }, - ); - (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) - }; + let (stored_len, elapsed) = + with_gpu_codec_locked(copy_gate, &gpu.codec, |guard| { + let start = Instant::now(); + let res = guard.encode_from_device_with( + &self.cpu.gpu_row, + base_unit, + &self.gpu_profile, + &spans, + stream, + event, + |unit, bytes| { + let slen = unit.stored_length; + capture.push_slice(unit, bytes); + slen + }, + ); + Ok(( + sync_on_err(stream, res).map_err(decode_error)?, + start.elapsed(), + )) + })?; stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += n as u64; @@ -529,8 +532,8 @@ impl RankCodec { #[allow(clippy::too_many_arguments)] fn decode_pages_cpu_batch( &mut self, - items: &[(&PackedUnit, DecodeRoute, Vec<&[u8]>)], - batch_spans: &[(usize, Vec)], + items: &[(&PackedUnit, DecodeRoute, &[&[u8]])], + batch_spans: &[(usize, &[DeviceSpan])], stream: &Stream, event: &Event, copy_gate: Option<&super::super::CopyEngineGate>, @@ -563,7 +566,12 @@ impl RankCodec { }) })?; } - stats.transform_ns += start.elapsed().as_nanos() as u64; + if items + .iter() + .any(|(_, route, _)| *route != DecodeRoute::Literal) + { + stats.transform_ns += start.elapsed().as_nanos() as u64; + } copy_spans_batch( stream, event, @@ -574,6 +582,79 @@ impl RankCodec { ) } + #[allow(clippy::too_many_arguments)] + fn restore_single_unit( + &mut self, + row: bool, + u: &PackedUnit, + mut route: DecodeRoute, + chunks: &[&[u8]], + spans: &[DeviceSpan], + stream: &Stream, + event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, + stats: &mut DecodeStats, + ) -> Result { + let n = self.original_bytes(row); + if route == DecodeRoute::GpuOnDevice { + let plan = if row { + &self.cpu.gpu_row + } else { + &self.cpu.gpu_page + }; + let gpu_elapsed = try_with_gpu_codec_locked( + copy_gate, + &self.gpu.as_ref().unwrap().codec, + |guard| { + let start = Instant::now(); + let res = guard.decode_to_device( + plan, + chunks, + spans, + u.stored_crc, + u.original_crc, + stream, + event, + ); + sync_on_err(stream, res).map_err(decode_error)?; + Ok(start.elapsed()) + }, + ) + .transpose()?; + if let Some(elapsed) = gpu_elapsed { + stats.transform_ns += elapsed.as_nanos() as u64; + } else { + route = DecodeRoute::GpuOnCpu; + } + } + if route != DecodeRoute::GpuOnDevice { + let cpu_plan = if row { &self.cpu.row } else { &self.cpu.page }; + let gpu_plan = if row { + &self.cpu.gpu_row + } else { + &self.cpu.gpu_page + }; + let raw = &mut self.cpu.staging.bytes_mut()[..n]; + let pool = (route != DecodeRoute::Literal) + .then(cpu_pool) + .transpose()?; + let start = Instant::now(); + decode_unit_cpu(u, route, chunks, raw, cpu_plan, gpu_plan, pool)?; + if route != DecodeRoute::Literal { + stats.transform_ns += start.elapsed().as_nanos() as u64; + } + copy_spans_batch( + stream, + event, + copy_gate, + Direction::In, + &[(0, spans)], + self.cpu.staging_alias, + )?; + } + Ok(n) + } + #[allow(clippy::too_many_arguments)] fn restore_window( &mut self, @@ -592,215 +673,238 @@ impl RankCodec { let mut transferred = 0u64; let mut stored = 0u64; let page_bytes = self.cpu.page.original_bytes(); - let batch_cap = (self.cpu.staging.bytes().len() / page_bytes.max(1)).max(1); - let all_pages_cpu_path = job.pages.len() > 1 - && job.pages.iter().enumerate().all(|(i, _)| { - let idx = first + i as u64; - window.packets.iter().any(|p| { - let u = &p.unit; - u.kind == Kind::Page as i32 - && u.logical_index == idx - && (u.stored_rank == rank as u32 || u.replicas.contains(&(rank as u32))) - && Representation::try_from(u.representation) - .ok() - .and_then(|rep| self.decode_route(u, rep).ok()) - .is_some_and(|route| !matches!(route, DecodeRoute::GpuOnDevice)) - }) - }); - - let mut remaining_pages_offset = 0usize; - if all_pages_cpu_path { - for chunk in job.pages.chunks(batch_cap) { - let mut items = Vec::with_capacity(chunk.len()); - let mut batch_spans = Vec::with_capacity(chunk.len()); - for (slot_idx, (page, _)) in chunk.iter().enumerate() { - let index = first + (remaining_pages_offset + slot_idx) as u64; - let spans = device_spans(geometry, layout, false, u64::from(page.0))?; - let (u, representation, chunks) = - select_packet(window, false, index, rank, page_bytes)?; - let route = self.decode_route(u, representation)?; - debug_assert!(!matches!(route, DecodeRoute::GpuOnDevice)); - stored += u.stored_length; - items.push((u, route, chunks)); - batch_spans.push((slot_idx * page_bytes, spans)); - } - self.decode_pages_cpu_batch(&items, &batch_spans, stream, event, copy_gate, stats)?; - transferred += (chunk.len() * page_bytes) as u64; - remaining_pages_offset += chunk.len(); - } - } - - // Batch contiguous runs of GKV1 pages on GPU (handles mixed GKV1 + Literal windows cleanly). - if remaining_pages_offset < job.pages.len() - && self.cpu.gpu_page.num_mats() == 0 + let cpu_batch_cap = (self.cpu.staging.bytes().len() / page_bytes.max(1)).max(1); + let gpu_batch_cap = if self.cpu.gpu_page.num_mats() == 0 && self.cpu.gpu_page.num_chunks() > 0 - && self.gpu.is_some() { - let gpu_batch_cap = self.gpu.as_ref().unwrap().page_batch_cap; - if gpu_batch_cap > 1 { - let mut i = remaining_pages_offset; - while i < job.pages.len() { - let mut run_units: Vec<&PackedUnit> = Vec::new(); - let mut run_chunks: Vec> = Vec::new(); - let mut run_spans: Vec> = Vec::new(); - let mut run_stored = 0u64; - let mut j = i; - while j < job.pages.len() && run_chunks.len() < gpu_batch_cap { - let index = first + j as u64; - let (u, representation, chunks) = - select_packet(window, false, index, rank, page_bytes)?; - if self.decode_route(u, representation)? != DecodeRoute::GpuOnDevice { - break; - } - let spans = - device_spans(geometry, layout, false, u64::from(job.pages[j].0.0))?; - run_stored += u.stored_length; - run_units.push(u); - run_chunks.push(chunks); - run_spans.push(spans); - j += 1; - } - if run_chunks.len() > 1 { - let gpu_elapsed = { - if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { - let _ce = copy_gate - .map(super::super::CopyEngineGate::enter_offload_batch); - let start = Instant::now(); - let packets: Vec<(&[&[u8]], u32, u32)> = run_chunks - .iter() - .zip(&run_units) - .map(|(ch, u)| (ch.as_slice(), u.stored_crc, u.original_crc)) - .collect(); - let res = guard.decode_pages_batch_to_device( - &self.cpu.gpu_page, - &packets, - &run_spans, - stream, - event, - ); - sync_on_err(stream, res).map_err(decode_error)?; - Some(start.elapsed()) - } else { - None - } - }; - if let Some(elapsed) = gpu_elapsed { - stats.transform_ns += elapsed.as_nanos() as u64; - } else { - // Background GPU capture currently holds the codec mutex: decode this - // critical-path restore run on the bounded CPU pool instead of blocking. - let mut off = 0usize; - while off < run_chunks.len() { - let take = (run_chunks.len() - off).min(batch_cap); - let items: Vec<(&PackedUnit, DecodeRoute, Vec<&[u8]>)> = - run_units[off..off + take] - .iter() - .zip(&run_chunks[off..off + take]) - .map(|(&u, ch)| (u, DecodeRoute::GpuOnCpu, ch.clone())) - .collect(); - let batch_spans: Vec<(usize, Vec)> = run_spans - [off..off + take] - .iter() - .enumerate() - .map(|(s, sp)| (s * page_bytes, sp.clone())) - .collect(); - self.decode_pages_cpu_batch( - &items, - &batch_spans, - stream, - event, - copy_gate, - stats, - )?; - off += take; - } - } - stored += run_stored; - transferred += (page_bytes * run_chunks.len()) as u64; - i = j; - } else { - // Single GPU or non-GPU page: fall through to the per-unit loop below. - break; - } - } - remaining_pages_offset = i; - } + self.gpu.as_ref().map_or(1, |gpu| gpu.page_batch_cap) + } else { + 1 + }; + + let mut pages = Vec::with_capacity(job.pages.len()); + for (i, (page, _)) in job.pages.iter().enumerate() { + let index = first + i as u64; + let spans = device_spans(geometry, layout, false, u64::from(page.0))?; + let (u, representation, chunks) = + select_packet(window, false, index, rank, page_bytes)?; + let route = self.decode_route(u, representation)?; + pages.push((u, route, chunks, spans)); } - let ids = job - .pages - .iter() - .enumerate() - .skip(remaining_pages_offset) - .map(|(i, (page, _))| (false, first + i as u64, u64::from(page.0))) - .chain(job.row.iter().map(|(slot, _)| (true, 0, u64::from(slot.0)))); - for (row, index, id) in ids { - let n = self.original_bytes(row); - let spans = device_spans(geometry, layout, row, id)?; - let (u, representation, chunks) = select_packet(window, row, index, rank, n)?; - let mut route = self.decode_route(u, representation)?; - stored += u.stored_length; - if route == DecodeRoute::GpuOnDevice { - let plan = if row { - &self.cpu.gpu_row - } else { - &self.cpu.gpu_page - }; - let gpu_elapsed = { - if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { - let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); - let start = Instant::now(); - let res = guard.decode_to_device( - plan, - &chunks, - &spans, - u.stored_crc, - u.original_crc, - stream, - event, - ); - sync_on_err(stream, res).map_err(decode_error)?; - Some(start.elapsed()) + // Partition the window into maximal GPU-batched, CPU-batched, and singleton runs + // so Literal or CPU-encoded pages never disable GPU batching for later pages. + for run in partition_restore_pages_by( + pages.len(), + |idx| pages[idx].1, + gpu_batch_cap, + cpu_batch_cap, + ) { + match run.kind { + PageRunKind::GpuBatch => { + let slice = &pages[run.start..run.end]; + let run_stored: u64 = slice.iter().map(|(u, _, _, _)| u.stored_length).sum(); + let gpu_elapsed = try_with_gpu_codec_locked( + copy_gate, + &self.gpu.as_ref().unwrap().codec, + |guard| { + let start = Instant::now(); + let packets: Vec<(&[&[u8]], u32, u32)> = slice + .iter() + .map(|(u, _, ch, _)| (ch.as_slice(), u.stored_crc, u.original_crc)) + .collect(); + let run_spans: Vec> = + slice.iter().map(|(_, _, _, sp)| sp.clone()).collect(); + let res = guard.decode_pages_batch_to_device( + &self.cpu.gpu_page, + &packets, + &run_spans, + stream, + event, + ); + sync_on_err(stream, res).map_err(decode_error)?; + Ok(start.elapsed()) + }, + ) + .transpose()?; + if let Some(elapsed) = gpu_elapsed { + stats.transform_ns += elapsed.as_nanos() as u64; } else { - None + // Background GPU capture holds the codec mutex or a peer-copy graph + // blocks CopyEngineGate: decode this run on CPU instead of blocking. + let mut off = 0usize; + while off < slice.len() { + let take = (slice.len() - off).min(cpu_batch_cap); + let items: Vec<(&PackedUnit, DecodeRoute, &[&[u8]])> = slice + [off..off + take] + .iter() + .map(|(u, _, ch, _)| (*u, DecodeRoute::GpuOnCpu, ch.as_slice())) + .collect(); + let batch_spans: Vec<(usize, &[DeviceSpan])> = slice[off..off + take] + .iter() + .enumerate() + .map(|(s, (_, _, _, sp))| (s * page_bytes, sp.as_slice())) + .collect(); + self.decode_pages_cpu_batch( + &items, + &batch_spans, + stream, + event, + copy_gate, + stats, + )?; + off += take; + } } - }; - if let Some(elapsed) = gpu_elapsed { - stats.transform_ns += elapsed.as_nanos() as u64; - } else { - route = DecodeRoute::GpuOnCpu; + stored += run_stored; + transferred += (page_bytes * slice.len()) as u64; } - } - if route != DecodeRoute::GpuOnDevice { - let cpu_plan = if row { &self.cpu.row } else { &self.cpu.page }; - let gpu_plan = if row { - &self.cpu.gpu_row - } else { - &self.cpu.gpu_page - }; - let raw = &mut self.cpu.staging.bytes_mut()[..n]; - let pool = (route != DecodeRoute::Literal).then(cpu_pool).transpose()?; - let start = Instant::now(); - decode_unit_cpu(u, route, &chunks, raw, cpu_plan, gpu_plan, pool)?; - if route != DecodeRoute::Literal { - stats.transform_ns += start.elapsed().as_nanos() as u64; + PageRunKind::CpuBatch => { + let slice = &pages[run.start..run.end]; + let run_stored: u64 = slice.iter().map(|(u, _, _, _)| u.stored_length).sum(); + let items: Vec<(&PackedUnit, DecodeRoute, &[&[u8]])> = slice + .iter() + .map(|(u, route, ch, _)| (*u, *route, ch.as_slice())) + .collect(); + let batch_spans: Vec<(usize, &[DeviceSpan])> = slice + .iter() + .enumerate() + .map(|(s, (_, _, _, sp))| (s * page_bytes, sp.as_slice())) + .collect(); + self.decode_pages_cpu_batch( + &items, + &batch_spans, + stream, + event, + copy_gate, + stats, + )?; + stored += run_stored; + transferred += (page_bytes * slice.len()) as u64; + } + PageRunKind::Single => { + let (u, route, chunks, spans) = &pages[run.start]; + stored += u.stored_length; + transferred += self.restore_single_unit( + false, + u, + *route, + chunks, + spans, + stream, + event, + copy_gate, + stats, + )? as u64; } - copy_spans_batch( - stream, - event, - copy_gate, - Direction::In, - &[(0, spans)], - self.cpu.staging_alias, - )?; } - transferred += n as u64; + } + + if let Some((slot, _)) = &job.row { + let n = self.original_bytes(true); + let spans = device_spans(geometry, layout, true, u64::from(slot.0))?; + let (u, representation, chunks) = select_packet(window, true, 0, rank, n)?; + let route = self.decode_route(u, representation)?; + stored += u.stored_length; + transferred += self.restore_single_unit( + true, + u, + route, + &chunks, + &spans, + stream, + event, + copy_gate, + stats, + )? as u64; } stats.stored_bytes = stored; Ok(transferred) } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PageRunKind { + GpuBatch, + CpuBatch, + Single, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PageRun { + kind: PageRunKind, + start: usize, + end: usize, +} + +fn partition_restore_pages_by( + len: usize, + route_at: impl Fn(usize) -> DecodeRoute, + gpu_batch_cap: usize, + cpu_batch_cap: usize, +) -> Vec { + let gpu_cap = gpu_batch_cap.max(1); + let cpu_cap = cpu_batch_cap.max(1); + let mut runs = Vec::new(); + let mut i = 0; + while i < len { + let is_gpu = route_at(i) == DecodeRoute::GpuOnDevice; + let cap = if is_gpu { gpu_cap } else { cpu_cap }; + let mut j = i; + while j < len + && (route_at(j) == DecodeRoute::GpuOnDevice) == is_gpu + && j - i < cap + { + j += 1; + } + let kind = if j - i > 1 { + if is_gpu { + PageRunKind::GpuBatch + } else { + PageRunKind::CpuBatch + } + } else { + PageRunKind::Single + }; + runs.push(PageRun { + kind, + start: i, + end: j, + }); + i = j; + } + runs +} + +/// Acquires `CopyEngineGate::enter_offload_batch` before locking the GPU codec mutex so +/// background capture threads waiting on active peer-copy graphs never hold the codec mutex. +fn with_gpu_codec_locked( + copy_gate: Option<&super::super::CopyEngineGate>, + codec: &Mutex, + f: impl FnOnce(&mut T) -> Result, +) -> Result { + let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let mut guard = codec.lock().unwrap(); + f(&mut guard) +} + +/// Non-blockingly acquires the GPU codec mutex and an immediate `CopyEngineGate` offload +/// batch lease. Returns `None` without waiting or consuming a gate wave token when another +/// thread holds the codec mutex or a peer-copy graph blocks the gate, allowing foreground +/// restores to fall back immediately to CPU decoding without deadlock. +fn try_with_gpu_codec_locked( + copy_gate: Option<&super::super::CopyEngineGate>, + codec: &Mutex, + f: impl FnOnce(&mut T) -> Result, +) -> Option> { + let mut guard = codec.try_lock().ok()?; + let _ce = match copy_gate { + Some(gate) => Some(gate.try_enter_offload_batch()?), + None => None, + }; + Some(f(&mut guard)) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum DecodeRoute { Literal, @@ -955,12 +1059,12 @@ fn zero_span_gaps(buf: &mut [u8], spans: &[DeviceSpan]) { buf.fill(0); } -fn copy_spans_batch( +fn copy_spans_batch>( stream: &Stream, event: &Event, copy_gate: Option<&super::super::CopyEngineGate>, direction: Direction, - batch: &[(usize, Vec)], + batch: &[(usize, S)], host: u64, ) -> Result<()> { let mut copies = GatedCopies::new(stream, event, copy_gate); @@ -987,7 +1091,7 @@ fn copy_spans_batch( }; for (slot_start, spans) in batch { let base = host + *slot_start as u64; - for p in spans { + for p in spans.as_ref() { for start in (0..p.length).step_by(BATCH_BYTES) { let n = (p.length - start).min(BATCH_BYTES); if !lens.is_empty() && (lens.len() >= BATCH_ENTRIES || queued + n > BATCH_BYTES) { @@ -1509,4 +1613,163 @@ mod tests { assert!(device_spans(&geometry, &layout.ranks[0], true, 1).is_ok()); assert!(device_spans(&geometry, &layout.ranks[0], true, 4).is_err()); } + + #[test] + fn partition_restore_pages_continues_gpu_batching_after_literal_and_cpu_pages() { + use DecodeRoute::*; + use PageRunKind::*; + + let partition_restore_pages = |routes: &[DecodeRoute], gpu_cap: usize, cpu_cap: usize| { + partition_restore_pages_by(routes.len(), |i| routes[i], gpu_cap, cpu_cap) + }; + + // Leading Literal page must not abort GPU batching for trailing GpuOnDevice pages. + let runs = partition_restore_pages( + &[Literal, GpuOnDevice, GpuOnDevice, GpuOnDevice, GpuOnDevice], + 4, + 4, + ); + assert_eq!( + runs, + vec![ + PageRun { kind: Single, start: 0, end: 1 }, + PageRun { kind: GpuBatch, start: 1, end: 5 }, + ] + ); + + // Interleaved singleton GpuOnDevice, Literal, Cpu batches, and multi-page GpuOnDevice runs. + let runs = partition_restore_pages( + &[ + GpuOnDevice, + Literal, + GpuOnDevice, + GpuOnDevice, + GpuOnDevice, + Cpu, + GpuOnCpu, + GpuOnDevice, + GpuOnDevice, + ], + 4, + 4, + ); + assert_eq!( + runs, + vec![ + PageRun { kind: Single, start: 0, end: 1 }, + PageRun { kind: Single, start: 1, end: 2 }, + PageRun { kind: GpuBatch, start: 2, end: 5 }, + PageRun { kind: CpuBatch, start: 5, end: 7 }, + PageRun { kind: GpuBatch, start: 7, end: 9 }, + ] + ); + + // Respects gpu_batch_cap and cpu_batch_cap limits and degenerates cleanly at cap == 1. + let runs = partition_restore_pages( + &[GpuOnDevice, GpuOnDevice, GpuOnDevice, Cpu, Cpu, Cpu], + 2, + 2, + ); + assert_eq!( + runs, + vec![ + PageRun { kind: GpuBatch, start: 0, end: 2 }, + PageRun { kind: Single, start: 2, end: 3 }, + PageRun { kind: CpuBatch, start: 3, end: 5 }, + PageRun { kind: Single, start: 5, end: 6 }, + ] + ); + let single_cap = partition_restore_pages(&[GpuOnDevice, GpuOnDevice], 1, 4); + assert_eq!( + single_cap, + vec![ + PageRun { kind: Single, start: 0, end: 1 }, + PageRun { kind: Single, start: 1, end: 2 }, + ] + ); + assert!(partition_restore_pages(&[], 4, 4).is_empty()); + } + + #[test] + fn copy_engine_gate_before_codec_mutex_leaves_mutex_unheld_while_waiting_on_peer_graph() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let gate = Arc::new(crate::offload::CopyEngineGate::new()); + let codec_mutex = Arc::new(Mutex::new(0usize)); + let peer_guard = gate.enter_peer_graph().unwrap(); + + let entering = Arc::new(AtomicBool::new(false)); + let finished = Arc::new(AtomicBool::new(false)); + let gate_c = Arc::clone(&gate); + let mutex_c = Arc::clone(&codec_mutex); + let entering_c = Arc::clone(&entering); + let finished_c = Arc::clone(&finished); + + // Exercises the production capture lock helper while a peer-copy graph holds CopyEngineGate. + let capture = std::thread::spawn(move || { + entering_c.store(true, Ordering::Release); + with_gpu_codec_locked(Some(&gate_c), &mutex_c, |count| { + *count += 1; + Ok(()) + }) + .unwrap(); + finished_c.store(true, Ordering::Release); + }); + + while !entering.load(Ordering::Acquire) { + std::thread::yield_now(); + } + std::thread::sleep(Duration::from_millis(20)); + assert!(!finished.load(Ordering::Acquire)); + // Waiting background capture must not hold the codec mutex while blocked on CopyEngineGate. + assert!( + codec_mutex.try_lock().is_ok(), + "background capture blocked on CopyEngineGate must not hold gpu.codec mutex" + ); + + // While PeerGraphGuard is held, foreground try_with_gpu_codec_locked must return None + // immediately (without blocking on CopyEngineGate) so CPU decode runs in parallel. + let try_start = Instant::now(); + assert!( + try_with_gpu_codec_locked(Some(&gate), &codec_mutex, |count| { + *count += 1; + Ok(()) + }) + .is_none(), + "foreground try_with_gpu_codec_locked must fall back immediately while peer graph holds gate" + ); + assert!( + try_start.elapsed() < Duration::from_millis(50), + "try_with_gpu_codec_locked blocked behind PeerGraphGuard" + ); + + drop(peer_guard); + capture.join().unwrap(); + assert!(finished.load(Ordering::Acquire)); + assert_eq!(*codec_mutex.lock().unwrap(), 1); + + // Contended codec.try_lock() returns None without blocking or touching CopyEngineGate. + let held = codec_mutex.lock().unwrap(); + assert!( + try_with_gpu_codec_locked(Some(&gate), &codec_mutex, |count| { + *count += 1; + Ok(()) + }) + .is_none() + ); + let peer_after_contention = gate.enter_peer_graph().unwrap(); + drop(peer_after_contention); + drop(held); + + // Uncontended foreground try-lock succeeds through the same helper. + assert_eq!( + try_with_gpu_codec_locked(Some(&gate), &codec_mutex, |count| { + *count += 1; + Ok(*count) + }) + .transpose() + .unwrap(), + Some(2) + ); + } } diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 8f651b6bb..daae9d9fb 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -265,6 +265,8 @@ pub struct LiveRequest { growable_output: bool, /// Finishing to free its pages; the runtime readmits its history instead of completing it. preempted: bool, + /// Waiting for an in-flight frame to drain before transitioning to a checkpoint-preserving park. + paused_for_park: bool, admission_order: u64, core_parameters: crate::model::CoreParameters, } @@ -274,6 +276,18 @@ impl LiveRequest { &self.core_parameters } + pub fn pending(&self) -> usize { + self.pending + } + + pub fn deferred_prefill(&self) -> bool { + self.deferred_prefill + } + + pub fn paused_for_park(&self) -> bool { + self.paused_for_park + } + pub fn checkpoint_accounting(&self) -> CheckpointAccounting { self.checkpoints.clone() } @@ -1428,6 +1442,7 @@ impl RequestScheduler { .any(|request| { request.phase == RequestPhase::Decode && !request.preempted + && !request.paused_for_park && !self.fits_next_rounds(request) }) } @@ -1443,6 +1458,7 @@ impl RequestScheduler { Some(request) if request.growable_output && !request.preempted + && !request.paused_for_park && request.phase == RequestPhase::Decode => { self.pages_through(request, request.scheduled_consumed + ahead) @@ -1524,6 +1540,7 @@ impl RequestScheduler { .filter(|request| { request.growable_output && !request.preempted + && !request.paused_for_park && request.phase == RequestPhase::Decode && request.pending == 0 }) @@ -1910,6 +1927,7 @@ impl RequestScheduler { prefill_spans: Vec::new(), growable_output: spec.growable_output, preempted: false, + paused_for_park: false, admission_order: self.admissions, core_parameters, }); @@ -3228,6 +3246,70 @@ impl RequestScheduler { Ok(()) } + /// Toggles device-side grammar enforcement for an active request with no pending GPU work. + pub fn set_grammar_constrained( + &mut self, + handle: RequestHandle, + constrained: bool, + ) -> Result<()> { + let request = self.request(handle)?; + if request.pending != 0 + || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing) + || (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none()) + { + return Err( + "grammar constraint mode requires a live request with no pending GPU work".into(), + ); + } + self.request_mut(handle)?.grammar_constrained = constrained; + Ok(()) + } + + /// Pauses a request with pending GPU work from receiving additional steps while its + /// in-flight frame drains for a checkpoint-preserving park. + pub fn pause_for_park(&mut self, handle: RequestHandle) -> Result<()> { + let request = self.request(handle)?; + if request.pending == 0 + || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing) + { + return Err("pausing for park requires an active request with pending GPU work".into()); + } + self.request_mut(handle)?.paused_for_park = true; + Ok(()) + } + + /// Transitions a live request with no pending GPU work to terminal checkpoint publication + /// so the runtime can park and readmit it without discarding KV or recurrent state. + pub fn finish_for_park(&mut self, handle: RequestHandle) -> Result<()> { + let request = self.request(handle)?; + if request.pending != 0 || request.phase == RequestPhase::Inbound { + return Err( + "finishing for park requires a live request with no pending GPU work".into(), + ); + } + if let Some(capture) = request.boundary_capture + && matches!(capture.kind, BoundaryKind::ConditionedWindow) + { + return Err("cannot park during a conditioned-window boundary capture".into()); + } + let now_ns = self.now_ns; + let phase = request.phase; + let has_boundary = request.boundary_capture.is_some(); + let has_terminal = request.terminal_snapshot.is_some(); + self.request_mut(handle)?.paused_for_park = false; + match phase { + RequestPhase::Finishing => Ok(()), + RequestPhase::Snapshot if has_boundary => { + let request = self.request_mut(handle)?; + request.boundary_capture.as_mut().unwrap().resume = RequestPhase::Finishing; + request.accounting.terminal_since_ns.get_or_insert(now_ns); + Ok(()) + } + RequestPhase::Snapshot if has_terminal => Ok(()), + _ => self.finish_early(handle, false), + } + } + /// Cancels scheduling immediately; resources remain reserved through last GPU use. pub fn cancel(&mut self, handle: RequestHandle) -> Result<()> { self.retire(handle, false).map(|_| ()) diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 2e7211b17..b621acfbe 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -76,14 +76,26 @@ pub(super) struct FullChunkAffine { pub slope_per_pos_ns: f64, } +fn clamp_nanos(value: f64) -> u64 { + if !value.is_finite() || value <= 1.0 { + 1 + } else if value >= u64::MAX as f64 { + u64::MAX + } else { + value.round() as u64 + } +} + #[derive(Clone, Copy, Debug)] pub(super) struct PrefillPredictor { capacity: usize, constant_nanos: Option, theta: [f64; 3], - u_min: f64, - u_max: f64, - t_at_umax: f64, + pos_u_min: f64, + pos_u_max: f64, + t_at_umin: f64, + pos_t_at_umax: f64, + has_zero_fill: bool, has_deep_context: bool, } @@ -94,14 +106,15 @@ impl PrefillPredictor { capacity: capacity.max(1), constant_nanos: Some(nanos), theta: [nanos_f, 0.0, 0.0], - u_min: 1.0, - u_max: 1.0, - t_at_umax: nanos_f, + pos_u_min: 1.0, + pos_u_max: 1.0, + t_at_umin: nanos_f, + pos_t_at_umax: nanos_f, + has_zero_fill: false, has_deep_context: false, } } - #[cfg(test)] pub fn is_constant(&self) -> bool { self.constant_nanos.is_some() } @@ -111,6 +124,10 @@ impl PrefillPredictor { self.constant_nanos } + pub fn has_positive_fill(&self) -> bool { + self.pos_u_max > 0.0 + } + pub fn has_deep_context(&self) -> bool { self.has_deep_context } @@ -121,7 +138,7 @@ impl PrefillPredictor { } pub fn with_borrowed_context_slope(mut self, theta2: f64) -> Self { - if !self.has_deep_context && theta2 > 0.0 && theta2.is_finite() { + if !self.has_deep_context && self.pos_u_max > 0.0 && theta2 > 0.0 && theta2.is_finite() { self.theta[2] = theta2; self.constant_nanos = None; } @@ -129,8 +146,11 @@ impl PrefillPredictor { } fn upward_extrapolation_floor(&self, u: f64) -> f64 { - if (self.u_max - self.u_min) < 0.15 && u > self.u_max && self.u_max > 0.0 { - self.t_at_umax * (u / self.u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION) + if self.pos_u_max > 0.0 + && (self.pos_u_max - self.pos_u_min) < 0.15 + && u > self.pos_u_max + { + self.pos_t_at_umax * (u / self.pos_u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION) } else { 0.0 } @@ -146,6 +166,13 @@ impl PrefillPredictor { slope_per_pos_ns: 0.0, }; } + if self.pos_u_max <= 0.0 { + return FullChunkAffine { + exact_constant_ns: Some(0), + intercept_ns: 0.0, + slope_per_pos_ns: 0.0, + }; + } let intercept = (self.theta[0] + self.theta[1]).max(self.upward_extrapolation_floor(1.0)); let slope = self.theta[2] / PREFILL_CTX_SCALE; if slope == 0.0 { @@ -168,21 +195,30 @@ impl PrefillPredictor { if let Some(nanos) = self.constant_nanos { return nanos; } + if work == 0 { + // Only trust NNLS intercept `theta[0]` when an actual zero-fill sample anchors it; + // barely sub-linear positive-fill pairs can otherwise fit a tiny positive intercept + // and collapse decode-only pricing toward 1 ns. + let base = if self.has_zero_fill && self.theta[0] > 0.0 && self.theta[0].is_finite() { + self.theta[0] + } else { + self.t_at_umin + }; + return clamp_nanos(base); + } + if self.pos_u_max <= 0.0 { + // Only zero-fill (decode-only) samples have been observed; positive-fill duration + // remains unmeasured (0 ns) until a positive-fill step executes. + return 0; + } let cap = self.capacity.max(1); let u = work.clamp(1, cap) as f64 / cap as f64; let h = u * (start_position as f64 / PREFILL_CTX_SCALE); - // Bounded constant-throughput upward guard when only a narrow fill regime has been - // observed (`u_max - u_min < 0.15`), preventing partial fills from discounting + // Bounded constant-throughput upward guard when only a narrow positive-fill regime has + // been observed (`pos_u_max - pos_u_min < 0.15`), preventing partial fills from discounting // full-chunk cost while avoiding uncapped post-TTL lockout on large capacities. let base = (self.theta[0] + self.theta[1] * u).max(self.upward_extrapolation_floor(u)); - let pred = base + self.theta[2] * h; - if !pred.is_finite() || pred <= 1.0 { - 1 - } else if pred >= u64::MAX as f64 { - u64::MAX - } else { - pred.round() as u64 - } + clamp_nanos(base + self.theta[2] * h) } } @@ -264,6 +300,7 @@ impl PrefillBucket { #[derive(Clone)] struct PrefillCostModel { capacity: usize, + zero_fill: PrefillBucket, strata: [PrefillBucket; PREFILL_STRATA], predictor: Option, } @@ -272,6 +309,7 @@ impl PrefillCostModel { fn new(capacity: usize) -> Self { Self { capacity: capacity.max(1), + zero_fill: PrefillBucket::default(), strata: [PrefillBucket::default(); PREFILL_STRATA], predictor: None, } @@ -279,6 +317,7 @@ impl PrefillCostModel { #[cfg(test)] fn reset_with_full(&mut self, nanos: u64) { + self.zero_fill = PrefillBucket::default(); self.strata = [PrefillBucket::default(); PREFILL_STRATA]; if nanos == 0 { self.predictor = None; @@ -288,39 +327,79 @@ impl PrefillCostModel { self.predictor = Some(PrefillPredictor::constant(self.capacity, nanos)); } - /// Records a prefill replay sample and returns the fitted full-fill, zero-context - /// prediction (`predict(capacity, 0)`), which `Estimate::nanos` and telemetry - /// (`SubmittedTiming.retained_ns`) retain as the graph's baseline duration. + /// Records a prefill or mixed-graph replay sample and returns the fitted full-fill, + /// zero-context prediction (`predict(capacity, 0)`), which `Estimate::nanos` and + /// telemetry (`SubmittedTiming.retained_ns`) retain as the graph's baseline duration. fn observe(&mut self, nanos: u64, work: usize, start_position: u64, fresh: bool) -> u64 { if !fresh { + self.zero_fill = PrefillBucket::default(); self.strata = [PrefillBucket::default(); PREFILL_STRATA]; } - let cap = self.capacity.max(1); - let u = work.clamp(1, cap) as f64 / cap as f64; - let h = u * (start_position as f64 / PREFILL_CTX_SCALE); - let fill_bin = usize::from(u > 0.5); - let ctx_bin = if start_position < 4096 { - 0 - } else if start_position < 32768 { - 1 + if work == 0 { + self.zero_fill + .observe(PrefillSample { nanos, u: 0.0, h: 0.0 }); } else { - 2 - }; - self.strata[fill_bin * PREFILL_CTX_STRATA + ctx_bin] - .observe(PrefillSample { nanos, u, h }); + let cap = self.capacity.max(1); + let u = work.clamp(1, cap) as f64 / cap as f64; + let h = u * (start_position as f64 / PREFILL_CTX_SCALE); + let fill_bin = usize::from(u > 0.5); + let ctx_bin = if start_position < 4096 { + 0 + } else if start_position < 32768 { + 1 + } else { + 2 + }; + self.strata[fill_bin * PREFILL_CTX_STRATA + ctx_bin] + .observe(PrefillSample { nanos, u, h }); + } let predictor = self.fit(); self.predictor = Some(predictor); - predictor.predict(self.capacity, 0) + if predictor.has_positive_fill() { + predictor.predict(self.capacity, 0) + } else { + predictor.predict(0, 0) + } } fn fit(&self) -> PrefillPredictor { - let mut pts = [(0.0f64, 0.0f64, 0.0f64); PREFILL_STRATA]; + let mut pts = [(0.0f64, 0.0f64, 0.0f64); PREFILL_STRATA + 1]; let mut n = 0usize; let mut u_min = f64::INFINITY; - let mut u_max = f64::NEG_INFINITY; - let mut t_at_umax = 0.0f64; - let mut h_at_umax = f64::INFINITY; + let mut t_at_umin = 0.0f64; + let mut h_at_umin = f64::INFINITY; + let mut pos_u_min = f64::INFINITY; + let mut pos_u_max = 0.0f64; + let mut pos_t_at_umax = 0.0f64; + let mut pos_h_at_umax = f64::INFINITY; + let mut has_zero_fill = false; let mut has_deep_context = false; + let mut record_point = |t: f64, u: f64, h: f64| { + pts[n] = (t, u, h); + n += 1; + if u < u_min - 1e-12 || ((u - u_min).abs() <= 1e-12 && h < h_at_umin) { + u_min = u; + t_at_umin = t; + h_at_umin = h; + } + if u > 0.0 { + if u < pos_u_min - 1e-12 { + pos_u_min = u; + } + if u > pos_u_max + 1e-12 || ((u - pos_u_max).abs() <= 1e-12 && h < pos_h_at_umax) { + pos_u_max = u; + pos_t_at_umax = t; + pos_h_at_umax = h; + } + } + }; + if let Some((t, u, h)) = self.zero_fill.median() + && t > 0.0 + && t.is_finite() + { + has_zero_fill = true; + record_point(t, u, h); + } for (stratum_idx, bucket) in self.strata.iter().enumerate() { let Some((t, u, h)) = bucket.median() else { continue; @@ -331,14 +410,7 @@ impl PrefillCostModel { if stratum_idx % PREFILL_CTX_STRATA > 0 { has_deep_context = true; } - pts[n] = (t, u, h); - n += 1; - u_min = u_min.min(u); - if u > u_max + 1e-12 || ((u - u_max).abs() <= 1e-12 && h < h_at_umax) { - u_max = u; - t_at_umax = t; - h_at_umax = h; - } + record_point(t, u, h); } if n == 0 { return PrefillPredictor::constant(self.capacity, 1); @@ -358,7 +430,8 @@ impl PrefillCostModel { } } } - let mut best_theta = [t_at_umax, 0.0, 0.0]; + let fallback_t = if pos_u_max > 0.0 { pos_t_at_umax } else { t_at_umin }; + let mut best_theta = [fallback_t, 0.0, 0.0]; let mut best_sse = f64::INFINITY; let mut best_params = usize::MAX; for mask in 1u8..8u8 { @@ -395,17 +468,21 @@ impl PrefillCostModel { best_params = k; } } + let wide_or_full_positive = + pos_u_max > 0.0 && (pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15); let constant_nanos = (best_theta[1] == 0.0 && best_theta[2] == 0.0 - && (u_max >= 1.0 - 1e-9 || (u_max - u_min) >= 0.15)) - .then_some(best_theta[0].round().clamp(1.0, u64::MAX as f64) as u64); + && wide_or_full_positive) + .then_some(clamp_nanos(best_theta[0])); PrefillPredictor { capacity: self.capacity, constant_nanos, theta: best_theta, - u_min, - u_max, - t_at_umax, + pos_u_min: if pos_u_max > 0.0 { pos_u_min } else { 0.0 }, + pos_u_max, + t_at_umin, + pos_t_at_umax, + has_zero_fill, has_deep_context, } } @@ -541,6 +618,15 @@ fn prefill_kind_slot(kind: GraphKind) -> Option { } } +#[derive(Clone, Copy)] +struct MixedContextSlope { + batch: usize, + width: usize, + prefill: usize, + slope: f64, + observed_at_ns: u64, +} + #[derive(Default)] pub(super) struct ActionCosts { entries: Vec<(Key, Estimate)>, @@ -551,6 +637,8 @@ pub(super) struct ActionCosts { /// sorted descending by `capacity` so unmeasured-at-deep-context smaller capacities can /// borrow KV-attention scaling from strictly larger fresh peers without extra lookups. prefill_context_slopes: [Vec<(usize, f64, u64)>; 3], + /// Measured peers for `GraphKind::Mixed`, sorted descending by `prefill`. + mixed_context_slopes: Vec, now_ns: u64, ttl_ns: u64, } @@ -578,7 +666,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.kind == GraphKind::Mixed { self.refresh_prefill_context_slopes(); } } @@ -603,7 +691,13 @@ impl ActionCosts { Estimate { nanos: 0, replays: ReplayTimes::default(), - prefill: key.kind.is_prefill().then(|| PrefillCostModel::new(key.tokens)), + prefill: if key.kind.is_prefill() { + Some(PrefillCostModel::new(key.tokens)) + } else if key.kind == GraphKind::Mixed && key.prefill > 0 { + Some(PrefillCostModel::new(key.prefill)) + } else { + None + }, observed_at_ns: 0, last_attempt_ns: 0, }, @@ -685,6 +779,49 @@ impl ActionCosts { self.prefill_entry(kind, capacity).flatten() } + pub fn mixed_entry( + &self, + batch: usize, + width: usize, + prefill: usize, + ) -> Option> { + let key = Key { + drafts: 0, + kind: GraphKind::Mixed, + batch, + tokens: width, + prefill, + packed: 0, + }; + let estimate = self.entry(key)?; + if estimate.nanos == 0 { + return Some(None); + } + let mut predictor = estimate + .prefill + .as_ref() + .and_then(|model| model.predictor) + .unwrap_or_else(|| PrefillPredictor::constant(prefill.max(1), estimate.nanos)); + if !predictor.has_deep_context() + && let Some(theta2) = self.borrowed_mixed_context_slope(batch, width, prefill) + { + predictor = predictor.with_borrowed_context_slope(theta2); + } + Some(Some(predictor)) + } + + pub fn mixed_duration( + &self, + batch: usize, + width: usize, + prefill: usize, + work: usize, + start_position: u64, + ) -> Option { + self.mixed_entry(batch, width, prefill) + .map(|predictor| predictor.map_or(0, |p| p.predict(work, start_position))) + } + /// Positive duration estimate for an unmeasured pure-prefill capacity derived /// strictly from already-measured GPU durations: first a measured sibling /// (`Prefill` <-> `TerminalPrefill`) at the same capacity, else linear @@ -784,17 +921,33 @@ impl ActionCosts { .map(|&(_, slope, _)| slope * capacity.max(1) as f64) } + fn borrowed_mixed_context_slope( + &self, + batch: usize, + width: usize, + prefill: usize, + ) -> Option { + self.mixed_context_slopes + .iter() + .find(|peer| { + peer.batch == batch + && peer.width == width + && peer.prefill > prefill + && peer.slope > 0.0 + && self.now_ns.saturating_sub(peer.observed_at_ns) < self.ttl_ns + }) + .map(|peer| peer.slope * prefill.max(1) as f64) + } + fn refresh_prefill_context_slopes(&mut self) { for list in &mut self.prefill_context_slopes { list.clear(); } + self.mixed_context_slopes.clear(); for (key, estimate) in &self.entries { - if key.batch != 1 || estimate.nanos == 0 { + if estimate.nanos == 0 { continue; } - let Some(slot) = prefill_kind_slot(key.kind) else { - continue; - }; let Some(slope) = estimate .prefill .as_ref() @@ -803,11 +956,25 @@ impl ActionCosts { else { continue; }; - self.prefill_context_slopes[slot].push((key.tokens, slope, estimate.observed_at_ns)); + if key.batch == 1 + && let Some(slot) = prefill_kind_slot(key.kind) + { + self.prefill_context_slopes[slot].push((key.tokens, slope, estimate.observed_at_ns)); + } else if key.kind == GraphKind::Mixed && key.prefill > 0 { + self.mixed_context_slopes.push(MixedContextSlope { + batch: key.batch, + width: key.tokens, + prefill: key.prefill, + slope, + observed_at_ns: estimate.observed_at_ns, + }); + } } for list in &mut self.prefill_context_slopes { list.sort_unstable_by(|a, b| b.0.cmp(&a.0)); } + self.mixed_context_slopes + .sort_unstable_by(|a, b| b.prefill.cmp(&a.prefill)); } fn refresh_packed_durations(&mut self) { @@ -915,6 +1082,21 @@ impl ActionCosts { ); } } + if step.kind == GraphKind::Mixed { + let (work, start_position) = step + .mixed + .as_ref() + .and_then(|m| m.prefill_row) + .and_then(|row| step.lanes.get(row)) + .map_or((0, 0), |lane| (lane.tokens, lane.start_position)); + return self.mixed_duration( + step.batch_capacity, + step.token_capacity, + step.prefill_capacity(), + work, + start_position, + ); + } self.duration_key(Key::from_step(step)) } @@ -938,17 +1120,28 @@ impl ActionCosts { let estimate = &mut self.entries[index].1; let fresh = estimate.fresh(self.now_ns, self.ttl_ns); if let Some(model) = estimate.prefill.as_mut() { - let (work, start_position) = step - .lanes - .first() - .map_or((step.token_capacity, 0), |lane| (lane.tokens, lane.start_position)); + let (work, start_position) = if step.kind == GraphKind::Mixed { + if step.lanes.is_empty() { + (step.prefill_capacity(), 0) + } else { + step.mixed + .as_ref() + .and_then(|m| m.prefill_row) + .and_then(|row| step.lanes.get(row)) + .map_or((0, 0), |lane| (lane.tokens, lane.start_position)) + } + } else { + step.lanes + .first() + .map_or((step.token_capacity, 0), |lane| (lane.tokens, lane.start_position)) + }; estimate.nanos = model.observe(sample, work, start_position, fresh); } else { estimate.nanos = estimate.replays.observe(sample, fresh); } estimate.observed_at_ns = self.now_ns; self.refresh_packed_durations(); - if key.kind.is_prefill() { + if key.kind.is_prefill() || key.kind == GraphKind::Mixed { self.refresh_prefill_context_slopes(); } } @@ -1586,4 +1779,153 @@ mod tests { Some(expected_spec) ); } + + #[test] + fn mixed_cost_model_tracks_zero_fill_partial_fill_deep_context_and_peer_slope() { + use crate::scheduler::{MixedStep, RequestHandle, ScheduledLane}; + + let make_mixed = |name: &str, batch: usize, width: usize, prefill: usize| GraphDescriptor { + name: name.into(), + kind: GraphKind::Mixed, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: batch, + token_capacity: width, + packed_token_capacity: 0, + prefill_capacity: prefill, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }; + let mixed_step = |batch: usize, + width: usize, + prefill: usize, + prompt: Option<(usize, u64)>| ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Mixed, + batch_capacity: batch, + token_capacity: width, + packed_token_capacity: 0, + mixed: Some(MixedStep { + prefill_capacity: prefill, + prefill_row: prompt.map(|_| 0), + speculative: width > 1, + }), + lanes: match prompt { + Some((tokens, start_position)) => vec![ + ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position, + tokens, + }, + ScheduledLane { + request: RequestHandle { slot: 1, generation: 1 }, + start_position: 128, + tokens: width, + }, + ], + None => vec![ScheduledLane { + request: RequestHandle { slot: 1, generation: 1 }, + start_position: 128, + tokens: width, + }], + }, + requires_feedback: true, + }; + + let graphs = vec![ + make_mixed("m4-1-512", 4, 1, 512), + make_mixed("m4-1-2048", 4, 1, 2048), + make_mixed("m2-1-512", 2, 1, 512), + ]; + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + let ttl = 30_000_000_000u64; + costs.advance_to(1_000_000_000, ttl); + + // Observe decode-only (work=0, 15 ms), full shallow prefill (2048 @ 0, 95 ms), + // and deep-context full prefill (2048 @ 32768, 175 ms). + costs.observe(&mixed_step(4, 1, 2048, None), make_test_timing(15_000_000)); + costs.observe(&mixed_step(4, 1, 2048, Some((2048, 0))), make_test_timing(95_000_000)); + costs.observe(&mixed_step(4, 1, 2048, Some((2048, 32_768))), make_test_timing(175_000_000)); + + // 50 consecutive decode-only or short-tail steps must not poison full-chunk predictions. + for _ in 0..50 { + costs.observe(&mixed_step(4, 1, 2048, None), make_test_timing(15_000_000)); + costs.observe(&mixed_step(4, 1, 2048, Some((256, 0))), make_test_timing(25_000_000)); + } + let decode_only = costs.mixed_duration(4, 1, 2048, 0, 0).unwrap(); + let quarter_fill = costs.mixed_duration(4, 1, 2048, 512, 0).unwrap(); + let full_shallow = costs.mixed_duration(4, 1, 2048, 2048, 0).unwrap(); + let full_mid_ctx = costs.mixed_duration(4, 1, 2048, 2048, 16_384).unwrap(); + let full_deep = costs.mixed_duration(4, 1, 2048, 2048, 32_768).unwrap(); + assert!((decode_only as i64 - 15_000_000).abs() < 2_000_000, "decode_only={decode_only}"); + assert!((quarter_fill as i64 - 35_000_000).abs() < 3_000_000, "quarter={quarter_fill}"); + assert!((full_shallow as i64 - 95_000_000).abs() < 3_000_000, "shallow={full_shallow}"); + assert!((full_mid_ctx as i64 - 135_000_000).abs() < 3_000_000, "mid={full_mid_ctx}"); + assert!((full_deep as i64 - 175_000_000).abs() < 3_000_000, "deep={full_deep}"); + + // ActionCosts::get routes Mixed steps through (work, start_position). + assert_eq!(costs.get(&mixed_step(4, 1, 2048, None)), Some(decode_only)); + assert_eq!(costs.get(&mixed_step(4, 1, 2048, Some((2048, 32_768)))), Some(full_deep)); + + // Smaller same-(batch, width) Mixed peer borrows per-token KV-context slope from 2048, + // while a different-batch peer (batch=2) does not cross-borrow. + costs.observe(&mixed_step(4, 1, 512, Some((512, 0))), make_test_timing(35_000_000)); + costs.observe(&mixed_step(2, 1, 512, Some((512, 0))), make_test_timing(30_000_000)); + let borrowed_512 = costs.mixed_duration(4, 1, 512, 512, 32_768).unwrap(); + let isolated_b2 = costs.mixed_duration(2, 1, 512, 512, 32_768).unwrap(); + assert!( + (borrowed_512 as i64 - 55_000_000).abs() < 3_000_000, + "same-(B,W) peer must borrow 20ms KV slope at 32k: {borrowed_512}" + ); + assert_eq!(isolated_b2, 30_000_000, "different batch must not borrow slope"); + + // Super-linear fill without a work==0 sample (NNLS clamps theta_0 = 0) must fall back + // to t_at_umin for work==0 instead of returning 1 ns. + costs.advance_to(1_000_000_000 + ttl + 1, ttl); + costs.observe(&mixed_step(2, 1, 512, Some((128, 0))), make_test_timing(20_000_000)); + costs.observe(&mixed_step(2, 1, 512, Some((512, 0))), make_test_timing(90_000_000)); + let safe_zero = costs.mixed_duration(2, 1, 512, 0, 0).unwrap(); + assert!( + safe_zero >= 20_000_000, + "zero-intercept fit must not extrapolate work==0 below t_at_umin: {safe_zero}" + ); + + // Barely sub-linear positive-fill observations without a zero_fill sample fit a tiny + // positive theta[0]; predict(0, 0) must still return t_at_umin rather than collapsing to 1 ns. + costs.advance_to(1_000_000_000 + 2 * ttl + 2, ttl); + costs.observe(&mixed_step(2, 1, 512, Some((128, 0))), make_test_timing(20_000_000)); + costs.observe(&mixed_step(2, 1, 512, Some((512, 0))), make_test_timing(79_999_999)); + let guarded_zero = costs.mixed_duration(2, 1, 512, 0, 0).unwrap(); + assert_eq!( + guarded_zero, 20_000_000, + "barely sub-linear positive-fill points without zero_fill must not collapse work==0" + ); + + // Post-TTL zero_fill-only observations must price decode-only (work==0) accurately while + // leaving positive-fill queries unmeasured (0 ns, non-constant) until a positive-fill step + // executes, so full-chunk prefills are never under-priced at decode_ns. + costs.advance_to(1_000_000_000 + 3 * ttl + 3, ttl); + costs.observe(&mixed_step(4, 1, 2048, None), make_test_timing(15_000_000)); + let zero_only_pred = costs.mixed_entry(4, 1, 2048).flatten().unwrap(); + assert_eq!(zero_only_pred.constant_ns(), None); + assert!(!zero_only_pred.has_positive_fill()); + assert_eq!(costs.mixed_duration(4, 1, 2048, 0, 0), Some(15_000_000)); + assert_eq!(costs.mixed_duration(4, 1, 2048, 2048, 0), Some(0)); + assert_eq!(costs.mixed_duration(4, 1, 2048, 2048, 32_768), Some(0)); + + // Adding a single narrow positive tail (u=0.0625) on top of zero_fill must still apply + // the bounded 4x upward floor over positive-fill strata (64 ms vs 31 ms raw NNLS). + costs.observe(&mixed_step(4, 1, 2048, Some((128, 0))), make_test_timing(16_000_000)); + let guarded_with_zero = costs.mixed_duration(4, 1, 2048, 2048, 0).unwrap(); + assert_eq!(guarded_with_zero, 64_000_000); + + // Post-TTL single narrow positive tail (no zero_fill) applies bounded 4x upward floor. + costs.advance_to(1_000_000_000 + 4 * ttl + 4, ttl); + costs.observe(&mixed_step(4, 1, 2048, Some((128, 0))), make_test_timing(20_000_000)); + let guarded = costs.mixed_duration(4, 1, 2048, 2048, 0).unwrap(); + assert_eq!(guarded, 80_000_000); + } } diff --git a/helios/src/scheduler/lifecycle_tests.rs b/helios/src/scheduler/lifecycle_tests.rs index c4d8743e7..cee737b61 100644 --- a/helios/src/scheduler/lifecycle_tests.rs +++ b/helios/src/scheduler/lifecycle_tests.rs @@ -106,8 +106,12 @@ impl Fixture { result[0] = self.logical_fence(s.submitted); result[1] = self.logical_fence(s.completed); for (index, slot) in s.slots.iter().enumerate() { - result[2 + index] = if slot.request.is_some() { - 1 + result[2 + index] = if let Some(request) = &slot.request { + if request.paused_for_park { + 3 + } else { + 1 + } } else if slot.retiring { 2 } else { @@ -153,6 +157,8 @@ impl Fixture { request.generated_tokens, request.scheduled_consumed, request.pending, + request.paused_for_park, + request.grammar_constrained, ( request.private_pages.clone(), request.reserved_pages.clone(), @@ -308,8 +314,26 @@ impl Fixture { actions.push([3, 0, 0]); } for (index, slot) in s.slots.iter().enumerate() { - if slot.request.is_some() { + if let Some(request) = &slot.request { actions.push([4, index as u64, 0]); + if index == 0 { + if !request.paused_for_park + && request.pending > 0 + && !matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing) + { + actions.push([7, 0, 0]); + } + if request.paused_for_park && request.pending == 0 { + actions.push([8, 0, 0]); + } + if !request.paused_for_park + && request.pending == 0 + && request.phase == RequestPhase::Decode + && !request.grammar_constrained + { + actions.push([9, 0, 0]); + } + } } } if s.slots @@ -493,6 +517,36 @@ impl Fixture { "confirmed drain lost private snapshots" ); } + 7 => { + let slot = action[1] as usize; + let handle = s.slots[slot].request.as_ref().unwrap().handle; + s.pause_for_park(handle).unwrap(); + assert!(s.request(handle).unwrap().paused_for_park); + // A paused request must never be scheduled into another frame. + if let Some(plan) = s.plan() { + assert!( + plan.lanes.iter().all(|lane| lane.request != handle), + "paused_for_park request was scheduled into a new plan" + ); + } + } + 8 => { + let slot = action[1] as usize; + let handle = s.slots[slot].request.as_ref().unwrap().handle; + s.finish_for_park(handle).unwrap(); + assert!(!s.request(handle).unwrap().paused_for_park); + assert!(matches!( + s.request(handle).unwrap().phase, + RequestPhase::Snapshot | RequestPhase::Finishing + )); + } + 9 => { + let slot = action[1] as usize; + let handle = s.slots[slot].request.as_ref().unwrap().handle; + let target = !s.request(handle).unwrap().grammar_constrained; + s.set_grammar_constrained(handle, target).unwrap(); + assert_eq!(s.request(handle).unwrap().grammar_constrained, target); + } _ => unreachable!(), } self.assert_ownership(); @@ -515,6 +569,13 @@ struct Coverage { feedback_barrier: bool, full_window_rejection: bool, feedback_rejection: bool, + paused_for_park: bool, + finished_for_park: bool, + cancelled_while_paused: bool, + toggled_grammar: bool, + rejected_pause_idle: bool, + rejected_toggle_pending: bool, + rejected_finish_pending: bool, } fn check_rejections(fixture: &mut Fixture, coverage: &mut Coverage) { @@ -596,6 +657,57 @@ fn check_rejections(fixture: &mut Fixture, coverage: &mut Coverage) { ); coverage.stale_handle = true; } + let live_slots = s + .slots + .iter() + .filter_map(|slot| { + slot.request.as_ref().map(|request| { + ( + request.handle, + request.pending, + request.paused_for_park, + request.grammar_constrained, + request.phase, + ) + }) + }) + .collect::>(); + for (handle, pending, paused, grammar_constrained, phase) in live_slots { + if pending == 0 { + assert!( + s.pause_for_park(handle).is_err(), + "pause_for_park accepted a request with no pending work" + ); + coverage.rejected_pause_idle = true; + } else { + assert!( + s.set_grammar_constrained(handle, !grammar_constrained) + .is_err(), + "set_grammar_constrained accepted a request with pending GPU work" + ); + assert!( + s.finish_for_park(handle).is_err(), + "finish_for_park accepted a request with pending GPU work" + ); + coverage.rejected_toggle_pending = true; + coverage.rejected_finish_pending = true; + } + if paused + && let Some(plan) = s.plan() + { + assert!( + plan.lanes.iter().all(|lane| lane.request != handle), + "paused_for_park request was offered by plan()" + ); + } + if phase == RequestPhase::Finishing { + assert!( + s.set_grammar_constrained(handle, !grammar_constrained) + .is_err(), + "set_grammar_constrained accepted a finishing request" + ); + } + } assert_eq!( fixture.state_key(), before, @@ -681,6 +793,10 @@ fn scheduler_matches_lifecycle_model() { } coverage.uncertain_drain |= action[0] == 5 && before[8] != 0; coverage.feedback_barrier |= action[0] == 2 && action[2] == 1; + coverage.paused_for_park |= action[0] == 7; + coverage.finished_for_park |= action[0] == 8; + coverage.cancelled_while_paused |= action[0] == 4 && before[2 + action[1] as usize] == 3; + coverage.toggled_grammar |= action[0] == 9; edges.insert((before, action, after)); let mut successor = path.clone(); successor.push(action); @@ -710,6 +826,16 @@ fn scheduler_matches_lifecycle_model() { && coverage.feedback_rejection, "missing drain or barrier coverage: {coverage:?}" ); + assert!( + coverage.paused_for_park + && coverage.finished_for_park + && coverage.cancelled_while_paused + && coverage.toggled_grammar + && coverage.rejected_pause_idle + && coverage.rejected_toggle_pending + && coverage.rejected_finish_pending, + "missing grammar-toggle or park lifecycle coverage: {coverage:?}" + ); for (before, action, after) in &edges { println!("LIFECYCLE_EDGE [{before:?}, {action:?}, {after:?}]"); } diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index d976a8734..ed0cc70d2 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -366,7 +366,8 @@ impl RequestScheduler { } pub(super) fn eligible(&self, request: &LiveRequest) -> bool { - if request.window_snapshot_ready + if request.paused_for_park + || request.window_snapshot_ready || self.request_kind(request).is_none() || (request.phase == RequestPhase::Vision && !request.conditioned_inputs_ready) { @@ -972,10 +973,7 @@ impl RequestScheduler { } } for &(batch, width, prefill) in &self.mixed_catalog { - let Some(ns) = self - .costs - .shape_duration(GraphKind::Mixed, batch, width, prefill) - else { + let Some(predictor) = self.costs.mixed_entry(batch, width, prefill) else { continue; }; if r.consumed_tokens < r.prompt_tokens as u64 @@ -988,6 +986,7 @@ impl RequestScheduler { } let work = self.prefill_work_through(r, prefill, cut); if work > 0 { + let ns = predictor.map_or(0, |p| p.predict(work, r.scheduled_consumed)); consider( ns, value.prefill_within( @@ -998,6 +997,7 @@ impl RequestScheduler { ); } } else if r.consumed_tokens >= r.prompt_tokens as u64 && r.generated_tokens > 0 { + let ns = predictor.map_or(0, |p| p.predict(0, 0)); let expected = if self.speculative_widths.is_empty() { 1.0 } else { @@ -1202,9 +1202,159 @@ impl RequestScheduler { } return; } + let mixed_predictor = if following == GraphKind::Mixed { + let Some(predictor) = self.costs.mixed_entry(batch, width, prefill) else { + return; + }; + predictor + } else { + None + }; + if following == GraphKind::Mixed + && let Some(pred) = mixed_predictor + && !pred.is_constant() + { + let first_ms = duration_ns as f64 / 1e6; + let decode = if self.speculative_widths.is_empty() { + GraphKind::Decode + } else { + GraphKind::Speculative + }; + let mut prompt_offers = [(0usize, 0usize, 0u64, false); REQUEST_LANES]; + let mut prompt_count = 0usize; + for (slot, entry) in self.slots.iter().enumerate() { + let Some(request) = entry.request.as_ref() else { + continue; + }; + let offered = mask & (1 << slot) != 0; + if offered && terminal_cleanup(request) { + continue; + } + let promoted_kind = offered + .then(|| self.following_kind(request, kind)) + .flatten(); + let ready_kind = self + .eligible(request) + .then(|| self.request_kind(request)) + .flatten(); + let promoted = if promoted_kind == Some(GraphKind::Prefill) + && !request.deferred_prefill + { + true + } else if ready_kind == Some(GraphKind::Prefill) && !request.deferred_prefill { + false + } else { + continue; + }; + let cut = self.estimated_checkpoint_cut(request); + let work = self.prefill_work_through(request, prefill, cut); + if work == 0 { + continue; + } + prompt_offers[prompt_count] = + (slot, work, request.scheduled_consumed, promoted); + prompt_count += 1; + } + let mut eval_mixed = |ns: u64, prompt: Option<(usize, usize, bool)>| { + let horizon = if ns == 0 || duration_ns == 0 { + 0 + } else { + ns.saturating_add(duration_ns) + }; + let total_ms = horizon as f64 / 1e6; + let preceding = if horizon == 0 { 0 } else { duration_ns }; + let mut preparing = [(0usize, 0.0); REQUEST_LANES]; + let mut ready = preparing; + let mut finishing = preparing; + let (mut p, mut r, mut f) = (0, 0, 0); + for (slot, entry) in self.slots.iter().enumerate() { + let Some(request) = entry.request.as_ref() else { + continue; + }; + let offered = mask & (1 << slot) != 0; + if offered && terminal_cleanup(request) { + finishing[f] = (slot, values[slot].finish(first_ms, total_ms)); + f += 1; + continue; + } + let promoted_kind = offered + .then(|| self.following_kind(request, kind)) + .flatten(); + let ready_kind = self + .eligible(request) + .then(|| self.request_kind(request)) + .flatten(); + let promoted = if promoted_kind == Some(decode) { + true + } else if ready_kind == Some(decode) { + false + } else { + continue; + }; + let offer = ( + slot, + self.cached_lane_value_within( + request, + decode, + width, + preceding, + horizon, + values[slot], + curves, + ), + ); + if promoted { + preparing[p] = offer; + p += 1; + } else { + ready[r] = offer; + r += 1; + } + } + let preparing_prompt = usize::from(prompt.is_some_and(|(_, _, pr)| pr)); + let Some((mut selected, _, mut value)) = + best_two_stage_cohort::( + &preparing[..p], + &ready[..r], + &finishing[..f], + capacity - preparing_prompt, + batch - usize::from(prompt.is_some()), + 1 - preparing_prompt, + ) + else { + return; + }; + if let Some((slot, work, promoted)) = prompt { + let request = self.slots[slot].request.as_ref().unwrap(); + value += self.cached_lane_value_for_tokens_within( + request, + GraphKind::Prefill, + work, + preceding, + horizon, + values[slot], + curves, + ); + if promoted { + selected |= 1 << slot; + } + } + let rate = ValueRate::new(horizon, value, age_price); + if best.is_none_or(|(_, old)| rate.compare(old).is_gt()) { + best = Some((fill(selected), rate)); + } + }; + eval_mixed(pred.predict(0, 0), None); + for &(slot, work, start_pos, promoted) in &prompt_offers[..prompt_count] { + eval_mixed(pred.predict(work, start_pos), Some((slot, work, promoted))); + } + return; + } let ns = if following == GraphKind::Speculative { // The full B x W graph is already included in the packed round aggregate. self.costs.packed_round_duration(batch, width) + } else if following == GraphKind::Mixed { + Some(mixed_predictor.map_or(0, |p| p.predict(0, 0))) } else { self.costs.shape_duration(following, batch, width, prefill) }; @@ -1725,99 +1875,167 @@ impl RequestScheduler { GraphKind::Speculative }; for &(batch, width, prefill) in &self.mixed_catalog { - let Some(duration_ns) = - self.costs - .shape_duration(GraphKind::Mixed, batch, width, prefill) - else { + let Some(predictor) = self.costs.mixed_entry(batch, width, prefill) else { continue; }; - let mut decoders = [(0usize, 0.0); REQUEST_LANES]; - let mut count = 0; - let mut prompt: Option<(usize, f64)> = None; + let decode_ns = predictor.map_or(0, |p| p.predict(0, 0)); + let prefill_unmeasured = predictor.is_none_or(|p| !p.has_positive_fill()); + let variable_cost = predictor.is_some_and(|p| !p.is_constant()); + let mut decoder_slots = [0usize; REQUEST_LANES]; + let mut decoder_count = 0usize; + let mut prefill_slots = [(0usize, 0usize, 0u64); REQUEST_LANES]; + let mut prefill_count = 0usize; for (slot, entry) in self.slots.iter().enumerate() { let Some(r) = entry.request.as_ref().filter(|r| self.eligible(r)) else { continue; }; - let kind = self.request_kind(r); - match kind { - Some(GraphKind::Prefill) - if !r.deferred_prefill && self.prefill_work(r, prefill) > 0 => - { - if duration_ns == 0 && self.mixed_catalog.iter().any(|&(b, w, smaller)| { - b == batch && w == width && smaller < prefill - && self.prefill_work(r, smaller) == self.prefill_work(r, prefill) - }) { + match self.request_kind(r) { + Some(GraphKind::Prefill) if !r.deferred_prefill => { + let work = self.prefill_work(r, prefill); + if work == 0 { continue; } - let value = self.prefill_lane_value( - r, - GraphKind::Prefill, - self.prefill_work(r, prefill), - values[slot], - ); - if prompt.is_none_or(|(_, best)| value > best) { - prompt = Some((slot, value)); + if prefill_unmeasured + && self.mixed_catalog.iter().any(|&(b, w, smaller)| { + b == batch + && w == width + && smaller < prefill + && self.prefill_work(r, smaller) == work + }) + { + continue; } + prefill_slots[prefill_count] = (slot, work, r.scheduled_consumed); + prefill_count += 1; } Some(kind) if kind == decode => { - decoders[count] = ( - slot, - if optimistic { - let tokens = self.speculative_tokens(r, width); - values[slot].decode( - self.cached_expected_tokens(r, tokens, true, curves), - duration_ns as f64 / 1e6, - ) - } else { - self.cached_lane_value( - r, - decode, - width, - duration_ns, - values[slot], - curves, - ) - }, - ); - count += 1; + decoder_slots[decoder_count] = slot; + decoder_count += 1; } _ => {} } } - for prompt in std::iter::once(None).chain(prompt.map(Some)) { - if prompt.is_none() && duration_ns == 0 - && self.mixed_catalog.iter().any(|&(b, w, smaller)| { - b == batch && w == width && smaller < prefill - }) - { - continue; + let mut score_decoders = |duration_ns: u64, limit: usize| -> (u64, f64) { + if decoder_count == 0 || limit == 0 { + return (0, 0.0); } - let mut mask = best_cohort::( - &decoders[..count], - batch - usize::from(prompt.is_some()), - ); - let mut expected = decoders[..count] + let mut decoders = [(0usize, 0.0); REQUEST_LANES]; + for (idx, &slot) in decoder_slots[..decoder_count].iter().enumerate() { + let r = self.slots[slot].request.as_ref().unwrap(); + let val = if optimistic { + let tokens = self.speculative_tokens(r, width); + values[slot].decode( + self.cached_expected_tokens(r, tokens, true, curves), + duration_ns as f64 / 1e6, + ) + } else { + self.cached_lane_value(r, decode, width, duration_ns, values[slot], curves) + }; + decoders[idx] = (slot, val); + } + let mask = best_cohort::(&decoders[..decoder_count], limit); + let expected = decoders[..decoder_count] .iter() .filter(|(s, _)| mask & (1 << s) != 0) - .map(|(_, v)| v) + .map(|(_, v)| *v) .sum::(); - if let Some((slot, value)) = prompt { + (mask, expected) + }; + let skip_unmeasured_decode = decode_ns == 0 + && self + .mixed_catalog + .iter() + .any(|&(b, w, smaller)| b == batch && w == width && smaller < prefill); + if !skip_unmeasured_decode { + let (decode_mask, decode_expected) = score_decoders(decode_ns, batch); + if decode_mask != 0 { + output.push(Candidate { + host_lengths: None, + draft_tokens: 0, + packed_token_capacity: 0, + kind: GraphKind::Mixed, + mask: decode_mask, + batch, + capacity: width, + prefill_capacity: prefill, + prefill_slot: None, + work: 0, + duration_ns: decode_ns, + rate: ValueRate::new(decode_ns, decode_expected, age_price), + feedback: true, + }); + } + } + if prefill_count == 0 { + continue; + } + let best_prompt = if variable_cost { + let pred = predictor.unwrap(); + let mut best: Option<(usize, u64, u64, ValueRate)> = None; + for &(slot, work, start_pos) in &prefill_slots[..prefill_count] { + let slot_ns = pred.predict(work, start_pos); + let r = self.slots[slot].request.as_ref().unwrap(); + let prompt_value = self.prefill_lane_value( + r, + GraphKind::Prefill, + work, + values[slot], + ); + let (mut mask, mut expected) = score_decoders(slot_ns, batch - 1); mask |= 1 << slot; - expected += value; + expected += prompt_value; + let rate = ValueRate::new(slot_ns, expected, age_price); + if best.is_none_or(|(best_slot, _, _, best_rate)| { + match rate.compare(best_rate) { + std::cmp::Ordering::Greater => true, + std::cmp::Ordering::Equal => slot < best_slot, + std::cmp::Ordering::Less => false, + } + }) { + best = Some((slot, mask, slot_ns, rate)); + } } - if mask == 0 { - continue; + best + } else { + let mut best_value: Option<(usize, f64)> = None; + for &(slot, work, _) in &prefill_slots[..prefill_count] { + let r = self.slots[slot].request.as_ref().unwrap(); + let value = self.prefill_lane_value( + r, + GraphKind::Prefill, + work, + values[slot], + ); + if best_value.is_none_or(|(_, best)| value > best) { + best_value = Some((slot, value)); + } } - output.push(Candidate { host_lengths: None, draft_tokens: 0, packed_token_capacity: 0, + best_value.map(|(slot, value)| { + let (mut mask, mut expected) = score_decoders(decode_ns, batch - 1); + mask |= 1 << slot; + expected += value; + ( + slot, + mask, + decode_ns, + ValueRate::new(decode_ns, expected, age_price), + ) + }) + }; + if let Some((slot, mask, duration_ns, rate)) = best_prompt { + output.push(Candidate { + host_lengths: None, + draft_tokens: 0, + packed_token_capacity: 0, kind: GraphKind::Mixed, mask, batch, capacity: width, prefill_capacity: prefill, - prefill_slot: prompt.map(|(s, _)| s), + prefill_slot: Some(slot), work: 0, duration_ns, - rate: ValueRate::new(duration_ns, expected, age_price), + rate, feedback: true, }); } @@ -1987,7 +2205,13 @@ impl RequestScheduler { (kind, capacity, 0, work) }; let duration_ns = if mixed { - self.costs.shape_duration(kind, candidate.batch, capacity, prefill)? + self.costs.mixed_duration( + candidate.batch, + capacity, + prefill, + work, + request.scheduled_consumed, + )? } else { self.costs.prefill_duration(kind, capacity, work, request.scheduled_consumed)? }; diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index fe72dae4c..d9b93b5ce 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -9521,6 +9521,116 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() } } +#[test] +fn mixed_candidates_price_fill_and_kv_context_per_prompt_and_decode_only() { + let mut s = mixed_engine(4, false, &[(4, 1, 2048, 2 * MS)]); + throughput_only(&mut s); + + // Train Mixed(4, 1, 2048) with distinct decode-only (1 ms), full shallow (2 ms), + // and deep-context full (6 ms at 32k) observations so Mixed beats separate graphs. + let observe_mixed = |s: &mut RequestScheduler, prompt: Option<(usize, u64)>, ns: u64| { + let step = ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Mixed, + batch_capacity: 4, + token_capacity: 1, + packed_token_capacity: 0, + mixed: Some(MixedStep { + prefill_capacity: 2048, + prefill_row: prompt.map(|_| 0), + speculative: false, + }), + lanes: match prompt { + Some((tokens, start_position)) => vec![ + ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position, + tokens, + }, + ScheduledLane { + request: RequestHandle { slot: 1, generation: 1 }, + start_position: 128, + tokens: 1, + }, + ], + None => vec![ScheduledLane { + request: RequestHandle { slot: 1, generation: 1 }, + start_position: 128, + tokens: 1, + }], + }, + requires_feedback: true, + }; + s.costs.observe(&step, gpu_time(ns)); + }; + s.advance_to(s.now_ns + s.policy.estimate_ttl_ns + 1).unwrap(); + observe_mixed(&mut s, None, MS); + observe_mixed(&mut s, Some((2048, 0)), 2 * MS); + observe_mixed(&mut s, Some((2048, 32_768)), 6 * MS); + + // Two prefillers with identical 2048-token chunk work: `deep` is at 32k KV context (6 ms) + // while `shallow` is at 0 KV context (2 ms), paired with an active decoder. + let d = add(&mut s, 1, 64, 1024); + ready(&mut s, &[d]); + let deep = add(&mut s, 2, 40_000, 128); + let shallow = add(&mut s, 3, 4096, 128); + initialize(&mut s, deep); + initialize(&mut s, shallow); + s.request_mut(deep).unwrap().consumed_tokens = 32_768; + s.request_mut(deep).unwrap().scheduled_consumed = 32_768; + + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::Mixed); + let prefill_row = plan.mixed.as_ref().unwrap().prefill_row.unwrap(); + // Shallow prompt (2 ms) yields strictly higher value-rate than deep prompt (6 ms). + assert_eq!(plan.lanes[prefill_row].request, shallow); + let est = plan.estimated_duration_ns(); + assert!((est as i64 - (2 * MS) as i64).abs() < 100_000, "est={est}"); + assert_eq!(s.estimated_duration_ns(&plan), Some(est)); +} + +#[test] +fn zero_fill_only_mixed_model_does_not_inflate_prefill_service_rates() { + let mut s = mixed_engine(4, false, &[(4, 1, 2048, 700 * MS)]); + throughput_only(&mut s); + + // Expire startup seed and record only a fast zero-fill (decode-only) Mixed observation (1 ms), + // which would otherwise report 2048 tok/ms (~33x above mixed_engine's ~62 tok/ms prefill rate). + let prompt = add(&mut s, 1, 4096, 128); + initialize(&mut s, prompt); + let baseline_rate = s.service_rates(s.request(prompt).unwrap()).0.unwrap(); + assert!(baseline_rate < 100.0, "baseline_rate={baseline_rate}"); + + s.advance_to(s.now_ns + s.policy.estimate_ttl_ns + 1).unwrap(); + let decode_only_step = ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Mixed, + batch_capacity: 4, + token_capacity: 1, + packed_token_capacity: 0, + mixed: Some(MixedStep { + prefill_capacity: 2048, + prefill_row: None, + speculative: false, + }), + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position: 128, + tokens: 1, + }], + requires_feedback: true, + }; + s.costs.observe(&decode_only_step, gpu_time(MS)); + + assert_eq!(s.costs.mixed_duration(4, 1, 2048, 0, 0), Some(MS)); + assert_eq!(s.costs.mixed_duration(4, 1, 2048, 2048, 0), Some(0)); + let after_rate = s.service_rates(s.request(prompt).unwrap()).0.unwrap(); + assert!( + (after_rate - baseline_rate).abs() < 1e-6, + "zero_fill-only Mixed model must not inflate prefill service_rates: before={baseline_rate}, after={after_rate}" + ); +} + #[test] fn waiting_init_prices_each_decoding_lane_curve_once_per_candidate_pass() { let shapes = [ diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index c923c5f8e..06212572a 100644 --- a/helios/src/scheduler/service.rs +++ b/helios/src/scheduler/service.rs @@ -232,7 +232,7 @@ impl RequestScheduler { for &(batch, width, prefill) in &self.mixed_catalog { if let Some(ns) = self .costs - .shape_duration(GraphKind::Mixed, batch, width, prefill) + .mixed_duration(batch, width, prefill, 0, 0) .filter(|ns| *ns > 0) { consider(&mut best, ns, batch, mask); @@ -351,14 +351,13 @@ impl RequestScheduler { if !policy::terminal_cleanup(request) { let mut mixed_curve = None; for &(batch, width, capacity) in &self.mixed_catalog { - let Some(ns) = self + let Some(predictor) = self .costs - .shape_duration(GraphKind::Mixed, batch, width, capacity) - .filter(|ns| *ns > 0) + .mixed_entry(batch, width, capacity) + .flatten() else { continue; }; - let per_ms = 1e6 / ns as f64; if prefill && !request.prompt_logprobs && !request.deferred_prefill @@ -371,15 +370,21 @@ impl RequestScheduler { let start = request.consumed_tokens as usize; let work = self.prefill_work_from(request, start, capacity, cut); if work > 0 { - let first = start + work == request.prompt_tokens; - token_rate = token_rate.max((work as f64 + f64::from(first)) * per_ms); + let ns = predictor.predict(work, request.consumed_tokens); + if ns > 0 { + let per_ms = 1e6 / ns as f64; + let first = start + work == request.prompt_tokens; + token_rate = token_rate.max((work as f64 + f64::from(first)) * per_ms); + } } } else if !prefill && request.generated_tokens > 0 && request.generated_tokens < request.max_new_tokens { + let ns = predictor.predict(0, 0); let tokens = self.speculative_tokens(request, width); - if tokens > 0 { + if tokens > 0 && ns > 0 { + let per_ms = 1e6 / ns as f64; let expected = if self.speculative_widths.is_empty() { 1.0 } else { diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index 7fe05213d..aaef2d563 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -4255,3 +4255,81 @@ fn scheduler_enumerates_arbitrary_prepared_batch_capacities_and_preserves_legacy } } } + +#[test] +fn set_grammar_constrained_and_checkpoint_park_guards_reject_invalid_states_atomically() { + let mut s = scheduler(2, 64, 16); + let h = s.admit(spec(64, 16)).unwrap(); + + // Init -> Prefill -> boundary Snapshot. + let init = s.plan().unwrap(); + assert_eq!(init.kind, GraphKind::Init); + s.commit(&init, Fence(1)).unwrap(); + s.complete(Fence(1), &records(h, 1, 0, 0, -1, 1), Default::default()) + .unwrap(); + + let prefill = s.plan().unwrap(); + assert_eq!(prefill.kind, GraphKind::Prefill); + s.commit(&prefill, Fence(2)).unwrap(); + // Rejects toggling while GPU work is pending without mutating scheduler state. + assert!(s.set_grammar_constrained(h, true).is_err()); + assert!(!s.request(h).unwrap().grammar_constrained); + assert_eq!(s.request(h).unwrap().phase, RequestPhase::Prefill); + assert!(s.finish_for_park(h).is_err()); + + s.complete(Fence(2), &records(h, 2, 64, 1, 7, 1), Default::default()) + .unwrap(); + // Mid-request prompt boundary Snapshot allows set_grammar_constrained when pending == 0. + assert_eq!(s.request(h).unwrap().phase, RequestPhase::Snapshot); + assert!(s.request(h).unwrap().boundary_capture.is_some()); + s.set_grammar_constrained(h, true).unwrap(); + assert!(s.request(h).unwrap().grammar_constrained); + + let snap = s.plan().unwrap(); + assert_eq!(snap.kind, GraphKind::Snapshot); + s.commit(&snap, Fence(3)).unwrap(); + s.complete(Fence(3), &records(h, 3, 64, 1, -1, 1), Default::default()) + .unwrap(); + assert_eq!(s.request(h).unwrap().phase, RequestPhase::Decode); + + // Toggling grammar_constrained changes feedback requirements so stale plans are rejected. + let stale_plan = s.plan().unwrap(); + assert_eq!(stale_plan.kind, GraphKind::Decode); + assert!(stale_plan.requires_feedback); + s.set_grammar_constrained(h, false).unwrap(); + assert!(!s.request(h).unwrap().grammar_constrained); + assert!(s.commit(&stale_plan, Fence(4)).is_err()); + + // pause_for_park requires pending > 0 and rejects pending == 0 without mutating state. + assert!(s.pause_for_park(h).is_err()); + assert!(!s.request(h).unwrap().paused_for_park); + + // Commit a non-feedback decode frame and pause_for_park while pending == 1. + let decode = s.plan().unwrap(); + assert_eq!(decode.kind, GraphKind::Decode); + assert!(!decode.requires_feedback); + s.commit(&decode, Fence(4)).unwrap(); + assert_eq!(s.request(h).unwrap().pending(), 1); + s.pause_for_park(h).unwrap(); + // Paused slot must not schedule a second pipelined frame while draining. + assert!(s.plan().is_none()); + + // Complete draining frame -> finish_for_park arms a terminal Snapshot. + s.complete(Fence(4), &records(h, 4, 65, 2, 8, 1), Default::default()) + .unwrap(); + assert_eq!(s.request(h).unwrap().pending(), 0); + s.finish_for_park(h).unwrap(); + assert_eq!(s.request(h).unwrap().phase, RequestPhase::Snapshot); + assert!(s.request(h).unwrap().terminal_snapshot.is_some()); + // Terminal Snapshot rejects set_grammar_constrained without mutating flag. + assert!(s.set_grammar_constrained(h, true).is_err()); + assert!(!s.request(h).unwrap().grammar_constrained); + + let term_snap = s.plan().unwrap(); + assert_eq!(term_snap.kind, GraphKind::Snapshot); + s.commit(&term_snap, Fence(5)).unwrap(); + s.complete(Fence(5), &records(h, 5, 65, 2, -1, 1), Default::default()) + .unwrap(); + assert_eq!(s.request(h).unwrap().phase, RequestPhase::Finishing); + assert!(s.finish(h).unwrap().is_some()); +} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 51a0f2616..d58403da3 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -502,14 +502,17 @@ impl Incoming { }) } - fn spec(&self) -> RequestSpec { + fn spec(&self, speculative: bool) -> RequestSpec { RequestSpec { message_boundaries: self.prompt.message_boundaries.clone(), prompt: self.prompt.tokens.clone(), conditioning: self.prompt.conditioning.clone(), max_new_tokens: self.prompt.max_new_tokens, + // Non-speculative models gain no multi-token verification from unmasked + // reasoning; disabling two-frame pipelining avoids in-flight overshoot at + // `` and lets the grammar mask toggle in place without parking. grammar_constrained: self.prompt.grammar.is_some() - && !self.speculative_grammar_reasoning(), + && (!speculative || !self.speculative_grammar_reasoning()), prompt_logprobs: self.prompt_scored < self.prompt_score_end, growable_output: true, preserve_message_anchor: self.prompt.preserve_message_anchor, @@ -681,6 +684,72 @@ impl Incoming { } } +struct GrammarPark { + exact_len: usize, + emitted: u32, + remaining: u32, + speculative_reasoning: bool, + drop_reasoning: bool, +} + +enum GrammarTransitionAction { + ToggleInPlace, + CheckpointPark { pause_for_drain: bool }, + Rollback, +} + +fn decide_grammar_transition( + live: &crate::scheduler::LiveRequest, + skipped: u32, + extra: u32, + can_toggle_in_place: bool, +) -> GrammarTransitionAction { + let can_toggle_live = skipped == 0 + && live.pending() == 0 + && extra == 0 + && live.error_code.is_none() + && can_toggle_in_place + && !matches!(live.phase, RequestPhase::Inbound | RequestPhase::Finishing) + && !(live.phase == RequestPhase::Snapshot && live.terminal_snapshot.is_some()); + if can_toggle_live { + GrammarTransitionAction::ToggleInPlace + } else if skipped == 0 && live.error_code.is_none() && !live.deferred_prefill() { + GrammarTransitionAction::CheckpointPark { + pause_for_drain: live.pending() > 0, + } + } else { + GrammarTransitionAction::Rollback + } +} + +fn sampling_graphs_bind_grammar_enabled(config: &ModelConfig) -> bool { + use crate::model::contract::{GraphOperation, ValueSource}; + + let mut saw_sampling = false; + for graph in &config.contract.graphs { + if matches!( + graph.kind, + GraphOperation::Prefill + | GraphOperation::TerminalPrefill + | GraphOperation::ScoredPrefill + | GraphOperation::Decode + | GraphOperation::Speculative + | GraphOperation::Mixed + | GraphOperation::Resume + ) { + saw_sampling = true; + if !graph + .inputs + .iter() + .any(|binding| binding.source == ValueSource::GrammarEnabled) + { + return false; + } + } + } + saw_sampling +} + struct Active<'a> { request: RequestHandle, incoming: Incoming, @@ -695,6 +764,7 @@ struct Active<'a> { held_logprobs: VecDeque>, // The client decoder runs on another thread; the worker needs reasoning state at the cut. reasoning: Option>, + pending_grammar_park: Option, } /// Output accounting retained across admissions. @@ -1469,6 +1539,7 @@ struct Worker<'a> { image_preparation: Option, preparing_image: Option, image_preparation_cursor: usize, + can_toggle_grammar_in_place: bool, } fn close_store(store: Option>, shutdown: &mut Shutdown) { @@ -1527,6 +1598,8 @@ impl<'a> Worker<'a> { image_preparation: None, preparing_image: None, image_preparation_cursor: 0, + can_toggle_grammar_in_place: config.speculative_widths.is_empty() + || sampling_graphs_bind_grammar_enabled(config), } } @@ -1745,9 +1818,13 @@ impl<'a> Worker<'a> { { let active = self.clear_active_slot(slot).unwrap(); let live = self.scheduler.request(active.request)?; + let generated = active + .pending_grammar_park + .as_ref() + .map_or(live.generated_tokens, |park| park.emitted); active.incoming.finish_cancelled(Carried { prompt_tokens: Some(active.carried.prompt_tokens.unwrap_or(live.prompt_tokens)), - generated_tokens: active.carried.generated_tokens + live.generated_tokens, + generated_tokens: active.carried.generated_tokens + generated, reused_prompt_tokens: Some(active.carried.reused_prompt_tokens.unwrap_or(live.reused_prompt_tokens())), ..active.carried }); @@ -1823,8 +1900,15 @@ impl<'a> Worker<'a> { matches!(ticket.state(), flare_selene::pool::LookupState::Pending) }); let checkpoint_accounting = parked.as_ref().map(|parked| parked.checkpoint_accounting.clone()); - let spec = incoming.spec(); - let grammar_constrained = spec.grammar_constrained; + let speculative = !self.config.speculative_widths.is_empty(); + let spec = incoming.spec(speculative); + let unmasked_reasoning = incoming.speculative_grammar_reasoning(); + let grammar_mask_active = incoming.prompt.grammar.is_some() && !unmasked_reasoning; + // Non-speculative cores do not gate verification width on `grammar_enabled`, so + // initializing `grammar_enabled = 1` with a cached all-ones mask allows in-place + // mask toggling at `` and reasoning re-entry without re-running `Restore`. + let device_grammar_enabled = + incoming.prompt.grammar.is_some() && (!unmasked_reasoning || !speculative); self.scheduler .advance_to(super::observation::monotonic_ns())?; let admission = if let Some(store) = @@ -1933,7 +2017,8 @@ impl<'a> Worker<'a> { &incoming.prompt, initial_prompt_tokens, incoming.prompt.ignore_eos, - grammar_constrained, + grammar_mask_active, + device_grammar_enabled, ) { Ok(admission) => admission, Err(error) => { @@ -2033,6 +2118,7 @@ impl<'a> Worker<'a> { checkpoint_accounting: self.scheduler.request(handle)?.checkpoint_accounting(), held_logprobs: parked.held_logprobs, reasoning: parked.reasoning, + pending_grammar_park: None, }); progress = true; } @@ -2220,24 +2306,19 @@ impl<'a> Worker<'a> { for token in &generated { burst_counts[token.request.slot as usize] += 1; } - struct GrammarTransition { - slot: usize, - handle: RequestHandle, - exact_len: usize, - emitted: u32, - remaining: u32, - speculative_reasoning: bool, - drop_reasoning: bool, - } let mut stopped = Vec::new(); - let mut transitions: Vec = Vec::new(); + let mut transitions: Vec<(usize, RequestHandle, GrammarPark)> = Vec::new(); + let mut checkpoint_parks: Vec<(usize, RequestHandle, GrammarPark, bool)> = Vec::new(); + let speculative = !self.config.speculative_widths.is_empty(); + let can_toggle_in_place = self.can_toggle_grammar_in_place; let mut positions = [0usize; crate::execution::REQUEST_LANES]; for token in generated { let slot = token.request.slot as usize; let position = positions[slot]; positions[slot] += 1; if stopped.contains(&token.request) - || transitions.iter().any(|t| t.handle == token.request) + || transitions.iter().any(|(_, h, _)| *h == token.request) + || checkpoint_parks.iter().any(|(_, h, _, _)| *h == token.request) { continue; } @@ -2245,6 +2326,9 @@ impl<'a> Worker<'a> { .as_mut() .filter(|a| a.request == token.request) { + if request.pending_grammar_park.is_some() { + continue; + } let speculative_grammar = request.incoming.speculative_grammar_reasoning(); if speculative_grammar { let allowed = match request @@ -2293,15 +2377,17 @@ impl<'a> Worker<'a> { let remaining = request.incoming.prompt.max_new_tokens.saturating_sub(emitted); let exact_len = live.prompt_tokens + emitted as usize; if remaining > 0 && exact_len < self.config.limits.max_sequence_tokens { - transitions.push(GrammarTransition { + transitions.push(( slot, - handle: token.request, - exact_len, - emitted, - remaining, - speculative_reasoning: false, - drop_reasoning: false, - }); + token.request, + GrammarPark { + exact_len, + emitted, + remaining, + speculative_reasoning: false, + drop_reasoning: false, + }, + )); } else { request.incoming.fail(Error::execution( ExecutionError::Completion, @@ -2433,7 +2519,7 @@ impl<'a> Worker<'a> { .incoming .prompt .reasoning_cut - .take() + .as_ref() .map_or(0, |cut| cut.after); let remaining = request .incoming @@ -2460,16 +2546,62 @@ impl<'a> Worker<'a> { stopped.push(token.request); continue; } + request.incoming.prompt.reasoning_cut = None; let drop_reasoning = !request.incoming.allow_reasoning_reentry(); - transitions.push(GrammarTransition { - slot, - handle: token.request, - exact_len, - emitted, - remaining, - speculative_reasoning: false, - drop_reasoning, - }); + match decide_grammar_transition( + live, + skipped, + extra, + can_toggle_in_place, + ) { + GrammarTransitionAction::ToggleInPlace => { + let mask = request + .incoming + .prompt + .grammar + .as_ref() + .unwrap() + .mask() + .to_vec(); + self.scheduler + .set_grammar_constrained(token.request, true)?; + request.incoming.grammar_reasoning_mode = Some(false); + if drop_reasoning { + request.reasoning = None; + } + self.admissions[slot] + .as_mut() + .unwrap() + .set_grammar(crate::model::AdmissionGrammar::Masked(mask)); + } + GrammarTransitionAction::CheckpointPark { pause_for_drain } => { + checkpoint_parks.push(( + slot, + token.request, + GrammarPark { + exact_len, + emitted, + remaining, + speculative_reasoning: false, + drop_reasoning, + }, + pause_for_drain, + )); + } + GrammarTransitionAction::Rollback => { + transitions.push(( + slot, + token.request, + GrammarPark { + exact_len, + emitted, + remaining, + speculative_reasoning: false, + drop_reasoning, + }, + )); + } + } } } } else if !speculative_grammar @@ -2493,29 +2625,92 @@ impl<'a> Worker<'a> { && remaining > 1 && exact_len + 1 < self.config.limits.max_sequence_tokens { - transitions.push(GrammarTransition { - slot, - handle: token.request, - exact_len, - emitted, - remaining, - speculative_reasoning: true, - drop_reasoning: false, - }); + match decide_grammar_transition(live, skipped, 0, can_toggle_in_place) { + GrammarTransitionAction::ToggleInPlace => { + if speculative { + self.scheduler + .set_grammar_constrained(token.request, false)?; + self.admissions[slot].as_mut().unwrap().set_grammar( + crate::model::AdmissionGrammar::Disabled, + ); + } else { + self.admissions[slot].as_mut().unwrap().set_grammar( + crate::model::AdmissionGrammar::UnmaskedEnabled, + ); + } + request.incoming.grammar_reasoning_mode = Some(true); + } + GrammarTransitionAction::CheckpointPark { pause_for_drain } => { + checkpoint_parks.push(( + slot, + token.request, + GrammarPark { + exact_len, + emitted, + remaining, + speculative_reasoning: true, + drop_reasoning: false, + }, + pause_for_drain, + )); + } + GrammarTransitionAction::Rollback => { + transitions.push(( + slot, + token.request, + GrammarPark { + exact_len, + emitted, + remaining, + speculative_reasoning: true, + drop_reasoning: false, + }, + )); + } + } } } } } self.retire(&stopped)?; - for transition in transitions { - self.park_grammar_transition( - transition.slot, - transition.exact_len, - transition.emitted, - transition.remaining, - transition.speculative_reasoning, - transition.drop_reasoning, - )?; + for lane in &measured_step.lanes { + let slot = lane.request.slot as usize; + let Some(active) = self.active[slot].as_ref() else { + continue; + }; + if active.request != lane.request || active.pending_grammar_park.is_none() { + continue; + } + let live = self.scheduler.request(lane.request)?; + if !live.paused_for_park() || live.pending() != 0 { + continue; + } + let exact_len = active.pending_grammar_park.as_ref().unwrap().exact_len; + if live.error_code.is_some() { + self.active[slot].as_mut().unwrap().pending_grammar_park = None; + self.scheduler.finish_for_park(lane.request)?; + } else if live.consumed_tokens <= exact_len as u64 && !live.deferred_prefill() { + self.scheduler.finish_for_park(lane.request)?; + } else { + let park = self.active[slot] + .as_mut() + .unwrap() + .pending_grammar_park + .take() + .unwrap(); + transitions.push((slot, lane.request, park)); + } + } + for (slot, handle, park, pause_for_drain) in checkpoint_parks { + if pause_for_drain { + self.scheduler.pause_for_park(handle)?; + } else { + self.scheduler.finish_for_park(handle)?; + } + self.active[slot].as_mut().unwrap().pending_grammar_park = Some(park); + } + for (slot, _, park) in transitions { + self.park_grammar_transition(slot, &park)?; } Ok(()) } @@ -2539,6 +2734,36 @@ impl<'a> Worker<'a> { progress = true; } } + if let Some(request) = &mut self.active[slot] { + let live = self.scheduler.request(request.request)?; + if live.phase == RequestPhase::Finishing + && live.last_use() <= self.scheduler.completed() + && !live.paused_for_park() + && let Some(park) = request.pending_grammar_park.take() + { + if let Some(error) = live.error_code { + let handle = request.request; + request + .incoming + .fail(ExecutionError::Device { code: error }.into()); + self.scheduler.finish(handle)?; + self.clear_active_slot(slot); + } else { + let tokens = live.tokens()[..park.exact_len].to_vec(); + self.park_with_tokens( + slot, + tokens, + park.emitted, + park.remaining, + true, + Some(park.speculative_reasoning), + park.drop_reasoning, + )?; + } + progress = true; + continue; + } + } if self.park_if_preempted(slot)? { progress = true; continue; @@ -2740,9 +2965,13 @@ impl<'a> Worker<'a> { /// becomes the prompt, its output limit drops by what it generated, and its output /// state and counters carry over to the next admission. fn park_if_preempted(&mut self, slot: usize) -> Result { - let Some(handle) = self.active[slot].as_ref().map(|active| active.request) else { + let Some(active) = self.active[slot].as_ref() else { return Ok(false); }; + if active.pending_grammar_park.is_some() { + return Ok(false); + } + let handle = active.request; let live = self.scheduler.request(handle)?; if !live.preempted() || live.phase != RequestPhase::Finishing @@ -2774,26 +3003,18 @@ impl<'a> Worker<'a> { self.park_with_tokens(slot, tokens, generated, remaining, true, None, false) } - fn park_grammar_transition( - &mut self, - slot: usize, - exact_len: usize, - emitted: u32, - remaining: u32, - speculative_reasoning: bool, - drop_reasoning: bool, - ) -> Result<()> { + fn park_grammar_transition(&mut self, slot: usize, park: &GrammarPark) -> Result<()> { let handle = self.active[slot].as_ref().unwrap().request; let live = self.scheduler.request(handle)?; - let tokens = live.tokens()[..exact_len].to_vec(); + let tokens = live.tokens()[..park.exact_len].to_vec(); self.park_with_tokens( slot, tokens, - emitted, - remaining, + park.emitted, + park.remaining, false, - Some(speculative_reasoning), - drop_reasoning, + Some(park.speculative_reasoning), + park.drop_reasoning, ) } @@ -3491,7 +3712,7 @@ fn begin_pool_lookup( } } else { let Ok(plan) = scheduler.plan_admission_with_core_parameters( - &incoming.spec(), + &incoming.spec(false), &incoming.prompt.core_parameters, ) else { return false; @@ -3865,7 +4086,7 @@ mod tests { vision_token_indices: vec![-1], ..Default::default() }, - grammar_mask: None, + grammar: crate::model::AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }) @@ -4426,6 +4647,7 @@ mod tests { carried: Carried::default(), checkpoint_accounting: Default::default(), reasoning: None, + pending_grammar_park: None, }; let mut active: [Option>; 4] = std::array::from_fn(|_| None); active[failed.slot as usize] = Some(make_active(failed, incoming)); @@ -4443,7 +4665,7 @@ mod tests { vision_token_indices: vec![-1], ..Default::default() }, - grammar_mask: None, + grammar: crate::model::AdmissionGrammar::Disabled, ignore_eos: false, prompt_logprobs: false, }); @@ -4621,6 +4843,7 @@ mod tests { carried: Carried::default(), checkpoint_accounting: Default::default(), reasoning: None, + pending_grammar_park: None, }; request.incoming.observe_token(0, 0); assert!(!request.emit_output(0, &[248046], None).unwrap()); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 8a490875d..9a7599b38 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -7928,7 +7928,7 @@ fn speculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_ov let handle = worker.active[0].as_ref().unwrap().request; let slot = handle.slot as usize; assert!(!worker.scheduler.request(handle).unwrap().grammar_constrained); - assert!(worker.admissions[slot].as_ref().unwrap().grammar_mask.is_none()); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.mask().is_none()); advance(&mut worker, GraphKind::Init, 1, None); advance(&mut worker, GraphKind::Prefill, 2, Some(0)); // "a" (reasoning) @@ -7993,7 +7993,7 @@ fn speculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_ov let next_handle = worker.active.iter().flatten().next().unwrap().request; let next_slot = next_handle.slot as usize; assert!(worker.scheduler.request(next_handle).unwrap().grammar_constrained); - assert!(worker.admissions[next_slot].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[next_slot].as_ref().unwrap().grammar.mask().is_some()); advance(&mut worker, GraphKind::Restore, 6, None); advance(&mut worker, GraphKind::Prefill, 7, Some(2)); // "c" @@ -8133,7 +8133,7 @@ fn speculative_grammar_reasoning_rolls_back_forbidden_token_including_premature_ let next_handle = worker.active.iter().flatten().next().unwrap().request; let next_slot = next_handle.slot as usize; assert!(worker.scheduler.request(next_handle).unwrap().grammar_constrained); - assert!(worker.admissions[next_slot].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[next_slot].as_ref().unwrap().grammar.mask().is_some()); let mut seq = 10; if first_token_forbidden { @@ -8317,7 +8317,7 @@ fn speculative_grammar_reasoning_integrates_with_thinking_budget_and_logprobs() let next_handle = worker.active.iter().flatten().next().unwrap().request; let next_slot = next_handle.slot as usize; assert!(worker.scheduler.request(next_handle).unwrap().grammar_constrained); - assert!(worker.admissions[next_slot].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[next_slot].as_ref().unwrap().grammar.mask().is_some()); let mut logprob_tokens = Vec::new(); let mut plain_tokens = Vec::new(); @@ -8362,7 +8362,7 @@ fn speculative_grammar_reasoning_preserves_mode_on_preemption_and_stays_constrai assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let handle = worker.active[0].as_ref().unwrap().request; assert!(worker.scheduler.request(handle).unwrap().grammar_constrained); - assert!(worker.admissions[0].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[0].as_ref().unwrap().grammar.mask().is_some()); advance(&mut worker, GraphKind::Init, 1, None); advance(&mut worker, GraphKind::Prefill, 2, Some(2)); advance(&mut worker, GraphKind::Snapshot, 3, None); @@ -8416,7 +8416,7 @@ fn speculative_grammar_reasoning_preserves_mode_on_preemption_and_stays_constrai let next_handle = worker.active.iter().flatten().next().unwrap().request; let next_slot = next_handle.slot as usize; assert!(!worker.scheduler.request(next_handle).unwrap().grammar_constrained); - assert!(worker.admissions[next_slot].as_ref().unwrap().grammar_mask.is_none()); + assert!(worker.admissions[next_slot].as_ref().unwrap().grammar.mask().is_none()); } #[test] @@ -8517,25 +8517,28 @@ fn content_header_envelope_enters_speculative_reasoning_after_header_and_returns assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let h0 = worker.active[0].as_ref().unwrap().request; assert!(worker.scheduler.request(h0).unwrap().grammar_constrained); - assert!(worker.admissions[0].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[0].as_ref().unwrap().grammar.mask().is_some()); advance(&mut worker, GraphKind::Init, 1, None); - // Prefill emits `<|content_thinking|>`, opening reasoning and triggering transition. + // Prefill emits `<|content_thinking|>`, opening reasoning and triggering a checkpoint-preserving + // transition (Snapshot -> publish -> Restore) instead of discarding the prompt KV via cancel. advance(&mut worker, GraphKind::Prefill, 2, Some(think)); + advance(&mut worker, GraphKind::Snapshot, 3, None); + assert!(worker.publish().unwrap()); assert_eq!(worker.parked.len(), 1); - // Readmits in unconstrained speculative reasoning mode. + // Readmits in unconstrained speculative reasoning mode, restoring the cached prompt checkpoint. assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let h1 = worker.active.iter().flatten().next().unwrap().request; let s1 = h1.slot as usize; assert!(!worker.scheduler.request(h1).unwrap().grammar_constrained); - assert!(worker.admissions[s1].as_ref().unwrap().grammar_mask.is_none()); + assert!(worker.admissions[s1].as_ref().unwrap().grammar.mask().is_none()); - advance(&mut worker, GraphKind::Init, 3, None); - advance(&mut worker, GraphKind::Prefill, 4, Some(1)); // "b" - advance(&mut worker, GraphKind::Snapshot, 5, None); + advance(&mut worker, GraphKind::Restore, 4, None); + advance(&mut worker, GraphKind::Prefill, 5, Some(1)); // "b" + advance(&mut worker, GraphKind::Snapshot, 6, None); - let step = planned(&mut worker, GraphKind::Speculative, 6); + let step = planned(&mut worker, GraphKind::Speculative, 7); assert_eq!(step.lanes[0].tokens, 8); assert!(!step.requires_feedback); let live = worker.scheduler.request(h1).unwrap(); @@ -8543,7 +8546,7 @@ fn content_header_envelope_enters_speculative_reasoning_after_header_and_returns let frame = speculative_burst_frame( &worker, &step, - 6, + 7, s1, live.consumed_tokens as i64, live.generated_tokens as i64, @@ -8563,18 +8566,18 @@ fn content_header_envelope_enters_speculative_reasoning_after_header_and_returns let h2 = worker.active.iter().flatten().next().unwrap().request; let s2 = h2.slot as usize; assert!(worker.scheduler.request(h2).unwrap().grammar_constrained); - assert!(worker.admissions[s2].as_ref().unwrap().grammar_mask.is_some()); + assert!(worker.admissions[s2].as_ref().unwrap().grammar.mask().is_some()); - advance(&mut worker, GraphKind::Restore, 7, None); - advance(&mut worker, GraphKind::Prefill, 8, Some(model)); + advance(&mut worker, GraphKind::Restore, 8, None); + advance(&mut worker, GraphKind::Prefill, 9, Some(model)); if worker .scheduler .request(h2) .is_ok_and(|r| r.phase == RequestPhase::Snapshot) { - advance(&mut worker, GraphKind::Snapshot, 9, None); + advance(&mut worker, GraphKind::Snapshot, 10, None); } - let mut seq = 10; + let mut seq = 11; for &(token, done) in &[(text, false), (2u32, false), (end, false), (eos, true)] { let step = planned(&mut worker, GraphKind::Speculative, seq); assert_eq!(step.lanes[0].tokens, 1); @@ -8623,6 +8626,662 @@ fn content_header_envelope_enters_speculative_reasoning_after_header_and_returns assert_eq!(finished, Some((9, "stop"))); } +#[test] +fn non_speculative_grammar_reasoning_toggles_in_place_without_cancel_or_reprefill() { + let (mut fixture, compiler, eos, think_end) = speculative_reasoning_fixture(); + // Non-speculative core: empty speculative_widths. + fixture.config.speculative_widths.clear(); + fixture.config.speculative_fixed_width = None; + let output_cfg = reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"cd\"", Some(&envelope)) + .unwrap(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, mut generation) = fixture.incoming(vec![0, 1], 16); + incoming.prompt.grammar = Some(grammar); + incoming.prompt.grammar_reasoning = Some(output_cfg); + sender.send(vec![incoming]).unwrap(); + + let mut worker = fixture.worker(receiver); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let slot = handle.slot as usize; + // Non-speculative models keep grammar_constrained=true (no 2-frame pipelining) while + // initializing device grammar_enabled=true with a cached all-ones mask during reasoning. + assert!(worker.scheduler.request(handle).unwrap().grammar_constrained); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.is_enabled()); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.mask().is_none()); + + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(0)); // "a" (reasoning) + advance(&mut worker, GraphKind::Snapshot, 3, None); + + // Decode emits reasoning token 1 then closes reasoning with ``. + let d1 = planned(&mut worker, GraphKind::Decode, 4); + assert!(d1.requires_feedback); + let f1 = completion(&worker, &d1, 4, Some(1)); + worker.complete(GraphKind::Decode, f1).unwrap(); + assert_eq!(worker.active[slot].as_ref().unwrap().request, handle); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.mask().is_none()); + + let d2 = planned(&mut worker, GraphKind::Decode, 5); + assert!(d2.requires_feedback); + let f2 = completion(&worker, &d2, 5, Some(think_end)); + worker.complete(GraphKind::Decode, f2).unwrap(); + + // Must stay live on the exact same handle with zero park, zero cancel, and synced mask. + assert!(worker.parked.is_empty()); + assert_eq!(worker.active[slot].as_ref().unwrap().request, handle); + assert!(worker.scheduler.request(handle).unwrap().grammar_constrained); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.is_enabled()); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.mask().is_some()); + assert!(worker.active[slot].as_ref().unwrap().reasoning.is_none()); + let synced = worker.active[slot] + .as_ref() + .unwrap() + .incoming + .prompt + .grammar + .as_ref() + .unwrap(); + assert!(synced.allows(2)); + assert!(!synced.allows(4)); + + // Continue decoding answer directly on the live KV cache without Restore or Prefill. + let d3 = planned(&mut worker, GraphKind::Decode, 6); + let f3 = completion(&worker, &d3, 6, Some(2)); // "c" + worker.complete(GraphKind::Decode, f3).unwrap(); + let d4 = planned(&mut worker, GraphKind::Decode, 7); + let f4 = completion(&worker, &d4, 7, Some(3)); // "d" + worker.complete(GraphKind::Decode, f4).unwrap(); + let d5 = planned(&mut worker, GraphKind::Decode, 8); + let mut f5 = completion(&worker, &d5, 8, Some(eos)); + f5.records[slot].status = 2; + worker.complete(GraphKind::Decode, f5).unwrap(); + if worker + .scheduler + .request(handle) + .is_ok_and(|r| r.phase == RequestPhase::Snapshot) + { + advance(&mut worker, GraphKind::Snapshot, 9, None); + } + assert!(worker.publish().unwrap()); + + let mut tokens = Vec::new(); + let mut finished = None; + while let Ok(event) = generation.events.try_recv() { + match event { + GenerationEvent::Token(t) => tokens.push(t), + GenerationEvent::ObservedToken { .. } => {} + GenerationEvent::Finished { generated_tokens, reason, .. } => { + finished = Some((generated_tokens, reason)); + } + other => panic!("unexpected event: {other:?}"), + } + } + assert_eq!(tokens, vec![0, 1, think_end, 2, 3, eos]); + assert_eq!(finished, Some((6, "stop"))); +} + +#[test] +fn speculative_grammar_reasoning_with_grammar_enabled_binding_toggles_in_place() { + use crate::model::contract::{GraphOperation, InputIndexing, ValueBinding, ValueSource}; + + let (mut fixture, compiler, eos, think_end) = speculative_reasoning_fixture(); + // Declare per-step `GrammarEnabled` binding on every sampling graph in the contract. + for graph in &mut fixture.config.contract.graphs { + if matches!( + graph.kind, + GraphOperation::Prefill + | GraphOperation::TerminalPrefill + | GraphOperation::ScoredPrefill + | GraphOperation::Decode + | GraphOperation::Speculative + | GraphOperation::Mixed + | GraphOperation::Resume + ) { + graph.inputs.push(ValueBinding { + buffer: "sampling_grammar_enabled".into(), + source: ValueSource::GrammarEnabled, + indexing: InputIndexing::RequestRow, + value_offset: 0, + padding: 0, + tensor: String::new(), + parameter: String::new(), + }); + } + } + let output_cfg = reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"cd\"", Some(&envelope)) + .unwrap(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, mut generation) = fixture.incoming(vec![0, 1], 16); + incoming.prompt.grammar = Some(grammar); + incoming.prompt.grammar_reasoning = Some(output_cfg); + sender.send(vec![incoming]).unwrap(); + + let mut worker = fixture.worker(receiver); + enable_speculative_worker(&mut worker, &fixture.config); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let slot = handle.slot as usize; + assert!(!worker.scheduler.request(handle).unwrap().grammar_constrained); + assert!(!worker.admissions[slot].as_ref().unwrap().grammar.is_enabled()); + + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(0)); + advance(&mut worker, GraphKind::Snapshot, 3, None); + + // Single speculative frame closes cleanly on `` with skipped == 0 && pending == 0. + let step = planned(&mut worker, GraphKind::Speculative, 4); + assert_eq!(step.lanes[0].tokens, 8); + assert!(!step.requires_feedback); + let live = worker.scheduler.request(handle).unwrap(); + let frame = speculative_burst_frame( + &worker, + &step, + 4, + slot, + live.consumed_tokens as i64, + live.generated_tokens as i64, + &[1, think_end], + false, + ); + worker.complete(GraphKind::Speculative, frame).unwrap(); + + // Toggled strictly in place on the exact same handle: zero cancel, zero park, zero Restore. + assert!(worker.parked.is_empty()); + assert_eq!(worker.active[slot].as_ref().unwrap().request, handle); + assert!(worker.scheduler.request(handle).unwrap().grammar_constrained); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.is_enabled()); + assert!(worker.admissions[slot].as_ref().unwrap().grammar.mask().is_some()); + + // Next speculative step runs width-1 constrained directly on the live slot. + for (seq, &(tok, done)) in [(2u32, false), (3u32, false), (eos, true)].iter().enumerate() { + let s = 5 + seq as u64; + let next = planned(&mut worker, GraphKind::Speculative, s); + assert_eq!(next.lanes[0].tokens, 1); + assert!(next.requires_feedback); + let live = worker.scheduler.request(handle).unwrap(); + let f = speculative_burst_frame( + &worker, + &next, + s, + slot, + live.consumed_tokens as i64, + live.generated_tokens as i64, + &[tok], + done, + ); + worker.complete(GraphKind::Speculative, f).unwrap(); + } + if worker + .scheduler + .request(handle) + .is_ok_and(|r| r.phase == RequestPhase::Snapshot) + { + advance(&mut worker, GraphKind::Snapshot, 8, None); + } + assert!(worker.publish().unwrap()); + + let mut tokens = Vec::new(); + while let Ok(event) = generation.events.try_recv() { + if let GenerationEvent::Token(t) = event { + tokens.push(t); + } + } + assert_eq!(tokens, vec![0, 1, think_end, 2, 3, eos]); +} + +#[test] +fn speculative_grammar_reasoning_without_binding_publishes_terminal_checkpoint_for_zero_overshoot_and_pending_frame() { + // 1. Existing speculative core (no per-step GrammarEnabled binding) with skipped == 0, pending == 0: + // publishes a terminal checkpoint covering reasoning KV state so Restore reuses all reasoning tokens. + { + let (fixture, compiler, eos, think_end) = speculative_reasoning_fixture(); + let output_cfg = + reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"c\"", Some(&envelope)) + .unwrap(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, mut generation) = fixture.incoming(vec![0, 1], 16); + incoming.prompt.grammar = Some(grammar); + incoming.prompt.grammar_reasoning = Some(output_cfg); + sender.send(vec![incoming]).unwrap(); + + let mut worker = fixture.worker(receiver); + enable_speculative_worker(&mut worker, &fixture.config); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let slot = handle.slot as usize; + + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(0)); + advance(&mut worker, GraphKind::Snapshot, 3, None); + + let step = planned(&mut worker, GraphKind::Speculative, 4); + let live = worker.scheduler.request(handle).unwrap(); + // Reasoning burst ends cleanly on `` with skipped == 0 and no 2nd frame queued. + let frame = speculative_burst_frame( + &worker, + &step, + 4, + slot, + live.consumed_tokens as i64, + live.generated_tokens as i64, + &[1, 1, think_end], + false, + ); + worker.complete(GraphKind::Speculative, frame).unwrap(); + // Must arm terminal Snapshot rather than discarding reasoning KV via cancel. + assert_eq!( + worker.scheduler.request(handle).unwrap().phase, + RequestPhase::Snapshot + ); + advance(&mut worker, GraphKind::Snapshot, 5, None); + assert!(worker.publish().unwrap()); + assert_eq!(worker.parked.len(), 1); + + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let next = worker.active.iter().flatten().next().unwrap().request; + let next_live = worker.scheduler.request(next).unwrap(); + assert!(next_live.grammar_constrained); + // Reuses all 5 consumed tokens ([0, 1, 0, 1, 1]) instead of rolling back to 2 prompt tokens! + assert_eq!(next_live.consumed_tokens, 5); + assert_eq!(next_live.prompt_tokens, 6); + advance(&mut worker, GraphKind::Restore, 6, None); + advance(&mut worker, GraphKind::Prefill, 7, Some(2)); // only 1 token (``) prefilled! + if worker + .scheduler + .request(next) + .is_ok_and(|r| r.phase == RequestPhase::Snapshot) + { + advance(&mut worker, GraphKind::Snapshot, 8, None); + } + let s = planned(&mut worker, GraphKind::Speculative, 9); + let live = worker.scheduler.request(next).unwrap(); + let f = speculative_burst_frame( + &worker, + &s, + 9, + next.slot as usize, + live.consumed_tokens as i64, + live.generated_tokens as i64, + &[eos], + true, + ); + worker.complete(GraphKind::Speculative, f).unwrap(); + if worker + .scheduler + .request(next) + .is_ok_and(|r| r.phase == RequestPhase::Snapshot) + { + advance(&mut worker, GraphKind::Snapshot, 10, None); + } + assert!(worker.publish().unwrap()); + let tokens: Vec = std::iter::from_fn(|| generation.events.try_recv().ok()) + .filter_map(|e| match e { + GenerationEvent::Token(t) => Some(t), + _ => None, + }) + .collect(); + assert_eq!(tokens, vec![0, 1, 1, think_end, 2, eos]); + } + + // 2. Existing speculative core with skipped == 0 && pending == 1: + // Frame 2 consumes only `` (0 accepted overshoot drafts) -> suppresses Frame 2 token, + // publishes terminal checkpoint at exact_len, and readmits via Restore -> Resume (0 re-prefill!). + { + let (fixture, compiler, eos, think_end) = speculative_reasoning_fixture(); + let output_cfg = + reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"c\"", Some(&envelope)) + .unwrap(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, mut generation) = fixture.incoming(vec![0, 1], 16); + incoming.prompt.grammar = Some(grammar); + incoming.prompt.grammar_reasoning = Some(output_cfg); + sender.send(vec![incoming]).unwrap(); + + let mut worker = fixture.worker(receiver); + enable_speculative_worker(&mut worker, &fixture.config); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let slot = handle.slot as usize; + + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(0)); + advance(&mut worker, GraphKind::Snapshot, 3, None); + + let first = planned(&mut worker, GraphKind::Speculative, 4); + let second = planned(&mut worker, GraphKind::Speculative, 5); + assert_eq!(worker.scheduler.request(handle).unwrap().pending(), 2); + + let live = worker.scheduler.request(handle).unwrap(); + let consumed_before = live.consumed_tokens as i64; + let generated_before = live.generated_tokens as i64; + let frame1 = speculative_burst_frame( + &worker, + &first, + 4, + slot, + consumed_before, + generated_before, + &[1, think_end], + false, + ); + // Frame 2 consumes `` (consumed += 1 -> exact_len = 5) and emits 1 overshoot token `4`. + let frame2 = speculative_burst_frame( + &worker, + &second, + 5, + slot, + consumed_before + 2, + generated_before + 2, + &[4], + false, + ); + + worker.complete(GraphKind::Speculative, frame1).unwrap(); + assert_eq!(worker.scheduler.request(handle).unwrap().pending(), 1); + // Must pause the slot so no Frame 3 can be scheduled while Frame 2 drains. + assert!(worker.scheduler.plan().is_none()); + assert!(worker.parked.is_empty()); + + worker.complete(GraphKind::Speculative, frame2).unwrap(); + // Frame 2 consumed exactly through `` (5 == exact_len), so terminal Snapshot arms! + assert_eq!( + worker.scheduler.request(handle).unwrap().phase, + RequestPhase::Snapshot + ); + advance(&mut worker, GraphKind::Snapshot, 6, None); + assert!(worker.publish().unwrap()); + assert_eq!(worker.parked.len(), 1); + + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let next = worker.active.iter().flatten().next().unwrap().request; + let next_live = worker.scheduler.request(next).unwrap(); + assert!(next_live.grammar_constrained); + // Full exact_len (5/5 tokens) cached: Restore -> Resume with zero re-prefill! + assert_eq!(next_live.consumed_tokens, 5); + assert_eq!(next_live.prompt_tokens, 5); + advance(&mut worker, GraphKind::Restore, 7, None); + advance(&mut worker, GraphKind::Resume, 8, Some(2)); // "c" + let s = planned(&mut worker, GraphKind::Speculative, 9); + let live = worker.scheduler.request(next).unwrap(); + let f = speculative_burst_frame( + &worker, + &s, + 9, + next.slot as usize, + live.consumed_tokens as i64, + live.generated_tokens as i64, + &[eos], + true, + ); + worker.complete(GraphKind::Speculative, f).unwrap(); + if worker + .scheduler + .request(next) + .is_ok_and(|r| r.phase == RequestPhase::Snapshot) + { + advance(&mut worker, GraphKind::Snapshot, 10, None); + } + assert!(worker.publish().unwrap()); + let tokens: Vec = std::iter::from_fn(|| generation.events.try_recv().ok()) + .filter_map(|e| match e { + GenerationEvent::Token(t) => Some(t), + _ => None, + }) + .collect(); + // Overshoot token `4` from Frame 2 was never emitted! + assert_eq!(tokens, vec![0, 1, think_end, 2, eos]); + } + + // 3. Existing speculative core with skipped == 0 && pending == 1 where Frame 2 DOES accept + // an overshoot draft into KV/state (consumed_tokens > exact_len): safely falls back to cancel. + { + let (fixture, compiler, _eos, think_end) = speculative_reasoning_fixture(); + let output_cfg = + reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"c\"", Some(&envelope)) + .unwrap(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, _generation) = fixture.incoming(vec![0, 1], 16); + incoming.prompt.grammar = Some(grammar); + incoming.prompt.grammar_reasoning = Some(output_cfg); + sender.send(vec![incoming]).unwrap(); + + let mut worker = fixture.worker(receiver); + enable_speculative_worker(&mut worker, &fixture.config); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let slot = handle.slot as usize; + + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(0)); + advance(&mut worker, GraphKind::Snapshot, 3, None); + + let first = planned(&mut worker, GraphKind::Speculative, 4); + let second = planned(&mut worker, GraphKind::Speculative, 5); + let live = worker.scheduler.request(handle).unwrap(); + let consumed_before = live.consumed_tokens as i64; + let generated_before = live.generated_tokens as i64; + let frame1 = speculative_burst_frame( + &worker, + &first, + 4, + slot, + consumed_before, + generated_before, + &[1, think_end], + false, + ); + // Frame 2 emits TWO overshoot tokens `[4, 4]`, advancing consumed_tokens to 6 > exact_len (5). + let frame2 = speculative_burst_frame( + &worker, + &second, + 5, + slot, + consumed_before + 2, + generated_before + 2, + &[4, 4], + false, + ); + + worker.complete(GraphKind::Speculative, frame1).unwrap(); + worker.complete(GraphKind::Speculative, frame2).unwrap(); + assert!(worker.active.iter().all(Option::is_none)); + assert_eq!(worker.parked.len(), 1); + let (parked_in, parked_state) = worker.parked.front().unwrap(); + assert_eq!(parked_in.prompt.tokens, vec![0, 1, 0, 1, think_end]); + assert_eq!(parked_state.carried.generated_tokens, 3); + } +} + +#[test] +fn preemption_coincident_with_grammar_transition_preserves_grammar_mode_and_reasoning_budget() { + // Under page pressure, `complete_inner` can invoke `preempt_newest()` on the exact step where + // a growable request closes reasoning with `reasoning_cut.after > 0`. `Worker::publish()` must + // apply `PendingGrammarPark` rather than letting `park_if_preempted` discard the transition. + let (mut fixture, compiler, eos, think_end) = speculative_reasoning_fixture(); + let caps = crate::model::scheduler_capabilities(&fixture.config); + let page_tokens = caps.page_tokens; + fixture.config.prepared_sequence_tokens = page_tokens * 8; + fixture.config.limits.max_sequence_tokens = page_tokens * 8; + // Both requests hold `2 + draft_pages` pages each (prompt + 1 growable output + draft), + // leaving 0 free pages so h0 crossing into page 3 preempts h1. + fixture.config.limits.pages = ((2 + caps.draft_pages_per_request) * 2) as u32; + let output_cfg = + reasoning_output_config(&fixture, crate::output::tagged::OutputStart::Reasoning); + let envelope = crate::output::OutputPipeline::grammar_envelope(&output_cfg).unwrap(); + let grammar = compiler + .compile_lark_in("start: \"c\"", Some(&envelope)) + .unwrap(); + + let (sender, receiver) = mpsc::channel(); + let (mut older, _older_gen) = fixture.incoming(vec![0; page_tokens], (page_tokens * 2) as u32); + older.prompt.max_new_tokens = (page_tokens * 2) as u32; + let (mut newer, mut newer_gen) = fixture.incoming(vec![1; page_tokens], 20); + newer.prompt.max_new_tokens = 20; + newer.prompt.grammar = Some(grammar); + newer.prompt.grammar_reasoning = Some(output_cfg.clone()); + newer.prompt.reasoning_cut = Some(ReasoningCut { + after: 10, + close: vec![think_end], + output: Some(output_cfg), + }); + sender.send(vec![older, newer]).unwrap(); + + let mut worker = fixture.worker(receiver); + enable_speculative_worker(&mut worker, &fixture.config); + let mut graphs = crate::model::testing::manifest(&fixture.config).graphs; + for graph in &mut graphs { + graph.estimated_duration_ns = if matches!( + graph.kind, + GraphKind::Init | GraphKind::Prefill | GraphKind::Snapshot + ) { + 1_000 + } else { + 10_000_000_000 + }; + } + worker.scheduler.measured_graph_durations(&graphs).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert_eq!(worker.active.iter().flatten().count(), 2); + assert_eq!(worker.scheduler.free_page_count(), 0); + let h0 = worker.active[0].as_ref().unwrap().request; + let h1 = worker.active[1].as_ref().unwrap().request; + + let make_spec_frame = + |worker: &Worker<'_>, step: &ScheduledStep, seq: u64, bursts: &[(RequestHandle, &[u32])]| { + let mut frame = completion(worker, step, seq, Some(0)); + for (lane_idx, lane) in step.lanes.iter().enumerate() { + let r = worker.scheduler.request(lane.request).unwrap(); + let tokens = bursts + .iter() + .find(|(h, _)| *h == lane.request) + .map(|(_, t)| *t) + .unwrap_or(&[0]); + let count = tokens.len() as i64; + let rec = &mut frame.records[lane.request.slot as usize]; + rec.consumed_tokens = r.consumed_tokens as i64 + count; + rec.generated_tokens = i64::from(r.generated_tokens) + count; + rec.token_id = i64::from(*tokens.last().unwrap()); + rec.status = 1; + let mut vec_tokens = vec![-1i64; 16]; + for (i, &t) in tokens.iter().enumerate() { + vec_tokens[i] = i64::from(t); + } + rec.vector = Some(crate::execution::TokenVector { + verification_width: step.token_capacity as i64, + offered_drafts: step.lanes[lane_idx].tokens as i64 - 1, + emitted_count: count, + accepted_drafts: (count - 1).max(0), + draft_cache_consumed: rec.consumed_tokens - 1, + tokens: vec_tokens, + ..Default::default() + }); + } + frame + }; + + // Advance both through Init -> Prefill -> Snapshot -> Decode. + let mut seq = 1u64; + for _ in 0..16 { + let p0 = worker.scheduler.request(h0).unwrap().phase; + let p1 = worker.scheduler.request(h1).unwrap().phase; + if p0 == RequestPhase::Decode && p1 == RequestPhase::Decode { + break; + } + let step = worker.plan().unwrap().0.expect("warmup step"); + let kind = step.kind; + worker.reserve_and_pack(&step, Fence(seq)).unwrap(); + let frame = if kind == GraphKind::Speculative { + make_spec_frame(&worker, &step, seq, &[]) + } else { + let token = kind.is_prefill().then_some(0); + completion(&worker, &step, seq, token) + }; + worker.complete(kind, frame).unwrap(); + seq += 1; + } + assert_eq!(worker.scheduler.request(h0).unwrap().phase, RequestPhase::Decode); + assert_eq!(worker.scheduler.request(h1).unwrap().phase, RequestPhase::Decode); + + // Advance h0 close to its 2nd page boundary so one more speculative burst pushes + // `consumed + decode_horizon (16) > page_tokens * 2`, triggering `refill_reservations()` -> + // `preempt_newest()` on h1 in the same `complete_inner` call where h1 closes reasoning with + // `` (`skipped == 0`, `pending == 0`). + let mut h1_closed = false; + while !h1_closed { + let step = worker.plan().unwrap().0.expect("decode step"); + let kind = step.kind; + assert!(step.lanes.iter().any(|l| l.request == h0)); + assert!(step.lanes.iter().any(|l| l.request == h1)); + worker.reserve_and_pack(&step, Fence(seq)).unwrap(); + let r0 = worker.scheduler.request(h0).unwrap(); + let burst0 = ((page_tokens * 2) as i64 - r0.consumed_tokens as i64).clamp(1, 8) as usize; + let b0 = vec![0u32; burst0]; + let tok1 = if r0.consumed_tokens as usize + burst0 + 16 > page_tokens * 2 { + h1_closed = true; + think_end + } else { + 0 + }; + let b1 = [tok1]; + let frame = make_spec_frame(&worker, &step, seq, &[(h0, &b0), (h1, &b1)]); + worker.complete(kind, frame).unwrap(); + seq += 1; + } + + // Verify h1 WAS preempted in complete_inner AND still retained PendingGrammarPark. + assert!( + worker.scheduler.request(h1).unwrap().preempted(), + "test setup must trigger preempt_newest on the grammar-transitioning request" + ); + assert!( + worker.active[h1.slot as usize] + .as_ref() + .unwrap() + .pending_grammar_park + .is_some() + ); + + if worker.scheduler.request(h1).unwrap().phase == RequestPhase::Snapshot { + advance(&mut worker, GraphKind::Snapshot, seq, None); + } + assert!(worker.publish().unwrap()); + assert_eq!( + worker.parked.len(), + 1, + "publish must apply pending_grammar_park before park_if_preempted" + ); + let (parked_in, parked_state) = worker.parked.front().unwrap(); + // Must switch to constrained answer mode, drop reasoning decoder, and preserve cut.after (+10). + assert_eq!( + parked_in.grammar_reasoning_mode, + Some(false), + "publish must apply pending_grammar_park before park_if_preempted" + ); + assert!(!parked_in.speculative_grammar_reasoning()); + assert!(parked_state.reasoning.is_none()); + let expected_remaining = 20u32 + .saturating_sub(parked_state.carried.generated_tokens) + .saturating_add(10); + assert_eq!(parked_in.prompt.max_new_tokens, expected_remaining); + let _ = (eos, &mut newer_gen); +} + #[test] fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_envelopes() { use crate::server::protocol::Protocol; @@ -8644,7 +9303,8 @@ fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_env assert!(incoming.prompt.grammar.is_some()); assert!(incoming.prompt.grammar_reasoning.is_some()); assert!(incoming.speculative_grammar_reasoning()); - assert!(!incoming.spec().grammar_constrained); + assert!(!incoming.spec(true).grammar_constrained); + assert!(incoming.spec(false).grammar_constrained); // 2. Content-start chat request with grammar gets `grammar_reasoning: None` (constrained immediately). let content_fixture = Fixture::new(); @@ -8662,7 +9322,8 @@ fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_env assert!(incoming.prompt.grammar.is_some()); assert!(incoming.prompt.grammar_reasoning.is_none()); assert!(!incoming.speculative_grammar_reasoning()); - assert!(incoming.spec().grammar_constrained); + assert!(incoming.spec(true).grammar_constrained); + assert!(incoming.spec(false).grammar_constrained); // 3. Raw completions request with grammar gets `grammar_reasoning: None` (constrained immediately). let (incoming, _, _, _) = prepared_budget_request( @@ -8678,7 +9339,8 @@ fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_env assert!(incoming.prompt.grammar.is_some()); assert!(incoming.prompt.grammar_reasoning.is_none()); assert!(!incoming.speculative_grammar_reasoning()); - assert!(incoming.spec().grammar_constrained); + assert!(incoming.spec(true).grammar_constrained); + assert!(incoming.spec(false).grammar_constrained); } #[test] @@ -8726,7 +9388,7 @@ fn prepare_inference_sets_preserve_message_anchor_and_preserves_across_readmissi let (incoming, _generation, _, _) = prepared_budget_request(&reasoning_fixture, Protocol::Chat, reasoning_body); assert!(incoming.prompt.preserve_message_anchor); - assert!(incoming.spec().preserve_message_anchor); + assert!(incoming.spec(false).preserve_message_anchor); let (sender, receiver) = mpsc::channel(); sender.send(vec![incoming]).unwrap(); let mut worker = reasoning_fixture.worker(receiver); diff --git a/verification/helios-lifecycle/Lifecycle.tla b/verification/helios-lifecycle/Lifecycle.tla index 6c36193ce..8063270c3 100644 --- a/verification/helios-lifecycle/Lifecycle.tla +++ b/verification/helios-lifecycle/Lifecycle.tla @@ -8,6 +8,7 @@ Slots == {0, 1} Free == 0 Live == 1 Retiring == 2 +Paused == 3 Members(mask) == CASE mask = 1 -> {0} [] mask = 2 -> {1} @@ -56,11 +57,26 @@ Complete(before, after) == IF s \in released THEN 0 ELSE before.lastUse[s]]] Cancel(before, after, slot) == - /\ before.phase[slot] = Live + /\ before.phase[slot] \in {Live, Paused} /\ LET waiting == before.lastUse[slot] > before.completed IN after = [before EXCEPT !.phase[slot] = IF waiting THEN Retiring ELSE Free, !.lastUse[slot] = IF waiting THEN @ ELSE 0] +PauseForPark(before, after, slot) == + /\ before.phase[slot] = Live + /\ \E i \in 1..Len(before.queue) : slot \in before.queue[i].members + /\ after = [before EXCEPT !.phase[slot] = Paused] + +FinishForPark(before, after, slot) == + /\ before.phase[slot] \in {Live, Paused} + /\ ~\E i \in 1..Len(before.queue) : slot \in before.queue[i].members + /\ after = [before EXCEPT !.phase[slot] = Live] + +ToggleGrammar(before, after, slot) == + /\ before.phase[slot] = Live + /\ ~\E i \in 1..Len(before.queue) : slot \in before.queue[i].members + /\ after = before + UnconfirmedDrain(before, after) == after = before ConfirmedDrain(before, after) == after = [before EXCEPT !.completed = before.submitted, !.queue = <<>>, @@ -71,13 +87,16 @@ Next == (\E s \in Slots : Admit(state, state', s)) \/ (\E mask \in 1..3, barrier \in 0..1 : Commit(state, state', mask, barrier)) \/ Complete(state, state') \/ (\E s \in Slots : Cancel(state, state', s)) + \/ (\E s \in Slots : PauseForPark(state, state', s)) + \/ (\E s \in Slots : FinishForPark(state, state', s)) + \/ (\E s \in Slots : ToggleGrammar(state, state', s)) \/ UnconfirmedDrain(state, state') \/ ConfirmedDrain(state, state') WellTyped(st) == /\ st.submitted \in 0..MaxSubmissions /\ st.completed \in 0..st.submitted - /\ st.phase \in [Slots -> {Free, Live, Retiring}] + /\ st.phase \in [Slots -> {Free, Live, Retiring, Paused}] /\ st.generation \in [Slots -> 1..MaxGeneration] /\ st.lastUse \in [Slots -> 0..st.submitted] /\ Len(st.queue) <= 2 @@ -152,6 +171,9 @@ AllowedEdge(edge) == [] action[1] = 4 -> Cancel(before, after, action[2]) [] action[1] = 5 -> UnconfirmedDrain(before, after) [] action[1] = 6 -> ConfirmedDrain(before, after) + [] action[1] = 7 -> PauseForPark(before, after, action[2]) + [] action[1] = 8 -> FinishForPark(before, after, action[2]) + [] action[1] = 9 -> ToggleGrammar(before, after, action[2]) [] OTHER -> FALSE Spec == Init /\ [][Next]_state diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index f24508d53..30e57924c 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -49,9 +49,10 @@ speculative pending bounds, and publication before checkpoint-copy completion. `Lifecycle.tla` checks two request slots, two queued submissions, four submission identities, and two generations per slot. Its initial state represents two -requests ready for ordinary decode. A slot is free, live, or retiring. Each -submission retains its fence, participating slots and generations, and whether it -requires exclusive execution. Completion consumes the oldest submission. +requests ready for ordinary decode. A slot is free, live, retiring, or paused +for a checkpoint-preserving park. Each submission retains its fence, +participating slots and generations, and whether it requires exclusive +execution. Completion consumes the oldest submission. | Model operation | Rust implementation | |---|---| @@ -59,6 +60,9 @@ requires exclusive execution. Completion consumes the oldest submission. | `Commit` | `RequestScheduler::commit` | | `Complete` | `RequestScheduler::complete_inner` and `advance_retirement` | | `Cancel` | `RequestScheduler::cancel` and `retire` | +| `PauseForPark` | `RequestScheduler::pause_for_park` | +| `FinishForPark` | `RequestScheduler::finish_for_park` | +| `ToggleGrammar` | `RequestScheduler::set_grammar_constrained` | | `UnconfirmedDrain`, `ConfirmedDrain` | `RequestScheduler::release_after_shutdown` | The invariants require ordered completion, retained ownership and generation diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index 2a09c68b8..fab1ad648 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -479,7 +479,57 @@ def run_aux(test): "stale generation completion accepted"), ("unconfirmed drain", "if !shutdown.drained {", "if false {", "unconfirmed drain accepted resource release"), + ("grammar toggle with pending work", + " if request.pending != 0\n" + " || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)\n" + " || (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())", + " if matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)\n" + " || (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())", + "set_grammar_constrained accepted a request with pending GPU work"), + ("pause_for_park without pending work", + " if request.pending == 0\n" + " || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)", + " if matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)", + "pause_for_park accepted a request with no pending work"), + ("finish_for_park with pending work", + " if request.pending != 0 || request.phase == RequestPhase::Inbound {", + " if request.phase == RequestPhase::Inbound {", + "finish_for_park accepted a request with pending GPU work"), ]) + check_mutations(cargo, ROOT / "helios/src/scheduler/policy.rs", TEST, [ + ("paused_for_park scheduling bypass", + " if request.paused_for_park\n || request.window_snapshot_ready", + " if request.window_snapshot_ready", + "paused_for_park request was scheduled into a new plan"), + ]) + check_mutations( + cargo, + ROOT / "helios/src/server/runtime.rs", + "server::runtime::phase_tests::preemption_coincident_with_grammar_transition_preserves_grammar_mode_and_reasoning_budget", + [ + ("preemption clobbers pending_grammar_park", + " && !live.paused_for_park()\n" + " && let Some(park) = request.pending_grammar_park.take()", + " && false\n" + " && let Some(park) = request.pending_grammar_park.take()", + "publish must apply pending_grammar_park before park_if_preempted"), + ], + ) + check_mutations( + cargo, + ROOT / "helios/src/offload/copy_gate.rs", + "offload::copy_gate::tests::try_enter_offload_batch_returns_none_without_blocking_or_burning_wave_tokens", + [ + ("try_enter_offload_batch ignores peer gate", + " pub fn try_enter_offload_batch(&self) -> Option> {\n" + " let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());\n" + " if Self::offload_must_wait(&state) {", + " pub fn try_enter_offload_batch(&self) -> Option> {\n" + " let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());\n" + " if false {", + "try_enter_offload_batch must return None while peer-copy graphs block entry"), + ], + ) check_mutations(cargo, ROOT / "helios/src/execution/threaded/protocol.rs", RANK_TEST, [ ("partial readiness", "frame.ready().iter().all(|ready| *ready)", "frame.ready().iter().any(|ready| *ready)", "commit must wait for every peer readiness"),