diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs index 124a0af931..fae31a5ac8 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs @@ -720,13 +720,15 @@ async fn dropped_native_stream_cancels_local_and_remote_generation_under_backpre /// Both the consumer and the provider must keep it alive: the window is per /// chunk, not per request, wherever the chunk is produced. async fn slow_generation_survives_the_window(remote: bool) { - let window = Duration::from_millis(150); - let chunks = 15usize; + // Allow for scheduling and QUIC setup on shared CI runners. The paced + // fixture still takes at least 1.5 inactivity windows to deliver all chunks. + let window = Duration::from_secs(2); + let chunks = 12; let (provider, _, _) = serving_node(Some(vec!["high".into()])).await; provider.set_native_stream_idle(window); let backend = Arc::new(RecordingBackend { pacing: Some(Pacing::Slow { - every: Duration::from_millis(20), + every: window / 8, chunks, }), ..Default::default() @@ -752,11 +754,11 @@ async fn slow_generation_survives_the_window(remote: bool) { .await .unwrap(); let mut seen = 0usize; - while let Some(chunk) = tokio::time::timeout(Duration::from_secs(5), stream.next_chunk()) + while let Some(chunk) = tokio::time::timeout(Duration::from_secs(30), stream.next_chunk()) .await .unwrap_or_else(|error| panic!("slow stream stalled (remote={remote}): {error}")) { - chunk.unwrap(); + chunk.unwrap_or_else(|error| panic!("slow stream failed (remote={remote}): {error:#}")); seen += 1; } let elapsed = started.elapsed(); diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index a3234ae957..c2ab95fb18 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "3a02d72808e96026b3b4e3ccbfed64a795681d3d03af7617d668f2aadcf774af" + "patch_queue_sha256": "85a61b8d48b96bdcd030664304197d0e55157200edf49e9c6aa8bcd85cf3254d" }, "architectures": [ "afmoe", diff --git a/skippy/crates/skippy-cache/src/radix.rs b/skippy/crates/skippy-cache/src/radix.rs index 31314ec081..144c785245 100644 --- a/skippy/crates/skippy-cache/src/radix.rs +++ b/skippy/crates/skippy-cache/src/radix.rs @@ -405,6 +405,35 @@ impl UnifiedRadixCache { }) } + /// Evict the least-recently-used unreferenced recurrent entry that is a + /// strict prefix of another recurrent entry in its namespace. A longer + /// entry already continues that conversation, so the shorter one is the + /// cheapest snapshot to lose. + pub fn evict_lru_superseded_recurrent(&mut self) -> Option> { + let mut victim = None; + for (namespace, root) in &self.roots { + collect_lru_superseded_recurrent(namespace, root, &mut Vec::new(), &mut victim); + } + let victim = victim?; + let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?; + self.recurrent_evictions = self.recurrent_evictions.saturating_add(1); + Some(RadixEviction { + namespace: victim.namespace, + tokens: victim.tokens, + logical_bytes: victim.logical_bytes, + value, + }) + } + + /// Recurrent entries with no longer recurrent entry below them: the latest + /// continuation of each distinct conversation. + pub fn recurrent_leaf_entries(&self) -> usize { + self.roots + .values() + .map(|root| count_recurrent_leaves(root).0) + .sum() + } + pub fn stats(&self) -> UnifiedRadixCacheStats { let mut stats = UnifiedRadixCacheStats { namespaces: self.roots.len(), @@ -933,6 +962,59 @@ fn collect_lru_victim( path.truncate(original_len); } +/// Returns (leaf recurrent entries, whether the subtree holds any recurrent entry). +fn count_recurrent_leaves(node: &RadixNode) -> (usize, bool) { + let mut leaves = 0; + let mut below = false; + for child in node.children.values() { + let (child_leaves, child_any) = count_recurrent_leaves(child); + leaves += child_leaves; + below |= child_any; + } + let here = node.components.recurrent.is_some(); + if here && !below { + leaves += 1; + } + (leaves, here || below) +} + +/// Returns whether the subtree holds any recurrent entry. +fn collect_lru_superseded_recurrent( + namespace: &str, + node: &RadixNode, + path: &mut Vec, + victim: &mut Option, +) -> bool { + let original_len = path.len(); + path.extend_from_slice(&node.edge); + let mut below = false; + for child in node.children.values() { + below |= collect_lru_superseded_recurrent(namespace, child, path, victim); + } + let entry = node.components.recurrent.as_ref(); + if below && let Some(entry) = entry.filter(|entry| entry.active_refs == 0) { + let replace = victim.as_ref().is_none_or(|current| { + (entry.last_used, namespace, path.as_slice()) + < ( + current.last_used, + current.namespace.as_str(), + current.tokens.as_slice(), + ) + }); + if replace { + *victim = Some(Victim { + namespace: namespace.to_string(), + tokens: path.clone(), + logical_bytes: entry.logical_bytes, + last_used: entry.last_used, + retention: 0, + }); + } + } + path.truncate(original_len); + below || entry.is_some() +} + fn collect_resident_eviction_candidates( namespace: &str, node: &RadixNode, @@ -1370,6 +1452,27 @@ mod tests { assert!(cache.release_resident("stage", &[1])); } + #[test] + fn superseded_recurrent_eviction_keeps_each_conversations_latest_entry() { + let mut cache = UnifiedRadixCache::<(), &str>::new(); + cache + .insert_recurrent("stage", &[1, 2], 1, "a-prefill") + .unwrap(); + cache + .insert_recurrent("stage", &[7, 8], 1, "b-prefill") + .unwrap(); + cache + .insert_recurrent("stage", &[1, 2, 3, 4], 1, "a-decode") + .unwrap(); + assert_eq!(cache.recurrent_leaf_entries(), 2); + assert_eq!( + cache.evict_lru_superseded_recurrent().unwrap().value, + "a-prefill" + ); + assert!(cache.evict_lru_superseded_recurrent().is_none()); + assert_eq!(cache.recurrent_leaf_entries(), 2); + } + #[test] fn component_eviction_preserves_other_payload_at_same_prefix() { let mut cache = UnifiedRadixCache::new(); diff --git a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs index ca076f48dc..6d8b502941 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs @@ -828,6 +828,16 @@ pub(in crate::frontend) fn prewarm_generation_sessions( let timer = PhaseTimer::start(); let mut runtime = lock_runtime(runtime); let generation_graph_warmed = runtime.warmup_generation_graph()?; + // The one-token warmup above does not reserve the graphs real traffic + // uses: the first full prefill ubatch and the first concurrent decode + // wave each grow the reservation mid-request. Warm the serving shapes + // now so no request pays the graph growth. + let warmup_prefill_tokens = config + .n_ubatch + .or(config.n_batch) + .unwrap_or(512) + .min(config.ctx_size.saturating_sub(64)) as usize; + runtime.warmup_serving_shapes(warmup_prefill_tokens)?; let sessions = runtime.prewarm_idle_sessions(generation_concurrency)?; let mut attrs = lifecycle_attrs(config); attrs.insert( diff --git a/skippy/crates/skippy-serving/src/frontend/tests/generation.rs b/skippy/crates/skippy-serving/src/frontend/tests/generation.rs index 9265c47549..8f7c4c400d 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/generation.rs @@ -1,7 +1,6 @@ use super::*; use crate::frontend::generation::run_blocking_generation_worker; use skippy_inference_api::chat::ChatCompletionRequest; -use std::sync::atomic::AtomicBool; fn assert_generation_rate_limit(error: InferenceError, message_fragment: &str) { assert_eq!(error.status(), StatusCode::TOO_MANY_REQUESTS); @@ -203,65 +202,70 @@ fn queued_arrival_cannot_be_overtaken_when_a_lane_opens() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn cancelled_worker_stops_before_the_next_request_acquires_the_only_lane() { + use tokio::sync::oneshot; + + struct CancelOnDrop(InferenceRequestContext); + impl Drop for CancelOnDrop { + fn drop(&mut self) { + self.0.cancel(); + } + } + + let wait = Duration::from_secs(30); let generation_limit = Arc::new(Semaphore::new(1)); let queue_depth = Arc::new(AtomicUsize::new(0)); let first_permit = acquire_generation_permit_with_queue( generation_limit.clone(), queue_depth.clone(), 1, - Duration::from_secs(1), + wait, ) .await .unwrap(); - let first_context = InferenceRequestContext::new(); - let worker_started = Arc::new(AtomicBool::new(false)); - let worker_stopped = Arc::new(AtomicBool::new(false)); - let started = worker_started.clone(); - let stopped = worker_stopped.clone(); + let first_context = CancelOnDrop(InferenceRequestContext::new()); + let (started, worker_started) = oneshot::channel(); + let (cancelled, worker_cancelled) = oneshot::channel(); + let (finish, worker_finish) = oneshot::channel(); let first_worker = tokio::spawn(run_blocking_generation_worker( first_permit, - first_context.clone(), + first_context.0.clone(), move |cancellation| { - started.store(true, Ordering::Release); - while !cancellation.is_cancelled() { - std::thread::sleep(Duration::from_millis(1)); - } - stopped.store(true, Ordering::Release); + tokio::runtime::Handle::current().block_on(async move { + let _ = started.send(()); + // A failed assertion must not strand a blocking worker at runtime shutdown. + tokio::time::timeout(wait, async { + cancellation.cancelled().await; + let _ = cancelled.send(()); + let _ = worker_finish.await; + }) + .await + .expect("worker must receive cancellation and permission to finish"); + }); }, )); - tokio::time::timeout(Duration::from_millis(100), async { - while !worker_started.load(Ordering::Acquire) { - tokio::task::yield_now().await; - } - }) - .await - .expect("first generation worker started"); - - let second_limit = generation_limit.clone(); - let second_queue_depth = queue_depth.clone(); - let second = tokio::spawn(async move { - let permit = acquire_generation_permit_with_queue( - second_limit, - second_queue_depth, - 1, - Duration::from_secs(1), - ) + tokio::time::timeout(wait, worker_started) .await + .expect("first generation worker started") .unwrap(); - assert!( - worker_stopped.load(Ordering::Acquire), - "the first worker must stop before its permit is released" - ); - drop(permit); - }); + let second = + acquire_generation_permit_with_queue(generation_limit.clone(), queue_depth, 1, wait); + tokio::pin!(second); + assert!(futures_util::poll!(second.as_mut()).is_pending()); - first_context.cancel(); - tokio::time::timeout(Duration::from_millis(200), second) + first_context.0.cancel(); + tokio::time::timeout(wait, worker_cancelled) .await - .expect("second request acquired the lane promptly") + .expect("first worker observed cancellation") .unwrap(); + assert!( + futures_util::poll!(second.as_mut()).is_pending(), + "the first worker must retain its permit while unwinding" + ); + finish.send(()).unwrap(); + let second_permit = second.await.expect("second request acquired the lane"); first_worker.await.unwrap().unwrap(); + drop(second_permit); assert_eq!(generation_limit.available_permits(), 1); } diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 3f1b23f3e9..c4c791dd91 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -19,31 +19,26 @@ use super::{ output_tokens::OutputTokenCache, }; -use super::cache_payload::{durable_cache_payload, effective_cache_payload}; +use super::{ + cache_payload::{durable_cache_payload, effective_cache_payload}, + exact_state::exact_state_admission_total_for_lanes, +}; pub(super) mod durable_spill; mod exact_state_limits; +mod exact_state_retention; mod resident_policy; mod runtime_identity; use durable_spill::{ DurableRecordTarget, PendingDurableSpill, spill_exact_record_to_l3, start_durable_spill_worker, }; use exact_state_limits::exact_state_byte_limits; +use exact_state_retention::enforce_exact_state_limits; // Recurrent and hybrid payloads share the native n_ctx cell pool across // sequence lanes, so their exact-state catalog must remain deliberately small. const RECURRENT_CACHE_MAX_ENTRIES: usize = 16; -// Exact-state snapshots are indivisible and carry architecture-specific state -// (recurrent and convolution buffers) that `estimate_stage_cache_max_bytes` -// cannot see, because that estimate is derived from attention KV metadata -// alone. A single snapshot therefore routinely exceeds the soft cap. Keep this -// many snapshots (subject to the configured entry limit) before the soft cap -// evicts anything: falling to one entry -// turns the catalog into a single-entry cache, where two concurrent sessions -// on the same stage evict each other on every request. -const EXACT_STATE_MIN_RETAINED_ENTRIES: usize = 4; - // Operator override for the limit above, in bytes, for workers whose memory // headroom does not match the attention-derived estimate. The last indivisible // snapshot may exceed it. Zero disables the limit. @@ -221,8 +216,11 @@ impl KvStageIntegration { ); let radix = Arc::new(Mutex::new(UnifiedRadixCache::new())); let exact_blobs = Arc::new(Mutex::new(CacheBlobStore::default())); + let admission_total_cap = exact_state_admission_total_for_lanes(config.lane_count); + // All admitted captures can reach the queue before the recorder receives one. + let record_queue_capacity = EXACT_STATE_RECORD_CAPACITY.max(admission_total_cap); let (exact_state_record_tx, exact_state_record_rx) = - std::sync::mpsc::sync_channel::(EXACT_STATE_RECORD_CAPACITY); + std::sync::mpsc::sync_channel::(record_queue_capacity); let worker_radix = radix.clone(); let worker_exact_blobs = exact_blobs.clone(); let worker_l3 = l3.clone(); @@ -391,6 +389,7 @@ impl KvStageIntegration { exact_state_records_pending, admission_outstanding, admission_best_effort_outstanding, + admission_total_cap, #[cfg(test)] exact_state_captures_outstanding: Arc::new(std::sync::atomic::AtomicUsize::new(0)), #[cfg(test)] @@ -785,9 +784,9 @@ fn store_exact_radix_record_with_codec( released.push(replaced.payload); } while radix.stats().recurrent_entries > max_entries { - let Some(evicted) = + let Some(evicted) = radix.evict_lru_superseded_recurrent().or_else(|| { radix.evict_recurrent_by_retention(RadixExactEntry::retention_priority) - else { + }) else { break; }; released.push(evicted.value.payload); @@ -812,22 +811,7 @@ fn store_exact_radix_record_with_codec( payload.release_from(&mut blobs)?; } } - // Exact snapshots are indivisible, and the soft cap is estimated from - // attention KV metadata that cannot include architecture-specific - // recurrent state, so one snapshot can legitimately exceed it. Hold a small - // working set past the soft cap (never more than the configured entry - // limit) so concurrent sessions on a stage stop evicting each other, then - // apply the hard limit so that allowance stays bounded apart from one - // indivisible snapshot. Neither pass evicts the last entry: a snapshot that - // self-evicts disables exact prefix caching for the stage entirely, which - // is the regression this retention policy exists to prevent. - evict_exact_entries_over( - radix, - blobs, - limits.soft_bytes, - EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries), - )?; - evict_exact_entries_over(radix, blobs, limits.hard_bytes, 1)?; + enforce_exact_state_limits(radix, blobs, limits, max_entries, logical_bytes)?; #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); @@ -903,50 +887,6 @@ fn cachegen_descriptor_is_qualified(desc: &RuntimeKvPageDesc) -> bool { ) } -/// Evicts least-recently-used exact entries while the catalog holds more than -/// `limit_bytes`, never dropping below `min_retained_entries`. A zero limit -/// means the catalog has no byte ceiling and nothing is evicted. -fn evict_exact_entries_over( - radix: &Mutex>, - blobs: &Mutex, - limit_bytes: u64, - min_retained_entries: usize, -) -> Result<()> { - if limit_bytes == 0 { - return Ok(()); - } - let floor = min_retained_entries.max(1); - loop { - let over_bytes = blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .physical_bytes() - > limit_bytes; - let above_floor = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .stats() - .recurrent_entries - > floor; - if !over_bytes || !above_floor { - break; - } - let evicted = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .evict_recurrent_by_retention(RadixExactEntry::retention_priority); - let Some(evicted) = evicted else { - break; - }; - evicted.value.payload.release_from( - &mut blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner), - )?; - } - Ok(()) -} - /// Either kill-switch variable resolving to `off` disables the cache, so an /// explicit `SKIPPY_KV_CACHE=on` cannot mask `SKIPPY_PREFIX_CACHE=off`. fn cache_disabled_by_env(kv_cache: Option<&str>, prefix_cache: Option<&str>) -> bool { @@ -1028,6 +968,7 @@ mod tests { mod cache_admission; mod durable_spill; + mod exact_state_retention; mod reserved_admission; mod runtime_admission; @@ -1035,6 +976,7 @@ mod tests { ExactStateByteLimits { soft_bytes, hard_bytes, + hard_is_explicit: false, } } @@ -1058,6 +1000,7 @@ mod tests { crate::kv_integration::exact_state::ExactStateAdmissionCredit::acquire( &self.total, &self.best_effort, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, crate::kv_integration::exact_state::CaptureAdmission::Continuation, ) .expect("a fresh per-test budget must admit") @@ -1553,15 +1496,21 @@ mod tests { } #[test] - fn exact_working_set_is_bounded_by_the_hard_ceiling() { + fn exact_working_set_is_bounded_by_the_retention_floor_not_the_ceiling() { let radix = Mutex::new(UnifiedRadixCache::new()); let blobs = Mutex::new(CacheBlobStore::new(4)); let budget = StorageBudget::new(); + // Six sessions' snapshots against byte limits smaller than one + // snapshot, as happens when the attention-derived estimate cannot see + // hybrid recurrent state. for (page_id, tokens, bytes) in [ - ("first", [1, 2], b"aaaabbbb"), - ("second", [1, 3], b"ccccdddd"), - ("third", [1, 4], b"eeeeffff"), + ("s1", [1, 2], b"aaaabbbb"), + ("s2", [1, 3], b"ccccdddd"), + ("s3", [1, 4], b"eeeeffff"), + ("s4", [1, 5], b"gggghhhh"), + ("s5", [1, 6], b"iiiijjjj"), + ("s6", [1, 7], b"kkkkllll"), ] { store_exact_radix_record( &radix, @@ -1575,14 +1524,21 @@ mod tests { .unwrap(); } - // The retention floor yields to the ceiling, leaving the most recent - // snapshot rather than an unbounded working set. + // The ceiling still bounds the working set above the retention floor: + // the two least-recently-used snapshots go. At the floor the ceiling + // yields, because collapsing to a single entry made concurrent + // sessions evict each other on every request. let mut radix = radix.lock().unwrap(); - assert_eq!(radix.stats().recurrent_entries, 1); + assert_eq!(radix.stats().recurrent_entries, 4); assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); assert!(radix.lookup_recurrent("model", &[1, 3]).is_none()); - assert!(radix.lookup_recurrent("model", &[1, 4]).is_some()); - assert_eq!(blobs.lock().unwrap().physical_bytes(), 8); + for tokens in [[1, 4], [1, 5], [1, 6], [1, 7]] { + assert!( + radix.lookup_recurrent("model", &tokens).is_some(), + "the retention floor must keep the newest four sessions" + ); + } + assert_eq!(blobs.lock().unwrap().physical_bytes(), 32); } #[test] diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs index a13bfc6aab..5f6bec1aa2 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs @@ -20,12 +20,13 @@ pub(super) fn exact_state_byte_limits( configured_exact_max_bytes: Option, override_max_bytes: Option<&str>, ) -> ExactStateByteLimits { - let hard_bytes = configured_exact_max_bytes - .or_else(|| override_max_bytes.and_then(|value| value.trim().parse::().ok())) - .unwrap_or_else(|| configured_max_bytes.saturating_mul(EXACT_STATE_HARD_CAP_MULTIPLE)); + let explicit = configured_exact_max_bytes + .or_else(|| override_max_bytes.and_then(|value| value.trim().parse::().ok())); ExactStateByteLimits { soft_bytes: configured_max_bytes, - hard_bytes, + hard_bytes: explicit + .unwrap_or_else(|| configured_max_bytes.saturating_mul(EXACT_STATE_HARD_CAP_MULTIPLE)), + hard_is_explicit: explicit.is_some(), } } @@ -36,6 +37,13 @@ mod tests { ExactStateByteLimits { soft_bytes, hard_bytes, + hard_is_explicit: false, + } + } + fn explicit(soft_bytes: u64, hard_bytes: u64) -> ExactStateByteLimits { + ExactStateByteLimits { + hard_is_explicit: true, + ..limits(soft_bytes, hard_bytes) } } #[test] @@ -52,11 +60,11 @@ mod tests { fn exact_state_byte_limits_honour_the_operator_override() { assert_eq!( exact_state_byte_limits(1_024, None, Some(" 4096 ")), - limits(1_024, 4_096) + explicit(1_024, 4_096) ); assert_eq!( exact_state_byte_limits(1_024, None, Some("0")), - limits(1_024, 0) + explicit(1_024, 0) ); // A malformed override must not silently disable the ceiling. assert_eq!( @@ -69,11 +77,11 @@ mod tests { fn configured_limit_overrides_the_legacy_environment_including_unbounded() { assert_eq!( exact_state_byte_limits(1024, Some(2048), Some("4096")), - limits(1024, 2048) + explicit(1024, 2048) ); assert_eq!( exact_state_byte_limits(1024, Some(0), Some("4096")), - limits(1024, 0) + explicit(1024, 0) ); } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs new file mode 100644 index 0000000000..259e52cfdb --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs @@ -0,0 +1,140 @@ +//! Byte-pressure eviction for the exact-state catalog. +use std::sync::{Mutex, PoisonError}; + +use anyhow::Result; +use skippy_cache::{CacheBlobStore, UnifiedRadixCache}; + +use super::{ExactStateByteLimits, RadixExactEntry}; +use crate::kv_integration::RadixResidentEntry; + +// Exact-state snapshots are indivisible and carry architecture-specific state +// (recurrent and convolution buffers) that `estimate_stage_cache_max_bytes` +// cannot see, because that estimate is derived from attention KV metadata +// alone. A single snapshot therefore routinely exceeds the soft cap. Keep this +// many snapshots (subject to the configured entry limit) before the soft cap +// evicts anything: falling to one entry +// turns the catalog into a single-entry cache, where two concurrent sessions +// on the same stage evict each other on every request. +const EXACT_STATE_MIN_RETAINED_ENTRIES: usize = 4; + +pub(super) fn enforce_exact_state_limits( + radix: &Mutex>, + blobs: &Mutex, + limits: ExactStateByteLimits, + max_entries: usize, + logical_bytes: u64, +) -> Result<()> { + // Exact snapshots are indivisible, and the soft cap is estimated from + // attention KV metadata that cannot include architecture-specific + // recurrent state, so one snapshot can legitimately exceed it. Hold a + // working set of conversations past the soft cap (never more than the + // configured entry limit) so concurrent sessions on a stage stop evicting + // each other. The floor counts each conversation's latest continuation: + // a checkpoint that a longer retained checkpoint extends is evicted first. + let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); + let conversations = RetentionFloor::Conversations(retention_floor.max(1)); + evict_exact_entries_over(radix, blobs, limits.soft_bytes, conversations)?; + // Zero means unbounded: no hard pass at all. + if limits.hard_bytes > 0 { + // An explicit operator budget is a strict ceiling: only one + // indivisible snapshot may exceed it. The attention-derived default + // stretches to hold the working set, since it cannot see hybrid + // recurrent state and would otherwise collapse the catalog. + let (hard_limit, hard_floor) = if limits.hard_is_explicit { + (limits.hard_bytes, RetentionFloor::SingleSnapshot) + } else { + let floor_bytes = logical_bytes + .max(1) + .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); + (limits.hard_bytes.max(floor_bytes), conversations) + }; + evict_exact_entries_over(radix, blobs, hard_limit, hard_floor)?; + let retained = blobs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .physical_bytes(); + if retained > limits.hard_bytes && exact_state_over_limit_warning_due() { + // Observable signal that the retained working set sits above the + // hard limit, e.g. the attention-derived estimate undercounts this + // stage's snapshots. Set an explicit exact-state budget when this + // repeats and memory must stay bounded. + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "exact-state catalog retained more than its hard byte limit" + .to_string(), + context: Some(format!( + "retained_bytes={retained} soft_bytes={} hard_bytes={} explicit={} floor_entries={retention_floor}", + limits.soft_bytes, limits.hard_bytes, limits.hard_is_explicit + )), + }, + ); + } + } + Ok(()) +} + +/// At most one over-limit warning per minute per process. +fn exact_state_over_limit_warning_due() -> bool { + use std::sync::atomic::{AtomicU64, Ordering}; + static LAST_WARNED_SECS: AtomicU64 = AtomicU64::new(0); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let last = LAST_WARNED_SECS.load(Ordering::Relaxed); + (last == 0 || now.saturating_sub(last) >= 60) + && LAST_WARNED_SECS + .compare_exchange(last, now.max(1), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() +} + +#[derive(Clone, Copy)] +enum RetentionFloor { + Conversations(usize), + SingleSnapshot, +} + +/// Evict superseded checkpoints first, then evict by recency above the floor. +fn evict_exact_entries_over( + radix: &Mutex>, + blobs: &Mutex, + limit_bytes: u64, + floor: RetentionFloor, +) -> Result<()> { + if limit_bytes == 0 { + return Ok(()); + } + loop { + let over_bytes = blobs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .physical_bytes() + > limit_bytes; + if !over_bytes { + break; + } + let evicted = { + let mut radix = radix.lock().unwrap_or_else(PoisonError::into_inner); + radix.evict_lru_superseded_recurrent().or_else(|| { + let above_floor = match floor { + RetentionFloor::Conversations(minimum) => { + radix.recurrent_leaf_entries() > minimum + } + RetentionFloor::SingleSnapshot => radix.stats().recurrent_entries > 1, + }; + above_floor + .then(|| { + radix.evict_recurrent_by_retention(RadixExactEntry::retention_priority) + }) + .flatten() + }) + }; + let Some(evicted) = evicted else { + break; + }; + evicted + .value + .payload + .release_from(&mut blobs.lock().unwrap_or_else(PoisonError::into_inner))?; + } + Ok(()) +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs index 540cbcede7..487f0bc9ac 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs @@ -22,7 +22,7 @@ impl KvStageIntegration { // Verification stays outside the runtime lock. Unix can reuse the // load-time digest through a strong file fingerprint; other platforms // recheck bytes when equivalent identity/change-time evidence is absent. - let content = content.filter(|proof| proof.still_matches(config)); + let content = content.and_then(|proof| proof.revalidate(config)); Self::from_loaded_model_with_l3(config, kind, memory, content, || Ok(manager), observer) } diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs new file mode 100644 index 0000000000..2e890d61b2 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs @@ -0,0 +1,213 @@ +use super::*; +use crate::kv_integration::RadixResidentEntry; + +#[test] +fn exact_state_retention_floor_survives_a_hard_cap_blind_to_recurrent_state() { + // Regression: the byte limits are derived from attention KV metadata, + // so hybrid snapshots (recurrent state the estimate cannot see) can + // push the retained working set past the hard cap. The retention floor + // must keep every concurrent session's entry; collapsing to a single + // entry made sessions evict each other on every request. + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + // Each snapshot is 32 bytes; four of them (128) exceed the hard cap + // of 80 even though each individually fits the 8x headroom. + let oversized_for_attention_estimate = limits(10, 80); + for index in 0..4 { + store_exact_radix_record( + &radix, + &blobs, + 512, + oversized_for_attention_estimate, + None, + None, + pending( + &format!("session-{index}"), + &[1, index + 2], + &distinct_payload(index as u8, 32), + &budget, + ), + ) + .unwrap(); + } + // Distinct blocks, so the retained set really is past the hard cap and + // the pre-floor policy would have evicted down to one entry. + assert!(blobs.lock().unwrap().physical_bytes() > 80); + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 4); + for index in 0..4 { + assert!( + radix.lookup_recurrent("model", &[1, index + 2]).is_some(), + "session {index} must retain its exact-state entry" + ); + } +} + +/// Payload bytes that dedupe into distinct 4-byte blocks per `seed`. +fn distinct_payload(seed: u8, len: usize) -> Vec { + (0..len) + .map(|offset| seed.wrapping_mul(64).wrapping_add(offset as u8)) + .collect() +} + +fn store_sessions( + radix: &Mutex>, + blobs: &Mutex, + limits: ExactStateByteLimits, + sessions: &[(&str, &[i32], u8)], +) { + let budget = StorageBudget::new(); + for (page, tokens, seed) in sessions { + store_exact_radix_record( + radix, + blobs, + 512, + limits, + None, + None, + pending(page, tokens, &distinct_payload(*seed, 32), &budget), + ) + .unwrap(); + } +} + +#[test] +fn explicit_exact_budget_stays_a_strict_ceiling_past_the_retention_floor() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let explicit_ceiling = ExactStateByteLimits { + soft_bytes: 10, + hard_bytes: 40, + hard_is_explicit: true, + }; + store_sessions( + &radix, + &blobs, + explicit_ceiling, + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ], + ); + // One indivisible 32-byte snapshot fits the ceiling; a second does not. + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 1); + assert!(blobs.lock().unwrap().physical_bytes() <= 40); +} + +#[test] +fn explicit_exact_budget_evicts_a_continuation_when_its_parent_is_leased() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let explicit_ceiling = ExactStateByteLimits { + soft_bytes: 10, + hard_bytes: 40, + hard_is_explicit: true, + }; + let checkpoint = [1, 2]; + let continuation = [1, 2, 3]; + store_sessions(&radix, &blobs, explicit_ceiling, &[("a", &checkpoint, 0)]); + radix + .lock() + .unwrap() + .acquire_recurrent("model", &checkpoint) + .unwrap(); + store_sessions( + &radix, + &blobs, + explicit_ceiling, + &[("a-continued", &continuation, 1)], + ); + + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 1); + assert!(radix.recurrent_exact("model", &continuation).is_none()); + assert!(radix.release_recurrent("model", &checkpoint)); + assert_eq!(blobs.lock().unwrap().physical_bytes(), 32); +} + +#[test] +fn unbounded_byte_limits_keep_every_entry_the_entry_limit_allows() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + store_sessions( + &radix, + &blobs, + limits(0, 0), + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ("e", &[1, 6], 4), + ], + ); + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 5); +} + +#[test] +fn retention_floor_keeps_each_sessions_latest_continuation() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + // Session A stores a prefill and a post-decode checkpoint between the + // other sessions' prefills. Five snapshots exceed the derived hard + // cap; the superseded prefill must go, not another session's only one. + store_sessions( + &radix, + &blobs, + limits(10, 80), + &[ + ("a-prefill", &[1, 2], 0), + ("b", &[1, 3], 1), + ("a-decode", &[1, 2, 9, 9], 2), + ("c", &[1, 4], 3), + ("d", &[1, 5], 4), + ], + ); + let mut radix = radix.lock().unwrap(); + assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); + for tokens in [&[1, 2, 9, 9][..], &[1, 3], &[1, 4], &[1, 5]] { + assert!( + radix.lookup_recurrent("model", tokens).is_some(), + "latest continuation {tokens:?} must survive" + ); + } +} + +#[test] +fn entry_limit_prefers_superseded_checkpoints_to_other_conversations() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + let limits = limits(0, 0); + let store = |page, tokens, seed| { + store_exact_radix_record( + &radix, + &blobs, + 4, + limits, + None, + None, + pending(page, tokens, &distinct_payload(seed, 32), &budget), + ) + .unwrap(); + }; + store("a-prefill", &[1, 2], 0); + store("b", &[1, 3], 1); + store("c", &[1, 4], 2); + store("d", &[1, 5], 3); + radix + .lock() + .unwrap() + .lookup_recurrent("model", &[1, 2]) + .unwrap(); + store("a-continued", &[1, 2, 9], 4); + + let mut radix = radix.lock().unwrap(); + assert!(radix.recurrent_exact("model", &[1, 2]).is_none()); + for tokens in [&[1, 2, 9][..], &[1, 3], &[1, 4], &[1, 5]] { + assert!(radix.recurrent_exact("model", tokens).is_some()); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs index a540f65795..1b12ecccab 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs @@ -15,6 +15,7 @@ fn harness_config() -> StageConfig { StageConfig { stage_id: "stage-0".to_string(), model_id: NAMESPACE.to_string(), + lane_count: 1, kv_cache: Some(StageKvCacheConfig { exact_max_bytes: None, mode: StageKvCacheMode::LookupRecord, @@ -88,6 +89,7 @@ fn acquire(kv: &KvStageIntegration, class: CaptureAdmission) -> Option bool { .is_some() } +#[test] +fn lane_scaled_recorder_can_queue_the_reserved_continuation() { + use std::sync::atomic::AtomicBool; + + struct ResumeRecorder<'a>(&'a AtomicBool); + impl Drop for ResumeRecorder<'_> { + fn drop(&mut self) { + self.0.store(false, AtomicOrdering::Release); + } + } + + let lanes = 9; + let mut config = harness_config(); + config.lane_count = lanes; + config.kv_cache.as_mut().unwrap().max_entries = 16; + let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) + .unwrap() + .unwrap(); + kv.exact_state_worker_pause + .store(true, AtomicOrdering::Release); + let resume = ResumeRecorder(&kv.exact_state_worker_pause); + + for lane in 0..lanes { + let credit = acquire(&kv, CaptureAdmission::BestEffort).expect("lane capture admitted"); + assert_eq!( + kv.enqueue_exact_state_record(record( + &format!("lane-{lane}"), + vec![i32::try_from(lane).unwrap()], + credit, + )), + ExactStateRecordAdmission::Queued, + ); + if lane == 0 { + kv.wait_for_exact_state_worker_received(1, WAIT).unwrap(); + } + } + let credit = acquire(&kv, CaptureAdmission::Continuation).expect("reserved capture admitted"); + let continuation = vec![20]; + assert_eq!( + kv.enqueue_exact_state_record(record("continuation", continuation.clone(), credit)), + ExactStateRecordAdmission::Queued, + ); + + drop(resume); + kv.wait_for_exact_state_recording(WAIT).unwrap(); + assert!(stored(&kv, &continuation)); +} + /// Reserved-credit delivery end-to-end under an EXPLICITLY paused /// recorder worker (no radix contention): the BestEffort payload is /// received worker-side and paused BEFORE storage, the Continuation @@ -446,45 +496,3 @@ fn record_exact_state_releases_credit_when_export_fails() { assert_eq!(outstanding(&kv), 0, "credit released when the export fails"); assert!(kv.inflight_records.lock().unwrap().is_empty()); } - -/// Without L3, a snapshot that every stored entry outranks would be evicted -/// as soon as it is stored, so it is not exported at all. A snapshot at the -/// stored entries' tier still goes ahead (and here fails to export, as the -/// session does not exist). -#[test] -fn a_crowded_out_snapshot_is_not_exported_without_l3() { - let (kv, config) = harness(); - assert!(kv.l3.is_none()); - for token in 0..kv.exact_max_entries { - let token = i32::try_from(token).unwrap() + 100; - seed_exact_state(&kv, &identity(&kv, &config, &[token])); - } - let mut runtime = RuntimeState::new_modelless_for_test(1); - let mut mesh = identity(&kv, &config, &[1, 2, 3]); - mesh.identity.chat_template_id = skippy_inference_api::InferenceRequestClass::new( - skippy_inference_api::InferenceRequestTier::Mesh, - false, - ) - .cache_namespace(None) - .unwrap(); - assert!(mesh.retention_priority() < identity(&kv, &config, &[1]).retention_priority()); - - let skipped = kv.record_exact_state( - &mut runtime, - "missing-session", - &mesh, - CaptureAdmission::BestEffort, - ); - assert!(matches!(skipped, Ok(None)), "{skipped:?}"); - assert_eq!(outstanding(&kv), 0); - - let local = identity(&kv, &config, &[1, 2, 3]); - let exported = kv.record_exact_state( - &mut runtime, - "missing-session", - &local, - CaptureAdmission::BestEffort, - ); - assert!(exported.is_err(), "a local snapshot is exported"); - assert_eq!(outstanding(&kv), 0); -} diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index e1bbdd4946..1b0b90de7c 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -83,15 +83,24 @@ pub(crate) enum SessionEndCapture { Deferred, } -/// Total in-flight exact-state payloads per stage — exporting, queued in the -/// recorder channel, or held by the recorder worker. Sized as channel -/// capacity (1) plus one worker-held record. +/// Minimum in-flight exact-state payload slots per stage, including exports, +/// queued records, and the record held by the worker. pub const EXACT_STATE_ADMISSION_TOTAL: usize = 2; /// Slots reserved for [`CaptureAdmission::Continuation`]: BestEffort captures /// can never occupy more than `TOTAL - RESERVED` slots, so a continuation /// boundary always finds a slot unless the whole budget is exhausted. pub const EXACT_STATE_ADMISSION_RESERVED: usize = 1; +/// Per-stage admission slots, with one in-flight payload per lane plus one +/// slot reserved for continuations. The recorder channel can hold the entire +/// admitted set even when the worker holds no record. +/// Concurrent multi-turn sessions measured on the fleet starved at the floor: +/// whichever session completed first held the only best-effort slot and every +/// other lane's record was declined for the whole wave. +pub(crate) fn exact_state_admission_total_for_lanes(lane_count: u32) -> usize { + EXACT_STATE_ADMISSION_TOTAL.max(lane_count as usize + 1) +} + /// Move-only credit for one in-flight exact-state payload. Construction /// reserves a slot atomically (CAS, so competing producers cannot /// oversubscribe the budget); Drop releases it exactly once on every terminal @@ -110,14 +119,16 @@ impl ExactStateAdmissionCredit { pub(crate) fn acquire( total: &Arc, best_effort: &Arc, + total_cap: usize, class: CaptureAdmission, ) -> Option { + let total_cap = total_cap.max(EXACT_STATE_ADMISSION_TOTAL); use std::sync::atomic::Ordering::{AcqRel, Acquire}; match class { CaptureAdmission::Continuation => { let mut observed = total.load(Acquire); loop { - if observed >= EXACT_STATE_ADMISSION_TOTAL { + if observed >= total_cap { return None; } match total.compare_exchange_weak(observed, observed + 1, AcqRel, Acquire) { @@ -134,7 +145,7 @@ impl ExactStateAdmissionCredit { } } CaptureAdmission::BestEffort => { - let reserved_cap = EXACT_STATE_ADMISSION_TOTAL - EXACT_STATE_ADMISSION_RESERVED; + let reserved_cap = total_cap - EXACT_STATE_ADMISSION_RESERVED; let mut observed_best_effort = best_effort.load(Acquire); loop { if observed_best_effort >= reserved_cap { @@ -154,7 +165,7 @@ impl ExactStateAdmissionCredit { // if the total budget was exhausted concurrently. let mut observed_total = total.load(Acquire); loop { - if observed_total >= EXACT_STATE_ADMISSION_TOTAL { + if observed_total >= total_cap { best_effort.fetch_sub(1, AcqRel); return None; } @@ -414,6 +425,7 @@ impl KvStageIntegration { && let Some(admission_credit) = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) && self.try_begin_record(&page_id) @@ -754,6 +766,7 @@ impl KvStageIntegration { let Some(mut admission_credit) = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, admission, ) else { #[cfg(test)] @@ -1185,6 +1198,7 @@ impl KvStageIntegration { let rewarm_enqueued = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) .is_some_and(|admission_credit| { @@ -1508,6 +1522,7 @@ mod admission_credit_tests { let guard = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!(guard.is_some(), "fresh budget admits Continuation"); @@ -1522,17 +1537,20 @@ mod admission_credit_tests { let first = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); let second = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!(first.is_some() && second.is_some(), "two slots for TOTAL=2"); let third = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!( @@ -1545,11 +1563,19 @@ mod admission_credit_tests { #[test] fn best_effort_declines_at_reserved_cap_even_with_budget_headroom() { let (total, best_effort) = counters(); - let first = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let first = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!(first.is_some()); - let second = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let second = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!( second.is_none(), "BestEffort cap is TOTAL - RESERVED = 1; second must decline" @@ -1557,15 +1583,68 @@ mod admission_credit_tests { assert_eq!(best_effort.load(Ordering::Acquire), 1); } + #[test] + fn multi_lane_stages_admit_one_capture_per_lane() { + // Fleet regression: concurrent multi-turn sessions starved at the + // single-stream floor — whichever session completed first held the + // only best-effort slot and every other lane's capture was declined, + // so its exchange was lost and its next turn re-prefilled it. A stage + // serving four lanes must admit four concurrent captures. + let (total, best_effort) = counters(); + let cap = super::exact_state_admission_total_for_lanes(4); + assert_eq!(cap, 5, "four lanes plus recorder headroom"); + let held: Vec<_> = (0..4) + .map(|_| { + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::BestEffort, + ) + }) + .collect(); + assert!( + held.iter().all(|credit| credit.is_some()), + "every lane's capture must be admitted" + ); + assert_eq!(total.load(Ordering::Acquire), 4); + let continuation = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::Continuation, + ); + assert!( + continuation.is_some(), + "the reserved continuation share still admits" + ); + assert_eq!(total.load(Ordering::Acquire), 5); + assert!( + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::BestEffort + ) + .is_none(), + "budget exhausted at the lane-scaled cap" + ); + } + #[test] fn continuation_admits_after_best_effort_under_reserved_share() { let (total, best_effort) = counters(); - let best = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let best = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!(best.is_some(), "BestEffort takes its single slot"); let cont = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!( @@ -1599,9 +1678,12 @@ mod admission_credit_tests { } else { CaptureAdmission::BestEffort }; - if let Some(credit) = - ExactStateAdmissionCredit::acquire(&total, &best_effort, class) - { + if let Some(credit) = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + class, + ) { held.push((class, credit)); } } @@ -1642,6 +1724,7 @@ mod admission_credit_tests { let credit = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("topping up an under-subscribed budget must succeed"); @@ -1665,7 +1748,8 @@ mod admission_credit_tests { ExactStateAdmissionCredit::acquire( &total, &best_effort, - CaptureAdmission::BestEffort + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, ) .is_none(), "an exhausted budget must decline every BestEffort attempt" @@ -1696,10 +1780,15 @@ mod admission_credit_tests { let recovery_continuation = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); - let recovery_best_effort = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let recovery_best_effort = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!( recovery_continuation.is_some() && recovery_best_effort.is_some(), "budget must recover after the drain" @@ -1723,12 +1812,14 @@ mod admission_credit_tests { let first = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("first Continuation admitted"); let second = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("second Continuation admitted"); @@ -1748,7 +1839,8 @@ mod admission_credit_tests { ExactStateAdmissionCredit::acquire( &total, &best_effort, - CaptureAdmission::BestEffort + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, ) .is_none(), "a continuation-exhausted budget must decline every BestEffort via rollback" @@ -1776,8 +1868,13 @@ mod admission_credit_tests { assert_eq!(total.load(Ordering::Acquire), 0); assert_eq!(best_effort.load(Ordering::Acquire), 0); assert!( - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort) - .is_some(), + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort + ) + .is_some(), "budget recovers after the drain" ); } diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs index 8e20ade36a..4caf778158 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs @@ -26,8 +26,13 @@ fn credit( best_effort: &Arc, class: CaptureAdmission, ) -> ExactStateAdmissionCredit { - ExactStateAdmissionCredit::acquire(total, best_effort, class) - .expect("a fresh budget must admit") + ExactStateAdmissionCredit::acquire( + total, + best_effort, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, + class, + ) + .expect("a fresh budget must admit") } struct RecordingObserver(Arc>>); diff --git a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs index 8f3215ee15..a453d0d4a1 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -328,6 +328,7 @@ impl KvStageIntegration { let rewarm_enqueued = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) .is_some_and(|admission_credit| { diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 51716bee8a..34296df211 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -157,6 +157,9 @@ pub enum StageKvMode { pub(crate) struct ExactStateByteLimits { pub(crate) soft_bytes: u64, pub(crate) hard_bytes: u64, + /// The hard limit came from an operator budget rather than the + /// attention-derived estimate, so it is a strict ceiling. + pub(crate) hard_is_explicit: bool, } #[derive(Clone)] @@ -204,6 +207,9 @@ pub struct KvStageIntegration { /// the worker. See `ExactStateAdmissionCredit`. pub(crate) admission_outstanding: Arc, pub(crate) admission_best_effort_outstanding: Arc, + /// Per-stage admission ceiling, scaled by lane count; see + /// `exact_state::exact_state_admission_total_for_lanes`. + pub(crate) admission_total_cap: usize, /// Test-only outstanding-capture tracking: incremented when a capture task /// is scheduled onto the iteration scheduler, released when that task /// reaches ANY terminal outcome (recorded, skipped, error, panic) via a @@ -267,8 +273,7 @@ pub enum StagePrefixCachePayload { FullState, } -/// Entry backstop on the record queue. The binding limit is -/// [`EXACT_STATE_RECORD_QUEUE_BYTES`]; this only caps bookkeeping. +/// Baseline serving recorder queue capacity and fixed durable spill queue capacity. pub(crate) const EXACT_STATE_RECORD_CAPACITY: usize = 8; /// Payload bytes the record queue may hold. A record that does not fit is diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index f928553eeb..17a83be2fb 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -433,10 +433,9 @@ fn runtime_from_verified_model( config: &StageConfig, model: StageModel, observer: Option>, - content: Option, + content: Option>, ) -> Result>> { // Verification and its post-open file checks finished outside this lock. - let content = content.map(Arc::new); let runtime = runtime_from_loaded_model(config, model, observer)?; panic_recovery::lock_runtime(&runtime).verified_model_content = content; Ok(runtime) diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 02a92a2098..affe513f64 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -68,19 +68,7 @@ impl RuntimeState { } pub(crate) fn warmup_generation_graph(&mut self) -> Result { - // Prewarming invokes decode_step. Encode-only models cannot decode, - // and encoder-decoder models must encode a source first. - if self.model.workload_info()?.kind != ModelWorkload::CausalGeneration { - return Ok(false); - } - if self.model.input_activation_boundary().is_some() - || self.model.output_activation_boundary().is_some() - { - return Ok(false); - } - // DiffusionGemma runs non-causally with no KV memory, so a decode - // step has no graph to warm and the reset would fail. - if self.serves_system_one() { + if !self.can_warm_generation_graph() { return Ok(false); } let token_id = self @@ -109,6 +97,207 @@ impl RuntimeState { Ok(true) } + /// Whether [`Self::warmup_generation_graph`] can run for this runtime. + fn can_warm_generation_graph(&self) -> bool { + // Prewarming invokes decode_step. Encode-only models cannot decode, + // and encoder-decoder models must encode a source first. + if !matches!( + self.model.workload_info().map(|info| info.kind), + Ok(ModelWorkload::CausalGeneration) + ) { + return false; + } + if self.model.input_activation_boundary().is_some() + || self.model.output_activation_boundary().is_some() + { + return false; + } + // DiffusionGemma runs non-causally with no KV memory, so a decode + // step has no graph to warm and the reset would fail. + !self.serves_system_one() + } + + /// Reserve the compute graphs serving will actually use before the first + /// request pays for them. [`Self::warmup_generation_graph`] exercises a + /// one-token single-sequence decode; the first real prefill and the first + /// concurrent decode wave each need a larger graph, and the native + /// runtime's lazy graph reservation charges that growth to the request + /// that triggers it (a 314 ms `sched_reserve` on a GB10 spark for the + /// first full ubatch). Warm both serving shapes at startup instead: one + /// single-session prefill capped to the loaded batch limit, then one + /// one-token decode wave within that limit. Best-effort: a model that cannot run the + /// larger shapes still serves, keeping the lazy reservation. + pub(crate) fn warmup_serving_shapes(&mut self, prefill_tokens: usize) -> Result<()> { + if !self.can_warm_generation_graph() || prefill_tokens == 0 { + return Ok(()); + } + let token_id = self + .model + .tokenize("", true)? + .into_iter() + .next() + .unwrap_or(0); + self.warmup_prefill_shape(token_id, prefill_tokens); + self.warmup_concurrent_decode_shape(token_id); + Ok(()) + } + + fn warmup_prefill_shape(&mut self, token_id: i32, prefill_tokens: usize) { + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let mut lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(error) => { + tracing::warn!(?error, "serving prefill warmup could not borrow a lane"); + return; + } + }, + }; + let warmed = (|| { + // The native context clamps configured limits during loading. + let tokens = vec![token_id; prefill_tokens.min(lane.session.batch_size()?)]; + let request = IterationBatchRequest { + session: &mut lane.session, + token_ids: &tokens, + positions: &[], + sampling: None, + input: None, + // Real prefill chunks sample their final row: the graph the + // reservation must cover includes the output head, which a + // consumerless warmup iteration omits entirely. + sample_last: true, + phase: IterationBatchPhase::Prefill, + }; + StageSession::iteration_batch_sampled(&mut [request]).map(|_| ()) + })(); + let result = warmed.and_then(|_| lane.session.reset()); + if let Err(error) = self.finish_generation_warmup(lane, result, idle_index.is_some()) { + tracing::warn!( + ?error, + "serving prefill warmup failed; keeping lazy reservation" + ); + } + } + + fn warmup_concurrent_decode_shape(&mut self, token_id: i32) { + let mut lanes = Vec::new(); + let mut wave_limit = self.lane_count as usize; + while lanes.len() < wave_limit { + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(_) => break, + }, + }; + match lane.session.batch_size() { + Ok(batch_size) => wave_limit = wave_limit.min(batch_size), + Err(error) => { + let _ = self.finish_generation_warmup(lane, Err(error), false); + break; + } + } + lanes.push((lane, idle_index.is_some())); + } + if lanes.is_empty() { + return; + } + let mut requests = Vec::with_capacity(lanes.len()); + let warmup_sampling = SamplingConfig { + enabled: true, + temperature: 0.0, + ..SamplingConfig::default() + }; + // An empty metadata string clears chat sampling instead of + // configuring it (the native entry's early-out), so the attach the + // warmup exists to provoke never happened. A minimal grammar-free + // metadata document reaches the real configure path. + const WARMUP_SAMPLING_METADATA: &str = r#"{"grammar":""}"#; + for (lane, _) in lanes.iter_mut() { + // Real requests configure chat sampling through the frontend + // before their first iteration; that configuration is what + // attaches the backend sampler and grows the reservation. Walk + // the same entry here so the sampler-aware reservation is built + // at startup instead of on the first request. + if let Err(error) = lane.session.configure_chat_sampling( + WARMUP_SAMPLING_METADATA, + 0, + Some(&warmup_sampling), + ) { + tracing::warn!(?error, "serving warmup could not configure chat sampling"); + } + requests.push(IterationBatchRequest { + session: &mut lane.session, + token_ids: std::slice::from_ref(&token_id), + positions: &[], + // Real decode steps sample every iteration; warm the shape + // that includes the sampler's logits row, and attach the + // samplers so the sampler-aware graph reservation happens + // here rather than on the first request. + sampling: Some(&warmup_sampling), + input: None, + sample_last: true, + phase: IterationBatchPhase::Decode, + }); + } + let warmed = StageSession::iteration_batch_sampled(&mut requests).map(|_| ()); + if let Err(error) = &warmed { + tracing::warn!( + ?error, + "serving decode-wave warmup failed; keeping lazy reservation" + ); + } + for (mut lane, borrowed) in lanes { + // Only successfully warmed and reset borrowed lanes are reusable. + let result = lane.session.reset(); + if let Err(error) = + self.finish_generation_warmup(lane, result, borrowed && warmed.is_ok()) + { + tracing::warn!(?error, "serving decode-wave warmup cleanup failed"); + } + } + // Converge the sampler-aware reservation: sampling attaches happen + // after an iteration's decode, so the warmup so far can end with + // the re-reserve armed (or never consumed) and the reservation + // still sampler-less; the first request would then pay a + // worst-case graph re-reserve. One decode with a sampler attached + // guarantees the reservation is rebuilt sampler-aware (or confirmed + // already covering) before traffic arrives. + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let mut lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(error) => { + tracing::warn!(?error, "sampler-aware warmup could not borrow a lane"); + return; + } + }, + }; + let converged = lane + .session + .configure_chat_sampling(WARMUP_SAMPLING_METADATA, 0, Some(&warmup_sampling)) + .and_then(|_| lane.session.decode_step(token_id)) + .and_then(|_| lane.session.reset()); + if let Err(error) = self.finish_generation_warmup(lane, converged, idle_index.is_some()) { + tracing::warn!( + ?error, + "sampler-aware warmup failed; keeping lazy reservation" + ); + } + } + fn finish_generation_warmup( &mut self, lane: RuntimeLaneSession, diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs index e7d68d4954..7c95628379 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs @@ -2,11 +2,19 @@ use super::*; fn fixture(lanes: u32) -> Result>> { + fixture_with_batch(lanes, None) +} + +fn fixture_with_batch(lanes: u32, batch: Option<(u32, u32)>) -> Result>> { let path = std::env::var_os("SKIPPY_WARMUP_STAGE_CONFIG") .context("set SKIPPY_WARMUP_STAGE_CONFIG to a full causal-model stage config")?; let mut config: StageConfig = serde_json::from_slice(&std::fs::read(path)?)?; config.lane_count = lanes; config.cache_idle_slots = None; + if let Some((n_batch, n_ubatch)) = batch { + config.n_batch = Some(n_batch); + config.n_ubatch = Some(n_ubatch); + } crate::runtime_state::load_runtime(&config)?.context("fixture must load a native model") } @@ -47,6 +55,74 @@ fn full_idle_pool_warms_repeatedly_and_all_lanes_still_decode() -> Result<()> { Ok(()) } +#[test] +#[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] +fn serving_shape_warmup_keeps_every_lane_usable() -> Result<()> { + for lanes in [1, 4] { + let runtime = fixture(lanes)?; + let mut runtime = runtime.lock().unwrap(); + runtime.prewarm_idle_sessions(lanes as usize)?; + runtime.warmup_serving_shapes(64)?; + // The shape warmup borrows and releases lanes; the pool must be + // whole again and every lane must still decode. + assert_eq!(runtime.idle_sessions.len(), lanes as usize); + assert!( + runtime + .idle_sessions + .iter() + .all(|lane| lane.session.token_count() == 0) + ); + let token = runtime.model.tokenize("Hello", true)?[0]; + let prediction = runtime + .session("shape-warmup-request")? + .decode_step(token)?; + assert!(prediction >= 0); + } + Ok(()) +} + +#[test] +#[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] +fn serving_shape_warmup_respects_loaded_batch_capacity() -> Result<()> { + // Cover clamped prefill and a decode wave at the batch limit. The native + // loader cannot construct a context with more lanes than batch tokens. + for (lanes, n_batch, n_ubatch) in [(4, 64, 512), (4, 4, 4)] { + let runtime = fixture_with_batch(lanes, Some((n_batch, n_ubatch)))?; + let mut runtime = runtime.lock().unwrap(); + runtime.prewarm_idle_sessions(lanes as usize)?; + assert_eq!( + runtime.idle_sessions[0].session.batch_size()?, + n_batch as usize + ); + for _ in 0..2 { + runtime.warmup_serving_shapes(n_ubatch as usize)?; + assert_eq!(runtime.idle_sessions.len(), lanes as usize); + assert!(runtime.free_lane_indices.is_empty()); + assert!( + runtime + .idle_sessions + .iter() + .all(|lane| lane.session.token_count() == 0) + ); + } + let token = runtime.model.tokenize("Hello", true)?[0]; + let mut predictions = Vec::new(); + for index in 0..lanes { + predictions.push( + runtime + .session(&format!("bounded-{index}"))? + .decode_step(token)?, + ); + } + assert!( + predictions + .iter() + .all(|prediction| *prediction == predictions[0]) + ); + } + Ok(()) +} + #[test] #[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] fn temporary_warmup_releases_capacity_with_idle_pool_disabled() -> Result<()> { @@ -55,6 +131,7 @@ fn temporary_warmup_releases_capacity_with_idle_pool_disabled() -> Result<()> { runtime.max_idle_sessions = Some(0); for _ in 0..3 { assert!(runtime.warmup_generation_graph()?); + runtime.warmup_serving_shapes(64)?; assert!(runtime.idle_sessions.is_empty()); assert_eq!(runtime.next_lane_index, 1); assert_eq!(runtime.free_lane_indices, [0]); diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs index 4f04eda759..983b90c6ff 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -6,7 +6,10 @@ use std::{ fs::{File, Metadata}, io::{BufReader, Read}, path::{Path, PathBuf}, - sync::atomic::{AtomicBool, Ordering}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, time::{Instant, SystemTime}, }; @@ -16,8 +19,15 @@ type ObservedFiles = Vec<(String, PathBuf, FileStamp)>; pub(crate) struct VerifiedModelContent { digest: String, files: ObservedFiles, + /// A stamp written within the timestamp-granularity window can hide a + /// same-length rewrite, so such proofs are rechecked by content. + racy: bool, } +/// Coarse filesystem clocks (e.g. ext4 ctime ticks) can leave a rewrite in the +/// same tick with an identical stamp; treat recent stamps as untrusted. +const RACY_STAMP_WINDOW: std::time::Duration = std::time::Duration::from_secs(2); + #[derive(Clone, PartialEq, Eq)] struct FileStamp { bytes: u64, @@ -44,6 +54,29 @@ impl FileStamp { ), } } + + fn is_racy(&self, now: SystemTime) -> bool { + #[cfg(unix)] + let changed = u64::try_from(self.identity.2).ok().map(|secs| { + SystemTime::UNIX_EPOCH + + std::time::Duration::new(secs, self.identity.3.clamp(0, 999_999_999) as u32) + }); + #[cfg(not(unix))] + let changed = None; + [self.modified, self.created, changed] + .into_iter() + .any(|time| match time { + Some(time) => now + .duration_since(time) + .map_or(true, |age| age < RACY_STAMP_WINDOW), + None => true, + }) + } +} + +fn any_racy(files: &ObservedFiles) -> bool { + let now = SystemTime::now(); + files.iter().any(|(_, _, stamp)| stamp.is_racy(now)) } impl VerifiedModelContent { @@ -53,9 +86,15 @@ impl VerifiedModelContent { pub(crate) fn verify_during_load( config: &StageConfig, load: impl FnOnce() -> Result, - ) -> Result<(T, Option)> { + ) -> Result<(T, Option>)> { #[cfg(unix)] let (model, content) = match Self::observe_files(config).ok().flatten() { + // Recent stamps cannot prove the bytes the loader reads, so hash + // before load and recheck content afterwards instead. + Some(files) if any_racy(&files) => { + let content = Self::from_observed(files, &AtomicBool::new(false)).ok(); + (load()?, content) + } Some(files) => { verify_alongside_load(load, |cancelled| Self::from_observed(files, cancelled))? } @@ -66,7 +105,10 @@ impl VerifiedModelContent { let content = Self::observe(config).ok().flatten(); (load()?, content) }; - Ok((model, content.filter(|proof| proof.still_matches(config)))) + Ok(( + model, + content.and_then(|proof| Arc::new(proof).revalidate(config)), + )) } #[cfg(any(not(unix), test))] @@ -87,13 +129,14 @@ impl VerifiedModelContent { capture_files(files).map(Some) } - #[cfg(any(not(unix), test))] + #[cfg(test)] fn from_files(files: Vec<(String, PathBuf)>) -> Result { Self::from_observed(capture_files(files)?, &AtomicBool::new(false)) } fn from_observed(files: ObservedFiles, cancelled: &AtomicBool) -> Result { let started = Instant::now(); + let racy = any_racy(&files); let mut verified_bytes = 0_u64; let mut digest = Sha256::new(); digest.update(b"skippy-loaded-model-content-v1\0"); @@ -146,38 +189,22 @@ impl VerifiedModelContent { Ok(Self { digest, files: observed, + racy, }) } - /// Reject a proof if model input selection or bytes changed while opening. - pub(crate) fn still_matches(&self, config: &StageConfig) -> bool { - let Ok(files) = source_files(config) else { - return false; - }; - let unchanged = files.len() == self.files.len() - && files.iter().zip(&self.files).all( - |((name, path), (expected_name, expected_path, stamp))| { - name == expected_name - && path == expected_path - && std::fs::metadata(path).is_ok_and(|metadata| { - metadata.is_file() && FileStamp::read(&metadata) == *stamp - }) - }, - ); - if !unchanged { - return false; + /// Reuse strong file stamps or refresh the proof by hashing the same inputs. + pub(crate) fn revalidate(self: Arc, config: &StageConfig) -> Option> { + let files = capture_files(source_files(config).ok()?).ok()?; + if files != self.files { + return None; } - #[cfg(unix)] - { - true - } - #[cfg(not(unix))] - { - // Size and last-write timestamps are not a strong file identity on - // these platforms. Recheck actual content after model open and at - // backend construction rather than trusting preserved timestamps. - Self::from_files(files).is_ok_and(|current| current.digest == self.digest) + if cfg!(unix) && !self.racy { + return Some(self); } + // Recent or missing timestamps and non-Unix stamps require a digest check. + let refreshed = Self::from_observed(files, &AtomicBool::new(false)).ok()?; + (refreshed.digest == self.digest).then(|| Arc::new(refreshed)) } pub(crate) fn bind(&self, identity: &str) -> String { @@ -437,6 +464,7 @@ mod tests { Ok(VerifiedModelContent { digest: "proof".into(), files: Vec::new(), + racy: false, }) }, ) @@ -479,8 +507,9 @@ mod tests { source_model_sha256: Some("ab".repeat(32)), ..StageConfig::default() }; - let first = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); - assert!(first.still_matches(&config)); + let first = + Arc::new(VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap()); + assert!(first.clone().revalidate(&config).is_some()); let modified = model.metadata().unwrap().modified().unwrap(); wait_for_ctime_to_advance_past(&model); std::fs::write(&model, b"other weights").unwrap(); @@ -490,7 +519,7 @@ mod tests { .unwrap() .set_times(std::fs::FileTimes::new().set_modified(modified)) .unwrap(); - assert!(!first.still_matches(&config)); + assert!(first.clone().revalidate(&config).is_none()); let second = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); assert_ne!(first.bind("same namespace"), second.bind("same namespace")); config.model_path = Some( @@ -499,7 +528,24 @@ mod tests { .to_string_lossy() .into_owned(), ); - assert!(!second.still_matches(&config)); + assert!(Arc::new(second).revalidate(&config).is_none()); + } + + #[test] + fn revalidation_keeps_the_refreshed_proof_when_it_rehashes() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("model.gguf"); + std::fs::write(&path, b"weights").unwrap(); + let config = StageConfig { + model_path: Some(path.to_string_lossy().into_owned()), + ..StageConfig::default() + }; + let mut proof = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); + proof.racy = true; + let proof = Arc::new(proof); + let refreshed = proof.clone().revalidate(&config).unwrap(); + assert!(!Arc::ptr_eq(&refreshed, &proof)); + assert_eq!(refreshed.digest, proof.digest); } #[test] diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 03e358678c..271cd5093a 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -1,8 +1,9 @@ -From 1fc84889eba64be3be623ac2dadb8ccf82e53fe3 Mon Sep 17 00:00:00 2001 +From bdf3bfa0cce61bfb5fbd467c1f2c3788fbf11422 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 -Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs +Subject: [PATCH] feat(skippy): realize admitted stages from live graphs +Co-authored-by: Melkor --- common/common.cpp | 109 --- common/common.h | 20 +- @@ -23,7 +24,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/llama-memory-hybrid-idx.cpp | 10 + src/llama-memory-hybrid-idx.h | 4 + src/skippy/abi.cpp | 59 ++ - src/skippy/activation.cpp | 1028 ++++++++++++++++++++ + src/skippy/activation.cpp | 1028 +++++++++++++++++++ src/skippy/activation_internal.h | 88 ++ src/skippy/activation_layout.cpp | 164 ++++ src/skippy/block_boundaries.cpp | 64 ++ @@ -37,7 +38,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/events_internal.h | 35 + src/skippy/executable_graph.cpp | 335 +++++++ src/skippy/executable_graph.h | 37 + - src/skippy/execution-batch.cpp | 499 ++++++++++ + src/skippy/execution-batch.cpp | 515 ++++++++++ src/skippy/execution-single.cpp | 642 ++++++++++++ src/skippy/execution_internal.h | 20 + src/skippy/glm_dsa.cpp | 857 ++++++++++++++++ @@ -50,7 +51,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/model_lifecycle.cpp | 155 +++ src/skippy/model_load_config.cpp | 213 ++++ src/skippy/model_load_config_internal.h | 35 + - src/skippy/model_loading.cpp | 1189 +++++++++++++++++++++++ + src/skippy/model_loading.cpp | 1189 ++++++++++++++++++++++ src/skippy/model_loading_internal.h | 38 + src/skippy/model_package.cpp | 782 +++++++++++++++ src/skippy/model_source.cpp | 463 +++++++++ @@ -73,7 +74,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/stage_realization.h | 21 + src/skippy/stage_slice_plan.cpp | 907 +++++++++++++++++ src/skippy/stage_slice_plan.h | 136 +++ - src/skippy/state.cpp | 1189 +++++++++++++++++++++++ + src/skippy/state.cpp | 1195 +++++++++++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ src/skippy/state_memory.cpp | 116 +++ @@ -83,7 +84,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/workloads.cpp | 373 +++++++ src/skippy/workloads_internal.h | 8 + tests/test-batch-alloc.cpp | 21 + - 79 files changed, 16496 insertions(+), 407 deletions(-) + 79 files changed, 16518 insertions(+), 407 deletions(-) create mode 100644 common/log-terminal.cpp create mode 100644 common/regex-escape.cpp create mode 100644 common/sampling-config.cpp @@ -4067,10 +4068,10 @@ index 000000000..aa02187d1 + std::string & error); diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp new file mode 100644 -index 000000000..2b9593e0c +index 000000000..31a65905b --- /dev/null +++ b/src/skippy/execution-batch.cpp -@@ -0,0 +1,499 @@ +@@ -0,0 +1,515 @@ +#include "skippy.h" +#include "skippy/activation_internal.h" +#include "skippy/errors.h" @@ -4485,9 +4486,25 @@ index 000000000..2b9593e0c + return SKIPPY_STATUS_RUNTIME_ERROR; + } + skippy_mark_context_work_pending(first->stage_model); -+ skippy_synchronize_context_if_pending(first->stage_model); + + size_t sampled_index = 0; ++ // Synchronize only when this iteration consumes GPU results: a sampled ++ // last token or a batched activation export. Prefill ++ // chunks without any of those return with the context still pending, so ++ // the scheduler prepares and the backend encodes the next chunk while ++ // the GPU still executes this one; command-queue order sequences the ++ // chunks' KV writes and reads. The Rust sizing protocol always passes a ++ // non-null descriptor array, so gate on the sessions that actually emit ++ // activation frames rather than on the array pointer. ++ const bool consumes_gpu_results = std::any_of( ++ requests, requests + request_count, ++ [](const skippy_iteration_request & request) { ++ return request.sample_last || ++ skippy_emits_activation_frame(request.session); ++ }); ++ if (consumes_gpu_results) { ++ skippy_synchronize_context_if_pending(first->stage_model); ++ } + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; + status = skippy_copy_batched_exports( @@ -15213,10 +15230,10 @@ index 000000000..1cb24c7cb + std::string & error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp new file mode 100644 -index 000000000..f035ea13f +index 000000000..d4a5c9673 --- /dev/null +++ b/src/skippy/state.cpp -@@ -0,0 +1,1189 @@ +@@ -0,0 +1,1195 @@ +#include "skippy/state.h" +#include "skippy/state_memory.h" +#include "skippy/errors.h" @@ -15822,6 +15839,9 @@ index 000000000..f035ea13f + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session, descriptor, and payload are required"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } ++ // Imports can write host-visible KV buffers before any backend submission. ++ session->ctx->synchronize(); ++ skippy_mark_context_synchronized(session->stage_model); + std::string error; + bool ok = false; + bool invalid_argument = false; @@ -15885,6 +15905,9 @@ index 000000000..f035ea13f + return SKIPPY_STATUS_INVALID_ARGUMENT; + } + ++ // Fence before either cache mutation or composite-import rollback. ++ session->ctx->synchronize(); ++ skippy_mark_context_synchronized(session->stage_model); + std::string error; + bool ok = false; + bool unsupported = false; @@ -17958,3 +17981,6 @@ index c41e91d61..eee60d81d 100644 t.test("token_batch_explicit_fields", [&](testing & t) { llama_token token[3] = { 5, 6, 7 }; llama_pos pos[3] = { 3, 4, 5 }; +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index 984f82f56c..13463d990c 100644 --- a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -1,8 +1,7 @@ -From b9ec689e4254c785289de4dbabf440d34f8e9fd4 Mon Sep 17 00:00:00 2001 +From 69e8740d65764e61c73895ee0e25294922b177a4 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 -Subject: [PATCH 03/32] feat(llama): integrate live stage planning and - execution +Subject: [PATCH] feat(llama): integrate live stage planning and execution Graph node-budget migration debt: @@ -20,12 +19,12 @@ the owning model builders supply that bound, retain the shared LoRA and sampler additions, and test reserved ubatch sizes and stage boundaries against actual node counts on CPU, Metal and CUDA. Remove the architecture branches only after those bounds cover their current allowances and parity/reservation tests pass. - +Co-authored-by: Melkor --- include/llama.h | 7 + src/llama-arch.cpp | 22 + src/llama-arch.h | 2 + - src/llama-context.cpp | 573 +++++++++-- + src/llama-context.cpp | 578 +++++++++-- src/llama-context.h | 99 +- src/llama-ext.h | 6 + src/llama-graph.h | 6 + @@ -47,7 +46,7 @@ those bounds cover their current allowances and parity/reservation tests pass. src/llama-quant.cpp | 12 +- src/llama.cpp | 91 +- src/skippy-verify-checkpoint.h | 24 + - 25 files changed, 3066 insertions(+), 338 deletions(-) + 25 files changed, 3069 insertions(+), 340 deletions(-) create mode 100644 src/skippy-verify-checkpoint.h diff --git a/include/llama.h b/include/llama.h @@ -139,7 +138,7 @@ index 3b8f45d26..cd34e36a9 100644 LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, LLM_KV_ATTENTION_INDEXER_TYPES, diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index d597273a2..082b3229c 100644 +index d597273a2..26c5ebbb6 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -13,10 +13,16 @@ @@ -473,7 +472,49 @@ index d597273a2..082b3229c 100644 if (sampler && model.split_mode() == LLAMA_SPLIT_MODE_TENSOR) { static bool warned = false; if (!warned) { -@@ -1779,6 +1870,7 @@ void llama_context::set_adapters_lora(llama_adapter_lora ** adapters, size_t n_a +@@ -1721,7 +1812,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + warned = true; + } + if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a ++ // detach must not force the next request to re-reserve. + } + sampling.samplers.erase(seq_id); + return false; +@@ -1740,6 +1832,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers[seq_id] = sampler; + ++ // Each attached chain can grow the graph, including a replacement. ++ // Preserve any reservation already required by a shape change. + sched_need_reserve = true; + + return true; +@@ -1748,10 +1842,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + if (sampler && !can_offload) { + LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id); + +- if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; +- } +- ++ // Detaching only shrinks what the reservation must cover; a detach ++ // must not force the next request to re-reserve. + sampling.samplers.erase(seq_id); + + return false; +@@ -1759,7 +1851,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers.erase(seq_id); + +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a detach must ++ // not force the next request to re-reserve. + + return true; + } +@@ -1779,6 +1872,7 @@ void llama_context::set_adapters_lora(llama_adapter_lora ** adapters, size_t n_a } } @@ -481,7 +522,7 @@ index d597273a2..082b3229c 100644 sched_need_reserve = true; } -@@ -1818,12 +1910,18 @@ bool llama_context::set_adapter_cvec( +@@ -1818,12 +1912,18 @@ bool llama_context::set_adapter_cvec( bool res = cvec->apply(model, data, len, n_embd, il_start, il_end); @@ -501,7 +542,7 @@ index d597273a2..082b3229c 100644 if (mctx && !mctx->apply()) { LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); ret = GGML_STATUS_FAILED; -@@ -1835,7 +1933,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1835,7 +1935,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll // the new graph parameters // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters @@ -510,7 +551,7 @@ index d597273a2..082b3229c 100644 if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); -@@ -1867,6 +1965,16 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1867,6 +1967,16 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } @@ -527,7 +568,7 @@ index d597273a2..082b3229c 100644 if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) { LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__); ret = GGML_STATUS_ALLOC_FAILED; -@@ -1881,7 +1989,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1881,7 +1991,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll //const auto t_start_us = ggml_time_us(); // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated @@ -536,7 +577,7 @@ index d597273a2..082b3229c 100644 //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); } -@@ -1899,6 +2007,12 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1899,6 +2009,12 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll } int llama_context::encode(const llama_batch_ext & batch_inp) { @@ -549,31 +590,22 @@ index d597273a2..082b3229c 100644 if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; -@@ -1936,6 +2050,10 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { - // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot - GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens"); - -+ if (t_compute_start_us == 0) { -+ t_compute_start_us = ggml_time_us(); -+ } -+ - // TODO: this clear of the buffer can easily be forgotten - need something better - // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { -@@ -1943,11 +2061,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1943,12 +2059,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } embd_seq.clear(); -- if (t_compute_start_us == 0) { -- t_compute_start_us = ggml_time_us(); -- } ++ sched_reserve(graph_build_inputs); ++ + if (t_compute_start_us == 0) { + t_compute_start_us = ggml_time_us(); + } - - sched_reserve(); -+ sched_reserve(graph_build_inputs); - +- n_queued_tokens += n_tokens; -@@ -1974,7 +2088,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { + const uint32_t n_outputs_all = balloc->get_n_outputs(); +@@ -1974,7 +2089,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { cparams.causal_attn = false; ggml_status status; @@ -582,7 +614,7 @@ index d597273a2..082b3229c 100644 cparams.causal_attn = causal_attn_org; -@@ -2094,6 +2208,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -2094,6 +2209,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return 0; } @@ -607,7 +639,7 @@ index d597273a2..082b3229c 100644 template static void copy_tensor_async_rows( const std::vector & tensors, -@@ -2147,9 +2279,15 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); - -+ if (t_compute_start_us == 0) { -+ t_compute_start_us = ggml_time_us(); -+ } -+ n_queued_tokens += n_tokens_all; -+ - // TODO: this clear of the buffer can easily be forgotten - need something better - // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { +@@ -2245,21 +2385,20 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { synchronize(); } embd_seq.clear(); -- -- if (t_compute_start_us == 0) { -- t_compute_start_us = ggml_time_us(); -- } -- n_queued_tokens += n_tokens_all; -- - output_swaps.clear(); - embd_batch_idxs.clear(); - -- sched_reserve(); ++ output_swaps.clear(); ++ embd_batch_idxs.clear(); ++ + sched_reserve(graph_build_inputs); + if (t_compute_start_us == 0) { + t_compute_start_us = ggml_time_us(); + } + n_queued_tokens += n_tokens_all; + +- output_swaps.clear(); +- embd_batch_idxs.clear(); +- +- sched_reserve(); +- bool did_optimize = false; // handle any pending shifts/copies @@ -679,7 +703,7 @@ index d597273a2..082b3229c 100644 llama_memory_context_ptr mctx; -@@ -2284,7 +2422,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2284,7 +2423,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (!did_optimize) { did_optimize = true; @@ -688,7 +712,7 @@ index d597273a2..082b3229c 100644 LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens()); continue; -@@ -2312,11 +2450,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2312,11 +2451,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -2; }; @@ -700,7 +724,7 @@ index d597273a2..082b3229c 100644 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2375,7 +2508,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2375,7 +2509,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_status status; @@ -714,7 +738,7 @@ index d597273a2..082b3229c 100644 if (!res) { // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module -@@ -2513,9 +2651,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2513,9 +2652,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { const uint32_t n_embd = hparams.n_embd_out(); float * embd_nextn_out = embd_nextn.data + offset*n_embd; @@ -738,7 +762,7 @@ index d597273a2..082b3229c 100644 extract_all_idxs = extract_all_idxs || !masked; } } -@@ -2527,7 +2678,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2527,7 +2679,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { embd_batch_idxs.insert(embd_batch_idxs.end(), batch_idxs.begin(), batch_idxs.end()); } @@ -749,7 +773,7 @@ index d597273a2..082b3229c 100644 const auto stride = n_vocab; // async copy the sampling data from the backend to the host -@@ -2539,6 +2692,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2539,6 +2693,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { n_outputs_prev += n_outputs; n_tokens_prev += ubatch.n_tokens; @@ -760,7 +784,7 @@ index d597273a2..082b3229c 100644 } while (mctx->next()); if (layer_inp_dev && ev_layer_inp_written) { -@@ -2824,9 +2981,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -2824,9 +2982,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -773,7 +797,7 @@ index d597273a2..082b3229c 100644 for (size_t s = 0; s < output_swaps.size(); ++s) { const uint64_t i0 = output_swaps[s].i0; -@@ -2839,6 +2996,7 @@ void llama_context::output_reorder() { +@@ -2839,6 +2997,7 @@ void llama_context::output_reorder() { } if (embd.size > 0) { @@ -781,7 +805,7 @@ index d597273a2..082b3229c 100644 for (uint64_t k = 0; k < n_embd_out; k++) { std::swap(embd.data[i0*n_embd_out + k], embd.data[i1*n_embd_out + k]); } -@@ -2909,6 +3067,8 @@ void llama_context::output_reorder() { +@@ -2909,6 +3068,8 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { @@ -790,7 +814,7 @@ index d597273a2..082b3229c 100644 uint32_t res; if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || model.arch == LLM_ARCH_HRM_TEXT) { -@@ -2936,10 +3096,13 @@ uint32_t llama_context::graph_max_nodes() const { +@@ -2936,10 +3097,13 @@ uint32_t llama_context::graph_max_nodes() const { // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft res = std::max(1024u, 12u*model.n_tensors()); } else { @@ -808,7 +832,7 @@ index d597273a2..082b3229c 100644 } // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling -@@ -2979,7 +3142,6 @@ static void ubatch_prepare_reserve( +@@ -2979,7 +3143,6 @@ static void ubatch_prepare_reserve( } } @@ -816,7 +840,7 @@ index d597273a2..082b3229c 100644 std::vector sampler_seqs; std::vector has_sampler(n_seqs, false); for (const auto & entry : samplers) { -@@ -2987,40 +3149,83 @@ static void ubatch_prepare_reserve( +@@ -2987,40 +3150,83 @@ static void ubatch_prepare_reserve( if (seq_id < 0 || (uint32_t) seq_id >= n_seqs) { continue; } @@ -907,7 +931,7 @@ index d597273a2..082b3229c 100644 LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); -@@ -3045,16 +3250,40 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3045,16 +3251,40 @@ ggml_cgraph * llama_context::graph_reserve( llama_batch_allocr balloc(model.hparams.n_pos_per_embd()); llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs); @@ -949,7 +973,7 @@ index d597273a2..082b3229c 100644 // check the graph before scheduling: cross-backend copies break the producer chain that the check follows if (!hadamard_verified && gf && (!model.hdmd.rot.empty() || !model.hdmd.inv.empty())) { -@@ -3063,6 +3292,130 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3063,6 +3293,130 @@ ggml_cgraph * llama_context::graph_reserve( } this->n_input_tensors = llama_graph_n_input_tensors(gf); @@ -1080,7 +1104,7 @@ index d597273a2..082b3229c 100644 this->n_outputs = save_n_outputs; // initialize scheduler with the specified graph -@@ -3085,7 +3438,18 @@ llm_graph_params llama_context::graph_params( +@@ -3085,7 +3439,18 @@ llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, const llama_memory_context_i * mctx, @@ -1100,7 +1124,7 @@ index d597273a2..082b3229c 100644 return { /*.model =*/ &model, /*.hparams =*/ model.hparams, -@@ -3106,6 +3470,9 @@ llm_graph_params llama_context::graph_params( +@@ -3106,6 +3471,9 @@ llm_graph_params llama_context::graph_params( /*.h_nextn_dev =*/ cparams.embeddings_nextn_dev ? h_nextn_dev : nullptr, /*.h_nextn_src =*/ supports_state_row() ? cparams.ctx_state_src->get_h_nextn_dev() : nullptr, /*.samplers =*/ sampling.samplers, @@ -1110,7 +1134,7 @@ index d597273a2..082b3229c 100644 /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, -@@ -4325,7 +4692,8 @@ void llama_context::opt_epoch_iter( +@@ -4325,7 +4693,8 @@ void llama_context::opt_epoch_iter( auto * res = get_gf_res_prev(); @@ -1120,7 +1144,7 @@ index d597273a2..082b3229c 100644 // the optimizer graph is allocated outside sched, so the next decode must rebuild gf_res_prev_active = nullptr; -@@ -4431,7 +4799,7 @@ llama_context_params llama_context_default_params() { +@@ -4431,7 +4800,7 @@ llama_context_params llama_context_default_params() { /*.n_seq_max =*/ 1, /*.n_rs_seq =*/ 0, /*.n_outputs_max =*/ 0, @@ -1129,7 +1153,7 @@ index d597273a2..082b3229c 100644 /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS, /*.ctx_type =*/ LLAMA_CONTEXT_TYPE_DEFAULT, -@@ -4469,9 +4837,10 @@ llama_context_params llama_context_default_params() { +@@ -4469,9 +4838,10 @@ llama_context_params llama_context_default_params() { return result; } @@ -1143,7 +1167,7 @@ index d597273a2..082b3229c 100644 if (!model) { LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__); return nullptr; -@@ -4491,6 +4860,10 @@ llama_context * llama_init_from_model( +@@ -4491,6 +4861,10 @@ llama_context * llama_init_from_model( LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__); params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; } @@ -1154,7 +1178,7 @@ index d597273a2..082b3229c 100644 if (model->split_mode() == LLAMA_SPLIT_MODE_TENSOR) { if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) { -@@ -4590,15 +4963,14 @@ llama_context * llama_init_from_model( +@@ -4590,15 +4964,14 @@ llama_context * llama_init_from_model( model->hparams.pooling_type, params.pooling_type); } @@ -1172,7 +1196,7 @@ index d597273a2..082b3229c 100644 const auto & cparams = ctx->get_cparams(); if (cparams.rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN && cparams.rope_freq_scale != model->hparams.rope_freq_scale_train) { -@@ -4615,6 +4987,12 @@ llama_context * llama_init_from_model( +@@ -4615,6 +4988,12 @@ llama_context * llama_init_from_model( return nullptr; } @@ -1185,7 +1209,7 @@ index d597273a2..082b3229c 100644 // deprecated llama_context * llama_new_context_with_model( llama_model * model, -@@ -4861,7 +5239,8 @@ struct ggml_cgraph * llama_graph_reserve( +@@ -4861,7 +5240,8 @@ struct ggml_cgraph * llama_graph_reserve( if (memory) { mctx = memory->init_full(); } @@ -1195,7 +1219,7 @@ index d597273a2..082b3229c 100644 } // llama adapter API -@@ -5113,13 +5492,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla +@@ -5113,13 +5493,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla // compat: llama_batch -> llama_batch_ext -> encode/decode int llama_context::encode(const llama_batch & batch_inp) { @@ -1225,7 +1249,7 @@ index d597273a2..082b3229c 100644 } /// -@@ -5138,7 +5529,11 @@ int32_t llama_encode( +@@ -5138,7 +5530,11 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { @@ -5369,3 +5393,6 @@ index 000000000..8793000c1 + checkpoints.erase(it); + return true; +} +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 67abef0157..e4ef61efc5 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -1,9 +1,12 @@ -From bf3f7c50c6f91dec75704e4c79bbe91f8f4542bb Mon Sep 17 00:00:00 2001 +From f1b7fd6e06d38c305f214533e7c59587a67e922d Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:43 +1100 -Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts +Subject: [PATCH] test(skippy): cover live graph and state contracts +Co-authored-by: Melkor --- + src/CMakeLists.txt | 9 + + src/skippy/tests/async_state.cpp | 245 +++ .../tests/cast_destination_regression.h | 27 + src/skippy/tests/embedding_input_regression.h | 91 + src/skippy/tests/graph_build_inputs.cpp | 948 ++++++++++ @@ -42,7 +45,8 @@ Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts tests/test-skippy-rerank-template.cpp | 34 + tests/test-skippy-sampling-suppress.cpp | 90 + ...st-skippy-verify-checkpoint-retirement.cpp | 26 + - 38 files changed, 10272 insertions(+), 30 deletions(-) + 40 files changed, 10526 insertions(+), 30 deletions(-) + create mode 100644 src/skippy/tests/async_state.cpp create mode 100644 src/skippy/tests/cast_destination_regression.h create mode 100644 src/skippy/tests/embedding_input_regression.h create mode 100644 src/skippy/tests/graph_build_inputs.cpp @@ -76,6 +80,277 @@ Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts create mode 100644 tests/test-skippy-sampling-suppress.cpp create mode 100644 tests/test-skippy-verify-checkpoint-retirement.cpp +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 2bc7d6f6e..dc8465589 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -270,6 +270,15 @@ if (LLAMA_STAGE_BUILD_TESTS) + set_tests_properties(skippy_runtime_event_native_model_load_production PROPERTIES + FIXTURES_REQUIRED skippy-model-loader-fixtures) + ++ add_executable(skippy-async-state-test skippy/tests/async_state.cpp) ++ target_include_directories(skippy-async-state-test PRIVATE .) ++ target_compile_features(skippy-async-state-test PRIVATE cxx_std_17) ++ target_link_libraries(skippy-async-state-test PRIVATE llama) ++ add_test(NAME skippy_async_state_contracts COMMAND skippy-async-state-test ++ "${SKIPPY_MODEL_FIXTURE_DIR}/gemma-dense.gguf") ++ set_tests_properties(skippy_async_state_contracts PROPERTIES ++ FIXTURES_REQUIRED skippy-model-loader-fixtures) ++ + add_executable(skippy-noalloc-graph-planning + skippy/tests/noalloc_graph_planning.cpp) + target_include_directories(skippy-noalloc-graph-planning PRIVATE .) +diff --git a/src/skippy/tests/async_state.cpp b/src/skippy/tests/async_state.cpp +new file mode 100644 +index 000000000..efe8d28ba +--- /dev/null ++++ b/src/skippy/tests/async_state.cpp +@@ -0,0 +1,245 @@ ++#include "../runtime_support.h" ++#include "../runtime_types.h" ++#include "../selected_logits.h" ++#include "skippy.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(condition) \ ++ do { \ ++ if (!(condition)) { \ ++ std::fprintf(stderr, "CHECK failed: %s (%s:%d)\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); \ ++ } \ ++ } while (0) ++ ++namespace { ++ ++void queue_prefill(skippy_session * session) { ++ const llama_token tokens[] = { 0, 1 }; ++ skippy_iteration_request request{}; ++ request.session = session; ++ request.token_ids = tokens; ++ request.token_count = 2; ++ size_t sampled = 0; ++ skippy_error * error = nullptr; ++ CHECK(skippy_iteration_batch_sampled(&request, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, &sampled, ++ &error) == SKIPPY_STATUS_OK); ++ CHECK(sampled == 0); ++ CHECK(session->stage_model->context_work_pending.load()); ++} ++ ++void test_import_error_fences(skippy_session * source, skippy_session * fresh) { ++ skippy_kv_page_desc page{}; ++ page.codec = UINT32_MAX; ++ const uint8_t payload = 0; ++ skippy_error * error = nullptr; ++ queue_prefill(source); ++ CHECK(skippy_import_kv_page(source, &page, &payload, 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ skippy_error_free(error); ++ error = nullptr; ++ ++ // A failed import has no trailing fence; it must drain the shared context ++ // before entering the mutation/rollback path, even on another lane. ++ queue_prefill(source); ++ skippy_cachegen_record_v1 record{}; ++ CHECK(skippy_import_cachegen_kv_page_v1(fresh, &page, &record, 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ skippy_error_free(error); ++} ++ ++void test_plain_restore_parity(skippy_session * source, skippy_session * target) { ++ skippy_error * error = nullptr; ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ queue_prefill(source); ++ skippy_kv_page_desc page{}; ++ size_t bytes = 0; ++ const int layers = source->stage_model->model->hparams.n_layer(); ++ CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, nullptr, 0, &bytes, &error) == ++ SKIPPY_STATUS_BUFFER_TOO_SMALL); ++ skippy_error_free(error); ++ error = nullptr; ++ CHECK(bytes > 0); ++ std::vector payload(bytes); ++ CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, payload.data(), payload.size(), &bytes, &error) == ++ SKIPPY_STATUS_OK); ++ ++ const int vocab = llama_vocab_n_tokens(llama_model_get_vocab(source->stage_model->model)); ++ const int selected = std::min(vocab, static_cast(SKIPPY_MAX_SELECTED_TOKENS)); ++ std::vector ids(selected); ++ for (int i = 0; i < selected; ++i) { ++ ids[i] = selected == 1 ? 0 : static_cast(i) * (vocab - 1) / (selected - 1); ++ } ++ std::vector reference(selected); ++ for (int attempt = 0; attempt < 9; ++attempt) { ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_reset(target, &error) == SKIPPY_STATUS_OK); ++ queue_prefill(source); ++ if (attempt == 0) { ++ source->ctx->synchronize(); ++ skippy_mark_context_synchronized(source->stage_model); ++ } ++ CHECK(skippy_import_kv_page(target, &page, payload.data(), payload.size(), &error) == SKIPPY_STATUS_OK); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ std::vector scores(selected); ++ skippy_token_score_request readout{ ids.data(), ids.size(), scores.data() }; ++ const llama_token token = 2; ++ skippy_iteration_request request{}; ++ request.session = target; ++ request.token_ids = &token; ++ request.token_count = 1; ++ request.readout = &readout; ++ size_t sampled = 0; ++ CHECK(skippy_iteration_batch_sampled(&request, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, ++ &sampled, &error) == SKIPPY_STATUS_OK); ++ CHECK(sampled == 0); ++ if (attempt == 0) { ++ reference = scores; ++ } ++ for (int i = 0; i < selected; ++i) { ++ CHECK(std::isfinite(scores[i])); ++ CHECK(std::fabs(scores[i] - reference[i]) <= 1e-5f); ++ } ++ } ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_reset(target, &error) == SKIPPY_STATUS_OK); ++} ++ ++void decode_attached_samplers(skippy_session * first, skippy_session * second, llama_pos position) { ++ llama_batch batch = llama_batch_init(2, 0, 1); ++ batch.n_tokens = 2; ++ for (int i = 0; i < 2; ++i) { ++ batch.token[i] = 1; ++ batch.pos[i] = position; ++ batch.n_seq_id[i] = 1; ++ batch.seq_id[i][0] = i == 0 ? first->seq_id : second->seq_id; ++ batch.logits[i] = 1; ++ } ++ CHECK(llama_decode(first->ctx, batch) == 0); ++ first->ctx->synchronize(); ++ CHECK(llama_get_sampled_token_ith(first->ctx, 0) != LLAMA_TOKEN_NULL); ++ CHECK(llama_get_sampled_token_ith(first->ctx, 1) != LLAMA_TOKEN_NULL); ++ llama_batch_free(batch); ++} ++ ++void test_pooled_embedding_accounting(const skippy_model * model) { ++ auto params = llama_context_default_params(); ++ params.n_ctx = 64; ++ params.n_batch = 64; ++ params.n_ubatch = 64; ++ params.n_threads = 1; ++ params.n_threads_batch = 1; ++ params.embeddings = true; ++ params.pooling_type = LLAMA_POOLING_TYPE_MEAN; ++ params.no_perf = false; ++ llama_context * ctx = llama_init_from_model(model->model, params); ++ CHECK(ctx != nullptr); ++ ++ llama_token tokens[] = { 0, 1, 2 }; ++ const auto first = llama_batch_get_one(tokens, 2); ++ const auto second = llama_batch_get_one(tokens, 3); ++ ++ // Size the output buffer before measuring the embedding cleanup fence. ++ CHECK(llama_decode(ctx, second) == 0); ++ CHECK(llama_get_embeddings_seq(ctx, 0) != nullptr); ++ llama_perf_context_reset(ctx); ++ ++ CHECK(llama_decode(ctx, first) == 0); ++ // Starting the second batch fences the first batch's pooled outputs. ++ CHECK(llama_decode(ctx, second) == 0); ++ CHECK(llama_perf_context(ctx).n_p_eval == first.n_tokens); ++ llama_synchronize(ctx); ++ CHECK(llama_get_embeddings_seq(ctx, 0) != nullptr); ++ CHECK(llama_perf_context(ctx).n_p_eval == first.n_tokens + second.n_tokens); ++ llama_free(ctx); ++} ++ ++void test_sampler_reservations(skippy_session * first, skippy_session * second) { ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.repeat_penalty = 1.0f; ++ sampling.reasoning_budget_tokens = -1; ++ skippy_error * error = nullptr; ++ CHECK(skippy_session_configure_chat_sampling(first, &sampling, "{}", 0, &error) == SKIPPY_STATUS_OK); ++ CHECK(first->sampling_backend_enabled); ++ first->ctx->sched_reserve(); ++ uint64_t reserved = first->ctx->get_sched_reserve_count(); ++ ++ first->ctx->set_embeddings(true); ++ llama_sampler * shape_chain = llama_sampler_chain_init(llama_sampler_chain_default_params()); ++ llama_sampler_chain_add(shape_chain, llama_sampler_init_dist(42)); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, shape_chain)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ first->ctx->set_embeddings(false); ++ first->ctx->sched_reserve(); ++ reserved = first->ctx->get_sched_reserve_count(); ++ ++ CHECK(skippy_session_configure_chat_sampling(second, &sampling, "{}", 0, &error) == SKIPPY_STATUS_OK); ++ CHECK(second->sampling_backend_enabled); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ reserved = first->ctx->get_sched_reserve_count(); ++ ++ decode_attached_samplers(first, second, 0); ++ llama_sampler * replacement = llama_sampler_chain_init(llama_sampler_chain_default_params()); ++ llama_sampler_chain_add(replacement, llama_sampler_init_top_k(20)); ++ llama_sampler_chain_add(replacement, llama_sampler_init_dist(88)); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, replacement)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ decode_attached_samplers(first, second, 1); ++ const uint64_t reserved_before_detach = first->ctx->get_sched_reserve_count(); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, nullptr)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() == reserved_before_detach); ++ llama_sampler_free(replacement); ++ llama_sampler_free(shape_chain); ++} ++ ++} // namespace ++ ++int main(int argc, char ** argv) { ++ CHECK(argc >= 2 && argc <= 4); ++ const char * mode = argc == 4 ? argv[3] : "all"; ++ CHECK(std::strcmp(mode, "all") == 0 || std::strcmp(mode, "imports") == 0 || std::strcmp(mode, "restore") == 0 || ++ std::strcmp(mode, "samplers") == 0); ++ skippy_runtime_config config = skippy_runtime_config_default(); ++ config.lane_count = 2; ++ config.n_batch = 64; ++ config.n_ubatch = 64; ++ config.selected_backend_device = argc >= 3 ? argv[2] : "CPU"; ++ config.n_gpu_layers = std::strcmp(config.selected_backend_device, "CPU") == 0 ? 0 : 99; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ CHECK(skippy_model_open(argv[1], &config, &model, &error) == SKIPPY_STATUS_OK); ++ skippy_session * first = nullptr; ++ skippy_session * second = nullptr; ++ CHECK(skippy_session_create(model, &first, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_create(model, &second, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "imports") == 0) { ++ test_import_error_fences(first, second); ++ } ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "restore") == 0) { ++ test_plain_restore_parity(first, second); ++ } ++ CHECK(skippy_session_reset(first, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "samplers") == 0) { ++ test_sampler_reservations(first, second); ++ } ++ CHECK(skippy_session_free(first, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_free(second, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0) { ++ test_pooled_embedding_accounting(model); ++ } ++ CHECK(skippy_model_free(model, &error) == SKIPPY_STATUS_OK); ++ return 0; ++} diff --git a/src/skippy/tests/cast_destination_regression.h b/src/skippy/tests/cast_destination_regression.h new file mode 100644 index 000000000..84da82c91 @@ -10926,3 +11201,6 @@ index 000000000..d09acccb4 + if (skippy_retire_verify_checkpoint_exact(checkpoints, 10, 3)) return 6; + return 0; +} +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch b/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch index 0d58d5379f..68feb16786 100644 --- a/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch +++ b/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch @@ -1,19 +1,18 @@ -From 20bd1020fa04e7f55bdf30fa2201abbd20a53213 Mon Sep 17 00:00:00 2001 +From 4762ecd45539dcd02163ecc3111ff665db043fbd Mon Sep 17 00:00:00 2001 From: IvGolovach <20299097+IvGolovach@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:00:00 -0700 -Subject: [PATCH 10/32] feat(skippy): read selected token scores in causal - batches +Subject: [PATCH] feat(skippy): read selected token scores in causal batches Keep full vocabulary logits on the terminal worker and read bounded conditional log probabilities before another iteration can replace them. Readouts do not invoke samplers or advance generation history. --- include/skippy/execution.h | 19 ++++++++++ - src/CMakeLists.txt | 4 +++ - src/skippy/execution-batch.cpp | 52 +++++++++++++++++++++++++++- - src/skippy/selected_logits.h | 43 +++++++++++++++++++++++ + src/CMakeLists.txt | 4 ++ + src/skippy/execution-batch.cpp | 56 ++++++++++++++++++++++++++-- + src/skippy/selected_logits.h | 43 +++++++++++++++++++++ src/skippy/tests/selected_logits.cpp | 25 +++++++++++++ - 5 files changed, 142 insertions(+), 1 deletion(-) + 5 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 src/skippy/selected_logits.h create mode 100644 src/skippy/tests/selected_logits.cpp @@ -55,7 +54,7 @@ index 7098677d8..bf9fb497c 100644 /** diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 2bc7d6f6e..05108ad38 100644 +index dc8465589..a2cd419b3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -168,6 +168,10 @@ endif() @@ -70,7 +69,7 @@ index 2bc7d6f6e..05108ad38 100644 skippy/tests/hardware_application_probe.cpp) target_include_directories(skippy-hardware-application-probe PRIVATE .) diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 2b9593e0c..86ea1ed55 100644 +index 31a65905b..07ccf0b7a 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -5,6 +5,7 @@ @@ -150,7 +149,25 @@ index 2b9593e0c..86ea1ed55 100644 for (int32_t axis = 0; axis < n_pos_per_embd; ++axis) { const size_t destination = static_cast(axis)*total_tokens + flat; if (request.positions != nullptr) { -@@ -429,6 +469,16 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -415,7 +455,7 @@ enum skippy_status skippy_iteration_batch_sampled( + + size_t sampled_index = 0; + // Synchronize only when this iteration consumes GPU results: a sampled +- // last token or a batched activation export. Prefill ++ // last token, a causal readout, or a batched activation export. Prefill + // chunks without any of those return with the context still pending, so + // the scheduler prepares and the backend encodes the next chunk while + // the GPU still executes this one; command-queue order sequences the +@@ -425,7 +465,7 @@ enum skippy_status skippy_iteration_batch_sampled( + const bool consumes_gpu_results = std::any_of( + requests, requests + request_count, + [](const skippy_iteration_request & request) { +- return request.sample_last || ++ return request.sample_last || request.readout != nullptr || + skippy_emits_activation_frame(request.session); + }); + if (consumes_gpu_results) { +@@ -445,6 +485,16 @@ enum skippy_status skippy_iteration_batch_sampled( request.session->sampling_backend_row_invalid = false; request.session->n_past += static_cast(request.token_count); skippy_record_tokens(request.session, request.token_ids, request.token_count); @@ -247,3 +264,6 @@ index 000000000..d33237d1a + if (skippy_selected_log_probabilities(inf.data(), inf.size(), selected.data() + 1, 1, result.data())) return 8; + return 0; +} +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch index fed63180f3..284199d0a0 100644 --- a/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch +++ b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch @@ -1,8 +1,7 @@ -From cf937afd998fce2d584ed5ed092205deded25a01 Mon Sep 17 00:00:00 2001 +From a922d83e220feb2a4f00fd7d8b9837c131aee5b7 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 2 Nov 2026 09:00:00 +1100 -Subject: [PATCH 19/32] skippy: report native trace spans and GPU command - timing +Subject: [PATCH] skippy: report native trace spans and GPU command timing skippy/tracing.h reports where time goes inside a native call, for a caller that already times the call itself. skippy_set_native_span_callback @@ -463,7 +462,7 @@ index e12c55a39..f89c8ebe6 100644 [cmd_buf commit]; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index 8c21125d5..7c42724af 100644 +index 9ab481093..db9889c79 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -5,6 +5,7 @@ @@ -511,7 +510,7 @@ index 8c21125d5..7c42724af 100644 if (!dev->library) { GGML_LOG_ERROR("%s: error: failed to create library\n", __func__); } -@@ -2305,6 +2314,8 @@ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { +@@ -2323,6 +2332,8 @@ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { return true; } @@ -520,7 +519,7 @@ index 8c21125d5..7c42724af 100644 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { MTLResidencySetDescriptor * desc = [[MTLResidencySetDescriptor alloc] init]; -@@ -2364,6 +2375,10 @@ static void * ggml_metal_host_malloc(size_t n) { +@@ -2382,6 +2393,10 @@ static void * ggml_metal_host_malloc(size_t n) { } ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared) { @@ -531,7 +530,7 @@ index 8c21125d5..7c42724af 100644 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); res->dev = dev; -@@ -2434,6 +2449,10 @@ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, +@@ -2452,6 +2467,10 @@ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, } ggml_metal_buffer_t ggml_metal_buffer_map(ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size) { @@ -542,7 +541,7 @@ index 8c21125d5..7c42724af 100644 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); res->dev = dev; -@@ -2588,6 +2607,9 @@ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * +@@ -2606,6 +2625,9 @@ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * return; } @@ -552,7 +551,7 @@ index 8c21125d5..7c42724af 100644 @autoreleasepool { // src void * data_ptr = (void *)(uintptr_t) data; // "const cast" the src data -@@ -2644,6 +2666,8 @@ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_ten +@@ -2662,6 +2684,8 @@ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_ten return; } @@ -1461,7 +1460,7 @@ index 000000000..e9e57357c + +#endif // SKIPPY_TRACING_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 75cb30503..6e4e9023b 100644 +index 211edbe3b..0e0970876 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -64,6 +64,7 @@ add_library(llama @@ -1473,7 +1472,7 @@ index 75cb30503..6e4e9023b 100644 skippy/graph_dependencies.cpp skippy/graph_identity.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index e460d2250..b3ec732f9 100644 +index 7cdb0c1f0..545f4eb5b 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -17,6 +17,7 @@ @@ -1484,7 +1483,7 @@ index e460d2250..b3ec732f9 100644 #include #include -@@ -499,6 +500,7 @@ llama_context::llama_context( +@@ -494,6 +495,7 @@ llama_context::llama_context( } if (!hparams.vocab_only) { @@ -1492,7 +1491,7 @@ index e460d2250..b3ec732f9 100644 // GPU backends for (const auto & dev : model.devices) { ggml_backend_t backend = ggml_backend_dev_init(dev.dev, nullptr); -@@ -580,6 +582,8 @@ llama_context::llama_context( +@@ -575,6 +577,8 @@ llama_context::llama_context( /*.no_alloc =*/ model.no_alloc(), }; @@ -1501,7 +1500,7 @@ index e460d2250..b3ec732f9 100644 memory.reset(model.create_memory(params_mem, cparams, graph_build_inputs.selection)); } -@@ -852,6 +856,8 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ +@@ -845,6 +849,8 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ return; } @@ -1510,7 +1509,7 @@ index e460d2250..b3ec732f9 100644 sched_need_reserve = false; ++sched_reserve_count; -@@ -1010,7 +1016,11 @@ void llama_context::synchronize() { +@@ -1014,7 +1020,11 @@ void llama_context::synchronize() { return; } @@ -1523,7 +1522,7 @@ index e460d2250..b3ec732f9 100644 // FIXME: if multiple single tokens are evaluated without a synchronization, // the stats will be added to the prompt evaluation stats -@@ -1138,6 +1148,8 @@ bool llama_context::memory_update( +@@ -1132,6 +1142,8 @@ bool llama_context::memory_update( } } @@ -1532,7 +1531,7 @@ index e460d2250..b3ec732f9 100644 // reset the previous graph results to make sure that they won't be reused // TODO: make mctx->apply() report if a graph reserve is needed, then reset graph results only if the memory module reset the scheduler for (auto & res : gf_res_prev) { -@@ -1790,7 +1802,13 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1926,7 +1938,13 @@ llm_graph_result * llama_context::process_ubatch( llama_memory_context_i * mctx, ggml_status & ret, const skippy_graph_build_inputs & graph_build_inputs) { @@ -1547,7 +1546,7 @@ index e460d2250..b3ec732f9 100644 LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); ret = GGML_STATUS_FAILED; return nullptr; -@@ -1805,6 +1823,7 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1941,6 +1959,7 @@ llm_graph_result * llama_context::process_ubatch( if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); @@ -1555,7 +1554,7 @@ index e460d2250..b3ec732f9 100644 // with pipeline parallelism, the previous graph_compute_async may still be running // on the GPU. we must synchronize before set_inputs to avoid overwriting input tensors -@@ -1823,7 +1842,10 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1959,7 +1978,10 @@ llm_graph_result * llama_context::process_ubatch( //const auto t_start_us = ggml_time_us(); @@ -1566,7 +1565,7 @@ index e460d2250..b3ec732f9 100644 //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); -@@ -1843,11 +1865,13 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1979,11 +2001,13 @@ llm_graph_result * llama_context::process_ubatch( return nullptr; } @@ -1580,7 +1579,7 @@ index e460d2250..b3ec732f9 100644 gf_res_prev_active = res; } -@@ -1857,12 +1881,16 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1993,12 +2017,16 @@ llm_graph_result * llama_context::process_ubatch( //const auto t_start_us = ggml_time_us(); // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated @@ -1597,7 +1596,7 @@ index e460d2250..b3ec732f9 100644 if (status != GGML_STATUS_SUCCESS) { LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status); ret = status; -@@ -2159,6 +2187,8 @@ int llama_context::decode( +@@ -2295,6 +2323,8 @@ int llama_context::decode( return encode(batch_inp, graph_build_inputs); } @@ -1606,7 +1605,7 @@ index e460d2250..b3ec732f9 100644 if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; -@@ -2219,12 +2249,14 @@ int llama_context::decode( +@@ -2361,12 +2391,14 @@ int llama_context::decode( } } @@ -1621,7 +1620,7 @@ index e460d2250..b3ec732f9 100644 const uint32_t n_tokens_all = balloc->get_n_tokens(); const uint32_t n_outputs_all = balloc->get_n_outputs(); -@@ -2265,6 +2297,8 @@ int llama_context::decode( +@@ -2407,6 +2439,8 @@ int llama_context::decode( llama_memory_context_ptr mctx; @@ -1630,7 +1629,7 @@ index e460d2250..b3ec732f9 100644 while (true) { mctx = memory->init_batch(*balloc, cparams.n_ubatch, embd_all); if (!mctx) { -@@ -2308,11 +2342,15 @@ int llama_context::decode( +@@ -2450,11 +2484,15 @@ int llama_context::decode( break; } @@ -1646,7 +1645,7 @@ index e460d2250..b3ec732f9 100644 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2399,6 +2437,9 @@ int llama_context::decode( +@@ -2557,6 +2595,9 @@ int llama_context::decode( // ggml_graph_dump_dot(gf, NULL, "llama.dot"); //} @@ -1656,7 +1655,7 @@ index e460d2250..b3ec732f9 100644 auto * t_logits = res->get_logits(); auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr; auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr; -@@ -2537,10 +2578,13 @@ int llama_context::decode( +@@ -2696,10 +2737,13 @@ int llama_context::decode( copy_tensor_async_rows(res->t_candidates, sampling.candidates, stride, n_outputs_prev, sched.get(), &sampling.candidates_count); } @@ -1670,7 +1669,7 @@ index e460d2250..b3ec732f9 100644 ggml_backend_sched_synchronize(sched.get()); } } while (mctx->next()); -@@ -3106,6 +3150,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3273,6 +3317,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); @@ -1679,7 +1678,7 @@ index e460d2250..b3ec732f9 100644 if (n_tokens % n_seqs != 0) { n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs); -@@ -4121,6 +4167,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl +@@ -4288,6 +4334,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl } size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) { @@ -1687,7 +1686,7 @@ index e460d2250..b3ec732f9 100644 std::unique_ptr io; if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { io = std::make_unique(dst, size, mem_storage[seq_id]); -@@ -4140,6 +4187,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz +@@ -4307,6 +4354,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz } size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) { @@ -1696,7 +1695,7 @@ index e460d2250..b3ec732f9 100644 if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { // create a temporary io to read the magic and the src seq_id diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index fd12f9966..fe7101445 100644 +index b8fdbd578..2f4662742 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1,4 +1,5 @@ @@ -1705,7 +1704,7 @@ index fd12f9966..fe7101445 100644 #include "llama-impl.h" #include "llama-io.h" -@@ -452,6 +453,7 @@ void llama_kv_cache::init_rotation(const char * name_tag) { +@@ -457,6 +458,7 @@ void llama_kv_cache::init_rotation(const char * name_tag) { } void llama_kv_cache::clear(bool data) { @@ -1713,7 +1712,7 @@ index fd12f9966..fe7101445 100644 for (uint32_t s = 0; s < n_stream; ++s) { v_cells[s].reset(); v_heads[s] = 0; -@@ -465,6 +467,7 @@ void llama_kv_cache::clear(bool data) { +@@ -470,6 +472,7 @@ void llama_kv_cache::clear(bool data) { } bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { @@ -1721,7 +1720,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return true; -@@ -567,6 +570,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { +@@ -572,6 +575,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { } void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { @@ -1729,7 +1728,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -659,6 +663,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll +@@ -664,6 +668,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll } void llama_kv_cache::seq_keep(llama_seq_id seq_id) { @@ -1737,7 +1736,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -686,6 +691,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { +@@ -691,6 +696,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { } void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { @@ -1745,7 +1744,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -1636,6 +1642,7 @@ bool llama_kv_cache::stage_export_kv_page( +@@ -1651,6 +1657,7 @@ bool llama_kv_cache::stage_export_kv_page( size_t output_capacity, size_t * out_bytes, std::string & error) const { @@ -1753,7 +1752,7 @@ index fd12f9966..fe7101445 100644 if (out_desc == nullptr || out_bytes == nullptr) { error = "out_desc and out_bytes are required"; return false; -@@ -1878,6 +1885,7 @@ bool llama_kv_cache::stage_import_kv_page( +@@ -1893,6 +1900,7 @@ bool llama_kv_cache::stage_import_kv_page( size_t input_bytes, std::string & error, bool validate_only) { @@ -1761,7 +1760,7 @@ index fd12f9966..fe7101445 100644 if (input == nullptr) { error = "input payload is required"; return false; -@@ -3527,6 +3535,7 @@ ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_co +@@ -3574,6 +3582,7 @@ ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_co } void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { @@ -1769,7 +1768,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -3599,6 +3608,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla +@@ -3646,6 +3655,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla } void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { @@ -1844,7 +1843,7 @@ index b7570d445..c488e921c 100644 uint32_t cell_count; diff --git a/src/llama-model.cpp b/src/llama-model.cpp -index 8ded67e17..f93cbad04 100644 +index 143c1f895..0f4d15e68 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1,4 +1,5 @@ @@ -1853,7 +1852,7 @@ index 8ded67e17..f93cbad04 100644 #include "llama-arch.h" #include "llama-ext.h" -@@ -2193,11 +2194,13 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { +@@ -2203,11 +2204,13 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } // load tensor data @@ -2021,7 +2020,7 @@ index 7167e5f7a..885b602e9 100644 int32_t rc = 0; const bool decoded = skippy_contain_native_failure( diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 40faff815..a31540652 100644 +index 7d7973520..2d34652b9 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -6,6 +6,7 @@ @@ -2049,15 +2048,15 @@ index 40faff815..a31540652 100644 int32_t decode_rc = 0; if (!skippy_contain_native_failure( out_error, [&] { decode_rc = first->ctx->decode(batch, graph_inputs); })) { -@@ -461,6 +465,8 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -460,6 +464,8 @@ enum skippy_status skippy_iteration_batch_sampled( + } skippy_mark_context_work_pending(first->stage_model); - skippy_synchronize_context_if_pending(first->stage_model); + // exports, readouts and sampling, request by request + skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); size_t sampled_index = 0; - for (size_t request_index = 0; request_index < request_count; ++request_index) { - const auto & request = requests[request_index]; + // Synchronize only when this iteration consumes GPU results: a sampled + // last token, a causal readout, or a batched activation export. Prefill diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp index bbc1c2d42..a4bf2a475 100644 --- a/src/skippy/model_loading.cpp @@ -2539,7 +2538,7 @@ index 000000000..9aa48e08c + } +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index b8b159025..638e84e37 100644 +index 7c55e2c5f..ce3fe92ac 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -185,6 +185,9 @@ llama_build_and_test(test-skippy-rerank-template.cpp) @@ -2552,7 +2551,7 @@ index b8b159025..638e84e37 100644 llama_build_and_test(test-skippy-cachegen-import.cpp) llama_build_and_test(test-skippy-sampling-suppress.cpp) llama_build_and_test(test-skippy-kv-page-export.cpp) -@@ -330,6 +333,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) +@@ -344,6 +347,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) if (GGML_METAL) llama_build_and_test(test-skippy-cachegen-metal.cpp) @@ -3034,5 +3033,5 @@ index 000000000..804c2f7e0 + return 0; +} -- -2.43.0 +2.56.0 diff --git a/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch index 11f828c08b..3b34a2b0eb 100644 --- a/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch +++ b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch @@ -1,7 +1,7 @@ -From 53c13a8bef39b480fb887be77cbed4602cadb63f Mon Sep 17 00:00:00 2001 +From 316ea6dea9b1b29b384fa6b7382dae0c20db8bb8 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 5 Nov 2026 01:00:00 +1100 -Subject: [PATCH 20/32] skippy: sample a batch's requests concurrently +Subject: [PATCH] skippy: sample a batch's requests concurrently An iteration's sampled requests waited for one another: after the batch's outputs were recorded, each request ran its sampler chain in turn on the @@ -48,7 +48,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 src/skippy/tests/concurrent_sampling.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 6e4e9023b..7eee0656e 100644 +index 0e0970876..7da1090f3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -82,6 +82,7 @@ add_library(llama @@ -59,7 +59,7 @@ index 6e4e9023b..7eee0656e 100644 skippy/sampling_config.cpp skippy/chat_sampling.cpp skippy/sampling_vocab.cpp -@@ -493,6 +494,17 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -502,6 +503,17 @@ if (LLAMA_STAGE_BUILD_TESTS) endfunction() add_skippy_sampling_history_state_tests(granitehybrid skippy-noalloc-granite-hybrid-fixture recurrent) @@ -78,10 +78,10 @@ index 6e4e9023b..7eee0656e 100644 NAME skippy_generate_qwen3_fixture COMMAND skippy-model-fixture-generator diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index b3ec732f9..d9068d348 100644 +index 545f4eb5b..8b751f7e4 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -1011,8 +1011,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ +@@ -1015,8 +1015,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ __func__, (t_end_us - t_start_us)/1000.0, ggml_backend_sched_get_n_copies(sched.get())); } @@ -109,7 +109,7 @@ index b3ec732f9..d9068d348 100644 return; } -@@ -2860,6 +2878,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -3031,6 +3049,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -120,7 +120,7 @@ index b3ec732f9..d9068d348 100644 const uint64_t n_embd = model.hparams.n_embd; const uint64_t n_embd_out = model.hparams.n_embd_out(); diff --git a/src/llama-context.h b/src/llama-context.h -index f8884668f..919813ac8 100644 +index d699a1088..020f55b78 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -66,6 +66,36 @@ struct llama_memory_buffer { @@ -171,10 +171,10 @@ index f8884668f..919813ac8 100644 const llama_cparams & get_cparams() const; const skippy_graph_build_inputs & get_graph_build_inputs() const; diff --git a/src/llama-graph.h b/src/llama-graph.h -index 2622c5878..54fd815ef 100644 +index 0e4431fe6..6364da9f8 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h -@@ -1674,7 +1674,7 @@ struct llm_graph_context { +@@ -1689,7 +1689,7 @@ struct llm_graph_context { int32_t state_size, int32_t n_seqs, skippy_state_kind kind, int il, @@ -307,7 +307,7 @@ index 000000000..0c253ca71 +// same time, one thread each; the rest sample first, on this thread. +std::vector skippy_sample_requests(const std::vector & requests); diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index a31540652..83c290ee2 100644 +index 2d34652b9..46b0d1a27 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -1,5 +1,6 @@ @@ -317,7 +317,7 @@ index a31540652..83c290ee2 100644 #include "skippy/errors.h" #include "skippy/graph_build_inputs.h" #include "skippy/runtime_support.h" -@@ -467,7 +468,10 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -466,7 +467,10 @@ enum skippy_status skippy_iteration_batch_sampled( // exports, readouts and sampling, request by request skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); @@ -326,10 +326,10 @@ index a31540652..83c290ee2 100644 + // once every request's outputs are recorded + std::vector samples; + std::vector sample_request_indexes; - for (size_t request_index = 0; request_index < request_count; ++request_index) { - const auto & request = requests[request_index]; - status = skippy_copy_batched_exports( -@@ -495,16 +499,19 @@ enum skippy_status skippy_iteration_batch_sampled( + // Synchronize only when this iteration consumes GPU results: a sampled + // last token, a causal readout, or a batched activation export. Prefill + // chunks without any of those return with the context still pending, so +@@ -511,16 +515,19 @@ enum skippy_status skippy_iteration_batch_sampled( if (request.sample_last && request_logits) { // Logits are indexed by the original batch row; llama.cpp handles // sparse output-row translation internally. @@ -617,5 +617,5 @@ index 000000000..0e19dbce5 + return 0; +} -- -2.43.0 +2.56.0 diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 80c9400aad..e5ee629b22 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -528,6 +528,7 @@ if [[ "$LLAMA_STAGE_WORKLOAD_ORACLE" == "ON" ]]; then fi if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then BUILD_TARGETS+=( + skippy-async-state-test skippy-backend-sample-capacity skippy-graph-build-inputs skippy-hardware-application-probe