Merge branch 'claude/ms-trim' into claude/port-gpu-bringup
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
//! Operator profile of the driver's host-side spans (`LELEKA_SERVE_PROFILE=1`, off by default), summed per thread
|
||||
//! and printed by the runtime's serve profile next to its own spans. Inclusive wall-clock; nested spans are not
|
||||
//! additive. When the switch is off a span is one cached boolean test.
|
||||
use std::cell::RefCell;
|
||||
use std::time::Instant;
|
||||
|
||||
/// `LELEKA_SERVE_PROFILE` set to anything but `0`, read once.
|
||||
pub fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_SERVE_PROFILE").is_ok_and(|v| !v.is_empty() && v != "0"))
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SUMS: RefCell<Vec<(&'static str, f64, u64)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// A running span; its time is added to `name` when it is dropped.
|
||||
pub struct Span {
|
||||
name: &'static str,
|
||||
started: Option<Instant>,
|
||||
}
|
||||
impl Span {
|
||||
pub fn stop(&mut self) {
|
||||
if let Some(started) = self.started.take() {
|
||||
add(self.name, started.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Span {
|
||||
fn drop(&mut self) {
|
||||
if let Some(started) = self.started {
|
||||
add(self.name, started.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a span (a no-op unless the profile is on).
|
||||
pub fn span(name: &'static str) -> Span {
|
||||
Span { name, started: enabled().then(Instant::now) }
|
||||
}
|
||||
|
||||
/// Add `ms` to `name` (one call).
|
||||
pub fn add(name: &'static str, ms: f64) {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
SUMS.with(|sums| {
|
||||
let mut sums = sums.borrow_mut();
|
||||
match sums.iter_mut().find(|(n, _, _)| *n == name) {
|
||||
Some(entry) => {
|
||||
entry.1 += ms;
|
||||
entry.2 += 1;
|
||||
}
|
||||
None => sums.push((name, ms, 1)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The sums since the last call, `(name, total ms, count)`, and reset them.
|
||||
pub fn take() -> Vec<(&'static str, f64, u64)> {
|
||||
SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut()))
|
||||
}
|
||||
@@ -132,6 +132,7 @@ pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace};
|
||||
#[allow(unsafe_code)]
|
||||
mod qwen_ffi;
|
||||
|
||||
pub mod host_profile;
|
||||
pub mod experimental;
|
||||
/// Per-command timing of the batched prompt producers (bring-up profiling only).
|
||||
pub mod command_profile;
|
||||
|
||||
@@ -294,6 +294,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let span_record = crate::host_profile::span("mtp.launch_record");
|
||||
let first_capture = graphs.find_mut(key)?.is_none();
|
||||
let graph = graphs.record(
|
||||
key,
|
||||
@@ -314,12 +315,14 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
},
|
||||
|c, r| r.capture(c),
|
||||
)?;
|
||||
drop(span_record);
|
||||
if first_capture {
|
||||
self.graph_metadata = self
|
||||
.graph_metadata
|
||||
.checked_add(graph.mtp_resource_metadata()?)
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
}
|
||||
let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue");
|
||||
// generate.cpp enqueues the draft on the commit's stream: here the draft stream waits the verifier's
|
||||
// commit event before its first command, so the GPU orders them without a host wait.
|
||||
if let Some(event) = after {
|
||||
@@ -388,7 +391,9 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
let mut ids = [0i32; 8];
|
||||
let mut probabilities = [0f32; 8];
|
||||
let mut count;
|
||||
let span_first = crate::host_profile::span("mtp.finish_first_step");
|
||||
let first_result = graph.mtp_finish_step(stream);
|
||||
drop(span_first);
|
||||
let output = match first_result {
|
||||
Ok(o) => o,
|
||||
Err(error) => {
|
||||
@@ -404,6 +409,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
let limit = (self.max_t as i32 - 1).min(max_drafts);
|
||||
let mut j = 1usize;
|
||||
while (j as i32) < limit && probabilities[j - 1] >= min_p {
|
||||
let _span_chain = crate::host_profile::span("mtp.chain_step");
|
||||
let key = OriginalGraphKey::MtpStep {
|
||||
step: j as u8,
|
||||
coupled: cp,
|
||||
@@ -444,6 +450,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
let end = first
|
||||
.checked_add(rows.max(a + count))
|
||||
.ok_or(Error::InvalidSize)?;
|
||||
let _span_ring = crate::host_profile::span("mtp.finish_ring");
|
||||
let snapshot = ring.finish_original_graph_mutation(prior, first, end, generation)?;
|
||||
Ok(CompletedOriginalMtpDraft {
|
||||
snapshot,
|
||||
|
||||
@@ -769,11 +769,14 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
|
||||
stream.native_head_stream_key()?,
|
||||
)?;
|
||||
self.prepare_commands(&commands)?;
|
||||
let span_sample = crate::host_profile::span("head.sample_sync");
|
||||
let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands)));
|
||||
let sync = stream.synchronize();
|
||||
drop(span_sample);
|
||||
combine(operation, sync)?;
|
||||
self.commands.borrow_mut().clear();
|
||||
}
|
||||
let _span_ids = crate::host_profile::span("head.read_ids");
|
||||
let ids = self
|
||||
.mapped
|
||||
.as_ref()
|
||||
|
||||
@@ -62,6 +62,9 @@ pub struct OriginalExpertCache<'ctx> {
|
||||
/// The adaptive tier's own non-blocking stream (generate.cpp `adapt_stream`) and the completion event of
|
||||
/// its last batch (`adapt_ev`); created on the first swap.
|
||||
swap_stream: Option<api::Stream>,
|
||||
/// Non-blocking stream of `fill_slot_queued_async` (the lent-slot refill): its copies do not order the legacy default
|
||||
/// stream's other users behind them; `sync_queued` waits for it as well.
|
||||
fill_stream: Option<api::Stream>,
|
||||
swap_event: Option<api::Event>,
|
||||
/// Slots whose swap copy is queued on `swap_stream`, with the retained sources they read.
|
||||
swapping: Vec<usize>,
|
||||
@@ -161,6 +164,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
attempted: false,
|
||||
failed: false,
|
||||
swap_stream: None,
|
||||
fill_stream: None,
|
||||
swap_event: None,
|
||||
swapping: Vec::new(),
|
||||
swap_sources: Vec::new(),
|
||||
@@ -474,6 +478,25 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
slot: usize,
|
||||
bank: Rc<MappedExpertBank<'ctx>>,
|
||||
spans: [ResidentExpertBankSpan; 3],
|
||||
) -> Result<()> {
|
||||
self.fill_slot_queued_on(slot, bank, spans, false)
|
||||
}
|
||||
/// `fill_slot_queued` on the cache's own non-blocking stream: other users of the default stream (small synchronous
|
||||
/// uploads of the decode phase) do not wait behind the copies. `sync_queued` is still the fence.
|
||||
pub fn fill_slot_queued_async(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
bank: Rc<MappedExpertBank<'ctx>>,
|
||||
spans: [ResidentExpertBankSpan; 3],
|
||||
) -> Result<()> {
|
||||
self.fill_slot_queued_on(slot, bank, spans, true)
|
||||
}
|
||||
fn fill_slot_queued_on(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
bank: Rc<MappedExpertBank<'ctx>>,
|
||||
spans: [ResidentExpertBankSpan; 3],
|
||||
own_stream: bool,
|
||||
) -> Result<()> {
|
||||
self.ensure_live()?;
|
||||
if self.file_source_digest.is_some() {
|
||||
@@ -522,6 +545,14 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
else {
|
||||
return Err(Error::InvalidSize);
|
||||
};
|
||||
let stream = if own_stream {
|
||||
if self.fill_stream.is_none() {
|
||||
self.fill_stream = Some(self.api.as_ref().ok_or(Error::ContextPoisoned)?.create_stream()?);
|
||||
}
|
||||
self.fill_stream.ok_or(Error::ContextPoisoned)?
|
||||
} else {
|
||||
api::Stream(0)
|
||||
};
|
||||
let mut offset = 0usize;
|
||||
for span in spans {
|
||||
let source = bank.cache_source(span)?;
|
||||
@@ -531,7 +562,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy(
|
||||
destination.qwen_address(),
|
||||
&source[at..at + bytes],
|
||||
api::Stream(0),
|
||||
stream,
|
||||
)?;
|
||||
}
|
||||
offset += source.len();
|
||||
@@ -730,6 +761,10 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.synchronize_stream(api::Stream(0));
|
||||
let wait = match (wait, self.fill_stream, self.api.as_ref()) {
|
||||
(Ok(()), Some(stream), Some(api)) => api.synchronize_stream(stream),
|
||||
(wait, _, _) => wait,
|
||||
};
|
||||
let result = combine(wait, guard.finish());
|
||||
if result.is_err() {
|
||||
self.poison();
|
||||
@@ -899,12 +934,15 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
self.failed = true;
|
||||
self.pending.clear();
|
||||
let mut released = Ok(());
|
||||
if self.swap_event.is_some() || self.swap_stream.is_some() {
|
||||
if self.swap_event.is_some() || self.swap_stream.is_some() || self.fill_stream.is_some() {
|
||||
let guard = self.context.enter()?;
|
||||
if let Some(api) = self.api.as_ref() {
|
||||
if let Some(event) = self.swap_event.take() {
|
||||
released = combine(released, api.destroy_event(event));
|
||||
}
|
||||
if let Some(stream) = self.fill_stream.take() {
|
||||
released = combine(released, api.destroy_stream(stream));
|
||||
}
|
||||
if let Some(stream) = self.swap_stream.take() {
|
||||
released = combine(released, api.destroy_stream(stream));
|
||||
}
|
||||
|
||||
@@ -63,9 +63,16 @@ struct Canonical<'ctx>{context:&'ctx Context<'ctx>,buffer:Option<DeviceBuffer<'c
|
||||
pub struct OriginalVerifyCanonicalGdn<'ctx>{inner:Rc<Canonical<'ctx>>}
|
||||
impl<'ctx> Context<'ctx>{
|
||||
pub fn original_verify_canonical_gdn(&'ctx self,states:[&[f32];36],histories:[&[f32];36])->Result<OriginalVerifyCanonicalGdn<'ctx>>{
|
||||
for i in 0..36{if states[i].len()!=STATE_WORDS||histories[i].len()!=HISTORY_WORDS{return Err(Error::InvalidQwenShape)}if states[i].iter().chain(histories[i]).any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"))}}
|
||||
let _span_canonical=crate::host_profile::span("drv.canonical_gdn");
|
||||
for i in 0..36{if states[i].len()!=STATE_WORDS||histories[i].len()!=HISTORY_WORDS{return Err(Error::InvalidQwenShape)}}
|
||||
admission(self,CANONICAL_BYTES)?;let mut owner=Canonical{context:self,buffer:Some(self.allocate(CANONICAL_BYTES)?),failed:Cell::new(false)};
|
||||
let operation=(||{let mut bytes=zero(LAYER_BYTES)?;for i in 0..36{for(x,b)in states[i].iter().chain(histories[i]).zip(bytes.as_chunks_mut::<4>().0){b.copy_from_slice(&x.to_le_bytes())}owner.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i*LAYER_BYTES,&bytes)?;}Ok(())})();
|
||||
// One pass per layer converts to little-endian bytes and checks every word finite (two plain slice loops, not a chained
|
||||
// iterator: they compile to wide copies); a non-finite word refuses the intake before the layer is uploaded.
|
||||
let operation=(||{let mut bytes=zero(LAYER_BYTES)?;for i in 0..36{let(head,tail)=bytes.split_at_mut(STATE_WORDS*4);let mut finite=true;
|
||||
for(x,b)in states[i].iter().zip(head.chunks_exact_mut(4)){finite&=x.is_finite();b.copy_from_slice(&x.to_le_bytes())}
|
||||
for(x,b)in histories[i].iter().zip(tail.chunks_exact_mut(4)){finite&=x.is_finite();b.copy_from_slice(&x.to_le_bytes())}
|
||||
if !finite{return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"))}
|
||||
owner.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i*LAYER_BYTES,&bytes)?;}Ok(())})();
|
||||
if let Err(primary)=operation{return combine(Err(primary),owner.close_inner())}Ok(OriginalVerifyCanonicalGdn{inner:Rc::new(owner)})
|
||||
}
|
||||
pub fn original_verify_bank(&'ctx self,geometry:OriginalVerifyGeometry)->Result<OriginalVerifyBank<'ctx>>{OriginalVerifyBank::new(self,geometry)}
|
||||
@@ -187,7 +194,7 @@ impl<'ctx> OriginalVerifyBank<'ctx>{
|
||||
for flag in 9..=12{mapped[flag].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,0)?}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
|
||||
self.last_t=t;self.last_position=position;self.last_tokens[..t].copy_from_slice(tokens);self.generation=generation;self.physical.generation.set(generation);self.last_keep=0;Ok(generation)
|
||||
}
|
||||
pub(crate) fn stage_ple(&mut self,values:&[f32])->Result<()>{self.validate_context(self.physical.context)?;if self.last_t==0||values.len()!=self.last_t*self.geometry().n||values.iter().any(|x|!x.is_finite()){return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[4].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=slot.as_mut().ok_or(Error::ContextPoisoned)?;for(i,x)in values.iter().enumerate(){m.write(i*4,&x.to_le_bytes())?}Ok(())}
|
||||
pub(crate) fn stage_ple(&mut self,values:&[f32])->Result<()>{self.validate_context(self.physical.context)?;if self.last_t==0||values.len()!=self.last_t*self.geometry().n||values.iter().any(|x|!x.is_finite()){return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[4].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=slot.as_mut().ok_or(Error::ContextPoisoned)?;let mut bytes=Vec::new();bytes.try_reserve_exact(values.len()*4).map_err(|_|Error::HostAllocation)?;for x in values{bytes.extend_from_slice(&x.to_le_bytes())}m.write(0,&bytes)?;Ok(())}
|
||||
pub(crate) fn stage_commit(&mut self,keep:usize)->Result<()>{self.validate_context(self.physical.context)?;if !(1..=self.last_t).contains(&keep){return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[3].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=slot.as_mut().ok_or(Error::ContextPoisoned)?;m.write(0,&(keep as i32).to_le_bytes())?;m.write(4,&(keep as i32-1).to_le_bytes())?;for t in 0..self.geometry().max_t{let p=if t<keep{(self.last_position+t)as i32}else{-1};m.write((2+t)*4,&p.to_le_bytes())?}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);self.last_keep=keep;Ok(())}
|
||||
pub(crate) fn release_gpu_waits(&mut self)->Result<()>{self.released=true;let m=&self.physical.mapped;for i in 10..=12{m[i].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,u32::MAX)?}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(())}
|
||||
/// Host words the live release/diagnostic registry may read and raise.
|
||||
@@ -339,11 +346,11 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{
|
||||
/// is an integration finite gate, never an id-as-finite certificate. The four
|
||||
/// byte status reuses retired hit_count scratch; no active kernel can alias it.
|
||||
pub(crate) fn validate_completed_logits(&self,stream:&mut crate::OriginalGpuStream<'ctx>,logits:&DeviceBuffer<'ctx>,rows:usize)->Result<()>{
|
||||
self.validate_context(self.physical.context)?;stream.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if !(1..=g.max_t).contains(&rows){return Err(Error::InvalidQwenShape)}let words=rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?;let src=admit(self.physical.context,logits,words.checked_mul(4).ok_or(Error::InvalidSize)?)?;
|
||||
let _span_validate=crate::host_profile::span("head.validate_logits");self.validate_context(self.physical.context)?;stream.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if !(1..=g.max_t).contains(&rows){return Err(Error::InvalidQwenShape)}let words=rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?;let src=admit(self.physical.context,logits,words.checked_mul(4).ok_or(Error::InvalidSize)?)?;
|
||||
let arena=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;if handle(logits)?.overlaps(logits.len(),handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)}let status=self.span("hit_count",0,4)?;
|
||||
let mut commands=vec![command("verify_clear_status",[1,1,1],[32,1,1],vec![Arg::Address(status.qwen_address())])?,command("verify_scan_logits",[words.div_ceil(256).min(65535)as u32,1,1],[256,1,1],vec![Arg::Address(src),Arg::U64(words as u64),Arg::Address(status.qwen_address())])?];
|
||||
let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?;}let launched=stream.with_enqueue(|h|{for c in &mut commands{module.launch(h,c)?;}Ok(())});let sync=stream.synchronize();if sync.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(commands);return combine(launched,sync)}combine(launched,sync)?;
|
||||
let mut bytes=zero(4)?;let guard=self.physical.context.enter()?;let copy=self.physical.context.driver.api.copy_to(status,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish();if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop)}combine(combine(copy,sync),pop)?;if u32::from_le_bytes(bytes[..4].try_into().map_err(|_|Error::InvalidSize)?)!=0{return Err(Error::NonFiniteMmqOutput("Original Verifier full logits"))}Ok(())
|
||||
let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?;}let span_vs=crate::host_profile::span("head.validate_stream");let launched=stream.with_enqueue(|h|{for c in &mut commands{module.launch(h,c)?;}Ok(())});let sync=stream.synchronize();drop(span_vs);if sync.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(commands);return combine(launched,sync)}combine(launched,sync)?;
|
||||
let span_vc=crate::host_profile::span("head.validate_ctx_copy");let mut bytes=zero(4)?;let guard=self.physical.context.enter()?;let copy=self.physical.context.driver.api.copy_to(status,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish();drop(span_vc);if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop)}combine(combine(copy,sync),pop)?;if u32::from_le_bytes(bytes[..4].try_into().map_err(|_|Error::InvalidSize)?)!=0{return Err(Error::NonFiniteMmqOutput("Original Verifier full logits"))}Ok(())
|
||||
}
|
||||
/// Actual original PLE history image; selected accepted row, never final-image
|
||||
/// metadata relabel. Borrowed destination must survive the graph aggregate.
|
||||
|
||||
@@ -6,6 +6,8 @@ use crate::{OriginalGpuStream,OriginalGpuEvent,OriginalGpuGraph,OriginalCaptureP
|
||||
use crate::OriginalNativeHeadGraphResources;
|
||||
use std::time::{Duration,Instant};
|
||||
use std::io::Write;
|
||||
/// `STRATA_COMMIT_SYNC`, read once (it sat on the per-round commit path).
|
||||
fn commit_sync_forced()->bool{static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var_os("STRATA_COMMIT_SYNC").is_some())}
|
||||
/// CPU source callback receives borrowed actual mapped layer rows. No tensor or
|
||||
/// source certificate is minted; Root keeps descriptor/cache owners through it.
|
||||
pub struct OriginalVerifyCpuRows<'a>{pub layer:usize,pub group:usize,pub first_row:usize,pub activation:&'a [f32],pub ids:&'a [i32],pub route_weights:&'a [f32]}
|
||||
@@ -43,6 +45,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
if resources.native_head_rows()?.rows()!=t||resources.native_head_rows()?.completed_logits()?.len()!=t*self.bank()?.geometry().vocabulary*4{return Err(Error::InvalidQwenShape)}
|
||||
let groups=window_plan::window_groups(t,self.split);let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let graph=stream.capture_owned(OriginalCapturePolicy::VerifierWindow,resources,|capture,r|{r.verifier_journal().capture_inputs(capture,t)?;record(capture,r,groups)})?;
|
||||
if crate::host_profile::enabled(){eprintln!("DBG graph window t={t} groups={groups} nodes={:?}",graph.nodes());}
|
||||
self.window[t-1]=Some(graph);self.groups[t-1]=groups;Ok(())
|
||||
}
|
||||
pub fn record_commit(&mut self,resources:R,mut record_extra:impl FnMut(&mut OriginalCapture<'_, 'ctx>,&mut R,usize)->Result<()>)->Result<()>{
|
||||
@@ -52,7 +55,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
r.verifier_journal().capture_commit_begin(capture)?;let mut gi=0;let mut qi=0;
|
||||
for layer in 0..48{if layer%4==3{r.verifier_qsa().capture_commit_layer(r.verifier_journal(),capture,qi)?;record_extra(capture,r,layer)?;qi+=1}else{r.verifier_journal().capture_commit_layer(capture,gi)?;gi+=1}}
|
||||
if r.verifier_journal().ple.is_some(){r.verifier_journal().capture_ple_commit(capture)?;}Ok(())
|
||||
})?);Ok(())
|
||||
})?);if crate::host_profile::enabled(){eprintln!("DBG graph commit nodes={:?}",self.commit.as_ref().and_then(|g|g.nodes()));}Ok(())
|
||||
}
|
||||
/// Cached real all-T graph; CPU/GPU split and mapped flag rings match Original.
|
||||
/// Callback must finish actual expert/source work before returning. An error
|
||||
@@ -65,18 +68,28 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
if wants_ple!=ple.is_some(){return Err(Error::InvalidQwenShape)}
|
||||
// The preceding asynchronous commit has the same compute stream. Its actual
|
||||
// mapped records are overwritten only after that completed receipt/window.
|
||||
let span_wait=crate::host_profile::span("drv.run_wait_commit");
|
||||
self.wait_commit()?;
|
||||
drop(span_wait);
|
||||
let span_stage=crate::host_profile::span("drv.stage");
|
||||
let generation=self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens,position)?;
|
||||
if let Some(ple)=ple{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)?}
|
||||
drop(span_stage);
|
||||
let span_begin=crate::host_profile::span("drv.begin_window");
|
||||
self.window[t-1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?;
|
||||
drop(span_begin);
|
||||
self.active=true;if let Some(r)=&self.registration{r.begin_window(t,position as u64)}
|
||||
let operation=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||->Result<NativeHeadSelection>{
|
||||
let span_launch=crate::host_profile::span("drv.launch");
|
||||
self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
|
||||
let _=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
|
||||
drop(span_launch);
|
||||
let groups=self.groups[t-1];for k in 0..window_plan::window_rings(groups){
|
||||
let layer=k/groups;let group=k%groups;let want=window_plan::ring(layer,groups,group);let start=Instant::now();let mut last_flush=start;let mut spins=0u32;
|
||||
if let Some(r)=&self.registration{r.layer_step(want)}
|
||||
let span_bell=crate::host_profile::span("drv.doorbell_wait");
|
||||
loop{if self.bank()?.doorbell_sequence()?>=want{break}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue}let now=Instant::now();if self.registration.as_ref().is_some_and(diag::Registration::is_released){return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)"))}if now.duration_since(last_flush)>Duration::from_micros(2000){last_flush=now;let q=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;if q&&self.bank()?.doorbell_sequence()?<want{return Err(Error::InvalidDriverValue("Verifier layer never rang"))}}if now.duration_since(start)>Duration::from_secs(20){return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"))}}
|
||||
drop(span_bell);
|
||||
let (begin,end)=window_plan::group_rows(t,groups,group);let rows=end-begin;let g=self.bank()?.geometry();let physical=self.bank()?.physical.clone();
|
||||
let x=physical.mapped[6].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
|
||||
let ids=physical.mapped[7].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
|
||||
@@ -85,19 +98,26 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
drop((x,ids,w));
|
||||
// A pool with no GPU plan publishes the literal empty plan; actual DMA
|
||||
// producers publish A and raise B only from completed host callbacks.
|
||||
let span_flag=crate::host_profile::span("drv.group_publish");
|
||||
let flag=self.bank()?.physical.mapped[11].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?;
|
||||
if flag!=want{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group,want)?}
|
||||
let stalled=self.test_stall>0&&self.windows+1==self.test_stall&&k+1==window_plan::window_rings(groups);
|
||||
if !stalled{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,want)?;}
|
||||
drop(span_flag);
|
||||
}
|
||||
// Original order: compute fence, then copy-stream fence (no late flag B),
|
||||
// then request sampling with Philox counter tied to actual position.
|
||||
let span_sync=crate::host_profile::span("drv.sync_compute");
|
||||
let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;
|
||||
drop(span_sync);
|
||||
let span_copy=crate::host_profile::span("drv.sync_copy");
|
||||
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
drop(span_copy);
|
||||
// Every PCIe copy of the window has landed: the registered sources it read may go.
|
||||
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources();
|
||||
// The window's GPU stage stamps (single-group windows only, as in Original).
|
||||
if groups==1&&self.bank()?.profile_enabled(){let stamps=self.bank()?.read_profile()?;self.profile.add_window(&stamps,48,|l|l%4==3);}
|
||||
let _span_head=crate::host_profile::span("drv.head");
|
||||
self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(self.compute.as_mut().ok_or(Error::ContextPoisoned)?,&receipt,sampling)
|
||||
}));
|
||||
if let Some(r)=&self.registration{r.end_window()}
|
||||
@@ -107,17 +127,17 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
/// Root prepares all genuine accepted-prefix publication permits AFTER this
|
||||
/// commit completion; this controller does not forge session capabilities.
|
||||
pub fn commit(&mut self,n_keep:usize,async_commit:bool)->Result<()>{
|
||||
if self.failed||self.active||!self.window_ready{return Err(Error::InvalidQwenShape)}self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?;
|
||||
if self.failed||self.active||!self.window_ready{return Err(Error::InvalidQwenShape)}let span_commit=crate::host_profile::span("drv.commit_enqueue");self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?;
|
||||
let operation=(||{self.commit.as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.window_ready=false;
|
||||
let forced=std::env::var_os("STRATA_COMMIT_SYNC").is_some();
|
||||
let forced=commit_sync_forced();
|
||||
if async_commit&&!forced{self.event.as_mut().ok_or(Error::ContextPoisoned)?.record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit_pending=true;Ok(())}
|
||||
else{let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())}
|
||||
})();if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())
|
||||
})();drop(span_commit);if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())
|
||||
}
|
||||
/// The pending asynchronous commit's completion event (generate.cpp: what the next work on the commit's stream
|
||||
/// follows), for another stream to wait on the device. `None` when no commit is outstanding.
|
||||
pub fn pending_commit_event(&mut self)->Option<&mut OriginalGpuEvent<'ctx>>{if !self.commit_pending||self.failed{return None}self.event.as_mut()}
|
||||
pub fn wait_commit(&mut self)->Result<()>{if !self.commit_pending{return Ok(())}let operation=(||{self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())})();self.commit_pending=false;if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())}
|
||||
pub fn wait_commit(&mut self)->Result<()>{if !self.commit_pending{return Ok(())}let _span_wait=crate::host_profile::span("drv.commit_event_wait");let operation=(||{self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())})();self.commit_pending=false;if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())}
|
||||
/// Original final_R row, minted only after a genuine completed window.
|
||||
pub fn final_row(&self,row:usize)->Result<OriginalVerifyRow<'ctx>>{self.require_completed_window()?;self.bank()?.completed_row(row)}
|
||||
fn require_completed_window(&self)->Result<()>{if self.failed||self.active||self.completed_generation!=Some(self.bank()?.generation){return Err(Error::InvalidQwenShape)}self.bank()?.staged_window()?;Ok(())}
|
||||
|
||||
@@ -89,7 +89,7 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
let device = driver.device(0).expect("CUDA device 0 unavailable");
|
||||
let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable"));
|
||||
|
||||
let mut config = StackConfig::new(4096);
|
||||
let mut config = StackConfig::new(env::var("LELEKA_SMOKE_MAX_CONTEXT").ok().and_then(|v| v.parse().ok()).unwrap_or(4096));
|
||||
config.capacity = env::var("LELEKA_ORIGINAL_SERVE_CAPACITY").ok().and_then(|v| v.parse().ok()).unwrap_or(1024);
|
||||
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
|
||||
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
|
||||
@@ -193,12 +193,27 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
// LELEKA_SMOKE_REPEAT serves every prompt N times (default 1) so warm timings are visible next to the first request.
|
||||
let repeat: usize = env::var("LELEKA_SMOKE_REPEAT").ok().and_then(|v| v.parse().ok()).unwrap_or(1).max(1);
|
||||
for (index, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() {
|
||||
let ids = tokenizer.encode(line, true).expect("corpus tokenization failed");
|
||||
// LELEKA_SMOKE_CHAT=1: each line is one user turn of a Qwen chat (thinking off), the shape an agent request has
|
||||
// (a turn checkpoint at the last <|im_start|>, a resume on the repeated pass).
|
||||
let chat = env::var("LELEKA_SMOKE_CHAT").is_ok_and(|v| v == "1");
|
||||
let turn = if chat {
|
||||
format!("<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", line.trim())
|
||||
} else {
|
||||
line.to_owned()
|
||||
};
|
||||
let ids = tokenizer.encode(&turn, true).expect("corpus tokenization failed");
|
||||
eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(","));
|
||||
for pass in 0..repeat {
|
||||
let mut out = Vec::new();
|
||||
let min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0);
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, None, 7, min_p, vec![eos as i32]);
|
||||
// LELEKA_SMOKE_SAMPLED=1: the corpus is served with the sampling head and a penalty window (an agent-style
|
||||
// request: temperature 0.7, top-k 20, top-p 0.95, repeat penalty 1.1 over 64, fixed seed) instead of greedy.
|
||||
let sampled = env::var("LELEKA_SMOKE_SAMPLED").is_ok_and(|v| v == "1");
|
||||
let sampler = leleka_sampler_ref::SamplerParams {
|
||||
top_k: 20, top_p: 0.95, min_p: 0.0, temperature: 0.7, min_keep: 1, penalty_last_n: 64, penalty_repeat: 1.1,
|
||||
penalty_freq: 0.0, penalty_present: 0.0, seed: 1234, counter: 0, greedy: false,
|
||||
};
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, sampled.then_some(&sampler), 7, min_p, vec![eos as i32]);
|
||||
let started = std::time::Instant::now();
|
||||
let mut first: Option<std::time::Duration> = None;
|
||||
let served = stack.serve(&corpus_request, &mut |round| {
|
||||
|
||||
@@ -243,7 +243,7 @@ impl InputStage {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
let rows = hash::rows(token as u32, before, binding.input_constants())?;
|
||||
if std::env::var_os("LELEKA_TRACE_PLE").is_some() {
|
||||
if trace_ple() {
|
||||
eprintln!("DBG ple token={token} before={before:?} rows={rows:?}");
|
||||
}
|
||||
let gathered = match (binding.kar_ple_binding(), kar.as_deref_mut()) {
|
||||
@@ -300,6 +300,11 @@ impl InputStage {
|
||||
})
|
||||
}
|
||||
}
|
||||
/// `LELEKA_TRACE_PLE`, read once (it sat on the per-token path of every window).
|
||||
fn trace_ple() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("LELEKA_TRACE_PLE").is_some())
|
||||
}
|
||||
fn validate_ids(
|
||||
constants: &crate::model_binding::qwen4exp_input::InputConstants,
|
||||
token: TokenId,
|
||||
|
||||
@@ -373,17 +373,25 @@ pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:us
|
||||
pub(crate) fn serve_request<E:OriginalSpecEngine>(controller:&mut OriginalSpecController,engine:&mut E,
|
||||
prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>,
|
||||
mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result<ServeOutcome,SpecError> {
|
||||
let begin_span=super::original_serve_profile::span("ctrl.begin_request");
|
||||
controller.begin_request(prompt,max_new,min_p,eos)?;
|
||||
drop(begin_span);
|
||||
let (mut produced,mut rounds,mut stop)=(0usize,0usize,None);
|
||||
let looped=(||->std::result::Result<(),SpecError> {
|
||||
while !controller.finished() {
|
||||
let started=clock_ms();
|
||||
let vc_span=super::original_serve_profile::span("round.verify_commit");
|
||||
let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break};
|
||||
drop(vc_span);
|
||||
let emit_span=super::original_serve_profile::span("round.emit");
|
||||
let emitted=emit(round.tokens());
|
||||
drop(emit_span);
|
||||
produced+=round.tokens().len();rounds+=1;
|
||||
if round.stopped_on_eos() {stop=Some(ServeStop::Eos);}
|
||||
// A failed emit still finishes the round (drain + join) before reporting.
|
||||
let fr_span=super::original_serve_profile::span("round.finish");
|
||||
let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel);
|
||||
drop(fr_span);
|
||||
emitted?;finished?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -104,6 +104,16 @@ where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -146,7 +156,7 @@ where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx
|
||||
if !ok {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let ids=result.selection.ids().to_vec();
|
||||
// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
|
||||
if let Some(k)=std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::<usize>().ok()).filter(|k|*k>0) {
|
||||
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) {
|
||||
@@ -156,7 +166,7 @@ where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx
|
||||
}
|
||||
// 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)=std::env::var_os("LELEKA_TRACE_RESIDUAL") {
|
||||
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();
|
||||
|
||||
@@ -64,7 +64,9 @@ pub(crate) fn report(label: &str) {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let sums = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut()));
|
||||
let mut sums = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut()));
|
||||
// the driver's own host spans (window launch, doorbell waits, syncs, head, MTP draft graphs)
|
||||
sums.extend(leleka_cuda_driver::host_profile::take());
|
||||
let mut line = format!("DBG profile {label}:");
|
||||
for (name, ms, count) in sums {
|
||||
line.push_str(&format!(" {name}={ms:.2}/{count}"));
|
||||
|
||||
@@ -29,6 +29,7 @@ use super::{
|
||||
original_serve_verifier::driver_error,
|
||||
};
|
||||
use crate::model_binding::qwen4exp_input::ModelBinding;
|
||||
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
|
||||
use leleka_cuda_driver::{
|
||||
Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream,
|
||||
OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource,
|
||||
@@ -348,6 +349,38 @@ impl ResidencyStats {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered source spans (gate, up, down) of routed experts by (layer, expert), kept for the life of the stack:
|
||||
/// the mapped bank never moves, so a span set found once (the per-call scan through the binding costs 30-70 us) is
|
||||
/// the span set of every later PCIe stage, adaptive swap and lent-slot refill of that expert.
|
||||
/// `LELEKA_SPAN_CACHE=off` looks every set up again (A/B control).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SpanCache {
|
||||
sets: std::collections::HashMap<u32, [ResidentExpertBankSpan; 3]>,
|
||||
}
|
||||
impl std::fmt::Debug for SpanCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "SpanCache({} sets)", self.sets.len())
|
||||
}
|
||||
}
|
||||
fn span_cache_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| !std::env::var("LELEKA_SPAN_CACHE").is_ok_and(|v| v == "off" || v == "0"))
|
||||
}
|
||||
impl SpanCache {
|
||||
fn key(layer: usize, expert: u32) -> u32 {
|
||||
(layer * EXPERTS) as u32 + expert
|
||||
}
|
||||
fn get(&self, layer: usize, expert: u32) -> Option<[ResidentExpertBankSpan; 3]> {
|
||||
self.sets.get(&Self::key(layer, expert)).cloned()
|
||||
}
|
||||
fn contains(&self, layer: usize, expert: u32) -> bool {
|
||||
self.sets.contains_key(&Self::key(layer, expert))
|
||||
}
|
||||
fn insert(&mut self, layer: usize, expert: u32, spans: [ResidentExpertBankSpan; 3]) {
|
||||
self.sets.insert(Self::key(layer, expert), spans);
|
||||
}
|
||||
}
|
||||
|
||||
/// What survives requests: the routed counts of the adaptive tier (`drive.d.usage`) and the counters.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ResidencyState {
|
||||
@@ -356,6 +389,7 @@ pub(crate) struct ResidencyState {
|
||||
/// generate.cpp `--dump-routing FILE` (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING`): every decode window row's routed
|
||||
/// experts, as `tools/make_profile.py` reads them (layer i32, k i32, k ids i32, k weights f32).
|
||||
routing: Option<std::io::BufWriter<std::fs::File>>,
|
||||
pub(crate) spans: SpanCache,
|
||||
}
|
||||
impl ResidencyState {
|
||||
pub(crate) fn new(config: &ExpertTierConfig) -> Self {
|
||||
@@ -366,6 +400,7 @@ impl ResidencyState {
|
||||
usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() },
|
||||
stats: ResidencyStats::default(),
|
||||
routing,
|
||||
spans: SpanCache::default(),
|
||||
}
|
||||
}
|
||||
/// Write the buffered routing records out (end of a request).
|
||||
@@ -404,6 +439,64 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) adapt_every: u32,
|
||||
pub(in crate::qwen_forward) adapt_swaps: usize,
|
||||
}
|
||||
impl GpuExpertPool<'_, '_, '_> {
|
||||
fn source_spans(&mut self, layer: usize, experts: &[u32]) -> Result<Vec<[ResidentExpertBankSpan; 3]>> {
|
||||
source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, experts)
|
||||
}
|
||||
}
|
||||
/// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU
|
||||
/// tier's admission (or the binding's own scan on the legacy path) and remembered.
|
||||
fn source_spans(
|
||||
cpu: &mut CpuExpertPool<'_>,
|
||||
bank: &MappedExpertBank<'_>,
|
||||
moe: &MoeWeightCache<'_>,
|
||||
binding: &ModelBinding,
|
||||
known: &mut SpanCache,
|
||||
layer: usize,
|
||||
experts: &[u32],
|
||||
) -> Result<Vec<[ResidentExpertBankSpan; 3]>> {
|
||||
{
|
||||
let cached = span_cache_enabled();
|
||||
let fetch: Vec<u32> = if cached {
|
||||
experts.iter().copied().filter(|&e| !known.contains(layer, e)).collect()
|
||||
} else {
|
||||
experts.to_vec()
|
||||
};
|
||||
let mut fetched: Vec<[ResidentExpertBankSpan; 3]> = Vec::new();
|
||||
fetched.try_reserve_exact(fetch.len()).map_err(|_| Error::InputAllocation)?;
|
||||
if !fetch.is_empty() {
|
||||
// The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the
|
||||
// PCIe sources too; the legacy path keeps the per-expert full scan.
|
||||
match cpu.admitted_spans(layer as u32, &fetch) {
|
||||
Some(admitted) => {
|
||||
for spans_of in admitted? {
|
||||
if !bank.eligible(&spans_of) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
fetched.push(spans_of);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for &e in &fetch {
|
||||
fetched.push(moe.original_expert_spans(binding, layer as u32, e)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !cached {
|
||||
return Ok(fetched);
|
||||
}
|
||||
for (&e, spans_of) in fetch.iter().zip(fetched) {
|
||||
known.insert(layer, e, spans_of);
|
||||
}
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for &e in experts {
|
||||
spans.push(known.get(layer, e).ok_or(Error::IdentityMismatch)?);
|
||||
}
|
||||
Ok(spans)
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
fn run_group(
|
||||
&mut self,
|
||||
@@ -437,25 +530,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock);
|
||||
drop(profile_split);
|
||||
let profile_spans = super::original_serve_profile::span("pool.spans");
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
// The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the
|
||||
// PCIe sources too; the legacy path keeps the per-expert full scan.
|
||||
match self.cpu.admitted_spans(layer as u32, &split.pcie_experts) {
|
||||
Some(admitted) => {
|
||||
for spans_of in admitted? {
|
||||
if !self.bank.eligible(&spans_of) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
spans.push(spans_of);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for &e in &split.pcie_experts {
|
||||
spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
let spans = source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, &split.pcie_experts)?;
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock);
|
||||
super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64);
|
||||
drop(profile_spans);
|
||||
@@ -503,16 +578,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps);
|
||||
for swap in &swaps {
|
||||
let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
|
||||
let spans = match self.cpu.admitted_spans(swap.layer as u32, &[swap.incoming as u32]) {
|
||||
Some(admitted) => {
|
||||
let admitted = admitted?.pop().ok_or(Error::IdentityMismatch)?;
|
||||
if !self.bank.eligible(&admitted) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
admitted
|
||||
}
|
||||
None => self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?,
|
||||
};
|
||||
let spans = self.source_spans(swap.layer, &[swap.incoming as u32])?.pop().ok_or(Error::IdentityMismatch)?;
|
||||
self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?;
|
||||
}
|
||||
self.cache.arm_swaps().map_err(|e| driver_error(&e))?;
|
||||
@@ -647,19 +713,58 @@ pub(in crate::qwen_forward) fn refill_lent<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
moe: &MoeWeightCache<'ctx>,
|
||||
cache: &mut OriginalExpertCache<'ctx>,
|
||||
known: &mut SpanCache,
|
||||
defer_wait: bool,
|
||||
) -> Result<usize> {
|
||||
let cached = span_cache_enabled();
|
||||
let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?;
|
||||
let mut refilled = 0usize;
|
||||
for slot in 0..cache.slots() {
|
||||
let Some((layer, expert)) = cache.needs_refill(slot).map_err(|e| driver_error(&e))? else { continue };
|
||||
let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?;
|
||||
cache.fill_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
|
||||
let span_spans = super::original_serve_profile::span("refill.spans");
|
||||
let spans = match if cached { known.get(layer, expert as u32) } else { None } {
|
||||
Some(spans) => spans,
|
||||
None => {
|
||||
let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?;
|
||||
if cached {
|
||||
known.insert(layer, expert as u32, spans.clone());
|
||||
}
|
||||
spans
|
||||
}
|
||||
};
|
||||
drop(span_spans);
|
||||
let _span_queue = super::original_serve_profile::span("refill.queue");
|
||||
if defer_wait {
|
||||
cache.fill_slot_queued_async(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
|
||||
} else {
|
||||
cache.fill_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
|
||||
}
|
||||
refilled += 1;
|
||||
}
|
||||
cache.sync_queued().map_err(|e| driver_error(&e))?;
|
||||
if defer_wait {
|
||||
// the copies run behind the host's assembly of the decode phase; `settle_refill` waits for them before any
|
||||
// window reads the cache
|
||||
return Ok(refilled);
|
||||
}
|
||||
settle_refill(cache)?;
|
||||
Ok(refilled)
|
||||
}
|
||||
|
||||
/// Wait for the refill copies queued by `refill_lent(.., defer_wait = true)` (a no-op when none are queued).
|
||||
pub(in crate::qwen_forward) fn settle_refill(cache: &mut OriginalExpertCache<'_>) -> Result<()> {
|
||||
let _span_sync = super::original_serve_profile::span("refill.sync");
|
||||
cache.sync_queued().map_err(|e| driver_error(&e))
|
||||
}
|
||||
|
||||
/// `LELEKA_REFILL_DEFER=on` (EXPERIMENTAL, off by default): queue the lent-slot refill inside the decode phase's assembly, after
|
||||
/// its intake uploads and before the graph capture, instead of waiting for it at the end of the prompt phase. Job 902 measured
|
||||
/// the earlier variant (queued at the end of the prompt phase, waited later) as no gain: the PLE seed upload waited for the same
|
||||
/// DMA. The current variant has no GPU result yet (job 904), so it stays opt-in.
|
||||
pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_REFILL_DEFER").is_ok_and(|v| v == "on" || v == "1"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -186,6 +186,12 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> {
|
||||
expert_cache: Option<OriginalExpertCache<'ctx>>,
|
||||
loan: Option<usize>,
|
||||
residency: ResidencyState,
|
||||
/// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any
|
||||
/// window reads the cache; every other user of the cache waits inside its own entry points.
|
||||
refill_pending: bool,
|
||||
/// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake
|
||||
/// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA).
|
||||
refill_due: bool,
|
||||
/// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements).
|
||||
timing: (f64, f64),
|
||||
executor: OriginalPromptExecutor<'ctx>,
|
||||
@@ -346,6 +352,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
expert_cache,
|
||||
loan,
|
||||
residency,
|
||||
refill_pending: false,
|
||||
refill_due: false,
|
||||
timing: (0.0, 0.0),
|
||||
executor,
|
||||
draft,
|
||||
@@ -413,10 +421,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
/// Close every owner in dependency order; the first failure is reported after all were attempted.
|
||||
pub(crate) fn close(self) -> Result<()> {
|
||||
let Self {
|
||||
conversation, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, moe,
|
||||
dense, output, embedding, ..
|
||||
conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar,
|
||||
moe, dense, output, embedding, ..
|
||||
} = self;
|
||||
drop(conversation);
|
||||
// the span cache retains registered-source spans of the bank `moe` closes below
|
||||
drop(residency);
|
||||
let mut first: Option<Error> = None;
|
||||
let mut note = |result: Result<()>| {
|
||||
if let Err(error) = result {
|
||||
@@ -477,6 +487,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
conversation,
|
||||
expert_cache,
|
||||
residency,
|
||||
refill_pending,
|
||||
refill_due,
|
||||
..
|
||||
} = self;
|
||||
let binding: &ModelBinding = *binding;
|
||||
@@ -514,11 +526,36 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
let ple_history: &DeviceBuffer<'ctx> = &*ple_history;
|
||||
let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch };
|
||||
let p = profile::span("decode.assemble");
|
||||
// queued after assembly's own uploads (canonical GDN image), before the graph capture
|
||||
let mut queue_refill = || -> Result<()> {
|
||||
if !std::mem::take(&mut *refill_due) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(cache) = expert_cache.as_mut() {
|
||||
let _p = profile::span("prefill.refill");
|
||||
original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?;
|
||||
*refill_pending = true;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let assembled = assemble(
|
||||
binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, settings.max_t, *max_cells,
|
||||
pcie_mode,
|
||||
pcie_mode, &mut queue_refill,
|
||||
);
|
||||
drop(p);
|
||||
// the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them
|
||||
// before a window or the tier's own bookkeeping touches the cache
|
||||
if std::mem::take(refill_pending) {
|
||||
if let Some(cache) = expert_cache.as_mut() {
|
||||
if let Err(error) = original_serve_residency::settle_refill(cache) {
|
||||
broken.get_or_insert(error);
|
||||
if let Ok(resources) = assembled {
|
||||
let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners));
|
||||
}
|
||||
return Err(SpecError::Forward(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" });
|
||||
let resources = match assembled {
|
||||
Ok(resources) => resources,
|
||||
@@ -605,6 +642,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
drop(serve_span);
|
||||
if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); }
|
||||
let (mut verifier, mut host) = engine.into_port().0.into_parts();
|
||||
// STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise)
|
||||
let gpu_profile = verifier.profile_report();
|
||||
if !gpu_profile.is_empty() {
|
||||
eprintln!("DBG verify-profile:{gpu_profile}");
|
||||
}
|
||||
// conversation cache: the session can be continued as is only when the draft ring
|
||||
// stands at its position (then its recurrent state is settled to match)
|
||||
let live = conversation.is_some()
|
||||
@@ -683,10 +725,16 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
let read = self.prefill_actions(request, resume, cancel);
|
||||
drop(p);
|
||||
let _p = profile::span("prefill.refill");
|
||||
// a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the
|
||||
// decode phase's host-side assembly
|
||||
let defer = read.is_ok() && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some();
|
||||
let refilled = match (self.loan, self.expert_cache.as_mut()) {
|
||||
(Some(_), Some(cache)) => original_serve_residency::refill_lent(self.binding, &self.moe, cache).map(|_| ()),
|
||||
(Some(_), Some(cache)) if !defer => {
|
||||
original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ())
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
self.refill_due = defer;
|
||||
match (read, refilled) {
|
||||
(Ok(()), Err(error)) => {
|
||||
self.mark_broken(error);
|
||||
@@ -707,12 +755,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el());
|
||||
// generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's
|
||||
// sampling parameters configure the actor for the whole request.
|
||||
let mtp_setup_span = profile::span("prefill.mtp_setup");
|
||||
self.executor.set_mtp_prompt_len(binding, n as i64)?;
|
||||
self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?;
|
||||
self.executor.set_mtp_draft_sampling(binding, &request.params)?;
|
||||
drop(mtp_setup_span);
|
||||
if n < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
let setup_span = profile::span("prefill.setup");
|
||||
let tokens: Vec<u32> = request.prompt.iter().map(|&t| t as u32).collect();
|
||||
let source = OriginalPromptInput::from_tokenized(binding, &tokens)?;
|
||||
let options = PromptOptions {
|
||||
@@ -734,6 +785,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
let capacity = self.config.capacity;
|
||||
let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el());
|
||||
drop(setup_span);
|
||||
for action in plan {
|
||||
crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count);
|
||||
if action.path == PromptPath::FinalSeed {
|
||||
@@ -806,6 +858,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
/// the cache, never the request: the cache is dropped and the request goes on.
|
||||
fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) {
|
||||
let Some(mut conversation) = self.conversation.take() else { return };
|
||||
let _span = profile::span("conv.after_action");
|
||||
if let Err(error) = conversation.after_action(self, prompt, action) {
|
||||
operator_text(&format!("conversation cache: {error}; dropping the cache"));
|
||||
conversation.invalidate();
|
||||
@@ -967,6 +1020,7 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
|
||||
self.reused = 0;
|
||||
self.resume_point = 0;
|
||||
let mut conversation = self.conversation.take()?;
|
||||
let _resume_span = profile::span("request.resume");
|
||||
let resume = if self.broken.is_some() {
|
||||
conversation.invalidate();
|
||||
None
|
||||
@@ -1003,6 +1057,21 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
|
||||
) -> std::result::Result<ServeOutcome, SpecError> {
|
||||
let started = Instant::now();
|
||||
let result = self.decode_phase(request, emit, cancel);
|
||||
// an exit before the decode phase queued the refill still refills now; one before it waited still waits
|
||||
if std::mem::take(&mut self.refill_due) {
|
||||
if let Some(cache) = self.expert_cache.as_mut() {
|
||||
if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) {
|
||||
self.mark_broken(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if std::mem::take(&mut self.refill_pending) {
|
||||
if let Some(cache) = self.expert_cache.as_mut() {
|
||||
if let Err(error) = original_serve_residency::settle_refill(cache) {
|
||||
self.mark_broken(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.timing.1 = started.elapsed().as_secs_f64() * 1e3;
|
||||
profile::add("decode.phase", self.timing.1);
|
||||
// graphs captured after the window/commit graphs: the MTP round programs of this request's drafts
|
||||
|
||||
@@ -170,6 +170,7 @@ pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
|
||||
max_t: usize,
|
||||
max_cells: usize,
|
||||
pcie_mode: u8,
|
||||
after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>,
|
||||
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
|
||||
let dense = weights.dense;
|
||||
// The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its
|
||||
@@ -199,6 +200,11 @@ pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
|
||||
Ok(parts) => parts,
|
||||
Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners) }),
|
||||
};
|
||||
// The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies).
|
||||
if let Err(error) = after_prepare() {
|
||||
drop(canonical);
|
||||
return Err(AssembleFailure { failure: error.into(), owners: Some(owners) });
|
||||
}
|
||||
// ---- from here the owners move into the journal
|
||||
let mut slots = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
|
||||
@@ -4,6 +4,14 @@ use super::contract::{Error, Result};
|
||||
struct Slot { key:u64,pos:[u32;4],n:u8 }
|
||||
pub(crate) struct SuffixDrafter {
|
||||
min_match:usize,max_match:usize,history:Vec<i32>,table:Box<[Slot]>,mask:usize,last_match:usize,
|
||||
/// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is
|
||||
/// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots).
|
||||
touched:Vec<u32>,
|
||||
}
|
||||
/// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control).
|
||||
fn sparse_reset()->bool {
|
||||
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
|
||||
*ON.get_or_init(||!std::env::var("LELEKA_SUFFIX_RESET").is_ok_and(|v|v=="full"))
|
||||
}
|
||||
fn mix(mut x:u64)->u64 {
|
||||
x^=x>>33;x=x.wrapping_mul(0xff51afd7ed558ccd);x^=x>>33;
|
||||
@@ -16,14 +24,23 @@ impl SuffixDrafter {
|
||||
let mut table=Vec::new();table.try_reserve_exact(cap).map_err(|_|Error::InputAllocation)?;
|
||||
table.resize(cap,Slot::default());
|
||||
let mut history=Vec::new();history.try_reserve_exact(capacity_tokens).map_err(|_|Error::InputAllocation)?;
|
||||
Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0})
|
||||
Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0,touched:Vec::new()})
|
||||
}
|
||||
pub(crate) fn metadata_bytes(&self)->Result<usize> {
|
||||
self.history.capacity().checked_mul(std::mem::size_of::<i32>())
|
||||
.and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::<Slot>())?))
|
||||
.and_then(|n|n.checked_add(std::mem::size_of::<Self>())).ok_or(Error::Overflow)
|
||||
}
|
||||
pub(crate) fn reset(&mut self) {self.history.clear();self.table.fill(Slot::default());self.last_match=0;}
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.history.clear();self.last_match=0;
|
||||
// Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill.
|
||||
if sparse_reset()&&self.touched.len()<=self.table.len()/4 {
|
||||
for &i in &self.touched {self.table[i as usize]=Slot::default();}
|
||||
} else {
|
||||
self.table.fill(Slot::default());
|
||||
}
|
||||
self.touched.clear();
|
||||
}
|
||||
pub(crate) fn reserve_reset(&self,n:usize)->Result<()> {
|
||||
if n>self.history.capacity() {return Err(Error::InputAllocation);}Ok(())
|
||||
}
|
||||
@@ -38,7 +55,7 @@ impl SuffixDrafter {
|
||||
let mut i=key as usize & self.mask;
|
||||
for _ in 0..=self.mask {
|
||||
if self.table[i].key==key {return Some(i);}
|
||||
if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;return Some(i);}
|
||||
if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;self.touched.push(i as u32);return Some(i);}
|
||||
i=(i+1)&self.mask;
|
||||
}None
|
||||
}
|
||||
@@ -68,3 +85,26 @@ impl SuffixDrafter {
|
||||
pub(crate) fn last_match(&self)->usize {self.last_match}
|
||||
pub(crate) fn len(&self)->usize {self.history.len()}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_sparse_reset_leaves_the_same_empty_table_as_a_full_clear() {
|
||||
let mut drafter=SuffixDrafter::new(3,64,4096).unwrap();
|
||||
let tokens:Vec<i32>=(0..300).map(|i|(i*7+i/3)%97).collect();
|
||||
drafter.append(&tokens).unwrap();
|
||||
assert!(!drafter.touched.is_empty());
|
||||
drafter.reset();
|
||||
assert!(drafter.table.iter().all(|s|s.key==0&&s.n==0&&s.pos==[0;4]),"every claimed slot is cleared");
|
||||
assert!(drafter.touched.is_empty()&&drafter.len()==0);
|
||||
// the same tokens give the same proposals after the reset as on a fresh drafter
|
||||
let mut fresh=SuffixDrafter::new(3,64,4096).unwrap();
|
||||
drafter.append(&tokens).unwrap();fresh.append(&tokens).unwrap();
|
||||
let (mut a,mut b)=([0;7],[0;7]);
|
||||
assert_eq!(drafter.propose(&mut a),fresh.propose(&mut b));
|
||||
assert_eq!(a,b);
|
||||
assert_eq!(drafter.last_match(),fresh.last_match());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1113,14 +1113,7 @@ impl VerifiedKarPleArtifact {
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?,
|
||||
)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?;
|
||||
self.reader
|
||||
.file
|
||||
.seek(SeekFrom::Start(scale))
|
||||
.map_err(KarError::Io)?;
|
||||
self.reader
|
||||
.file
|
||||
.read_exact(&mut packet.payload[..10])
|
||||
.map_err(KarError::Io)?;
|
||||
read_at(&mut self.reader.file, scale, &mut packet.payload[..10])?;
|
||||
for plane in 0..2usize {
|
||||
let at = p
|
||||
.planes
|
||||
@@ -1131,14 +1124,7 @@ impl VerifiedKarPleArtifact {
|
||||
)
|
||||
.and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n)))
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?;
|
||||
self.reader
|
||||
.file
|
||||
.seek(SeekFrom::Start(at))
|
||||
.map_err(KarError::Io)?;
|
||||
self.reader
|
||||
.file
|
||||
.read_exact(&mut packet.payload[10 + plane * 20..30 + plane * 20])
|
||||
.map_err(KarError::Io)?;
|
||||
read_at(&mut self.reader.file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?;
|
||||
}
|
||||
if packet.payload[..10]
|
||||
.as_chunks::<2>()
|
||||
@@ -1272,6 +1258,21 @@ fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read exactly `buf.len()` bytes at absolute offset `at`: one `pread` on unix (the PLE row reader issues ~50 reads
|
||||
/// per decoded token; a seek + read pair doubled the system calls and left the file offset moving).
|
||||
fn read_at(file: &mut File, at: u64, buf: &mut [u8]) -> Result<(), KarError> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::FileExt;
|
||||
file.read_exact_at(buf, at).map_err(KarError::Io)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
file.seek(SeekFrom::Start(at)).map_err(KarError::Io)?;
|
||||
file.read_exact(buf).map_err(KarError::Io)
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "kar_nested.rs"]
|
||||
mod nested;
|
||||
pub use nested::{KarNestedRecord, NESTING_TOPDOWN};
|
||||
|
||||
@@ -460,6 +460,7 @@ impl ResidentExpertBankLease {
|
||||
}
|
||||
/// Exact named bank retained from an admitted catalog, not caller bytes/ranges.
|
||||
/// `bytes` is initialized immutable addressability, never a finite/pinned proof.
|
||||
#[derive(Clone)]
|
||||
pub struct ResidentExpertBankMember {
|
||||
descriptor: BankDescriptor,
|
||||
tensor: Rc<gguf::ResidentTensor>,
|
||||
@@ -557,6 +558,7 @@ impl Qwen4ExpArtifact {
|
||||
|
||||
/// Immutable initialized fixed-expert addressability, not source health,
|
||||
/// registration, finite data or a runtime row/Context certificate.
|
||||
#[derive(Clone)]
|
||||
pub struct ResidentExpertBankSpan {
|
||||
member: ResidentExpertBankMember,
|
||||
expert: u32,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Encode/decode throughput of the tokenizer on a long synthetic prompt (host cost of TTFT and of token publication).
|
||||
//!
|
||||
//! `cargo run --release -p leleka-tokenizer --example bench_encode -- TOKENIZER_DIR PROMPTS.txt [REPEAT]`
|
||||
|
||||
use std::{env, fs, path::Path, process::ExitCode, time::Instant};
|
||||
|
||||
use leleka_tokenizer::Tokenizer;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() < 3 {
|
||||
eprintln!("usage: bench_encode TOKENIZER_DIR PROMPTS.txt [REPEAT]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let tokenizer = Tokenizer::from_assets(Path::new(&args[1])).expect("tokenizer assets");
|
||||
let corpus = fs::read_to_string(&args[2]).expect("prompts");
|
||||
let repeat: usize = args.get(3).and_then(|v| v.parse().ok()).unwrap_or(200);
|
||||
let text: String = (0..repeat).map(|_| corpus.as_str()).collect::<Vec<_>>().join("\n");
|
||||
for _ in 0..2 {
|
||||
let started = Instant::now();
|
||||
let ids = tokenizer.encode(&text, true).expect("encode");
|
||||
let encode = started.elapsed();
|
||||
let started = Instant::now();
|
||||
let mut bytes = 0usize;
|
||||
for &id in &ids {
|
||||
bytes += tokenizer.decode_bytes(&[id]).expect("decode").len();
|
||||
}
|
||||
let decode = started.elapsed();
|
||||
eprintln!(
|
||||
"text {} bytes -> {} tokens: encode {:.1} ms ({:.2} Mtok/s); decode_bytes one id at a time {:.2} us/token ({} bytes)",
|
||||
text.len(),
|
||||
ids.len(),
|
||||
encode.as_secs_f64() * 1e3,
|
||||
ids.len() as f64 / encode.as_secs_f64() / 1e6,
|
||||
decode.as_secs_f64() * 1e6 / ids.len() as f64,
|
||||
bytes
|
||||
);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Per-step host costs of the Original serve loop (`claude/ms-trim`)
|
||||
|
||||
Status: measurements and host-side trims, RTX 5090 server, jobs 901/902 (`LELEKA_SERVE_PROFILE=1`). Not a quality or
|
||||
throughput claim beyond the paired A/B rows below.
|
||||
|
||||
## Method
|
||||
|
||||
* `LELEKA_SERVE_PROFILE=1` prints one `DBG profile request:` line per request. Besides the stack's spans it now carries
|
||||
the driver's host spans (`drv.*`, `head.*`, `mtp.*`; `crates/cuda-driver/src/host_profile.rs`) and the controller's
|
||||
(`ctrl.*`, `round.verify_commit|emit|finish`). Off, a span is one cached boolean test.
|
||||
* `STRATA_VERIFY_PROFILE=1` now prints `DBG verify-profile:` per request: the GPU stage stamps of the window graphs
|
||||
(verify.cpp's `profile_report`, never wired before).
|
||||
* Bring-up `DBG`/`eprintln!` on the hot paths are all behind `LELEKA_BRINGUP_TRACE` or the profile switch (checked); three
|
||||
per-window `env::var` reads (`LELEKA_TRACE_LOGPROBS`, `LELEKA_TRACE_RESIDUAL`, `LELEKA_TRACE_PLE`) and `STRATA_COMMIT_SYNC`
|
||||
are read once now (microseconds, kept for hygiene).
|
||||
|
||||
## Where a round goes (job 901, static residency, greedy corpus, 523 rounds, ms per round)
|
||||
|
||||
| span | ms | note |
|
||||
| --- | --- | --- |
|
||||
| round (`round.verify_commit` + `round.finish`) | 49.8 | 1 / 50 ms = the decode rate |
|
||||
| window (`window.verifier`) | 47.4 | |
|
||||
| - CPU pool compute (`pool.cpu`) | 26.2 | owner: `claude/pool-zero-copy` |
|
||||
| - host spinning for the GPU's next doorbell (`drv.doorbell_wait`) | 19.3 | GPU critical path while the host is idle |
|
||||
| - PCIe span lookup (`pool.spans`) | 0.86 | cached since this branch (0.06 once warm) |
|
||||
| - split + plan publish + PLE rows + sampling history + stage + launch | 0.37 | |
|
||||
| - final GPU drain + head (`drv.sync_compute`, `drv.head`) | 0.88 | head validation scan 0.05 |
|
||||
| draft (`draft.finish`: first MTP graph 0.64, chain steps 0.98) | 1.6 | GPU-latency bound, one host sync per graph |
|
||||
| commit wait + publish | 0.5 | |
|
||||
| emit, adapt (static), commit enqueue, controller | < 0.05 | |
|
||||
|
||||
GPU stage profile of one window (sum over the layers, ms): non-wait GPU work 12.3 (GDN 8.4, QSA 3.4, head 0.5; about
|
||||
25 small kernels per layer, 0.26 ms per layer), `waitB` 48.8 (the PCIe copy-kernel stage of the layer, ~1.0 ms per layer
|
||||
for ~22 MB), `waitA` 1.6 (host split + plan publish), `waitCPU` 0.3. At `pcie_frac` 0.55 the PCIe staging, not the CPU
|
||||
pool (0.5 ms per layer), is the layer's critical path. SM clock while busy: median 2917 MHz, P1 (no clock problem).
|
||||
|
||||
Conclusion: the host work between GPU phases is < 1 ms of a 50 ms round; the rest is GPU latency (kernel count), the
|
||||
PCIe stage and the CPU pool.
|
||||
|
||||
## Per request (ms)
|
||||
|
||||
| span | before | after |
|
||||
| --- | --- | --- |
|
||||
| lent-slot refill (`prefill.refill`) | 48-50 (46 in the per-call span scan) | 42 (21 enqueue with cached spans + 21 DMA wait); the DMA is 1.4 GB at ~34 GB/s, hidden only if nothing else uploads behind it |
|
||||
| table clear of the suffix drafter (`ctrl.begin_request`, 262144-cell context) | 1.0 | 0.0 |
|
||||
| canonical GDN intake (`drv.canonical_gdn`, 113 MB) | 11.5 | 11.7 (H2D bound, single pass kept) |
|
||||
| verifier assembly (`decode.assemble`) | 61 | unchanged (owner: `claude/round-overhead`) |
|
||||
| prompt read (`prefill.read`) | 520-570 for 60-100 token prompts | unchanged (owner: `claude/prefill-throughput`) |
|
||||
|
||||
Tokenizer: encode 1.0 Mtok/s (139K tokens in 130 ms), decode_bytes 0.06 us per token (`examples/bench_encode.rs`): not a cost.
|
||||
Token publication: one `try_emit` per token on a 16-slot channel, issued right after the commit is enqueued and before the
|
||||
draft: not a cost.
|
||||
|
||||
## Changes (all greedy-neutral; controls in brackets)
|
||||
|
||||
* PCIe / swap / refill source spans are looked up once per (layer, expert) and kept (`LELEKA_SPAN_CACHE=off`).
|
||||
* Suffix drafter clears the slots it claimed instead of the whole table (`LELEKA_SUFFIX_RESET=full`).
|
||||
* Lent-slot refill queued after the decode phase's intake uploads, on its own stream (`LELEKA_REFILL_DEFER=on`; EXPERIMENTAL, off by default: the end-of-prompt variant measured no gain, this one is unmeasured).
|
||||
* KAR PLE rows with `pread` (half the system calls), one write for the window PLE staging, one-pass canonical GDN intake.
|
||||
|
||||
## Paired A/B (jobs 901, 902; RTX 5090, driver 595.99.02, CUDA 13.2, 6-prompt corpus x 2 passes, 128 new tokens, spec-min-p 0.5,
|
||||
expert tier 2048 slots/layer, placeholder profile, KAR PLE, conversation cache on, 12 requests per arm; decode tok/s is the mean of
|
||||
the per-request rates of corpus 0-4, ttft the mean of all 10)
|
||||
|
||||
| comparison (order) | decode tok/s | ttft ms | corpus tokens |
|
||||
| --- | --- | --- | --- |
|
||||
| static tier: toggles off, on, on, off (901) | 49.93, 50.03, 50.03, 49.91 | 766, 758, 751, 760 | 12/12 identical in every arm |
|
||||
| adaptive tier: off, on, on, off (901) | 65.80, 65.88, 65.43, 65.77 | 743, 737, 739, 739 | placement differs per run (4/12 equal, as before) |
|
||||
| head d777560 (`rt-base2`) against this branch (`rt-ms5`), static: base, new, new, base (902) | 47.01*, 50.02, 50.03, 49.90 | 778, 750, 751, 771 | new == base-2 12/12; base-1 differs from base-2 in corpus 4 at token 77 (a near tie flipping inside the base itself) |
|
||||
| refill deferral, static: off, on, on, off (902) | 50.07, 49.99, 50.01, 50.05 | 759, 756, 752, 758 | 12/12 |
|
||||
| chat template + adaptive tier: off, on, on, off (902) | 66.60, 66.80, 66.50, 66.58 | 723, 723, 725, 723 | - |
|
||||
| sampled head + penalty window, chat (901) | 50.13 (on) vs 49.97 (off) | 734 vs 740 | not comparable with greedy |
|
||||
|
||||
(*) first arm after a long idle, an outlier of the base binary; the second base arm is 49.90.
|
||||
|
||||
Reading: the host trims move decode by 0.1-0.3 % (inside the arm-to-arm spread of 0.1 tok/s) and ttft by 8-20 ms. That is what the
|
||||
span table predicts: the per-round host work they remove is under 1 ms of 50 ms (the span cache converts 0.86 ms per round to
|
||||
0.06 once every expert pair has been seen; 16 requests are not enough to warm 24,576 pairs).
|
||||
|
||||
pcie_frac probe (902, static tier, `LELEKA_ORIGINAL_SERVE_PCIE_FRAC`, owner `claude/round-overhead`): 0.55 gives 49.30 / 50.04
|
||||
tok/s, 0.35 gives 56.40 / 57.04 (+14 %), 0.25 gives 53.87 / 54.96. Placement differs, so tokens do too. The GPU stage profile
|
||||
explains it: at 0.55 the PCIe copy-kernel stage (1.0 ms per layer) outlasts the CPU pool (0.5 ms per layer).
|
||||
Reference in New Issue
Block a user