serve: plan and queue the adaptive swaps while the GPU runs the draft, not before the commit (LELEKA_SERVE_ADAPT_DEFER=off restores the earlier order)

begin_adaptation (choose_swaps over 24,576 counts, up to 96 span lookups and swap queueings, the count decay) ran on the host between the window and the commit/draft launch:
0.6 ms on an adaptation round, 0.15 ms per round on average, during which the GPU sat idle. The host now records the round at begin_adaptation and runs the same work right after
launch_draft (span round.adapt_deferred), at the latest at join_adaptation, always before the next round's apply_pending. The decision inputs (counts, residency) cannot change in between,
so the swaps are the same ones in the same order; only the host time they take moves into the draft's shadow. Not yet measured on the 5090.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 02:24:02 +01:00
co-authored by Claude Sonnet 5.5
parent 359b4b5a6a
commit bb47b296c0
2 changed files with 910 additions and 879 deletions
File diff suppressed because it is too large Load Diff
@@ -1,278 +1,283 @@
//! Native binding of `OriginalServePort` to the genuine driver Verifier. //! Native binding of `OriginalServePort` to the genuine driver Verifier.
//! //!
//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`) //! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`)
//! is bound here directly: windows are only the receipts of a genuinely completed //! is bound here directly: windows are only the receipts of a genuinely completed
//! `run`, the commit is the driver's asynchronous event commit, and the accepted //! `run`, the commit is the driver's asynchronous event commit, and the accepted
//! prefix is cross-checked against the driver's own staged commit tokens before the //! prefix is cross-checked against the driver's own staged commit tokens before the
//! session lineage is published. Everything that needs owners that do not exist as //! session lineage is published. Everything that needs owners that do not exist as
//! typed runtime objects yet is demanded from a `NativeServeHost` implementation //! typed runtime objects yet is demanded from a `NativeServeHost` implementation
//! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan //! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan
//! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the //! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the
//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. //! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them.
use super::contract::{Error,Result}; use super::contract::{Error,Result};
use super::original_serve_profile as profile; use super::original_serve_profile as profile;
use super::original_serve_engine::{DraftCompletion,OriginalServePort}; use super::original_serve_engine::{DraftCompletion,OriginalServePort};
use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier,
OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult};
use std::cell::RefCell; use std::cell::RefCell;
/// What the serving owner must supply for the verified-window serve path. /// What the serving owner must supply for the verified-window serve path.
pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { pub(in crate::qwen_forward) trait NativeServeHost<'ctx> {
type TargetCheckpoint; type TargetCheckpoint;
type DraftCheckpoint; type DraftCheckpoint;
type Adaptive; type Adaptive;
type Seed; type Seed;
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>;
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint>; fn checkpoint_target(&self)->Result<Self::TargetCheckpoint>;
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint>; fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint>;
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>;
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>;
fn apply_pending(&mut self)->Result<()>; fn apply_pending(&mut self)->Result<()>;
/// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU
/// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window.
fn run_window<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>( fn run_window<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32],
)->Result<OriginalVerifyWindowResult>; )->Result<OriginalVerifyWindowResult>;
/// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so
/// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier).
fn commit_enqueued(&mut self,keep:usize)->Result<()>; fn commit_enqueued(&mut self,keep:usize)->Result<()>;
/// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent
/// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the
/// accepted input tokens exactly as the driver staged them. /// accepted input tokens exactly as the driver staged them.
fn publish_committed<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>( fn publish_committed<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32],
)->Result<()>; )->Result<()>;
fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive>; fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive>;
fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work
fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred.
/// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())}
#[allow(clippy::too_many_arguments)] fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>;
fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>;
accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>; /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage.
/// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the #[allow(clippy::too_many_arguments)]
/// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
#[allow(clippy::too_many_arguments)] accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>;
fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the
accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`...
/// ...and completed AFTER it, over the published branch. #[allow(clippy::too_many_arguments)]
fn finish_draft(&mut self)->Result<DraftCompletion>; fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
fn drain_draft(&mut self)->Result<()>; accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>;
#[allow(clippy::too_many_arguments)] /// ...and completed AFTER it, over the published branch.
fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>; fn finish_draft(&mut self)->Result<DraftCompletion>;
fn drain_first(&mut self)->Result<()>; fn drain_draft(&mut self)->Result<()>;
} #[allow(clippy::too_many_arguments)]
fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>;
/// Receipt of one completed driver window. The head selection is single-use: the fn drain_first(&mut self)->Result<()>;
/// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. }
pub(in crate::qwen_forward) struct NativeWindow {
generation:u64,position:i64,rows:usize,ids:Vec<i32>,inputs:Vec<i32>, /// Receipt of one completed driver window. The head selection is single-use: the
selection:RefCell<Option<NativeHeadSelection>>,keep:Option<usize>, /// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument.
} pub(in crate::qwen_forward) struct NativeWindow {
impl NativeWindow { generation:u64,position:i64,rows:usize,ids:Vec<i32>,inputs:Vec<i32>,
pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} selection:RefCell<Option<NativeHeadSelection>>,keep:Option<usize>,
} }
impl NativeWindow {
pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation}
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { }
verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec<i32>)>,failed:bool,
} pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H>
impl<'ctx,R,H> NativeServePort<'ctx,R,H> where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec<i32>)>,failed:bool,
pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self { }
Self{verifier,host,pending_publish:None,failed:false} impl<'ctx,R,H> NativeServePort<'ctx,R,H>
} where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self {
pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} Self{verifier,host,pending_publish:None,failed:false}
pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} }
pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier}
fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier}
/// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with pub(in crate::qwen_forward) fn host(&self)->&H {&self.host}
/// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)}
/// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}}
fn settle_commit(&mut self)->Result<()> { /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with
let Some((position,expected))=self.pending_publish.take() else { /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target
return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op).
}; fn settle_commit(&mut self)->Result<()> {
let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; let Some((position,expected))=self.pending_publish.take() else {
if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}};
// The driver staged the commit tokens itself; they must be exactly the accepted prefix. };
let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()};
if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);}
let _p=profile::span("commit.publish"); // The driver staged the commit tokens itself; they must be exactly the accepted prefix.
let published=self.host.publish_committed(&mut self.verifier,position,&expected); let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}};
if published.is_err() {self.failed=true;}published if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);}
} let _p=profile::span("commit.publish");
} let published=self.host.publish_committed(&mut self.verifier,position,&expected);
if published.is_err() {self.failed=true;}published
/// The two bring-up window traces, read once (they sat on the per-window path). }
fn trace_logprobs()->Option<usize> { }
static TOPK:std::sync::OnceLock<Option<usize>>=std::sync::OnceLock::new();
*TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::<usize>().ok()).filter(|k|*k>0)) /// The two bring-up window traces, read once (they sat on the per-window path).
} fn trace_logprobs()->Option<usize> {
fn trace_residual()->Option<&'static std::ffi::OsString> { static TOPK:std::sync::OnceLock<Option<usize>>=std::sync::OnceLock::new();
static DIR:std::sync::OnceLock<Option<std::ffi::OsString>>=std::sync::OnceLock::new(); *TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::<usize>().ok()).filter(|k|*k>0))
DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref() }
} fn trace_residual()->Option<&'static std::ffi::OsString> {
static DIR:std::sync::OnceLock<Option<std::ffi::OsString>>=std::sync::OnceLock::new();
/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref()
/// order; A/B control). Default: generate.cpp's order, the draft enqueued behind the commit event. }
fn overlap()->bool {
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new(); /// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized
*ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0")) /// order; A/B control). Default: generate.cpp's order, the draft enqueued behind the commit event.
} fn overlap()->bool {
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> *ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0"))
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { }
type Window=NativeWindow;
type Seed=H::Seed; impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H>
type TargetCheckpoint=H::TargetCheckpoint; where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
type DraftCheckpoint=H::DraftCheckpoint; type Window=NativeWindow;
type Adaptive=H::Adaptive; type Seed=H::Seed;
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { type TargetCheckpoint=H::TargetCheckpoint;
self.live()?;self.host.validate_current(consumed,input,position) type DraftCheckpoint=H::DraftCheckpoint;
} type Adaptive=H::Adaptive;
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint> {self.live()?;self.host.checkpoint_target()} fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> {
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint> {self.live()?;self.host.checkpoint_draft()} self.live()?;self.host.validate_current(consumed,input,position)
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { }
// Whatever was in flight is dead: the window state is discarded by the driver (the fn checkpoint_target(&self)->Result<Self::TargetCheckpoint> {self.live()?;self.host.checkpoint_target()}
// uncommitted window never touched GDN state, and a committed one is fenced first). fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint> {self.live()?;self.host.checkpoint_draft()}
self.pending_publish=None; fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> {
let restored=self.host.restore_target(checkpoint); // Whatever was in flight is dead: the window state is discarded by the driver (the
if restored.is_err() {self.failed=true;}restored // uncommitted window never touched GDN state, and a committed one is fenced first).
} self.pending_publish=None;
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { let restored=self.host.restore_target(checkpoint);
let restored=self.host.restore_draft(checkpoint); if restored.is_err() {self.failed=true;}restored
if restored.is_err() {self.failed=true;}restored }
} fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> {
fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} let restored=self.host.restore_draft(checkpoint);
fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result<NativeWindow> { if restored.is_err() {self.failed=true;}restored
self.live()?; }
let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()}
let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result<NativeWindow> {
// The driver's own receipt is authoritative: it must describe exactly this window. self.live()?;
let t=inputs.len(); let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?;
let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?};
&&result.selection.position()==position as u64; // The driver's own receipt is authoritative: it must describe exactly this window.
if !ok {self.failed=true;return Err(Error::IdentityMismatch);} let t=inputs.len();
let mut ids=result.selection.ids().to_vec(); let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t
// Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks &&result.selection.position()==position as u64;
// the controller verifies drafts against and commits next are the forced text's tokens. if !ok {self.failed=true;return Err(Error::IdentityMismatch);}
let forced_differ=super::quality_force::apply(position,&mut ids); let mut ids=result.selection.ids().to_vec();
if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks
// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window. // the controller verifies drafts against and commits next are the forced text's tokens.
if let Some(k)=trace_logprobs() { let forced_differ=super::quality_force::apply(position,&mut ids);
let mut line:Vec<u8>=Vec::new(); if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");}
crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}"); // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
match self.verifier.window_logprobs_topk(&ids,-1,k,&mut line) { if let Some(k)=trace_logprobs() {
Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), let mut line:Vec<u8>=Vec::new();
Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}");
} match self.verifier.window_logprobs_topk(&ids,-1,k,&mut line) {
} Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()),
// Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=<dir>): the final residual R of every row of the completed window, Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"),
// raw little-endian f32 (rows, hc*n_embd), file `r_win<seq>_pos<first position>.f32`. }
if let Some(dir)=trace_residual() { }
match self.verifier.window_residual_rows() { // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=<dir>): the final residual R of every row of the completed window,
Ok((rows,start,values))=>{ // raw little-endian f32 (rows, hc*n_embd), file `r_win<seq>_pos<first position>.f32`.
let bytes:Vec<u8>=values.iter().flat_map(|v|v.to_le_bytes()).collect(); if let Some(dir)=trace_residual() {
static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); match self.verifier.window_residual_rows() {
let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); Ok((rows,start,values))=>{
let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); let bytes:Vec<u8>=values.iter().flat_map(|v|v.to_le_bytes()).collect();
eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0);
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed);
if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32"));
let bytes:Vec<u8>=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display());
let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); }
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } if let Ok(Some(ladder))=self.verifier.window_ladder_rows() {
} let bytes:Vec<u8>=ladder.iter().flat_map(|v|v.to_le_bytes()).collect();
} let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32"));
Err(e)=>eprintln!("DBG residual err {e:?}"), if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); }
} }
} }
Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), Err(e)=>eprintln!("DBG residual err {e:?}"),
selection:RefCell::new(Some(result.selection)),keep:None}) }
} }
fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(),
self.live()?; selection:RefCell::new(Some(result.selection)),keep:None})
if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} }
// A capture-only or already-superseded window cannot pass: the driver mints fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> {
// `completed_window` only for the genuinely completed current generation. self.live()?;
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);}
if completed.generation()!=window.generation||completed.rows()!=window.rows // A capture-only or already-superseded window cannot pass: the driver mints
||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { // `completed_window` only for the genuinely completed current generation.
return Err(Error::IdentityMismatch); let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?;
} if completed.generation()!=window.generation||completed.rows()!=window.rows
if let Some(selection)=window.selection.borrow().as_ref() { ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? {
completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; return Err(Error::IdentityMismatch);
} }
Ok(()) if let Some(selection)=window.selection.borrow().as_ref() {
} completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?;
fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} }
fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { Ok(())
self.live()?; }
if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids}
let _p=profile::span("round.commit"); fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> {
if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} self.live()?;
if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);}
window.keep=Some(keep); let _p=profile::span("round.commit");
self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);}
} if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);}
fn wait_commit(&mut self)->Result<()> {self.settle_commit()} window.keep=Some(keep);
fn drain_window(&mut self,_window:NativeWindow)->Result<()> { self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(())
// The retained residuals belong to the driver bank; they stay alive until the next }
// window (the bank, not this receipt, owns them), so draining releases only the receipt. fn wait_commit(&mut self)->Result<()> {self.settle_commit()}
Ok(()) fn drain_window(&mut self,_window:NativeWindow)->Result<()> {
} // The retained residuals belong to the driver bank; they stay alive until the next
fn discard_window(&mut self)->Result<()> { // window (the bank, not this receipt, owns them), so draining releases only the receipt.
// an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) Ok(())
if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} }
let _p=profile::span("round.discard_window"); fn discard_window(&mut self)->Result<()> {
if let Err(e)=self.verifier.discard_window() { // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`)
eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);}
self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); let _p=profile::span("round.discard_window");
} if let Err(e)=self.verifier.discard_window() {
Ok(()) eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})");
} self.failed=true;return Err(super::original_serve_verifier::driver_error(&e));
fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive> {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} }
fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} Ok(())
fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} }
fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive> {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)}
max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> { fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)}
self.live()?; fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)}
let _p=profile::span("round.draft_committed"); fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32],
// Literal order: commit enqueued first, draft depends on its event on the same stream. max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> {
if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() { self.live()?;
return Err(Error::IdentityMismatch); let _p=profile::span("round.draft_committed");
} // Literal order: commit enqueued first, draft depends on its event on the same stream.
if overlap() && self.pending_publish.is_some() { if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() {
// generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is return Err(Error::IdentityMismatch);
// enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and }
// the draft completes only over that published branch. if overlap() && self.pending_publish.is_some() {
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is
let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and
let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; // the draft completes only over that published branch.
let launched={let _p=profile::span("draft.launch"); let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())}; let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch);
if let Err(e)=launched {self.failed=true;return Err(e);} let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)};
self.settle_commit()?; let launched={let _p=profile::span("draft.launch");
let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())};
if finished.is_err() {self.failed=true;} if let Err(e)=launched {self.failed=true;return Err(e);}
return finished; // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow
} if let Err(e)={let _p=profile::span("round.adapt_deferred");self.host.run_deferred_adaptation()} {self.failed=true;return Err(e);}
// Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is self.settle_commit()?;
// published before the draft launches. let finished={let _p=profile::span("draft.finish");self.host.finish_draft()};
self.settle_commit()?; if finished.is_err() {self.failed=true;}
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); return finished;
let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); }
let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is
let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; // published before the draft launches.
if draft.is_err() {self.failed=true;}draft self.settle_commit()?;
} let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
fn drain_draft(&mut self)->Result<()> { let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch);
let drained=self.host.drain_draft(); let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)};
if drained.is_err() {self.failed=true;}drained let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)};
} if draft.is_err() {self.failed=true;}draft
fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> { }
self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled) fn drain_draft(&mut self)->Result<()> {
} let drained=self.host.drain_draft();
fn drain_first(&mut self)->Result<()> {self.host.drain_first()} if drained.is_err() {self.failed=true;}drained
} }
fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> {
self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled)
}
fn drain_first(&mut self)->Result<()> {self.host.drain_first()}
}