diff --git a/Cargo.lock b/Cargo.lock index a26ed6fe52..875f19a3be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3109,6 +3109,8 @@ dependencies = [ "continuum-cli-lifecycle", "continuum-host", "continuum-kernel", + "continuum-persona-engine", + "continuum-persona-llama", "continuum-process", "continuum-saved-state", "continuum-service", diff --git a/core/continuum-core/Cargo.toml b/core/continuum-core/Cargo.toml index b66b66a645..0ea1823e4e 100644 --- a/core/continuum-core/Cargo.toml +++ b/core/continuum-core/Cargo.toml @@ -377,12 +377,6 @@ vulkan = ["llama/vulkan", "continuum-kernel/vulkan", "continuum-engine/vulkan", rocm = ["ort/rocm", "continuum-engine/rocm"] directml = ["ort/directml", "continuum-engine/directml"] openvino = ["ort/openvino", "continuum-engine/openvino"] -# MLX — Apple Silicon native inference path (phases A–E of continuum#897). -# Only compiles on macOS/aarch64; the adapter module is guarded by this feature -# AND by cfg(target_os = "macos") so non-Mac targets simply don't see the code. -# Phase A: flag only, no mlx-rs dep yet. Phase B will add `dep:mlx-rs` back -# once we're writing forward() and can ensure full Xcode is installed. -mlx = ["continuum-engine/mlx"] accelerate = ["candle-core/accelerate", "candle-nn/accelerate", "candle-transformers/accelerate"] # Linux: swap ORT from static (download-binaries) to dynamic loading. # Avoids protobuf symbol conflict with webrtc-sys. macOS uses static (default). diff --git a/core/continuum-engine/Cargo.toml b/core/continuum-engine/Cargo.toml index 03ff4e8c1c..a3c4970abd 100644 --- a/core/continuum-engine/Cargo.toml +++ b/core/continuum-engine/Cargo.toml @@ -5,6 +5,8 @@ edition = "2021" publish = false [dependencies] +continuum-persona-engine = { path = "../continuum-persona-engine" } +continuum-persona-llama = { path = "../continuum-persona-llama" } continuum-process = { path = "../continuum-process" } tempfile = { workspace = true, optional = true } continuum-kernel = { path = "../continuum-kernel" } @@ -83,7 +85,6 @@ coreml = [] cuda = ["candle-core/cuda", "candle-nn/cuda", "candle-transformers/cuda", "llama/cuda", "ort/cuda", "continuum-kernel/cuda"] directml = ["ort/directml"] metal = ["candle-core/metal", "candle-nn/metal", "candle-transformers/metal", "llama/metal", "ort/coreml"] -mlx = [] openvino = ["ort/openvino"] rocm = ["ort/rocm"] test-fixtures = ["continuum-kernel/test-fixtures", "dep:tempfile"] diff --git a/core/continuum-engine/src/inference/backends/llamacpp.rs b/core/continuum-engine/src/inference/backends/llamacpp.rs index 98ab135fa1..513a2a77c7 100644 --- a/core/continuum-engine/src/inference/backends/llamacpp.rs +++ b/core/continuum-engine/src/inference/backends/llamacpp.rs @@ -4,17 +4,10 @@ //! platform-specific features (metal/cuda). This backend is the adapter //! between Continuum's TextGenerationRequest pipeline and the safe Rust API. //! -//! Architecture: ONE shared `Context` driven by a continuous-batching -//! scheduler (see `llamacpp_scheduler`). Each `generate()` call enqueues a -//! request that becomes one sequence (`seq_id`) in the shared batch. -//! Multiple sequences advance per decode step — weights are read once, -//! used for N sequences at once. This replaces the prior per-call-context -//! design where N concurrent generations created N independent contexts -//! that fought for memory bandwidth (each got ~1/N throughput). -//! -//! Measured 67.8 tok/s on M5 Metal with forged Qwen3.5 Q4_K_M (single seq -//! bench). With continuous batching across 3 seqs the per-stream cost -//! drops only ~10% rather than dividing by 3. +//! Architecture: ONE `Context` driven by the persona scheduler (see `persona_scheduler`): one mind +//! decodes at a time, each persona keeps her blocks between turns, and a turn prefills only what her +//! blocks do not hold. A switch is the persona engine's native bind. Measured on the M5: four minds +//! decoding at once ran 2 tok/s each; one at a time runs at the full rate. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -23,7 +16,7 @@ use std::time::Instant; use llama::{FlashAttn, KvCacheType, LoraAdapter, Model, ModelParams}; -use super::llamacpp_scheduler::{GenerationRequest, Scheduler, SchedulerConfig, TokenEvent}; +use super::persona_scheduler::{GenerationRequest, Scheduler, SchedulerConfig, SchedulerError, TokenEvent}; use super::SamplingConfig; use crate::runtime; diff --git a/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs b/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs index cbe7662024..1436ec487d 100644 --- a/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs +++ b/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs @@ -418,15 +418,14 @@ impl LlamaCppBackend { Ok(()) } - /// Lazily spawn (or get) the scheduler. Single instance per backend — - /// owns the shared Context and the OS-thread driver loop. + /// Lazily spawn (or get) the persona scheduler. Single instance per backend: it owns the context + /// and the driver thread. Its window holds `STREAMS` minds' windows (the active mind and the next), + /// whatever sequence count the launch carried: one mind decodes at a time. pub(super) fn scheduler(&self, allocation: GenerationAllocation) -> Result<&Scheduler, String> { - let per_seq = self.effective_context_length(allocation)?; - if self.config.n_seq_max == 0 { - return Err("generation requires a nonzero sequence allocation".into()); - } - let total_n_ctx = per_seq - .checked_mul(self.config.n_seq_max) + let per_mind = self.effective_context_length(allocation)?; + let streams = u32::try_from(continuum_persona_llama::STREAMS).map_err(|_| "stream count exceeds native representation")?; + let total_n_ctx = per_mind + .checked_mul(streams) .ok_or("context allocation exceeds native representation")?; let (bound, scheduler) = self.scheduler.get_or_init(|| { ( @@ -437,7 +436,6 @@ impl LlamaCppBackend { n_ctx: total_n_ctx, n_batch: self.config.n_batch, n_ubatch: self.config.n_ubatch, - n_seq_max: self.config.n_seq_max, flash_attn: self.config.flash_attn, fused_gdn_ar: self.config.fused_gdn_ar, fused_gdn_ch: self.config.fused_gdn_ch, @@ -452,14 +450,15 @@ impl LlamaCppBackend { "scheduler allocation changed; release the existing backend before resizing".into(), ); } - Ok(scheduler) + match scheduler { + Ok(scheduler) => Ok(scheduler), + Err(refused) => Err(refused.to_string()), + } } - /// Generate text. Routes through the continuous-batching scheduler: - /// the request becomes one sequence in the shared batch and tokens - /// stream back as they're sampled. Multiple concurrent generate() - /// calls share the single Context — weights are read once per decode - /// step and used to advance every active sequence in parallel. + /// Generate text through the persona scheduler: the turn continues her mind (one decodes at a + /// time, the next waits its turn) and tokens stream back as they are sampled. Concurrent + /// generate() calls are served one after another on the one context. /// /// `active_loras` is `(id, scale)` pairs naming genes previously paged /// in via [`ensure_adapter`]. They are resolved to live adapter handles @@ -560,7 +559,9 @@ impl LlamaCppBackend { persona_id, }; - self.scheduler(allocation)?.enqueue(req)?; + if let Err(refused) = self.scheduler(allocation)?.enqueue(req) { + return Err(refused.to_string()); + } // Collect tokens from the channel until Done/Error. We're called // synchronously from spawn_blocking by CandleAdapter — block_in_place diff --git a/core/continuum-engine/src/inference/backends/llamacpp/validate_embedding_model.rs b/core/continuum-engine/src/inference/backends/llamacpp/validate_embedding_model.rs index cd8f2361d7..fb8ebc8c47 100644 --- a/core/continuum-engine/src/inference/backends/llamacpp/validate_embedding_model.rs +++ b/core/continuum-engine/src/inference/backends/llamacpp/validate_embedding_model.rs @@ -233,14 +233,12 @@ impl ModelCapabilities { /// The backend: owns a `Model` plus a continuous-batching `Scheduler`. /// /// Models are Send+Sync (read-only after load). The scheduler owns the -/// shared Context (n_seq_max sequences, single OS-thread driver loop) -/// and is the only place llama.cpp decode happens. Generate calls -/// enqueue requests and stream tokens back over channels — there's no -/// per-call context creation, no Rust-side semaphore. +/// context (two execution streams, one OS-thread driver loop; see `persona_scheduler`) and is the +/// only place llama.cpp decode happens. Generate calls enqueue turns and stream tokens back over +/// channels; one mind decodes at a time. /// -/// LoRAs are loaded into `loras` for genome paging, but per-request LoRA -/// activation is a v2 follow-up — the scheduler currently ignores -/// `active_loras` (see `llamacpp_scheduler` module docs). +/// LoRAs are loaded into `loras` for genome paging; a turn's genes are applied for her decodes +/// when she is bound. pub struct LlamaCppBackend { /// One temporary embedding context is admitted per loaded model. pub(super) embedding_lane: super::embedding_lane::EmbeddingLane, @@ -258,7 +256,7 @@ pub struct LlamaCppBackend { pub(super) caps: ModelCapabilities, /// Lazy-spawned scheduler. Lives behind OnceLock because spawning /// touches the Model Arc and we want a single instance per backend. - pub(super) scheduler: OnceLock<(GenerationAllocation, Scheduler)>, + pub(super) scheduler: OnceLock<(GenerationAllocation, Result)>, /// Lazy-loaded multimodal projector. Built on first `generate_with_image` /// call from `config.mmproj_path` (so text-only backends pay zero cost). /// Sits behind a Mutex> so concurrent first-call requests diff --git a/core/continuum-engine/src/inference/backends/llamacpp_scheduler.rs b/core/continuum-engine/src/inference/backends/llamacpp_scheduler.rs deleted file mode 100644 index cbbca1fa22..0000000000 --- a/core/continuum-engine/src/inference/backends/llamacpp_scheduler.rs +++ /dev/null @@ -1,776 +0,0 @@ -//! Continuous-batching scheduler for llama.cpp. -//! -//! Owns a single `Context` with `n_seq_max = N` and runs a dedicated OS -//! thread that drives one decode call per loop iteration, advancing every -//! active sequence in parallel within that single decode. Replaces the -//! old per-call-context + Rust-side semaphore design where N concurrent -//! generations created N independent contexts that fought for memory -//! bandwidth. -//! -//! Why this is the right shape: -//! - Inference is memory-bound — for each generated token, the model's -//! weights have to traverse memory once. Independent contexts each -//! re-read the weights, splitting bandwidth N ways. A shared context -//! reads the weights ONCE per decode step and uses them to advance -//! N sequences in parallel via batched matmul (cheap on GPU). -//! - llama.cpp natively supports this via `llama_batch` with multiple -//! `seq_id` values per token. Setting `n_seq_max=1` (the prior fix -//! that worked around the "memory slot" bug) was explicitly -//! constraining us out of the right architecture. -//! -//! Design: -//! - `Scheduler::enqueue(req)` sends a `GenerationRequest` to the driver -//! thread via std::sync::mpsc. -//! - The request carries a `tokio::sync::mpsc::UnboundedSender` -//! that streams tokens back to the caller as they're sampled. -//! - The driver loop assigns a free `seq_id` (0..n_seq_max), prefills the -//! prompt in chunks (interleaved with other seqs' generation), then -//! transitions to generating; each loop iteration emits one token per -//! active generating seq. -//! - When EOG / max_tokens / stop-sequence hits, the seq is closed: -//! `Done` event sent, `memory_seq_rm` frees the KV slot, seq_id -//! returned to free pool. -//! -//! LoRA / genome paging: -//! - Each request carries resolved gene handles (`active_loras`). The driver -//! applies them **context-level** via `Context::set_loras` right before -//! `decode`. The shared context applies one gene set per decode, so the -//! batch builder enforces a **homogeneity gate**: a decode batch adopts the -//! gene set of the lowest-seq_id seq with work, and seqs wanting a different -//! set are deferred to a later iteration. A seq is therefore only ever -//! decoded under its own gene — its entire KV history stays consistent, and -//! we never silently decode under the wrong adapter (Rule 2). Same-gene -//! seqs still co-batch (the eval, and the single-gene-per-machine common -//! case); mixed-gene load serializes by group rather than corrupting. -//! - True per-seq LoRA mixing within one decode (distinct genes co-batched) -//! is a future optimization; correctness here does not depend on it. -//! - Stop-sequence trimming happens in the caller (we still emit the -//! stop sequence's tokens before signaling Done) — same as the prior -//! per-call generate. - -use std::collections::HashMap; -use std::sync::Arc; -use std::time::Instant; - -use llama::{Batch, ContextParams, FlashAttn, KvCacheType, LoraAdapter, Model, Sampler}; -use uuid::Uuid; - -use crate::inference::footprint_registry::{self, FootprintKey, ResourceType}; -use crate::inference::kv_quant::Residency; -use crate::runtime; - -use super::SamplingConfig; - -/// Token event streamed from the scheduler to the requester. -#[derive(Debug)] -pub enum TokenEvent { - /// One generated token piece (UTF-8 fragment from llama tokenizer). - Token(String), - /// Generation finished cleanly (EOG / max_tokens / stop sequence). - Done { - tokens_generated: usize, - elapsed_ms: u64, - }, - /// Generation failed — decode error, batch overflow, etc. - Error(String), -} - -/// What a caller submits to the scheduler. -pub struct GenerationRequest { - pub prompt: String, - pub max_tokens: usize, - pub sampling: SamplingConfig, - pub stop_sequences: Vec, - /// Genes to apply for this generation: `(id, handle, scale)`. Resolved to - /// live adapter handles by the backend before enqueue (the scheduler - /// thread can't lock the backend's cache). `id` is kept for the - /// homogeneity signature; the `Arc` keeps the adapter alive for this - /// seq's lifetime even across a cache eviction. Empty = base model. - pub active_loras: Vec<(String, Arc, f32)>, - /// Tokens stream back through this. Use `tokio::sync::mpsc::unbounded_channel()`. - pub response_tx: tokio::sync::mpsc::UnboundedSender, - /// Persona that owns this generation — flows down from - /// `TextGenerationRequest::persona_id` so the scheduler can attribute - /// the seq slot's KV bytes to the right persona in the global - /// FootprintRegistry. None = no attribution (test rigs, ad-hoc - /// probes); production paths set this. Kept as `Uuid` here (not - /// `Option` like the wire format) because parsing happens at - /// the adapter boundary — the scheduler always sees a typed value. - pub persona_id: Option, -} - -/// Scheduler config — sized at construction. -#[derive(Debug, Clone)] -pub struct SchedulerConfig { - pub n_ctx: u32, - pub n_batch: u32, - pub n_ubatch: u32, - pub n_seq_max: u32, - /// Flash attention. Default `Auto` lets llama.cpp pick per-backend; on - /// Metal with supported head dims (qwen3.5-4b's 256 qualifies) it turns - /// on. Helps prefill more than single-token decode but cheap to enable. - pub flash_attn: FlashAttn, - pub fused_gdn_ar: bool, - pub fused_gdn_ch: bool, - /// KV cache K element type. `F16` lossless / `Q8_0` halves K memory. - pub type_k: KvCacheType, - /// KV cache V element type. `F16` lossless / `Q8_0` halves V memory. - /// V is more sensitive to quantization than K — keep F16 unless RAM - /// is tight. - pub type_v: KvCacheType, -} - -/// Public handle. Cloneable; clones share the same driver thread + context. -#[derive(Clone)] -pub struct Scheduler { - request_tx: std::sync::mpsc::Sender, -} - -impl Scheduler { - /// Spawn the driver thread and return a handle. The thread runs until - /// the last `Scheduler` clone is dropped (channel closed) AND no - /// active sequences remain. - pub fn spawn(model: Arc, config: SchedulerConfig) -> Self { - let (request_tx, request_rx) = std::sync::mpsc::channel(); - let model_for_thread = model.clone(); - let cfg = config.clone(); - std::thread::Builder::new() - .name("llamacpp-scheduler".to_string()) - .spawn(move || driver_loop(model_for_thread, cfg, request_rx)) - .expect("failed to spawn scheduler thread"); - Self { request_tx } - } - - /// Enqueue a request. Returns Err if the scheduler thread has exited. - pub fn enqueue(&self, req: GenerationRequest) -> Result<(), String> { - self.request_tx - .send(req) - .map_err(|e| format!("scheduler closed: {e}")) - } -} - -/// Per-sequence state inside the driver. -struct ActiveSeq { - seq_id: i32, - prompt_tokens: Vec, - /// How many of `prompt_tokens` have been pushed into the context KV. - prefill_pos: usize, - /// Absolute KV position to use for the NEXT pushed token (post-prefill). - gen_pos: i32, - /// Sampled-but-not-yet-pushed token from the previous iteration. None - /// while the seq is still in prefill phase. - next_token: Option, - tokens_generated: usize, - max_tokens: usize, - sampler: Sampler, - stop_sequences: Vec, - output_so_far: String, - response_tx: tokio::sync::mpsc::UnboundedSender, - started_at: Instant, - /// Persona that owns this seq slot — copied from - /// `GenerationRequest::persona_id`. Used by the registry-reporting - /// path (Piece 2 of this work) to attribute KV bytes per-persona on - /// alloc/free. None = test rig or ad-hoc probe; reporting skipped. - persona_id: Option, - /// Resolved genes `(handle, scale)` this seq decodes under. Fixed for the - /// seq's lifetime, so its KV history is always consistent with the gene - /// the driver applies when this seq is in the batch. Empty = base model. - active_loras: Vec<(Arc, f32)>, - /// Canonical signature of `active_loras` (sorted `id:scale`, comma-joined; - /// empty string = base). The homogeneity gate compares these to decide - /// which seqs co-batch under one context-level `set_loras`. - lora_sig: String, -} - -/// Per-batch-slot bookkeeping so we know which logit index to sample for -/// which seq after `decode` returns. `logit_idx` is the BATCH POSITION -/// (not a sequential want-logits counter) — `llama_get_logits_ith(idx)` -/// dereferences the i-th batch position's logits buffer and asserts that -/// `batch.logits[idx] == true`. Passing a role-counter instead of the -/// actual batch position is what caused the -/// `GGML_ASSERT(logits != nullptr)` crash on first iteration. -enum BatchRole { - /// This seq just finished its prefill in this batch. Sample to get - /// the first generation token; future generation pushes use `gen_pos`. - PrefillFinal { - seq_id: i32, - gen_pos: i32, - logit_idx: i32, - }, - /// This seq is mid-generation. Next sampled token continues from - /// position `pos_after`. - Generating { - seq_id: i32, - pos_after: i32, - logit_idx: i32, - }, -} - -fn driver_loop( - model: Arc, - config: SchedulerConfig, - request_rx: std::sync::mpsc::Receiver, -) { - let log = runtime::logger("llamacpp-scheduler"); - - let mut ctx = match model.new_context(ContextParams { - n_ctx: config.n_ctx, - n_batch: config.n_batch, - n_ubatch: config.n_ubatch, - n_seq_max: config.n_seq_max, - flash_attn: config.flash_attn, - fused_gdn_ar: config.fused_gdn_ar, - fused_gdn_ch: config.fused_gdn_ch, - type_k: config.type_k, - type_v: config.type_v, - embeddings: false, - pooling_type: llama::PoolingType::None, - // MoE expert-selection observer — None for now; the K3 serving path sets a - // LiveExpertObserver here to feed the residency PGO tally. - expert_observer: None, - }) { - Ok(c) => c, - Err(e) => { - log.error(&format!("Failed to create scheduler context: {e}")); - return; - } - }; - log.info(&format!( - "Scheduler context ready (n_ctx={}, n_batch={}, n_ubatch={}, n_seq_max={})", - config.n_ctx, config.n_batch, config.n_ubatch, config.n_seq_max - )); - - let n_batch = config.n_batch as usize; - let n_seq_max = config.n_seq_max as i32; - let mut batch = Batch::allocated(n_batch as i32, n_seq_max); - - let mut active: HashMap = HashMap::new(); - let mut free_seqs: Vec = (0..n_seq_max).collect(); - - // The gene set currently applied to the shared context (its signature). - // Starts base (""). The driver calls `set_loras`/`clear_loras` only when - // the batch's chosen group differs from this — the cheap hot-swap. - let mut current_ctx_lora_sig = String::new(); - - // Per-phase timing — answers Joel's "I am not sure I believe your results" - // about whether the GPU is actually doing work. We accumulate decode (Metal - // compute + KV update) separately from sample (logits readback + sampler - // chain on CPU + token-to-piece UTF-8 decode) so the periodic log line - // makes the bottleneck obvious. If decode_ms ≫ sample_ms the model is - // GPU-bound (good). If sample_ms is comparable or larger, sampling is the - // problem and the win is moving sampling off the decode thread or pruning - // the sampler chain. - let mut decode_total = std::time::Duration::ZERO; - let mut decode_count: u64 = 0; - // Sampling time is split into two sub-phases so the GPU sync cost is - // visible on its own. `sample_call_total` is just the `sampler.sample()` - // call — which is what forces `llama_get_logits_ith()` to wait on the - // outstanding Metal command buffer before the sampler chain reads the - // logits. `post_sample_total` is everything else (token_to_piece, - // string concat, channel send, stop-sequence scan) — which is pure CPU - // and shouldn't be measurable. - // - // Why this split matters: post-Metal-fix we observed sample_avg jump - // from 0.66ms to 20ms while decode_avg dropped from 31ms to 0.80ms. - // Hypothesis is that decode is async-dispatch and the real GPU compute - // wait moved into sampler.sample(). This split confirms or refutes it. - let mut sample_call_total = std::time::Duration::ZERO; - let mut post_sample_total = std::time::Duration::ZERO; - let mut tokens_sampled_window: u64 = 0; - // context-budget-exempt: how often the scheduler emits a throughput log line — a logging cadence - const PERF_LOG_INTERVAL_TOKENS: u64 = 50; - loop { - // ── Phase 1: Accept new requests into free slots ── - // If nothing is active, block on the first request (avoid spinning). - // Otherwise non-blocking try_recv to keep the decode loop hot. - loop { - if free_seqs.is_empty() { - break; - } - let recv = if active.is_empty() { - match request_rx.recv() { - Ok(r) => Ok(r), - Err(_) => Err(()), - } - } else { - match request_rx.try_recv() { - Ok(r) => Ok(r), - Err(_) => Err(()), - } - }; - match recv { - Ok(req) => { - let seq_id = free_seqs.pop().unwrap(); - match start_request(&model, seq_id, req) { - Ok(seq) => { - log.info(&format!( - "Seq {} started: prompt={} tokens, max_tokens={}", - seq_id, - seq.prompt_tokens.len(), - seq.max_tokens - )); - // Pending registry entry — bytes:0 marks "this seq - // exists but llama.cpp hasn't committed KV yet." - // Resolves to the real number after PrefillFinal - // succeeds. Skipped when persona_id is None - // (test rigs / ad-hoc probes don't get attribution). - if let Some(pid) = seq.persona_id { - footprint_registry::global().add( - FootprintKey::for_persona( - pid, - ResourceType::KvCache, - Residency::Active, - ), - 0, - ); - } - active.insert(seq_id, seq); - } - Err(e) => { - log.warn(&format!("start_request failed: {e}")); - free_seqs.push(seq_id); - } - } - } - Err(()) => break, - } - } - - // If the channel is closed AND no active work, exit. - if active.is_empty() { - log.info("Scheduler exiting (no active seqs and channel closed)"); - break; - } - - // ── Phase 2: Build batch ── - // Combine continuing-prefill chunks + next-token-per-generating-seq. - // Cap total tokens at n_batch. - batch.clear(); - let mut roles: Vec = Vec::new(); - let mut tokens_in_batch = 0usize; - let mut to_remove: Vec = Vec::new(); - // Homogeneity gate: this decode applies exactly one gene set. The - // first seq with work (lowest seq_id) defines the group; seqs wanting - // a different gene are deferred to a later iteration so a seq is never - // decoded under another seq's adapter. - let mut batch_lora_sig: Option = None; - let mut batch_lora_rep: Option = None; - - // Iterate sorted by seq_id for determinism in tests/logs. - let seq_ids: Vec = { - let mut v: Vec = active.keys().copied().collect(); - v.sort_unstable(); - v - }; - - for seq_id in seq_ids { - let room = n_batch.saturating_sub(tokens_in_batch); - if room == 0 { - break; - } - let seq = active.get_mut(&seq_id).expect("seq present"); - - // Gene-group gate (see batch_lora_sig above). A seq with no work - // this iteration is skipped without claiming the group. - let has_work = seq.prefill_pos < seq.prompt_tokens.len() || seq.next_token.is_some(); - if !has_work { - continue; - } - match batch_lora_sig { - None => { - batch_lora_sig = Some(seq.lora_sig.clone()); - batch_lora_rep = Some(seq_id); - } - Some(ref sig) if *sig != seq.lora_sig => continue, - Some(_) => {} - } - - if seq.prefill_pos < seq.prompt_tokens.len() { - let chunk_end = (seq.prefill_pos + room).min(seq.prompt_tokens.len()); - let is_final = chunk_end == seq.prompt_tokens.len(); - let mut final_logit_idx: i32 = -1; - for i in seq.prefill_pos..chunk_end { - let want_logits = is_final && i == chunk_end - 1; - batch.push(seq.prompt_tokens[i], i as i32, &[seq_id], want_logits); - if want_logits { - // Record the BATCH POSITION (not role count) where - // this seq's logits live — required by - // llama_get_logits_ith. - final_logit_idx = tokens_in_batch as i32; - } - tokens_in_batch += 1; - } - if is_final { - debug_assert!( - final_logit_idx >= 0, - "final prefill chunk must record logit idx" - ); - roles.push(BatchRole::PrefillFinal { - seq_id, - gen_pos: chunk_end as i32, - logit_idx: final_logit_idx, - }); - } - seq.prefill_pos = chunk_end; - } else if let Some(token) = seq.next_token { - let logit_idx = tokens_in_batch as i32; - batch.push(token, seq.gen_pos, &[seq_id], true); - tokens_in_batch += 1; - roles.push(BatchRole::Generating { - seq_id, - pos_after: seq.gen_pos + 1, - logit_idx, - }); - } - } - - if tokens_in_batch == 0 { - // Nothing to do this iteration — yield briefly. - std::thread::sleep(std::time::Duration::from_millis(1)); - continue; - } - - // ── Phase 3: Apply this batch's gene group, then decode ── - // Context-level LoRA. The homogeneity gate guarantees every seq in - // this batch shares `batch_lora_sig`, and a seq is only ever decoded - // under its own gene, so its KV history stays consistent. We only call - // set_loras/clear_loras when the desired group differs from what's - // already on the context (the cheap hot-swap). A set_loras failure is - // routed through the same fan-out as a decode failure — never decode - // under the wrong gene (Rule 2). - let desired_sig = batch_lora_sig.clone().unwrap_or_default(); - let lora_apply: Result<(), String> = if desired_sig == current_ctx_lora_sig { - Ok(()) - } else if desired_sig.is_empty() { - ctx.clear_loras() - } else { - let rep = - batch_lora_rep.expect("non-empty gene signature must have a representative seq"); - let refs: Vec<(&LoraAdapter, f32)> = active - .get(&rep) - .expect("representative seq present") - .active_loras - .iter() - .map(|(a, s)| (a.as_ref(), *s)) - .collect(); - ctx.set_loras(&refs) - }; - - let decode_start = Instant::now(); - let decode_result = match lora_apply { - Ok(()) => { - // Context now reflects this gene group (even if decode later - // fails) — record it so the next iteration skips a redundant - // re-apply. - current_ctx_lora_sig = desired_sig.clone(); - ctx.decode(&batch) - } - Err(e) => Err(format!("set_loras failed (gene '{desired_sig}'): {e}")), - }; - if let Err(e) = decode_result { - log.error(&format!( - "Decode error: {e} (batch={} tokens, {} active seqs)", - tokens_in_batch, - active.len() - )); - // Fail every seq that had work in this batch — we can't tell - // which one caused the failure, so the safe thing is to error - // all participants and let callers retry. - for role in &roles { - let sid = match role { - BatchRole::PrefillFinal { seq_id, .. } => *seq_id, - BatchRole::Generating { seq_id, .. } => *seq_id, - }; - if let Some(seq) = active.get(&sid) { - let _ = seq.response_tx.send(TokenEvent::Error(e.clone())); - } - to_remove.push(sid); - } - } else { - // Decode succeeded — record Metal-compute time. This is the - // wall-clock time the Metal command buffer + dispatch took, - // including any CPU↔GPU graph splits if the Metal backend fell - // back to CPU for unsupported ops. - decode_total += decode_start.elapsed(); - decode_count += 1; - - // ── Phase 4: Sample for each logit-bearing position ── - // Logits are addressed by BATCH POSITION (not role-vec index). - // `llama_get_logits_ith(idx)` reads `batch.logits[idx]` and - // panics if it's not `true`. We recorded `logit_idx` while - // building the batch — it's the absolute batch position - // where this seq's want_logits=true token sits. - let sample_start = Instant::now(); - let mut sample_call_iter_total = std::time::Duration::ZERO; - for role in &roles { - let (seq_id, advance_pos, logit_idx) = match role { - BatchRole::PrefillFinal { - seq_id, - gen_pos, - logit_idx, - } => (*seq_id, *gen_pos, *logit_idx), - BatchRole::Generating { - seq_id, - pos_after, - logit_idx, - } => (*seq_id, *pos_after, *logit_idx), - }; - let seq = match active.get_mut(&seq_id) { - Some(s) => s, - None => continue, - }; - - // Time the sampler.sample() call independently. This is the - // implicit GPU sync point — llama_get_logits_ith() blocks - // until the outstanding Metal command buffer completes, so - // most of the apparent "sample" cost lives here, not in the - // post-sample work below. - let sample_call_start = Instant::now(); - let token = seq.sampler.sample(&ctx, logit_idx); - let sample_call_elapsed = sample_call_start.elapsed(); - sample_call_iter_total += sample_call_elapsed; - - // If this role was PrefillFinal (first decode for the seq), - // llama.cpp has now committed the seq's KV cache. Ask the - // backend for the exact bytes and overwrite the pending - // registry entry. Done here (not in a separate pass) because - // we already have the seq + role in scope and the cost is - // one FFI call. seq_state_bytes returns 0 if seq doesn't - // exist — defensive fallback never lands a fake number. - let was_prefill_final = matches!(role, BatchRole::PrefillFinal { .. }); - if was_prefill_final { - if let Some(pid) = seq.persona_id { - let bytes = ctx.seq_state_bytes(seq_id); - if bytes > 0 { - footprint_registry::global().report_authoritative( - FootprintKey::for_persona( - pid, - ResourceType::KvCache, - Residency::Active, - ), - bytes, - ); - } - } - } - - if model.is_eog_token(token) { - // Registry cleanup MUST happen before sending Done, so - // any caller awaiting on the channel sees a consistent - // registry state (entry removed) the moment generate - // returns. Phase 5 only does memory_seq_rm + free_seq. - if let Some(pid) = seq.persona_id { - let bytes = ctx.seq_state_bytes(seq_id); - footprint_registry::global().remove( - &FootprintKey::for_persona( - pid, - ResourceType::KvCache, - Residency::Active, - ), - bytes, - ); - } - let _ = seq.response_tx.send(TokenEvent::Done { - tokens_generated: seq.tokens_generated, - elapsed_ms: seq.started_at.elapsed().as_millis() as u64, - }); - to_remove.push(seq_id); - continue; - } - - let piece = model.token_to_piece(token); - seq.output_so_far.push_str(&piece); - let _ = seq.response_tx.send(TokenEvent::Token(piece)); - seq.tokens_generated += 1; - - let stop_hit = seq - .stop_sequences - .iter() - .any(|s| seq.output_so_far.ends_with(s)); - if stop_hit || seq.tokens_generated >= seq.max_tokens { - // Same pre-Done registry cleanup as the EOG path — - // single source of truth on what state the channel - // completion signals. - if let Some(pid) = seq.persona_id { - let bytes = ctx.seq_state_bytes(seq_id); - footprint_registry::global().remove( - &FootprintKey::for_persona( - pid, - ResourceType::KvCache, - Residency::Active, - ), - bytes, - ); - } - let _ = seq.response_tx.send(TokenEvent::Done { - tokens_generated: seq.tokens_generated, - elapsed_ms: seq.started_at.elapsed().as_millis() as u64, - }); - to_remove.push(seq_id); - continue; - } - - seq.next_token = Some(token); - seq.gen_pos = advance_pos; - } - // Phase-4 wall time minus the per-iteration sample-call cost = - // post-sample CPU work (token_to_piece, push_str, channel send, - // stop-sequence scan). - let phase4_total = sample_start.elapsed(); - sample_call_total += sample_call_iter_total; - post_sample_total += phase4_total.saturating_sub(sample_call_iter_total); - tokens_sampled_window += roles.len() as u64; - } - - // ── Periodic GPU/CPU bottleneck telemetry ── - // Emit once per PERF_LOG_INTERVAL_TOKENS so chat sees real per-phase - // numbers without log spam. Decode = Metal-side compute. Sample = - // CPU-side sampler chain + UTF-8 decode + channel send. If decode_ms - // dominates we're GPU-bound (expected). If sample_ms is comparable - // the CPU tail is the bottleneck. - if tokens_sampled_window >= PERF_LOG_INTERVAL_TOKENS && decode_count > 0 { - let avg_decode_us = decode_total.as_micros() as f64 / decode_count as f64; - let avg_sample_call_us = - sample_call_total.as_micros() as f64 / tokens_sampled_window as f64; - let avg_post_sample_us = - post_sample_total.as_micros() as f64 / tokens_sampled_window as f64; - let total_us_per_tok = avg_decode_us + avg_sample_call_us + avg_post_sample_us; - let tok_per_s = if total_us_per_tok > 0.0 { - 1_000_000.0 / total_us_per_tok - } else { - 0.0 - }; - // sample_call captures the GPU sync wait + sampler chain CPU - // work. post_sample is everything else (token_to_piece, send, - // stop scan). When sample_call ≫ post_sample the bottleneck is - // GPU sync, not CPU sampler chain — and the lever is async - // pipelining or a leaner sampler, not faster string ops. - log.info(&format!( - "perf: decode_dispatch={:.2}ms sample_call={:.2}ms post_sample={:.2}ms \ - ({} decodes / {} sampled) → {:.1} tok/s", - avg_decode_us / 1000.0, - avg_sample_call_us / 1000.0, - avg_post_sample_us / 1000.0, - decode_count, - tokens_sampled_window, - tok_per_s, - )); - decode_total = std::time::Duration::ZERO; - decode_count = 0; - sample_call_total = std::time::Duration::ZERO; - post_sample_total = std::time::Duration::ZERO; - tokens_sampled_window = 0; - } - - // ── Phase 5: Free completed seqs ── - // Registry cleanup happens UPSTREAM at the Done send (Phase 4), - // so callers awaiting on the channel see a consistent registry - // state when they unblock. Here we only do the llama.cpp seq_rm - // and return the seq_id to the free pool. - // - // Decode-error path: also pushes to to_remove, but bypasses the - // Phase 4 cleanup. We catch it here as a fallback — if the seq is - // still in `active` AND has a persona_id with a registry entry, - // remove it. seq_state_bytes(seq_id) is still valid before - // memory_seq_rm. - for seq_id in to_remove { - // Fallback registry cleanup (only fires for paths that didn't - // already clean up — the decode-error path is the only one). - if let Some(seq) = active.get(&seq_id) { - if let Some(pid) = seq.persona_id { - let key = - FootprintKey::for_persona(pid, ResourceType::KvCache, Residency::Active); - // If the entry was already cleaned up by Phase 4, this - // is a no-op (remove on missing key does nothing). If - // it's still here (decode-error path), drain it to 0. - let bytes = ctx.seq_state_bytes(seq_id); - footprint_registry::global().remove(&key, bytes); - } - } - - ctx.memory_seq_rm(seq_id, -1, -1); - - if let Some(seq) = active.remove(&seq_id) { - log.info(&format!( - "Seq {} finished: {} tokens in {}ms ({:.1} tok/s)", - seq_id, - seq.tokens_generated, - seq.started_at.elapsed().as_millis(), - seq.tokens_generated as f64 / seq.started_at.elapsed().as_secs_f64().max(0.001) - )); - } - free_seqs.push(seq_id); - } - } -} - -/// Canonical signature of a gene set — sorted `id:scale`, comma-joined. -/// Empty string = base model. Two seqs co-batch under one context-level -/// `set_loras` iff their signatures match (the homogeneity gate). -fn lora_signature(loras: &[(String, Arc, f32)]) -> String { - if loras.is_empty() { - return String::new(); - } - let mut parts: Vec = loras.iter().map(|(id, _, s)| format!("{id}:{s}")).collect(); - parts.sort_unstable(); - parts.join(",") -} - -fn start_request(model: &Model, _seq_id: i32, req: GenerationRequest) -> Result { - let lora_sig = lora_signature(&req.active_loras); - let active_loras: Vec<(Arc, f32)> = req - .active_loras - .into_iter() - .map(|(_, h, s)| (h, s)) - .collect(); - // special=true so chat-template boundary markers (<|im_start|>, - // <|im_end|>) are tokenized as the model's actual special token IDs - // (151644/151645 for qwen3) rather than character-level text. With - // special=false the model never sees the boundary tokens it was - // trained on — output collapsed to short fragments terminating early - // at character-matched stop sequences. - let prompt_tokens = model.tokenize(&req.prompt, true, true)?; - let sampler = if req.sampling.temperature <= 0.0 && req.sampling.grammar.is_none() { - Sampler::greedy() - } else { - // Build the full sampler chain. Order: grammar → top_k → top_p → - // penalties → temp → dist. Grammar early so structural constraint - // applies BEFORE probabilistic sampling (otherwise temp could pick - // a token that the grammar would have rejected). - let mut chain = Sampler::chain(); - if let Some(g) = req.sampling.grammar.as_ref() { - chain = chain.grammar(model, g, "root"); - } - if req.sampling.top_k > 0 { - chain = chain.top_k(req.sampling.top_k as i32); - } - if req.sampling.top_p > 0.0 && req.sampling.top_p < 1.0 { - chain = chain.top_p(req.sampling.top_p as f32, 1); - } - // 64 = llama.cpp default last-n window for the penalty calculation. - chain = chain.penalties(model.n_vocab(), 64, req.sampling.repeat_penalty, 0.0, 0.0); - let temp = if req.sampling.temperature > 0.0 { - req.sampling.temperature as f32 - } else { - 0.01 - }; - chain.temp(temp).dist(42).build() - }; - Ok(ActiveSeq { - seq_id: _seq_id, - prompt_tokens, - prefill_pos: 0, - gen_pos: 0, - next_token: None, - tokens_generated: 0, - max_tokens: req.max_tokens, - sampler, - stop_sequences: req.stop_sequences, - output_so_far: String::new(), - response_tx: req.response_tx, - started_at: Instant::now(), - persona_id: req.persona_id, - active_loras, - lora_sig, - }) -} diff --git a/core/continuum-engine/src/inference/backends/mlx_adapter.rs b/core/continuum-engine/src/inference/backends/mlx_adapter.rs deleted file mode 100644 index ee3cd2edbc..0000000000 --- a/core/continuum-engine/src/inference/backends/mlx_adapter.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! MLX Backend Adapter — Phase A scaffold -//! -//! Native Apple Silicon inference via `mlx-rs` (oxideai 0.25). This file is -//! the landing zone for phases A–E of [continuum#897]. Only compiles when -//! both the `mlx` cargo feature is enabled AND we're on macOS; on other -//! platforms the module is absent entirely. -//! -//! ## Status: phase A — scaffold only -//! -//! This file compiles and registers, nothing more. Actual inference lands in -//! phase B; audio in phase C; vision in phase D; forge tier publication in -//! phase E. See `docs/inference/MLX-BACKEND.md` for the staged plan and -//! `docs/inference/SD-PORT-PATTERNS.md` for the runtime-boundary research -//! memento (continuum-3bb8) landed while I slept on it. -//! -//! ## Why MLX -//! -//! Continuum's primary audience is the M-series Mac (see -//! `memory/project_m5_is_primary_audience.md`). MLX gives us: -//! -//! - Native Metal dispatch (no ggml-metal translation overhead) -//! - Unified memory residency handled by the framework (no `.to_device()`) -//! - First-class support for Qwen3.5-Omni's audio + vision heads in the -//! `mlx-community` ports — which llama.cpp and ort don't match -//! - Lazy evaluation: the full forward + CFG-blend + scheduler step can be -//! fused into one graph per timestep, only materialized on `eval()` -//! -//! ## The trait-shape problem (phase B gate) -//! -//! The existing `ModelBackend` trait signs its forward methods against -//! `candle_core::Tensor`, which is a Candle runtime object. MLX has its own -//! `mlx_rs::Array` with different lifetime + device semantics (lazy, unified -//! memory). Two resolutions possible, to be decided in phase B: -//! -//! 1. **Generic trait over tensor type.** Refactor `ModelBackend` to be -//! parameterized by a tensor type, with associated `type TensorT: ...`. -//! Cleanest long-term; biggest churn to existing backends. -//! -//! 2. **Additive MLX-native methods with defaults.** Add `forward_mlx()`, -//! `eval_mlx()`, etc., defaulting to `unimplemented!()`. Existing -//! backends unchanged; MLX backend doesn't implement the Candle-tensor -//! methods. Callers dispatch on which methods a backend supports. -//! -//! Promised to memento: additive with defaults so their Vulkan work -//! doesn't need to change. Decision deferred to phase B because the right -//! shape depends on whether KV cache ownership lives in the backend or the -//! scheduler (separate open question in SD-PORT-PATTERNS.md). -//! -//! [continuum#897]: https://github.com/CambrianTech/continuum/pull/897 - -#![cfg(all(feature = "mlx", target_os = "macos"))] - -use std::path::Path; - -/// Placeholder for the MLX-backed adapter. Holds no state in phase A; -/// phase B fills in the `mlx_rs::Module` reference, weight metadata, and -/// the MLX-native forward/eval methods. -/// -/// Construction deliberately fails until phase B so any caller that tries -/// to actually use this gets a clear "not implemented" error instead of a -/// silent no-op — same philosophy as the error-evidence rule we learned -/// the hard way today. -#[derive(Debug)] -pub struct MlxAdapter { - _private: (), -} - -impl MlxAdapter { - /// Load a model from an MLX-native artifact directory. Phase B will: - /// - /// 1. Resolve the model tier for this device (same logic as - /// `qwen35_gguf.rs` uses for GGUF — pick the right quant based on - /// available VRAM from `GpuMemoryManager`). - /// 2. Load weights via `mlx_rs` (indexed NPY + JSON index — not raw - /// safetensors; see SD-PORT-PATTERNS.md for the format rationale). - /// 3. Apply the HF→MLX key remap table (static data, same pattern as - /// mlx-community's `model_io.py`). - /// 4. Construct the transformer module graph. - /// - /// In phase A this just returns a sentinel error so nobody can - /// accidentally wire it up yet. - pub fn load(_model_path: &Path) -> Result { - Err("MlxAdapter::load not implemented — phase A scaffold only. \ - See docs/inference/MLX-BACKEND.md for the staged plan." - .to_string()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn load_returns_phase_a_sentinel() { - let err = MlxAdapter::load(Path::new("/nonexistent")).unwrap_err(); - assert!( - err.contains("phase A"), - "error should call out phase A status: {err}" - ); - } -} diff --git a/core/continuum-engine/src/inference/backends/mod.rs b/core/continuum-engine/src/inference/backends/mod.rs index c41d176d96..6330e3c763 100644 --- a/core/continuum-engine/src/inference/backends/mod.rs +++ b/core/continuum-engine/src/inference/backends/mod.rs @@ -3,13 +3,7 @@ //! `JSON_GRAMMAR`) the adapters share. pub mod llamacpp; -pub mod llamacpp_scheduler; - -// MLX adapter: macOS + `mlx` feature only. Gated here so non-Mac / feature-off -// builds don't see the module at all. Phase A scaffold — see continuum#897 -// and docs/inference/MLX-BACKEND.md. -#[cfg(all(feature = "mlx", target_os = "macos"))] -pub mod mlx_adapter; +pub mod persona_scheduler; use std::path::Path; diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs new file mode 100644 index 0000000000..dd4b1e9236 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -0,0 +1,101 @@ +//! The in-process scheduler for our minds (CONTINUUM-ENGINE 4.14): one libllama context driven by +//! the persona engine, ONE mind decoding at a time. It replaces the continuous-batching scheduler +//! that advanced N sequences per decode (4 at once = 2 tok/s each; one at a time = the full rate). +//! +//! Each persona keeps her blocks between turns, so a turn prefills only the tokens her blocks do not +//! hold ([`continuum_persona_engine::turn::plan`]); the old scheduler dropped every sequence when its +//! turn ended and re-prefilled the whole prompt next time. A switch is the engine's native bind (her +//! blocks stay in RAM as she left them), never a serialize to disk. +//! +//! - [`Scheduler::enqueue`] sends a [`GenerationRequest`] to the driver thread; +//! - the driver serves turns one after another: switches to her (stage, settle, handoff, release the +//! previous mind to the RAM tier), prefills her new tail, decodes until EOG / a stop sequence / +//! max_tokens, and streams [`TokenEvent`]s back; +//! - genes apply when she is bound, for her decodes only, so her history is never decoded under +//! another gene set; the gene set is part of her basis, so a turn under another set starts her over. +//! +//! Not yet: overlapping the next mind's copy-in with the active decode (the tier's moves are +//! synchronous today), and paging cold minds out of RAM. + +mod driver; +mod sampling; + +use std::sync::Arc; + +use llama::{FlashAttn, KvCacheType, LoraAdapter, Model}; +use uuid::Uuid; + +use super::SamplingConfig; + +/// Token event streamed from the scheduler to the requester. +#[derive(Debug)] +pub enum TokenEvent { + /// One generated token piece (UTF-8 fragment from the tokenizer). + Token(String), + /// Generation finished cleanly (EOG / max_tokens / stop sequence). + Done { tokens_generated: usize, elapsed_ms: u64 }, + /// Generation failed: a refused move, a decode error. + Error(String), +} + +/// What a caller submits to the scheduler. +pub struct GenerationRequest { + pub prompt: String, + pub max_tokens: usize, + pub sampling: SamplingConfig, + pub stop_sequences: Vec, + /// Genes for this turn: `(id, handle, scale)`, resolved by the backend before enqueue. Empty is + /// the base model. + pub active_loras: Vec<(String, Arc, f32)>, + /// Tokens stream back through this. + pub response_tx: tokio::sync::mpsc::UnboundedSender, + /// The persona whose mind this turn continues. `None` is a one-off (a probe, a test rig): it + /// runs as a mind of its own and its blocks are released when the turn ends. + pub persona_id: Option, +} + +/// The context the scheduler creates. Its window holds [`continuum_persona_llama::STREAMS`] minds' +/// windows (the active mind's and the next one's); no sequence count is configurable. +#[derive(Debug, Clone)] +pub struct SchedulerConfig { + pub n_ctx: u32, + pub n_batch: u32, + pub n_ubatch: u32, + pub flash_attn: FlashAttn, + pub fused_gdn_ar: bool, + pub fused_gdn_ch: bool, + pub type_k: KvCacheType, + pub type_v: KvCacheType, +} + +/// Public handle. Cloneable; clones share the one driver thread and context. +#[derive(Clone)] +pub struct Scheduler { + request_tx: std::sync::mpsc::Sender, +} + +impl Scheduler { + /// Spawn the driver thread. It runs until the last handle is dropped and its last turn ended. + pub fn spawn(model: Arc, config: SchedulerConfig) -> Result { + let (request_tx, request_rx) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("persona-scheduler".to_string()) + .spawn(move || driver::run(&model, &config, &request_rx)) + .map_err(|spawn| SchedulerError::Spawn(Arc::new(spawn)))?; + Ok(Self { request_tx }) + } + + /// Enqueue a turn. Refused once the driver thread has exited. + pub fn enqueue(&self, req: GenerationRequest) -> Result<(), SchedulerError> { + self.request_tx.send(req).map_err(|_| SchedulerError::Closed) + } +} + +/// Why the scheduler could not take a turn. +#[derive(Debug, Clone, thiserror::Error)] +pub enum SchedulerError { + #[error("the persona scheduler thread could not be spawned: {0}")] + Spawn(Arc), + #[error("the persona scheduler has stopped")] + Closed, +} diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs new file mode 100644 index 0000000000..649b3e65c3 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -0,0 +1,274 @@ +//! The driver thread: serves turns one after another on one context, through the persona engine. + +use std::collections::HashMap; +use std::num::NonZeroUsize; +use std::sync::mpsc::Receiver; +use std::sync::Arc; +use std::time::Instant; + +use continuum_persona_engine::engine::{DecodeError, HandoffError, PersonaEngine, RetireError, StageError}; +use continuum_persona_engine::persona::{Epoch, PersonaId}; +use continuum_persona_engine::pipeline::Identified; +use continuum_persona_engine::residency::TierRefusal; +use continuum_persona_engine::turn::{plan, History, Prefill}; +use continuum_persona_llama::{Genes, Step, UnifiedTier, STREAMS}; +use llama::{ContextParams, LoraAdapter, Model}; +use uuid::Uuid; + +use super::{sampling, GenerationRequest, SchedulerConfig, TokenEvent}; +use crate::inference::footprint_registry::{self, FootprintKey, ResourceType}; +use crate::inference::kv_quant::Residency; +use crate::runtime; + +/// Why a turn did not complete. The mind stays in the engine's custody either way. +#[derive(Debug, thiserror::Error)] +pub(super) enum TurnError { + #[error("her prompt did not tokenize: {0}")] + Tokenize(String), + #[error(transparent)] + Stage(#[from] StageError), + #[error(transparent)] + Handoff(#[from] HandoffError), + #[error(transparent)] + Decode(#[from] DecodeError), + #[error(transparent)] + Tier(#[from] TierRefusal), + #[error(transparent)] + Retire(#[from] RetireError), + #[error("no mind is active after the switch")] + NoneActive, + #[error("her history is longer than a context position holds")] + TooLong, + #[error("nothing was decoded for her turn")] + NothingDecoded, +} + +/// The context could not be made, so no turn can run. +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("the persona scheduler's context was refused: {0}")] + Context(String), + #[error("the persona scheduler's batch size is zero")] + ZeroBatch, +} + +/// What her blocks were computed under beside the token ids. The model is this context's own, and no +/// native media reaches this path (the prompt is text), so her gene set (ids and scales) is the rest. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +struct Basis { + genes: String, +} + +/// One mind this scheduler serves: her id and epoch, the tokens her blocks hold, and their basis. +struct Mind { + id: PersonaId, + epoch: Epoch, + held: Vec, + basis: Basis, + /// A one-off (no persona): her blocks are released when her turn ends. + one_off: bool, +} + +impl Identified for Mind { + fn persona(&self) -> PersonaId { + self.id + } + fn epoch(&self) -> Epoch { + self.epoch + } +} + +/// The driver's state: the model, the one engine over the one context, and every mind not active. +struct Driver<'c, 'm> { + model: &'m Model, + batch: NonZeroUsize, + engine: PersonaEngine>, + parked: HashMap, +} + +/// Run until every handle is dropped. +pub(super) fn run(model: &Model, config: &SchedulerConfig, requests: &Receiver) { + let log = runtime::logger("persona-scheduler"); + let mut ctx = match context(model, config) { + Ok(ctx) => ctx, + Err(refused) => { + log.error(&refused.to_string()); + 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 _ = 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 mut driver = Driver { model, batch, engine: PersonaEngine::new(UnifiedTier::new(&mut ctx)), parked: HashMap::new() }; + for req in requests { + let respond = req.response_tx.clone(); + let event = match driver.serve(req) { + Ok(done) => done, + Err(refused) => { + log.warn(&format!("turn refused: {refused}")); + TokenEvent::Error(refused.to_string()) + } + }; + let _ = respond.send(event); + } +} + +/// The one context: `STREAMS` sequences (the active mind's and the next one's). +fn context<'m>(model: &'m Model, config: &SchedulerConfig) -> Result, StartError> { + let streams = u32::try_from(STREAMS).map_err(|_| StartError::Context("stream count exceeds a sequence count".into()))?; + model + .new_context(ContextParams { + n_ctx: config.n_ctx, + n_batch: config.n_batch, + n_ubatch: config.n_ubatch, + n_seq_max: streams, + flash_attn: config.flash_attn, + fused_gdn_ar: config.fused_gdn_ar, + fused_gdn_ch: config.fused_gdn_ch, + type_k: config.type_k, + type_v: config.type_v, + embeddings: false, + pooling_type: llama::PoolingType::None, + expert_observer: None, + }) + .map_err(StartError::Context) +} + +impl Driver<'_, '_> { + /// One turn: switch to her, prefill what her blocks do not hold, decode until she stops. + fn serve(&mut self, req: GenerationRequest) -> Result { + let started = Instant::now(); + let (id, one_off) = match req.persona_id { + Some(persona) => (PersonaId(persona), false), + None => (PersonaId(Uuid::new_v4()), true), + }; + // special=true so chat-template markers tokenize as the model's own special tokens + let prompt = self.model.tokenize(&req.prompt, true, true).map_err(TurnError::Tokenize)?; + let basis = Basis { genes: signature(&req.active_loras) }; + let genes: Genes = req.active_loras.iter().map(|(_, adapter, scale)| (Arc::clone(adapter), *scale)).collect::>().into(); + + self.switch_to(id, one_off)?; + let from = { + let her = self.engine.active_mut().ok_or(TurnError::NoneActive)?; + let from = match plan(History { basis: &her.basis, tokens: &her.held }, History { basis: &basis, tokens: &prompt }) { + Prefill::Append { from } => from, + Prefill::Restart => 0, + }; + her.held.truncate(from); + her.basis = basis; + from + }; + + let mut sampler = sampling::sampler(self.model, &req.sampling); + let mut pos = i32::try_from(from).map_err(|_| TurnError::TooLong)?; + // Only her final prompt position is sampled: the sampler accepts what it samples, so sampling + // an earlier chunk would advance her grammar, penalties and RNG on output that never happened + // (Codex on #6140). Earlier chunks request no logits and are settled, not read. + let chunks: Vec<&[i32]> = prompt[from..].chunks(self.batch.get()).collect(); + let (last_chunk, earlier) = chunks.split_last().ok_or(TurnError::NothingDecoded)?; + for chunk in earlier { + self.engine.submit(Step { tokens: chunk.to_vec(), from: pos, logits_at_end: false, genes: Arc::clone(&genes) })?; + pos += i32::try_from(chunk.len()).map_err(|_| TurnError::TooLong)?; + self.engine.settle()?; + } + self.engine.submit(Step { tokens: last_chunk.to_vec(), from: pos, logits_at_end: true, genes: Arc::clone(&genes) })?; + pos += i32::try_from(last_chunk.len()).map_err(|_| TurnError::TooLong)?; + let last = i32::try_from(last_chunk.len() - 1).map_err(|_| TurnError::TooLong)?; + let mut token = self.engine.tier().sample(&mut sampler, last); + self.record(|her| her.held.extend_from_slice(&prompt[from..]))?; + self.report_footprint(id, one_off); + + let mut generated = 0usize; + let mut output = String::new(); + loop { + if self.model.is_eog_token(token) { + break; + } + let piece = self.model.token_to_piece(token); + output.push_str(&piece); + let _ = req.response_tx.send(TokenEvent::Token(piece)); + generated += 1; + if generated >= req.max_tokens || req.stop_sequences.iter().any(|stop| output.ends_with(stop)) { + break; + } + self.engine.submit(Step { tokens: vec![token], from: pos, logits_at_end: true, genes: Arc::clone(&genes) })?; + pos += 1; + self.record(|her| her.held.push(token))?; + token = self.engine.tier().sample(&mut sampler, 0); + } + self.report_footprint(id, one_off); + let took = started.elapsed(); + let elapsed_ms = took.as_secs().saturating_mul(1000).saturating_add(u64::from(took.subsec_millis())); + Ok(TokenEvent::Done { tokens_generated: generated, elapsed_ms }) + } + + /// Make `id` the active mind: her parked state comes back (or a new mind starts), the previous + /// mind moves out to the RAM tier and is parked, or forgotten if she was a one-off. + /// + /// A retirement a refused copy-out left behind is finished first, so it is retried rather than + /// skipped and the retiring mind is never staged while still in custody (Codex on #6140). A + /// copy-out refused during this handoff leaves next bound; it is retried right after, and again + /// at the start of the next turn if the tier still refuses. + fn switch_to(&mut self, id: PersonaId, one_off: bool) -> Result<(), TurnError> { + self.retire_previous()?; + if self.engine.active() == Some(id) { + return Ok(()); + } + let mind = match self.parked.remove(&id) { + Some(parked) => parked, + None => Mind { id, epoch: Epoch(1), held: Vec::new(), basis: Basis::default(), one_off }, + }; + if let Err(refused) = self.engine.stage(mind) { + self.parked.insert(refused.returned.id, refused.returned); + return Err(refused.reason.into()); + } + self.engine.settle()?; + match self.engine.handoff() { + Ok(_) | Err(HandoffError::CopyOut { .. }) => {} + Err(refused) => return Err(refused.into()), + } + self.retire_previous() + } + + /// Park the mind whose retirement finishes (or forget her if she was a one-off). + fn retire_previous(&mut self) -> Result<(), TurnError> { + let Some(previous) = self.engine.finish_retirement()? else { return Ok(()) }; + if previous.one_off { + self.engine.forget(previous.id)?; + } else { + self.parked.insert(previous.id, previous); + } + Ok(()) + } + + /// Update the active mind's own record (what her blocks now hold). + fn record(&mut self, change: impl FnOnce(&mut Mind)) -> Result<(), TurnError> { + change(self.engine.active_mut().ok_or(TurnError::NoneActive)?); + Ok(()) + } + + /// Attribute her stream's bytes to her in the footprint registry (one-offs are not attributed). + fn report_footprint(&self, id: PersonaId, one_off: bool) { + if one_off { + return; + } + if let Some(bytes) = self.engine.tier().state_bytes_of(id).filter(|bytes| *bytes > 0) { + footprint_registry::global().report_authoritative(FootprintKey::for_persona(id.0, ResourceType::KvCache, Residency::Active), bytes); + } + } +} + +/// A gene set's identity: sorted `id:scale`, comma-joined; empty is the base model. +fn signature(genes: &[(String, Arc, f32)]) -> String { + let mut parts: Vec = genes.iter().map(|(id, _, scale)| format!("{id}:{scale}")).collect(); + parts.sort_unstable(); + parts.join(",") +} diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/sampling.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/sampling.rs new file mode 100644 index 0000000000..f39efc5a45 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/sampling.rs @@ -0,0 +1,28 @@ +//! A turn's sampler chain from its [`SamplingConfig`] (moved unchanged from the old scheduler). + +use llama::{Model, Sampler}; + +use super::super::SamplingConfig; + +/// Greedy at temperature 0 without a grammar; otherwise grammar, top_k, top_p, penalties, temperature, +/// then the distribution. Grammar first, so the structural constraint applies before probabilistic +/// sampling could pick a token it rejects. +pub(super) fn sampler(model: &Model, sampling: &SamplingConfig) -> Sampler { + if sampling.temperature <= 0.0 && sampling.grammar.is_none() { + return Sampler::greedy(); + } + let mut chain = Sampler::chain(); + if let Some(grammar) = sampling.grammar.as_ref() { + chain = chain.grammar(model, grammar, "root"); + } + if sampling.top_k > 0 { + chain = chain.top_k(sampling.top_k as i32); + } + if sampling.top_p > 0.0 && sampling.top_p < 1.0 { + chain = chain.top_p(sampling.top_p as f32, 1); + } + // 64 = llama.cpp's default last-n window for the penalty calculation. + chain = chain.penalties(model.n_vocab(), 64, sampling.repeat_penalty, 0.0, 0.0); + let temp = if sampling.temperature > 0.0 { sampling.temperature as f32 } else { 0.01 }; + chain.temp(temp).dist(42).build() +} diff --git a/core/continuum-engine/src/inference/llamacpp_adapter.rs b/core/continuum-engine/src/inference/llamacpp_adapter.rs index 210a1ed9c1..89f45c38e2 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter.rs @@ -149,9 +149,9 @@ pub struct LlamaCppAdapter { /// Continuous-batching slot count. `None` = single-seq mode /// (the conservative qwen3.5 default — its recurrent / /// Gated-Delta-Net Metal graph aborts on multi-seq). When set, - /// the in-backend scheduler multiplexes N concurrent - /// generations through one shared model load via - /// `llamacpp_scheduler.rs`'s driver loop. + /// the in-backend scheduler admitted N concurrent generations. The + /// persona scheduler now serves one mind at a time whatever this says; + /// the field is removed with the lanes (serving integration S3). /// /// **Coordinator wiring:** `InferenceCoordinator::open_lane` /// admits up to `lane_budgets.max_concurrency` lanes against diff --git a/core/continuum-persona-engine/src/engine.rs b/core/continuum-persona-engine/src/engine.rs index 15277bc451..18a7c484fc 100644 --- a/core/continuum-persona-engine/src/engine.rs +++ b/core/continuum-persona-engine/src/engine.rs @@ -77,6 +77,17 @@ pub enum HandoffError { CopyOut { previous: PersonaId, refusal: TierRefusal }, } +/// Why a retirement did not finish. She stays retiring, in the engine's custody. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum RetireError { + /// Her copy-out could not begin. + #[error(transparent)] + CopyOut(#[from] HandoffError), + /// Her copy-out has not landed, or the pipeline refused the release. + #[error(transparent)] + Release(#[from] RetireRefusal), +} + /// One engine's decode, its three places, and the tier that moves minds between them and runs them. pub struct PersonaEngine { roles: Roles, @@ -203,6 +214,27 @@ impl PersonaEngine { self.roles.release_retired() } + /// Bring a retirement to its end: begin her copy-out if a refusal left it unbegun, then give her + /// back once it landed. `Ok(None)` when nobody is retiring. A driver calls this before it stages, + /// so a refused copy-out is retried rather than skipped, and the retiring mind is never handed + /// out twice (Codex on #6140). + pub fn finish_retirement(&mut self) -> Result, RetireError> { + if self.retiring().is_none() { + return Ok(None); + } + self.retry_retire()?; + Ok(Some(self.release_retired()?)) + } + + /// Give up the blocks of a mind that has left the pipeline (a one-off whose turn ended). Refused + /// while she is active, staged or retiring: custody of a present mind is never dropped. + pub fn forget(&mut self, persona: PersonaId) -> Result<(), TierRefusal> { + if self.present(persona) || self.staged() == Some(persona) { + return Err(TierRefusal { tier: self.tier.name(), persona, reason: "she is still in the pipeline", native: Native::NotAsked }); + } + self.tier.release(persona) + } + fn present(&self, persona: PersonaId) -> bool { self.active() == Some(persona) || self.retiring() == Some(persona) } diff --git a/core/continuum-persona-engine/src/engine/tests.rs b/core/continuum-persona-engine/src/engine/tests.rs index 1f89db4a02..81ffeaa3da 100644 --- a/core/continuum-persona-engine/src/engine/tests.rs +++ b/core/continuum-persona-engine/src/engine/tests.rs @@ -46,6 +46,7 @@ struct Recording { moves: Log, decodes: Log, refuse: Rc>>, + released: Rc>>, } impl Tier for Recording { type Fence = Pending; @@ -60,6 +61,10 @@ impl Tier for Recording { self.moves.borrow_mut().push((what, Rc::clone(&landed))); Ok(Pending { tag: what, landed }) } + fn release(&mut self, persona: PersonaId) -> Result<(), TierRefusal> { + self.released.borrow_mut().push(persona); + Ok(()) + } } impl Execute for Recording { type Work = (); @@ -215,3 +220,48 @@ fn a_refused_copy_out_keeps_her_retiring_until_it_begins() { land_last(&h.moves); assert_eq!(h.engine.release_retired().map(|unit| unit.id()), Ok(id(1))); } + +// what this catches (Codex on #6140 at 17c208cf5): a refused copy-out skipped by the next switch, or +// the retiring mind handed out twice. finish_retirement keeps her retiring while her copy-out is +// refused or still moving, gives her back exactly once, and an A/B/A switch then holds one of each. +#[test] +fn a_refused_copy_out_is_finished_before_the_next_switch_and_given_back_once() { + let mut h = with_one_active(); + assert!(h.engine.stage(mind(2)).is_ok()); + land_last(&h.moves); + h.refuse.set(Some(Direction::Out)); + assert!(matches!(h.engine.handoff(), Err(HandoffError::CopyOut { .. }))); + + assert!(matches!(h.engine.finish_retirement(), Err(RetireError::CopyOut(_))), "still refused"); + assert_eq!(h.engine.retiring(), Some(id(1)), "she stays in custody"); + h.refuse.set(None); + assert!(matches!(h.engine.finish_retirement(), Err(RetireError::Release(RetireRefusal::NotLanded { .. }))), "begun, not landed"); + land_last(&h.moves); + assert_eq!(h.engine.finish_retirement().map(|unit| unit.map(|unit| unit.id())), Ok(Some(id(1)))); + assert_eq!(h.engine.finish_retirement().map(|unit| unit.is_none()), Ok(true), "given back once"); + + assert!(h.engine.stage(mind(1)).is_ok(), "A comes back after B"); + land_last(&h.moves); + assert_eq!(h.engine.handoff(), Ok(Some(id(2)))); + land_last(&h.moves); + assert_eq!(h.engine.finish_retirement().map(|unit| unit.map(|unit| unit.id())), Ok(Some(id(2)))); + assert_eq!((h.engine.active(), h.engine.staged(), h.engine.retiring()), (Some(id(1)), None, None)); +} + +// what this catches: dropping the blocks of a mind still in custody. A one-off's blocks are given up +// only once she has left the pipeline; while active or retiring the release is refused and the tier +// is not asked. +#[test] +fn a_mind_is_forgotten_only_after_she_left_the_pipeline() { + let mut h = with_one_active(); + let released = Rc::clone(&h.engine.tier().released); + assert!(h.engine.forget(id(1)).is_err(), "active"); + assert!(h.engine.stage(mind(2)).is_ok()); + land_last(&h.moves); + assert_eq!(h.engine.handoff(), Ok(Some(id(1)))); + assert!(h.engine.forget(id(1)).is_err(), "retiring"); + land_last(&h.moves); + assert_eq!(h.engine.release_retired().map(|unit| unit.id()), Ok(id(1))); + assert_eq!(h.engine.forget(id(1)), Ok(())); + assert_eq!(*released.borrow(), vec![id(1)], "the tier was asked once, after she left"); +} diff --git a/core/continuum-persona-engine/src/lib.rs b/core/continuum-persona-engine/src/lib.rs index 0fba4302bf..2a29df94cb 100644 --- a/core/continuum-persona-engine/src/lib.rs +++ b/core/continuum-persona-engine/src/lib.rs @@ -1,5 +1,5 @@ -//! The persona engine (CONTINUUM-ENGINE 4.14): our loop over libllama, replacing -//! `llamacpp_scheduler`. ONE mind decodes at a time. The next is staged as data while she +//! The persona engine (CONTINUUM-ENGINE 4.14): our loop over libllama, which replaced the +//! continuous-batching scheduler (continuum-engine `persona_scheduler` drives it). ONE mind decodes at a time. The next is staged as data while she //! decodes, the previous retires to the RAM tier after the handoff fence, and a switch binds //! her blocks in milliseconds. Nothing here is a launch flag or a slot count: one-at-a-time is //! the shape of [`pipeline::Roles`], which cannot hold two active minds. @@ -13,3 +13,4 @@ pub mod persona; pub mod pipeline; pub mod residency; pub mod schedule; +pub mod turn; diff --git a/core/continuum-persona-engine/src/pipeline/tests.rs b/core/continuum-persona-engine/src/pipeline/tests.rs index e253c6bb7f..a1bbd2540b 100644 --- a/core/continuum-persona-engine/src/pipeline/tests.rs +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -184,6 +184,9 @@ impl crate::residency::Tier for TestTier { fn begin(&mut self, what: FenceTag) -> Result { Ok(Transfer { tag: what, landed: Rc::new(Cell::new(true)), drops: self.drops.clone() }) } + fn release(&mut self, _persona: crate::persona::PersonaId) -> Result<(), crate::residency::TierRefusal> { + Ok(()) + } } // what this catches (Codex on #6130 at 9446c2be7): the copy-out begun for a persona by id alone, diff --git a/core/continuum-persona-engine/src/residency/tier.rs b/core/continuum-persona-engine/src/residency/tier.rs index a1f3a6db89..4b80634fb1 100644 --- a/core/continuum-persona-engine/src/residency/tier.rs +++ b/core/continuum-persona-engine/src/residency/tier.rs @@ -48,4 +48,8 @@ pub trait Tier { /// execution stream, layer order behind compute; or out of it into this tier). The fence it /// returns carries the same tag, so [`crate::pipeline::Roles`] accepts it only for that unit. fn begin(&mut self, what: FenceTag) -> Result; + + /// Give up `persona`'s blocks held in this tier (a mind that will not come back, such as a one-off + /// probe). Refused while she is in the execution stream. + fn release(&mut self, persona: PersonaId) -> Result<(), TierRefusal>; } diff --git a/core/continuum-persona-engine/src/turn.rs b/core/continuum-persona-engine/src/turn.rs new file mode 100644 index 0000000000..0ac78dbc5a --- /dev/null +++ b/core/continuum-persona-engine/src/turn.rs @@ -0,0 +1,44 @@ +//! A turn's prefill, from what her blocks already hold (MEMORY: never process twice). Her token +//! history is the engine's: a turn whose prompt extends it under the same basis prefills only the new +//! tail; anything else (another model or adapter set, another epoch, other media behind the same +//! token ids, a rewritten conversation) starts a newer epoch, so stale blocks are never decoded +//! against. + +#[cfg(test)] +mod tests; + +/// A token history and its basis: what her blocks were computed under beside the token ids (the +/// model, the adapter set and its scales, her epoch, the identity of any native media spliced into +/// the prompt). Two equal token sequences under different bases are different histories (Codex on the +/// serving slice). +#[derive(Debug, Clone, Copy)] +pub struct History<'a, B> { + pub basis: &'a B, + pub tokens: &'a [i32], +} + +/// What a turn must decode before she can sample. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Prefill { + /// Her blocks hold the prompt's first `from` tokens under the turn's basis; decode the rest from + /// there. + Append { from: usize }, + /// Her blocks do not hold a prefix of this prompt under this basis: start a newer epoch and + /// decode all of it. + Restart, +} + +/// Plan a turn's prefill from `held` (what her blocks hold) and `turn` (the whole prompt this turn +/// renders, and its basis). +/// +/// Sampling needs the logits of the prompt's last token, which a held position does not keep. So +/// when the prompt adds nothing past what she holds, the last token is re-decoded +/// (`Append { from: len - 1 }`, after the tier drops that one position). An empty prompt cannot be +/// sampled from and restarts, as does a mind with nothing held. +pub fn plan(held: History<'_, B>, turn: History<'_, B>) -> Prefill { + let extends = held.basis == turn.basis && !held.tokens.is_empty() && turn.tokens.starts_with(held.tokens); + if !extends || turn.tokens.is_empty() { + return Prefill::Restart; + } + Prefill::Append { from: held.tokens.len().min(turn.tokens.len() - 1) } +} diff --git a/core/continuum-persona-engine/src/turn/tests.rs b/core/continuum-persona-engine/src/turn/tests.rs new file mode 100644 index 0000000000..007007901f --- /dev/null +++ b/core/continuum-persona-engine/src/turn/tests.rs @@ -0,0 +1,58 @@ +//! A turn decodes only what her blocks do not hold, and never decodes against stale blocks. + +use super::*; + +#[derive(Debug, PartialEq)] +struct Under { + model: &'static str, + genes: &'static str, + epoch: u64, + media: &'static str, +} + +const BASE: Under = Under { model: "35b", genes: "", epoch: 1, media: "" }; + +fn h<'a>(basis: &'a Under, tokens: &'a [i32]) -> History<'a, Under> { + History { basis, tokens } +} + +// what this catches: re-prefilling her whole history every turn (the old scheduler's +// memory_seq_rm-per-request; 4.4-50 s re-prefills measured on the 35B). An extending prompt under the +// same basis decodes only its tail. +#[test] +fn an_extending_prompt_prefills_only_its_tail() { + assert_eq!(plan(h(&BASE, &[1, 2, 3]), h(&BASE, &[1, 2, 3, 4, 5])), Prefill::Append { from: 3 }); +} + +// what this catches: sampling from logits no position kept. A prompt that adds nothing re-decodes her +// last token so its logits exist. +#[test] +fn a_prompt_that_adds_nothing_re_decodes_her_last_token() { + assert_eq!(plan(h(&BASE, &[1, 2, 3]), h(&BASE, &[1, 2, 3])), Prefill::Append { from: 2 }); +} + +// what this catches: decoding a rewritten conversation against blocks that hold another history. A +// diverging, shorter or empty prompt, and a mind with nothing held, start a newer epoch. +#[test] +fn a_prompt_that_does_not_extend_her_history_restarts() { + assert_eq!(plan(h(&BASE, &[1, 2, 3]), h(&BASE, &[1, 9, 3, 4])), Prefill::Restart, "diverges"); + assert_eq!(plan(h(&BASE, &[1, 2, 3]), h(&BASE, &[1, 2])), Prefill::Restart, "shorter than she holds"); + assert_eq!(plan(h(&BASE, &[1, 2, 3]), h(&BASE, &[])), Prefill::Restart, "nothing to sample from"); + assert_eq!(plan(h(&BASE, &[]), h(&BASE, &[1, 2])), Prefill::Restart, "nothing held yet"); +} + +// what this catches: reusing blocks computed under another basis because the token ids match (Codex +// on the serving slice). Another model, adapter set, epoch or media identity restarts. +#[test] +fn the_same_tokens_under_another_basis_restart() { + let tokens = [1, 2, 3]; + let longer = [1, 2, 3, 4]; + for other in [ + Under { model: "4b", ..BASE }, + Under { genes: "rust-review:1.0", ..BASE }, + Under { epoch: 2, ..BASE }, + Under { media: "sha256:ab12", ..BASE }, + ] { + assert_eq!(plan(h(&BASE, &tokens), h(&other, &longer)), Prefill::Restart, "{other:?}"); + } +} diff --git a/core/continuum-persona-llama/examples/persona_switch.rs b/core/continuum-persona-llama/examples/persona_switch.rs index cb49d82954..788273dcef 100644 --- a/core/continuum-persona-llama/examples/persona_switch.rs +++ b/core/continuum-persona-llama/examples/persona_switch.rs @@ -6,13 +6,14 @@ //! //! cargo run --release --features metal,test-fixtures --example persona_switch -- +use std::sync::Arc; use std::time::{Duration, Instant}; use continuum_persona_engine::engine::PersonaEngine; use continuum_persona_engine::persona::{Epoch, PersonaId}; use continuum_persona_engine::pipeline::Identified; use continuum_persona_engine::residency::{Direction, Execute, FenceTag, Tier}; -use continuum_persona_llama::{Rebind, Step, UnifiedTier}; +use continuum_persona_llama::{base_genes, Rebind, Step, UnifiedTier}; use llama::{Batch, ContextParams, FlashAttn, Model, ModelParams}; /// One mind in the run: who she is, where her history ends, and her last sampled token. @@ -86,7 +87,7 @@ fn a_refused_newer_epoch_keeps_her_parked_blocks(model: &Model, ctx: &mut llama: let mut tier = UnifiedTier::new(ctx); tier.begin(tag(1, Direction::In)).map_err(|e| e.to_string())?; let seq = tier.stream_of(her).ok_or("replay: she is not bound")?.seq(); - tier.submit(her, Epoch(1), Step { tokens: tokens.clone(), from: 0, logits_at_end: false }).map_err(|e| e.to_string())?; + tier.submit(her, Epoch(1), Step { tokens: tokens.clone(), from: 0, logits_at_end: false, genes: base_genes() }).map_err(|e| e.to_string())?; tier.settle().map_err(|e| e.to_string())?; let held_to = tier.position_of(her).ok_or("replay: she is not bound after her decode")?; tier.begin(tag(1, Direction::Out)).map_err(|e| e.to_string())?; @@ -123,6 +124,7 @@ fn main() -> Result<(), String> { adopted_context_is_refused(&model, &mut ctx)?; a_refused_newer_epoch_keeps_her_parked_blocks(&model, &mut ctx)?; let mut engine: PersonaEngine> = PersonaEngine::new(UnifiedTier::new(&mut ctx)); + let genes = base_genes(); let mut parked: Vec = (0..minds) .map(|i| { @@ -165,7 +167,7 @@ fn main() -> Result<(), String> { if !prompt.is_empty() { let t = Instant::now(); for chunk in prompt.chunks(2048) { - engine.submit(Step { tokens: chunk.to_vec(), from: pos, logits_at_end: true }).map_err(|e| e.to_string())?; + engine.submit(Step { tokens: chunk.to_vec(), from: pos, logits_at_end: true, genes: Arc::clone(&genes) }).map_err(|e| e.to_string())?; pos += chunk.len() as i32; last = argmax(engine.tier().logits_ith(chunk.len() as i32 - 1)); } @@ -173,7 +175,7 @@ fn main() -> Result<(), String> { } let t = Instant::now(); for _ in 0..decode_tokens { - engine.submit(Step { tokens: vec![last], from: pos, logits_at_end: true }).map_err(|e| e.to_string())?; + engine.submit(Step { tokens: vec![last], from: pos, logits_at_end: true, genes: Arc::clone(&genes) }).map_err(|e| e.to_string())?; pos += 1; last = argmax(engine.tier().logits_ith(0)); } diff --git a/core/continuum-persona-llama/src/lib.rs b/core/continuum-persona-llama/src/lib.rs index 964a1e07b3..6adb2ffb3d 100644 --- a/core/continuum-persona-llama/src/lib.rs +++ b/core/continuum-persona-llama/src/lib.rs @@ -6,4 +6,4 @@ mod unified_tier; -pub use unified_tier::{Decoded, Landed, Rebind, Step, Stream, UnifiedTier}; +pub use unified_tier::{base_genes, Decoded, Genes, Landed, Rebind, Step, Stream, UnifiedTier, STREAMS}; diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index c4f1c00db0..02ed0d742e 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -8,10 +8,15 @@ use std::cell::Cell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::Arc; use continuum_persona_engine::persona::{Epoch, PersonaId}; use continuum_persona_engine::residency::{Completion, Direction, Execute, Fence, FenceTag, Native, Tier, TierRefusal}; -use llama::{Batch, BindRefusal, Context, PersonaBlocks, PersonaOwner, PersonaRefusal}; +use llama::{Batch, BindRefusal, Context, LoraAdapter, PersonaBlocks, PersonaOwner, PersonaRefusal, Sampler}; + +/// Execution streams one context holds: the active mind's and the next mind's. The context is +/// created with this many sequences; no more are ever decoded at once (one decodes, one binds). +pub const STREAMS: usize = 2; /// One of the context's two execution streams, by the sequence id the context knows it as. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -58,7 +63,7 @@ struct Mind { pub struct UnifiedTier<'c, 'm> { ctx: &'c mut Context<'m>, /// Who occupies each execution stream: occupancy is the streams', never a scan of every mind. - streams: [Option; 2], + streams: [Option; STREAMS], minds: HashMap, /// Each persona's owner stamp for the fork, issued once per persona by this tier: exact within the /// process the RAM tier lives in (a persona is a 128-bit id; the fork stamps 64 bits). @@ -66,11 +71,13 @@ pub struct UnifiedTier<'c, 'm> { last_rebind: Option, /// The last submitted decode's landed flag, until the device is known to have finished it. in_flight: Option>>, + /// The gene set on the context now (`None` before any step). + applied_genes: Option, } impl<'c, 'm> UnifiedTier<'c, 'm> { pub fn new(ctx: &'c mut Context<'m>) -> Self { - Self { ctx, streams: [None, None], minds: HashMap::new(), handles: HashMap::new(), last_rebind: None, in_flight: None } + Self { ctx, streams: [None; STREAMS], minds: HashMap::new(), handles: HashMap::new(), last_rebind: None, in_flight: None, applied_genes: None } } /// The stream `persona` is bound to, if she is in the execution stream. @@ -93,6 +100,21 @@ impl<'c, 'm> UnifiedTier<'c, 'm> { self.stream_of(persona).map(|stream| self.ctx.memory_seq_pos_max(stream.seq())) } + /// Sample her next token from output `i` of the last decode. Like [`Self::logits_ith`], reading the + /// logits synchronizes, so it also attests the last decode landed. + pub fn sample(&self, sampler: &mut Sampler, i: i32) -> i32 { + let token = sampler.sample(self.ctx, i); + if let Some(landed) = &self.in_flight { + landed.set(true); + } + token + } + + /// The bytes `persona`'s stream holds, while she is bound (her footprint). + pub fn state_bytes_of(&self, persona: PersonaId) -> Option { + self.stream_of(persona).map(|stream| self.ctx.seq_state_bytes(stream.seq())) + } + /// The raw context, past every binding: only for custody replays that must put foreign state on a /// stream (an adopted context). Never on the production path. #[cfg(feature = "test-fixtures")] @@ -199,15 +221,35 @@ impl Tier for UnifiedTier<'_, '_> { } Ok(Landed(what)) } + + fn release(&mut self, persona: PersonaId) -> Result<(), TierRefusal> { + if self.stream_of(persona).is_some() { + return Err(refused(persona, "bound: move her out before releasing her")); + } + self.minds.remove(&persona); + Ok(()) + } } /// One step of the bound mind's decode: her tokens from position `from`, with the logits of the last /// one if `logits_at_end`. It names no sequence: the tier decodes on the stream she is bound to. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone)] pub struct Step { pub tokens: Vec, pub from: i32, pub logits_at_end: bool, + /// The gene set she decodes under. The tier applies it only when it differs from the set + /// already on the context, and only for her: no step is decoded under another mind's genes. + pub genes: Genes, +} + +/// A gene set: adapter handles and their scales, shared so steps name it without copying. Empty is +/// the base model. +pub type Genes = Arc<[(Arc, f32)]>; + +/// The base model's gene set (no adapters). +pub fn base_genes() -> Genes { + Arc::from(Vec::new()) } /// A decode this tier submitted. `llama_decode` may return while the device still runs it (libllama @@ -234,6 +276,20 @@ impl Execute for UnifiedTier<'_, '_> { if held != Some(epoch) { return Err(refused(persona, "another epoch of her is bound")); } + // A step at `from` replaces whatever she held from there (a re-decoded last token, a restart + // at 0, a failed turn's partial tail), so her stream never holds two tokens at one position. + if self.ctx.memory_seq_pos_max(stream.seq()) >= step.from { + self.settle()?; + if !self.ctx.memory_seq_rm(stream.seq(), step.from, -1) { + return Err(refused(persona, "the engine could not drop her positions")); + } + } + if !self.applied_genes.as_ref().is_some_and(|applied| Arc::ptr_eq(applied, &step.genes)) { + let genes: Vec<(&LoraAdapter, f32)> = step.genes.iter().map(|(adapter, scale)| (adapter.as_ref(), *scale)).collect(); + let applied = if genes.is_empty() { self.ctx.clear_loras() } else { self.ctx.set_loras(&genes) }; + applied.map_err(|message| TierRefusal { tier: TIER, persona, reason: "the engine refused her genes", native: Native::Reported(message) })?; + self.applied_genes = Some(Arc::clone(&step.genes)); + } let last = step.tokens.len().checked_sub(1).ok_or_else(|| refused(persona, "an empty step"))?; let count = i32::try_from(step.tokens.len()).map_err(|_| refused(persona, "a step longer than a batch can hold"))?; let mut batch = Batch::allocated(count, 1); diff --git a/scripts/ratchets/rust-warnings-baseline.txt b/scripts/ratchets/rust-warnings-baseline.txt index 48082f72f0..b4de394767 100644 --- a/scripts/ratchets/rust-warnings-baseline.txt +++ b/scripts/ratchets/rust-warnings-baseline.txt @@ -1 +1 @@ -12 +11 diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index c718d1e2d8..6a683db998 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -148,7 +148,9 @@ test('a crate-local change runs that crate and every crate that depends on it', const belowMind = crates('continuum-engine', 'continuum-vitals', 'continuum-prompt', 'continuum-engram', 'continuum-capture', 'continuum-embedding', 'continuum-store', 'continuum-models', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-academy', 'continuum-sentinel', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core', 'continuum-gateway'); assert.deepEqual(scope(['core/continuum-engine/src/lib.rs']), belowMind); // The floor crates (base, host, git) sit below the kernel: a kernel change runs everything above them. - assert.deepEqual(scope(['core/continuum-persona-engine/src/persona/unit.rs']), crates('continuum-persona-engine', 'continuum-persona-llama')); + // The persona engine sits under serving's engine now (persona_scheduler drives it): a change runs it, + // its llama tier, and everything the engine reaches. + assert.deepEqual(scope(['core/continuum-persona-engine/src/persona/unit.rs']), crates(...belowMind.crates, 'continuum-persona-engine', 'continuum-persona-llama')); const aboveFloor = TESTED_CRATES.filter(n => !BELOW_KERNEL.includes(n)); assert.deepEqual(scope(['core/continuum-kernel/src/lib.rs']), { crates: aboveFloor, cli: false }); // A floor change runs the floor crate and every crate built on it.