diff --git a/Cargo.toml b/Cargo.toml index 476db3d1..ced7c591 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,11 @@ tokio-tungstenite = "0.29" cognitive_complexity = "warn" too_many_lines = "warn" +# Hardware cache qualification uses the cold-prefill budget when staging a +# disk restore. Keep the pack digest on the same optimized path as release. +[profile.dev.package.blake3] +opt-level = 3 + [profile.dev.package.sha2] opt-level = 3 diff --git a/crates/skippy-api/src/family_policy.rs b/crates/skippy-api/src/family_policy.rs index 423c7d88..0bba7b00 100644 --- a/crates/skippy-api/src/family_policy.rs +++ b/crates/skippy-api/src/family_policy.rs @@ -53,6 +53,7 @@ impl FamilyPolicy { max_entries: bounded_entries, max_bytes, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-api/src/native-recipe.json b/crates/skippy-api/src/native-recipe.json index 2c5b51b7..58b09b09 100644 --- a/crates/skippy-api/src/native-recipe.json +++ b/crates/skippy-api/src/native-recipe.json @@ -1,4 +1,4 @@ { "llama_upstream_sha": "09c1410642fa0395ca234571980093bc5c7f2ef5", - "patch_queue_sha256": "d041c8627af7278b018ca3b5c8c534e376f12cdb215ed05ac811aa22aae8b91a" + "patch_queue_sha256": "6309a388e7bb1e21b610c93c546ade5b48e50b32b276b28b453f699a8651355b" } \ No newline at end of file diff --git a/crates/skippy-cache/src/identity.rs b/crates/skippy-cache/src/identity.rs index 86e76ddc..a5d8aa46 100644 --- a/crates/skippy-cache/src/identity.rs +++ b/crates/skippy-cache/src/identity.rs @@ -1078,6 +1078,7 @@ mod identity_stability_tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: StageKvCacheCodec::CacheGen, min_tokens: 64, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-cache/src/l2/mod.rs b/crates/skippy-cache/src/l2/mod.rs index 0a73565c..4bbf2380 100644 --- a/crates/skippy-cache/src/l2/mod.rs +++ b/crates/skippy-cache/src/l2/mod.rs @@ -3,7 +3,7 @@ //! The radix cache (L1) holds resident payloads; the L3 tier holds the same //! state durably on disk as content-addressed packed segments. This module //! adds the missing middle tier: a bounded host-RAM cache of *immutable -//! packed segments*, keyed and identified exactly like the L3 entries they +//! checkpoint bytes*, keyed and identified exactly like the L3 entries they //! mirror. //! //! Contract (mirrors `crate::tier::L3Tier`): @@ -20,7 +20,7 @@ //! entry's L3 manifest segment list onto those handles. A longer prefix //! that extends a shorter one references the same segment handles, so //! turn growth shares prefix bytes instead of duplicating them — L2 RAM -//! tracks *distinct segment* bytes, not per-prefix assembled bytes. +//! tracks *distinct segment* bytes. //! - **Integrity**: the whole concatenated L3 wire digest (the manifest key) //! is verified exactly once, at admission, against the payload being //! admitted. After admission the segment bytes are immutable, so every @@ -35,12 +35,13 @@ //! first admission pays for it. //! - **Zero-copy reads**: `get` clones handles, not bytes; the returned //! `CacheBytes` is a block-backed view over the shared segment storages, -//! contiguous in the single-segment case. +//! contiguous in the single-segment case. Native import can consume the +//! shared segments directly. //! //! `skippy-server` wires this tier as a bounded mirror of repeated or //! high-value L3 fills. An L2 hit rewarms L1. use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, ops::Range, sync::{ Arc, Mutex, @@ -52,7 +53,8 @@ use std::{ use crate::PayloadCodec; use crate::payload::{CacheBytes, ExactStatePayload, ExactStatePayloadKind}; use crate::{ - HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION, SegmentCodecIdentity, segment_digest, + CHECKPOINT_MANIFEST_VERSION, HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION, + SegmentCodecIdentity, segment_digest, }; const DIRECT_SEGMENT_BYTES: usize = 1024 * 1024; @@ -91,8 +93,7 @@ pub struct L2Stats { pub entries: u64, /// Sum of entries' distinct segment charges — the live budget usage. pub bytes: u64, - /// Sum of entry payload lengths including cross-entry sharing; larger - /// than `bytes` exactly when entries share prefix segments. + /// Sum of entry payload lengths, including cross-entry sharing. pub logical_bytes: u64, /// Distinct immutable segment handles currently held. pub segments: u64, @@ -229,13 +230,13 @@ impl ExactStatePayloadMirror { /// Segment digests in wire order, deduplicated. fn segment_digests(&self) -> Vec<&str> { - let mut seen = Vec::new(); - for (digest, _) in &self.layout().segments { - if !seen.contains(&digest.as_str()) { - seen.push(digest.as_str()); - } - } - seen + let mut seen = HashSet::new(); + self.layout() + .segments + .iter() + .map(|(digest, _)| digest.as_str()) + .filter(|digest| seen.insert(*digest)) + .collect() } } @@ -260,13 +261,16 @@ impl L2Hit { /// `Cow` on `as_cow`. pub fn to_payload(&self) -> crate::payload::ExactStatePayload { let layout = self.payload.layout(); - let wire = self.wire_view(0..layout.total_bytes); match self.payload.kind() { crate::payload::ExactStatePayloadKind::FullState => { - crate::payload::ExactStatePayload::FullState { bytes: wire } + crate::payload::ExactStatePayload::FullState { + bytes: self.wire_view(0..layout.total_bytes), + } } crate::payload::ExactStatePayloadKind::RecurrentOnly => { - crate::payload::ExactStatePayload::RecurrentOnly { recurrent: wire } + crate::payload::ExactStatePayload::RecurrentOnly { + recurrent: self.wire_view(0..layout.total_bytes), + } } crate::payload::ExactStatePayloadKind::KvRecurrent => { // Split the wire at kv_bytes exactly like L3 load does: kv @@ -280,6 +284,23 @@ impl L2Hit { } } + /// Borrows the verified KV portion in wire order. The last segment may + /// also contain recurrent bytes, which are outside this view. + pub fn kv_chunks(&self) -> Option> { + let layout = self.payload.layout(); + if layout.payload_kind != ExactStatePayloadKind::KvRecurrent { + return None; + } + let kv_len = layout.kv_bytes.min(layout.total_bytes); + let end = layout + .segments + .partition_point(|(_, range)| range.start < kv_len); + Some(layout.segments[..end].iter().map(move |(digest, range)| { + let len = (range.end.min(kv_len) - range.start) as usize; + &self.segments[digest].bytes[..len] + })) + } + /// Block-backed `CacheBytes` over `range` of the assembled wire, in /// wire order. Blocks outside `range` are skipped; edge blocks are /// narrowed to the overlap. Byte-identical views share the same @@ -625,6 +646,42 @@ impl L2Tier { self.budget_bytes } + /// Mirror the exact layout of a checkpoint without hashing its bytes as + /// a second, monolithic object. The shared admission path verifies every + /// segment before installing it in the immutable pool. + pub fn admit_manifest_payload( + &self, + cache_key: String, + manifest: &HandoffManifest, + payload: &ExactStatePayload, + ) -> Result, L2InsertRefusal> { + let mirror = ExactStatePayloadMirror::from_manifest(manifest)?; + let digest = manifest.payload_digest.clone(); + if manifest.version != CHECKPOINT_MANIFEST_VERSION { + let (wire, _, _) = payload_wire(payload)?; + return self.admit( + cache_key, + manifest.token_count, + digest, + &wire, + mirror, + L2Origin::FromL3, + ); + } + manifest + .verify_checkpoint() + .map_err(|error| L2InsertRefusal::MalformedManifest(error.to_string()))?; + let (wire, _, _) = payload_wire(payload)?; + self.admit_segments( + cache_key, + manifest.token_count, + digest, + &wire, + mirror, + L2Origin::FromL3, + ) + } + /// Admit an exact-state payload restored from the authoritative L3 tier. /// /// The payload is cut into stable one-MiB content chunks. This preserves @@ -726,6 +783,18 @@ impl L2Tier { actual, }); } + self.admit_segments(cache_key, token_count, payload_digest, wire, mirror, origin) + } + + fn admit_segments( + &self, + cache_key: String, + token_count: u64, + payload_digest: String, + wire: &[u8], + mirror: ExactStatePayloadMirror, + origin: L2Origin, + ) -> Result, L2InsertRefusal> { let payload_bytes = mirror.byte_len(); if payload_bytes == 0 { // Mirrors L3: an empty payload cannot represent state. @@ -752,8 +821,9 @@ impl L2Tier { let mut new_segments: Vec<(String, SegmentHandle)> = Vec::new(); let mut new_bytes = 0u64; let mut shared_bytes = 0u64; - for &(digest, slice) in segments.iter() { - if new_segments.iter().any(|(d, _)| d == digest) { + let mut seen = HashSet::with_capacity(segments.len()); + for (digest, slice) in segments { + if !seen.insert(digest) { // Within-admission duplicate digest: the validation pass // already proved both slices have identical content, so // keep the first copy. @@ -786,22 +856,18 @@ impl L2Tier { .to_string(), }); } - new_bytes = new_bytes.saturating_add(slice.len() as u64); - new_segments.push(( - digest.to_string(), - SegmentHandle { - bytes: Arc::new(slice.to_vec()), - }, - )); + let handle = SegmentHandle { + bytes: Arc::new(slice.to_vec()), + }; + new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64); + new_segments.push((digest.to_string(), handle)); } None => { - new_bytes = new_bytes.saturating_add(slice.len() as u64); - new_segments.push(( - digest.to_string(), - SegmentHandle { - bytes: Arc::new(slice.to_vec()), - }, - )); + let handle = SegmentHandle { + bytes: Arc::new(slice.to_vec()), + }; + new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64); + new_segments.push((digest.to_string(), handle)); } } } @@ -1182,23 +1248,26 @@ impl L2Tier { /// corruption cleanup, and rollback alike. Deterministic: identical /// map states produce identical ownership. fn recompute_all_charges(inner: &mut L2Inner) { - let mut ownership: HashMap = HashMap::new(); - for digest in inner.segments.keys() { - let Some(bytes) = inner.segments.get(digest).map(|h| h.bytes.len() as u64) else { - continue; - }; - let owner = inner - .map - .iter() - .filter(|(_, entry)| entry.payload.segment_digests().contains(&digest.as_str())) - .map(|(key, _)| key.clone()) - .min(); - if let Some(owner) = owner { - *ownership.entry(owner).or_insert(0) += bytes; + let mut owners = HashMap::<&str, &str>::with_capacity(inner.segments.len()); + for (key, entry) in &inner.map { + for (digest, _) in &entry.payload.layout().segments { + let owner = owners.entry(digest).or_insert(key); + *owner = (*owner).min(key); + } + } + let mut charges = HashMap::::with_capacity(inner.map.len()); + for (digest, owner) in owners { + if let Some(segment) = inner.segments.get(digest) { + let bytes = segment.bytes.len() as u64; + if let Some(charge) = charges.get_mut(owner) { + *charge += bytes; + } else { + charges.insert(owner.to_owned(), bytes); + } } } for (key, entry) in inner.map.iter_mut() { - entry.charge_bytes = ownership.get(key).copied().unwrap_or(0); + entry.charge_bytes = charges.get(key).copied().unwrap_or(0); } } @@ -1404,6 +1473,50 @@ mod tests { l2_cache_key("model-a", "state-a", namespace, tokens) } + #[test] + fn kv_chunks_borrow_shared_segments_and_exclude_recurrent_bytes() { + let tier = L2Tier::new(16); + let admit = |key: &str, wire: &[u8], kv_bytes: u64| { + let mut start = 0; + let segments = wire + .chunks(4) + .map(|chunk| { + let end = start + chunk.len() as u64; + let segment = (segment_digest(chunk), start..end); + start = end; + segment + }) + .collect(); + let layout = L2Layout { + payload_kind: ExactStatePayloadKind::KvRecurrent, + total_bytes: wire.len() as u64, + kv_bytes, + recurrent_bytes: wire.len() as u64 - kv_bytes, + kv_desc_json: None, + segments, + }; + tier.admit( + key.into(), + 2, + segment_digest(wire), + wire, + ExactStatePayloadMirror::KvRecurrent { layout }, + L2Origin::Direct, + ) + .unwrap(); + }; + admit("first", b"abcdefRR", 6); + admit("grown", b"abcdefghiirr", 10); + assert_eq!(tier.stats().bytes, 16); + let first = tier.get("first").unwrap(); + let grown = tier.get("grown").unwrap(); + let first_chunks: Vec<_> = first.kv_chunks().unwrap().collect(); + let grown_chunks: Vec<_> = grown.kv_chunks().unwrap().collect(); + assert_eq!(first_chunks, [b"abcd".as_slice(), b"ef"]); + assert_eq!(grown_chunks, [b"abcd".as_slice(), b"efgh", b"ii"]); + assert_eq!(first_chunks[0].as_ptr(), grown_chunks[0].as_ptr()); + } + #[test] fn admit_get_round_trip_serves_wire_bytes() { let tier = L2Tier::new(1 << 20); @@ -1940,6 +2053,7 @@ mod tests { payload_kind: "kv-recurrent".to_string(), total_bytes: wire_bytes.len() as u64, payload_digest: digest.clone(), + prefix_key: None, segments: vec![ HandoffSegmentRef { index: 0, @@ -2000,6 +2114,7 @@ mod tests { payload_kind: "blob".to_string(), total_bytes: 10, payload_digest: "blake3:aa".to_string(), + prefix_key: None, segments: Vec::new(), kv_bytes: 10, kv_decoded_bytes: 10, @@ -2725,6 +2840,7 @@ mod tests { payload_kind: "full-state".to_string(), total_bytes: 32, payload_digest: digest.clone(), + prefix_key: None, segments: vec![HandoffSegmentRef { index, offset, diff --git a/crates/skippy-cache/src/l3.rs b/crates/skippy-cache/src/l3.rs index 15ca37a3..c42dca83 100644 --- a/crates/skippy-cache/src/l3.rs +++ b/crates/skippy-cache/src/l3.rs @@ -61,6 +61,9 @@ const EVICTION_LOW_WATER_PERCENT: u64 = 85; /// version whose segment lacks it is rejected rather than reinterpreted. pub const MANIFEST_VERSION: u32 = 4; +/// Serving checkpoints address ordered page metadata instead of concatenated bytes. +pub const CHECKPOINT_MANIFEST_VERSION: u32 = 5; + /// The pre-codec-identity manifest format. These entries predate codec /// identity, are always raw by construction, and are decoded as raw through /// the explicit legacy path in [`decode_manifest`]. New manifests are never @@ -313,8 +316,12 @@ pub struct HandoffManifest { #[serde(default)] pub codec: Option, pub total_bytes: u64, - /// BLAKE3 of the assembled payload; also the manifest's key. + /// Manifest key. Older handoff manifests use the digest of the assembled bytes. + /// Serving checkpoints use the digest of the manifest with this field cleared. pub payload_digest: String, + /// The serving prefix coordinate includes the cache namespace and token IDs. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prefix_key: Option, pub segments: Vec, pub kv_bytes: u64, /// Decoded native KV length. Equal to `kv_bytes` for native pages; for a @@ -335,6 +342,32 @@ pub struct HandoffManifest { } impl HandoffManifest { + pub(crate) fn checkpoint_digest(&self) -> Result { + let mut manifest = self.clone(); + manifest.payload_digest.clear(); + let mut hasher = blake3::Hasher::new_derive_key("Skippy L3 checkpoint manifest v5"); + hasher.update(&serde_json::to_vec(&manifest)?); + Ok(hasher.finalize().to_hex().to_string()) + } + + pub(crate) fn verify_checkpoint(&self) -> Result<()> { + if self.version == CHECKPOINT_MANIFEST_VERSION { + if !self + .prefix_key + .as_deref() + .is_some_and(|key| key.strip_prefix("blake3:").is_some_and(packed::is_digest)) + { + bail!("checkpoint manifest has no valid prefix key"); + } + if self.checkpoint_digest()? != self.payload_digest { + bail!("checkpoint manifest does not match its digest"); + } + } else if self.prefix_key.is_some() { + bail!("handoff manifest carries a serving checkpoint prefix key"); + } + Ok(()) + } + pub fn new(state_identity: String, payload_kind: String) -> Self { Self::new_for_model(state_identity.clone(), state_identity, payload_kind) } @@ -352,6 +385,7 @@ impl HandoffManifest { codec: Some(PayloadCodec::raw()), total_bytes: 0, payload_digest: String::new(), + prefix_key: None, segments: Vec::new(), kv_bytes: 0, kv_decoded_bytes: 0, @@ -1173,29 +1207,36 @@ impl HandoffSegmentStore { } /// Store one spill's logical segments in one immutable physical pack. - pub fn try_put_segments<'store>( - &'store self, + pub fn try_put_segments( + &self, segments: &[&[u8]], - ) -> Result>, WriteRefusal>> { - let digests = segments + ) -> Result>, WriteRefusal>> { + let inputs = segments .iter() - .map(|bytes| segment_digest(bytes)) + .map(|bytes| (segment_digest(bytes), *bytes)) .collect::>(); - let holds = digests + let inputs = inputs .iter() - .map(|digest| self.hold_segment(digest)) + .map(|(digest, bytes)| (digest.as_str(), *bytes)) .collect::>(); - let inputs = digests + self.try_put_hashed_segments(&inputs) + } + + /// Callers must compute each digest from the supplied immutable slice. + pub(crate) fn try_put_hashed_segments( + &self, + inputs: &[(&str, &[u8])], + ) -> Result>, WriteRefusal>> { + let holds = inputs .iter() - .zip(segments) - .map(|(digest, bytes)| (digest.as_str(), *bytes)) + .map(|(digest, _)| self.hold_segment(digest)) .collect::>(); - let estimated = self.packed.estimated_new_bytes(&inputs); + let estimated = self.packed.estimated_new_bytes(inputs); let reservation = match self.reserve(estimated)? { Ok(reservation) => reservation, Err(refusal) => return Ok(Err(refusal)), }; - let (packed, new_bytes) = match self.packed.write_batch(&inputs) { + let (packed, new_bytes) = match self.packed.write_batch(inputs) { Ok(result) => result, Err(error) => { self.invalidate_usage(); @@ -1204,13 +1245,12 @@ impl HandoffSegmentStore { }; self.add_usage_bytes(new_bytes); drop(reservation); - Ok(Ok(digests - .into_iter() + Ok(Ok(inputs + .iter() .zip(holds) .zip(packed) - .zip(segments) - .map(|(((digest, hold), packed), bytes)| StoredSegment { - digest, + .map(|(((digest, bytes), hold), packed)| StoredSegment { + digest: (*digest).to_owned(), put: SegmentPut { new: packed.new, bytes: bytes.len() as u64, @@ -1439,13 +1479,14 @@ impl HandoffSegmentStore { Ok(entries.into_iter().map(|(_, stem)| stem).collect()) } - /// Assemble the full payload for a manifest, verifying every segment - /// digest, the tiling, and the whole-payload digest. + /// Assemble a checkpoint from verified pages. Legacy handoff manifests + /// additionally verify the digest of the assembled bytes. pub fn assemble(&self, manifest: &HandoffManifest) -> Result> { validate_manifest_compatibility(manifest)?; let total = usize::try_from(manifest.total_bytes).context("payload exceeds usize")?; let mut payload = Vec::with_capacity(total); - let mut payload_hasher = blake3::Hasher::new(); + let mut payload_hasher = + (manifest.version != CHECKPOINT_MANIFEST_VERSION).then(blake3::Hasher::new); let locations = self .packed .load_manifest_index(&manifest.payload_digest, manifest.segments.len())?; @@ -1478,21 +1519,25 @@ impl HandoffSegmentStore { output_offset: segment.offset, }); } else { - self.append_packed(&packed_requests, &mut payload, &mut payload_hasher)?; + self.append_packed(&packed_requests, &mut payload, payload_hasher.as_mut())?; packed_requests.clear(); let bytes = self.read_segment(&segment.digest)?; - payload_hasher.update(&bytes); + if let Some(hasher) = &mut payload_hasher { + hasher.update(&bytes); + } payload.extend_from_slice(&bytes); } } - self.append_packed(&packed_requests, &mut payload, &mut payload_hasher)?; + self.append_packed(&packed_requests, &mut payload, payload_hasher.as_mut())?; if payload.len() != total { bail!( "assembled {} bytes but manifest records {total}", payload.len() ); } - if payload_hasher.finalize().to_hex().as_str() != manifest.payload_digest { + if payload_hasher + .is_some_and(|hasher| hasher.finalize().to_hex().as_str() != manifest.payload_digest) + { bail!("assembled payload failed manifest digest verification"); } Ok(payload) @@ -1502,12 +1547,9 @@ impl HandoffSegmentStore { &self, requests: &[PackedReadRequest<'_>], payload: &mut Vec, - payload_hasher: &mut blake3::Hasher, + payload_hasher: Option<&mut blake3::Hasher>, ) -> Result<()> { - match self - .packed - .append_many(requests, payload, Some(payload_hasher)) - { + match self.packed.append_many(requests, payload, payload_hasher) { Ok(()) => Ok(()), Err(failure) => { let path = self.packed.pack_path(&failure.pack_digest); @@ -1999,10 +2041,15 @@ fn reject_unsupported_codec(manifest: &HandoffManifest) -> Result<()> { /// and the two legacy formats (pre-codec and payload-level-codec). fn manifest_version_is_supported(version: u32) -> bool { version == MANIFEST_VERSION + || version == CHECKPOINT_MANIFEST_VERSION || version == LEGACY_MANIFEST_VERSION || version == LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION } +fn manifest_has_segment_codecs(version: u32) -> bool { + matches!(version, MANIFEST_VERSION | CHECKPOINT_MANIFEST_VERSION) +} + /// Reject a manifest whose segment codec identities this build cannot decode, /// before any segment is read or reassembled. Also enforces the per-segment /// negotiation contract: every identity must be internally consistent with @@ -2036,7 +2083,7 @@ fn reject_unsupported_segment_codecs(manifest: &HandoffManifest) -> Result<()> { .as_deref() .is_some_and(|descriptor| serde_json::from_str::(descriptor).is_ok()); if has_native_kv - && (manifest.version != MANIFEST_VERSION + && (!manifest_has_segment_codecs(manifest.version) || manifest.payload_kind != "kv-recurrent" || manifest.kv_bytes == 0 || !has_runtime_descriptor @@ -2049,7 +2096,7 @@ fn reject_unsupported_segment_codecs(manifest: &HandoffManifest) -> Result<()> { ); } if has_cachegen_kv - && (manifest.version != MANIFEST_VERSION + && (!manifest_has_segment_codecs(manifest.version) || manifest.payload_kind != "kv-recurrent" || manifest.kv_bytes == 0 || manifest.kv_decoded_bytes == 0 @@ -2183,7 +2230,8 @@ fn validate_manifest_compatibility(manifest: &HandoffManifest) -> Result<()> { manifest.version ); } - if manifest.version == MANIFEST_VERSION { + manifest.verify_checkpoint()?; + if manifest_has_segment_codecs(manifest.version) { require_v4_segment_identities(manifest)?; } reject_unsupported_codec(manifest)?; @@ -2194,7 +2242,7 @@ fn decode_manifest(payload_digest: &str, bytes: &[u8]) -> Result { + MANIFEST_VERSION | CHECKPOINT_MANIFEST_VERSION => { // The current format must stamp both the payload codec and every // per-segment codec identity explicitly. A missing field means it // was stripped to force a reinterpretation of bytes this build @@ -2243,6 +2291,7 @@ fn decode_manifest(payload_digest: &str, bytes: &[u8]) -> Result::new(); let mut pack_segments = Vec::new(); - let mut pack_hasher = blake3::Hasher::new(); + let mut pack_hasher = blake3::Hasher::new_derive_key("Skippy L3 pack page list v1"); let mut candidate_bytes = 0u64; let mut new_digests = HashSet::new(); @@ -140,7 +140,8 @@ impl PackedSegmentStore { candidate_bytes = candidate_bytes .checked_add(bytes.len() as u64) .context("packed object size overflows u64")?; - pack_hasher.update(bytes); + // Page digests are fixed-width and already cover the stored bytes. + pack_hasher.update(digest.as_bytes()); pack_segments.push(*bytes); planned.insert( (*digest).to_string(), @@ -562,7 +563,7 @@ fn write_pack_atomically(path: &Path, segments: &[&[u8]]) -> Result<()> { Ok(()) } -fn is_digest(value: &str) -> bool { +pub(super) fn is_digest(value: &str) -> bool { value.len() == 64 && value .bytes() diff --git a/crates/skippy-cache/src/l3/tests.rs b/crates/skippy-cache/src/l3/tests.rs index 12828f80..926ec864 100644 --- a/crates/skippy-cache/src/l3/tests.rs +++ b/crates/skippy-cache/src/l3/tests.rs @@ -914,7 +914,7 @@ fn future_version_raw_manifest_is_refused_at_commit_and_leaves_no_manifest() { let (mut manifest, held) = manifest_for(&store, &payload, 4096); // A supported (raw) codec but an unknown future version: commit must refuse // it, or it would persist a manifest load_manifest immediately rejects. - manifest.version = MANIFEST_VERSION + 1; + manifest.version = CHECKPOINT_MANIFEST_VERSION + 1; let error = store .commit(&manifest) .expect_err("a future manifest version must not commit"); @@ -938,7 +938,7 @@ fn future_version_raw_manifest_is_refused_before_assembly() { let mut loaded = store .load_manifest(&manifest.payload_digest) .expect("load manifest"); - loaded.version = MANIFEST_VERSION + 1; + loaded.version = CHECKPOINT_MANIFEST_VERSION + 1; let error = store .assemble(&loaded) .expect_err("a future manifest version must not assemble"); diff --git a/crates/skippy-cache/src/lib.rs b/crates/skippy-cache/src/lib.rs index fa242835..007136e6 100644 --- a/crates/skippy-cache/src/lib.rs +++ b/crates/skippy-cache/src/lib.rs @@ -26,13 +26,13 @@ pub use l2::{ l2_cache_key, }; pub use l3::{ - CODEC_CACHEGEN_KV_ENVELOPE, CODEC_CACHEGEN_KV_ENVELOPE_VERSION, CODEC_NATIVE_KV_PAGE, - CODEC_NATIVE_KV_PAGE_VERSION, CODEC_RAW, CODEC_RAW_VERSION, CacheRootInUse, CodecClass, - GeometryBlock, GeometryKind, HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, - LEGACY_MANIFEST_VERSION, LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION, MANIFEST_VERSION, ManifestPin, - PayloadCodec, PayloadGeometry, Reservation, SegmentCodecIdentity, SegmentHold, SegmentPut, - StoreLimits, StorePressure, StoreReconciliation, StoreUsage, StoredSegment, WriteRefusal, - segment_digest, + CHECKPOINT_MANIFEST_VERSION, CODEC_CACHEGEN_KV_ENVELOPE, CODEC_CACHEGEN_KV_ENVELOPE_VERSION, + CODEC_NATIVE_KV_PAGE, CODEC_NATIVE_KV_PAGE_VERSION, CODEC_RAW, CODEC_RAW_VERSION, + CacheRootInUse, CodecClass, GeometryBlock, GeometryKind, HandoffManifest, HandoffSegmentRef, + HandoffSegmentStore, LEGACY_MANIFEST_VERSION, LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION, + MANIFEST_VERSION, ManifestPin, PayloadCodec, PayloadGeometry, Reservation, + SegmentCodecIdentity, SegmentHold, SegmentPut, StoreLimits, StorePressure, StoreReconciliation, + StoreUsage, StoredSegment, WriteRefusal, segment_digest, }; pub use l3_remote::{ FetchStats, KvFetchClient, serve_connection, serve_store, serve_store_with_timeout, @@ -55,7 +55,8 @@ pub use resident::{ pub use source::{ManifestSource, SegmentSource}; pub use tier::{ - CacheGenKvPayload, L3Fill, L3Location, L3Status, L3Tier, l3_namespace_key, l3_prefix_key, + CacheGenKvPayload, L3Fill, L3Location, L3Status, L3Tier, NativeKvExtension, l3_namespace_key, + l3_prefix_key, }; /// llama.cpp's hard sequence-id capacity for one context. diff --git a/crates/skippy-cache/src/manager.rs b/crates/skippy-cache/src/manager.rs index 25243a1d..acb8468a 100644 --- a/crates/skippy-cache/src/manager.rs +++ b/crates/skippy-cache/src/manager.rs @@ -851,7 +851,7 @@ mod tests { fs::write(root.join("manifests/corrupt.json"), b"{").unwrap(); let mut incompatible = crate::HandoffManifest::new("state".to_string(), "full-state".to_string()); - incompatible.version = crate::MANIFEST_VERSION + 1; + incompatible.version = crate::CHECKPOINT_MANIFEST_VERSION + 1; incompatible.payload_digest = "incompatible".to_string(); fs::write( root.join("manifests/incompatible.json"), diff --git a/crates/skippy-cache/src/tier.rs b/crates/skippy-cache/src/tier.rs index e6284972..4e581175 100644 --- a/crates/skippy-cache/src/tier.rs +++ b/crates/skippy-cache/src/tier.rs @@ -10,8 +10,10 @@ use std::sync::atomic::Ordering; +mod native_extension; mod spill_payload; mod spill_segments; +pub use native_extension::NativeKvExtension; use spill_payload::SpillPayload; #[cfg(test)] @@ -20,8 +22,8 @@ use anyhow::{Context, Result, bail}; use serde::Serialize; use crate::l3::{ - HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, MANIFEST_VERSION, PayloadCodec, - PayloadGeometry, StoreLimits, StoreUsage, segment_digest, + CHECKPOINT_MANIFEST_VERSION, HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, + PayloadCodec, PayloadGeometry, StoreLimits, StoreUsage, segment_digest, }; use crate::manager::{ BenefitRestoreObservation, L3ActivitySnapshot, L3CacheManager, L3EffectiveStatus, @@ -48,13 +50,26 @@ pub struct L3Status { /// namespace (which already binds the numerical stage identity) and the /// exact token path. pub fn l3_prefix_key(namespace: &str, token_ids: &[i32]) -> String { + let mut hasher = l3_prefix_hasher(namespace); + hash_l3_tokens(&mut hasher, token_ids); + format!("blake3:{}", hasher.finalize().to_hex()) +} + +fn l3_prefix_hasher(namespace: &str) -> blake3::Hasher { let mut hasher = blake3::Hasher::new(); hasher.update(b"l3-prefix-key-v1"); hasher.update(namespace.as_bytes()); - for token_id in token_ids { - hasher.update(&token_id.to_le_bytes()); + hasher +} + +fn hash_l3_tokens(hasher: &mut blake3::Hasher, token_ids: &[i32]) { + let mut encoded = [0; 4096]; + for tokens in token_ids.chunks(encoded.len() / size_of::()) { + for (bytes, token) in encoded.as_chunks_mut::<4>().0.iter_mut().zip(tokens) { + *bytes = token.to_le_bytes(); + } + hasher.update(&encoded[..size_of_val(tokens)]); } - format!("blake3:{}", hasher.finalize().to_hex()) } /// The namespace's own index key. @@ -88,7 +103,7 @@ pub struct L3Location { pub namespace_key: String, pub prefix_key: String, pub token_count: u64, - /// Manifest key (payload digest) — the identity of the physical entry; + /// Manifest key, the identity of the stored checkpoint and /// the correct single-flight claim key. pub manifest_key: String, /// Metadata copied from the located manifest so the runtime can reject an @@ -101,8 +116,10 @@ pub struct L3Location { } /// A successful fill from the tier. +#[derive(Clone)] pub struct L3Fill { pub payload: ExactStatePayload, + pub manifest: HandoffManifest, /// How many of the query's leading tokens the filled state covers — the /// length the entry was recorded at, which may be shorter than the /// query (longest-recorded-prefix semantics, mirroring the radix). @@ -230,13 +247,10 @@ impl L3Tier { &self, namespace: &str, token_ids: &[i32], - location: &L3Location, + manifest: &HandoffManifest, cold_prefill_cost: Option, restore_cost: f64, ) { - let Ok(manifest) = self.store().load_manifest(&location.manifest_key) else { - return; - }; let shared = manifest .segments .iter() @@ -246,7 +260,7 @@ impl L3Tier { .benefit_observe_restore(BenefitRestoreObservation { state_identity: self.state_identity.clone(), key: benefit_entry_key(namespace, token_ids), - manifest: location.manifest_key.clone(), + manifest: manifest.payload_digest.clone(), exclusive_bytes: 0, shared, cold_prefill_cost, @@ -277,7 +291,7 @@ impl L3Tier { model_identity: self.model_identity.clone(), state_identity: self.state_identity.clone(), effective: self.manager.effective_status(), - format_version: MANIFEST_VERSION, + format_version: CHECKPOINT_MANIFEST_VERSION, usage: self.store().usage()?, restorable_manifests: restorable_manifests as u64, restorable_tokens, @@ -384,15 +398,14 @@ impl L3Tier { let kv_decoded_bytes = wire.decoded_kv_bytes; let kv_bytes = wire.kv_bytes(); let recurrent_bytes = wire.recurrent_bytes(); - let payload_digest = wire.digest(); - let mut manifest = HandoffManifest::new_for_model( self.model_identity.clone(), self.state_identity.clone(), payload.kind().as_str().to_string(), ); + manifest.version = CHECKPOINT_MANIFEST_VERSION; manifest.total_bytes = wire.len() as u64; - manifest.payload_digest = payload_digest.clone(); + manifest.prefix_key = Some(l3_prefix_key(namespace, token_ids)); manifest.kv_bytes = kv_bytes; manifest.kv_decoded_bytes = kv_decoded_bytes; manifest.recurrent_bytes = recurrent_bytes; @@ -457,6 +470,30 @@ impl L3Tier { meta_json: (!cut.label.is_empty()).then(|| cut.label.clone()), }) .collect(); + self.commit_spill( + namespace, + token_ids, + manifest, + segment_slices.into_iter().map(Some).collect(), + cost, + ) + } + + fn commit_spill( + &self, + namespace: &str, + token_ids: &[i32], + mut manifest: HandoffManifest, + fresh_segments: Vec>, + cost: Option, + ) -> Result> { + let prefix_key = manifest + .prefix_key + .clone() + .context("missing checkpoint prefix")?; + let token_count = manifest.token_count; + let payload_digest = manifest.checkpoint_digest()?; + manifest.payload_digest.clone_from(&payload_digest); let exclusive_bytes = serde_json::to_vec(&manifest) .map(|bytes| bytes.len() as u64) .unwrap_or_default(); @@ -474,11 +511,22 @@ impl L3Tier { } if !self.manager.benefit_prepare_write( benefit_key, - (wire.len() as u64).saturating_add(exclusive_bytes), + fresh_segments + .iter() + .flatten() + .fold(exclusive_bytes, |total, bytes| { + total.saturating_add(bytes.len() as u64) + }), )? { return Ok(None); } - let stored_segments = match self.store().try_put_segments(&segment_slices) { + let hashed_segments = manifest + .segments + .iter() + .zip(fresh_segments) + .filter_map(|(segment, bytes)| bytes.map(|bytes| (segment.digest.as_str(), bytes))) + .collect::>(); + let stored_segments = match self.store().try_put_hashed_segments(&hashed_segments) { Ok(Ok(stored)) => stored, Ok(Err(refusal)) => { self.manager.record_write_refusal(refusal); @@ -521,7 +569,7 @@ impl L3Tier { if let Err(error) = self.store().link_prefix( &l3_namespace_key(namespace), token_count, - &l3_prefix_key(namespace, token_ids), + &prefix_key, &payload_digest, ) { self.manager.record_storage_error(); @@ -583,18 +631,40 @@ impl L3Tier { let namespace_key = l3_namespace_key(namespace); let query_len = token_ids.len() as u64; let lengths = self.store().recorded_prefix_lengths(&namespace_key)?; - for length in lengths + let candidates: Vec<_> = lengths .into_iter() .filter(|length| *length > 0 && *length <= query_len) .take(max_probes.max(1)) - { - let prefix_key = l3_prefix_key(namespace, &token_ids[..length as usize]); + .collect(); + // Snapshot each selected prefix from the same token stream. Probe + // disk in the original longest-first order. + let mut hasher = l3_prefix_hasher(namespace); + let mut hashed = 0; + let digests: Vec<_> = candidates + .iter() + .rev() + .map(|&length| { + let end = length as usize; + hash_l3_tokens(&mut hasher, &token_ids[hashed..end]); + hashed = end; + hasher.finalize() + }) + .collect(); + for (length, digest) in candidates.into_iter().zip(digests.into_iter().rev()) { + let prefix_key = format!("blake3:{}", digest.to_hex()); let Some(manifest) = self.store() .manifest_for_prefix(&namespace_key, length, &prefix_key)? else { continue; }; + if manifest + .prefix_key + .as_ref() + .is_some_and(|key| key != &prefix_key) + { + continue; + } if manifest.model_identity != self.model_identity || manifest.state_identity != self.state_identity { @@ -633,13 +703,18 @@ impl L3Tier { /// itself. Full-state fills are whole-blob by nature; kv-recurrent /// fills could stream per segment later. pub fn load(&self, location: &L3Location) -> Result { + self.load_bounded(location, u64::MAX) + } + + /// Bound the packed buffers allocated before any page bytes are read. + pub fn load_bounded(&self, location: &L3Location, max_bytes: u64) -> Result { let Some(_operation) = self.manager.try_operation_guard() else { bail!("disk cache lifecycle operation in progress"); }; // Pinned for the whole load: eviction under a concurrent spill must // not remove the segments this fill is assembling. let _pin = self.store().pin(&location.manifest_key); - let result = self.load_inner(location); + let result = self.load_inner(location, max_bytes); match &result { Ok(fill) => { self.manager @@ -656,8 +731,19 @@ impl L3Tier { result } - fn load_inner(&self, location: &L3Location) -> Result { + fn load_inner(&self, location: &L3Location, max_bytes: u64) -> Result { let manifest = self.store().load_manifest(&location.manifest_key)?; + if manifest.total_bytes > max_bytes { + bail!("L3 checkpoint exceeds the staging budget"); + } + if manifest.token_count != location.token_count + || manifest + .prefix_key + .as_ref() + .is_some_and(|key| key != &location.prefix_key) + { + bail!("L3 manifest does not match the located prefix"); + } if manifest.model_identity != self.model_identity || manifest.state_identity != self.state_identity { @@ -693,10 +779,11 @@ impl L3Tier { Ok(L3Fill { payload, token_count: manifest.token_count, - kv_desc_json: manifest.kv_desc_json, + kv_desc_json: manifest.kv_desc_json.clone(), payload_bytes, cachegen_kv, kv_decoded_bytes: manifest.kv_decoded_bytes, + manifest, }) } @@ -741,6 +828,31 @@ mod tests { CODEC_NATIVE_KV_PAGE, CODEC_NATIVE_KV_PAGE_VERSION, GeometryBlock, GeometryKind, }; + #[test] + fn streaming_prefix_hashes_match_the_existing_disk_keys() { + let namespace = "model/prefix-v1"; + let tokens: Vec = (-1400..1700).collect(); + let mut hashed = 0; + let mut stream = l3_prefix_hasher(namespace); + for end in [1, 19, 1025, 2505, tokens.len()] { + hash_l3_tokens(&mut stream, &tokens[hashed..end]); + hashed = end; + + let mut original = blake3::Hasher::new(); + original.update(b"l3-prefix-key-v1"); + original.update(namespace.as_bytes()); + for token in &tokens[..end] { + original.update(&token.to_le_bytes()); + } + let digest = original.finalize(); + assert_eq!(stream.finalize(), digest); + assert_eq!( + l3_prefix_key(namespace, &tokens[..end]), + format!("blake3:{}", digest.to_hex()), + ); + } + } + fn temp_root(name: &str) -> std::path::PathBuf { let root = std::env::temp_dir() .join("skippy-l3-tier-tests") @@ -861,7 +973,13 @@ mod tests { .expect("seed locate") .expect("seed location"); assert_eq!(seed_location.manifest_key, seed); - tier.benefit_observe_l3_restore("ns", &seed_tokens, &seed_location, Some(400.0), 100.0); + tier.benefit_observe_l3_restore( + "ns", + &seed_tokens, + &tier.load(&seed_location).unwrap().manifest, + Some(400.0), + 100.0, + ); let candidate_tokens = tokens(8); let candidate_payload = ExactStatePayload::full_state(vec![9; 256]); @@ -1176,6 +1294,77 @@ mod tests { ); } + #[test] + fn native_extension_reuses_whole_windows_and_restores_the_new_recurrent_state() { + use std::num::NonZeroU64; + + let tier = tier("native-tail", "blake3:native"); + let base = kv_payload(1, 10, 16, 16); + let plan = kv_geometry(1, 10, 16, 16, 4); + tier.spill( + "ns", + &tokens(10), + &base, + Some(runtime_kv_desc(1, 10, 320)), + Some(&plan), + ) + .unwrap(); + let base = tier.locate_longest("ns", &tokens(10), 1).unwrap().unwrap(); + let bytes_before = tier.activity().bytes_written; + let full = kv_payload(1, 15, 16, 16); + let full = full.kv_bytes().unwrap().unwrap(); + let tail = [&full[128..240], &full[368..480]].concat(); + let recurrent = [42u8; 50]; + let geometry = PayloadGeometry { + tail_bytes: 50, + ..kv_geometry(1, 15, 16, 16, 4) + }; + let key = tier + .spill_native_extension( + "ns", + &tokens(15), + NativeKvExtension { + base: &base, + reused_rows: NonZeroU64::new(8).unwrap(), + geometry: &geometry, + kv_desc_json: runtime_kv_desc(1, 15, 480), + kv_tail: &tail, + recurrent: &recurrent, + }, + ) + .unwrap() + .unwrap(); + assert_eq!( + tier.activity().bytes_written - bytes_before, + (tail.len() + recurrent.len()) as u64 + ); + + let fill = tier.fill_longest("ns", &tokens(15), 1).unwrap().unwrap(); + assert_eq!(fill.payload.kv_bytes().unwrap().unwrap(), full); + assert_eq!( + fill.payload.recurrent_state_bytes().unwrap().as_ref(), + recurrent + ); + assert_eq!(fill.manifest.payload_digest, key); + let mut tampered = fill.manifest; + tampered.segments[0].digest = segment_digest(b"wrong page"); + assert!(tier.store().assemble(&tampered).is_err()); + + tier.store() + .link_prefix( + &l3_namespace_key("other"), + 15, + &l3_prefix_key("other", &tokens(15)), + &key, + ) + .unwrap(); + assert!( + tier.locate_longest("other", &tokens(15), 1) + .unwrap() + .is_none() + ); + } + #[test] fn fixed_offset_cutting_is_what_fails_the_gate() { // The same growth without geometry: this is the 8x the probe measured, @@ -1238,7 +1427,7 @@ mod tests { let fill = tier.load(&location).unwrap(); let status = tier.status().unwrap(); - assert_eq!(status.format_version, MANIFEST_VERSION); + assert_eq!(status.format_version, CHECKPOINT_MANIFEST_VERSION); assert_eq!(status.restorable_manifests, 1); assert_eq!(status.restorable_tokens, 3); assert_eq!(status.namespaces, 1); diff --git a/crates/skippy-cache/src/tier/native_extension.rs b/crates/skippy-cache/src/tier/native_extension.rs new file mode 100644 index 00000000..994e92f3 --- /dev/null +++ b/crates/skippy-cache/src/tier/native_extension.rs @@ -0,0 +1,188 @@ +use std::{collections::HashMap, num::NonZeroU64}; + +use anyhow::{Context, Result, ensure}; + +use crate::{GeometryBlock, SegmentCodecIdentity}; + +use super::*; + +/// New native rows and recurrent state for a prefix backed by durable pages. +/// The geometry describes the full checkpoint at its final token boundary. +pub struct NativeKvExtension<'a> { + pub base: &'a L3Location, + pub reused_rows: NonZeroU64, + pub geometry: &'a PayloadGeometry, + pub kv_desc_json: String, + pub kv_tail: &'a [u8], + pub recurrent: &'a [u8], +} + +impl L3Tier { + pub fn spill_native_extension( + &self, + namespace: &str, + tokens: &[i32], + extension: NativeKvExtension<'_>, + ) -> Result> { + let _operation = self.manager.operation_guard(); + let _base_pin = self.store().pin(&extension.base.manifest_key); + let base = self.store().load_manifest(&extension.base.manifest_key)?; + let base_tokens = tokens + .get(..usize::try_from(base.token_count)?) + .context("base extends past the new checkpoint")?; + ensure!( + base.version == CHECKPOINT_MANIFEST_VERSION + && base.uses_native_kv_passthrough() + && base.model_identity == self.model_identity + && base.state_identity == self.state_identity + && base.prefix_key.as_deref() == Some(&l3_prefix_key(namespace, base_tokens)), + "base checkpoint is incompatible with this extension" + ); + let reused = extension.reused_rows.get(); + let geometry = extension.geometry; + ensure!( + geometry.rows == tokens.len() as u64 + && geometry.window_rows > 0 + && reused.is_multiple_of(geometry.window_rows) + && reused <= base.token_count + && reused < geometry.rows + && geometry.tail_bytes == extension.recurrent.len() as u64, + "invalid native extension geometry" + ); + + let mut manifest = HandoffManifest::new_for_model( + self.model_identity.clone(), + self.state_identity.clone(), + "kv-recurrent".to_owned(), + ); + manifest.version = CHECKPOINT_MANIFEST_VERSION; + manifest.prefix_key = Some(l3_prefix_key(namespace, tokens)); + manifest.token_count = geometry.rows; + manifest.total_bytes = geometry.total_bytes(); + manifest.recurrent_bytes = geometry.tail_bytes; + manifest.kv_bytes = manifest + .total_bytes + .checked_sub(geometry.tail_bytes) + .context("native extension KV size underflows")?; + manifest.kv_decoded_bytes = manifest.kv_bytes; + manifest.kv_desc_json = Some(extension.kv_desc_json); + + let mut pages = ExtensionPages { + reusable: base + .segments + .iter() + .filter_map(|page| { + page.codec_identity + .as_ref() + .filter(|codec| codec.is_native_kv_page())?; + Some((page.meta_json.as_deref()?, page)) + }) + .collect(), + fresh: Vec::new(), + manifest: &mut manifest, + offset: 0, + }; + let mut tail = extension.kv_tail; + for block in &geometry.blocks { + pages.append_run(block, &mut tail, geometry, reused)?; + } + ensure!(tail.is_empty(), "unused native extension KV bytes"); + for chunk in extension.recurrent.chunks(self.segment_bytes) { + pages.append( + chunk.len() as u64, + Some(chunk), + None, + SegmentCodecIdentity::raw(chunk.len() as u64), + "tail".into(), + )?; + } + ensure!( + pages.offset == pages.manifest.total_bytes, + "incorrect native extension length" + ); + let fresh = pages.fresh; + self.commit_spill(namespace, tokens, manifest, fresh, None) + } +} + +struct ExtensionPages<'base, 'fresh, 'out> { + reusable: HashMap<&'base str, &'base HandoffSegmentRef>, + fresh: Vec>, + manifest: &'out mut HandoffManifest, + offset: u64, +} + +impl<'fresh> ExtensionPages<'_, 'fresh, '_> { + fn append_run( + &mut self, + block: &GeometryBlock, + tail: &mut &'fresh [u8], + geometry: &PayloadGeometry, + reused: u64, + ) -> Result<()> { + let mut row = 0; + while row < geometry.rows { + let rows = geometry.window_rows.min(geometry.rows - row); + let bytes = rows + .checked_mul(block.stride) + .context("page size overflows")?; + let label = format!( + "{}:{}:{}:{row}", + block.kind.as_str(), + block.layer, + block.column + ); + let (fresh, reused_page) = if row < reused { + let page = self + .reusable + .get(label.as_str()) + .filter(|page| page.bytes == bytes) + .context("base checkpoint is missing a reusable page")?; + (None, Some(page.digest.clone())) + } else { + let (chunk, next) = tail + .split_at_checked(usize::try_from(bytes)?) + .context("native extension KV is truncated")?; + *tail = next; + (Some(chunk), None) + }; + self.append( + bytes, + fresh, + reused_page, + SegmentCodecIdentity::native_kv_page(bytes), + label, + )?; + row += rows; + } + Ok(()) + } + + fn append( + &mut self, + bytes: u64, + fresh: Option<&'fresh [u8]>, + reused: Option, + codec: SegmentCodecIdentity, + label: String, + ) -> Result<()> { + let digest = fresh + .map(segment_digest) + .or(reused) + .context("page has no digest")?; + self.manifest.segments.push(HandoffSegmentRef { + index: u32::try_from(self.manifest.segments.len())?, + offset: self.offset, + bytes, + digest, + codec_identity: Some(codec), + meta_json: Some(label), + }); + self.fresh.push(fresh); + self.offset = self + .offset + .checked_add(bytes) + .context("checkpoint size overflows")?; + Ok(()) + } +} diff --git a/crates/skippy-cache/src/tier/spill_payload.rs b/crates/skippy-cache/src/tier/spill_payload.rs index 620735f2..b8d93d4d 100644 --- a/crates/skippy-cache/src/tier/spill_payload.rs +++ b/crates/skippy-cache/src/tier/spill_payload.rs @@ -71,13 +71,6 @@ impl<'a> SpillPayload<'a> { self.recurrent.len() as u64 } - pub(super) fn digest(&self) -> String { - let mut hasher = blake3::Hasher::new(); - hasher.update(&self.kv); - hasher.update(&self.recurrent); - hasher.finalize().to_hex().to_string() - } - /// Ordinary segments borrow one immutable component. Only a cut spanning /// their boundary needs scratch storage, bounded by the configured segment. pub(super) fn segment( @@ -133,21 +126,6 @@ fn validate_cachegen( #[cfg(test)] mod tests { use super::*; - use crate::l3::segment_digest; - - #[test] - fn component_stream_digest_matches_concatenation_for_every_boundary() { - let bytes: Vec = (0..8195).map(|n| (n % 251) as u8).collect(); - for split in [0, 1, 63, 64, 1023, 1024, 4096, 8194, 8195] { - let view = SpillPayload { - kv: Cow::Borrowed(&bytes[..split]), - recurrent: Cow::Borrowed(&bytes[split..]), - total_bytes: bytes.len(), - decoded_kv_bytes: split as u64, - }; - assert_eq!(view.digest(), segment_digest(&bytes)); - } - } #[test] fn native_components_and_boundary_aligned_segments_borrow_original_storage() { @@ -185,7 +163,6 @@ mod tests { ExactStatePayload::kv_recurrent(vec![7, 8, 9], Vec::new()), ] { let view = SpillPayload::new(&payload, None, None).unwrap(); - assert_eq!(view.digest(), segment_digest(&[7, 8, 9])); assert_eq!(view.len(), 3); assert!(matches!(view.segment(0, 3, 1).unwrap(), Cow::Borrowed(_))); assert!(matches!(view.segment(3, 0, 1).unwrap(), Cow::Borrowed(_))); diff --git a/crates/skippy-cli/src/serve_settings/catalog.rs b/crates/skippy-cli/src/serve_settings/catalog.rs index 5e479622..b8c90ce5 100644 --- a/crates/skippy-cli/src/serve_settings/catalog.rs +++ b/crates/skippy-cli/src/serve_settings/catalog.rs @@ -243,7 +243,14 @@ pub const OPTIONS: &[OptionSpec] = &[ "cache", "kv_cache.l2_max_bytes", Kind::Bytes, - "Resident checkpoint RAM budget: off for default or a fixed IEC size; independent of disk", + "L2 host-RAM mirror: off or a fixed IEC size", + ), + option( + "prefix-cache-checkpoint-ram", + "cache", + "kv_cache.l1_checkpoint_max_bytes", + Kind::Bytes, + "L1 recurrent-checkpoint RAM: auto (default 1GiB) or a positive fixed IEC size", ), option( "prefix-cache-max-entries", diff --git a/crates/skippy-cli/src/serve_settings/resolution.rs b/crates/skippy-cli/src/serve_settings/resolution.rs index f2cde875..201ae585 100644 --- a/crates/skippy-cli/src/serve_settings/resolution.rs +++ b/crates/skippy-cli/src/serve_settings/resolution.rs @@ -63,7 +63,8 @@ impl ServeSettings { pub fn validate_cache_dependencies(&self, config: &StageConfig) -> Result<()> { if let Some(cache) = &config.kv_cache { anyhow::ensure!( - cache.mode != StageKvCacheMode::Disabled || cache.l2_max_bytes == 0, + cache.mode != StageKvCacheMode::Disabled + || (cache.l2_max_bytes == 0 && cache.l1_checkpoint_max_bytes.is_none()), "RAM caching requires enabled prefix caching" ); } @@ -111,7 +112,13 @@ impl ServeSettings { spec.name != "prefix-cache-budget" || value.as_str() != Some("off"), "use --prefix-cache off to disable caching" ); - bytes(value)? + let budget = bytes(value)?; + anyhow::ensure!( + spec.name != "prefix-cache-checkpoint-ram" + || budget.as_u64().is_some_and(|bytes| bytes > 0), + "prefix-cache-checkpoint-ram requires auto or a positive fixed IEC budget" + ); + budget } else if spec.name == "prefix-cache-retention-tokens" { retention(value)? } else if spec.name == "prefix-cache" { diff --git a/crates/skippy-cli/src/serve_settings/tests.rs b/crates/skippy-cli/src/serve_settings/tests.rs index 1a29acd3..a770ab86 100644 --- a/crates/skippy-cli/src/serve_settings/tests.rs +++ b/crates/skippy-cli/src/serve_settings/tests.rs @@ -865,7 +865,7 @@ fn checkpoint_ram_budget_does_not_require_disk() { "missing.gguf", "--prefix-cache", "on", - "--prefix-cache-ram", + "--prefix-cache-checkpoint-ram", "1GiB", ]) .unwrap() @@ -880,9 +880,10 @@ fn checkpoint_ram_budget_does_not_require_disk() { .validate_cache_dependencies(&stage) .unwrap(); assert_eq!( - stage.kv_cache.as_ref().unwrap().l2_max_bytes, - 1024 * 1024 * 1024 + stage.kv_cache.as_ref().unwrap().l1_checkpoint_max_bytes, + std::num::NonZeroU64::new(1024 * 1024 * 1024) ); + assert_eq!(stage.kv_cache.as_ref().unwrap().l2_max_bytes, 0); let tuning = args .public .settings diff --git a/crates/skippy-ffi/README.md b/crates/skippy-ffi/README.md index 85aaf3b2..5fe47273 100644 --- a/crates/skippy-ffi/README.md +++ b/crates/skippy-ffi/README.md @@ -105,11 +105,15 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.94`. The patch header in +The staged ABI is versioned as `0.1.95`. The patch header in `llama_cpp/patches/` and the Rust constants in `crates/skippy-ffi/src/lib.rs` are the source of truth, so keep this README aligned with those files instead of treating it as canonical prose. +ABI `0.1.95` adds borrowed-chunk KV import, resident sliding-window KV component +export, and byte-range recurrent state export. Existing on-disk checkpoint +layouts and whole-state export entry points retain their contracts. + ABI `0.1.94` combines the b12780 upstream C layouts with the shared target verification API, device row entry points, and their request descriptors. Rebuild the native runtime and callers from the matching source recipe. ABI `0.1.88` includes b12780’s enlarged `llama_model_quantize_params`, which crosses the FFI boundary by value and by pointer. diff --git a/crates/skippy-ffi/src/bindings/skippy.rs b/crates/skippy-ffi/src/bindings/skippy.rs index 8b9fa7dd..4ab63ab2 100644 --- a/crates/skippy-ffi/src/bindings/skippy.rs +++ b/crates/skippy-ffi/src/bindings/skippy.rs @@ -6,7 +6,7 @@ pub const SKIPPY_ABI_VERSION_MAJOR: u32 = 0; pub const SKIPPY_ABI_VERSION_MINOR: u32 = 1; -pub const SKIPPY_ABI_VERSION_PATCH: u32 = 94; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 95; pub const SKIPPY_ACTIVATION_FRAME_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_IDENTITY_BYTES: u32 = 32; @@ -1638,6 +1638,23 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +#[doc = " @brief A borrowed range of raw KV page bytes."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_kv_page_chunk { + pub data: *const ::std::os::raw::c_void, + pub bytes: usize, +} +unsafe extern "C" { + #[doc = " @brief Imports a single raw KV page from non-empty chunks in wire order.\n The ranges must remain readable until return and together cover exactly\n desc->payload_bytes. Unsupported layouts or backends leave the session\n untouched, so the caller can retry with a contiguous payload."] + pub fn skippy_import_kv_page_chunks( + session: *mut skippy_session, + desc: *const skippy_kv_page_desc, + chunks: *const skippy_kv_page_chunk, + chunk_count: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Imports validated CacheGen records directly into resident KV storage."] pub fn skippy_import_cachegen_kv_page_v1( @@ -1683,6 +1700,23 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +unsafe extern "C" { + #[doc = " @brief Exports an absolute token range from one resident sliding-window page component.\n The selected range must still be resident in that component.\n The returned descriptor is a single page, with no component offset."] + pub fn skippy_session_export_resident_kv_component( + session: *mut skippy_session, + cache_seq_id: i32, + role: skippy_kv_page_component_role, + layer_start: i32, + layer_end: i32, + token_start: u64, + token_count: u64, + out_desc: *mut skippy_kv_page_desc, + output: *mut ::std::os::raw::c_void, + output_capacity: usize, + out_bytes: *mut usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors."] pub fn skippy_session_export_resident_recurrent_state( @@ -1694,6 +1728,17 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +unsafe extern "C" { + #[doc = " @brief Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint."] + pub fn skippy_session_copy_resident_recurrent_range( + session: *mut skippy_session, + cache_seq_id: i32, + offset: usize, + output: *mut ::std::os::raw::c_void, + bytes: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool."] pub fn skippy_session_resident_prefix_bytes( diff --git a/crates/skippy-ffi/src/dynamic.rs b/crates/skippy-ffi/src/dynamic.rs index ce0eb63e..68263544 100644 --- a/crates/skippy-ffi/src/dynamic.rs +++ b/crates/skippy-ffi/src/dynamic.rs @@ -10,17 +10,17 @@ use crate::{ ABI_VERSION_MAJOR, ABI_VERSION_MINOR, ABI_VERSION_PATCH, AbiVersion, ActivationBoundaryDesc, ActivationDesc, AsrAbortCallback, AsrInfoV1, AsrModel, AsrResult, AsrSegmentV1, AsrTranscribeParamsV1, BackendDevice, CacheGenRecordV1, ClefInfoV1, ClefModel, Error, - GenerationSignalWindow, IterationRequest, KvPageDesc, LayaInfoV1, LayaMemoryV1, LayaModel, - LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, LlamaPerfContextFn, Model, ModelInfo, - MtmdBitmap, MtmdContext, MtmdContextParams, MtmdDecoderPos, MtmdGenAudioInfo, - MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, MtmdHelperGenAudio, MtmdHelperGenAudioInput, - MtmdHelperInitOpt, MtmdHelperVideo, MtmdInputChunkType, MtmdInputChunks, MtmdInputText, - NativeMtpDraft, NativeRuntimeLoadError, NgramCache, Opaque, RuntimeConfig, SamplingConfig, - Session, SkippyDecodeStepSampledMtpFn, SkippyModelAttachMtpDraftModelFn, - SkippyRuntimeEventReporterV1, StagePlan, StagePlanDescV1, StagePlanProfileDescV1, - StagePlanStateDescV1, StagePlanStringRefV1, StagePlanValueDescV1, StagePlanValueKind, - StagePlanner, StagePlannerConfigV1, Status, SystemOneSlot, TensorInfo, TokenLogprobs, - TokenSignal, WorkloadInfoV1, runtime_abi_supported, + GenerationSignalWindow, IterationRequest, KvPageChunk, KvPageComponentRole, KvPageDesc, + LayaInfoV1, LayaMemoryV1, LayaModel, LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, + LlamaPerfContextFn, Model, ModelInfo, MtmdBitmap, MtmdContext, MtmdContextParams, + MtmdDecoderPos, MtmdGenAudioInfo, MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, + MtmdHelperGenAudio, MtmdHelperGenAudioInput, MtmdHelperInitOpt, MtmdHelperVideo, + MtmdInputChunkType, MtmdInputChunks, MtmdInputText, NativeMtpDraft, NativeRuntimeLoadError, + NgramCache, Opaque, RuntimeConfig, SamplingConfig, Session, SkippyDecodeStepSampledMtpFn, + SkippyModelAttachMtpDraftModelFn, SkippyRuntimeEventReporterV1, StagePlan, StagePlanDescV1, + StagePlanProfileDescV1, StagePlanStateDescV1, StagePlanStringRefV1, StagePlanValueDescV1, + StagePlanValueKind, StagePlanner, StagePlannerConfigV1, Status, SystemOneSlot, TensorInfo, + TokenLogprobs, TokenSignal, WorkloadInfoV1, runtime_abi_supported, }; static SYMBOLS: OnceLock = OnceLock::new(); @@ -263,12 +263,15 @@ dynamic_symbols! { skippy_import_full_state(session: *mut Session, layer_start: i32, layer_end: i32, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; skippy_export_kv_page(session: *mut Session, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_import_kv_page(session: *mut Session, desc: *const KvPageDesc, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; + skippy_import_kv_page_chunks(session: *mut Session, desc: *const KvPageDesc, chunks: *const KvPageChunk, chunk_count: usize, out_error: *mut *mut Error) -> Status; skippy_import_cachegen_kv_page_v1(session: *mut Session, desc: *const KvPageDesc, records: *const CacheGenRecordV1, record_count: usize, out_error: *mut *mut Error) -> Status; skippy_model_memory_cache_capabilities(model: *const Model) -> u32; skippy_model_kv_pool_cells(model: *const Model) -> u32; skippy_export_recurrent_state(session: *mut Session, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_import_recurrent_state(session: *mut Session, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; + skippy_session_export_resident_kv_component(session: *mut Session, cache_seq_id: i32, role: KvPageComponentRole, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_session_export_resident_kv_page(session: *mut Session, cache_seq_id: i32, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; + skippy_session_copy_resident_recurrent_range(session: *mut Session, cache_seq_id: i32, offset: usize, output: *mut c_void, bytes: usize, out_error: *mut *mut Error) -> Status; skippy_session_export_resident_recurrent_state(session: *mut Session, cache_seq_id: i32, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_session_resident_prefix_bytes(session: *mut Session, cache_seq_id: i32, out_bytes: *mut u64, out_error: *mut *mut Error) -> Status; skippy_session_save_prefix(session: *mut Session, cache_seq_id: i32, token_count: u64, out_error: *mut *mut Error) -> Status; diff --git a/crates/skippy-ffi/src/lib.rs b/crates/skippy-ffi/src/lib.rs index e2aa71ca..5fe390f1 100644 --- a/crates/skippy-ffi/src/lib.rs +++ b/crates/skippy-ffi/src/lib.rs @@ -5,7 +5,7 @@ mod dynamic_library; // without compiling the crate to determine native-runtime compatibility. pub const ABI_VERSION_MAJOR: u32 = 0; pub const ABI_VERSION_MINOR: u32 = 1; -pub const ABI_VERSION_PATCH: u32 = 94; +pub const ABI_VERSION_PATCH: u32 = 95; // The facade constants are parsed without compiling; tie them to the generated // bindings' view of the native ABI version at compile time so a common.h bump @@ -140,7 +140,8 @@ pub use state::{ CACHEGEN_RECORD_F32, CACHEGEN_RECORD_F32_TRANSPOSED, CACHEGEN_RECORD_Q4_0, CACHEGEN_RECORD_Q8_0, CACHEGEN_RECORD_V1_ABI_VERSION, CacheGenRecordV1, KV_PAGE_CODEC_ISWA_COMPOSITE_V1, KV_PAGE_CODEC_SINGLE_V1, KV_PAGE_FLAG_CANONICAL_POSITIONS, - KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentDesc, KvPageDesc, + KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, KvPageChunk, KvPageComponentDesc, + KvPageComponentRole, KvPageDesc, }; #[cfg(not(feature = "dynamic-runtime"))] @@ -184,27 +185,29 @@ pub use dynamic::{ skippy_decode_step_sampled, skippy_decode_step_sampled_mtp, skippy_decode_step_sampled_mtp_fn, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, skippy_import_cachegen_kv_page_v1, - skippy_import_full_state, skippy_import_kv_page, skippy_import_recurrent_state, - skippy_import_state, skippy_iteration_batch_sampled, skippy_laya_model_free, - skippy_laya_model_info_v1, skippy_laya_model_memory_v1, skippy_laya_model_open, - skippy_laya_read, skippy_laya_tokenize, skippy_model_attach_mtp_draft_model_fn, - skippy_model_free, skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, - skippy_model_info_tensor_count, skippy_model_input_activation_boundary, - skippy_model_kv_pool_cells, skippy_model_llama_model, skippy_model_memory_cache_capabilities, - skippy_model_open, skippy_model_open_from_parts, skippy_model_open_from_parts_with_events_fn, - skippy_model_open_with_events_fn, skippy_model_output_activation_boundary, - skippy_model_supports_causal_readout, skippy_model_workload_info_v1, skippy_ngram_cache_append, - skippy_ngram_cache_create, skippy_ngram_cache_draft, skippy_ngram_cache_free, - skippy_ngram_cache_reset, skippy_parse_chat_response_json, skippy_prefill_chunk, - skippy_prefill_chunk_frame, skippy_prefill_chunk_frame_sampled, - skippy_prefill_chunk_frame_sampled_with_positions, skippy_prefill_chunk_frame_with_positions, - skippy_retire_verify_checkpoint, skippy_session_batch_size, - skippy_session_begin_external_decode, skippy_session_configure_chat_sampling, - skippy_session_copy_output_activation_frame, skippy_session_create, + skippy_import_full_state, skippy_import_kv_page, skippy_import_kv_page_chunks, + skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, + skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, + skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, + skippy_model_attach_mtp_draft_model_fn, skippy_model_free, skippy_model_info_free, + skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, + skippy_model_input_activation_boundary, skippy_model_kv_pool_cells, skippy_model_llama_model, + skippy_model_memory_cache_capabilities, skippy_model_open, skippy_model_open_from_parts, + skippy_model_open_from_parts_with_events_fn, skippy_model_open_with_events_fn, + skippy_model_output_activation_boundary, skippy_model_supports_causal_readout, + skippy_model_workload_info_v1, skippy_ngram_cache_append, skippy_ngram_cache_create, + skippy_ngram_cache_draft, skippy_ngram_cache_free, skippy_ngram_cache_reset, + skippy_parse_chat_response_json, skippy_prefill_chunk, skippy_prefill_chunk_frame, + skippy_prefill_chunk_frame_sampled, skippy_prefill_chunk_frame_sampled_with_positions, + skippy_prefill_chunk_frame_with_positions, skippy_retire_verify_checkpoint, + skippy_session_batch_size, skippy_session_begin_external_decode, + skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, + skippy_session_copy_resident_recurrent_range, skippy_session_create, skippy_session_create_from_resident_prefix, skippy_session_drop_sequence, skippy_session_embed, skippy_session_encode_prompt, skippy_session_end_external_decode, - skippy_session_export_resident_kv_page, skippy_session_export_resident_recurrent_state, - skippy_session_free, skippy_session_last_token_signal, skippy_session_llama_context, + skippy_session_export_resident_kv_component, skippy_session_export_resident_kv_page, + skippy_session_export_resident_recurrent_state, skippy_session_free, + skippy_session_last_token_signal, skippy_session_llama_context, skippy_session_memory_used_cells, skippy_session_position, skippy_session_rerank, skippy_session_reset, skippy_session_resident_prefix_bytes, skippy_session_restore_prefix, skippy_session_restore_token_history, skippy_session_sample_current, @@ -257,9 +260,9 @@ pub use static_bindings::{ skippy_decode_step_sampled_mtp, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, skippy_import_cachegen_kv_page_v1, skippy_import_full_state, skippy_import_kv_page, - skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, - skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, - skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, + skippy_import_kv_page_chunks, skippy_import_recurrent_state, skippy_import_state, + skippy_iteration_batch_sampled, skippy_laya_model_free, skippy_laya_model_info_v1, + skippy_laya_model_memory_v1, skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, skippy_model_attach_mtp_draft_model, skippy_model_free, skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, skippy_model_input_activation_boundary, skippy_model_kv_pool_cells, skippy_model_llama_model, @@ -272,9 +275,10 @@ pub use static_bindings::{ skippy_prefill_chunk_frame_with_positions, skippy_retire_verify_checkpoint, skippy_session_batch_size, skippy_session_begin_external_decode, skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, - skippy_session_create, skippy_session_create_from_resident_prefix, - skippy_session_drop_sequence, skippy_session_embed, skippy_session_encode_prompt, - skippy_session_end_external_decode, skippy_session_export_resident_kv_page, + skippy_session_copy_resident_recurrent_range, skippy_session_create, + skippy_session_create_from_resident_prefix, skippy_session_drop_sequence, skippy_session_embed, + skippy_session_encode_prompt, skippy_session_end_external_decode, + skippy_session_export_resident_kv_component, skippy_session_export_resident_kv_page, skippy_session_export_resident_recurrent_state, skippy_session_free, skippy_session_last_token_signal, skippy_session_llama_context, skippy_session_memory_used_cells, skippy_session_position, skippy_session_rerank, diff --git a/crates/skippy-ffi/src/state.rs b/crates/skippy-ffi/src/state.rs index 1ddf5df5..69263494 100644 --- a/crates/skippy-ffi/src/state.rs +++ b/crates/skippy-ffi/src/state.rs @@ -50,7 +50,9 @@ pub const CACHEGEN_RECORD_Q4_0: u32 = bindings::skippy::skippy_cachegen_record_k pub type CacheGenRecordV1 = bindings::skippy::skippy_cachegen_record_v1; +pub type KvPageComponentRole = bindings::skippy::skippy_kv_page_component_role; pub type KvPageDesc = bindings::skippy::skippy_kv_page_desc; +pub type KvPageChunk = bindings::skippy::skippy_kv_page_chunk; #[allow(clippy::derivable_impls)] impl Default for KvPageDesc { diff --git a/crates/skippy-protocol/src/config.rs b/crates/skippy-protocol/src/config.rs index 631f8637..2c9971cb 100644 --- a/crates/skippy-protocol/src/config.rs +++ b/crates/skippy-protocol/src/config.rs @@ -1,7 +1,7 @@ //! Stage configuration, topology, and activation contracts. use serde::{Deserialize, Deserializer, Serialize, de}; -use std::num::NonZeroU32; +use std::num::{NonZeroU32, NonZeroU64}; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct StageIdentity { pub run_id: String, @@ -653,12 +653,13 @@ pub struct StageKvCacheConfig { pub max_entries: usize, #[serde(default)] pub max_bytes: u64, - /// Host-RAM byte budget. Native resident caching uses this for retained - /// checkpoint and token metadata, independently of disk; zero selects its - /// bounded default. Serialized runtimes use an opt-in L2 mirror, where zero - /// disables that mirror. + /// Host-RAM byte budget for the L2 mirror. Zero disables the mirror. #[serde(default)] pub l2_max_bytes: u64, + /// Host-RAM byte limit for resident recurrent checkpoints and metadata. + /// When unset, the runtime uses its bounded resident default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub l1_checkpoint_max_bytes: Option, /// Exact-state retention ceiling; None derives eight times max_bytes. /// One indivisible snapshot may exceed it. Some(0) disables the ceiling. #[serde(default)] diff --git a/crates/skippy-runtime/src/kv_pages.rs b/crates/skippy-runtime/src/kv_pages.rs index cb5a1408..1211d66b 100644 --- a/crates/skippy-runtime/src/kv_pages.rs +++ b/crates/skippy-runtime/src/kv_pages.rs @@ -6,7 +6,7 @@ use skippy_cache::cachegen::archive::{ CacheGenArchive, ComponentLayout, PageLayout, RecordKind, ValidatedArchive, ValueType, decode_page, encode_page, validate_archive, }; -use skippy_ffi::{CacheGenRecordV1, KvPageDesc as RawKvPageDesc}; +use skippy_ffi::{CacheGenRecordV1, KvPageChunk, KvPageDesc as RawKvPageDesc}; use crate::error::{ensure_ok, free_error}; use crate::session::StageSession; @@ -491,12 +491,63 @@ impl StageSession { )) }; ensure_ok(status, error)?; + self.finish_kv_page_import(desc); + Ok(()) + } + + /// Imports a raw page from borrowed chunks. Returns false when this + /// layout or backend needs the contiguous importer. + pub fn try_import_kv_page_chunks<'a>( + &mut self, + desc: &RuntimeKvPageDesc, + chunks: impl ExactSizeIterator, + ) -> Result { + if chunks.len() < 2 || desc.has_sliding_window_component() { + return Ok(false); + } + let mut raw_chunks = Vec::with_capacity(chunks.len()); + let mut bytes = 0usize; + for chunk in chunks.filter(|chunk| !chunk.is_empty()) { + bytes = bytes + .checked_add(chunk.len()) + .ok_or_else(|| anyhow::anyhow!("KV page chunk lengths overflow"))?; + raw_chunks.push(KvPageChunk { + data: chunk.as_ptr().cast(), + bytes: chunk.len(), + }); + } + desc.validate_payload(bytes)?; + if raw_chunks.len() < 2 { + return Ok(false); + } + let raw = desc.as_raw(); + let mut error = ptr::null_mut(); + // SAFETY: the slices and descriptor array stay alive for the call. + // The native importer synchronously copies the bytes into KV storage. + let status = unsafe { + native_call!(skippy_import_kv_page_chunks( + self.raw, + &raw, + raw_chunks.as_ptr(), + raw_chunks.len(), + &mut error, + )) + }; + if status == crate::Status::Unsupported { + free_error(error); + return Ok(false); + } + ensure_ok(status, error)?; + self.finish_kv_page_import(desc); + Ok(true) + } + + fn finish_kv_page_import(&mut self, desc: &RuntimeKvPageDesc) { self.token_count = self .token_count .max(desc.token_start.saturating_add(desc.token_count)); // Imported target state has no matching draft features. self.dflash_after_replace(); - Ok(()) } pub fn import_cachegen_kv_page( diff --git a/crates/skippy-runtime/src/lib.rs b/crates/skippy-runtime/src/lib.rs index 68e68387..2ae2de0a 100644 --- a/crates/skippy-runtime/src/lib.rs +++ b/crates/skippy-runtime/src/lib.rs @@ -115,6 +115,7 @@ pub use stage_planning::{ // without taking a direct dependency on the raw ABI crate. pub use skippy_ffi::{ KV_PAGE_FLAG_CANONICAL_POSITIONS, KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, + KvPageComponentRole, }; // Native renderer identity. Re-exported so callers can fingerprint a chat-template // render (for example a rendered-prompt probe) without taking a direct dependency diff --git a/crates/skippy-runtime/src/resident_prefix.rs b/crates/skippy-runtime/src/resident_prefix.rs index 743e782b..3f1baf08 100644 --- a/crates/skippy-runtime/src/resident_prefix.rs +++ b/crates/skippy-runtime/src/resident_prefix.rs @@ -1,9 +1,9 @@ //! Export cache-owned prefixes only at explicit cold/offload boundaries. use crate::error::{ensure_ok, free_error}; use crate::native_timing::native_call; -use crate::{RuntimeKvPage, RuntimeKvPageDesc, Status, session::StageSession}; +use crate::{KvPageComponentRole, RuntimeKvPage, RuntimeKvPageDesc, Status, session::StageSession}; use anyhow::{Result, ensure}; -use std::ptr; +use std::{ops::Range, ptr}; impl StageSession { pub fn resident_kv_page_desc( @@ -12,6 +12,19 @@ impl StageSession { layers: (i32, i32), tokens: u64, ) -> Result { + self.resident_kv_range_desc(sequence, layers, 0..tokens) + } + + pub fn resident_kv_range_desc( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + ) -> Result { + let count = tokens + .end + .checked_sub(tokens.start) + .ok_or_else(|| anyhow::anyhow!("resident KV token range is reversed"))?; let mut desc = skippy_ffi::KvPageDesc::default(); let mut bytes = 0; let mut error = ptr::null_mut(); @@ -22,8 +35,8 @@ impl StageSession { sequence, layers.0, layers.1, - 0, - tokens, + tokens.start, + count, &mut desc, ptr::null_mut(), 0, @@ -46,25 +59,68 @@ impl StageSession { tokens: u64, bytes: usize, ) -> Result { + self.export_resident_kv_range(sequence, layers, 0..tokens, bytes) + } + + pub fn export_resident_kv_range( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + bytes: usize, + ) -> Result { + self.export_resident_attention_range(sequence, layers, tokens, bytes, None) + } + + /// Export a saved token range either from the whole native page or from + /// one explicitly selected sliding-window component. + pub fn export_resident_attention_range( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + bytes: usize, + component: Option, + ) -> Result { + let count = tokens + .end + .checked_sub(tokens.start) + .ok_or_else(|| anyhow::anyhow!("resident KV token range is reversed"))?; let mut desc = skippy_ffi::KvPageDesc::default(); let mut payload = vec![0; bytes]; let mut written = 0; let mut error = ptr::null_mut(); // SAFETY: The session is live and the output allocation has the advertised capacity. let status = unsafe { - native_call!(skippy_session_export_resident_kv_page( - self.raw, - sequence, - layers.0, - layers.1, - 0, - tokens, - &mut desc, - payload.as_mut_ptr().cast(), - payload.len(), - &mut written, - &mut error, - )) + match component { + None => native_call!(skippy_session_export_resident_kv_page( + self.raw, + sequence, + layers.0, + layers.1, + tokens.start, + count, + &mut desc, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + )), + Some(role) => native_call!(skippy_session_export_resident_kv_component( + self.raw, + sequence, + role, + layers.0, + layers.1, + tokens.start, + count, + &mut desc, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + )), + } }; ensure_ok(status, error)?; ensure!( @@ -96,6 +152,27 @@ impl StageSession { Ok(bytes) } + pub fn copy_resident_recurrent_range( + &mut self, + sequence: i32, + offset: usize, + output: &mut [u8], + ) -> Result<()> { + let mut error = ptr::null_mut(); + // SAFETY: The session is live and the mutable slice is writable for its entire length. + let status = unsafe { + native_call!(skippy_session_copy_resident_recurrent_range( + self.raw, + sequence, + offset, + output.as_mut_ptr().cast(), + output.len(), + &mut error, + )) + }; + ensure_ok(status, error) + } + pub fn export_resident_recurrent_state( &mut self, sequence: i32, diff --git a/crates/skippy-runtime/src/types.rs b/crates/skippy-runtime/src/types.rs index efdfbfb1..3a8c9e5c 100644 --- a/crates/skippy-runtime/src/types.rs +++ b/crates/skippy-runtime/src/types.rs @@ -447,6 +447,40 @@ pub struct RuntimeKvPageDesc { } impl RuntimeKvPageDesc { + /// Describe one component using the same layout as a native single page. + pub fn component_page(&self, role: skippy_ffi::KvPageComponentRole) -> Option { + if !self.has_sliding_window_component() || self.component_count != 2 { + return None; + } + let index = match role { + skippy_ffi::KvPageComponentRole::Base => 0, + skippy_ffi::KvPageComponentRole::Swa => 1, + }; + let component = &self.components[index]; + if component.role != role as u32 { + return None; + } + Some(Self { + version: component.version, + layer_start: self.layer_start, + layer_end: self.layer_end, + token_start: component.token_start, + token_count: component.token_count, + layer_count: component.layer_count, + k_type: component.k_type, + v_type: component.v_type, + k_row_bytes: component.k_row_bytes, + v_row_bytes: component.v_row_bytes, + v_element_bytes: component.v_element_bytes, + k_idx_row_bytes: component.k_idx_row_bytes, + payload_bytes: component.payload_bytes, + flags: component.flags, + codec: skippy_ffi::KV_PAGE_CODEC_SINGLE_V1, + component_count: 0, + components: Box::default(), + }) + } + /// Whether the page includes a sliding-window cache's rows. That cache /// reuses rows that fall out of the window as the sequence grows, so its /// rows below a position do not stay resident. diff --git a/crates/skippy-serving/src/binary_transport/binary_kv.rs b/crates/skippy-serving/src/binary_transport/binary_kv.rs index 6c8810e9..be8c77bd 100644 --- a/crates/skippy-serving/src/binary_transport/binary_kv.rs +++ b/crates/skippy-serving/src/binary_transport/binary_kv.rs @@ -638,7 +638,7 @@ pub(in crate::binary_transport) fn maybe_record_binary_prefill( } } } - match kv.record_resident_prefix( + match kv.record_resident_prefix_for_idle_capture( runtime, session_id, &identity, @@ -923,7 +923,7 @@ pub(in crate::binary_transport) fn maybe_record_binary_full_prefill( } } } - match kv.record_resident_prefix( + match kv.record_resident_prefix_for_idle_capture( runtime, session_id, &identity, diff --git a/crates/skippy-serving/src/binary_transport/stage_execution.rs b/crates/skippy-serving/src/binary_transport/stage_execution.rs index 5eff8f09..aea8040a 100644 --- a/crates/skippy-serving/src/binary_transport/stage_execution.rs +++ b/crates/skippy-serving/src/binary_transport/stage_execution.rs @@ -1162,6 +1162,7 @@ pub(in crate::binary_transport) fn prefix_cache_test_config() -> StageConfig { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/crates/skippy-serving/src/frontend/iteration_scheduler.rs index c8180660..b5a9a0f0 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -1069,7 +1069,7 @@ impl SchedulerWorker { continue; } self.run_work_turn(); - if !self.wait_iteration_interval() { + if !self.run_prefix_capture_after_work() || !self.wait_iteration_interval() { return; } } diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs index 845372d2..4c1a3a42 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs @@ -4,11 +4,55 @@ //! so time the runtime sits unused between native calls has a name. use super::*; +use crate::runtime_state::panic_recovery::try_lock_runtime; impl SchedulerWorker { - /// Block for the next command while no work is queued; false once the - /// worker should stop. + /// Give already-queued requests priority over the next checkpoint copy. + pub(super) fn run_prefix_capture_after_work(&mut self) -> bool { + let Some(mut runtime) = try_lock_runtime(&self.runtime) else { + return true; + }; + if !runtime.has_prefix_capture_work() { + return true; + } + match self.commands.try_recv() { + Ok(SchedulerCommand::Shutdown) | Err(std_mpsc::TryRecvError::Disconnected) => { + drop(runtime); + self.fail_all(InferenceError::backend("iteration scheduler stopped")); + false + } + Ok(command) => { + drop(runtime); + self.handle_command(command); + true + } + Err(std_mpsc::TryRecvError::Empty) => { + runtime.run_prefix_capture_step(); + true + } + } + } + + fn advance_prefix_capture(&mut self) -> bool { + try_lock_runtime(&self.runtime).is_some_and(|mut runtime| runtime.run_prefix_capture_step()) + } + + /// Advance pending checkpoint copies while idle, checking for requests + /// before every bounded step. When no copy can run, block for commands. pub(super) fn wait_idle(&mut self) -> bool { + loop { + match self.commands.try_recv() { + Ok(SchedulerCommand::Shutdown) | Err(std_mpsc::TryRecvError::Disconnected) => { + return false; + } + Ok(command) => { + self.handle_command(command); + return true; + } + Err(std_mpsc::TryRecvError::Empty) if self.advance_prefix_capture() => {} + Err(std_mpsc::TryRecvError::Empty) => break, + } + } let span = ActiveSpan::start( self.telemetry.as_ref(), "stage.scheduler_idle", diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index 13500c36..4ff593dd 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -552,9 +552,8 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { assert!(worker.scheduler.sequence("resumed").is_none()); } -#[test] -fn feature_runtime_operations_execute_on_the_scheduler_worker() { - let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(3))); +fn feature_test_scheduler(runtime: RuntimeState) -> IterationScheduler { + let runtime = Arc::new(Mutex::new(runtime)); let (commands, receiver) = std_mpsc::sync_channel(8); let worker = thread::spawn(move || { SchedulerWorker { @@ -585,15 +584,19 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { } .run(); }); - let scheduler = IterationScheduler { + IterationScheduler { shared: Arc::new(IterationSchedulerShared { commands, max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, owner_count: AtomicUsize::new(1), worker: Mutex::new(Some(worker)), }), - }; + } +} +#[test] +fn feature_runtime_operations_execute_on_the_scheduler_worker() { + let scheduler = feature_test_scheduler(RuntimeState::new_modelless_for_test(3)); let outcome = scheduler .execute_runtime_timed("test-feature-runtime", |runtime| Ok(runtime.lane_count())) .unwrap(); @@ -603,6 +606,39 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { assert!(outcome.runtime_lock_hold_ms >= 0.0); } +#[test] +fn queued_runtime_command_runs_between_prefix_capture_steps() { + let mut runtime = RuntimeState::split_dflash_final_stage_for_test(); + runtime.ensure_session_active("capture-source").unwrap(); + let (started, first_step) = std_mpsc::sync_channel(1); + let (release, resume) = std_mpsc::sync_channel(1); + let steps = Arc::new(AtomicUsize::new(0)); + let capture_steps = Arc::clone(&steps); + let timeout = Duration::from_secs(5); + runtime.offer_prefix_capture("capture-source", true, move |_, _| { + if capture_steps.fetch_add(1, Ordering::Relaxed) == 0 { + started.send(()).unwrap(); + resume.recv_timeout(timeout).unwrap(); + std::ops::ControlFlow::Continue(()) + } else { + std::ops::ControlFlow::Break(()) + } + }); + let scheduler = feature_test_scheduler(runtime); + first_step.recv_timeout(timeout).unwrap(); + + let (operation, response) = runtime_operation("queued-during-prefix-capture", move |_| { + Ok(steps.load(Ordering::Relaxed)) + }); + scheduler + .enqueue_command(SchedulerCommand::ExecuteRuntime(operation)) + .unwrap(); + release.send(()).unwrap(); + + let outcome = response.recv_timeout(timeout).unwrap().unwrap(); + assert_eq!(outcome.value, 1); +} + #[test] fn detached_runtime_operation_returns_before_work_completes() { let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(3))); diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs b/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs index 2f199fb2..9de872c8 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs @@ -158,8 +158,6 @@ fn capture_large_owner( kv.record_resident_prefix(&mut runtime, "source", &large, tokens)? .expect("large native checkpoint captured"); runtime.drop_session_timed("source")?; - runtime.prefill("continuing-decode", &[21, 22, 23])?; - runtime.ensure_session_active("eviction")?; Ok((proof, pin)) } @@ -183,12 +181,18 @@ fn offload_while_disk_is_paused( ) -> Result<()> { let kv = backend.kv.as_ref().unwrap(); let stored = identity(backend, tokens); - proof.baseline_decode_ms = next_decode(backend, 24)?.as_secs_f64() * 1000.0; kv.l3_spill_worker_pause.store(true, Ordering::Release); let mut paused = DiskPause { pause: kv.l3_spill_worker_pause.clone(), worker: None, }; + { + let mut runtime = backend.runtime.lock().unwrap(); + assert!(kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); + runtime.prefill("continuing-decode", &[21, 22, 23])?; + runtime.ensure_session_active("eviction")?; + } + proof.baseline_decode_ms = next_decode(backend, 24)?.as_secs_f64() * 1000.0; let scheduler = backend.iteration_scheduler.clone(); let worker_kv = kv.clone(); let (started_tx, started_rx) = mpsc::channel(); @@ -205,8 +209,8 @@ fn offload_while_disk_is_paused( }) })); started_rx.recv_timeout(Duration::from_secs(30))?; - // Enqueue while eviction owns the runtime. Waiting for synchronous export - // is expected and measured; progress DURING D2H is deliberately not asserted. + // Enqueue while eviction owns the runtime. The owned payload is already + // with the paused writer, so neither cell release nor decode needs it. proof.concurrent_decode_wait_ms = next_decode(backend, 25)?.as_secs_f64() * 1000.0; proof.eviction_runtime_ms = paused .worker diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index 4e6a73fd..83337cc5 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -108,6 +108,65 @@ struct CheckpointPreferenceCase { descriptor: skippy_runtime::RuntimeKvPageDesc, } +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn native_exact_prefix_import_admits_capacity_first() -> Result<()> { + for expected_source in ["l3", "l2"] { + let root = tempfile::tempdir()?; + let CheckpointPreferenceCase { + backend, + tokens, + attention, + recurrent, + .. + } = checkpoint_preference_case(root.path())?; + let kv = backend.kv.as_ref().unwrap(); + let target = identity(&backend, &tokens); + if expected_source == "l2" { + let fill = kv + .l3 + .as_ref() + .unwrap() + .fill_longest(&target.namespace, &tokens, 64)? + .unwrap(); + assert!(kv.l2.as_ref().unwrap().promote( + &target.namespace, + &tokens, + &fill.manifest, + &fill.payload, + )); + } + + let mut runtime = backend.runtime.lock().unwrap(); + runtime.ensure_session_active("pressure")?; + let capacity = u64::from(runtime.kv_pool_tokens()); + let occupied = runtime.memory_used_cells("pressure")?; + let pressure_tokens = vec![9; usize::try_from(capacity - occupied)?]; + let unrelated = identity(&backend, &pressure_tokens); + runtime.prefill("pressure", &pressure_tokens)?; + kv.record_resident_prefix(&mut runtime, "pressure", &unrelated, &pressure_tokens)? + .unwrap(); + runtime.drop_session_timed("pressure")?; + runtime.ensure_session_active("target")?; + assert!(capacity - runtime.memory_used_cells("target")? < tokens.len() as u64); + + let restored = kv + .restore_exact_state(&mut runtime, "target", std::slice::from_ref(&target))? + .expect("exact restore should reclaim cells before importing"); + assert_eq!(restored.source, expected_source); + assert_eq!(restored.token_count, tokens.len()); + assert!(kv.probe_resident_prefix(&unrelated).is_none()); + assert_eq!( + runtime + .export_kv_page("target", 0, tokens.len() as u64)? + .payload, + attention + ); + assert_eq!(runtime.export_recurrent_state("target")?, recurrent); + } + Ok(()) +} + #[test] #[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] fn failed_long_l3_import_rolls_back_then_reuses_the_short_native_owner() -> Result<()> { @@ -205,6 +264,7 @@ fn checkpoint_preference_case(root: &Path) -> Result { kv.record_resident_prefix(&mut rt, "long-source", &long, &tokens)? .unwrap(); rt.drop_session_timed("long-source")?; + assert!(kv.capture_resident_prefix_for_l3(&mut rt, &long)?); rt.ensure_session_active("eviction")?; assert_eq!( kv.evict_resident_prefix_for_tokens(&mut rt, "eviction", u64::MAX)? @@ -277,7 +337,7 @@ fn capture_and_commit(root: &Path) -> Result { assert!(!attention.is_empty()); assert!(!recurrent.is_empty()); let record = kv - .record_resident_prefix(&mut runtime, "source", &stored, &tokens)? + .record_resident_prefix_for_idle_capture(&mut runtime, "source", &stored, &tokens)? .expect("native checkpoint captured"); assert!(record.stored); assert!(kv.probe_resident_prefix(&stored).is_some()); @@ -293,13 +353,15 @@ fn capture_and_commit(root: &Path) -> Result { .iter() .map(|&token| runtime.decode("source", token)) .collect::>>()?; - runtime.drop_session_timed("source")?; - runtime.ensure_session_active("eviction")?; - let evicted = - kv.evict_resident_prefix_for_tokens(&mut runtime, "eviction", u64::MAX)?; - assert_eq!(evicted.evicted_entries, 1); (attention, recurrent, output) }; + backend + .iteration_scheduler + .execute_runtime("finish-source", |runtime| { + runtime + .drop_session_timed("source") + .map_err(crate::frontend::util::openai_backend_error) + })?; let l3 = kv.l3.as_ref().expect("persistent tier enabled"); let deadline = Instant::now() + Duration::from_secs(30); loop { @@ -313,6 +375,14 @@ fn capture_and_commit(root: &Path) -> Result { ); thread::sleep(Duration::from_millis(2)); } + { + let mut runtime = backend.runtime.lock().unwrap(); + runtime.ensure_session_active("eviction")?; + let evicted = + kv.evict_resident_prefix_for_tokens(&mut runtime, "eviction", u64::MAX)?; + assert_eq!(evicted.evicted_entries, 1); + assert_eq!(runtime.memory_used_cells("eviction")?, 0); + } PrefixReference { seed_process_id: std::process::id(), attention_sha256: digest(&attention), @@ -442,7 +512,9 @@ fn native_cold_offload_refusal_keeps_inference_usable() -> Result<()> { .map(|&token| runtime.decode("source", token)) .collect::>>()?; runtime.drop_session_timed("source")?; + assert!(kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); runtime.ensure_session_active("reuse")?; + assert!(!kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); assert_eq!( kv.evict_resident_prefix_for_tokens(&mut runtime, "reuse", u64::MAX)? .evicted_entries, diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index fc4f7ee1..61c43405 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -114,6 +114,7 @@ pub(super) fn recurrent_test_backend_with_lanes( max_entries: 8, max_bytes: 0, l2_max_bytes: RECURRENT_TEST_CHECKPOINT_RAM_BYTES, + l1_checkpoint_max_bytes: std::num::NonZeroU64::new(RECURRENT_TEST_CHECKPOINT_RAM_BYTES), codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index fc5958a3..d760457a 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -143,10 +143,12 @@ impl StageOpenAiBackend { { return Err(InferenceError::backend("request cancelled")); } - let prepared_restore = self - .kv - .as_ref() - .map(|kv| kv.prepare_exact_state_restore(lookup_identities.as_ref(), false)); + let prepared_restore = self.kv.as_ref().map(|kv| { + kv.prepare_standalone_restore(&lookup_identities, cache_operation_deadline, |tokens| { + self.generation_service_estimator + .estimated_prefill_ms(tokens) + }) + }); let outcome = self.iteration_scheduler.execute_cache_aware_runtime_timed( "feature-kv-restore-prefill-record", crate::frontend::iteration_scheduler::cache_runtime::CacheAwareRuntimeRequest { diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index 8f708ebf..cf472cc5 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -264,6 +264,12 @@ impl StageOpenAiBackend { Some(&identity.namespace), ); } + if recorded && write_through_l3 && kv.l3.is_some() { + // A shared grid boundary is also a fallback. It can be + // offered before this request's exact chat prompt arrives. + let preferred = decision_prefix == "chat_prefix_checkpoint"; + kv.offer_prefix_capture(runtime, session_id, identity, preferred); + } return recorded; } #[cfg(test)] diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs index cf547833..f8095fbc 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs @@ -293,9 +293,13 @@ impl StageOpenAiBackend { .emit("stage.openai_kv_record_decision", attrs); } for identity in kv.record_identities(&self.config, &base, 0, prefill_tokens) { - if let Ok(Some(record)) = - kv.record_resident_prefix(runtime, session_id, &identity, prefill_tokens) - { + if let Ok(Some(record)) = kv.record_resident_prefix_with_capture( + runtime, + session_id, + &identity, + prefill_tokens, + true, + ) { resident_recorded_pages = resident_recorded_pages.saturating_add(1); let mut attrs = self.openai_attrs(ids); attrs.insert( diff --git a/crates/skippy-serving/src/frontend/prefix_cache.rs b/crates/skippy-serving/src/frontend/prefix_cache.rs index 370c2261..04b03bb8 100644 --- a/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -440,7 +440,7 @@ impl StageOpenAiBackend { .unwrap_or(usize::MAX) .min(scheduler_token_ids.len()); scheduler_kv - .record_resident_prefix( + .record_resident_prefix_for_idle_capture( runtime, &scheduler_session_id, identity, @@ -553,7 +553,7 @@ impl StageOpenAiBackend { .unwrap_or(usize::MAX) .min(scheduler_token_ids.len()); scheduler_kv - .record_resident_prefix( + .record_resident_prefix_for_idle_capture( runtime, &scheduler_session_id, identity, @@ -1306,6 +1306,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -1396,6 +1397,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs index e28ab158..7e290a88 100644 --- a/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs @@ -47,15 +47,15 @@ async fn observe(directory: &Path, report: &mut Report) -> Result<()> { report.cold = Some(runner.generate(&request)?); let cache = runner.enable_cache(Some(manager.clone()))?; report.seed = Some(runner.generate(&request)?); - tiers::drain_workers(&cache)?; - report.replay = Some(runner.generate(&request)?); - tiers::drain_workers(&cache)?; - tiers::evict_l1(&runner, &cache)?; - tiers::published_checkpoint( + let checkpoint = tiers::published_checkpoint( family, &manager, report.seed.as_ref().context("missing cache seed")?, - ) + )?; + report.replay = Some(runner.generate(&request)?); + tiers::drain_workers(&cache)?; + tiers::evict_l1(&runner, &cache)?; + Ok::<_, anyhow::Error>(checkpoint) })(); skippy_runtime::restore_native_logs(); let checkpoint = observed?; diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs index 358d25b3..e10db136 100644 --- a/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs @@ -132,8 +132,8 @@ fn observe( let manager = tiers::open_store(directory)?; let cache = runner.enable_cache(Some(manager.clone()))?; let seed = observation.seed.insert(runner.generate(original)?); - tiers::evict_l1(&runner, &cache)?; observation.checkpoint = Some(tiers::published_checkpoint(runner.family, &manager, seed)?); + tiers::evict_l1(&runner, &cache)?; for attempt in 0..3 { if attempt > 0 { tiers::evict_l1(&runner, &cache)?; diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs index 67fa7a54..ebbeaec5 100644 --- a/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs @@ -38,8 +38,8 @@ pub(super) fn observe( .context("loaded runtime did not admit L2")?; let seed = observations.seed.insert(runner.generate(request)?); - observations.evictions.push(evict_l1(&runner, &cache)?); let checkpoint = published_checkpoint(family, &manager, seed)?; + observations.evictions.push(evict_l1(&runner, &cache)?); observations.checkpoint_tokens = Some(checkpoint); let pack_name = published_pack_name(directory, &cache, checkpoint)?; @@ -113,19 +113,26 @@ fn published_pack_name( checkpoint: u32, ) -> Result { let store = cache.l3.as_ref().context("missing disk tier")?.store(); - let mut found = None; - for digest in store.list_manifests()? { - let manifest = store.load_manifest(&digest)?; - if manifest.token_count == u64::from(checkpoint) { - let pack = PathBuf::from(digest).with_extension("pack"); - ensure!( - directory.join("l3/packs").join(&pack).is_file() && found.is_none(), - "expected one packed object for the qualification checkpoint" - ); - found = Some(pack); - } - } - found.context("missing packed payload for the qualification checkpoint") + let manifests = store.list_manifests()?; + let [manifest] = manifests.as_slice() else { + anyhow::bail!("expected one manifest in the fresh qualification store"); + }; + ensure!( + store.load_manifest(manifest)?.token_count == u64::from(checkpoint), + "published manifest has the wrong checkpoint length" + ); + // The isolated store has one checkpoint. A raw pack is named by its + // content digest, which can differ from the manifest digest. + let mut packs = fs::read_dir(directory.join("l3/packs"))?; + let pack = packs.next().context("missing qualification pack")??; + let name = PathBuf::from(pack.file_name()); + ensure!( + packs.next().is_none() + && pack.file_type()?.is_file() + && name.extension() == Some(OsStr::new("pack")), + "expected one packed object for the qualification checkpoint" + ); + Ok(name) } pub(super) fn wait_for_checkpoint(manager: &L3CacheManager, tokens: u64) -> Result<()> { diff --git a/crates/skippy-serving/src/frontend/tests/support.rs b/crates/skippy-serving/src/frontend/tests/support.rs index 0d138bca..f84845bf 100644 --- a/crates/skippy-serving/src/frontend/tests/support.rs +++ b/crates/skippy-serving/src/frontend/tests/support.rs @@ -49,6 +49,7 @@ pub(super) fn prefix_cache_test_config() -> StageConfig { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-serving/src/kv_integration/activation.rs b/crates/skippy-serving/src/kv_integration/activation.rs index 6e315545..91b6693f 100644 --- a/crates/skippy-serving/src/kv_integration/activation.rs +++ b/crates/skippy-serving/src/kv_integration/activation.rs @@ -213,6 +213,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/crates/skippy-serving/src/kv_integration/cache_affinity.rs index e9f50f26..e4166a68 100644 --- a/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -110,6 +110,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 64, shared_prefix_stride_tokens: 32, @@ -170,6 +171,7 @@ mod checkpoint_matching_tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 128, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), min_tokens: 1, diff --git a/crates/skippy-serving/src/kv_integration/config.rs b/crates/skippy-serving/src/kv_integration/config.rs index fee77e6d..58ef80ed 100644 --- a/crates/skippy-serving/src/kv_integration/config.rs +++ b/crates/skippy-serving/src/kv_integration/config.rs @@ -295,17 +295,16 @@ impl KvStageIntegration { pending, |pending| { if admitted.resident - && let (Some(l2), Some(digest)) = - (worker_l2.as_ref(), pending.l2_promotion_digest.as_deref()) + && let (Some(l2), Some(manifest)) = + (worker_l2.as_ref(), pending.l2_promotion_manifest.as_deref()) { // The native resident prefix already owns L1. // Publish only the bounded host-RAM mirror. let _ = l2.promote( &pending.namespace, &pending.token_ids, - digest, + manifest, &pending.payload, - &pending.extra, ); return Ok(()); } @@ -418,6 +417,7 @@ impl KvStageIntegration { l3, cachegen_serving_enabled: worker_cachegen, inflight_fills, + l3_staging: Arc::new(std::sync::atomic::AtomicBool::new(false)), dense_without_recurrent, resident_checkpoint_max_bytes, }; @@ -587,13 +587,19 @@ fn l3_payload_kind(payload: StagePrefixCachePayload) -> &'static str { /// run after the first — measured at 8x on an M4 mini. Cutting per run into /// fixed token windows writes only the new rows. /// -/// Returns `None` when the layout is not one this mapping can state exactly; -/// the store then falls back to fixed-size cutting, which is correct but not -/// cheap. -fn kv_page_geometry(desc: &RuntimeKvPageDesc, payload_bytes: u64) -> Option { - // A composite (ISWA) page is two independently-shaped components; its - // geometry is not this single-run description. - if desc.component_count != 0 || desc.token_count == 0 || desc.layer_count == 0 { +/// Falls back to fixed-size segments for layouts without contiguous token rows. +/// In particular, windowing each transposed V column separately creates hundreds +/// of thousands of segment records for a short checkpoint. Fixed-size packing +/// bounds that metadata and preserves the native bytes and restore descriptor. +pub(super) fn kv_page_geometry( + desc: &RuntimeKvPageDesc, + payload_bytes: u64, +) -> Option { + if desc.component_count != 0 + || desc.flags & skippy_runtime::KV_PAGE_FLAG_V_TRANSPOSED != 0 + || desc.token_count == 0 + || desc.layer_count == 0 + { return None; } let rows = desc.token_count; @@ -611,35 +617,7 @@ fn kv_page_geometry(desc: &RuntimeKvPageDesc, payload_bytes: u64) -> Option 0 { + if desc.v_row_bytes > 0 { for layer in 0..layers { blocks.push(GeometryBlock { stride: u64::from(desc.v_row_bytes), @@ -754,7 +732,7 @@ fn store_exact_radix_record_with_codec( token_ids, l3_fill_claim: _, write_through_l3, - l2_promotion_digest, + l2_promotion_manifest, l3_cost, admission_credit: _admission_credit, } = pending; @@ -822,8 +800,8 @@ fn store_exact_radix_record_with_codec( #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); - if let (Some(l2), Some(payload_digest)) = (l2, l2_promotion_digest.as_deref()) { - let _ = l2.promote(&namespace, &token_ids, payload_digest, &payload, &extra); + if let (Some(l2), Some(manifest)) = (l2, l2_promotion_manifest.as_deref()) { + let _ = l2.promote(&namespace, &token_ids, manifest, &payload); } // Durable write-through is best-effort after L1 publication: a slow, full, // or failing disk must not delay or invalidate the in-memory record. The @@ -832,7 +810,8 @@ fn store_exact_radix_record_with_codec( let durable_spill = write_through_l3.then_some(PendingDurableSpill { page_id, native_raw: false, - payload, + extension: None, + payload: payload.into(), extra, namespace, token_ids, @@ -947,6 +926,7 @@ pub(super) fn effective_cache_config(config: &StageConfig) -> Option { @@ -12,12 +15,55 @@ pub(in crate::kv_integration) struct DurableRecordTarget<'a> { #[derive(Debug)] pub(in crate::kv_integration) struct PendingDurableSpill { pub(in crate::kv_integration) page_id: String, - pub(in crate::kv_integration) payload: skippy_cache::ExactStatePayload, + pub(in crate::kv_integration) payload: DurableSpillPayload, pub(in crate::kv_integration) extra: super::super::ExactStateExtra, pub(in crate::kv_integration) namespace: String, pub(in crate::kv_integration) token_ids: Vec, pub(in crate::kv_integration) native_raw: bool, pub(in crate::kv_integration) l3_cost: Option, + pub(in crate::kv_integration) extension: Option, +} + +#[derive(Debug)] +pub(in crate::kv_integration) enum DurableSpillPayload { + Assembled(skippy_cache::ExactStatePayload), + Native(NativeCapturePayload), +} + +impl From for DurableSpillPayload { + fn from(payload: skippy_cache::ExactStatePayload) -> Self { + Self::Assembled(payload) + } +} + +impl DurableSpillPayload { + fn byte_len(&self) -> u64 { + match self { + Self::Assembled(payload) => payload.byte_len(), + Self::Native(payload) => payload.byte_len(), + } + } + + fn assemble(self) -> Result { + match self { + Self::Assembled(payload) => Ok(payload), + Self::Native(payload) => payload.assemble(), + } + } +} + +#[derive(Debug)] +pub(in crate::kv_integration) struct NativeSpillExtension { + pub(in crate::kv_integration) base: skippy_cache::L3Location, + pub(in crate::kv_integration) reused_rows: NonZeroU64, + pub(in crate::kv_integration) geometry: PayloadGeometry, +} + +#[derive(Debug)] +struct NativeCheckpoint { + namespace: String, + tokens: Vec, + location: skippy_cache::L3Location, } pub(in crate::kv_integration) struct DurableSpillReservation { @@ -43,17 +89,85 @@ pub(in crate::kv_integration) struct DurableSpillSender { tx: std::sync::mpsc::SyncSender, held_bytes: Arc, byte_cap: u64, + recent_checkpoints: Arc>>, } impl DurableSpillSender { + pub(in crate::kv_integration) fn has_native_checkpoint( + &self, + namespace: &str, + tokens: &[i32], + ) -> bool { + self.recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .any(|entry| entry.namespace == namespace && entry.tokens == tokens) + } + fn new(tx: std::sync::mpsc::SyncSender, byte_cap: u64) -> Self { Self { tx, held_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)), byte_cap, + recent_checkpoints: Arc::default(), } } + pub(in crate::kv_integration) fn native_base( + &self, + namespace: &str, + tokens: &[i32], + ) -> Option { + self.recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .filter(|entry| { + entry.namespace == namespace + && entry.tokens.len() < tokens.len() + && tokens.starts_with(&entry.tokens) + }) + .max_by_key(|entry| entry.tokens.len()) + .map(|entry| entry.location.clone()) + } + + pub(in crate::kv_integration) fn remember_loaded( + &self, + namespace: &str, + tokens: &[i32], + location: &skippy_cache::L3Location, + ) { + if location.native_kv_passthrough + && let Ok(len) = usize::try_from(location.token_count) + && let Some(prefix) = tokens.get(..len) + { + Self::remember_native_checkpoint( + &self.recent_checkpoints, + NativeCheckpoint { + namespace: namespace.to_owned(), + tokens: prefix.to_vec(), + location: location.clone(), + }, + ); + } + } + + fn remember_native_checkpoint( + recent: &Mutex>, + checkpoint: NativeCheckpoint, + ) { + const RECENT_NATIVE_CHECKPOINTS: usize = 16; + let mut recent = recent + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + recent.retain(|entry| entry.location.manifest_key != checkpoint.location.manifest_key); + if recent.len() >= RECENT_NATIVE_CHECKPOINTS { + recent.pop_front(); + } + recent.push_back(checkpoint); + } + /// Reserve bounded host bytes before materializing a native cold prefix. /// Unlike the legacy recorder, native offload never admits an oversized exception. pub(in crate::kv_integration) fn try_reserve( @@ -146,6 +260,7 @@ pub(in crate::kv_integration) fn start_durable_spill_worker( }; let (tx, rx) = std::sync::mpsc::sync_channel::(EXACT_STATE_RECORD_CAPACITY); let sender = DurableSpillSender::new(tx, byte_cap); + let recent_checkpoints = Arc::clone(&sender.recent_checkpoints); let task = std::thread::Builder::new() .name(format!("skippy-l3-spill-{stage_id}")) .spawn(move || { @@ -161,7 +276,33 @@ pub(in crate::kv_integration) fn start_durable_spill_worker( while pause.load(std::sync::atomic::Ordering::Acquire) { std::thread::sleep(std::time::Duration::from_millis(2)); } + let prefix = pending + .native_raw + .then(|| (pending.namespace.clone(), pending.token_ids.clone())); + let reused_base = pending + .extension + .as_ref() + .map(|extension| extension.base.manifest_key.clone()); spill_exact_record_to_l3(&l3, cachegen_enabled, pending); + if let Some((namespace, tokens)) = prefix + && let Ok(Some(location)) = l3.locate_longest(&namespace, &tokens, 1) + && location.token_count == tokens.len() as u64 + && location.native_kv_passthrough + { + DurableSpillSender::remember_native_checkpoint( + &recent_checkpoints, + NativeCheckpoint { + namespace, + tokens, + location, + }, + ); + } else if let Some(base) = reused_base { + recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .retain(|entry| entry.location.manifest_key != base); + } } })?; Ok((Some(sender), Some(task))) @@ -181,6 +322,7 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( token_ids, l3_cost, native_raw, + extension, } = pending; // Native eviction already owns the runtime and resident index. Resolve // committed disk entries here on the durable worker, never under either @@ -194,6 +336,10 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( { return; } + let Ok(payload) = payload.assemble() else { + tracing::debug!(%page_id, "durable checkpoint assembly failed"); + return; + }; let kv_desc_json = extra .kv_desc .as_ref() @@ -243,16 +389,27 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( } else { None }; - let spill = cachegen_spill.unwrap_or_else(|| { - l3.spill_with_cost( + let spill = if let Some(extension) = extension { + spill_native_extension( + l3, &namespace, &token_ids, &payload, kv_desc_json, - geometry.as_ref(), - l3_cost, + &extension, ) - }); + } else { + cachegen_spill.unwrap_or_else(|| { + l3.spill_with_cost( + &namespace, + &token_ids, + &payload, + kv_desc_json, + geometry.as_ref(), + l3_cost, + ) + }) + }; emit_l3_state_transitions(l3); if let Err(error) = spill { static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -267,6 +424,33 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( } } +fn spill_native_extension( + l3: &L3Tier, + namespace: &str, + tokens: &[i32], + payload: &skippy_cache::ExactStatePayload, + descriptor: Option, + extension: &NativeSpillExtension, +) -> Result> { + let descriptor = descriptor.context("native extension has no full checkpoint descriptor")?; + let kv = payload + .kv_bytes()? + .context("native extension has no KV suffix")?; + let recurrent = payload.recurrent_state_bytes()?; + l3.spill_native_extension( + namespace, + tokens, + skippy_cache::NativeKvExtension { + base: &extension.base, + reused_rows: extension.reused_rows, + geometry: &extension.geometry, + kv_desc_json: descriptor, + kv_tail: &kv, + recurrent: &recurrent, + }, + ) +} + #[cfg(test)] mod tests { use super::*; @@ -274,12 +458,13 @@ mod tests { fn pending(bytes: usize) -> PendingDurableSpill { PendingDurableSpill { page_id: format!("spill-{bytes}"), - payload: skippy_cache::ExactStatePayload::full_state(vec![7; bytes]), + payload: skippy_cache::ExactStatePayload::full_state(vec![7; bytes]).into(), extra: super::super::super::ExactStateExtra::default(), namespace: "model".to_string(), token_ids: vec![1, 2], l3_cost: None, native_raw: false, + extension: None, } } diff --git a/crates/skippy-serving/src/kv_integration/config/resident_policy.rs b/crates/skippy-serving/src/kv_integration/config/resident_policy.rs index 41e1405e..322c0eb2 100644 --- a/crates/skippy-serving/src/kv_integration/config/resident_policy.rs +++ b/crates/skippy-serving/src/kv_integration/config/resident_policy.rs @@ -1,16 +1,13 @@ //! Native radix prefixes own shared KV references and bounded recurrent host state. use skippy_protocol::StageKvCacheConfig; +use std::num::NonZeroU64; -/// Zero RAM mirrors means use the native checkpoint default, not disable prefix reuse. -/// Disabling the stage cache itself remains the explicit off switch. const DEFAULT_CHECKPOINT_BYTES: u64 = 1024 * 1024 * 1024; pub(super) fn checkpoint_budget(cache: &StageKvCacheConfig) -> u64 { - if cache.l2_max_bytes > 0 { - cache.l2_max_bytes - } else { - DEFAULT_CHECKPOINT_BYTES - } + cache + .l1_checkpoint_max_bytes + .map_or(DEFAULT_CHECKPOINT_BYTES, NonZeroU64::get) } #[cfg(test)] @@ -18,11 +15,12 @@ mod tests { use super::*; #[test] - fn checkpoint_ram_budget_is_independent_of_disk_and_attention_estimates() { + fn checkpoint_ram_budget_is_independent_of_l2_and_attention_estimates() { let cache = StageKvCacheConfig { max_bytes: 32, exact_max_bytes: Some(64), l2_max_bytes: 256, + l1_checkpoint_max_bytes: None, mode: skippy_protocol::StageKvCacheMode::LookupRecord, max_entries: 64, codec: Default::default(), @@ -32,13 +30,13 @@ mod tests { prefill_admission: Default::default(), retention: Default::default(), }; - assert_eq!(checkpoint_budget(&cache), 256); + assert_eq!(checkpoint_budget(&cache), DEFAULT_CHECKPOINT_BYTES); assert_eq!( checkpoint_budget(&StageKvCacheConfig { - l2_max_bytes: 0, + l1_checkpoint_max_bytes: NonZeroU64::new(512), ..cache }), - DEFAULT_CHECKPOINT_BYTES + 512 ); } } diff --git a/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs b/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs index 799bcb1a..c3beec34 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs +++ b/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs @@ -9,11 +9,13 @@ fn pending(token: i32, bytes: usize) -> PendingDurableSpill { payload: skippy_cache::ExactStatePayload::kv_recurrent( vec![7; bytes / 2], vec![9; bytes - bytes / 2], - ), + ) + .into(), extra: super::super::super::ExactStateExtra::default(), namespace: "native-test".into(), token_ids: vec![token], native_raw: true, + extension: None, l3_cost: None, } } diff --git a/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs b/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs index 1b12eccc..edb08ada 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs +++ b/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs @@ -22,6 +22,7 @@ fn harness_config() -> StageConfig { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -79,7 +80,7 @@ fn record( token_ids, l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit, } @@ -459,6 +460,7 @@ fn a_deferred_capture_of_a_cached_checkpoint_skips_at_registration() { /// recurrent state; session-end admission checks the radix again. #[test] fn a_deferred_capture_goes_ahead_on_a_miss_or_a_busy_radix() { + skippy_runtime::test_support::require_native_runtime(); let (kv, config) = harness(); let mut runtime = RuntimeState::new_modelless_for_test(1); let chat_identity = identity(&kv, &config, &[1, 2, 3]); diff --git a/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs b/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs index b7eb6a45..56dd2e25 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs +++ b/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs @@ -301,7 +301,7 @@ fn native_checkpoint_ram_budget_works_without_disk() { .kv_cache .as_mut() .expect("enabled cache config") - .l2_max_bytes = 64 * 1024 * 1024; + .l1_checkpoint_max_bytes = std::num::NonZeroU64::new(64 * 1024 * 1024); let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, diff --git a/crates/skippy-serving/src/kv_integration/exact_state.rs b/crates/skippy-serving/src/kv_integration/exact_state.rs index c36681dc..0661624d 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -15,8 +15,8 @@ use super::{ const MAX_PREFIX_PROBES: usize = 64; mod resident_preference; -use resident_preference::DurableRestoreLookup; pub(crate) use resident_preference::PreparedExactStateRestore; +use resident_preference::{DurableFill, DurableRestoreLookup}; mod restore; mod snapshot_headroom; @@ -255,6 +255,7 @@ impl KvStageIntegration { DurableRestoreLookup { started: lookup_started, location, + fill: candidate.fill, }, cold_prefill_cost, )? { @@ -330,6 +331,14 @@ impl KvStageIntegration { "cached KV page token range mismatch for exact-state checkpoint" )); } + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(false); + } let import_started = Instant::now(); runtime.import_kv_page(session_id, desc, kv.as_ref())?; kv_import_ms = import_started.elapsed().as_secs_f64() * 1000.0; @@ -440,7 +449,7 @@ impl KvStageIntegration { token_ids: stored_tokens, l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit, }), @@ -881,7 +890,7 @@ impl KvStageIntegration { token_ids: identity.token_ids.clone(), l3_fill_claim: None, write_through_l3, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost, admission_credit, }) { @@ -951,6 +960,9 @@ impl KvStageIntegration { { return Ok(Some(restored)); } + if matches!(lookup.fill, DurableFill::Skip) { + return Ok(None); + } // Segment and manifest digests intentionally deduplicate bytes across // numerical states. A fill claim must not: one state's fill cannot // warm another state's radix namespace, even when their payload bytes @@ -965,15 +977,8 @@ impl KvStageIntegration { return Ok(None); } } - let outcome = self.fill_and_import( - runtime, - session_id, - identity, - lookup.started, - l3, - location, - cold_prefill_cost, - ); + let outcome = + self.fill_and_import(runtime, session_id, identity, l3, lookup, cold_prefill_cost); // On success the claim travels with the re-warm record and the worker // releases it once the entry is radix-resident. On any other outcome // release it here. @@ -993,11 +998,12 @@ impl KvStageIntegration { runtime: &mut RuntimeState, session_id: &str, identity: &PrefillKvIdentity, - lookup_started: Instant, l3: &std::sync::Arc, - location: &skippy_cache::L3Location, + lookup: DurableRestoreLookup<'_>, cold_prefill_cost: Option, ) -> Result> { + let location = lookup.location; + let lookup_started = lookup.started; // Native page capability is checked from manifest metadata before the // tier reads any segment bytes. Runtime ABI, platform and numerical // mode are already bound by the tier's exact-state identity; the page @@ -1005,18 +1011,24 @@ impl KvStageIntegration { let Ok(native_kv_desc) = preflight_l3_kv_location(location) else { return Ok(None); }; - let fill_started = Instant::now(); // A load failure (corrupt segment, now quarantined) is a miss, not a // request failure. Import failures below do propagate: the transaction // rolls the lane back and the caller falls back to cold prefill. - let fill = match l3.load(location) { - Ok(fill) => fill, - Err(_) => { - if let Some(l2) = &self.l2 { - l2.invalidate_digest(&location.manifest_key); + let (fill, fill_elapsed, prior_fill_elapsed) = match lookup.fill { + DurableFill::Staged(staged) => (staged.fill.clone(), staged.elapsed, staged.elapsed), + DurableFill::Inline => { + let started = Instant::now(); + match l3.load(location) { + Ok(fill) => (fill, started.elapsed(), std::time::Duration::ZERO), + Err(_) => { + if let Some(l2) = &self.l2 { + l2.invalidate_digest(&location.manifest_key); + } + return Ok(None); + } } - return Ok(None); } + DurableFill::Skip => return Ok(None), }; if fill.payload.byte_len() == 0 { return Ok(None); @@ -1032,7 +1044,7 @@ impl KvStageIntegration { if !self.native_payload_is_complete(fill.payload.kind()) { return Ok(None); } - let fill_ms = fill_started.elapsed().as_secs_f64() * 1000.0; + let fill_ms = fill_elapsed.as_secs_f64() * 1000.0; let token_count = fill.token_count; let kv_desc: Option = native_kv_desc.or_else(|| { fill.kv_desc_json @@ -1117,6 +1129,14 @@ impl KvStageIntegration { return Ok(None); } if let Some((kv, desc)) = kv_page { + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(None); + } let import_started = Instant::now(); if fill.cachegen_kv { runtime.import_cachegen_kv_page(session_id, desc, kv.as_ref())?; @@ -1150,11 +1170,11 @@ impl KvStageIntegration { fill.payload.byte_len() }; let payload_kind = fill.payload.kind(); - let restore_cost = lookup_started.elapsed().as_secs_f64() * 1_000.0; + let restore_cost = (prior_fill_elapsed + lookup_started.elapsed()).as_secs_f64() * 1_000.0; l3.benefit_observe_l3_restore( &identity.namespace, &identity.token_ids[..token_count as usize], - location, + &fill.manifest, cold_prefill_cost, restore_cost, ); @@ -1163,15 +1183,15 @@ impl KvStageIntegration { if resident { self.rewarm_resident_prefix(runtime, session_id, identity, tokens)?; } - let l2_promotion_digest = if fill.cachegen_kv { + let l2_promotion_manifest = if fill.cachegen_kv { None } else { self.l2.as_ref().and_then(|l2| { l2.consider_l3_fill(&location.manifest_key, token_count, fill.payload.byte_len()) - .then(|| location.manifest_key.clone()) + .then(|| Box::new(fill.manifest)) }) }; - if fill.cachegen_kv || (resident && l2_promotion_digest.is_none()) { + if fill.cachegen_kv || (resident && l2_promotion_manifest.is_none()) { return Ok(Some(ExactStateRestore { page_id: identity.page_id.clone(), token_count: token_count as usize, @@ -1210,7 +1230,7 @@ impl KvStageIntegration { token_ids: identity.token_ids[..token_count as usize].to_vec(), l3_fill_claim: Some(l3_fill_claim_key(l3, location)), write_through_l3: false, - l2_promotion_digest, + l2_promotion_manifest, l3_cost: None, admission_credit, }), diff --git a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs index af1dcf16..db9ff57a 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -1,14 +1,41 @@ //! Compare token metadata before choosing a warm alias or loading durable bytes. use super::*; +use std::{ + sync::atomic::{AtomicBool, Ordering}, + time::Duration, +}; pub(super) struct RestoreCandidate<'a> { pub(super) identity: &'a PrefillKvIdentity, pub(super) location: Option<&'a skippy_cache::L3Location>, + pub(super) fill: DurableFill<'a>, } pub(super) struct DurableRestoreLookup<'a> { pub(super) started: Instant, pub(super) location: &'a skippy_cache::L3Location, + pub(super) fill: DurableFill<'a>, +} + +#[derive(Clone, Copy)] +pub(super) enum DurableFill<'a> { + Inline, + Staged(&'a StagedL3Restore), + Skip, +} + +struct StagingLease(Arc); + +impl Drop for StagingLease { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +pub(super) struct StagedL3Restore { + pub(super) fill: skippy_cache::L3Fill, + pub(super) elapsed: Duration, + _lease: StagingLease, } /// Durable metadata resolved before entering a scheduled runtime operation. @@ -16,6 +43,8 @@ pub(super) struct DurableRestoreLookup<'a> { pub(crate) struct PreparedExactStateRestore { identities: Vec, locations: Vec>, + staged: Option, + allow_inline_fill: bool, } impl PreparedExactStateRestore { @@ -23,6 +52,20 @@ impl PreparedExactStateRestore { pub(crate) fn identities(&self) -> &[PrefillKvIdentity] { &self.identities } + + fn fill_for(&self, location: Option<&skippy_cache::L3Location>) -> DurableFill<'_> { + if self.allow_inline_fill { + return DurableFill::Inline; + } + match (&self.staged, location) { + (Some(staged), Some(location)) + if staged.fill.manifest.payload_digest == location.manifest_key => + { + DurableFill::Staged(staged) + } + _ => DurableFill::Skip, + } + } } impl KvStageIntegration { @@ -61,7 +104,102 @@ impl KvStageIntegration { PreparedExactStateRestore { identities: identities.to_vec(), locations, + staged: None, + allow_inline_fill: true, + } + } + + /// Stage one disk candidate before the standalone request takes the + /// runtime. A busy reader, expired budget or failed load is a cache miss. + pub(crate) fn prepare_standalone_restore( + &self, + identities: &[PrefillKvIdentity], + deadline: Instant, + estimate_prefill_ms: impl FnOnce(usize) -> Option, + ) -> PreparedExactStateRestore { + let mut prepared = self.prepare_exact_state_restore(identities, false); + prepared.allow_inline_fill = false; + let candidate = self + .ordered_restore_candidates(&prepared) + .into_iter() + .find(|candidate| { + candidate + .location + .is_some_and(|location| preflight_l3_kv_location(location).is_ok()) + }); + if let Some(candidate) = candidate + && let Some(location) = candidate.location + && !self + .l2 + .as_ref() + .is_some_and(|tier| tier.contains_location(candidate.identity, location)) + && let Some(l3) = &self.l3 + { + let resident = self.longest_resident(&prepared.identities); + let saved = usize::try_from(location.token_count.saturating_sub(resident)).unwrap_or(0); + let recompute_ms = estimate_prefill_ms(saved).filter(|ms| ms.is_finite() && *ms > 0.0); + let wait = recompute_ms.map_or(Duration::from_secs(1), |ms| { + Duration::from_secs_f64(ms.min(1000.0) / 1000.0) + }); + let available = wait.min(deadline.saturating_duration_since(Instant::now())); + if !available.is_zero() { + let staged = self.stage_l3_fill(l3.clone(), location.clone(), available); + if staged.is_some() + && let Some(sender) = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + { + sender.remember_loaded( + &candidate.identity.namespace, + &candidate.identity.token_ids, + location, + ); + } + prepared.staged = staged; + } } + prepared + } + + fn stage_l3_fill( + &self, + tier: Arc, + location: skippy_cache::L3Location, + wait: Duration, + ) -> Option { + self.l3_staging + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .ok()?; + let lease = StagingLease(self.l3_staging.clone()); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + std::thread::Builder::new() + .name("skippy-l3-read".into()) + .spawn(move || { + let start = Instant::now(); + if let Ok(fill) = + tier.load_bounded(&location, super::super::EXACT_STATE_RECORD_QUEUE_BYTES) + { + let _ = tx.send(StagedL3Restore { + fill, + elapsed: start.elapsed(), + _lease: lease, + }); + } + }) + .ok()?; + rx.recv_timeout(wait).ok() + } + + fn longest_resident(&self, identities: &[PrefillKvIdentity]) -> u64 { + identities + .iter() + .filter_map(|identity| self.probe_resident_prefix(identity)) + .map(|hit| hit.token_count as u64) + .max() + .unwrap_or(0) } pub(super) fn ordered_restore_candidates<'a>( @@ -76,16 +214,11 @@ impl KvStageIntegration { .map(|(identity, location)| RestoreCandidate { identity, location: location.as_ref(), + fill: prepared.fill_for(location.as_ref()), }) .collect(); } - let resident = prepared - .identities - .iter() - .filter_map(|identity| self.probe_resident_prefix(identity)) - .map(|hit| hit.token_count as u64) - .max() - .unwrap_or(0); + let resident = self.longest_resident(&prepared.identities); let mut durable = prepared .identities .iter() @@ -98,6 +231,7 @@ impl KvStageIntegration { RestoreCandidate { identity, location: Some(location), + fill: prepared.fill_for(Some(location)), }, )) }) diff --git a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs index 67026c4f..acd041df 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs @@ -22,6 +22,7 @@ fn fixture(root: &Path) -> (KvStageIntegration, PrefillKvIdentity) { max_entries: 8, max_bytes: 0, l2_max_bytes: 1024, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/kv_integration/exact_state/restore.rs b/crates/skippy-serving/src/kv_integration/exact_state/restore.rs index d69067c3..2a42aa48 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/restore.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/restore.rs @@ -2,6 +2,37 @@ use super::*; impl KvStageIntegration { + /// Exact prefix import materializes KV cells before suffix admission. + /// Make room in the same runtime operation as the import. Protect a + /// matching resident prefix so it can still serve a failed durable fill. + pub(in crate::kv_integration) fn admit_native_prefix_import( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_count: u64, + ) -> Result { + if self.payload != StagePrefixCachePayload::ResidentKv + || runtime.session_token_count(session_id).unwrap_or_default() != 0 + { + // In-place imports own an existing range and can replace its cells. + return Ok(true); + } + let capacity = u64::from(runtime.kv_pool_tokens()); + if token_count > capacity { + return Ok(false); + } + runtime.ensure_session_active(session_id)?; + let free_cells = capacity.saturating_sub(runtime.memory_used_cells(session_id)?); + if free_cells >= token_count { + return Ok(true); + } + let protected = self.probe_resident_prefix(identity).map(|hit| hit.seq_id); + Ok(self + .admit_resident_capacity(runtime, session_id, token_count, 0, 0, protected)? + .admitted) + } + /// Synchronously locate and restore an exact prefix. Scheduled callers use /// prepared metadata so this lookup does not hold the shared runtime lock. pub fn restore_exact_state( diff --git a/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs b/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs index 4caf7781..3ff4a664 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs @@ -53,7 +53,7 @@ fn pending(page_id: &str, admission_credit: ExactStateAdmissionCredit) -> Pendin token_ids: vec![1], l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit, } diff --git a/crates/skippy-serving/src/kv_integration/identity.rs b/crates/skippy-serving/src/kv_integration/identity.rs index 13a9b343..a1f4c7ad 100644 --- a/crates/skippy-serving/src/kv_integration/identity.rs +++ b/crates/skippy-serving/src/kv_integration/identity.rs @@ -268,6 +268,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 64, shared_prefix_stride_tokens: 32, diff --git a/crates/skippy-serving/src/kv_integration/l2_serving.rs b/crates/skippy-serving/src/kv_integration/l2_serving.rs index 66f204d1..3963239d 100644 --- a/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -5,7 +5,7 @@ use std::{ }; use anyhow::{Context, Result}; -use skippy_cache::{L2Hit, L2Origin, L2Stats, L2Tier, l2_cache_key}; +use skippy_cache::{ExactStatePayload, L2Hit, L2Stats, L2Tier, l2_cache_key}; use skippy_runtime::RuntimeKvPageDesc; use crate::runtime_state::RuntimeState; @@ -74,6 +74,25 @@ impl StageL2 { let _ = self.tier.remove(key); } + pub(super) fn contains_location( + &self, + identity: &PrefillKvIdentity, + location: &skippy_cache::L3Location, + ) -> bool { + let Ok(token_count) = usize::try_from(location.token_count) else { + return false; + }; + let Some(tokens) = identity.token_ids.get(..token_count) else { + return false; + }; + self.tier + .peek(&self.cache_key(&identity.namespace, tokens)) + .is_some_and(|hit| { + hit.token_count == location.token_count + && hit.payload_digest == location.manifest_key + }) + } + pub(crate) fn invalidate_digest(&self, payload_digest: &str) { let _ = self.tier.remove_by_digest(payload_digest); } @@ -91,31 +110,19 @@ impl StageL2 { &self, namespace: &str, tokens: &[i32], - expected_payload_digest: &str, + manifest: &skippy_cache::HandoffManifest, payload: &skippy_cache::ExactStatePayload, - extra: &ExactStateExtra, ) -> bool { let key = self.cache_key(namespace, tokens); - let kv_desc_json = extra - .kv_desc - .as_ref() - .and_then(|desc| serde_json::to_string(desc).ok()); let admitted = self .tier - .admit_payload( - key, - tokens.len() as u64, - expected_payload_digest, - payload, - kv_desc_json, - L2Origin::FromL3, - ) + .admit_manifest_payload(key, manifest, payload) .is_ok(); if let Some(observation) = self .promotions .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .get_mut(expected_payload_digest) + .get_mut(&manifest.payload_digest) { observation.terminal = true; } @@ -248,29 +255,68 @@ impl KvStageIntegration { kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; } StagePrefixCachePayload::KvRecurrent => { - if let Some((kv, stats)) = payload - .kv_bytes_timed() - .context("reconstruct L2 KV payload") - .map_err(|error| mark_failure(&mut deterministic_failure, error))? - { - add_reconstruct_stats( - &mut reconstruct_ms, - &mut reconstruct_bytes, - &mut reconstruct_blocks, - stats, - ); + let (recurrent, stats) = payload + .recurrent_state_bytes_timed() + .context("reconstruct L2 recurrent payload") + .map_err(|error| mark_failure(&mut deterministic_failure, error))?; + if recurrent.is_empty() && !self.dense_without_recurrent { + deterministic_failure = true; + anyhow::bail!("L2 recurrent-state payload is empty"); + } + add_reconstruct_stats( + &mut reconstruct_ms, + &mut reconstruct_bytes, + &mut reconstruct_blocks, + stats, + ); + if let ExactStatePayload::KvRecurrent { kv, .. } = &payload { match kv_desc.as_ref() { Some(desc) => { - desc.validate_payload(kv.len()).map_err(|error| { + let kv_len = usize::try_from(kv.len()) + .context("L2 KV payload exceeds addressable memory") + .map_err(|error| { + mark_failure(&mut deterministic_failure, error) + })?; + desc.validate_payload(kv_len).map_err(|error| { mark_failure(&mut deterministic_failure, error) })?; if desc.token_start != 0 || desc.token_count != token_count { deterministic_failure = true; anyhow::bail!("L2 KV page token range mismatch"); } + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(false); + } let started = Instant::now(); - runtime.import_kv_page(session_id, desc, kv.as_ref())?; - kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + let imported = match hit.kv_chunks() { + Some(chunks) => runtime + .try_import_kv_page_chunks(session_id, desc, chunks)?, + None => false, + }; + if imported { + kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + } else { + let (bytes, stats) = kv + .as_cow_timed() + .context("reconstruct L2 KV payload") + .map_err(|error| { + mark_failure(&mut deterministic_failure, error) + })?; + add_reconstruct_stats( + &mut reconstruct_ms, + &mut reconstruct_bytes, + &mut reconstruct_blocks, + stats, + ); + let started = Instant::now(); + runtime.import_kv_page(session_id, desc, bytes.as_ref())?; + kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + } } None if !kv.is_empty() => { deterministic_failure = true; @@ -279,20 +325,6 @@ impl KvStageIntegration { None => {} } } - let (recurrent, stats) = payload - .recurrent_state_bytes_timed() - .context("reconstruct L2 recurrent payload") - .map_err(|error| mark_failure(&mut deterministic_failure, error))?; - if recurrent.is_empty() && !self.dense_without_recurrent { - deterministic_failure = true; - anyhow::bail!("L2 recurrent-state payload is empty"); - } - add_reconstruct_stats( - &mut reconstruct_ms, - &mut reconstruct_bytes, - &mut reconstruct_blocks, - stats, - ); let started = Instant::now(); if recurrent.is_empty() { runtime.set_session_position(session_id, token_count)?; @@ -348,7 +380,7 @@ impl KvStageIntegration { token_ids: tokens.to_vec(), l3_fill_claim: None, write_through_l3: false, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit, }), @@ -380,6 +412,30 @@ fn mark_failure(deterministic: &mut bool, error: anyhow::Error) -> anyhow::Error error } +#[cfg(test)] +pub(super) fn legacy_test_manifest( + token_count: u64, + bytes: &[u8], +) -> skippy_cache::HandoffManifest { + let mut manifest = + skippy_cache::HandoffManifest::new("test".to_owned(), "full-state".to_owned()); + manifest.token_count = token_count; + manifest.total_bytes = bytes.len() as u64; + manifest.kv_bytes = manifest.total_bytes; + manifest.payload_digest = skippy_cache::segment_digest(bytes); + manifest.segments.push(skippy_cache::HandoffSegmentRef { + index: 0, + offset: 0, + bytes: manifest.total_bytes, + digest: manifest.payload_digest.clone(), + codec_identity: Some(skippy_cache::SegmentCodecIdentity::raw( + manifest.total_bytes, + )), + meta_json: None, + }); + manifest +} + #[cfg(test)] mod tests { use super::*; @@ -421,9 +477,8 @@ mod tests { assert!(l2.promote( &identity.namespace, &identity.token_ids[..3], - &digest, + &legacy_test_manifest(3, &[7; 128]), &payload, - &ExactStateExtra { kv_desc: None }, )); assert!(!l2.consider_l3_fill(&digest, 3, payload.byte_len())); @@ -449,15 +504,13 @@ mod tests { fn a_changed_durable_digest_invalidates_the_mirror() { let l2 = StageL2::new(1 << 20, "model".to_string(), "state".to_string()); let bytes = vec![7; 128]; - let digest = skippy_cache::segment_digest(&bytes); let payload = skippy_cache::ExactStatePayload::full_state(bytes); let identity = identity(vec![1, 2, 3]); assert!(l2.promote( &identity.namespace, &identity.token_ids, - &digest, + &legacy_test_manifest(3, &[7; 128]), &payload, - &ExactStateExtra { kv_desc: None }, )); let changed = location(3, skippy_cache::segment_digest(b"changed")); diff --git a/crates/skippy-serving/src/kv_integration/mod.rs b/crates/skippy-serving/src/kv_integration/mod.rs index c9dfbbaf..a079a6cb 100644 --- a/crates/skippy-serving/src/kv_integration/mod.rs +++ b/crates/skippy-serving/src/kv_integration/mod.rs @@ -257,6 +257,7 @@ pub struct KvStageIntegration { /// stored prefix must not each read it from disk: the loser prefills /// normally while the winner re-warms the radix for everyone. pub(crate) inflight_fills: Arc>>, + l3_staging: Arc, /// The model has attention KV but no recurrent memory, so an exact-state /// entry legitimately carries an empty recurrent snapshot. Restores set /// the position directly instead of importing one. Never true for a @@ -300,9 +301,9 @@ pub(crate) struct PendingExactStateRecord { /// Only freshly exported request state writes through. Tier fills that /// merely re-warm L1 must not rewrite their existing durable entry. pub(crate) write_through_l3: bool, - /// Durable manifest digest to mirror into L2 on this worker job. `None` + /// Durable manifest to mirror into L2 on this worker job. `None` /// leaves the payload out of L2. - pub(crate) l2_promotion_digest: Option, + pub(crate) l2_promotion_manifest: Option>, /// Measured cold-versus-restore cost for L3 benefit admission. Missing /// telemetry preserves the established LRU write-through behavior. pub(crate) l3_cost: Option, diff --git a/crates/skippy-serving/src/kv_integration/resident_offload.rs b/crates/skippy-serving/src/kv_integration/resident_offload.rs index c8de000b..b4f0a943 100644 --- a/crates/skippy-serving/src/kv_integration/resident_offload.rs +++ b/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -1,7 +1,13 @@ -//! Materialize a native prefix only when releasing it to the persistent tier. +//! Capture resident prefixes for optional persistence between scheduler work turns. use super::*; use crate::runtime_state::RuntimeState; -use config::durable_spill::PendingDurableSpill; +use config::durable_spill::{DurableSpillSender, NativeSpillExtension}; +use std::num::NonZeroU64; + +mod kv_chunks; +mod work; + +pub(in crate::kv_integration) use work::NativeCapturePayload; #[derive(Debug)] pub(super) struct NativeOffloadClaim { @@ -94,112 +100,79 @@ impl KvStageIntegration { session: &str, victim: &skippy_cache::RadixEvictionCandidate, ) -> Result<()> { - // Disk admission/export is optional. Failure must not prevent reclaiming - // native cells needed by an active request. - if let Err(error) = self.offload_native_prefix(runtime, session, victim) { - static WARNED: AtomicBool = AtomicBool::new(false); - if !WARNED.swap(true, std::sync::atomic::Ordering::AcqRel) { - let _ = skippy_events::diagnostics::emit( - skippy_events::diagnostics::ServingDiagnostic::Warning { - message: - "Native prefix cold offload failed; continuing with cache eviction" - .into(), - context: Some(format!("reason={error:#}")), - }, - ); - } - } runtime.drop_resident_prefix_sequence(session, victim.value.seq_id) } - fn offload_native_prefix( + pub(crate) fn offer_prefix_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: PrefillKvIdentity, + preferred: bool, + ) { + let cache = Arc::downgrade(self); + let mut capture = None; + runtime.offer_prefix_capture(session_id, preferred, move |runtime, session| { + let Some(cache) = cache.upgrade() else { + return std::ops::ControlFlow::Break(()); + }; + match cache.advance_prefix_capture(runtime, session, &identity, &mut capture) { + Ok(std::ops::ControlFlow::Continue(())) => std::ops::ControlFlow::Continue(()), + Ok(std::ops::ControlFlow::Break(_)) => std::ops::ControlFlow::Break(()), + Err(error) => { + tracing::debug!(%error, "durable prefix capture abandoned"); + std::ops::ControlFlow::Break(()) + } + } + }); + } + + #[cfg(test)] + pub(crate) fn capture_resident_prefix_for_l3( &self, runtime: &mut RuntimeState, - session: &str, - victim: &skippy_cache::RadixEvictionCandidate, + identity: &PrefillKvIdentity, ) -> Result { - let sender = self - .exact_state_record_worker - .durable_sender - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - let Some(sender) = sender else { - return Ok(false); - }; - let Some(capabilities) = self.loaded_memory_cache else { - return Ok(false); - }; - if self.l3.is_none() { - return Ok(false); - } - let Some(claim) = - NativeOffloadClaim::acquire(&self.inflight_records, &victim.namespace, &victim.tokens) - else { - return Ok(false); - }; - let sequence = victim.value.seq_id; - let tokens = victim.tokens.len() as u64; - let desc = if capabilities.resident_attention { - Some(runtime.resident_kv_page_desc(session, sequence, tokens)?) - } else { - None - }; - let recurrent_bytes = if capabilities.resident_checkpoint { - runtime.resident_recurrent_state_bytes(session, sequence)? - } else { - 0 - }; - let kv_bytes = desc.as_ref().map_or(0, |desc| desc.payload_bytes); - let bytes = kv_bytes - .checked_add(recurrent_bytes as u64) - .ok_or_else(|| anyhow::anyhow!("native offload size overflow"))?; - if bytes == 0 { - return Ok(false); - } - let Some(reservation) = sender.try_reserve(bytes) else { - return Ok(false); - }; - let kv = if let Some(desc) = &desc { - runtime - .export_resident_kv_page( - session, - sequence, - tokens, - usize::try_from(desc.payload_bytes)?, - )? - .payload - } else { - Vec::new() - }; - let recurrent = if recurrent_bytes > 0 { - runtime.export_resident_recurrent_state(session, sequence, recurrent_bytes)? - } else { - Vec::new() - }; - let payload = if capabilities.resident_attention { - ExactStatePayload::kv_recurrent(kv, recurrent) - } else { - anyhow::ensure!( - capabilities.resident_checkpoint && !recurrent.is_empty(), - "resident prefix has no complete export component" - ); - ExactStatePayload::recurrent_only(recurrent) + let mut capture = None; + const SESSION: &str = "test-durable-prefix-capture"; + runtime.ensure_session_active(SESSION)?; + let result = loop { + match self.advance_prefix_capture(runtime, SESSION, identity, &mut capture) { + Ok(std::ops::ControlFlow::Continue(())) => {} + Ok(std::ops::ControlFlow::Break(committed)) => break Ok(committed), + Err(error) => break Err(error), + } }; - Ok(sender.send_reserved( - PendingDurableSpill { - page_id: victim.value.page_id.clone(), - payload, - extra: ExactStateExtra { kv_desc: desc }, - namespace: victim.namespace.clone(), - token_ids: victim.tokens.clone(), - l3_cost: None, - native_raw: true, - }, - reservation, - claim, - )) + runtime.drop_session_timed(SESSION)?; + result + } +} + +fn incremental_capture( + sender: &DurableSpillSender, + identity: &PrefillKvIdentity, + full: &skippy_runtime::RuntimeKvPageDesc, + recurrent_bytes: usize, +) -> Option { + let base = sender.native_base(&identity.namespace, &identity.token_ids)?; + let base_desc = serde_json::from_str(base.kv_desc_json.as_deref()?).ok()?; + let base_geometry = config::kv_page_geometry(&base_desc, base.kv_bytes)?; + let total = full.payload_bytes.checked_add(recurrent_bytes as u64)?; + let geometry = config::kv_page_geometry(full, total)?; + if base_geometry.blocks != geometry.blocks + || base_geometry.window_rows != geometry.window_rows + || base_geometry.rows != base.token_count + || full.token_start != 0 + { + return None; } + let reused_rows = + NonZeroU64::new(base.token_count / geometry.window_rows * geometry.window_rows)?; + Some(NativeSpillExtension { + base, + reused_rows, + geometry, + }) } #[cfg(test)] diff --git a/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs b/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs new file mode 100644 index 00000000..237c3b02 --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs @@ -0,0 +1,374 @@ +//! Collect independently exported token ranges in native K, V and index order. +//! +//! A native range contains complete runs for its own token window. Joining +//! whole window buffers would put V before K for later windows, so assemble the +//! runs on the spill worker, after releasing the serving runtime. + +use std::num::NonZeroU64; +use std::ops::Range; + +use anyhow::{Context, Result, ensure}; +use skippy_runtime::{ + KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentRole, RuntimeKvPage, RuntimeKvPageDesc, +}; + +use crate::runtime_state::RuntimeState; + +#[derive(Debug)] +pub(super) struct AttentionCapture { + page: RuntimeKvPageDesc, + parts: Vec<(Option, KvCaptureChunks)>, +} + +impl AttentionCapture { + pub(super) fn new(page: RuntimeKvPageDesc, step_bytes: u64) -> Result> { + page.validate_payload(usize::try_from(page.payload_bytes)?)?; + let parts = if page.has_sliding_window_component() { + [KvPageComponentRole::Base, KvPageComponentRole::Swa] + .into_iter() + .map(|role| { + let component = page.component_page(role)?; + Some((Some(role), KvCaptureChunks::try_new(component, step_bytes)?)) + }) + .collect::>>() + } else { + KvCaptureChunks::try_new(page.clone(), step_bytes).map(|part| vec![(None, part)]) + }; + Ok(parts.map(|parts| Self { page, parts })) + } + + pub(super) fn step( + &mut self, + runtime: &mut RuntimeState, + session: &str, + sequence: i32, + ) -> Result { + for (role, part) in &mut self.parts { + if let Some(range) = part.next_range() { + let bytes = part.range_bytes(&range)?; + part.append( + runtime.export_resident_kv_page(session, sequence, range, bytes, *role)?, + )?; + return Ok(true); + } + } + Ok(false) + } + + pub(super) fn byte_len(&self) -> u64 { + self.page.payload_bytes + } + + pub(super) fn assemble(self) -> Result> { + let mut parts = self.parts.into_iter(); + let (_, first) = parts + .next() + .context("native attention capture has no parts")?; + let mut payload = first.assemble()?; + let total = usize::try_from(self.page.payload_bytes)?; + payload.reserve_exact( + total + .checked_sub(payload.len()) + .context("native capture exceeds the page")?, + ); + for (_, part) in parts { + payload.extend(part.assemble()?); + } + self.page.validate_payload(payload.len())?; + Ok(payload) + } +} + +#[derive(Debug)] +struct KvCaptureChunks { + full: RuntimeKvPageDesc, + tokens_per_step: NonZeroU64, + bytes_per_token: u64, + next_token: u64, + end_token: u64, + runs: [(u64, u64); 3], + chunks: Vec>, +} + +impl KvCaptureChunks { + pub(super) fn try_new(full: RuntimeKvPageDesc, step_bytes: u64) -> Option { + if full.component_count != 0 + || full.token_count == 0 + || full.layer_count == 0 + || full.k_row_bytes == 0 + || !full.payload_bytes.is_multiple_of(full.token_count) + { + return None; + } + let layers = u64::from(full.layer_count); + let bytes_per_token = full.payload_bytes / full.token_count; + let tokens_per_step = NonZeroU64::new(step_bytes.checked_div(bytes_per_token)?)?; + let key = u64::from(full.k_row_bytes); + let index = u64::from(full.k_idx_row_bytes); + let other_bytes = layers.checked_mul(key.checked_add(index)?)?; + let value_bytes = bytes_per_token.checked_sub(other_bytes)?; + let (values, stride) = if full.flags & KV_PAGE_FLAG_V_TRANSPOSED == 0 { + let stride = u64::from(full.v_row_bytes); + if value_bytes != layers.checked_mul(stride)? { + return None; + } + (layers, stride) + } else { + let stride = NonZeroU64::new(u64::from(full.v_element_bytes))?.get(); + if !value_bytes.is_multiple_of(stride) { + return None; + } + (value_bytes / stride, stride) + }; + + Some(Self { + tokens_per_step, + bytes_per_token, + next_token: full.token_start, + end_token: full.token_start.checked_add(full.token_count)?, + full, + runs: [(layers, key), (values, stride), (layers, index)], + chunks: Vec::new(), + }) + } + + pub(super) fn next_range(&self) -> Option> { + (self.next_token < self.end_token).then(|| { + self.next_token + ..self + .next_token + .saturating_add(self.tokens_per_step.get()) + .min(self.end_token) + }) + } + + pub(super) fn range_bytes(&self, range: &Range) -> Result { + usize::try_from((range.end - range.start) * self.bytes_per_token) + .context("KV capture slice length exceeds usize") + } + + pub(super) fn append(&mut self, page: RuntimeKvPage) -> Result<()> { + let range = self + .next_range() + .context("KV capture is already complete")?; + let expected = self.range_bytes(&range)?; + let RuntimeKvPage { mut desc, payload } = page; + ensure!( + desc.token_start == range.start + && desc.token_count == range.end - range.start + && desc.payload_bytes == expected as u64 + && payload.len() == expected, + "native export does not match the capture slice" + ); + desc.token_start = self.full.token_start; + desc.token_count = self.full.token_count; + desc.payload_bytes = self.full.payload_bytes; + ensure!(desc == self.full, "native KV layout changed during capture"); + self.chunks.push(payload); + self.next_token = range.end; + Ok(()) + } + + fn assemble(self) -> Result> { + ensure!(self.next_range().is_none(), "KV capture is incomplete"); + if self.chunks.len() == 1 { + return Ok(self.chunks.into_iter().next().unwrap_or_default()); + } + + // One iterator per window. Interleave one run of each iterator at a + // time to reconstruct the original full-length native runs. + let mut windows: Vec<_> = self + .chunks + .iter() + .map(|bytes| { + let count = u64::try_from(bytes.len())? / self.bytes_per_token; + Ok((usize::try_from(count)?, bytes.as_slice())) + }) + .collect::>()?; + let mut payload = Vec::with_capacity(usize::try_from(self.full.payload_bytes)?); + for (count, stride) in self.runs { + let stride = usize::try_from(stride)?; + if stride == 0 { + continue; + } + for _ in 0..count { + for (tokens, remaining) in &mut windows { + let (run, suffix) = remaining + .split_at_checked(*tokens * stride) + .context("native KV capture window is truncated")?; + payload.extend_from_slice(run); + *remaining = suffix; + } + } + } + ensure!( + windows.iter().all(|(_, remaining)| remaining.is_empty()), + "native KV capture has trailing bytes" + ); + self.full.validate_payload(payload.len())?; + Ok(payload) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_runtime::KV_PAGE_FLAG_HAS_K_IDX; + + #[test] + fn composite_capture_preserves_base_and_sliding_window_byte_order() { + let mut page = RuntimeKvPageDesc { + version: 2, + codec: 2, + layer_start: 0, + layer_end: 1, + layer_count: 0, + token_start: 0, + token_count: 4, + k_type: 0, + v_type: 0, + k_row_bytes: 0, + v_row_bytes: 0, + v_element_bytes: 0, + k_idx_row_bytes: 0, + payload_bytes: 6, + flags: 0, + component_count: 2, + components: Box::default(), + }; + let [base, swa] = page.components.as_mut(); + base.version = 1; + base.role = KvPageComponentRole::Base as u32; + base.token_count = 4; + base.layer_count = 1; + base.k_row_bytes = 1; + base.payload_bytes = 4; + *swa = *base; + swa.role = KvPageComponentRole::Swa as u32; + swa.token_start = 2; + swa.token_count = 2; + swa.payload_offset = 4; + swa.payload_bytes = 2; + let mut capture = AttentionCapture::new(page, 2).unwrap().unwrap(); + for (role, part) in &mut capture.parts { + while let Some(range) = part.next_range() { + let mut desc = part.full.clone(); + desc.token_start = range.start; + desc.token_count = range.end - range.start; + desc.payload_bytes = desc.token_count; + let base = u8::from(*role == Some(KvPageComponentRole::Swa)) * 16; + let payload = range + .map(|token| base + u8::try_from(token).unwrap()) + .collect(); + part.append(RuntimeKvPage { desc, payload }).unwrap(); + } + } + assert_eq!(capture.assemble().unwrap(), [0, 1, 2, 3, 18, 19]); + } + + fn descriptor(transposed: bool) -> RuntimeKvPageDesc { + RuntimeKvPageDesc { + version: 1, + codec: 1, + layer_start: 0, + layer_end: 1, + layer_count: 1, + token_start: 64, + token_count: 3, + k_type: 1, + v_type: 1, + k_row_bytes: 2, + v_row_bytes: if transposed { 0 } else { 3 }, + v_element_bytes: u32::from(transposed), + k_idx_row_bytes: 1, + payload_bytes: 18, + flags: KV_PAGE_FLAG_HAS_K_IDX + | if transposed { + KV_PAGE_FLAG_V_TRANSPOSED + } else { + 0 + }, + component_count: 0, + components: Default::default(), + } + } + + #[test] + fn token_windows_reassemble_in_native_order() { + let first_key = [10, 11, 12, 13]; + let last_key = [14, 15]; + let first_index = [30, 31]; + let last_index = [32]; + for (transposed, first_value, last_value, full_value) in [ + ( + false, + [20, 21, 22, 23, 24, 25], + [26, 27, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28], + ), + ( + true, + [20, 21, 23, 24, 26, 27], + [22, 25, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28], + ), + ] { + let desc = descriptor(transposed); + let mut chunks = KvCaptureChunks::try_new(desc.clone(), 12).unwrap(); + assert_eq!(chunks.next_range(), Some(64..66)); + chunks + .append(RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_count: 2, + payload_bytes: 12, + ..desc.clone() + }, + payload: [&first_key[..], &first_value, &first_index].concat(), + }) + .unwrap(); + assert_eq!(chunks.next_range(), Some(66..67)); + chunks + .append(RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_start: 66, + token_count: 1, + payload_bytes: 6, + ..desc + }, + payload: [&last_key[..], &last_value, &last_index].concat(), + }) + .unwrap(); + assert_eq!( + chunks.assemble().unwrap(), + [ + &first_key[..], + &last_key, + &full_value, + &first_index, + &last_index + ] + .concat() + ); + } + } + + #[test] + fn token_windows_reject_a_wrong_layout_and_unfinished_capture() { + let desc = descriptor(false); + let mut chunks = KvCaptureChunks::try_new(desc.clone(), 12).unwrap(); + let bad = RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_count: 2, + payload_bytes: 12, + // A raw KV page with a different value type cannot be mixed + // with the descriptor used to size the complete checkpoint. + v_type: desc.v_type + 1, + ..desc + }, + payload: vec![0; 12], + }; + assert!(chunks.append(bad).is_err()); + assert_eq!(chunks.next_range(), Some(64..66)); + assert!(chunks.assemble().is_err()); + } +} diff --git a/crates/skippy-serving/src/kv_integration/resident_offload/work.rs b/crates/skippy-serving/src/kv_integration/resident_offload/work.rs new file mode 100644 index 00000000..9b6376fc --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/resident_offload/work.rs @@ -0,0 +1,246 @@ +//! A durable capture owns the host bytes it has copied. A resident entry can +//! leave L1 between steps. Its eviction cancels the unfinished copy and never +//! runs or waits for the exporter. + +use std::ops::ControlFlow; + +use anyhow::{Context, ensure}; + +use super::kv_chunks::AttentionCapture; +use super::*; +use crate::kv_integration::config::durable_spill::{ + DurableSpillPayload, DurableSpillReservation, PendingDurableSpill, +}; + +const CAPTURE_STEP_BYTES: usize = 8 * 1024 * 1024; +const MAX_CAPTURE_BYTES: u64 = 1024 * 1024 * 1024; + +pub(super) struct NativePrefixCapture { + entry: RadixResidentEntry, + full_desc: Option, + payload: NativeCapturePayload, + extension: Option, + reservation: DurableSpillReservation, + claim: NativeOffloadClaim, +} + +#[derive(Debug)] +pub(in crate::kv_integration) struct NativeCapturePayload { + attention: Option, + recurrent_bytes: usize, + recurrent_copied: usize, + recurrent_chunks: Vec>, +} + +impl NativeCapturePayload { + fn step(&mut self, runtime: &mut RuntimeState, session: &str, sequence: i32) -> Result { + if let Some(attention) = self.attention.as_mut() + && attention.step(runtime, session, sequence)? + { + return Ok(true); + } + if self.recurrent_copied == self.recurrent_bytes { + return Ok(false); + } + let bytes = (self.recurrent_bytes - self.recurrent_copied).min(CAPTURE_STEP_BYTES); + let mut chunk = vec![0; bytes]; + runtime.copy_resident_recurrent_range( + session, + sequence, + self.recurrent_copied, + &mut chunk, + )?; + self.recurrent_copied += bytes; + self.recurrent_chunks.push(chunk); + Ok(true) + } + + pub(in crate::kv_integration) fn byte_len(&self) -> u64 { + self.attention + .as_ref() + .map_or(0, AttentionCapture::byte_len) + + self.recurrent_bytes as u64 + } + + pub(in crate::kv_integration) fn assemble(mut self) -> Result { + ensure!( + self.recurrent_copied == self.recurrent_bytes, + "resident recurrent copy is incomplete" + ); + let recurrent = if self.recurrent_chunks.len() == 1 { + self.recurrent_chunks.pop().unwrap_or_default() + } else { + let mut recurrent = Vec::with_capacity(self.recurrent_bytes); + for chunk in self.recurrent_chunks { + recurrent.extend(chunk); + } + recurrent + }; + match self.attention { + Some(attention) => Ok(ExactStatePayload::kv_recurrent( + attention.assemble()?, + recurrent, + )), + None => Ok(ExactStatePayload::recurrent_only(recurrent)), + } + } +} + +impl KvStageIntegration { + pub(super) fn advance_prefix_capture( + &self, + runtime: &mut RuntimeState, + session: &str, + identity: &PrefillKvIdentity, + state: &mut Option, + ) -> Result> { + let entry = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .resident_exact(&identity.namespace, &identity.token_ids) + .map(|entry| entry.value); + let Some(entry) = entry else { + return Ok(ControlFlow::Break(false)); + }; + let Some(capture) = state.as_mut() else { + *state = self.prepare_prefix_capture(runtime, session, identity, entry)?; + return Ok(if state.is_some() { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(false) + }); + }; + if capture.entry.seq_id != entry.seq_id || capture.entry.page_id != entry.page_id { + return Ok(ControlFlow::Break(false)); + } + if capture.payload.step(runtime, session, entry.seq_id)? { + return Ok(ControlFlow::Continue(())); + } + + let capture = state.take().context("missing durable prefix capture")?; + // A paused capture must not keep the spill channel open. The cache + // can lose its last owner on this scheduler thread, and its drop + // joins the spill worker before the paused captures are dropped. + let sender = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(sender) = sender.as_ref() else { + return Ok(ControlFlow::Break(false)); + }; + Ok(ControlFlow::Break(sender.send_reserved( + PendingDurableSpill { + page_id: entry.page_id, + payload: DurableSpillPayload::Native(capture.payload), + extra: ExactStateExtra { + kv_desc: capture.full_desc, + }, + namespace: identity.namespace.clone(), + token_ids: identity.token_ids.to_vec(), + l3_cost: None, + native_raw: true, + extension: capture.extension, + }, + capture.reservation, + capture.claim, + ))) + } + + fn prepare_prefix_capture( + &self, + runtime: &mut RuntimeState, + session: &str, + identity: &PrefillKvIdentity, + entry: RadixResidentEntry, + ) -> Result> { + let sender = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let (Some(sender), Some(capabilities)) = (sender, self.loaded_memory_cache) else { + return Ok(None); + }; + if self.l3.is_none() + || sender.has_native_checkpoint(&identity.namespace, &identity.token_ids) + { + return Ok(None); + } + let Some(claim) = NativeOffloadClaim::acquire( + &self.inflight_records, + &identity.namespace, + &identity.token_ids, + ) else { + return Ok(None); + }; + let sequence = entry.seq_id; + let tokens = entry.token_count; + let full_desc = capabilities + .resident_attention + .then(|| runtime.resident_kv_page_desc(session, sequence, 0..tokens)) + .transpose()?; + let recurrent_bytes = if capabilities.resident_checkpoint { + runtime.resident_recurrent_state_bytes(session, sequence)? + } else { + 0 + }; + let incremental = full_desc + .as_ref() + .and_then(|full| incremental_capture(&sender, identity, full, recurrent_bytes)) + .and_then(|extension| { + let start = extension.reused_rows.get(); + let tail = runtime + .resident_kv_page_desc(session, sequence, start..tokens) + .ok()?; + let geometry = config::kv_page_geometry(&tail, tail.payload_bytes)?; + (tail.token_start == start + && tail.token_count == tokens - start + && geometry.blocks == extension.geometry.blocks + && geometry.window_rows == extension.geometry.window_rows) + .then_some((extension, tail)) + }); + let (extension, capture_desc) = match incremental { + Some((extension, tail)) => (Some(extension), Some(tail)), + None => (None, full_desc.clone()), + }; + let kv_bytes = capture_desc.as_ref().map_or(0, |desc| desc.payload_bytes); + let bytes = kv_bytes + .checked_add(recurrent_bytes as u64) + .context("native offload size overflow")?; + if bytes == 0 || bytes > MAX_CAPTURE_BYTES { + return Ok(None); + } + let attention = match capture_desc { + Some(desc) => { + let Some(attention) = AttentionCapture::new(desc, CAPTURE_STEP_BYTES as u64)? + else { + return Ok(None); + }; + Some(attention) + } + None => None, + }; + // Reserve room for simultaneous source slices and their assembled + // payload. The serving scheduler never allocates the assembled copy. + let reserved = 2 * bytes; + let Some(reservation) = sender.try_reserve(reserved) else { + return Ok(None); + }; + Ok(Some(NativePrefixCapture { + entry, + full_desc, + payload: NativeCapturePayload { + attention, + recurrent_bytes, + recurrent_copied: 0, + recurrent_chunks: Vec::new(), + }, + extension, + reservation, + claim, + })) + } +} diff --git a/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs b/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs index 4437c76e..02737402 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs @@ -16,6 +16,7 @@ fn config(capacity: u32) -> StageConfig { max_entries: 32, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, min_tokens: 1, shared_prefix_stride_tokens: 32, shared_prefix_record_limit: 32, diff --git a/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/crates/skippy-serving/src/kv_integration/resident_prefix.rs index 8cd1a447..5a32d673 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -732,6 +732,7 @@ mod proactive_eviction_tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -809,6 +810,7 @@ mod proactive_eviction_tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs index c5a961ed..85809a7c 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -12,6 +12,37 @@ impl KvStageIntegration { .map(ResidentRecordOutcome::into_record) } + pub(crate) fn record_resident_prefix_for_idle_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + ) -> Result> { + self.record_resident_prefix_with_capture(runtime, session_id, identity, token_ids, false) + } + + pub(crate) fn record_resident_prefix_with_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + prefer_full_prompt: bool, + ) -> Result> { + let record = self.record_resident_prefix(runtime, session_id, identity, token_ids)?; + if let Some(record) = &record + && self.l3.is_some() + { + let mut identity = identity.clone(); + identity.token_ids.truncate(record.token_count); + identity.identity.token_count = record.token_count as u64; + let preferred = prefer_full_prompt && record.token_count == token_ids.len(); + self.offer_prefix_capture(runtime, session_id, identity, preferred); + } + Ok(record) + } + /// Record a resident prefix, saying why when none is kept. pub fn record_resident_prefix_outcome( &self, diff --git a/crates/skippy-serving/src/kv_integration/scheduling.rs b/crates/skippy-serving/src/kv_integration/scheduling.rs index 88ca14eb..b219087e 100644 --- a/crates/skippy-serving/src/kv_integration/scheduling.rs +++ b/crates/skippy-serving/src/kv_integration/scheduling.rs @@ -73,6 +73,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 1024, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/kv_integration/snapshot_validation.rs b/crates/skippy-serving/src/kv_integration/snapshot_validation.rs index 202d9169..93f4427e 100644 --- a/crates/skippy-serving/src/kv_integration/snapshot_validation.rs +++ b/crates/skippy-serving/src/kv_integration/snapshot_validation.rs @@ -63,6 +63,7 @@ mod tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, diff --git a/crates/skippy-serving/src/runtime_state.rs b/crates/skippy-serving/src/runtime_state.rs index e15f160f..6ff12a79 100644 --- a/crates/skippy-serving/src/runtime_state.rs +++ b/crates/skippy-serving/src/runtime_state.rs @@ -98,6 +98,8 @@ pub struct RuntimeState { /// Set while parked sessions' exports run, so their own runtime calls do /// not start completing the rest. completing_parked_session_ends: bool, + prefix_capture: Option, + next_prefix_capture: Option, #[cfg(test)] modelless_for_test: bool, /// Lets modelless tests exercise a split DFlash final stage. @@ -298,6 +300,8 @@ impl RuntimeState { session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + prefix_capture: None, + next_prefix_capture: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer: None, compute_meter: Arc::default(), @@ -455,6 +459,8 @@ fn runtime_from_loaded_model( session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + prefix_capture: None, + next_prefix_capture: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer, compute_meter: Arc::default(), diff --git a/crates/skippy-serving/src/runtime_state/context_capacity.rs b/crates/skippy-serving/src/runtime_state/context_capacity.rs index d050cfab..aa38e856 100644 --- a/crates/skippy-serving/src/runtime_state/context_capacity.rs +++ b/crates/skippy-serving/src/runtime_state/context_capacity.rs @@ -124,6 +124,7 @@ mod tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index affe513f..9204e423 100644 --- a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -645,6 +645,31 @@ impl RuntimeState { self.abandon_session_end_kv_exports(session_id); let session = self.session(session_id)?; session.import_kv_page(desc, bytes)?; + self.record_imported_kv_page(session_id, desc) + } + + pub fn try_import_kv_page_chunks<'a>( + &mut self, + session_id: &str, + desc: &RuntimeKvPageDesc, + chunks: impl ExactSizeIterator, + ) -> Result { + self.abandon_session_end_kv_exports(session_id); + if !self + .session(session_id)? + .try_import_kv_page_chunks(desc, chunks)? + { + return Ok(false); + } + self.record_imported_kv_page(session_id, desc)?; + Ok(true) + } + + fn record_imported_kv_page( + &mut self, + session_id: &str, + desc: &RuntimeKvPageDesc, + ) -> Result<()> { let token_end = desc .token_start .checked_add(desc.token_count) diff --git a/crates/skippy-serving/src/runtime_state/panic_recovery.rs b/crates/skippy-serving/src/runtime_state/panic_recovery.rs index 296826a0..f56ee069 100644 --- a/crates/skippy-serving/src/runtime_state/panic_recovery.rs +++ b/crates/skippy-serving/src/runtime_state/panic_recovery.rs @@ -34,6 +34,8 @@ impl PanicRecovery for RuntimeState { // A panic leaves every lane suspect, so no owed export may read one. // A sink that panicked left the completion flag set. self.completing_parked_session_ends = false; + self.prefix_capture = None; + self.next_prefix_capture = None; self.abandon_all_session_end_kv_exports(); let mut session_ids: Vec = self.sessions.keys().cloned().collect(); session_ids.extend(self.session_token_counts.keys().cloned()); diff --git a/crates/skippy-serving/src/runtime_state/resident_prefix.rs b/crates/skippy-serving/src/runtime_state/resident_prefix.rs index c1baa6b3..67b55962 100644 --- a/crates/skippy-serving/src/runtime_state/resident_prefix.rs +++ b/crates/skippy-serving/src/runtime_state/resident_prefix.rs @@ -1,34 +1,130 @@ //! Cold exports read immutable cache owners, never a borrowed execution lane. use super::*; +use std::ops::ControlFlow; + +type CaptureStep = Box ControlFlow<()> + Send>; + +pub(super) struct PrefixCaptureJob { + session_id: String, + preferred: bool, + started: bool, + advance: CaptureStep, +} + +impl RuntimeState { + pub(crate) fn offer_prefix_capture( + &mut self, + session_id: &str, + preferred: bool, + advance: impl FnMut(&mut Self, &str) -> ControlFlow<()> + Send + 'static, + ) { + let job = PrefixCaptureJob { + session_id: session_id.to_owned(), + preferred, + started: false, + advance: Box::new(advance), + }; + match self.prefix_capture.as_ref() { + None => self.prefix_capture = Some(job), + Some(current) + if (!current.preferred && preferred) + || (!current.started + && current.preferred == preferred + && current.session_id == session_id) => + { + self.prefix_capture = Some(job); + } + Some(current) + if current.preferred && !preferred && current.session_id == session_id => {} + Some(_) => { + // Do not let an extension or unrelated request overwrite the + // seed in progress. Keep one later opportunity without + // pinning either entry against eviction. + if self.next_prefix_capture.as_ref().is_none_or(|next| { + !next.preferred || (preferred && next.session_id == session_id) + }) { + self.next_prefix_capture = Some(job); + } + } + } + } + + pub(crate) fn has_prefix_capture_work(&self) -> bool { + self.parked_session_ends.is_empty() + && self.prefix_capture.as_ref().is_some_and(|job| { + // A grid boundary is a fallback. Wait for its canonical + // prompt boundary while requests are still using the runtime. + job.preferred || self.sessions.is_empty() + }) + } + + /// Attempt one copy or admission step using an execution view on the + /// shared model. The saved sequence remains owned by the resident cache. + pub(crate) fn run_prefix_capture_step(&mut self) -> bool { + if !self.has_prefix_capture_work() { + return false; + } + let Some(mut job) = self.prefix_capture.take() else { + return false; + }; + const IDLE_SESSION: &str = "native-prefix-durable-capture"; + let active = self.sessions.keys().next().cloned(); + let session = match active.as_deref() { + Some(session) => session, + None => { + if let Err(error) = self.ensure_session_active(IDLE_SESSION) { + tracing::debug!(%error, "durable prefix capture could not acquire idle lane"); + self.prefix_capture = self.next_prefix_capture.take(); + return true; + } + IDLE_SESSION + } + }; + job.started = true; + let outcome = (job.advance)(self, session); + if active.is_none() + && let Err(error) = self.drop_session_timed(IDLE_SESSION) + { + tracing::debug!(%error, "durable prefix capture could not release idle lane"); + } + self.prefix_capture = match outcome { + ControlFlow::Continue(()) => Some(job), + ControlFlow::Break(()) => self.next_prefix_capture.take(), + }; + true + } +} + impl RuntimeState { pub(crate) fn resident_kv_page_desc( &mut self, session: &str, sequence: i32, - tokens: u64, + tokens: std::ops::Range, ) -> Result { let layers = ( i32::try_from(self.model_layer_start())?, i32::try_from(self.model_layer_end())?, ); self.session(session)? - .resident_kv_page_desc(sequence, layers, tokens) + .resident_kv_range_desc(sequence, layers, tokens) } pub(crate) fn export_resident_kv_page( &mut self, session: &str, sequence: i32, - tokens: u64, + tokens: std::ops::Range, bytes: usize, + component: Option, ) -> Result { let layers = ( i32::try_from(self.model_layer_start())?, i32::try_from(self.model_layer_end())?, ); self.session(session)? - .export_resident_kv_page(sequence, layers, tokens, bytes) + .export_resident_attention_range(sequence, layers, tokens, bytes, component) } pub(crate) fn resident_recurrent_state_bytes( @@ -40,13 +136,80 @@ impl RuntimeState { .resident_recurrent_state_bytes(sequence) } - pub(crate) fn export_resident_recurrent_state( + pub(crate) fn copy_resident_recurrent_range( &mut self, session: &str, sequence: i32, - bytes: usize, - ) -> Result> { + offset: usize, + output: &mut [u8], + ) -> Result<()> { self.session(session)? - .export_resident_recurrent_state(sequence, bytes) + .copy_resident_recurrent_range(sequence, offset, output) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + fn runtime_with_active_lane() -> RuntimeState { + let mut runtime = RuntimeState::new_modelless_for_test(1); + runtime.sessions.insert( + "active".to_owned(), + RuntimeLaneSession { + index: 0, + session: skippy_runtime::StageSession::detached_dflash_for_test(), + resident_prefix: None, + }, + ); + runtime + } + + #[test] + fn later_requests_cannot_replace_the_reusable_seed() { + let mut runtime = runtime_with_active_lane(); + let steps = Arc::new(Mutex::new(Vec::new())); + let seed = steps.clone(); + let mut advanced = false; + runtime.offer_prefix_capture("seed", true, move |_, _| { + seed.lock().unwrap().push("seed"); + if std::mem::replace(&mut advanced, true) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }); + let extension = steps.clone(); + runtime.offer_prefix_capture("extension", true, move |_, _| { + extension.lock().unwrap().push("extension"); + ControlFlow::Break(()) + }); + + assert!(runtime.run_prefix_capture_step()); + runtime.offer_prefix_capture("pressure", false, |_, _| { + panic!("unrelated pressure replaced a reusable capture") + }); + assert!(runtime.run_prefix_capture_step()); + assert!(runtime.run_prefix_capture_step()); + assert!(!runtime.run_prefix_capture_step()); + assert_eq!(*steps.lock().unwrap(), ["seed", "seed", "extension"]); + } + + #[test] + fn preferred_boundary_can_replace_an_unstarted_grid_capture_in_the_same_request() { + let mut runtime = runtime_with_active_lane(); + let advanced = Arc::new(Mutex::new(false)); + runtime.offer_prefix_capture("seed", false, |_, _| panic!("obsolete checkpoint")); + assert!(!runtime.run_prefix_capture_step()); + let completed = advanced.clone(); + runtime.offer_prefix_capture("seed", true, move |_, _| { + *completed.lock().unwrap() = true; + ControlFlow::Break(()) + }); + + assert!(runtime.run_prefix_capture_step()); + assert!(*advanced.lock().unwrap()); + assert!(!runtime.run_prefix_capture_step()); } } diff --git a/docs-site/content/cli.mdx b/docs-site/content/cli.mdx index 47663375..67d6302f 100644 --- a/docs-site/content/cli.mdx +++ b/docs-site/content/cli.mdx @@ -89,6 +89,8 @@ run its full path, such as `skippy models download --help`. | `--n-gpu-layers N` | Set the number of local model layers to offload. Use `-1` to offload all supported layers. | | `--gpu-id ID` | Pin an offloaded local model to a stable GPU ID. Use `doctor --device-inventory` to inspect IDs and visibility. | | `--generation-concurrency N` | Set the maximum active generation requests. Automatic local planning defaults to four lanes sharing a KV pool. | +| `--prefix-cache-checkpoint-ram SIZE` | Set the native L1 recurrent-checkpoint budget. The default is 1 GiB. | +| `--prefix-cache-ram SIZE` | Set the separate L2 host-RAM budget for disk fills. Use `off` to disable L2. | | `--mmproj PATH` | Select a multimodal projector GGUF. By default, Skippy looks for a matching installed projector. | | `--on-demand` | Defer an unsplit model's native load until the first inference request. Eager loading is the default. | | `--idle-evict-secs N` | Release an unsplit model after 1–86,400 idle seconds. Omit to disable idle eviction. | diff --git a/docs-site/content/configuration/reference.mdx b/docs-site/content/configuration/reference.mdx index fb0e9643..c94bbbbe 100644 --- a/docs-site/content/configuration/reference.mdx +++ b/docs-site/content/configuration/reference.mdx @@ -91,7 +91,8 @@ The environment overrides are `SKIPPY_SERVE_ON_DEMAND`, | `prefix_cache` | Select `auto`, `on`, `off`, or `record` | | `prefix_cache_budget` | Set the resident retention target | | `prefix_cache_max_entries`, `prefix_cache_min_tokens` | Bound retained entries and minimum useful prefixes | -| `prefix_cache_ram` | Bound native recurrent-checkpoint RAM; serialized runtimes use an optional tier above disk | +| `prefix_cache_ram` | Set the L2 host-RAM budget for disk fills | +| `prefix_cache_checkpoint_ram` | Set the L1 recurrent-checkpoint RAM budget, which defaults to 1 GiB | | `prefix_cache_retention_tokens` | Bound attention cells retained after requests finish. Defaults to 16,384 tokens. Use `0` to release all finished-request cells or `unbounded` to retain as much as the shared pool allows. | | `prefill_admission` | Select `cooperative` (default) or `serialized` suffix prefill | | `kv_cache_disk`, `kv_cache_disk_dir` | Set the disk cache budget and location. The default is `off`. The `auto` budget is capped at 64 GiB. | diff --git a/docs-site/content/kv-caching/disk-tier.mdx b/docs-site/content/kv-caching/disk-tier.mdx index 5e6cdd09..c23bc3c1 100644 --- a/docs-site/content/kv-caching/disk-tier.mdx +++ b/docs-site/content/kv-caching/disk-tier.mdx @@ -41,10 +41,11 @@ honors the minimum free-space reserve. Use `off` to disable the tier. ## How the tiers interact Skippy compares compatible resident and committed disk prefixes and restores -the longest valid checkpoint. A resident prefix wins a tie. Resident native -state is exported when it is cold-evicted, rather than serializing every warm -record. Restored disk entries are verified before use. A refused or failed -cold offload can lose reuse and require cold prefill on a later request. +the longest valid checkpoint. A resident prefix wins a tie. Eviction releases +native KV cells immediately. While the runtime is idle, Skippy can export a +retained checkpoint and queue a bounded write. A prefix evicted before capture +may require cold prefill on a later request. Skippy verifies restored disk +entries before use. ## Failure policy @@ -53,13 +54,14 @@ operator's retention policy. Once a valid configuration is running, storage unavailability fails open for inference: Skippy logs the problem and serves with cold prefill rather than making the model unavailable. -Native resident runtimes use `prefix_cache_ram` for recurrent checkpoints, -independently of disk. Serialized runtimes use it for an optional host-RAM tier -above an active disk tier: +`prefix_cache_ram` sets the optional L2 host-RAM tier above an active disk +tier. `prefix_cache_checkpoint_ram` sets the separate L1 recurrent-checkpoint +budget: ```toml [cache] prefix_cache_ram = "4GiB" +prefix_cache_checkpoint_ram = "1GiB" kv_cache_disk = "32GiB" ``` @@ -78,7 +80,8 @@ kill switches. Unset them before explicitly enabling prefix caching. | `kv_cache_disk` | `off` (default), `auto`, or IEC size | Enable and bound durable storage | | `kv_cache_disk_dir` | Local directory | Choose the cache root. Defaults to `$SKIPPY_HOME/kv-cache` or `~/.skippy/kv-cache`. | | `kv_cache_min_free` | IEC size of at least `1GiB` | Reserve free space on the volume. Defaults to `16GiB`. | -| `prefix_cache_ram` | `off` or IEC size | Bound native checkpoint RAM; serialized runtimes can add a RAM tier above disk | +| `prefix_cache_ram` | `off` or IEC size | Set the L2 host-RAM budget for disk fills. | +| `prefix_cache_checkpoint_ram` | `auto` or positive IEC size | Set the L1 checkpoint budget. Defaults to 1 GiB. | Invalid startup configuration is fatal. Runtime storage failure is not: inference continues with cold prefill and Skippy reports the cache error. diff --git a/docs-site/content/kv-caching/index.mdx b/docs-site/content/kv-caching/index.mdx index 8621a924..98c503d7 100644 --- a/docs-site/content/kv-caching/index.mdx +++ b/docs-site/content/kv-caching/index.mdx @@ -78,9 +78,11 @@ explicit choice fails rather than silently changing precision. Native resident caching keeps attention cells in the shared KV pool. Hybrid and recurrent models also retain immutable checkpoints in a separate, bounded -host-RAM budget. This works with disk caching disabled. Set `prefix_cache_ram` -to an IEC size to bound those checkpoints; `off` or an unset value selects the -1 GiB default. Disable prefix caching itself to retain no checkpoints. +host-RAM budget. This works with disk caching disabled. Set +`prefix_cache_checkpoint_ram` to a positive IEC size or leave it at the +1 GiB default. Move any previous native checkpoint override from +`prefix_cache_ram` to this setting. Disable prefix caching itself to retain +no checkpoints. For serialized runtimes on unified-memory systems, set `prefix_cache_ram = "off"` to avoid a second copy in the same physical memory. @@ -118,7 +120,8 @@ status, matched prefix tokens, suffix prefill tokens, and restore source. | `prefix_cache_budget` | Set the resident retention target | | `prefix_cache_exact_budget` | Set the exact-state retention ceiling; one snapshot may exceed it | | `prefix_cache_max_entries` | Limit retained prefix entries | -| `prefix_cache_ram` | Bound native recurrent checkpoints; serialized runtimes use optional L2 | +| `prefix_cache_ram` | Set the L2 host-RAM budget for disk fills | +| `prefix_cache_checkpoint_ram` | Bound native L1 recurrent checkpoints | | `prefix_cache_retention_tokens` | Bound attention cells retained after requests finish | | `prefill_admission` | Cooperatively batch uncached suffixes, or serialize their prefill | | `prefix_cache_min_tokens` | Avoid recording prefixes below a token threshold | diff --git a/docs/CAUSAL_DECISIONS.md b/docs/CAUSAL_DECISIONS.md index d607e0a0..f9b574a8 100644 --- a/docs/CAUSAL_DECISIONS.md +++ b/docs/CAUSAL_DECISIONS.md @@ -112,7 +112,7 @@ fallback. In split execution, the terminal worker computes scores and returns only a bounded selected-token vector. Full vocabulary logits remain inside the native runtime. All workers must support stage protocol generation 19, wire header -version 18 and Skippy ABI 0.1.94. Upgrade the whole chain together so +version 18 and Skippy ABI 0.1.95. Upgrade the whole chain together so they can negotiate. Additive `system_one` discovery does not grant this ability to an older runtime. No persisted-data migration is required. diff --git a/docs/PROMPT_CACHE.md b/docs/PROMPT_CACHE.md index fdb8e05e..a0a45798 100644 --- a/docs/PROMPT_CACHE.md +++ b/docs/PROMPT_CACHE.md @@ -85,10 +85,11 @@ working set grows. Recurrent checkpoints consume host RAM independently of the attention pool. Their budget is bounded and does not require a disk cache. An entry that cannot fit the checkpoint budget is not retained; it cannot remain indefinitely over -budget merely because it is the last entry. Standalone -`--prefix-cache-ram SIZE` supplies this -budget. A zero/unset value selects the bounded 1 GiB native-cache default; -disable prefix caching itself to retain no entries. +budget merely because it is the last entry. Set +`--prefix-cache-checkpoint-ram SIZE` to override the 1 GiB default. +`--prefix-cache-ram` controls the separate L2 host-RAM tier. Move an +existing native checkpoint override to the new flag to preserve its size. +Disable prefix caching itself to retain no entries. ## Admission @@ -113,11 +114,11 @@ prompt chunks with decode rows is visible per native batch on the ## Persistence boundary -The resident path does not eagerly export complete KV state into a blob store -or mirror every new prefix to disk. When persistent L3 is enabled, eviction is -the cold offload boundary: serving exports the retained attention cells and -their recurrent checkpoint, then queues a bounded durable write before -releasing native cache ownership. Disk payload integrity remains verified. +The resident path reclaims cells immediately when it evicts a prefix. +With L3 enabled, the scheduler can capture one retained prefix while the +runtime is idle and hand its owned payload to the disk writer. A prefix can +be evicted before capture or skipped when the export or writer queue exceeds +its byte limit. L3 verifies payload integrity on restore. An L3 fill restores the complete state after a resident miss and can warm the native radix cache again. Completed durable records survive a process restart. diff --git a/docs/SERVING_SETTINGS.md b/docs/SERVING_SETTINGS.md index 3cd504dd..3d35dd69 100644 --- a/docs/SERVING_SETTINGS.md +++ b/docs/SERVING_SETTINGS.md @@ -376,7 +376,8 @@ known size. Use them without `--prompt` or `--stage-transport`. | `--prefix-cache` | `prefix_cache` | Prompt reuse: auto, on, off, record | | `--prefix-cache-codec` | `prefix_cache_codec` | Durable representation: native or experimental cachegen | | `--prefix-cache-budget` | `prefix_cache_budget` | Retention target: auto, unbounded, or IEC size; exact snapshots may exceed it | -| `--prefix-cache-ram` | `prefix_cache_ram` | Native recurrent-checkpoint RAM budget, independent of disk; off/unset selects the bounded default. Serialized runtimes use an optional host-RAM tier requiring disk caching | +| `--prefix-cache-ram` | `prefix_cache_ram` | L2 host-RAM tier for disk fills. Use off or a fixed IEC size. | +| `--prefix-cache-checkpoint-ram` | `prefix_cache_checkpoint_ram` | L1 recurrent-checkpoint RAM. Use auto for 1 GiB or a positive IEC size. | | `--prefix-cache-max-entries` | `prefix_cache_max_entries` | Maximum retained prefix entries | | `--prefix-cache-min-tokens` | `prefix_cache_min_tokens` | Minimum prefix length to record or reuse | | `--prefix-cache-stride-tokens` | `prefix_cache_stride_tokens` | Shared-prefix checkpoint spacing in tokens | diff --git a/docs/native-api.md b/docs/native-api.md index 39122694..d59dedb7 100644 --- a/docs/native-api.md +++ b/docs/native-api.md @@ -9,7 +9,7 @@ description: Generated reference for the capability-oriented Skippy C ABI. This reference is generated from the patched llama.cpp public headers. It documents the native C ABI used by Skippy's Rust FFI layer and staged runtime. The ABI is experimental and versioned for lockstep native/Rust builds. -Current generated surface: **21 headers** and **138 exported functions**. +Current generated surface: **21 headers** and **141 exported functions**. ## Quick navigation @@ -194,7 +194,7 @@ Current generated surface: **21 headers** and **138 exported functions**.
- state.h21 functions + state.h24 functions
skippy_model_memory_cache_capabilities skippy_model_kv_pool_cells @@ -209,11 +209,14 @@ Current generated surface: **21 headers** and **138 exported functions**. skippy_session_verify_rollback_counts skippy_export_kv_page skippy_import_kv_page + skippy_import_kv_page_chunks skippy_import_cachegen_kv_page_v1 skippy_session_save_prefix skippy_session_restore_prefix skippy_session_export_resident_kv_page + skippy_session_export_resident_kv_component skippy_session_export_resident_recurrent_state + skippy_session_copy_resident_recurrent_range skippy_session_resident_prefix_bytes skippy_session_memory_used_cells skippy_session_drop_sequence @@ -1923,6 +1926,20 @@ LLAMA_API enum skippy_status skippy_import_kv_page( struct skippy_error ** out_error); ``` + +#### `skippy_import_kv_page_chunks` + +Imports a single raw KV page from non-empty chunks in wire order. The ranges must remain readable until return and together cover exactly desc->payload_bytes. Unsupported layouts or backends leave the session untouched, so the caller can retry with a contiguous payload. + +```cpp +LLAMA_API enum skippy_status skippy_import_kv_page_chunks( + struct skippy_session * session, + const struct skippy_kv_page_desc * desc, + const struct skippy_kv_page_chunk * chunks, + size_t chunk_count, + struct skippy_error ** out_error); +``` + #### `skippy_import_cachegen_kv_page_v1` @@ -1984,6 +2001,27 @@ LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( struct skippy_error ** out_error); ``` + +#### `skippy_session_export_resident_kv_component` + +Exports an absolute token range from one resident sliding-window page component. The selected range must still be resident in that component. The returned descriptor is a single page, with no component offset. + +```cpp +LLAMA_API enum skippy_status skippy_session_export_resident_kv_component( + struct skippy_session * session, + int32_t cache_seq_id, + enum skippy_kv_page_component_role role, + int32_t layer_start, + int32_t layer_end, + uint64_t token_start, + uint64_t token_count, + struct skippy_kv_page_desc * out_desc, + void * output, + size_t output_capacity, + size_t * out_bytes, + struct skippy_error ** out_error); +``` + #### `skippy_session_export_resident_recurrent_state` @@ -1999,6 +2037,21 @@ LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( struct skippy_error ** out_error); ``` + +#### `skippy_session_copy_resident_recurrent_range` + +Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint. + +```cpp +LLAMA_API enum skippy_status skippy_session_copy_resident_recurrent_range( + struct skippy_session * session, + int32_t cache_seq_id, + size_t offset, + void * output, + size_t bytes, + struct skippy_error ** out_error); +``` + #### `skippy_session_resident_prefix_bytes` @@ -2291,7 +2344,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `activation.h`: `skippy_activation_part_desc`, `skippy_activation_boundary_desc`, `skippy_activation_desc`, `SKIPPY_ACTIVATION_FRAME_VERSION = 2`, `SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION = 2`, `SKIPPY_ACTIVATION_IDENTITY_BYTES = 32`, `SKIPPY_ACTIVATION_MAX_DIMS = 4`, `SKIPPY_ACTIVATION_MAX_PARTS = 16`, `SKIPPY_ACTIVATION_PART_OPTIONAL = (UINT32_C(1) << 0)` - `asr.h`: `skippy_asr_model`, `skippy_asr_result`, `skippy_asr_info_v1`, `skippy_asr_transcribe_params_v1`, `skippy_asr_segment_v1`, `SKIPPY_ASR_INFO_V1_ABI_VERSION = 1`, `SKIPPY_ASR_TRANSCRIBE_PARAMS_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SEGMENT_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SAMPLE_RATE = 16000`, `SKIPPY_ASR_MAX_SAMPLES = (SKIPPY_ASR_SAMPLE_RATE * 60 * 30)` - `clef.h`: `skippy_clef_model`, `skippy_clef_order`, `skippy_clef_info_v1`, `SKIPPY_CLEF_INFO_V1_ABI_VERSION = 1` -- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 94`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` +- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 95`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` - `devices.h`: `skippy_backend_device_type`, `skippy_backend_device_cap`, `skippy_backend_device` - `events.h`: `skippy_runtime_event_v1`, `skippy_runtime_event_reporter_v1`, `SKIPPY_RUNTIME_EVENT_V1_ABI_VERSION = 1` - `execution.h`: `skippy_token_score_request`, `skippy_iteration_request`, `skippy_verify_request` @@ -2303,7 +2356,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `signals.h`: `skippy_token_signal`, `skippy_generation_signal_window` - `speculative_decoding.h`: `skippy_ngram_cache`, `skippy_native_mtp_draft`, `SKIPPY_NATIVE_MTP_MAX_DRAFT_TOKENS = 8` - `stage_plan.h`: `skippy_stage_planner`, `skippy_stage_plan`, `skippy_stage_plan_string_ref_v1`, `skippy_stage_planner_tensor_v1`, `skippy_stage_planner_profile_v1`, `skippy_stage_planner_config_v1`, `skippy_stage_plan_value_kind`, `skippy_stage_plan_state_kind`, `skippy_stage_plan_state_access`, `skippy_stage_plan_state_residency`, `skippy_stage_plan_desc_v1`, `skippy_stage_plan_profile_desc_v1`, `skippy_stage_plan_value_desc_v1`, `skippy_stage_plan_state_desc_v1`, `SKIPPY_STAGE_PLANNER_CONFIG_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_TENSOR_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_PROFILE_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_PROFILE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_VALUE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_STATE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_MAX_DIMS = 4` -- `state.h`: `skippy_memory_cache_capability`, `skippy_kv_page_flag`, `skippy_kv_page_codec`, `skippy_kv_page_component_role`, `skippy_cachegen_record_kind`, `skippy_cachegen_record_v1`, `skippy_kv_page_component_desc`, `skippy_kv_page_desc`, `SKIPPY_CACHEGEN_RECORD_V1_ABI_VERSION = 1` +- `state.h`: `skippy_memory_cache_capability`, `skippy_kv_page_flag`, `skippy_kv_page_codec`, `skippy_kv_page_component_role`, `skippy_cachegen_record_kind`, `skippy_cachegen_record_v1`, `skippy_kv_page_component_desc`, `skippy_kv_page_desc`, `skippy_kv_page_chunk`, `SKIPPY_CACHEGEN_RECORD_V1_ABI_VERSION = 1` - `system_one.h`: `skippy_model`, `skippy_system_one_slot` - `tracing.h`: `skippy_native_span_v1`, `skippy_gpu_command_timing_v1`, `SKIPPY_NATIVE_SPAN_V1_ABI_VERSION = 1`, `SKIPPY_NATIVE_SPAN_ID_BIT = (UINT64_C(1) << 63)`, `SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION = 1` - `workloads.h`: `skippy_model`, `skippy_session`, `skippy_workload_kind`, `skippy_workload_pooling`, `skippy_workload_info_v1`, `SKIPPY_WORKLOAD_INFO_V1_ABI_VERSION = 1` diff --git a/llama_cpp/patches/0074-import-raw-kv-pages-from-borrowed-chunks.patch b/llama_cpp/patches/0074-import-raw-kv-pages-from-borrowed-chunks.patch new file mode 100644 index 00000000..71e9ebd0 --- /dev/null +++ b/llama_cpp/patches/0074-import-raw-kv-pages-from-borrowed-chunks.patch @@ -0,0 +1,341 @@ +From de42cb4d3632d3e287b77d5e48817b1d69bfb6cb Mon Sep 17 00:00:00 2001 +From: Skippy contributors +Date: Mon, 23 Nov 2026 14:44:16 +1100 +Subject: [PATCH] skippy: import raw KV pages from borrowed chunks + +--- + include/skippy/state.h | 18 +++++++ + src/llama-kv-cache.cpp | 83 ++++++++++++++++++++++++++------ + src/llama-kv-cache.h | 11 +++++ + src/skippy/state.cpp | 63 +++++++++++++++++++++--- + src/skippy/tests/async_state.cpp | 24 ++++++++- + 5 files changed, 177 insertions(+), 22 deletions(-) + +diff --git a/include/skippy/state.h b/include/skippy/state.h +index fc5dcd389..8dbf42c99 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -216,6 +216,24 @@ LLAMA_API enum skippy_status skippy_import_kv_page( + size_t input_bytes, + struct skippy_error ** out_error); + ++/** @brief A borrowed range of raw KV page bytes. */ ++struct skippy_kv_page_chunk { ++ const void * data; ++ size_t bytes; ++}; ++ ++/** @brief Imports a single raw KV page from non-empty chunks in wire order. ++ * The ranges must remain readable until return and together cover exactly ++ * desc->payload_bytes. Unsupported layouts or backends leave the session ++ * untouched, so the caller can retry with a contiguous payload. ++ */ ++LLAMA_API enum skippy_status skippy_import_kv_page_chunks( ++ struct skippy_session * session, ++ const struct skippy_kv_page_desc * desc, ++ const struct skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ struct skippy_error ** out_error); ++ + /** @brief Imports validated CacheGen records directly into resident KV storage. */ + LLAMA_API enum skippy_status skippy_import_cachegen_kv_page_v1( + struct skippy_session * session, +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index 7d7901d8e..652457368 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -2183,11 +2183,54 @@ bool llama_kv_cache::stage_import_kv_page( + size_t input_bytes, + std::string & error, + bool validate_only) { +- skippy_trace::scope trace("llama.kv_page_import", "bytes", (int64_t) input_bytes); + if (input == nullptr) { + error = "input payload is required"; + return false; + } ++ const skippy_kv_page_chunk chunk{input, input_bytes}; ++ bool unsupported = false; ++ return stage_import_kv_page_chunks(seq_id, desc, &chunk, 1, input_bytes, error, unsupported, validate_only); ++} ++ ++namespace { ++ ++class kv_page_reader { ++public: ++ explicit kv_page_reader(const skippy_kv_page_chunk * chunks) : chunk(chunks) {} ++ ++ void write(ggml_tensor * tensor, size_t offset, size_t bytes) { ++ while (bytes != 0) { ++ const size_t count = std::min(bytes, chunk->bytes - consumed); ++ const auto * source = static_cast(chunk->data); ++ ggml_backend_tensor_set(tensor, source + consumed, offset, count); ++ consumed += count; ++ if (consumed == chunk->bytes) { ++ ++chunk; ++ consumed = 0; ++ } ++ offset += count; ++ bytes -= count; ++ } ++ } ++ ++private: ++ const skippy_kv_page_chunk * chunk; ++ size_t consumed = 0; ++}; ++ ++} // namespace ++ ++bool llama_kv_cache::stage_import_kv_page_chunks( ++ llama_seq_id seq_id, ++ const skippy_kv_page_desc & desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ size_t input_bytes, ++ std::string & error, ++ bool & unsupported, ++ bool validate_only) { ++ skippy_trace::scope trace("llama.kv_page_import", "bytes", (int64_t) input_bytes); ++ unsupported = false; + if (desc.version != 1) { + error = "unsupported native KV page descriptor version"; + return false; +@@ -2287,6 +2330,21 @@ bool llama_kv_cache::stage_import_kv_page( + return true; + } + ++ // Fragmented writes are cheap on host and shared Metal buffers. A device ++ // buffer could turn every input chunk into a synchronous upload. ++ if (chunk_count > 1 && !std::all_of(selected.begin(), selected.end(), [strm](const kv_layer * layer) { ++ const auto host = [](const std::vector & streams, uint32_t index) { ++ return index >= streams.size() || streams[index] == nullptr || ++ skippy_kv_buffer_pages_are_host(streams[index]->view_src ? ++ streams[index]->view_src->buffer : streams[index]->buffer); ++ }; ++ return host(layer->k_stream, strm) && host(layer->v_stream, strm) && host(layer->k_idx_stream, strm); ++ })) { ++ unsupported = true; ++ error = "chunked KV page import requires host-visible cache buffers"; ++ return false; ++ } ++ + llama_ubatch ubatch = {}; + auto udata = std::make_shared(); + const uint32_t n_tokens = static_cast(desc.token_count); +@@ -2364,13 +2422,12 @@ bool llama_kv_cache::stage_import_kv_page( + apply_ubatch(sinfo, ubatch, overwrites_full_rows); + + const auto cell_runs = llama_kv_cache_cell_runs(sinfo.idxs[0]); +- const char * src = static_cast(input); ++ kv_page_reader reader(chunks); + for (const auto * layer : selected) { + auto * k = layer->k_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.k_row_bytes; +- ggml_backend_tensor_set(k, src, static_cast(run.first) * desc.k_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(k, static_cast(run.first) * desc.k_row_bytes, ++ static_cast(run.count) * desc.k_row_bytes); + } + } + +@@ -2382,9 +2439,8 @@ bool llama_kv_cache::stage_import_kv_page( + } + auto * v = layer->v_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.v_row_bytes; +- ggml_backend_tensor_set(v, src, static_cast(run.first) * desc.v_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(v, static_cast(run.first) * desc.v_row_bytes, ++ static_cast(run.count) * desc.v_row_bytes); + } + } + } else { +@@ -2396,10 +2452,8 @@ bool llama_kv_cache::stage_import_kv_page( + const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(layer->il); + for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.v_element_bytes; + const size_t dst_offset = (static_cast(run.first) + static_cast(j) * cells.size()) * desc.v_element_bytes; +- ggml_backend_tensor_set(v, src, dst_offset, run_bytes); +- src += run_bytes; ++ reader.write(v, dst_offset, static_cast(run.count) * desc.v_element_bytes); + } + } + } +@@ -2410,14 +2464,13 @@ bool llama_kv_cache::stage_import_kv_page( + for (const auto * layer : selected) { + auto * k_idx = layer->k_idx_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.k_idx_row_bytes; +- ggml_backend_tensor_set(k_idx, src, static_cast(run.first) * desc.k_idx_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(k_idx, static_cast(run.first) * desc.k_idx_row_bytes, ++ static_cast(run.count) * desc.k_idx_row_bytes); + } + } + } + +- return src == static_cast(input) + input_bytes; ++ return true; + } + + static uint16_t skippy_cachegen_read_u16(const uint8_t * bytes) { +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index f77e14586..a886ac793 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -15,6 +15,7 @@ struct llama_hparams; + struct llama_model; + struct llama_context; + struct skippy_kv_page_desc; ++struct skippy_kv_page_chunk; + struct skippy_cachegen_record_v1; + + // +@@ -220,6 +221,16 @@ public: + std::string & error, + bool validate_only = false); + ++ bool stage_import_kv_page_chunks( ++ llama_seq_id seq_id, ++ const skippy_kv_page_desc & desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ size_t input_bytes, ++ std::string & error, ++ bool & unsupported, ++ bool validate_only = false); ++ + bool stage_import_cachegen_kv_page( + llama_seq_id seq_id, + const skippy_kv_page_desc & desc, +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +index bab58a50f..bc842ee9e 100644 +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -479,6 +479,18 @@ static bool skippy_validate_composite_desc(const skippy_kv_page_desc & desc, siz + return true; + } + ++static skippy_status skippy_finish_kv_page_import( ++ skippy_session * session, const skippy_kv_page_desc & desc, skippy_error ** out_error) { ++ if (llm_graph_result * graph = session->ctx->get_gf_res_prev_active()) { ++ graph->reset(); ++ } ++ session->n_past = std::max(session->n_past, static_cast(std::min(desc.token_start + desc.token_count, std::numeric_limits::max()))); ++ skippy_mtp_clear_session_state(session); ++ skippy_clear_verify_windows(session); ++ session->ctx->synchronize(); ++ return skippy_success(out_error); ++} ++ + enum skippy_status skippy_import_kv_page( + struct skippy_session * session, + const struct skippy_kv_page_desc * desc, +@@ -530,14 +542,53 @@ enum skippy_status skippy_import_kv_page( + skippy_set_error(out_error, status, error.c_str()); + return status; + } +- if (llm_graph_result * graph = session->ctx->get_gf_res_prev_active()) { +- graph->reset(); ++ return skippy_finish_kv_page_import(session, *desc, out_error); ++} ++ ++enum skippy_status skippy_import_kv_page_chunks( ++ skippy_session * session, ++ const skippy_kv_page_desc * desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ skippy_error ** out_error) { ++ if (session == nullptr || session->ctx == nullptr || desc == nullptr || chunks == nullptr || chunk_count == 0 || ++ chunk_count > desc->payload_bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session, descriptor, and KV chunks are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ size_t bytes = 0; ++ for (size_t i = 0; i < chunk_count; ++i) { ++ if (chunks[i].data == nullptr || chunks[i].bytes == 0 || ++ chunks[i].bytes > std::numeric_limits::max() - bytes || ++ chunks[i].bytes > desc->payload_bytes - bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "invalid KV page chunk"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ bytes += chunks[i].bytes; ++ } ++ if (bytes != desc->payload_bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "KV chunks do not cover the page"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (desc->codec != 0 && desc->codec != SKIPPY_KV_PAGE_CODEC_SINGLE_V1) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "chunked KV import requires a single raw page"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ auto * kv = skippy_get_kv_cache(session, nullptr); ++ if (kv == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "runtime memory does not support single raw KV pages"); ++ return SKIPPY_STATUS_UNSUPPORTED; + } +- session->n_past = std::max(session->n_past, static_cast(std::min(desc->token_start + desc->token_count, std::numeric_limits::max()))); +- skippy_mtp_clear_session_state(session); +- skippy_clear_verify_windows(session); + session->ctx->synchronize(); +- return skippy_success(out_error); ++ skippy_mark_context_synchronized(session->stage_model); ++ std::string error; ++ bool unsupported = false; ++ if (!kv->stage_import_kv_page_chunks(session->seq_id, *desc, chunks, chunk_count, bytes, error, unsupported)) { ++ const auto status = unsupported ? SKIPPY_STATUS_UNSUPPORTED : SKIPPY_STATUS_RUNTIME_ERROR; ++ skippy_set_error(out_error, status, error.c_str()); ++ return status; ++ } ++ return skippy_finish_kv_page_import(session, *desc, out_error); + } + + enum skippy_status skippy_import_cachegen_kv_page_v1(struct skippy_session * session, +diff --git a/src/skippy/tests/async_state.cpp b/src/skippy/tests/async_state.cpp +index efe8d28ba..ba1de093b 100644 +--- a/src/skippy/tests/async_state.cpp ++++ b/src/skippy/tests/async_state.cpp +@@ -71,6 +71,13 @@ void test_plain_restore_parity(skippy_session * source, skippy_session * target) + CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, payload.data(), payload.size(), &bytes, &error) == + SKIPPY_STATUS_OK); + ++ std::vector chunks; ++ for (size_t offset = 0; offset < payload.size();) { ++ const size_t count = std::min(17, payload.size() - offset); ++ chunks.push_back({payload.data() + offset, count}); ++ offset += count; ++ } ++ CHECK(chunks.size() > 1); + 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); +@@ -86,8 +93,23 @@ void test_plain_restore_parity(skippy_session * source, skippy_session * target) + 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); ++ if (attempt % 2 == 0) { ++ CHECK(skippy_import_kv_page(target, &page, payload.data(), payload.size(), &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_import_kv_page_chunks(target, &page, chunks.data(), chunks.size() - 1, &error) == ++ SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ error = nullptr; ++ CHECK(target->n_past == 2); ++ } else { ++ CHECK(skippy_import_kv_page_chunks(target, &page, chunks.data(), chunks.size(), &error) == SKIPPY_STATUS_OK); ++ } + CHECK(!source->stage_model->context_work_pending.load()); ++ std::vector restored(bytes); ++ size_t restored_bytes = 0; ++ skippy_kv_page_desc restored_page{}; ++ CHECK(skippy_export_kv_page(target, 0, layers, 0, 2, ++ &restored_page, restored.data(), restored.size(), &restored_bytes, &error) == SKIPPY_STATUS_OK); ++ CHECK(restored_bytes == bytes && restored == payload); + std::vector scores(selected); + skippy_token_score_request readout{ ids.data(), ids.size(), scores.data() }; + const llama_token token = 2; +-- +2.56.0 + diff --git a/llama_cpp/patches/0075-batch-native-kv-page-reads.patch b/llama_cpp/patches/0075-batch-native-kv-page-reads.patch new file mode 100644 index 00000000..558fe87c --- /dev/null +++ b/llama_cpp/patches/0075-batch-native-kv-page-reads.patch @@ -0,0 +1,101 @@ +From: Skippy contributors +Subject: [PATCH] skippy: batch native KV page reads + +Skip backend fences for descriptor-only queries. Preserve the existing page +layout while batching device reads for bounded groups of spans. + +--- +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -2123,13 +2123,36 @@ + } + + const auto cell_runs = llama_kv_cache_cell_runs(cell_idxs); +- char * dst = static_cast(output); ++ // Each span writes directly into its original place in the K, V, index ++ // layout. Submit bounded batches so CUDA can share a transfer fence. ++ constexpr size_t batch_capacity = 256; ++ std::array tensors; ++ std::array offsets; ++ std::array sizes; ++ std::array data_offsets; ++ size_t batch_size = 0; ++ size_t output_offset = 0; ++ const auto flush = [&]() { ++ if (batch_size != 0) { ++ ggml_backend_tensor_get_n(tensors.data(), output, offsets.data(), sizes.data(), data_offsets.data(), batch_size); ++ batch_size = 0; ++ } ++ }; ++ const auto read = [&](const ggml_tensor * tensor, size_t offset, size_t bytes) { ++ tensors[batch_size] = tensor; ++ offsets[batch_size] = offset; ++ sizes[batch_size] = bytes; ++ data_offsets[batch_size] = output_offset; ++ output_offset += bytes; ++ if (++batch_size == batch_capacity) { ++ flush(); ++ } ++ }; + for (const auto * layer : selected) { + auto * k = layer->k_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * k_row_bytes; +- ggml_backend_tensor_get(k, dst, static_cast(run.first) * k_row_bytes, run_bytes); +- dst += run_bytes; ++ read(k, static_cast(run.first) * k_row_bytes, run_bytes); + } + } + +@@ -2141,8 +2164,7 @@ + auto * v = layer->v_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * v_row_bytes; +- ggml_backend_tensor_get(v, dst, static_cast(run.first) * v_row_bytes, run_bytes); +- dst += run_bytes; ++ read(v, static_cast(run.first) * v_row_bytes, run_bytes); + } + } + } else { +@@ -2156,8 +2178,7 @@ + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * v_element_bytes; + const size_t src_offset = (static_cast(run.first) + static_cast(j) * cells.size()) * v_element_bytes; +- ggml_backend_tensor_get(v, dst, src_offset, run_bytes); +- dst += run_bytes; ++ read(v, src_offset, run_bytes); + } + } + } +@@ -2171,10 +2192,10 @@ + auto * k_idx = layer->k_idx_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * k_idx_row_bytes; +- ggml_backend_tensor_get(k_idx, dst, static_cast(run.first) * k_idx_row_bytes, run_bytes); +- dst += run_bytes; +- } +- } ++ read(k_idx, static_cast(run.first) * k_idx_row_bytes, run_bytes); ++ } ++ } ++ flush(); + + return true; + } +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -435,7 +435,11 @@ + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } +- session->ctx->synchronize(); ++ // A size query reads cell ownership and tensor layout maintained by the ++ // host. Only a payload export needs completed device writes. ++ if (output != nullptr) { ++ session->ctx->synchronize(); ++ } + std::string error; + bool ok = false; + if (auto * iswa = skippy_get_iswa_cache(session)) { diff --git a/llama_cpp/patches/0076-export-resident-kv-in-bounded-slices.patch b/llama_cpp/patches/0076-export-resident-kv-in-bounded-slices.patch new file mode 100644 index 00000000..b9ae66bb --- /dev/null +++ b/llama_cpp/patches/0076-export-resident-kv-in-bounded-slices.patch @@ -0,0 +1,222 @@ +From: Skippy contributors +Subject: [PATCH] skippy: export resident KV in bounded slices + +Expose independent sliding-window components and recurrent byte ranges to +allow eviction and generation between checkpoint copy steps. + +--- +diff --git a/include/skippy/state.h b/include/skippy/state.h +index 489d72a4c..be7323fb3 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -277,6 +277,24 @@ LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( + size_t * out_bytes, + struct skippy_error ** out_error); + ++/** @brief Exports an absolute token range from one resident sliding-window page component. ++ * The selected range must still be resident in that component. ++ * The returned descriptor is a single page, with no component offset. ++ */ ++LLAMA_API enum skippy_status skippy_session_export_resident_kv_component( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ enum skippy_kv_page_component_role role, ++ int32_t layer_start, ++ int32_t layer_end, ++ uint64_t token_start, ++ uint64_t token_count, ++ struct skippy_kv_page_desc * out_desc, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error); ++ + /** @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors. */ + LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( + struct skippy_session * session, +@@ -286,6 +304,15 @@ LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( + size_t * out_bytes, + struct skippy_error ** out_error); + ++/** @brief Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint. */ ++LLAMA_API enum skippy_status skippy_session_copy_resident_recurrent_range( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ size_t offset, ++ void * output, ++ size_t bytes, ++ struct skippy_error ** out_error); ++ + /** @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool. */ + LLAMA_API enum skippy_status skippy_session_resident_prefix_bytes( + struct skippy_session * session, +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +index ebe660b64..e140f53e3 100644 +--- a/src/skippy/resident_prefix.cpp ++++ b/src/skippy/resident_prefix.cpp +@@ -19,6 +19,7 @@ + #include + #include + #include ++#include + #include + + namespace { +@@ -434,10 +435,72 @@ enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session + } catch (const std::exception & exception) { return native_error(error, exception); } + } + +-enum skippy_status skippy_session_export_resident_kv_page(skippy_session * session, +- int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, ++enum skippy_status skippy_session_copy_resident_recurrent_range(skippy_session * session, ++ int32_t cache_seq_id, size_t offset, void * output, size_t bytes, skippy_error ** error) { ++ if (!output || bytes == 0) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent destination range is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto & prefixes = session->stage_model->resident_prefixes; ++ const auto found = prefixes.find(cache_seq_id); ++ if (found == prefixes.end() || offset > found->second.recurrent.size() ++ || bytes > found->second.recurrent.size() - offset) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent copy exceeds the saved prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ std::memcpy(output, found->second.recurrent.data() + offset, bytes); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++} // extern "C" ++ ++namespace { ++ ++skippy_status export_resident_kv_component(skippy_session * session, int32_t cache_seq_id, ++ skippy_kv_page_component_role role, int32_t layer_start, int32_t layer_end, + uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, + void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (!descriptor || !bytes || ++ (role != SKIPPY_KV_PAGE_COMPONENT_BASE && role != SKIPPY_KV_PAGE_COMPONENT_SWA)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "valid component and descriptor outputs are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * iswa = skippy_memory_iswa_adapter(session->ctx->get_memory()); ++ if (!iswa) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "runtime memory has no composite KV page"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ auto * kv = role == SKIPPY_KV_PAGE_COMPONENT_BASE ? iswa->get_base() : iswa->get_swa(); ++ if (output) { ++ session->ctx->synchronize(); ++ } ++ *descriptor = {}; ++ std::string message; ++ const bool exported = kv->stage_export_kv_page(cache_seq_id, layer_start, layer_end, token_start, ++ token_count, descriptor, output, capacity, bytes, message); ++ descriptor->codec = SKIPPY_KV_PAGE_CODEC_SINGLE_V1; ++ if (!exported) { ++ const auto status = *bytes > capacity ? SKIPPY_STATUS_BUFFER_TOO_SMALL : SKIPPY_STATUS_RUNTIME_ERROR; ++ skippy_set_error(error, status, message.c_str()); ++ return status; ++ } ++ if (!output) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "KV component output buffer is required"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ return skippy_success(error); ++} ++ ++skippy_status export_resident_kv_page(skippy_session * session, ++ int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, ++ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, ++ void * output, size_t capacity, size_t * bytes, skippy_error ** error, ++ std::optional role) { + if (bytes) { *bytes = 0; } + const auto valid = validate_session(session, cache_seq_id, error); + if (valid != SKIPPY_STATUS_OK) { return valid; } +@@ -450,6 +513,10 @@ enum skippy_status skippy_session_export_resident_kv_page(skippy_session * sessi + skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident KV export exceeds the saved prefix"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } ++ if (role) { ++ return export_resident_kv_component(session, cache_seq_id, *role, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error); ++ } + // This stack view neither claims an execution lane nor changes its + // state. Only the explicitly requested cold payload is materialized. + skippy_session view{}; +@@ -462,4 +529,24 @@ enum skippy_status skippy_session_export_resident_kv_page(skippy_session * sessi + } catch (const std::exception & exception) { return native_error(error, exception); } + } + ++} // namespace ++ ++extern "C" { ++ ++enum skippy_status skippy_session_export_resident_kv_page(skippy_session * session, ++ int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, ++ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, ++ void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ return export_resident_kv_page(session, cache_seq_id, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error, std::nullopt); ++} ++ ++enum skippy_status skippy_session_export_resident_kv_component(skippy_session * session, ++ int32_t cache_seq_id, skippy_kv_page_component_role role, int32_t layer_start, int32_t layer_end, ++ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, ++ void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ return export_resident_kv_page(session, cache_seq_id, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error, role); ++} ++ + } // extern "C" +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index fea240bea..8764d65f8 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -826,6 +826,21 @@ void resident_prefix_ownership(skippy_model * model, bool typed = false) { + 0, prefix.size(), &persistent.page, persistent.payload.data(), kv_bytes, + &kv_bytes, &error), error); + CHECK(persistent.payload == source_page); ++ if (persistent.page.codec == SKIPPY_KV_PAGE_CODEC_ISWA_COMPOSITE_V1) { ++ for (const auto & component : persistent.page.components) { ++ skippy_kv_page_desc slice{}; ++ std::vector payload(component.payload_bytes); ++ size_t bytes = 0; ++ error = nullptr; ++ ok(skippy_session_export_resident_kv_component(a, cache_id, ++ static_cast(component.role), 0, persistent.layers, ++ component.token_start, component.token_count, &slice, payload.data(), payload.size(), ++ &bytes, &error), error); ++ CHECK(bytes == payload.size()); ++ CHECK(slice.codec == SKIPPY_KV_PAGE_CODEC_SINGLE_V1 && slice.component_count == 0); ++ CHECK(std::equal(payload.begin(), payload.end(), source_page.begin() + component.payload_offset)); ++ } ++ } + size_t recurrent_bytes = 0; + error = nullptr; + const auto recurrent_status = skippy_session_export_resident_recurrent_state(a, +@@ -839,6 +854,20 @@ void resident_prefix_ownership(skippy_model * model, bool typed = false) { + ok(skippy_session_export_resident_recurrent_state(a, cache_id, + retained_recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); + CHECK(retained_recurrent == persistent.recurrent); ++ const size_t split = recurrent_bytes / 3; ++ CHECK(split > 0); ++ std::vector sliced_recurrent(recurrent_bytes); ++ error = nullptr; ++ ok(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ 0, sliced_recurrent.data(), split, &error), error); ++ error = nullptr; ++ ok(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ split, sliced_recurrent.data() + split, recurrent_bytes - split, &error), error); ++ CHECK(sliced_recurrent == retained_recurrent); ++ error = nullptr; ++ CHECK(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ recurrent_bytes, sliced_recurrent.data(), 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); + } + CHECK(a->token_history == history_a && b->token_history == history_b); + CHECK(a->n_past == static_cast(prefix.size()) && b->n_past == a->n_past); diff --git a/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch b/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch new file mode 100644 index 00000000..e9511a92 --- /dev/null +++ b/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch @@ -0,0 +1,17 @@ +From: Skippy contributors +Subject: [PATCH] skippy: bump native ABI for resident cache slice exports + +--- +diff --git a/include/skippy/common.h b/include/skippy/common.h +index 465c7bf45..f3887a80e 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -46,7 +46,7 @@ extern "C" { + + #define SKIPPY_ABI_VERSION_MAJOR 0 + #define SKIPPY_ABI_VERSION_MINOR 1 +-#define SKIPPY_ABI_VERSION_PATCH 94 ++#define SKIPPY_ABI_VERSION_PATCH 95 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/llama_cpp/patches/model_support/series b/llama_cpp/patches/model_support/series index 7020e5ce..a2d89dff 100644 --- a/llama_cpp/patches/model_support/series +++ b/llama_cpp/patches/model_support/series @@ -24,3 +24,4 @@ 0024-models-preserve-checkpoint-layouts-and-head-scales.patch 0025-abi-distinguish-b12780-upstream-c-layouts.patch 0026-skippy-bump-abi-for-merged-runtime.patch +0027-skippy-bump-abi-for-resident-cache-slices.patch