diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs index 4612d6f81b..b0a82a82a4 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -190,10 +190,10 @@ fn resume(tier: &mut UnifiedTier<'_, '_>, preserved: &mut preserve::Preserved, m let id = PersonaId(mind.persona); let epoch = Epoch(mind.epoch); match preserved.restore(tier, &mind) { - Ok((blocks, held)) => { + Ok(preserve::Restored { blocks, held, checkpoint }) => { continuum_base::probe!(class = "persona.engine.resumed", persona = %mind.persona, tokens = held.len() as u64, in_place = mind.kv.is_some(), "a mind came back from her preserved files"); // a mind resumed from disk keeps her genes and their files, never the adapters themselves - let parts = Parts { blocks, tokens: History::from(held), genome: Basis::resumed(mind.basis, mind.genes), learning: (), decode: Tenure::Resident }; + let genome = Basis::resumed(mind.basis, mind.genes); let parts = Parts { blocks, tokens: History::from(held).with_view(checkpoint, &genome), genome, learning: (), decode: Tenure::Resident }; parked.insert(id, Mind::new(id, epoch, parts)); } Err(refused) => { @@ -598,7 +598,7 @@ impl Driver<'_, '_> { } let her = self.parked.remove(&id).ok_or(PreserveError::NotReturned)?; let (epoch, parts) = (her.epoch().0, her.into_parts()); - let leaving = preserve::Leaving { persona: id.0, epoch, basis: parts.genome.genes, genes: &parts.genome.sources, blocks: parts.blocks, held: &parts.tokens.held }; + let leaving = preserve::Leaving { checkpoint: parts.tokens.view_checkpoint(&parts.genome), persona: id.0, epoch, basis: parts.genome.genes, genes: &parts.genome.sources, blocks: parts.blocks, held: &parts.tokens.held }; Ok(store.hand_over(leaving, generation)?) } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs index 54b08cdacb..14abe1008f 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -1,4 +1,4 @@ -use super::{reuse, Basis, Footprint, Held}; +use super::{preserve, reuse, Basis, Footprint, Held}; /// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still /// runs through it. @@ -108,6 +108,24 @@ impl From> for History { } impl History { + /// Her view-end checkpoint as a stop hands it over, when it was taken under `under`, the genes her + /// blocks were computed under (the only genes her resumed blocks carry). + pub(super) fn view_checkpoint(&self, under: &Basis) -> Option> { + let [view, ..] = &self.kept; + view.as_ref() + .filter(|kept| &kept.basis == under) + .map(|kept| preserve::LeavingCheckpoint { blocks: &kept.blocks, end: kept.end }) + } + + /// Her history back from a restart with her view-end checkpoint, when it came back + /// with her blocks, under `basis`, the genes they resume under. + pub(super) fn with_view(mut self, view: Option, basis: &Basis) -> Self { + if let Some(view) = view { + self.save(Boundary::View, view.blocks, view.end, basis); + } + self + } + /// Her deepest checkpoint at or below `end`, the furthest she can be rewound without passing it. pub(super) fn deepest_at_or_below(&self, end: usize) -> Option { self.kept.iter().flatten().map(|kept| kept.end).filter(|&at| at <= end).max() diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/preserve.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/preserve.rs index 42a598e3ab..4645d47bdd 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/preserve.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/preserve.rs @@ -20,7 +20,7 @@ use std::path::{Path, PathBuf}; use continuum_saved_state::{OwnedFile, Retention, SaveError, SavedState, Singleton, Store}; mod mind_files; -pub(super) use mind_files::{HandOverError, Leaving}; +pub(super) use mind_files::{HandOverError, Leaving, LeavingCheckpoint, Restored, RestoredCheckpoint}; /// Why preserved minds cannot be opened or published. Each leaves the last complete generation /// standing. @@ -53,6 +53,17 @@ pub(super) struct PreservedMind { /// Her KV file: her attention rows, exactly her storage, handed over by a rename. pub kv: Option, pub tokens: Tokens, + /// Her view-end checkpoint, handed over in the same generation as her blocks: the first turn after a + /// restart rewinds to it instead of re-prefilling her whole prompt. `None` when she had none to keep. + pub checkpoint: Option, +} + +/// Her checkpoint as the manifest names it: its file and the tokens it holds through (exclusive end), +/// a prefix of her token history under the genes her blocks were computed under. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub(super) struct PreservedCheckpoint { + pub file: String, + pub end: u64, } /// Her token history, as the manifest names it. @@ -88,7 +99,7 @@ pub(super) struct PreservedMinds; impl SavedState for PreservedMinds { const KIND: &'static str = "preserved-minds"; - const FORMAT: u32 = 3; + const FORMAT: u32 = 4; const RETENTION: Retention = Retention::PerKey { bound: "one per node: the last complete generation, replaced only once a stop's every write landed" }; type Key = Singleton; type Contract = ServedModel; @@ -97,8 +108,16 @@ impl SavedState for PreservedMinds { /// Formats 1 and 2 held her rows inside her one block file and her history inline: each becomes a /// record holding her rows (the fork reads a format-1 record as one) and a migrating history, so she - /// resumes warm, and her next stop writes format 3. + /// resumes warm, and her next stop writes the current format. Format 3 kept no checkpoint: each of + /// its minds is read as she was, with none (her first turn after it re-prefills once, as before). fn upgrade(found: u32, old: serde_json::Value) -> Option { + if found == 3 { + let serde_json::Value::Array(mut minds) = old else { return None }; + for mind in &mut minds { + mind.as_object_mut()?.insert("checkpoint".into(), serde_json::Value::Null); + } + return serde_json::from_value(serde_json::Value::Array(minds)).ok(); // disk boundary: the saved-state envelope's format-3 body + } let minds: Vec = matches!(found, 1 | 2).then(|| serde_json::from_value(old).ok()).flatten()?; // disk boundary: the saved-state envelope's format-1/2 body Some(minds.into_iter().map(|m| PreservedMind { record: m.blocks.unwrap_or_else(|| format!("{}.cpb", m.persona)), // unwrap_or_else: format 1 named no file; hers was fixed @@ -109,6 +128,7 @@ impl SavedState for PreservedMinds { generation: 0, // a format-1 record carries none, and the fork reads it under any kv: None, tokens: Tokens::Migrating(m.held), + checkpoint: None, // a format-1 or format-2 manifest kept no checkpoint }).collect()) } } @@ -141,6 +161,11 @@ impl Generation { pub(super) fn tokens(self, persona: uuid::Uuid) -> String { format!("{persona}.{:016x}.tok", self.0) } + + /// Her checkpoint's name in this generation. + pub(super) fn checkpoint(self, persona: uuid::Uuid) -> String { + format!("{persona}.{:016x}.ckp", self.0) + } } /// The manifest a stop publishes: every mind written this generation, and every other mind of the @@ -162,7 +187,7 @@ fn unreferenced(dir: &Path, manifest: &[PreservedMind]) -> std::io::Result Some(name.as_str()), Tokens::Migrating(_) => None, }; - std::iter::once(self.record.as_str()).chain(self.kv.as_deref()).chain(tokens) + let checkpoint = self.checkpoint.as_ref().map(|checkpoint| checkpoint.file.as_str()); + std::iter::once(self.record.as_str()).chain(self.kv.as_deref()).chain(tokens).chain(checkpoint) } } @@ -268,7 +294,7 @@ mod tests { use continuum_saved_state::Loaded; fn mind(n: u128, blocks: &str) -> PreservedMind { - PreservedMind { persona: uuid::Uuid::from_u128(n), epoch: 1, basis: String::new(), genes: Vec::new(), generation: 1, record: blocks.to_owned(), kv: None, tokens: Tokens::Migrating(vec![n as i32]) } + PreservedMind { persona: uuid::Uuid::from_u128(n), epoch: 1, basis: String::new(), genes: Vec::new(), generation: 1, record: blocks.to_owned(), kv: None, tokens: Tokens::Migrating(vec![n as i32]), checkpoint: None } } // what this catches (Codex on #6159): a stop interrupted between a block write and the manifest @@ -320,7 +346,7 @@ mod tests { std::fs::write(saved_at.path(&file), b"her rows at the large window").expect("test: write"); // expect: the test's own precondition // her genes and their files travel with her (a resumed resident learns before her next turn, 2026-11-26) let genes = vec![crate::inference::backends::persona_scheduler::Gene { id: "served".into(), path: "/genes/served/adapter.gguf".into(), scale: 1.0 }]; - let original = vec![PreservedMind { persona: her, epoch: 1, basis: "served:1".into(), genes, generation: 1, record: file.clone(), kv: None, tokens: Tokens::File { name: format!("{her}.tok"), count: 3 } }]; + let original = vec![PreservedMind { persona: her, epoch: 1, basis: "served:1".into(), genes, generation: 1, record: file.clone(), kv: None, tokens: Tokens::File { name: format!("{her}.tok"), count: 3 }, checkpoint: None }]; saved_at.publish(&served, &original).expect("test: publish"); // expect: the test's own precondition // the smaller boot: her manifest loads, her read is refused, so she never enters the warm @@ -359,34 +385,39 @@ mod tests { // what this catches: publishing removing a file the manifest names (her record, KV file or history), // removing a custody lock (deleting a lock file races the next locker), or leaving a file it no - // longer names to fill the disk. After a publish only the named files and the locks remain. + // longer names to fill the disk (her checkpoint of an older generation, or a torn one, included). + // After a publish only the named files and the locks remain. #[test] fn a_publish_removes_only_what_it_no_longer_names() { let dir = tempfile::tempdir().expect("test: a temp dir"); // expect: the test's own precondition let mut preserved = Preserved::at(dir.path().to_path_buf()).expect("test: a store"); // expect: the test's own precondition - let files = ["a.g1.cpb", "a.g2.cpb", "a.g2.kv", "a.g2.tok", "a.g1.kv", "a.g1.tok", "b.g1.cpb", "b.g2.cpb.tmp", "a.custody"]; + let files = ["a.g1.cpb", "a.g2.cpb", "a.g2.kv", "a.g2.tok", "a.g2.ckp", "a.g1.kv", "a.g1.tok", "a.g1.ckp", "a.g2.ckp.tmp", "b.g1.cpb", "b.g2.cpb.tmp", "a.custody"]; for file in files { std::fs::write(preserved.path(file), b"rows").expect("test: write"); // expect: the test's own precondition } - let a = PreservedMind { kv: Some("a.g2.kv".into()), tokens: Tokens::File { name: "a.g2.tok".into(), count: 1 }, ..mind(1, "a.g2.cpb") }; + let a = PreservedMind { kv: Some("a.g2.kv".into()), tokens: Tokens::File { name: "a.g2.tok".into(), count: 1 }, checkpoint: Some(PreservedCheckpoint { file: "a.g2.ckp".into(), end: 1 }), ..mind(1, "a.g2.cpb") }; let kept = preserved.publish(&ServedModel { model: "m".into() }, &[a, mind(2, "b.g1.cpb")]).expect("test: publish"); // expect: the test's own precondition assert!(kept.is_empty(), "{kept:?}"); let mut left: Vec = std::fs::read_dir(dir.path()).expect("test: list").filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| files.contains(&n.as_str())).collect(); // expect: the test's own precondition left.sort(); - assert_eq!(left, ["a.custody", "a.g2.cpb", "a.g2.kv", "a.g2.tok", "b.g1.cpb"].map(str::to_owned)); + assert_eq!(left, ["a.custody", "a.g2.ckp", "a.g2.cpb", "a.g2.kv", "a.g2.tok", "b.g1.cpb"].map(str::to_owned)); } // what this catches (Codex, 2026-11-25: a named cold start loses her continuity): a format change // dropping every preserved mind at the first start after it. Format 1 (her blocks at a fixed name) // and format 2 (named per generation) both upgrade to a record holding her rows and her history - // carried until her next stop, so she resumes warm. + // carried until her next stop, so she resumes warm; format 3 (no checkpoint kept) reads as she was. #[test] - fn a_format_one_or_two_manifest_upgrades_to_a_record_with_her_rows() { + fn an_older_manifest_upgrades_and_her_mind_resumes_warm() { let id = uuid::Uuid::from_u128(7); - let migrated = |record: String| vec![PreservedMind { persona: id, epoch: 3, basis: String::new(), genes: Vec::new(), generation: 0, record, kv: None, tokens: Tokens::Migrating(vec![1, 2]) }]; + let migrated = |record: String| vec![PreservedMind { persona: id, epoch: 3, basis: String::new(), genes: Vec::new(), generation: 0, record, kv: None, tokens: Tokens::Migrating(vec![1, 2]), checkpoint: None }]; let one = serde_json::json!([{ "persona": id, "epoch": 3, "basis": "", "held": [1, 2] }]); assert_eq!(PreservedMinds::upgrade(1, one), Some(migrated(format!("{id}.cpb")))); let two = serde_json::json!([{ "persona": id, "epoch": 3, "basis": "", "held": [1, 2], "blocks": format!("{id}.abc.cpb") }]); assert_eq!(PreservedMinds::upgrade(2, two), Some(migrated(format!("{id}.abc.cpb")))); + // format 3 kept no checkpoint: each mind as she was, with none + let mut three = serde_json::to_value(migrated(format!("{id}.abc.cpb"))).expect("test: a format-3 body"); // expect: the test's own precondition + three[0].as_object_mut().expect("test: one mind").remove("checkpoint"); // expect: the test's own precondition + assert_eq!(PreservedMinds::upgrade(3, three), Some(migrated(format!("{id}.abc.cpb")))); } } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/preserve/mind_files.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/preserve/mind_files.rs index 1502fc3603..0e0b314cdf 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/preserve/mind_files.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/preserve/mind_files.rs @@ -5,7 +5,9 @@ //! directory, so a refused restore leaves the last generation whole and a crash after the move leaves her //! cold and named. A stop writes her history, then hands her blocks over: her record made durable, her //! file synced, unmapped and renamed into the preserved directory. Only once every mind's files are -//! durable is the manifest naming them published (`Preserved::publish`). +//! durable is the manifest naming them published (`Preserved::publish`). Her view-end checkpoint travels +//! the same way, written beside her record while it is still valid against her blocks and read back into +//! her restored blocks, so her first turn after a restart rewinds to it instead of re-prefilling. use std::io; use std::path::PathBuf; @@ -13,8 +15,9 @@ use std::path::PathBuf; use continuum_persona_engine::persona::{Epoch, MindId, PersonaId}; use continuum_persona_engine::residency::TierRefusal; use continuum_persona_llama::{Blocks, HandOverRefusal, UnifiedTier}; +use llama::{PersonaCheckpoint, PersonaRefusal}; -use super::{Generation, Preserved, PreservedMind, Tokens}; +use super::{Generation, Preserved, PreservedCheckpoint, PreservedMind, Tokens}; /// Bytes of one token in her history file: a raw `i32`. const TOKEN_BYTES: usize = std::mem::size_of::(); @@ -52,6 +55,55 @@ pub(in crate::inference::backends::persona_scheduler) struct Leaving<'a> { pub genes: &'a [crate::inference::backends::persona_scheduler::Gene], pub blocks: Blocks, pub held: &'a [i32], + /// Her view-end checkpoint, when she keeps one under the genes her blocks were computed under. + pub checkpoint: Option>, +} + +/// Her checkpoint as a stop hands it over: its rows and the tokens it holds through (exclusive end). +pub(in crate::inference::backends::persona_scheduler) struct LeavingCheckpoint<'a> { + pub blocks: &'a PersonaCheckpoint, + pub end: usize, +} + +/// What a restore brings back: her blocks, her token history, and her checkpoint when it came back too. +pub(in crate::inference::backends::persona_scheduler) struct Restored { + pub blocks: Blocks, + pub held: Vec, + pub checkpoint: Option, +} + +/// Her checkpoint back from a restart, bound to her restored cells. +pub(in crate::inference::backends::persona_scheduler) struct RestoredCheckpoint { + pub blocks: PersonaCheckpoint, + pub end: usize, +} + +/// Why her checkpoint did not cross a restart. Her blocks and history do either way; only the rewind past +/// them is lost, so her next turn re-prefills once, and the loss is a probe, never silent. +#[derive(Debug, thiserror::Error)] +enum CheckpointLoss { + #[error("it holds through {end} tokens, she holds {held}")] + Beyond { end: usize, held: usize }, + #[error("it holds through position {pos:?}, its end names {end} tokens")] + Position { pos: Option, end: usize }, + #[error("no memory for its rows")] + NoMemory, + #[error(transparent)] + Fork(#[from] PersonaRefusal), + #[error(transparent)] + HandOver(#[from] HandOverRefusal), +} + +/// Her checkpoint is the one the manifest can name: it holds exactly `end` tokens, all of them hers. +fn holds_exactly(checkpoint: &PersonaCheckpoint, end: usize, held: usize) -> Result<(), CheckpointLoss> { + if end > held { + return Err(CheckpointLoss::Beyond { end, held }); + } + let pos = checkpoint.pos(); + if pos.map(|pos| pos as usize + 1) != Some(end) { + return Err(CheckpointLoss::Position { pos, end }); + } + Ok(()) } impl Preserved { @@ -67,7 +119,7 @@ impl Preserved { } /// Her blocks and token history back from the files `mind` names, under her custody. - pub(in crate::inference::backends::persona_scheduler) fn restore(&mut self, tier: &mut UnifiedTier<'_, '_>, mind: &PreservedMind) -> Result<(Blocks, Vec), RestoreRefusal> { + pub(in crate::inference::backends::persona_scheduler) fn restore(&mut self, tier: &mut UnifiedTier<'_, '_>, mind: &PreservedMind) -> Result { self.take_custody(mind.persona).map_err(RestoreRefusal::Custody)?; let held = match &mind.tokens { Tokens::File { name, count } => self.read_tokens(name, *count)?, @@ -75,8 +127,24 @@ impl Preserved { }; let id = MindId { persona: PersonaId(mind.persona), epoch: Epoch(mind.epoch) }; let kv = mind.kv.as_deref().map(|name| self.path(name)); - let blocks = tier.restore(id, &self.path(&mind.record), kv.as_deref(), mind.generation)?; - Ok((blocks, held)) + let mut blocks = tier.restore(id, &self.path(&mind.record), kv.as_deref(), mind.generation)?; + let checkpoint = mind.checkpoint.as_ref().and_then(|kept| { + let end = kept.end as usize; + let restored = self.restore_checkpoint(&mut blocks, kept, mind.generation, held.len()); + restored + .inspect_err(|lost| continuum_base::probe!(class = "persona.engine.checkpoint_not_restored", persona = %mind.persona, end = end as u64, why = %lost, "her checkpoint did not come back; her first turn re-prefills")) + .ok() + .map(|blocks| RestoredCheckpoint { blocks, end }) + }); + Ok(Restored { blocks, held, checkpoint }) + } + + /// Her checkpoint from `kept`, read into her restored blocks and holding exactly its end within her history. + fn restore_checkpoint(&self, blocks: &mut Blocks, kept: &PreservedCheckpoint, generation: u64, held: usize) -> Result { + let mut checkpoint = PersonaCheckpoint::new().ok_or(CheckpointLoss::NoMemory)?; + blocks.restore_checkpoint(&mut checkpoint, &self.path(&kept.file), generation)?; + holds_exactly(&checkpoint, kept.end as usize, held)?; + Ok(checkpoint) } /// Her history from `name`: exactly `count` raw tokens, refused by the file's length before any byte is read, @@ -99,11 +167,20 @@ impl Preserved { /// Hand one mind over in `generation`: her history, then her blocks (record durable, KV file synced, /// unmapped and renamed), all under her custody. Returns her manifest entry, published with the stop's. pub(in crate::inference::backends::persona_scheduler) fn hand_over(&mut self, her: Leaving<'_>, generation: Generation) -> Result { - let Leaving { persona, epoch, basis, genes, blocks, held } = her; + let Leaving { persona, epoch, basis, genes, blocks, held, checkpoint } = her; self.take_custody(persona).map_err(HandOverError::Custody)?; let tokens = generation.tokens(persona); // her history's own bytes, written as they lie in memory: no per-token encode, no staging copy continuum_host::durable::write_replace(&self.path(&tokens), bytemuck::cast_slice(held)).map_err(HandOverError::Tokens)?; + // her checkpoint before her blocks go: the fork checks it against them as they are + let checkpoint = checkpoint.and_then(|kept| { + let file = generation.checkpoint(persona); + let written = holds_exactly(kept.blocks, kept.end, held.len()).and_then(|()| blocks.hand_over_checkpoint(kept.blocks, &self.path(&file), generation.number()).map_err(CheckpointLoss::from)); + written + .inspect_err(|lost| continuum_base::probe!(class = "persona.engine.checkpoint_not_preserved", persona = %persona, end = kept.end as u64, why = %lost, "her checkpoint was not handed over; her first turn after the restart re-prefills")) + .ok() + .map(|()| PreservedCheckpoint { file, end: kept.end as u64 }) + }); let (record, kv) = (generation.record(persona), generation.kv(persona)); let in_kv = blocks.hand_over(&self.path(&record), &self.path(&kv), generation.number())?; Ok(PreservedMind { @@ -115,6 +192,7 @@ impl Preserved { record, kv: in_kv.then_some(kv), tokens: Tokens::File { name: tokens, count: held.len() as u64 }, + checkpoint, }) } } diff --git a/core/continuum-persona-llama/Cargo.toml b/core/continuum-persona-llama/Cargo.toml index 4e4de77455..61d77af8c0 100644 --- a/core/continuum-persona-llama/Cargo.toml +++ b/core/continuum-persona-llama/Cargo.toml @@ -18,6 +18,10 @@ required-features = ["test-fixtures"] name = "persona_handoff" required-features = ["test-fixtures"] +[[example]] +name = "checkpoint_handoff" +required-features = ["test-fixtures"] + [dependencies] continuum-base = { workspace = true } # probe!: a refused decode reports what the engine held continuum-persona-engine = { workspace = true } diff --git a/core/continuum-persona-llama/examples/checkpoint_handoff.rs b/core/continuum-persona-llama/examples/checkpoint_handoff.rs new file mode 100644 index 0000000000..51acdd2238 --- /dev/null +++ b/core/continuum-persona-llama/examples/checkpoint_handoff.rs @@ -0,0 +1,168 @@ +//! A mind's view-end checkpoint handed over by a stop with her blocks and taken back by a new core, on a +//! real model (CONTINUUM-ENGINE 4.15 and 4.16). Without it a hybrid mind restored with every token she held +//! could not rewind to her view's end, so her first turn after a restart re-prefilled her whole prompt (the +//! M5, 2026-11-27: Aiko shared 214,911 of 246,764 tokens with what she held and prefilled 1,019 s). +//! +//! The old core prefills her view, takes her checkpoint at its end, prefills the turn's tail and decodes, +//! parks her and hands over her checkpoint and her blocks. A new core restores her blocks, refuses her +//! checkpoint of another generation, takes it back of hers, rewinds her to it and prefills a NEW tail: only +//! the tail, never her view. A control mind that never stopped prefills her view and the new tail whole. +//! Every token she decodes after the rewind must equal the control's (next-token continuity), and the +//! prefill she paid after the restart is the tail's, not her view's. +//! +//! cargo run --release --features metal,test-fixtures --example checkpoint_handoff -- + +use std::time::Instant; + +use continuum_persona_engine::persona::{Epoch, MindId, PersonaId}; +use continuum_persona_engine::residency::{Direction, Execute, Tier}; +use continuum_persona_llama::{base_genes, Blocks, KvHome, Step, Tokens, UnifiedTier}; +use llama::{ContextParams, FlashAttn, Model, ModelParams, PersonaCheckpoint, Pos}; + +fn argmax(logits: &[f32]) -> i32 { + let mut best = (0usize, f32::MIN); + for (i, &v) in logits.iter().enumerate() { + if v > best.1 { + best = (i, v); + } + } + best.0 as i32 +} + +fn arg(args: &[String], i: usize, what: &str) -> Result { + args.get(i).ok_or(format!("missing {what}"))?.parse().map_err(|e| format!("{what}: {e}")) +} + +/// The most tokens one step submits: the context's batch. +const BATCH: usize = 2048; + +/// Where her decode stands: the next position and her last sampled token. +#[derive(Clone, Copy)] +struct Cursor { + pos: Pos, + last: i32, +} + +/// Prefill `tokens` for a bound mind from `at`. +fn prefill(tier: &mut UnifiedTier<'_, '_>, mind: MindId, tokens: &[i32], at: Cursor) -> Result { + let Cursor { mut pos, mut last } = at; + for chunk in tokens.chunks(BATCH) { + tier.submit(mind, Step { tokens: Tokens::copied(chunk), from: pos, logits_at_end: true, genes: base_genes() }).map_err(|e| e.to_string())?; + tier.settle().map_err(|e| e.to_string())?; + pos = pos.advanced(chunk.len()).map_err(|e| e.to_string())?; + last = argmax(tier.logits_ith(chunk.len() as i32 - 1)); + } + Ok(Cursor { pos, last }) +} + +/// Decode `n` greedy tokens for a bound mind from `at`. +fn decode(tier: &mut UnifiedTier<'_, '_>, mind: MindId, n: usize, at: Cursor) -> Result, String> { + let Cursor { mut pos, mut last } = at; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + tier.submit(mind, Step { tokens: Tokens::One(last), from: pos, logits_at_end: true, genes: base_genes() }).map_err(|e| e.to_string())?; + tier.settle().map_err(|e| e.to_string())?; + pos = pos.advanced(1).map_err(|e| e.to_string())?; + last = argmax(tier.logits_ith(0)); + out.push(last); + } + Ok(out) +} + +fn main() -> Result<(), String> { + run().inspect_err(|why| eprintln!("checkpoint_handoff: refused: {why}")) +} + +fn run() -> Result<(), String> { + let args: Vec = std::env::args().collect(); + let model_path = args.get(1).ok_or("usage: checkpoint_handoff ")?; + let (view_tokens, tail_tokens, decode_tokens) = (arg(&args, 2, "view_tokens")?, arg(&args, 3, "tail_tokens")?, arg(&args, 4, "decode_tokens")?); + llama::backend_init(); + let model = Model::load(model_path, ModelParams::default())?; + let window = (view_tokens + 2 * tail_tokens + 2 * decode_tokens + 64) as u32; + let params = || ContextParams { n_ctx: window, n_batch: BATCH as u32, n_ubatch: BATCH as u32, n_seq_max: 1, flash_attn: FlashAttn::Enabled, ..ContextParams::default() }; + let tokens_of = |text: &str, n: usize, bos: bool| -> Result, String> { + let mut tokens = model.tokenize(&text.repeat(n / 8 + 1), bos, false)?; + tokens.truncate(n); + Ok(tokens) + }; + let view = tokens_of("She keeps her own notes, and picks up exactly where she left off. ", view_tokens, true)?; + let (old_tail, new_tail) = (tokens_of("The clock reads nine and the ask is the build. ", tail_tokens, false)?, tokens_of("Now it is ten, and the review came back green. ", tail_tokens, false)?); + let start = Cursor { pos: Pos::ZERO, last: 0 }; + + let root = tempfile::tempdir().map_err(|e| e.to_string())?; + let (live, preserved) = (root.path().join("live"), root.path().join("preserved")); + std::fs::create_dir_all(&preserved).map_err(|e| e.to_string())?; + + // the control: one mind, never stopped, her view and the new tail prefilled whole + let control = { + let mut ctx = model.new_context(params())?; + let (home, _) = continuum_blocks::Instance::join(&root.path().join("control"), "control").map_err(|e| e.to_string())?; + let mut tier = UnifiedTier::new(&mut ctx, KvHome::Mapped { instance: home }); + let mind = MindId { persona: PersonaId(uuid::Uuid::new_v4()), epoch: Epoch(1) }; + let mut blocks = tier.blocks_for(mind).map_err(|e| e.to_string())?; + tier.begin(mind, &mut blocks, Direction::In).map_err(|e| e.to_string())?; + let at = prefill(&mut tier, mind, &view, start)?; + let at = prefill(&mut tier, mind, &new_tail, at)?; + decode(&mut tier, mind, decode_tokens, at)? + }; + + // the old core: her view, her checkpoint at its end, the old tail and a decode; then her hand-over + let her = MindId { persona: PersonaId(uuid::Uuid::new_v4()), epoch: Epoch(1) }; + let (record, kv, checkpoint_file, generation) = (preserved.join("her.cpb"), preserved.join("her.kv"), preserved.join("her.ckp"), 0x5107_u64); + let (in_kv, view_end) = { + let mut ctx = model.new_context(params())?; + let (home, _) = continuum_blocks::Instance::join(&live, "old").map_err(|e| e.to_string())?; + let mut tier = UnifiedTier::new(&mut ctx, KvHome::Mapped { instance: home }); + let mut blocks: Blocks = tier.blocks_for(her).map_err(|e| e.to_string())?; + let mut checkpoint = PersonaCheckpoint::new().ok_or("no memory for a checkpoint")?; + tier.begin(her, &mut blocks, Direction::In).map_err(|e| e.to_string())?; + let at = prefill(&mut tier, her, &view, start)?; + let view_end = tier.checkpoint(her, &mut checkpoint).map_err(|e| e.to_string())?; + let at = prefill(&mut tier, her, &old_tail, at)?; + decode(&mut tier, her, decode_tokens, at)?; + tier.begin(her, &mut blocks, Direction::Out).map_err(|e| e.to_string())?; + blocks.hand_over_checkpoint(&checkpoint, &checkpoint_file, generation).map_err(|e| e.to_string())?; + let in_kv = blocks.hand_over(&record, &kv, generation).map_err(|e| e.to_string())?; + (in_kv, view_end) + }; // the old core ends + if view_end as usize + 1 != view.len() { + return Err(format!("her checkpoint holds through position {view_end}, her view ends at {}", view.len())); + } + let kv = in_kv.then_some(kv); + + // the new core: her blocks back, then her checkpoint of this generation only + let mut ctx = model.new_context(params())?; + let (home, _) = continuum_blocks::Instance::join(&live, "new").map_err(|e| e.to_string())?; + let mut tier = UnifiedTier::new(&mut ctx, KvHome::Mapped { instance: home }); + let mut blocks = tier.restore(her, &record, kv.as_deref(), generation).map_err(|e| e.to_string())?; + let mut checkpoint = PersonaCheckpoint::new().ok_or("no memory for a checkpoint")?; + if blocks.restore_checkpoint(&mut checkpoint, &checkpoint_file, generation + 1).is_ok() || checkpoint.pos().is_some() { + return Err("a checkpoint of another generation was taken, or left one taken".into()); + } + let t = Instant::now(); + blocks.restore_checkpoint(&mut checkpoint, &checkpoint_file, generation).map_err(|e| e.to_string())?; + if checkpoint.pos() != Some(view_end) { + return Err(format!("her restored checkpoint holds through {:?}, it was taken at {view_end}", checkpoint.pos())); + } + tier.begin(her, &mut blocks, Direction::In).map_err(|e| e.to_string())?; + tier.rewind(her, &checkpoint).map_err(|e| e.to_string())?; + let restored_at = Cursor { pos: Pos::ZERO.advanced(view.len()).map_err(|e| e.to_string())?, last: 0 }; + let at = prefill(&mut tier, her, &new_tail, restored_at)?; + let after = decode(&mut tier, her, decode_tokens, at)?; + let resumed_ms = t.elapsed().as_secs_f64() * 1e3; + if after != control { + let differs = after.iter().zip(&control).position(|(a, b)| a != b); + return Err(format!("next-token continuity broken after the rewind: first difference at token {differs:?}")); + } + println!( + "checkpoint_handoff: view={} tail={} decode={decode_tokens} | checkpoint {:.1} KB | after the restart she prefilled {} tokens (the tail), not {} | resumed in {resumed_ms:.1} ms | {} tokens equal the control's; another generation refused", + view.len(), + new_tail.len(), + std::fs::metadata(&checkpoint_file).map(|m| m.len()).unwrap_or(0) as f64 / 1e3, // unwrap_or: a file not there reports 0 bytes + new_tail.len(), + view.len() + new_tail.len(), + after.len() + ); + Ok(()) +} diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index 2474194a79..b07d488aa0 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -111,6 +111,22 @@ impl Blocks { drop(native); // the fork's tensors over her mapping go before the mapping does Ok(memory.hand_over(kv)?) } + + /// Hand her checkpoint over beside her blocks, before [`Self::hand_over`] consumes them: written to + /// `path` for the stop's `generation` only while it is still valid against these blocks, and made + /// durable, so a manifest names it only once it is whole. + pub fn hand_over_checkpoint(&self, checkpoint: &PersonaCheckpoint, path: &std::path::Path, generation: u64) -> Result<(), HandOverRefusal> { + checkpoint.write_file(&self.native, path, generation)?; + continuum_host::durable::fence_path(path)?; + Ok(()) + } + + /// Her checkpoint back into `into` from what the stop of `generation` handed over, once these blocks + /// were restored from her record of it ([`UnifiedTier::restore`]): bound to her restored cells, so it + /// rewinds as one taken before the stop. + pub fn restore_checkpoint(&mut self, into: &mut PersonaCheckpoint, path: &std::path::Path, generation: u64) -> Result<(), PersonaRefusal> { + into.read_file(&mut self.native, path, generation) + } } /// Her owner stamp for the fork: a fold of her 128-bit id, the same in every process, so the blocks diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs index 572ba0b035..3fafd87ffb 100644 --- a/core/llama/src/safe/persona.rs +++ b/core/llama/src/safe/persona.rs @@ -240,6 +240,25 @@ impl PersonaCheckpoint { // SAFETY: `self.ptr` is live for this handle. unsafe { sys::llama_persona_checkpoint_bytes(self.ptr.as_ptr()) } } + + /// Write it to `path` beside her record of the stop's `generation` (through `.tmp` and a + /// rename), with the parked `blocks` it is still valid against: her owner, the cells it was taken + /// from, uncut at or below it since. Anything else is refused and nothing is written. The caller + /// makes it durable before naming it in a manifest. + pub fn write_file(&self, blocks: &PersonaBlocks, path: &std::path::Path, generation: u64) -> Result<(), PersonaRefusal> { + let path = path_c(path)?; + // SAFETY: both pointers are live; the fork only reads them and writes the file. + status(unsafe { sys::llama_persona_checkpoint_write_file(blocks.ptr.as_ptr(), self.ptr.as_ptr(), path.as_ptr(), generation) }) + } + + /// Fill it from `path`, written by the stop of `generation`, for `blocks` already read back from + /// her record of that generation: checked against them, then bound to their restored cells, so it + /// rewinds as one taken before the stop. A refusal leaves nothing taken. + pub fn read_file(&mut self, blocks: &mut PersonaBlocks, path: &std::path::Path, generation: u64) -> Result<(), PersonaRefusal> { + let path = path_c(path)?; + // SAFETY: both pointers are live; the fork checks the whole file before committing anything. + status(unsafe { sys::llama_persona_checkpoint_read_file(blocks.ptr.as_ptr(), path.as_ptr(), generation, self.ptr.as_ptr()) }) + } } impl Drop for PersonaCheckpoint { diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index b3d9ef014a..4ac59ca291 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -6ac8921872f99d1c5727d112cccc741960b5925d +fad04059f8bb19a7e86c1e60fb8a9a37fd0cf0ff diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 6ac8921872..fad04059f8 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 6ac8921872f99d1c5727d112cccc741960b5925d +Subproject commit fad04059f8bb19a7e86c1e60fb8a9a37fd0cf0ff