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
16 changes: 14 additions & 2 deletions core/continuum-engine/src/inference/backends/persona_scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@
//! synchronous today), and paging cold minds out of RAM.

mod driver;
mod geometry;
mod sampling;

pub use geometry::{EngineGeometry, EngineState, Incarnation, Requested};

use std::sync::Arc;

use llama::{FlashAttn, KvCacheType, LoraAdapter, Model};
Expand Down Expand Up @@ -72,17 +75,26 @@ pub struct SchedulerConfig {
#[derive(Clone)]
pub struct Scheduler {
request_tx: std::sync::mpsc::Sender<GenerationRequest>,
state: tokio::sync::watch::Receiver<EngineState>,
}

impl Scheduler {
/// Spawn the driver thread. It runs until the last handle is dropped and its last turn ended.
pub fn spawn(model: Arc<Model>, config: SchedulerConfig) -> Result<Self, SchedulerError> {
let (request_tx, request_rx) = std::sync::mpsc::channel();
let incarnation = Incarnation::next();
let (state_tx, state) = tokio::sync::watch::channel(EngineState::Starting(incarnation));
std::thread::Builder::new()
.name("persona-scheduler".to_string())
.spawn(move || driver::run(&model, &config, &request_rx))
.spawn(move || driver::run(&model, &config, driver::Start { incarnation, state: state_tx, requests: request_rx }))
.map_err(|spawn| SchedulerError::Spawn(Arc::new(spawn)))?;
Ok(Self { request_tx })
Ok(Self { request_tx, state })
}

/// The engine as it is: starting, the geometry its context applied, or why it was refused. The
/// one place serving reads the window, the batch and the KV layout from.
pub fn state(&self) -> tokio::sync::watch::Receiver<EngineState> {
self.state.clone()
}

/// Enqueue a turn. Refused once the driver thread has exited.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use continuum_persona_llama::{Genes, Step, UnifiedTier, STREAMS};
use llama::{ContextParams, LoraAdapter, Model};
use uuid::Uuid;

use super::{sampling, GenerationRequest, SchedulerConfig, TokenEvent};
use super::geometry::StopsOnExit;
use super::{sampling, EngineGeometry, EngineState, GenerationRequest, Incarnation, SchedulerConfig, TokenEvent};
use crate::inference::footprint_registry::{self, FootprintKey, ResourceType};
use crate::inference::kv_quant::Residency;
use crate::runtime;
Expand Down Expand Up @@ -86,29 +87,47 @@ struct Driver<'c, 'm> {
parked: HashMap<PersonaId, Mind>,
}

/// What the driver thread starts with: the incarnation it serves as, where it publishes what the engine
/// is, and its one queue.
pub(super) struct Start {
pub(super) incarnation: Incarnation,
pub(super) state: tokio::sync::watch::Sender<EngineState>,
pub(super) requests: Receiver<GenerationRequest>,
}

/// Run until every handle is dropped.
pub(super) fn run(model: &Model, config: &SchedulerConfig, requests: &Receiver<GenerationRequest>) {
pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) {
let log = runtime::logger("persona-scheduler");
let Start { incarnation, state, requests } = start;
// However this thread ends (its last handle dropped, an early return, or a panic unwinding it),
// a Starting or Ready it leaves becomes Stopped: serving never grants turns to a gone engine.
let _stops = StopsOnExit { state: &state, incarnation };
let refuse = |refused: &StartError| {
log.error(&refused.to_string());
state.send_replace(EngineState::Refused { incarnation, reason: refused.to_string().into() });
};
let mut ctx = match context(model, config) {
Ok(ctx) => ctx,
Err(refused) => {
log.error(&refused.to_string());
for req in requests {
refuse(&refused);
for req in &requests {
let _ = req.response_tx.send(TokenEvent::Error(refused.to_string()));
}
return;
}
};
let Some(batch) = usize::try_from(config.n_batch).ok().and_then(NonZeroUsize::new) else {
log.error(&StartError::ZeroBatch.to_string());
for req in requests {
let Some(batch) = usize::try_from(ctx.n_batch()).ok().and_then(NonZeroUsize::new) else {
refuse(&StartError::ZeroBatch);
for req in &requests {
let _ = req.response_tx.send(TokenEvent::Error(StartError::ZeroBatch.to_string()));
}
return;
};
log.info(&format!("persona scheduler ready (n_ctx={}, streams={STREAMS}, one mind decodes at a time)", config.n_ctx));
let geometry = EngineGeometry::applied(incarnation, &ctx, config);
log.info(&format!("persona scheduler ready: {geometry:?} (one mind decodes at a time)"));
state.send_replace(EngineState::Ready(geometry));
let mut driver = Driver { model, batch, engine: PersonaEngine::new(UnifiedTier::new(&mut ctx)), parked: HashMap::new() };
for req in requests {
for req in &requests {
let respond = req.response_tx.clone();
let event = match driver.serve(req) {
Ok(done) => done,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//! What the engine actually is, read from the context it created (never from what was asked): the
//! one owner serving reads for the window, the batch and the sequence layout. Each snapshot names
//! the engine incarnation it was read from, so a reader retires a stale observation instead of
//! acting on an engine that is gone, and a driver that exits (or panics) says so.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use llama::{FlashAttn, KvCacheType};

use super::SchedulerConfig;

/// Which engine a snapshot came from: one per scheduler spawn in this process, rising.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Incarnation(u64);

impl Incarnation {
pub(super) fn next() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(1);
Self(NEXT.fetch_add(1, Ordering::Relaxed))
}

pub fn get(self) -> u64 {
self.0
}
}

/// Settings the context was ASKED for that llama.cpp does not report back: flash attention may be
/// `Auto` (resolved natively per backend), and the KV types are requests. Never read as applied
/// capability.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Requested {
pub type_k: KvCacheType,
pub type_v: KvCacheType,
pub flash_attn: FlashAttn,
}

/// The applied geometry of one engine, as llama.cpp reports it from the created context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EngineGeometry {
pub incarnation: Incarnation,
/// The window the context holds, across every sequence.
pub n_ctx: u32,
/// The window ONE mind may use: what serving publishes as her usable context.
pub n_ctx_seq: u32,
/// Sequences the context holds: the decoding mind's and the staged ones.
pub n_seq_max: u32,
pub n_batch: u32,
pub n_ubatch: u32,
/// Minds that decode at once: always one (one mind decodes at a time).
pub decoding: u32,
/// Sequences held beside the decoding one for the next mind, staged as data, never decoding.
pub staging: u32,
pub requested: Requested,
}

impl EngineGeometry {
/// Read from the created context; only what it cannot report comes from the request.
pub(super) fn applied(incarnation: Incarnation, ctx: &llama::Context<'_>, config: &SchedulerConfig) -> Self {
let n_seq_max = ctx.n_seq_max();
Self {
incarnation,
n_ctx: ctx.n_ctx(),
n_ctx_seq: ctx.n_ctx_seq(),
n_seq_max,
n_batch: ctx.n_batch(),
n_ubatch: ctx.n_ubatch(),
decoding: 1,
staging: n_seq_max.saturating_sub(1),
requested: Requested { type_k: config.type_k, type_v: config.type_v, flash_attn: config.flash_attn },
}
}
}

/// The engine as serving sees it.
#[derive(Debug, Clone)]
pub enum EngineState {
/// Spawned; its context is not made yet.
Starting(Incarnation),
/// Its context is made: this is what it is.
Ready(EngineGeometry),
/// Its context was refused; no turn runs on this incarnation.
Refused { incarnation: Incarnation, reason: Arc<str> },
/// Its driver has exited (its last handle dropped, or a panic unwound it): no turn runs on this
/// incarnation, and nothing it published before is current.
Stopped(Incarnation),
}

impl EngineState {
pub fn incarnation(&self) -> Incarnation {
match self {
Self::Starting(incarnation) | Self::Refused { incarnation, .. } | Self::Stopped(incarnation) => *incarnation,
Self::Ready(geometry) => geometry.incarnation,
}
}

/// The geometry, only while the engine is serving.
pub fn ready(&self) -> Option<&EngineGeometry> {
match self {
Self::Ready(geometry) => Some(geometry),
Self::Starting(_) | Self::Refused { .. } | Self::Stopped(_) => None,
}
}
}

/// Owned by the driver thread: when it exits by any path, including a panic unwinding it, a
/// `Starting` or `Ready` it left behind becomes `Stopped`. A `Refused` keeps its reason.
pub(super) struct StopsOnExit<'s> {
pub(super) state: &'s tokio::sync::watch::Sender<EngineState>,
pub(super) incarnation: Incarnation,
}

impl Drop for StopsOnExit<'_> {
fn drop(&mut self) {
let incarnation = self.incarnation;
self.state.send_if_modified(|state| match state {
EngineState::Starting(_) | EngineState::Ready(_) => {
*state = EngineState::Stopped(incarnation);
true
}
EngineState::Refused { .. } | EngineState::Stopped(_) => false,
});
}
}

#[cfg(test)]
mod tests {
use super::*;

// what this catches: two engines in one process sharing an incarnation, so serving cannot tell
// a snapshot of the engine that is gone from one of the engine that replaced it.
#[test]
fn each_engine_spawn_is_a_later_incarnation() {
let first = Incarnation::next();
let second = Incarnation::next();
assert!(second > first);
assert_eq!(EngineState::Starting(second).incarnation(), second);
}

// what this catches (Codex on #6150): a driver that exited or panicked leaving its last Ready
// in the watch, so serving grants turns to an engine that is gone; and a Refused reason
// overwritten on the way out.
#[test]
fn an_exiting_driver_leaves_stopped_never_a_stale_ready_and_keeps_a_refusal() {
let incarnation = Incarnation::next();
let (state, seen) = tokio::sync::watch::channel(EngineState::Starting(incarnation));
drop(StopsOnExit { state: &state, incarnation });
assert!(matches!(*seen.borrow(), EngineState::Stopped(i) if i == incarnation));
assert!(seen.borrow().ready().is_none());

let reason: Arc<str> = "the context was refused".into();
state.send_replace(EngineState::Refused { incarnation, reason });
drop(StopsOnExit { state: &state, incarnation });
assert!(matches!(&*seen.borrow(), EngineState::Refused { reason, .. } if &**reason == "the context was refused"));

// A panic unwinding the driver drops the guard the same way.
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
state.send_replace(EngineState::Starting(incarnation));
let _stops = StopsOnExit { state: &state, incarnation };
panic!("the driver failed");
}));
assert!(panicked.is_err());
assert!(matches!(*seen.borrow(), EngineState::Stopped(_)));
}
}
20 changes: 20 additions & 0 deletions core/llama/src/safe/expert_eval_cb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ impl<'m> Context<'m> {
unsafe { sys::llama_n_ctx(self.ptr.as_ptr()) }
}

/// The logical batch the context was created with (llama.cpp may clamp what was asked).
pub fn n_batch(&self) -> u32 {
unsafe { sys::llama_n_batch(self.ptr.as_ptr()) }
}

/// The physical micro-batch the context was created with.
pub fn n_ubatch(&self) -> u32 {
unsafe { sys::llama_n_ubatch(self.ptr.as_ptr()) }
}

/// The window one sequence may use, as the context applied it.
pub fn n_ctx_seq(&self) -> u32 {
unsafe { sys::llama_n_ctx_seq(self.ptr.as_ptr()) }
}

/// The sequences the context holds.
pub fn n_seq_max(&self) -> u32 {
unsafe { sys::llama_n_seq_max(self.ptr.as_ptr()) }
}

/// Bytes llama.cpp has actually committed to the KV cache for the given
/// sequence id. The honest source of truth for per-seq KV size — works
/// across any model architecture (uniform attention, hybrid attention+SSM
Expand Down
Loading