Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/skippy-api/src/execution/split/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ impl SplitOptions {
ctx_size: options.ctx_size,
lane_count: options.generation_concurrency as u32,
selected_device: options.selected_device.clone(),
max_request_tier: None,
package_ref: identity.package_ref.clone(),
manifest_sha256: identity.manifest_sha256.clone(),
model_path: Some(identity.source_model_path.to_string_lossy().into_owned()),
Expand Down Expand Up @@ -170,6 +171,7 @@ impl SplitOptions {
upstream: (index == 1).then(|| peer(0)),
downstream: (index == 0).then(|| peer(1)),
admission,
max_request_tier: None,
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions crates/skippy-api/src/serving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pub struct InferenceOptions {
pub pipeline_decode_groups: Option<usize>,
pub adaptive_generation_min_concurrency: Option<usize>,
pub generation_queue_capacity: usize,
/// Percent of the KV token budget only `local`-tier requests may reserve.
pub local_kv_reserve_percent: u8,
pub generation_admission_timeout_secs: u64,
pub prefill_chunk_size: usize,
pub prefill_chunk_policy: String,
Expand Down Expand Up @@ -88,6 +90,7 @@ impl InferenceOptions {
generation_queue_capacity: skippy_serving::frontend::default_generation_queue_capacity(
generation_concurrency,
),
local_kv_reserve_percent: 0,
generation_admission_timeout_secs: DEFAULT_GENERATION_ADMISSION_TIMEOUT_SECS,
prefill_chunk_size: BUILTIN_PREFILL_CHUNK_SIZE,
prefill_chunk_policy: skippy_config::local_serving::PREFILL_CHUNK_POLICY.to_string(),
Expand Down Expand Up @@ -148,6 +151,7 @@ impl InferenceOptions {
pipeline_decode_groups: self.pipeline_decode_groups,
adaptive_generation_min_concurrency: self.adaptive_generation_min_concurrency,
generation_queue_capacity: self.generation_queue_capacity,
local_kv_reserve_percent: self.local_kv_reserve_percent,
generation_admission_timeout_secs: self.generation_admission_timeout_secs,
prefill_chunk_size: self.prefill_chunk_size,
prefill_chunk_policy: self.prefill_chunk_policy,
Expand Down
1 change: 1 addition & 0 deletions crates/skippy-api/src/split_execution/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ fn realize_configs(
upstream: index.checked_sub(1).map(peer),
downstream: (index + 1 < topology.stages.len()).then(|| peer(index + 1)),
admission: admission.clone(),
max_request_tier: None,
};
configs.push(stage_load::admitted_stage_config(&load, None, names)?);
}
Expand Down
1 change: 1 addition & 0 deletions crates/skippy-api/src/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ pub fn single_stage_config(
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
max_request_tier: None,
};
config.kv_cache = options
.kv_cache
Expand Down
4 changes: 4 additions & 0 deletions crates/skippy-api/src/stage_load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ pub struct AdmittedStageOptions {
pub upstream: Option<PeerConfig>,
pub downstream: Option<PeerConfig>,
pub admission: skippy_protocol::StageAdmissionDescriptor,
/// Highest request tier this stage serves; see
/// [`StageConfig::max_request_tier`]. `None` serves the stamped tier.
pub max_request_tier: Option<String>,
}

impl AdmittedStageOptions {
Expand Down Expand Up @@ -199,6 +202,7 @@ pub fn admitted_stage_config(
bind_addr: load.bind_addr.clone(),
upstream: load.upstream.clone(),
downstream: load.downstream.clone(),
max_request_tier: load.max_request_tier.clone(),
};
let family_policy = crate::family_policy::family_policy_for_stage_config(&config);
config.kv_cache = package.map_or_else(
Expand Down
6 changes: 6 additions & 0 deletions crates/skippy-cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ used to discover shared resident prefixes. Attention admission uses physical
native occupancy rather than summing overlapping logical prefix lengths.
Recurrent checkpoint RAM is bounded separately and works with disk disabled.

Serving puts the request tier and private partition in the cache namespace
(see `skippy-inference-api`'s request tiers), so a prefix one tier or partition
computed never matches another's. Recurrent entries are evicted by the
retention their owner gives them (`evict_recurrent_by_retention`), least
recently used first among equals; serving uses the storing request's tier.

This adopts SGLang's separation of radix-owned attention blocks and recurrent
checkpoints through llama.cpp's native memory interfaces. It does not embed
SGLang's Torch runtime. See [the prompt-cache design](../../docs/PROMPT_CACHE.md)
Expand Down
2 changes: 2 additions & 0 deletions crates/skippy-cache/src/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,7 @@ mod identity_completeness_tests {
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
max_request_tier: None,
}
}

Expand Down Expand Up @@ -1047,6 +1048,7 @@ mod identity_stability_tests {
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
max_request_tier: None,
}
}

Expand Down
194 changes: 174 additions & 20 deletions crates/skippy-cache/src/radix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,47 @@ impl<R, E> UnifiedRadixCache<R, E> {
}

pub fn evict_lru_recurrent(&mut self) -> Option<RadixEviction<E>> {
let victim = self.lru_victim(ComponentKind::KvRecurrent)?;
self.evict_recurrent_by_retention(|_| 0)
}

/// The retention of the entry [`Self::evict_recurrent_by_retention`]
/// would evict next, if any is evictable.
pub fn recurrent_victim_retention(&self, retention: impl Fn(&E) -> u64) -> Option<u64> {
self.ranked_victim(&|node| {
node.components
.recurrent
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| {
(
retention(&entry.value),
entry.last_used,
entry.logical_bytes,
)
})
})
.map(|victim| victim.retention)
}

/// Evict the unreferenced recurrent entry with the lowest `retention`,
/// least recently used first among equals.
pub fn evict_recurrent_by_retention(
&mut self,
retention: impl Fn(&E) -> u64,
) -> Option<RadixEviction<E>> {
let victim = self.ranked_victim(&|node| {
node.components
.recurrent
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| {
(
retention(&entry.value),
entry.last_used,
entry.logical_bytes,
)
})
})?;
let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?;
self.recurrent_evictions = self.recurrent_evictions.saturating_add(1);
Some(RadixEviction {
Expand All @@ -365,6 +405,35 @@ impl<R, E> UnifiedRadixCache<R, E> {
})
}

/// Evict the least-recently-used unreferenced recurrent entry that is a
/// strict prefix of another recurrent entry in its namespace. A longer
/// entry already continues that conversation, so the shorter one is the
/// cheapest snapshot to lose.
pub fn evict_lru_superseded_recurrent(&mut self) -> Option<RadixEviction<E>> {
let mut victim = None;
for (namespace, root) in &self.roots {
collect_lru_superseded_recurrent(namespace, root, &mut Vec::new(), &mut victim);
}
let victim = victim?;
let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?;
self.recurrent_evictions = self.recurrent_evictions.saturating_add(1);
Some(RadixEviction {
namespace: victim.namespace,
tokens: victim.tokens,
logical_bytes: victim.logical_bytes,
value,
})
}

/// Recurrent entries with no longer recurrent entry below them: the latest
/// continuation of each distinct conversation.
pub fn recurrent_leaf_entries(&self) -> usize {
self.roots
.values()
.map(|root| count_recurrent_leaves(root).0)
.sum()
}

pub fn stats(&self) -> UnifiedRadixCacheStats {
let mut stats = UnifiedRadixCacheStats {
namespaces: self.roots.len(),
Expand All @@ -391,9 +460,29 @@ impl<R, E> UnifiedRadixCache<R, E> {
}

fn lru_victim(&self, component: ComponentKind) -> Option<Victim> {
self.ranked_victim(&|node| match component {
ComponentKind::ResidentKv => node
.components
.resident
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| (0, entry.last_used, entry.logical_bytes)),
ComponentKind::KvRecurrent => node
.components
.recurrent
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| (0, entry.last_used, entry.logical_bytes)),
})
}

/// The evictable node with the lowest `(retention, last_used)`, where
/// `candidate` yields `(retention, last_used, logical_bytes)` for nodes
/// holding an evictable entry.
fn ranked_victim(&self, candidate: &VictimCandidate<'_, R, E>) -> Option<Victim> {
let mut victim = None;
for (namespace, root) in &self.roots {
collect_lru_victim(namespace, root, component, &mut Vec::new(), &mut victim);
collect_lru_victim(namespace, root, candidate, &mut Vec::new(), &mut victim);
}
victim
}
Expand Down Expand Up @@ -636,6 +725,7 @@ struct Victim {
tokens: Vec<i32>,
logical_bytes: u64,
last_used: u64,
retention: u64,
}

fn validate_tokens(tokens: &[i32]) -> Result<()> {
Expand Down Expand Up @@ -832,35 +922,24 @@ fn find_recurrent_path<R, E>(
None
}

type VictimCandidate<'a, R, E> = dyn Fn(&RadixNode<R, E>) -> Option<(u64, u64, u64)> + 'a;

fn collect_lru_victim<R, E>(
namespace: &str,
node: &RadixNode<R, E>,
component: ComponentKind,
candidate: &VictimCandidate<'_, R, E>,
path: &mut Vec<i32>,
victim: &mut Option<Victim>,
) {
let original_len = path.len();
path.extend_from_slice(&node.edge);
let candidate = match component {
ComponentKind::ResidentKv => node
.components
.resident
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| (entry.last_used, entry.logical_bytes)),
ComponentKind::KvRecurrent => node
.components
.recurrent
.as_ref()
.filter(|entry| entry.active_refs == 0)
.map(|entry| (entry.last_used, entry.logical_bytes)),
};
if let Some((last_used, logical_bytes)) = candidate {
if let Some((retention, last_used, logical_bytes)) = candidate(node) {
let replace = victim
.as_ref()
.map(|current| {
(last_used, namespace, path.as_slice())
(retention, last_used, namespace, path.as_slice())
< (
current.retention,
current.last_used,
current.namespace.as_str(),
current.tokens.as_slice(),
Expand All @@ -873,15 +952,69 @@ fn collect_lru_victim<R, E>(
tokens: path.clone(),
logical_bytes,
last_used,
retention,
});
}
}
for child in node.children.values() {
collect_lru_victim(namespace, child, component, path, victim);
collect_lru_victim(namespace, child, candidate, path, victim);
}
path.truncate(original_len);
}

/// Returns (leaf recurrent entries, whether the subtree holds any recurrent entry).
fn count_recurrent_leaves<R, E>(node: &RadixNode<R, E>) -> (usize, bool) {
let mut leaves = 0;
let mut below = false;
for child in node.children.values() {
let (child_leaves, child_any) = count_recurrent_leaves(child);
leaves += child_leaves;
below |= child_any;
}
let here = node.components.recurrent.is_some();
if here && !below {
leaves += 1;
}
(leaves, here || below)
}

/// Returns whether the subtree holds any recurrent entry.
fn collect_lru_superseded_recurrent<R, E>(
namespace: &str,
node: &RadixNode<R, E>,
path: &mut Vec<i32>,
victim: &mut Option<Victim>,
) -> bool {
let original_len = path.len();
path.extend_from_slice(&node.edge);
let mut below = false;
for child in node.children.values() {
below |= collect_lru_superseded_recurrent(namespace, child, path, victim);
}
let entry = node.components.recurrent.as_ref();
if below && let Some(entry) = entry.filter(|entry| entry.active_refs == 0) {
let replace = victim.as_ref().is_none_or(|current| {
(entry.last_used, namespace, path.as_slice())
< (
current.last_used,
current.namespace.as_str(),
current.tokens.as_slice(),
)
});
if replace {
*victim = Some(Victim {
namespace: namespace.to_string(),
tokens: path.clone(),
logical_bytes: entry.logical_bytes,
last_used: entry.last_used,
retention: 0,
});
}
}
path.truncate(original_len);
below || entry.is_some()
}

fn collect_resident_eviction_candidates<R: Clone, E>(
namespace: &str,
node: &RadixNode<R, E>,
Expand Down Expand Up @@ -1319,6 +1452,27 @@ mod tests {
assert!(cache.release_resident("stage", &[1]));
}

#[test]
fn superseded_recurrent_eviction_keeps_each_conversations_latest_entry() {
let mut cache = UnifiedRadixCache::<(), &str>::new();
cache
.insert_recurrent("stage", &[1, 2], 1, "a-prefill")
.unwrap();
cache
.insert_recurrent("stage", &[7, 8], 1, "b-prefill")
.unwrap();
cache
.insert_recurrent("stage", &[1, 2, 3, 4], 1, "a-decode")
.unwrap();
assert_eq!(cache.recurrent_leaf_entries(), 2);
assert_eq!(
cache.evict_lru_superseded_recurrent().unwrap().value,
"a-prefill"
);
assert!(cache.evict_lru_superseded_recurrent().is_none());
assert_eq!(cache.recurrent_leaf_entries(), 2);
}

#[test]
fn component_eviction_preserves_other_payload_at_same_prefix() {
let mut cache = UnifiedRadixCache::new();
Expand Down
17 changes: 17 additions & 0 deletions crates/skippy-inference-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,23 @@ perform exact string matching on requests. Resolution to a concrete Hugging Face
revision, GGUF file, split-shard distribution, local runtime, or staged binary
chain remains backend-owned.

## Request Tiers

Every request carries an `InferenceRequestClass` with a tier (`local`,
`trusted` or `mesh`, highest first) and a private cache partition flag.
The public standalone router uses the default local class. An embedding
host behind a trusted upstream can enable
`InferenceFrontendConfig::with_trusted_request_class_headers` to read
`x-skippy-request-tier` and `x-skippy-cache-partition`. The upstream must
strip client-supplied values and stamp its own classification. The router
sets the class on `InferenceRequestContext`. Embedding hosts that call a
backend directly set it on the context. A backend reads the class from the context and stamps it on the
`GenerationRequest` (`request_class`) for its hooks; request bodies never set
it. `InferenceRequestClass::cache_namespace` turns the class into the cache
namespace prefix (`tier:<partition>:`) that keeps each tier's, and each side
of the private line's, cached prefixes apart; a `local`, non-private request
keeps the plain namespace.

## Backend Responsibility Matrix

| Area | Frontend responsibility | Backend responsibility | Status |
Expand Down
Loading
Loading