Skip to content
Closed
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
27 changes: 24 additions & 3 deletions core/continuum-engine/src/ai/openai_adapter/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,10 @@ impl OpenAICompatibleAdapter {
})?;
// The endpoint's own permits, shared by every adapter and the learner (card 23069702).
let endpoint_permits = crate::inference::slots::directory().endpoint(root).concurrency().bound();
let adm = crate::inference::turn_admission::admit_turn(
// Her state streams in while she waits for a lane (fork #139: a mind on flash is inserted into a parked
// sequence, so her switch is a sequence move), only from an engine that declared resident minds.
let stream_in = turn_key.filter(|_| class.holds_a_page()).zip(pool.resident_minds());
let admit = crate::inference::turn_admission::admit_turn(
endpoint_permits,
class,
turn_key,
Expand All @@ -221,8 +224,21 @@ impl OpenAICompatibleAdapter {
root,
approx_tokens,
crate::inference::turn_admission::AdmissionPatience::for_turn(),
)
.await
);
let adm = match stream_in {
None => admit.await,
Some((key, minds)) => {
// Admission first: a turn admitted at once never streams. The stream lives only while she
// waits, and is dropped with her wait (admitted or cancelled), so it never outlives its turn.
let mut admit = std::pin::pin!(admit);
let stream = crate::inference::minds::prefetch(&self.client, root, minds, key);
tokio::select! {
biased;
adm = &mut admit => adm,
() = stream => admit.await,
}
}
}
.map_err(crate::ai::inference_error::InferenceError::Unavailable)?;
let scratch = adm.scratch_slot();
// Only a turn that names its page owns a slot. A Turn with no persona (or a Fork
Expand Down Expand Up @@ -273,6 +289,11 @@ impl OpenAICompatibleAdapter {
if let Some(slot) = placement {
if let Some(obj) = body.as_object_mut() {
obj.insert("id_slot".to_string(), json!(slot));
// the mind this turn is (fork #139): the engine switches minds on a lane by sequence moves,
// never through its prompt cache; an engine without minds ignores the field
if let (true, Some(key)) = (keyed_turn, turn_key.as_ref()) {
obj.insert("page".to_string(), json!(key.engine_id().simple().to_string()));
}
}
if let (true, Some(persona)) = (
keyed_turn,
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-engine/src/inference/llama_server/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ pub trait LlamaServerControl: Send + Sync {
None
}

/// The resident minds the next launch keeps beside its lanes (`--minds`, fork #139): the seated minds plus
/// the learner's side sequence. Only the resident lane's controller holds them; no other lane is asked.
fn seat_minds(&self, _minds: std::num::NonZeroU32) {}

async fn serve_if_current(
&self,
target: &ServingTarget,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,10 @@ impl LlamaServerControl for LlamaServerProcess {
self.last_started.lock().clone()
}

fn seat_minds(&self, minds: std::num::NonZeroU32) {
self.seated_minds.store(minds.get(), std::sync::atomic::Ordering::Relaxed);
}

async fn serve_if_current(
&self,
target: &ServingTarget,
Expand Down
17 changes: 14 additions & 3 deletions core/continuum-engine/src/inference/llama_server/genome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(super) static ENGINE_PROBES: parking_lot::Mutex<BTreeMap<String, ProbeOutcom
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ProbeOutcome {
/// It answered (`answered` or `did_not_enumerate`): never asked again.
Answered { train_dir: bool },
Answered { train_dir: bool, minds: bool },
/// It was asked and did not answer: no, for now, and asked again at its next use.
Unanswered,
}
Expand All @@ -34,14 +34,14 @@ pub(super) fn train_dir_support(bin: &str) -> Option<bool> {
/// PURE: what the record says about `bin`: its answer, no when it did not answer, nothing when it
/// was never asked.
pub(super) fn answer_for(probes: &BTreeMap<String, ProbeOutcome>, bin: &str) -> Option<bool> {
probes.get(bin).map(|outcome| matches!(outcome, ProbeOutcome::Answered { train_dir: true }))
probes.get(bin).map(|outcome| matches!(outcome, ProbeOutcome::Answered { train_dir: true, .. }))
}

/// PURE: what a decision may rest on: `bin`'s answer when it answered, else nothing (never asked,
/// or asked without an answer), and the caller asks it now.
pub(super) fn train_dir_known(probes: &BTreeMap<String, ProbeOutcome>, bin: &str) -> Option<bool> {
match probes.get(bin) {
Some(ProbeOutcome::Answered { train_dir }) => Some(*train_dir),
Some(ProbeOutcome::Answered { train_dir, .. }) => Some(*train_dir),
_ => None,
}
}
Expand All @@ -63,6 +63,17 @@ pub(super) fn engine_help_lists_train_dir(help: &str) -> bool {
help.lines().any(|l| l.trim_start().starts_with("--train-dir"))
}

/// The engine keeps resident minds as parked sequences (`--minds`, fork #139): a mind switch is a sequence
/// move, never a serialization.
pub(super) fn engine_help_lists_minds(help: &str) -> bool {
help.lines().any(|l| l.trim_start().starts_with("--minds"))
}

/// Whether `bin` accepts `--minds`. "Not asked yet" reads as no: an older engine refuses to start with it.
pub fn engine_accepts_minds(bin: &str) -> bool {
matches!(ENGINE_PROBES.lock().get(bin), Some(ProbeOutcome::Answered { minds: true, .. }))
}


/// Where every lane's `POST /train` writes its adapters (`--train-dir`). One directory
/// for all lanes: a job names its output `<job-uuid>.gguf`, and the engine trainer moves
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to
return;
}
let mut train_dir = false;
let mut minds = false;
command.arg("--help");
// owned (continuum_process::run_owned): a help probe that hangs is ended with anything it started
let probe = continuum_process::run_owned(command, Some(Duration::from_secs(10)), "engine-help-probe", std::sync::Arc::default()).await;
Expand All @@ -30,6 +31,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to
text.push('\n');
text.push_str(&String::from_utf8_lossy(&out.stderr.bytes));
train_dir = engine_help_lists_train_dir(&text);
minds = super::genome::engine_help_lists_minds(&text);
match crate::inference::kv_cache_plan::parse_engine_kv_support(&text) {
Some(v) => ("answered", Some(v), String::new()),
None => ("did_not_enumerate", None, String::new()),
Expand All @@ -40,7 +42,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to
crate::inference::kv_cache_plan::record_engine_quantized_kv_support(support); // None = unanswered: the backend table decides
// This binary's entry alone, written whole: what it said, or that it did not answer.
let outcome_of_probe = match matches!(outcome, "answered" | "did_not_enumerate") {
true => super::genome::ProbeOutcome::Answered { train_dir },
true => super::genome::ProbeOutcome::Answered { train_dir, minds },
false => super::genome::ProbeOutcome::Unanswered,
};
super::genome::ENGINE_PROBES.lock().insert(bin.to_owned(), outcome_of_probe);
Expand Down
7 changes: 5 additions & 2 deletions core/continuum-engine/src/inference/llama_server/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,9 @@ impl LlamaServerProcess {
max_ubatch: target.model.serving.max_ubatch,
reasoning_budget: target.model.serving.reasoning_budget,
});
let mut invocation = super::shared_pool::on_shared_pool(invocation);
let seated = std::num::NonZeroU32::new(self.seated_minds.load(std::sync::atomic::Ordering::Relaxed));
let minds = seated.filter(|_| super::genome::engine_accepts_minds(&bin));
let mut invocation = super::shared_pool::on_shared_pool(invocation, minds);
// MoE glass-box env seam (#278): when expert paging is active, the DAEMON
// hands the fork its capture + plan file locations. Previously these envs
// existed only when an operator hand-exported them before booting the
Expand Down Expand Up @@ -492,7 +494,8 @@ impl LlamaServerProcess {
let ambiguous_adapter = lora_paths
.iter()
.any(|p| p.to_str().is_none_or(|p| p.contains(',')));
let local_inputs = if !cfg!(windows) || engine_install.is_none() {
// the receipt is made only where the engine contract exists (`EngineInstallReceipt::load`): none elsewhere
let local_inputs = if engine_install.is_none() {
Err(
"exact restoration requires original Windows application and local input pins"
.into(),
Expand Down
5 changes: 5 additions & 0 deletions core/continuum-engine/src/inference/llama_server/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ pub struct LlamaServerProcess {
/// what the running process was given, read by the serving daemon into the
/// snapshot — never the plan's latest derivation of what it would give.
pub(super) launched_prompt_cache_mib: std::sync::atomic::AtomicU32,
/// Resident minds the next launch keeps beside its lanes as parked sequences (`--minds`, fork #139), seated
/// by the serving daemon ([`super::LlamaServerControl::seat_minds`]). 0: none (every ephemeral lane).
pub(super) seated_minds: std::sync::atomic::AtomicU32,
}


Expand Down Expand Up @@ -160,6 +163,7 @@ impl LlamaServerProcess {
smoke_proven_thinking: std::sync::atomic::AtomicBool::new(false),
mmproj_on_lane: std::sync::atomic::AtomicU8::new(0),
launched_prompt_cache_mib: std::sync::atomic::AtomicU32::new(0),
seated_minds: std::sync::atomic::AtomicU32::new(0),
}
}

Expand Down Expand Up @@ -198,6 +202,7 @@ impl LlamaServerProcess {
smoke_proven_thinking: std::sync::atomic::AtomicBool::new(false),
mmproj_on_lane: std::sync::atomic::AtomicU8::new(0),
launched_prompt_cache_mib: std::sync::atomic::AtomicU32::new(0),
seated_minds: std::sync::atomic::AtomicU32::new(0),
}
}

Expand Down
13 changes: 11 additions & 2 deletions core/continuum-engine/src/inference/llama_server/shared_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,20 @@ const SHARED_POOL_SHORT: &str = "-kvu";
/// tokens, Aris 20,962 at 38 tok/s, Aiko 62,026), while back-to-back turns reused 28-38k each.
const KEEP_IDLE_SLOTS: &str = "--no-cache-idle-slots";

/// The engine's resident minds beside its lanes (fork #139): each a parked sequence of the pool, so a
/// mind switch is a sequence move in milliseconds (parked) or through flash, never a serialization.
const RESIDENT_MINDS: &str = "--minds";

/// Launch on the shared pool: every sequence draws on all of `-c`, and an idle one keeps what
/// she holds until the core pages her.
pub(super) fn on_shared_pool(mut invocation: LaneInvocation) -> LaneInvocation {
/// she holds until the core pages her. `minds`: parked sequence ids beside the lanes, given only to an engine
/// that lists `--minds`: the seated minds plus one side sequence for learning (`LlamaServerControl::seat_minds`).
pub(super) fn on_shared_pool(mut invocation: LaneInvocation, minds: Option<std::num::NonZeroU32>) -> LaneInvocation {
invocation.args.push(SHARED_POOL.to_string());
invocation.args.push(KEEP_IDLE_SLOTS.to_string());
if let Some(n) = minds {
invocation.args.push(RESIDENT_MINDS.to_string());
invocation.args.push(n.to_string());
}
invocation
}

Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/llama_server/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ impl LlamaServerControl for FakeControl {
allocated_tokens: u64::from(self.served_window.saturating_mul(lanes)),
max_tokens_per_sequence: u64::from(self.served_window),
sequence_capacity: u64::from(lanes),
resident_minds: None,
})
}
async fn served_lanes(&self) -> Result<u32, LlamaServerError> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,10 @@ fn the_engine_launches_on_one_shared_pool() {
Path::new("fixture.gguf"), planned.model_id(), "127.0.0.1", 1,
planned.parallel_lanes(), planned.served_total_ctx(),
planned.host_prompt_cache_mib, Path::new("pages"),
));
), std::num::NonZeroU32::new(planned.parallel_lanes()));
assert_eq!(invocation.value_of("-c"), Some("290560"));
assert_eq!(invocation.value_of("--parallel"), Some("5"));
// what this catches: a mind switch serialized through the prompt cache because the engine had no parked ids
assert_eq!(invocation.value_of("--minds"), Some("5"), "an engine that lists --minds keeps one parked id per lane");
assert_eq!(super::super::shared_pool::pool_launch(&invocation.args), super::super::PoolLaunch::Shared, "the launch and the read-back agree");
}
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ fn an_adopted_engines_report_reads_back_as_the_genes_it_holds() {
#[test]
fn a_train_dir_answer_is_about_the_binary_asked_and_no_other() {
let probes = std::collections::BTreeMap::from([
("/slots/engine-a/llama-server".to_string(), ProbeOutcome::Answered { train_dir: true }),
("/slots/engine-a/llama-server".to_string(), ProbeOutcome::Answered { train_dir: true, minds: false }),
("/slots/engine-b/llama-server".to_string(), ProbeOutcome::Unanswered),
]);
assert_eq!(answer_for(&probes, "/slots/engine-a/llama-server"), Some(true));
Expand All @@ -394,8 +394,8 @@ fn a_train_dir_answer_is_about_the_binary_asked_and_no_other() {
#[test]
fn an_in_place_decision_rests_only_on_an_answer() {
let probes = std::collections::BTreeMap::from([
("answered-yes".to_string(), ProbeOutcome::Answered { train_dir: true }),
("answered-no".to_string(), ProbeOutcome::Answered { train_dir: false }),
("answered-yes".to_string(), ProbeOutcome::Answered { train_dir: true, minds: false }),
("answered-no".to_string(), ProbeOutcome::Answered { train_dir: false, minds: false }),
("timed-out".to_string(), ProbeOutcome::Unanswered),
]);
assert_eq!(train_dir_known(&probes, "answered-yes"), Some(true));
Expand Down
28 changes: 28 additions & 0 deletions core/continuum-engine/src/inference/minds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//! Resident minds on the engine (fork #139): a mind switch is a sequence move, never a serialization.
//!
//! An engine that declares `resident_minds` on `/props` keeps every mind it serves as a sequence of its unified
//! KV pool (parked when another mind holds the lane) or, when the pool needs her cells, as a page on flash it maps
//! back in. A turn names its mind (`"page"`, [`super::slots::PageKey::engine_id`]) so the engine moves the right
//! sequence; and while she waits for a lane her state streams in, the way a game engine streams what the camera
//! needs next, so her switch is the sub-millisecond sequence move.

use super::slots::PageKey;
use super::weight_residency::ResidentMinds;

/// Bring `key`'s mind into the pool of the engine at `root` (`POST /minds/prefetch`), carrying the incarnation
/// token that engine declared (`minds`), so a replaced engine refuses it. The turn waiting for a lane owns this
/// future: admitted, or cancelled, it is dropped with her wait; it never runs for a turn that did not wait.
pub(crate) async fn prefetch(client: &reqwest::Client, root: &str, minds: ResidentMinds, key: PageKey) {
let url = format!("{}/minds/prefetch", root.trim_end_matches('/'));
let body = serde_json::json!({ "page": key.engine_id().simple().to_string(), "incarnation": minds.incarnation });
let outcome = match client.post(&url).json(&body).send().await {
Ok(response) => response.status().as_u16().to_string(),
Err(e) => e.to_string(),
};
continuum_base::probe!(
class = "inference.minds.prefetch",
page = %key,
outcome = outcome.as_str(),
"her state streamed in while she waited for a lane (the engine's reply names where she is)"
);
}
1 change: 1 addition & 0 deletions core/continuum-engine/src/inference/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub mod handle_store;
pub mod kv_cache_plan;
pub mod kv_quant;
pub mod lane_args;
pub mod minds;
pub mod lane_demand;
pub mod lane_health;
pub mod lane_send;
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-engine/src/inference/slots/citizen_slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ pub struct KvSlotPool {
/// one it verified (`slots/discover.rs`), with or without a page ledger: the identity every
/// endpoint admission on this pool is bound to (`EndpointAdmission::incarnation`).
pub(super) incarnation: std::sync::OnceLock<(u32, u64)>,
/// The engine's resident minds (fork #139) as its `/props` declared them, recorded ONCE: by discovery when it
/// installs the pool, or by the first discovery of a pool an owned spawn published (a spawn knows its launch
/// contract, not the engine's declaration). Unset means not yet declared, never "no minds".
pub(super) resident_minds: std::sync::OnceLock<Option<crate::inference::weight_residency::ResidentMinds>>,
/// Numbers each change of [`Self::saved`] for the ledger, so a write taken outside the
/// lock never replaces a newer one ([`Self::ledger_snapshot`]).
pub(super) ledger_generation: AtomicU64,
Expand Down
14 changes: 12 additions & 2 deletions core/continuum-engine/src/inference/slots/discover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ pub enum PoolDiscoveryMiss {
/// The pool already installed for this server disagrees with what `/props` reports.
#[error("installed pool has {installed} slots, props reports {props}")]
GeometryMismatch { installed: u32, props: u32 },
/// The installed pool's resident-minds declaration (or its incarnation token) is not this `/props`'s.
#[error("installed pool's resident minds disagree with props")]
MindsMismatch,
/// The page-admission negotiation refused this pool.
#[error("page admission refused this pool")]
PageAdmissionRefused,
Expand Down Expand Up @@ -71,6 +74,7 @@ impl PoolDiscoveryMiss {
Self::NoGeometry => "no_geometry",
Self::Superseded => "superseded",
Self::GeometryMismatch { .. } => "geometry_mismatch",
Self::MindsMismatch => "minds_mismatch",
Self::PageAdmissionRefused => "page_admission_refused",
}
}
Expand Down Expand Up @@ -197,13 +201,18 @@ impl SlotDirectory {
// The directory arbitrates the probe race: only the first writer installs the pool, once
// per SERVER, and it installs it with its page store already settled. A pool known here
// was published by that writer, so no caller ever admits against an undecided store.
// whether this engine owns mind switches, declared in the same body (never inferred from a 404)
let minds = crate::inference::weight_residency::ContextGeometry::from_props(&body).and_then(|g| g.resident_minds);
let pool = match existing_pool {
Some(pool) => pool,
None => self.install_settled_pool(root, n_slots, |pool| settle_adopted_page_store(pool, root)),
None => self.install_settled_pool(root, n_slots, minds, |pool| settle_adopted_page_store(pool, root)),
};
if pool.n_slots() != n_slots {
return Err(Miss::GeometryMismatch { installed: pool.n_slots(), props: n_slots }); // they must agree
}
if !pool.declare_resident_minds(minds) {
return Err(Miss::MindsMismatch); // the installed pool's paging authority belongs to another engine
}
if !self.negotiate_page_admission(root, &pool, discovery_generation, body.get("slot_save_size_version")).await {
return Err(Miss::PageAdmissionRefused);
}
Expand All @@ -229,9 +238,10 @@ impl SlotDirectory {
&self,
root: &str,
n_slots: u32,
minds: Option<crate::inference::weight_residency::ResidentMinds>,
settle: impl FnOnce(&KvSlotPool) -> SettledPageStore,
) -> Arc<KvSlotPool> {
let candidate = Arc::new(KvSlotPool::new(root, n_slots));
let candidate = Arc::new(KvSlotPool::new(root, n_slots).with_resident_minds(minds));
let settled = settle(&candidate);
let pool = self.install_pool(root, || Arc::clone(&candidate));
if Arc::ptr_eq(&pool, &candidate) {
Expand Down
Loading
Loading