Normalize line endings to LF in files the decode-tail/sm120 branches had converted to CRLF (whitespace only)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 08:27:39 +01:00
co-authored by Claude Sonnet 5.5
parent 463a432a9c
commit 47707480d0
11 changed files with 10829 additions and 10829 deletions
File diff suppressed because it is too large Load Diff
@@ -1,202 +1,202 @@
//! Child of mtp_original_int8. A skipped Original prompt group advances only
//! the logical conditioning cursor; it NEVER manufactures materialized KV pages.
use super::*;
use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity};
/// Genuine ring- and prompt-lease-bound no-work result. The retained physical
/// snapshot remains unchanged and may be empty even when `logical_end` is large.
pub struct OriginalMtpSkippedPrefix {
physical: MtpInt8Snapshot,
generation: u64,
start: usize,
logical_end: usize,
full_prompt_length: usize,
first_needed: usize,
lease: OriginalPromptLeaseIdentity,
}
impl OriginalMtpSkippedPrefix {
pub fn logical_end(&self) -> usize {
self.logical_end
}
pub fn first_needed(&self) -> usize {
self.first_needed
}
pub fn physical_snapshot(&self) -> &MtpInt8Snapshot {
&self.physical
}
pub fn materialized_end(&self) -> usize {
self.physical.0.end
}
pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> {
ring.validate_snapshot(&self.physical)?;
if ring.generation != self.generation
|| !ring
.current
.as_ref()
.is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0))
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
pub fn validate_source(
&self,
residual: &OriginalDeviceResidual<'_, '_, '_>,
cell0: usize,
full_prompt_length: usize,
) -> Result<()> {
if self.start != cell0
|| self.logical_end.checked_sub(cell0) != Some(residual.rows())
|| full_prompt_length != self.full_prompt_length
|| !self.lease.same_lease(&residual.lease_identity())
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
pub fn metadata_bytes(&self) -> usize {
std::mem::size_of::<Self>()
}
}
impl MtpOriginalInt8<'_> {
/// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root
/// supplies full_prompt_length from retained OriginalPromptTxn source, not
/// from this chunk's end. No stream, kernel, page allocation or numerical
/// completion occurs in this outcome.
pub fn skip_original_prompt_prefix(
&mut self,
residual: &OriginalDeviceResidual<'_, '_, '_>,
physical_prior: &MtpInt8Snapshot,
logical_prior: Option<&OriginalMtpSkippedPrefix>,
cell0: usize,
full_prompt_length: usize,
) -> Result<Option<OriginalMtpSkippedPrefix>> {
self.validate_snapshot(physical_prior)?;
if !residual.context_matches(self.context)
|| residual.rows() == 0
|| full_prompt_length > MTP_ORIGINAL_MAX_CELLS
{
return Err(Error::InvalidProjectionShape);
}
let end = cell0
.checked_add(residual.rows())
.ok_or(Error::InvalidSize)?;
if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS {
return Err(Error::InvalidProjectionShape);
}
let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64);
let logical_start = if let Some(old) = logical_prior {
old.validate_current(self)?;
if old.full_prompt_length != full_prompt_length
|| old.first_needed != first_needed
|| !Rc::ptr_eq(&old.physical.0, &physical_prior.0)
{
return Err(Error::InvalidQwenShape);
}
old.logical_end
} else {
if self
.current
.as_ref()
.is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0))
{
return Err(Error::InvalidQwenShape);
}
if self.current.is_none() && physical_prior.0.end != 0 {
return Err(Error::InvalidQwenShape);
}
physical_prior.0.end
};
if logical_start != cell0 {
return Err(Error::InvalidQwenShape);
}
// All complete groups are skipped iff the last group's end<=cutoff. This
// includes Original short remainder group; no individual-cell rounding.
if end > first_needed {
return Ok(None);
}
let generation = self
.generation
.checked_add(1)
.ok_or(Error::InvalidQwenShape)?;
let result = OriginalMtpSkippedPrefix {
physical: physical_prior.clone(),
generation,
start: cell0,
logical_end: end,
full_prompt_length,
first_needed,
lease: residual.lease_identity(),
};
self.current = Some(physical_prior.clone());
self.generation = generation;
Ok(Some(result))
}
}
impl MtpOriginalInt8<'_> {
/// Private affine transition used only by the literal captured drafter. Actual
/// graph/window guards and successful drain, not these integers, authorize it.
pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result<u64> {
self.validate_snapshot(prior)?;
if self
.current
.as_ref()
.is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0))
|| self.current.is_none() && prior.0.end != 0
{
return Err(Error::InvalidQwenShape);
}
let generation = self
.generation
.checked_add(1)
.ok_or(Error::InvalidQwenShape)?;
self.current = None;
self.generation = generation;
Ok(generation)
}
pub(crate) fn finish_original_graph_mutation(
&mut self,
prior: &MtpInt8Snapshot,
first: usize,
end: usize,
generation: u64,
) -> Result<MtpInt8Snapshot> {
self.validate_snapshot(prior)?;
if self.current.is_some()
|| self.generation != generation
|| first > prior.0.end
|| end <= first
|| end > MTP_ORIGINAL_MAX_CELLS
{
return Err(Error::InvalidQwenShape);
}
let page0 = first / 4;
let page1 = end.div_ceil(4);
if page0 > prior.0.pages.len() {
return Err(Error::InvalidQwenShape);
}
// The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back.
let mut tail = Vec::new();
tail.try_reserve_exact(page1.saturating_sub(page0))
.map_err(|_| Error::HostAllocation)?;
for p in page0..page1 {
let mut runs: [Vec<u8>; 4] = std::array::from_fn(|_| Vec::new());
for (i, n) in PAGE_BYTES.into_iter().enumerate() {
runs[i] = zero_bytes(n)?;
}
self.read_encoded_page(p, &mut runs)?;
tail.push(Rc::new(Page {
runs: runs.map(Vec::into_boxed_slice),
}));
}
let snapshot = MtpInt8Snapshot(Rc::new(Snapshot {
origin: self.origin.clone(),
pages: prior.0.pages.with_tail(page0, tail),
end,
// the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes`
checked: std::cell::Cell::new(true),
}));
self.current = Some(snapshot.clone());
Ok(snapshot)
}
}
//! Child of mtp_original_int8. A skipped Original prompt group advances only
//! the logical conditioning cursor; it NEVER manufactures materialized KV pages.
use super::*;
use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity};
/// Genuine ring- and prompt-lease-bound no-work result. The retained physical
/// snapshot remains unchanged and may be empty even when `logical_end` is large.
pub struct OriginalMtpSkippedPrefix {
physical: MtpInt8Snapshot,
generation: u64,
start: usize,
logical_end: usize,
full_prompt_length: usize,
first_needed: usize,
lease: OriginalPromptLeaseIdentity,
}
impl OriginalMtpSkippedPrefix {
pub fn logical_end(&self) -> usize {
self.logical_end
}
pub fn first_needed(&self) -> usize {
self.first_needed
}
pub fn physical_snapshot(&self) -> &MtpInt8Snapshot {
&self.physical
}
pub fn materialized_end(&self) -> usize {
self.physical.0.end
}
pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> {
ring.validate_snapshot(&self.physical)?;
if ring.generation != self.generation
|| !ring
.current
.as_ref()
.is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0))
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
pub fn validate_source(
&self,
residual: &OriginalDeviceResidual<'_, '_, '_>,
cell0: usize,
full_prompt_length: usize,
) -> Result<()> {
if self.start != cell0
|| self.logical_end.checked_sub(cell0) != Some(residual.rows())
|| full_prompt_length != self.full_prompt_length
|| !self.lease.same_lease(&residual.lease_identity())
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
pub fn metadata_bytes(&self) -> usize {
std::mem::size_of::<Self>()
}
}
impl MtpOriginalInt8<'_> {
/// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root
/// supplies full_prompt_length from retained OriginalPromptTxn source, not
/// from this chunk's end. No stream, kernel, page allocation or numerical
/// completion occurs in this outcome.
pub fn skip_original_prompt_prefix(
&mut self,
residual: &OriginalDeviceResidual<'_, '_, '_>,
physical_prior: &MtpInt8Snapshot,
logical_prior: Option<&OriginalMtpSkippedPrefix>,
cell0: usize,
full_prompt_length: usize,
) -> Result<Option<OriginalMtpSkippedPrefix>> {
self.validate_snapshot(physical_prior)?;
if !residual.context_matches(self.context)
|| residual.rows() == 0
|| full_prompt_length > MTP_ORIGINAL_MAX_CELLS
{
return Err(Error::InvalidProjectionShape);
}
let end = cell0
.checked_add(residual.rows())
.ok_or(Error::InvalidSize)?;
if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS {
return Err(Error::InvalidProjectionShape);
}
let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64);
let logical_start = if let Some(old) = logical_prior {
old.validate_current(self)?;
if old.full_prompt_length != full_prompt_length
|| old.first_needed != first_needed
|| !Rc::ptr_eq(&old.physical.0, &physical_prior.0)
{
return Err(Error::InvalidQwenShape);
}
old.logical_end
} else {
if self
.current
.as_ref()
.is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0))
{
return Err(Error::InvalidQwenShape);
}
if self.current.is_none() && physical_prior.0.end != 0 {
return Err(Error::InvalidQwenShape);
}
physical_prior.0.end
};
if logical_start != cell0 {
return Err(Error::InvalidQwenShape);
}
// All complete groups are skipped iff the last group's end<=cutoff. This
// includes Original short remainder group; no individual-cell rounding.
if end > first_needed {
return Ok(None);
}
let generation = self
.generation
.checked_add(1)
.ok_or(Error::InvalidQwenShape)?;
let result = OriginalMtpSkippedPrefix {
physical: physical_prior.clone(),
generation,
start: cell0,
logical_end: end,
full_prompt_length,
first_needed,
lease: residual.lease_identity(),
};
self.current = Some(physical_prior.clone());
self.generation = generation;
Ok(Some(result))
}
}
impl MtpOriginalInt8<'_> {
/// Private affine transition used only by the literal captured drafter. Actual
/// graph/window guards and successful drain, not these integers, authorize it.
pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result<u64> {
self.validate_snapshot(prior)?;
if self
.current
.as_ref()
.is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0))
|| self.current.is_none() && prior.0.end != 0
{
return Err(Error::InvalidQwenShape);
}
let generation = self
.generation
.checked_add(1)
.ok_or(Error::InvalidQwenShape)?;
self.current = None;
self.generation = generation;
Ok(generation)
}
pub(crate) fn finish_original_graph_mutation(
&mut self,
prior: &MtpInt8Snapshot,
first: usize,
end: usize,
generation: u64,
) -> Result<MtpInt8Snapshot> {
self.validate_snapshot(prior)?;
if self.current.is_some()
|| self.generation != generation
|| first > prior.0.end
|| end <= first
|| end > MTP_ORIGINAL_MAX_CELLS
{
return Err(Error::InvalidQwenShape);
}
let page0 = first / 4;
let page1 = end.div_ceil(4);
if page0 > prior.0.pages.len() {
return Err(Error::InvalidQwenShape);
}
// The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back.
let mut tail = Vec::new();
tail.try_reserve_exact(page1.saturating_sub(page0))
.map_err(|_| Error::HostAllocation)?;
for p in page0..page1 {
let mut runs: [Vec<u8>; 4] = std::array::from_fn(|_| Vec::new());
for (i, n) in PAGE_BYTES.into_iter().enumerate() {
runs[i] = zero_bytes(n)?;
}
self.read_encoded_page(p, &mut runs)?;
tail.push(Rc::new(Page {
runs: runs.map(Vec::into_boxed_slice),
}));
}
let snapshot = MtpInt8Snapshot(Rc::new(Snapshot {
origin: self.origin.clone(),
pages: prior.0.pages.with_tail(page0, tail),
end,
// the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes`
checked: std::cell::Cell::new(true),
}));
self.current = Some(snapshot.clone());
Ok(snapshot)
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,283 +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>;
/// 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()}
}
//! 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()}
}
File diff suppressed because it is too large Load Diff
@@ -1,197 +1,197 @@
//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing.
//!
//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time
//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement
//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert
//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`).
//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the
//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive
//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy
//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them.
//!
//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an
//! experiment can compare first-request behaviour with and without the seed inside one process.
use super::{
contract::{Error, Result},
moe_weight_cache::MoeWeightCache,
original_serve_pool::CpuExpertPool,
original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap},
original_serve_verifier::driver_error,
};
use crate::model_binding::qwen4exp_input::ModelBinding;
use leleka_cuda_driver::OriginalExpertCache;
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
use std::rc::Rc;
const LAYERS: usize = 48;
const EXPERTS: usize = 512;
/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides).
pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096;
/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts up to a few thousand tokens" of
/// docs/original-serve.md. Prompts of 45k-247k tokens measured worse than no seed on the ranked upstream profile.
#[allow(dead_code)]
pub(crate) const SUGGESTED_SEED_MAX_ROWS: usize = 4096;
/// One request's seed, for the operator's lines and the experiments.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct SeedReport {
/// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed.
pub(crate) rows: u64,
pub(crate) planned: usize,
pub(crate) plan_ms: f64,
pub(crate) queue_ms: f64,
/// Sum of the swaps' gains (routed rows won) and the most any layer changed.
pub(crate) gain: f64,
pub(crate) max_layer_swaps: usize,
}
/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every
/// resident expert (the blend with the profile's placement).
pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec<Swap> {
let mut usage: Vec<f32> = counts.to_vec();
if keep > 0.0 {
for layer in 0..LAYERS {
for expert in 0..EXPERTS {
if cache.resident_slot(layer, expert).is_some() {
usage[layer * EXPERTS + expert] += keep;
}
}
}
}
choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps)
}
/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the batch;
/// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened
/// under one fence (the direct CPU tier's admission when it is on).
pub(super) fn queue_swaps<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
swaps: &[Swap],
) -> Result<()> {
let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?;
let mut layer_swaps: Vec<Vec<&Swap>> = vec![Vec::new(); LAYERS];
for swap in swaps {
layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap);
}
for (layer, group) in layer_swaps.iter().enumerate() {
if group.is_empty() {
continue;
}
let incoming: Vec<u32> = group.iter().map(|s| s.incoming as u32).collect();
let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?;
for (swap, spans) in group.iter().zip(spans) {
let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
}
}
cache.arm_swaps().map_err(|e| driver_error(&e))
}
/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot):
/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order.
/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a
/// cycle is broken through one temporary expert. Returns the swaps made.
pub(super) fn restore_placement<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
initial: &[Option<(usize, usize)>],
) -> Result<usize> {
let mut made = 0usize;
for _round in 0..64 {
cache.wait_swaps().map_err(|e| driver_error(&e))?;
let mut mapped = vec![false; LAYERS * EXPERTS];
for slot in 0..cache.slots() {
if let Some((layer, expert)) = cache.slot_owner(slot) {
mapped[layer * EXPERTS + expert] = true;
}
}
let mut swaps = Vec::new();
let mut stuck = None;
for (slot, target) in initial.iter().enumerate() {
let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue };
if have == want {
continue;
}
if mapped[layer * EXPERTS + want] {
stuck.get_or_insert((layer, have));
continue;
}
swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have });
mapped[layer * EXPERTS + have] = false;
mapped[layer * EXPERTS + want] = true;
}
if swaps.is_empty() {
let Some((layer, have)) = stuck else { return Ok(made) };
// only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest
let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?;
swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have });
}
made += swaps.len();
queue_swaps(binding, moe, cache, cpu, known, &swaps)?;
}
Err(Error::IdentityMismatch)
}
/// The report of a planned batch (`rows`: from the counts).
pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport {
let mut per_layer = [0usize; LAYERS];
for swap in swaps {
per_layer[swap.layer] += 1;
}
SeedReport {
rows: (counts.iter().map(|&c| f64::from(c)).sum::<f64>() / (10 * LAYERS) as f64).round() as u64,
planned: swaps.len(),
plan_ms: 0.0,
queue_ms: 0.0,
gain: swaps.iter().map(|s| f64::from(s.gain)).sum(),
max_layer_swaps: per_layer.into_iter().max().unwrap_or(0),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_counts_prompt_rows_and_the_busiest_layer() {
let mut counts = vec![0f32; LAYERS * EXPERTS];
// 3 rows routed to 10 experts in every layer
for layer in 0..LAYERS {
for expert in 0..10 {
counts[layer * EXPERTS + expert] = 3.0;
}
}
let swaps = [
Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 },
Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 },
Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 },
];
let report = summarize(&counts, &swaps);
assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2));
assert_eq!(report.gain, 15.5);
assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0);
}
#[test]
fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() {
let mut usage = vec![0.0f32; LAYERS * EXPERTS];
// layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows)
for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] {
usage[3 * EXPERTS + e] = u;
}
let resident = |l: usize, e: usize| l == 3 && e < 2;
let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS);
// (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops
assert_eq!(swaps.len(), 1);
assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0));
}
}
//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing.
//!
//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time
//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement
//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert
//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`).
//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the
//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive
//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy
//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them.
//!
//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an
//! experiment can compare first-request behaviour with and without the seed inside one process.
use super::{
contract::{Error, Result},
moe_weight_cache::MoeWeightCache,
original_serve_pool::CpuExpertPool,
original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap},
original_serve_verifier::driver_error,
};
use crate::model_binding::qwen4exp_input::ModelBinding;
use leleka_cuda_driver::OriginalExpertCache;
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
use std::rc::Rc;
const LAYERS: usize = 48;
const EXPERTS: usize = 512;
/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides).
pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096;
/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts up to a few thousand tokens" of
/// docs/original-serve.md. Prompts of 45k-247k tokens measured worse than no seed on the ranked upstream profile.
#[allow(dead_code)]
pub(crate) const SUGGESTED_SEED_MAX_ROWS: usize = 4096;
/// One request's seed, for the operator's lines and the experiments.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct SeedReport {
/// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed.
pub(crate) rows: u64,
pub(crate) planned: usize,
pub(crate) plan_ms: f64,
pub(crate) queue_ms: f64,
/// Sum of the swaps' gains (routed rows won) and the most any layer changed.
pub(crate) gain: f64,
pub(crate) max_layer_swaps: usize,
}
/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every
/// resident expert (the blend with the profile's placement).
pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec<Swap> {
let mut usage: Vec<f32> = counts.to_vec();
if keep > 0.0 {
for layer in 0..LAYERS {
for expert in 0..EXPERTS {
if cache.resident_slot(layer, expert).is_some() {
usage[layer * EXPERTS + expert] += keep;
}
}
}
}
choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps)
}
/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the batch;
/// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened
/// under one fence (the direct CPU tier's admission when it is on).
pub(super) fn queue_swaps<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
swaps: &[Swap],
) -> Result<()> {
let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?;
let mut layer_swaps: Vec<Vec<&Swap>> = vec![Vec::new(); LAYERS];
for swap in swaps {
layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap);
}
for (layer, group) in layer_swaps.iter().enumerate() {
if group.is_empty() {
continue;
}
let incoming: Vec<u32> = group.iter().map(|s| s.incoming as u32).collect();
let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?;
for (swap, spans) in group.iter().zip(spans) {
let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
}
}
cache.arm_swaps().map_err(|e| driver_error(&e))
}
/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot):
/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order.
/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a
/// cycle is broken through one temporary expert. Returns the swaps made.
pub(super) fn restore_placement<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
initial: &[Option<(usize, usize)>],
) -> Result<usize> {
let mut made = 0usize;
for _round in 0..64 {
cache.wait_swaps().map_err(|e| driver_error(&e))?;
let mut mapped = vec![false; LAYERS * EXPERTS];
for slot in 0..cache.slots() {
if let Some((layer, expert)) = cache.slot_owner(slot) {
mapped[layer * EXPERTS + expert] = true;
}
}
let mut swaps = Vec::new();
let mut stuck = None;
for (slot, target) in initial.iter().enumerate() {
let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue };
if have == want {
continue;
}
if mapped[layer * EXPERTS + want] {
stuck.get_or_insert((layer, have));
continue;
}
swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have });
mapped[layer * EXPERTS + have] = false;
mapped[layer * EXPERTS + want] = true;
}
if swaps.is_empty() {
let Some((layer, have)) = stuck else { return Ok(made) };
// only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest
let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?;
swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have });
}
made += swaps.len();
queue_swaps(binding, moe, cache, cpu, known, &swaps)?;
}
Err(Error::IdentityMismatch)
}
/// The report of a planned batch (`rows`: from the counts).
pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport {
let mut per_layer = [0usize; LAYERS];
for swap in swaps {
per_layer[swap.layer] += 1;
}
SeedReport {
rows: (counts.iter().map(|&c| f64::from(c)).sum::<f64>() / (10 * LAYERS) as f64).round() as u64,
planned: swaps.len(),
plan_ms: 0.0,
queue_ms: 0.0,
gain: swaps.iter().map(|s| f64::from(s.gain)).sum(),
max_layer_swaps: per_layer.into_iter().max().unwrap_or(0),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_counts_prompt_rows_and_the_busiest_layer() {
let mut counts = vec![0f32; LAYERS * EXPERTS];
// 3 rows routed to 10 experts in every layer
for layer in 0..LAYERS {
for expert in 0..10 {
counts[layer * EXPERTS + expert] = 3.0;
}
}
let swaps = [
Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 },
Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 },
Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 },
];
let report = summarize(&counts, &swaps);
assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2));
assert_eq!(report.gain, 15.5);
assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0);
}
#[test]
fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() {
let mut usage = vec![0.0f32; LAYERS * EXPERTS];
// layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows)
for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] {
usage[3 * EXPERTS + e] = u;
}
let resident = |l: usize, e: usize| l == 3 && e < 2;
let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS);
// (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops
assert_eq!(swaps.len(), 1);
assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0));
}
}
File diff suppressed because it is too large Load Diff
+23 -23
View File
@@ -1,23 +1,23 @@
#!/usr/bin/env bash
# Build the leleka-runtime test binary (the replay smoke) of THIS worktree in WSL (never on the server).
# scripts/decode-sm120/build_rt.sh TAG run from Git Bash in the worktree
# Result: WSL ~/sm120-stack/rt-TAG; copy to rnr5090:/data/leleka-e2e/sm120/rt-TAG.
set -euo pipefail
tag=${1:?tag}
root=$(git rev-parse --show-toplevel)
tar_win="$root/../wt-sm120-rt.tar"
git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win"
w=$(cygpath -m "$tar_win"); tar_wsl="/mnt/c${w#C:}"
wsl -d Ubuntu -e bash -lc "
set -e
source ~/.cargo/env
export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin
rm -rf ~/sm120-src-rt && mkdir -p ~/sm120-src-rt ~/sm120-stack && tar -xf '$tar_wsl' -C ~/sm120-src-rt
cd ~/sm120-src-rt
export CARGO_TARGET_DIR=\$HOME/sm120-target-rel
nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib > ~/sm120-stack/build-rt-$tag.log 2>&1
exe=\$(grep -o 'release/deps/leleka_runtime-[0-9a-f]*' ~/sm120-stack/build-rt-$tag.log | tail -1)
cp \$CARGO_TARGET_DIR/\$exe ~/sm120-stack/rt-$tag
sha256sum ~/sm120-stack/rt-$tag
"
rm -f "$tar_win"
#!/usr/bin/env bash
# Build the leleka-runtime test binary (the replay smoke) of THIS worktree in WSL (never on the server).
# scripts/decode-sm120/build_rt.sh TAG run from Git Bash in the worktree
# Result: WSL ~/sm120-stack/rt-TAG; copy to rnr5090:/data/leleka-e2e/sm120/rt-TAG.
set -euo pipefail
tag=${1:?tag}
root=$(git rev-parse --show-toplevel)
tar_win="$root/../wt-sm120-rt.tar"
git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win"
w=$(cygpath -m "$tar_win"); tar_wsl="/mnt/c${w#C:}"
wsl -d Ubuntu -e bash -lc "
set -e
source ~/.cargo/env
export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin
rm -rf ~/sm120-src-rt && mkdir -p ~/sm120-src-rt ~/sm120-stack && tar -xf '$tar_wsl' -C ~/sm120-src-rt
cd ~/sm120-src-rt
export CARGO_TARGET_DIR=\$HOME/sm120-target-rel
nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib > ~/sm120-stack/build-rt-$tag.log 2>&1
exe=\$(grep -o 'release/deps/leleka_runtime-[0-9a-f]*' ~/sm120-stack/build-rt-$tag.log | tail -1)
cp \$CARGO_TARGET_DIR/\$exe ~/sm120-stack/rt-$tag
sha256sum ~/sm120-stack/rt-$tag
"
rm -f "$tar_win"