From 70e0f4a80f332b79455fe50752f1c73147e45a3f Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 28 Nov 2026 12:25:33 -0800 Subject: [PATCH 01/27] helios: fix InitialState hash bypass, TP startup drain hang, VLM teardown deadlock, and PatchMerge validation (#579) Why Four runtime defects in Helios affect core integrity verification, tensor-parallel startup teardown, multimodal image-preparation liveness, and PatchMerge image processing: 1. Core authorization hashes supporting payloads unconditionally and gates weight payloads on `--verify-weights` (default false). `PayloadSource::supporting_payload_ids()` collected only `rank.modules[..].globals` and `core.assets`, leaving all `rank.initializers` gated on `verify_weights`. On cache-backed exports (where `initial-state.safetensors` has a separate payload identity from `initial-state-globals.safetensors`) or ranks without module globals, `PayloadRole::InitialState` initializers carrying GPU dispatch tables and TMA `CUtensorMap` descriptors loaded into GPU memory without SHA-256 verification. 2. During `ThreadedExecutor::new()`, each peer thread that completes `GraphExecutor::new_unstarted()` enters the startup command loop waiting solely on `mpsc::Receiver` until `Command::FinishStartup` transitions it to `DispatchRing`. When a later peer fails `new_unstarted()` or thread spawn, dropping the partially constructed `ThreadedExecutor` calls `close()`, which signaled only `ring.request_drain()`. Initialized peers never observed `DispatchRing`, so `close()` timed out sequentially (120 s in the primary loop plus 120 s per peer in best-effort teardown) and abandoned rank-zero CUDA resources. 3. `Worker` tracks one global in-flight or buffered multimodal image preparation slot in `self.preparing_image`. Once the background worker delivers `active.prepared_image = Some(images)`, no further worker reply arrives to clear `self.preparing_image`. Teardown paths in `park()`, `publish()` (abandon, text-stop error, user stop, device error, and normal finish), `plan()` (copy-grammar failure), and `cancel_stopped()` cleared `self.active[slot]` without releasing `self.preparing_image`, permanently blocking all subsequent multimodal image preparation across the server. 4. `PreparedImageInput::valid_processed()` omitted `Profile::PatchMerge(_)`, falling through `_ => 588` instead of `1176` (`3 * 2 * 14 * 14` f32 values per patch) and rejecting every `materialize()` and `materialize_cached()` call for `PatchMerge` (MiniMax-M3-VL). `PatchProcessor::process()` also passed the hardcoded 16x16 constant `FEATURES` (`1536`) to `reserve_outputs`, over-allocating `pixel_values` capacity for 14x14 patches. What changed - `helios/src/runtime_core/protection.rs`: - Before: `supporting_payload_ids()` inspected only `rank.modules[..].globals` and `core.assets`. - After: `supporting_payload_ids()` also inserts every `rank.initializers` slice whose `source.role` is `PayloadRole::InitialState`. Weight (`Weights`, `TunedWeights`) initializers remain gated on `verify_weights`. Extended the TP2 payload fixture with standalone `initial-state/rank-{rank}.safetensors` `InitialState` initializers distinct from `globals/rank-{rank}.safetensors` and updated verification and rank-isolation tests. - `helios/src/execution/threaded.rs`: - Before: `ThreadedExecutor` did not track whether peers had transitioned past `FinishStartup`, and `close()` signaled only `ring.request_drain()`. - After: Added `started: bool` (set `true` only after `startup` finishes `Command::FinishStartup` on all ranks), and extracted `close_peers`, `best_effort_drain_peers`, and `run_startup_phase`. When `!started`, both `close_peers` and `best_effort_drain_peers` send `Command::Drain` to startup peers in addition to `ring.request_drain()`, allowing initialized peers to drain, acknowledge `Reply::Drained`, and join immediately so rank zero executes `local.close()`. The serving-phase `DispatchRing` prepare/commit/cancel/drain happens-before order is unchanged. Added 3 multi-thread CPU tests covering pre-start close, pre-start best-effort drain after a peer disconnect, and post-start `DispatchRing` close. - `helios/src/server/runtime.rs` and `helios/src/server/runtime/phase_tests.rs`: - Before: Individual teardown sites cleared `self.active[slot]` and `self.admissions[slot]` directly, only releasing `self.preparing_image` in `admit()` cancellation and `requeue()`. - After: Centralized active-slot removal in `clear_active_entry()` and `Worker::clear_active_slot()`, routing all active-slot removals (`complete_image_preparation`, `admit`, `publish`, `park`, `plan`, `requeue`, and `retire`/`cancel_stopped`) through it. Clearing a slot resets `preparing_image` when `removed.prepared_image.is_some()` and preserves it when `prepared_image` is `None` so an in-flight background worker reply still clears `preparing_image` once drained (guarded by `self.preparing_image == Some(handle)`). Added CPU worker tests covering `park()`, `publish()` device-error teardown, `cancel_stopped()`, and in-flight worker retention. - `helios/src/frontend/images/conditioned.rs`, `helios/src/frontend/images/patches.rs`, and `helios/src/frontend/images/mod.rs`: - Before: `valid_processed()` used a wildcard `_ => 588` that misclassified `Profile::PatchMerge(_)`, and `PatchProcessor::process()` reserved `FEATURES` (`1536`) elements per patch regardless of `patch_size`. - After: Added `PatchProcessor::pixel_width()` (`3 * 2 * patch_size * patch_size`), used it in `PatchProcessor::process()` for both initial capacity and `reserve_outputs`, scoped `mod.rs::FEATURES` to `#[cfg(test)]`, and replaced the wildcard match in `valid_processed()` with an exhaustive match over `Profile`. Added `PatchMerge` and `Glm` to `conditioned::tests::settings()` and added `patch_merge_materializes_and_caches_with_exact_pixel_width`. Claimed benefit and result - Default core loads (`--verify-weights` unset) now SHA-256 verify all `PayloadRole::InitialState` initializers before uploading them to GPU memory; on the live TP2 and TP4 SM120 cores tested below, stored-data verification checked 1.3 GiB in 0.3 s and 306.1 MiB in 0.0 s respectively. - Partial-initialization teardown in `ThreadedExecutor::close()` wakes and joins pre-start peers immediately via `Command::Drain` instead of timing out sequentially and abandoning rank-zero resources. - Multimodal image preparation no longer deadlocks server-wide after request preemption (`park()`), device-error teardown (`publish()`), copy-grammar failure, or `cancel_stopped()` while a prepared image is buffered. - `Profile::PatchMerge` (MiniMax-M3-VL) `materialize()` and `materialize_cached()` succeed with exact `1176` f32/patch length and capacity. Supporting evidence and limitations - Targeted P0 CPU release tests (`cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server -- runtime_core::protection:: execution::threaded::tests:: server::runtime::tests:: server::runtime::phase_tests::park_and_device_error_teardown_release_prepared_image_slot_for_next_request server::runtime::phase_tests::clear_active_slot_retains_in_flight_preparing_image_until_stale_reply_arrives server::runtime::phase_tests::prepared_image_window_stays_global_until_pack_or_cancellation frontend::images::conditioned::tests:: frontend::images::patch_merge::tests::`): 78 passed, 0 failed. - Formal lifecycle conformance and mutation suite (`python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar --mutations`): passed across all 9 TLA+ models, all 8 observed-edge Rust conformance suites (`DispatchRing`, `ResponseLifecycle`, `Lifecycle`, `RankProtocol`, `OffloadTransfer`, `CacheOwnership`, `Speculation`, `CheckpointReservation`), all 12 TLA+ model mutations, all 19 Rust source mutations, and post-mutation re-verification. - Full `helios` release unit suite (`cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server`): 1667 passed, 43 ignored, 7 unrelated failures (6 chat-template tests requiring `FLARE_TEST_TEMPLATE_DIR` and 1 pre-existing `model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape`). - `flare-cli` integration suites (`cache_commands`, `cli`, `inspect`, `unverified_payload`) plus `tests::actual_load_core_leases_managed_local_entries_and_releases_on_failure`: 25 passed, 0 failed (`flare-cli` bin suite had 1 unrelated `distribution::tests::source_waits_for_receiver_file_verification` BrokenPipe failure; `flare` lib suite had 225 passed and 2 unrelated local-HTTP `hub::tests` failures). - Live multi-GPU collective serving on SM120 (RTX PRO 6000 Blackwell Max-Q) with the rebuilt `flare-cli/target/release/flare` binary: - TP2 `nvidia/Qwen3.8-Flash-Next-FP4-Local@gb202-tp2-202610270419` on GPUs 8,9: verified 1.3 GiB stored data without `--verify-weights` (0.3 s), served single text, 4-way concurrent chat completions, and 2 sequential PNG VLM requests, and drained cleanly on `SIGTERM` (exit 0 in 5.32 s). - TP4 `Inkling-2-Small-NVFP4@gb202-tp4-202611150002` on GPUs 8,9,10,11: verified 306.1 MiB stored data without `--verify-weights` (0.0 s), served single text, 4-way concurrent chat completions with prefix reuse, and 2 sequential PNG VLM requests, and drained cleanly on `SIGTERM` (exit 0 in 3.07 s). - Unrun checks: no exported MiniMax-M3-VL (`Profile::PatchMerge`) core is present locally for live GPU serving (covered by CPU unit and cache tests); `cargo-kani` is not installed (no Kani-covered validators changed); `FLARE_TEST_TEMPLATE_DIR` chat templates were not fetched; partial-init failure in `ThreadedExecutor::new()` was verified on multi-thread CPU tests rather than injecting a live CUDA init fault. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=c3a9 Signed-off-by: Luke Alonso --- helios/src/execution/threaded.rs | 371 ++++++++++++++++++---- helios/src/frontend/images/conditioned.rs | 61 +++- helios/src/frontend/images/mod.rs | 1 + helios/src/frontend/images/patches.rs | 9 +- helios/src/runtime_core/protection.rs | 44 ++- helios/src/server/runtime.rs | 103 ++++-- helios/src/server/runtime/phase_tests.rs | 194 +++++++++++ 7 files changed, 681 insertions(+), 102 deletions(-) diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index af9e56de8..567a7ecad 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -601,6 +601,7 @@ pub(crate) struct ThreadedExecutor { local: GraphExecutor, peers: Vec, ring: Arc, + started: bool, next_epoch: u64, pending: VecDeque, poison: Option, @@ -640,6 +641,7 @@ impl ThreadedExecutor { local, peers: Vec::new(), ring, + started: false, next_epoch: 1, pending: VecDeque::with_capacity(2), poison: None, @@ -806,6 +808,7 @@ impl ThreadedExecutor { result.shutdown = Some(shutdown); return Err(error); } + result.started = true; Ok(result) } #[cfg(feature = "server")] @@ -980,54 +983,12 @@ impl ThreadedExecutor { if let Some(error) = &self.poison { return Err(error.clone()); } - self.ring.request_drain(); - for peer in &mut self.peers { - if !matches!(peer.receive()?, Reply::Drained) { - return Err(invalid("rank thread did not drain")); - } - let shutdown = peer - .thread - .take() - .unwrap() - .join() - .map_err(|_| invalid("rank thread panicked"))?; - if !shutdown.drained { - return Err(invalid("rank thread did not confirm drain")); - } - if let Some(error) = shutdown.error { - return Err(error); - } - } - Ok(()) + close_peers(&self.ring, &mut self.peers, self.started, TIMEOUT) })(); if result.is_err() { // Best-effort drain and join of any peers that can still exit cleanly so live // peer threads are not detached on poisoned teardown. - self.ring.request_drain(); - for peer in &mut self.peers { - if peer.thread.is_none() { - continue; - } - let deadline = Instant::now() + TIMEOUT; - let mut exited = false; - while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { - match receive(&peer.receiver, Some(remaining)) { - Ok(Ok(Reply::Drained)) - | Ok(Err(_)) - | Err(mpsc::RecvTimeoutError::Disconnected) => { - exited = true; - break; - } - Ok(Ok(_)) => continue, - Err(mpsc::RecvTimeoutError::Timeout) => break, - } - } - if exited { - if let Some(thread) = peer.thread.take() { - let _ = thread.join(); - } - } - } + best_effort_drain_peers(&self.ring, &mut self.peers, self.started, TIMEOUT); } let shutdown = match result { Ok(()) => self.local.close(), @@ -1043,10 +1004,84 @@ impl Drop for ThreadedExecutor { } } +fn close_peers( + ring: &DispatchRing, + peers: &mut [Peer], + started: bool, + timeout: Duration, +) -> Result<()> { + ring.request_drain(); + if !started { + for peer in peers.iter() { + peer.send(Command::Drain)?; + } + } + for peer in peers.iter_mut() { + let reply = receive(&peer.receiver, Some(timeout)) + .map_err(|_| invalid("rank thread response deadline expired"))??; + if !matches!(reply, Reply::Drained) { + return Err(invalid("rank thread did not drain")); + } + let shutdown = peer + .thread + .take() + .unwrap() + .join() + .map_err(|_| invalid("rank thread panicked"))?; + if !shutdown.drained { + return Err(invalid("rank thread did not confirm drain")); + } + if let Some(error) = shutdown.error { + return Err(error); + } + } + Ok(()) +} + +fn best_effort_drain_peers( + ring: &DispatchRing, + peers: &mut [Peer], + started: bool, + timeout: Duration, +) { + ring.request_drain(); + if !started { + for peer in peers.iter() { + if peer.thread.is_some() { + let _ = peer.send(Command::Drain); + } + } + } + for peer in peers.iter_mut() { + if peer.thread.is_none() { + continue; + } + let deadline = Instant::now() + timeout; + let mut exited = false; + while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { + match receive(&peer.receiver, Some(remaining)) { + Ok(Ok(Reply::Drained)) + | Ok(Err(_)) + | Err(mpsc::RecvTimeoutError::Disconnected) => { + exited = true; + break; + } + Ok(Ok(_)) => continue, + Err(mpsc::RecvTimeoutError::Timeout) => break, + } + } + if exited { + if let Some(thread) = peer.thread.take() { + let _ = thread.join(); + } + } + } +} + fn drain_rank( executor: &mut GraphExecutor, started: &mut VecDeque, - send: &impl Fn(Reply) -> Result<()>, + send: &(impl Fn(Reply) -> Result<()> + ?Sized), ) -> Result<()> { drain_outstanding_frames( executor, @@ -1069,41 +1104,69 @@ fn drain_rank( Ok(()) } -fn rank_loop( - peer_index: usize, - executor: &mut GraphExecutor, - commands: mpsc::Receiver, +/// Startup control loop executed by each peer rank before entering `DispatchRing` serving. +/// Returns `Ok(true)` once `Command::FinishStartup` succeeds, or `Ok(false)` on drain/exit. +fn run_startup_phase( + executor: &mut E, + commands: &mpsc::Receiver, replies: &mpsc::Sender>, - ring: &DispatchRing, -) -> Result<()> { + mut run_tuning: impl FnMut(&mut E, usize) -> Result<()>, + mut finish_startup: impl FnMut(&mut E) -> Result<()>, + mut drain: impl FnMut(&mut E, &dyn Fn(Reply) -> Result<()>) -> Result<()>, +) -> Result { let send = |reply| { replies .send(Ok(reply)) .map_err(|_| invalid("rank coordinator disconnected")) }; send(Reply::Initialized)?; - let mut started = VecDeque::with_capacity(2); - // Startup phase: run startup tuning graphs and FinishStartup over the control channel. loop { - match receive(&commands, None) { + match receive(commands, None) { Ok(Command::Tune(index)) => { - let status = executor.run_tuning_graph(index); + let status = run_tuning(executor, index); send(Reply::Tuned(index, status))?; } Ok(Command::FinishStartup) => { - if let Err(error) = executor.finish_startup() { + if let Err(error) = finish_startup(executor) { let _ = replies.send(Err(error)); - return Ok(()); + return Ok(false); } send(Reply::Started)?; - break; + return Ok(true); } Ok(Command::Drain) => { - return drain_rank(executor, &mut started, &send); + drain(executor, &send)?; + return Ok(false); } - Err(_) => return Ok(()), + Err(_) => return Ok(false), } } +} + +fn rank_loop( + peer_index: usize, + executor: &mut GraphExecutor, + commands: mpsc::Receiver, + replies: &mpsc::Sender>, + ring: &DispatchRing, +) -> Result<()> { + let send = |reply| { + replies + .send(Ok(reply)) + .map_err(|_| invalid("rank coordinator disconnected")) + }; + let mut started = VecDeque::with_capacity(2); + // Startup phase: run startup tuning graphs and FinishStartup over the control channel. + if !run_startup_phase( + executor, + &commands, + replies, + |exec, index| exec.run_tuning_graph(index), + |exec| exec.finish_startup(), + |exec, send| drain_rank(exec, &mut started, send), + )? { + return Ok(()); + } // Serving phase: lock-free Prepare -> Ready -> Commit/Cancel step dispatch over DispatchRing. let mut next_epoch = 1u64; loop { @@ -2906,6 +2969,194 @@ mod tests { } } + #[test] + fn close_before_startup_drains_initialized_peers_without_timeout() { + let ring = Arc::new(DispatchRing::new(64, 4)); + let drained_count = Arc::new(AtomicUsize::new(0)); + let mut peers = Vec::new(); + for _ in 0..2 { + let (sender, commands) = mpsc::channel(); + let (replies, receiver) = mpsc::channel(); + let drained = drained_count.clone(); + let peer_ring = ring.clone(); + let thread = thread::spawn(move || { + let _exit_guard = PeerExitGuard(peer_ring); + let mut state = (); + let entered = run_startup_phase( + &mut state, + &commands, + &replies, + |_, _| Ok(()), + |_| Ok(()), + |_, send| { + drained.fetch_add(1, Ordering::SeqCst); + send(Reply::Drained) + }, + ) + .unwrap(); + assert!(!entered); + Shutdown { + drained: true, + error: None, + } + }); + assert!(matches!( + receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Initialized + )); + peers.push(Peer { + sender, + receiver, + thread: Some(thread), + }); + } + let started = Instant::now(); + close_peers(&ring, &mut peers, false, Duration::from_secs(5)).unwrap(); + assert!( + started.elapsed() < Duration::from_secs(1), + "pre-start close should wake peers immediately via Command::Drain" + ); + assert_eq!(drained_count.load(Ordering::SeqCst), 2); + assert!(peers.iter().all(|peer| peer.thread.is_none())); + } + + #[test] + fn best_effort_drain_before_startup_wakes_surviving_peers_after_peer_disconnect() { + let ring = Arc::new(DispatchRing::new(64, 4)); + let drained_count = Arc::new(AtomicUsize::new(0)); + let mut peers = Vec::new(); + + // Peer 0 exits early so its command channel is disconnected before close. + let (dead_sender, dead_commands) = mpsc::channel(); + let (dead_replies, dead_receiver) = mpsc::channel(); + let dead_thread = thread::spawn(move || { + let _ = dead_replies.send(Ok(Reply::Initialized)); + drop(dead_commands); + Shutdown { + drained: true, + error: None, + } + }); + assert!(matches!( + dead_receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Initialized + )); + peers.push(Peer { + sender: dead_sender, + receiver: dead_receiver, + thread: Some(dead_thread), + }); + + // Peer 1 stays blocked in the startup command loop waiting on mpsc. + let (live_sender, live_commands) = mpsc::channel(); + let (live_replies, live_receiver) = mpsc::channel(); + let drained = drained_count.clone(); + let peer_ring = ring.clone(); + let live_thread = thread::spawn(move || { + let _exit_guard = PeerExitGuard(peer_ring); + let mut state = (); + let entered = run_startup_phase( + &mut state, + &live_commands, + &live_replies, + |_, _| Ok(()), + |_| Ok(()), + |_, send| { + drained.fetch_add(1, Ordering::SeqCst); + send(Reply::Drained) + }, + ) + .unwrap(); + assert!(!entered); + Shutdown { + drained: true, + error: None, + } + }); + assert!(matches!( + live_receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Initialized + )); + peers.push(Peer { + sender: live_sender, + receiver: live_receiver, + thread: Some(live_thread), + }); + + // Wait until peer 0 has dropped its receiver so close_peers hits an error on peer 0. + let wait_deadline = Instant::now() + Duration::from_secs(2); + while !matches!( + peers[0].receiver.try_recv(), + Err(mpsc::TryRecvError::Disconnected) + ) { + assert!(Instant::now() < wait_deadline); + thread::yield_now(); + } + + let started = Instant::now(); + assert!(close_peers(&ring, &mut peers, false, Duration::from_secs(5)).is_err()); + best_effort_drain_peers(&ring, &mut peers, false, Duration::from_secs(5)); + assert!( + started.elapsed() < Duration::from_secs(1), + "best-effort pre-start drain should wake surviving peers immediately" + ); + assert_eq!(drained_count.load(Ordering::SeqCst), 1); + assert!(peers.iter().all(|peer| peer.thread.is_none())); + } + + #[test] + fn close_after_startup_drains_serving_peers_through_dispatch_ring() { + let ring = Arc::new(DispatchRing::new(64, 4)); + let mut peers = Vec::new(); + for _ in 0..2 { + let (sender, commands) = mpsc::channel(); + let (replies, receiver) = mpsc::channel(); + let peer_ring = ring.clone(); + let thread = thread::spawn(move || { + let _exit_guard = PeerExitGuard(peer_ring.clone()); + let mut state = (); + let entered = run_startup_phase( + &mut state, + &commands, + &replies, + |_, _| Ok(()), + |_| Ok(()), + |_, send| send(Reply::Drained), + ) + .unwrap(); + assert!(entered); + assert_eq!(peer_ring.wait_next(1), DispatchEvent::Drain); + replies.send(Ok(Reply::Drained)).unwrap(); + Shutdown { + drained: true, + error: None, + } + }); + assert!(matches!( + receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Initialized + )); + peers.push(Peer { + sender, + receiver, + thread: Some(thread), + }); + } + for peer in &peers { + peer.send(Command::FinishStartup).unwrap(); + } + for peer in &peers { + assert!(matches!( + peer.receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Started + )); + } + let started = Instant::now(); + close_peers(&ring, &mut peers, true, Duration::from_secs(5)).unwrap(); + assert!(started.elapsed() < Duration::from_secs(1)); + assert!(peers.iter().all(|peer| peer.thread.is_none())); + } + #[test] fn dispatch_ring_matches_model_edges() { const MAX_EPOCHS: u64 = 3; diff --git a/helios/src/frontend/images/conditioned.rs b/helios/src/frontend/images/conditioned.rs index 704f0d0fb..41a2ed467 100644 --- a/helios/src/frontend/images/conditioned.rs +++ b/helios/src/frontend/images/conditioned.rs @@ -184,12 +184,17 @@ impl PreparedImageInput { fn valid_processed(&self, images: &ProcessedImages) -> bool { use super::Profile; - let pixel_width = match self.processor.profile { - Profile::Qwen(_) | Profile::MiMo(_) => 1536, + let pixel_width = match &self.processor.profile { + Profile::Qwen(profile) => profile.patches.pixel_width(), + Profile::MiMo(profile) => profile.pixel_width(), + Profile::PatchMerge(profile) => profile.patches.pixel_width(), Profile::Radio => 768, Profile::Glm => 1176, Profile::PaddedGrid => super::padded_grid::FEATURES, - _ => 588, + Profile::DeepSeek4 + | Profile::DeepseekRowMajor(_) + | Profile::Moonvit + | Profile::Step => 588, }; let patches = self.geometry.patches; let interpolation = matches!( @@ -329,7 +334,7 @@ mod tests { use super::*; use crate::frontend::images::{ DeepseekRowMajorImageSettings, ImageLimits, ImageSettings, MimoImageSettings, - QwenImageSettings, + PatchMergeImageSettings, QwenImageSettings, }; fn settings() -> Vec { @@ -347,6 +352,16 @@ mod tests { image_mean: [0.5; 3], image_std: [0.5; 3], }), + ImageSettings::PatchMerge(PatchMergeImageSettings { + patch_size: 14, + min_pixels: 3136, + max_pixels: 451584, + image_mean: [0.48145466, 0.4578275, 0.40821073], + image_std: [0.26862954, 0.26130258, 0.27577711], + image_token: "image".into(), + start_token: "start".into(), + end_token: "end".into(), + }), ImageSettings::Deepseek4 {}, ImageSettings::DeepseekRowMajor(DeepseekRowMajorImageSettings { min_pixels: 46656, @@ -356,6 +371,7 @@ mod tests { ImageSettings::Moonvit {}, ImageSettings::Step {}, ImageSettings::Radio {}, + ImageSettings::Glm {}, ImageSettings::PaddedGrid {}, ] } @@ -709,6 +725,43 @@ mod tests { assert_eq!(store.stats().hits, 1); } + #[cfg(feature = "server")] + #[test] + fn patch_merge_materializes_and_caches_with_exact_pixel_width() { + let store = flare_selene::input::InputStore::start( + 64 << 20, + None, + flare_selene::input::DiskBudget::new(0, 0), + ) + .unwrap(); + let processor = processor(ImageSettings::PatchMerge(PatchMergeImageSettings { + patch_size: 14, + min_pixels: 3136, + max_pixels: 451584, + image_mean: [0.48145466, 0.4578275, 0.40821073], + image_std: [0.26862954, 0.26130258, 0.27577711], + image_token: "image".into(), + start_token: "start".into(), + end_token: "end".into(), + })); + let source = image(56, 56, 7); + let description = processor.describe_image(&source).unwrap(); + let patches = description.geometry.patches; + let prepared = input( + processor.clone(), + processor.encoded_source(ImageEncoding::Png, png(&source), None), + description, + ); + let first = prepared.materialize_cached(Some(&store)).unwrap(); + assert_eq!(first.pixel_values.len(), patches * 1176); + assert_eq!(first.pixel_values.capacity(), first.pixel_values.len()); + let cached = processor.preparation_counts(); + let second = prepared.materialize_cached(Some(&store)).unwrap(); + assert_eq!(second.pixel_values, first.pixel_values); + assert_eq!(processor.preparation_counts(), cached); + assert_eq!(store.stats().hits, 1); + } + #[cfg(feature = "server")] #[test] fn cached_tensor_extents_are_validated_before_use() { diff --git a/helios/src/frontend/images/mod.rs b/helios/src/frontend/images/mod.rs index 1882362da..fc9897970 100644 --- a/helios/src/frontend/images/mod.rs +++ b/helios/src/frontend/images/mod.rs @@ -36,6 +36,7 @@ use crate::{Error, Failure, FrontendError, Result}; const PATCH: usize = 16; const MERGE: usize = 2; +#[cfg(test)] const FEATURES: usize = 3 * 2 * PATCH * PATCH; const IMAGE_TOKEN: &str = "<|image_pad|>"; diff --git a/helios/src/frontend/images/patches.rs b/helios/src/frontend/images/patches.rs index a949c8132..a7dae57d1 100644 --- a/helios/src/frontend/images/patches.rs +++ b/helios/src/frontend/images/patches.rs @@ -26,6 +26,10 @@ pub(super) struct PatchProcessor { } impl PatchProcessor { + pub(super) fn pixel_width(&self) -> usize { + 3 * 2 * self.patch_size * self.patch_size + } + pub fn geometry(&self, width: usize, height: usize) -> Result { check_input_extent(self.limits, width, height)?; if width.max(height) as f64 / width.min(height) as f64 > 200.0 { @@ -83,10 +87,11 @@ impl PatchProcessor { Error::frontend(FrontendError::Input(Failure::new("patch count overflow"))) })?; self.limits.check_batch(images.len(), total)?; + let pixel_width = self.pixel_width(); let mut result = ProcessedImages { pixel_values: Vec::with_capacity( total - .checked_mul(3 * 2 * self.patch_size * self.patch_size) + .checked_mul(pixel_width) .ok_or(Error::frontend(FrontendError::Input(Failure::new( "patch buffer extent overflow", ))))?, @@ -97,7 +102,7 @@ impl PatchProcessor { interpolation_weights: Vec::new(), cu_seqlens: vec![0], }; - result.reserve_outputs(total, FEATURES, false, images.len(), images.len() + 1)?; + result.reserve_outputs(total, pixel_width, false, images.len(), images.len() + 1)?; let normalized: [Vec; 3] = std::array::from_fn(|channel| { (0..256) .map(|value| match self.normalization { diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index 864323517..3be68db90 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -1668,6 +1668,16 @@ impl PayloadSource { fn supporting_payload_ids(&self) -> Result>> { let mut ids = std::collections::BTreeSet::new(); for rank in self.authorized.verified().ranks() { + for initializer in &rank.initializers { + let Some(use_) = initializer.source.as_ref() else { + continue; + }; + if use_.role == payload_wire::PayloadRole::InitialState as i32 + && let Some(slice) = use_.slice.as_ref() + { + ids.insert(slice.payload_id.clone()); + } + } for module in &rank.modules { for global in &module.globals { if let Some(slice) = global @@ -3441,12 +3451,31 @@ mod payload_core_tests { format!("initializer rank {rank}").as_bytes(), pw::PayloadRole::Weights, ); + let (state_id, state_len, state_payload) = payload( + &format!("initial-state/rank-{rank}.safetensors"), + format!("initial state rank {rank}").as_bytes(), + pw::PayloadRole::InitialState, + ); let (global_id, global_len, global) = payload( &format!("globals/rank-{rank}.safetensors"), format!("module global rank {rank}").as_bytes(), pw::PayloadRole::InitialState, ); let mut body = rank_body("sm120-tp2", rank, weight_id.as_bytes(), weight_len); + body.allocations.push(pw::Allocation { + name: format!("initial-state-{rank}"), + nbytes: state_len, + alignment: 256, + address: Some(0x10_0000), + memory: 0, + sizing: None, + relocations: vec![], + }); + body.initializers.push(pw::Initializer { + allocation: format!("initial-state-{rank}"), + destination_offset: 0, + source: Some(use_of(state_id, state_len, pw::PayloadRole::InitialState)), + }); body.modules[0].globals.push(pw::ModuleGlobal { symbol: format!("global_{rank}"), contents: Some(use_of(global_id, global_len, pw::PayloadRole::InitialState)), @@ -3455,7 +3484,7 @@ mod payload_core_tests { }); ranks.push(PublishRank { body, - payloads: vec![weight, global], + payloads: vec![weight, state_payload, global], resources: resources(), }); } @@ -3748,7 +3777,7 @@ mod payload_core_tests { #[test] fn payload_stored_data_hashes_every_selected_role_and_respects_rank_scope() { use crate::core::reader::Metadata; - for role in ["frontend", "global", "engram", "executable"] { + for role in ["frontend", "global", "initial-state", "engram", "executable"] { let (root, publishers) = engram_core(); let baseline = VerifiedCore::open_tensor_parallel(&root, &publishers, 2, None).unwrap(); @@ -3758,6 +3787,7 @@ mod payload_core_tests { let needle = match role { "frontend" => "assets/tokenizer", "global" => "globals/rank-0", + "initial-state" => "initial-state/rank-0", "engram" => "engram/shared-weights", "executable" => "deployments/sm120-tp2/rank-0/graphs", _ => unreachable!(), @@ -3813,6 +3843,7 @@ mod payload_core_tests { for (name, optional) in [ ("frontend.tokenizer", false), ("globals/rank-1", false), + ("initial-state/rank-1", false), ("engram/shared-weights", true), ("engram/shared-scales", true), ("engram/shard-1-weights", true), @@ -3845,7 +3876,12 @@ mod payload_core_tests { } let (root, publishers) = engram_core(); - for name in ["globals/rank-0", "engram/shard-0-weights", "weights/rank-0"] { + for name in [ + "globals/rank-0", + "initial-state/rank-0", + "engram/shard-0-weights", + "weights/rank-0", + ] { let metadata = payload_reader::Metadata::open(&root).unwrap(); let location = metadata.locations.locations.iter().find(|location| location.file.contains(name)).unwrap(); corrupt_payload_companion(&root.join(&location.file)); @@ -3887,6 +3923,7 @@ mod payload_core_tests { "{names:?}" ); assert!(names.contains(&"weights/rank-1.safetensors"), "{names:?}"); + assert!(names.contains(&"initial-state/rank-1.safetensors"), "{names:?}"); assert!(names.contains(&"globals/rank-1.safetensors"), "{names:?}"); let ranks = payload.source.authorized.verified().ranks(); let metadata = crate::core::reader::Metadata::open(&root).unwrap(); @@ -3899,6 +3936,7 @@ mod payload_core_tests { assert!(names.contains(&location.file.as_str()), "{names:?}"); } assert!(!names.contains(&"weights/rank-0.safetensors"), "{names:?}"); + assert!(!names.contains(&"initial-state/rank-0.safetensors"), "{names:?}"); assert!(!names.contains(&"globals/rank-0.safetensors"), "{names:?}"); let _ = std::fs::remove_dir_all(root); } diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 745cc0805..b017f962d 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -1261,6 +1261,15 @@ impl<'a> Worker<'a> { } } + fn clear_active_slot(&mut self, slot: usize) -> Option> { + clear_active_entry( + &mut self.active, + &mut self.admissions, + &mut self.preparing_image, + slot, + ) + } + fn complete_image_preparation(&mut self) -> Result { let mut progress = false; loop { @@ -1280,7 +1289,9 @@ impl<'a> Worker<'a> { .as_mut() .filter(|active| active.request == handle) else { - self.preparing_image = None; + if self.preparing_image == Some(handle) { + self.preparing_image = None; + } continue; }; match prepared { @@ -1294,8 +1305,7 @@ impl<'a> Worker<'a> { Err(error) => { self.preparing_image = None; self.scheduler.cancel(handle)?; - let active = self.active[slot].take().unwrap(); - self.admissions[slot] = None; + let active = self.clear_active_slot(slot).unwrap(); active.incoming.fail(error); } } @@ -1342,10 +1352,7 @@ impl<'a> Worker<'a> { .as_ref() .is_some_and(|a| a.incoming.cancelled.load(Ordering::Acquire)) { - let active = self.active[slot].take().unwrap(); - if active.prepared_image.is_some() { - self.preparing_image = None; - } + let active = self.clear_active_slot(slot).unwrap(); let live = self.scheduler.request(active.request)?; active.incoming.finish_cancelled(Carried { prompt_tokens: Some(active.carried.prompt_tokens.unwrap_or(live.prompt_tokens)), @@ -1355,7 +1362,6 @@ impl<'a> Worker<'a> { }); self.scheduler.cancel(active.request)?; self.metrics.cancelled.fetch_add(1, Ordering::Relaxed); - self.admissions[slot] = None; progress = true; } } @@ -1940,9 +1946,9 @@ impl<'a> Worker<'a> { continue; } if abandon { - self.scheduler.cancel(request.request)?; - self.active[slot] = None; - self.admissions[slot] = None; + let handle = request.request; + self.scheduler.cancel(handle)?; + self.clear_active_slot(slot); progress = true; continue; } @@ -1970,10 +1976,10 @@ impl<'a> Worker<'a> { matched } Err(error) => { + let handle = request.request; request.incoming.fail(error); - self.scheduler.cancel(request.request)?; - self.active[slot] = None; - self.admissions[slot] = None; + self.scheduler.cancel(handle)?; + self.clear_active_slot(slot); progress = true; continue; } @@ -2021,16 +2027,16 @@ impl<'a> Worker<'a> { }, }); if user_stop { - self.scheduler.cancel(request.request)?; - self.active[slot] = None; - self.admissions[slot] = None; + let handle = request.request; + self.scheduler.cancel(handle)?; + self.clear_active_slot(slot); progress = true; continue; } } - self.scheduler.finish(request.request)?; - self.active[slot] = None; - self.admissions[slot] = None; + let handle = request.request; + self.scheduler.finish(handle)?; + self.clear_active_slot(slot); progress = true; } } @@ -2077,8 +2083,7 @@ impl<'a> Worker<'a> { ); let checkpoint_accounting = live.checkpoint_accounting(); self.scheduler.finish(handle)?; - let active = self.active[slot].take().unwrap(); - self.admissions[slot] = None; + let active = self.clear_active_slot(slot).unwrap(); let mut incoming = active.incoming; crate::model::prompt_metadata(&mut incoming.prompt.data) .extend_text(incoming.prompt.tokens.len(), tokens.len())?; @@ -2114,6 +2119,7 @@ impl<'a> Worker<'a> { &mut self.scheduler, &mut self.active, &mut self.admissions, + &mut self.preparing_image, ) } @@ -2152,6 +2158,7 @@ impl<'a> Worker<'a> { .scheduler .set_copy_proposal(request.request, proposal)?, Err(error) => { + let handle = request.request; request.incoming.fail( ExecutionError::State(Failure::caused_by( format!("copy grammar preparation failed: {error}"), @@ -2159,9 +2166,8 @@ impl<'a> Worker<'a> { )) .into(), ); - self.scheduler.cancel(request.request)?; - self.active[slot] = None; - self.admissions[slot] = None; + self.scheduler.cancel(handle)?; + self.clear_active_slot(slot); progress = true; } } @@ -2580,13 +2586,13 @@ impl<'a> Worker<'a> { /// Return a retired request to the front of the queue for another admission. fn requeue(&mut self, handle: RequestHandle, host_lookup: bool) { let slot = handle.slot as usize; - let Some(active) = self.active[slot].take_if(|active| active.request == handle) else { + if !self.active[slot] + .as_ref() + .is_some_and(|active| active.request == handle) + { return; - }; - self.admissions[slot] = None; - if active.prepared_image.is_some() { - self.preparing_image = None; } + let active = self.clear_active_slot(slot).unwrap(); let mut incoming = active.incoming; incoming.host_lookup = host_lookup; if !host_lookup { @@ -2835,11 +2841,30 @@ fn admit_with_host_store( result } +fn clear_active_entry<'a>( + active: &mut [Option>], + admissions: &mut [Option], + preparing_image: &mut Option, + slot: usize, +) -> Option> { + admissions[slot] = None; + let removed = active[slot].take()?; + // When the worker already delivered `prepared_image`, no reply remains in flight to + // clear `preparing_image`, so releasing the slot must release the global preparation slot. + // When `prepared_image` is `None`, any in-flight worker reply clears `preparing_image` + // once drained by `complete_image_preparation`. + if removed.prepared_image.is_some() { + *preparing_image = None; + } + Some(removed) +} + fn cancel_stopped( stopped: &[RequestHandle], scheduler: &mut RequestScheduler, active: &mut [Option>], admissions: &mut [Option], + preparing_image: &mut Option, ) -> Result<()> { for (index, &handle) in stopped.iter().enumerate() { // Several tokens from one completion can encounter the same poisoned grammar. @@ -2847,8 +2872,7 @@ fn cancel_stopped( continue; } scheduler.cancel(handle)?; - active[handle.slot as usize] = None; - admissions[handle.slot as usize] = None; + clear_active_entry(active, admissions, preparing_image, handle.slot as usize); } Ok(()) } @@ -3578,7 +3602,18 @@ mod tests { } assert_eq!(stopped, [failed; 3]); assert_eq!(failure_metrics.failed.load(Ordering::Relaxed), 1); - cancel_stopped(&stopped, &mut scheduler, &mut active, &mut admissions).unwrap(); + let mut preparing_image = Some(failed); + active[failed.slot as usize].as_mut().unwrap().prepared_image = + Some(crate::frontend::images::ProcessedImages::default()); + cancel_stopped( + &stopped, + &mut scheduler, + &mut active, + &mut admissions, + &mut preparing_image, + ) + .unwrap(); + assert_eq!(preparing_image, None); assert!(scheduler.request(failed).is_err()); assert!(active[failed.slot as usize].is_none()); assert!(admissions[failed.slot as usize].is_none()); @@ -3637,6 +3672,7 @@ mod tests { &mut scheduler, &mut active, &mut admissions, + &mut None, ) .unwrap(); assert_eq!(scheduler.stats().retiring_slots, 1); @@ -3680,6 +3716,7 @@ mod tests { &mut scheduler, &mut active, &mut admissions, + &mut None, ) .unwrap_err(); assert!(matches!(error, Error::Execution(ExecutionError::State(_)))); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 5aa313c40..e8e539713 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5638,6 +5638,200 @@ fn prepared_image_window_stays_global_until_pack_or_cancellation() { ); } +#[test] +fn park_and_device_error_teardown_release_prepared_image_slot_for_next_request() { + use crate::frontend::images::{ + ImageInput, ImageLimits, ImageProcessor, ImageSettings, ImageSource, PreparedImageInput, + RgbImage, + }; + let make_worker = || { + let mut fixture = Fixture::new(); + fixture.config.contract.vision = crate::model::VisionCapabilities { + feature_slots: 2, + features_per_request: 64, + max_images: 4, + patches_per_feature: 4, + patch_capacities: vec![256], + }; + fixture.config.contract.frontend = serde_json::from_str::( + include_str!("../../../tests/support/contracts/qwen38.json"), + ) + .unwrap() + .frontend; + let processor = Arc::new( + ImageProcessor::load(ImageSettings::Moonvit {}, ImageLimits::default()).unwrap(), + ); + let pixels = Arc::new(RgbImage::new(112, 112, vec![42; 112 * 112 * 3]).unwrap()); + let descriptor = PreparedImageInput::new( + ImageInput { + description: processor.describe_image(&pixels).unwrap(), + source: ImageSource::Decoded(pixels), + }, + 10..26, + 0..16, + processor.clone(), + ); + (fixture, processor, descriptor) + }; + + // Case 1: parking an active request that already holds `prepared_image` must release + // `worker.preparing_image` so the second multimodal request proceeds. + let (fixture, processor, descriptor) = make_worker(); + let (sender, receiver) = mpsc::channel(); + let (mut first, _first_generation) = fixture.incoming(vec![0; 30], 4); + first.prompt.conditioned_inputs = vec![descriptor.clone()]; + let (mut second, _second_generation) = fixture.incoming(vec![1; 30], 4); + second.prompt.conditioned_inputs = vec![descriptor.clone()]; + sender.send(vec![first, second]).unwrap(); + let mut worker = fixture.worker(receiver); + worker.image_preparation = Some(ImagePreparation::new(None)); + let _ = worker.admit().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while worker.active[0].as_ref().unwrap().prepared_image.is_none() { + assert!(std::time::Instant::now() < deadline); + let _ = worker.admit().unwrap(); + std::thread::yield_now(); + } + let first_handle = worker.active[0].as_ref().unwrap().request; + let second_handle = worker.active[1].as_ref().unwrap().request; + assert_eq!(worker.preparing_image, Some(first_handle)); + assert!(worker.active[1].as_ref().unwrap().prepared_image.is_none()); + + // Move slot 0 into Finishing via a completed Init step so `worker.park` executes cleanly + // while `active[0].prepared_image` is populated. + let step = worker.scheduler.plan().unwrap(); + assert_eq!(step.kind, GraphKind::Init); + assert!(step.lanes.iter().any(|lane| lane.request == first_handle)); + worker.scheduler.commit(&step, Fence(1)).unwrap(); + let mut records = vec![CompletionRecord::default(); 4]; + for lane in &step.lanes { + records[lane.request.slot as usize] = CompletionRecord { + generation: lane.request.generation as i64, + submission_sequence: 1, + token_id: -1, + status: if lane.request == first_handle { 3 } else { 1 }, + error_code: if lane.request == first_handle { 1 } else { 0 }, + ..Default::default() + }; + } + worker + .scheduler + .complete(Fence(1), &records, Default::default()) + .unwrap(); + + worker.park(0, &[], 4).unwrap(); + assert!(worker.active[0].is_none()); + assert!(worker.admissions[0].is_none()); + assert_eq!(worker.preparing_image, None); + + while worker.active[1].as_ref().unwrap().prepared_image.is_none() { + assert!( + std::time::Instant::now() < deadline, + "second VLM request deadlocked after park()" + ); + let _ = worker.admit().unwrap(); + std::thread::yield_now(); + } + assert_eq!(worker.preparing_image, Some(second_handle)); + assert_eq!(processor.preparation_counts().prepared_images, 2); + + // Case 2: device error teardown in `publish()` while holding `prepared_image` must + // release `worker.preparing_image` so the second multimodal request proceeds. + let (fixture, processor, descriptor) = make_worker(); + let (sender, receiver) = mpsc::channel(); + let (mut first, mut first_generation) = fixture.incoming(vec![0; 30], 4); + first.prompt.conditioned_inputs = vec![descriptor.clone()]; + let (mut second, _second_generation) = fixture.incoming(vec![1; 30], 4); + second.prompt.conditioned_inputs = vec![descriptor]; + sender.send(vec![first, second]).unwrap(); + let mut worker = fixture.worker(receiver); + worker.image_preparation = Some(ImagePreparation::new(None)); + let _ = worker.admit().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while worker.active[0].as_ref().unwrap().prepared_image.is_none() { + assert!(std::time::Instant::now() < deadline); + let _ = worker.admit().unwrap(); + std::thread::yield_now(); + } + let first_handle = worker.active[0].as_ref().unwrap().request; + let second_handle = worker.active[1].as_ref().unwrap().request; + assert_eq!(worker.preparing_image, Some(first_handle)); + + // Drive an Initialize step for slot 0 that completes with a device error (status = 3). + let step = worker.scheduler.plan().unwrap(); + assert_eq!(step.kind, GraphKind::Init); + assert!(step.lanes.iter().any(|lane| lane.request == first_handle)); + worker.scheduler.commit(&step, Fence(1)).unwrap(); + let mut records = vec![CompletionRecord::default(); 4]; + for lane in &step.lanes { + records[lane.request.slot as usize] = CompletionRecord { + generation: lane.request.generation as i64, + submission_sequence: 1, + token_id: -1, + status: if lane.request == first_handle { 3 } else { 1 }, + error_code: if lane.request == first_handle { 77 } else { 0 }, + ..Default::default() + }; + } + worker + .scheduler + .complete(Fence(1), &records, Default::default()) + .unwrap(); + assert!(worker.publish().unwrap()); + assert!(worker.active[0].is_none()); + assert!(worker.admissions[0].is_none()); + assert_eq!(worker.preparing_image, None); + assert!(matches!( + first_generation.events.try_recv().unwrap(), + GenerationEvent::Error(Error::Execution(ExecutionError::Device { code: 77 })) + )); + + while worker.active[1].as_ref().unwrap().prepared_image.is_none() { + assert!( + std::time::Instant::now() < deadline, + "second VLM request deadlocked after publish() error teardown" + ); + let _ = worker.admit().unwrap(); + std::thread::yield_now(); + } + assert_eq!(worker.preparing_image, Some(second_handle)); + assert_eq!(processor.preparation_counts().prepared_images, 2); +} + +#[test] +fn clear_active_slot_retains_in_flight_preparing_image_until_stale_reply_arrives() { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let (incoming, _generation) = fixture.incoming(vec![0; 8], 4); + sender.send(vec![incoming]).unwrap(); + let mut worker = fixture.worker(receiver); + let _ = worker.admit().unwrap(); + let handle = worker.active[0].as_ref().unwrap().request; + let (_job_tx, _job_rx) = mpsc::sync_channel::(1); + let (res_tx, res_rx) = mpsc::sync_channel::(1); + worker.image_preparation = Some(ImagePreparation { + sender: Some(_job_tx), + receiver: Some(res_rx), + stop: Arc::new(AtomicBool::new(false)), + thread: None, + }); + // Simulate a job currently in flight on the background thread (prepared_image is None). + worker.preparing_image = Some(handle); + assert!(worker.active[0].as_ref().unwrap().prepared_image.is_none()); + worker.clear_active_slot(0); + assert_eq!(worker.preparing_image, Some(handle)); + + // When the stale reply finally arrives, complete_image_preparation clears preparing_image. + res_tx + .send(( + handle, + Ok(Some(crate::frontend::images::ProcessedImages::default())), + )) + .unwrap(); + worker.complete_image_preparation().unwrap(); + assert_eq!(worker.preparing_image, None); +} + #[test] fn worker_restores_conditioned_windows_with_fresh_generation_and_unchanged_sampling() { use crate::execution::{BufferDescriptor, Dtype, GraphDescriptor, InputBinding, SamplingMode}; From a54a8b8a8590b2a0b5e4fa0226fc8c36025e8010 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 28 Nov 2026 12:25:28 -0800 Subject: [PATCH 02/27] Bound multimodal decoded-source retention by patch capacity On integrated GPUs, Helios reserves host-side multimodal buffers (`input_window + source_window`) from the shared memory budget before sizing KV and continuation cache pages in `helios/src/runtime_core/memory.rs`. Previously, `ImageLimits::source_retention_bytes()` returned `max_input_pixels * 8` (`512 MiB` under the default 64M-pixel ceiling) regardless of a model's declared patch capacity, and `memory.rs` queried `ImageLimits::default()` instead of the model's `VisionCapabilities`. That buffer only caches decoded pixels opportunistically between HTTP prompt admission and vision preprocessing; images outside the retention budget are re-decoded on demand from their compressed bytes during `ImageProcessor::materialize()`. Reserving a flat `512 MiB` withholds `448-496 MiB` of unified memory from KV pages on memory-constrained integrated GPUs without changing admission limits or decoding semantics. Three files changed to derive decoded-source retention from the model's vision contract in one place: - `helios/src/frontend/images/mod.rs`: added `ImageLimits::for_vision(vision, context_tokens)` and bounded `ImageLimits::source_retention_bytes()` to `(max_input_pixels * 8).min((max_patches_per_image * 4096).clamp(16 MiB, 64 MiB))`. Admission limits (`max_input_pixels`, `max_images`, `max_patches_per_image`, and `max_total_patches`) are unchanged. - `helios/src/server/config.rs`: delegated `image_limits()` to `ImageLimits::for_vision()` and verified `source_retention_bytes()` and `ImageProcessor::preparation_counts().decoded_source_capacity` in `image_limits_follow_graph_and_feature_storage_capacities`. - `helios/src/runtime_core/memory.rs`: replaced `ImageLimits::default().source_retention_bytes()?` with `ImageLimits::for_vision(&contract.vision, context_tokens)?.source_retention_bytes()?` when `contract.vision.enabled()` is true so unified-memory sizing matches the runtime retention cap enforced by `ImageProcessor::load`. Multimodal models now cap both decoded-source retention and the integrated-GPU `source_window` reservation at `16 MiB` for `4,096`-patch models up to `64 MiB` for models with at least `16,384` patches, down from `512 MiB`. On integrated GPUs, this is expected to reclaim `448-496 MiB` of unified memory for KV and state pages. Text-only models and discrete-GPU VRAM sizing (`rank.integrated == false`) are unaffected. On all platforms, concurrent bursts whose queued uncompressed pixels exceed `64 MiB` before preprocessing incur an on-demand CPU re-decode from compressed bytes instead of remaining cached up to `512 MiB`. Validation: - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target -- images:: server::config:: runtime_core::memory::` passed (`61 passed, 0 failed, 1 ignored` GPU-only `cuda_memory_limits_account_for_context_and_allocations`) on x86_64 and ARM64 (Jetson AGX Orin). - Full `helios` lib tests (`1,649 passed`), `flare` unit and integration tests (`226 + 2 retried single-threaded + 8 integration passed`), and `flare-cli` unit tests (`195 passed`) ran on x86_64; unrelated failures occurred in `model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape`, `6` `helios` lib and `3` `message_boundaries` tests requiring `FLARE_TEST_TEMPLATE_DIR`, and `2` `flare-cli` distribution/lease tests (`source_waits_for_receiver_file_verification` and `actual_load_core_leases_managed_local_entries_and_releases_on_failure`). - Live `flare run` on Jetson AGX Orin (`SM87`) with a `4,096`-patch multimodal core exposed `flare_input_decoded_source_capacity = 16777216` (`16 MiB`). Discrete-GPU high-concurrency multimodal burst re-decode overhead and `FLARE_TEST_TEMPLATE_DIR` template tests were not run. Design-Signed-Off-By: Antigravity (Gemini); design-review=c3a9 Signed-off-by: Luke Alonso --- helios/src/frontend/images/mod.rs | 46 +++++++++++++++++++++++++++++-- helios/src/runtime_core/memory.rs | 5 ++++ helios/src/server/config.rs | 26 +++-------------- 3 files changed, 53 insertions(+), 24 deletions(-) diff --git a/helios/src/frontend/images/mod.rs b/helios/src/frontend/images/mod.rs index fc9897970..03925031e 100644 --- a/helios/src/frontend/images/mod.rs +++ b/helios/src/frontend/images/mod.rs @@ -39,6 +39,12 @@ const MERGE: usize = 2; #[cfg(test)] const FEATURES: usize = 3 * 2 * PATCH * PATCH; const IMAGE_TOKEN: &str = "<|image_pad|>"; +/// Upper bound on opportunistically retained decoded source images between request +/// admission and vision preprocessing. Images that exceed the remaining budget are +/// re-decoded from their encoded bytes on demand during preprocessing. +const MAX_SOURCE_RETENTION_BYTES: u64 = 64 << 20; +const MIN_SOURCE_RETENTION_BYTES: u64 = 16 << 20; +const SOURCE_RETENTION_BYTES_PER_PATCH: u64 = 4096; /// Admission limits for one request's images. Patch counts are the encoder's unit; /// `patches_per_feature` patches merge into one image token, the unit that the model card @@ -78,14 +84,50 @@ pub struct ImageOverrun { } impl ImageLimits { + /// Derive admission and decoded-source retention limits from a model's declared vision contract. + pub fn for_vision(vision: &crate::model::VisionCapabilities, context_tokens: usize) -> Result { + let live_patches = vision + .features_per_request + .checked_mul(vision.patches_per_feature) + .ok_or("prepared image patch capacity overflow")?; + let max_patches_per_image = vision + .patch_capacities + .last() + .copied() + .ok_or("vision requires a captured patch capacity")? + .min(live_patches); + let max_total_patches = context_tokens + .checked_mul(vision.patches_per_feature) + .ok_or("image context patch capacity overflow")?; + if context_tokens == 0 || context_tokens > i32::MAX as usize { + return Err("image context capacity must fit positive int32 indices".into()); + } + Ok(Self { + max_images: context_tokens, + max_patches_per_image, + max_total_patches, + patches_per_feature: vision.patches_per_feature, + ..Self::default() + }) + } + /// Image tokens for `patches`, rounding partial features up. pub fn tokens(&self, patches: usize) -> usize { patches.div_ceil(self.patches_per_feature.max(1)) } + /// Soft byte cap for decoded source images retained between prompt admission and preprocessing. + /// + /// Scales with `max_patches_per_image` within `[16 MiB, 64 MiB]` and never exceeds the + /// single-image decoder limit `max_input_pixels * 8`. pub fn source_retention_bytes(&self) -> Result { - (self.max_input_pixels as u64).checked_mul(8) - .ok_or_else(|| "decoded image source capacity overflows".into()) + let decode_limit = (self.max_input_pixels as u64) + .checked_mul(8) + .ok_or_else(|| "decoded image source capacity overflows")?; + let patch_budget = (self.max_patches_per_image as u64) + .saturating_mul(SOURCE_RETENTION_BYTES_PER_PATCH) + .clamp(MIN_SOURCE_RETENTION_BYTES, MAX_SOURCE_RETENTION_BYTES); + Ok(decode_limit.min(patch_budget)) } pub fn max_image_tokens_per_prompt(&self) -> usize { diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index 1c20aef85..ac5d22b6f 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -783,6 +783,11 @@ impl NativeModel { #[cfg(feature = "images")] let source_window = if input_window == 0 { 0 + } else if contract.vision.enabled() { + let context_tokens = usize::try_from(context) + .map_err(|_| invalid("prepared context ceiling exceeds usize"))?; + crate::frontend::images::ImageLimits::for_vision(&contract.vision, context_tokens)? + .source_retention_bytes()? } else { crate::frontend::images::ImageLimits::default().source_retention_bytes()? }; diff --git a/helios/src/server/config.rs b/helios/src/server/config.rs index ffd22c6bc..ab76fa86b 100644 --- a/helios/src/server/config.rs +++ b/helios/src/server/config.rs @@ -439,28 +439,7 @@ impl ServerConfig { } pub(crate) fn image_limits(vision: &crate::model::VisionCapabilities, context_tokens: usize) -> Result { - let live_patches = vision - .features_per_request - .checked_mul(vision.patches_per_feature) - .ok_or("prepared image patch capacity overflow")?; - let max_patches_per_image = vision - .patch_capacities - .last() - .copied() - .ok_or("vision requires a captured patch capacity")? - .min(live_patches); - let max_total_patches = context_tokens.checked_mul(vision.patches_per_feature) - .ok_or("image context patch capacity overflow")?; - if context_tokens == 0 || context_tokens > i32::MAX as usize { - return Err("image context capacity must fit positive int32 indices".into()); - } - Ok(ImageLimits { - max_images: context_tokens, - max_patches_per_image, - max_total_patches, - patches_per_feature: vision.patches_per_feature, - ..ImageLimits::default() - }) + ImageLimits::for_vision(vision, context_tokens) } #[cfg(test)] @@ -491,7 +470,10 @@ mod tests { assert_eq!(limits.patches_per_feature, merge); assert_eq!(limits.max_image_tokens_per_prompt(), features * 3); assert_eq!(limits.max_image_tokens_per_image(), graph_patches.min(total) / merge); + let expected_retention = ((graph_patches.min(total) as u64) * 4096).clamp(16 << 20, 64 << 20); + assert_eq!(limits.source_retention_bytes().unwrap(), expected_retention); let processor = ImageProcessor::load(ImageSettings::Moonvit {}, limits).unwrap(); + assert_eq!(processor.preparation_counts().decoded_source_capacity, expected_retention); let geometry = processor.geometry(3584, 3584); if graph_patches == 65536 { let geometry = geometry.unwrap(); From 2bdc8472e492ad392cc795563d5b0f8db47a5a25 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 28 Nov 2026 13:17:39 -0800 Subject: [PATCH 03/27] helios: tolerate omitted closing tags on complete tagged tool calls at EOS (#573) * helios: tolerate omitted closing tags on complete tagged tool calls at EOS Models using tagged tool-call syntaxes occasionally finish a complete, self-delimited argument payload and terminate with natural end-of-sequence (EOS) without emitting the final closing wrapper tag (such as `` in GLM argument-tag calls, `` in Qwen/MiMo function tags, `` in Gemma 4 calls, or `` in MiniMax XML). Previously `TaggedTools::finish` rejected every unclosed call at `Termination::Eos` unconditionally, failing the entire request even when all arguments were closed and unambiguous. Before this change, `TaggedTools::finish(Termination::Eos)` always returned an incomplete-call error, `TaggedOutput::finish` did not increment `self.calls` for tool calls emitted on finish, and `TaggedOutput` always set `outer_tool_pending = D::FUNCTION.is_some()` after closing a tool even when `D::CLOSE` had already been consumed. This change adds a shared `ToolDialect::parse_eos(body, tools)` hook with no per-model boolean flags and wires EOS recovery across all tagged dialects: - `helios/src/output/tagged.rs`: Tracks whether `TaggedTools` entered `Mode::Tool` from a confirmed opener (`confirmed`) rather than an undecided tag promoted during `finish()`, tracks `outer_closed` so `outer_tool_pending` is only set when the inner closer ended the call, rejects unconfirmed calls and unfinished JSON strings on `Termination::Eos`, delegates confirmed EOS bodies to `D::parse_eos`, and advances `TaggedOutput.calls` when `finish()` emits `ToolBegin` events. - `helios/src/output/argument_tags.rs`: Implements `ArgumentTags::parse_eos` requiring a valid function name (no `<`, `>`, or whitespace), at least one closed `......` pair, no trailing non-whitespace, and a non-strict tool. - `helios/src/output/chatml.rs`: Implements `FunctionTags::parse_eos` and allows `parse_candidate` to close non-strict calls missing `` at `` or EOS when at least one closed `...` is present with no trailing non-whitespace. - `helios/src/output/gemma_call.rs`: Implements `GemmaCall::parse_eos` for non-strict brace-balanced `call:name{...}` payloads (including explicit `{}`) with no trailing non-whitespace. - `helios/src/output/minimax_xml.rs`: Implements `MiniMaxXml::parse_eos` and allows `parse_candidate` to close non-strict invocations missing `` at `` or EOS when at least one closed parameter element is present with no trailing unclosed elements or text. - `helios/src/output/pipeline.rs`: Implements `PlainText::parse_eos` returning the existing unconfigured-parser error. - `docs/api.md`: Documents the natural-completion recovery rules and the rejected/omitted cases. Bare headers without a closing argument delimiter (such as `run` or ``), undecided openers, partial arguments, trailing non-whitespace, `strict: true` calls missing their wire closer, and all non-EOS terminations (`OutputLimit`, `UserStop`, `Cancelled`, `ExecutionError`) remain rejected or omitted. Verified with Helios unit tests across all tagged dialects, protocol encoder tests across Chat/Messages/Responses (buffered and streamed), logprob and reasoning-token accounting tests, and DeepSeek output tests. Design-Signed-Off-By: Luke Alonso ; design-review=c3a9 Signed-off-by: Luke Alonso * helios: add Kani proofs and mutation-driven tests for tagged tool parsing Tagged tool-call framing relies on sequential invariants that example tests alone do not exhaustively establish: `partial_marker` must return the exact longest proper prefix on a UTF-8 char boundary, `select_candidate` must pick the earliest closing tag without overflow and track `outer_closed`, and `TaggedTools::eos_decision` must omit non-EOS terminations and reject unconfirmed or mid-JSON-string EOS states. Mutation testing against the EOS recovery diff also surfaced 16 untested boundary paths across the tagged dialects. Before this change, `cargo kani` covered only `execution/transport.rs`, `model.rs`, and `model/contract.rs` under default features, and `helios/src/output/` had no Kani proofs or mutation-calibrated boundary tests for `starts_call` prefix monotonicity, `<`/`>` in GLM `ToolBody` names, `in_json_string` at EOS, `outer_tool_pending` after `outer_closed`, bare `` in `parse_eos`, `TaggedOutput.calls` post-finish, or multi-call `emit_calls` indexing. This change adds four Kani proofs in `helios/src/output/tagged/kani_proofs.rs`, enables them in CI under `cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib`, and closes the mutation-testing gaps: - `helios/src/output/tagged.rs` and `helios/src/output/tagged/kani_proofs.rs`: Extracts `TaggedTools::eos_decision` and `select_candidate`, simplifies `partial_marker` from a nested iterator chain to an explicit reverse byte scan preserving UTF-8 char boundaries, and adds four Kani harnesses (`partial_marker_ascii_matches_oracle`, `partial_marker_utf8_preserves_char_boundaries`, `tagged_tools_eos_decision_enforces_termination_and_confirmation`, and `select_candidate_picks_earliest_closer_and_tracks_outer_closed`) with `kani::cover!` reachability checks. - `helios/src/lib.rs`, `.github/workflows/helios-lifecycle.yml`, and `verification/helios-lifecycle/README.md`: Gates `pub mod output` on `any(feature = "server", all(kani, feature = "runtime-core"))`, runs CI Kani with `--features runtime-core`, and documents the four proofs and their domains and limits. - `helios/src/output/{tagged,argument_tags,chatml,pipeline}.rs`: Adds exhaustive prefix-monotonicity tests for `ArgumentTags::starts_call` and `FunctionTags::starts_call` (plus `possible_parameter_start` prefix completeness) and targeted unit tests killing all 16 real surviving mutants. Verified with `cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib` (11/11 harnesses passing, 0 failures), `cargo-mutants` across all 168 mutants in the `helios/src/output/` diff (157 caught, 7 unviable, 2 timeouts on infinite-loop mutations, 2 mathematically equivalent survivors), and release Helios unit/protocol/logprob/grammar/DeepSeek tests (206 + 14 passing). Design-Signed-Off-By: Luke Alonso ; design-review=c3a9 Signed-off-by: Luke Alonso --------- Signed-off-by: Luke Alonso --- .github/workflows/helios-lifecycle.yml | 2 +- docs/api.md | 18 +- helios/src/lib.rs | 3 +- helios/src/output/argument_tags.rs | 352 +++++++++++++++++++++++- helios/src/output/chatml.rs | 313 ++++++++++++++++++++- helios/src/output/gemma_call.rs | 140 +++++++++- helios/src/output/minimax_xml.rs | 182 +++++++++++- helios/src/output/pipeline.rs | 111 ++++++++ helios/src/output/tagged.rs | 254 +++++++++++++---- helios/src/output/tagged/kani_proofs.rs | 176 ++++++++++++ helios/src/server/logprobs.rs | 101 +++++++ helios/src/server/protocol/tests.rs | 348 +++++++++++++++++++++++ verification/helios-lifecycle/README.md | 41 ++- 13 files changed, 1937 insertions(+), 104 deletions(-) create mode 100644 helios/src/output/tagged/kani_proofs.rs diff --git a/.github/workflows/helios-lifecycle.yml b/.github/workflows/helios-lifecycle.yml index 8e965febf..2b97e47e6 100644 --- a/.github/workflows/helios-lifecycle.yml +++ b/.github/workflows/helios-lifecycle.yml @@ -44,4 +44,4 @@ jobs: - name: Set up Kani compiler run: cargo kani setup - name: Prove sequential validator properties - run: cargo kani --manifest-path helios/Cargo.toml --lib + run: cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib diff --git a/docs/api.md b/docs/api.md index 1f953b407..4704c8c34 100644 --- a/docs/api.md +++ b/docs/api.md @@ -444,7 +444,11 @@ the same accumulated output for buffered responses and SSE. Tool arguments are JSON objects, bounded to 8 MiB. The model parsers buffer tool envelopes until they are complete, so argument events do not imply incremental generation of an unfinished call. Truncated tool envelopes are omitted and the response reports -its output limit; recognized but incomplete calls at natural completion are errors. +its output limit. At natural completion, tagged tool parsers accept a non-strict +call whose inner arguments are structurally complete and self-delimited when +only its closing wrapper tag is omitted; undecided openers, bare headers +without a closing argument delimiter, unclosed arguments, trailing text, and +unclosed strict calls remain errors. DeepSeek reasoning and both DSML tool syntaxes use the pinned official `deepseek-recipe` state machine. Helios adapts its actions into the same neutral @@ -507,6 +511,18 @@ Gemma 4's `<|tool_call>` opener and MiniMax's namespace-prefixed opener always start a call; they do not take part in this check. DeepSeek DSML and XTML are parsed by their own parsers rather than this path. A missing `` is closed by the next parameter or function boundary. +When a non-strict tagged call omits its closing wrapper tag at natural +completion, each dialect accepts it only when its argument body is +self-delimited with no trailing non-whitespace: GLM requires at least one closed +`......` pair without ``, +function-tag parsers require at least one closed `...` +without `` (also accepted when closed by ``), Gemma 4 +requires a balanced `{...}` argument object without ``, and MiniMax +XML requires at least one closed parameter element without `` (also +accepted when closed by ``). Bare headers without a closing argument +delimiter, undecided openers, unclosed arguments, strict calls missing their +wire closer, and calls cut off by output limits or stop sequences are never +recovered. Parameter schemas guide best-effort type conversion; non-strict schemas do not reject invalid values. Qwen removes one leading and one trailing wrapping newline from parameter values; diff --git a/helios/src/lib.rs b/helios/src/lib.rs index 2402b90aa..a893143fa 100644 --- a/helios/src/lib.rs +++ b/helios/src/lib.rs @@ -17,7 +17,8 @@ pub mod grammar; pub mod model; pub mod offload; mod os; -#[cfg(feature = "server")] +#[cfg(any(feature = "server", all(kani, feature = "runtime-core")))] +#[cfg_attr(all(kani, not(feature = "server")), allow(dead_code))] pub mod output; #[cfg(feature = "runtime-core")] pub mod core; diff --git a/helios/src/output/argument_tags.rs b/helios/src/output/argument_tags.rs index 0b9463a0a..a27dc27cb 100644 --- a/helios/src/output/argument_tags.rs +++ b/helios/src/output/argument_tags.rs @@ -21,28 +21,33 @@ pub(crate) const ARGUMENT_MARKERS: [&str; 4] = ["", "", "", ""]; pub struct ArgumentTags; -impl ToolDialect for ArgumentTags { - const NAME: &'static str = "GLM"; - const TRIM_NEWLINES: bool = false; - const OPEN: &'static str = ""; - const CLOSE: &'static str = ""; - - fn parse(body: &str, tools: &[Value]) -> Result> { - Self::parse_candidate(body, tools)?.ok_or_else(|| "incomplete JSON argument".into()) - } - fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { +impl ArgumentTags { + fn parse_body( + body: &str, + tools: &[Value], + eos: bool, + ) -> Result>> { let body = body.trim(); let split = body.find("").unwrap_or(body.len()); let name = body[..split].trim(); if name.is_empty() { return Err("tool function name is empty".into()); } + if eos && name.chars().any(|c| c == '<' || c == '>' || c.is_whitespace()) { + return Err("incomplete GLM tool call".into()); + } let mut rest = &body[split..]; let function = tools .iter() .filter_map(|tool| tool.get("function")) .find(|function| function.get("name").and_then(Value::as_str) == Some(name)); let strict = function.is_some_and(|f| f["strict"].as_bool() == Some(true)); + if eos && strict { + return Err("incomplete strict GLM tool call".into()); + } + if eos && rest.trim().is_empty() { + return Err("incomplete GLM tool call".into()); + } let properties = function .and_then(|function| function.get("parameters")) .and_then(|parameters| parameters.get("properties")) @@ -88,6 +93,22 @@ impl ToolDialect for ArgumentTags { } Ok(Some(vec![(name.to_owned(), arguments.to_json_string()?)])) } +} +impl ToolDialect for ArgumentTags { + const NAME: &'static str = "GLM"; + const TRIM_NEWLINES: bool = false; + const OPEN: &'static str = ""; + const CLOSE: &'static str = ""; + + fn parse(body: &str, tools: &[Value]) -> Result> { + Self::parse_candidate(body, tools)?.ok_or_else(|| "incomplete JSON argument".into()) + } + fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { + Self::parse_body(body, tools, false) + } + fn parse_eos(body: &str, tools: &[Value]) -> Result> { + Self::parse_body(body, tools, true)?.ok_or_else(|| "incomplete GLM tool call".into()) + } fn starts_call(text: &str) -> Option { // Calls continue with the function name and an argument key or closing tag; // quoted tags followed by prose remain text. @@ -341,4 +362,315 @@ mod tests { )] ); } + + #[test] + fn unclosed_eos_calls_recover_complete_arguments_across_every_utf8_split() { + let cases: &[(&str, crate::output::tagged::OutputStart, Option<&str>, Option<&str>, &[(&str, Value)])] = &[ + ( + "\nreason α\nruntext\nhello α\ncount2enabledtrueitems[1,2]options{\"x\":1}emptynull", + crate::output::tagged::OutputStart::Reasoning, + Some("\nreason α\n"), + None, + &[( + "run", + json!({"text":"\nhello α\n", "count":2, "enabled":true, "items":[1,2], "options":{"x":1}, "empty":null}), + )], + ), + ( + "\nChecking.\nrun\ntext\n\n", + crate::output::tagged::OutputStart::Reasoning, + None, + Some("\nChecking.\n"), + &[("run", json!({"text":""}))], + ), + ( + "runtextliteral k value", + crate::output::tagged::OutputStart::Reasoning, + None, + None, + &[("run", json!({"text":"literal k value"}))], + ), + ( + "undeclared_fncount7", + crate::output::tagged::OutputStart::Reasoning, + None, + None, + &[("undeclared_fn", json!({"count":"7"}))], + ), + ( + "First.\nruncount1\nSecond.\nruncount2", + crate::output::tagged::OutputStart::Reasoning, + None, + Some("First.\n\nSecond.\n"), + &[ + ("run", json!({"count":1})), + ("run", json!({"count":2})), + ], + ), + ( + "runtextprefilled\n", + crate::output::tagged::OutputStart::ToolBody, + None, + None, + &[("run", json!({"text":"prefilled"}))], + ), + ]; + for &(text, start, reasoning, content, expected_calls) in cases { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = ArgumentTagOutput::new(OutputConfig { start, ..config() }); + let mut output = Accumulator::new("eos".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let message = output.message(); + assert_eq!( + message.get("reasoning_content").and_then(Value::as_str), + reasoning, + "{text:?} split {split}" + ); + assert_eq!( + message.get("content").and_then(Value::as_str), + content, + "{text:?} split {split}" + ); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), expected_calls.len(), "{text:?} split {split}"); + for (index, ((name, expected_args), call)) in + expected_calls.iter().zip(calls.iter()).enumerate() + { + assert_eq!(call["function"]["name"], *name, "{text:?} split {split}"); + let args: Value = + serde_json::from_str(call["function"]["arguments"].as_str().unwrap()) + .unwrap(); + assert_eq!(&args, expected_args, "{text:?} split {split} call {index}"); + } + } + } + // Implicit reasoning end when `` is declared as a terminal marker. + let mut syntax = crate::model::testing::metadata().frontend; + syntax.tools = Some(crate::model::contract::ToolParser { + kind: crate::model::contract::ToolParserKind::GlmArgumentTags, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + syntax.reasoning = Some(crate::model::contract::ReasoningParser { + kind: crate::model::contract::ReasoningParserKind::ThinkTags, + open: "".into(), + close: "".into(), + wrapping_newlines: 0, + terminal_markers: vec!["".into()], + }); + let implicit = "Need to run.runtextok"; + for split in implicit.char_indices().map(|(at, _)| at) { + let mut parser = crate::output::OutputPipeline::new(crate::output::OutputConfig { + syntax: syntax.clone(), + control_tokens: vec![], + content: config(), + }); + let mut output = Accumulator::new("implicit".into()); + for part in [&implicit[..split], &implicit[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let message = output.message(); + assert_eq!(message["reasoning_content"], "Need to run.", "split {split}"); + assert_eq!(message["tool_calls"][0]["function"]["name"], "run"); + assert_eq!( + message["tool_calls"][0]["function"]["arguments"], + r#"{"text":"ok"}"# + ); + } + // Undecided opener during implicit reasoning end still errors and never fabricates. + let mut parser = crate::output::OutputPipeline::new(crate::output::OutputConfig { + syntax, + control_tokens: vec![], + content: config(), + }); + parser + .push(Input::Text("Need to run.run")) + .unwrap(); + assert!(parser.finish(Termination::Eos).is_err()); + } + + #[test] + fn unclosed_eos_calls_reject_incomplete_truncated_strict_and_undecided_inputs() { + for incomplete in [ + "", + " ", + "run", + "run ", + "runrunWrite run", + "runtext", + "runtextunfinished", + "runtextokruntextoktrailing", + "runtextokcount", + "runtextokcount2", + "runa", + "runtextatextb", + "runtextaruntextb", + ] { + for split in incomplete.char_indices().map(|(at, _)| at) { + let mut parser = ArgumentTagOutput::new(config()); + let pushed = parser + .push(Input::Text(&incomplete[..split])) + .and_then(|_| parser.push(Input::Text(&incomplete[split..]))); + assert!( + pushed.is_err() || parser.finish(Termination::Eos).is_err(), + "{incomplete:?} at split {split}" + ); + } + } + // OutputStart::ToolBody rejects bare or malformed function names at EOS. + for body in [ + "run", + "runtextx", + "badtextx", + "bad>nametextx", + ] { + let mut parser = ArgumentTagOutput::new(OutputConfig { + start: crate::output::tagged::OutputStart::ToolBody, + ..config() + }); + parser.push(Input::Text(body)).unwrap(); + assert!(parser.finish(Termination::Eos).is_err(), "{body:?}"); + } + // Strict tools still require explicit `` at EOS while non-strict siblings recover. + let mixed_tools = vec![ + json!({"type":"function", "function": { + "name":"strict_run", "strict":true, + "parameters":{"type":"object", "additionalProperties":false, "required":["text"], + "properties":{"text":{"type":"string"}}} + }}), + json!({"type":"function", "function": { + "name":"loose_run", + "parameters":{"type":"object", "properties":{"text":{"type":"string"}}} + }}), + ]; + let mut strict_parser = ArgumentTagOutput::new(OutputConfig { + tools: mixed_tools.clone(), + ..config() + }); + strict_parser + .push(Input::Text( + "strict_runtextok", + )) + .unwrap(); + assert!(strict_parser.finish(Termination::Eos).is_err()); + + let mut loose_parser = ArgumentTagOutput::new(OutputConfig { + tools: mixed_tools, + ..config() + }); + loose_parser + .push(Input::Text( + "loose_runtextok", + )) + .unwrap(); + let events = loose_parser.finish(Termination::Eos).unwrap(); + assert_eq!( + events, + vec![ + crate::output::Event::ToolBegin { + index: 0, + name: "loose_run".into(), + id: None, + }, + crate::output::Event::ToolArguments { + index: 0, + text: r#"{"text":"ok"}"#.into(), + }, + crate::output::Event::ToolEnd { index: 0 }, + ] + ); + // Non-EOS termination causes always omit unclosed calls, even when arguments are closed. + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut parser = ArgumentTagOutput::new(config()); + parser + .push(Input::Text( + "runtextok", + )) + .unwrap(); + assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); + } + } + + #[test] + fn starts_call_is_prefix_monotonic_and_never_confirms_bare_names() { + const TOKENS: [&str; 10] = [ + "run", + " ", + "\n", + "", + "", + "", + "α", + ]; + // Exhaustively check all 1..=3 token sequences after `` at every + // UTF-8 prefix/extension boundary pair. + let mut samples = Vec::new(); + for &a in &TOKENS { + samples.push(format!("{a}")); + for &b in &TOKENS { + samples.push(format!("{a}{b}")); + for &c in &TOKENS { + samples.push(format!("{a}{b}{c}")); + } + } + } + let (mut saw_true, mut saw_false, mut saw_none) = (false, false, false); + for full in &samples { + let mut prev: Option = None; + for (at, _) in full.char_indices().chain([(full.len(), '\0')]) { + if at < ArgumentTags::OPEN.len() { + continue; + } + let prefix = &full[..at]; + let decision = ArgumentTags::starts_call(prefix); + match decision { + Some(true) => saw_true = true, + Some(false) => saw_false = true, + None => saw_none = true, + } + if let Some(settled) = prev { + assert_eq!( + decision, + Some(settled), + "non-monotonic starts_call transition on {full:?} at {at} ({prefix:?})" + ); + } + if !prefix.contains("") && !prefix.contains("") { + assert_ne!( + decision, + Some(true), + "confirmed without delimiter on {prefix:?}" + ); + } + prev = prev.or(decision); + } + } + assert!(saw_true && saw_false && saw_none); + } } diff --git a/helios/src/output/chatml.rs b/helios/src/output/chatml.rs index e49f64701..f994245de 100644 --- a/helios/src/output/chatml.rs +++ b/helios/src/output/chatml.rs @@ -22,10 +22,13 @@ impl ToolDialect for FunctionTags = Some(("")); const TOOL_ENDS_REASONING: bool = true; fn parse(body: &str, tools: &[Value]) -> Result> { - Ok(vec![parse_tool(body, tools, WRAPPING_NEWLINES)?]) + Ok(vec![parse_tool(body, tools, WRAPPING_NEWLINES, false)?]) } fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { - Ok(parse_tool_candidate(body, tools, WRAPPING_NEWLINES)?.map(|call| vec![call])) + Ok(parse_tool_candidate(body, tools, WRAPPING_NEWLINES, true)?.map(|call| vec![call])) + } + fn parse_eos(body: &str, tools: &[Value]) -> Result> { + Ok(vec![parse_tool(body, tools, WRAPPING_NEWLINES, true)?]) } fn starts_call(text: &str) -> Option { // Calls continue with `` and a parameter or closing tag; quoted @@ -79,8 +82,13 @@ fn possible_parameter_start(text: &str) -> bool { pub type ChatMlOutput = TaggedOutput>; pub type CompactChatMlOutput = TaggedOutput>; -fn parse_tool(body: &str, tools: &[Value], wrapped_parameters: bool) -> Result<(String, String)> { - parse_tool_candidate(body, tools, wrapped_parameters)? +fn parse_tool( + body: &str, + tools: &[Value], + wrapped_parameters: bool, + allow_unclosed_function: bool, +) -> Result<(String, String)> { + parse_tool_candidate(body, tools, wrapped_parameters, allow_unclosed_function)? .ok_or_else(|| "incomplete JSON parameter".into()) } @@ -88,6 +96,7 @@ fn parse_tool_candidate( body: &str, tools: &[Value], wrapped_parameters: bool, + allow_unclosed_function: bool, ) -> Result> { let body = body .trim() @@ -115,6 +124,9 @@ fn parse_tool_candidate( } break; } + if allow_unclosed_function && !strict && !arguments.is_empty() && rest.is_empty() { + break; + } let (parameter, tail) = parameter_start(rest).ok_or("tool function requires parameter or closing tag")?; if parameter.is_empty() || arguments.contains_key(parameter) { @@ -392,12 +404,13 @@ mod tests { ); parser.push("").unwrap(); assert!(parser.finish().is_err()); - assert!(parse_tool("", &config().tools, true).is_err()); + assert!(parse_tool("", &config().tools, true, false).is_err()); assert!( parse_tool( "12", &config().tools, - true + true, + false, ) .is_err() ); @@ -885,4 +898,292 @@ mod tests { assert!(parser.finish(cause).unwrap().is_empty()); } } + + #[test] + fn unclosed_function_tags_recover_complete_parameters_at_eos_or_tool_close() { + let cases: &[(&str, crate::output::tagged::OutputStart, Option<&str>, Option<&str>, &[(&str, Value)])] = &[ + ( + "\n\n\nParis\n\n", + crate::output::tagged::OutputStart::Content, + None, + None, + &[("lookup", json!({"city":"Paris"}))], + ), + ( + "Paris3", + crate::output::tagged::OutputStart::Content, + None, + None, + &[("lookup", json!({"city":"Paris","n":3}))], + ), + ( + "", + crate::output::tagged::OutputStart::Content, + None, + None, + &[("lookup", json!({"city":""}))], + ), + ( + "Paris", + crate::output::tagged::OutputStart::Content, + None, + None, + &[("lookup", json!({"city":"Paris"}))], + ), + ( + "ParisDone.", + crate::output::tagged::OutputStart::Content, + None, + Some("Done."), + &[("lookup", json!({"city":"Paris"}))], + ), + ( + "Paris", + crate::output::tagged::OutputStart::Content, + None, + Some(""), + &[("lookup", json!({"city":"Paris"}))], + ), + ( + "ParisLyon", + crate::output::tagged::OutputStart::Content, + None, + None, + &[ + ("lookup", json!({"city":"Paris"})), + ("lookup", json!({"city":"Lyon"})), + ], + ), + ( + "Plan.Paris", + crate::output::tagged::OutputStart::Reasoning, + Some("Plan."), + None, + &[("lookup", json!({"city":"Paris"}))], + ), + ( + "Paris\nLyon", + crate::output::tagged::OutputStart::Content, + None, + None, + &[ + ("lookup", json!({"city":"Paris"})), + ("lookup", json!({"city":"Lyon"})), + ], + ), + ]; + for &(text, start, reasoning, content, expected_calls) in cases { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = Harness::new(OutputConfig { start, ..config() }, "eos".into()); + parser.push(&text[..split]).unwrap(); + parser.push(&text[split..]).unwrap(); + parser.finish().unwrap(); + let message = parser.message(); + assert_eq!( + message.get("reasoning_content").and_then(Value::as_str), + reasoning, + "{text:?} split {split}" + ); + assert_eq!( + message.get("content").and_then(Value::as_str), + content, + "{text:?} split {split}" + ); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), expected_calls.len(), "{text:?} split {split}"); + for ((name, expected_args), call) in expected_calls.iter().zip(calls.iter()) { + assert_eq!(call["function"]["name"], *name, "{text:?} split {split}"); + let args: Value = + serde_json::from_str(call["function"]["arguments"].as_str().unwrap()) + .unwrap(); + assert_eq!(&args, expected_args, "{text:?} split {split}"); + } + } + } + // Compact dialect preserves wrapping newlines verbatim on EOS recovery too. + let compact = "\n café\n\n"; + for split in compact.char_indices().map(|(at, _)| at) { + let mut parser = CompactChatMlOutput::new(OutputConfig { + start: crate::output::tagged::OutputStart::Content, + ..config() + }); + let mut output = Accumulator::new("compact-eos".into()); + for part in [&compact[..split], &compact[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let args: Value = serde_json::from_str( + output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(args, json!({"city":"\n café\n"}), "split {split}"); + } + } + + #[test] + fn unclosed_function_tags_reject_partial_values_strict_and_non_eos() { + for invalid in [ + "", + "Paris", + "Paris", + "Paris3", + "ParisParistrailing", + "Paris3", + ] { + for split in invalid.char_indices().map(|(at, _)| at) { + let mut parser = ChatMlOutput::new(OutputConfig { + start: crate::output::tagged::OutputStart::Content, + ..config() + }); + let pushed = parser + .push(Input::Text(&invalid[..split])) + .and_then(|_| parser.push(Input::Text(&invalid[split..]))); + assert!( + pushed.is_err() || parser.finish(Termination::Eos).is_err(), + "{invalid:?} at split {split}" + ); + } + } + // Strict function tools still require explicit ``. + let strict_config = OutputConfig { + structured: false, + start: crate::output::tagged::OutputStart::Content, + tools: vec![json!({"type":"function","function":{ + "name":"lookup","strict":true, + "parameters":{"type":"object","additionalProperties":false,"required":["city"], + "properties":{"city":{"type":"string"}}} + }})], + }; + for strict_missing in [ + "Paris", + "Paris", + ] { + let mut parser = ChatMlOutput::new(strict_config.clone()); + let pushed = parser.push(Input::Text(strict_missing)); + assert!( + pushed.is_err() || parser.finish(Termination::Eos).is_err(), + "{strict_missing:?}" + ); + } + // Direct ToolDialect::parse / parse_eos and OutputStart::ToolBody enforce closing rules. + assert_eq!( + FunctionTags::::parse( + "Paris", + &config().tools, + ) + .unwrap(), + vec![("lookup".into(), r#"{"city":"Paris"}"#.into())] + ); + assert!( + FunctionTags::::parse( + "Paris", + &config().tools, + ) + .is_err() + ); + assert!(FunctionTags::::parse_eos("", &config().tools).is_err()); + let mut tool_body = ChatMlOutput::new(OutputConfig { + start: crate::output::tagged::OutputStart::ToolBody, + ..config() + }); + tool_body.push(Input::Text("")).unwrap(); + assert!(tool_body.finish(Termination::Eos).is_err()); + + // Non-EOS termination causes always omit unclosed calls. + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut parser = ChatMlOutput::new(OutputConfig { + start: crate::output::tagged::OutputStart::Content, + ..config() + }); + parser + .push(Input::Text( + "Paris", + )) + .unwrap(); + assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); + } + } + + #[test] + fn starts_call_is_prefix_monotonic_and_possible_parameter_start_covers_all_prefixes() { + // Every whitespace-padded `< parameter = name >` prefix before `>` must keep + // `possible_parameter_start` true so streaming never misclassifies it as prose. + for sp1 in ["", " ", "\n\t"] { + for sp2 in ["", " ", "\n"] { + for sp3 in ["", " ", "\t"] { + for name in ["k", "city", "α_1"] { + let full = format!("<{sp1}parameter{sp2}={sp3}{name}>"); + assert_eq!(parameter_start(&full), Some((name, "")), "{full:?}"); + for (at, _) in full.char_indices() { + if at == 0 { + continue; + } + let prefix = &full[..at]; + assert!(parameter_start(prefix).is_none(), "{prefix:?}"); + assert!(possible_parameter_start(prefix), "{prefix:?}"); + } + } + } + } + } + // Exhaustively check prefix monotonicity of `FunctionTags::starts_call` across + // `` and bare `", + " ", + "\n", + "", + "ized>", + "α", + ]; + let (mut saw_true, mut saw_false, mut saw_none) = (false, false, false); + for opener in ["", " = None; + for (at, _) in full.char_indices().chain([(full.len(), '\0')]) { + if at < opener.len() { + continue; + } + let prefix = &full[..at]; + let decision = FunctionTags::::starts_call(prefix); + match decision { + Some(true) => saw_true = true, + Some(false) => saw_false = true, + None => saw_none = true, + } + if let Some(settled) = prev { + assert_eq!( + decision, + Some(settled), + "non-monotonic starts_call transition on {full:?} at {at} ({prefix:?})" + ); + } + prev = prev.or(decision); + } + } + } + } + } + assert!(saw_true && saw_false && saw_none); + } } diff --git a/helios/src/output/gemma_call.rs b/helios/src/output/gemma_call.rs index e4d0b65b0..1e9ad47ac 100644 --- a/helios/src/output/gemma_call.rs +++ b/helios/src/output/gemma_call.rs @@ -105,13 +105,8 @@ fn value(text: &mut &str, schema: Option<&Value>, depth: usize) -> Result } pub struct GemmaCall; -impl super::tagged::ToolDialect for GemmaCall { - const NAME: &'static str = "Gemma call"; - const TRIM_NEWLINES: bool = false; - const OPEN: &'static str = "<|tool_call>"; - const CLOSE: &'static str = ""; - - fn parse(body: &str, tools: &[Value]) -> Result> { +impl GemmaCall { + fn parse_body(body: &str, tools: &[Value], eos: bool) -> Result> { let body = body.trim_start(); let call = body .strip_prefix("call:") @@ -125,11 +120,14 @@ impl super::tagged::ToolDialect for GemmaCall { if name.is_empty() { return Err("tool function name is empty".into()); } - let schema = tools + let function = tools .iter() .filter_map(|tool| tool.get("function")) - .find(|function| function.get("name").and_then(Value::as_str) == Some(name)) - .and_then(|function| function.get("parameters")); + .find(|function| function.get("name").and_then(Value::as_str) == Some(name)); + if eos && function.is_some_and(|f| f["strict"].as_bool() == Some(true)) { + return Err("incomplete strict Gemma call tool call".into()); + } + let schema = function.and_then(|function| function.get("parameters")); let arguments = value(&mut rest, schema, 0)?; if !rest.trim().is_empty() { return Err("unexpected content after tool call arguments".into()); @@ -137,6 +135,19 @@ impl super::tagged::ToolDialect for GemmaCall { Ok(vec![(name.to_owned(), arguments.to_string())]) } } +impl super::tagged::ToolDialect for GemmaCall { + const NAME: &'static str = "Gemma call"; + const TRIM_NEWLINES: bool = false; + const OPEN: &'static str = "<|tool_call>"; + const CLOSE: &'static str = ""; + + fn parse(body: &str, tools: &[Value]) -> Result> { + Self::parse_body(body, tools, false) + } + fn parse_eos(body: &str, tools: &[Value]) -> Result> { + Self::parse_body(body, tools, true) + } +} #[cfg(test)] mod tests { @@ -203,4 +214,113 @@ mod tests { let nested = format!("call:lookup{{a:{}{}}}", "[".repeat(130), "]".repeat(130)); assert!(GemmaCall::parse(&nested, &[]).is_err()); } + + #[test] + fn unclosed_gemma_calls_recover_balanced_braces_at_eos_and_reject_incomplete() { + use crate::output::{ + Input, ModelOutput, Termination, + tagged::{OutputConfig, OutputStart, TaggedOutput}, + }; + use crate::server::output::Accumulator; + + let tools = vec![json!({"function":{"name":"lookup","parameters":{"properties":{ + "n":{"type":"integer"},"q":{"type":"string"} + }}}})]; + for (text, expected_calls) in [ + ( + "<|tool_call>call:lookup{n:3,q:<|\"|>a,b<|\"|>}", + vec![("lookup", json!({"n":3,"q":"a,b"}))], + ), + ( + "<|tool_call>call:lookup{}\n", + vec![("lookup", json!({}))], + ), + ( + "<|tool_call>:lookup{n:1}", + vec![("lookup", json!({"n":1}))], + ), + ( + "<|tool_call>call:lookup{n:1}<|tool_call>call:other{q:<|\"|>café<|\"|>}", + vec![ + ("lookup", json!({"n":1})), + ("other", json!({"q":"café"})), + ], + ), + ] { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let mut output = Accumulator::new("gemma-eos".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let calls = output.message()["tool_calls"].as_array().unwrap().clone(); + assert_eq!(calls.len(), expected_calls.len(), "{text:?} split {split}"); + for ((name, expected_args), call) in expected_calls.iter().zip(calls.iter()) { + assert_eq!(call["function"]["name"], *name, "{text:?} split {split}"); + let args: Value = + serde_json::from_str(call["function"]["arguments"].as_str().unwrap()) + .unwrap(); + assert_eq!(&args, expected_args, "{text:?} split {split}"); + } + } + } + for invalid in [ + "<|tool_call>", + "<|tool_call>call:lookup", + "<|tool_call>call:lookup{n:3", + "<|tool_call>call:lookup{q:<|\"|>open}", + "<|tool_call>call:lookup{n:3}call:lookup{n:3}trailing", + "<|tool_call>call:lookup{n:1}<|tool_call>call:lookup{n:2}", + ] { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + parser.push(Input::Text(invalid)).unwrap(); + assert!(parser.finish(Termination::Eos).is_err(), "{invalid:?}"); + } + // Strict tool rejects omitted `` at EOS. + let mut strict_parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"function":{"name":"lookup","strict":true,"parameters":{ + "type":"object","additionalProperties":false,"required":["n"], + "properties":{"n":{"type":"integer"}} + }}})], + }); + strict_parser + .push(Input::Text("<|tool_call>call:lookup{n:3}")) + .unwrap(); + assert!(strict_parser.finish(Termination::Eos).is_err()); + + // Non-EOS termination causes always omit unclosed calls. + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + parser + .push(Input::Text("<|tool_call>call:lookup{n:3}")) + .unwrap(); + assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); + } + } } diff --git a/helios/src/output/minimax_xml.rs b/helios/src/output/minimax_xml.rs index aae3d842b..cd8ae5a68 100644 --- a/helios/src/output/minimax_xml.rs +++ b/helios/src/output/minimax_xml.rs @@ -140,14 +140,12 @@ fn object(elements: Vec<(String, Element)>, schema: Option<&Value>) -> Value { } pub struct MiniMaxXml; -impl super::tagged::ToolDialect for MiniMaxXml { - const NAME: &'static str = "namespace XML"; - const TRIM_NEWLINES: bool = false; - const OPEN: &'static str = "]<]minimax[>["; - const CLOSE: &'static str = "]<]minimax[>["; - const FUNCTION: Option<(&'static str, &'static str)> = Some((INVOKE, INVOKE_END)); - - fn parse(body: &str, tools: &[Value]) -> Result> { +impl MiniMaxXml { + fn parse_body( + body: &str, + tools: &[Value], + allow_unclosed_invoke: bool, + ) -> Result> { let mut rest = body.trim(); let mut calls = Vec::new(); while !rest.is_empty() { @@ -161,24 +159,51 @@ impl super::tagged::ToolDialect for MiniMaxXml { if name.is_empty() { return Err("tool function name is empty".into()); } - let schema = tools + let function = tools .iter() - .find(|t| t["function"]["name"].as_str() == Some(name)) - .and_then(|tool| tool["function"].get("parameters")); - let (mut parameters, tail) = tail - .split_once(INVOKE_END) - .ok_or("unterminated XML invocation")?; + .filter_map(|tool| tool.get("function")) + .find(|function| function.get("name").and_then(Value::as_str) == Some(name)); + let strict = function.is_some_and(|f| f["strict"].as_bool() == Some(true)); + let schema = function.and_then(|tool| tool.get("parameters")); + let (mut parameters, next, closed) = match tail.split_once(INVOKE_END) { + Some((parameters, next)) => (parameters, next, true), + None if allow_unclosed_invoke && !strict => (tail, "", false), + None => return Err("unterminated XML invocation".into()), + }; let mut values = Vec::new(); while let Some((name, value, tail)) = element(parameters.trim_start(), 1) { values.push((name, value)); parameters = tail; } + if !closed && (values.is_empty() || !parameters.trim().is_empty()) { + return Err("unterminated XML invocation".into()); + } calls.push((name.to_owned(), object(values, schema).to_string())); - rest = tail.trim_start(); + rest = next.trim_start(); + } + if allow_unclosed_invoke && calls.is_empty() { + return Err("XML tool call requires an invoke tag".into()); } Ok(calls) } } +impl super::tagged::ToolDialect for MiniMaxXml { + const NAME: &'static str = "namespace XML"; + const TRIM_NEWLINES: bool = false; + const OPEN: &'static str = "]<]minimax[>["; + const CLOSE: &'static str = "]<]minimax[>["; + const FUNCTION: Option<(&'static str, &'static str)> = Some((INVOKE, INVOKE_END)); + + fn parse(body: &str, tools: &[Value]) -> Result> { + Self::parse_body(body, tools, false) + } + fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { + Self::parse_body(body, tools, true).map(Some) + } + fn parse_eos(body: &str, tools: &[Value]) -> Result> { + Self::parse_body(body, tools, true) + } +} #[cfg(test)] mod tests { @@ -266,4 +291,131 @@ mod tests { assert!(MiniMaxXml::parse(&body, &tools).is_err()); } } + + #[test] + fn unclosed_minimax_invocations_recover_complete_elements_at_eos_or_tool_close() { + use crate::output::{ + Input, ModelOutput, Termination, + tagged::{OutputConfig, OutputStart, TaggedOutput}, + }; + use crate::server::output::Accumulator; + + let tools = vec![json!({"function":{"name":"lookup","parameters":{"properties":{ + "n":{"type":"integer"}, + "items":{"type":"array","items":{"type":"string"}} + }}}})]; + let open = MiniMaxXml::OPEN; + let close = MiniMaxXml::CLOSE; + for (text, content, expected_calls) in [ + ( + format!("{open}\n{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}\n"), + None, + vec![("lookup", json!({"n":3}))], + ), + ( + format!("{open}{INVOKE}'lookup'>{ELEMENT}items>{ELEMENT}item>café{NAMESPACE}{NAMESPACE}"), + None, + vec![("lookup", json!({"items":["café"]}))], + ), + ( + format!("{open}{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}{close}Done."), + Some("Done."), + vec![("lookup", json!({"n":3}))], + ), + ( + format!("{open}{INVOKE}'lookup'>{ELEMENT}n>1{NAMESPACE}{INVOKE_END}\n{INVOKE}'search'>{ELEMENT}q>7{NAMESPACE}"), + None, + vec![("lookup", json!({"n":1})), ("search", json!({"q":"7"}))], + ), + ] { + for split in text.char_indices().map(|(at, _)| at).chain([text.len()]) { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let mut output = Accumulator::new("minimax-eos".into()); + for part in [&text[..split], &text[split..]] { + output + .apply(parser.push(Input::Text(part)).unwrap()) + .unwrap(); + } + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + let message = output.message(); + assert_eq!( + message.get("content").and_then(Value::as_str), + content, + "{text:?} split {split}" + ); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), expected_calls.len(), "{text:?} split {split}"); + for ((name, expected_args), call) in expected_calls.iter().zip(calls.iter()) { + assert_eq!(call["function"]["name"], *name, "{text:?} split {split}"); + let args: Value = + serde_json::from_str(call["function"]["arguments"].as_str().unwrap()) + .unwrap(); + assert_eq!(&args, expected_args, "{text:?} split {split}"); + } + } + } + for invalid in [ + open.to_owned(), + format!("{open}{close}"), + format!("{open}{INVOKE}'lookup'>"), + format!("{open}{INVOKE}'lookup'>{close}"), + format!("{open}{INVOKE}'lookup'>{ELEMENT}n>3"), + format!("{open}{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}{ELEMENT}b>broken"), + format!("{open}{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}{NAMESPACE}{ELEMENT}n>1{NAMESPACE}{INVOKE}'search'>{ELEMENT}q>2{NAMESPACE}"), + ] { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + let pushed = parser.push(Input::Text(&invalid)); + assert!( + pushed.is_err() || parser.finish(Termination::Eos).is_err(), + "{invalid:?}" + ); + } + // Strict tool requires explicit ``. + let mut strict_parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"function":{"name":"lookup","strict":true,"parameters":{ + "type":"object","additionalProperties":false,"required":["n"], + "properties":{"n":{"type":"integer"}} + }}})], + }); + strict_parser + .push(Input::Text(&format!( + "{open}{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}" + ))) + .unwrap(); + assert!(strict_parser.finish(Termination::Eos).is_err()); + + // Non-EOS termination causes always omit unclosed calls. + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: tools.clone(), + }); + parser + .push(Input::Text(&format!( + "{open}{INVOKE}'lookup'>{ELEMENT}n>3{NAMESPACE}" + ))) + .unwrap(); + assert!(parser.finish(cause).unwrap().is_empty(), "{cause:?}"); + } + } } diff --git a/helios/src/output/pipeline.rs b/helios/src/output/pipeline.rs index fe6de165b..c64e8ccaf 100644 --- a/helios/src/output/pipeline.rs +++ b/helios/src/output/pipeline.rs @@ -46,6 +46,9 @@ impl super::tagged::ToolDialect for PlainText { fn parse(_: &str, _: &[serde_json::Value]) -> Result> { Err("tool parsing is not configured".into()) } + fn parse_eos(_: &str, _: &[serde_json::Value]) -> Result> { + Err("tool parsing is not configured".into()) + } } macro_rules! dispatch { @@ -383,6 +386,9 @@ mod tests { #[test] fn absent_parsers_preserve_plain_and_structured_content() { + use super::super::tagged::ToolDialect; + assert!(PlainText::parse("body", &[]).is_err()); + assert!(PlainText::parse_eos("body", &[]).is_err()); for structured in [false, true] { let text = "{\"literal\":\"content\"}"; assert_eq!( @@ -1364,4 +1370,109 @@ mod tests { } } } + + #[test] + fn token_gated_reasoning_delimiters_preserve_unclosed_eos_tool_calls() { + use crate::output::tagged::OutputStart; + let glm = contract(include_str!("../../tests/support/contracts/glm53.json")); + let tools = [json!({"type":"function","function":{ + "name":"run","parameters":{"type":"object","properties":{"text":{"type":"string"}}} + }})]; + let close = (true, ""); + let text = |s| (false, s); + + // Token-gated `` (including a duplicate close delimiter) followed by an + // unclosed GLM call at EOS recovers the call across all delivery modes. + for (pieces, content) in [ + ( + &[ + text("Plan."), + close, + text("runtextok"), + ][..], + "", + ), + ( + &[ + text("Plan."), + close, + text("Note. "), + close, + text("runtextok"), + ][..], + "Note. ", + ), + ] { + for feed in 0..3 { + let message = delimited(&glm, OutputStart::Reasoning, &tools, pieces, feed); + assert_eq!(message["reasoning_content"], "Plan.", "{pieces:?} feed {feed}"); + assert_eq!( + message["content"].as_str().unwrap_or_default(), + content, + "{pieces:?} feed {feed}" + ); + let calls = message["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), 1, "{pieces:?} feed {feed}"); + assert_eq!(calls[0]["function"]["name"], "run"); + assert_eq!(calls[0]["function"]["arguments"], r#"{"text":"ok"}"#); + } + } + + // Plain-text `` (not the control token) keeps `...` inside reasoning. + for feed in 0..3 { + let message = delimited( + &glm, + OutputStart::Reasoning, + &tools, + &[text( + "Plan.runtextok", + )], + feed, + ); + assert_eq!( + message["reasoning_content"], + "Plan.runtextok", + "feed {feed}" + ); + assert!(message.get("tool_calls").is_none(), "feed {feed}"); + } + + // Gemma 4 implicit reasoning end into an unclosed `<|tool_call>` at EOS. + let mut gemma = crate::model::testing::metadata().frontend; + gemma.tools = Some(ToolParser { + kind: ToolParserKind::GemmaCall, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + gemma.reasoning = Some(ReasoningParser { + kind: ReasoningParserKind::ChannelThought, + open: "<|channel>thought".into(), + close: "".into(), + wrapping_newlines: 1, + terminal_markers: vec!["<|tool_call>".into()], + }); + let gemma_control = [(2, "".to_owned())]; + let gemma_tools = [json!({"function":{"name":"lookup","parameters":{"properties":{ + "n":{"type":"integer"} + }}}})]; + for feed in 0..3 { + let message = delimited_by( + &gemma, + &gemma_control, + OutputStart::Reasoning, + &gemma_tools, + &[text("Quote first."), text("<|tool_call>call:lookup{n:1}")], + feed, + ); + assert_eq!( + message["reasoning_content"], "Quote first.", + "feed {feed}" + ); + assert_eq!( + message["tool_calls"][0]["function"]["arguments"], + r#"{"n":1}"#, + "feed {feed}" + ); + } + } } diff --git a/helios/src/output/tagged.rs b/helios/src/output/tagged.rs index a205ecaa1..8e24fea51 100644 --- a/helios/src/output/tagged.rs +++ b/helios/src/output/tagged.rs @@ -40,6 +40,9 @@ pub trait ToolDialect { fn parse_candidate(body: &str, tools: &[Value]) -> Result>> { Self::parse(body, tools).map(Some) } + /// Parse an unclosed call body at natural end-of-sequence (`Termination::Eos`). + /// Accepts only structurally complete, self-delimited, non-strict calls. + fn parse_eos(body: &str, tools: &[Value]) -> Result>; /// Whether text beginning with `OPEN` or the function opener starts a call /// rather than mentioning the tag in prose; `None` until more text decides. fn starts_call(_text: &str) -> Option { @@ -213,9 +216,74 @@ pub struct TaggedTools { search_from: usize, in_json_string: bool, escaped: bool, + confirmed: bool, + outer_closed: bool, tools: Arc<[Value]>, index: usize, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum EosDecision { + Omit, + Reject, + ParseEos, +} + +fn select_candidate( + outer: Option, + outer_len: usize, + inner: Option, + inner_len: usize, +) -> Option<(usize, usize, bool)> { + let mut candidate = outer.map(|at| (at, at + outer_len, true)); + if let Some(at) = inner + && candidate.is_none_or(|(end, _, _)| at < end) + { + candidate = Some((at + inner_len, at + inner_len, false)); + } + candidate +} + +impl TaggedTools { + fn eos_decision(&self, cause: Termination) -> EosDecision { + if matches!( + cause, + Termination::Cancelled + | Termination::ExecutionError + | Termination::UserStop + | Termination::OutputLimit + ) { + EosDecision::Omit + } else if !self.confirmed || self.in_json_string { + EosDecision::Reject + } else { + EosDecision::ParseEos + } + } + fn emit_calls(&self, calls: Vec<(String, String)>) -> Vec { + let mut events = Vec::with_capacity(calls.len() * 3); + for (offset, (name, arguments)) in calls.into_iter().enumerate() { + let index = self.index + offset; + events.push(Event::ToolBegin { + index, + name, + id: None, + }); + events.push(Event::ToolArguments { + index, + text: arguments, + }); + events.push(Event::ToolEnd { index }); + } + events + } + fn incomplete_error() -> crate::Error { + let mut message = String::with_capacity(21 + D::NAME.len()); + message.push_str("incomplete "); + message.push_str(D::NAME); + message.push_str(" tool call"); + message.into() + } +} impl ToolCallParser for TaggedTools { fn push(&mut self, input: Input<'_>) -> Result { let Input::Text(text) = input else { @@ -244,14 +312,13 @@ impl ToolCallParser for TaggedTools { } } let tail = &self.buffer[self.search_from..]; - let mut candidate = tail.find(D::CLOSE).map(|at| (at, at + D::CLOSE.len())); - if let Some((_, close)) = D::FUNCTION - && let Some(at) = tail.find(close) - && candidate.is_none_or(|(end, _)| at < end) - { - candidate = Some((at + close.len(), at + close.len())); - } - let Some((end, consumed)) = candidate else { + let (inner, inner_len) = match D::FUNCTION { + Some((_, close)) => (tail.find(close), close.len()), + None => (None, 0), + }; + let Some((end, consumed, outer_closed)) = + select_candidate(tail.find(D::CLOSE), D::CLOSE.len(), inner, inner_len) + else { return Ok(Progress::default()); }; let end = self.search_from + end; @@ -259,46 +326,30 @@ impl ToolCallParser for TaggedTools { if let Some(calls) = D::parse_candidate(&self.buffer[..end], &self.tools)? { self.buffer.drain(..self.search_from); self.search_from = 0; + self.outer_closed = outer_closed; break calls; } self.in_json_string = true; }; - let events = calls - .into_iter() - .enumerate() - .flat_map(|(offset, (name, arguments))| { - let index = self.index + offset; - [ - Event::ToolBegin { - index, - name, - id: None, - }, - Event::ToolArguments { - index, - text: arguments, - }, - Event::ToolEnd { index }, - ] - }) - .collect(); Ok(Progress { - events, + events: self.emit_calls(calls), remainder: Some(std::mem::take(&mut self.buffer)), }) } fn finish(&mut self, cause: Termination) -> Result> { - if matches!( - cause, - Termination::Cancelled - | Termination::ExecutionError - | Termination::UserStop - | Termination::OutputLimit - ) { - self.buffer.clear(); - return Ok(vec![]); + let decision = self.eos_decision(cause); + let body = std::mem::take(&mut self.buffer); + self.search_from = 0; + self.in_json_string = false; + self.escaped = false; + match decision { + EosDecision::Omit => Ok(vec![]), + EosDecision::Reject => Err(Self::incomplete_error()), + EosDecision::ParseEos => { + let calls = D::parse_eos(&body, &self.tools)?; + Ok(self.emit_calls(calls)) + } } - Err(format!("incomplete {} tool call", D::NAME).into()) } } @@ -408,6 +459,8 @@ impl ModelOutput for TaggedOutput { search_from: 0, in_json_string: false, escaped: false, + confirmed: true, + outer_closed: false, tools: definitions, index: 0, }), @@ -497,7 +550,14 @@ impl ModelOutput for TaggedOutput { let mut output = self.push(Input::Text(""))?; match self.mode { Mode::Reasoning => output.extend(self.reasoning.finish(cause)?), - Mode::Tool => output.extend(self.tool.as_mut().unwrap().finish(cause)?), + Mode::Tool => { + let events = self.tool.as_mut().unwrap().finish(cause)?; + self.calls += events + .iter() + .filter(|event| matches!(event, Event::ToolBegin { .. })) + .count(); + output.extend(events); + } _ => { let start = self.received - self.buffer.len(); let text = std::mem::take(&mut self.buffer); @@ -561,8 +621,10 @@ impl TaggedOutput { if reasoning { self.trim_newlines = if self.reasoning.trim_wrap { 2 } else { 0 }; } else { + let outer_closed = + self.tool.as_ref().is_some_and(|tool| tool.outer_closed); self.tool = None; - self.outer_tool_pending = D::FUNCTION.is_some(); + self.outer_tool_pending = D::FUNCTION.is_some() && !outer_closed; } } Mode::Content => { @@ -664,6 +726,7 @@ impl TaggedOutput { .flatten() .map(|at| (at, false)); let mut bare_function = false; + let mut confirmed = true; let mut undecided = None; if !self.tools.is_empty() { let mut openers: Vec<_> = self @@ -683,9 +746,10 @@ impl TaggedOutput { match D::starts_call(&self.buffer[at..]) { Some(false) => continue, None if !self.finishing => undecided = Some(at), - _ => { + decision => { marker = Some((at, true)); bare_function = opener != D::OPEN; + confirmed = decision == Some(true); } } break; @@ -724,6 +788,8 @@ impl TaggedOutput { search_from: 0, in_json_string: false, escaped: false, + confirmed, + outer_closed: false, tools: self.tools.clone(), index: self.calls, }); @@ -787,19 +853,18 @@ impl TaggedOutput { } fn partial_marker(text: &str, markers: &[&str]) -> usize { - markers - .iter() - .flat_map(|marker| { - marker - .char_indices() - .map(|(index, _)| index) - .filter(|index| *index > 0) - .rev() - .filter(|length| text.ends_with(&marker[..*length])) - .take(1) - }) - .max() - .unwrap_or(0) + let mut best = 0; + for marker in markers { + let mut len = text.len().min(marker.len().saturating_sub(1)); + while len > best { + if marker.is_char_boundary(len) && text.ends_with(&marker[..len]) { + best = len; + break; + } + len -= 1; + } + } + best } /// Insertion-ordered argument map that preserves raw JSON tokens. @@ -809,6 +874,9 @@ impl RawArguments { pub(super) fn new() -> Self { Self(Vec::new()) } + pub(super) fn is_empty(&self) -> bool { + self.0.is_empty() + } pub(super) fn contains_key(&self, key: &str) -> bool { self.0.iter().any(|(k, _)| k == key) } @@ -964,3 +1032,81 @@ fn declared_value(raw: &str, schema: Option<&Value>) -> Result> { } Ok(None) } + +#[cfg(kani)] +mod kani_proofs; + +#[cfg(test)] +mod tests { + use super::*; + + struct MultiCallDialect; + impl ToolDialect for MultiCallDialect { + const NAME: &'static str = "multi"; + const TRIM_NEWLINES: bool = false; + const OPEN: &'static str = ""; + const CLOSE: &'static str = ""; + fn parse(body: &str, _tools: &[Value]) -> Result> { + Ok(body + .split(',') + .map(|name| (name.to_owned(), "{}".to_owned())) + .collect()) + } + fn parse_eos(body: &str, tools: &[Value]) -> Result> { + Self::parse(body, tools) + } + fn starts_call(text: &str) -> Option { + let rest = text.strip_prefix(Self::OPEN).unwrap_or(text); + if rest.is_empty() || rest == "maybe" { + None + } else { + Some(true) + } + } + } + + #[test] + fn emit_calls_and_finish_track_call_indices_and_reject_unconfirmed_or_json_string() { + let mut parser = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![serde_json::json!({"function": {"name": "a"}})], + }); + let first = parser.push(Input::Text("ab,c")).unwrap(); + assert_eq!(parser.calls, 1); + assert!(matches!(first[0], Event::ToolBegin { index: 0, .. })); + let rest = parser.finish(Termination::Eos).unwrap(); + assert_eq!(parser.calls, 3); + let indices: Vec<_> = rest + .iter() + .filter_map(|e| match e { + Event::ToolBegin { index, .. } => Some(*index), + _ => None, + }) + .collect(); + assert_eq!(indices, vec![1, 2]); + + // Unconfirmed opener promoted at finish is rejected even if parse_eos would succeed. + let mut undecided = TaggedOutput::::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![serde_json::json!({"function": {"name": "maybe"}})], + }); + assert!(undecided.push(Input::Text("maybe")).unwrap().is_empty()); + assert!(undecided.finish(Termination::Eos).is_err()); + + // Unfinished JSON string inside TaggedTools is rejected at EOS even if confirmed. + let mut tools = TaggedTools:: { + dialect: std::marker::PhantomData, + buffer: "a".into(), + search_from: 0, + in_json_string: true, + escaped: false, + confirmed: true, + outer_closed: false, + tools: Arc::from([]), + index: 0, + }; + assert!(tools.finish(Termination::Eos).is_err()); + } +} diff --git a/helios/src/output/tagged/kani_proofs.rs b/helios/src/output/tagged/kani_proofs.rs new file mode 100644 index 000000000..c574818cf --- /dev/null +++ b/helios/src/output/tagged/kani_proofs.rs @@ -0,0 +1,176 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +use super::*; + +#[kani::proof] +#[kani::unwind(8)] +fn partial_marker_ascii_matches_oracle() { + const MARKERS: [&str; 3] = ["", "\n", ""]; + let raw: [u8; 6] = kani::any(); + let mut i = 0; + while i < raw.len() { + kani::assume(raw[i] < 0x80); + i += 1; + } + let len = usize::from(kani::any::()); + kani::assume(len <= raw.len()); + // SAFETY: Every byte in `raw` is ASCII (`< 0x80`), so every slice is valid UTF-8. + let text = unsafe { std::str::from_utf8_unchecked(&raw[..len]) }; + + let hold = partial_marker(text, &MARKERS); + + let mut expected = 0usize; + for marker in MARKERS { + let mut k = 1; + while k < marker.len() { + if text.ends_with(&marker[..k]) && k > expected { + expected = k; + } + k += 1; + } + } + + assert_eq!(hold, expected); + assert!(hold <= len); + assert!(text.is_char_boundary(len - hold)); + kani::cover!(hold > 0, "nonzero partial prefix"); + kani::cover!(hold == 0, "no partial prefix"); +} + +#[kani::proof] +#[kani::unwind(8)] +fn partial_marker_utf8_preserves_char_boundaries() { + const MARKERS: [&str; 2] = ["<α>", "<世>"]; + const SAMPLES: [&str; 8] = ["", "<", "<α", "<世", "x<α", "α<世", "<α>", "世<"]; + let idx = usize::from(kani::any::()) % SAMPLES.len(); + let text = SAMPLES[idx]; + + let hold = partial_marker(text, &MARKERS); + + let mut expected = 0usize; + for marker in MARKERS { + let mut k = 1; + while k < marker.len() { + if marker.is_char_boundary(k) && text.ends_with(&marker[..k]) && k > expected { + expected = k; + } + k += 1; + } + } + + assert_eq!(hold, expected); + assert!(hold <= text.len()); + assert!(text.is_char_boundary(text.len() - hold)); + kani::cover!(hold >= 3, "multibyte utf8 partial prefix held"); +} + +struct SymbolicDialect; +impl ToolDialect for SymbolicDialect { + const NAME: &'static str = "s"; + const TRIM_NEWLINES: bool = false; + const OPEN: &'static str = " Result> { + Err("bad".into()) + } + + fn parse_eos(_: &str, _: &[Value]) -> Result> { + Err("bad".into()) + } +} + +#[kani::proof] +#[kani::unwind(4)] +fn tagged_tools_eos_decision_enforces_termination_and_confirmation() { + let cause = match kani::any::() % 5 { + 0 => Termination::Eos, + 1 => Termination::OutputLimit, + 2 => Termination::UserStop, + 3 => Termination::Cancelled, + _ => Termination::ExecutionError, + }; + let confirmed: bool = kani::any(); + let in_json_string: bool = kani::any(); + + let tools = TaggedTools:: { + dialect: std::marker::PhantomData, + buffer: String::new(), + search_from: 0, + in_json_string, + escaped: kani::any(), + confirmed, + outer_closed: kani::any(), + tools: Arc::from([]), + index: kani::any(), + }; + + let decision = tools.eos_decision(cause); + let expected = if cause != Termination::Eos { + EosDecision::Omit + } else if !confirmed || in_json_string { + EosDecision::Reject + } else { + EosDecision::ParseEos + }; + assert_eq!(decision, expected); + kani::cover!(decision == EosDecision::Omit, "non-eos omits"); + kani::cover!( + cause == Termination::Eos && !confirmed && !in_json_string, + "unconfirmed rejected at eos" + ); + kani::cover!( + cause == Termination::Eos && confirmed && in_json_string, + "unclosed json string rejected at eos" + ); + kani::cover!(decision == EosDecision::ParseEos, "confirmed eos parses"); + // Isolate borrowed `eos_decision` from `Arc<[serde_json::Value]>` drop unwinding. + std::mem::forget(tools); +} + +#[kani::proof] +#[kani::unwind(4)] +fn select_candidate_picks_earliest_closer_and_tracks_outer_closed() { + let buf_len: usize = kani::any(); + let outer_len: usize = kani::any(); + let inner_len: usize = kani::any(); + kani::assume(buf_len <= 1024 * 1024); + kani::assume((1..=64).contains(&outer_len)); + kani::assume((1..=64).contains(&inner_len)); + + let has_outer: bool = kani::any(); + let has_inner: bool = kani::any(); + let outer_at: usize = kani::any(); + let inner_at: usize = kani::any(); + kani::assume(!has_outer || (outer_len <= buf_len && outer_at <= buf_len - outer_len)); + kani::assume(!has_inner || (inner_len <= buf_len && inner_at <= buf_len - inner_len)); + // Distinct non-prefix outer and inner closing markers cannot start at the same byte. + kani::assume(!(has_outer && has_inner && outer_at == inner_at)); + + let outer = has_outer.then_some(outer_at); + let inner = has_inner.then_some(inner_at); + let result = select_candidate(outer, outer_len, inner, inner_len); + + match (outer, inner) { + (None, None) => assert_eq!(result, None), + (Some(o), None) => assert_eq!(result, Some((o, o + outer_len, true))), + (None, Some(i)) => assert_eq!(result, Some((i + inner_len, i + inner_len, false))), + (Some(o), Some(i)) if i < o => { + assert_eq!(result, Some((i + inner_len, i + inner_len, false))); + kani::cover!(true, "inner closer precedes outer closer"); + } + (Some(o), Some(_)) => { + assert_eq!(result, Some((o, o + outer_len, true))); + kani::cover!(true, "outer closer precedes inner closer"); + } + } + if let Some((end, consumed, outer_closed)) = result { + assert!(end <= consumed); + assert!(consumed <= buf_len); + assert_eq!(outer_closed, end < consumed); + } +} diff --git a/helios/src/server/logprobs.rs b/helios/src/server/logprobs.rs index f2b7adb33..5acc24847 100644 --- a/helios/src/server/logprobs.rs +++ b/helios/src/server/logprobs.rs @@ -359,6 +359,107 @@ mod tests { } } + #[test] + fn unclosed_glm_tool_call_at_eos_preserves_content_logprobs_and_reasoning_tokens() { + use crate::model::contract::{ReasoningParser, ReasoningParserKind, ToolParser, ToolParserKind}; + let pieces = [ + "plan", + "", + "Answer.", + "", + "run", + "", + "text", + "", + "", + "ok", + "", + ]; + let frontend = Arc::new(crate::server::output::tests::frontend(&pieces)); + let mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = Some(ReasoningParser { + kind: ReasoningParserKind::ThinkTags, + open: "".into(), + close: "".into(), + wrapping_newlines: 0, + terminal_markers: vec![], + }); + syntax.tools = Some(ToolParser { + kind: ToolParserKind::GlmArgumentTags, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + let cfg = OutputConfig { + syntax, + control_tokens: vec![(1, "".into())], + content: Tags { + structured: false, + start: OutputStart::Reasoning, + tools: vec![json!({"type":"function","function":{ + "name":"run","parameters":{"type":"object","properties":{"text":{"type":"string"}}} + }})], + }, + }; + for (worker, streaming) in [(false, false), (false, true), (true, false), (true, true)] { + let mut decoder = Decoder::::new(&frontend, &[], Some(cfg.clone())); + decoder.track_logprobs(&frontend, true); + let mut encoder = encoder(Protocol::Responses, frontend.clone(), streaming); + let mut streamed = Vec::new(); + let mut stops = + crate::server::stops::TextStops::new(&frontend, vec!["UNMATCHED".into()]).unwrap(); + stops.track(&frontend); + for token in 0..pieces.len() as u32 { + let events = if worker { + let (p, matched) = stops.push_logprob(token, value(token), false).unwrap(); + assert!(!matched); + decoder.push_protocol(p).unwrap() + } else { + decoder.push_logprob(value(token)).unwrap() + }; + for frame in encoder.apply(0, events).unwrap() { + if frame.data["type"] == "response.output_text.delta" { + streamed.extend(frame.data["logprobs"].as_array().unwrap().iter().cloned()); + } + } + } + if worker { + let (p, _) = stops.finish(None).unwrap(); + encoder + .apply(0, decoder.push_protocol(p).unwrap()) + .unwrap(); + } + let tail = decoder.finish(Termination::Eos).unwrap(); + encoder.apply(0, tail).unwrap(); + encoder.report_reasoning_tokens(0, decoder.reasoning_tokens()); + encoder + .finish(0, Termination::Eos, pieces.len() as u32, 0, None) + .unwrap(); + let response = encoder.response(); + assert_eq!(response["status"], "completed"); + assert_eq!(response["output"][0]["content"][0]["text"], "plan"); + let part = &response["output"][1]["content"][0]; + assert_eq!(part["text"], "Answer."); + let tokens: Vec<_> = part["logprobs"] + .as_array() + .unwrap() + .iter() + .map(|e| e["token"].clone()) + .collect(); + assert_eq!(tokens, ["token_id:2"], "worker {worker} streaming {streaming}"); + assert_eq!(response["output"][2]["type"], "function_call"); + assert_eq!(response["output"][2]["name"], "run"); + assert_eq!(response["output"][2]["arguments"], r#"{"text":"ok"}"#); + assert_eq!( + response["usage"]["output_tokens_details"]["reasoning_tokens"], + 1, + "worker {worker} streaming {streaming}" + ); + if streaming { + assert_eq!(json!(streamed), part["logprobs"]); + } + } + } + #[test] fn streamed_token_suffix_at_finish_reuses_its_previously_delivered_entry() { for (reasoning, token_text) in [(true, "tail\n"), (false, "tail<")] { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index ead6a6cfa..c7e130b56 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2312,5 +2312,353 @@ fn strict_tool_wires_reach_encoder_only_after_parser_completion() { "{} truncated call reached the response", case.name ); + + // Strict calls missing only their outer closing tag still fail at EOS. + if let Some(unclosed_strict) = match case.kind { + ToolParserKind::QwenCoder => Some("ok"), + ToolParserKind::GlmArgumentTags => { + Some("lookupqok") + } + _ => None, + } { + let mut parser = make_parser(); + let mut encoder = make_encoder(); + let _ = encoder.start(); + assert_eq!( + stream_wire( + &mut parser, + &mut encoder, + unclosed_strict, + &controls, + case.name + ) + .unwrap(), + 0, + "{} unclosed strict call streamed early", + case.name + ); + assert!( + parser.finish(Termination::Eos).is_err(), + "{} unclosed strict call unexpectedly succeeded at EOS", + case.name + ); + } + } +} + +#[test] +fn unclosed_tagged_tool_calls_at_eos_match_protocol_and_control_semantics() { + use crate::{ + model::contract::{ToolParser, ToolParserKind}, + output::{Input as OutputInput, OutputConfig, OutputPipeline, tagged}, + }; + + struct Case { + name: &'static str, + kind: ToolParserKind, + wrapping_newlines: u32, + declared_unclosed: &'static str, + undeclared_unclosed: &'static str, + two_calls_second_unclosed: &'static str, + } + let cases = [ + Case { + name: "glm", + kind: ToolParserKind::GlmArgumentTags, + wrapping_newlines: 0, + declared_unclosed: "Answer.lookupquerycafé", + undeclared_unclosed: "missing__lookupquerycafé", + two_calls_second_unclosed: "lookupqueryfirstlookupquerysecond", + }, + Case { + name: "qwen", + kind: ToolParserKind::QwenCoder, + wrapping_newlines: 1, + declared_unclosed: "Answer.\n\n\n\n\ncafé\n\n", + undeclared_unclosed: "\n\n\ncafé\n\n", + two_calls_second_unclosed: "firstsecond", + }, + Case { + name: "mimo", + kind: ToolParserKind::QwenCoder, + wrapping_newlines: 0, + declared_unclosed: "Answer.café", + undeclared_unclosed: "café", + two_calls_second_unclosed: "firstsecond", + }, + Case { + name: "gemma", + kind: ToolParserKind::GemmaCall, + wrapping_newlines: 0, + declared_unclosed: "Answer.<|tool_call>call:lookup{query:<|\"|>café<|\"|>}", + undeclared_unclosed: "<|tool_call>call:missing__lookup{query:<|\"|>café<|\"|>}", + two_calls_second_unclosed: "<|tool_call>call:lookup{query:<|\"|>first<|\"|>}<|tool_call>call:lookup{query:<|\"|>second<|\"|>}", + }, + Case { + name: "minimax", + kind: ToolParserKind::MiniMaxXml, + wrapping_newlines: 0, + declared_unclosed: "Answer.]<]minimax[>[]<]minimax[>[]<]minimax[>[café]<]minimax[>[", + undeclared_unclosed: "]<]minimax[>[]<]minimax[>[]<]minimax[>[café]<]minimax[>[", + two_calls_second_unclosed: "]<]minimax[>[]<]minimax[>[]<]minimax[>[first]<]minimax[>[]<]minimax[>[]<]minimax[>[]<]minimax[>[second]<]minimax[>[", + }, + ]; + let declared_tool = json!({"type":"function","function":{ + "name":"lookup","parameters":{"type":"object","properties":{"query":{"type":"string"}}} + }}); + + for case in cases { + let make_parser = || { + let mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = None; + syntax.tools = Some(ToolParser { + kind: case.kind, + wrapping_newlines: case.wrapping_newlines, + tag_separator: String::new(), + }); + OutputPipeline::new(OutputConfig { + syntax, + control_tokens: vec![], + content: tagged::OutputConfig { + structured: false, + start: tagged::OutputStart::Content, + tools: vec![declared_tool.clone()], + }, + }) + }; + + for protocol in [Protocol::Chat, Protocol::Messages, Protocol::Responses] { + // 1. Auto mode with declared unclosed call at EOS (char-by-char streaming). + let mut parser = make_parser(); + let mut enc = encoder(protocol); + let mut frames = enc.start(); + for (at, ch) in case.declared_unclosed.char_indices() { + let parsed = parser + .push(OutputInput::Text(&case.declared_unclosed[at..at + ch.len_utf8()])) + .unwrap(); + frames.extend(enc.apply(0, parsed).unwrap()); + } + let tail = parser.finish(Termination::Eos).unwrap(); + frames.extend(enc.apply(0, tail).unwrap()); + frames.extend(enc.finish(0, Termination::Eos, 12, 0, None).unwrap()); + let response = enc.response(); + let expected = json!({"query":"café"}); + match protocol { + Protocol::Chat => { + assert_eq!(response["choices"][0]["finish_reason"], "tool_calls", "{}", case.name); + assert_eq!(response["choices"][0]["message"]["content"], "Answer.", "{}", case.name); + let call = &response["choices"][0]["message"]["tool_calls"][0]; + assert_eq!(call["function"]["name"], "lookup", "{}", case.name); + assert_eq!( + serde_json::from_str::(call["function"]["arguments"].as_str().unwrap()).unwrap(), + expected + ); + assert!(frames.last().unwrap().done); + } + Protocol::Messages => { + assert_eq!(response["stop_reason"], "tool_use", "{}", case.name); + assert_eq!(response["content"][0]["text"], "Answer.", "{}", case.name); + assert_eq!(response["content"][1]["name"], "lookup", "{}", case.name); + assert_eq!(response["content"][1]["input"], expected); + assert_eq!(frames.last().unwrap().data["type"], "message_stop"); + } + Protocol::Responses => { + assert_eq!(response["status"], "completed", "{}", case.name); + assert_eq!(response["output"][0]["content"][0]["text"], "Answer.", "{}", case.name); + let call = &response["output"][1]; + assert_eq!(call["name"], "lookup", "{}", case.name); + assert_eq!( + serde_json::from_str::(call["arguments"].as_str().unwrap()).unwrap(), + expected + ); + assert_eq!(frames.last().unwrap().data["type"], "response.completed"); + } + _ => unreachable!(), + } + let streamed_arguments: String = frames + .iter() + .filter_map(|frame| match protocol { + Protocol::Chat => frame.data["choices"][0]["delta"]["tool_calls"][0] + ["function"]["arguments"] + .as_str(), + Protocol::Messages => frame.data["delta"]["partial_json"].as_str(), + Protocol::Responses + if frame.data["type"] == "response.function_call_arguments.delta" => + { + frame.data["delta"].as_str() + } + _ => None, + }) + .collect(); + assert_eq!( + serde_json::from_str::(&streamed_arguments).unwrap(), + expected, + "{} {protocol:?}", + case.name + ); + + // 1b. Required tool_choice succeeds on declared unclosed EOS call. + let mut parser = make_parser(); + let mut req_ok = encoder_with_choice(protocol, ToolChoice::Required); + let _ = req_ok.start(); + let ev1 = parser.push(OutputInput::Text(case.declared_unclosed)).unwrap(); + req_ok.apply(0, ev1).unwrap(); + let ev2 = parser.finish(Termination::Eos).unwrap(); + req_ok.apply(0, ev2).unwrap(); + req_ok.finish(0, Termination::Eos, 12, 0, None).unwrap(); + match protocol { + Protocol::Chat => assert_eq!(req_ok.response()["choices"][0]["finish_reason"], "tool_calls"), + Protocol::Messages => assert_eq!(req_ok.response()["stop_reason"], "tool_use"), + Protocol::Responses => assert_eq!(req_ok.response()["status"], "completed"), + _ => unreachable!(), + } + + // 2. Named tool_choice omits answer text and succeeds on unclosed EOS call. + let mut parser = make_parser(); + let mut named = encoder_with_choice(protocol, ToolChoice::Named("lookup".into())); + let _ = named.start(); + let ev1 = parser.push(OutputInput::Text(case.declared_unclosed)).unwrap(); + named.apply(0, ev1).unwrap(); + let ev2 = parser.finish(Termination::Eos).unwrap(); + named.apply(0, ev2).unwrap(); + named.finish(0, Termination::Eos, 12, 0, None).unwrap(); + let named_resp = named.response(); + match protocol { + Protocol::Chat => { + assert!(named_resp["choices"][0]["message"]["content"].is_null(), "{}", case.name); + assert_eq!(named_resp["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "lookup"); + } + Protocol::Messages => { + assert_eq!(named_resp["content"].as_array().unwrap().len(), 1, "{}", case.name); + assert_eq!(named_resp["content"][0]["name"], "lookup"); + } + Protocol::Responses => { + assert_eq!(named_resp["output"].as_array().unwrap().len(), 1, "{}", case.name); + assert_eq!(named_resp["output"][0]["name"], "lookup"); + } + _ => unreachable!(), + } + + // 3. Auto accepts undeclared unclosed EOS call; Required and Named reject it. + let mut parser = make_parser(); + let mut events = parser.push(OutputInput::Text(case.undeclared_unclosed)).unwrap(); + events.extend(parser.finish(Termination::Eos).unwrap()); + let mut auto_enc = encoder(protocol); + auto_enc.apply(0, events.clone()).unwrap(); + auto_enc.finish(0, Termination::Eos, 8, 0, None).unwrap(); + let mut required_enc = encoder_with_choice(protocol, ToolChoice::Required); + assert!(required_enc.apply(0, events.clone()).is_err(), "{} {protocol:?}", case.name); + let mut wrong_named = encoder_with_choice(protocol, ToolChoice::Named("lookup".into())); + assert!(wrong_named.apply(0, events).is_err(), "{} {protocol:?}", case.name); + + // 4. parallel_tool_calls: false keeps call 1 and discards unclosed call 2 at EOS. + let mut parser = make_parser(); + let mut single = Encoder::new( + protocol, + format!("single_{}", case.name), + "model".into(), + 0, + 1, + vec![PromptUsage::default()], + vec![inference::Tool { + name: "lookup".into(), + namespace: None, + description: String::new(), + parameters: json!({"type":"object","properties":{"query":{"type":"string"}}}), + declared_parameters: true, + strict: false, + custom: false, + grammar: None, + }], + ToolChoice::Auto, + false, + false, + Value::Null, + ); + let _ = single.start(); + let ev1 = parser.push(OutputInput::Text(case.two_calls_second_unclosed)).unwrap(); + single.apply(0, ev1).unwrap(); + let ev2 = parser.finish(Termination::Eos).unwrap(); + single.apply(0, ev2).unwrap(); + assert!(single.tool_limit_reached, "{} {protocol:?}", case.name); + single.finish(0, Termination::Eos, 12, 0, None).unwrap(); + let single_resp = single.response(); + match protocol { + Protocol::Chat => { + let calls = single_resp["choices"][0]["message"]["tool_calls"].as_array().unwrap(); + assert_eq!(calls.len(), 1, "{}", case.name); + assert_eq!(calls[0]["function"]["arguments"], r#"{"query":"first"}"#); + assert_eq!(single_resp["choices"][0]["finish_reason"], "tool_calls"); + } + Protocol::Messages => { + assert_eq!(single_resp["content"].as_array().unwrap().len(), 1, "{}", case.name); + assert_eq!(single_resp["content"][0]["input"], json!({"query":"first"})); + assert_eq!(single_resp["stop_reason"], "tool_use"); + } + Protocol::Responses => { + assert_eq!(single_resp["output"].as_array().unwrap().len(), 1, "{}", case.name); + assert_eq!(single_resp["output"][0]["arguments"], r#"{"query":"first"}"#); + assert_eq!(single_resp["status"], "completed"); + } + _ => unreachable!(), + } + + // 5. OutputLimit omits structurally complete unclosed call and reports limit finish reason. + let mut parser = make_parser(); + let mut limited = encoder(protocol); + let _ = limited.start(); + let ev1 = parser.push(OutputInput::Text(case.declared_unclosed)).unwrap(); + limited.apply(0, ev1).unwrap(); + let ev2 = parser.finish(Termination::OutputLimit).unwrap(); + assert!(ev2.is_empty(), "{}", case.name); + limited.apply(0, ev2).unwrap(); + limited.finish(0, Termination::OutputLimit, 12, 0, None).unwrap(); + let limited_resp = limited.response(); + match protocol { + Protocol::Chat => { + assert_eq!(limited_resp["choices"][0]["finish_reason"], "length", "{}", case.name); + assert!(limited_resp["choices"][0]["message"]["tool_calls"].is_null()); + } + Protocol::Messages => { + assert_eq!(limited_resp["stop_reason"], "max_tokens", "{}", case.name); + assert_eq!(limited_resp["content"].as_array().unwrap().len(), 1); + } + Protocol::Responses => { + assert_eq!(limited_resp["status"], "incomplete", "{}", case.name); + assert_eq!(limited_resp["output"].as_array().unwrap().len(), 1); + } + _ => unreachable!(), + } + + // 6. UserStop omits structurally complete unclosed call and reports stop reason. + let mut parser = make_parser(); + let mut stopped = encoder(protocol); + let _ = stopped.start(); + let ev1 = parser.push(OutputInput::Text(case.declared_unclosed)).unwrap(); + stopped.apply(0, ev1).unwrap(); + let ev2 = parser.finish(Termination::UserStop).unwrap(); + assert!(ev2.is_empty(), "{}", case.name); + stopped.apply(0, ev2).unwrap(); + stopped + .finish(0, Termination::UserStop, 12, 0, Some("STOP".into())) + .unwrap(); + let stopped_resp = stopped.response(); + match protocol { + Protocol::Chat => { + assert_eq!(stopped_resp["choices"][0]["finish_reason"], "stop", "{}", case.name); + assert!(stopped_resp["choices"][0]["message"]["tool_calls"].is_null()); + } + Protocol::Messages => { + assert_eq!(stopped_resp["stop_reason"], "stop_sequence", "{}", case.name); + assert_eq!(stopped_resp["stop_sequence"], "STOP"); + assert_eq!(stopped_resp["content"].as_array().unwrap().len(), 1); + } + Protocol::Responses => { + assert_eq!(stopped_resp["status"], "completed", "{}", case.name); + assert_eq!(stopped_resp["output"].as_array().unwrap().len(), 1); + } + _ => unreachable!(), + } + } } } diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index 136266b65..b75a80614 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -379,15 +379,17 @@ cargo kani setup Run the sequential validator proofs from the repository root: ```sh -cargo kani --manifest-path helios/Cargo.toml --lib +cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib ``` The harnesses call production functions in `execution/transport.rs`, `model.rs`, -and `model/contract.rs`. They compile only under `cfg(kani)` and do not select a -serving path. Kani 0.68.0 uses CBMC 6.11.0 and nightly-2026-08-21. Automatic -safety and unwinding checks remain enabled. The completion harnesses use unwind -bound 20, the 65-token mask-boundary harness uses 66, and the state-view -harnesses use 16. +`model/contract.rs`, and `output/tagged.rs`. They compile only under `cfg(kani)` +and do not select a serving path. Kani 0.68.0 uses CBMC 6.11.0 and +nightly-2026-08-21. Automatic safety and unwinding checks remain enabled. The +completion harnesses use unwind bound 20, the 65-token mask-boundary harness +uses 66, the state-view harnesses use 16, the output-parser `partial_marker` +harnesses use 8, and the output-parser EOS-decision and closer-selection +harnesses use 4. The vector safety harness supplies arbitrary `i64` fields and token IDs in owned vectors of every length zero through sixteen, including inactive and @@ -443,6 +445,33 @@ their lengths and first elements. Core validity, allocation failure, resource-owner destruction, GPU state, and rank interleavings require their separate checks. +The output-parser proofs verify four sequential properties in +`helios/src/output/tagged.rs`: + +- `partial_marker_ascii_matches_oracle` checks `partial_marker` against an + independent longest-proper-prefix specification across all ASCII strings of + length zero through six and three markers, including UTF-8 char-boundary + preservation on `text.len() - hold`. +- `partial_marker_utf8_preserves_char_boundaries` checks `partial_marker` + across representative 1-, 2-, and 3-byte UTF-8 sequences and multibyte + markers. +- `tagged_tools_eos_decision_enforces_termination_and_confirmation` checks + `TaggedTools::eos_decision` across all five `Termination` causes, both + `confirmed` states, and both `in_json_string` states: non-EOS always omits, + unconfirmed or `in_json_string` at EOS always rejects, and only confirmed + non-JSON-string EOS parses. It keeps the empty `Arc<[serde_json::Value]>` + fixture alive via `mem::forget` so the proof isolates the borrowed decision + method rather than `serde_json::Value::drop`. +- `select_candidate_picks_earliest_closer_and_tracks_outer_closed` checks + `select_candidate` over all buffer lengths through the 1 MiB parser bound, + marker lengths 1 through 64, and distinct non-prefix outer/inner match + positions for overflow safety, earliest-closer selection, `end <= consumed <= buf_len`, + and `outer_closed == (end < consumed)`. + +JSON argument parsing, schema-guided coercion, dialect-specific tag grammars, +and full streaming state-machine transitions remain covered by ordinary Rust +unit, protocol, logprob, and mutation tests. + ## Mutation coverage with cargo-mutants Install cargo-mutants 27.1.0, then run the scoped rank-helper selection: From 19c098c8a21d342444cd3475d9053ac54e36da3e Mon Sep 17 00:00:00 2001 From: Drew Botwinick <6953152+dbotwinick@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:25:31 -0600 Subject: [PATCH 04/27] Add DGX Spark CX7 preflight checks to flare doctor (#506) * Add DGX Spark CX7 preflight checks to flare doctor Multi-host serving on DGX Spark needs an active ConnectX-7 interface with an IPv4 RoCEv2 GID. The existing PCIe diagnostics leave operators to verify the Spark fabric separately before launch. Detect the DGX Spark GB10 PCI device and reuse serving's RoCE discovery to report CX7 interfaces, IPv4 prefixes, and MTUs. Fail when discovery finds no active CX7 device with an assigned IPv4 RoCEv2 endpoint. Warn about overlapping subnets, suspect addresses or prefixes, and MTUs below 9000 bytes. Apply PCIe tuning checks on Sparks when selected GPU pairs require PCIe P2P. Operators can run one command on each Spark to find local fabric issues before launching a multi-host core. All 10 focused Flare doctor tests passed on Linux x86_64. The ARM64 CLI reported exactly one passing CX7 check on each of four DGX Sparks with two active IPv4 RoCEv2 devices at MTU 9000. The live check covered local configuration. Peer reachability and RDMA throughput require separate tests. Design-Signed-Off-By: Codex (GPT-6.2-sol); design-review=eb2f Signed-off-by: Drew Botwinick * Report CX7 preflight applicability on GB10 and N1X The Spark diagnostics matched a single PCI ID and failed when no CX7 device or link was available. A GB10 or RTX Spark N1X host may serve locally without a CX7 fabric. A single-GPU report also omitted the PCIe checks without saying why. Use the shared GB10 device table and probe PCI for the ConnectX-7 adapter before looking for RDMA devices. Report an absent adapter as not applicable and warn about an installed adapter with no usable endpoint. Report PCIe applicability explicitly. Reuse the serving predicates for link state, GID selection, and link-local subnets. Distinguish devices beyond the serving limit from missing GIDs and allow link-local interfaces to share a subnet. Describe MTU below 9000 as a throughput advisory. A standalone host can run doctor successfully, while operators configuring a multi-host core still get the local interface, subnet, and MTU details they need to find configuration issues. Linux release tests for Flare doctor passed, covering absent adapters for all five PCI IDs, one configured interface, advisory MTU 1500, subnet overlap, and a fifth active device. Helios RoCE fabric tests passed with runtime-core and server features, covering GID selection and rail planning. On four DGX Sparks the ARM64 CLI passed with two active CX7 interfaces at GID index 3 and MTU 9000. With its GPU hidden, one Spark reported PCIe as unverified and still passed CX7. The absent-adapter case used synthetic PCI data. The live check did not exercise peer traffic or measure throughput. Design-Signed-Off-By: Codex (GPT-6.2-sol); design-review=eb2f Signed-off-by: Drew Botwinick * Report observed CX7 MTUs and serving endpoints MTU 1500 is a valid setting for switched Spark fabrics, but doctor warned on every value below 9000. Doctor also inferred why serving left devices out of its selection and could suggest fixing a GID when discovery could not resolve a local IPv4 prefix. Report the observed MTU and leave the internal MTU preference unset. Read the device selection from serving's discovery result. List other active devices by name and report unresolved IPv4 addresses and prefixes on selected devices. Document the switched cluster used for the live check and record the remaining qualification work. Operators can compare the actual interface settings without a warning for a valid MTU or a diagnosis based on an inferred selection reason. The Linux x86_64 release doctor tests passed with default features. Fixtures verified a single usable interface at MTU 1500, unreadable MTU warnings, and distinct reports for unselected and unresolved devices. The ARM64 CLI passed on four DGX Sparks configured as a switched cluster, with two active interfaces per node on separate IPv4 /24 subnets, RoCEv2 GID index 3, and MTU 9000. N1X hardware, peer reachability, and throughput at different MTUs remain untested. Design-Signed-Off-By: Codex (GPT-6.2-sol); design-review=eb2f Signed-off-by: Drew Botwinick --------- Signed-off-by: Drew Botwinick --- docs/TODO.txt | 6 + docs/cli-design.md | 47 ++- docs/multi-host.md | 3 + flare-cli/src/cli.rs | 2 +- flare-cli/src/doctor.rs | 222 ++++++++---- flare-cli/src/doctor/spark.rs | 524 ++++++++++++++++++++++++++++ helios/src/execution/roce_fabric.rs | 51 +-- 7 files changed, 752 insertions(+), 103 deletions(-) create mode 100644 flare-cli/src/doctor/spark.rs diff --git a/docs/TODO.txt b/docs/TODO.txt index 6e9adcab4..5a257441f 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -268,6 +268,12 @@ verification, and coordinated shutdown complete on that configuration. See roce-ring.md. +[ ] Verify ConnectX-7 peer reachability and measure throughput with MTU 1500 + and MTU 9000 on direct and switched DGX Spark fabrics before preferring + an MTU in flare doctor. Run the local preflight on Linux RTX Spark N1X + hardware and verify that hosts without a ConnectX-7 adapter skip it. + See cli-design.md#54-flare-doctor. + [ ] Qualify x86_64 RoCE serving on RDMA hardware; its coverage is functional, over Soft-RoCE. See multi-host.md. diff --git a/docs/cli-design.md b/docs/cli-design.md index 96d9e4f9e..9cab000bc 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -122,7 +122,7 @@ flare-cli/target/release/flare run CORE --gpus 0 flare run [CORE] [flags] serve locally, join a rank, or launch peer agents flare download REPOSITORY [flags] download a prepared core flare inspect CORE|MODEL[@VERSION] [--tensor-parallel N] [--rank N] [--unverified] [--memory-map] [--graphs] [--frontend] [--all] [--json | --plain] -flare doctor [--gpus N[,N...]] [--json | --plain] check Linux PCIe TP>1 driver, IOMMU, and ACS settings +flare doctor [--gpus N[,N...]] [--json | --plain] check Linux PCIe TP>1 settings and DGX Spark CX7 readiness flare agent [--listen IP:PORT] run this host's rank agent flare agent install [--join-code CODE | --accept-first] [--listen IP:PORT] flare agent pair HOST... [--code CODE] pair for --hosts or Orbit launches @@ -1635,8 +1635,7 @@ envelope has format 4 or 6. ### 5.4 `flare doctor` -Inspect Linux host configuration for multi-GPU tensor-parallel serving over -PCIe: +Inspect Linux host readiness for tensor-parallel serving: ```sh flare doctor [--gpus N[,N...]] [--json | --plain] @@ -1662,12 +1661,42 @@ On Linux PCIe hosts, `flare doctor` verifies: connecting the selected GPUs (from their lowest common ancestor downward). Reading PCIe extended configuration space from `/sys/bus/pci/devices//config` requires root (`CAP_SYS_ADMIN`); without - it, ACS is reported as `unverified` with a hint to run `sudo flare doctor`. - -`--json` prints the structured report; `--plain` disables terminal styling and -conflicts with `--json`. The command exits zero when no check fails and -non-zero when one or more checks fail. On non-Linux hosts, the command reports -the checks as not applicable and exits zero. + it, ACS is reported as `unverified` and its remediation suggests running + `sudo flare doctor`. + +On Linux GB10 and RTX Spark N1X hosts, `flare doctor` checks the local +ConnectX-7 fabric for multi-host serving. `--gpus` does not affect this host +check. PCIe tuning checks are not applicable when exactly one GPU is selected +on these hosts and are unverified when no GPU is selected or detected. + +- PCI identifies the ConnectX-7 physical function (`15b3:1021`) even if its + RDMA driver has not bound. The fabric check is not applicable when the + adapter is absent. +- The report uses serving's RoCEv2 GID index and lists the selected + ConnectX-7 devices, interface names, IPv4 prefixes, and observed MTUs. + One active device with an assigned IPv4 address and RoCEv2 GID is + sufficient. The report identifies active devices skipped by discovery. +- The check warns if there is no driver, active link, or usable IPv4 RoCEv2 + endpoint. It warns if the address and prefix for a selected device or its + MTU cannot be read. It also flags /0 and /32 prefixes, network and broadcast + addresses, and overlapping subnets on different interfaces. Two link-local + interfaces may share a subnet. Link-local IPv4 requires an LLDP-confirmed + direct peer. + +Compare the reported Ethernet MTUs with the settings on the intended peers +and switch. +NVIDIA's [Spark setup guide](https://build.nvidia.com/spark/connect-multiple-sparks/advance) +uses MTU 9000 for a direct two-node link and MTU 1500 for ring and switched +connections. Peer reachability requires a separate check. + +The local check passed on four Linux DGX Sparks configured as a switched +cluster. Each host had two active interfaces on separate IPv4 /24 subnets, +RoCEv2 GID index 3, and Ethernet MTU 9000. + +`--json` prints the structured report. `--plain` disables terminal styling and +conflicts with `--json`. Check statuses are `pass`, `fail`, `warn`, `unverified`, +and `not_applicable` in JSON. Only `fail` produces a nonzero exit status. On +non-Linux hosts, the command reports the checks as not applicable and exits zero. ## 6. Capacity errors diff --git a/docs/multi-host.md b/docs/multi-host.md index 3cc2b6cb4..8a89bfd71 100644 --- a/docs/multi-host.md +++ b/docs/multi-host.md @@ -53,6 +53,9 @@ Staging (`--stage-only`) does not need RoCE. Not qualified: x86_64 RoCE serving on RDMA hardware; its coverage is functional, over Soft-RoCE. The separate `rdma` feature enables the prefix pool's data channel. +Run [`flare doctor`](cli-design.md#54-flare-doctor) on each DGX Spark to +verify its local ConnectX-7 link and IPv4 RoCEv2 configuration before launch. + ### Prefix cache pool A multi-host instance can use a Selene prefix cache pool (see diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 5139b6024..ed93bfc55 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -47,7 +47,7 @@ pub enum Command { Download(Download), /// Summarize a core's metadata, with optional memory, graph, and frontend details. Inspect(Inspect), - /// Check Linux host PCIe, NVIDIA driver, IOMMU, and ACS settings for TP>1 serving. + /// Check Linux host readiness for PCIe and DGX Spark tensor-parallel serving. Doctor(Doctor), #[command(hide = true)] HardwareRevision { diff --git a/flare-cli/src/doctor.rs b/flare-cli/src/doctor.rs index 100571722..fac6b6563 100644 --- a/flare-cli/src/doctor.rs +++ b/flare-cli/src/doctor.rs @@ -4,7 +4,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -//! Host preflight diagnostics for multi-GPU tensor-parallel serving over PCIe on Linux. +//! Host preflight diagnostics for tensor-parallel serving on Linux. + +#[cfg(any(target_os = "linux", test))] +mod spark; use std::{ collections::{BTreeMap, BTreeSet}, @@ -63,6 +66,7 @@ const IOMMU_REMEDIATION: &str = pub enum CheckStatus { Pass, Fail, + Warn, Unverified, NotApplicable, } @@ -72,6 +76,7 @@ impl CheckStatus { match self { Self::Pass => "PASS", Self::Fail => "FAIL", + Self::Warn => "WARN", Self::Unverified => "UNVERIFIED", Self::NotApplicable => "N/A", } @@ -85,7 +90,7 @@ impl CheckStatus { let code = match self { Self::Pass => "1;32", Self::Fail => "1;31", - Self::Unverified => "1;33", + Self::Warn | Self::Unverified => "1;33", Self::NotApplicable => "2", }; format!("\x1b[{code}m{label}\x1b[0m") @@ -217,11 +222,13 @@ fn diagnose(requested_gpus: &[i32]) -> Result { { let inherited = std::env::var("CUDA_VISIBLE_DEVICES").ok(); let probe = probe_linux_gpus(requested_gpus, inherited.as_deref())?; + let sysfs = Path::new(SYSFS_ROOT); Ok(evaluate_linux_host( probe, - Path::new(SYSFS_ROOT), + sysfs, Path::new(NVIDIA_PARAMS_PATH), Path::new(CMDLINE_PATH), + flare_helios::execution::roce_fabric::discover, )) } #[cfg(not(target_os = "linux"))] @@ -259,11 +266,13 @@ struct GpuProbe { notes: Vec, } +#[cfg(any(target_os = "linux", test))] fn evaluate_linux_host( probe: GpuProbe, sysfs_root: &Path, nvidia_params_path: &Path, cmdline_path: &Path, + discover: impl FnOnce() -> flare_helios::Result, ) -> Report { let gpu_bdfs: Vec = probe.gpus.iter().map(|g| g.pci_bus_id.clone()).collect(); let ancestor_chains = collect_ancestor_chains(sysfs_root, &gpu_bdfs); @@ -274,51 +283,66 @@ fn evaluate_linux_host( Interconnect::Pcie | Interconnect::Mixed ); + let spark_check = spark::check_host(sysfs_root, discover); let mut notes = probe.notes; - if probe.interconnect == Interconnect::NvLink { + let mut checks = if probe.interconnect == Interconnect::NvLink { notes.push( "All selected GPU pairs have NVLink P2P; PCIe TP>1 tuning checks are not required." .into(), ); - return Report { - platform: "linux", - interconnect: probe.interconnect, - pcie_tp_checks_required: false, - gpus: probe.gpus, - bridges, - notes, - checks: vec![Check { - id: "pcie.interconnect".into(), - name: "PCIe TP>1 preflight".into(), - status: CheckStatus::NotApplicable, - expected: None, - actual: Some("NVLink".into()), - detail: "Selected GPUs are connected over NVLink.".into(), - remediation: None, - }], - ok: true, - all_verified: true, + vec![Check { + id: "pcie.interconnect".into(), + name: "PCIe TP>1 preflight".into(), + status: CheckStatus::NotApplicable, + expected: None, + actual: Some("NVLink".into()), + detail: "Selected GPUs are connected over NVLink.".into(), + remediation: None, + }] + } else if spark_check.is_some() && !pcie_tp_checks_required { + let (status, detail) = if probe.interconnect == Interconnect::SingleGpu { + ( + CheckStatus::NotApplicable, + "PCIe TP>1 checks require at least two selected GPUs.", + ) + } else { + ( + CheckStatus::Unverified, + "No GPUs were selected or detected for PCIe topology checks.", + ) }; - } - - if matches!( - probe.interconnect, - Interconnect::SingleGpu | Interconnect::NoGpus - ) { - notes.push( - "Fewer than two GPUs selected; reporting host readiness for PCIe TP>1 serving.".into(), - ); - } + vec![Check { + id: "pcie.interconnect".into(), + name: "PCIe TP>1 preflight".into(), + status, + expected: None, + actual: Some(probe.interconnect.description().into()), + detail: detail.into(), + remediation: None, + }] + } else { + if matches!( + probe.interconnect, + Interconnect::SingleGpu | Interconnect::NoGpus + ) { + notes.push( + "Fewer than two GPUs selected; reporting host readiness for PCIe TP>1 serving." + .into(), + ); + } - let params_text = std::fs::read_to_string(nvidia_params_path); - let params_result = params_text - .as_deref() - .map_err(|error| format!("cannot read {}: {error}", nvidia_params_path.display())); - let mut checks = check_nvidia_params(params_result); + let params_text = std::fs::read_to_string(nvidia_params_path); + let params_result = params_text + .as_deref() + .map_err(|error| format!("cannot read {}: {error}", nvidia_params_path.display())); + let mut checks = check_nvidia_params(params_result); + let cmdline = std::fs::read_to_string(cmdline_path).ok(); + checks.push(check_iommu(sysfs_root, &gpu_bdfs, cmdline.as_deref())); + checks.push(check_acs(sysfs_root, &bridges)); + checks + }; - let cmdline = std::fs::read_to_string(cmdline_path).ok(); - checks.push(check_iommu(sysfs_root, &gpu_bdfs, cmdline.as_deref())); - checks.push(check_acs(sysfs_root, &bridges)); + checks.extend(spark_check); Report { platform: "linux", @@ -445,7 +469,7 @@ fn all_pairs_nvlink_by_pci_bdfs(gpu_bdfs: &[String]) -> Option { /// Render a human-readable `flare doctor` report into `canvas`. pub fn render(report: &Report, mut canvas: Canvas) -> String { let color = canvas.is_color(); - canvas.open("Flare doctor · PCIe TP>1 preflight"); + canvas.open("Flare doctor · Host preflight"); canvas.row("platform", report.platform); canvas.row("interconnect", report.interconnect.description()); canvas.row( @@ -492,7 +516,7 @@ pub fn render(report: &Report, mut canvas: Canvas) -> String { let mut remediations = Vec::new(); for check in &report.checks { - if matches!(check.status, CheckStatus::Fail | CheckStatus::Unverified) + if matches!(check.status, CheckStatus::Fail | CheckStatus::Warn | CheckStatus::Unverified) && let Some(hint) = &check.remediation && !remediations.contains(hint) { @@ -506,26 +530,12 @@ pub fn render(report: &Report, mut canvas: Canvas) -> String { } } - let passed = report - .checks - .iter() - .filter(|c| c.status == CheckStatus::Pass) - .count(); - let failed = report - .checks - .iter() - .filter(|c| c.status == CheckStatus::Fail) - .count(); - let unverified = report - .checks - .iter() - .filter(|c| c.status == CheckStatus::Unverified) - .count(); - let na = report - .checks - .iter() - .filter(|c| c.status == CheckStatus::NotApplicable) - .count(); + let count = |status| report.checks.iter().filter(|c| c.status == status).count(); + let passed = count(CheckStatus::Pass); + let failed = count(CheckStatus::Fail); + let warnings = count(CheckStatus::Warn); + let unverified = count(CheckStatus::Unverified); + let na = count(CheckStatus::NotApplicable); let mut summary = Vec::new(); if passed > 0 { @@ -534,6 +544,11 @@ pub fn render(report: &Report, mut canvas: Canvas) -> String { if failed > 0 { summary.push(format!("{failed} failed")); } + if warnings == 1 { + summary.push("1 warning".into()); + } else if warnings > 1 { + summary.push(format!("{warnings} warnings")); + } if unverified > 0 { summary.push(format!("{unverified} unverified")); } @@ -545,13 +560,11 @@ pub fn render(report: &Report, mut canvas: Canvas) -> String { if failed > 0 { canvas.row("status", &CheckStatus::Fail.styled(color)); } else if unverified > 0 { - canvas.row( - "status", - &format!( - "{} (run with sudo to complete privileged checks)", - CheckStatus::Unverified.styled(color) - ), - ); + canvas.row("status", &CheckStatus::Unverified.styled(color)); + } else if warnings > 0 { + canvas.row("status", &CheckStatus::Warn.styled(color)); + } else if passed == 0 && na > 0 { + canvas.row("status", &CheckStatus::NotApplicable.styled(color)); } else { canvas.row("status", &CheckStatus::Pass.styled(color)); } @@ -1504,6 +1517,72 @@ EnableResizableBar: 1 RegistryDwords: "ForceP2P=0x11;RMForceP2PType=1;RMPcieP2PType=2;GrdmaPciTopoCheckOverride=1" "#; + #[cfg(target_os = "linux")] + #[test] + fn gb10_and_n1x_without_cx7_skip_fabric_preflight() { + use flare_helios::core::naming::GB10_DEVICES; + + let dir = tempfile::tempdir().unwrap(); + let sysfs = dir.path(); + let gpu = sysfs.join("bus/pci/devices/000f:01:00.0"); + fs::create_dir_all(&gpu).unwrap(); + fs::write(gpu.join("vendor"), "0x10de\n").unwrap(); + let report = |interconnect| { + evaluate_linux_host( + GpuProbe { + gpus: Vec::new(), + interconnect, + notes: Vec::new(), + }, + sysfs, + &sysfs.join("params"), + &sysfs.join("cmdline"), + || panic!("RoCE discovery must be skipped when there is no CX7 adapter"), + ) + }; + + fs::write(gpu.join("device"), "0x2b85\n").unwrap(); + assert!( + report(Interconnect::SingleGpu) + .checks + .iter() + .all(|check| check.id != "spark.cx7") + ); + + for device in GB10_DEVICES { + fs::write(gpu.join("device"), format!("0x{device:04x}\n")).unwrap(); + let report = report(Interconnect::SingleGpu); + assert!(report.ok); + assert_eq!(report.checks.len(), 2); + assert!( + report.checks.iter().any(|check| check.id == "pcie.interconnect") + ); + let cx7 = report + .checks + .iter() + .find(|check| check.id == "spark.cx7") + .unwrap(); + assert!( + report.checks.iter().all(|check| check.status == CheckStatus::NotApplicable) + ); + assert_eq!( + serde_json::to_value(cx7).unwrap()["status"], + "not_applicable" + ); + assert!(!render(&report, Canvas::sized(100, false)).contains("PASS")); + } + + let report = report(Interconnect::NoGpus); + assert!(report.ok); + assert!(!report.all_verified); + let pcie = report + .checks + .iter() + .find(|check| check.id == "pcie.interconnect") + .unwrap(); + assert_eq!(pcie.status, CheckStatus::Unverified); + } + #[test] fn nvidia_params_parser_and_checks_validate_all_required_fields() { let checks = check_nvidia_params(Ok(HEALTHY_NVIDIA_PARAMS)); @@ -1875,6 +1954,7 @@ RegistryDwords: "ForceP2P=0x01;RMForceP2PType=1;RMPcieP2PType=0" dir.path(), &dir.path().join("missing-params"), &dir.path().join("missing-cmdline"), + || panic!("RoCE discovery must be skipped on this host"), ); assert!(report.ok); assert!(!report.pcie_tp_checks_required); @@ -1933,7 +2013,9 @@ RegistryDwords: "ForceP2P=0x01;RMForceP2PType=1;RMPcieP2PType=0" interconnect: Interconnect::Pcie, notes: Vec::new(), }; - let report = evaluate_linux_host(pcie_probe, dir.path(), ¶ms, &cmdline); + let report = evaluate_linux_host(pcie_probe, dir.path(), ¶ms, &cmdline, || { + panic!("RoCE discovery must be skipped on this host") + }); assert!(!report.ok); let plain = render(&report, Canvas::sized(100, false)); assert!(plain.contains("Flare doctor"), "{plain}"); diff --git a/flare-cli/src/doctor/spark.rs b/flare-cli/src/doctor/spark.rs new file mode 100644 index 000000000..16a9cb2a1 --- /dev/null +++ b/flare-cli/src/doctor/spark.rs @@ -0,0 +1,524 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +use std::{fs, io, net::Ipv4Addr, path::Path}; + +use flare_helios::{ + core::naming::platform_from_pci, + execution::roce_fabric::{Fabric, ipv4_subnet_mask, link_local, port1_active}, +}; + +use super::{Check, CheckStatus, parse_u64_param}; + +const CONNECTX_7: u32 = 0x1021_15b3; +// NVIDIA's Spark setup guide uses MTU 9000 for a direct pair and 1500 for rings +// and switches. Set this to Some(9000) only after qualifying the intended fabric. +const PREFERRED_MTU: Option = None; + +fn pci_id(device: &Path) -> Option { + let read_id = |name| u16::try_from(parse_u64_param(&read(&device.join(name))?)?).ok(); + // NVML packs the device ID in the upper half and the vendor ID in the lower half. + Some((u32::from(read_id("device")?) << 16) | u32::from(read_id("vendor")?)) +} + +fn read(file: &Path) -> Option { + fs::read_to_string(file).ok().map(|s| s.trim().to_owned()) +} + +pub(super) fn check_host( + sysfs: &Path, + discover: impl FnOnce() -> flare_helios::Result, +) -> Option { + let mut gb10 = false; + let mut cx7 = false; + for id in fs::read_dir(sysfs.join("bus/pci/devices")) + .ok()? + .filter_map(Result::ok) + .filter_map(|device| pci_id(&device.path())) + { + gb10 |= platform_from_pci(id) == Some("gb10"); + cx7 |= id == CONNECTX_7; + } + if !gb10 { + return None; + } + if !cx7 { + return Some(result( + CheckStatus::NotApplicable, + Some("No ConnectX-7 PCI device".into()), + "This host has no ConnectX-7 adapter.".into(), + None, + )); + } + Some(check_fabric(sysfs, discover)) +} + +fn check_fabric(sysfs: &Path, discover: impl FnOnce() -> flare_helios::Result) -> Check { + match inspect(sysfs, discover) { + Ok(outcome) => outcome, + Err(error) => result( + CheckStatus::Unverified, + Some("RDMA device list unreadable".into()), + format!("Could not list RDMA devices in /sys/class/infiniband: {error}."), + Some("Check access to /sys/class/infiniband on this host."), + ), + } +} + +fn result( + status: CheckStatus, + actual: Option, + detail: String, + remediation: Option<&str>, +) -> Check { + Check { + id: "spark.cx7".into(), + name: "ConnectX-7 fabric".into(), + status, + expected: Some( + "An active ConnectX-7 link with an assigned IPv4 address and a RoCEv2 GID".into(), + ), + actual, + detail, + remediation: remediation.map(str::to_owned), + } +} + +fn inspect( + sysfs: &Path, + discover: impl FnOnce() -> flare_helios::Result, +) -> io::Result { + let root = sysfs.join("class/infiniband"); + let mut devices = match fs::read_dir(&root) { + Ok(entries) => entries.collect::>>()?, + Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(), + Err(error) => return Err(error), + }; + devices.retain(|device| pci_id(&device.path().join("device")) == Some(CONNECTX_7)); + devices.sort_by_key(|device| device.file_name()); + if devices.is_empty() { + return Ok(result( + CheckStatus::Warn, + Some("No ConnectX-7 RDMA devices".into()), + "ConnectX-7 is present on PCI, but the kernel exposes no CX7 RDMA devices.".into(), + Some( + "Check that the ConnectX-7 adapter is visible and the mlx5 RDMA driver is loaded.", + ), + )); + } + + let mut active = Vec::new(); + let mut unreadable = Vec::new(); + for device in &devices { + let name = device.file_name().to_string_lossy().into_owned(); + match port1_active(&device.path()) { + Ok(true) => active.push(name), + Ok(false) => {} + Err(_) => unreadable.push(name), + } + } + if active.is_empty() { + if !unreadable.is_empty() { + let names = unreadable.join(", "); + return Ok(result( + CheckStatus::Unverified, + Some(format!("Unreadable link state: {names}")), + format!("Could not read the link state for {names}."), + Some("Check the host's RDMA port state in /sys/class/infiniband."), + )); + } + let names: Vec<_> = devices + .iter() + .map(|device| device.file_name().to_string_lossy().into_owned()) + .collect(); + return Ok(result( + CheckStatus::Warn, + Some("No active ConnectX-7 links".into()), + format!( + "No active ConnectX-7 RDMA links ({}) for multi-host serving.", + names.join(", ") + ), + Some("Connect a CX7 port to a peer or switch and bring up its network interface."), + )); + } + + // Use the same GID index and assigned-address verification as serving. + let fabric = discover(); + let mut ready = Vec::new(); + if let Ok(fabric) = &fabric { + let mut unresolved = Vec::new(); + for endpoint in &fabric.endpoints { + // Serving discovers every RDMA adapter. This check covers ConnectX-7 devices. + if !active.contains(&endpoint.name) { + continue; + } + let Some((address, prefix)) = endpoint.ipv4 else { + unresolved.push(endpoint.name.as_str()); + continue; + }; + let netdev = root + .join(&endpoint.name) + .join(format!("ports/1/gid_attrs/ndevs/{}", fabric.gid_index)); + let Some(interface) = read(&netdev) else { + unresolved.push(endpoint.name.as_str()); + continue; + }; + let mtu = read(&sysfs.join("class/net").join(&interface).join("mtu")) + .and_then(|mtu| mtu.parse().ok()); + ready.push(Interface { + device: &endpoint.name, + interface, + address, + prefix, + mtu, + }); + } + if !ready.is_empty() { + let listed = ready + .iter() + .map(Interface::describe) + .collect::>() + .join(", "); + let mut detail = format!( + "{} of {} active CX7 devices supply IPv4 endpoints for serving at RoCEv2 GID index {}: {listed}.", + ready.len(), + active.len(), + fabric.gid_index + ); + let mut warnings = configuration_warnings(&ready); + if ready.iter().any(Interface::is_link_local) { + detail.push_str(" Link-local IPv4 requires an LLDP-confirmed direct peer."); + } + let unselected: Vec<_> = active + .iter() + .filter(|name| { + !fabric + .endpoints + .iter() + .any(|endpoint| &endpoint.name == *name) + }) + .map(String::as_str) + .collect(); + if !unselected.is_empty() { + detail.push_str(&format!( + " Serving discovery did not select {}.", + unselected.join(", ") + )); + } + if !unresolved.is_empty() { + warnings.push(format!( + "Could not resolve a local IPv4 address and prefix for {}.", + unresolved.join(", ") + )); + } + if !unreadable.is_empty() { + warnings.push(format!( + "Could not read the link state for {}.", + unreadable.join(", ") + )); + } + if warnings.is_empty() { + return Ok(result(CheckStatus::Pass, Some(listed), detail, None)); + } + detail.push(' '); + detail.push_str(&warnings.join(" ")); + return Ok(result( + CheckStatus::Warn, + Some(listed), + detail, + Some("Check IPv4 subnet and MTU settings against the intended peers and switch."), + )); + } + } + + let reason = match fabric { + Err(error) => error.to_string(), + Ok(fabric) => format!( + "discovery could not verify a local IPv4 address and prefix on a ConnectX-7 device at RoCEv2 GID index {}", + fabric.gid_index + ), + }; + Ok(result( + CheckStatus::Warn, + Some("No usable ConnectX-7 IPv4 endpoint".into()), + format!("Active ConnectX-7 links ({}): {reason}.", active.join(", ")), + Some( + "Check the IPv4 addresses, prefixes, and RoCEv2 GID entries on the ConnectX-7 interfaces.", + ), + )) +} + +struct Interface<'a> { + device: &'a str, + interface: String, + address: Ipv4Addr, + prefix: u8, + mtu: Option, +} + +impl Interface<'_> { + fn is_link_local(&self) -> bool { + link_local((u32::from(self.address), self.prefix)) + } + + fn describe(&self) -> String { + let mtu = self + .mtu + .map_or_else(String::new, |mtu| format!(", MTU {mtu}")); + format!( + "{} ({}, {}/{}{mtu})", + self.device, self.interface, self.address, self.prefix + ) + } +} + +fn configuration_warnings(ports: &[Interface<'_>]) -> Vec { + let mut warnings = Vec::new(); + for (i, port) in ports.iter().enumerate() { + let name = &port.interface; + let address = u32::from(port.address); + let host_bits = !ipv4_subnet_mask(port.prefix); + let host = address & host_bits; + if matches!(port.prefix, 0 | 32) || (port.prefix < 31 && (host == 0 || host == host_bits)) { + warnings.push(format!( + "Review {name}'s IPv4 subnet ({}/{}).", + port.address, port.prefix + )); + } + + match (port.mtu, PREFERRED_MTU) { + (Some(mtu), Some(preferred)) if mtu < preferred => { + warnings.push(format!( + "{name}'s MTU {mtu} is below the preferred {preferred}. A larger MTU can reduce packet overhead when the full path supports it." + )); + } + (None, _) => warnings.push(format!("Could not read the MTU for {name}.")), + _ => {} + } + + for other in &ports[..i] { + if port.interface == other.interface || (port.is_link_local() && other.is_link_local()) + { + continue; + } + let mask = ipv4_subnet_mask(port.prefix.min(other.prefix)); + if address & mask == u32::from(other.address) & mask { + warnings.push(format!( + "IPv4 subnets overlap on {} and {name}.", + other.interface + )); + } + } + } + warnings +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + use crate::doctor::{GpuProbe, Interconnect, Report, evaluate_linux_host, render}; + use crate::inspect::Canvas; + use flare_helios::execution::roce_fabric; + + fn write(root: &Path, path: &str, content: &str) { + let file = root.join(path); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, content).unwrap(); + } + + fn add_spark(sysfs: &Path) { + write(sysfs, "bus/pci/devices/000f:01:00.0/vendor", "0x10de\n"); + write(sysfs, "bus/pci/devices/000f:01:00.0/device", "0x2e12\n"); + write(sysfs, "bus/pci/devices/0000:01:00.0/vendor", "0x15b3\n"); + write(sysfs, "bus/pci/devices/0000:01:00.0/device", "0x1021\n"); + } + + fn report(sysfs: &Path, prefix: impl Fn(&str, Ipv4Addr) -> Option) -> Report { + evaluate_linux_host( + GpuProbe { + gpus: Vec::new(), + interconnect: Interconnect::SingleGpu, + notes: Vec::new(), + }, + sysfs, + &sysfs.join("params"), + &sysfs.join("cmdline"), + || { + roce_fabric::discover_in(&sysfs.join("class/infiniband"), prefix, |_| { + Default::default() + }) + }, + ) + } + + fn cx7(report: &Report) -> &Check { + report + .checks + .iter() + .find(|check| check.id == "spark.cx7") + .unwrap() + } + + #[test] + fn cx7_readiness_requires_a_live_ipv4_address_at_the_serving_gid_index() { + let dir = tempfile::tempdir().unwrap(); + let sysfs = dir.path(); + add_spark(sysfs); + let no_driver = report(sysfs, |_, _| None); + assert!(no_driver.ok); + assert_eq!(cx7(&no_driver).status, CheckStatus::Warn); + assert!( + cx7(&no_driver) + .detail + .contains("kernel exposes no CX7 RDMA devices") + ); + assert!(render(&no_driver, Canvas::sized(100, false)).contains("1 warning,")); + + let root = sysfs.join("class/infiniband"); + let port = root.join("roce0/ports/1"); + write(&root, "roce0/device/vendor", "0x15b3\n"); + write(&root, "roce0/device/device", "0x1021\n"); + write(&root, "roce1/device/vendor", "0x15b3\n"); + write(&root, "roce1/device/device", "0x1021\n"); + write(&root, "roce1/ports/1/state", "1: DOWN\n"); + write(&port, "state", "1: DOWN\n"); + let no_links = report(sysfs, |_, _| None); + assert!(no_links.ok); + assert_eq!(cx7(&no_links).status, CheckStatus::Warn); + assert!( + cx7(&no_links) + .detail + .contains("No active ConnectX-7 RDMA links") + ); + write(&port, "state", "4: ACTIVE\n"); + write(&port, "gid_attrs/ndevs/3", "enp1s0f0np0\n"); + write(&port, "gids/3", "0000:0000:0000:0000:0000:ffff:c0a8:0b02\n"); + write(sysfs, "class/net/enp1s0f0np0/mtu", "9000\n"); + + let inspect = |has_ip| { + report(sysfs, |netdev, addr| { + (has_ip && netdev == "enp1s0f0np0" && addr.octets() == [192, 168, 11, 2]) + .then_some(24) + }) + }; + write(&port, "gid_attrs/types/3", "RoCE v1\n"); + assert_eq!(cx7(&inspect(true)).status, CheckStatus::Warn); + write(&port, "gid_attrs/types/3", "RoCE v2\n"); + assert_eq!(cx7(&inspect(false)).status, CheckStatus::Warn); + let report = inspect(true); + let ready = cx7(&report); + assert!(report.ok); + assert_eq!(ready.status, CheckStatus::Pass, "{}", ready.detail); + assert!( + ready + .actual + .as_deref() + .unwrap() + .contains("enp1s0f0np0, 192.168.11.2/24, MTU 9000") + ); + write(sysfs, "class/net/enp1s0f0np0/mtu", "1500\n"); + let standard_mtu = inspect(true); + assert!(standard_mtu.ok); + assert_eq!(cx7(&standard_mtu).status, CheckStatus::Pass); + assert!(cx7(&standard_mtu).detail.contains("MTU 1500")); + fs::remove_file(sysfs.join("class/net/enp1s0f0np0/mtu")).unwrap(); + let unreadable_mtu = inspect(true); + assert_eq!(cx7(&unreadable_mtu).status, CheckStatus::Warn); + assert!( + cx7(&unreadable_mtu) + .detail + .contains("Could not read the MTU") + ); + fs::remove_file(port.join("state")).unwrap(); + let unreadable_link = inspect(true); + assert!(!unreadable_link.all_verified); + assert_eq!(cx7(&unreadable_link).status, CheckStatus::Unverified); + } + + #[test] + fn cx7_preflight_reports_unselected_devices_and_unresolved_prefixes() { + let dir = tempfile::tempdir().unwrap(); + let sysfs = dir.path(); + add_spark(sysfs); + for i in 0..3 { + let device = sysfs.join(format!("class/infiniband/roce{i}")); + write(&device, "device/vendor", "0x15b3\n"); + write(&device, "device/device", "0x1021\n"); + write(&device, "ports/1/state", "4: ACTIVE\n"); + if i == 2 { + continue; + } + write(&device, "ports/1/gid_attrs/types/3", "RoCE v2\n"); + write(&device, "ports/1/gid_attrs/ndevs/3", &format!("eth{i}\n")); + write( + &device, + "ports/1/gids/3", + &format!("0000:0000:0000:0000:0000:ffff:c0a8:{i:02x}02\n"), + ); + write(sysfs, &format!("class/net/eth{i}/mtu"), "9000\n"); + } + let ready = report(sysfs, |_, _| Some(24)); + let check = cx7(&ready); + assert_eq!(check.status, CheckStatus::Pass, "{}", check.detail); + assert!(check.detail.contains("2 of 3 active CX7 devices")); + assert!( + check + .detail + .contains("Serving discovery did not select roce2.") + ); + + let unresolved = report(sysfs, |netdev, _| (netdev == "eth0").then_some(24)); + assert!(unresolved.ok); + let check = cx7(&unresolved); + assert_eq!(check.status, CheckStatus::Warn, "{}", check.detail); + assert!( + check + .detail + .contains("Serving discovery did not select roce2.") + ); + assert!( + check + .detail + .contains("Could not resolve a local IPv4 address and prefix for roce1.") + ); + } + + #[test] + fn cx7_subnets_accept_point_to_point_prefixes_and_flag_overlap() { + let mut interfaces = [ + Interface { + device: "roce0", + interface: "enp1s0f0np0".into(), + address: Ipv4Addr::new(192, 168, 0, 0), + prefix: 31, + mtu: Some(9000), + }, + Interface { + device: "roce1", + interface: "enp1s0f1np1".into(), + address: Ipv4Addr::new(192, 168, 1, 15), + prefix: 24, + mtu: Some(9000), + }, + ]; + assert!(configuration_warnings(&interfaces).is_empty()); + interfaces[1].address = Ipv4Addr::new(192, 168, 0, 15); + assert!( + configuration_warnings(&interfaces) + .join(" ") + .contains("subnets overlap") + ); + interfaces[1].prefix = 32; + assert!( + configuration_warnings(&interfaces) + .join(" ") + .contains("192.168.0.15/32") + ); + interfaces[0].address = Ipv4Addr::new(169, 254, 1, 2); + interfaces[1].address = Ipv4Addr::new(169, 254, 2, 2); + interfaces.iter_mut().for_each(|port| port.prefix = 16); + assert!(configuration_warnings(&interfaces).is_empty()); + } +} diff --git a/helios/src/execution/roce_fabric.rs b/helios/src/execution/roce_fabric.rs index b428cbef4..e61018a5c 100644 --- a/helios/src/execution/roce_fabric.rs +++ b/helios/src/execution/roce_fabric.rs @@ -192,17 +192,16 @@ fn lldp_neighbors(netdevs: &[String]) -> std::collections::BTreeMap Option<(u32, u8)> { - self.ipv4.map(|(address, prefix)| { - let mask = if prefix == 0 { - 0 - } else { - u32::MAX << (32 - prefix as u32) - }; - (u32::from(address) & mask, prefix) - }) + self.ipv4 + .map(|(address, prefix)| (u32::from(address) & ipv4_subnet_mask(prefix), prefix)) } } +/// IPv4 subnet mask for a prefix length in 0..=32, shared by route planning and `flare doctor`. +pub fn ipv4_subnet_mask(prefix: u8) -> u32 { + u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0) +} + /// This host's RoCE devices in name order, and the GID index and traffic class they use. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Fabric { @@ -345,6 +344,22 @@ fn mapped_ipv4(gid: &str) -> Option { u32::from_str_radix(&hex[24..], 16).ok().map(Ipv4Addr::from) } +/// Whether serving and `flare doctor` consider port 1 active, from the RDMA device's sysfs directory. +pub fn port1_active(device: &Path) -> std::io::Result { + std::fs::read_to_string(device.join("ports/1/state")).map(|state| state.contains("ACTIVE")) +} + +/// Whether port 1 advertises an IPv4-mapped RoCEv2 GID at the given index. +fn has_rocev2_ipv4_gid(device: &Path, index: u32) -> bool { + let port = device.join("ports/1"); + read(&port.join(format!("gid_attrs/types/{index}"))) + .is_some_and(|kind| kind.eq_ignore_ascii_case("RoCE v2")) + && read(&port.join(format!("gids/{index}"))) + .as_deref() + .and_then(mapped_ipv4) + .is_some() +} + /// Discover the RoCE devices under `root` (normally /sys/class/infiniband): every device whose /// port 1 is active and holds a RoCEv2 GID at the chosen index. The index is 3 when every active /// device has a RoCEv2 IPv4 GID there, otherwise the lowest index at which one does. `prefix` @@ -367,21 +382,10 @@ pub fn discover_in( .ok() .map(|entry| entry.file_name().to_string_lossy().into_owned()) }) - .filter(|name| { - read(&root.join(name).join("ports/1/state")) - .is_some_and(|state| state.contains("ACTIVE")) - }) + .filter(|name| port1_active(&root.join(name)).unwrap_or(false)) .collect(); names.sort(); - let roce_v2_ipv4 = |name: &str, index: u32| { - let port = root.join(name).join("ports/1"); - read(&port.join(format!("gid_attrs/types/{index}"))) - .is_some_and(|kind| kind.eq_ignore_ascii_case("RoCE v2")) - && read(&port.join(format!("gids/{index}"))) - .as_deref() - .and_then(mapped_ipv4) - .is_some() - }; + let roce_v2_ipv4 = |name: &str, index: u32| has_rocev2_ipv4_gid(&root.join(name), index); let gid_index = if !names.is_empty() && names .iter() @@ -617,8 +621,9 @@ fn any_lldp_adjacency(endpoints: &[Vec]) -> bool { } /// Whether `network` lies in IPv4 link-local space (169.254.0.0/16). Hosts using link-local -/// addressing share that subnet whether or not their ports are linked. -fn link_local((address, prefix): (u32, u8)) -> bool { +/// addressing share that subnet whether or not their ports are linked. Route planning and +/// `flare doctor` use the same link-local classification. +pub fn link_local((address, prefix): (u32, u8)) -> bool { prefix >= 16 && address & 0xffff_0000 == 0xa9fe_0000 } From 9375d679ccd2c9b68958e8d5f3d935ee5eb6615a Mon Sep 17 00:00:00 2001 From: Wiktor Zdrojewski <59113535+wektorz@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:41:16 +0100 Subject: [PATCH 05/27] feat: add gb206 platform support (#502) Automatic Hub revision detection and core export naming previously recognized only `ga102`, `ga10b`, `gb10`, `gb202`, and `gb300` in `helios/src/core/naming.rs`. Running `flare download`, `flare run`, or core export naming on NVIDIA Blackwell GB206 GPUs (such as GeForce RTX 5060 Ti, PCI device ID `0x2d04`) therefore failed with an unsupported PCI ID error unless `--revision` was specified manually. Adding `gb206` to the shared PCI-to-platform table extends hardware detection, catalog matching, and export naming without duplicating device tables. What changed: - `helios/src/core/naming.rs`: expands `PLATFORMS` from 5 to 6 entries (`["ga102", "ga10b", "gb10", "gb202", "gb206", "gb300"]`), defines `GB206_DEVICES` with 9 NVIDIA GB206 PCI device IDs (`0x2d04`, `0x2d05`, `0x2d18`, `0x2d19`, `0x2d30`, `0x2d39`, `0x2d58`, `0x2d59`, `0x2d79`), adds a `GB206_DEVICES` branch in `platform_from_pci`, and adds unit tests covering every `GB206_DEVICES` entry and rejecting non-NVIDIA vendor IDs (`0x2d04_1af4`). - `flare/src/catalog.rs`: adds `{"name": "gb206"}` to the all-platforms branch fixture in `published_build_match_uses_all_platform_branches`. - `flare-cli/src/cli.rs`, `docs/cli-design.md`, and `docs/core-format-design.md`: lists `gb206` alongside the other supported platform revision and cache-entry identifiers. - Orbit GPU revision detection (`flare-cli/src/orbit/gpu.rs`) remains unchanged. Result: `flare` device detection, Hub catalog platform matching, and core export naming recognize supported NVIDIA GB206 PCI device IDs as `gb206` while preserving all existing platform mappings (`ga102`, `ga10b`, `gb10`, `gb202`, and `gb300`). Evidence: - Local CPU tests (`--locked --release`) on merged head `e4166286` (base `2bdc8472`): - `helios` (`--features runtime-core,server --lib -- core::`): 483 passed, 0 failed, 11 ignored (including `core::naming::` tests for `gb206`, `ga10b`, and `gb300`). - `flare`: 228 unit tests passed (4 ignored), 7 `packed_canonical_download` tests passed, and 1 `reference_workflows` test passed (including `catalog::tests::published_build_match_uses_all_platform_branches`). - `flare-cli`: 24 integration tests passed (`cache_commands`: 7, `cli`: 6, `inspect`: 4, `unverified_payload`: 7); 196 of 197 unit tests passed (3 ignored), with 1 unrelated pre-existing `BrokenPipe` failure in `distribution::tests::source_waits_for_receiver_file_verification`. - Author-reported hardware verification on PR #502: verified on GeForce RTX 5060 Ti 16GB (`0x2d04`). - Limitations: live GB206 hardware detection and the remaining PCI IDs in `GB206_DEVICES` were not exercised locally in this merge environment, and Orbit placement remains capability-derived. Signed-off-by: Wiktor Zdrojewski Co-Authored-By: Luke Alonso Signed-off-by: Luke Alonso Design-Signed-Off-By: Antigravity (Gemini); design-review=c3a9 --- docs/cli-design.md | 6 +++--- docs/core-format-design.md | 2 +- flare-cli/src/cli.rs | 2 +- flare/src/catalog.rs | 2 +- helios/src/core/naming.rs | 20 +++++++++++++++++++- 5 files changed, 25 insertions(+), 7 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 9cab000bc..d90ceb0ff 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -901,10 +901,10 @@ flare run ORG/MODEL@gb202 --filename model.safetensors --gpus 0,1,2,3 These examples use `ORG/MODEL` as a repository placeholder. Repositories contain prepared Flare cores, not source Transformers checkpoints. Hardware variants -are separate Hugging Face revisions named `ga102`, `gb10`, `gb202`, and `gb300`. Automatic selection +are separate Hugging Face revisions named `ga102`, `gb10`, `gb202`, `gb206`, and `gb300`. Automatic selection queries the selected GPUs' PCI device identifiers through NVML without initializing CUDA. GB10 selects `gb10`; known GB202 devices, including RTX PRO -6000 Blackwell, select `gb202`; GB300 selects `gb300`; known GA102 devices select `ga102`. All selected GPUs must belong to the same family. +6000 Blackwell, select `gb202`; known GB206 devices, including GeForce RTX 5060 Ti, select `gb206`; GB300 selects `gb300`; known GA102 devices select `ga102`. All selected GPUs must belong to the same family. An unknown identifier or a driver unable to report it requires an explicit revision. GPU selection follows `CUDA_VISIBLE_DEVICES` for both commands. Revision detection runs in a short-lived process so NVML's worker threads cannot @@ -937,7 +937,7 @@ Both commands accept these download options: | Flag | Meaning | Default | |---|---|---| -| `--revision REVISION` | Explicit Hub branch, tag, or commit | Recorded model origin, otherwise detected `ga102`, `gb10`, `gb202`, or `gb300` | +| `--revision REVISION` | Explicit Hub branch, tag, or commit | Recorded model origin, otherwise detected `ga102`, `gb10`, `gb202`, `gb206`, or `gb300` | | `--filename FILE` | Repository-relative prepared core filename | Sole primary `.safetensors` file | | `--cache-dir PATH` | Parent for the shared Hugging Face download transport cache | Flare model cache | | `--token-file PATH` | File containing a Hub access token (must exist and be non-empty when passed) | `HF_TOKEN`, then `$HF_TOKEN_PATH` / `$HF_HOME/token` / `~/.cache/huggingface/token` when present, otherwise unauthenticated | diff --git a/docs/core-format-design.md b/docs/core-format-design.md index 8582e4a11..416d03a62 100644 --- a/docs/core-format-design.md +++ b/docs/core-format-design.md @@ -751,7 +751,7 @@ A published cache entry is named for its selected deployments: An entry containing several TP sizes joins their labels in ascending order, without duplicates: `gb202-tp1+tp2-202610170923`. The platform is the device identifier recorded by preparation (`ga102`, `gb10`, -`gb202`, or `gb300`), never an SM architecture name. Downloads use the authenticated device +`gb202`, `gb206`, or `gb300`), never an SM architecture name. Downloads use the authenticated device identity; cores without one use `unknown-device`, including union names such as `unknown-device-tp1+tp2-202610170923`. The timestamp records entry creation in UTC with minute resolution. diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index ed93bfc55..8e50b534f 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -199,7 +199,7 @@ pub struct CacheGc { #[derive(Debug, Args, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct HubOptions { - /// Hub revision; uses the model origin when cached, otherwise detects ga102, gb10, gb202, or gb300. + /// Hub revision; uses the model origin when cached, otherwise detects ga102, gb10, gb202, gb206, or gb300. #[arg(long, value_name = "REVISION", help_heading = "Download options")] pub revision: Option, diff --git a/flare/src/catalog.rs b/flare/src/catalog.rs index 783e0658d..0a4cbcfff 100644 --- a/flare/src/catalog.rs +++ b/flare/src/catalog.rs @@ -559,7 +559,7 @@ mod tests { } } let refs = serde_json::from_value(json!({"branches": [ - {"name": "ga102-tp1"}, {"name": "ga10b-tp1"}, {"name": "gb10-tp1"}, {"name": "gb202"}, {"name": "gb300-tp8"} + {"name": "ga102-tp1"}, {"name": "ga10b-tp1"}, {"name": "gb10-tp1"}, {"name": "gb202"}, {"name": "gb206"}, {"name": "gb300-tp8"} ]})).unwrap(); let mut entry = CatalogEntry::default(); let branches = apply_refs(&mut entry, refs, Some(target)); diff --git a/helios/src/core/naming.rs b/helios/src/core/naming.rs index defb6db59..ddd6b7d34 100644 --- a/helios/src/core/naming.rs +++ b/helios/src/core/naming.rs @@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// Platforms a core may be named for. These are the NVIDIA device /// identifiers Flare already uses for revisions, not SM architecture names. -pub const PLATFORMS: [&str; 5] = ["ga102", "ga10b", "gb10", "gb202", "gb300"]; +pub const PLATFORMS: [&str; 6] = ["ga102", "ga10b", "gb10", "gb202", "gb206", "gb300"]; /// Platform for one NVIDIA PCI id in NVML's `device<<16 | vendor` layout. /// @@ -22,6 +22,12 @@ pub const GB202_DEVICES: [u32; 9] = [ 0x2b85, 0x2b87, 0x2b8c, 0x2bb1, 0x2bb2, 0x2bb3, 0x2bb4, 0x2bb5, 0x2bb9, ]; +/// GB206 device identifiers for the SM120 platform: GeForce RTX 5060 Ti, 5060, +/// and mobile/workstation variants. +pub const GB206_DEVICES: [u32; 9] = [ + 0x2d04, 0x2d05, 0x2d18, 0x2d19, 0x2d30, 0x2d39, 0x2d58, 0x2d59, 0x2d79, +]; + /// GB10 and RTX Spark N1X device identifiers for the SM121 platform. pub const GB10_DEVICES: [u32; 5] = [0x2e02, 0x2e03, 0x2e06, 0x2e12, 0x2e2a]; @@ -46,6 +52,9 @@ pub fn platform_from_pci(pci_id: u32) -> Option<&'static str> { if GA102_DEVICES.contains(&device) { return Some("ga102"); } + if GB206_DEVICES.contains(&device) { + return Some("gb206") + } GB202_DEVICES.contains(&device).then_some("gb202") } @@ -204,6 +213,13 @@ mod tests { "{device:#06x}" ); } + for device in GB206_DEVICES { + assert_eq!( + platform_from_pci(device << 16 | 0x10de), + Some("gb206"), + "{device:#06x}" + ); + } for device in GA102_DEVICES { assert_eq!( platform_from_pci(device << 16 | 0x10de), @@ -211,6 +227,8 @@ mod tests { "{device:#06x}" ); } + assert_eq!(platform_from_pci(0x2d04_10de), Some("gb206")); + assert_eq!(platform_from_pci(0x2d04_1af4), None); assert_eq!(platform_from_pci(0x2204_1af4), None); assert_eq!(platform_from_pci(0x2484_10de), None); assert_eq!(platform_from_pci(0x2bbc_1af4), None); From ba3afb13a7e9836080c23eadf8e1c17ee96e6e7a Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 28 Nov 2026 14:18:41 -0800 Subject: [PATCH 06/27] Fix CUDA 12 batched copies, Linux ARM64 release portability, and Selene unified-memory budgeting (#589) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three concrete defects affect CUDA 12.x GPUs, stock JetPack 6 / Ubuntu 22.04 Linux hosts, and unified-memory prefix-cache offloading: 1. On CUDA < 13.0 drivers where `cuMemcpyBatchAsync_v2` is absent, `Stream::copy_batch` in `helios/src/cuda.rs` fell back to `cuMemcpyDtoDAsync_v2`. Callers in `helios/src/execution/transport.rs` and `helios/src/offload/transfer.rs` pass raw pinned-host pointers from `cuMemHostAlloc(..., 0)` alongside device pointers, which breaks discrete CUDA 12.x GPUs because `cuMemcpyDtoDAsync_v2` requires device-to-device semantics whereas `cuMemcpyAsync` infers transfer direction under UVA. 2. `.github/workflows/release.yml` built Linux release tarballs on Ubuntu 24.04 runners (`GLIBC_2.39`), and `helios/build.rs` hard-linked `libibverbs` when the `roce` feature is enabled (default on Linux aarch64). Stock JetPack 6 (Ubuntu 22.04, `glibc 2.35`, without `libibverbs1`) therefore could not execute `flare-linux-arm64.tgz`, which CI missed because smoke checks ran only in `ubuntu:24.04` with `libibverbs1` installed. 3. In `selene/src/offload.rs`, `host_pool_budget` always subtracted an unscaled `2 GiB + total / 20` reserve and `prepare_with_inputs` re-evaluated it after GPU KV allocation—ignoring small-SoC headroom scaling (`<= 16 GiB` and `<= 64 GiB`) and explicit `--memory-limit` settings on integrated GPUs, which shrunk intake or failed pool-only capture startup. Separately, memory-only `--prefix-cache-memory` unconditionally required `HOST_NUMA` VMM split allocation (`SlabPool::sized_by_rank`), failing on GA10B and Windows WDDM. Finally, `eos/src/unix.rs` passed `MAP_POPULATE` to `mmap` before calling `madvise(MADV_HUGEPAGE)`, faulting 4 KiB base pages before transparent huge page advice took effect. Changes: - CUDA 12 batched-copy fallback (`helios/src/cuda.rs`, `docs/prefix-cache-offload.md`): Added `cuMemcpyAsync` to `Driver` and replaced `cuMemcpyDtoDAsync_v2` in `Stream::copy_batch`'s fallback loop with `cuMemcpyAsync` while retaining `cuMemcpyDtoDAsync_v2` for `copy_dtod_async`. - Lazy `libibverbs.so.1` loading and Ubuntu 22.04 release builds (`helios/native/roce_proxy_dlopen.c`, `helios/build.rs`, `helios/src/execution/roce.rs`, `.github/workflows/release.yml`, `flare-cli/Cargo.toml`, `flare/Cargo.toml`, `helios/Cargo.toml`, `docs/release.md`, `docs/runtime-core-design.md`, `docs/multi-host.md`): Replaced direct `-libverbs` linking in `helios/build.rs` with `-ldl` and compiled `helios/native/roce_proxy_dlopen.c`, which lazily loads `libibverbs.so.1` via `dlopen` / `dlvsym` (`IBVERBS_1.1`, optional `IBVERBS_1.8`) under `pthread_once` and wraps the vendored `helios/native/roce_proxy.c` without modifying it. `RoceTransport::open` calls `roce_ensure_libibverbs` after preflight checks so missing RDMA libraries fail with an install hint only during multi-host RoCE setup. Updated `.github/workflows/release.yml` to build and package both Linux targets inside `ubuntu:22.04`, assert no `libibverbs.so` `DT_NEEDED` entry and no `GLIBC_` symbol version above `2.35`, and smoke-test the extracted archive in clean `ubuntu:22.04` and `ubuntu:24.04` containers without `libibverbs1`. - Selene host budgeting, `HOST_NUMA` fallback, and Eos THP ordering (`selene/src/offload.rs`, `selene/src/offload/tests.rs`, `selene/src/registrar.rs`, `selene/src/slab.rs`, `helios/src/cuda.rs`, `helios/src/offload/mod.rs`, `helios/src/offload/registrar.rs`, `helios/src/runtime_core/memory.rs`, `helios/src/runtime_core/model.rs`, `eos/src/unix.rs`, `docs/prefix-cache-offload.md`): Replaced the fixed `2 GiB` host headroom in `selene/src/offload.rs` with `host_service_headroom_bytes` (`64 MiB` at `<= 16 GiB`, `min(2 GiB, total / 32)` above `16 GiB`) shared by `helios/src/runtime_core/memory.rs`. Added `integrated_offload_host_budget` to honor explicit `--memory-limit` on integrated GPUs without implicit reserves, and threaded the pre-planned offload host budget from `NativeModel::allocate_caches` into `NativeModel::prepare_offload` -> `prepare_with_inputs_budget` so post-KV-allocation setup matches the budget already reserved. Added `try_map_device_host_parts` / `HostRegistrar::try_map_split` / `SlabPool::try_sized_by_rank` so `CUDA_ERROR_INVALID_VALUE` (1) or `CUDA_ERROR_NOT_SUPPORTED` (801) on `HOST_NUMA` VMM falls back to a registered anonymous mapping while real errors such as OOM still propagate. Updated `eos/src/unix.rs::map_host` to omit `MAP_POPULATE`, call `madvise(MADV_HUGEPAGE)` first, and then prefault via `madvise(MADV_POPULATE_WRITE)` on Linux with a page-stride `write_volatile` fallback. Claimed results: - Observed on x86_64 Linux: building `flare-cli --features roce` inside `ubuntu:22.04` with `libibverbs-dev` produces an executable with `Max GLIBC: GLIBC_2.34`, no `libibverbs.so` `DT_NEEDED` entry, and no `ibv_*` dynamic symbols, passing `flare --version` and `flare {run,agent,orbit} --help` in clean `ubuntu:22.04` and `ubuntu:24.04` containers without `libibverbs1`. `eos::map_host` sets `MADV_HUGEPAGE` (`VmFlags: hg`) before prefaulting. - Expected on hardware not tested here: stock JetPack 6 ARM64 hosts can run `flare-linux-arm64.tgz` without `libibverbs1`, discrete CUDA 12.x GPUs execute `Stream::copy_batch` without `cuMemcpyDtoDAsync_v2` host-pointer failures, and GA10B / Windows WDDM hosts support `--prefix-cache-memory` without `HOST_NUMA` VMM failure or post-KV-allocation host-budget double-subtraction. Supporting evidence and limitations: - `cargo test --locked --release --manifest-path eos/Cargo.toml`: 2 passed (including `map_host_advises_hugepages_and_prefaults_zeroed_pages`). - `cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support`: 506 passed (including small-SoC/explicit-limit budget tests, `prepare_with_inputs_budget` tests, and `HOST_NUMA` fallback vs OOM tests). - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server,roce --lib -- cuda::tests runtime_core::memory::tests runtime_core::model::tests offload:: execution::roce::tests`: 40 passed, 16 ignored (GPU-only), including `lazy_libibverbs_loader_resolves_symbols_or_reports_install_hint` and `integrated_offload_host_budget_matches_small_soc_scaling_and_explicit_limits`. - `cargo test --locked --release --manifest-path flare/Cargo.toml`: 228 passed across full run (226 passed + 2 hub tests passed on individual rerun), 4 ignored. - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`: 24/24 integration tests passed (`cache_commands`, `cli`, `inspect`, `unverified_payload`); 196 unit tests passed (195 + 1 serial rerun), 3 ignored, with 1 unrelated timeout/BrokenPipe in untouched `distribution::tests::source_waits_for_receiver_file_verification`. - `cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support`: 84/85 passed in `tests/client.rs`; 1 unrelated failure in untouched `a_record_put_into_a_manager_on_another_host_is_restored_over_tcp` (`stream: 2 windows` vs `>= 3` on `moved()` metrics snapshot). - End-to-end x86_64 Docker build in `ubuntu:22.04` (`--features roce`, `libibverbs-dev`, `packaging/archive.py`) + ELF `DT_NEEDED`/`--version-info` checks + clean `ubuntu:22.04` and `ubuntu:24.04` smoke checks passed. - Unrun checks: native `aarch64` build and `ubuntu-24.04-arm` CI run, live hardware GPU tests on discrete CUDA 12.x / Jetson Orin GA10B / Windows WDDM, and full `helios` chat-template tests requiring `FLARE_TEST_TEMPLATE_DIR`. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=c3a9 Signed-off-by: Luke Alonso --- .github/workflows/release.yml | 82 +++++++---- docs/multi-host.md | 6 +- docs/prefix-cache-offload.md | 19 ++- docs/release.md | 25 ++-- docs/runtime-core-design.md | 4 +- eos/src/unix.rs | 61 +++++++- flare-cli/Cargo.toml | 4 +- flare/Cargo.toml | 4 +- helios/Cargo.toml | 2 +- helios/build.rs | 5 +- helios/native/roce_proxy_dlopen.c | 236 ++++++++++++++++++++++++++++++ helios/src/cuda.rs | 79 +++++++--- helios/src/execution/roce.rs | 21 ++- helios/src/offload/mod.rs | 28 +++- helios/src/offload/registrar.rs | 8 + helios/src/runtime_core/memory.rs | 174 +++++++++++++++++++--- helios/src/runtime_core/model.rs | 12 +- selene/src/offload.rs | 148 +++++++++++++++++-- selene/src/offload/tests.rs | 159 ++++++++++++++++++++ selene/src/registrar.rs | 11 ++ selene/src/slab.rs | 39 +++-- 21 files changed, 994 insertions(+), 133 deletions(-) create mode 100644 helios/native/roce_proxy_dlopen.c diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 15a94e6bf..3f8499e12 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,26 +47,38 @@ jobs: arch: arm64 target: aarch64-unknown-linux-gnu build-packages: libibverbs-dev - runtime-packages: libibverbs1 ibverbs-providers runs-on: ${{ matrix.os }} env: VERSION: ${{ needs.version.outputs.version }} ARCHIVE: flare-linux-${{ matrix.arch }}.tgz steps: - uses: actions/checkout@v4 - - name: Install build dependencies - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends build-essential cmake nasm pkg-config protobuf-compiler ${{ matrix.build-packages }} - rustup toolchain install "$RUST_TOOLCHAIN" --profile minimal --component rust-docs - rustup default "$RUST_TOOLCHAIN" - name: Set the release version run: python3 scripts/set_release_version.py "$VERSION" - - name: Build the CLI - run: cargo build --locked --release --manifest-path flare-cli/Cargo.toml --bin flare - - name: Package the CLI and license notices - run: python3 packaging/archive.py --binary flare-cli/target/release/flare --target ${{ matrix.target }} --output "$ARCHIVE" - - name: Check the archive in a clean Ubuntu 24.04 container + - name: Build and package the CLI in Ubuntu 22.04 (glibc 2.35) + run: | + docker run --rm --volume "$PWD:/src" --workdir /src \ + --env RUST_TOOLCHAIN \ + --env TARGET="${{ matrix.target }}" \ + --env ARCHIVE \ + --env BUILD_PACKAGES="${{ matrix.build-packages }}" \ + --env HOST_UID="$(id -u)" \ + --env HOST_GID="$(id -g)" \ + ubuntu:22.04 bash -euc ' + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends \ + build-essential ca-certificates cmake curl git nasm pkg-config \ + protobuf-compiler python3 $BUILD_PACKAGES + curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ + --profile minimal --default-toolchain "$RUST_TOOLCHAIN" --component rust-docs + export PATH="$HOME/.cargo/bin:$PATH" + export CARGO_TARGET_DIR=/tmp/target + cargo build --locked --release --manifest-path flare-cli/Cargo.toml --bin flare + python3 packaging/archive.py --binary /tmp/target/release/flare \ + --target "$TARGET" --output "$ARCHIVE" + chown "$HOST_UID:$HOST_GID" "$ARCHIVE"' + - name: Verify ELF dependencies and check the archive in clean Ubuntu 22.04 and 24.04 containers run: | mkdir check tar -xzf "$ARCHIVE" -C check @@ -77,22 +89,36 @@ jobs: exit 1 fi done - # The container has only Ubuntu 24.04's libraries, so libraries - # installed on the runner cannot satisfy the executable. - docker run --rm --volume "$PWD/check/flare:/opt/flare:ro" \ - --env VERSION --env RUNTIME_PACKAGES="${{ matrix.runtime-packages }}" ubuntu:24.04 bash -euc ' - if [[ -n "$RUNTIME_PACKAGES" ]]; then - apt-get update - apt-get install -y --no-install-recommends $RUNTIME_PACKAGES - fi - reported=$(/opt/flare/flare --version) - if [[ "$reported" != "flare $VERSION" ]]; then - echo "::error::flare --version printed \"$reported\"; expected \"flare $VERSION\"." - exit 1 - fi - for command in run agent orbit; do - /opt/flare/flare "$command" --help > /dev/null - done' + if readelf -d check/flare/flare | grep -F "libibverbs.so"; then + echo "::error::flare must not hard-link libibverbs.so in DT_NEEDED." + exit 1 + fi + python3 - <<'PY' + import re, subprocess, sys + out = subprocess.check_output(["readelf", "--version-info", "check/flare/flare"], text=True) + too_new = sorted({ + m.group(0) + for m in re.finditer(r"GLIBC_(\d+)\.(\d+)", out) + if (int(m.group(1)), int(m.group(2))) > (2, 35) + }) + if too_new: + print(f"::error::flare requires glibc newer than 2.35: {', '.join(too_new)}", file=sys.stderr) + sys.exit(1) + PY + # Both containers hold only base image libraries (no libibverbs1), proving + # glibc <= 2.35 compatibility (including JetPack 6) and lazy libibverbs loading. + for image in ubuntu:22.04 ubuntu:24.04; do + docker run --rm --volume "$PWD/check/flare:/opt/flare:ro" \ + --env VERSION "$image" bash -euc ' + reported=$(/opt/flare/flare --version) + if [[ "$reported" != "flare $VERSION" ]]; then + echo "::error::flare --version printed \"$reported\"; expected \"flare $VERSION\"." + exit 1 + fi + for command in run agent orbit; do + /opt/flare/flare "$command" --help > /dev/null + done' + done - uses: actions/upload-artifact@v4 with: name: flare-linux-${{ matrix.arch }} diff --git a/docs/multi-host.md b/docs/multi-host.md index 8a89bfd71..a3f9c505e 100644 --- a/docs/multi-host.md +++ b/docs/multi-host.md @@ -47,8 +47,10 @@ needs only Flare, the driver, and the core. Linux aarch64 builds include RoCE transport by default. To enable it on Linux x86_64, install the libibverbs development package and build with `cargo build --release --locked --manifest-path flare-cli/Cargo.toml --features roce`. -The resulting executable requires libibverbs at runtime. Default x86_64 builds -do not link it and reject multi-host serving before loading GPU resources. +Both builds load `libibverbs.so.1` lazily at run time only when opening a +multi-host RoCE transport, so single-host serving runs without RDMA packages. +Default x86_64 builds omit RoCE transport and reject multi-host serving before +loading GPU resources. Staging (`--stage-only`) does not need RoCE. Not qualified: x86_64 RoCE serving on RDMA hardware; its coverage is functional, over Soft-RoCE. The separate `rdma` feature enables the prefix pool's data channel. diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 4386c9e28..ff3bab6fe 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -474,8 +474,9 @@ offload event. Transfers move records in windows of at most 64 pages plus the multi-slot row. The pool contains warm checkpoint slots plus automatic intake slots. It is one -4 KiB aligned anonymous mapping (`MAP_PRIVATE`, `MAP_ANONYMOUS`, `MAP_POPULATE`, -advised for transparent huge pages), registered once at startup. Rows use each +4 KiB aligned anonymous mapping (`MAP_PRIVATE`, `MAP_ANONYMOUS`, advised for +transparent huge pages with `MADV_HUGEPAGE` before prefaulting via +`MADV_POPULATE_WRITE`), registered once at startup. Rows use each rank's page share across as many slots as needed; their pieces need not be contiguous. CPU readers traverse pieces in rank order, preserving disk bytes and streaming xxh3 checksum values. After copy-out, Selene compares local ranks' @@ -524,7 +525,10 @@ slabs the same way in a split pool and a registered pool; each transfer thread holds its rank's `RankPart` and places a split slab's planes at their offsets relative to the rank's first plane. Composite and disk stores, whose disk threads read and write whole records, -keep the registered mapping. Cache sizing leaves each device 1/512 of the +keep the registered mapping. On hosts where `HOST_NUMA` virtual memory +allocation is unsupported (such as Windows WDDM and integrated Tegra/GA10B +GPUs), a memory-only store also falls back to a registered anonymous mapping. +Cache sizing leaves each device 1/512 of the host memory it maps, its share of a split pool or the whole registered pool including intake, plus 16 MiB for transfer streams. @@ -642,7 +646,8 @@ that drain cannot finish before the deadline. driver symbol `cuMemcpyBatchAsync_v2`, with the CUDA 13 signature (destinations, sources, sizes, count, attributes, attribute indices, attribute count, stream) and one attribute whose source access order is -stream-ordered; `cuMemHostRegister_v2` with the portable flag; +stream-ordered, falling back to per-entry `cuMemcpyAsync` on CUDA < 13.0 drivers +where `cuMemcpyBatchAsync_v2` is absent; `cuMemHostRegister_v2` with the portable flag; `cuMemHostUnregister`; `cuEventSynchronize`; `cuStreamCreateWithPriority`; `cuDeviceGetAttribute` for the integrated-memory check and the host NUMA node, which the loader's driver binding also provides; and `cuMemAddressReserve`, @@ -1133,8 +1138,10 @@ startup retries its existing attachment after a lost connection. Before any CUDA registration, the complete Hello plan must fit both budgets: the manager's arena plus staging on this host, or the client's data staging for a remote manager. Host supply is available physical memory less future local -host allocations, a 2 GiB server allowance and five percent of total RAM for the -system. Every GPU is charged one device byte per 512 registered host bytes, +host allocations and, unless an explicit `--memory-limit` overrides implicit +reserves on an integrated GPU, a scaled service allowance (`64 MiB` at or below +`16 GiB` total RAM, `min(2 GiB, total / 32)` above `16 GiB`) plus five percent +of total RAM for the system. Every GPU is charged one device byte per 512 registered host bytes, rounded up separately for each region, as for local registered tiers. Integrated GPUs also share the host-byte charge once per host. The check preserves runtime headroom, explicit memory limits and minimum execution/KV capacity; accepted diff --git a/docs/release.md b/docs/release.md index 62e7cf708..0c1d095ab 100644 --- a/docs/release.md +++ b/docs/release.md @@ -27,10 +27,12 @@ preparation inputs and are never part of a release. Every executable loads the NVIDIA driver at run time; no archive contains CUDA libraries, and no build links the CUDA toolkit. -- The Linux executables are built on Ubuntu 24.04 and require glibc 2.39 or - later. -- The arm64 Linux executable links `libibverbs` for multi-host RoCE serving. - Install `libibverbs1` and `ibverbs-providers`. +- The Linux executables are built in Ubuntu 22.04 and require glibc 2.35 or + later (covering Ubuntu 22.04+, JetPack 6, and Ubuntu 24.04+). +- The arm64 Linux executable loads `libibverbs.so.1` lazily at run time only + when serving multi-host RoCE cores. Single-host serving requires no RDMA + packages; multi-host RoCE serving requires `libibverbs1` and + `ibverbs-providers`. - The Windows desktop requires Windows 11. It bundles its Windows App SDK and Visual C++ runtime files. `Flare.exe` is unsigned. @@ -65,13 +67,16 @@ before anything is published; no target can be skipped. default branch and all three release manifests and lockfiles to contain `0.0.0`. Each build job applies the tag's version before compiling. A dispatched run builds `0.0.0` without publishing a release. -- **Linux.** The runner builds `flare` with +- **Linux.** Each runner builds `flare` with `cargo build --locked --release --manifest-path flare-cli/Cargo.toml` and - packages it with `packaging/archive.py`. The extracted archive then runs in - an `ubuntu:24.04` container that holds only that image's libraries, plus the - two RoCE packages on arm64: `flare --version` must print `flare VERSION`, and - `flare run --help`, `flare agent --help`, and `flare orbit --help` must - succeed. The job also requires the license and notice files in the archive. + packages it with `packaging/archive.py` inside an `ubuntu:22.04` container so + dynamic symbol versions stay at or below `GLIBC_2.35`. The job verifies that + `flare` has no `libibverbs.so` `DT_NEEDED` entry and no `GLIBC_` symbol + version newer than `2.35`, requires the license and notice files in the + archive, and runs the extracted archive in clean `ubuntu:22.04` and + `ubuntu:24.04` containers with only base image libraries (no RDMA packages): + `flare --version` must print `flare VERSION`, and `flare run --help`, + `flare agent --help`, and `flare orbit --help` must succeed. - **Windows.** The runner installs tools with `scripts/setup_windows.ps1 -RustToolchain 1.94.1 -BuildToolsOnly`, builds with `scripts/build_winui.ps1 -Platform PLATFORM -SingleFile`, and packages diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 463437aa6..978c4715f 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -7,8 +7,8 @@ interpreter. The [core format](core-format-design.md) defines a packed payload companions. The Flare model cache stores the directory form. Engine upgrades preserve previously supported models without re-export. Execution ABI labels do not gate loading; declared operations and layouts are validated. Preparation happens in Python with PyTorch, Transformers, and b12x. Serving requires the NVIDIA driver, the core, the Rust `flare` executable, and its system library dependencies: -the C and C++ runtime libraries, plus libibverbs on aarch64 Linux builds, which -enable RoCE. libjpeg-turbo is compiled from source through the `turbojpeg` +the C and C++ runtime libraries, plus `libibverbs.so.1` loaded lazily at run +time on aarch64 Linux builds only when serving multi-host RoCE cores. libjpeg-turbo is compiled from source through the `turbojpeg` crate's `cmake` feature; the x86-64 Linux executable has no dynamic libturbojpeg dependency. Python and preparation tools are not required. The [core design](core-design.md) defines the model contracts, scheduling, diff --git a/eos/src/unix.rs b/eos/src/unix.rs index 0a2583ae8..178b0bfc1 100644 --- a/eos/src/unix.rs +++ b/eos/src/unix.rs @@ -88,7 +88,7 @@ pub fn map_host(bytes: usize) -> io::Result { std::ptr::null_mut(), bytes, libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_POPULATE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, -1, 0, ) @@ -96,9 +96,25 @@ pub fn map_host(bytes: usize) -> io::Result { if ptr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } + // Advise transparent huge pages before faulting so Linux backs the mapping + // with 2 MiB pages when THP is set to `madvise` rather than faulting 4 KiB + // pages first via MAP_POPULATE. unsafe { libc::madvise(ptr, bytes, libc::MADV_HUGEPAGE); } + #[cfg(target_os = "linux")] + let populated = unsafe { libc::madvise(ptr, bytes, libc::MADV_POPULATE_WRITE) == 0 }; + #[cfg(not(target_os = "linux"))] + let populated = false; + if !populated { + let step = page_size().max(1); + for offset in (0..bytes).step_by(step) { + // SAFETY: `offset < bytes` and the mapping is writable. + unsafe { + ptr.cast::().add(offset).write_volatile(0); + } + } + } Ok(ptr as usize) } @@ -187,4 +203,47 @@ mod tests { // Restore the prior soft limit so other tests in the process see the original value. let _ = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &before) }; } + + #[test] + fn map_host_advises_hugepages_and_prefaults_zeroed_pages() { + let bytes = 4 << 20; + let address = map_host(bytes).unwrap(); + let slice = unsafe { std::slice::from_raw_parts(address as *const u8, bytes) }; + assert!(slice.iter().all(|&b| b == 0)); + #[cfg(target_os = "linux")] + if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") { + let needle = format!("{address:x}-"); + if let Some(start) = smaps.find(&needle) { + let block = &smaps[start..]; + let end = block[1..] + .find('\n') + .and_then(|first_nl| { + block[first_nl + 1..] + .lines() + .position(|line| { + line.as_bytes().first().is_some_and(u8::is_ascii_hexdigit) + && line.contains('-') + }) + .map(|idx| { + block[first_nl + 1..] + .lines() + .take(idx) + .map(|l| l.len() + 1) + .sum::() + + first_nl + + 1 + }) + }) + .unwrap_or(block.len()); + let vma = &block[..end]; + if let Some(flags) = vma.lines().find(|l| l.starts_with("VmFlags:")) { + assert!( + flags.split_whitespace().any(|flag| flag == "hg"), + "expected MADV_HUGEPAGE (hg) in VmFlags, got: {flags}" + ); + } + } + } + unsafe { unmap_host(address, bytes) }; + } } diff --git a/flare-cli/Cargo.toml b/flare-cli/Cargo.toml index ef8c1ba88..4b68a3403 100644 --- a/flare-cli/Cargo.toml +++ b/flare-cli/Cargo.toml @@ -7,7 +7,7 @@ rust-version = "1.88" publish = false [features] -# Multi-host collectives on Linux x86_64; links libibverbs. +# Multi-host collectives on Linux x86_64; loads libibverbs.so.1 at run time. roce = ["flare-helios/roce", "flare/roce"] # The prefix cache pool's data channel may use RDMA when its manager offers it (experimental). rdma = ["flare-helios/rdma", "flare/rdma"] @@ -39,7 +39,7 @@ tempfile = "3" [dev-dependencies] prost = "0.14" -# DGX Spark and Grace hosts serve multi-host cores over RoCEnante, which links libibverbs. +# DGX Spark and Grace hosts serve multi-host cores over RoCEnante, which loads libibverbs.so.1 lazily at run time. [target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dependencies] flare-helios = { path = "../helios", features = ["runtime-core", "server", "roce"] } # sha2 0.10 gates ARM SHA-256 instructions behind its asm feature. diff --git a/flare/Cargo.toml b/flare/Cargo.toml index 008e23f5a..de103f7a2 100644 --- a/flare/Cargo.toml +++ b/flare/Cargo.toml @@ -7,7 +7,7 @@ rust-version = "1.88" publish = false [features] -# Multi-host collectives on Linux x86_64; links libibverbs. +# Multi-host collectives on Linux x86_64; loads libibverbs.so.1 at run time. roce = ["flare-helios/roce"] # The prefix cache pool's data channel may use RDMA when its manager offers it (experimental). rdma = ["flare-helios/rdma"] @@ -49,7 +49,7 @@ tempfile = "3" [dev-dependencies] prost = "0.14" -# DGX Spark and Grace hosts serve multi-host cores over RoCEnante, which links libibverbs. +# DGX Spark and Grace hosts serve multi-host cores over RoCEnante, which loads libibverbs.so.1 lazily at run time. [target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dependencies] flare-helios = { path = "../helios", features = ["runtime-core", "server", "roce"] } # sha2 0.10 gates ARM SHA-256 instructions behind its asm feature. diff --git a/helios/Cargo.toml b/helios/Cargo.toml index eeb4e4c9c..97d0fb279 100644 --- a/helios/Cargo.toml +++ b/helios/Cargo.toml @@ -23,7 +23,7 @@ frontend = ["dep:serde", "dep:tokenizers", "dep:serde_json", "dep:sha2", "dep:ry images = ["frontend", "dep:png", "dep:turbojpeg", "dep:image-webp", "dep:gif"] grammar = ["frontend", "dep:llguidance"] server = ["dep:serde", "images", "grammar", "dep:axum", "dep:tokio", "dep:async-stream", "dep:base64", "dep:ratatui", "dep:crossterm", "dep:futures-util", "dep:flate2", "dep:zstd", "dep:brotli", "dep:httpdate", "dep:deepseek-recipe"] -# RoCEnante's RDMA proxy for ranks on separate hosts; links libibverbs. +# RoCEnante's RDMA proxy for ranks on separate hosts; loads libibverbs.so.1 lazily at run time. roce = ["runtime-core", "dep:cc"] # Lets the prefix cache pool's data channel use RDMA when its manager offers it (experimental); # links libibverbs. diff --git a/helios/build.rs b/helios/build.rs index 1c1033cdb..047460407 100644 --- a/helios/build.rs +++ b/helios/build.rs @@ -67,11 +67,12 @@ fn main() { #[cfg(feature = "roce")] { println!("cargo:rerun-if-changed=native/roce_proxy.c"); + println!("cargo:rerun-if-changed=native/roce_proxy_dlopen.c"); cc::Build::new() - .file("native/roce_proxy.c") + .file("native/roce_proxy_dlopen.c") .std("gnu11") .compile("flare_roce_proxy"); - println!("cargo:rustc-link-lib=ibverbs"); + println!("cargo:rustc-link-lib=dl"); println!("cargo:rustc-link-lib=pthread"); } } diff --git a/helios/native/roce_proxy_dlopen.c b/helios/native/roce_proxy_dlopen.c new file mode 100644 index 000000000..30882394c --- /dev/null +++ b/helios/native/roce_proxy_dlopen.c @@ -0,0 +1,236 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Loads libibverbs.so.1 lazily with dlopen so single-host serving runs on Linux +// hosts without RDMA packages (such as stock JetPack 6 on Jetson Orin) while +// keeping the vendored roce_proxy.c byte-for-byte identical to FlashInfer. + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + struct ibv_device** (*get_device_list)(int* num_devices); + const char* (*get_device_name)(struct ibv_device* device); + void (*free_device_list)(struct ibv_device** list); + struct ibv_context* (*open_device)(struct ibv_device* device); + int (*close_device)(struct ibv_context* context); + int (*query_port)(struct ibv_context* context, uint8_t port_num, + struct _compat_ibv_port_attr* port_attr); + int (*query_gid)(struct ibv_context* context, uint8_t port_num, int index, union ibv_gid* gid); + struct ibv_pd* (*alloc_pd)(struct ibv_context* context); + int (*dealloc_pd)(struct ibv_pd* pd); + struct ibv_mr* (*reg_mr)(struct ibv_pd* pd, void* addr, size_t length, int access); + struct ibv_mr* (*reg_mr_iova2)(struct ibv_pd* pd, void* addr, size_t length, uint64_t iova, + unsigned int access); + int (*dereg_mr)(struct ibv_mr* mr); + struct ibv_cq* (*create_cq)(struct ibv_context* context, int cqe, void* cq_context, + struct ibv_comp_channel* channel, int comp_vector); + int (*destroy_cq)(struct ibv_cq* cq); + struct ibv_qp* (*create_qp)(struct ibv_pd* pd, struct ibv_qp_init_attr* qp_init_attr); + int (*destroy_qp)(struct ibv_qp* qp); + int (*modify_qp)(struct ibv_qp* qp, struct ibv_qp_attr* attr, int attr_mask); + const char* (*wc_status_str)(enum ibv_wc_status status); +} flare_ibv_table_t; + +static flare_ibv_table_t flare_ibv; +static pthread_once_t flare_ibv_once = PTHREAD_ONCE_INIT; +static int flare_ibv_ready = 0; +static char flare_ibv_err[512] = {0}; + +static void* flare_ibv_sym(void* handle, const char* name, const char* version) { + void* sym = dlvsym(handle, name, version); + if (sym == NULL) { + sym = dlsym(handle, name); + } + return sym; +} + +static void flare_ibv_init(void) { + // RTLD_GLOBAL allows older provider plugins that omit DT_NEEDED on + // libibverbs.so.1 to resolve verbs symbols; this translation unit exports + // no ibv_* symbols of its own. + void* handle = dlopen("libibverbs.so.1", RTLD_NOW | RTLD_GLOBAL); + if (handle == NULL) { + const char* detail = dlerror(); + snprintf(flare_ibv_err, sizeof(flare_ibv_err), + "cannot load libibverbs.so.1 (%s); install libibverbs1 and ibverbs-providers for " + "multi-host RoCE serving", + detail != NULL ? detail : "unknown dlopen error"); + return; + } + +#define FLARE_LOAD_IBV(field, name, version) \ + do { \ + void* sym = flare_ibv_sym(handle, name, version); \ + if (sym == NULL) { \ + snprintf(flare_ibv_err, sizeof(flare_ibv_err), \ + "libibverbs.so.1 is missing required symbol %s", name); \ + dlclose(handle); \ + return; \ + } \ + memcpy(&flare_ibv.field, &sym, sizeof(sym)); \ + } while (0) + + FLARE_LOAD_IBV(get_device_list, "ibv_get_device_list", "IBVERBS_1.1"); + FLARE_LOAD_IBV(get_device_name, "ibv_get_device_name", "IBVERBS_1.1"); + FLARE_LOAD_IBV(free_device_list, "ibv_free_device_list", "IBVERBS_1.1"); + FLARE_LOAD_IBV(open_device, "ibv_open_device", "IBVERBS_1.1"); + FLARE_LOAD_IBV(close_device, "ibv_close_device", "IBVERBS_1.1"); + FLARE_LOAD_IBV(query_port, "ibv_query_port", "IBVERBS_1.1"); + FLARE_LOAD_IBV(query_gid, "ibv_query_gid", "IBVERBS_1.1"); + FLARE_LOAD_IBV(alloc_pd, "ibv_alloc_pd", "IBVERBS_1.1"); + FLARE_LOAD_IBV(dealloc_pd, "ibv_dealloc_pd", "IBVERBS_1.1"); + FLARE_LOAD_IBV(reg_mr, "ibv_reg_mr", "IBVERBS_1.1"); + FLARE_LOAD_IBV(dereg_mr, "ibv_dereg_mr", "IBVERBS_1.1"); + FLARE_LOAD_IBV(create_cq, "ibv_create_cq", "IBVERBS_1.1"); + FLARE_LOAD_IBV(destroy_cq, "ibv_destroy_cq", "IBVERBS_1.1"); + FLARE_LOAD_IBV(create_qp, "ibv_create_qp", "IBVERBS_1.1"); + FLARE_LOAD_IBV(destroy_qp, "ibv_destroy_qp", "IBVERBS_1.1"); + FLARE_LOAD_IBV(modify_qp, "ibv_modify_qp", "IBVERBS_1.1"); + FLARE_LOAD_IBV(wc_status_str, "ibv_wc_status_str", "IBVERBS_1.1"); + +#undef FLARE_LOAD_IBV + + void* reg_iova2 = flare_ibv_sym(handle, "ibv_reg_mr_iova2", "IBVERBS_1.8"); + if (reg_iova2 != NULL) { + memcpy(&flare_ibv.reg_mr_iova2, ®_iova2, sizeof(reg_iova2)); + } + flare_ibv_ready = 1; +} + +int roce_ensure_libibverbs(char* err, uint64_t err_len) { + pthread_once(&flare_ibv_once, flare_ibv_init); + if (!flare_ibv_ready) { + if (err != NULL && err_len > 0) { + snprintf(err, (size_t)err_len, "%s", flare_ibv_err); + } + return -1; + } + return 0; +} + +static struct ibv_device** flare_ibv_get_device_list(int* num_devices) { + if (roce_ensure_libibverbs(NULL, 0) != 0) { + errno = ENOSYS; + return NULL; + } + return flare_ibv.get_device_list(num_devices); +} + +static const char* flare_ibv_get_device_name(struct ibv_device* device) { + return flare_ibv.get_device_name(device); +} + +static void flare_ibv_free_device_list(struct ibv_device** list) { + flare_ibv.free_device_list(list); +} + +static struct ibv_context* flare_ibv_open_device(struct ibv_device* device) { + return flare_ibv.open_device(device); +} + +static int flare_ibv_close_device(struct ibv_context* context) { + return flare_ibv.close_device(context); +} + +static int flare_ibv_query_port(struct ibv_context* context, uint8_t port_num, + struct ibv_port_attr* port_attr) { + struct verbs_context* vctx = verbs_get_ctx_op(context, query_port); + if (!vctx) { + memset(port_attr, 0, sizeof(*port_attr)); + return flare_ibv.query_port(context, port_num, (struct _compat_ibv_port_attr*)port_attr); + } + return vctx->query_port(context, port_num, port_attr, sizeof(*port_attr)); +} + +static int flare_ibv_query_gid(struct ibv_context* context, uint8_t port_num, int index, + union ibv_gid* gid) { + return flare_ibv.query_gid(context, port_num, index, gid); +} + +static struct ibv_pd* flare_ibv_alloc_pd(struct ibv_context* context) { + return flare_ibv.alloc_pd(context); +} + +static int flare_ibv_dealloc_pd(struct ibv_pd* pd) { + return flare_ibv.dealloc_pd(pd); +} + +static struct ibv_mr* flare_ibv_reg_mr(struct ibv_pd* pd, void* addr, size_t length, + unsigned int access) { +#ifdef IBV_ACCESS_OPTIONAL_RANGE + if ((access & IBV_ACCESS_OPTIONAL_RANGE) != 0) { + if (flare_ibv.reg_mr_iova2 == NULL) { + errno = ENOSYS; + return NULL; + } + return flare_ibv.reg_mr_iova2(pd, addr, length, (uintptr_t)addr, access); + } +#endif + return flare_ibv.reg_mr(pd, addr, length, (int)access); +} + +static int flare_ibv_dereg_mr(struct ibv_mr* mr) { + return flare_ibv.dereg_mr(mr); +} + +static struct ibv_cq* flare_ibv_create_cq(struct ibv_context* context, int cqe, void* cq_context, + struct ibv_comp_channel* channel, int comp_vector) { + return flare_ibv.create_cq(context, cqe, cq_context, channel, comp_vector); +} + +static int flare_ibv_destroy_cq(struct ibv_cq* cq) { + return flare_ibv.destroy_cq(cq); +} + +static struct ibv_qp* flare_ibv_create_qp(struct ibv_pd* pd, + struct ibv_qp_init_attr* qp_init_attr) { + return flare_ibv.create_qp(pd, qp_init_attr); +} + +static int flare_ibv_destroy_qp(struct ibv_qp* qp) { + return flare_ibv.destroy_qp(qp); +} + +static int flare_ibv_modify_qp(struct ibv_qp* qp, struct ibv_qp_attr* attr, int attr_mask) { + return flare_ibv.modify_qp(qp, attr, attr_mask); +} + +static const char* flare_ibv_wc_status_str(enum ibv_wc_status status) { + return flare_ibv.wc_status_str(status); +} + +#undef ibv_query_port +#undef ibv_reg_mr + +#define ibv_get_device_list flare_ibv_get_device_list +#define ibv_get_device_name flare_ibv_get_device_name +#define ibv_free_device_list flare_ibv_free_device_list +#define ibv_open_device flare_ibv_open_device +#define ibv_close_device flare_ibv_close_device +#define ibv_query_port flare_ibv_query_port +#define ibv_query_gid flare_ibv_query_gid +#define ibv_alloc_pd flare_ibv_alloc_pd +#define ibv_dealloc_pd flare_ibv_dealloc_pd +#define ibv_reg_mr flare_ibv_reg_mr +#define ibv_dereg_mr flare_ibv_dereg_mr +#define ibv_create_cq flare_ibv_create_cq +#define ibv_destroy_cq flare_ibv_destroy_cq +#define ibv_create_qp flare_ibv_create_qp +#define ibv_destroy_qp flare_ibv_destroy_qp +#define ibv_modify_qp flare_ibv_modify_qp +#define ibv_wc_status_str flare_ibv_wc_status_str + +// roce_proxy.c defines _GNU_SOURCE itself. +#undef _GNU_SOURCE +#include "roce_proxy.c" diff --git a/helios/src/cuda.rs b/helios/src/cuda.rs index 838baea5e..249619806 100644 --- a/helios/src/cuda.rs +++ b/helios/src/cuda.rs @@ -78,6 +78,7 @@ type MemAlloc = unsafe extern "C" fn(*mut u64, usize) -> c_int; type MemFree = unsafe extern "C" fn(u64) -> c_int; type MemsetD8 = unsafe extern "C" fn(u64, u8, usize, Handle) -> c_int; type CopyDtoD = unsafe extern "C" fn(u64, u64, usize, Handle) -> c_int; +type CopyAsync = unsafe extern "C" fn(u64, u64, usize, Handle) -> c_int; /// `CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES`. const FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: c_int = 8; @@ -221,6 +222,7 @@ struct Driver { mem_free: MemFree, memset_d8: MemsetD8, copy_dtod: CopyDtoD, + copy_async: CopyAsync, } impl Driver { @@ -298,6 +300,7 @@ impl Driver { mem_free: symbol!("cuMemFree_v2"), memset_d8: symbol!("cuMemsetD8Async"), copy_dtod: symbol!("cuMemcpyDtoDAsync_v2"), + copy_async: symbol!("cuMemcpyAsync"), _library: library, })) } @@ -526,13 +529,25 @@ impl Drop for DeviceHostParts { } } +/// `CUDA_ERROR_INVALID_VALUE` (1) or `CUDA_ERROR_NOT_SUPPORTED` (801), returned by +/// CUDA drivers on platforms without `CU_MEM_LOCATION_TYPE_HOST_NUMA` VMM support +/// (such as Windows WDDM and integrated Tegra/GA10B GPUs). +fn is_host_numa_unsupported(status: c_int) -> bool { + matches!(status, 1 | 801) +} + /// Reserve one range and back it with one pinned host part per `(context, /// device, bytes)` request, in request order. Each part is created on the host /// NUMA node closest to its device, rounded up to the allocation granularity, /// and made accessible to that device and the host only. Each request's /// context is made current on the calling thread while its part is planned /// and created. -pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result { +/// +/// Returns `Ok(None)` when the driver reports `HOST_NUMA` VMM allocation is +/// unsupported on this platform; real failures (such as out-of-memory) return `Err`. +pub(crate) fn try_map_device_host_parts( + requests: &[(usize, i32, usize)], +) -> Result> { let invalid = |message: String| Error::execution(ExecutionError::State, message); if requests.is_empty() || requests.iter().any(|(_, _, bytes)| *bytes == 0) { return Err(invalid( @@ -559,16 +574,20 @@ pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result< // this call; every output pointer is valid for its call. unsafe { driver.check("cuCtxSetCurrent", (driver.set_context)(context as Handle))?; - driver.check( - "cuDeviceGetAttribute", - (driver.device_attribute)(&mut node, ATTRIBUTE_HOST_NUMA_ID, device), - )?; + let node_status = + (driver.device_attribute)(&mut node, ATTRIBUTE_HOST_NUMA_ID, device); + if is_host_numa_unsupported(node_status) { + return Ok(None); + } + driver.check("cuDeviceGetAttribute", node_status)?; // A host without NUMA reports -1 and takes node 0. properties.location.id = node.max(0); - driver.check( - "cuMemGetAllocationGranularity", - (driver.granularity)(&mut granularity, &properties, GRANULARITY_MINIMUM), - )?; + let gran_status = + (driver.granularity)(&mut granularity, &properties, GRANULARITY_MINIMUM); + if is_host_numa_unsupported(gran_status) { + return Ok(None); + } + driver.check("cuMemGetAllocationGranularity", gran_status)?; } let granularity = granularity.max(1); let offset = total.checked_next_multiple_of(granularity); @@ -619,10 +638,11 @@ pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result< // reservation, and `memory` records each step so its drop undoes it. unsafe { driver.check("cuCtxSetCurrent", (driver.set_context)(context as Handle))?; - driver.check( - "cuMemCreate", - (driver.memory_create)(&mut handle, nbytes, &properties, 0), - )?; + let create_status = (driver.memory_create)(&mut handle, nbytes, &properties, 0); + if is_host_numa_unsupported(create_status) { + return Ok(None); + } + driver.check("cuMemCreate", create_status)?; memory.parts.push(HostPart { offset, nbytes, @@ -633,13 +653,26 @@ pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result< if let Some(part) = memory.parts.last_mut() { part.mapped = true; } - driver.check( - "cuMemSetAccess", - (driver.memory_access)(start, nbytes, access.as_ptr(), access.len()), - )?; + let access_status = + (driver.memory_access)(start, nbytes, access.as_ptr(), access.len()); + if is_host_numa_unsupported(access_status) { + return Ok(None); + } + driver.check("cuMemSetAccess", access_status)?; } } - Ok(memory) + Ok(Some(memory)) +} + +/// Like [`try_map_device_host_parts`], returning an error when `HOST_NUMA` VMM +/// allocation is unsupported on this device or driver. +pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result { + try_map_device_host_parts(requests)?.ok_or_else(|| { + Error::execution( + ExecutionError::State, + "HOST_NUMA virtual memory allocation is not supported on this device or driver", + ) + }) } pub(crate) struct Stream { @@ -788,11 +821,13 @@ impl Stream { ) }); } - // Fallback for CUDA < 13.0 drivers (e.g. JetPack 6 / CUDA 12.6 on Jetson Orin) - // where cuMemcpyBatchAsync_v2 is absent: issue individual stream-ordered async copies. + // Fallback for CUDA < 13.0 drivers (e.g. JetPack 6 / CUDA 12.6 on Jetson Orin + // and discrete CUDA 12.x GPUs) where cuMemcpyBatchAsync_v2 is absent: issue + // individual UVA stream-ordered copies via cuMemcpyAsync, which accepts device + // addresses, registered host aliases, and raw cuMemHostAlloc(..., flags=0) pointers. for ((&dst, &src), &size) in destinations.iter().zip(sources.iter()).zip(sizes.iter()) { - self.driver.check("cuMemcpyDtoDAsync_v2", unsafe { - (self.driver.copy_dtod)(dst, src, size, self.handle as Handle) + self.driver.check("cuMemcpyAsync", unsafe { + (self.driver.copy_async)(dst, src, size, self.handle as Handle) })?; } Ok(()) diff --git a/helios/src/execution/roce.rs b/helios/src/execution/roce.rs index ad1f542c9..9b29e9c44 100644 --- a/helios/src/execution/roce.rs +++ b/helios/src/execution/roce.rs @@ -33,6 +33,7 @@ struct Context { } unsafe extern "C" { + fn roce_ensure_libibverbs(err: *mut c_char, err_len: u64) -> c_int; fn roce_abi_version() -> c_int; fn roce_layout( world: c_int, @@ -187,10 +188,14 @@ impl RoceTransport { if spec.region_address == 0 { return Err(failure("RoCE transport region address is null")); } + let mut message = [0 as c_char; 512]; + if unsafe { roce_ensure_libibverbs(message.as_mut_ptr(), message.len() as u64) } != 0 { + let text = unsafe { CStr::from_ptr(message.as_ptr()) }.to_string_lossy(); + return Err(failure(format!("RoCE transport setup failed: {text}"))); + } let region = spec.region_address as *mut c_void; // Flags and the control record must start at zero: every rank begins again at sequence 1. unsafe { std::ptr::write_bytes(region.cast::(), 0, spec.region_bytes as usize) }; - let mut message = [0 as c_char; 512]; let context = unsafe { roce_create( spec.world as c_int, @@ -502,4 +507,18 @@ mod tests { // A subsequent health poll cannot turn the failed sequence into success. assert!(check_control(2, &words).is_err()); } + + #[test] + fn lazy_libibverbs_loader_resolves_symbols_or_reports_install_hint() { + let mut message = [0 as c_char; 512]; + // SAFETY: `message` is a valid writable buffer of length 512. + let status = unsafe { roce_ensure_libibverbs(message.as_mut_ptr(), message.len() as u64) }; + if status != 0 { + let text = unsafe { CStr::from_ptr(message.as_ptr()) }.to_string_lossy(); + assert!( + text.contains("libibverbs.so.1") && text.contains("libibverbs1"), + "unexpected dlopen error: {text}" + ); + } + } } diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 21804969d..20ae84ade 100644 --- a/helios/src/offload/mod.rs +++ b/helios/src/offload/mod.rs @@ -89,7 +89,7 @@ pub fn prepare_with_inputs( input_staging: u64, shard: Option<(usize, usize)>, ) -> Result { - Ok(flare_selene::offload::prepare_with_inputs( + prepare_with_inputs_budget( options, core, identity, @@ -98,6 +98,32 @@ pub fn prepare_with_inputs( max_active, input_staging, shard, + None, + ) +} + +#[allow(clippy::too_many_arguments)] +pub fn prepare_with_inputs_budget( + options: &PrefixCacheOffload, + core: &std::path::Path, + identity: [u8; 32], + geometry: Vec, + contexts: Vec<(usize, i32)>, + max_active: usize, + input_staging: u64, + shard: Option<(usize, usize)>, + host_budget: Option, +) -> Result { + Ok(flare_selene::offload::prepare_with_inputs_budget( + options, + core, + identity, + geometry, + contexts, + max_active, + input_staging, + shard, + host_budget, ®istrar::CudaRegistrar, )?) } diff --git a/helios/src/offload/registrar.rs b/helios/src/offload/registrar.rs index 495d3a4d4..c0b838f5e 100644 --- a/helios/src/offload/registrar.rs +++ b/helios/src/offload/registrar.rs @@ -27,6 +27,14 @@ impl HostRegistrar for CudaRegistrar { fn map_split(&self, requests: &[(usize, i32, usize)]) -> Result> { Ok(Box::new(cuda::map_device_host_parts(requests)?)) } + + fn try_map_split( + &self, + requests: &[(usize, i32, usize)], + ) -> Result>> { + Ok(cuda::try_map_device_host_parts(requests)? + .map(|parts| Box::new(parts) as Box)) + } } impl Registration for HostRegistration { diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index ac5d22b6f..8e72150bf 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -22,13 +22,10 @@ use crate::{ // Graphs are uploaded before sizing caches; leave room for driver bookkeeping // and the execution streams and events created when the server starts. pub(super) const HEADROOM_BYTES: u64 = 64 << 20; -// A GPU that allocates from system memory (GB10) shares it with the operating system and with -// the server's host allocations made after sizing: frontend workers, tokenizers and request +// A GPU that allocates from system memory (GB10, GA10B) shares it with the operating system and +// with the server's host allocations made after sizing: frontend workers, tokenizers and request // buffers took about 1.4 GiB on a DGX Spark. Caches leave room for both beyond the reserve. -use flare_selene::offload::{ - HOST_SERVICE_HEADROOM_BYTES as INTEGRATED_HOST_BYTES, - HOST_SYSTEM_SHARE as INTEGRATED_SYSTEM_SHARE, -}; +use flare_selene::offload::host_reserve_bytes; #[cfg(any(unix, test))] pub(super) fn shared_available(meminfo: &str, total: usize) -> Result { @@ -180,26 +177,49 @@ fn headroom(config: &serde_json::Value) -> Result { .ok_or_else(|| invalid("memory reserve overflows the device budget")) } -fn integrated_host_bytes(total: u64) -> u64 { - if total <= (16u64 << 30) { - 64 << 20 - } else { - INTEGRATED_HOST_BYTES.min(total / 32) - } -} - /// Memory caches may use on one rank: free memory less the headroom, and on an integrated GPU /// also the server's later host allocations and a twentieth of memory for the system when using /// the default reserve. An explicit memory limit removes those implicit reserves. fn budget(free: u64, total: u64, headroom: u64, integrated: bool, explicit_limit: bool) -> u64 { let host = if integrated && !explicit_limit { - integrated_host_bytes(total) + total / INTEGRATED_SYSTEM_SHARE + host_reserve_bytes(total) } else { 0 }; free.saturating_sub(headroom.saturating_add(host)) } +/// Host memory available for prefix-cache offload on an integrated (unified-memory) GPU. +/// Honors an explicit `--memory-limit` directly without subtracting implicit service or +/// system reserves; otherwise applies the same scaled host reserve as [`budget`]. +fn integrated_offload_host_budget( + memory: MemorySnapshot, + loaded: u64, + limit: Option, + future: u64, +) -> u64 { + match limit { + None => flare_selene::offload::host_pool_budget_from( + memory.free, + memory.total, + future, + true, + ), + Some(MemoryLimit::Reserve(reserve)) => memory + .free + .min(memory.total) + .saturating_sub(reserve) + .saturating_sub(future), + Some(limit) => { + let physical = memory.free.min(memory.total).saturating_sub(future); + match limit.occupied_bytes(memory.total) { + Some(cap) => physical.min(cap.saturating_sub(loaded.saturating_add(future))), + None => physical, + } + } + } +} + /// Account for loaded storage and observed module/graph growth. The device observation is /// taken before loading model resources; on integrated GPUs it includes host allocations too. #[derive(Clone, Copy, Debug)] @@ -581,7 +601,7 @@ impl NativeModel { options: &LoadOptions, initial: &[MemorySnapshot], embedding_host_bytes: u64, - ) -> Result<()> { + ) -> Result> { // Local host tiers register after cache backing; pool regions register before sizing. let reserve = headroom(&self.server_config)?; let page_tokens = self.server_config["page_tokens"] @@ -623,6 +643,55 @@ impl NativeModel { .map(|rank| unsafe { rank.memory_snapshot() }) .collect::>>()?; let integrated = self.ranks.iter().filter(|rank| rank.integrated).count() as u64; + let integrated_state = (integrated > 0) + .then(|| -> Result<(MemorySnapshot, u64)> { + let free = observations + .iter() + .zip(&self.ranks) + .filter(|(_, r)| r.integrated) + .map(|(m, _)| m.free) + .min() + .unwrap(); + let total = observations + .iter() + .zip(&self.ranks) + .filter(|(_, r)| r.integrated) + .map(|(m, _)| m.total) + .min() + .unwrap(); + let fixed = cores + .iter() + .zip(&self.ranks) + .filter(|(_, r)| r.integrated) + .try_fold(0u64, |n, (p, _)| { + fixed_bytes(p, true).and_then(|bytes| { + n.checked_add(bytes) + .ok_or_else(|| invalid("shared fixed memory overflow")) + }) + })? + .checked_add(embedding_host_bytes) + .ok_or_else(|| invalid("resident host memory overflows the shared budget"))?; + let observed_drop = initial + .iter() + .zip(&self.ranks) + .filter(|(_, r)| r.integrated) + .map(|(m, _)| m.free.saturating_sub(free)) + .max() + .unwrap_or(0); + Ok((MemorySnapshot { free, total }, fixed.max(observed_drop))) + }) + .transpose()?; + let host_budget_for = |future: u64| -> Result { + match integrated_state { + Some((memory, loaded)) => Ok(integrated_offload_host_budget( + memory, + loaded, + options.memory_limit, + future, + )), + None => Ok(flare_selene::offload::host_pool_budget(future)?), + } + }; let input_window = crate::offload::input_staging_bytes(&contract, |name| { cores[0] .execution @@ -756,12 +825,18 @@ impl NativeModel { let (offload_bytes, offload_host, tier_host) = if cfg.enabled() { let layout = flare_selene::Layout::new(&geometry)?; let staging = input_window; - let (device, tier_host) = options.prefix_cache.headroom_with_inputs( + let initial_budget = host_budget_for(if capture { + 0 + } else { + options.prefix_cache.memory_bytes.unwrap_or(0) + })?; + let (device, tier_host) = options.prefix_cache.headroom_with_inputs_for_budget( self.ranks.len(), &layout, active, staging != 0, capture.then_some(minimum_pages), + initial_budget, )?; let device = device .checked_add(codec_device) @@ -878,6 +953,7 @@ impl NativeModel { } else { None }; + let mut pool_host_charge = 0u64; if let Some(pool) = &options.prefix_cache.pool { let minimum = cores .iter() @@ -897,8 +973,7 @@ impl NativeModel { ceiling, |_, _| Some(0), )?; - let host = flare_selene::offload::host_pool_budget(host_future) - .map_err(|error| error.to_string()); + let host = host_budget_for(host_future).map_err(|error| error.to_string()); let budget = crate::offload::pool::Budget { host, devices: available @@ -935,13 +1010,16 @@ impl NativeModel { None => Ok(true), }, )?; - for (available, charge) in available.iter_mut().zip(charges) { + for ((available, charge), rank) in available.iter_mut().zip(charges).zip(&self.ranks) { *available = available.saturating_sub(charge); + if rank.integrated { + pool_host_charge = pool_host_charge.saturating_add(charge); + } } } let capture_layout = capture.then(|| flare_selene::Layout::new(&geometry)).transpose()?; let host_growth = if capture { - flare_selene::offload::host_pool_budget(host_future)? + host_budget_for(host_future.saturating_add(pool_host_charge))? } else { 0 }; @@ -1021,6 +1099,17 @@ impl NativeModel { "ranks agreed on a cache capacity this rank cannot back", )); } + let planned_offload_host = if capture { + let layout = capture_layout.as_ref().unwrap(); + let chain_bytes = pages + .saturating_add(layout.row_slots() as u64) + .saturating_mul(layout.page_record_bytes); + Some(tier_host.max(chain_bytes)) + } else if cfg.enabled() { + Some(tier_host.saturating_sub(cfg.memory_bytes.unwrap_or(0))) + } else { + None + }; summary.push_str(&format!(" · {pages} KV pages · {} shared snapshot slots", rows - execution)); progress.phase("Plan cache", None).finish(summary); unsafe { @@ -1034,8 +1123,9 @@ impl NativeModel { pages, execution, &limiting, - ) + )?; } + Ok(planned_offload_host) } #[allow(clippy::too_many_arguments)] @@ -1392,6 +1482,46 @@ mod tests { assert_eq!(budget(6 * gib, 120 * gib, 0, true, false), 0); // Explicit memory limit drops both the host server bytes and the 5% system reserve. assert_eq!(budget(40 * gib, 120 * gib, 5 * gib, true, true), 35 * gib); + // Small integrated SoCs (<= 16 GiB) scale host headroom down to 64 MiB. + assert_eq!( + budget(4 * gib, 8 * gib, 0, true, false), + 4 * gib - ((64 << 20) + (8 * gib) / 20) + ); + } + + #[test] + fn integrated_offload_host_budget_matches_small_soc_scaling_and_explicit_limits() { + let mib = 1u64 << 20; + let gib = 1u64 << 30; + let orin8 = MemorySnapshot { + free: 3 * gib, + total: 8 * gib, + }; + // Default uses scaled 64 MiB + total/20 reserve. + assert_eq!( + integrated_offload_host_budget(orin8, 4 * gib, None, 512 * mib), + 3 * gib - 512 * mib - (64 * mib + (8 * gib) / 20) + ); + // Explicit reserve replaces implicit host/system reserve. + assert_eq!( + integrated_offload_host_budget( + orin8, + 4 * gib, + Some(MemoryLimit::Reserve(256 * mib)), + 512 * mib + ), + 3 * gib - 256 * mib - 512 * mib + ); + // Explicit occupied cap bounds host supply by remaining cap without implicit reserve. + assert_eq!( + integrated_offload_host_budget( + orin8, + 4 * gib, + Some(MemoryLimit::Bytes(6 * gib)), + 512 * mib + ), + 2 * gib - 512 * mib + ); } #[test] diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 084e61487..44f32f81e 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -906,7 +906,7 @@ impl NativeModel { }); } Files::release_page_cache(&files); - model.allocate_caches( + let planned_offload_host = model.allocate_caches( &mut cores, progress, active, @@ -915,7 +915,7 @@ impl NativeModel { &initial, embedding_host_bytes, )?; - model.prepare_offload(root, options, progress, active)?; + model.prepare_offload(root, options, progress, active, planned_offload_host)?; } Ok(model) } @@ -928,6 +928,7 @@ impl NativeModel { options: &LoadOptions, progress: &StartupProgress, max_active: usize, + planned_host_budget: Option, ) -> Result<()> { if !options.prefix_cache.enabled() { return Ok(()); @@ -963,7 +964,7 @@ impl NativeModel { .cluster .as_ref() .map(|cluster| (cluster.rank, cluster.world)); - let prepared = crate::offload::prepare_with_inputs( + let prepared = crate::offload::prepare_with_inputs_budget( &options.prefix_cache, root, identity, @@ -972,6 +973,7 @@ impl NativeModel { max_active, staging, shard, + planned_host_budget, )?; phase.finish(self.attach_offload(prepared)?); Ok(()) @@ -1317,7 +1319,7 @@ mod tests { }; unsafe { model - .prepare_offload(Path::new("unopened-core"), &options, &progress, 1) + .prepare_offload(Path::new("unopened-core"), &options, &progress, 1, None) .unwrap(); } assert!(model.offload.shared().is_none()); @@ -1330,7 +1332,7 @@ mod tests { ..Default::default() }; let error = - unsafe { model.prepare_offload(Path::new("unopened-core"), &options, &progress, 1) } + unsafe { model.prepare_offload(Path::new("unopened-core"), &options, &progress, 1, None) } .unwrap_err(); assert!(error.to_string().contains("lacks an identity")); } diff --git a/selene/src/offload.rs b/selene/src/offload.rs index 1d2329765..7cda0341c 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -121,6 +121,41 @@ impl PrefixCacheOffload { max_active: usize, inputs: bool, local_pages: Option, + ) -> Result<(u64, u64)> { + if !self.enabled() { + return Ok((0, 0)); + } + let memory = self.memory_bytes.unwrap_or(0); + let disk = self.disk.is_some() && self.disk_limit != Some(0); + let capture = local_pages.filter(|_| self.pool_only()); + let host_budget = if capture.is_some() { + host_pool_budget(0)? + } else if memory != 0 || disk { + host_pool_budget(memory)? + } else { + 0 + }; + self.headroom_with_inputs_for_budget( + ranks, + layout, + max_active, + inputs, + local_pages, + host_budget, + ) + } + + /// Like [`Self::headroom_with_inputs`], using a caller-supplied host budget + /// (bytes available beyond `memory_bytes` for intake, or total host bytes for + /// a pool-only capture buffer) instead of re-reading system memory. + pub fn headroom_with_inputs_for_budget( + &self, + ranks: usize, + layout: &Layout, + max_active: usize, + inputs: bool, + local_pages: Option, + host_budget: u64, ) -> Result<(u64, u64)> { if !self.enabled() { return Ok((0, 0)); @@ -131,14 +166,14 @@ impl PrefixCacheOffload { let intake = if let Some(pages) = capture { let chain = pages.checked_add(layout.row_slots() as u64) .ok_or("pool capture slot count overflow")?; - let budget = host_pool_budget(0)? / layout.page_record_bytes; + let budget = host_budget / layout.page_record_bytes; if chain > budget { return Err("host budget cannot hold a full pool capture".into()); } chain.max(intake_slots(layout, max_active) as u64).min(budget) } else if memory != 0 || disk { intake_slots(layout, max_active) - .min((host_pool_budget(memory)? / layout.page_record_bytes) as usize) + .min((host_budget / layout.page_record_bytes) as usize) .max(intake_slots(layout, 1)) as u64 } else { 0 @@ -460,6 +495,32 @@ pub fn prepare( } pub fn prepare_with_inputs( + options: &PrefixCacheOffload, + core: &std::path::Path, + identity: [u8; 32], + geometry: Vec, + contexts: Vec<(usize, i32)>, + max_active: usize, + input_staging: u64, + shard: Option<(usize, usize)>, + registrar: &dyn crate::HostRegistrar, +) -> Result { + prepare_with_inputs_budget( + options, + core, + identity, + geometry, + contexts, + max_active, + input_staging, + shard, + None, + registrar, + ) +} + +#[allow(clippy::too_many_arguments)] +pub fn prepare_with_inputs_budget( options: &PrefixCacheOffload, core: &std::path::Path, identity: [u8; 32], @@ -468,6 +529,7 @@ pub fn prepare_with_inputs( max_active: usize, input_staging: u64, shard: Option<(usize, usize)>, + host_budget: Option, registrar: &dyn crate::HostRegistrar, ) -> Result { options.validate_compression()?; @@ -538,22 +600,42 @@ pub fn prepare_with_inputs( let capture = local_pages.is_some() && options.pool_only(); let memory_pool = (capture || checkpoint_memory != 0 || directory.is_some()) .then(|| { - let (_, host) = options.headroom_with_inputs( - contexts.len(), - &layout, - max_active, - input_staging != 0, - local_pages, - )?; + let (_, host) = match host_budget { + Some(budget) => options.headroom_with_inputs_for_budget( + contexts.len(), + &layout, + max_active, + input_staging != 0, + local_pages, + budget, + )?, + None => options.headroom_with_inputs( + contexts.len(), + &layout, + max_active, + input_staging != 0, + local_pages, + )?, + }; let transfer_slots = (host - memory_bytes) / layout.page_record_bytes; let intake = if capture { 0 } else { transfer_slots as usize }; let bytes = (checkpoint_memory / layout.page_record_bytes + transfer_slots) * layout.page_record_bytes; // Shared and compressed records must be readable by the CPU. + // Memory-only pools split by rank through HOST_NUMA VMM where the driver + // supports it, and fall back to a registered anonymous mapping on hosts + // without HOST_NUMA VMM (such as GA10B or Windows). let pool = if directory.is_none() && options.pool.is_none() && options.compression == KvCompression::Off { - slab::SlabPool::sized_by_rank(&layout, bytes, intake, &contexts, registrar)? + match slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)? { + Some(pool) => pool, + None => { + let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?; + pool.register(registrar, context)?; + pool + } + } } else { let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?; pool.register(registrar, context)?; @@ -719,6 +801,40 @@ mod tests; pub const HOST_SERVICE_HEADROOM_BYTES: u64 = 2 << 30; pub const HOST_SYSTEM_SHARE: u64 = 20; + +/// Service headroom kept for later host allocations on a host with `total` bytes of RAM. +/// Small unified-memory SoCs (<= 16 GiB) scale down to 64 MiB; larger hosts scale up to +/// `min(2 GiB, total / 32)`, matching integrated GPU cache planning. +pub fn host_service_headroom_bytes(total: u64) -> u64 { + if total <= (16u64 << 30) { + 64 << 20 + } else { + HOST_SERVICE_HEADROOM_BYTES.min(total / 32) + } +} + +/// Implicit host reserve (service headroom plus the system share) when no explicit +/// memory limit overrides it. +pub fn host_reserve_bytes(total: u64) -> u64 { + host_service_headroom_bytes(total) + total / HOST_SYSTEM_SHARE +} + +/// Available host memory for prefix-cache pools after reserving `future` bytes and, +/// when `apply_reserve` is true, the scaled host service and system reserves. +pub fn host_pool_budget_from( + available: u64, + total: u64, + future: u64, + apply_reserve: bool, +) -> u64 { + let reserve = if apply_reserve { + host_reserve_bytes(total) + } else { + 0 + }; + available.saturating_sub(future).saturating_sub(reserve) +} + pub fn available_memory(meminfo: &str, total: usize) -> Result { let available = meminfo.lines().find_map(|line| { let mut fields = line.split_whitespace(); @@ -732,8 +848,14 @@ pub fn available_memory(meminfo: &str, total: usize) -> Result { crate::Error::new("Linux MemAvailable is required to size integrated GPU memory") }) } -/// Keep the same server allowance and system share as integrated GPU planning. +/// Keep the same scaled server allowance and system share as integrated GPU planning. pub fn host_pool_budget(future: u64) -> Result { + host_pool_budget_with_reserve(future, true) +} + +/// Like [`host_pool_budget`], allowing callers with an explicit unified-memory limit +/// to omit the implicit service and system reserves. +pub fn host_pool_budget_with_reserve(future: u64, apply_reserve: bool) -> Result { #[cfg(unix)] let (available, total) = { let info = std::fs::read_to_string("/proc/meminfo").map_err(|e| e.to_string())?; @@ -760,9 +882,7 @@ pub fn host_pool_budget(future: u64) -> Result { } (memory.ullAvailPhys, memory.ullTotalPhys) }; - Ok(available - .saturating_sub(future) - .saturating_sub(HOST_SERVICE_HEADROOM_BYTES + total / HOST_SYSTEM_SHARE)) + Ok(host_pool_budget_from(available, total, future, apply_reserve)) } /// Resources retained from pre-sizing registration through the worker's store attachment. diff --git a/selene/src/offload/tests.rs b/selene/src/offload/tests.rs index bfd0bde36..92d53d53a 100644 --- a/selene/src/offload/tests.rs +++ b/selene/src/offload/tests.rs @@ -701,3 +701,162 @@ fn intake_shrinks_to_two_full_windows_without_refusing() { intake_slots(&layout, 1) as u64 * layout.page_record_bytes ); } + +#[test] +fn host_pool_budget_scales_small_socs_and_honors_explicit_limit_override() { + let mib = 1u64 << 20; + let gib = 1u64 << 30; + // <= 16 GiB SoCs use 64 MiB service headroom + total/20. + assert_eq!(host_service_headroom_bytes(8 * gib), 64 * mib); + assert_eq!(host_service_headroom_bytes(16 * gib), 64 * mib); + // Above 16 GiB scales as min(2 GiB, total/32). + assert_eq!(host_service_headroom_bytes(32 * gib), gib); + assert_eq!(host_service_headroom_bytes(64 * gib), 2 * gib); + assert_eq!(host_service_headroom_bytes(128 * gib), 2 * gib); + + // 8 GiB Jetson Orin with 3 GiB available: scaled reserve is 64 MiB + 409.6 MiB, + // leaving ~2.54 GiB rather than 0 (which an unscaled 2 GiB + total/20 reserve would leave). + let expected_8g = 3 * gib - (64 * mib + (8 * gib) / HOST_SYSTEM_SHARE); + assert_eq!(host_pool_budget_from(3 * gib, 8 * gib, 0, true), expected_8g); + // Explicit limit bypasses implicit service/system reserves. + assert_eq!(host_pool_budget_from(3 * gib, 8 * gib, 512 * mib, false), 3 * gib - 512 * mib); + assert_eq!(host_pool_budget_from(3 * gib, 128 * gib, 512 * mib, false), 3 * gib - 512 * mib); +} + +#[test] +fn prepare_with_inputs_budget_avoids_post_kv_alloc_shrinkage_and_capture_failure() { + let g = qualified_rank(); + let layout = Layout::new(std::slice::from_ref(&g)).unwrap(); + let full_intake = intake_slots(&layout, 16) as u64 * layout.page_record_bytes; + let options = PrefixCacheOffload { + memory_bytes: Some(8 * layout.page_record_bytes), + pool: Some(pool("unix:/run/selene.sock")), + ..Default::default() + }; + // Explicit pre-planned host budget preserves exact reserved intake slots. + let Preparation::Store(prepared) = super::prepare_with_inputs_budget( + &options, + std::path::Path::new("unused"), + [0; 32], + vec![g.clone()], + vec![(0, 0)], + 16, + 0, + None, + Some(full_intake), + &crate::testing::IdentityRegistrar, + ) + .unwrap() else { + panic!("missing store"); + }; + let pool_mem = prepared.memory_pool.as_ref().unwrap(); + assert_eq!(pool_mem.intake_slots(), intake_slots(&layout, 16)); + assert!(prepared.intake_warning(16).is_none()); + + // Pool-only capture honors the pre-planned host budget without failing post-KV-alloc. + let mut ranked = g; + ranked.page_capacity = 256; + let capture_opts = PrefixCacheOffload { + pool: Some(pool("unix:/run/selene.sock")), + ..Default::default() + }; + let capture_bytes = (256 + layout.row_slots() as u64) * layout.page_record_bytes; + let Preparation::Store(captured) = super::prepare_with_inputs_budget( + &capture_opts, + std::path::Path::new("unused"), + [0; 32], + vec![ranked], + vec![(0, 0)], + 4, + 0, + None, + Some(capture_bytes), + &crate::testing::IdentityRegistrar, + ) + .unwrap() else { + panic!("missing capture store"); + }; + assert_eq!( + captured.memory_pool.as_ref().unwrap().slot_count(), + 256 + layout.row_slots() + ); +} + +struct UnsupportedSplitRegistrar { + inner: crate::testing::TrackingRegistrar, + split_error: Option<&'static str>, +} + +impl crate::HostRegistrar for UnsupportedSplitRegistrar { + fn register( + &self, + context: usize, + address: usize, + bytes: usize, + ) -> Result> { + self.inner.register(context, address, bytes) + } + + fn map_split(&self, _requests: &[(usize, i32, usize)]) -> Result> { + Err(self + .split_error + .unwrap_or("HOST_NUMA split mapping unsupported") + .into()) + } + + fn try_map_split( + &self, + _requests: &[(usize, i32, usize)], + ) -> Result>> { + match self.split_error { + Some(err) => Err(err.into()), + None => Ok(None), + } + } +} + +#[test] +fn memory_only_falls_back_to_registered_mapping_when_host_numa_split_is_unsupported() { + let options = PrefixCacheOffload { + memory_bytes: Some(16 * 4096), + ..Default::default() + }; + let geometry = vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)]; + let registrar = UnsupportedSplitRegistrar { + inner: crate::testing::TrackingRegistrar::default(), + split_error: None, + }; + let Preparation::Store(prepared) = super::prepare( + &options, + std::path::Path::new("model.safetensors"), + [0; 32], + geometry.clone(), + vec![(0, 0)], + ®istrar, + ) + .unwrap() else { + panic!("missing memory store"); + }; + let pool = prepared.memory_pool.as_ref().unwrap(); + assert!(pool.registered()); + assert!(pool.rank_parts().is_none()); + assert_eq!(registrar.inner.calls.lock().unwrap().len(), 1); + + // Real split allocation errors (e.g. OOM) must propagate rather than falling back. + let oom = UnsupportedSplitRegistrar { + inner: crate::testing::TrackingRegistrar::default(), + split_error: Some("out of memory"), + }; + let error = super::prepare( + &options, + std::path::Path::new("model.safetensors"), + [0; 32], + geometry, + vec![(0, 0)], + &oom, + ) + .err() + .expect("OOM must not fall back"); + assert!(error.to_string().contains("out of memory")); + assert!(oom.inner.calls.lock().unwrap().is_empty()); +} diff --git a/selene/src/registrar.rs b/selene/src/registrar.rs index f98d0b35e..449e1f3f9 100644 --- a/selene/src/registrar.rs +++ b/selene/src/registrar.rs @@ -24,6 +24,17 @@ pub trait HostRegistrar { /// to its own device and the host only. The host cannot address a record /// across parts, so slot addresses in such a pool are identities. fn map_split(&self, requests: &[(usize, i32, usize)]) -> Result>; + + /// Like [`HostRegistrar::map_split`], returning `Ok(None)` when the device + /// or driver does not support per-rank `HOST_NUMA` split mappings so the + /// caller can fall back to a registered anonymous host mapping. Allocation + /// failures such as out-of-memory still return `Err`. + fn try_map_split( + &self, + requests: &[(usize, i32, usize)], + ) -> Result>> { + self.map_split(requests).map(Some) + } } /// An owned registration. Dropping it unregisters the range; the caller diff --git a/selene/src/slab.rs b/selene/src/slab.rs index 6aee5d04d..6d183e69a 100644 --- a/selene/src/slab.rs +++ b/selene/src/slab.rs @@ -186,20 +186,15 @@ impl SlabPool { ) } - /// A pool with the slot counts of [`SlabPool::sized`], split by - /// rank: each rank's part of every slot is pinned host memory that only the - /// device of `contexts[rank]` and the host access. Registering one mapping - /// maps it into every device at about 2 MiB of device memory per GiB; a - /// split pool costs each device that for its own part only. The CPU cannot - /// address a slot's record, so the pool suits stores that move records only - /// between devices and slots; [`SlabPool::rank_parts`] locates the parts. - pub fn sized_by_rank( + /// Like [`SlabPool::sized_by_rank`], returning `Ok(None)` when the registrar + /// reports per-rank `HOST_NUMA` split mapping is unsupported on this host. + pub fn try_sized_by_rank( layout: &Layout, bytes: u64, intake_slots: usize, contexts: &[(usize, i32)], registrar: &dyn HostRegistrar, - ) -> Result { + ) -> Result> { if contexts.len() != layout.ranks.len() { return Err(invalid(format!( "a pool split by rank needs one context per rank: {} contexts for {} ranks", @@ -217,7 +212,9 @@ impl SlabPool { .zip(&shares) .map(|(&(context, device), page)| (context, device, page * slot_count)) .collect(); - let memory = registrar.map_split(&requests)?; + let Some(memory) = registrar.try_map_split(&requests)? else { + return Ok(None); + }; let base = memory.address(); if memory.nbytes() < page_region { return Err(invalid( @@ -237,7 +234,7 @@ impl SlabPool { part_bytes: page, }) .collect(); - Ok(Self { + Ok(Some(Self { memory: Arc::new(Memory { intake_slots, mapping: base, @@ -251,7 +248,25 @@ impl SlabPool { }), }), slots: Arc::new(Mutex::new(Slots::new(slot_count))), - }) + })) + } + + /// A pool with the slot counts of [`SlabPool::sized`], split by + /// rank: each rank's part of every slot is pinned host memory that only the + /// device of `contexts[rank]` and the host access. Registering one mapping + /// maps it into every device at about 2 MiB of device memory per GiB; a + /// split pool costs each device that for its own part only. The CPU cannot + /// address a slot's record, so the pool suits stores that move records only + /// between devices and slots; [`SlabPool::rank_parts`] locates the parts. + pub fn sized_by_rank( + layout: &Layout, + bytes: u64, + intake_slots: usize, + contexts: &[(usize, i32)], + registrar: &dyn HostRegistrar, + ) -> Result { + Self::try_sized_by_rank(layout, bytes, intake_slots, contexts, registrar)? + .ok_or_else(|| invalid("split host mapping is not supported on this host")) } /// Each rank's part of the slots, in rank order, for a pool split by rank. From 85de9eae209472e35c287f3400d5327bd215339b Mon Sep 17 00:00:00 2001 From: Joshua Cartu Date: Sat, 28 Nov 2026 14:41:07 -0800 Subject: [PATCH 07/27] Bind core-declared FP32 parameters into text forward graphs Captured CUDA graphs already receive per-request inputs such as token IDs, positions, and the six-column sampling parameters, which are consumed only by post-logit sampling. Model recipes that condition forward computation on a client-supplied FP32 parameter cannot reuse the sampling layout without widening a contract shared by every core, and cannot isolate prefix-cache checkpoints by the conditioning value without native scheduler support. Declaring named FP32 core parameters in the model contract lets a single loaded core serve requests with different conditioning values without model-specific native policy or per-model flags. This change extends the runtime core contract, Helios runtime, Heliopause exporter, and Ignition preparation and direct-execution paths additively: - Schema and helpers (`helios/proto/runtime_core.proto`, `ignition/preparation/runtime_core_pb2.py`, `ignition/preparation/contract.py`): add `ModelContract.core_parameters = 8`, `CoreParameter`, `CoreParameterRange`, `ValueSource::CORE_PARAMETER = 43`, and `ValueBinding.parameter = 7`, keeping `ModelContract.version` at 3 and leaving existing cores without declarations unchanged. - Contract and export validation (`helios/src/model/contract.rs`, `helios/src/runtime_core/protobuf.rs`, `heliopause/src/export/binding.rs`): validate unique nonempty names, required finite FP32 defaults, ordered finite ranges containing their defaults, contiguous width-one FP32 destination buffers covering prepared request capacity, zero offset and padding, and an empty `tensor` field. Restrict `CORE_PARAMETER` bindings to text forward graphs (`PREFILL`, `TERMINAL_PREFILL`, `SCORED_PREFILL`, `RESUME`, `DECODE`, `SPECULATIVE`, and `MIXED`), rejecting `VISION`, `INIT`, `RESTORE`, and `SNAPSHOT` graphs, and require every selected text forward graph to bind every declared core parameter so no forward step can read stale slot storage. - HTTP decoding, discovery, admission, prefix hashing, and packing (`helios/src/server/`, `helios/src/scheduler.rs`, `helios/src/cache/hash.rs`, `helios/src/model/{admission,packing}.rs`): accept an optional top-level `core_parameters` object on Chat, Completions, Responses, and Messages requests (treating omitted or `null` as prepared defaults, rejecting unknown names, non-objects, booleans, non-numbers, non-finite values, magnitudes above `f32::MAX`, and nonzero underflow to FP32 zero with HTTP 400), clamp finite values to declared inclusive ranges, canonicalize `-0.0` to `+0.0`, advertise declarations under `flare.core_parameters` in `/v1/models`, hash every declared core parameter in declaration order into the prefix-history root (leaving the root hash unchanged when no core parameters are declared), retain the resolved map in `AdmissionPlan` across pool lookup retries and preemption/readmission, verify exact bit equality against the planned value during step packing, and pre-allocate staging storage in `Inputs::new` with checked offset and extent arithmetic. - Direct diagnostic execution and documentation (`ignition/direct/`, `docs/api.md`, `docs/direct-execution.md`, `helios/model-contract.md`): mirror the same text-forward binding rules, top-level-only `core_parameters` decoding, `/v1/models` metadata, packing, immutable request parameter map, and checkpoint isolation. Claimed result: a model core can declare generic per-request FP32 core parameters consumed by text forward graphs with shared admission validation, prefix-cache isolation, and zero steady-state packing allocation, while cores without declarations retain their wire contract and prefix-cache hashes. No recipe in this repository binds a core parameter, and no throughput or output-quality improvement is claimed. Supporting evidence and limitations: - Python CPU tests (`tests/direct`, `tests/cli`, `tests/preparation/test_core_boundary.py`): 218 passed, 2 CUDA-gated skipped. - Rust CPU tests (`--locked --release`): `flare-helios --features runtime-core,server --lib` 1,692 passed, 43 ignored, 1 unrelated pre-existing `origin/main` failure (`packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape`); `flare-helios --test '*'` 61 passed, 37 ignored; `flare-heliopause` 209 passed, 5 ignored (including `serving_metadata_round_trips_and_validates_core_parameters`); `flare` 236 passed, 4 ignored; `flare-cli` 224 passed, 3 ignored (`distribution::tests::source_waits_for_receiver_file_verification` skipped as a pre-existing 130 s environment failure). - TLA+ models and Rust lifecycle conformance (`verification/helios-lifecycle/check.py`, TLC 2.19): all 9 models, model mutations, Rust source mutations, and observed Rust transition replays passed across all 8 conformance suites. - Kani (`cargo kani --manifest-path helios/Cargo.toml --lib`, Kani 0.68.0 / CBMC 6.11.0): 9 of 9 harnesses verified, 0 failures, including `core_parameter_validation_enforces_finite_ordered_bounds` and `core_parameter_resolution_produces_valid_canonical_value`. - Unrun checks: live GPU export and serving of a core declaring `core_parameters` were not run on this rebased revision in this CPU verification environment. Signed-off-by: Joshua Cartu Co-Authored-By: Luke Alonso Signed-off-by: Luke Alonso Design-Signed-Off-By: Antigravity (Gemini); design-review=c3a9 --- docs/api.md | 19 + docs/direct-execution.md | 15 +- heliopause/src/export/binding.rs | 77 +++- helios/model-contract.md | 30 ++ helios/proto/runtime_core.proto | 15 + helios/src/cache/hash.rs | 13 + helios/src/cache/tests.rs | 30 ++ helios/src/model.rs | 2 + helios/src/model/admission.rs | 8 + helios/src/model/contract.rs | 190 ++++++++- helios/src/model/contract/kani_proofs.rs | 59 +++ helios/src/model/kani_proofs.rs | 1 + helios/src/model/packed_round_tests.rs | 3 +- helios/src/model/packing.rs | 216 ++++++++-- helios/src/model/testing.rs | 4 +- helios/src/model/tests.rs | 463 ++++++++++++++++++++++ helios/src/runtime_core/mod.rs | 3 + helios/src/runtime_core/protobuf.rs | 125 +++++- helios/src/scheduler.rs | 46 ++- helios/src/server/inference.rs | 1 + helios/src/server/models.rs | 50 +++ helios/src/server/protocol/decode.rs | 74 ++++ helios/src/server/request.rs | 4 + helios/src/server/runtime.rs | 76 +++- helios/src/server/runtime/phase_tests.rs | 224 +++++++++++ helios/src/server/runtime/prompt_tests.rs | 2 +- ignition/direct/packing.py | 1 + ignition/direct/scheduler.py | 187 ++++++++- ignition/direct/server.py | 30 +- ignition/preparation/contract.py | 57 ++- ignition/preparation/runtime_core_pb2.py | 356 +++++++++-------- tests/direct/test_scheduler.py | 273 +++++++++++++ 32 files changed, 2393 insertions(+), 261 deletions(-) diff --git a/docs/api.md b/docs/api.md index 4704c8c34..d84c9be34 100644 --- a/docs/api.md +++ b/docs/api.md @@ -42,6 +42,7 @@ The additional `flare` object reports prepared and selected serving metadata: | `sampling_defaults` | Prepared seed, temperature, filters, and penalties used for omitted request fields | | `thinking_token_budget` | Operator default reasoning-token cap for conversational requests; null when unset | | `sampling_ranges` | Inclusive `{min, max}` bounds for distribution parameters; null fixes a parameter at its prepared default; seed is request-controlled | +| `core_parameters` | Ordered per-request FP32 parameters declared by the model core; each entry contains `name`, `default`, and an optional inclusive `range` with `min` and `max` | | `max_images_per_prompt` | Context-derived upper bound on image count; image sizes, framing, text, output, and HTTP body size further constrain admission; zero for text-only cores | | `max_image_tokens_per_prompt` | Context-derived upper bound on image tokens across the entire conversation; text, framing, and output also occupy context; zero for text-only cores | | `image_feature_window_tokens` | Prepared feature storage per active image request; chunked prefill reuses this storage across windows, so it does not limit total conversation image tokens | @@ -745,6 +746,24 @@ request-controlled and uses its prepared default when omitted. Sampling defaults and ranges come from the model author's recommendations declared in the recipe, except for DeepSeek V4.1's repetition-penalty range based on measured use. +Every generation protocol accepts an optional top-level `core_parameters` JSON +object whose keys name FP32 parameters declared by the loaded model core +(and advertised under `flare.core_parameters` in `/v1/models`). Omitting +`core_parameters` or setting it to `null` uses prepared defaults for all +declared parameters. Non-object values, empty or undeclared names, booleans, +non-numeric values, non-finite numbers, values whose magnitude exceeds +`f32::MAX`, and nonzero values that underflow to FP32 zero return HTTP 400. + +An omitted declared parameter uses its prepared default. A declaration with an +inclusive `range` clamps finite FP32 request values to `[min, max]`; a +declaration without a range accepts any finite FP32 value. Resolution +canonicalizes `-0.0` to `+0.0`. Declared core parameters are bound +independently of the six-column sampling layout. Prefix-cache identity hashes +every declared effective parameter in declaration order (length-prefixed name +and canonical FP32 bits) into the prefix root, so requests with different +resolved values cannot share checkpoints. For cores without declared core +parameters, the prefix root hashes only the domain tag and core identity. + The recipes use these default-mode settings. Parameters without an interval in the table are fixed at their defaults. Bounds span the minimum and maximum values across each card's task or mode presets, including intermediate values and diff --git a/docs/direct-execution.md b/docs/direct-execution.md index 74469fcbc..c45aff7b0 100644 --- a/docs/direct-execution.md +++ b/docs/direct-execution.md @@ -81,6 +81,11 @@ kind, device errors by code, request outcomes and prefix-cache counters. Each retired request prints one line on stderr: prompt and reused tokens, generated tokens, speculative rounds and outcome. +`/v1/models` reports the core's declared `core_parameters` under `flare`. Chat +requests accept the same top-level `core_parameters` object as native serving; +omitting it or passing `null` uses declared defaults, and the direct scheduler +resolves defaults and ranges before prefix lookup. + ## Design **Scheduler** (`ignition/direct/scheduler.py`, CPU only). FIFO admission @@ -146,10 +151,12 @@ would otherwise age every request and expire estimates sooner than under Helios. **Packing.** Each step's uploads follow the prepared graph's typed value bindings, as in Helios's shared packer: state-row indices, row slots and generations, page and draft page tables, token IDs, query lengths, sampling -flags, state-transfer commands and admission rows. Bytes it does not write -keep their resident values, as with native partial uploads. Combined packed -rounds bind `SPECULATIVE_PREFIX_LIMIT` and leave query lengths to the captured -GPU allocator. +flags, state-transfer commands, admission rows, and declared FP32 core +parameters on text forward graphs. Bytes it does not write keep their resident +values, as with native partial uploads. Combined packed rounds bind +`SPECULATIVE_PREFIX_LIMIT` and leave query lengths to the captured GPU +allocator. Direct prefix keys include the same canonical core-parameter +identity as native serving when a core declares core parameters. Completion records are validated against the step before any state changes; a record that contradicts it stops execution. diff --git a/heliopause/src/export/binding.rs b/heliopause/src/export/binding.rs index 3f8308573..0e6572805 100644 --- a/heliopause/src/export/binding.rs +++ b/heliopause/src/export/binding.rs @@ -1041,7 +1041,11 @@ pub(crate) fn serving_metadata( server .entry("speculative_proposal_source") .or_insert("mtp".into()); - index.contract = Some(message("ServingContract", &server.into())?); + let contract: super::wire::ServingContract = message("ServingContract", &server.into())?; + if let Some(model_contract) = contract.model_contract.as_ref() { + helios_core::runtime_core::validate_core_parameters(model_contract)?; + } + index.contract = Some(contract); Ok(assets.clone()) } @@ -1561,6 +1565,77 @@ mod asset_tests { .is_err() ); } + + #[test] + fn serving_metadata_round_trips_and_validates_core_parameters() { + let base_server = |core_parameters: serde_json::Value| { + serde_json::json!({ + "model_id": "test/model", + "identity": "test/model", + "max_sequence_tokens": 128, + "prefill_chunk_size": 64, + "pages": 4, + "state_rows": 4, + "page_tokens": 64, + "assets": {"tokenizer": {"path": "/tmp/tok.json", "sha256": "00"}}, + "sampling_defaults": { + "seed": 0, "temperature": 1.0, "top_k": 20, "top_p": 0.95, + "min_p": 0.0, "repetition_penalty": 1.0, "presence_penalty": 0.0, + "frequency_penalty": 0.0 + }, + "frontend": {"prompt_encoder": 1, "eos_token_ids": [2]}, + "model_contract": { + "version": 3, + "vocabulary": 100, + "input_vocabulary": 100, + "core_parameters": core_parameters, + "graphs": [{ + "graph": "decode", + "kind": 5, + "inputs": [{ + "buffer": "request_gain", + "source": 43, + "indexing": 3, + "value_offset": 0, + "padding": 0, + "tensor": "", + "parameter": "gain" + }], + "state_rows_per_request": 1 + }] + } + }) + }; + let mut index = super::super::wire::ModelIndex::default(); + super::serving_metadata( + &mut index, + &base_server(serde_json::json!([ + {"name": "gain", "default_value": 0.5, "range": {"min": 0.0, "max": 1.0}}, + {"name": "offset", "default_value": 0.0} + ])), + ) + .unwrap(); + let contract = index.contract.unwrap().model_contract.unwrap(); + assert_eq!(contract.core_parameters.len(), 2); + assert_eq!(contract.core_parameters[0].name, "gain"); + assert_eq!(contract.core_parameters[0].default_value, Some(0.5)); + assert_eq!(contract.core_parameters[1].range, None); + assert_eq!(contract.graphs[0].inputs[0].source, 43); + assert_eq!(contract.graphs[0].inputs[0].parameter, "gain"); + + for invalid in [ + serde_json::json!([{"name": "gain"}]), + serde_json::json!([{"name": "", "default_value": 0.0}]), + serde_json::json!([{"name": "gain", "default_value": 2.0, "range": {"min": 0.0, "max": 1.0}}]), + serde_json::json!([ + {"name": "gain", "default_value": 0.0}, + {"name": "gain", "default_value": 0.5} + ]), + ] { + let mut bad = super::super::wire::ModelIndex::default(); + assert!(super::serving_metadata(&mut bad, &base_server(invalid)).is_err()); + } + } } #[pyclass(frozen, module = "flare_heliopause")] diff --git a/helios/model-contract.md b/helios/model-contract.md index 2ab226b76..569616487 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -83,6 +83,7 @@ serving contract and replay path unchanged. | `cache` | Logical page tokens, attention-history storage, and page-table views | | `graphs` | Per-program operation, value bindings, persistent-state accesses, and resource dependencies | | `frontend` | Independent parser and image implementation identifiers plus their syntax and layout data | +| `core_parameters` | Ordered per-request FP32 core parameters, each with a unique nonempty name, finite default, and optional inclusive range | Every enum has an unspecified zero value, which cannot select an implementation. Unknown identifiers, unsupported versions, and unknown semantic JSON fields are @@ -104,12 +105,33 @@ registered transport destination and an enum-selected source: | Copied proposals | Candidate IDs, count, generation, consumed endpoint, and per-position grammar masks | | Constants | Declared integer values and inactive-row padding | | Image tensors | Named outputs of the selected image layout implementation | +| Declared core parameters | One named FP32 value per request row on text forward graphs, bound independently of sampling storage | Indexing is explicit: scalar, submission row, active row, physical request row, or packed token. Active rows omit inactive tails; submission rows initialize padding across the request capacity. Packed-token indices follow each lane's actual token count. Integer offsets and padding are declared separately. Omitted transfers retain device bytes; scratch buffers need no host value source. + +`CORE_PARAMETER` (`ValueSource` 43) requires a nonempty `ValueBinding.parameter` +matching one unique `ModelContract.core_parameters` declaration; every other +value source leaves `ValueBinding.parameter` empty. Its destination is a +contiguous width-one FP32 buffer covering at least the prepared request capacity +with `SUBMISSION_ROW`, `ACTIVE_ROW`, or `REQUEST_ROW` indexing, zero value +offset, zero padding, and an empty `tensor` field. `CORE_PARAMETER` bindings +belong only to text forward graphs (`PREFILL`, `TERMINAL_PREFILL`, +`SCORED_PREFILL`, `RESUME`, `DECODE`, `SPECULATIVE`, and `MIXED`), not `VISION`, +`INIT`, `RESTORE`, or `SNAPSHOT` graphs. Every selected text forward graph must +bind every declared core parameter, and a core with declarations requires at +least one selected text forward graph, ensuring every forward submission writes +each active lane's resolved value rather than reading stale slot contents. +Inactive rows of a `SUBMISSION_ROW` core-parameter binding receive `0.0`. Shared +admission fills omitted names from declared defaults, clamps finite FP32 request +values to declared inclusive ranges, accepts any finite FP32 value when `range` +is omitted, canonicalizes `-0.0` to `+0.0`, and rejects unknown names or +out-of-range numeric encodings. The six-column `SAMPLING_PARAMETERS` layout +remains unchanged. + The execution transport owns frame index and submission sequence. Prefill-capable graphs (`PREFILL`, `TERMINAL_PREFILL`, `SCORED_PREFILL`, `MIXED`) @@ -250,6 +272,14 @@ storage. Restore copies those payloads to private writable pages. Cancellation and preemption retain resources through their final GPU fence. Failed execution cannot publish a successful checkpoint. +Prefix-history roots include every declared core parameter in declaration order, +including zero values, encoded as length-prefixed name bytes and canonical FP32 +bits (`-0.0` canonicalized to `+0.0`). A core with no declared core parameters +hashes only the domain tag and core identity into the prefix root. Admission +plans retain the resolved parameter map through pool lookup retries, preemption, +and readmission, and input packing verifies that every uploaded parameter bit +pattern matches the admission plan's prefix-history value. + ## Frontend implementations Tool parsers, reasoning parsers, image preparation, and image layouts each have diff --git a/helios/proto/runtime_core.proto b/helios/proto/runtime_core.proto index a0c3247d5..d217b4ea6 100644 --- a/helios/proto/runtime_core.proto +++ b/helios/proto/runtime_core.proto @@ -270,6 +270,17 @@ message ModelContract { CacheContract cache = 5; repeated GraphContract graphs = 6; FrontendContract frontend = 7; + // Generic per-request FP32 values consumed by CORE_PARAMETER graph bindings. + repeated CoreParameter core_parameters = 8; +} +message CoreParameter { + string name = 1; + optional float default_value = 2; + CoreParameterRange range = 3; +} +message CoreParameterRange { + optional float min = 1; + optional float max = 2; } message VisionCapacity { // Zero inherits prepared execution concurrency when max_images is nonzero. @@ -368,6 +379,8 @@ enum ValueSource { PROMPT_LOOKAHEAD_TOKEN = 41; // Number of valid lookahead tokens following each prefill lane's current chunk (zero when absent). PROMPT_LOOKAHEAD_LENGTH = 42; + // Named FP32 parameter declared by ModelContract.core_parameters. + CORE_PARAMETER = 43; } enum InputIndexing { INDEXING_UNSPECIFIED = 0; @@ -384,6 +397,8 @@ message ValueBinding { sint64 value_offset = 4; sint64 padding = 5; string tensor = 6; + // CoreParameter.name for CORE_PARAMETER; empty for every other source. + string parameter = 7; } enum StateAccessKind { STATE_ACCESS_UNSPECIFIED = 0; diff --git a/helios/src/cache/hash.rs b/helios/src/cache/hash.rs index 74551476c..8a3f0b21f 100644 --- a/helios/src/cache/hash.rs +++ b/helios/src/cache/hash.rs @@ -35,9 +35,22 @@ pub struct PrefixHistory { impl PrefixHistory { pub fn new(identity: [u8; 32]) -> Self { + Self::with_core_parameters(identity, std::iter::empty::<(&str, f32)>()) + } + + pub fn with_core_parameters<'a>( + identity: [u8; 32], + parameters: impl IntoIterator, + ) -> Self { let mut hash = Blake2b::::new(); hash.update(b"flare-prefix-root-v1\0"); hash.update(identity); + for (name, value) in parameters { + let value = crate::model::contract::canonical_core_parameter(value); + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name.as_bytes()); + hash.update(value.to_bits().to_le_bytes()); + } Self { identity, boundaries: vec![PrefixKey { diff --git a/helios/src/cache/tests.rs b/helios/src/cache/tests.rs index 27559367e..af16ec6d4 100644 --- a/helios/src/cache/tests.rs +++ b/helios/src/cache/tests.rs @@ -124,6 +124,36 @@ fn hash_matches_independent_blake2b128_vectors() { ); } +#[test] +fn core_parameter_names_fp32_bits_and_declaration_order_isolate_prefixes() { + let tokens = (0..130).collect::>(); + let build = |parameters: &[(&str, f32)]| { + let mut history = + PrefixHistory::with_core_parameters([7; 32], parameters.iter().copied()); + history.append(&tokens, &[]).unwrap(); + history + }; + let baseline = build(&[]); + let zero = build(&[("alpha", 0.), ("beta", -0.)]); + let zero_pos = build(&[("alpha", 0.), ("beta", 0.)]); + for endpoint in [0, 5, 64, 128, 130] { + assert_ne!(baseline.key_at(endpoint), zero.key_at(endpoint)); + assert_eq!(zero.key_at(endpoint), zero_pos.key_at(endpoint)); + } + let first = build(&[("alpha", 0.5), ("beta", 1.)]); + let same = build(&[("alpha", 0.5), ("beta", 1.)]); + let other_value = build(&[("alpha", 0.25), ("beta", 1.)]); + let other_name = build(&[("gamma", 0.5), ("beta", 1.)]); + let other_order = build(&[("beta", 1.), ("alpha", 0.5)]); + for endpoint in [0, 5, 64, 128, 130] { + assert_eq!(first.key_at(endpoint), same.key_at(endpoint)); + assert_ne!(first.key_at(endpoint), baseline.key_at(endpoint)); + assert_ne!(first.key_at(endpoint), other_value.key_at(endpoint)); + assert_ne!(first.key_at(endpoint), other_name.key_at(endpoint)); + assert_ne!(first.key_at(endpoint), other_order.key_at(endpoint)); + } +} + #[test] fn chunking_retains_partial_tokens_and_conditioning_until_complete() { let mut whole = PrefixHistory::new([7; 32]); diff --git a/helios/src/model.rs b/helios/src/model.rs index 0402f28b0..00ae80ead 100644 --- a/helios/src/model.rs +++ b/helios/src/model.rs @@ -25,6 +25,8 @@ pub use admission::Admission; pub use contract::PreparedContract; pub use inputs::{InputStep, pack_inputs}; pub use packing::Inputs; + +pub type CoreParameters = std::collections::BTreeMap; #[cfg(feature = "server")] pub use prompt::{ declared_control_tokens, prepare_image_inputs, prepare_input, prepare_output, reasoning_delimiter_tokens, diff --git a/helios/src/model/admission.rs b/helios/src/model/admission.rs index 4c92fbe36..aea769770 100644 --- a/helios/src/model/admission.rs +++ b/helios/src/model/admission.rs @@ -59,6 +59,7 @@ impl PromptMetadataMut<'_> { pub struct Admission { pub handle: RequestHandle, pub sampling: SamplingParameters, + pub core_parameters: crate::model::CoreParameters, pub max_new_tokens: u32, pub prompt: Vec, pub data: crate::model::PromptData, @@ -70,6 +71,9 @@ pub struct Admission { impl Admission { pub fn validate(&self, config: &ModelConfig) -> Result<()> { self.sampling.validate()?; + config + .contract + .validate_core_parameters(&self.core_parameters)?; if self.handle.slot as usize >= config.limits.max_active || self.handle.generation == 0 || self.handle.generation > i64::MAX as u64 @@ -111,6 +115,7 @@ impl Admission { let admission = Self { handle, sampling: prompt.sampling.clone(), + core_parameters: prompt.core_parameters.clone(), max_new_tokens: prompt.max_new_tokens, prompt: prompt.tokens.clone(), data: prompt.data.clone(), @@ -129,6 +134,9 @@ impl Admission { #[cfg(feature = "server")] pub fn validate_prompt(config: &ModelConfig, prompt: &crate::server::Prompt) -> Result<()> { prompt.sampling.validate()?; + config + .contract + .validate_core_parameters(&prompt.core_parameters)?; if !prompt.logprob_token_ids.is_empty() { if config.logprob_token_id_capacity == 0 { return Err("logprob_token_ids are not available in this model core; re-export to enable them".into()); diff --git a/helios/src/model/contract.rs b/helios/src/model/contract.rs index b07d2f24b..24c19155c 100644 --- a/helios/src/model/contract.rs +++ b/helios/src/model/contract.rs @@ -60,7 +60,7 @@ contract_enum!(ValueSource { GrammarEnabled = 30, CopyTokenIds = 31, CopyTokenCount = 32, CopyConsumedTokens = 33, CopyGeneration = 34, CopyGrammarMask = 35, CopyGrammarCount = 36, ImageTensor = 37, ImageFeatureSlot = 38, PromptTargetToken = 39, SpeculativePrefixLimit = 40, - PromptLookaheadToken = 41, PromptLookaheadLength = 42, + PromptLookaheadToken = 41, PromptLookaheadLength = 42, CoreParameter = 43, }); contract_enum!(InputIndexing { Scalar = 1, SubmissionRow = 2, RequestRow = 3, PackedToken = 4, ActiveRow = 5 }); contract_enum!(StateAccessKind { Read = 1, Write = 2, ReadWrite = 3 }); @@ -107,6 +107,37 @@ pub struct PreparedContract { pub cache: CacheContract, pub graphs: Vec, pub frontend: FrontendContract, + #[cfg_attr(any(feature = "frontend", feature = "runtime-core"), serde(default))] + pub core_parameters: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr( + any(feature = "frontend", feature = "runtime-core"), + derive(serde::Serialize, serde::Deserialize) +)] +#[cfg_attr( + any(feature = "frontend", feature = "runtime-core"), + serde(deny_unknown_fields) +)] +pub struct CoreParameterRange { + pub min: f32, + pub max: f32, +} + +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr( + any(feature = "frontend", feature = "runtime-core"), + derive(serde::Serialize, serde::Deserialize) +)] +#[cfg_attr( + any(feature = "frontend", feature = "runtime-core"), + serde(deny_unknown_fields) +)] +pub struct CoreParameter { + pub name: String, + pub default_value: f32, + pub range: Option, } #[derive(Clone, Debug)] @@ -200,6 +231,8 @@ pub struct ValueBinding { pub value_offset: i64, pub padding: i64, pub tensor: String, + #[cfg_attr(any(feature = "frontend", feature = "runtime-core"), serde(default))] + pub parameter: String, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -384,6 +417,86 @@ impl ImageTokenLayout { } } +pub fn canonical_core_parameter(value: f32) -> f32 { + if value == 0. { 0. } else { value } +} + +pub(crate) fn is_text_forward_graph(kind: GraphKind) -> bool { + matches!( + kind, + GraphKind::Prefill + | GraphKind::TerminalPrefill + | GraphKind::ScoredPrefill + | GraphKind::Resume + | GraphKind::Decode + | GraphKind::Speculative + | GraphKind::Mixed + ) +} + +impl CoreParameter { + pub fn validate(&self) -> Result<()> { + if self.name.is_empty() + || !self.default_value.is_finite() + || self.range.is_some_and(|range| { + !range.min.is_finite() + || !range.max.is_finite() + || range.min > range.max + || !(range.min..=range.max).contains(&self.default_value) + }) + { + return Err("invalid core-parameter declaration".into()); + } + Ok(()) + } + + pub fn resolve_value(&self, requested: Option) -> Result { + let mut value = requested.unwrap_or(self.default_value); + if !value.is_finite() { + return Err("core_parameters values must be finite FP32 numbers".into()); + } + if let Some(range) = self.range { + value = value.clamp(range.min, range.max); + } + Ok(canonical_core_parameter(value)) + } + + pub fn validate_value(&self, value: f32) -> bool { + value.is_finite() + && value.to_bits() == canonical_core_parameter(value).to_bits() + && self + .range + .is_none_or(|range| value >= range.min && value <= range.max) + } +} + +pub fn validate_core_parameter_declarations(parameters: &[CoreParameter]) -> Result<()> { + let mut names = std::collections::HashSet::new(); + for parameter in parameters { + parameter.validate()?; + if !names.insert(parameter.name.as_str()) { + return Err("duplicate core-parameter declaration".into()); + } + } + Ok(()) +} + +pub fn validate_resolved_core_parameters( + parameters: &[CoreParameter], + values: &crate::model::CoreParameters, +) -> Result<()> { + if values.len() != parameters.len() + || parameters.iter().any(|parameter| { + values + .get(¶meter.name) + .is_none_or(|&value| !parameter.validate_value(value)) + }) + { + return Err("core_parameters does not match the model core's resolved parameters".into()); + } + Ok(()) +} + impl PreparedContract { pub fn graph(&self, name: &str) -> Result<&GraphContract> { self.graphs @@ -392,6 +505,36 @@ impl PreparedContract { .ok_or_else(|| format!("graph {name} has no semantic contract").into()) } + pub fn core_parameter(&self, name: &str) -> Option<&CoreParameter> { + self.core_parameters + .iter() + .find(|parameter| parameter.name == name) + } + + pub fn resolve_core_parameters( + &self, + requested: &crate::model::CoreParameters, + ) -> Result { + if requested + .keys() + .any(|name| self.core_parameter(name).is_none()) + { + return Err( + "core_parameters contains a parameter not declared by the model core".into(), + ); + } + let mut resolved = crate::model::CoreParameters::new(); + for parameter in &self.core_parameters { + let value = parameter.resolve_value(requested.get(¶meter.name).copied())?; + resolved.insert(parameter.name.clone(), value); + } + Ok(resolved) + } + + pub fn validate_core_parameters(&self, values: &crate::model::CoreParameters) -> Result<()> { + validate_resolved_core_parameters(&self.core_parameters, values) + } + pub fn validate(&self, manifest: &ExecutionManifest) -> Result<()> { if !(1..=3).contains(&self.version) { return Err("unsupported prepared model contract version; re-export the model core".into()); @@ -405,6 +548,8 @@ impl PreparedContract { return Err("invalid prepared model contract vocabulary or geometry".into()); } self.vision.validate()?; + validate_core_parameter_declarations(&self.core_parameters)?; + let mut saw_text_forward = false; self.frontend.validate()?; if self.vision.enabled() != self.frontend.image_layout.is_some() || self.frontend.image_layout.is_some() != self.frontend.image_preparation.is_some() @@ -517,6 +662,9 @@ impl PreparedContract { return Err("prompt lookahead requires paired packed lookahead_token_ids and int32 submission-row lookahead_query_lengths bindings".into()); } } + let text_forward = is_text_forward_graph(descriptor.kind); + saw_text_forward |= text_forward; + let mut graph_parameters = std::collections::HashSet::new(); let mut destinations = std::collections::HashSet::new(); for input in &graph.inputs { if !destinations.insert(&input.buffer) @@ -542,6 +690,41 @@ impl PreparedContract { { return Err("host input bindings require contiguous prepared storage".into()); } + let core_parameter = input.source == ValueSource::CoreParameter; + if core_parameter == input.parameter.is_empty() { + return Err("invalid core-parameter graph binding".into()); + } + if core_parameter { + if !text_forward { + return Err( + "core-parameter bindings belong only to text forward graphs".into(), + ); + } + if self.core_parameter(&input.parameter).is_none() + || buffer.dtype != crate::execution::Dtype::Float32 + || buffer.shape.is_empty() + || buffer.shape[0] < manifest.request_capacity() + || buffer.shape[1..].iter().any(|&extent| extent != 1) + || !matches!( + input.indexing, + InputIndexing::SubmissionRow + | InputIndexing::RequestRow + | InputIndexing::ActiveRow + ) + || input.value_offset != 0 + || input.padding != 0 + || !input.tensor.is_empty() + { + return Err("invalid core-parameter graph binding".into()); + } + graph_parameters.insert(input.parameter.as_str()); + } + } + if text_forward && graph_parameters.len() != self.core_parameters.len() { + return Err( + "every selected text forward graph must bind every declared core parameter" + .into(), + ); } let prefix: Vec<_> = graph.inputs.iter().filter(|input| input.source == ValueSource::SpeculativePrefixLimit).collect(); let query: Vec<_> = graph.inputs.iter().filter(|input| input.source == ValueSource::QueryLength).collect(); @@ -642,6 +825,11 @@ impl PreparedContract { return Err("decode graph must declare its pending token source".into()); } } + if !self.core_parameters.is_empty() && !saw_text_forward { + return Err( + "declared core parameters require at least one selected text forward graph".into(), + ); + } Ok(()) } } diff --git a/helios/src/model/contract/kani_proofs.rs b/helios/src/model/contract/kani_proofs.rs index b2a17fb0b..91f46d2cc 100644 --- a/helios/src/model/contract/kani_proofs.rs +++ b/helios/src/model/contract/kani_proofs.rs @@ -81,3 +81,62 @@ fn state_view_storage_validation_matches_wide_arithmetic() { && rows as u128 * view.stride as u128 <= nbytes as u128; assert_eq!(view.fits_storage(&buffer), expected); } + +#[kani::proof] +fn core_parameter_validation_enforces_finite_ordered_bounds() { + let default_value: f32 = kani::any(); + let has_range: bool = kani::any(); + let min: f32 = kani::any(); + let max: f32 = kani::any(); + let empty_name: bool = kani::any(); + let parameter = CoreParameter { + name: if empty_name { String::new() } else { "x".into() }, + default_value, + range: has_range.then_some(CoreParameterRange { min, max }), + }; + let expected = !empty_name + && default_value.is_finite() + && (!has_range + || (min.is_finite() + && max.is_finite() + && min <= max + && min <= default_value + && default_value <= max)); + assert_eq!(parameter.validate().is_ok(), expected); +} + +#[kani::proof] +fn core_parameter_resolution_produces_valid_canonical_value() { + let default_value: f32 = kani::any(); + let has_range: bool = kani::any(); + let min: f32 = kani::any(); + let max: f32 = kani::any(); + let parameter = CoreParameter { + name: "x".into(), + default_value, + range: has_range.then_some(CoreParameterRange { min, max }), + }; + kani::assume(parameter.validate().is_ok()); + + let requested: Option = if kani::any() { + Some(kani::any()) + } else { + None + }; + match parameter.resolve_value(requested) { + Ok(resolved) => { + if let Some(value) = requested { + assert!(value.is_finite()); + } + assert!(resolved.is_finite()); + assert_ne!(resolved.to_bits(), (-0.0f32).to_bits()); + if let Some(range) = parameter.range { + assert!(resolved >= range.min && resolved <= range.max); + } + assert!(parameter.validate_value(resolved)); + } + Err(_) => { + assert!(requested.is_some_and(|value| !value.is_finite())); + } + } +} diff --git a/helios/src/model/kani_proofs.rs b/helios/src/model/kani_proofs.rs index 2d97df0c5..efda74ac5 100644 --- a/helios/src/model/kani_proofs.rs +++ b/helios/src/model/kani_proofs.rs @@ -79,6 +79,7 @@ fn completion_fixture(tokens_below_vocabulary: bool) -> CompletionFixture { prefix_boundary: None, image_tokens: None, }, + core_parameters: Vec::new(), }, identity: [0; 32], model_id: String::new(), diff --git a/helios/src/model/packed_round_tests.rs b/helios/src/model/packed_round_tests.rs index 77ac0e8f4..1d6bcc70f 100644 --- a/helios/src/model/packed_round_tests.rs +++ b/helios/src/model/packed_round_tests.rs @@ -120,7 +120,8 @@ fn packed_combined_packing_preserves_sparse_slot_keys_and_ceiling_padding() { let prompt = vec![7; 64]; let h = scheduler.admit(RequestSpec { prompt_logprobs: false, message_boundaries: vec![], prompt: prompt.clone(), conditioning: vec![], max_new_tokens: 64, grammar_constrained: false, host_stops: false, growable_output: false }).unwrap(); - admissions[h.slot as usize] = Some(Admission { prompt_logprobs: false, handle: h, sampling: SamplingParameters::default(), + 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 }); handles.push(h); diff --git a/helios/src/model/packing.rs b/helios/src/model/packing.rs index bf06dfadb..b483405e8 100644 --- a/helios/src/model/packing.rs +++ b/helios/src/model/packing.rs @@ -47,6 +47,7 @@ pub struct Inputs { /// Grammar-mask byte ranges (buffer, offset, length) that already hold an unconstrained mask. unconstrained_masks: Vec<(String, usize, usize)>, integers: Vec, + core_parameters: Vec, values: Vec, } @@ -135,6 +136,13 @@ impl Inputs { RequestSlot | RequestGeneration if graph.kind == GraphKind::Vision => { binding.indexing == Scalar } + CoreParameter => { + is_text_forward_graph(graph.kind) + && matches!( + binding.indexing, + SubmissionRow | RequestRow | ActiveRow + ) + } _ => matches!(binding.indexing, SubmissionRow | RequestRow | ActiveRow), }; if !valid_indexing { @@ -143,12 +151,18 @@ impl Inputs { ); } if matches!(binding.indexing, SubmissionRow | RequestRow | ActiveRow) - && elements < config.limits.request_capacity() * width + && config + .limits + .request_capacity() + .checked_mul(width) + .is_none_or(|required| elements < required) { return Err("row input cannot cover the prepared request slots".into()); } - if matches!(binding.source, SamplingParameters | ImageTensor | PageTable) - && binding.value_offset != 0 + if matches!( + binding.source, + SamplingParameters | CoreParameter | ImageTensor | PageTable + ) && binding.value_offset != 0 { return Err("value offset requires an integer value source".into()); } @@ -168,7 +182,10 @@ impl Inputs { } else { graph.packed_tokens() }; - if elements < rows * width { + if rows + .checked_mul(width) + .is_none_or(|required| elements < required) + { return Err( "packed input cannot cover the graph token capacity".into() ); @@ -216,13 +233,21 @@ impl Inputs { | ValueSource::RequestGeneration | ValueSource::CopyGeneration ) && buffer.dtype != Dtype::Int64) - || (binding.source == ValueSource::SamplingParameters - && buffer.dtype != Dtype::Float32) - || (binding.source != ValueSource::SamplingParameters - && binding.source != ValueSource::ImageTensor - && !matches!(buffer.dtype, Dtype::Int32 | Dtype::Int64)) + || (matches!( + binding.source, + ValueSource::SamplingParameters | ValueSource::CoreParameter + ) && buffer.dtype != Dtype::Float32) + || (!matches!( + binding.source, + ValueSource::SamplingParameters + | ValueSource::CoreParameter + | ValueSource::ImageTensor + ) && !matches!(buffer.dtype, Dtype::Int32 | Dtype::Int64)) || (binding.indexing != InputIndexing::Scalar - && elements < width * graph.batch_capacity) + && graph + .batch_capacity + .checked_mul(width) + .is_none_or(|required| elements < required)) { return Err(format!( "invalid shape or dtype for semantic input {}", @@ -258,6 +283,14 @@ impl Inputs { }) }) .collect::>>()?; + let core_parameter_capacity = if graphs.iter().flat_map(|graph| &graph.inputs).any(|input| { + input.binding.source == ValueSource::CoreParameter + && input.binding.indexing == InputIndexing::SubmissionRow + }) { + config.limits.request_capacity() + } else { + 0 + }; let maximum = graphs .iter() .flat_map(|g| &g.inputs) @@ -271,6 +304,7 @@ impl Inputs { pages: vec![[(0, 0); REQUEST_LANES]; config.contract.cache.page_tables.len()], unconstrained_masks: Vec::new(), integers: Vec::with_capacity(maximum), + core_parameters: Vec::with_capacity(core_parameter_capacity), values: Vec::with_capacity(maximum), }) } @@ -348,7 +382,11 @@ impl Inputs { .iter() .find(|t| t.buffer == input.binding.tensor) .ok_or("image layout did not produce a required tensor")?; - if tensor.offset + tensor.bytes.len() > input.elements * input.dtype.size() { + if tensor + .offset + .checked_add(tensor.bytes.len()) + .is_none_or(|end| end > input.elements * input.dtype.size()) + { return Err("image tensor exceeds prepared graph capacity".into()); } self.staging.put( @@ -493,13 +531,24 @@ impl Inputs { continue; } if binding.indexing == InputIndexing::SubmissionRow { - self.integers.clear(); - self.integers.resize( - frame.config.limits.request_capacity() * input.width, - binding.padding, - ); + let elements = frame + .config + .limits + .request_capacity() + .checked_mul(input.width) + .ok_or("submission-row input extent overflow")?; + if elements > input.elements { + return Err("packed values exceed prepared input storage".into()); + } + if binding.source == ValueSource::CoreParameter { + self.core_parameters.clear(); + self.core_parameters.resize(elements, 0.); + } else if binding.source != ValueSource::SamplingParameters { + self.integers.clear(); + self.integers.resize(elements, binding.padding); + } } - let mut packed_offset = 0; + let mut packed_offset: usize = 0; let is_lookahead_tokens = binding.source == ValueSource::PromptLookaheadToken; for (row, lane) in frame.step.lanes.iter().enumerate() { let slot = lane.request.slot as usize; @@ -509,26 +558,62 @@ impl Inputs { let live = frame.scheduler.request(lane.request)?; let lane_kind = frame.step.lane_kind(row); let destination = match binding.indexing { - InputIndexing::SubmissionRow | InputIndexing::ActiveRow => row * input.width, - InputIndexing::RequestRow => slot * input.width, - InputIndexing::PackedToken => packed_offset * input.width, + InputIndexing::SubmissionRow | InputIndexing::ActiveRow => { + row.checked_mul(input.width) + } + InputIndexing::RequestRow => slot.checked_mul(input.width), + InputIndexing::PackedToken => packed_offset.checked_mul(input.width), InputIndexing::Scalar => unreachable!(), - }; - packed_offset += if is_lookahead_tokens { + } + .ok_or("packed input offset overflow")?; + let advance = if is_lookahead_tokens { lookahead[row].1 } else { lane.tokens }; + packed_offset = packed_offset + .checked_add(advance) + .ok_or("packed token offset overflow")?; if binding.source == ValueSource::SamplingParameters { - self.staging.put( - &binding.buffer, - destination * 4, - admission - .sampling - .values() - .into_iter() - .flat_map(f32::to_le_bytes), - ); + let values = admission.sampling.values(); + write_floats(&mut self.staging, input, destination, &values)?; + continue; + } + if binding.source == ValueSource::CoreParameter { + let value = admission + .core_parameters + .get(&binding.parameter) + .copied() + .ok_or("core-parameter admission is incomplete")?; + let planned = live + .core_parameters() + .get(&binding.parameter) + .copied() + .ok_or("core-parameter admission plan is incomplete")?; + if value.to_bits() != planned.to_bits() { + return Err( + "packed core parameter differs from its prefix-history value".into(), + ); + } + if destination + .checked_add(1) + .is_none_or(|end| end > input.elements) + { + return Err("packed values exceed prepared input storage".into()); + } + if binding.indexing == InputIndexing::SubmissionRow { + *self + .core_parameters + .get_mut(destination) + .ok_or("packed values exceed core-parameter staging storage")? = value; + } else { + write_floats( + &mut self.staging, + input, + destination, + std::slice::from_ref(&value), + )?; + } continue; } if binding.source == ValueSource::GrammarMask @@ -823,10 +908,14 @@ impl Inputs { if values.len() != input.width { return Err("submission row has an invalid value count".into()); } - for (to, value) in self.integers[destination..destination + input.width] - .iter_mut() - .zip(values.iter()) - { + let end = destination + .checked_add(input.width) + .ok_or("submission-row input extent overflow")?; + let target = self + .integers + .get_mut(destination..end) + .ok_or("packed values exceed integer staging storage")?; + for (to, value) in target.iter_mut().zip(values.iter()) { *to = value .checked_add(binding.value_offset) .ok_or("input value overflow")?; @@ -835,16 +924,50 @@ impl Inputs { write_integers(&mut self.staging, input, destination, &values)?; } } - if binding.indexing == InputIndexing::SubmissionRow - && binding.source != ValueSource::SamplingParameters - { - write_raw(&mut self.staging, input, 0, self.integers.iter().copied())?; + if binding.indexing == InputIndexing::SubmissionRow { + if binding.source == ValueSource::CoreParameter { + write_floats(&mut self.staging, input, 0, &self.core_parameters)?; + } else if binding.source != ValueSource::SamplingParameters { + write_raw( + &mut self.staging, + input, + 0, + self.integers.len(), + self.integers.iter().copied(), + )?; + } } } Ok(()) } } +fn write_floats( + staging: &mut UploadBatch, + input: &BoundInput, + offset: usize, + values: &[f32], +) -> Result<()> { + if input.dtype != Dtype::Float32 { + return Err("floating-point source requires a float32 input buffer".into()); + } + if offset + .checked_add(values.len()) + .is_none_or(|end| end > input.elements) + { + return Err("packed values exceed prepared input storage".into()); + } + let byte_offset = offset + .checked_mul(input.dtype.size()) + .ok_or("packed input byte offset overflow")?; + staging.put( + &input.binding.buffer, + byte_offset, + values.iter().flat_map(|value| (*value).to_le_bytes()), + ); + Ok(()) +} + fn write_integers( staging: &mut UploadBatch, input: &BoundInput, @@ -863,6 +986,7 @@ fn write_integers( staging, input, offset, + values.len(), values.iter().map(|v| v + input.binding.value_offset), ) } @@ -871,15 +995,25 @@ fn write_raw( staging: &mut UploadBatch, input: &BoundInput, offset: usize, + count: usize, values: impl Iterator + Clone, ) -> Result<()> { + if offset + .checked_add(count) + .is_none_or(|end| end > input.elements) + { + return Err("packed values exceed prepared input storage".into()); + } + let byte_offset = offset + .checked_mul(input.dtype.size()) + .ok_or("packed input byte offset overflow")?; match input.dtype { - Dtype::Int64 => staging.i64(&input.binding.buffer, offset * 8, values), + Dtype::Int64 => staging.i64(&input.binding.buffer, byte_offset, values), Dtype::Int32 => { if values.clone().any(|value| i32::try_from(value).is_err()) { return Err("input value exceeds int32".into()); } - staging.i32(&input.binding.buffer, offset * 4, values.map(|v| v as i32)); + staging.i32(&input.binding.buffer, byte_offset, values.map(|v| v as i32)); } _ => return Err("integer source requires an integer input buffer".into()), } diff --git a/helios/src/model/testing.rs b/helios/src/model/testing.rs index d3f6da014..b82fc3cb7 100644 --- a/helios/src/model/testing.rs +++ b/helios/src/model/testing.rs @@ -26,6 +26,7 @@ pub fn binding( value_offset, padding, tensor: String::new(), + parameter: String::new(), } } @@ -237,6 +238,7 @@ pub fn metadata() -> PreparedContract { prefix_boundary: None, image_tokens: None, }, + core_parameters: vec![], } } @@ -275,7 +277,7 @@ pub fn manifest(config: &ModelConfig) -> ExecutionManifest { } }; let dtype = match b.source { - SamplingParameters => Dtype::Float32, + SamplingParameters | CoreParameter => Dtype::Float32, RequestSlot if b.buffer == "row_slot_ids" || b.buffer == "admission_slots" => { Dtype::Int32 } diff --git a/helios/src/model/tests.rs b/helios/src/model/tests.rs index 6cad8b778..5f11b8bd5 100644 --- a/helios/src/model/tests.rs +++ b/helios/src/model/tests.rs @@ -56,6 +56,459 @@ pub(super) fn config() -> ModelConfig { } } +fn bind_text_forward_core_parameters( + contract: &mut PreparedContract, + bindings: &[(&str, &str)], + indexing: InputIndexing, +) { + for graph in &mut contract.graphs { + if !matches!( + graph.kind, + GraphOperation::Prefill + | GraphOperation::TerminalPrefill + | GraphOperation::ScoredPrefill + | GraphOperation::Resume + | GraphOperation::Decode + | GraphOperation::Speculative + | GraphOperation::Mixed + ) { + continue; + } + for &(buffer, parameter) in bindings { + let mut binding = + testing::binding(buffer, ValueSource::CoreParameter, indexing, 0, 0); + binding.parameter = parameter.into(); + graph.inputs.push(binding); + } + } +} + +#[test] +fn generic_core_parameters_resolve_pack_and_enforce_text_forward_contracts() { + let mut config = config(); + config.contract.core_parameters = vec![ + CoreParameter { + name: "gain".into(), + default_value: 0., + range: Some(CoreParameterRange { min: 0., max: 1. }), + }, + CoreParameter { + name: "offset".into(), + default_value: 0.25, + range: None, + }, + ]; + bind_text_forward_core_parameters( + &mut config.contract, + &[("request_gain", "gain"), ("request_offset", "offset")], + InputIndexing::RequestRow, + ); + let manifest = manifest(&config); + assert_eq!( + manifest.buffer("admission_parameters").unwrap().shape, + [config.limits.request_capacity(), 6] + ); + let requested = std::collections::BTreeMap::from([("gain".into(), 3.)]); + let resolved = config.contract.resolve_core_parameters(&requested).unwrap(); + assert_eq!( + resolved, + std::collections::BTreeMap::from([("gain".into(), 1.), ("offset".into(), 0.25)]) + ); + let mut unknown = requested.clone(); + unknown.insert("unknown".into(), 1.); + assert!(config.contract.resolve_core_parameters(&unknown).is_err()); + + let mut scheduler = RequestScheduler::new( + config.identity, + config.limits, + scheduler_capabilities(&config), + ) + .unwrap(); + scheduler.measured_graph_durations(&manifest.graphs).unwrap(); + let spec = RequestSpec { + message_boundaries: vec![], + prompt: vec![7; 4], + conditioning: vec![], + max_new_tokens: 2, + grammar_constrained: false, + host_stops: false, + prompt_logprobs: false, + growable_output: false, + }; + // Unified validation rejects out-of-range and non-canonical -0.0 values in plan_admission_with_core_parameters. + let out_of_range = + std::collections::BTreeMap::from([("gain".into(), 2.), ("offset".into(), 0.25)]); + assert!( + scheduler + .plan_admission_with_core_parameters(&spec, &config.contract.core_parameters, &out_of_range) + .is_err() + ); + let neg_zero = + std::collections::BTreeMap::from([("gain".into(), -0.0f32), ("offset".into(), 0.25)]); + assert!( + scheduler + .plan_admission_with_core_parameters(&spec, &config.contract.core_parameters, &neg_zero) + .is_err() + ); + + let plan = scheduler + .plan_admission_with_core_parameters(&spec, &config.contract.core_parameters, &resolved) + .unwrap(); + let handle = scheduler.admit_planned(spec, plan, None).unwrap().handle; + let mut admissions: [Option; 4] = std::array::from_fn(|_| None); + admissions[handle.slot as usize] = Some(Admission { + handle, + sampling: SamplingParameters::default(), + core_parameters: resolved, + max_new_tokens: 2, + prompt: vec![7; 4], + data: PromptData { + positions: (0..4).map(|position| [position; 3]).collect(), + vision_token_indices: vec![-1; 4], + ..Default::default() + }, + grammar_mask: None, + ignore_eos: false, + prompt_logprobs: false, + }); + let mut inputs = Inputs::new(&config, &manifest).unwrap(); + let init = scheduler.plan().unwrap(); + assert_eq!(init.kind, GraphKind::Init); + scheduler.commit(&init, Fence(1)).unwrap(); + pack_inputs(&mut inputs, &config, &scheduler, &init, &admissions).unwrap(); + assert!( + !inputs + .uploads() + .iter() + .any(|upload| upload.buffer == "request_gain") + ); + let mut initialized = vec![CompletionRecord::default(); config.limits.request_capacity()]; + initialized[handle.slot as usize] = CompletionRecord { + generation: handle.generation as i64, + submission_sequence: 1, + status: 1, + token_id: -1, + ..Default::default() + }; + scheduler + .complete(Fence(1), &initialized, Default::default()) + .unwrap(); + + let prefill = scheduler.plan().unwrap(); + assert_eq!(prefill.kind, GraphKind::Prefill); + scheduler.commit(&prefill, Fence(2)).unwrap(); + pack_inputs(&mut inputs, &config, &scheduler, &prefill, &admissions).unwrap(); + let uploads = inputs.uploads(); + for (buffer, expected) in [("request_gain", 1.0f32), ("request_offset", 0.25f32)] { + let upload = uploads.iter().find(|upload| upload.buffer == buffer).unwrap(); + assert_eq!(upload.offset, 0); + assert_eq!(upload.bytes, expected.to_le_bytes()); + } + + config.contract.validate(&manifest).unwrap(); + let mut wrong_type = manifest.clone(); + wrong_type + .buffers + .iter_mut() + .find(|buffer| buffer.name == "request_gain") + .unwrap() + .dtype = crate::execution::Dtype::Int32; + assert!(config.contract.validate(&wrong_type).is_err()); + + let mut wrong_width = manifest.clone(); + wrong_width + .buffers + .iter_mut() + .find(|buffer| buffer.name == "request_gain") + .unwrap() + .shape + .push(2); + assert!(config.contract.validate(&wrong_width).is_err()); + + let mut no_row_dimension = manifest.clone(); + no_row_dimension + .buffers + .iter_mut() + .find(|buffer| buffer.name == "request_gain") + .unwrap() + .shape = vec![]; + assert!(config.contract.validate(&no_row_dimension).is_err()); + + let mut short_buffer = manifest.clone(); + short_buffer + .buffers + .iter_mut() + .find(|buffer| buffer.name == "request_gain") + .unwrap() + .shape[0] -= 1; + assert!(config.contract.validate(&short_buffer).is_err()); + + // Omitting a core-parameter binding from even one selected text forward graph is rejected. + let mut missing_on_decode = config.contract.clone(); + missing_on_decode + .graphs + .iter_mut() + .find(|graph| graph.kind == GraphOperation::Decode) + .unwrap() + .inputs + .retain(|input| input.parameter != "gain"); + let error = missing_on_decode + .validate(&manifest) + .unwrap_err() + .to_string(); + assert!(error.contains("every selected text forward graph"), "{error}"); + + // Binding a core parameter on a non-forward graph (Init, Restore, Snapshot, Vision) is rejected. + for forbidden in [ + GraphOperation::Init, + GraphOperation::Restore, + GraphOperation::Snapshot, + ] { + let mut on_maintenance = config.clone(); + let target = on_maintenance + .contract + .graphs + .iter_mut() + .find(|graph| graph.kind == forbidden) + .unwrap(); + let mut binding = testing::binding( + "request_gain", + ValueSource::CoreParameter, + InputIndexing::RequestRow, + 0, + 0, + ); + binding.parameter = "gain".into(); + target.inputs.push(binding); + let maintenance_manifest = self::manifest(&on_maintenance); + let error = on_maintenance + .contract + .validate(&maintenance_manifest) + .unwrap_err() + .to_string(); + assert!(error.contains("text forward graphs"), "{forbidden:?}: {error}"); + } + + // Binding a core parameter on a Vision graph is rejected at load time (never deferred to pack_vision). + let mut on_vision = config.clone(); + let mut vision_binding = testing::binding( + "request_gain", + ValueSource::CoreParameter, + InputIndexing::RequestRow, + 0, + 0, + ); + vision_binding.parameter = "gain".into(); + on_vision.contract.graphs.push(GraphContract { + graph: "vision-1-1".into(), + kind: GraphOperation::Vision, + inputs: vec![vision_binding], + state: vec![], + state_rows_per_request: 1, + draft_cursor: None, + embedding_tables: vec![], + pending_token: None, + tuned_bindings: vec![], + }); + let mut vision_manifest = manifest.clone(); + vision_manifest.graphs.push(crate::execution::GraphDescriptor { + name: "vision-1-1".into(), + kind: GraphKind::Vision, + batch_capacity: 1, + token_capacity: 1, + packed_token_capacity: 0, + prefill_capacity: 0, + draft_tokens: 0, + confidence_width: 0, + sampling_mode: crate::execution::SamplingMode::General, + handle: 0, + input_bindings: vec![crate::execution::InputBinding { + buffer_name: "request_gain".into(), + host_offset: 0, + nbytes: config.limits.request_capacity() * 4, + }], + tuned_bindings: vec![], + estimated_duration_ns: 1000, + }); + let error = on_vision + .contract + .validate(&vision_manifest) + .unwrap_err() + .to_string(); + assert!(error.contains("text forward graphs"), "{error}"); + + let mut duplicate = config.contract.clone(); + duplicate + .core_parameters + .push(duplicate.core_parameters[0].clone()); + assert!(duplicate.validate(&manifest).is_err()); + + let mut non_core_parameter = config.contract.clone(); + non_core_parameter.graphs.iter_mut().for_each(|graph| { + if let Some(binding) = graph.inputs.first_mut() { + binding.parameter = "undeclared".into(); + } + }); + assert!(non_core_parameter.validate(&manifest).is_err()); +} + +#[test] +fn core_parameters_pack_sparse_permuted_rows_and_preserve_prefix_values() { + let mut config = config(); + config.contract.core_parameters = vec![CoreParameter { + name: "gain".into(), + default_value: 0.25, + range: None, + }]; + bind_text_forward_core_parameters( + &mut config.contract, + &[("request_gain", "gain")], + InputIndexing::SubmissionRow, + ); + let manifest = manifest(&config); + let mut scheduler = RequestScheduler::new( + config.identity, + config.limits, + scheduler_capabilities(&config), + ) + .unwrap(); + scheduler.measured_graph_durations(&manifest.graphs).unwrap(); + let spec = RequestSpec { + message_boundaries: vec![], + prompt: vec![7; 4], + conditioning: vec![], + max_new_tokens: 2, + grammar_constrained: false, + host_stops: false, + prompt_logprobs: false, + growable_output: false, + }; + let requests = [0.125f32, 0.25, 0.5, 0.75] + .into_iter() + .map(|gain| { + let parameters = std::collections::BTreeMap::from([("gain".into(), gain)]); + let plan = scheduler + .plan_admission_with_core_parameters( + &spec, + &config.contract.core_parameters, + ¶meters, + ) + .unwrap(); + let handle = scheduler + .admit_planned(spec.clone(), plan, None) + .unwrap() + .handle; + assert_eq!(scheduler.request(handle).unwrap().core_parameters(), ¶meters); + (handle, parameters) + }) + .collect::>(); + for index in [0, 2] { + scheduler.cancel(requests[index].0).unwrap(); + } + + let mut admissions: [Option; 4] = std::array::from_fn(|_| None); + for index in [1, 3] { + let handle = requests[index].0; + admissions[handle.slot as usize] = Some(Admission { + handle, + sampling: SamplingParameters::default(), + core_parameters: requests[index].1.clone(), + max_new_tokens: 2, + prompt: vec![7; 4], + data: PromptData { + positions: (0..4).map(|position| [position; 3]).collect(), + vision_token_indices: vec![-1; 4], + ..Default::default() + }, + grammar_mask: None, + ignore_eos: false, + prompt_logprobs: false, + }); + } + let step = crate::scheduler::ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Decode, + batch_capacity: 4, + token_capacity: 1, + packed_token_capacity: 0, + mixed: None, + requires_feedback: true, + lanes: [3, 1] + .map(|index| crate::scheduler::ScheduledLane { + request: requests[index].0, + start_position: 0, + tokens: 1, + }) + .into(), + }; + + for indexing in [ + InputIndexing::SubmissionRow, + InputIndexing::ActiveRow, + InputIndexing::RequestRow, + ] { + let mut indexed_config = config.clone(); + for graph in &mut indexed_config.contract.graphs { + if let Some(binding) = graph + .inputs + .iter_mut() + .find(|binding| binding.buffer == "request_gain") + { + binding.indexing = indexing; + } + } + let mut inputs = Inputs::new(&indexed_config, &manifest).unwrap(); + admissions[3] + .as_mut() + .unwrap() + .core_parameters + .insert("gain".into(), 0.5); + assert!( + pack_inputs(&mut inputs, &indexed_config, &scheduler, &step, &admissions).is_err() + ); + admissions[3] + .as_mut() + .unwrap() + .core_parameters + .insert("gain".into(), 0.75); + pack_inputs(&mut inputs, &indexed_config, &scheduler, &step, &admissions).unwrap(); + + let uploads = inputs + .uploads() + .into_iter() + .filter(|upload| upload.buffer == "request_gain") + .collect::>(); + assert_eq!( + uploads.len(), + if indexing == InputIndexing::SubmissionRow { + 1 + } else { + 2 + } + ); + let mut actual = vec![0xa5; config.limits.request_capacity() * 4]; + for upload in uploads { + let end = upload.offset + upload.bytes.len(); + actual[upload.offset..end].copy_from_slice(upload.bytes); + } + let mut expected = vec![0xa5; actual.len()]; + let destinations = match indexing { + InputIndexing::SubmissionRow => { + expected.fill(0); + [0, 1] + } + InputIndexing::ActiveRow => [0, 1], + InputIndexing::RequestRow => [3, 1], + InputIndexing::Scalar | InputIndexing::PackedToken => unreachable!(), + }; + for (destination, value) in destinations.into_iter().zip([0.75f32, 0.25]) { + expected[destination * 4..(destination + 1) * 4] + .copy_from_slice(&value.to_le_bytes()); + } + assert_eq!(actual, expected, "{indexing:?}"); + } +} + #[test] fn admission_histogram_seed_and_partial_page_uploads_preserve_native_semantics() { let config = config(); @@ -88,6 +541,7 @@ fn admission_histogram_seed_and_partial_page_uploads_preserve_native_semantics() temperature: 1., ..Default::default() }, + core_parameters: Default::default(), max_new_tokens: 4, prompt: vec![7; 65], data: PromptData { @@ -232,6 +686,7 @@ fn large_prefill_uploads_preserve_token_position_and_image_indices_without_tail_ admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 4, data: PromptData { positions: prompt.iter().map(|&token| [token as i64; 3]).collect(), @@ -547,6 +1002,7 @@ fn packing_follows_value_bindings_after_buffers_and_model_are_renamed() { seed: u64::MAX, ..Default::default() }, + core_parameters: Default::default(), max_new_tokens: 4, prompt: vec![7; 65], data: PromptData { @@ -704,6 +1160,7 @@ fn copy_staging_uses_physical_slots_stochastic_defaults_and_bonus_mask() { admissions[2] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 16, prompt: vec![7; 65], data: PromptData { @@ -917,6 +1374,7 @@ fn mixed_native_uploads_pack_prompt_after_the_decode_extent_and_sample_only_elig admissions[h.slot as usize] = Some(Admission { handle: h, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 16, prompt, data: PromptData { @@ -1131,6 +1589,7 @@ fn state_transfer_and_resume_upload_fixture() { admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 2, prompt, data: PromptData { @@ -1349,6 +1808,7 @@ fn grammar_packing_fixture() -> ( admissions.push(Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 512, prompt: vec![7; 66], data: PromptData::default(), @@ -1587,6 +2047,7 @@ fn prefill_compacts_execution_feature_indices_and_preserves_admission_metadata() admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 1, prompt: vec![7; 4], data: PromptData { @@ -1688,6 +2149,7 @@ fn committed_generation_cursors_require_feedback_while_unused_prompt_positions_d max_new_tokens: 64, grammar_constrained: false, host_stops: false, prompt_logprobs: false, growable_output: false }).unwrap(); let mut admissions: [Option; 4] = std::array::from_fn(|_| None); admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), 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() @@ -1950,6 +2412,7 @@ fn prompt_lookahead_packing_distributes_budget_across_single_multi_and_mixed_lan admissions[h.slot as usize] = Some(Admission { handle: h, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 16, prompt, data: PromptData { diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 16454644b..8b104e571 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -43,6 +43,9 @@ pub use preparation::{ pub fn validate_sampling_defaults(value: &wire::DefaultSamplingParameters) -> crate::Result<()> { protobuf::sampling_defaults(value.clone()).map(|_| ()) } +pub fn validate_core_parameters(value: &wire::ModelContract) -> crate::Result<()> { + protobuf::validate_core_parameters(value) +} pub const WIRE_DESCRIPTOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/runtime_core_descriptor.bin")); mod publishers; diff --git a/helios/src/runtime_core/protobuf.rs b/helios/src/runtime_core/protobuf.rs index 99e36978e..e675938b3 100644 --- a/helios/src/runtime_core/protobuf.rs +++ b/helios/src/runtime_core/protobuf.rs @@ -51,13 +51,38 @@ pub(super) fn size(value: u64) -> Result { usize::try_from(value).map_err(|_| invalid("resource size exceeds host address space")) } +pub(super) fn validate_core_parameters(contract: &wire::ModelContract) -> Result<()> { + let mut parsed = Vec::with_capacity(contract.core_parameters.len()); + for parameter in &contract.core_parameters { + let default_value = required(parameter.default_value, "core parameter default_value")?; + let range = match ¶meter.range { + Some(range) => Some(crate::model::contract::CoreParameterRange { + min: required(range.min, "core parameter range min")?, + max: required(range.max, "core parameter range max")?, + }), + None => None, + }; + parsed.push(crate::model::contract::CoreParameter { + name: parameter.name.clone(), + default_value, + range, + }); + } + crate::model::contract::validate_core_parameter_declarations(&parsed) + .map_err(|error| invalid(error.to_string())) +} + pub(super) fn serving_contract( value: wire::ServingContract, _prepared_concurrency: u64, ) -> Result { - if value.model_contract.as_ref().is_none_or(|contract| !(1..=3).contains(&contract.version)) { + let Some(contract) = value.model_contract.as_ref() else { + return Err(invalid("unsupported prepared model contract version; re-export the model core")); + }; + if !(1..=3).contains(&contract.version) { return Err(invalid("unsupported prepared model contract version; re-export the model core")); } + validate_core_parameters(contract)?; let mut value = serde_json::to_value(value).map_err(|e| invalid(e.to_string()))?; value.as_object_mut().unwrap().retain(|_, v| !v.is_null()); Ok(value) @@ -879,6 +904,7 @@ mod tests { contract.inputs[0].indexing, crate::model::contract::InputIndexing::PackedToken ); + assert!(contract.inputs[0].parameter.is_empty()); let execution = wire::ExecutionGraph::decode(b"\x12\x0escored_prefill\x20\x01\x28\x40".as_slice()) .unwrap(); @@ -890,6 +916,103 @@ mod tests { assert_eq!(execution.packed_tokens(), 64); } + #[test] + fn core_parameter_declarations_and_bindings_round_trip_additively() { + let contract = wire::ModelContract { + version: 3, + core_parameters: vec![ + wire::CoreParameter { + name: "gain".into(), + default_value: Some(0.), + range: Some(wire::CoreParameterRange { + min: Some(0.), + max: Some(1.), + }), + }, + wire::CoreParameter { + name: "residual_gain".into(), + default_value: Some(0.25), + range: None, + }, + ], + graphs: vec![wire::GraphContract { + inputs: vec![wire::ValueBinding { + buffer: "request_gain".into(), + source: 43, + indexing: 3, + parameter: "gain".into(), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }; + let restored = wire::ModelContract::decode(contract.encode_to_vec().as_slice()).unwrap(); + assert_eq!(restored, contract); + validate_core_parameters(&restored).unwrap(); + let binding: crate::model::contract::ValueBinding = serde_json::from_value( + serde_json::to_value(&restored.graphs[0].inputs[0]).unwrap(), + ) + .unwrap(); + assert_eq!( + binding.source, + crate::model::contract::ValueSource::CoreParameter + ); + assert_eq!(binding.parameter, "gain"); + + let previous = wire::ModelContract::decode(b"\x08\x03".as_slice()).unwrap(); + assert_eq!(previous.version, 3); + assert!(previous.core_parameters.is_empty()); + validate_core_parameters(&previous).unwrap(); + + for invalid_contract in [ + wire::ModelContract { + version: 3, + core_parameters: vec![wire::CoreParameter { + name: "gain".into(), + default_value: None, + range: None, + }], + ..Default::default() + }, + wire::ModelContract { + version: 3, + core_parameters: vec![wire::CoreParameter { + name: "gain".into(), + default_value: Some(0.5), + range: Some(wire::CoreParameterRange { + min: Some(0.0), + max: None, + }), + }], + ..Default::default() + }, + wire::ModelContract { + version: 3, + core_parameters: vec![wire::CoreParameter { + name: "gain".into(), + default_value: Some(2.0), + range: Some(wire::CoreParameterRange { + min: Some(0.0), + max: Some(1.0), + }), + }], + ..Default::default() + }, + wire::ModelContract { + version: 3, + core_parameters: vec![wire::CoreParameter { + name: "gain".into(), + default_value: Some(f32::NAN), + range: None, + }], + ..Default::default() + }, + ] { + assert!(validate_core_parameters(&invalid_contract).is_err()); + } + } + #[test] fn serialized_terminal_prefill_preserves_operation_and_kind() { // GraphContract(graph="terminal", kind=14) diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 8fb63e20e..6527b4573 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -265,9 +265,14 @@ pub struct LiveRequest { /// Finishing to free its pages; the runtime readmits its history instead of completing it. preempted: bool, admission_order: u64, + core_parameters: crate::model::CoreParameters, } impl LiveRequest { + pub fn core_parameters(&self) -> &crate::model::CoreParameters { + &self.core_parameters + } + pub fn checkpoint_accounting(&self) -> CheckpointAccounting { self.checkpoints.clone() } @@ -596,6 +601,7 @@ struct Slot { pub struct AdmissionPlan { history: PrefixHistory, lookup: Lookup, + core_parameters: crate::model::CoreParameters, } impl AdmissionPlan { @@ -1518,6 +1524,17 @@ impl RequestScheduler { /// Validates the request, builds its prefix history, and looks up the GPU /// cache without reserving anything. pub fn plan_admission(&mut self, spec: &RequestSpec) -> Result { + self.plan_admission_with_core_parameters(spec, &[], &Default::default()) + } + + /// Validates the request and its resolved core parameters, builds its + /// salted prefix history, and looks up the GPU cache without reserving anything. + pub fn plan_admission_with_core_parameters( + &mut self, + spec: &RequestSpec, + parameters: &[crate::model::contract::CoreParameter], + core_parameters: &crate::model::CoreParameters, + ) -> Result { if spec.prompt.is_empty() || spec.message_boundaries.first() == Some(&0) || spec.message_boundaries.last().is_some_and(|n| *n > spec.prompt.len()) @@ -1528,14 +1545,25 @@ impl RequestScheduler { .len() .checked_add(spec.max_new_tokens as usize) .is_none_or(|count| count > self.limits.max_sequence_tokens) + || crate::model::contract::validate_resolved_core_parameters( + parameters, + core_parameters, + ) + .is_err() { return Err(crate::Error::admission( crate::AdmissionError::Invalid, - "request requires a nonempty prompt, positive output limit, and bounded total tokens", + "request requires a nonempty prompt, positive output limit, bounded total tokens, and resolved core parameters", )); } self.free_slot()?; - let mut history = PrefixHistory::new(self.identity); + let parameter_values = parameters.iter().map(|parameter| { + ( + parameter.name.as_str(), + core_parameters[parameter.name.as_str()], + ) + }); + let mut history = PrefixHistory::with_core_parameters(self.identity, parameter_values); history.append(&spec.prompt, &spec.conditioning)?; if spec.prompt_logprobs && self.scored_prefill_catalog.is_empty() { return Err(crate::Error::admission(crate::AdmissionError::Invalid, @@ -1544,7 +1572,11 @@ impl RequestScheduler { let lookup = if spec.prompt_logprobs { Lookup { checkpoint: None, consumed_tokens: 0, pages: Vec::new(), snapshot: None } } else { self.cache.lookup(&history)? }; - Ok(AdmissionPlan { history, lookup }) + Ok(AdmissionPlan { + history, + lookup, + core_parameters: core_parameters.clone(), + }) } /// Recheck GPU residency while retaining a queued request's validated history. @@ -1553,6 +1585,7 @@ impl RequestScheduler { Ok(AdmissionPlan { history: plan.history.clone(), lookup: self.cache.lookup(&plan.history)?, + core_parameters: plan.core_parameters.clone(), }) } @@ -1596,7 +1629,11 @@ impl RequestScheduler { inbound: Option, accounting: Option, ) -> Result { - let AdmissionPlan { history, lookup } = plan; + let AdmissionPlan { + history, + lookup, + core_parameters, + } = plan; // Lookups count once per admitted request, not per attempt of a waiting one. let (hit, reused) = (lookup.checkpoint.is_some(), lookup.consumed_tokens); let page_tokens = self.capabilities.page_tokens as u64; @@ -1787,6 +1824,7 @@ impl RequestScheduler { growable_output: spec.growable_output, preempted: false, admission_order: self.admissions, + core_parameters, }); self.admissions += 1; if let Some(inbound) = &inbound { diff --git a/helios/src/server/inference.rs b/helios/src/server/inference.rs index 0f3f3be45..39a986273 100644 --- a/helios/src/server/inference.rs +++ b/helios/src/server/inference.rs @@ -144,6 +144,7 @@ impl ThinkingBudget { #[derive(Clone, Debug, Default, PartialEq)] pub struct Options { pub sampling: Sampling, + pub core_parameters: crate::model::CoreParameters, pub logprobs: Option, pub prompt_logprobs: Option, pub effort: Option, diff --git a/helios/src/server/models.rs b/helios/src/server/models.rs index 579e5e1ab..e1ae9aafa 100644 --- a/helios/src/server/models.rs +++ b/helios/src/server/models.rs @@ -69,6 +69,24 @@ impl ModelCatalog { .ok() }) .flatten(); + let core_parameters: Vec<_> = model + .contract + .core_parameters + .iter() + .map(|parameter| { + let range = parameter.range.map(|range| { + crate::model::contract::CoreParameterRange { + min: crate::model::contract::canonical_core_parameter(range.min), + max: crate::model::contract::canonical_core_parameter(range.max), + } + }); + json!({ + "name": ¶meter.name, + "default": crate::model::contract::canonical_core_parameter(parameter.default_value), + "range": range, + }) + }) + .collect(); // Match vLLM's ModelCard / ModelPermission wire fields while // advertising only features supported by this server. let card = json!({ @@ -102,6 +120,7 @@ impl ModelCatalog { "sampling_defaults": model.sampling_defaults, "thinking_token_budget": thinking_token_budget, "sampling_ranges": model.sampling_ranges, + "core_parameters": core_parameters, "max_images_per_prompt": limits.map_or(0, |l| l.max_images), "max_image_tokens_per_prompt": limits.map_or(0, |l| l.max_image_tokens_per_prompt()), "image_feature_window_tokens": model.contract.vision.features_per_request, @@ -322,6 +341,37 @@ mod tests { text["flare"]["sampling_ranges"], json!(model.sampling_ranges) ); + assert_eq!(text["flare"]["core_parameters"], json!([])); + model.contract.core_parameters = vec![ + crate::model::contract::CoreParameter { + name: "gain".into(), + default_value: -0., + range: Some(crate::model::contract::CoreParameterRange { + min: -0., + max: 1., + }), + }, + crate::model::contract::CoreParameter { + name: "residual_gain".into(), + default_value: 0.25, + range: None, + }, + ]; + let parameter_card = ModelCatalog::new(&model, &[], None).card; + assert_eq!( + parameter_card["flare"]["core_parameters"], + json!([ + {"name":"gain","default":0.,"range":{"min":0.,"max":1.}}, + {"name":"residual_gain","default":0.25,"range":null}, + ]) + ); + assert_eq!( + parameter_card["flare"]["core_parameters"][0]["default"] + .as_f64() + .unwrap() + .to_bits(), + 0.0f64.to_bits() + ); assert_eq!(text["flare"]["input_modalities"], json!(["text"])); assert_eq!(text["flare"]["output_modalities"], json!(["text"])); assert_eq!(text["flare"]["max_images_per_prompt"], 0); diff --git a/helios/src/server/protocol/decode.rs b/helios/src/server/protocol/decode.rs index af2b6207a..3abb39d9d 100644 --- a/helios/src/server/protocol/decode.rs +++ b/helios/src/server/protocol/decode.rs @@ -46,6 +46,33 @@ fn reject(v: &Value, keys: &[&str]) -> Result<()> { } Ok(()) } +fn core_parameter_map(value: &Value) -> Result { + let object = value + .as_object() + .ok_or("core_parameters must be a JSON object")?; + let mut result = crate::model::CoreParameters::new(); + for (name, value) in object { + if name.is_empty() { + return Err("core_parameters names must be nonempty".into()); + } + let number = value + .as_number() + .ok_or_else(|| format!("core_parameters.{name} must be a finite FP32 number"))?; + let wide = number + .as_f64() + .filter(|value| value.is_finite() && value.abs() <= f32::MAX as f64) + .ok_or_else(|| format!("core_parameters.{name} must be a finite FP32 number"))?; + let narrowed = wide as f32; + if !narrowed.is_finite() || (wide != 0. && narrowed == 0.) { + return Err(format!("core_parameters.{name} is outside the finite FP32 range").into()); + } + result.insert( + name.clone(), + crate::model::contract::canonical_core_parameter(narrowed), + ); + } + Ok(result) +} fn strings(v: Option<&Value>) -> Result> { match v { None | Some(Value::Null) => Ok(vec![]), @@ -584,6 +611,9 @@ fn options(body: &Value, protocol: Protocol) -> Result { options.template.insert(key.into(), value.clone()); } } + if present(body, "core_parameters") { + options.core_parameters = core_parameter_map(&body["core_parameters"])?; + } if present(body, "chat_template_kwargs") { options.template.extend( body["chat_template_kwargs"] @@ -940,6 +970,50 @@ mod tests { assert!(normalize_tool_arguments(&mut message).is_err()); } } + #[test] + fn core_parameters_decode_consistently_across_all_generation_protocols() { + for (protocol, mut body) in [ + (Protocol::Chat, json!({"messages":[{"role":"user","content":"x"}]})), + (Protocol::Completions, json!({"prompt":"x"})), + (Protocol::Responses, json!({"input":"x"})), + (Protocol::Messages, json!({"max_tokens": 4, "messages":[{"role":"user","content":"x"}]})), + ] { + body.as_object_mut() + .unwrap() + .insert("core_parameters".into(), json!({"alpha": 0.5, "zero": -0.0})); + let decoded = decode(protocol, body, false).unwrap(); + assert_eq!(decoded.request.options.core_parameters["alpha"], 0.5); + assert_eq!( + decoded.request.options.core_parameters["zero"].to_bits(), + 0.0f32.to_bits() + ); + } + + let chat = |extra: Value| { + let mut body = json!({"messages":[{"role":"user","content":"x"}]}); + body.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + decode(Protocol::Chat, body, false) + }; + assert!(chat(json!({"core_parameters": null})).unwrap().request.options.core_parameters.is_empty()); + let boundary: Value = + serde_json::from_str("340282346638528859811704183484516925441").unwrap(); + let decoded = chat(json!({"core_parameters": {"alpha": boundary}})).unwrap(); + assert_eq!(decoded.request.options.core_parameters["alpha"], f32::MAX); + for invalid in [ + json!({"core_parameters": []}), + json!({"core_parameters": 1}), + json!({"core_parameters": {"": 0.5}}), + json!({"core_parameters": {"alpha": null}}), + json!({"core_parameters": {"alpha": true}}), + json!({"core_parameters": {"alpha": "0.5"}}), + json!({"core_parameters": {"alpha": 1e100}}), + json!({"core_parameters": {"alpha": 1e-100}}), + ] { + assert!(chat(invalid.clone()).is_err(), "{invalid}"); + } + } } #[cfg(test)] mod native_prompt_tests { diff --git a/helios/src/server/request.rs b/helios/src/server/request.rs index 294e0f0c5..ea00845af 100644 --- a/helios/src/server/request.rs +++ b/helios/src/server/request.rs @@ -330,6 +330,9 @@ pub(super) fn prepare_validated_inference( } let mut sampling = sampling_parameters(object, &config.sampling_defaults, &config.sampling_ranges)?; sampling.seed = sampling.seed.wrapping_add(index as u64); + let core_parameters = config + .contract + .resolve_core_parameters(&opts.core_parameters)?; let stop_sequences = opts.token_stops.clone(); super::stops::TokenStops::new(stop_sequences.clone(), config.contract.vocabulary)?; let stop_strings = opts.stops.clone(); @@ -403,6 +406,7 @@ pub(super) fn prepare_validated_inference( conditioned_inputs, conditioning, sampling, + core_parameters, max_new_tokens, reasoning_cut, stop_sequences, diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index b017f962d..d2c49bcc7 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -34,6 +34,7 @@ pub struct Prompt { pub conditioned_inputs: Vec, pub conditioning: Vec, pub sampling: SamplingParameters, + pub core_parameters: crate::model::CoreParameters, pub max_new_tokens: u32, pub reasoning_cut: Option, pub stop_sequences: Vec>, @@ -1235,7 +1236,12 @@ impl<'a> Worker<'a> { return; }; for incoming in requests { - begin_pool_lookup(&mut self.scheduler, store.as_mut(), incoming); + begin_pool_lookup( + &mut self.scheduler, + store.as_mut(), + &self.config.contract.core_parameters, + incoming, + ); } } @@ -1371,7 +1377,12 @@ impl<'a> Worker<'a> { if incoming.pool_plan.is_none() && let Some(store) = self.store.as_mut().filter(|store| store.pooled()) { - begin_pool_lookup(&mut self.scheduler, store.as_mut(), incoming); + begin_pool_lookup( + &mut self.scheduler, + store.as_mut(), + &self.config.contract.core_parameters, + incoming, + ); } incoming.poll_pool_lookup(); incoming.poll_restore_wait(now); @@ -1415,7 +1426,12 @@ impl<'a> Worker<'a> { continue; } if let Some(store) = self.store.as_mut().filter(|store| store.pooled()) { - begin_pool_lookup(&mut self.scheduler, store.as_mut(), &mut incoming); + begin_pool_lookup( + &mut self.scheduler, + store.as_mut(), + &self.config.contract.core_parameters, + &mut incoming, + ); } if incoming.awaits_pool(std::time::Instant::now()) { match parked { @@ -1439,6 +1455,8 @@ impl<'a> Worker<'a> { store.as_mut(), incoming.pool_lookup.as_ref(), spec, + &self.config.contract.core_parameters, + &incoming.prompt.core_parameters, incoming.pool_plan.as_ref(), checkpoint_accounting, self.prefill_rate, @@ -1452,7 +1470,13 @@ impl<'a> Worker<'a> { handle }) } else { - admit_with_checkpoint_accounting(&mut self.scheduler, spec, checkpoint_accounting) + admit_with_checkpoint_accounting( + &mut self.scheduler, + spec, + &self.config.contract.core_parameters, + &incoming.prompt.core_parameters, + checkpoint_accounting, + ) }; let handle = match admission { Ok(handle) => handle, @@ -2714,6 +2738,7 @@ fn serve_export( fn begin_pool_lookup( scheduler: &mut RequestScheduler, store: &mut dyn flare_selene::HostStore, + core_parameter_defs: &[crate::model::contract::CoreParameter], incoming: &mut Incoming, ) { if !incoming.host_lookup || incoming.prompt_scored < incoming.prompt_score_end { @@ -2727,7 +2752,11 @@ fn begin_pool_lookup( } let plan = match incoming.pool_plan.as_ref() { Some(plan) => scheduler.refresh_admission_plan(plan), - None => scheduler.plan_admission(&incoming.spec()), + None => scheduler.plan_admission_with_core_parameters( + &incoming.spec(), + core_parameter_defs, + &incoming.prompt.core_parameters, + ), }; let Ok(plan) = plan else { return; @@ -2745,9 +2774,15 @@ fn begin_pool_lookup( fn admit_with_checkpoint_accounting( scheduler: &mut RequestScheduler, spec: RequestSpec, + core_parameter_defs: &[crate::model::contract::CoreParameter], + core_parameters: &crate::model::CoreParameters, accounting: Option, ) -> Result { - let plan = scheduler.plan_admission(&spec)?; + let plan = scheduler.plan_admission_with_core_parameters( + &spec, + core_parameter_defs, + core_parameters, + )?; Ok(scheduler.admit_planned_with_checkpoint_accounting(spec, plan, None, accounting)?.handle) } @@ -2758,6 +2793,8 @@ fn admit_with_host_store( store: &mut dyn flare_selene::HostStore, pool_lookup: Option<&flare_selene::pool::LookupTicket>, spec: RequestSpec, + core_parameter_defs: &[crate::model::contract::CoreParameter], + core_parameters: &crate::model::CoreParameters, queued_plan: Option<&crate::scheduler::AdmissionPlan>, accounting: Option, prefill_rate: f64, @@ -2766,7 +2803,11 @@ fn admit_with_host_store( ) -> Result<(RequestHandle, Option)> { let plan = match queued_plan { Some(plan) => scheduler.refresh_admission_plan(plan)?, - None => scheduler.plan_admission(&spec)?, + None => scheduler.plan_admission_with_core_parameters( + &spec, + core_parameter_defs, + core_parameters, + )?, }; let reused = (plan.resident_tokens() != 0) .then(|| plan.history().key_at(plan.resident_tokens())) @@ -2814,7 +2855,13 @@ fn admit_with_host_store( return Err(Error::Admission(AdmissionError::Capacity(failure))); } restore_wait.retry_at = None; - let handle = admit_with_checkpoint_accounting(scheduler, spec, accounting.clone())?; + let handle = admit_with_checkpoint_accounting( + scheduler, + spec, + core_parameter_defs, + core_parameters, + accounting.clone(), + )?; scheduler.record_host_lookup(); return Ok((handle, Some(LookupOutcome::CapacityRejected))); } @@ -2830,8 +2877,14 @@ fn admit_with_host_store( // No event follows a rejected fetch; this request is the ticket's only // waiter, so retire it and admit the request again without the store. scheduler.finish_inbound(key, false)?; - return admit_with_checkpoint_accounting(scheduler, spec, Some(admitted_accounting)) - .map(|handle| (handle, Some(LookupOutcome::EnqueueRejected))); + return admit_with_checkpoint_accounting( + scheduler, + spec, + core_parameter_defs, + core_parameters, + Some(admitted_accounting), + ) + .map(|handle| (handle, Some(LookupOutcome::EnqueueRejected))); } Ok((admitted.handle, Some(LookupOutcome::Admitted))) })(); @@ -2974,6 +3027,7 @@ mod tests { top_k: 1, ..Default::default() }, + core_parameters: Default::default(), max_new_tokens: 16, prompt: vec![7], data: PromptData { @@ -3229,6 +3283,7 @@ mod tests { conditioned_inputs: vec![], conditioning: vec![], sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 10, reasoning_cut: None, stop_sequences: vec![], @@ -3563,6 +3618,7 @@ mod tests { admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: 10, prompt: vec![0], data: PromptData { diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index e8e539713..35735d258 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -212,6 +212,7 @@ impl Fixture { conditioned_inputs: vec![], conditioning: vec![], sampling: SamplingParameters::default(), + core_parameters: Default::default(), max_new_tokens: limit, reasoning_cut: None, stop_sequences: vec![], @@ -3268,6 +3269,7 @@ fn a_first_pool_lookup_starts_while_blocked_and_retries_when_selected() { begin_pool_lookup( &mut worker.scheduler, worker.store.as_mut().unwrap().as_mut(), + &worker.config.contract.core_parameters, &mut incoming, ); incoming.pool_lookup_started = @@ -6623,3 +6625,225 @@ fn local_copyout_rechecks_headroom_after_each_queued_pin() { assert_eq!(fake_store(&mut worker).stored.len(), 2); assert_eq!(pins(&worker, second), 1); } + +fn enable_core_parameter(config: &mut ModelConfig) { + config.contract.core_parameters = vec![crate::model::contract::CoreParameter { + name: "gain".into(), + default_value: 0., + range: Some(crate::model::contract::CoreParameterRange { + min: 0., + max: 1., + }), + }]; + for graph in &mut config.contract.graphs { + if !matches!( + graph.kind, + crate::model::contract::GraphOperation::Prefill + | crate::model::contract::GraphOperation::TerminalPrefill + | crate::model::contract::GraphOperation::ScoredPrefill + | crate::model::contract::GraphOperation::Resume + | crate::model::contract::GraphOperation::Decode + | crate::model::contract::GraphOperation::Speculative + | crate::model::contract::GraphOperation::Mixed + ) { + continue; + } + let mut binding = crate::model::testing::binding( + "request_gain", + crate::model::contract::ValueSource::CoreParameter, + crate::model::contract::InputIndexing::RequestRow, + 0, + 0, + ); + binding.parameter = "gain".into(); + graph.inputs.push(binding); + } +} + +#[test] +fn core_parameter_pool_lookup_retry_preserves_declared_history_and_value() { + let mut fixture = Fixture::new(); + fixture.config.contract = crate::model::testing::metadata(); + enable_core_parameter(&mut fixture.config); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, _generation) = fixture.incoming(vec![7; 70], 2); + incoming.prompt.core_parameters = + std::collections::BTreeMap::from([("gain".into(), 0.75)]); + + let mut parameter_history = crate::cache::PrefixHistory::with_core_parameters( + fixture.config.identity, + [("gain", 0.75)], + ); + parameter_history.append(&incoming.prompt.tokens, &[]).unwrap(); + let mut default_history = crate::cache::PrefixHistory::new(fixture.config.identity); + default_history.append(&incoming.prompt.tokens, &[]).unwrap(); + assert_ne!(parameter_history.key_at(64), default_history.key_at(64)); + + let mut worker = fixture.worker(receiver); + let mut store = FakeStore::new(Some(host_hit(¶meter_history, 64))); + store.pooled = true; + store.refused_lookups = 1; + worker.attach_store(Some(Box::new(store))); + + sender.send(vec![incoming]).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + let live = worker.scheduler.request(handle).unwrap(); + assert_eq!( + (live.phase, live.reused_prompt_tokens()), + (RequestPhase::Inbound, 64) + ); + assert_eq!(live.core_parameters()["gain"], 0.75); + let store = fake_store(&mut worker); + assert_eq!(store.begun, vec![70, 70]); + assert_eq!(store.tickets_seen, vec![true]); + assert_eq!(store.fetched.len(), 1); +} + +#[test] +fn core_parameter_preemption_preserves_prefix_identity_and_packed_value_on_forward_step() { + let mut fixture = Fixture::new(); + fixture.config.contract = crate::model::testing::metadata(); + enable_core_parameter(&mut fixture.config); + fixture.config.prepared_sequence_tokens = 4096; + fixture.config.limits.max_sequence_tokens = 4096; + fixture.config.limits.pages = 6; + fixture.config.limits.max_active = 2; + let page_tokens = crate::model::scheduler_capabilities(&fixture.config).page_tokens; + let budget = (page_tokens * 4) as u32; + let data = |count: usize| PromptData { + positions: (0..count).map(|position| [position as i64; 3]).collect(), + vision_token_indices: vec![-1; count], + ..Default::default() + }; + let (sender, receiver) = mpsc::channel(); + let (mut first, mut first_generation) = fixture.incoming_for(vec![3; 60], budget, data(60)); + let (mut second, mut second_generation) = fixture.incoming_for(vec![5; 60], budget, data(60)); + let parameters = std::collections::BTreeMap::from([("gain".into(), 0.75)]); + first.prompt.core_parameters = parameters.clone(); + second.prompt.core_parameters = parameters.clone(); + sender.send(vec![first, second]).unwrap(); + let mut worker = fixture.worker_for(receiver); + let manifest = crate::model::testing::manifest(&fixture.config); + worker.inputs = Some(crate::model::Inputs::new(&fixture.config, &manifest).unwrap()); + let mut graphs = manifest.graphs; + for graph in &mut graphs { + graph.estimated_duration_ns = if graph.kind == GraphKind::Snapshot { + 10 + } else { + 1000 + }; + } + worker.scheduler.measured_graph_durations(&graphs).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + + let mut sequence = 0; + while worker.parked.is_empty() { + sequence += 1; + assert!(sequence < (page_tokens * 8) as u64); + let step = worker.plan(0).unwrap().0.unwrap(); + worker.reserve_and_pack(&step, Fence(sequence)).unwrap(); + let sample = match step.kind { + GraphKind::Decode | GraphKind::Resume => Some(1), + GraphKind::Prefill => { + let lane = &step.lanes[0]; + let live = worker.scheduler.request(lane.request).unwrap(); + (lane.start_position as usize + lane.tokens == live.prompt_tokens).then_some(1) + } + _ => None, + }; + let mut frame = completion(&worker, &step, sequence, sample); + frame.timing.gpu_ns[0] = Some(if step.kind == GraphKind::Snapshot { + 10 + } else { + 1000 + }); + worker.complete(step.kind, frame).unwrap(); + worker.publish().unwrap(); + while first_generation.events.try_recv().is_ok() {} + while second_generation.events.try_recv().is_ok() {} + } + let (parked_incoming, _) = worker.parked.front().unwrap(); + assert_eq!(parked_incoming.prompt.core_parameters, parameters); + let parked_tokens = parked_incoming.prompt.tokens.clone(); + + let request = RequestSpec { + prompt: parked_tokens, + message_boundaries: vec![], + conditioning: vec![], + max_new_tokens: 1, + grammar_constrained: false, + host_stops: false, + prompt_logprobs: false, + growable_output: true, + }; + let running = worker + .active + .iter() + .flatten() + .map(|active| active.request) + .collect::>(); + worker.retire(&running).unwrap(); + assert_eq!( + worker + .scheduler + .plan_admission(&request) + .unwrap() + .resident_tokens(), + 0 + ); + assert!( + worker + .scheduler + .plan_admission_with_core_parameters( + &request, + &fixture.config.contract.core_parameters, + ¶meters, + ) + .unwrap() + .resident_tokens() + > 0 + ); + + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert!(worker.parked.is_empty()); + let active = worker.active.iter().flatten().next().unwrap(); + let readmitted = active.request; + assert!(worker.scheduler.request(readmitted).unwrap().reused_prompt_tokens() > 0); + sequence += 1; + let restore = worker.plan(0).unwrap().0.unwrap(); + assert_eq!(restore.kind, GraphKind::Restore); + worker.reserve_and_pack(&restore, Fence(sequence)).unwrap(); + assert!( + !worker + .inputs + .as_ref() + .unwrap() + .uploads() + .iter() + .any(|upload| upload.buffer == "request_gain") + ); + let mut frame = completion(&worker, &restore, sequence, None); + frame.timing.gpu_ns[0] = Some(1000); + worker.complete(restore.kind, frame).unwrap(); + worker.publish().unwrap(); + + sequence += 1; + let forward = worker.plan(0).unwrap().0.unwrap(); + assert!(matches!( + forward.kind, + GraphKind::Resume | GraphKind::Prefill | GraphKind::Decode + )); + worker.reserve_and_pack(&forward, Fence(sequence)).unwrap(); + let upload = worker + .inputs + .as_ref() + .unwrap() + .uploads() + .into_iter() + .find(|upload| { + upload.buffer == "request_gain" && upload.offset == readmitted.slot as usize * 4 + }) + .unwrap(); + assert_eq!(upload.bytes, 0.75f32.to_le_bytes()); +} diff --git a/helios/src/server/runtime/prompt_tests.rs b/helios/src/server/runtime/prompt_tests.rs index ae87bb16f..e427681bc 100644 --- a/helios/src/server/runtime/prompt_tests.rs +++ b/helios/src/server/runtime/prompt_tests.rs @@ -50,7 +50,7 @@ fn prompt_prefill_gpu_and_native_costs() { vision_token_indices: vec![-1; length], spans: vec![] }, conditioned_inputs: vec![], conditioning: vec![], sampling: crate::model::SamplingParameters { top_k: 1, ..Default::default() - }, max_new_tokens: budget, reasoning_cut: None, stop_sequences: vec![], stop_strings: vec![], + }, core_parameters: Default::default(), max_new_tokens: budget, reasoning_cut: None, stop_sequences: vec![], stop_strings: vec![], grammar: None, ignore_eos: false, logprobs: false, logprob_token_ids: vec![], prompt_logprobs: scored, }; diff --git a/ignition/direct/packing.py b/ignition/direct/packing.py index 4477d2c58..3503d6239 100644 --- a/ignition/direct/packing.py +++ b/ignition/direct/packing.py @@ -81,6 +81,7 @@ def put(offset, values): elif source in (p.CONSUMED_TOKENS, p.SNAPSHOT_CONSUMED_TOKENS): values = [request.consumed] elif source == p.SAMPLING_SEED: values = [request.sampling.seed if request.sampling.seed < 1 << 63 else request.sampling.seed - (1 << 64)] elif source == p.SAMPLING_PARAMETERS: values = request.sampling.values() + elif source == p.CORE_PARAMETER: values = [request.core_parameters[binding["parameter"]]] elif source == p.SAMPLING_TOP_K: values = [request.sampling.top_k] elif source == p.MAX_NEW_TOKENS: values = [request.max_new_tokens] elif source == p.EOS_TOKEN_IDS: values = list(layout.eos) + [-1] * (width - len(layout.eos)) diff --git a/ignition/direct/scheduler.py b/ignition/direct/scheduler.py index baa5a6e11..5211fabbe 100644 --- a/ignition/direct/scheduler.py +++ b/ignition/direct/scheduler.py @@ -40,11 +40,45 @@ import numpy as np from ignition.components.capacity import completion_token_capacity +from ignition.preparation import runtime_core_pb2 as wire from .policy import Accounting, Policy INACTIVE, RUNNING, FINISHED, ERROR = 0, 1, 2, 3 _MAINTENANCE = ("init", "restore", "snapshot") +_TEXT_FORWARD_KINDS = ("prefill", "terminal_prefill", "scored_prefill", "resume", "decode", "speculative", "mixed") +_FP32_MAX = float(np.finfo(np.float32).max) + + +def _wire_fp32(value): + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError + try: + wide = float(value) + except (OverflowError, TypeError, ValueError) as error: + raise ValueError from error + if not math.isfinite(wide) or abs(wide) > _FP32_MAX: + raise ValueError + narrowed = float(np.float32(wide)) + if not math.isfinite(narrowed) or (wide != 0.0 and narrowed == 0.0): + raise ValueError + return 0.0 if narrowed == 0.0 else narrowed + + +def _row_contiguous(tensor): + """Whether a buffer's rows are densely packed; None when the buffer does not report its layout.""" + flags = getattr(tensor, "flags", None) + if hasattr(flags, "c_contiguous"): + return bool(flags.c_contiguous) + contiguous = getattr(tensor, "is_contiguous", None) + return bool(contiguous()) if callable(contiguous) else None + + +def _core_parameter_rows(shape): + """Rows in a width-one buffer shape, or -1 without a row dimension or with a wider trailing one.""" + if len(shape) < 1 or any(extent != 1 for extent in shape[1:]): + return -1 + return shape[0] class AdmissionError(ValueError): @@ -80,6 +114,9 @@ class Layout: record_fields: int = 24 confidence_widths: dict = field(default_factory=dict) completion_cursors: dict = field(default_factory=dict) + # Buffer name to whether its rows are densely packed (True, False, or None when unreported). + buffer_contiguity: dict = field(default_factory=dict, kw_only=True) + core_parameters: tuple[dict, ...] = field(default=(), kw_only=True) def __post_init__(self): if not 1 <= self.max_active <= self.capacity or self.pages <= 0 or self.page_tokens <= 0: @@ -91,6 +128,61 @@ def __post_init__(self): or any(key[0] == "speculative" and key[2] > self.completion_token_capacity for key in self.graphs)): raise ValueError("verification width exceeds completion token capacity") object.__setattr__(self, "graphs", MappingProxyType(dict(self.graphs))) + parameters = tuple(dict(parameter) for parameter in self.core_parameters) + names = [parameter.get("name") for parameter in parameters] + if any(not isinstance(name, str) or not name for name in names) or len(set(names)) != len(names): + raise ValueError("direct execution requires distinct named core parameters") + for parameter in parameters: + try: + default = _wire_fp32(parameter.get("default_value")) + except ValueError: + raise ValueError("core parameter defaults must be finite FP32 values") from None + range_ = parameter.get("range") + if range_ is None: + normalized_range = None + elif not isinstance(range_, dict) or set(range_) != {"min", "max"}: + raise ValueError("core parameter ranges must be finite and contain their default") + else: + try: + minimum, maximum = _wire_fp32(range_["min"]), _wire_fp32(range_["max"]) + except ValueError: + raise ValueError("core parameter ranges must be finite and contain their default") from None + if minimum > maximum or not minimum <= default <= maximum: + raise ValueError("core parameter ranges must be finite and contain their default") + normalized_range = {"min": minimum, "max": maximum} + parameter["default_value"] = default + parameter["range"] = normalized_range + graph_kinds = {name: key[0] for key, name in self.graphs.items()} + name_set = set(names) + saw_text_forward = False + for graph_name, graph_bindings in self.bindings.items(): + kind = graph_kinds.get(graph_name) + text_forward = kind in _TEXT_FORWARD_KINDS + if text_forward: + saw_text_forward = True + bound = set() + for binding in graph_bindings: + if binding["source"] != wire.CORE_PARAMETER: + if binding.get("parameter", ""): + raise ValueError("only core-parameter bindings may name a parameter") + continue + if not text_forward: + raise ValueError("core-parameter bindings belong only to text forward graphs") + if (binding.get("parameter") not in name_set + or binding["indexing"] not in (wire.SUBMISSION_ROW, wire.REQUEST_ROW, wire.ACTIVE_ROW) + or binding.get("value_offset", 0) != 0 or binding.get("padding", 0) != 0 + or binding.get("tensor", "") + or binding["buffer"] not in self.buffer_specs + or self.buffer_specs[binding["buffer"]][0] != np.dtype("float32") + or _core_parameter_rows(self.buffer_specs[binding["buffer"]][1]) < self.capacity + or self.buffer_contiguity.get(binding["buffer"]) is not True): + raise ValueError("direct core-parameter bindings require one named FP32 value per request row") + bound.add(binding["parameter"]) + if text_forward and bound != name_set: + raise ValueError("every selected text forward graph must bind every declared core parameter") + if name_set and not saw_text_forward: + raise ValueError("declared core parameters require at least one selected text forward graph") + object.__setattr__(self, "core_parameters", parameters) @classmethod def of(cls, model): @@ -118,6 +210,11 @@ def of(cls, model): bindings={g["graph"]: g["inputs"] for g in config["model_contract"]["graphs"] if g["graph"] in graphs.values()}, buffer_specs={name: (np.dtype(str(tensor.dtype).removeprefix("torch.")), tuple(tensor.shape)) for name, tensor in buffers.items() if name in {b["buffer"] for g in config["model_contract"]["graphs"] if g["graph"] in graphs.values() for b in g["inputs"]}}, + buffer_contiguity={binding["buffer"]: _row_contiguous(buffers[binding["buffer"]]) + for g in config["model_contract"]["graphs"] if g["graph"] in graphs.values() + for binding in g["inputs"] + if binding["source"] == wire.CORE_PARAMETER and binding["buffer"] in buffers}, + core_parameters=tuple(config["model_contract"].get("core_parameters", ())), page_views={v["buffer"]: v["page_offset"] for v in config["model_contract"]["cache"]["page_tables"]}, state_rows_per_request=max(g["state_rows_per_request"] for g in config["model_contract"]["graphs"] if g["graph"] in graphs.values()), draft_pages=max((v["page_offset"] for v in config["model_contract"]["cache"]["page_tables"]), default=0), @@ -127,6 +224,36 @@ def of(cls, model): completion_cursors={g["graph"]: None if g["draft_cursor"] is None else g["draft_cursor"]["lag_tokens"] for g in config["model_contract"]["graphs"] if "draft_cursor" in g and g["graph"] in graphs.values()}) + def resolve_core_parameters(self, requested): + if not isinstance(requested, (dict, MappingProxyType)): + raise AdmissionError("core_parameters must be a JSON object") + names = {parameter["name"] for parameter in self.core_parameters} + unknown = set(requested) - names + if unknown: + raise AdmissionError( + "core_parameters contains unknown parameters: " + ", ".join(sorted(unknown))) + resolved = {} + for parameter in self.core_parameters: + name = parameter["name"] + if name in requested: + try: + narrowed = _wire_fp32(requested[name]) + except ValueError as exc: + raise AdmissionError(f"core_parameters.{name} must be a finite FP32 number") from exc + else: + narrowed = parameter["default_value"] + range_ = parameter.get("range") + if range_ is not None: + narrowed = min(max(narrowed, range_["min"]), range_["max"]) + resolved[name] = 0.0 if narrowed == 0.0 else narrowed + return resolved + + def core_parameter_identity(self, core_parameters): + return tuple( + (parameter["name"], int(np.float32(core_parameters[parameter["name"]]).view(np.uint32))) + for parameter in self.core_parameters + ) + @property def completion_token_capacity(self): return self.record_fields - 16 @@ -273,23 +400,38 @@ def expectations(self, maximum): @dataclass class Checkpoint: - """An immutable snapshot row holding the state after consuming exactly `key`, and its complete pages.""" + """An immutable snapshot row holding exact prompt and core-parameter identity.""" - key: tuple + tokens: tuple snapshot: int pages: tuple[int, ...] pins: int = 0 used: int = 0 + core_parameter_identity: tuple = () @property def consumed(self): - return len(self.key) + return len(self.tokens) + + # Without declared core parameters the key is the tokens alone; with them it + # is (core-parameter identity, tokens). The two shapes never compare equal. + @property + def cache_key(self): + return ( + self.tokens + if not self.core_parameter_identity + else (self.core_parameter_identity, self.tokens) + ) class Request: - def __init__(self, ident, prompt, max_new_tokens, sampling, *, ignore_eos=False): + def __init__(self, ident, prompt, max_new_tokens, sampling, *, ignore_eos=False, + core_parameters=None): self.ident, self.prompt = ident, list(prompt) self.max_new_tokens, self.sampling, self.ignore_eos = max_new_tokens, sampling, ignore_eos + if core_parameters is not None and not isinstance(core_parameters, dict): + raise AdmissionError("core_parameters must be a JSON object") + self._core_parameters = {} if core_parameters is None else core_parameters.copy() self.slot = self.prefix = self.capture = self.error = self.finish_reason = None self.generation = self.consumed = self.reused = self.shared = self.rounds = 0 self.pages, self.generated = [], [] @@ -300,6 +442,10 @@ def __init__(self, ident, prompt, max_new_tokens, sampling, *, ignore_eos=False) # Sequence of the last step that carried the request; Helios's `last_use` fence. self.last_use = 0 + @property + def core_parameters(self): + return self._core_parameters + @property def pending_token(self): return (self.prompt + self.generated)[self.consumed] @@ -395,6 +541,7 @@ def __init__(self, layout, *, prefix_cache=True): def validate(self, request): prompt, layout = request.prompt, self.layout + request._core_parameters = MappingProxyType(layout.resolve_core_parameters(request.core_parameters)) if not prompt or any(type(t) is not int or not 0 <= t < layout.vocabulary for t in prompt): raise AdmissionError("the prompt must be a nonempty list of vocabulary token IDs") if type(request.max_new_tokens) is not int or not 1 <= request.max_new_tokens < 1 << 31: @@ -446,7 +593,7 @@ def _evict(self, pages=0, snapshots=0): if not candidates: return False victim = min(candidates, key=lambda c: c.used) - del self.cache[victim.key] + del self.cache[victim.cache_key] self.page_pool.release(victim.pages) heapq.heappush(self.free_snapshots, victim.snapshot) self.stats["checkpoint_evictions"] += 1 @@ -458,7 +605,7 @@ def _admit(self): slot = next((index for index, occupant in enumerate(self.slots) if occupant is None), None) if slot is None: return - hit = self.cache.get(tuple(request.prompt)) if self.prefix_cache else None + hit = self.cache.get(self._cache_key(request)) if self.prefix_cache else None shared = hit.pages if hit is not None else () needed = self._pages_needed(request, len(shared)) if hit is not None: @@ -731,12 +878,24 @@ def _validate_packed_completion(self, step, records, confidence): if physical > step.packed_tokens: raise CompletionError("packed completion exceeds its physical row capacity") + def _cache_key(self, request, tokens=None): + tokens = tuple(request.prompt if tokens is None else tokens) + if not self.layout.core_parameters: + return tokens + return self.layout.core_parameter_identity(request.core_parameters), tokens + def _capture(self, request): """Reserve a snapshot row for the request's prompt endpoint unless that prompt is cached or in capture.""" if not self.prefix_cache: return False - key = tuple(request.prompt) - if key in self.cache or any(r.capture is not None and r.prompt == request.prompt for r in self.active): + key = self._cache_key(request) + parameter_identity = key[0] if self.layout.core_parameters else None + if key in self.cache or any( + r.capture is not None + and r.prompt == request.prompt + and (parameter_identity is None + or self.layout.core_parameter_identity(r.core_parameters) == parameter_identity) + for r in self.active): return False if not self.free_snapshots and not self._evict(snapshots=1): return False @@ -748,7 +907,15 @@ def _publish(self, request): pages = tuple(request.pages[:request.consumed // self.layout.page_tokens]) self.page_pool.retain(pages) self.clock += 1 - key = tuple(request.prompt[:request.consumed]) - self.cache[key] = Checkpoint(key, request.capture, pages, used=self.clock) + tokens = tuple(request.prompt[:request.consumed]) + parameter_identity = self.layout.core_parameter_identity(request.core_parameters) + checkpoint = Checkpoint( + tokens, + request.capture, + pages, + used=self.clock, + core_parameter_identity=parameter_identity, + ) + self.cache[checkpoint.cache_key] = checkpoint request.capture = None self.stats["checkpoints"] += 1 diff --git a/ignition/direct/server.py b/ignition/direct/server.py index ff6ec6f91..189aef3dd 100644 --- a/ignition/direct/server.py +++ b/ignition/direct/server.py @@ -108,6 +108,16 @@ def integer(name, default): top_k=integer("top_k", int(defaults.get("top_k", -1)))) +def _core_parameters(body, layout): + """Resolve the declared core parameters a request body names without mutating body.""" + raw = body.get("core_parameters") + if raw is None: + return layout.resolve_core_parameters({}) + if not isinstance(raw, dict): + raise AdmissionError("core_parameters must be a JSON object") + return layout.resolve_core_parameters(raw) + + class DirectServer: """Own the scheduler, the rank-zero step runner and the HTTP listener for one prepared model.""" @@ -122,6 +132,16 @@ def __init__(self, model, peers, *, bind, eager, served_names, verbose, graph_ti self.frontend = _Frontend(model.server_config) self.defaults = model.server_config.get("sampling_defaults", {}) self.served_names = tuple(served_names) + core_parameters = [ + {"name": parameter["name"], "default": parameter["default_value"], + "range": parameter.get("range")} + for parameter in self.layout.core_parameters + ] + self.model_cards = [ + {"id": name, "object": "model", "owned_by": "flare", + "flare": {"core_parameters": core_parameters}} + for name in self.served_names + ] self.inbox = queue.Queue() self.identities = iter(range(1, 1 << 62)) self.lock = threading.Lock() @@ -159,8 +179,7 @@ def do_GET(self): if self.path == "/health": self._send(503 if server.failure else 200, {"status": "failed" if server.failure else "ok"}) elif self.path == "/v1/models": - self._send(200, {"object": "list", "data": [ - {"id": name, "object": "model", "owned_by": "flare"} for name in server.served_names]}) + self._send(200, {"object": "list", "data": server.model_cards}) elif self.path == "/metrics": self._send(200, server.metrics().encode(), "text/plain; version=0.0.4") else: @@ -186,14 +205,17 @@ def chat(self, raw): raise AdmissionError("direct diagnostic serving answers non-streaming requests only") if body.get("n", 1) != 1: raise AdmissionError("direct diagnostic serving returns one choice") + core_parameters = _core_parameters(body, self.layout) prompt, rendered = self.frontend.render(body) limit = body.get("max_completion_tokens", body.get("max_tokens")) if limit is None: limit = min(_DEFAULT_OUTPUT_LIMIT, self.layout.context - len(prompt)) if isinstance(limit, bool) or not isinstance(limit, int): raise AdmissionError("the output limit must be an integer") - request = Request(next(self.identities), prompt, limit, _sampling(body, self.defaults), - ignore_eos=bool(body.get("ignore_eos", False))) + request = Request( + next(self.identities), prompt, limit, _sampling(body, self.defaults), + ignore_eos=bool(body.get("ignore_eos", False)), + core_parameters=core_parameters) self.scheduler.validate(request) except (AdmissionError, ValueError, TypeError) as error: return 400, {"error": {"message": str(error), "type": "invalid_request_error"}} diff --git a/ignition/preparation/contract.py b/ignition/preparation/contract.py index 3c1787764..69818b106 100644 --- a/ignition/preparation/contract.py +++ b/ignition/preparation/contract.py @@ -4,12 +4,36 @@ """Semantic host uploads and persistent-state dependencies of prepared programs.""" -from . import runtime_core_pb2 as p +import math +import struct +from . import runtime_core_pb2 as p -def binding(buffer, source, indexing=p.SUBMISSION_ROW, *, offset=0, padding=0, tensor=""): - return dict(buffer=buffer, source=source, indexing=indexing, value_offset=offset, - padding=padding, tensor=tensor) +_FP32_MAX = 3.4028234663852886e38 + + +def _wire_fp32(value, label): + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label} must be a finite FP32 number") + try: + wide = float(value) + except (OverflowError, TypeError, ValueError) as error: + raise ValueError(f"{label} must be a finite FP32 number") from error + if not math.isfinite(wide) or abs(wide) > _FP32_MAX: + raise ValueError(f"{label} must be a finite FP32 number") + narrowed = struct.unpack(" max_value or not min_value <= default_value <= max_value: + raise ValueError( + f"core parameter {name!r} range [{min_value}, {max_value}] must contain default {default_value}") + result["range"] = dict(min=min_value, max=max_value) + return result + + def model_contract(*, vocabulary, input_vocabulary=None, vision=None, page_tokens, page_tables, graphs, frontend, - regions, codec_layout=None): - return dict(version=3, vocabulary=vocabulary, input_vocabulary=input_vocabulary or vocabulary, + regions, codec_layout=None, core_parameters=()): + result = dict(version=3, vocabulary=vocabulary, input_vocabulary=input_vocabulary or vocabulary, vision={"feature_slots": 0, **(vision or dict(features_per_request=0, max_images=0, patches_per_feature=0, patch_capacities=[]))}, cache=dict(page_tokens=page_tokens, page_tables=page_tables, regions=regions, **({"codec_layout": codec_layout} if codec_layout else {})), graphs=graphs, frontend=frontend) + if core_parameters: + result["core_parameters"] = list(core_parameters) + return result def codec_layout(pool, regions, buffers, *, field_encoding=None): diff --git a/ignition/preparation/runtime_core_pb2.py b/ignition/preparation/runtime_core_pb2.py index 52e7d5560..76789f968 100644 --- a/ignition/preparation/runtime_core_pb2.py +++ b/ignition/preparation/runtime_core_pb2.py @@ -2,7 +2,7 @@ # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: runtime_core.proto -# Protobuf Python Version: 7.36.2 +# Protobuf Python Version: 7.36.1 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool @@ -13,7 +13,7 @@ _runtime_version.Domain.PUBLIC, 7, 36, - 2, + 1, '', 'runtime_core.proto' ) @@ -24,7 +24,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12runtime_core.proto\x12\rflare.runtime\"\x99\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0f\n\x07\x63ore_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\x8c\x04\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12\x33\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestB\x02\x18\x01\x12\x37\n\x0bpreparation\x18\x0c \x01(\x0b\x32\".flare.runtime.PreparationManifestJ\x04\x08\x04\x10\x05\"\xf9\x01\n\x13PreparationManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x18\n\x10local_checkpoint\x18\x06 \x01(\x08\x12\x19\n\x11reproduction_args\x18\x07 \x03(\t\x12\x37\n\nparameters\x18\x08 \x03(\x0b\x32#.flare.runtime.PreparationParameter\"\x8c\x01\n\x14PreparationParameter\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x37\n\x05scope\x18\x02 \x01(\x0e\x32(.flare.runtime.PreparationParameterScope\x12.\n\x05value\x18\x03 \x01(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xc6\x01\n\x10PreparationValue\x12\x14\n\nbool_value\x18\x01 \x01(\x08H\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nuint_value\x18\x03 \x01(\x04H\x00\x12\x15\n\x0b\x66loat_value\x18\x04 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x05 \x01(\tH\x00\x12\x39\n\nlist_value\x18\x06 \x01(\x0b\x32#.flare.runtime.PreparationValueListH\x00\x42\x07\n\x05value\"G\n\x14PreparationValueList\x12/\n\x06values\x18\x01 \x03(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xdb\x07\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x12\x19\n\x11row_shard_prefill\x18\x1c \x01(\x08\x12\x1a\n\x12online_mxfp8_scope\x18\x1e \x01(\t\x12\x1d\n\x15\x63ontext_parallel_size\x18\x1f \x01(\r\x12\x17\n\x0fprompt_logprobs\x18 \x01(\x08\x12\x17\n\x0f\x61utotune_effort\x18! \x01(\t\x12 \n\x18native_dense_activations\x18\" \x01(\x08\x12\x17\n\x0flock_gpu_clocks\x18# \x01(\x08\x12\x19\n\x11reproduction_args\x18$ \x03(\t:\x02\x18\x01\x42\x1b\n\x19_expert_scale_compressionJ\x04\x08\x17\x10\x18J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bR\x0cjoint_tuningR\x11\x63ollective_tuningR\x16\x63ollective_ladder_json\"\x82\x04\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\t\x12\x10\n\x08mtp_only\x18\r \x01(\x08\x12$\n\x17\x64raft_body_quantization\x18\x0e \x01(\tH\x03\x88\x01\x01:\x02\x18\x01\x42\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budgetB\x1a\n\x18_draft_body_quantization\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\x8b\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\xb8\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\x12\x30\n\x0c\x63odec_layout\x18\x04 \x01(\x0b\x32\x1a.flare.runtime.CodecLayout\"r\n\x0b\x43odecLayout\x12\x10\n\x08revision\x18\x01 \x01(\r\x12)\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x19.flare.runtime.CodecField\x12\x17\n\ngpu_module\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\r\n\x0b_gpu_module\"N\n\nCodecField\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06length\x18\x03 \x01(\x04\x12\x10\n\x08\x65ncoding\x18\x04 \x01(\r\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xb1\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"k\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xfc\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x12+\n\x0bpadded_grid\x18\n \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\x99\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\x12\x17\n\x0fprefetch_buffer\x18\x10 \x01(\t\"E\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xc3\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"v\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xb9\x02\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\x12;\n\x12persistent_workers\x18\x08 \x03(\x0b\x32\x1f.flare.runtime.PersistentWorker\"\xa9\x01\n\x10PersistentWorker\x12\x17\n\x0fworker_sm_count\x18\x01 \x01(\r\x12\r\n\x05graph\x18\x02 \x01(\t\x12+\n\tstop_flag\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12)\n\x07metrics\x18\x04 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rmetrics_count\x18\x05 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\xfa\x01\n\x19PreparationParameterScope\x12+\n\'PREPARATION_PARAMETER_SCOPE_UNSPECIFIED\x10\x00\x12*\n&PREPARATION_PARAMETER_SCOPE_DEPLOYMENT\x10\x01\x12\'\n#PREPARATION_PARAMETER_SCOPE_COMBINE\x10\x02\x12-\n)PREPARATION_PARAMETER_SCOPE_TARGET_WEIGHT\x10\x03\x12,\n(PREPARATION_PARAMETER_SCOPE_DRAFT_WEIGHT\x10\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xb3\x07\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(\x12\x1a\n\x16PROMPT_LOOKAHEAD_TOKEN\x10)\x12\x1b\n\x17PROMPT_LOOKAHEAD_LENGTH\x10**|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\x8b\x02\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\x12\x14\n\x10TERMINAL_PREFILL\x10\x0e\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\xa1\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07\x12\x0c\n\x08TML_JSON\x10\x08*\xa6\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05\x12\x13\n\x0f\x43ONTENT_HEADERS\x10\x06*\xf4\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t\x12!\n\x1dPADDED_GRID_IMAGE_PREPARATION\x10\n*\xb6\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t\x12\x1c\n\x18\x43LASS_TOKEN_IMAGE_LAYOUT\x10\n*P\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02\x12\n\n\x06TML_V0\x10\x03*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*(\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12runtime_core.proto\x12\rflare.runtime\"\x99\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0f\n\x07\x63ore_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\x8c\x04\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12\x33\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestB\x02\x18\x01\x12\x37\n\x0bpreparation\x18\x0c \x01(\x0b\x32\".flare.runtime.PreparationManifestJ\x04\x08\x04\x10\x05\"\xf9\x01\n\x13PreparationManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x18\n\x10local_checkpoint\x18\x06 \x01(\x08\x12\x19\n\x11reproduction_args\x18\x07 \x03(\t\x12\x37\n\nparameters\x18\x08 \x03(\x0b\x32#.flare.runtime.PreparationParameter\"\x8c\x01\n\x14PreparationParameter\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x37\n\x05scope\x18\x02 \x01(\x0e\x32(.flare.runtime.PreparationParameterScope\x12.\n\x05value\x18\x03 \x01(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xc6\x01\n\x10PreparationValue\x12\x14\n\nbool_value\x18\x01 \x01(\x08H\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nuint_value\x18\x03 \x01(\x04H\x00\x12\x15\n\x0b\x66loat_value\x18\x04 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x05 \x01(\tH\x00\x12\x39\n\nlist_value\x18\x06 \x01(\x0b\x32#.flare.runtime.PreparationValueListH\x00\x42\x07\n\x05value\"G\n\x14PreparationValueList\x12/\n\x06values\x18\x01 \x03(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xdb\x07\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x12\x19\n\x11row_shard_prefill\x18\x1c \x01(\x08\x12\x1a\n\x12online_mxfp8_scope\x18\x1e \x01(\t\x12\x1d\n\x15\x63ontext_parallel_size\x18\x1f \x01(\r\x12\x17\n\x0fprompt_logprobs\x18 \x01(\x08\x12\x17\n\x0f\x61utotune_effort\x18! \x01(\t\x12 \n\x18native_dense_activations\x18\" \x01(\x08\x12\x17\n\x0flock_gpu_clocks\x18# \x01(\x08\x12\x19\n\x11reproduction_args\x18$ \x03(\t:\x02\x18\x01\x42\x1b\n\x19_expert_scale_compressionJ\x04\x08\x17\x10\x18J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bR\x0cjoint_tuningR\x11\x63ollective_tuningR\x16\x63ollective_ladder_json\"\x82\x04\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\t\x12\x10\n\x08mtp_only\x18\r \x01(\x08\x12$\n\x17\x64raft_body_quantization\x18\x0e \x01(\tH\x03\x88\x01\x01:\x02\x18\x01\x42\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budgetB\x1a\n\x18_draft_body_quantization\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\xc2\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\x12\x35\n\x0f\x63ore_parameters\x18\x08 \x03(\x0b\x32\x1c.flare.runtime.CoreParameter\"}\n\rCoreParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1a\n\rdefault_value\x18\x02 \x01(\x02H\x00\x88\x01\x01\x12\x30\n\x05range\x18\x03 \x01(\x0b\x32!.flare.runtime.CoreParameterRangeB\x10\n\x0e_default_value\"H\n\x12\x43oreParameterRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\xb8\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\x12\x30\n\x0c\x63odec_layout\x18\x04 \x01(\x0b\x32\x1a.flare.runtime.CodecLayout\"r\n\x0b\x43odecLayout\x12\x10\n\x08revision\x18\x01 \x01(\r\x12)\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x19.flare.runtime.CodecField\x12\x17\n\ngpu_module\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\r\n\x0b_gpu_module\"N\n\nCodecField\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06length\x18\x03 \x01(\x04\x12\x10\n\x08\x65ncoding\x18\x04 \x01(\r\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xc4\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\x12\x11\n\tparameter\x18\x07 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"k\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xfc\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x12+\n\x0bpadded_grid\x18\n \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\x99\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\x12\x17\n\x0fprefetch_buffer\x18\x10 \x01(\t\"E\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xc3\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"v\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xb9\x02\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\x12;\n\x12persistent_workers\x18\x08 \x03(\x0b\x32\x1f.flare.runtime.PersistentWorker\"\xa9\x01\n\x10PersistentWorker\x12\x17\n\x0fworker_sm_count\x18\x01 \x01(\r\x12\r\n\x05graph\x18\x02 \x01(\t\x12+\n\tstop_flag\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12)\n\x07metrics\x18\x04 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rmetrics_count\x18\x05 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\xfa\x01\n\x19PreparationParameterScope\x12+\n\'PREPARATION_PARAMETER_SCOPE_UNSPECIFIED\x10\x00\x12*\n&PREPARATION_PARAMETER_SCOPE_DEPLOYMENT\x10\x01\x12\'\n#PREPARATION_PARAMETER_SCOPE_COMBINE\x10\x02\x12-\n)PREPARATION_PARAMETER_SCOPE_TARGET_WEIGHT\x10\x03\x12,\n(PREPARATION_PARAMETER_SCOPE_DRAFT_WEIGHT\x10\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xc7\x07\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(\x12\x1a\n\x16PROMPT_LOOKAHEAD_TOKEN\x10)\x12\x1b\n\x17PROMPT_LOOKAHEAD_LENGTH\x10*\x12\x12\n\x0e\x43ORE_PARAMETER\x10+*|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\x8b\x02\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\x12\x14\n\x10TERMINAL_PREFILL\x10\x0e\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\xa1\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07\x12\x0c\n\x08TML_JSON\x10\x08*\xa6\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05\x12\x13\n\x0f\x43ONTENT_HEADERS\x10\x06*\xf4\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t\x12!\n\x1dPADDED_GRID_IMAGE_PREPARATION\x10\n*\xb6\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t\x12\x1c\n\x18\x43LASS_TOKEN_IMAGE_LAYOUT\x10\n*P\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02\x12\n\n\x06TML_V0\x10\x03*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*(\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -39,38 +39,38 @@ _globals['_REBUILDSPECULATION']._serialized_options = b'\030\001' _globals['_BUNDLEINDEX_RESOURCESENTRY']._loaded_options = None _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_options = b'8\001' - _globals['_PREPARATIONPARAMETERSCOPE']._serialized_start=16068 - _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=16318 - _globals['_HISTORYKIND']._serialized_start=16321 - _globals['_HISTORYKIND']._serialized_end=16463 - _globals['_VALUESOURCE']._serialized_start=16466 - _globals['_VALUESOURCE']._serialized_end=17413 - _globals['_INPUTINDEXING']._serialized_start=17415 - _globals['_INPUTINDEXING']._serialized_end=17539 - _globals['_STATEACCESSKIND']._serialized_start=17541 - _globals['_STATEACCESSKIND']._serialized_end=17625 - _globals['_GRAPHOPERATION']._serialized_start=17628 - _globals['_GRAPHOPERATION']._serialized_end=17895 - _globals['_TOOLPARSERKIND']._serialized_start=17898 - _globals['_TOOLPARSERKIND']._serialized_end=18059 - _globals['_REASONINGPARSERKIND']._serialized_start=18062 - _globals['_REASONINGPARSERKIND']._serialized_end=18228 - _globals['_IMAGEPREPARATIONKIND']._serialized_start=18231 - _globals['_IMAGEPREPARATIONKIND']._serialized_end=18603 - _globals['_IMAGELAYOUTKIND']._serialized_start=18606 - _globals['_IMAGELAYOUTKIND']._serialized_end=18916 - _globals['_PROMPTENCODER']._serialized_start=18918 - _globals['_PROMPTENCODER']._serialized_end=18998 - _globals['_TEMPLATEENCODING']._serialized_start=19000 - _globals['_TEMPLATEENCODING']._serialized_end=19066 - _globals['_MEMORY']._serialized_start=19068 - _globals['_MEMORY']._serialized_end=19115 - _globals['_CAPACITY']._serialized_start=19117 - _globals['_CAPACITY']._serialized_end=19157 - _globals['_RELOCATIONKIND']._serialized_start=19159 - _globals['_RELOCATIONKIND']._serialized_end=19204 - _globals['_DRAFTSOURCE']._serialized_start=19206 - _globals['_DRAFTSOURCE']._serialized_end=19258 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_start=16343 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=16593 + _globals['_HISTORYKIND']._serialized_start=16596 + _globals['_HISTORYKIND']._serialized_end=16738 + _globals['_VALUESOURCE']._serialized_start=16741 + _globals['_VALUESOURCE']._serialized_end=17708 + _globals['_INPUTINDEXING']._serialized_start=17710 + _globals['_INPUTINDEXING']._serialized_end=17834 + _globals['_STATEACCESSKIND']._serialized_start=17836 + _globals['_STATEACCESSKIND']._serialized_end=17920 + _globals['_GRAPHOPERATION']._serialized_start=17923 + _globals['_GRAPHOPERATION']._serialized_end=18190 + _globals['_TOOLPARSERKIND']._serialized_start=18193 + _globals['_TOOLPARSERKIND']._serialized_end=18354 + _globals['_REASONINGPARSERKIND']._serialized_start=18357 + _globals['_REASONINGPARSERKIND']._serialized_end=18523 + _globals['_IMAGEPREPARATIONKIND']._serialized_start=18526 + _globals['_IMAGEPREPARATIONKIND']._serialized_end=18898 + _globals['_IMAGELAYOUTKIND']._serialized_start=18901 + _globals['_IMAGELAYOUTKIND']._serialized_end=19211 + _globals['_PROMPTENCODER']._serialized_start=19213 + _globals['_PROMPTENCODER']._serialized_end=19293 + _globals['_TEMPLATEENCODING']._serialized_start=19295 + _globals['_TEMPLATEENCODING']._serialized_end=19361 + _globals['_MEMORY']._serialized_start=19363 + _globals['_MEMORY']._serialized_end=19410 + _globals['_CAPACITY']._serialized_start=19412 + _globals['_CAPACITY']._serialized_end=19452 + _globals['_RELOCATIONKIND']._serialized_start=19454 + _globals['_RELOCATIONKIND']._serialized_end=19499 + _globals['_DRAFTSOURCE']._serialized_start=19501 + _globals['_DRAFTSOURCE']._serialized_end=19553 _globals['_PROTECTEDINDEX']._serialized_start=38 _globals['_PROTECTEDINDEX']._serialized_end=191 _globals['_SIGNEDGROUP']._serialized_start=193 @@ -108,145 +108,149 @@ _globals['_SERVINGCONTRACT']._serialized_start=3959 _globals['_SERVINGCONTRACT']._serialized_end=4802 _globals['_MODELCONTRACT']._serialized_start=4805 - _globals['_MODELCONTRACT']._serialized_end=5072 - _globals['_VISIONCAPACITY']._serialized_start=5075 - _globals['_VISIONCAPACITY']._serialized_end=5219 - _globals['_CACHECONTRACT']._serialized_start=5222 - _globals['_CACHECONTRACT']._serialized_end=5406 - _globals['_CODECLAYOUT']._serialized_start=5408 - _globals['_CODECLAYOUT']._serialized_end=5522 - _globals['_CODECFIELD']._serialized_start=5524 - _globals['_CODECFIELD']._serialized_end=5602 - _globals['_HISTORYREGION']._serialized_start=5605 - _globals['_HISTORYREGION']._serialized_end=5755 - _globals['_PAGETABLEVIEW']._serialized_start=5757 - _globals['_PAGETABLEVIEW']._serialized_end=5809 - _globals['_VALUEBINDING']._serialized_start=5812 - _globals['_VALUEBINDING']._serialized_end=5989 - _globals['_STATEVIEW']._serialized_start=5991 - _globals['_STATEVIEW']._serialized_end=6066 - _globals['_STATEACCESS']._serialized_start=6068 - _globals['_STATEACCESS']._serialized_end=6169 - _globals['_COMPLETIONCURSOR']._serialized_start=6171 - _globals['_COMPLETIONCURSOR']._serialized_end=6250 - _globals['_TUNEDBINDING']._serialized_start=6252 - _globals['_TUNEDBINDING']._serialized_end=6304 - _globals['_GRAPHCONTRACT']._serialized_start=6307 - _globals['_GRAPHCONTRACT']._serialized_end=6685 - _globals['_TOOLPARSER']._serialized_start=6687 - _globals['_TOOLPARSER']._serialized_end=6794 - _globals['_REASONINGPARSER']._serialized_start=6797 - _globals['_REASONINGPARSER']._serialized_end=6946 - _globals['_PREFIXBOUNDARY']._serialized_start=6949 - _globals['_PREFIXBOUNDARY']._serialized_end=7151 - _globals['_IMAGESPAN']._serialized_start=7153 - _globals['_IMAGESPAN']._serialized_end=7274 - _globals['_IMAGETOKENLAYOUT']._serialized_start=7276 - _globals['_IMAGETOKENLAYOUT']._serialized_end=7357 - _globals['_FRONTENDCONTRACT']._serialized_start=7360 - _globals['_FRONTENDCONTRACT']._serialized_end=7858 - _globals['_CLUSTER']._serialized_start=7860 - _globals['_CLUSTER']._serialized_end=7909 - _globals['_DEFAULTSAMPLINGPARAMETERS']._serialized_start=7912 - _globals['_DEFAULTSAMPLINGPARAMETERS']._serialized_end=8308 - _globals['_SAMPLINGFLOATRANGE']._serialized_start=8310 - _globals['_SAMPLINGFLOATRANGE']._serialized_end=8382 - _globals['_SAMPLINGINTRANGE']._serialized_start=8384 - _globals['_SAMPLINGINTRANGE']._serialized_end=8454 - _globals['_SAMPLINGRANGES']._serialized_start=8457 - _globals['_SAMPLINGRANGES']._serialized_end=8863 - _globals['_FRONTENDSETTINGS']._serialized_start=8866 - _globals['_FRONTENDSETTINGS']._serialized_end=9191 - _globals['_TOKENIZERSETTINGS']._serialized_start=9194 - _globals['_TOKENIZERSETTINGS']._serialized_end=9542 - _globals['_TOKENLIST']._serialized_start=9544 - _globals['_TOKENLIST']._serialized_end=9571 - _globals['_IMAGESETTINGS']._serialized_start=9574 - _globals['_IMAGESETTINGS']._serialized_end=10082 - _globals['_PATCHMERGEIMAGESETTINGS']._serialized_start=10085 - _globals['_PATCHMERGEIMAGESETTINGS']._serialized_end=10270 - _globals['_DEEPSEEKROWMAJORIMAGESETTINGS']._serialized_start=10273 - _globals['_DEEPSEEKROWMAJORIMAGESETTINGS']._serialized_end=10408 - _globals['_QWENIMAGESETTINGS']._serialized_start=10411 - _globals['_QWENIMAGESETTINGS']._serialized_end=10541 - _globals['_MIMOIMAGESETTINGS']._serialized_start=10543 - _globals['_MIMOIMAGESETTINGS']._serialized_end=10641 - _globals['_ENGRAM']._serialized_start=10643 - _globals['_ENGRAM']._serialized_end=10767 - _globals['_ENGRAMTABLE']._serialized_start=10770 - _globals['_ENGRAMTABLE']._serialized_end=11307 - _globals['_ENGRAMTABLE_ENCODING']._serialized_start=11238 - _globals['_ENGRAMTABLE_ENCODING']._serialized_end=11307 - _globals['_ENGRAMTABLESHARD']._serialized_start=11310 - _globals['_ENGRAMTABLESHARD']._serialized_end=11450 - _globals['_ENGRAMHASH']._serialized_start=11453 - _globals['_ENGRAMHASH']._serialized_end=11648 - _globals['_ENGRAMHASH_METHOD']._serialized_start=11587 - _globals['_ENGRAMHASH_METHOD']._serialized_end=11648 - _globals['_ASSET']._serialized_start=11650 - _globals['_ASSET']._serialized_end=11725 - _globals['_BUNDLEINDEX']._serialized_start=11728 - _globals['_BUNDLEINDEX']._serialized_end=12323 - _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_start=12254 - _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_end=12323 - _globals['_ROCETRANSPORT']._serialized_start=12326 - _globals['_ROCETRANSPORT']._serialized_end=12574 - _globals['_GRAPHINDEX']._serialized_start=12576 - _globals['_GRAPHINDEX']._serialized_end=12694 - _globals['_PEERMEMORY']._serialized_start=12696 - _globals['_PEERMEMORY']._serialized_end=12773 - _globals['_CONTEXT']._serialized_start=12775 - _globals['_CONTEXT']._serialized_end=12852 - _globals['_LIMIT']._serialized_start=12854 - _globals['_LIMIT']._serialized_end=12888 - _globals['_RESERVATION']._serialized_start=12890 - _globals['_RESERVATION']._serialized_end=12936 - _globals['_SPAN']._serialized_start=12938 - _globals['_SPAN']._serialized_end=12994 - _globals['_ALLOCATION']._serialized_start=12997 - _globals['_ALLOCATION']._serialized_end=13287 - _globals['_SIZING']._serialized_start=13289 - _globals['_SIZING']._serialized_end=13377 - _globals['_MODULE']._serialized_start=13379 - _globals['_MODULE']._serialized_end=13455 - _globals['_GLOBAL']._serialized_start=13457 - _globals['_GLOBAL']._serialized_end=13559 - _globals['_FUNCTION']._serialized_start=13561 - _globals['_FUNCTION']._serialized_end=13682 - _globals['_FUNCTIONATTRIBUTE']._serialized_start=13684 - _globals['_FUNCTIONATTRIBUTE']._serialized_end=13730 - _globals['_REFERENCE']._serialized_start=13732 - _globals['_REFERENCE']._serialized_end=13779 - _globals['_RELOCATION']._serialized_start=13781 - _globals['_RELOCATION']._serialized_end=13896 - _globals['_BLOB']._serialized_start=13898 - _globals['_BLOB']._serialized_end=13966 - _globals['_ATTRIBUTE']._serialized_start=13968 - _globals['_ATTRIBUTE']._serialized_end=14027 - _globals['_KERNEL']._serialized_start=14030 - _globals['_KERNEL']._serialized_end=14187 - _globals['_MEMSET']._serialized_start=14190 - _globals['_MEMSET']._serialized_end=14328 - _globals['_COPY']._serialized_start=14330 - _globals['_COPY']._serialized_end=14441 - _globals['_EMPTY']._serialized_start=14443 - _globals['_EMPTY']._serialized_end=14450 - _globals['_EVENTWAIT']._serialized_start=14452 - _globals['_EVENTWAIT']._serialized_end=14478 - _globals['_NODE']._serialized_start=14481 - _globals['_NODE']._serialized_end=14706 - _globals['_EDGE']._serialized_start=14708 - _globals['_EDGE']._serialized_end=14765 - _globals['_EXECUTION']._serialized_start=14768 - _globals['_EXECUTION']._serialized_end=15081 - _globals['_PERSISTENTWORKER']._serialized_start=15084 - _globals['_PERSISTENTWORKER']._serialized_end=15253 - _globals['_TUNINGGRAPH']._serialized_start=15255 - _globals['_TUNINGGRAPH']._serialized_end=15322 - _globals['_BUFFER']._serialized_start=15325 - _globals['_BUFFER']._serialized_end=15455 - _globals['_EXECUTIONGRAPH']._serialized_start=15458 - _globals['_EXECUTIONGRAPH']._serialized_end=15991 - _globals['_INPUTBINDING']._serialized_start=15993 - _globals['_INPUTBINDING']._serialized_end=16065 + _globals['_MODELCONTRACT']._serialized_end=5127 + _globals['_COREPARAMETER']._serialized_start=5129 + _globals['_COREPARAMETER']._serialized_end=5254 + _globals['_COREPARAMETERRANGE']._serialized_start=5256 + _globals['_COREPARAMETERRANGE']._serialized_end=5328 + _globals['_VISIONCAPACITY']._serialized_start=5331 + _globals['_VISIONCAPACITY']._serialized_end=5475 + _globals['_CACHECONTRACT']._serialized_start=5478 + _globals['_CACHECONTRACT']._serialized_end=5662 + _globals['_CODECLAYOUT']._serialized_start=5664 + _globals['_CODECLAYOUT']._serialized_end=5778 + _globals['_CODECFIELD']._serialized_start=5780 + _globals['_CODECFIELD']._serialized_end=5858 + _globals['_HISTORYREGION']._serialized_start=5861 + _globals['_HISTORYREGION']._serialized_end=6011 + _globals['_PAGETABLEVIEW']._serialized_start=6013 + _globals['_PAGETABLEVIEW']._serialized_end=6065 + _globals['_VALUEBINDING']._serialized_start=6068 + _globals['_VALUEBINDING']._serialized_end=6264 + _globals['_STATEVIEW']._serialized_start=6266 + _globals['_STATEVIEW']._serialized_end=6341 + _globals['_STATEACCESS']._serialized_start=6343 + _globals['_STATEACCESS']._serialized_end=6444 + _globals['_COMPLETIONCURSOR']._serialized_start=6446 + _globals['_COMPLETIONCURSOR']._serialized_end=6525 + _globals['_TUNEDBINDING']._serialized_start=6527 + _globals['_TUNEDBINDING']._serialized_end=6579 + _globals['_GRAPHCONTRACT']._serialized_start=6582 + _globals['_GRAPHCONTRACT']._serialized_end=6960 + _globals['_TOOLPARSER']._serialized_start=6962 + _globals['_TOOLPARSER']._serialized_end=7069 + _globals['_REASONINGPARSER']._serialized_start=7072 + _globals['_REASONINGPARSER']._serialized_end=7221 + _globals['_PREFIXBOUNDARY']._serialized_start=7224 + _globals['_PREFIXBOUNDARY']._serialized_end=7426 + _globals['_IMAGESPAN']._serialized_start=7428 + _globals['_IMAGESPAN']._serialized_end=7549 + _globals['_IMAGETOKENLAYOUT']._serialized_start=7551 + _globals['_IMAGETOKENLAYOUT']._serialized_end=7632 + _globals['_FRONTENDCONTRACT']._serialized_start=7635 + _globals['_FRONTENDCONTRACT']._serialized_end=8133 + _globals['_CLUSTER']._serialized_start=8135 + _globals['_CLUSTER']._serialized_end=8184 + _globals['_DEFAULTSAMPLINGPARAMETERS']._serialized_start=8187 + _globals['_DEFAULTSAMPLINGPARAMETERS']._serialized_end=8583 + _globals['_SAMPLINGFLOATRANGE']._serialized_start=8585 + _globals['_SAMPLINGFLOATRANGE']._serialized_end=8657 + _globals['_SAMPLINGINTRANGE']._serialized_start=8659 + _globals['_SAMPLINGINTRANGE']._serialized_end=8729 + _globals['_SAMPLINGRANGES']._serialized_start=8732 + _globals['_SAMPLINGRANGES']._serialized_end=9138 + _globals['_FRONTENDSETTINGS']._serialized_start=9141 + _globals['_FRONTENDSETTINGS']._serialized_end=9466 + _globals['_TOKENIZERSETTINGS']._serialized_start=9469 + _globals['_TOKENIZERSETTINGS']._serialized_end=9817 + _globals['_TOKENLIST']._serialized_start=9819 + _globals['_TOKENLIST']._serialized_end=9846 + _globals['_IMAGESETTINGS']._serialized_start=9849 + _globals['_IMAGESETTINGS']._serialized_end=10357 + _globals['_PATCHMERGEIMAGESETTINGS']._serialized_start=10360 + _globals['_PATCHMERGEIMAGESETTINGS']._serialized_end=10545 + _globals['_DEEPSEEKROWMAJORIMAGESETTINGS']._serialized_start=10548 + _globals['_DEEPSEEKROWMAJORIMAGESETTINGS']._serialized_end=10683 + _globals['_QWENIMAGESETTINGS']._serialized_start=10686 + _globals['_QWENIMAGESETTINGS']._serialized_end=10816 + _globals['_MIMOIMAGESETTINGS']._serialized_start=10818 + _globals['_MIMOIMAGESETTINGS']._serialized_end=10916 + _globals['_ENGRAM']._serialized_start=10918 + _globals['_ENGRAM']._serialized_end=11042 + _globals['_ENGRAMTABLE']._serialized_start=11045 + _globals['_ENGRAMTABLE']._serialized_end=11582 + _globals['_ENGRAMTABLE_ENCODING']._serialized_start=11513 + _globals['_ENGRAMTABLE_ENCODING']._serialized_end=11582 + _globals['_ENGRAMTABLESHARD']._serialized_start=11585 + _globals['_ENGRAMTABLESHARD']._serialized_end=11725 + _globals['_ENGRAMHASH']._serialized_start=11728 + _globals['_ENGRAMHASH']._serialized_end=11923 + _globals['_ENGRAMHASH_METHOD']._serialized_start=11862 + _globals['_ENGRAMHASH_METHOD']._serialized_end=11923 + _globals['_ASSET']._serialized_start=11925 + _globals['_ASSET']._serialized_end=12000 + _globals['_BUNDLEINDEX']._serialized_start=12003 + _globals['_BUNDLEINDEX']._serialized_end=12598 + _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_start=12529 + _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_end=12598 + _globals['_ROCETRANSPORT']._serialized_start=12601 + _globals['_ROCETRANSPORT']._serialized_end=12849 + _globals['_GRAPHINDEX']._serialized_start=12851 + _globals['_GRAPHINDEX']._serialized_end=12969 + _globals['_PEERMEMORY']._serialized_start=12971 + _globals['_PEERMEMORY']._serialized_end=13048 + _globals['_CONTEXT']._serialized_start=13050 + _globals['_CONTEXT']._serialized_end=13127 + _globals['_LIMIT']._serialized_start=13129 + _globals['_LIMIT']._serialized_end=13163 + _globals['_RESERVATION']._serialized_start=13165 + _globals['_RESERVATION']._serialized_end=13211 + _globals['_SPAN']._serialized_start=13213 + _globals['_SPAN']._serialized_end=13269 + _globals['_ALLOCATION']._serialized_start=13272 + _globals['_ALLOCATION']._serialized_end=13562 + _globals['_SIZING']._serialized_start=13564 + _globals['_SIZING']._serialized_end=13652 + _globals['_MODULE']._serialized_start=13654 + _globals['_MODULE']._serialized_end=13730 + _globals['_GLOBAL']._serialized_start=13732 + _globals['_GLOBAL']._serialized_end=13834 + _globals['_FUNCTION']._serialized_start=13836 + _globals['_FUNCTION']._serialized_end=13957 + _globals['_FUNCTIONATTRIBUTE']._serialized_start=13959 + _globals['_FUNCTIONATTRIBUTE']._serialized_end=14005 + _globals['_REFERENCE']._serialized_start=14007 + _globals['_REFERENCE']._serialized_end=14054 + _globals['_RELOCATION']._serialized_start=14056 + _globals['_RELOCATION']._serialized_end=14171 + _globals['_BLOB']._serialized_start=14173 + _globals['_BLOB']._serialized_end=14241 + _globals['_ATTRIBUTE']._serialized_start=14243 + _globals['_ATTRIBUTE']._serialized_end=14302 + _globals['_KERNEL']._serialized_start=14305 + _globals['_KERNEL']._serialized_end=14462 + _globals['_MEMSET']._serialized_start=14465 + _globals['_MEMSET']._serialized_end=14603 + _globals['_COPY']._serialized_start=14605 + _globals['_COPY']._serialized_end=14716 + _globals['_EMPTY']._serialized_start=14718 + _globals['_EMPTY']._serialized_end=14725 + _globals['_EVENTWAIT']._serialized_start=14727 + _globals['_EVENTWAIT']._serialized_end=14753 + _globals['_NODE']._serialized_start=14756 + _globals['_NODE']._serialized_end=14981 + _globals['_EDGE']._serialized_start=14983 + _globals['_EDGE']._serialized_end=15040 + _globals['_EXECUTION']._serialized_start=15043 + _globals['_EXECUTION']._serialized_end=15356 + _globals['_PERSISTENTWORKER']._serialized_start=15359 + _globals['_PERSISTENTWORKER']._serialized_end=15528 + _globals['_TUNINGGRAPH']._serialized_start=15530 + _globals['_TUNINGGRAPH']._serialized_end=15597 + _globals['_BUFFER']._serialized_start=15600 + _globals['_BUFFER']._serialized_end=15730 + _globals['_EXECUTIONGRAPH']._serialized_start=15733 + _globals['_EXECUTIONGRAPH']._serialized_end=16266 + _globals['_INPUTBINDING']._serialized_start=16268 + _globals['_INPUTBINDING']._serialized_end=16340 # @@protoc_insertion_point(module_scope) diff --git a/tests/direct/test_scheduler.py b/tests/direct/test_scheduler.py index 8303c3973..4a639acba 100644 --- a/tests/direct/test_scheduler.py +++ b/tests/direct/test_scheduler.py @@ -720,3 +720,276 @@ def test_terminal_prefill_contract_and_signature(): assert contracts[0]["kind"] == p.TERMINAL_PREFILL == 14 assert contracts[0]["embedding_tables"] == [0, 1] assert contracts[0]["pending_token"] is not None + + +def _core_parameter_layout( + *, + default=0.0, + minimum=None, + maximum=None, + indexing=None, + rows=None, + column=False, + contiguity=True, + tensor="", + omit_graph=None, + extra_graph_kind=None, +): + from ignition.preparation import contract as c, runtime_core_pb2 as p + + base = layout() + indexing = p.REQUEST_ROW if indexing is None else indexing + param = c.core_parameter("alpha", default, minimum=minimum, maximum=maximum) + bindings = {name: list(fields) for name, fields in base.bindings.items()} + graph_kinds = {name: key[0] for key, name in base.graphs.items()} + text_forward = {"prefill", "terminal_prefill", "scored_prefill", "resume", "decode", "speculative", "mixed"} + param_binding = c.binding("request_alpha", p.CORE_PARAMETER, indexing, tensor=tensor, parameter="alpha") + for name in bindings: + if graph_kinds.get(name) in text_forward and name != omit_graph: + bindings[name].append(param_binding) + elif extra_graph_kind is not None and graph_kinds.get(name) == extra_graph_kind: + bindings[name].append(param_binding) + specs = dict(base.buffer_specs) + row_count = base.capacity if rows is None else rows + specs["request_alpha"] = (np.dtype(np.float32), (row_count, 1) if column else (row_count,)) + return Layout( + capacity=base.capacity, + max_active=base.max_active, + context=base.context, + page_tokens=base.page_tokens, + table_width=base.table_width, + pages=base.pages, + snapshots=base.snapshots, + prefill_chunk=base.prefill_chunk, + vocabulary=base.vocabulary, + eos=base.eos, + graphs=base.graphs, + bindings=bindings, + buffer_specs=specs, + page_views=base.page_views, + widths=base.widths, + fixed_width=base.fixed_width, + state_rows_per_request=base.state_rows_per_request, + draft_pages=base.draft_pages, + record_fields=base.record_fields, + confidence_widths=base.confidence_widths, + completion_cursors=base.completion_cursors, + buffer_contiguity={"request_alpha": contiguity}, + core_parameters=(param,), + ) + + +def test_layout_constructor_preserves_positional_fields_and_keeps_extensions_keyword_only(): + import inspect + + parameters = inspect.signature(Layout).parameters + assert parameters["buffer_contiguity"].kind == inspect.Parameter.KEYWORD_ONLY + assert parameters["core_parameters"].kind == inspect.Parameter.KEYWORD_ONLY + + +def test_core_parameter_helper_validates_and_reaches_wire_contract(): + from google.protobuf import json_format + from ignition.preparation import contract as c, runtime_core_pb2 as p + + assert p.CORE_PARAMETER == 43 + param = c.core_parameter("gain", -0.0, minimum=-0.0, maximum=1.5) + assert param == {"name": "gain", "default_value": 0.0, "range": {"min": 0.0, "max": 1.5}} + assert np.float32(param["default_value"]).view(np.uint32) == 0 + + unbounded = c.core_parameter("offset", 0.25) + assert unbounded == {"name": "offset", "default_value": 0.25} + + param_binding = c.binding("request_gain", p.CORE_PARAMETER, p.REQUEST_ROW, parameter="gain") + plain_binding = c.binding("row_slot_ids", p.REQUEST_SLOT) + assert "parameter" not in plain_binding + declaring = c.model_contract( + vocabulary=100, + page_tokens=64, + page_tables=[], + regions=[], + graphs=[{"graph": "decode1", "kind": p.DECODE, "inputs": [param_binding], "state": [], "state_rows_per_request": 1}], + frontend=c.frontend(tools=p.QWEN_CODER, assistant_marker="", message_end_markers=[], prefix_boundary=None), + core_parameters=[param, unbounded], + ) + wire = json_format.ParseDict(declaring, p.ModelContract()) + assert [(a.name, a.default_value, a.HasField("range")) for a in wire.core_parameters] == [ + ("gain", 0.0, True), + ("offset", 0.25, False), + ] + assert wire.graphs[0].inputs[0].source == p.CORE_PARAMETER + assert wire.graphs[0].inputs[0].parameter == "gain" + + plain = c.model_contract( + vocabulary=100, + page_tokens=64, + page_tables=[], + regions=[], + graphs=[{"graph": "decode1", "kind": p.DECODE, "inputs": [plain_binding], "state": [], "state_rows_per_request": 1}], + frontend=c.frontend(tools=p.QWEN_CODER, assistant_marker="", message_end_markers=[], prefix_boundary=None), + ) + assert "core_parameters" not in plain + plain_wire = json_format.ParseDict(plain, p.ModelContract()) + assert list(plain_wire.core_parameters) == [] + assert plain_wire.graphs[0].inputs[0].parameter == "" + + for bad in [ + lambda: c.core_parameter("", 0.0), + lambda: c.core_parameter("gain", True), + lambda: c.core_parameter("gain", float("nan")), + lambda: c.core_parameter("gain", float("inf")), + lambda: c.core_parameter("gain", 1e-100), + lambda: c.core_parameter("gain", 0.5, minimum=0.0), + lambda: c.core_parameter("gain", 2.0, minimum=0.0, maximum=1.0), + lambda: c.core_parameter("gain", 0.5, minimum=1.0, maximum=0.0), + ]: + with pytest.raises(ValueError): + bad() + + +def test_direct_core_parameter_bindings_require_every_text_forward_graph_and_forbid_maintenance_graphs(): + _core_parameter_layout() + with pytest.raises(ValueError, match="every selected text forward graph"): + _core_parameter_layout(omit_graph="prefill128") + for forbidden in ("init", "restore", "snapshot"): + with pytest.raises(ValueError, match="text forward graphs"): + _core_parameter_layout(extra_graph_kind=forbidden) + + +def test_direct_packing_and_checkpoint_isolation_for_core_parameters(): + from ignition.preparation import runtime_core_pb2 as p + + for indexing in (p.SUBMISSION_ROW, p.ACTIVE_ROW, p.REQUEST_ROW): + lay = _core_parameter_layout(default=0.25, minimum=0.0, maximum=1.0, indexing=indexing) + sched = Scheduler(lay) + req = Request(1, [1, 2, 3, 4], 4, SamplingParameters(temperature=1.0, top_p=0.95), core_parameters={"alpha": 2.0}) + sched.submit(req) + assert req.core_parameters["alpha"] == 1.0 + with pytest.raises(TypeError): + req.core_parameters["alpha"] = 0.0 + + init = sched.plan() + assert init.kind == "init" + assert "request_alpha" not in {name for name, _, _ in sched.pack(init)} + sched.complete(init, respond(sched, init)) + + prefill = sched.plan() + assert prefill.kind == "prefill" + packed = { + name: np.frombuffer(data, dtype=np.float32).tolist() + for name, _, data in sched.pack(prefill) + if name == "request_alpha" + } + expected = [1.0, 0.0, 0.0, 0.0] if indexing == p.SUBMISSION_ROW else [1.0] + assert packed["request_alpha"] == expected + + # Two requests with different core-parameter values do not reuse each other's checkpoints or coalesce captures. + lay = _core_parameter_layout(default=0.25, minimum=0.0, maximum=1.0) + sched = Scheduler(lay) + prompt = [10] * 300 + r1 = Request(1, prompt, 64, SamplingParameters(temperature=1.0, top_p=0.95), core_parameters={"alpha": 0.25}) + r2 = Request(2, prompt, 64, SamplingParameters(temperature=1.0, top_p=0.95), core_parameters={"alpha": 0.75}) + sched.submit(r1) + sched.submit(r2) + while not (r1.phase == "decode" and r2.phase == "decode"): + step = sched.plan() + assert step is not None + sched.complete(step, respond(sched, step)) + assert len(sched.cache) == 2 + + # A third request matching r2's parameter hits r2's checkpoint; a fourth with 0.5 misses both. + r3 = Request(3, prompt, 64, SamplingParameters(temperature=1.0, top_p=0.95), core_parameters={"alpha": 0.75}) + r4 = Request(4, prompt, 64, SamplingParameters(temperature=1.0, top_p=0.95), core_parameters={"alpha": 0.5}) + sched.submit(r3) + sched.submit(r4) + sched._admit() + assert r3.reused == len(prompt) + assert r4.reused == 0 + + +def test_direct_server_core_parameters_and_model_card(): + from ignition.direct.server import _core_parameters + + lay = _core_parameter_layout(default=0.25, minimum=0.0, maximum=1.0) + body = {"messages": [{"role": "user", "content": "hi"}], "core_parameters": {"alpha": 2.0}} + before = dict(body) + assert _core_parameters(body, lay) == {"alpha": 1.0} + assert body == before + assert _core_parameters({"core_parameters": None}, lay) == {"alpha": 0.25} + assert _core_parameters({}, lay) == {"alpha": 0.25} + assert _core_parameters({"core_parameters": {"alpha": -0.0}}, lay)["alpha"] == 0.0 + for invalid in [ + {"core_parameters": []}, + {"core_parameters": {"unknown": 0.5}}, + {"core_parameters": {"alpha": True}}, + {"core_parameters": {"alpha": "0.5"}}, + {"core_parameters": {"alpha": 1e100}}, + {"core_parameters": {"alpha": 1e-100}}, + ]: + with pytest.raises(AdmissionError): + _core_parameters(invalid, lay) + + +def test_direct_core_parameter_destination_buffer_validation(): + from types import SimpleNamespace + from ignition.preparation import contract as c, runtime_core_pb2 as p + from ignition.preparation.execution import GraphSignature + + _core_parameter_layout(column=True) + with pytest.raises(ValueError): + _core_parameter_layout(tensor="some_tensor") + with pytest.raises(ValueError): + _core_parameter_layout(rows=1) + with pytest.raises(ValueError): + _core_parameter_layout(column=True, contiguity=False) + with pytest.raises(ValueError): + _core_parameter_layout(column=True, contiguity=None) + + lay = layout() + param = c.core_parameter("alpha", 0.0) + first_graph = "prefill128" + param_binding = c.binding("request_alpha", p.CORE_PARAMETER, p.REQUEST_ROW, parameter="alpha") + inputs_with = list(lay.bindings[first_graph]) + [param_binding] + inputs_plain = list(lay.bindings[first_graph]) + + class FakeTensor: + def __init__(self, arr): + self.arr, self.shape, self.dtype = arr, arr.shape, "torch.float32" + + def numel(self): + return self.arr.size + + def model(buffer, declared): + return SimpleNamespace( + server_config={ + "max_sequence_tokens": 4096, + "pages": 64, + "snapshots": 2, + "prefill_chunk_size": 512, + "model_contract": { + "vocabulary": 1000, + "cache": {"page_tokens": 256, "page_tables": [{"buffer": "page_tables", "page_offset": 0}]}, + "graphs": [{"graph": first_graph, "inputs": inputs_with if declared else inputs_plain, "state_rows_per_request": 1}], + "core_parameters": [param] if declared else [], + }, + "frontend": {"eos_token_ids": [7]}, + }, + buffers={ + "row_slot_ids": FakeTensor(np.zeros(4, dtype=np.int32)), + "page_tables": np.zeros((64, 16), dtype=np.int32), + "completion_records": np.zeros((4, 32), dtype=np.int64), + "request_alpha": buffer, + }, + signatures={first_graph: GraphSignature("prefill", 1, 128)}, + max_active=4, + ) + + backing = np.zeros(19, dtype=np.uint8) + column = backing[:16].view(np.float32).reshape(4, 1) + assert Layout.of(model(column, True)).buffer_contiguity["request_alpha"] is True + strided = np.lib.stride_tricks.as_strided(column, shape=(4, 1), strides=(5, 4)) + with pytest.raises(ValueError, match="one named FP32 value per request row"): + Layout.of(model(strided, True)) + opaque = FakeTensor(np.zeros(4, dtype=np.float32)) + with pytest.raises(ValueError, match="one named FP32 value per request row"): + Layout.of(model(opaque, True)) + assert "request_alpha" not in Layout.of(model(opaque, False)).buffer_contiguity From 9031847aacbc0037ac54c3ef854083c43b34124a Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 28 Nov 2026 14:00:14 -0800 Subject: [PATCH 08/27] helios,ignition: fix Engram reader bugs and add PLE lookahead publish Fixes #481 Why: Three defects affect Helios disk-backed and resident embedding tables, and PreparedPLELookup in core ignition lacked an advisory lookahead publish path needed for Qwen3.8's disk-backed per-layer embedding (PLE) table: 1. Multi-worker queue-depth collapse on Unix and Windows (helios/src/engram/reader.rs, helios/src/engram/reader/windows.rs) and direct Reader::warm truncation (helios/src/engram/reader.rs, helios/src/engram.rs): both Unix DiskReader and Windows Readers split the fixed DEPTH (128) slot budget evenly across workers (lane_depth = DEPTH / workers: 64, 32, or 16 for 2, 4, or 8 workers), yet both routed every batch with reads.len() <= DEPTH to lanes[0] alone. For 17-128 reads with 4 or 8 workers (including Windows' default of 4 workers), effective queue depth collapsed 4x-8x onto one lane. Separately, CachedReader::warm silently truncated &ids[..ids.len().min(self.max_rows)]; while the serving reader loop already bounds pending_warm.len() <= prefetch_max_rows <= max_rows through core validation, direct Reader::warm callers passing more than max_rows IDs silently dropped tail rows. 2. Pre-6.7 Linux EPERM on sealed resident tables (helios/src/engram/reader.rs, #481): Resident::initialize seals its O_RDWR memfd with F_SEAL_WRITE and then calls mmap(PROT_READ, MAP_SHARED) on the same O_RDWR descriptor. Linux kernels older than 6.7 reject shared mappings whose descriptor retains write permission (VM_MAYWRITE), causing --embedding-table-storage ram startup to fail with EPERM. 3. Unchecked mailbox byte-length multiplication and scored_prefill omission (helios/src/runtime_core/engram.rs, helios/src/engram.rs): validate_mailbox computed mailbox.shape[0] * 8 without overflow checking. In release builds, a malformed shape[0] such as (1 << 61) + 1 or 1 << 61 wraps to 8 or 0, bypassing validation and reaching out-of-bounds reads or pointer underflow (address + nbytes - 8) in Transfers::new and Requests::read. Both graph-kind filters in runtime_core/engram.rs also omitted "scored_prefill", diverging from engram::consumes. 4. Missing PLE advisory lookahead interface (ignition/components/ngram_delivery.py): PreparedEngramRequests exposed publish_lookahead, whereas PreparedPLELookup exposed only synchronous publish, blocking Qwen3.8 PLE recipes from using EngramTable.prefetch_buffer. What changed: - helios/src/engram/reader.rs and helios/src/engram/reader/windows.rs: - Before: both Unix DiskReader::gather and Windows Readers::gather dispatched to lanes[0] whenever reads.len() <= DEPTH (128). - After: both call shared helper lane_fanout(reads, lanes), which compares reads against DEPTH / lanes and fans across reads.div_ceil(lane_depth) .min(lanes) active lanes with reads.div_ceil(active_lanes) reads per lane. - Before: CachedReader::warm truncated &ids[..ids.len().min(self.max_rows)] and accounted only for the truncated prefix. - After: CachedReader::warm processes ids.chunks(self.max_rows) and increments prefetch_rows_loaded per completed chunk. - Before: ResidentMapping::new mapped file.as_raw_fd() directly for read-only remaps. - After: on Linux when !writable, ResidentMapping::new reopens /proc/self/fd/ read-only (O_RDONLY | O_CLOEXEC) for mmap, falls back to file.as_raw_fd() if procfs is unavailable, and includes any reopen io::Error alongside a pre-6.7 kernel hint if mmap returns EPERM. - helios/src/engram.rs: - Before: ReaderAction::Warm sliced by WARM_BATCH_ROWS (1024) directly, and Transfers::new subtracted 8/16 from nbytes without capacity checks. - After: ReaderAction::Warm caps its batch size to WARM_BATCH_ROWS.min(max_tokens * heads).max(1), and Transfers::new verifies checked minimum byte sizes for both request and prefetch mailboxes before computing flag and count addresses. - helios/src/runtime_core/engram.rs: - Before: validate_mailbox used unchecked shape[0] * 8, did not check MappedHost allocation bounds against offset + nbytes, and skipped "scored_prefill" in both graph-kind filters. - After: uses checked_mul(8) and checked_add, verifies offset + nbytes fits inside the named MappedHost allocation, and includes "scored_prefill" in both graph-kind filters. - ignition/components/ngram_delivery.py: - Before: PreparedPLELookup exposed only publish. - After: adds PreparedPLELookup.publish_lookahead(ids, count, step), writing row IDs, row count (nbytes - 16), and sequence flag (nbytes - 8) into a prepared lookahead buffer during graph capture. Claimed benefit and result: - Expected: eliminates pre-6.7 Linux EPERM startup failure for resident RAM tables (#481), restores multi-worker NVMe queue depth for 17-128 read batches on both Unix io_uring and Windows I/O rings, prevents release-build u64 overflow and allocation overrun in mailbox loading, aligns scored_prefill validation with engram::consumes, and unblocks disk-backed PLE lookahead prefetch in Qwen3.8 recipes. - Measured (strictly attributable to PreparedPLELookup.publish_lookahead paired with the companion Qwen3.8 recipe change in local-inference-lab/hyperflare-recipes#87, not to the reader or validator fixes): on Qwen3.8-Flash-Next-NVFP4-MXFP8-CSF-QAD TP1 on RTX PRO 6000 Blackwell (SM120, /dev/md0 NVMe RAID, exported core gb202-tp1-202611282155, --embedding-table-storage disk --embedding-table-cache-size 4GiB --embedding-table-resident-scales --embedding-table-workers 1), synchronous PLE gather time dropped 76.5% (0.881 s -> 0.207 s; row-cache hit 43.1% -> 94.7%) and cold 111,915-token TTFT dropped 4.6% (7.778 s -> 7.418 s; 14,388 -> 15,087 tok/s) with flare_engram_prefetch_errors_total = 0 and 4/4 needle-in-a-haystack passkey matches. Supporting evidence and material limitations: - cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- engram: 45 passed, 0 failed (covers lane_fanout across 1/2/4/8 workers, Unix io_uring multi-lane fan-out for 80 reads below DEPTH, chunked CachedReader::warm past max_rows, /proc/self/fd read-only remap with F_GETFL == O_RDONLY and mprotect EACCES, u64 mailbox overflow and MappedHost overrun rejection, and scored_prefill validation). - cargo test --locked --release --manifest-path flare/Cargo.toml: 228 + 7 + 1 passed, 0 failed, 4 ignored. - cargo check --locked --release --manifest-path heliopause/Cargo.toml: clean. - cargo clippy --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib --tests: 0 warnings in modified lines. - pytest tests/preparation/test_core_boundary.py tests/cli -q: 137 passed. - Limitations: - The paired Qwen3.8 served benchmark ran at --embedding-table-workers 1, which bypasses multi-worker fan-out; multi-worker QD fan-out, pre-6.7 EPERM handling, and u64/scored_prefill validation are verified by unit tests rather than exercised by that served run. - Pre-6.7 Linux EPERM handling was verified on Linux 6.18 via F_GETFL == O_RDONLY and mprotect EACCES rather than on a kernel older than 6.7. - Windows compilation and runtime I/O ring execution were not run on this Linux host; Windows shares the unit-tested lane_fanout planner with Unix. Design-Signed-Off-By: Antigravity (Gemini); design-review=c3a9 Signed-off-by: Luke Alonso --- helios/src/engram.rs | 24 +- helios/src/engram/reader.rs | 368 +++++++++++++++++++++----- helios/src/engram/reader/windows.rs | 13 +- helios/src/runtime_core/engram.rs | 133 ++++++++-- ignition/components/ngram_delivery.py | 29 ++ 5 files changed, 464 insertions(+), 103 deletions(-) diff --git a/helios/src/engram.rs b/helios/src/engram.rs index 5c260a336..5968904a5 100644 --- a/helios/src/engram.rs +++ b/helios/src/engram.rs @@ -549,6 +549,9 @@ impl Shared { } else { 0 }; + let warm_batch = WARM_BATCH_ROWS + .min(max_tokens.saturating_mul(table.heads)) + .max(1); let worker = thread::Builder::new() .name(format!("flare-{}", table.event)) .spawn(move || { @@ -608,7 +611,7 @@ impl Shared { buffers.signal(job.generation); } ReaderAction::Warm => { - let end = (warm_cursor + WARM_BATCH_ROWS).min(pending_warm.len()); + let end = (warm_cursor + warm_batch).min(pending_warm.len()); // Advisory warming is best-effort and never poisons a staging frame. let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe( || reader.warm(&planes, &pending_warm[warm_cursor..end]), @@ -779,6 +782,16 @@ impl Transfers { .as_deref() .map(|name| { let (address, nbytes) = resolve_mailbox(name)?; + let required = binding + .shared + .max_tokens + .checked_mul(table.heads) + .and_then(|rows| rows.checked_add(1)) + .and_then(|slots| slots.checked_mul(std::mem::size_of::())) + .ok_or("n-gram request mailbox exceeds host range")?; + if nbytes < required { + return Err("n-gram request mailbox is smaller than staged capacity".into()); + } Ok::<_, Error>((address, address + nbytes - 8)) }) .transpose()?; @@ -787,6 +800,15 @@ impl Transfers { .as_ref() .map(|(name, max_rows)| { let (address, nbytes) = resolve_mailbox(name)?; + let required = max_rows + .checked_add(2) + .and_then(|slots| slots.checked_mul(std::mem::size_of::())) + .ok_or("n-gram prefetch mailbox exceeds host range")?; + if nbytes < required { + return Err( + "n-gram prefetch mailbox is smaller than declared capacity".into(), + ); + } Ok::<_, Error>(AdvisoryMailbox { address, count: address + nbytes - 16, diff --git a/helios/src/engram/reader.rs b/helios/src/engram/reader.rs index bfe1abb66..ac48d8c1c 100644 --- a/helios/src/engram/reader.rs +++ b/helios/src/engram/reader.rs @@ -34,6 +34,21 @@ const PARALLEL_GATHER_MIN_ROWS: usize = 2048; const MAX_GATHER_THREADS: usize = 16; const PREFETCH_DISTANCE: usize = 8; +/// Returns `(active_lanes, reads_per_lane)` when a read batch exceeds one lane's queue depth. +/// Each worker owns `DEPTH / lanes` slots, so fanning out once `reads > lane_depth` preserves +/// full multi-worker queue depth for batches up to `DEPTH` reads. +fn lane_fanout(reads: usize, lanes: usize) -> Option<(usize, usize)> { + if lanes <= 1 { + return None; + } + let lane_depth = DEPTH / lanes; + if reads <= lane_depth { + return None; + } + let active_lanes = reads.div_ceil(lane_depth).min(lanes); + Some((active_lanes, reads.div_ceil(active_lanes))) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Plane { pub file: usize, @@ -105,32 +120,78 @@ struct ResidentMapping { #[cfg(unix)] impl ResidentMapping { - fn new(file: &File, nbytes: usize, writable: bool) -> Result { - let protection = libc::PROT_READ | if writable { libc::PROT_WRITE } else { 0 }; + #[cfg(target_os = "linux")] + fn open_readonly_view(file: &File) -> std::io::Result { + File::open(format!("/proc/self/fd/{}", file.as_raw_fd())) + } + + fn map_fd(fd: std::os::fd::RawFd, nbytes: usize, protection: i32) -> std::io::Result { let address = unsafe { libc::mmap( std::ptr::null_mut(), nbytes, protection, libc::MAP_SHARED, - file.as_raw_fd(), + fd, 0, ) }; if address == libc::MAP_FAILED { - return Err(format!( - "map resident embedding table: {}", - std::io::Error::last_os_error() - ) - .into()); + Err(std::io::Error::last_os_error()) + } else { + Ok(address as usize) } - let mapping = Self { - address: address as usize, - nbytes, + } + + fn new(file: &File, nbytes: usize, writable: bool) -> Result { + let protection = libc::PROT_READ | if writable { libc::PROT_WRITE } else { 0 }; + // Linux kernels prior to 6.7 refuse `MAP_SHARED | PROT_READ` on a write-sealed + // memfd through an `O_RDWR` descriptor because the VMA retains `VM_MAYWRITE`. + // Reopening `/proc/self/fd/` read-only yields a file description without + // write permission so the mapping succeeds on every kernel while referencing + // the same sealed backing pages. + #[cfg(target_os = "linux")] + let (readonly_view, reopen_error) = if !writable { + match Self::open_readonly_view(file) { + Ok(ro) => (Some(ro), None), + Err(error) => (None, Some(error)), + } + } else { + (None, None) }; + #[cfg(target_os = "linux")] + let map_fd = readonly_view + .as_ref() + .map_or(file.as_raw_fd(), |ro| ro.as_raw_fd()); + #[cfg(not(target_os = "linux"))] + let map_fd = file.as_raw_fd(); + + let address = Self::map_fd(map_fd, nbytes, protection).map_err(|error| { + #[cfg(target_os = "linux")] + if !writable && error.raw_os_error() == Some(libc::EPERM) { + return match &reopen_error { + Some(reopen) => format!( + "map resident embedding table: {error} (/proc/self/fd reopen failed: {reopen}; kernels older than 6.7 require a read-only fd to map a write-sealed memfd)" + ), + None => format!( + "map resident embedding table: {error} (kernels older than 6.7 require /proc/self/fd to map a write-sealed memfd read-only)" + ), + }; + } + format!("map resident embedding table: {error}") + })?; + let mapping = Self { address, nbytes }; // The sealed read-only remap has its own page tables, even after loading // populated the backing RAM. Prepare them before row delivery starts. - if !writable && unsafe { libc::madvise(address, nbytes, libc::MADV_POPULATE_READ) } != 0 { + if !writable + && unsafe { + libc::madvise( + address as *mut libc::c_void, + nbytes, + libc::MADV_POPULATE_READ, + ) + } != 0 + { let error = std::io::Error::last_os_error(); return Err(format!("populate resident embedding page tables: {error}").into()); } @@ -746,14 +807,11 @@ impl DiskReader { address: output.as_mut_ptr() as usize, len: output.len(), }; - if self.lanes.len() == 1 || self.reads.len() <= DEPTH { - self.lanes[0].gather(&self.reads, &self.fragments, output, &self.stats)?; - } else { - let chunk = self.reads.len().div_ceil(self.lanes.len()); + if let Some((active_lanes, chunk)) = lane_fanout(self.reads.len(), self.lanes.len()) { let fragments = &self.fragments; let stats = &self.stats; std::thread::scope(|scope| { - let (local, helpers) = self.lanes.split_first_mut().unwrap(); + let (local, helpers) = self.lanes[..active_lanes].split_first_mut().unwrap(); let mut jobs = self.reads.chunks(chunk); let first = jobs.next().unwrap(); let mut joins = Vec::with_capacity(helpers.len()); @@ -778,6 +836,8 @@ impl DiskReader { } result })?; + } else { + self.lanes[0].gather(&self.reads, &self.fragments, output, &self.stats)?; } } #[cfg(windows)] @@ -1037,55 +1097,62 @@ impl CachedReader { fn warm(&mut self, planes: &[Plane; 2], ids: &[i64]) -> Result { let [weights, scales] = planes.map(|plane| plane.row_bytes); let limit = planes[0].nbytes / weights; - let ids = &ids[..ids.len().min(self.max_rows)]; - self.miss_ids.clear(); - for &id in ids { - if id >= 0 && (id as usize) < limit { - self.miss_ids.push(id); + let mut total_loaded = 0usize; + for chunk in ids.chunks(self.max_rows) { + self.miss_ids.clear(); + for &id in chunk { + if id >= 0 && (id as usize) < limit { + self.miss_ids.push(id); + } } - } - if self.miss_ids.is_empty() { - return Ok(0); - } - self.miss_ids.sort_unstable(); - self.miss_ids.dedup(); - let mut misses = 0usize; - for index in 0..self.miss_ids.len() { - let id = self.miss_ids[index]; - if !self.cache.pin_if_present(id) { - self.miss_ids[misses] = id; - misses += 1; + if self.miss_ids.is_empty() { + continue; } + self.miss_ids.sort_unstable(); + self.miss_ids.dedup(); + let mut misses = 0usize; + for index in 0..self.miss_ids.len() { + let id = self.miss_ids[index]; + if !self.cache.pin_if_present(id) { + self.miss_ids[misses] = id; + misses += 1; + } + } + self.miss_ids.truncate(misses); + if self.miss_ids.is_empty() { + continue; + } + let count = self.miss_ids.len(); + self.disk.gather( + planes, + &self.miss_ids, + &mut self.miss_output[..count * (weights + scales)], + )?; + let mut added = 0u64; + let mut evicted = 0u64; + for (index, &id) in self.miss_ids.iter().enumerate() { + let w = &self.miss_output[index * weights..(index + 1) * weights]; + let s = &self.miss_output + [count * weights + index * scales..count * weights + (index + 1) * scales]; + let inserted = self.cache.insert_advisory(id, w, s); + added += u64::from(inserted.added); + evicted += u64::from(inserted.evicted); + } + self.disk + .stats + .resident_rows + .fetch_add(added, Ordering::Relaxed); + self.disk + .stats + .evictions + .fetch_add(evicted, Ordering::Relaxed); + self.disk + .stats + .prefetch_rows_loaded + .fetch_add(count as u64, Ordering::Relaxed); + total_loaded += count; } - self.miss_ids.truncate(misses); - if self.miss_ids.is_empty() { - return Ok(0); - } - let count = self.miss_ids.len(); - self.disk.gather( - planes, - &self.miss_ids, - &mut self.miss_output[..count * (weights + scales)], - )?; - let mut added = 0u64; - let mut evicted = 0u64; - for (index, &id) in self.miss_ids.iter().enumerate() { - let w = &self.miss_output[index * weights..(index + 1) * weights]; - let s = &self.miss_output - [count * weights + index * scales..count * weights + (index + 1) * scales]; - let inserted = self.cache.insert_advisory(id, w, s); - added += u64::from(inserted.added); - evicted += u64::from(inserted.evicted); - } - self.disk - .stats - .resident_rows - .fetch_add(added, Ordering::Relaxed); - self.disk - .stats - .evictions - .fetch_add(evicted, Ordering::Relaxed); - Ok(count) + Ok(total_loaded) } } @@ -1244,12 +1311,7 @@ impl Reader { return Ok(0); }; match reader.warm(planes, ids) { - Ok(loaded) => { - self.stats - .prefetch_rows_loaded - .fetch_add(loaded as u64, Ordering::Relaxed); - Ok(loaded) - } + Ok(loaded) => Ok(loaded), Err(error) => { self.stats.prefetch_errors.fetch_add(1, Ordering::Relaxed); Err(error) @@ -2124,4 +2186,172 @@ mod tests { assert_eq!(still_warm, expected); std::fs::remove_file(path).unwrap(); } + + #[test] + fn advisory_warm_chunks_ids_exceeding_workspace_max_rows() { + let path = std::env::temp_dir().join(format!( + "helios-engram-warm-chunked-{}.bin", + std::process::id() + )); + let rows = 64; + let first = 4096; + let second = first + rows * 80; + let bytes: Vec = (0..second + rows * 10) + .map(|i| (i * 29 + i / 61) as u8) + .collect(); + std::fs::write(&path, &bytes).unwrap(); + let planes = [ + Plane { + file: 0, + offset: first as u64, + nbytes: rows * 80, + row_bytes: 80, + }, + Plane { + file: 0, + offset: second as u64, + nbytes: rows * 10, + row_bytes: 10, + }, + ]; + let stats = Arc::new(Stats::default()); + // Workspace max_rows = 8, but warm receives 24 unique IDs (3 workspace chunks). + let mut reader = Reader::open(&path, &planes, false, 128 << 10, 8, stats.clone()).unwrap(); + let ids: Vec = (0..24).collect(); + let loaded = reader.warm(&planes, &ids).unwrap(); + assert_eq!(loaded, 24); + assert_eq!(stats.prefetch_rows_loaded.load(Ordering::Relaxed), 24); + let reads_after_warm = stats.disk_reads.load(Ordering::Relaxed); + for chunk in ids.chunks(8) { + let mut output = vec![0u8; chunk.len() * 90]; + reader.gather(&planes, chunk, &mut output).unwrap(); + } + // Every chunk after the first 8 rows must hit the cache with zero extra disk reads. + assert_eq!(stats.disk_reads.load(Ordering::Relaxed), reads_after_warm); + assert_eq!(stats.hits.load(Ordering::Relaxed), 24); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn lane_fanout_scales_workers_from_per_lane_depth() { + assert_eq!(lane_fanout(0, 1), None); + assert_eq!(lane_fanout(256, 1), None); + assert_eq!(lane_fanout(64, 2), None); + assert_eq!(lane_fanout(65, 2), Some((2, 33))); + assert_eq!(lane_fanout(32, 4), None); + assert_eq!(lane_fanout(33, 4), Some((2, 17))); + assert_eq!(lane_fanout(65, 4), Some((3, 22))); + assert_eq!(lane_fanout(128, 4), Some((4, 32))); + assert_eq!(lane_fanout(16, 8), None); + assert_eq!(lane_fanout(17, 8), Some((2, 9))); + assert_eq!(lane_fanout(80, 8), Some((5, 16))); + assert_eq!(lane_fanout(256, 8), Some((8, 32))); + } + + #[test] + #[cfg(unix)] + fn unix_disk_reader_fans_out_when_reads_exceed_single_lane_depth_below_total_depth() { + let path = std::env::temp_dir().join(format!( + "helios-engram-qd-fanout-{}.bin", + std::process::id() + )); + let rows = 28000; + let first = 4096; + let second = first + rows * 256; + let bytes: Vec = (0..second + rows * 8) + .map(|i| (i * 17 + i / 251) as u8) + .collect(); + std::fs::write(&path, &bytes).unwrap(); + let planes = [ + Plane { + file: 0, + offset: first as u64, + nbytes: rows * 256, + row_bytes: 256, + }, + Plane { + file: 0, + offset: second as u64, + nbytes: rows * 8, + row_bytes: 8, + }, + ]; + // Stride 300 rows = 76.8 KiB (> 64 KiB CHUNK). With resident scales, 80 IDs + // produce 80 reads: above lane_depth = 32 (workers = 4) and 16 (workers = 8), + // yet <= DEPTH (128). + let ids: Vec = (0..80).map(|i| (i * 300) as i64).collect(); + let mut expected = Vec::with_capacity(ids.len() * 264); + for plane in &planes { + for &id in &ids { + let start = plane.offset as usize + id as usize * plane.row_bytes; + expected.extend_from_slice(&bytes[start..start + plane.row_bytes]); + } + } + let files = [Arc::new(open_file(&path).unwrap())]; + for workers in [2, 4, 8] { + let stats = Arc::new(Stats::default()); + let mut reader = Reader::from_files( + &files, + &planes, + false, + 0, + ids.len(), + stats.clone(), + workers, + true, + ) + .unwrap(); + let mut actual = vec![0xA5u8; expected.len()]; + reader.gather(&planes, &ids, &mut actual).unwrap(); + assert_eq!(actual, expected, "worker count {workers} corrupted rows"); + assert_eq!(stats.disk_reads.load(Ordering::Relaxed), 80); + // Helper lanes must have executed reads (their slot_read table was populated). + if let Data::Disk(disk) = &reader.data { + let used_lanes = disk + .lanes + .iter() + .filter(|lane| lane.slot_read.iter().any(|&idx| idx > 0)) + .count(); + let lane_depth = DEPTH / workers; + let expected_lanes = 80usize.div_ceil(lane_depth).min(workers); + assert_eq!( + used_lanes, expected_lanes, + "workers={workers} should fan out across {expected_lanes} lanes for 80 reads" + ); + } + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + #[cfg(target_os = "linux")] + fn sealed_resident_readonly_mapping_drops_write_capability_via_proc_reopen() { + let file = unsealed_resident_file(); + { + let writable = ResidentMapping::new(&file, BLOCK, true).unwrap(); + unsafe { std::ptr::write_bytes(writable.address as *mut u8, 0x5C, BLOCK) }; + } + seal_resident(&file).unwrap(); + + let ro = ResidentMapping::open_readonly_view(&file).unwrap(); + let flags = unsafe { libc::fcntl(ro.as_raw_fd(), libc::F_GETFL) }; + assert_eq!(flags & libc::O_ACCMODE, libc::O_RDONLY); + + let mapping = ResidentMapping::new(&file, BLOCK, false).unwrap(); + let slice = unsafe { std::slice::from_raw_parts(mapping.address as *const u8, BLOCK) }; + assert_eq!(slice, &[0x5C; BLOCK]); + // Without VM_MAYWRITE, upgrading the mapping to PROT_WRITE fails with EACCES. + let rc = unsafe { + libc::mprotect( + mapping.address as *mut libc::c_void, + BLOCK, + libc::PROT_READ | libc::PROT_WRITE, + ) + }; + assert_eq!(rc, -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EACCES) + ); + } } diff --git a/helios/src/engram/reader/windows.rs b/helios/src/engram/reader/windows.rs index f584cdbcb..6b630dd8d 100644 --- a/helios/src/engram/reader/windows.rs +++ b/helios/src/engram/reader/windows.rs @@ -6,7 +6,7 @@ //! Windows disk readers share a fixed staging and queue budget across workers. -use super::{Aligned, CHUNK, DEPTH, DiskTimings, Fragment, Read, Stats}; +use super::{Aligned, CHUNK, DEPTH, DiskTimings, Fragment, Read, Stats, lane_fanout}; use crate::{Result, os::ioring::ReadRing}; use std::{ fs::File, @@ -86,14 +86,13 @@ impl Readers { address: output.as_mut_ptr() as usize, len: output.len(), }; - // Small gathers stay on the existing delivery thread. Large gathers use - // scoped helpers; their startup cost is included in measured gather time. - if self.lanes.len() == 1 || reads.len() <= DEPTH { + // Small gathers that fit inside one lane's queue depth stay on the delivery thread. + // Larger gathers fan out across only as many helper lanes as needed. + let Some((active_lanes, chunk)) = lane_fanout(reads.len(), self.lanes.len()) else { return self.lanes[0].gather(reads, fragments, output, stats); - } - let chunk = reads.len().div_ceil(self.lanes.len()); + }; std::thread::scope(|scope| { - let (local, helpers) = self.lanes.split_first_mut().unwrap(); + let (local, helpers) = self.lanes[..active_lanes].split_first_mut().unwrap(); let mut jobs = reads.chunks(chunk); let first = jobs.next().unwrap(); let mut joins = Vec::with_capacity(helpers.len()); diff --git a/helios/src/runtime_core/engram.rs b/helios/src/runtime_core/engram.rs index c55d85175..08fe8e248 100644 --- a/helios/src/runtime_core/engram.rs +++ b/helios/src/runtime_core/engram.rs @@ -11,6 +11,7 @@ use super::{ use crate::{ Result, engram::{Index, Plane, Table}, + execution::GraphKind, }; use std::collections::HashSet; @@ -220,12 +221,7 @@ pub(super) fn decode( let tokens = execution .graphs .iter() - .filter(|g| { - matches!( - g.kind.as_str(), - "prefill" | "terminal_prefill" | "decode" | "speculative" | "mixed" - ) - }) + .filter(|g| GraphKind::try_from(g.kind.as_str()).is_ok_and(crate::engram::consumes)) .map(|g| g.packed_tokens()) .max() .ok_or_else(|| invalid("Engram catalog lacks consumers"))?; @@ -243,17 +239,19 @@ pub(super) fn decode( return Err(invalid("invalid Engram staged head width")); } table_heads = core_heads; + let max_staged_rows = tokens + .checked_mul(core_heads as u64) + .ok_or_else(|| invalid("Engram staging row count overflow"))?; let validate_buffer = |buffer: &wire::Buffer, dtype: &str, rows: u64, columns: u64| { + let expected_nbytes = columns + .checked_mul(if dtype == "int64" { 8 } else { 1 }) + .and_then(|row_bytes| buffer.shape[0].checked_mul(row_bytes)); if buffer.dtype != dtype || buffer.shape.len() != 2 || buffer.shape[0] < rows || buffer.shape[1] != columns || buffer.strides != [columns, 1] - || buffer.nbytes - != buffer - .shape[0] - .checked_mul(columns * if dtype == "int64" { 8 } else { 1 }) - .unwrap_or(0) + || expected_nbytes != Some(buffer.nbytes) { return Err(invalid("invalid Engram buffer layout")); } @@ -269,7 +267,7 @@ pub(super) fn decode( .iter() .find(|b| &b.name == name) .ok_or_else(|| invalid("rank lacks Engram input buffer"))?; - validate_buffer(buffer, dtype, tokens * core_heads as u64, columns)?; + validate_buffer(buffer, dtype, max_staged_rows, columns)?; } let validate_mailbox = |name: &str, min_len: u64, max_len: Option, label: &str| { let mailbox = execution @@ -286,32 +284,40 @@ pub(super) fn decode( || mailbox.strides != [1] || mailbox.shape[0] < min_len || max_len.is_some_and(|limit| mailbox.shape[0] > limit) - || mailbox.nbytes != mailbox.shape[0] * 8 + || mailbox.shape[0].checked_mul(8) != Some(mailbox.nbytes) || !reference.offset.is_multiple_of(8) || !core.allocations.iter().any(|a| { - a.name == reference.allocation && matches!(a.memory, Memory::MappedHost) + a.name == reference.allocation + && matches!(a.memory, Memory::MappedHost) + && reference + .offset + .checked_add(mailbox.nbytes) + .is_some_and(|end| end <= a.nbytes as u64) }) { return Err(invalid(format!("invalid mapped {label}"))); } Ok(mailbox.shape[0]) }; - let max_staged_rows = tokens - .checked_mul(core_heads as u64) - .ok_or_else(|| invalid("Engram staging row count overflow"))?; if gpu { + let min_request_len = max_staged_rows + .checked_add(1) + .ok_or_else(|| invalid("Engram request mailbox length overflow"))?; validate_mailbox( &table.request_buffer, - max_staged_rows + 1, + min_request_len, None, "n-gram request mailbox", )?; } if has_prefetch { + let max_prefetch_len = max_staged_rows + .checked_add(2) + .ok_or_else(|| invalid("Engram prefetch mailbox length overflow"))?; let len = validate_mailbox( &table.prefetch_buffer, 3, - Some(max_staged_rows + 2), + Some(max_prefetch_len), "n-gram prefetch mailbox", )?; let cap = usize::try_from(len - 2) @@ -321,16 +327,19 @@ pub(super) fn decode( } prefetch_max_rows = cap; } - for graph in execution.graphs.iter().filter(|g| { - matches!( - g.kind.as_str(), - "prefill" | "terminal_prefill" | "decode" | "speculative" | "mixed" - ) - }) { + for graph in execution + .graphs + .iter() + .filter(|g| GraphKind::try_from(g.kind.as_str()).is_ok_and(crate::engram::consumes)) + { + let needed_bytes = graph + .packed_tokens() + .checked_mul(core_heads as u64) + .and_then(|rows| rows.checked_mul(8)); if !gpu && !graph.input_bindings.iter().any(|b| { b.buffer_name == table.hash_buffer - && b.nbytes >= graph.packed_tokens() * core_heads as u64 * 8 + && needed_bytes.is_some_and(|need| b.nbytes >= need) }) { return Err(invalid("Engram graph lacks hash input binding")); @@ -707,4 +716,76 @@ mod tests { let (_, core_b) = make(200); assert!(decode(cat_a, &archive, &[core_a, core_b], 0, 4).is_err()); } + + #[test] + fn mailbox_validation_rejects_u64_byte_length_overflow_and_allocation_overrun() { + let archive = StubFiles::new(); + // shape[0] = (1 << 61) + 1 wraps `shape[0] * 8` to 8; shape[0] = 1 << 61 wraps to 0. + for (bad_shape, wrapped_nbytes) in [((1u64 << 61) + 1, 8u64), (1u64 << 61, 0u64)] { + let (catalog, mut core) = decode_fixture(4, 6, true, true); + let mailbox = core + .execution + .as_mut() + .unwrap() + .buffers + .iter_mut() + .find(|b| b.name == "engram_1_requests") + .unwrap(); + mailbox.shape = vec![bad_shape]; + mailbox.nbytes = wrapped_nbytes; + assert!( + decode(catalog, &archive, &[core], 0, 4).is_err(), + "overflowing mailbox shape {bad_shape} must be rejected" + ); + } + + // Valid shape/nbytes that overruns its MappedHost allocation via offset must reject. + let (catalog, mut core) = decode_fixture(4, 6, true, true); + let mailbox = core + .execution + .as_mut() + .unwrap() + .buffers + .iter_mut() + .find(|b| b.name == "engram_1_requests") + .unwrap(); + mailbox.reference.as_mut().unwrap().offset = 8; + assert!(decode(catalog, &archive, &[core], 0, 4).is_err()); + } + + #[test] + fn scored_prefill_graphs_participate_in_capacity_and_hash_binding_validation() { + let archive = StubFiles::new(); + // Host-hashed catalog containing only scored_prefill must be accepted when bound... + let (catalog, mut core) = decode_fixture(1, 24, false, false); + core.execution.as_mut().unwrap().graphs[0].kind = "scored_prefill".into(); + assert!(decode(catalog, &archive, &[core], 0, 1).is_ok()); + + // ...and rejected if the scored_prefill graph lacks its hash input binding. + let (catalog, mut missing_binding) = decode_fixture(1, 24, false, false); + missing_binding.execution.as_mut().unwrap().graphs[0].kind = "scored_prefill".into(); + missing_binding.execution.as_mut().unwrap().graphs[0] + .input_bindings + .clear(); + assert!(decode(catalog, &archive, &[missing_binding], 0, 1).is_err()); + + // A scored_prefill graph wider than decode must increase the required staging capacity. + let (gpu_cat, mut gpu_core) = decode_fixture(4, 6, true, true); + gpu_core + .execution + .as_mut() + .unwrap() + .graphs + .push(wire::ExecutionGraph { + name: "scored_prefill256".into(), + kind: "scored_prefill".into(), + batch_capacity: 1, + token_capacity: 256, + packed_token_capacity: 256, + input_bindings: vec![], + ..Default::default() + }); + // Fixture buffers are sized for 128 tokens, so adding a 256-token scored_prefill must reject. + assert!(decode(gpu_cat, &archive, &[gpu_core], 0, 4).is_err()); + } } diff --git a/ignition/components/ngram_delivery.py b/ignition/components/ngram_delivery.py index 41730c95e..939d6df0d 100644 --- a/ignition/components/ngram_delivery.py +++ b/ignition/components/ngram_delivery.py @@ -75,6 +75,26 @@ def _requests_fake(token_ids, query_start, history, num_seqs, num_tokens, multip pass +@torch.library.custom_op("flare::ple_advisory_requests", mutates_args=("ids", "requests", "mailbox")) +def _advisory_requests(token_ids: torch.Tensor, query_start: torch.Tensor, history: torch.Tensor, + num_seqs: torch.Tensor, num_tokens: torch.Tensor, multipliers: torch.Tensor, + primes: torch.Tensor, offsets: torch.Tensor, ids: torch.Tensor, + requests: torch.Tensor, live_rows: torch.Tensor, mailbox: torch.Tensor, + sequence: torch.Tensor, plan: int) -> None: + state = require_prepared(plan_from_handle(plan), "sequence.ple_embedding", ids.device) + state.hash_state.run_tensors(token_ids, query_start, history, num_seqs, num_tokens, + multipliers, primes, offsets, ids, requests, token_count=ids.shape[0]) + n = ids.numel() + _copy_requests[(triton.cdiv(n, 256),)](ids, live_rows, mailbox, n, 256, True) + _publish[(1,)](mailbox, live_rows, sequence, mailbox.numel() - 1, True) + + +@_advisory_requests.register_fake +def _advisory_requests_fake(token_ids, query_start, history, num_seqs, num_tokens, multipliers, + primes, offsets, ids, requests, live_rows, mailbox, sequence, plan): + pass + + @torch.library.custom_op("flare::staged_ple", mutates_args=("out", "timings", "barrier_output")) def _lookup(source: torch.Tensor, weight: torch.Tensor, scales: torch.Tensor, scale: torch.Tensor, ids: torch.Tensor, count: torch.Tensor, out: torch.Tensor, @@ -134,6 +154,15 @@ def publish(self, metadata=None): g.multipliers, g.prime_sizes, g.table_offsets, self.ids, requests, self.mailbox, self.sequence, self.plan.handle) + def publish_lookahead(self, token_ids, query_start, history, num_seqs, num_tokens, live_rows, mailbox): + """Hash an upcoming prompt window during graph capture and publish to an advisory mailbox.""" + g = self.geometry + ids = torch.empty_like(self.ids) + requests = torch.empty(self.ids.shape[0], dtype=torch.int32, device=self.ids.device) + _advisory_requests(token_ids, query_start, history, num_seqs, num_tokens, + g.multipliers, g.prime_sizes, g.table_offsets, + ids, requests, live_rows, mailbox, self.sequence, self.plan.handle) + def __call__(self, source, metadata=None): metadata = self.metadata if metadata is None else metadata output = self.output From f5ce55348e3da55c209552e5b49eb658ce839718 Mon Sep 17 00:00:00 2001 From: eugr Date: Sat, 28 Nov 2026 17:38:07 -0800 Subject: [PATCH 09/27] Manage prepared core updates in WinUI (#591) * feat(winui): manage prepared core updates WinUI can identify installed Hugging Face cores from the acquisition records in the shared cache. The library previously offered to run the installed version and left users to check for publisher updates and manage retained versions outside the desktop app. The desktop controller now checks recorded Hub revisions and compares each available commit with the deployments already installed. The WinUI bridge carries the result to the Update action and the launch prompt. An approved update passes the displayed commit and recorded file and tensor-parallel selection to shared acquisition. Successful verification selects that version. Library cards show the installed version and its commit date or cache creation date, mark earlier entries for the same build, and confirm deletion through the cache's existing lease-aware removal operation. Users can discover and install a prepared-core update from WinUI, choose which retained version to run, and remove one version while other entries retain their shared payloads. On Windows ARM64, the Flare and WinUI bridge tests passed. A local Hub fixture verified acquisition of the approved commit and separation of installed and available update dates. Signed cache fixtures verified duplicate-offer suppression and that removal and collection preserved the retained deployment. The ARM64 Release build and embedded bundle extraction passed. CLI integration tests passed. Two CLI doctor unit tests failed because Windows rejects their Linux sysfs fixture names. The legacy core fixture checks and a live update followed by GPU serving were unrun. * Show the newest cached core on Home and report CLI updates Home used inventory order to choose which cached version to show. The CLI listed local versions without showing whether the tracked Hugging Face revision had changed. Both interfaces can use the acquisition record to identify the installed commit and the tracked revision. Choose the newest readable cached version for Home using the cache timestamp and numeric collision suffix. Share Hub revision lookups and the installed deployment check with flare models list. The CLI reports both dates, displays unknown results when metadata is unavailable, and accepts --offline to skip lookups. The Library styles its Delete button red in the standard theme and uses system colors in high contrast. Home shows one cached version per model. Terminal users can distinguish an available update from a revision already represented in the cache. On Windows ARM64, the Flare tests covered Home selection and distinct dates for the installed and available commits. The CLI smoke check listed both Inkling 2 Mini revisions, suppressed the offer for the installed update, and returned the same inventory offline. WinUI bridge and launcher tests passed, and the Release app packaged successfully. The first shared test run hit a Windows file-replacement error in an existing fixture. The repeat passed. CLI integration tests passed after the full run reproduced two doctor failures caused by Linux sysfs fixture filenames that Windows rejects. The Delete colors passed contrast checks. Interactive WinUI verification was unrun. Design-Signed-Off-By: Codex (GPT-6); design-review=c3a9 Signed-off-by: Eugene Rakhmatulin --- docs/cli-design.md | 8 +- flare-cli/src/cache_commands.rs | 40 ++- flare-cli/src/cli.rs | 6 + flare-winui/Dashboard.inl | 18 +- flare-winui/Details.inl | 12 +- flare-winui/README.md | 26 +- flare-winui/Theme.xaml.h | 26 ++ flare-winui/bridge/include/flare.h | 13 +- flare-winui/bridge/src/lib.rs | 106 ++++++ flare-winui/main.cpp | 187 ++++++++++- flare/src/application.rs | 4 + flare/src/controller.rs | 517 +++++++++++++++++++++++++++-- flare/src/hub.rs | 439 ++++++++++++++++++++++-- 13 files changed, 1323 insertions(+), 79 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index d90ceb0ff..6feab2035 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1884,7 +1884,7 @@ is an error. If the default `cores` directory does not exist and moving files. The CLI and desktop use the same resolution. ```sh -flare models list [MODEL] [--json] +flare models list [MODEL] [--json] [--offline] flare models inspect CORE|MODEL[@VERSION] [inspection flags] flare models download REPOSITORY [download flags] flare models select MODEL@VERSION @@ -2071,6 +2071,12 @@ tensor-parallel size and serving capacities, and distinct storage figures: `list` metadata is explicitly unverified: it decodes the manifest to report identity, deployments, and capacities without claiming authentication. +For downloaded versions with acquisition records, `list` checks Hugging Face +revision metadata. It reports `installed_updated_at` for the installed commit +and `update_available` for the tracked revision. An available update also has +`update_commit` and `update_updated_at` when the Hub reports a date. A matching +deployment already in the cache suppresses the offer. `--offline` skips Hub +lookups. Dates and uncompleted update checks are reported as unavailable. `inspect` resolves `MODEL[@VERSION]` to the selected version while holding its lease and then runs the normal core inspection path, so `--json`, `--unverified`, `--publisher-keys`, `--trust-store`, `--rank`, diff --git a/flare-cli/src/cache_commands.rs b/flare-cli/src/cache_commands.rs index a95a7897d..f0d965317 100644 --- a/flare-cli/src/cache_commands.rs +++ b/flare-cli/src/cache_commands.rs @@ -171,20 +171,25 @@ fn list_entries( .collect(), }; let mut documents = Vec::new(); + let mut hub_cores = Vec::new(); + let mut hub_rows = Vec::new(); for (model, identity) in models { let default = root.ref_entry(&model)?; let versions = root.versions(&model)?; let mut entries = Vec::new(); for version in versions { let selected = default.as_deref() == Some(version.as_str()); - let report = (|| -> Result<(bool, flare_helios::core::cache::EntrySummary, Usage), Box> { + let report = (|| -> Result<_, Box> { let leased = root.is_leased(&model, &version)?; let entry = root.entry(&model, &version)?; let summary = root.summarize_entry(&entry)?; let usage = usage(entry.directory())?; - Ok((leased, summary, usage)) + let ready_sizes = summary.deployments.iter().filter(|deployment| deployment.ready) + .map(|deployment| deployment.tensor_parallel).collect(); + let hub_core = flare::hub::InstalledHubCore::read(root, &entry, ready_sizes).ok().flatten(); + Ok((leased, summary, usage, hub_core)) })(); - let (leased, summary, usage) = match report { + let (leased, summary, usage, hub_core) = match report { Ok(values) => values, Err(error) => { // One unreadable entry must not hide the rest of the cache. @@ -220,6 +225,10 @@ fn list_entries( } else { (physical, None) }; + if let Some(hub_core) = hub_core { + hub_rows.push((documents.len(), entries.len())); + hub_cores.push(hub_core); + } entries.push(serde_json::json!({ "model": identity, "model_key": model, @@ -259,6 +268,15 @@ fn list_entries( "versions": entries, })); } + let options = flare::options::HubOptions { offline: list.offline, ..Default::default() }; + for ((model, version), report) in hub_rows.into_iter().zip(flare::hub::check_core_updates(&options, &hub_cores)) { + let row = &mut documents[model]["versions"][version]; + row["installed_updated_at"] = serde_json::json!(report.installed_updated_at); + row["update_available"] = serde_json::json!(report.update_available); + row["update_commit"] = serde_json::json!(report.update.as_ref().map(|update| &update.commit)); + row["update_updated_at"] = serde_json::json!(report.update.as_ref() + .map(|update| update.updated_at.as_str()).filter(|date| !date.is_empty())); + } let document = serde_json::json!({ "cache": root.path().display().to_string(), "models": documents, @@ -336,6 +354,22 @@ fn render_list(document: &Value, mut output: Canvas) -> String { output.note(""); continue; } + if let Some(installed) = entry.get("installed_updated_at") { + let date = |value: &Value| { + if value.is_null() { "unavailable".into() } else { text(value) } + }; + output.row("Last updated", &date(installed)); + let available = entry["update_available"].as_bool(); + let availability = match available { + Some(true) => "yes", + Some(false) => "no", + None => "unavailable", + }; + output.row("Update available", availability); + if available == Some(true) { + output.row("Update date", &date(&entry["update_updated_at"])); + } + } output.row( "Format", &format!( diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 8e50b534f..420ebd996 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -146,6 +146,10 @@ pub struct CacheList { /// Print the listing as JSON. #[arg(long)] pub json: bool, + + /// List the cache without checking Hugging Face for revision dates or updates. + #[arg(long)] + pub offline: bool, } #[derive(Debug, Args)] @@ -2429,6 +2433,7 @@ mod cache_cli_tests { "/cache", "list", "--json", + "--offline", ]); assert_eq!( list.core_cache.as_deref(), @@ -2438,6 +2443,7 @@ mod cache_cli_tests { CacheCommand::List(CacheList { model: None, json: true, + offline: true, }) => {} other => panic!("unexpected list command: {other:?}"), } diff --git a/flare-winui/Dashboard.inl b/flare-winui/Dashboard.inl index 3f2126d4c..8e0270c1c 100644 --- a/flare-winui/Dashboard.inl +++ b/flare-winui/Dashboard.inl @@ -24,7 +24,7 @@ StackPanel info;info.Spacing(5);Grid::SetColumn(info,1);info.VerticalAlignment(VerticalAlignment::Center); if(model.recommended())info.Children().Append(recommendation_badge()); auto name=label(model.name,15);name.MaxLines(2);name.FontWeight(Windows::UI::Text::FontWeights::SemiBold());info.Children().Append(name); - auto metadata=model.available()?(model.size_known?bytes(model.size)+L" · ":L"")+(model.flags&FLARE_MODEL_LOCAL?L"Downloaded":L"On this PC"):L""; + auto metadata=model.available()?(model.size_known?bytes(model.size)+L" · ":L"")+(model.previous()?L"Previous Version":model.flags&FLARE_MODEL_LOCAL?L"Downloaded":L"On this PC"):L""; if(!model.available()&&(model.metadata_known&FLARE_MODEL_REVISION_SIZE))metadata=bytes(model.revision_bytes)+L" repository files"; if(!model.revision_updated_at.empty())metadata+=(metadata.empty()?L"":L" · ")+std::wstring(L"Hub updated ")+updated_text(model.revision_updated_at,true); if(!model.error.empty())metadata=L"Needs attention"; @@ -34,16 +34,20 @@ Button use;use.Content(box_value(model.flags&FLARE_MODEL_ACTIVE?L"In use":model.available()?L"Run model":home_inventory_pending_?L"Checking…":L"Download"));use.Style(control + )xaml"; diff --git a/flare-winui/bridge/include/flare.h b/flare-winui/bridge/include/flare.h index 997c8956d..684bf5ac1 100644 --- a/flare-winui/bridge/include/flare.h +++ b/flare-winui/bridge/include/flare.h @@ -22,7 +22,8 @@ enum { enum { FLARE_MODEL_LOCAL = 1, FLARE_MODEL_EXTERNAL = 2, FLARE_MODEL_ACTIVE = 4, FLARE_MODEL_VERIFIED = 8, - FLARE_MODEL_CATALOG = 16, FLARE_MODEL_RECOMMENDED = 32 + FLARE_MODEL_CATALOG = 16, FLARE_MODEL_RECOMMENDED = 32, + FLARE_MODEL_SELECTED = 64, FLARE_MODEL_PREVIOUS = 128, FLARE_MODEL_HOME = 256 }; enum { FLARE_DOWNLOAD_QUEUED = 0, FLARE_DOWNLOAD_RUNNING = 1, @@ -144,7 +145,12 @@ typedef struct flare_model { uint32_t metadata_known; flare_string revision_updated_at; uint32_t published_build_mismatch; + flare_string update_commit, update_updated_at, installed_updated_at; } flare_model; +typedef struct flare_model_update_check { + uint64_t operation_id; + flare_string commit, updated_at; +} flare_model_update_check; enum { FLARE_MODEL_CONTEXT = 1, FLARE_MODEL_PARAMETERS = 2, FLARE_MODEL_REVISION_SIZE = 4, FLARE_MODEL_RANKS = 8 @@ -204,6 +210,7 @@ uint32_t flare_snapshot_runtime_settings(const flare_snapshot* snapshot, flare_r uint64_t flare_app_set_runtime_settings(flare_app* app, const flare_runtime_settings* value); size_t flare_snapshot_model_count(const flare_snapshot* snapshot); uint32_t flare_snapshot_model(const flare_snapshot* snapshot, size_t index, flare_model* value); +uint32_t flare_snapshot_model_update_check(const flare_snapshot* snapshot, flare_model_update_check* value); size_t flare_snapshot_download_count(const flare_snapshot* snapshot); uint32_t flare_snapshot_download(const flare_snapshot* snapshot, size_t index, flare_download* value); uint32_t flare_snapshot_trust(const flare_snapshot* snapshot, flare_trust_review* value); @@ -220,6 +227,8 @@ uint64_t flare_app_open_model(flare_app* app, const uint16_t* path, size_t lengt uint64_t flare_app_download(flare_app* app, const char* repository, size_t length); uint64_t flare_app_clear_failed_downloads(flare_app* app); uint64_t flare_app_activate(flare_app* app, const char* model_id, size_t length); +uint64_t flare_app_check_model_update(flare_app* app, const char* model_id, size_t length); +uint64_t flare_app_update_model(flare_app* app, const char* model_id, size_t model_length, const char* commit, size_t commit_length); uint64_t flare_app_stop(flare_app* app); uint64_t flare_app_cancel(flare_app* app, uint64_t operation_id); uint64_t flare_app_resume(flare_app* app, uint64_t operation_id); @@ -233,6 +242,8 @@ uint64_t flare_app_reject_publisher_key(flare_app* app, uint64_t decision_id); uint64_t flare_app_set_model_directory(flare_app* app, const uint16_t* path, size_t length); uint64_t flare_app_inspect_model(flare_app* app, const char* id, size_t length); uint64_t flare_app_remove_reference(flare_app* app, const char* id, size_t length); +uint64_t flare_app_delete_model(flare_app* app, const char* id, size_t id_length, + const uint16_t* directory, size_t directory_length, uint32_t clear_default); uint64_t flare_app_locate_reference(flare_app* app, const char* id, size_t id_length, const uint16_t* path, size_t path_length); uint64_t flare_app_try_model(flare_app* app, const char* prompt, size_t length); uint32_t flare_app_cancel_preview(flare_app* app); diff --git a/flare-winui/bridge/src/lib.rs b/flare-winui/bridge/src/lib.rs index 658d0475e..eb46d5131 100644 --- a/flare-winui/bridge/src/lib.rs +++ b/flare-winui/bridge/src/lib.rs @@ -136,6 +136,47 @@ mod tests { } } #[test] + fn model_update_snapshots_carry_the_commit_and_date() { + use flare::controller::{ModelUpdateCheck, ModelUpdateNotice, ModelView}; + + let notice = ModelUpdateNotice { + commit: "ab".repeat(20), + updated_at: "2026-11-05T18:06:29.000Z".into(), + }; + let installed_date = "2026-10-22T08:30:00.000Z"; + let snapshot = FlareSnapshot { + view: Snapshot { + models: vec![ModelView { + update: Some(notice.clone()), + installed_updated_at: installed_date.into(), + ..Default::default() + }], + model_update_check: Some(ModelUpdateCheck { + operation_id: 41, + update: Some(notice.clone()), + }), + ..Default::default() + }, + }; + let string = |value: FlareString| unsafe { + slice::from_raw_parts(value.data.cast::(), value.length) + }; + unsafe { + let mut model = std::mem::MaybeUninit::::uninit(); + let mut check = std::mem::MaybeUninit::::uninit(); + assert_eq!(flare_snapshot_model(&snapshot, 0, model.as_mut_ptr()), 1); + assert_eq!(flare_snapshot_model_update_check(&snapshot, check.as_mut_ptr()), 1); + let model = model.assume_init(); + let check = check.assume_init(); + assert_eq!(check.operation_id, 41); + assert_eq!(string(model.update_commit), notice.commit.as_bytes()); + assert_eq!(string(check.commit), string(model.update_commit)); + assert_eq!(string(model.update_updated_at), notice.updated_at.as_bytes()); + assert_eq!(string(check.updated_at), string(model.update_updated_at)); + assert_eq!(string(model.installed_updated_at), installed_date.as_bytes()); + } + } + #[test] fn immutable_snapshot_outlives_closed_application() { let folder = tempfile::tempdir().unwrap(); let config = folder.path().join("config.toml"); @@ -276,10 +317,29 @@ no_argument_command!(flare_app_clear_failed_downloads, Command::ClearFailedDownl string_command!(flare_app_discover, Command::Discover); string_command!(flare_app_download, Command::Download); string_command!(flare_app_activate, Command::Activate); +string_command!(flare_app_check_model_update, Command::CheckModelUpdate); path_command!(flare_app_open_model, Command::OpenModel); path_command!(flare_app_set_model_directory, Command::SetModelDirectory); string_command!(flare_app_inspect_model, Command::InspectModel); string_command!(flare_app_remove_reference, Command::RemoveReference); + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn flare_app_delete_model( + value: *mut FlareApp, + id: *const c_char, + id_length: usize, + directory: *const u16, + directory_length: usize, + clear_default: u32, +) -> u64 { + boundary(0, || { + unsafe { app(value) }?.controller.submit(Command::DeleteModel { + id: unsafe { utf8(id, id_length) }?, + directory: unsafe { path(directory, directory_length) }?.ok_or("Choose a library directory")?, + clear_default: clear_default != 0, + }) + }) +} #[unsafe(no_mangle)] pub unsafe extern "C" fn flare_app_locate_reference( value: *mut FlareApp, @@ -366,6 +426,22 @@ pub unsafe extern "C" fn flare_app_reject_trust(value: *mut FlareApp, id: u64) - .submit(Command::RejectTrust(id)) }) } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn flare_app_update_model( + value: *mut FlareApp, + id: *const c_char, + id_length: usize, + commit: *const c_char, + commit_length: usize, +) -> u64 { + boundary(0, || { + unsafe { app(value) }?.controller.submit(Command::UpdateModel { + id: unsafe { utf8(id, id_length) }?, + commit: unsafe { utf8(commit, commit_length) }?, + }) + }) +} + #[unsafe(no_mangle)] pub unsafe extern "C" fn flare_app_accept_trust( value: *mut FlareApp, @@ -603,6 +679,15 @@ pub struct FlareModel { metadata_known: u32, revision_updated_at: FlareString, published_build_mismatch: u32, + update_commit: FlareString, + update_updated_at: FlareString, + installed_updated_at: FlareString, +} +#[repr(C)] +pub struct FlareModelUpdateCheck { + operation_id: u64, + commit: FlareString, + updated_at: FlareString, } #[repr(C)] pub struct FlareDownload { @@ -705,12 +790,33 @@ pub unsafe extern "C" fn flare_snapshot_model( | (u32::from(s.metadata.rank_count.is_some()) << 3), revision_updated_at: text(&s.metadata.revision_updated_at), published_build_mismatch: u32::from(s.metadata.build_target_match == Some(false)), + update_commit: text(s.update.as_ref().map_or("", |update| &update.commit)), + update_updated_at: text(s.update.as_ref().map_or("", |update| &update.updated_at)), + installed_updated_at: text(&s.installed_updated_at), }, ) } }) } #[unsafe(no_mangle)] +pub unsafe extern "C" fn flare_snapshot_model_update_check( + value: *const FlareSnapshot, + out: *mut FlareModelUpdateCheck, +) -> u32 { + boundary(0, || { + let Some(check) = &unsafe { snapshot(value) }?.model_update_check else { + return Ok(0); + }; + unsafe { + output(out, FlareModelUpdateCheck { + operation_id: check.operation_id, + commit: text(check.update.as_ref().map_or("", |update| &update.commit)), + updated_at: text(check.update.as_ref().map_or("", |update| &update.updated_at)), + }) + } + }) +} +#[unsafe(no_mangle)] pub unsafe extern "C" fn flare_snapshot_download_count(value: *const FlareSnapshot) -> usize { boundary(0, || Ok(unsafe { snapshot(value) }?.downloads.len())) } diff --git a/flare-winui/main.cpp b/flare-winui/main.cpp index 4541a6735..048172fe6 100644 --- a/flare-winui/main.cpp +++ b/flare-winui/main.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -119,6 +120,30 @@ std::wstring updated_text(std::wstring const& value,bool date_only=false) { if(date_only)return std::format(L"{:%Y-%m-%d}",updated); return std::format(L"{:%Y-%m-%d %H:%M:%S} UTC",std::chrono::floor(updated)); } +std::wstring cache_added_date(std::wstring_view version) { + auto separator = version.rfind(L'-'); + if (separator == std::wstring_view::npos) return {}; + auto digits = [](std::wstring_view value) { + return !value.empty() && std::all_of(value.begin(), value.end(), [](wchar_t ch) { + return ch >= L'0' && ch <= L'9'; + }); + }; + auto suffix = version.substr(separator + 1); + if (!digits(suffix)) return {}; + if (suffix.size() != 12) { + if (suffix.size() > 10 || suffix.front() == L'0' || suffix == L"1") return {}; + version = version.substr(0, separator); + separator = version.rfind(L'-'); + if (separator == std::wstring_view::npos) return {}; + suffix = version.substr(separator + 1); + } + if (suffix.size() != 12 || !digits(suffix) || version.substr(0, separator).find(L"-tp") == std::wstring_view::npos) return {}; + std::chrono::year_month_day added; + std::wistringstream input{std::wstring(suffix.substr(0, 8))}; + input >> std::chrono::parse(L"%4Y%2m%2d", added); + if (input.fail() || !added.ok()) return {}; + return std::format(L"{:%Y-%m-%d}", added); +} std::wstring state_name(uint32_t state) { switch (state) { case FLARE_LOADING: return L"Loading"; @@ -143,9 +168,13 @@ struct ModelItem { uint32_t rank_count{}, metadata_known{}; std::wstring revision_updated_at; bool published_build_mismatch{}; + std::string update_commit; + std::wstring update_updated_at; + std::wstring installed_updated_at; bool catalog() const { return (flags & FLARE_MODEL_CATALOG) != 0; } bool available() const { return (flags & (FLARE_MODEL_LOCAL | FLARE_MODEL_EXTERNAL)) != 0; } bool recommended() const { return (flags & FLARE_MODEL_RECOMMENDED) != 0; } + bool previous() const { return (flags & FLARE_MODEL_PREVIOUS) != 0; } }; struct DesktopApp : ApplicationT { @@ -284,7 +313,10 @@ struct DesktopApp : ApplicationT { navigation.SelectedItem(navigation.MenuItems().GetAt(0)); clicked(L"ChooseModelButton", [this] { choose_model(); }); clicked(L"HomeAllModelsButton",[this]{select_source(false);select_page(1);}); - clicked(L"RefreshButton", [this] { if(discover_tab_)search_catalog();else accepted(flare_app_refresh(app_)); }); + clicked(L"RefreshButton", [this] { + accepted(flare_app_refresh(app_)); + if (discover_tab_) search_catalog(); + }); clicked(L"StopButton", [this] { stop_serving(); }); clicked(L"CancelSwitchButton", [this] { if (current_operation_) accepted(flare_app_cancel(app_, current_operation_)); }); for (auto name : { L"AddModelButton", L"EmptyAddButton", L"AddDirectButton",L"HomeAddButton",L"HomeEmptyAddButton" }) clicked(name, [this] { add_model(); }); @@ -403,10 +435,85 @@ struct DesktopApp : ApplicationT { accepted(operation); if (operation) select_page(2); } - fire_and_forget activate(std::string model, std::wstring name, bool reload=false) { + struct LaunchCheck { + uint64_t operation; + std::string model; + std::wstring name; + }; + void update_model(std::string const& model, std::string const& commit, bool run_after_update=false) { + auto operation = flare_app_update_model(app_, model.data(), model.size(), commit.data(), commit.size()); + accepted(operation); + if (operation) { + if (run_after_update) update_launch_operation_ = operation; + select_page(2); + } + } + Button model_update_button(ModelItem const& model) { + Button button; + button.Content(box_value(L"Update")); + Automation::AutomationProperties::SetName(button, L"Update " + model.name); + button.IsEnabled(model.error.empty()); + if (!model.update_updated_at.empty()) { + ToolTipService::SetToolTip(button, box_value(L"Updated " + updated_text(model.update_updated_at) + L" on Hugging Face")); + } + button.Click([this, id=model.id, commit=model.update_commit](auto const&, auto const&) { + update_model(id, commit); + }); + return button; + } + fire_and_forget confirm_delete_model(ModelItem model, std::wstring directory) { + auto lifetime = get_strong(); + ModalScope modal_scope{modal_open_}; + if (!modal_scope || closing_) co_return; + try { + bool selected = (model.flags & FLARE_MODEL_SELECTED) != 0; + auto prompt = dialog(L"Delete core version?"); + auto description = model.name + L"\nVersion " + model.version + + L"\n\nFiles shared with other versions stay available."; + if (selected) description += L"\n\nDeleting this version also clears the model’s default selection."; + prompt.Content(label(description)); + prompt.PrimaryButtonText(L"Delete"); + prompt.CloseButtonText(L"Cancel"); + prompt.DefaultButton(ContentDialogButton::Close); + if (co_await prompt.ShowAsync() == ContentDialogResult::Primary && !closing_) { + accepted(flare_app_delete_model(app_, model.id.data(), model.id.size(), + reinterpret_cast(directory.data()), directory.size(), selected)); + } + } catch (hresult_error const& error) { show_error(std::wstring(error.message())); } + } + void activate(std::string model, std::wstring name, bool reload=false) { + if (closing_ || modal_open_ || launch_check_) return; + update_launch_operation_ = 0; + if (!reload) { + auto operation = flare_app_check_model_update(app_, model.data(), model.size()); + accepted(operation); + if (operation) launch_check_ = LaunchCheck{operation, std::move(model), std::move(name)}; + return; + } + confirm_activation(std::move(model), std::move(name), reload); + } + fire_and_forget confirm_activation(std::string model, std::wstring name, bool reload=false, + std::string commit={}, std::wstring updated_at={}) { auto lifetime = get_strong(); ModalScope modal_scope{modal_open_};if(!modal_scope)co_return; try { + if (!commit.empty()) { + auto prompt = dialog(L"Model update available"); + auto message = L"An updated core is available for " + name + L".\n\n"; + message += updated_at.empty() ? L"Hugging Face did not report an update date." + : L"Updated " + updated_text(updated_at) + L" on Hugging Face."; + prompt.Content(label(message)); + prompt.PrimaryButtonText(L"Update and run"); + prompt.SecondaryButtonText(L"Run installed"); + prompt.CloseButtonText(L"Cancel"); + auto choice = co_await prompt.ShowAsync(); + if (closing_) co_return; + if (choice == ContentDialogResult::Primary) { + update_model(model, commit, true); + co_return; + } + if (choice != ContentDialogResult::Secondary) co_return; + } if (session_state_ == FLARE_READY) { ContentDialog dialog; dialog.XamlRoot(root_.XamlRoot()); @@ -424,6 +531,33 @@ struct DesktopApp : ApplicationT { if (operation) { can_change_model_=false;control