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:
co-authored by
Claude Sonnet 5.5
parent
359b4b5a6a
commit
bb47b296c0
File diff suppressed because it is too large
Load Diff
@@ -1,278 +1,283 @@
|
||||
//! Native binding of `OriginalServePort` to the genuine driver Verifier.
|
||||
//!
|
||||
//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`)
|
||||
//! 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
|
||||
//! 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
|
||||
//! typed runtime objects yet is demanded from a `NativeServeHost` implementation
|
||||
//! (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
|
||||
//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them.
|
||||
use super::contract::{Error,Result};
|
||||
use super::original_serve_profile as profile;
|
||||
use super::original_serve_engine::{DraftCompletion,OriginalServePort};
|
||||
use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier,
|
||||
OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// What the serving owner must supply for the verified-window serve path.
|
||||
pub(in crate::qwen_forward) trait NativeServeHost<'ctx> {
|
||||
type TargetCheckpoint;
|
||||
type DraftCheckpoint;
|
||||
type Adaptive;
|
||||
type Seed;
|
||||
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>;
|
||||
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint>;
|
||||
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint>;
|
||||
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>;
|
||||
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>;
|
||||
fn apply_pending(&mut self)->Result<()>;
|
||||
/// 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.
|
||||
fn run_window<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
|
||||
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32],
|
||||
)->Result<OriginalVerifyWindowResult>;
|
||||
/// 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).
|
||||
fn commit_enqueued(&mut self,keep:usize)->Result<()>;
|
||||
/// 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
|
||||
/// accepted input tokens exactly as the driver staged them.
|
||||
fn publish_committed<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
|
||||
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32],
|
||||
)->Result<()>;
|
||||
fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive>;
|
||||
fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>;
|
||||
fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>;
|
||||
/// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
|
||||
accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>;
|
||||
/// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the
|
||||
/// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`...
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
|
||||
accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>;
|
||||
/// ...and completed AFTER it, over the published branch.
|
||||
fn finish_draft(&mut self)->Result<DraftCompletion>;
|
||||
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>;
|
||||
fn drain_first(&mut self)->Result<()>;
|
||||
}
|
||||
|
||||
/// Receipt of one completed driver window. The head selection is single-use: the
|
||||
/// 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>,
|
||||
selection:RefCell<Option<NativeHeadSelection>>,keep:Option<usize>,
|
||||
}
|
||||
impl NativeWindow {
|
||||
pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation}
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec<i32>)>,failed:bool,
|
||||
}
|
||||
impl<'ctx,R,H> NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self {
|
||||
Self{verifier,host,pending_publish:None,failed:false}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier}
|
||||
pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier}
|
||||
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)}
|
||||
fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}}
|
||||
/// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with
|
||||
/// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target
|
||||
/// 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 Some((position,expected))=self.pending_publish.take() else {
|
||||
return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}};
|
||||
};
|
||||
let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()};
|
||||
if waited.is_err() {self.failed=true;return 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);}};
|
||||
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))
|
||||
}
|
||||
fn trace_residual()->Option<&'static std::ffi::OsString> {
|
||||
static DIR:std::sync::OnceLock<Option<std::ffi::OsString>>=std::sync::OnceLock::new();
|
||||
DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref()
|
||||
}
|
||||
|
||||
/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized
|
||||
/// 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();
|
||||
*ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0"))
|
||||
}
|
||||
|
||||
impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
type Window=NativeWindow;
|
||||
type Seed=H::Seed;
|
||||
type TargetCheckpoint=H::TargetCheckpoint;
|
||||
type DraftCheckpoint=H::DraftCheckpoint;
|
||||
type Adaptive=H::Adaptive;
|
||||
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> {
|
||||
self.live()?;self.host.validate_current(consumed,input,position)
|
||||
}
|
||||
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint> {self.live()?;self.host.checkpoint_target()}
|
||||
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint> {self.live()?;self.host.checkpoint_draft()}
|
||||
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> {
|
||||
// Whatever was in flight is dead: the window state is discarded by the driver (the
|
||||
// uncommitted window never touched GDN state, and a committed one is fenced first).
|
||||
self.pending_publish=None;
|
||||
let restored=self.host.restore_target(checkpoint);
|
||||
if restored.is_err() {self.failed=true;}restored
|
||||
}
|
||||
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> {
|
||||
let restored=self.host.restore_draft(checkpoint);
|
||||
if restored.is_err() {self.failed=true;}restored
|
||||
}
|
||||
fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()}
|
||||
fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result<NativeWindow> {
|
||||
self.live()?;
|
||||
let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?;
|
||||
let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?};
|
||||
// The driver's own receipt is authoritative: it must describe exactly this window.
|
||||
let t=inputs.len();
|
||||
let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t
|
||||
&&result.selection.position()==position as u64;
|
||||
if !ok {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let mut ids=result.selection.ids().to_vec();
|
||||
// Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks
|
||||
// the controller verifies drafts against and commits next are the forced text's tokens.
|
||||
let forced_differ=super::quality_force::apply(position,&mut ids);
|
||||
if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");}
|
||||
// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
|
||||
if let Some(k)=trace_logprobs() {
|
||||
let mut line:Vec<u8>=Vec::new();
|
||||
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()),
|
||||
Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"),
|
||||
}
|
||||
}
|
||||
// Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=<dir>): the final residual R of every row of the completed window,
|
||||
// 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() {
|
||||
Ok((rows,start,values))=>{
|
||||
let bytes:Vec<u8>=values.iter().flat_map(|v|v.to_le_bytes()).collect();
|
||||
static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0);
|
||||
let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed);
|
||||
let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32"));
|
||||
eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display());
|
||||
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual 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"));
|
||||
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); }
|
||||
}
|
||||
}
|
||||
Err(e)=>eprintln!("DBG residual err {e:?}"),
|
||||
}
|
||||
}
|
||||
Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(),
|
||||
selection:RefCell::new(Some(result.selection)),keep:None})
|
||||
}
|
||||
fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> {
|
||||
self.live()?;
|
||||
if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);}
|
||||
// A capture-only or already-superseded window cannot pass: the driver mints
|
||||
// `completed_window` only for the genuinely completed current generation.
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?;
|
||||
if completed.generation()!=window.generation||completed.rows()!=window.rows
|
||||
||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if let Some(selection)=window.selection.borrow().as_ref() {
|
||||
completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids}
|
||||
fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> {
|
||||
self.live()?;
|
||||
if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);}
|
||||
let _p=profile::span("round.commit");
|
||||
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);}
|
||||
window.keep=Some(keep);
|
||||
self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(())
|
||||
}
|
||||
fn wait_commit(&mut self)->Result<()> {self.settle_commit()}
|
||||
fn drain_window(&mut self,_window:NativeWindow)->Result<()> {
|
||||
// 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.
|
||||
Ok(())
|
||||
}
|
||||
fn discard_window(&mut self)->Result<()> {
|
||||
// an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`)
|
||||
if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let _p=profile::span("round.discard_window");
|
||||
if let Err(e)=self.verifier.discard_window() {
|
||||
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));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
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)}
|
||||
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],
|
||||
max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> {
|
||||
self.live()?;
|
||||
let _p=profile::span("round.draft_committed");
|
||||
// Literal order: commit enqueued first, draft depends on its event on the same stream.
|
||||
if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if overlap() && self.pending_publish.is_some() {
|
||||
// generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is
|
||||
// enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and
|
||||
// the draft completes only over that published branch.
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
|
||||
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)};
|
||||
let launched={let _p=profile::span("draft.launch");
|
||||
self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())};
|
||||
if let Err(e)=launched {self.failed=true;return Err(e);}
|
||||
self.settle_commit()?;
|
||||
let finished={let _p=profile::span("draft.finish");self.host.finish_draft()};
|
||||
if finished.is_err() {self.failed=true;}
|
||||
return finished;
|
||||
}
|
||||
// Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is
|
||||
// published before the draft launches.
|
||||
self.settle_commit()?;
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
|
||||
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)};
|
||||
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 drain_draft(&mut self)->Result<()> {
|
||||
let drained=self.host.drain_draft();
|
||||
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()}
|
||||
}
|
||||
//! Native binding of `OriginalServePort` to the genuine driver Verifier.
|
||||
//!
|
||||
//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`)
|
||||
//! 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
|
||||
//! 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
|
||||
//! typed runtime objects yet is demanded from a `NativeServeHost` implementation
|
||||
//! (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
|
||||
//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them.
|
||||
use super::contract::{Error,Result};
|
||||
use super::original_serve_profile as profile;
|
||||
use super::original_serve_engine::{DraftCompletion,OriginalServePort};
|
||||
use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier,
|
||||
OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// What the serving owner must supply for the verified-window serve path.
|
||||
pub(in crate::qwen_forward) trait NativeServeHost<'ctx> {
|
||||
type TargetCheckpoint;
|
||||
type DraftCheckpoint;
|
||||
type Adaptive;
|
||||
type Seed;
|
||||
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>;
|
||||
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint>;
|
||||
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint>;
|
||||
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>;
|
||||
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>;
|
||||
fn apply_pending(&mut self)->Result<()>;
|
||||
/// 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.
|
||||
fn run_window<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
|
||||
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32],
|
||||
)->Result<OriginalVerifyWindowResult>;
|
||||
/// 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).
|
||||
fn commit_enqueued(&mut self,keep:usize)->Result<()>;
|
||||
/// 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
|
||||
/// accepted input tokens exactly as the driver staged them.
|
||||
fn publish_committed<R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>(
|
||||
&mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32],
|
||||
)->Result<()>;
|
||||
fn begin_adaptation(&mut self,next_round:u64)->Result<Self::Adaptive>;
|
||||
/// 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
|
||||
/// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred.
|
||||
fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())}
|
||||
fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>;
|
||||
fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>;
|
||||
/// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
|
||||
accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion>;
|
||||
/// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the
|
||||
/// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`...
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64,
|
||||
accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>;
|
||||
/// ...and completed AFTER it, over the published branch.
|
||||
fn finish_draft(&mut self)->Result<DraftCompletion>;
|
||||
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>;
|
||||
fn drain_first(&mut self)->Result<()>;
|
||||
}
|
||||
|
||||
/// Receipt of one completed driver window. The head selection is single-use: the
|
||||
/// 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>,
|
||||
selection:RefCell<Option<NativeHeadSelection>>,keep:Option<usize>,
|
||||
}
|
||||
impl NativeWindow {
|
||||
pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation}
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec<i32>)>,failed:bool,
|
||||
}
|
||||
impl<'ctx,R,H> NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self {
|
||||
Self{verifier,host,pending_publish:None,failed:false}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier}
|
||||
pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier}
|
||||
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)}
|
||||
fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}}
|
||||
/// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with
|
||||
/// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target
|
||||
/// 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 Some((position,expected))=self.pending_publish.take() else {
|
||||
return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}};
|
||||
};
|
||||
let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()};
|
||||
if waited.is_err() {self.failed=true;return 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);}};
|
||||
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))
|
||||
}
|
||||
fn trace_residual()->Option<&'static std::ffi::OsString> {
|
||||
static DIR:std::sync::OnceLock<Option<std::ffi::OsString>>=std::sync::OnceLock::new();
|
||||
DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref()
|
||||
}
|
||||
|
||||
/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized
|
||||
/// 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();
|
||||
*ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0"))
|
||||
}
|
||||
|
||||
impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H>
|
||||
where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> {
|
||||
type Window=NativeWindow;
|
||||
type Seed=H::Seed;
|
||||
type TargetCheckpoint=H::TargetCheckpoint;
|
||||
type DraftCheckpoint=H::DraftCheckpoint;
|
||||
type Adaptive=H::Adaptive;
|
||||
fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> {
|
||||
self.live()?;self.host.validate_current(consumed,input,position)
|
||||
}
|
||||
fn checkpoint_target(&self)->Result<Self::TargetCheckpoint> {self.live()?;self.host.checkpoint_target()}
|
||||
fn checkpoint_draft(&self)->Result<Self::DraftCheckpoint> {self.live()?;self.host.checkpoint_draft()}
|
||||
fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> {
|
||||
// Whatever was in flight is dead: the window state is discarded by the driver (the
|
||||
// uncommitted window never touched GDN state, and a committed one is fenced first).
|
||||
self.pending_publish=None;
|
||||
let restored=self.host.restore_target(checkpoint);
|
||||
if restored.is_err() {self.failed=true;}restored
|
||||
}
|
||||
fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> {
|
||||
let restored=self.host.restore_draft(checkpoint);
|
||||
if restored.is_err() {self.failed=true;}restored
|
||||
}
|
||||
fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()}
|
||||
fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result<NativeWindow> {
|
||||
self.live()?;
|
||||
let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?;
|
||||
let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?};
|
||||
// The driver's own receipt is authoritative: it must describe exactly this window.
|
||||
let t=inputs.len();
|
||||
let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t
|
||||
&&result.selection.position()==position as u64;
|
||||
if !ok {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let mut ids=result.selection.ids().to_vec();
|
||||
// Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks
|
||||
// the controller verifies drafts against and commits next are the forced text's tokens.
|
||||
let forced_differ=super::quality_force::apply(position,&mut ids);
|
||||
if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");}
|
||||
// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
|
||||
if let Some(k)=trace_logprobs() {
|
||||
let mut line:Vec<u8>=Vec::new();
|
||||
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()),
|
||||
Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"),
|
||||
}
|
||||
}
|
||||
// Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=<dir>): the final residual R of every row of the completed window,
|
||||
// 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() {
|
||||
Ok((rows,start,values))=>{
|
||||
let bytes:Vec<u8>=values.iter().flat_map(|v|v.to_le_bytes()).collect();
|
||||
static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0);
|
||||
let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed);
|
||||
let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32"));
|
||||
eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display());
|
||||
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual 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"));
|
||||
if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); }
|
||||
}
|
||||
}
|
||||
Err(e)=>eprintln!("DBG residual err {e:?}"),
|
||||
}
|
||||
}
|
||||
Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(),
|
||||
selection:RefCell::new(Some(result.selection)),keep:None})
|
||||
}
|
||||
fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> {
|
||||
self.live()?;
|
||||
if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);}
|
||||
// A capture-only or already-superseded window cannot pass: the driver mints
|
||||
// `completed_window` only for the genuinely completed current generation.
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?;
|
||||
if completed.generation()!=window.generation||completed.rows()!=window.rows
|
||||
||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if let Some(selection)=window.selection.borrow().as_ref() {
|
||||
completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids}
|
||||
fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> {
|
||||
self.live()?;
|
||||
if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);}
|
||||
let _p=profile::span("round.commit");
|
||||
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);}
|
||||
window.keep=Some(keep);
|
||||
self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(())
|
||||
}
|
||||
fn wait_commit(&mut self)->Result<()> {self.settle_commit()}
|
||||
fn drain_window(&mut self,_window:NativeWindow)->Result<()> {
|
||||
// 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.
|
||||
Ok(())
|
||||
}
|
||||
fn discard_window(&mut self)->Result<()> {
|
||||
// an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`)
|
||||
if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let _p=profile::span("round.discard_window");
|
||||
if let Err(e)=self.verifier.discard_window() {
|
||||
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));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
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)}
|
||||
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],
|
||||
max_drafts:usize,min_p:f32,coupled:bool)->Result<DraftCompletion> {
|
||||
self.live()?;
|
||||
let _p=profile::span("round.draft_committed");
|
||||
// Literal order: commit enqueued first, draft depends on its event on the same stream.
|
||||
if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if overlap() && self.pending_publish.is_some() {
|
||||
// generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is
|
||||
// enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and
|
||||
// the draft completes only over that published branch.
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
|
||||
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)};
|
||||
let launched={let _p=profile::span("draft.launch");
|
||||
self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())};
|
||||
if let Err(e)=launched {self.failed=true;return Err(e);}
|
||||
// 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);}
|
||||
self.settle_commit()?;
|
||||
let finished={let _p=profile::span("draft.finish");self.host.finish_draft()};
|
||||
if finished.is_err() {self.failed=true;}
|
||||
return finished;
|
||||
}
|
||||
// Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is
|
||||
// published before the draft launches.
|
||||
self.settle_commit()?;
|
||||
let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch);
|
||||
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)};
|
||||
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 drain_draft(&mut self)->Result<()> {
|
||||
let drained=self.host.drain_draft();
|
||||
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()}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user