Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
42 changes: 29 additions & 13 deletions core/continuum-core/src/cognition/serving_plan/footprint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub fn footprint_for(model: &Model) -> Option<ModelFootprint> {
);
if header_rate.is_some() {
if let Some(record) = &measured {
fp.fixed_per_lane_bytes = fixed_per_lane_from(fp.kv_per_token, record);
fp.fixed_per_lane_bytes = fixed_per_lane_from(fp.kv_per_token, record)?;
// One row when the value CHANGES: this runs on every footprint read (measured
// 2026-09-19 23:2xZ on the M5: 840 identical rows in 12 minutes, 70/min — the
// ledger-rotation class, the same shape the knee clamp's row had).
Expand All @@ -100,13 +100,19 @@ pub fn footprint_for(model: &Model) -> Option<ModelFootprint> {
}

/// The residency a sample measured BEYOND the header's per-token rate, as fixed bytes per
/// lane: `(measured − rate) × the window it was measured at`. Zero when the sample agrees
/// with the header. The rate stays physics; the residency stays counted.
pub fn fixed_per_lane_from(header_rate: u64, record: &crate::inference::lane_footprint::MeasuredCost) -> u64 {
record
.per_token_bytes
.saturating_sub(header_rate)
.saturating_mul(record.window as u64)
/// lane: excess per physical token × allocated tokens / lanes. Historical records without
/// allocation retain their divided-cache window semantics. Invalid geometry is not a footprint.
pub fn fixed_per_lane_from(header_rate: u64, record: &crate::inference::lane_footprint::MeasuredCost) -> Option<u64> {
if record.lanes == 0 || record.window == 0 {
return None;
}
let tokens = match record.allocated_tokens {
Some(0) => return None,
Some(tokens) => u128::from(tokens),
None => u128::from(record.lanes) * u128::from(record.window),
};
let excess = u128::from(record.per_token_bytes.saturating_sub(header_rate));
u64::try_from(excess * tokens / u128::from(record.lanes)).ok()
}

/// THE PROCESS BEATS THE ARITHMETIC. When the live lane's anonymous footprint, read
Expand Down Expand Up @@ -284,8 +290,8 @@ mod tests {
for _ in 0..4 {
let per_token = crate::inference::lane_footprint::per_token_from(anon, lanes, window, fp.base_compute_buffer_per_lane(), 0)
.expect("test: a reading");
let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: per_token, lanes, window, anon_bytes: anon, last_ms: 0 };
fp.fixed_per_lane_bytes = fixed_per_lane_from(header_rate, &record);
let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: per_token, lanes, window, allocated_tokens: None, anon_bytes: anon, last_ms: 0 };
fp.fixed_per_lane_bytes = fixed_per_lane_from(header_rate, &record).expect("valid fixture geometry");
seen.push(fp.fixed_per_lane_bytes);
}
let tolerance = u64::from(window); // integer division loses under one byte per token
Expand All @@ -310,10 +316,20 @@ mod tests {
// sample of 55,925 at 67,340) yields ≈1.56 GB of fixed residency per lane, and
// across budgets the plan with it fits no more lanes than the header-only plan
// and no fewer than the raised-rate plan — strictly between them somewhere.
let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: 55_925, lanes: 1, window: 67_340, anon_bytes: 0, last_ms: 0 };
let fixed = fixed_per_lane_from(32_768, &record);
let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: 55_925, lanes: 1, window: 67_340, allocated_tokens: None, anon_bytes: 0, last_ms: 0 };
let fixed = fixed_per_lane_from(32_768, &record).expect("valid fixture geometry");
assert!((1_500_000_000..1_620_000_000).contains(&fixed), "{fixed} B per lane");
assert_eq!(fixed_per_lane_from(65_536, &record), 0, "a sample under the rate carries nothing");
assert_eq!(fixed_per_lane_from(65_536, &record), Some(0), "a sample under the rate carries nothing");
let mut unified = record.clone();
unified.per_token_bytes = 200;
unified.lanes = 2;
unified.window = 32_768;
unified.allocated_tokens = Some(32_768);
assert_eq!(fixed_per_lane_from(100, &unified), Some(1_638_400));
unified.allocated_tokens = None;
assert_eq!(fixed_per_lane_from(100, &unified), Some(3_276_800), "legacy divided allocation");
unified.lanes = 0;
assert_eq!(fixed_per_lane_from(100, &unified), None);
let base = ModelFootprint {
model_id: "m5-27b".into(), weights_bytes: 16_500_000_000, kv_per_token: 32_768, context_window: 262_144, capability_rank: 42, fixed_per_lane_bytes: 0,
};
Expand Down
4 changes: 2 additions & 2 deletions core/continuum-core/src/inference/engine_residency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ mod tests {
fn a_release_retires_only_the_footprint_sampled_during_the_work() {
use super::super::lane_footprint::{retire_sampled_since, MeasuredCost};
let bound_at = 1_000;
let reading = |last_ms| MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, anon_bytes: 20 << 30, last_ms };
let reading = |last_ms| MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, allocated_tokens: None, anon_bytes: 20 << 30, last_ms };
let mut costs = std::collections::BTreeMap::new();
costs.insert("during".to_string(), reading(bound_at + 60_000));
costs.insert("before".to_string(), reading(bound_at - 1));
Expand All @@ -571,7 +571,7 @@ mod tests {
#[test]
fn a_sample_that_straddles_a_residency_change_is_never_published() {
use super::super::lane_footprint::{begin_sample, publish_sample, MeasuredCost};
let reading = MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, anon_bytes: 20 << 30, last_ms: 5 };
let reading = MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, allocated_tokens: None, anon_bytes: 20 << 30, last_ms: 5 };
let dir = tempfile::tempdir().expect("tempdir");
let path = store_path(dir.path());
let w = work(10, 25281, 1_000, 58058);
Expand Down
69 changes: 46 additions & 23 deletions core/continuum-core/src/inference/lane_footprint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ pub struct MeasuredCost {
pub per_token_bytes: u64,
pub lanes: u32,
pub window: u32,
/// Physical token capacity. Absent only in records written by older cores.
#[serde(default)]
pub allocated_tokens: Option<u64>,
pub anon_bytes: u64,
pub last_ms: u64,
}
Expand Down Expand Up @@ -83,20 +86,19 @@ pub fn window_measurable(window: u32) -> bool {
window >= MEASURABLE_WINDOW_MIN
}

pub fn per_token_from(
anon_bytes: u64,
lanes: u32,
window: u32,
compute_floor_per_lane: u64,
host_cache_bytes: u64,
) -> Option<u64> {
if lanes == 0 || window == 0 {
pub fn per_token_from(anon_bytes: u64, lanes: u32, window: u32, compute_floor_per_lane: u64, host_cache_bytes: u64) -> Option<u64> {
per_token_for_allocation(anon_bytes, lanes, u64::from(lanes) * u64::from(window), compute_floor_per_lane, host_cache_bytes)
}

/// Attribute bytes to physical token storage, independently of sequence limits.
fn per_token_for_allocation(anon_bytes: u64, lanes: u32, allocated_tokens: u64, compute_floor_per_lane: u64, host_cache_bytes: u64) -> Option<u64> {
if lanes == 0 || allocated_tokens == 0 {
return None;
}
let beyond_cache = anon_bytes.checked_sub(host_cache_bytes)?;
let per_lane = beyond_cache / lanes as u64;
let beyond_floor = per_lane.checked_sub(compute_floor_per_lane)?;
let per_token = beyond_floor / window as u64;
let floors = compute_floor_per_lane.checked_mul(u64::from(lanes))?;
let beyond_floor = beyond_cache.checked_sub(floors)?;
let per_token = beyond_floor / allocated_tokens;
(per_token > 0).then_some(per_token)
}

Expand Down Expand Up @@ -182,14 +184,21 @@ pub fn observe(
model: &str,
lanes: u32,
window: u32,
allocated_tokens: u64,
anon_bytes: u64,
compute_floor_per_lane: u64,
host_cache_bytes: u64,
) -> Result<Option<u64>, ResidencyChanged> {
// A pre-1970 clock reads 0 here: every record is stale, so the estimate rules.
let now = EpochMs::now().millis();
let sample = per_token_from(anon_bytes, lanes, window, compute_floor_per_lane, host_cache_bytes)
.map(|per_token| MeasuredCost { per_token_bytes: per_token, lanes, window, anon_bytes, last_ms: now });
let sample = per_token_for_allocation(anon_bytes, lanes, allocated_tokens, compute_floor_per_lane, host_cache_bytes).map(|per_token| MeasuredCost {
per_token_bytes: per_token,
lanes,
window,
allocated_tokens: Some(allocated_tokens),
anon_bytes,
last_ms: now,
});
use std::sync::atomic::Ordering;
let mut costs = COSTS.lock();
let moved = publish_sample(&mut costs, RESIDENCY_EPOCH.load(Ordering::SeqCst), token, model, sample.as_ref())?;
Expand Down Expand Up @@ -263,7 +272,6 @@ pub fn measured_record(model: &str) -> Option<MeasuredCost> {
COSTS.lock().get(model).filter(|c| c.fresh_at(now)).cloned()
}


/// The ANONYMOUS memory a process holds — dirty + compressed/swapped, mapped files
/// excluded. On macOS `proc_pid_rusage` (libproc, no entitlement for our own user's
/// processes); on Linux `/proc/<pid>/status` `RssAnon + VmSwap`. `None` = could not
Expand Down Expand Up @@ -444,12 +452,7 @@ fn parse_procargs2(buf: &[u8]) -> Option<Vec<String>> {
#[cfg(target_os = "linux")]
fn process_args(pid: u32) -> Option<Vec<String>> {
let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
Some(
raw.split(|b| *b == 0)
.filter(|a| !a.is_empty())
.map(|a| String::from_utf8_lossy(a).into_owned())
.collect(),
)
Some(raw.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).into_owned()).collect())
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
Expand Down Expand Up @@ -536,7 +539,14 @@ mod tests {
let model = "trapped-fixture";
COSTS.lock().insert(
model.to_string(),
MeasuredCost { per_token_bytes: per_token, lanes: 1, window: 2_048, anon_bytes: 500_000_000, last_ms: EpochMs::now().millis() },
MeasuredCost {
per_token_bytes: per_token,
lanes: 1,
window: 2_048,
allocated_tokens: None,
anon_bytes: 500_000_000,
last_ms: EpochMs::now().millis(),
},
);
assert!(measured_record(model).is_some(), "the trap record rules before retirement");
assert!(retire(model), "a record was there to retire");
Expand All @@ -561,6 +571,12 @@ mod tests {
assert_eq!(per_token_from(gb, 0, 51_712, 0, 0), None);
assert_eq!(per_token_from(gb, 2, 0, 0, 0), None);
assert_eq!(per_token_from(gb, 2, 4096, gb, 0), None, "under the compute floors: nothing beyond them to attribute");
// Unified and divided caches may have equal sequence limits but different
// physical capacities. Charge only the capacity in the engine's receipt.
assert_eq!(per_token_for_allocation(4096, 2, 2048, 0, 0), Some(2));
assert_eq!(per_token_for_allocation(4096, 2, 4096, 0, 0), Some(1));
assert_eq!(per_token_for_allocation(4096, 2, 0, 0, 0), None);
assert_eq!(per_token_for_allocation(u64::MAX, 2, 2048, u64::MAX, 0), None);
}

// what this catches (2026-09-19, the M5 starved to one lane while running two): the
Expand All @@ -581,7 +597,7 @@ mod tests {
assert!(beyond < inflated && beyond > 32_768, "{beyond}: less than the inflated read, still a real excess");

let mut costs = BTreeMap::new();
let stale = MeasuredCost { per_token_bytes: 133_720, lanes, window, anon_bytes: anon, last_ms: 1 };
let stale = MeasuredCost { per_token_bytes: 133_720, lanes, window, allocated_tokens: None, anon_bytes: anon, last_ms: 1 };
assert!(apply_sample(&mut costs, "m", Some(&stale)), "first record is a move");
assert!(apply_sample(&mut costs, "m", None), "an unattributable sample retires it — a save is due");
assert!(costs.get("m").is_none(), "nothing rules the plan from disk");
Expand All @@ -595,9 +611,16 @@ mod tests {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("lane-footprint.json");
let mut costs = BTreeMap::new();
costs.insert("m".to_string(), MeasuredCost { per_token_bytes: 36_000, lanes: 8, window: 51_712, anon_bytes: 25_700_000_000, last_ms: 5 });
costs.insert(
"m".to_string(),
MeasuredCost { per_token_bytes: 36_000, lanes: 8, window: 51_712, allocated_tokens: None, anon_bytes: 25_700_000_000, last_ms: 5 },
);
save_to(&path, &costs);
assert_eq!(load_from(&path), costs);
let mut legacy = serde_json::to_value(&costs).expect("record fixture");
legacy["m"].as_object_mut().expect("record object").remove("allocated_tokens");
std::fs::write(&path, serde_json::to_vec(&legacy).expect("legacy bytes")).expect("write legacy");
assert_eq!(load_from(&path), costs, "old records omit allocated_tokens entirely");
std::fs::write(&path, b"{not json").expect("write");
assert!(load_from(&path).is_empty());
}
Expand Down
68 changes: 44 additions & 24 deletions core/continuum-core/src/inference/weight_residency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ impl WeightResidency {
/// buffer types: `CPU`, `CPU_Mapped`, `CPU_REPACK`, `*_Host` (CUDA pinned host
/// memory is still RAM), and BLAS (Accelerate on a Mac runs on the CPU).
pub fn accelerator_bytes(&self) -> u64 {
self.per_backend
.iter()
.filter(|(name, _)| !is_host_backend(name))
.map(|(_, b)| *b)
.sum()
self.per_backend.iter().filter(|(name, _)| !is_host_backend(name)).map(|(_, b)| *b).sum()
}

pub fn total_bytes(&self) -> u64 {
Expand All @@ -45,11 +41,7 @@ impl WeightResidency {

/// One line for a probe or a refusal message: `Metal=4.7GB CPU_Mapped=0.3GB`.
pub fn summary(&self) -> String {
self.per_backend
.iter()
.map(|(n, b)| format!("{n}={:.2}GB", *b as f64 / 1e9))
.collect::<Vec<_>>()
.join(" ")
self.per_backend.iter().map(|(n, b)| format!("{n}={:.2}GB", *b as f64 / 1e9)).collect::<Vec<_>>().join(" ")
}
}

Expand Down Expand Up @@ -81,11 +73,7 @@ impl EngineMemory {
/// The bytes BEYOND the weights on accelerators: KV cache + compute buffers on every buffer
/// type that is not host memory. What the device delta measures on a discrete GPU.
pub fn accelerator_beyond_weights(&self) -> u64 {
self.per_buffer
.iter()
.filter(|b| !is_host_backend(&b.buffer_type))
.map(|b| b.context_bytes + b.compute_bytes)
.sum()
self.per_buffer.iter().filter(|b| !is_host_backend(&b.buffer_type)).map(|b| b.context_bytes + b.compute_bytes).sum()
}

/// The KV (context) bytes alone on accelerators, compute buffers excluded.
Expand All @@ -106,8 +94,9 @@ pub struct EngineContext {
/// KV plus compute buffers on accelerators: everything the engine says it holds beyond weights.
pub beyond_weights: u64,
pub slots: u32,
/// Each slot's context. The lane passes `--parallel` explicitly, so the cache is never unified
/// and the engine holds `slots × n_ctx_per_slot` tokens.
/// Total physical token capacity; unified caches do not multiply this by slots.
pub allocated_tokens: u64,
/// Maximum context for one sequence, independently of total physical capacity.
pub n_ctx_per_slot: u32,
}

Expand All @@ -132,7 +121,7 @@ impl EngineContextReading {
// (`{"error": …}`), or a geometry that is missing, null or zero is not an old engine,
// and a missing breakdown there is no reading (Codex on #4961). The same parse decides
// here and in `from_props`, so the two cannot disagree about what a geometry is.
if slot_geometry(props).is_none() {
if slot_geometry(props).and_then(|(slots, window)| allocated_capacity(props, slots, window)).is_none() {
return Self::Invalid;
}
if props.get("memory_breakdown").is_none() {
Expand All @@ -148,13 +137,26 @@ impl EngineContext {
pub fn from_props(props: &serde_json::Value) -> Option<Self> {
let memory = EngineMemory::from_props(props)?;
let (slots, n_ctx_per_slot) = slot_geometry(props)?;
let allocated_tokens = allocated_capacity(props, slots, n_ctx_per_slot)?;
let context_bytes = memory.accelerator_context();
(context_bytes > 0).then(|| Self {
context_bytes,
beyond_weights: memory.accelerator_beyond_weights(),
slots,
n_ctx_per_slot,
})
(context_bytes > 0).then(|| Self { context_bytes, beyond_weights: memory.accelerator_beyond_weights(), slots, allocated_tokens, n_ctx_per_slot })
}
}

fn allocated_capacity(props: &serde_json::Value, slots: u32, n_ctx_per_slot: u32) -> Option<u64> {
match props.get("context_geometry") {
Some(geometry) => {
let tokens = geometry.get("allocated_tokens")?.as_u64()?;
let capacity = geometry.get("sequence_capacity")?.as_u64()?;
let window = geometry.get("max_tokens_per_sequence")?.as_u64()?;
if tokens == 0 || capacity != u64::from(slots) || window != u64::from(n_ctx_per_slot) || window > tokens {
return None;
}
Some(tokens)
}
// Older managed engines used divided caches. Only absence permits their
// legacy geometry; a present malformed receipt must never take this path.
None => Some(u64::from(slots) * u64::from(n_ctx_per_slot)),
}
}

Expand Down Expand Up @@ -202,7 +204,25 @@ mod tests {
let ctx = EngineContext::from_props(&with_slots).expect("reads");
assert_eq!((ctx.context_bytes, ctx.slots, ctx.n_ctx_per_slot), (117440512, 2, 2048));
assert_eq!(ctx.beyond_weights, 117440512 + 66594944);
assert_eq!(ctx.allocated_tokens, 4096);
assert_eq!(EngineContextReading::of(&with_slots), EngineContextReading::Read(ctx));
// A unified cache's per-sequence limit is not independent storage per slot.
let mut unified = with_slots.clone();
unified["context_geometry"] = serde_json::json!({
"allocated_tokens": 2048, "max_tokens_per_sequence": 2048, "sequence_capacity": 2
});
assert_eq!(EngineContext::from_props(&unified).expect("unified receipt").allocated_tokens, 2048);
for invalid in [
serde_json::Value::Null,
serde_json::json!({"allocated_tokens": 0, "max_tokens_per_sequence": 2048, "sequence_capacity": 2}),
serde_json::json!({"allocated_tokens": 2048, "max_tokens_per_sequence": 2048, "sequence_capacity": 3}),
] {
unified["context_geometry"] = invalid;
assert_eq!(EngineContextReading::of(&unified), EngineContextReading::Invalid);
let mut no_breakdown = unified.clone();
no_breakdown.as_object_mut().expect("props fixture").remove("memory_breakdown");
assert_eq!(EngineContextReading::of(&no_breakdown), EngineContextReading::Invalid);
}
// present but unusable is no reading, never the legacy fallback (Codex on #4961)
assert_eq!(EngineContextReading::of(&props), EngineContextReading::Invalid, "no slot geometry");
let mut zero_slots = with_slots.clone();
Expand Down
Loading
Loading