diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs new file mode 100644 index 00000000..eb597017 --- /dev/null +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs @@ -0,0 +1,196 @@ +//! The replay of the recorded graphs of the synthetic verifier: the host plays the all-CPU expert pool (zeros) and +//! the empty GPU plan. This runs every captured kernel with its real launch parameters (shared-memory attributes, +//! grids, the doorbell/ring spin kernels). A stuck window ends after the 20 s doorbell timeout. +use super::*; + +/// (window rows, sampler, rows kept by the commit, draft after the commit) +type Item = (usize, Option, usize, bool); + +/// The state of the replay of one request. +struct Replay<'ctx> { + position: usize, + publish_ws: NativeBatchWorkspace<'ctx>, + history: DeviceBuffer<'ctx>, + ring_prior: Option, + last_checkpoint: Option>, + last_prefix: Option, +} +/// Sampler parameters of a greedy window, or of the sampled one (every sampler path). +fn sampler_params(sampled: bool) -> SamplerParams { + let mut params = SamplerParams::default(); + params.greedy = !sampled; + params.temperature = if sampled { 0.7 } else { 0.0 }; + params.seed = 1; + if sampled { + params.top_k = 20; + params.top_p = 0.95; + params.min_keep = 1; + params.penalty_last_n = 64; + params.penalty_repeat = 1.1; + } + params +} +/// The windows of a request: greedy t=1,2,max_t, then SAMPLED (penalties, every sampler path) t=3. +/// Round shape of the serve loop: a T=1 window + draft, then a full T=max_t window that accepts `a+1` rows (a cycles +/// through PROBE_ACCEPTED_ROWS per request) + draft with the ring still anchored at the previous speculative snapshot. +fn plan(request: usize, max_t: usize) -> Vec { + let rows_list = env_list("PROBE_ACCEPTED_ROWS", "0,1,2,3,4,5"); + let a = rows_list[request % rows_list.len().max(1)] as usize % max_t; + vec![ + (1, None, 1, true), + (max_t, None, a + 1, true), + (2, None, 2, false), + (3, Some(SamplerPath::Split), 3, false), + (2, Some(SamplerPath::OneBlock), 2, false), + (2, Some(SamplerPath::Old), 2, false), + ] +} +fn full_policy() -> OriginalMtpFullPolicy { + OriginalMtpFullPolicy { + native_router: true, + legacy_router_mode: 0, + native_shared_scalar: true, + native_combine: true, + old_grouped_s2: false, + native_final_gr: true, + fp32_final_gr: false, + gr: OriginalMtpGrVariant::Plain, + kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)), + coupled_j: None, + } +} +impl<'ctx> Replay<'ctx> { + fn start(context: &'ctx Context<'ctx>) -> Option> { + let publish_ws = step!("native_batch_workspace (publish)", context.native_batch_workspace())?; + // the penalty-history stage of the stack: 8 rows x 4096 ids, -1 where unavailable + let mut history = step!("alloc penalty history", context.allocate(4096 * 8 * 4))?; + let _ = step!("penalty history init", history.copy_from(&vec![0xffu8; 4096 * 8 * 4])); + Some(Replay { position: 0, publish_ws, history, ring_prior: None, last_checkpoint: None, last_prefix: None }) + } + fn sampling(&self, sampled: Option) -> NativeHeadSampling<'_, 'ctx> { + NativeHeadSampling { + position: self.position as u64, + params: sampler_params(sampled.is_some()), + history: sampled.map(|_| &self.history), + history_len: if sampled.is_some() { 64 } else { 0 }, + path: sampled.unwrap_or(SamplerPath::Split), + enabled: sampled.is_some(), + } + } + /// Runs one window; its selection and the completed window (None when that read failed). None ends the replay. + fn run_window( + &mut self, + verifier: &mut Verifier<'_, 'ctx>, + t: usize, + sampled: Option, + ) -> Option<(NativeHeadSelection, Option>)> { + let position = self.position; + let tokens: Vec = (0..t).map(|i| 100 + i as i32).collect(); + let ple = vec![0.0f32; t * 2560]; + let sampling = self.sampling(sampled); + let started = std::time::Instant::now(); + let mut groups_seen = 0usize; + let result = verifier.run(&tokens, position, Some(&ple), sampling, |_rows, sink, _copy| { + groups_seen += 1; + sink.with_output(|out| { + out.fill(0.0); + Ok(()) + }) + }); + let window = step!( + format!( + "verifier.run(t={t}, position={position}, sampler={sampled:?}) in {:?}, {groups_seen} pool groups", + started.elapsed() + ), + result + )?; + eprintln!("PREFLIGHT window t={t} sampled ids {:?}", window.selection.ids()); + let completed = step!("verifier.completed_window", verifier.completed_window()); + Some((window.selection, completed)) + } + /// The reads `OriginalServeHost::publish_committed` / `settle_state` make after a commit. + fn reads<'w>(&mut self, verifier: &mut Verifier<'w, 'ctx>, qsa_journal: &Rc>) { + let _ = step!("verifier.accepted_tokens", verifier.accepted_tokens().map(|a| a.len())); + let publish_ws = &mut self.publish_ws; + self.last_checkpoint = step!( + "with_committed_qsa(0).checkpoint", + verifier.with_committed_qsa(0, |index| index.checkpoint(publish_ws)) + ); + self.last_prefix = step!("qsa_journal.committed_mapped_prefix(0)", qsa_journal.committed_mapped_prefix(0)); + let _ = step!( + "with_committed_gdn(0)", + verifier.with_committed_gdn(0, |values, history| Ok((values.len(), history.len()))) + ); + } + /// The draft session restores a stored checkpoint and uses that very snapshot as `prior`. + fn draft_prior( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + reset_snapshot: &mut Option, + ) -> Option { + match (self.ring_prior.take(), reset_snapshot.take()) { + (Some(speculative), _) => Some(speculative), + (None, Some(restored)) => Some(restored), + (None, None) => step!("ring.empty_snapshot", ring.empty_snapshot()), + } + } + /// `OriginalServeHost::draft_committed`: the MTP drafter over the completed window (first call records its graphs). + fn draft( + &mut self, + mtp: &mut Option>, + reset_snapshot: &mut Option, + window: (NativeHeadSelection, Option>), + (t, keep): (usize, usize), + ) { + let (selection, completed) = window; + let (Some((ring, actor)), Some(done)) = (mtp.as_mut(), completed) else { return }; + actor.set_prompt_len(1); + actor.set_max_drafts(3); + let Some(prior) = self.draft_prior(ring, reset_snapshot) else { return }; + let started = std::time::Instant::now(); + eprintln!( + "PREFLIGHT draft: window t={t} position={} accepted_row={} ring_prior_end={}", + self.position, + keep - 1, + prior.next_position() + ); + let drafted = actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &full_policy()); + if let Some(d) = + step!(format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), drafted) + { + let snapshot = d.final_snapshot(); + eprintln!("PREFLIGHT drafted ids {:?}, ring snapshot end {}", d.ids(), snapshot.next_position()); + self.ring_prior = Some(snapshot.clone()); + } + let _ = step!("actor.idle", actor.idle()); + } +} +impl<'a, 'ctx> Rig<'a, 'ctx> { + /// Replays the recorded graphs over zero weights; the QSA checkpoint and prefix the request ends with. + /// `None` ends the probe. + pub(super) fn replay<'w>( + &self, + request: usize, + verifier: &mut Verifier<'w, 'ctx>, + mtp: &mut Option>, + reset_snapshot: &mut Option, + qsa_journal: &Rc>, + ) -> Option> { + let mut replay = Replay::start(self.context)?; + for (t, sampled, keep, draft_after) in plan(request, self.max_t) { + let Some(window) = replay.run_window(verifier, t, sampled) else { break }; + // alternate the synchronous and the asynchronous (event) commit; the next run / read joins the event + let async_commit = t == 2; + let commit = verifier.commit(keep, async_commit); + if step!(format!("verifier.commit(keep={keep}, async={async_commit})"), commit).is_none() { + break; + } + replay.reads(verifier, qsa_journal); + if draft_after { + replay.draft(mtp, reset_snapshot, window, (t, keep)); + } + replay.position += keep; + } + Some((replay.last_checkpoint, replay.last_prefix)) + } +} diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/weights.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/weights.rs new file mode 100644 index 00000000..7272eaed --- /dev/null +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/weights.rs @@ -0,0 +1,139 @@ +//! The uninitialised, correctly sized weights of the synthetic verifier (every allocation is a preflight step). +use super::*; + +/// One allocation, reported as the other preflight steps are. +fn alloc<'ctx>(context: &'ctx Context<'ctx>, name: impl std::fmt::Display, bytes: usize) -> Option> { + step!(name, context.allocate(bytes)) +} +fn size(kind: u32, n_in: usize, n_out: usize) -> Result { + native_head_row_bytes(kind, n_in).map(|r| r * n_out) +} +/// The hyper-connection weights of one half layer. +pub(super) struct Hc<'ctx> { + pub(super) norm: DeviceBuffer<'ctx>, + pub(super) down: DeviceBuffer<'ctx>, + pub(super) up: DeviceBuffer<'ctx>, + pub(super) inject: DeviceBuffer<'ctx>, +} +pub(super) struct Ple<'ctx> { + pub(super) key: DeviceBuffer<'ctx>, + pub(super) value: DeviceBuffer<'ctx>, + pub(super) norm_key: DeviceBuffer<'ctx>, + pub(super) norm_query: DeviceBuffer<'ctx>, + pub(super) norm_conv: DeviceBuffer<'ctx>, + pub(super) conv1d: DeviceBuffer<'ctx>, + pub(super) scratch: DeviceBuffer<'ctx>, + pub(super) history: DeviceBuffer<'ctx>, +} +/// The router and the shared experts. +pub(super) struct Moe<'ctx> { + pub(super) router: DeviceBuffer<'ctx>, + pub(super) gate_inp: DeviceBuffer<'ctx>, + pub(super) gate: DeviceBuffer<'ctx>, + pub(super) up: DeviceBuffer<'ctx>, + pub(super) down: DeviceBuffer<'ctx>, +} +/// The GDN weights that are not matrices. +pub(super) struct Gdn<'ctx> { + pub(super) conv: DeviceBuffer<'ctx>, + pub(super) alpha: DeviceBuffer<'ctx>, + pub(super) beta: DeviceBuffer<'ctx>, + pub(super) dt: DeviceBuffer<'ctx>, + pub(super) a: DeviceBuffer<'ctx>, + pub(super) norm: DeviceBuffer<'ctx>, +} +pub(super) struct Weights<'ctx> { + pub(super) proj: Vec>, + pub(super) hc: Hc<'ctx>, + pub(super) ple: Ple<'ctx>, + /// QSA norms and indexer projections: pairwise disjoint per layer. + pub(super) qsa: Vec>>, + pub(super) gamma: Vec>, + pub(super) moe: Moe<'ctx>, + pub(super) gdn: Gdn<'ctx>, +} +fn projections<'ctx>(context: &'ctx Context<'ctx>, proj: &[u32]) -> Option>> { + let mats: Vec<(usize, usize)> = + vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)]; + let mut proj_bufs = Vec::new(); + for (i, (&(n_in, n_out), &k)) in mats.iter().zip(proj).enumerate() { + let bytes = step!("projection bytes", size(k, n_in, n_out))?; + proj_bufs.push(alloc(context, format!("alloc projection[{i}] kind {k} ({} MiB)", bytes >> 20), bytes)?); + } + Some(proj_bufs) +} +fn hyper_connection<'ctx>(context: &'ctx Context<'ctx>) -> Option> { + Some(Hc { + norm: alloc(context, "alloc hc_norm", 10240 * 4)?, + down: alloc(context, "alloc hc_down", 320 * 10240 * 2)?, + up: alloc(context, "alloc hc_up", 10240 * 320 * 2)?, + inject: alloc(context, "alloc hc_inject", 4 * 10240 * 2)?, + }) +} +fn ple<'ctx>(context: &'ctx Context<'ctx>) -> Option> { + Some(Ple { + key: alloc(context, "alloc ple_key", 10240 * 2560 * 2)?, + value: alloc(context, "alloc ple_value", 2560 * 2560 * 2)?, + norm_key: alloc(context, "alloc ple_norm_key", 10240 * 4)?, + norm_query: alloc(context, "alloc ple_norm_query", 10240 * 4)?, + norm_conv: alloc(context, "alloc ple_norm_conv", 10240 * 4)?, + conv1d: alloc(context, "alloc ple_conv1d", 4 * 10240 * 2)?, + scratch: alloc(context, "alloc ple_scratch", PLE_SCRATCH_BYTES)?, + history: alloc(context, "alloc ple_history", 9 * 10240 * 4)?, + }) +} +fn qsa_norms<'ctx>(context: &'ctx Context<'ctx>) -> Option>>> { + let mut qsa_bufs = Vec::new(); + for layer in 0..12 { + let mut five = Vec::new(); + for bytes in [256 * 4, 256 * 4, 128 * 4, 128 * 2560 * 2, 4 * 128 * 2560 * 2] { + five.push(alloc(context, format!("alloc qsa[{layer}] {bytes}"), bytes)?); + } + qsa_bufs.push(five); + } + Some(qsa_bufs) +} +fn gammas<'ctx>(context: &'ctx Context<'ctx>) -> Option>> { + let mut gamma_bufs = Vec::new(); + for i in 0..12 { + gamma_bufs.push(alloc(context, format!("alloc gamma[{i}]"), 512)?); + } + Some(gamma_bufs) +} +fn moe<'ctx>(context: &'ctx Context<'ctx>, shared: &[u32]) -> Option> { + let router = alloc(context, "alloc router", 512 * 2560 * 2)?; + let gate_inp = alloc(context, "alloc gate_inp_shexp", 2560 * 2)?; + let gate_bytes = step!("shared gate bytes", size(shared[0], 2560, 640))?; + let gate = alloc(context, "alloc shared gate", gate_bytes)?; + let up_bytes = step!("shared up bytes", size(shared[1], 2560, 640))?; + let up = alloc(context, "alloc shared up", up_bytes)?; + let down_bytes = step!("shared down bytes", size(shared[2], 640, 2560))?; + let down = alloc(context, "alloc shared down", down_bytes)?; + Some(Moe { router, gate_inp, gate, up, down }) +} +fn gdn<'ctx>(context: &'ctx Context<'ctx>) -> Option> { + Some(Gdn { + conv: alloc(context, "alloc gdn conv", 10240 * 4 * 4)?, + alpha: alloc(context, "alloc gdn alpha", 48 * 2560 * 2)?, + beta: alloc(context, "alloc gdn beta", 48 * 2560 * 2)?, + dt: alloc(context, "alloc gdn dt", 48 * 4)?, + a: alloc(context, "alloc gdn a", 48 * 4)?, + norm: alloc(context, "alloc gdn norm", 128 * 4)?, + }) +} +impl<'ctx> Weights<'ctx> { + /// Weights shared across layers where the binding allows it. + pub(super) fn allocate(context: &'ctx Context<'ctx>, proj: &[u32], shared: &[u32]) -> Option> { + let weights = Weights { + proj: projections(context, proj)?, + hc: hyper_connection(context)?, + ple: ple(context)?, + qsa: qsa_norms(context)?, + gamma: gammas(context)?, + moe: moe(context, shared)?, + gdn: gdn(context)?, + }; + eprintln!("PREFLIGHT synthetic verifier weights allocated={}MiB", context.allocated_bytes() >> 20); + Some(weights) + } +} diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/window.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/window.rs new file mode 100644 index 00000000..838f92f4 --- /dev/null +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/window.rs @@ -0,0 +1,158 @@ +//! The window aggregates of the synthetic verifier: one per window width plus the commit graph. +use super::*; + +impl<'a, 'ctx> Rig<'a, 'ctx> { + /// One aggregate per window width plus the commit graph (the last one). + pub(super) fn windows<'w>( + &'w self, + verifier: &Verifier<'w, 'ctx>, + canonical: &mut OriginalVerifyCanonicalGdn<'ctx>, + qsa_journal: &Rc>, + ) -> Option>>> { + let mut windows = Vec::new(); + for t in 1..=self.max_t + 1 { + let window_t = if t <= self.max_t { t } else { self.max_t }; + let w = self.base_window(window_t, verifier, canonical, qsa_journal)?; + let w = self.with_projections(w)?; + let w = self.with_gr(w)?; + let w = self.with_qsa(w)?; + windows.push(Some(self.with_moe(w)?)); + } + Some(windows) + } + fn gdn_weights(&self) -> [OriginalVerifyGdnWeights<'_, 'ctx>; 36] { + let gdn = &self.w.gdn; + std::array::from_fn(|_| OriginalVerifyGdnWeights { + conv: &gdn.conv, + alpha: &gdn.alpha, + beta: &gdn.beta, + dt: &gdn.dt, + a: &gdn.a, + norm: &gdn.norm, + }) + } + /// The GDN journal, the head and embedding rows and the layout. + fn base_window<'w>( + &'w self, + window_t: usize, + verifier: &Verifier<'w, 'ctx>, + canonical: &mut OriginalVerifyCanonicalGdn<'ctx>, + qsa_journal: &Rc>, + ) -> Option> { + let context = self.context; + let gdn_weights = self.gdn_weights(); + let bank = step!("verifier.bank()", verifier.bank())?; + let journal = step!( + format!("gdn_journal(t={window_t})"), + bank.gdn_journal(canonical, gdn_weights, Some(&self.w.ple.history)) + )?; + let head_rows = step!(format!("head.rows({window_t})"), self.parts.head.rows(window_t))?; + let resources = step!( + format!("OriginalVerifyResources::new(t={window_t})"), + OriginalVerifyResources::new(context, journal, Rc::clone(qsa_journal), head_rows) + )?; + let embed_rows = step!(format!("embed.rows({window_t})"), self.parts.embed.rows(window_t))?; + step!( + format!("OriginalVerifyWindowResources::new(t={window_t})"), + OriginalVerifyWindowResources::new(context, resources, embed_rows, self.parts.layout.clone(), window_t) + ) + } + fn gdn_proj(&self) -> Vec> { + let (proj, bufs) = (self.proj, &self.w.proj); + (0..36) + .map(|_| OriginalVerifyGdnProjections { + qkv: OriginalVerifyNativeMatrix { kind: proj[0], buffer: &bufs[0] }, + gate: OriginalVerifyNativeMatrix { kind: proj[1], buffer: &bufs[1] }, + out: OriginalVerifyNativeMatrix { kind: proj[2], buffer: &bufs[2] }, + }) + .collect::>() + } + fn qsa_proj(&self) -> Vec> { + let (proj, bufs) = (self.proj, &self.w.proj); + (0..12) + .map(|_| OriginalVerifyQsaProjections { + k: OriginalVerifyNativeMatrix { kind: proj[3], buffer: &bufs[3] }, + v: OriginalVerifyNativeMatrix { kind: proj[4], buffer: &bufs[4] }, + q: OriginalVerifyNativeMatrix { kind: proj[5], buffer: &bufs[5] }, + out: OriginalVerifyNativeMatrix { kind: proj[6], buffer: &bufs[6] }, + }) + .collect::>() + } + fn with_projections<'w>( + &'w self, + w: OriginalVerifyWindowResources<'w, 'ctx>, + ) -> Option> { + step!( + "with_projections", + OriginalVerifyProjBinding::new(self.context, &self.parts.g, self.gdn_proj(), self.qsa_proj()) + .and_then(|p| w.with_projections(p)) + ) + } + fn half(&self) -> HcHalfBuffers<'_, 'ctx> { + let hc = &self.w.hc; + HcHalfBuffers { norm: &hc.norm, down: &hc.down, up: &hc.up, inject: &hc.inject } + } + fn with_gr<'w>( + &'w self, + w: OriginalVerifyWindowResources<'w, 'ctx>, + ) -> Option> { + let (hc, ple) = (&self.w.hc, &self.w.ple); + let layers: Vec<_> = (0..48).map(|_| HcLayerBuffers { attention: self.half(), ffn: self.half() }).collect(); + let output = HcOutputBuffers { norm: &hc.norm, down: &hc.down, up: &hc.up }; + let ple = PleBuffers { + key: PleKeyBuffer::Bf16(&ple.key), + value: &ple.value, + norm_key: &ple.norm_key, + norm_query: &ple.norm_query, + norm_conv: &ple.norm_conv, + conv1d: &ple.conv1d, + scratch: &ple.scratch, + history: &ple.history, + }; + step!( + "with_gr", + OriginalVerifyGrBinding::new(self.context, layers, output, Some(ple)).and_then(|b| w.with_gr(b)) + ) + } + fn with_qsa<'w>( + &'w self, + w: OriginalVerifyWindowResources<'w, 'ctx>, + ) -> Option> { + let qsa = &self.w.qsa; + let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] = + std::array::from_fn(|i| OriginalVerifyQsaLayerWeights { + attn_q_norm: &qsa[i][0], + attn_k_norm: &qsa[i][1], + index_q_norm: &qsa[i][2], + index_k_proj: &qsa[i][3], + index_q_proj: &qsa[i][4], + }); + step!( + "with_qsa", + OriginalVerifyQsaBinding::new(self.context, self.parts.g, qsa_layers).and_then(|b| w.with_qsa(b)) + ) + } + fn with_moe<'w>( + &'w self, + w: OriginalVerifyWindowResources<'w, 'ctx>, + ) -> Option> { + let (moe, shared) = (&self.w.moe, self.shared); + let moe_layers: Vec<_> = (0..48) + .map(|_| OriginalVerifyMoeLayerWeights { + router: &moe.router, + gate_inp_shexp: &moe.gate_inp, + gate_shexp: &moe.gate, + gate_shexp_type: shared[0], + up_shexp: &moe.up, + up_shexp_type: shared[1], + down_shexp: &moe.down, + down_shexp_type: shared[2], + }) + .collect(); + step!( + "with_moe", + OriginalVerifyMoeBinding::new(self.context, &self.parts.g, moe_layers, self.parts.formats.clone()) + .and_then(|b| w.with_moe(b)) + ) + } +} diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs index 9bff0808..bf32e408 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs @@ -2,7 +2,111 @@ #[allow(unused_imports)] use super::*; +use std::rc::Rc; +use weights::Weights; +#[path = "synthetic_verifier/replay.rs"] +mod replay; +#[path = "synthetic_verifier/weights.rs"] +mod weights; +#[path = "synthetic_verifier/window.rs"] +mod window; + +/// The drafter of the serve stack: the draft ring and its actor. +type Mtp<'ctx> = (MtpOriginalInt8<'ctx>, OriginalMtpActor<'ctx>); +/// A verifier over the window resources of one request. +type Verifier<'w, 'ctx> = OriginalVerifier<'ctx, OriginalVerifyWindowResources<'w, 'ctx>>; +/// The QSA index checkpoint and the mapped prefix a request ends with. +type Kept<'ctx> = (Option>, Option); + +/// The twelve resident QSA indices and the twelve mapped journals. +type Owners<'ctx> = ([OriginalQsaResidentIndex<'ctx>; 12], [OriginalQsaMappedJournal<'ctx>; 12]); + +fn rope<'a, 'ctx>() -> OriginalVerifyRope<'a, 'ctx> { + OriginalVerifyRope { + theta_scale: 1e7f32.powf(-2.0 / 64.0), + freq_scale: 1.0, + corr_low: 0.0, + corr_high: 0.0, + ext_factor: 0.0, + magnitude: 1.0, + positions: None, + angles: None, + } +} + +/// The sizes of one synthetic verifier: window width, cells, vocabulary and the kinds of the head and the embedding. +struct Sizes { + max_t: usize, + cells: usize, + vocab: usize, + head_kind: u32, + embed_kind: u32, +} +/// The expert formats, geometry and layout, and the head and embedding rows. +struct Parts<'ctx> { + formats: OriginalVerifyExpertFormats, + g: OriginalVerifyGeometry, + layout: OriginalVerifyExpertLayout, + head: OriginalNativeHead<'ctx>, + embed: OriginalNativeEmbed<'ctx>, +} +/// The fixed parts of the synthetic verifier and its weights. +struct Rig<'a, 'ctx> { + context: &'ctx Context<'ctx>, + proj: &'a [u32], + shared: &'a [u32], + max_t: usize, + parts: Parts<'ctx>, + w: Weights<'ctx>, +} +impl<'ctx> Parts<'ctx> { + fn build(context: &'ctx Context<'ctx>, fmt: (u32, u32), sizes: &Sizes) -> Option> { + let formats = + step!("OriginalVerifyExpertFormats::new", OriginalVerifyExpertFormats::new([fmt; 48], 2560, 640))?; + let blob = step!("formats.blob_bytes(0)", formats.blob_bytes(0))?; + eprintln!("PREFLIGHT expert fmt gate/up={} down={} blob_bytes={blob}", fmt.0, fmt.1); + let g = geometry(sizes.max_t, sizes.cells, blob); + let layout = step!("OriginalVerifyExpertLayout::new", OriginalVerifyExpertLayout::new([blob; 48], blob))?; + let size = |k: u32, n_in: usize, n_out: usize| native_head_row_bytes(k, n_in).map(|r| r * n_out); + // ---- head rows and embedding rows + let head_bytes = step!("head bytes", size(sizes.head_kind, 2560, sizes.vocab))?; + let payload = vec![0u8; head_bytes]; + let head = step!( + "original_native_head", + context.original_native_head(sizes.head_kind, 2560, sizes.vocab, &payload, NativeHeadDispatch::default()) + )?; + let embed_bytes = step!("embed bytes", size(sizes.embed_kind, 2560, sizes.vocab))?; + let payload = vec![0u8; embed_bytes]; + let embed = step!( + "original_native_embed", + context.original_native_embed(sizes.embed_kind, 2560, sizes.vocab, &payload) + )?; + Some(Parts { formats, g, layout, head, embed }) + } +} +/// The MTP drafter over the same head allocation (the serve stack lends `OriginalNativeOutput::mtp_head`); the +/// outer `None` ends the probe, the inner one is a probe without a drafter. +fn drafter<'ctx>( + context: &'ctx Context<'ctx>, + head: &OriginalNativeHead<'ctx>, + sizes: &Sizes, +) -> Option>> { + if std::env::var("PROBE_DRAFT").map_or(true, |v| v != "0") { + let head_weights = step!("head.retain_weights", head.retain_weights())?; + Some(synthetic_mtp( + context, + Some(head_weights), + sizes.head_kind, + sizes.vocab, + env_usize("PROBE_MTP_MAX_T", 6), + env_usize("PROBE_CAPACITY", 1024), + false, + )) + } else { + Some(None) + } +} /// One synthetic verifier assembly: the window graphs T=1..=max_t and the commit graph are RECORDED /// (`OriginalVerifier::record_all`) over uninitialised correctly sized weights of the given ggml kinds. This is /// `original_serve_verifier::assemble` without the model: every sealed window module is loaded and every launch is @@ -19,177 +123,94 @@ pub(super) fn synthetic_verifier<'ctx>( head_kind: u32, embed_kind: u32, ) { - use std::rc::Rc; - let formats = need!("OriginalVerifyExpertFormats::new", OriginalVerifyExpertFormats::new([fmt; 48], 2560, 640)); - let blob = need!("formats.blob_bytes(0)", formats.blob_bytes(0)); - eprintln!("PREFLIGHT expert fmt gate/up={} down={} blob_bytes={blob}", fmt.0, fmt.1); - let g = geometry(max_t, cells, blob); - let layout = need!("OriginalVerifyExpertLayout::new", OriginalVerifyExpertLayout::new([blob; 48], blob)); - - let size = |k: u32, n_in: usize, n_out: usize| native_head_row_bytes(k, n_in).map(|r| r * n_out); - - // ---- head rows and embedding rows - let head_bytes = need!("head bytes", size(head_kind, 2560, vocab)); - let head = need!( - "original_native_head", - context.original_native_head(head_kind, 2560, vocab, &vec![0u8; head_bytes], NativeHeadDispatch::default()) - ); - let embed_bytes = need!("embed bytes", size(embed_kind, 2560, vocab)); - let embed = - need!("original_native_embed", context.original_native_embed(embed_kind, 2560, vocab, &vec![0u8; embed_bytes])); - - // ---- the MTP drafter over the same head allocation (the serve stack lends `OriginalNativeOutput::mtp_head`) - let mut mtp = if std::env::var("PROBE_DRAFT").map_or(true, |v| v != "0") { - let head_weights = need!("head.retain_weights", head.retain_weights()); - synthetic_mtp( - context, - Some(head_weights), - head_kind, - vocab, - env_usize("PROBE_MTP_MAX_T", 6), - env_usize("PROBE_CAPACITY", 1024), - false, - ) - } else { - None - }; - - // ---- weights (shared across layers where the binding allows it) - macro_rules! buf { - ($name:expr, $bytes:expr) => { - need!($name, context.allocate($bytes)) - }; - } - let mats: Vec<(usize, usize)> = - vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)]; - let mut proj_bufs = Vec::new(); - for (i, (&(n_in, n_out), &k)) in mats.iter().zip(proj).enumerate() { - let bytes = need!("projection bytes", size(k, n_in, n_out)); - proj_bufs.push(buf!(format!("alloc projection[{i}] kind {k} ({} MiB)", bytes >> 20), bytes)); - } - let gdn_proj = || { - (0..36) - .map(|_| OriginalVerifyGdnProjections { - qkv: OriginalVerifyNativeMatrix { kind: proj[0], buffer: &proj_bufs[0] }, - gate: OriginalVerifyNativeMatrix { kind: proj[1], buffer: &proj_bufs[1] }, - out: OriginalVerifyNativeMatrix { kind: proj[2], buffer: &proj_bufs[2] }, - }) - .collect::>() - }; - let qsa_proj = || { - (0..12) - .map(|_| OriginalVerifyQsaProjections { - k: OriginalVerifyNativeMatrix { kind: proj[3], buffer: &proj_bufs[3] }, - v: OriginalVerifyNativeMatrix { kind: proj[4], buffer: &proj_bufs[4] }, - q: OriginalVerifyNativeMatrix { kind: proj[5], buffer: &proj_bufs[5] }, - out: OriginalVerifyNativeMatrix { kind: proj[6], buffer: &proj_bufs[6] }, - }) - .collect::>() - }; - // hyper-connection weights - let hc_norm = buf!("alloc hc_norm", 10240 * 4); - let hc_down = buf!("alloc hc_down", 320 * 10240 * 2); - let hc_up = buf!("alloc hc_up", 10240 * 320 * 2); - let hc_inject = buf!("alloc hc_inject", 4 * 10240 * 2); - let half = || HcHalfBuffers { norm: &hc_norm, down: &hc_down, up: &hc_up, inject: &hc_inject }; - let ple_key = buf!("alloc ple_key", 10240 * 2560 * 2); - let ple_value = buf!("alloc ple_value", 2560 * 2560 * 2); - let ple_norm_key = buf!("alloc ple_norm_key", 10240 * 4); - let ple_norm_query = buf!("alloc ple_norm_query", 10240 * 4); - let ple_norm_conv = buf!("alloc ple_norm_conv", 10240 * 4); - let ple_conv1d = buf!("alloc ple_conv1d", 4 * 10240 * 2); - let ple_scratch = buf!("alloc ple_scratch", PLE_SCRATCH_BYTES); - let ple_history = buf!("alloc ple_history", 9 * 10240 * 4); - // QSA norms and indexer projections: pairwise disjoint per layer - let mut qsa_bufs = Vec::new(); - for layer in 0..12 { - let mut five = Vec::new(); - for bytes in [256 * 4, 256 * 4, 128 * 4, 128 * 2560 * 2, 4 * 128 * 2560 * 2] { - five.push(buf!(format!("alloc qsa[{layer}] {bytes}"), bytes)); - } - qsa_bufs.push(five); - } - let mut gamma_bufs = Vec::new(); - for i in 0..12 { - gamma_bufs.push(buf!(format!("alloc gamma[{i}]"), 512)); - } - // MoE: router, shared experts - let router = buf!("alloc router", 512 * 2560 * 2); - let gate_inp = buf!("alloc gate_inp_shexp", 2560 * 2); - let sh_gate = buf!("alloc shared gate", need!("shared gate bytes", size(shared[0], 2560, 640))); - let sh_up = buf!("alloc shared up", need!("shared up bytes", size(shared[1], 2560, 640))); - let sh_down = buf!("alloc shared down", need!("shared down bytes", size(shared[2], 640, 2560))); - // GDN non-matrix weights - let conv = buf!("alloc gdn conv", 10240 * 4 * 4); - let alpha = buf!("alloc gdn alpha", 48 * 2560 * 2); - let beta = buf!("alloc gdn beta", 48 * 2560 * 2); - let dt = buf!("alloc gdn dt", 48 * 4); - let a = buf!("alloc gdn a", 48 * 4); - let norm = buf!("alloc gdn norm", 128 * 4); - eprintln!("PREFLIGHT synthetic verifier weights allocated={}MiB", context.allocated_bytes() >> 20); - - // The stack assembles a NEW verifier per request (bank, graphs, QSA journal) over the same MTP drafter; run PROBE_REQUESTS of them. - let requests = env_usize("PROBE_REQUESTS", 6); - let mut reset_snapshot = None; - for request in 0..requests { - eprintln!("PREFLIGHT ---- request {request}"); - if request > 0 { - // the stack resets the draft ring to the empty prompt between requests - if let Some((ring, _)) = mtp.as_mut() { - let mut ws = need!("native_batch_workspace (ring reset)", context.native_batch_workspace()); - let empty = need!("ring.empty_snapshot (reset)", ring.empty_snapshot()); - let _ = step!("ring.restore(empty)", ring.restore(&mut ws, &empty)); - reset_snapshot = Some(empty); + let sizes = Sizes { max_t, cells, vocab, head_kind, embed_kind }; + let Some(parts) = Parts::build(context, fmt, &sizes) else { return }; + let Some(mtp) = drafter(context, &parts.head, &sizes) else { return }; + let Some(w) = Weights::allocate(context, proj, shared) else { return }; + Rig { context, proj, shared, max_t, parts, w }.requests(mtp); +} +impl<'a, 'ctx> Rig<'a, 'ctx> { + /// The stack assembles a NEW verifier per request (bank, graphs, QSA journal) over the same MTP drafter; run + /// PROBE_REQUESTS of them. + fn requests(&self, mut mtp: Option>) { + let requests = env_usize("PROBE_REQUESTS", 6); + let mut reset_snapshot = None; + for request in 0..requests { + eprintln!("PREFLIGHT ---- request {request}"); + if request > 0 { + // the stack resets the draft ring to the empty prompt between requests + if let Some((ring, _)) = mtp.as_mut() { + let Some(empty) = self.reset_ring(ring) else { return }; + reset_snapshot = Some(empty); + } + } + if self.request(request, &mut mtp, &mut reset_snapshot).is_none() { + return; } } - // ---- QSA owners, canonical GDN, verifier + if let Some((ring, actor)) = mtp { + let _ = step!("mtp actor.close", actor.close()); + let _ = step!("mtp ring.close", ring.close()); + } + } + /// Restores the draft ring to the empty prompt; returns that snapshot. + fn reset_ring(&self, ring: &mut MtpOriginalInt8<'ctx>) -> Option { + let mut ws = step!("native_batch_workspace (ring reset)", self.context.native_batch_workspace())?; + let empty = step!("ring.empty_snapshot (reset)", ring.empty_snapshot())?; + let _ = step!("ring.restore(empty)", ring.restore(&mut ws, &empty)); + Some(empty) + } + /// The twelve resident QSA indices and mapped journals, prepared on `batch_ws`. + fn qsa_owners(&self, batch_ws: &mut NativeBatchWorkspace<'ctx>) -> Option> { + let context = self.context; let mut indices = Vec::new(); let mut mapped = Vec::new(); - let mut batch_ws = need!("native_batch_workspace", context.native_batch_workspace()); for _ in 0..12 { - indices.push(need!("original_qsa_resident_index", context.original_qsa_resident_index())); - let mut journal = need!( + indices.push(step!("original_qsa_resident_index", context.original_qsa_resident_index())?); + let mut journal = step!( "qsa_prompt_kv.into_original_mapped_journal", context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal()) - ); - // the prompt path initialises the streamed-KV resolver lazily (append_resident_arena); a prompt of ONE token - // never runs it, so the serve assembly calls `ensure_resolver` (epoch-preserving) before the capture. + )?; + // the prompt path initialises the streamed-KV resolver lazily (append_resident_arena); a prompt of ONE + // token never runs it, so the serve assembly calls `ensure_resolver` (epoch-preserving) before the capture. if std::env::var_os("PROBE_SKIP_RESOLVER_RESET").is_none() { - let _ = need!("mapped_journal.ensure_resolver(workspace)", journal.ensure_resolver(&mut batch_ws)); + let _ = step!("mapped_journal.ensure_resolver(workspace)", journal.ensure_resolver(batch_ws))?; } mapped.push(journal); } - let indices: [_; 12] = indices.try_into().ok().expect("12"); - let mapped: [_; 12] = mapped.try_into().ok().expect("12"); - let rope = OriginalVerifyRope { - theta_scale: 1e7f32.powf(-2.0 / 64.0), - freq_scale: 1.0, - corr_low: 0.0, - corr_high: 0.0, - ext_factor: 0.0, - magnitude: 1.0, - positions: None, - angles: None, - }; - let gamma: [&DeviceBuffer<'ctx>; 12] = std::array::from_fn(|i| &gamma_bufs[i]); - let qsa_journal = need!( + Some((indices.try_into().ok().expect("12"), mapped.try_into().ok().expect("12"))) + } + /// The twelve QSA owners as one journal over the mapped prefixes, with the workspace they were prepared on. + fn qsa_journal<'w>(&'w self) -> Option<(Rc>, NativeBatchWorkspace<'ctx>)> { + let mut batch_ws = step!("native_batch_workspace", self.context.native_batch_workspace())?; + let (indices, mapped) = self.qsa_owners(&mut batch_ws)?; + let gamma: [&DeviceBuffer<'ctx>; 12] = std::array::from_fn(|i| &self.w.gamma[i]); + let journal = step!( "OriginalVerifyQsaJournal::new", - OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope) - ); + OriginalVerifyQsaJournal::new(self.context, indices, mapped, gamma, rope()) + )?; + Some((journal, batch_ws)) + } + /// The canonical GDN states over zeros. + fn canonical(&self) -> Option> { let states = vec![0.0f32; 128 * 48 * 128]; let histories = vec![0.0f32; 10240 * 3]; - let mut canonical = need!( + step!( "original_verify_canonical_gdn", - context.original_verify_canonical_gdn( + self.context.original_verify_canonical_gdn( std::array::from_fn(|_| states.as_slice()), std::array::from_fn(|_| histories.as_slice()) ) - ); + ) + } + /// A verifier over the sealed window modules, with the device and mapped bytes of its bank. + fn new_verifier<'w>(&'w self) -> Option> { + let context = self.context; let before_verifier = context.allocated_bytes(); - let mut verifier = need!( + let verifier = step!( "OriginalVerifier::new", - OriginalVerifier::>::new(context, g) - ); + OriginalVerifier::>::new(context, self.parts.g) + )?; eprintln!( "PREFLIGHT verifier bank device={}MiB mapped_host={}MiB (context allocated {}MiB -> {}MiB)", context.allocated_bytes().saturating_sub(before_verifier) >> 20, @@ -197,77 +218,35 @@ pub(super) fn synthetic_verifier<'ctx>( before_verifier >> 20, context.allocated_bytes() >> 20 ); - - // ---- one aggregate per window width plus the commit graph - let mut windows = Vec::new(); - for t in 1..=max_t + 1 { - let window_t = if t <= max_t { t } else { max_t }; - let gdn_weights: [OriginalVerifyGdnWeights<'_, 'ctx>; 36] = std::array::from_fn(|_| { - OriginalVerifyGdnWeights { conv: &conv, alpha: &alpha, beta: &beta, dt: &dt, a: &a, norm: &norm } - }); - let bank = need!("verifier.bank()", verifier.bank()); - let journal = need!( - format!("gdn_journal(t={window_t})"), - bank.gdn_journal(&mut canonical, gdn_weights, Some(&ple_history)) - ); - let head_rows = need!(format!("head.rows({window_t})"), head.rows(window_t)); - let resources = need!( - format!("OriginalVerifyResources::new(t={window_t})"), - OriginalVerifyResources::new(context, journal, Rc::clone(&qsa_journal), head_rows) - ); - let embed_rows = need!(format!("embed.rows({window_t})"), embed.rows(window_t)); - let w = need!( - format!("OriginalVerifyWindowResources::new(t={window_t})"), - OriginalVerifyWindowResources::new(context, resources, embed_rows, layout.clone(), window_t) - ); - let w = need!( - "with_projections", - OriginalVerifyProjBinding::new(context, &g, gdn_proj(), qsa_proj()).and_then(|p| w.with_projections(p)) - ); - let layers: Vec<_> = (0..48).map(|_| HcLayerBuffers { attention: half(), ffn: half() }).collect(); - let output = HcOutputBuffers { norm: &hc_norm, down: &hc_down, up: &hc_up }; - let ple = PleBuffers { - key: PleKeyBuffer::Bf16(&ple_key), - value: &ple_value, - norm_key: &ple_norm_key, - norm_query: &ple_norm_query, - norm_conv: &ple_norm_conv, - conv1d: &ple_conv1d, - scratch: &ple_scratch, - history: &ple_history, - }; - let w = need!( - "with_gr", - OriginalVerifyGrBinding::new(context, layers, output, Some(ple)).and_then(|b| w.with_gr(b)) - ); - let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] = - std::array::from_fn(|i| OriginalVerifyQsaLayerWeights { - attn_q_norm: &qsa_bufs[i][0], - attn_k_norm: &qsa_bufs[i][1], - index_q_norm: &qsa_bufs[i][2], - index_k_proj: &qsa_bufs[i][3], - index_q_proj: &qsa_bufs[i][4], - }); - let w = - need!("with_qsa", OriginalVerifyQsaBinding::new(context, g, qsa_layers).and_then(|b| w.with_qsa(b))); - let moe_layers: Vec<_> = (0..48) - .map(|_| OriginalVerifyMoeLayerWeights { - router: &router, - gate_inp_shexp: &gate_inp, - gate_shexp: &sh_gate, - gate_shexp_type: shared[0], - up_shexp: &sh_up, - up_shexp_type: shared[1], - down_shexp: &sh_down, - down_shexp_type: shared[2], - }) - .collect(); - let w = need!( - "with_moe", - OriginalVerifyMoeBinding::new(context, &g, moe_layers, formats.clone()).and_then(|b| w.with_moe(b)) - ); - windows.push(Some(w)); - } + Some(verifier) + } + /// One request: a new verifier over the weights, its graphs recorded and replayed, then taken apart. + fn request( + &self, + request: usize, + mtp: &mut Option>, + reset_snapshot: &mut Option, + ) -> Option<()> { + // ---- QSA owners, canonical GDN, verifier + let (qsa_journal, _batch_ws) = self.qsa_journal()?; + let mut canonical = self.canonical()?; + let mut verifier = self.new_verifier()?; + let windows = self.windows(&verifier, &mut canonical, &qsa_journal)?; + let recorded = self.record(&mut verifier, windows); + let kept = if recorded && std::env::var("PROBE_REPLAY").map_or(true, |v| v != "0") { + self.replay(request, &mut verifier, mtp, reset_snapshot, &qsa_journal)? + } else { + (None, None) + }; + self.take_apart(request, verifier, mtp, qsa_journal, kept) + } + /// Records the window graphs T=1..=max_t and the commit graph; whether that worked. + fn record<'w>( + &self, + verifier: &mut Verifier<'w, 'ctx>, + mut windows: Vec>>, + ) -> bool { + let max_t = self.max_t; let commit = windows.pop().flatten().expect("commit aggregate"); let started = std::time::Instant::now(); let recorded = verifier.record_all( @@ -275,157 +254,22 @@ pub(super) fn synthetic_verifier<'ctx>( |t| windows.get_mut(t - 1).and_then(Option::take).ok_or(Error::InvalidQwenShape), commit, ); - eprintln!("PREFLIGHT after record_all: context allocated {}MiB", context.allocated_bytes() >> 20); + eprintln!("PREFLIGHT after record_all: context allocated {}MiB", self.context.allocated_bytes() >> 20); let recorded_ok = recorded.is_ok(); let _ = step!(format!("record_all (T=1..{max_t} + commit) in {:?}", started.elapsed()), recorded); - drop(windows); - let mut last_checkpoint = None; - let mut last_prefix = None; - if recorded_ok && std::env::var("PROBE_REPLAY").map_or(true, |v| v != "0") { - // Replay the recorded graphs over zero weights: the host plays the all-CPU expert pool (zeros) and the - // empty GPU plan. This runs every captured kernel with its real launch parameters (shared-memory - // attributes, grids, the doorbell/ring spin kernels). A stuck window ends after the 20 s doorbell timeout. - let mut position = 0usize; - let mut publish_ws = need!("native_batch_workspace (publish)", context.native_batch_workspace()); - // the penalty-history stage of the stack: 8 rows x 4096 ids, -1 where unavailable - let mut history = need!("alloc penalty history", context.allocate(4096 * 8 * 4)); - let _ = step!("penalty history init", history.copy_from(&vec![0xffu8; 4096 * 8 * 4])); - // windows: greedy t=1,2,max_t, then SAMPLED (penalties, every sampler path) t=3 - // Round shape of the serve loop: a T=1 window + draft, then a full T=max_t window that accepts `a+1` rows (a cycles - // through PROBE_ACCEPTED_ROWS per request) + draft with the ring still anchored at the previous speculative snapshot. - let rows_list = env_list("PROBE_ACCEPTED_ROWS", "0,1,2,3,4,5"); - let a = rows_list[request % rows_list.len().max(1)] as usize % max_t; - // (window rows, sampler, rows kept by the commit, draft after the commit) - let plan: Vec<(usize, Option, usize, bool)> = vec![ - (1, None, 1, true), - (max_t, None, a + 1, true), - (2, None, 2, false), - (3, Some(SamplerPath::Split), 3, false), - (2, Some(SamplerPath::OneBlock), 2, false), - (2, Some(SamplerPath::Old), 2, false), - ]; - let mut ring_prior: Option = None; - for (t, sampled, keep, draft_after) in plan { - let tokens: Vec = (0..t).map(|i| 100 + i as i32).collect(); - let ple = vec![0.0f32; t * 2560]; - let mut params = SamplerParams::default(); - params.greedy = sampled.is_none(); - params.temperature = if sampled.is_some() { 0.7 } else { 0.0 }; - params.seed = 1; - if sampled.is_some() { - params.top_k = 20; - params.top_p = 0.95; - params.min_keep = 1; - params.penalty_last_n = 64; - params.penalty_repeat = 1.1; - } - let sampling = NativeHeadSampling { - position: position as u64, - params, - history: sampled.map(|_| &history), - history_len: if sampled.is_some() { 64 } else { 0 }, - path: sampled.unwrap_or(SamplerPath::Split), - enabled: sampled.is_some(), - }; - let started = std::time::Instant::now(); - let mut groups_seen = 0usize; - let result = verifier.run(&tokens, position, Some(&ple), sampling, |_rows, sink, _copy| { - groups_seen += 1; - sink.with_output(|out| { - out.fill(0.0); - Ok(()) - }) - }); - let mut selection = None; - let mut completed = None; - match step!( - format!( - "verifier.run(t={t}, position={position}, sampler={sampled:?}) in {:?}, {groups_seen} pool groups", - started.elapsed() - ), - result - ) { - Some(window) => { - eprintln!("PREFLIGHT window t={t} sampled ids {:?}", window.selection.ids()); - completed = step!("verifier.completed_window", verifier.completed_window()); - selection = Some(window.selection); - } - None => break, - } - // alternate the synchronous and the asynchronous (event) commit; the next run / read joins the event - let async_commit = t == 2; - if step!( - format!("verifier.commit(keep={keep}, async={async_commit})"), - verifier.commit(keep, async_commit) - ) - .is_none() - { - break; - } - // the reads `OriginalServeHost::publish_committed` / `settle_state` make after a commit - let _ = step!("verifier.accepted_tokens", verifier.accepted_tokens().map(|a| a.len())); - last_checkpoint = step!( - "with_committed_qsa(0).checkpoint", - verifier.with_committed_qsa(0, |index| index.checkpoint(&mut publish_ws)) - ); - last_prefix = step!("qsa_journal.committed_mapped_prefix(0)", qsa_journal.committed_mapped_prefix(0)); - let _ = step!( - "with_committed_gdn(0)", - verifier.with_committed_gdn(0, |values, history| Ok((values.len(), history.len()))) - ); - if draft_after { - if let (Some((ring, actor)), Some(selection), Some(done)) = - (mtp.as_mut(), selection.take(), completed.take()) - { - // `OriginalServeHost::draft_committed`: the MTP drafter over the completed window (first call records its graphs) - actor.set_prompt_len(1); - actor.set_max_drafts(3); - let policy = OriginalMtpFullPolicy { - native_router: true, - legacy_router_mode: 0, - native_shared_scalar: true, - native_combine: true, - old_grouped_s2: false, - native_final_gr: true, - fp32_final_gr: false, - gr: OriginalMtpGrVariant::Plain, - kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)), - coupled_j: None, - }; - // the draft session restores a stored checkpoint and uses that very snapshot as `prior` - let prior = match (ring_prior.take(), reset_snapshot.take()) { - (Some(speculative), _) => Some(speculative), - (None, Some(restored)) => Some(restored), - (None, None) => step!("ring.empty_snapshot", ring.empty_snapshot()), - }; - if let Some(prior) = prior { - let started = std::time::Instant::now(); - eprintln!( - "PREFLIGHT draft: window t={t} position={position} accepted_row={} ring_prior_end={}", - keep - 1, - prior.next_position() - ); - let drafted = - actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &policy); - if let Some(d) = step!( - format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), - drafted - ) { - eprintln!( - "PREFLIGHT drafted ids {:?}, ring snapshot end {}", - d.ids(), - d.final_snapshot().next_position() - ); - ring_prior = Some(d.final_snapshot().clone()); - } - let _ = step!("actor.idle", actor.idle()); - } - } - } - position += keep; - } - } - // `disassemble`: closing the verifier must succeed after a request that drafted, or the stack is marked broken + recorded_ok + } + /// `disassemble`: closing the verifier must succeed after a request that drafted, or the stack is marked + /// broken; then `recover` + `adopt_qsa_owners`: the journal gives the twelve owners back and each is rolled + /// back to the session's witness. + fn take_apart<'w>( + &self, + request: usize, + verifier: Verifier<'w, 'ctx>, + mtp: &mut Option>, + qsa_journal: Rc>, + (last_checkpoint, last_prefix): Kept<'ctx>, + ) -> Option<()> { if std::env::var_os("PROBE_NO_RELEASE").is_none() { if let Some((_, actor)) = mtp.as_mut() { let _ = step!( @@ -435,21 +279,28 @@ pub(super) fn synthetic_verifier<'ctx>( } } let _ = step!(format!("verifier.close (request {request})"), verifier.close()); - // `recover` + `adopt_qsa_owners`: the journal gives the twelve owners back and each is rolled back to the session's witness - if let Some((mut indices, mut mapped)) = step!( + let owners = step!( format!("OriginalVerifyQsaJournal::into_owners (request {request})"), OriginalVerifyQsaJournal::into_owners(qsa_journal) - ) { - if let (Some(cp), Some(prefix)) = (last_checkpoint.take(), last_prefix.take()) { - let mut ws = need!("native_batch_workspace (adopt)", context.native_batch_workspace()); - let _ = step!("owner index.restore(checkpoint)", indices[0].restore(&mut ws, &cp)); - let _ = step!("owner kv.rollback(prefix)", mapped[0].rollback(&mut ws, &prefix)); - } - drop((indices, mapped)); + ); + match owners { + Some(owners) => self.adopt(owners, last_checkpoint, last_prefix), + None => Some(()), } } - if let Some((ring, actor)) = mtp { - let _ = step!("mtp actor.close", actor.close()); - let _ = step!("mtp ring.close", ring.close()); + /// `adopt_qsa_owners`: each owner is rolled back to the session's witness. + fn adopt( + &self, + (mut indices, mut mapped): Owners<'ctx>, + last_checkpoint: Option>, + last_prefix: Option, + ) -> Option<()> { + if let (Some(cp), Some(prefix)) = (last_checkpoint, last_prefix) { + let mut ws = step!("native_batch_workspace (adopt)", self.context.native_batch_workspace())?; + let _ = step!("owner index.restore(checkpoint)", indices[0].restore(&mut ws, &cp)); + let _ = step!("owner kv.rollback(prefix)", mapped[0].rollback(&mut ws, &prefix)); + } + drop((indices, mapped)); + Some(()) } } diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs index ae51b9cc..fd7a6946 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs @@ -29,441 +29,24 @@ use super::super::qwen_forward::original_serve_stack::dbg_el; use super::*; use crate::qwen_forward::{ - original_serve_request::ServeRequest, + original_serve_request::{ServeError, ServeRequest}, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, }; use std::env; +#[path = "backend_original_serve_replay/arm_flags.rs"] +mod arm_flags; +#[path = "backend_original_serve_replay/load.rs"] +mod load; +#[path = "backend_original_serve_replay/pass.rs"] +mod pass; +#[path = "backend_original_serve_replay/run.rs"] +mod run; + #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; replay of captured agent traffic"] fn original_serve_replay_smoke() { - let _ = dbg_el(); - assert!(env::var("LELEKA_ORIGINAL_SERVE_REPLAY").is_ok_and(|v| v == "yes"), "explicit replay opt-in required"); - let number = |name: &str, default: usize| -> usize { - env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) - }; - let dir = required_path("LELEKA_REPLAY_DIR"); - let mut files: Vec = std::fs::read_dir(&dir) - .expect("capture directory unreadable") - .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| { - p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json")) - }) - .collect(); - files.sort(); - let files: Vec = files - .into_iter() - .skip(number("LELEKA_REPLAY_FIRST", 0)) - .take(number("LELEKA_REPLAY_COUNT", usize::MAX)) - .collect(); - assert!(!files.is_empty(), "no captured requests selected"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - // LELEKA_REPLAY_GGUF_PLE=1 (quality / speed study of `kar_source: none`, docs/experiments/kar-off-ab-5090.md): no KAR archive at all, the per-layer - // n-gram (PLE) rows are read from the GGUF shard by the native reader (the binding of the `qwen4exp-native-mtp-v1` load). Unset: the inherited KAR descriptor, as always. - let gguf_ple = env::var("LELEKA_REPLAY_GGUF_PLE").is_ok_and(|v| v == "1"); - let mut binding = if gguf_ple { - ModelBinding::from_artifact_with_pinned_mtp( - artifact, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("pinned GGUF-PLE+MTP binding failed") - } else { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - // LELEKA_KAR_SPARSE_EXTENTS_SHA256=<64 hex>: the descriptor is a sparse memfd (`leleka seal-exec --sparse-ple`, docs/kar-sparse-memfd.md); it is verified against the - // pinned digest of its extents instead of the archive's SHA-256. Unset: the full archive, as always. - let inherited = match env::var("LELEKA_KAR_SPARSE_EXTENTS_SHA256") { - Ok(text) => { - assert_eq!(text.len(), 64, "LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be 64 hex digits"); - let digest: [u8; 32] = std::array::from_fn(|i| { - u8::from_str_radix(&text[2 * i..2 * i + 2], 16) - .expect("LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be hex") - }); - InheritedKarArchive::open_sparse(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"), digest) - .expect("sparse inherited KAR admission failed") - } - Err(_) => InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited KAR admission failed"), - }; - ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed") - }; - binding.load_resident_expert_source().expect("resident expert source load failed"); - if let Some(report) = leleka_model_format::huge_pages::settle() { - eprintln!("{report}"); - } - let driver = Driver::load().expect("CUDA driver load failed"); - let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new( - device - .create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30) - .expect("bounded Context unavailable"), - ); - // arms: `label=mode,...` with mode conv (the conversation cache) | off | prompt | reply (the prefix cache with that tail mode); each arm is a - // fresh stack over the same loaded model. Default: one arm, the tail mode of `LELEKA_REPLAY_PREFIX_TAIL`. - let arms: Vec<(String, String)> = match env::var("LELEKA_REPLAY_ARMS") { - Ok(spec) => spec - .split(',') - .map(|a| { - let (label, mode) = a.split_once('=').expect("LELEKA_REPLAY_ARMS: label=mode,..."); - (label.to_owned(), mode.to_owned()) - }) - .collect(), - Err(_) => { - vec![("replay".to_owned(), env::var("LELEKA_REPLAY_PREFIX_TAIL").unwrap_or_else(|_| "off".to_owned()))] - } - }; - // LELEKA_REPLAY_FORCE=1: every request decodes along its RECORDED tokens (teacher forcing, `quality_force`), so all arms - // read the same path and, with LELEKA_TRACE_LOGPROBS=16 and LELEKA_BRINGUP_TRACE, print the top-16 rows that - // `scripts/quality/q_tail_gate.py` compares (the arm index plays the corpus pass). - let force = env::var_os("LELEKA_REPLAY_FORCE").is_some(); - for (arm_index, (label, arm)) in arms.iter().enumerate() { - // the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, grid = chunk) or `reply@8192/2048` - let mut down_override: i8 = -1; - let (mut sm120_attn, mut sm120_gu, mut sm120_side): (i8, i8, i8) = (-1, -1, -1); - let mut tail_flag: Option = None; - let ( - mut gdn_flag, - mut topk_flag, - mut cluster_flag, - mut nostore_flag, - mut sized_flag, - mut qpf_flag, - mut gpool_flag, - mut mspan_flag, - ): (i8, i8, i8, i8, i8, i8, i8, i8) = (-1, -1, -1, -1, -1, -1, -1, -1); - let (arm_mode, arm_capacity, arm_block, arm_tiers): (String, usize, usize, Option) = - match arm.split_once('@') { - Some((mode, shape)) => { - // flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: the stack's), `w8` (the previous - // 8-row x all-tokens hyper-connection down projection of the chain kernels instead of the tiled one) - let (shape, flags) = shape.split_once('!').map_or((shape, ""), |(s, f)| (s, f)); - let tiers = if flags.split('!').any(|f| f == "notiers") { - Some(false) - } else if flags.split('!').any(|f| f == "tiers") { - Some(true) - } else { - None - }; - down_override = if flags.split('!').any(|f| f == "w8") { 0 } else { -1 }; - // `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = off); without it the environment decides - tail_flag = flags - .split('!') - .find_map(|f| f.strip_prefix("tail")) - .map(|n| n.parse::().expect("arm flag !tailN")); - // docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the three-value-heads kernel, the two-barrier kernel, - // the sealed Original one), `wide` / `fast` (the prompt top-k), `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster) - let has = |name: &str| flags.split('!').any(|f| f == name); - gdn_flag = if has("kh") { - 1 - } else if has("rec") { - 2 - } else if has("orig") { - 0 - } else { - -1 - }; - topk_flag = if has("wide") { - 1 - } else if has("fast") { - 0 - } else { - -1 - }; - cluster_flag = if has("cluster") { - 1 - } else if has("nocluster") { - 0 - } else { - -1 - }; - nostore_flag = if has("nostore") { - 1 - } else if has("store") { - 0 - } else { - -1 - }; - sized_flag = if has("sized") { - 1 - } else if has("uniform") { - 0 - } else { - -1 - }; - qpf_flag = if has("qpf") { - 1 - } else if has("noqpf") { - 0 - } else { - -1 - }; - gpool_flag = if has("gpool") { - 1 - } else if has("nogpool") { - 0 - } else { - -1 - }; - mspan_flag = if has("mspan") { - 1 - } else if has("nomspan") { - 0 - } else { - -1 - }; - // claude/decode-sm120-switches: `attn` / `noattn` (ATTN_DAILY decode attention), `gus` / `nogus` (GU_SWIGLU fused expert gate/up); without a flag the environment and the card decide - sm120_attn = if has("attn") { - 1 - } else if has("noattn") { - 0 - } else { - -1 - }; - sm120_gu = if has("gus") { - 1 - } else if has("nogus") { - 0 - } else { - -1 - }; - sm120_side = if has("side") { - 1 - } else if has("noside") { - 0 - } else { - -1 - }; - let (cap, block) = shape.split_once('/').unwrap_or((shape, "0")); - ( - mode.to_owned(), - cap.parse::().expect("arm chunk: mode@CAP[/BLOCK]"), - block.parse::().expect("arm grid: mode@CAP[/BLOCK]"), - tiers, - ) - } - None => (arm.clone(), number("LELEKA_REPLAY_CAPACITY", 2048), 0, None), - }; - let arm = &arm_mode; - leleka_cuda_driver::set_chain_down_override(down_override); - leleka_cuda_driver::set_sm120_overrides(sm120_attn, sm120_gu, sm120_side); - leleka_cuda_driver::set_prefill_gdn_override(gdn_flag); - leleka_cuda_driver::set_qsa_topk_override(topk_flag); - leleka_cuda_driver::set_qsa_cluster_override(cluster_flag); - leleka_cuda_driver::set_prefill_gdn_nostore_override(nostore_flag); - crate::qwen_forward::original_cache_startup::set_sized_override(sized_flag); - leleka_cuda_driver::set_qsa_prefetch_override(qpf_flag); - crate::qwen_forward::gdn::set_pool_override(gpool_flag); - crate::qwen_forward::moe_weight_cache::set_span_cache_override(mspan_flag); - crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail_flag); - eprintln!( - "REPLAY-ARM start label={label} mode={arm} capacity={arm_capacity} block={arm_block} tiers={}", - arm_tiers.map_or("default", |on| if on { "on" } else { "off" }) - ); - let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); - config.capacity = arm_capacity; - if let Some(on) = arm_tiers { - config.loan_tiers = on; - } - // the Original's draft vocabulary (the MTP pack directory); unset = the full head, as the daemon did without --mtp-rt-dir - 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() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - if let (Ok(mib), true) = (env::var("LELEKA_REPLAY_PREFIX_MIB"), arm != "conv") { - config.prefix = Some(PrefixConfig { - tail: match Ok::<&str, ()>(arm.as_str()) { - Ok("prompt") => crate::qwen_forward::original_serve_stack::TailMode::Prompt, - Ok("reply") => crate::qwen_forward::original_serve_stack::TailMode::Reply, - Ok("off") | Err(_) => crate::qwen_forward::original_serve_stack::TailMode::Off, - Ok(other) => panic!("replay arm mode: conv | off | prompt | reply, not {other}"), - }, - budget: if mib == "auto" { - PrefixBudget::Auto - } else { - PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) - }, - block_tokens: arm_block, - ..PrefixConfig::auto() - }); - } - let min_p: f32 = env::var("LELEKA_REPLAY_SPEC_MIN_P") - .ok() - .map(|v| v.parse().expect("LELEKA_REPLAY_SPEC_MIN_P")) - .unwrap_or(0.0); - eprintln!( - "REPLAY config: {} requests from {:?}, capacity {}, spec_min_p {min_p}, prefix cache {}, tier {:?}", - files.len(), - dir, - config.capacity, - config.prefix.is_some(), - config.expert_tier - ); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - let spec_arms = stack.spec_arms(); - let reps = number("LELEKA_REPLAY_REPS", 1).max(1); - let force = env::var("LELEKA_REPLAY_FORCE").is_ok_and(|v| v == "1"); - // (label, arm) of every pass: a warm-up with arm 0, then reps x arms rotated per repetition - let mut passes: Vec<(String, Option)> = Vec::new(); - if spec_arms.is_empty() { - passes.extend((0..reps).map(|r| (format!("p{r}"), None))); - } else { - passes.push(("warm".to_owned(), Some(spec_arms[0].clone()))); - for r in 0..reps { - for q in 0..spec_arms.len() { - passes.push((format!("r{r}"), Some(spec_arms[(q + r) % spec_arms.len()].clone()))); - } - } - } - for (pass_no, (pass_label, arm)) in passes.iter().enumerate() { - if let Some(arm) = arm { - assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}"); - // `+tailN` in an arm label (`adaptive@0+tail7`): the experimental route tail skip of this pass (docs/upstream-port-plan.md 3.1); without it the environment decides - if spec_arms.iter().any(|a| a.contains("+tail")) { - let tail = arm - .split('+') - .skip(1) - .find_map(|f| f.strip_prefix("tail")) - .map(|n| n.parse::().expect("arm flag +tailN")); - crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail); - } - } - let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = - (0usize, 0f64, 0usize, 0usize, 0f64); - for (n, file) in files.iter().enumerate() { - let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")) - .expect("capture is not JSON"); - let ids = |key: &str| -> Vec { - doc[key].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect() - }; - let (prompt, recorded) = (ids("prompt_ids"), ids("generated_ids")); - let max_new = recorded - .len() - .clamp(1, doc["max_new"].as_u64().unwrap_or(4096) as usize) - .min(number("LELEKA_REPLAY_MAX_NEW", usize::MAX)); - let greedy = doc["temperature_milli"].as_u64() == Some(0) - && doc["repetition_penalty_micro"].as_u64().is_none_or(|v| v == 1_000_000 || v == 0); - if !greedy { - eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily"); - } - crate::qwen_forward::quality_force::set( - force.then(|| prompt.iter().copied().chain(recorded.iter().copied()).collect()), - ); - if force { - eprintln!("DBG corpus {n} pass={arm_index} begin forced=true"); - } - let started = std::time::Instant::now(); - let mut first: Option = None; - let mut out: Vec = Vec::new(); - let served = stack.serve( - &ServeRequest::new( - prompt.clone(), - max_new, - None, - 7, - stack.spec_arm_min_p().unwrap_or(min_p), - vec![eos as i32], - ), - &mut |round| { - if first.is_none() { - first = Some(started.elapsed()); - } - out.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ); - let total = started.elapsed(); - if force { - crate::qwen_forward::quality_force::set(None); - } - match served { - Ok(outcome) => { - let ttft = first.unwrap_or(total); - let decode = (total - ttft).as_secs_f64() * 1e3; - let agree = out.iter().zip(&recorded).take_while(|(a, b)| a == b).count(); - if let Some(path) = env::var_os("LELEKA_REPLAY_OUT") { - use std::io::Write; - let line = format!( - "REPLAY-OUT arm={label} #{n} {}\n", - out.iter().map(|t| t.to_string()).collect::>().join(",") - ); - let _ = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - .and_then(|mut f| f.write_all(line.as_bytes())); - } - let reused = stack.reused_tokens(); - let (p_ms, d_ms) = stack.last_timing(); - let m = stack.ttft_marks(); - eprintln!( - "REPLAY-MARKS #{n} prompt={} reprefill={} ttft_ms={:.1} resumed={:.1} prefilled={:.1} assembled={:.1} first_round={:.1} (stages: resume {:.1}, prefill {:.1}, assemble {:.1}, first round {:.1})", - prompt.len(), - prompt.len().saturating_sub(reused), - ttft.as_secs_f64() * 1e3, - m[0], - m[1], - m[2], - m[3], - m[0], - m[1] - m[0], - m[2] - m[1], - m[3] - m[2] - ); - eprintln!( - "REPLAY #{n} pass={pass_no} {pass_label} arm={} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}", - stack.spec_arm(), - file.file_name().and_then(|f| f.to_str()).unwrap_or("?"), - prompt.len(), - prompt.len().saturating_sub(reused), - ttft.as_secs_f64() * 1e3, - out.len(), - outcome.rounds, - out.len() as f64 / outcome.rounds.max(1) as f64, - if decode > 0.0 { out.len().saturating_sub(1) as f64 * 1e3 / decode } else { 0.0 }, - recorded.len() - ); - tokens += out.len().saturating_sub(1); - decode_ms += decode; - rounds_total += outcome.rounds; - prefill_tokens += prompt.len().saturating_sub(reused); - prefill_ms += ttft.as_secs_f64() * 1e3; - if let Some(stats) = stack.expert_tier_stats() { - eprintln!("REPLAY #{n} {}", stats.describe()); - } - } - Err(e) => eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()), - } - } - crate::qwen_forward::quality_force::set(None); - eprintln!( - "REPLAY PASS {pass_no} {pass_label} arm={} requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}", - stack.spec_arm(), - files.len(), - if decode_ms > 0.0 { tokens as f64 * 1e3 / decode_ms } else { 0.0 }, - decode_ms / 1e3, - prefill_ms / 1e3 - ); - } - stack.close().expect("stack cleanup failed"); - } - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + run::run(); } #[path = "backend_original_serve_replay/required_path_fn.rs"] diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay/arm_flags.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/arm_flags.rs new file mode 100644 index 00000000..c5602109 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/arm_flags.rs @@ -0,0 +1,141 @@ +//! The shape and the route flags of one replay arm: `mode@CAP[/BLOCK][!flag...]` (see `parse`). +use leleka_cuda_driver as driver; + +/// The route flags of one arm; -1 leaves the environment and the card to decide. +pub(super) struct ArmFlags { + down_override: i8, + attn: i8, + gus: i8, + side: i8, + tail: Option, + gdn: i8, + topk: i8, + cluster: i8, + nostore: i8, + sized: i8, + qpf: i8, + gpool: i8, + mspan: i8, +} +/// The mode, the prefill chunk and grid, the loan ladder and the route flags of one arm. +pub(super) struct ArmShape { + pub(super) mode: String, + pub(super) capacity: usize, + pub(super) block: usize, + pub(super) tiers: Option, + pub(super) flags: ArmFlags, +} +/// 1 when `on` is set, 0 when `off` is, else -1. +fn tri(has: &dyn Fn(&str) -> bool, on: &str, off: &str) -> i8 { + if has(on) { + 1 + } else if has(off) { + 0 + } else { + -1 + } +} +/// `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = +/// off); without it the environment decides. +fn tail_flag(flags: &str) -> Option { + flags.split('!').find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::().expect("arm flag !tailN")) +} +/// docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the +/// three-value-heads kernel, the two-barrier kernel, the sealed Original one); `wide` / `fast` (the prompt top-k) and +/// `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster) are plain on/off flags. +fn gdn_flag(has: &dyn Fn(&str) -> bool) -> i8 { + if has("kh") { + 1 + } else if has("rec") { + 2 + } else if has("orig") { + 0 + } else { + -1 + } +} +impl ArmFlags { + /// Every flag left to the environment. + fn environment() -> ArmFlags { + ArmFlags { + down_override: -1, + attn: -1, + gus: -1, + side: -1, + tail: None, + gdn: -1, + topk: -1, + cluster: -1, + nostore: -1, + sized: -1, + qpf: -1, + gpool: -1, + mspan: -1, + } + } + /// The flags after the shape, each introduced by `!`. + fn parse(flags: &str) -> ArmFlags { + let has = |name: &str| flags.split('!').any(|f| f == name); + // claude/decode-sm120-switches: `attn` / `noattn` (ATTN_DAILY decode attention), `gus` / `nogus` (GU_SWIGLU + // fused expert gate/up); without a flag the environment and the card decide + ArmFlags { + // `w8` (the previous 8-row x all-tokens hyper-connection down projection of the chain kernels instead + // of the tiled one) + down_override: if has("w8") { 0 } else { -1 }, + attn: tri(&has, "attn", "noattn"), + gus: tri(&has, "gus", "nogus"), + side: tri(&has, "side", "noside"), + tail: tail_flag(flags), + gdn: gdn_flag(&has), + topk: tri(&has, "wide", "fast"), + cluster: tri(&has, "cluster", "nocluster"), + nostore: tri(&has, "nostore", "store"), + sized: tri(&has, "sized", "uniform"), + qpf: tri(&has, "qpf", "noqpf"), + gpool: tri(&has, "gpool", "nogpool"), + mspan: tri(&has, "mspan", "nomspan"), + } + } + /// Sets the process-wide overrides of this arm. + pub(super) fn apply(&self) { + driver::set_chain_down_override(self.down_override); + driver::set_sm120_overrides(self.attn, self.gus, self.side); + driver::set_prefill_gdn_override(self.gdn); + driver::set_qsa_topk_override(self.topk); + driver::set_qsa_cluster_override(self.cluster); + driver::set_prefill_gdn_nostore_override(self.nostore); + crate::qwen_forward::original_cache_startup::set_sized_override(self.sized); + driver::set_qsa_prefetch_override(self.qpf); + crate::qwen_forward::gdn::set_pool_override(self.gpool); + crate::qwen_forward::moe_weight_cache::set_span_cache_override(self.mspan); + crate::qwen_forward::original_serve_residency::set_tail_skip_arm(self.tail); + } +} +/// `mode@CAP[/BLOCK][!flag...]`: the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, +/// grid = chunk) or `reply@8192/2048`. A bare mode takes `default_capacity()`. +pub(super) fn parse(arm: &str, default_capacity: &dyn Fn() -> usize) -> ArmShape { + let Some((mode, shape)) = arm.split_once('@') else { + let flags = ArmFlags::environment(); + return ArmShape { mode: arm.to_owned(), capacity: default_capacity(), block: 0, tiers: None, flags }; + }; + // flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: + // the stack's) + let (shape, flags) = shape.split_once('!').map_or((shape, ""), |(s, f)| (s, f)); + let has = |name: &str| flags.split('!').any(|f| f == name); + let tiers = if has("notiers") { + Some(false) + } else if has("tiers") { + Some(true) + } else { + None + }; + let flags = ArmFlags::parse(flags); + let (cap, block) = shape.split_once('/').unwrap_or((shape, "0")); + ArmShape { + mode: mode.to_owned(), + capacity: cap.parse::().expect("arm chunk: mode@CAP[/BLOCK]"), + block: block.parse::().expect("arm grid: mode@CAP[/BLOCK]"), + tiers, + flags, + } +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay/load.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/load.rs new file mode 100644 index 00000000..ffd13ff9 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/load.rs @@ -0,0 +1,101 @@ +//! The captured requests and the pinned model of the replay. +use super::*; + +pub(super) fn number(name: &str, default: usize) -> usize { + env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) +} +/// The capture directory and the selected requests, in file-name order. +pub(super) fn captures() -> (PathBuf, Vec) { + let dir = required_path("LELEKA_REPLAY_DIR"); + let mut files: Vec = std::fs::read_dir(&dir) + .expect("capture directory unreadable") + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json")) + }) + .collect(); + files.sort(); + let files: Vec = files + .into_iter() + .skip(number("LELEKA_REPLAY_FIRST", 0)) + .take(number("LELEKA_REPLAY_COUNT", usize::MAX)) + .collect(); + assert!(!files.is_empty(), "no captured requests selected"); + (dir, files) +} +/// LELEKA_KAR_SPARSE_EXTENTS_SHA256=<64 hex>: the descriptor is a sparse memfd (`leleka seal-exec --sparse-ple`, +/// docs/kar-sparse-memfd.md); it is verified against the pinned digest of its extents instead of the archive's +/// SHA-256. Unset: the full archive, as always. +fn open_inherited(fd: u32) -> InheritedKarArchive { + match env::var("LELEKA_KAR_SPARSE_EXTENTS_SHA256") { + Ok(text) => { + assert_eq!(text.len(), 64, "LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be 64 hex digits"); + let digest: [u8; 32] = std::array::from_fn(|i| { + u8::from_str_radix(&text[2 * i..2 * i + 2], 16).expect("LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be hex") + }); + InheritedKarArchive::open_sparse(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"), digest) + .expect("sparse inherited KAR admission failed") + } + Err(_) => InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"), + } +} +fn bind_inherited(artifact: Qwen4ExpArtifact) -> ModelBinding { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let inherited = open_inherited(fd); + ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed") +} +/// The pinned binding with its resident expert source, and the EOS of the pinned tokenizer. +pub(super) fn pinned() -> (ModelBinding, u32) { + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); + let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + // LELEKA_REPLAY_GGUF_PLE=1 (quality / speed study of `kar_source: none`, docs/experiments/kar-off-ab-5090.md): + // no KAR archive at all, the per-layer n-gram (PLE) rows are read from the GGUF shard by the native reader (the + // binding of the `qwen4exp-native-mtp-v1` load). Unset: the inherited KAR descriptor, as always. + let gguf_ple = env::var("LELEKA_REPLAY_GGUF_PLE").is_ok_and(|v| v == "1"); + let mut binding = if gguf_ple { + ModelBinding::from_artifact_with_pinned_mtp( + artifact, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("pinned GGUF-PLE+MTP binding failed") + } else { + bind_inherited(artifact) + }; + binding.load_resident_expert_source().expect("resident expert source load failed"); + if let Some(report) = leleka_model_format::huge_pages::settle() { + eprintln!("{report}"); + } + (binding, eos) +} +/// arms: `label=mode,...` with mode conv (the conversation cache) | off | prompt | reply (the prefix cache with that +/// tail mode); each arm is a fresh stack over the same loaded model. Default: one arm, the tail mode of +/// `LELEKA_REPLAY_PREFIX_TAIL`. +pub(super) fn arms() -> Vec<(String, String)> { + match env::var("LELEKA_REPLAY_ARMS") { + Ok(spec) => spec + .split(',') + .map(|a| { + let (label, mode) = a.split_once('=').expect("LELEKA_REPLAY_ARMS: label=mode,..."); + (label.to_owned(), mode.to_owned()) + }) + .collect(), + Err(_) => { + vec![("replay".to_owned(), env::var("LELEKA_REPLAY_PREFIX_TAIL").unwrap_or_else(|_| "off".to_owned()))] + } + } +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay/pass.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/pass.rs new file mode 100644 index 00000000..ddb3b59f --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/pass.rs @@ -0,0 +1,240 @@ +//! One pass of an arm over the captured requests: every recorded prompt served greedily with the recorded output +//! length as the budget, and what it printed. +use super::load::number; +use super::*; +use crate::qwen_forward::original_serve_engine::ServeOutcome; +use std::time::Duration; + +/// What the requests of a pass added up to. +#[derive(Default)] +struct Sums { + tokens: usize, + decode_ms: f64, + rounds_total: usize, + prefill_tokens: usize, + prefill_ms: f64, +} +/// A captured request: the prompt, the recorded reply and the decode budget. +struct Capture { + prompt: Vec, + recorded: Vec, + max_new: usize, + greedy: bool, +} +fn read_capture(file: &std::path::Path) -> Capture { + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON"); + let ids = |key: &str| -> Vec { + doc[key].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect() + }; + let (prompt, recorded) = (ids("prompt_ids"), ids("generated_ids")); + let max_new = recorded + .len() + .clamp(1, doc["max_new"].as_u64().unwrap_or(4096) as usize) + .min(number("LELEKA_REPLAY_MAX_NEW", usize::MAX)); + let greedy = doc["temperature_milli"].as_u64() == Some(0) + && doc["repetition_penalty_micro"].as_u64().is_none_or(|v| v == 1_000_000 || v == 0); + Capture { prompt, recorded, max_new, greedy } +} +/// The decoded tokens, the time to the first round and the total time of one request. +struct Timed { + out: Vec, + first: Option, + total: Duration, + served: Result, +} +fn serve_timed(stack: &mut OriginalServeStack<'_, '_>, capture: &Capture, min_p: f32, eos: u32) -> Timed { + let started = std::time::Instant::now(); + let mut first: Option = None; + let mut out: Vec = Vec::new(); + let request = ServeRequest::new( + capture.prompt.clone(), + capture.max_new, + None, + 7, + stack.spec_arm_min_p().unwrap_or(min_p), + vec![eos as i32], + ); + let served = stack.serve( + &request, + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); + Timed { out, first, total: started.elapsed(), served } +} +/// One `REPLAY-OUT` line per request, to compare arms token for token. +fn write_out(label: &str, n: usize, out: &[i32]) { + if let Some(path) = env::var_os("LELEKA_REPLAY_OUT") { + use std::io::Write; + let line = format!( + "REPLAY-OUT arm={label} #{n} {}\n", + out.iter().map(|t| t.to_string()).collect::>().join(",") + ); + let _ = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .and_then(|mut f| f.write_all(line.as_bytes())); + } +} +/// The identity of one request of a pass. +struct Which<'a> { + n: usize, + pass_no: usize, + pass_label: &'a str, + file: &'a std::path::Path, +} +fn print_marks(stack: &OriginalServeStack<'_, '_>, n: usize, prompt_len: usize, reused: usize, ttft: Duration) { + let m = stack.ttft_marks(); + eprintln!( + "REPLAY-MARKS #{n} prompt={prompt_len} reprefill={} ttft_ms={:.1} resumed={:.1} prefilled={:.1} \ + assembled={:.1} first_round={:.1} (stages: resume {:.1}, prefill {:.1}, assemble {:.1}, first round {:.1})", + prompt_len.saturating_sub(reused), + ttft.as_secs_f64() * 1e3, + m[0], + m[1], + m[2], + m[3], + m[0], + m[1] - m[0], + m[2] - m[1], + m[3] - m[2] + ); +} +/// The pass line of a request that was served. +fn print_request( + stack: &OriginalServeStack<'_, '_>, + which: &Which<'_>, + capture: &Capture, + timed: &Timed, + rounds: usize, +) { + let (reused, ttft) = (stack.reused_tokens(), timed.first.unwrap_or(timed.total)); + let decode = (timed.total - ttft).as_secs_f64() * 1e3; + let out = &timed.out; + let agree = out.iter().zip(&capture.recorded).take_while(|(a, b)| a == b).count(); + let (p_ms, d_ms) = stack.last_timing(); + let prompt_len = capture.prompt.len(); + eprintln!( + "REPLAY #{} pass={} {} arm={} file={} prompt={prompt_len} reused={reused} reprefill={} ttft_ms={:.1} \ + produced={} rounds={rounds} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} \ + engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}", + which.n, + which.pass_no, + which.pass_label, + stack.spec_arm(), + which.file.file_name().and_then(|f| f.to_str()).unwrap_or("?"), + prompt_len.saturating_sub(reused), + ttft.as_secs_f64() * 1e3, + out.len(), + out.len() as f64 / rounds.max(1) as f64, + if decode > 0.0 { out.len().saturating_sub(1) as f64 * 1e3 / decode } else { 0.0 }, + capture.recorded.len() + ); +} +/// The arm of this pass, and its own `+tailN` route tail skip. +fn select_arm(stack: &mut OriginalServeStack<'_, '_>, arm: &str, spec_arms: &[String]) { + assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}"); + // `+tailN` in an arm label (`adaptive@0+tail7`): the experimental route tail skip of this pass + // (docs/upstream-port-plan.md 3.1); without it the environment decides + if spec_arms.iter().any(|a| a.contains("+tail")) { + let tail = arm + .split('+') + .skip(1) + .find_map(|f| f.strip_prefix("tail")) + .map(|n| n.parse::().expect("arm flag +tailN")); + crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail); + } +} +/// What every pass of one arm shares. +pub(super) struct Replay<'a> { + pub(super) files: &'a [PathBuf], + pub(super) eos: u32, + /// LELEKA_REPLAY_FORCE=1: every request decodes along its RECORDED tokens (teacher forcing, `quality_force`). + pub(super) force: bool, + pub(super) min_p: f32, + pub(super) arm_index: usize, + pub(super) label: &'a str, +} +impl Replay<'_> { + /// With teacher forcing the request decodes along its recorded tokens. + fn begin_forced(&self, n: usize, capture: &Capture) { + crate::qwen_forward::quality_force::set( + self.force.then(|| capture.prompt.iter().copied().chain(capture.recorded.iter().copied()).collect()), + ); + if self.force { + eprintln!("DBG corpus {n} pass={} begin forced=true", self.arm_index); + } + } + /// Serves request `which.n`, prints it and adds it to `sums`. + fn request(&self, stack: &mut OriginalServeStack<'_, '_>, which: &Which<'_>, sums: &mut Sums) { + let n = which.n; + let capture = read_capture(which.file); + if !capture.greedy { + eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily"); + } + self.begin_forced(n, &capture); + let timed = serve_timed(stack, &capture, self.min_p, self.eos); + if self.force { + crate::qwen_forward::quality_force::set(None); + } + let outcome = match &timed.served { + Ok(outcome) => *outcome, + Err(e) => { + eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()); + return; + } + }; + write_out(self.label, n, &timed.out); + let reused = stack.reused_tokens(); + print_marks(stack, n, capture.prompt.len(), reused, timed.first.unwrap_or(timed.total)); + print_request(stack, which, &capture, &timed, outcome.rounds); + add(sums, &capture, &timed, outcome.rounds, reused); + if let Some(stats) = stack.expert_tier_stats() { + eprintln!("REPLAY #{n} {}", stats.describe()); + } + } + pub(super) fn pass( + &self, + stack: &mut OriginalServeStack<'_, '_>, + (pass_no, pass_label): (usize, &str), + arm: Option<&str>, + spec_arms: &[String], + ) { + if let Some(arm) = arm { + select_arm(stack, arm, spec_arms); + } + let mut sums = Sums::default(); + for (n, file) in self.files.iter().enumerate() { + self.request(stack, &Which { n, pass_no, pass_label, file }, &mut sums); + } + crate::qwen_forward::quality_force::set(None); + eprintln!( + "REPLAY PASS {pass_no} {pass_label} arm={} requests={} weighted_decode_tok_s={:.2} \ + (tokens {} / decode {:.1} s) rounds={} reprefilled_tokens={} sum_ttft_s={:.1}", + stack.spec_arm(), + self.files.len(), + if sums.decode_ms > 0.0 { sums.tokens as f64 * 1e3 / sums.decode_ms } else { 0.0 }, + sums.tokens, + sums.decode_ms / 1e3, + sums.rounds_total, + sums.prefill_tokens, + sums.prefill_ms / 1e3 + ); + } +} +/// Adds a served request to the sums of its pass. +fn add(sums: &mut Sums, capture: &Capture, timed: &Timed, rounds: usize, reused: usize) { + let ttft = timed.first.unwrap_or(timed.total); + sums.tokens += timed.out.len().saturating_sub(1); + sums.decode_ms += (timed.total - ttft).as_secs_f64() * 1e3; + sums.rounds_total += rounds; + sums.prefill_tokens += capture.prompt.len().saturating_sub(reused); + sums.prefill_ms += ttft.as_secs_f64() * 1e3; +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay/run.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/run.rs new file mode 100644 index 00000000..122e146a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/run.rs @@ -0,0 +1,126 @@ +//! The replay: the pinned model loaded once, then one fresh stack per arm over it. +use super::arm_flags::{self, ArmShape}; +use super::load::{self, number}; +use super::pass::Replay; +use super::*; +use crate::qwen_forward::original_serve_stack::TailMode; + +fn tail_mode(arm: &str) -> TailMode { + match arm { + "prompt" => TailMode::Prompt, + "reply" => TailMode::Reply, + "off" => TailMode::Off, + other => panic!("replay arm mode: conv | off | prompt | reply, not {other}"), + } +} +fn arm_config(shape: &ArmShape) -> StackConfig { + let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); + config.capacity = shape.capacity; + if let Some(on) = shape.tiers { + config.loan_tiers = on; + } + // the Original's draft vocabulary (the MTP pack directory); unset = the full head, as the daemon did without + // --mtp-rt-dir + 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() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + if let (Ok(mib), true) = (env::var("LELEKA_REPLAY_PREFIX_MIB"), shape.mode != "conv") { + config.prefix = Some(PrefixConfig { + tail: tail_mode(&shape.mode), + budget: if mib == "auto" { + PrefixBudget::Auto + } else { + PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) + }, + block_tokens: shape.block, + ..PrefixConfig::auto() + }); + } + config +} +/// (label, arm) of every pass: a warm-up with arm 0, then reps x arms rotated per repetition. +fn pass_plan(spec_arms: &[String], reps: usize) -> Vec<(String, Option)> { + let mut passes: Vec<(String, Option)> = Vec::new(); + if spec_arms.is_empty() { + passes.extend((0..reps).map(|r| (format!("p{r}"), None))); + } else { + passes.push(("warm".to_owned(), Some(spec_arms[0].clone()))); + for r in 0..reps { + for q in 0..spec_arms.len() { + passes.push((format!("r{r}"), Some(spec_arms[(q + r) % spec_arms.len()].clone()))); + } + } + } + passes +} +/// The loaded model and the captured requests every arm replays. +struct Model<'a> { + binding: &'a ModelBinding, + context: &'a Rc>, + files: &'a [PathBuf], + dir: &'a PathBuf, + eos: u32, +} +impl Model<'_> { + /// The stack configuration of an arm, and the draft floor of its requests. + fn config(&self, shape: &ArmShape) -> (StackConfig, f32) { + let config = arm_config(shape); + let min_p: f32 = env::var("LELEKA_REPLAY_SPEC_MIN_P") + .ok() + .map(|v| v.parse().expect("LELEKA_REPLAY_SPEC_MIN_P")) + .unwrap_or(0.0); + eprintln!( + "REPLAY config: {} requests from {:?}, capacity {}, spec_min_p {min_p}, prefix cache {}, tier {:?}", + self.files.len(), + self.dir, + config.capacity, + config.prefix.is_some(), + config.expert_tier + ); + (config, min_p) + } + fn run_arm(&self, arm_index: usize, label: &str, arm: &str) { + let shape = arm_flags::parse(arm, &|| number("LELEKA_REPLAY_CAPACITY", 2048)); + shape.flags.apply(); + eprintln!( + "REPLAY-ARM start label={label} mode={} capacity={} block={} tiers={}", + shape.mode, + shape.capacity, + shape.block, + shape.tiers.map_or("default", |on| if on { "on" } else { "off" }) + ); + let (config, min_p) = self.config(&shape); + let mut stack = + match OriginalServeStack::open(self.binding, self.context.as_ref(), Rc::clone(self.context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + let spec_arms = stack.spec_arms(); + let reps = number("LELEKA_REPLAY_REPS", 1).max(1); + // LELEKA_REPLAY_FORCE=1: every request decodes along its RECORDED tokens (teacher forcing, `quality_force`), so + // all arms read the same path and, with LELEKA_TRACE_LOGPROBS=16 and LELEKA_BRINGUP_TRACE, print the top-16 + // rows that `scripts/quality/q_tail_gate.py` compares (the arm index plays the corpus pass). + let force = env::var("LELEKA_REPLAY_FORCE").is_ok_and(|v| v == "1"); + let replay = Replay { files: self.files, eos: self.eos, force, min_p, arm_index, label }; + for (pass_no, (pass_label, arm)) in pass_plan(&spec_arms, reps).iter().enumerate() { + replay.pass(&mut stack, (pass_no, pass_label), arm.as_deref(), &spec_arms); + } + stack.close().expect("stack cleanup failed"); + } +} +pub(super) fn run() { + let _ = dbg_el(); + assert!(env::var("LELEKA_ORIGINAL_SERVE_REPLAY").is_ok_and(|v| v == "yes"), "explicit replay opt-in required"); + let (dir, files) = load::captures(); + let (binding, eos) = load::pinned(); + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device 0 unavailable"); + let budget = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30; + let context = Rc::new(device.create_context(budget).expect("bounded Context unavailable")); + let arms = load::arms(); + let model = Model { binding: &binding, context: &context, files: &files, dir: &dir, eos }; + for (arm_index, (label, arm)) in arms.iter().enumerate() { + model.run_arm(arm_index, label, arm); + } + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs index cad923db..e3f41069 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs @@ -56,6 +56,23 @@ impl Rng { } } +/// One line of deterministic code-like text. +fn code_line(a: u64, b: u64, c: u64, line: usize) -> String { + let first = format!(" let v{b} = table[{a}].checked_add({c}).ok_or(Error::Overflow)?; // step {line}\n"); + let second = format!(" if v{b} > limit_{a} {{ return Err(Error::Range({b})); }}\n"); + first + &second +} +/// One line of deterministic log-like text. +fn log_line(a: u64, b: u64, c: u64, line: usize) -> String { + format!( + "[{:02}:{:02}:{:02}] worker-{b} ok job={c} bytes={} path=src/mod_{a}/file_{line}.rs\n", + a % 24, + b % 60, + c % 60, + a * 31 + c + ) +} + /// Deterministic text of `kind` encoded to exactly `tokens` ids. fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec { let mut ids: Vec = Vec::with_capacity(tokens + 256); @@ -65,10 +82,8 @@ fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec< for _ in 0..24 { let (a, b, c) = (rng.next() % 997, rng.next() % 64, rng.next() % 9973); match kind { - 0 => chunk.push_str(&format!( - " let v{b} = table[{a}].checked_add({c}).ok_or(Error::Overflow)?; // step {line}\n if v{b} > limit_{a} {{ return Err(Error::Range({b})); }}\n" - )), - _ => chunk.push_str(&format!("[{:02}:{:02}:{:02}] worker-{b} ok job={c} bytes={} path=src/mod_{a}/file_{line}.rs\n", a % 24, b % 60, c % 60, a * 31 + c)), + 0 => chunk.push_str(&code_line(a, b, c, line)), + _ => chunk.push_str(&log_line(a, b, c, line)), } line += 1; } @@ -139,855 +154,35 @@ fn print_report(tag: &str) { } } +#[path = "backend_original_serve_memory_smoke_load.rs"] +mod load; +use load::*; +#[path = "backend_original_serve_memory_smoke_inventory.rs"] +mod inventory; +#[path = "backend_original_serve_memory_smoke_leak.rs"] +mod leak; +#[path = "backend_original_serve_memory_smoke_probe.rs"] +mod probe; +#[path = "backend_original_serve_memory_smoke_reader.rs"] +mod reader; +#[path = "backend_original_serve_memory_smoke_shed.rs"] +mod shed; +#[path = "backend_original_serve_memory_smoke_soak.rs"] +mod soak; +#[path = "backend_original_serve_memory_smoke_traffic.rs"] +mod traffic; + #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; long prompts"] fn original_serve_memory_smoke() { - let _ = dbg_el(); - assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); - let scenario = text("LELEKA_MEM_SCENARIO", "inventory"); - let abort_gib = number("LELEKA_MEM_ABORT_GIB", 15) as u64; - let experts_mapped = text("LELEKA_MEM_EXPERTS", "mapped") == "mapped"; - let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); - let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); - let capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); - let prefix_wish = text("LELEKA_MEM_PREFIX_MIB", "4096"); - guard(abort_gib, "before the load"); - - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); - let inherited = match env::var_os("LELEKA_MEM_KAR_FILE") { - Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) - .expect("read-only KAR admission failed"), - None => { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") - } - }; - let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); - // the production startup sequence: plan (or refuse), then lock/guard the memfd, before any model byte is read - let prefix_arg = match prefix_wish.as_str() { - "auto" => Some(None), - "0" | "off" => None, - mib => Some(Some(mib.parse::().expect("LELEKA_MEM_PREFIX_MIB: auto or MiB") << 20)), - }; - let governor = crate::memory_governor::startup( - &crate::memory_governor::StartArgs { - kv_resident: resident, - gpu_budget_bytes: (budget_gib as u64) << 30, - kar_file_backed: Some(inherited.file_backed()), - kar_sparse_bytes: None, - expert_source_mapped: experts_mapped, - prefix: prefix_arg, - prompt_cache: 6, - }, - crate::settings::process(), - ) - .unwrap_or_else(|e| panic!("memory plan refused: {}", e.message)); - crate::memory_governor::guard_archive(governor, &inherited) - .unwrap_or_else(|e| panic!("memory guard refused: {}", e.message)); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - let bank_stage = crate::memory_governor::begin("expert bank (resident copy or mappings)", None); - let bank = if experts_mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() } - .expect("expert source load failed"); - crate::memory_governor::end(bank_stage, None); - crate::memory_governor::account( - "expert_bank", - if experts_mapped { "file_mapped" } else { "resident" }, - if experts_mapped { leleka_memory::Space::HostMapped } else { leleka_memory::Space::HostPinned }, - leleka_memory::When::Startup, - "routed experts of shard 0 (ResidentExpertSourceReport::charged_bytes)", - bank.charged_bytes, - ); - if !experts_mapped { - crate::memory_governor::drop_file_cache(&[ - &required_path("LELEKA_STRA169_IQ3S_SHARD0"), - &required_path("LELEKA_STRA169_IQ3S_SHARD1"), - ]); - } - guard(abort_gib, "after the expert bank"); - let driver = Driver::load().expect("CUDA driver load failed"); - let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - crate::memory_governor::check_vram(governor, context.as_ref(), (budget_gib as u64) << 30) - .unwrap_or_else(|e| panic!("vram refused: {}", e.message)); - - let mut config = StackConfig::new(max_context as i64); - config.capacity = capacity; - config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); - config.kv_resident = resident; - if experts_mapped { - config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 15) as i32; - } - match prefix_arg { - Some(arg) => { - let budget = match arg { - None => PrefixBudget::Auto, - Some(bytes) => PrefixBudget::Bytes(bytes), - }; - config.prefix = - Some(PrefixConfig { budget, block_tokens: 0, laptop: experts_mapped, ..PrefixConfig::auto() }); - } - None => {} - } - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - guard(abort_gib, "after the stack opened"); - governor.sample_now(); - print_report("idle"); - eprintln!("MEM-CENSUS idle {}", serde_json::to_string(&census(context.as_ref())).unwrap()); - // the stack opens in the "plan -> open -> report" order production uses; also the residency of the memfd right now - let swapped = governor.residency_tick(); - eprintln!("MEM-ARCHIVE swapped_bytes={swapped}"); - - let mut failed: Vec = Vec::new(); - let mut rng = Rng(0x5eed_1234_abcd_0042); - let tok = |s: &str| tokenizer.encode(s, true).expect("tokenization failed"); - let mut system = tok("<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search.\n"); - system.extend(filler(&tokenizer, &mut rng, 0, 2000)); - system.extend(tok("<|im_end|>\n")); - - match scenario.as_str() { - "inventory" => { - for target in list("LELEKA_MEM_TOKENS", "180000") { - let mut prompt = system.clone(); - prompt.extend(tok("<|im_start|>user\nSummarise.\n")); - prompt.extend(filler(&tokenizer, &mut rng, 1, target.saturating_sub(prompt.len() + 8))); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - let started = std::time::Instant::now(); - match serve_one(&mut stack, &prompt, 8, eos, None, None) { - Ok((out, prompt_ms, decode_ms, reused)) => eprintln!( - "MEM-REQ tokens={} prompt_ms={prompt_ms:.0} decode_ms={decode_ms:.0} reused={reused} out={} wall_s={:.1}", - prompt.len(), - out.len(), - started.elapsed().as_secs_f64() - ), - Err(e) => failed.push(format!("{target}: {e:?}")), - } - governor.sample_now(); - guard(abort_gib, "after a long request"); - print_report(&format!("after-{target}")); - eprintln!("MEM-CENSUS after-{target} {}", serde_json::to_string(&census(context.as_ref())).unwrap()); - } - // fill the prefix cache: distinct sessions until the store is at its budget - let fill = number("LELEKA_MEM_FILL_TOKENS", 20_000); - for i in 0..number("LELEKA_MEM_FILL_MAX", 80) { - let mut prompt = system.clone(); - prompt.extend(tok(&format!("<|im_start|>user\nSession {i}.\n"))); - prompt.extend(filler(&tokenizer, &mut rng, (i % 2) as u8, fill)); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - if let Err(e) = serve_one(&mut stack, &prompt, 4, eos, None, None) { - failed.push(format!("fill {i}: {e:?}")); - break; - } - guard(abort_gib, "filling the prefix cache"); - let line = stack.prefix_metrics().unwrap_or_default(); - if i % 4 == 0 { - eprintln!("MEM-FILL i={i} {line}"); - } - let used = line - .split("used_mib=") - .nth(1) - .and_then(|s| s.split_whitespace().next()) - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - let budget = line - .split("budget_mib=") - .nth(1) - .and_then(|s| s.split_whitespace().next()) - .and_then(|s| s.parse::().ok()) - .unwrap_or(u64::MAX); - if used * 100 >= budget * 97 { - eprintln!("MEM-FILL full at i={i}: {line}"); - break; - } - } - governor.sample_now(); - print_report("prefix-full"); - eprintln!("MEM-CENSUS prefix-full {}", serde_json::to_string(&census(context.as_ref())).unwrap()); - } - "soak" => { - let requests = number("LELEKA_MEM_REQUESTS", 220); - let big = list("LELEKA_MEM_BIG", "100000,180000"); - let big_every = number("LELEKA_MEM_BIG_EVERY", 55); - let sessions_n = number("LELEKA_MEM_SESSIONS", 6); - let warmup = number("LELEKA_MEM_WARMUP", 30); - let mut sessions: Vec> = (0..sessions_n) - .map(|s| { - let mut p = system.clone(); - p.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests.\n"))); - p.extend(filler(&tokenizer, &mut rng, 1, 1500)); - p - }) - .collect(); - let mut series: Vec = Vec::new(); - let (mut served, mut cancelled, mut refused, mut bigs) = (0usize, 0usize, 0usize, 0usize); - let started = std::time::Instant::now(); - for i in 0..requests { - let s = (rng.next() as usize) % sessions_n; - let kind = if i > 0 && i % big_every == 0 { - "big" - } else if i % 11 == 7 { - "overlong" - } else if i % 7 == 3 { - "cancel" - } else { - "normal" - }; - match kind { - "overlong" => { - // a request that cannot fit the pinned K/V image: refused up front, nothing allocated - let prompt = vec![1u32; max_context + 16]; - let shape = RequestShape { - prompt_tokens: prompt.len() as u64, - max_new_tokens: 16, - max_context: max_context as u64, - }; - match governor.admit(&shape) { - Admission::Refuse(r) if r.status == 400 => refused += 1, - other => failed.push(format!("overlong {i} not refused with 400: {other:?}")), - } - match serve_one(&mut stack, &prompt, 16, eos, None, None) { - Err(ServeError::Refused(_)) => {} - other => { - failed.push(format!("overlong {i} reached the engine: {:?}", other.map(|o| o.0.len()))) - } - } - } - "big" => { - let target = big[bigs % big.len()]; - bigs += 1; - let mut prompt = system.clone(); - prompt.extend(tok(&format!("<|im_start|>user\nBig {i}.\n"))); - prompt.extend(filler(&tokenizer, &mut rng, 1, target.saturating_sub(prompt.len() + 8))); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - match serve_one(&mut stack, &prompt, 8, eos, None, None) { - Ok(_) => served += 1, - Err(e) => failed.push(format!("big {i}: {e:?}")), - } - } - _ => { - let grow = 300 + (rng.unit().powi(3) * 9000.0) as usize; - let mut next = std::mem::take(&mut sessions[s]); - next.extend(tok("shell {\"cmd\": \"cargo test\"}<|im_end|>\n<|im_start|>user\n\n")); - next.extend(filler(&tokenizer, &mut rng, (i % 2) as u8, grow)); - next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n")); - if next.len() > 60_000.min(max_context.saturating_sub(6000)) { - // keep sessions bounded: start over with a fresh task (prefix churn) - next = system.clone(); - next.extend(tok(&format!("<|im_start|>user\nTask {i}.\n"))); - next.extend(filler(&tokenizer, &mut rng, 1, 1500)); - } - let result = if kind == "cancel" { - let r = if i % 2 == 0 { - serve_one(&mut stack, &next, 32, eos, Some(3), None) - } else { - serve_one(&mut stack, &next, 64, eos, None, Some(1)) - }; - match r { - Err(ServeError::Cancelled) => { - cancelled += 1; - Ok(()) - } - Ok(_) => Ok(()), - Err(e) => Err(e), - } - } else { - serve_one(&mut stack, &next, 12, eos, None, None).map(|_| served += 1) - }; - if let Err(e) = result { - failed.push(format!("{kind} {i}: {e:?}")); - } - sessions[s] = next; - } - } - if stack.health().is_some() { - failed.push(format!("stack lost an owner at request {i}")); - break; - } - guard(abort_gib, "soak"); - if i % 5 == 4 || kind == "big" { - governor.sample_now(); - series.push(census(context.as_ref())); - } - if i % 20 == 19 { - eprintln!( - "MEM-SOAK i={} served={served} cancelled={cancelled} refused={refused} big={bigs} elapsed_s={:.0} census={} prefix={}", - i + 1, - started.elapsed().as_secs_f64(), - serde_json::to_string(series.last().unwrap()).unwrap(), - stack.prefix_metrics().unwrap_or_default() - ); - } - } - // the big prompts are not warm-up noise but they are rare: judge from the first quarter after warm-up - let tolerances = Tolerances { rss: 512 << 20, ..Tolerances::default() }; - let flat = check_flat(&series, warmup / 5, &tolerances); - eprintln!("MEM-SOAK-RESULT served={served} cancelled={cancelled} refused={refused} big={bigs}\n{flat}"); - eprintln!("MEM-SOAK-SERIES {}", serde_json::to_string(&series).unwrap()); - print_report("soak-end"); - if !flat.ok { - failed.push("process memory not flat after warm-up".into()); - } - } - "shed" => { - // move the floors next to the memory the host has now; the real limits are never approached - let a0 = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); - let soft_below = (number("LELEKA_MEM_SOFT_BELOW_MIB", 1536) as u64) << 20; - let hard_below = (number("LELEKA_MEM_HARD_BELOW_MIB", 3072) as u64) << 20; - let ballast_mib = number("LELEKA_MEM_BALLAST_MIB", 3584); - assert!(a0 >= abort_gib << 30, "start with more than the guard"); - governor.set_floors(a0 - soft_below, a0 - hard_below).expect("floors"); - eprintln!( - "MEM-SHED start available_mib={} soft_mib={} hard_mib={}", - a0 >> 20, - (a0 - soft_below) >> 20, - (a0 - hard_below) >> 20 - ); - let shape = - |n: usize| RequestShape { prompt_tokens: n as u64, max_new_tokens: 8, max_context: max_context as u64 }; - // 1. grow the prefix cache until the soft floor is crossed (or the budget is full) - let mut max_used = 0usize; - let mut shed_seen = false; - for i in 0..number("LELEKA_MEM_FILL_MAX", 60) { - let mut prompt = system.clone(); - prompt.extend(tok(&format!("<|im_start|>user\nShed {i}.\n"))); - prompt.extend(filler(&tokenizer, &mut rng, (i % 2) as u8, 20_000)); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - if let Err(e) = serve_one(&mut stack, &prompt, 4, eos, None, None) { - failed.push(format!("grow {i}: {e:?}")); - break; - } - governor.sample_now(); - let used = stack.prefix_bytes(); - max_used = max_used.max(used); - let level = governor.level(); - eprintln!( - "MEM-SHED grow i={i} level={} prefix_used_mib={} available_mib={}", - level.as_str(), - used >> 20, - crate::conversation::memory::available_memory().unwrap_or(0) >> 20 - ); - guard(abort_gib, "growing the prefix cache"); - if level != Level::Normal { - shed_seen = true; - break; - } - } - if !shed_seen { - eprintln!( - "MEM-SHED the prefix cache reached its budget ({} MiB) without crossing the soft floor", - max_used >> 20 - ); - failed.push("shed level never reached by cache growth".into()); - } - // the next request applies the directive: the cache evicts before it starts - let mut prompt = system.clone(); - prompt.extend(tok("<|im_start|>user\nafter shed\n")); - prompt.extend(filler(&tokenizer, &mut rng, 0, 3000)); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - if governor.admit(&shape(prompt.len())) != Admission::Admit { - failed.push("shedding must still admit requests".into()); - } - let used_before = stack.prefix_bytes(); - let (avail_before, rss_before) = - (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); - let _ = serve_one(&mut stack, &prompt, 4, eos, None, None); - let used_after = stack.prefix_bytes(); - let (avail_after, rss_after) = - (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); - eprintln!( - "MEM-SHED evicted: prefix {} MiB -> {} MiB (level {}); MemAvailable {} -> {} MiB, RSS {} -> {} MiB", - used_before >> 20, - used_after >> 20, - governor.level().as_str(), - avail_before >> 20, - avail_after >> 20, - rss_before >> 20, - rss_after >> 20 - ); - if used_after >= used_before && used_before > 0 { - failed.push("the prefix cache did not shrink under shed".into()); - } - // 2. ballast pushes the host below the hard floor: requests are refused, everything is shed - let mut ballast: Vec = Vec::new(); - let step = 256usize << 20; - while ballast.len() < ballast_mib << 20 && governor.level() != Level::Reject { - let at = ballast.len(); - ballast.resize(at + step, 1); - // touch every page so the allocation is resident - for i in (at..ballast.len()).step_by(4096) { - ballast[i] = (i >> 12) as u8; - } - governor.sample_now(); - guard(abort_gib, "ballast"); - } - eprintln!( - "MEM-SHED ballast {} MiB level={} available_mib={}", - ballast.len() >> 20, - governor.level().as_str(), - crate::conversation::memory::available_memory().unwrap_or(0) >> 20 - ); - match governor.admit(&shape(prompt.len())) { - Admission::Refuse(r) if r.status == 503 && r.code == "memory_pressure" => { - eprintln!("MEM-SHED refused: {} retry_after={}s", r.message, r.retry_after_secs) - } - other => failed.push(format!("no 503 at the hard floor: {other:?}")), - } - let _ = serve_one(&mut stack, &prompt, 4, eos, None, None); - if stack.prefix_bytes() != 0 { - failed.push(format!("the prefix cache still holds {} MiB at reject", stack.prefix_bytes() >> 20)); - } - print_report("reject"); - // 3. the pressure is over: three calm samples per step, budget restored, requests served and the cache refills - drop(ballast); - // the baseline drifted while the test ran (mapped expert pages warmed up): re-centre the floors on what the host has now, so the - // hysteresis margin (1 GiB above the soft floor) can be met; the recovery path itself is what is under test - std::thread::sleep(std::time::Duration::from_millis(500)); - let a_now = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); - governor.set_floors(a_now - (2048u64 << 20), a_now - (3584u64 << 20)).expect("floors"); - for i in 0..14 { - std::thread::sleep(std::time::Duration::from_millis(300)); - governor.sample_now(); - if governor.level() == Level::Normal { - eprintln!("MEM-SHED recovered after {} samples", i + 1); - break; - } - } - if governor.level() != Level::Normal { - failed.push(format!("level stayed {} after the ballast was freed", governor.level().as_str())); - } - if governor.admit(&shape(prompt.len())) != Admission::Admit { - failed.push("requests are not admitted again after recovery".into()); - } - let r = serve_one(&mut stack, &prompt, 4, eos, None, None); - let restored = stack.prefix_budget_bytes(); - eprintln!( - "MEM-SHED after recovery: served={} prefix_budget_mib={} prefix_used_mib={}", - r.is_ok(), - restored >> 20, - stack.prefix_bytes() >> 20 - ); - if r.is_err() || restored < (1 << 30) { - failed.push("the prefix budget was not restored".into()); - } - print_report("recovered"); - } - "leak" => { - // Time-bounded mixed workload for the RSS-slope question: sample every `LELEKA_MEM_LEAK_SAMPLE_S` seconds RSS split into - // anon / file / shmem, swap, meminfo (Cached, Shmem, file LRU), VRAM, the prefix store and the glibc heap, then fit the slope - // of each series against the request count after the warm-up and print it with its confidence interval. - let seconds = number("LELEKA_MEM_LEAK_SECS", 10_800) as u64; - let sample_every = number("LELEKA_MEM_LEAK_SAMPLE_S", 30) as u64; - let warm_frac = number("LELEKA_MEM_LEAK_WARMUP_PCT", 25) as f64 / 100.0; - let sessions_n = number("LELEKA_MEM_SESSIONS", 8); - let session_cap = number("LELEKA_MEM_SESSION_CAP", 40_000).min(max_context.saturating_sub(6000)); - let big = list("LELEKA_MEM_BIG", "100000,180000"); - let big_every = number("LELEKA_MEM_BIG_EVERY", 120); - let tsv_path = env::var_os("LELEKA_MEM_LEAK_TSV").map(PathBuf::from); - let mut tsv = String::from( - "t_s\treq\trss\trss_anon\trss_file\trss_shmem\tswap\tavail\tcached\tshmem_sys\tactive_file\tinactive_file\tvram_used\tvram_acct\tprefix_store\tmalloc_arena\tmalloc_in_use\tmalloc_free\tmalloc_mmapped\tthreads\tfds\n", - ); - let mut sessions: Vec> = (0..sessions_n) - .map(|s| { - let mut p = system.clone(); - p.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests.\n"))); - p.extend(filler(&tokenizer, &mut rng, 1, 1500)); - p - }) - .collect(); - let started = std::time::Instant::now(); - let mut next_sample = 0u64; - let (mut req, mut served, mut cancelled, mut refused, mut bigs, mut fresh) = - (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); - // req, rss, anon, file, shmem, swap, vram, vram_acct, prefix, malloc_in_use, malloc_free, avail - let mut series: Vec<[f64; 12]> = Vec::new(); - while started.elapsed().as_secs() < seconds { - let s = (rng.next() as usize) % sessions_n; - let roll = rng.next() % 100; - let kind = if req > 0 && req % big_every == 0 { - "big" - } else if roll < 4 { - "overlong" - } else if roll < 12 { - "cancel" - } else if roll < 18 { - "fresh" - } else { - "normal" - }; - match kind { - "overlong" => { - let prompt_len = max_context + 16; - let shape = RequestShape { - prompt_tokens: prompt_len as u64, - max_new_tokens: 16, - max_context: max_context as u64, - }; - match governor.admit(&shape) { - Admission::Refuse(r) if r.status == 400 => refused += 1, - other => failed.push(format!("overlong {req} not refused with 400: {other:?}")), - } - } - "big" => { - let target = big[bigs % big.len()].min(max_context.saturating_sub(64)); - bigs += 1; - let mut prompt = system.clone(); - prompt.extend(tok(&format!("<|im_start|>user\nBig {req}.\n"))); - prompt.extend(filler(&tokenizer, &mut rng, 1, target.saturating_sub(prompt.len() + 8))); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - match serve_one(&mut stack, &prompt, 8, eos, None, None) { - Ok(_) => served += 1, - Err(e) => failed.push(format!("big {req}: {e:?}")), - } - } - "fresh" => { - // an unshared session: its own task text, 8k..30k tokens, never seen again - fresh += 1; - let size = 8000 + (rng.next() as usize % 22_000); - let mut prompt = tok(&format!( - "<|im_start|>system\nIndependent agent {req}.<|im_end|>\n<|im_start|>user\nUnshared task {req}.\n" - )); - prompt.extend(filler( - &tokenizer, - &mut rng, - (req % 2) as u8, - size.min(max_context.saturating_sub(2000)), - )); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - match serve_one(&mut stack, &prompt, 12, eos, None, None) { - Ok(_) => served += 1, - Err(e) => failed.push(format!("fresh {req}: {e:?}")), - } - } - _ => { - let grow = 300 + (rng.unit().powi(3) * 9000.0) as usize; - let mut next = std::mem::take(&mut sessions[s]); - next.extend(tok("shell {\"cmd\": \"cargo test\"}<|im_end|>\n<|im_start|>user\n\n")); - next.extend(filler(&tokenizer, &mut rng, (req % 2) as u8, grow)); - next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n")); - if next.len() > session_cap { - next = system.clone(); - next.extend(tok(&format!("<|im_start|>user\nTask {req}.\n"))); - next.extend(filler(&tokenizer, &mut rng, 1, 1500)); - } - let result = if kind == "cancel" { - let r = if req % 2 == 0 { - serve_one(&mut stack, &next, 32, eos, Some(3), None) - } else { - serve_one(&mut stack, &next, 64, eos, None, Some(1)) - }; - match r { - Err(ServeError::Cancelled) => { - cancelled += 1; - Ok(()) - } - Ok(_) => Ok(()), - Err(e) => Err(e), - } - } else { - serve_one(&mut stack, &next, 12, eos, None, None).map(|_| served += 1) - }; - if let Err(e) = result { - failed.push(format!("{kind} {req}: {e:?}")); - } - sessions[s] = next; - } - } - req += 1; - if stack.health().is_some() { - failed.push(format!("stack lost an owner at request {req}")); - break; - } - guard(abort_gib, "leak soak"); - let t = started.elapsed().as_secs(); - if t >= next_sample { - next_sample = t + sample_every; - governor.sample_now(); - let c = census(context.as_ref()); - let facts = governor.probe(); - let heap = leleka_memory::heap::stats().unwrap_or_default(); - let mi = &facts.meminfo; - let prefix = stack.prefix_bytes() as u64; - tsv.push_str(&format!( - "{t}\t{req}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{prefix}\t{}\t{}\t{}\t{}\t{}\t{}\n", - c.rss, - c.rss_anon, - c.rss_file, - c.rss_shmem, - c.swap, - c.available, - mi.cached.unwrap_or(0), - mi.shmem.unwrap_or(0), - mi.active_file.unwrap_or(0), - mi.inactive_file.unwrap_or(0), - c.device_used.unwrap_or(0), - c.device_accounted.unwrap_or(0), - heap.arena, - heap.in_use, - heap.free, - heap.mmapped, - c.threads, - c.fds - )); - series.push([ - req as f64, - c.rss as f64, - c.rss_anon as f64, - c.rss_file as f64, - c.rss_shmem as f64, - c.swap as f64, - c.device_used.unwrap_or(0) as f64, - c.device_accounted.unwrap_or(0) as f64, - prefix as f64, - heap.in_use as f64, - heap.free as f64, - c.available as f64, - ]); - eprintln!( - "MEM-LEAK t={t} req={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs} rss={} anon={} file={} shmem={} swap={} avail={} vram={} prefix={} malloc_in_use={} malloc_free={} malloc_arena={} mmapped={} threads={} fds={}", - c.rss >> 20, - c.rss_anon >> 20, - c.rss_file >> 20, - c.rss_shmem >> 20, - c.swap >> 20, - c.available >> 20, - c.device_used.unwrap_or(0) >> 20, - prefix >> 20, - heap.in_use >> 20, - heap.free >> 20, - heap.arena >> 20, - heap.mmapped >> 20, - c.threads, - c.fds - ); - if let Some(path) = &tsv_path { - let _ = std::fs::write(path, &tsv); - } - } - } - if let Some(path) = &tsv_path { - let _ = std::fs::write(path, &tsv); - } - // slope after the warm-up, in MiB per 1000 requests, for every series - let skip = (series.len() as f64 * warm_frac) as usize; - let tail = &series[skip.min(series.len())..]; - let names = [ - "rss", - "rss_anon", - "rss_file", - "rss_shmem", - "swap", - "vram_used", - "vram_accounted", - "prefix_store", - "malloc_in_use", - "malloc_free", - "mem_available", - ]; - eprintln!( - "MEM-LEAK-FIT requests={req} samples={} used_for_fit={} (after {:.0}% warm-up); slope in MiB per 1000 requests with its 95% interval (OLS) and the Theil-Sen slope", - series.len(), - tail.len(), - warm_frac * 100.0 - ); - for (k, name) in names.iter().enumerate() { - let pts: Vec<(f64, f64)> = tail.iter().map(|r| (r[0], r[k + 1])).collect(); - match leleka_memory::census::fit_slope(&pts) { - Some(f) => eprintln!( - "MEM-LEAK-FIT {name:<15} slope {:+9.3} MiB/1000req [{:+9.3}, {:+9.3}] theil-sen {:+9.3} r2 {:.3} n={} first {:.0} MiB last {:.0} MiB{}", - f.slope * 1000.0 / 1_048_576.0, - f.ci95_low * 1000.0 / 1_048_576.0, - f.ci95_high * 1000.0 / 1_048_576.0, - f.theil_sen * 1000.0 / 1_048_576.0, - f.r2, - f.n, - pts.first().map_or(0.0, |p| p.1) / 1_048_576.0, - pts.last().map_or(0.0, |p| p.1) / 1_048_576.0, - if f.includes_zero() { " (zero inside)" } else { "" } - ), - None => eprintln!("MEM-LEAK-FIT {name}: too few samples"), - } - } - eprintln!( - "MEM-LEAK-RESULT requests={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs}" - ); - print_report("leak-end"); - } - "reader" => { - // decode speed and the memfd's residency while a competing reader streams a big file through the page cache (what the - // Original did when it read the KAR file next to the memfd): phase A without the reader, B with it, C after - let path = PathBuf::from(text("LELEKA_MEM_READER_FILE", "")); - assert!(path.is_file(), "LELEKA_MEM_READER_FILE must name a big file"); - let gib = number("LELEKA_MEM_READER_GIB", 40) as u64; - let n = number("LELEKA_MEM_READER_REQS", 6); - let new_tokens = number("LELEKA_MEM_READER_NEW", 96); - let mut prompt = system.clone(); - prompt.extend(tok("<|im_start|>user\nExplain.\n")); - prompt.extend(filler(&tokenizer, &mut rng, 1, 3000)); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); - let swap_counters = || { - let f = governor.probe(); - (f.pswpin.unwrap_or(0), f.pswpout.unwrap_or(0)) - }; - NO_STOP.store(true, std::sync::atomic::Ordering::Relaxed); - let mut phase = |label: &str, - stack: &mut OriginalServeStack<'_, '_>, - rates: &mut Vec, - until: &dyn Fn() -> bool| { - for i in 0..usize::MAX { - if i >= n && until() { - break; - } - if i >= 4 * n + 400 { - break; - } - let (in0, out0) = swap_counters(); - let mut p = prompt.clone(); - p.extend(tok(&format!("<|im_start|>user\nvariant {label} {i}\n"))); - let r = serve_one(stack, &p, new_tokens, eos, None, None); - let swapped = governor.residency_tick(); - let (in1, out1) = swap_counters(); - guard(abort_gib, "reader"); - match r { - Ok((out, prompt_ms, decode_ms, _)) => { - let rate = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 }; - rates.push(rate); - eprintln!( - "MEM-READER phase={label} i={i} prompt_ms={prompt_ms:.0} decode_ms={decode_ms:.0} new={} decode_tok_s={rate:.2} memfd_swapped_mib={} pswpin+={} pswpout+={} avail_mib={}", - out.len(), - swapped >> 20, - in1 - in0, - out1 - out0, - crate::conversation::memory::available_memory().unwrap_or(0) >> 20 - ); - } - Err(e) => failed.push(format!("reader {label} {i}: {e:?}")), - } - } - }; - let (mut a, mut b, mut c) = (Vec::new(), Vec::new(), Vec::new()); - phase("A-no-reader", &mut stack, &mut a, &|| true); - let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let read_bytes = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); - let reader = { - let (stop, read_bytes, path) = (stop.clone(), read_bytes.clone(), path.clone()); - std::thread::spawn(move || { - use std::io::Read; - let mut file = std::fs::File::open(path).expect("reader file"); - let mut buf = vec![0u8; 16 << 20]; - while !stop.load(std::sync::atomic::Ordering::Relaxed) - && read_bytes.load(std::sync::atomic::Ordering::Relaxed) < gib << 30 - { - match file.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(k) => { - read_bytes.fetch_add(k as u64, std::sync::atomic::Ordering::Relaxed); - } - } - } - }) - }; - // B lasts until the reader has streamed its volume (or finished): a request every ~1-2 s, minutes of page-cache churn - let (rb, st) = (read_bytes.clone(), stop.clone()); - phase("B-reader", &mut stack, &mut b, &move || { - rb.load(std::sync::atomic::Ordering::Relaxed) >= gib << 30 - || st.load(std::sync::atomic::Ordering::Relaxed) - }); - stop.store(true, std::sync::atomic::Ordering::Relaxed); - reader.join().expect("reader thread"); - eprintln!( - "MEM-READER the reader streamed {} GiB through the page cache", - read_bytes.load(std::sync::atomic::Ordering::Relaxed) >> 30 - ); - phase("C-after", &mut stack, &mut c, &|| true); - NO_STOP.store(false, std::sync::atomic::Ordering::Relaxed); - let mean = |v: &[f64]| v.iter().sum::() / v.len().max(1) as f64; - eprintln!( - "MEM-READER decode tok/s mean: A {:.2} B {:.2} C {:.2} (B/A {:.3})", - mean(&a), - mean(&b), - mean(&c), - mean(&b) / mean(&a).max(1e-9) - ); - print_report("reader-end"); - } - other => panic!("LELEKA_MEM_SCENARIO: inventory | soak | shed | reader | leak, not {other}"), - } - guard(abort_gib, "end"); - eprintln!("MEM-CENSUS end {}", serde_json::to_string(&census(context.as_ref())).unwrap()); - eprintln!("MEM-RESULT scenario={scenario} failed={failed:?}"); - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); - assert!(failed.is_empty(), "memory smoke checks failed: {failed:?}"); + load::run(); } /// Model-free: guard the real sealed KAR memfd of the holder (no model, no GPU), report the lock decision and the -/// memfd's swap for `LELEKA_MEM_PROBE_SECS` seconds. Run it next to a competing page-cache reader to see whether the archive -/// stays resident. +/// memfd's swap for `LELEKA_MEM_PROBE_SECS` seconds. Run it next to a competing page-cache reader to see whether +/// the archive stays resident. #[test] #[ignore = "needs the holder's inherited sealed KAR descriptor (LELEKA_STRA169_KAR_FD)"] fn memory_archive_guard_probe() { - assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); - let inherited = InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed"); - let governor = crate::memory_governor::install(false, crate::settings::process()).expect("governor"); - let started = std::time::Instant::now(); - let report = crate::memory_governor::guard_archive(governor, &inherited); - eprintln!( - "PROBE guard result: {:?} in {:.1} s", - report.as_ref().map(|_| "ok").map_err(|e| e.message.clone()), - started.elapsed().as_secs_f64() - ); - let secs = number("LELEKA_MEM_PROBE_SECS", 60); - let mut last_in = None; - for t in 0..secs { - let before = std::time::Instant::now(); - let swapped = governor.residency_tick(); - let facts = governor.probe(); - let (swp_in, swp_out) = (facts.pswpin.unwrap_or(0), facts.pswpout.unwrap_or(0)); - let delta = last_in.map(|(i, o)| (swp_in - i, swp_out - o)); - last_in = Some((swp_in, swp_out)); - eprintln!( - "PROBE t={t} memfd_swapped_mib={} smaps_ms={:.0} avail_mib={} shmem_mib={} swap_used_mib={} pswpin_pswpout_delta={delta:?}", - swapped >> 20, - before.elapsed().as_secs_f64() * 1e3, - facts.effective_available().unwrap_or(0) >> 20, - facts.meminfo.shmem.unwrap_or(0) >> 20, - (facts.meminfo.swap_total.unwrap_or(0) - facts.meminfo.swap_free.unwrap_or(0)) >> 20, - ); - guard(number("LELEKA_MEM_ABORT_GIB", 15) as u64, "probe"); - std::thread::sleep(std::time::Duration::from_secs(1)); - } - eprintln!("PROBE report {}", crate::memory_governor::report().unwrap_or_default()); + probe::run(); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_inventory.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_inventory.rs new file mode 100644 index 00000000..de0680d2 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_inventory.rs @@ -0,0 +1,66 @@ +//! The inventory scenario: the allocation inventory and the load ledger at idle, after a long request and with the +//! prefix cache full. +use super::*; + +/// The number after `key` in a prefix metrics line. +fn metric(line: &str, key: &str) -> Option { + line.split(key).nth(1).and_then(|s| s.split_whitespace().next()).and_then(|s| s.parse::().ok()) +} +impl Mem<'_, '_> { + pub(super) fn inventory(&mut self) { + for target in list("LELEKA_MEM_TOKENS", "180000") { + self.long_request(target); + } + self.fill_prefix_cache(); + self.governor.sample_now(); + print_report("prefix-full"); + self.census_line("prefix-full"); + } + fn long_request(&mut self, target: usize) { + let prompt = self.prompt_for("<|im_start|>user\nSummarise.\n", 1, target); + let started = std::time::Instant::now(); + match self.serve(&prompt, 8, None, None) { + Ok((out, prompt_ms, decode_ms, reused)) => eprintln!( + "MEM-REQ tokens={} prompt_ms={prompt_ms:.0} decode_ms={decode_ms:.0} reused={reused} out={} \ + wall_s={:.1}", + prompt.len(), + out.len(), + started.elapsed().as_secs_f64() + ), + Err(e) => self.failed.push(format!("{target}: {e:?}")), + } + self.governor.sample_now(); + self.guard("after a long request"); + print_report(&format!("after-{target}")); + self.census_line(&format!("after-{target}")); + } + /// Fills the prefix cache: distinct sessions until the store is at its budget. + fn fill_prefix_cache(&mut self) { + let fill = number("LELEKA_MEM_FILL_TOKENS", 20_000); + for i in 0..number("LELEKA_MEM_FILL_MAX", 80) { + if !self.fill_session(i, fill) { + break; + } + } + } + /// One more session; false when the fill is over (a failure or the store is full). + fn fill_session(&mut self, i: usize, fill: usize) -> bool { + let prompt = self.prompt(&format!("<|im_start|>user\nSession {i}.\n"), (i % 2) as u8, fill); + if let Err(e) = self.serve(&prompt, 4, None, None) { + self.failed.push(format!("fill {i}: {e:?}")); + return false; + } + self.guard("filling the prefix cache"); + let line = self.stack.prefix_metrics().unwrap_or_default(); + if i % 4 == 0 { + eprintln!("MEM-FILL i={i} {line}"); + } + let used = metric(&line, "used_mib=").unwrap_or(0); + let budget = metric(&line, "budget_mib=").unwrap_or(u64::MAX); + if used * 100 >= budget * 97 { + eprintln!("MEM-FILL full at i={i}: {line}"); + return false; + } + true + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_leak.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_leak.rs new file mode 100644 index 00000000..11d89ead --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_leak.rs @@ -0,0 +1,244 @@ +//! The leak scenario: a time-bounded mixed workload for the RSS-slope question. Every `LELEKA_MEM_LEAK_SAMPLE_S` +//! seconds it samples RSS split into anon / file / shmem, swap, meminfo (Cached, Shmem, file LRU), VRAM, the +//! prefix store and the glibc heap, then fits the slope of each series against the request count after the +//! warm-up and prints it with its confidence interval. +use super::traffic::Tally; +use super::*; + +const TSV_HEADER: &str = "t_s\treq\trss\trss_anon\trss_file\trss_shmem\tswap\tavail\tcached\tshmem_sys\t\ + active_file\tinactive_file\tvram_used\tvram_acct\tprefix_store\tmalloc_arena\tmalloc_in_use\tmalloc_free\t\ + malloc_mmapped\tthreads\tfds\n"; +/// The names of the series of a sample after the request count. +const SERIES: [&str; 11] = [ + "rss", + "rss_anon", + "rss_file", + "rss_shmem", + "swap", + "vram_used", + "vram_accounted", + "prefix_store", + "malloc_in_use", + "malloc_free", + "mem_available", +]; + +/// The knobs of the leak run. +struct Leak { + seconds: u64, + sample_every: u64, + warm_frac: f64, + sessions_n: usize, + session_cap: usize, + big: Vec, + big_every: usize, + tsv_path: Option, +} +impl Leak { + fn from_env(max_context: usize) -> Leak { + Leak { + seconds: number("LELEKA_MEM_LEAK_SECS", 10_800) as u64, + sample_every: number("LELEKA_MEM_LEAK_SAMPLE_S", 30) as u64, + warm_frac: number("LELEKA_MEM_LEAK_WARMUP_PCT", 25) as f64 / 100.0, + sessions_n: number("LELEKA_MEM_SESSIONS", 8), + session_cap: number("LELEKA_MEM_SESSION_CAP", 40_000).min(max_context.saturating_sub(6000)), + big: list("LELEKA_MEM_BIG", "100000,180000"), + big_every: number("LELEKA_MEM_BIG_EVERY", 120), + tsv_path: env::var_os("LELEKA_MEM_LEAK_TSV").map(PathBuf::from), + } + } + fn kind(&self, req: usize, roll: u64) -> &'static str { + if req > 0 && req % self.big_every == 0 { + "big" + } else if roll < 4 { + "overlong" + } else if roll < 12 { + "cancel" + } else if roll < 18 { + "fresh" + } else { + "normal" + } + } +} +/// The state of a leak run: the requests so far, the samples and the TSV of them. +struct Run { + tsv: String, + next_sample: u64, + tally: Tally, + req: usize, + /// req, rss, anon, file, shmem, swap, vram, vram_acct, prefix, malloc_in_use, malloc_free, avail + series: Vec<[f64; 12]>, +} +impl Mem<'_, '_> { + pub(super) fn leak(&mut self) { + let plan = Leak::from_env(self.max_context); + let mut sessions = self.sessions(plan.sessions_n); + let mut run = + Run { tsv: String::from(TSV_HEADER), next_sample: 0, tally: Tally::default(), req: 0, series: Vec::new() }; + let started = std::time::Instant::now(); + while started.elapsed().as_secs() < plan.seconds { + let s = (self.rng.next() as usize) % plan.sessions_n; + let roll = self.rng.next() % 100; + self.leak_request(&plan, plan.kind(run.req, roll), &mut sessions[s], &mut run); + run.req += 1; + if self.stack.health().is_some() { + self.failed.push(format!("stack lost an owner at request {}", run.req)); + break; + } + self.guard("leak soak"); + let t = started.elapsed().as_secs(); + if t >= run.next_sample { + run.next_sample = t + plan.sample_every; + self.leak_sample(t, &plan, &mut run); + } + } + if let Some(path) = &plan.tsv_path { + let _ = std::fs::write(path, &run.tsv); + } + leak_fit(&run, plan.warm_frac); + print_report("leak-end"); + } + fn leak_request(&mut self, plan: &Leak, kind: &str, session: &mut Vec, run: &mut Run) { + let (req, t) = (run.req, &mut run.tally); + match kind { + "overlong" => self.overlong(req, &mut t.refused, false), + "big" => { + let target = plan.big[t.bigs % plan.big.len()].min(self.max_context.saturating_sub(64)); + t.bigs += 1; + self.big(req, target, &mut t.served); + } + "fresh" => { + // an unshared session: its own task text, 8k..30k tokens, never seen again + t.fresh += 1; + self.fresh(req, &mut t.served); + } + _ => self.session_turn(kind, req, session, plan.session_cap, t), + } + } + /// One sample: the TSV row, the series point and the `MEM-LEAK` line. + fn leak_sample(&mut self, t: u64, plan: &Leak, run: &mut Run) { + self.governor.sample_now(); + let c = self.census(); + let facts = self.governor.probe(); + let heap = leleka_memory::heap::stats().unwrap_or_default(); + let prefix = self.stack.prefix_bytes() as u64; + let row = tsv_row(t, run.req, &c, (&facts, &heap), prefix); + run.tsv.push_str(&row.map(|v| v.to_string()).join("\t")); + run.tsv.push('\n'); + run.series.push(series_point(run.req, &c, &heap, prefix)); + print_leak_line(t, run, &row); + if let Some(path) = &plan.tsv_path { + let _ = std::fs::write(path, &run.tsv); + } + } +} +/// The numbers of the TSV row, in the order of `TSV_HEADER`. +fn tsv_row( + t: u64, + req: usize, + c: &Census, + (facts, heap): (&leleka_memory::HostFacts, &leleka_memory::heap::HeapStats), + prefix: u64, +) -> [u64; 21] { + let mi = &facts.meminfo; + let host = [t, req as u64, c.rss, c.rss_anon, c.rss_file, c.rss_shmem, c.swap, c.available]; + let meminfo = + [mi.cached.unwrap_or(0), mi.shmem.unwrap_or(0), mi.active_file.unwrap_or(0), mi.inactive_file.unwrap_or(0)]; + let device = [c.device_used.unwrap_or(0), c.device_accounted.unwrap_or(0), prefix]; + let process = [heap.arena, heap.in_use, heap.free, heap.mmapped, c.threads, c.fds]; + let mut row = [0u64; 21]; + for (slot, value) in row.iter_mut().zip(host.into_iter().chain(meminfo).chain(device).chain(process)) { + *slot = value; + } + row +} +/// The point of the series: the request count and the values the slopes are fitted to. +fn series_point(req: usize, c: &Census, heap: &leleka_memory::heap::HeapStats, prefix: u64) -> [f64; 12] { + [ + req as f64, + c.rss as f64, + c.rss_anon as f64, + c.rss_file as f64, + c.rss_shmem as f64, + c.swap as f64, + c.device_used.unwrap_or(0) as f64, + c.device_accounted.unwrap_or(0) as f64, + prefix as f64, + heap.in_use as f64, + heap.free as f64, + c.available as f64, + ] +} +/// The `MEM-LEAK` line of a sample, in MiB. +fn print_leak_line(t: u64, run: &Run, row: &[u64; 21]) { + let mib = |index: usize| row[index] >> 20; + let tally = &run.tally; + eprintln!( + "MEM-LEAK t={t} req={} served={} cancelled={} refused={} fresh={} big={} rss={} anon={} file={} shmem={} \ + swap={} avail={} vram={} prefix={} malloc_in_use={} malloc_free={} malloc_arena={} mmapped={} threads={} \ + fds={}", + run.req, + tally.served, + tally.cancelled, + tally.refused, + tally.fresh, + tally.bigs, + mib(2), + mib(3), + mib(4), + mib(5), + mib(6), + mib(7), + mib(12), + mib(14), + mib(16), + mib(17), + mib(15), + mib(18), + row[19], + row[20] + ); +} +/// The slope after the warm-up, in MiB per 1000 requests, for every series. +fn leak_fit(run: &Run, warm_frac: f64) { + let series = &run.series; + let skip = (series.len() as f64 * warm_frac) as usize; + let tail = &series[skip.min(series.len())..]; + eprintln!( + "MEM-LEAK-FIT requests={} samples={} used_for_fit={} (after {:.0}% warm-up); slope in MiB per 1000 requests \ + with its 95% interval (OLS) and the Theil-Sen slope", + run.req, + series.len(), + tail.len(), + warm_frac * 100.0 + ); + for (k, name) in SERIES.iter().enumerate() { + let pts: Vec<(f64, f64)> = tail.iter().map(|r| (r[0], r[k + 1])).collect(); + match leleka_memory::census::fit_slope(&pts) { + Some(f) => print_fit(name, &f, &pts), + None => eprintln!("MEM-LEAK-FIT {name}: too few samples"), + } + } + let t = &run.tally; + eprintln!( + "MEM-LEAK-RESULT requests={} served={} cancelled={} refused={} fresh={} big={}", + run.req, t.served, t.cancelled, t.refused, t.fresh, t.bigs + ); +} +fn print_fit(name: &str, f: &leleka_memory::census::SlopeFit, pts: &[(f64, f64)]) { + const MIB: f64 = 1_048_576.0; + eprintln!( + "MEM-LEAK-FIT {name:<15} slope {:+9.3} MiB/1000req [{:+9.3}, {:+9.3}] theil-sen {:+9.3} r2 {:.3} n={} \ + first {:.0} MiB last {:.0} MiB{}", + f.slope * 1000.0 / MIB, + f.ci95_low * 1000.0 / MIB, + f.ci95_high * 1000.0 / MIB, + f.theil_sen * 1000.0 / MIB, + f.r2, + f.n, + pts.first().map_or(0.0, |p| p.1) / MIB, + pts.last().map_or(0.0, |p| p.1) / MIB, + if f.includes_zero() { " (zero inside)" } else { "" } + ); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_load.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_load.rs new file mode 100644 index 00000000..384997a8 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_load.rs @@ -0,0 +1,284 @@ +//! Loads the pinned model under the memory governor, opens the serve stack as production starts it and runs the +//! scenario of `LELEKA_MEM_SCENARIO` on it. +use super::*; + +/// What the operator asked for. +struct Plan { + scenario: String, + abort_gib: u64, + experts_mapped: bool, + max_context: usize, + resident: usize, + capacity: usize, + prefix_wish: String, +} +impl Plan { + fn from_env() -> Plan { + let scenario = text("LELEKA_MEM_SCENARIO", "inventory"); + let abort_gib = number("LELEKA_MEM_ABORT_GIB", 15) as u64; + let experts_mapped = text("LELEKA_MEM_EXPERTS", "mapped") == "mapped"; + let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); + let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); + let capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); + let prefix_wish = text("LELEKA_MEM_PREFIX_MIB", "4096"); + Plan { scenario, abort_gib, experts_mapped, max_context, resident, capacity, prefix_wish } + } + /// The prefix budget argument of the production startup: `None` is off, `Some(None)` is auto. + fn prefix_arg(&self) -> Option> { + match self.prefix_wish.as_str() { + "auto" => Some(None), + "0" | "off" => None, + mib => Some(Some(mib.parse::().expect("LELEKA_MEM_PREFIX_MIB: auto or MiB") << 20)), + } + } +} +/// The pinned tokenizer and EOS, the KAR archive and the binding with its expert bank. +struct Loaded { + binding: ModelBinding, + _inherited: InheritedKarArchive, + tokenizer: Tokenizer, + eos: u32, + governor: &'static Governor, + budget_gib: usize, +} +fn pinned_artifact() -> Qwen4ExpArtifact { + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); + Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed") +} +fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) { + let metadata = artifact.tokenizer(); + let tokenizer = Tokenizer::from_vocabulary( + &metadata.model, + &metadata.pre, + metadata.tokens.clone(), + metadata.merges.clone(), + metadata.token_types.clone(), + ) + .expect("verified tokenizer construction failed"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + (tokenizer, eos) +} +fn open_archive() -> InheritedKarArchive { + let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); + match env::var_os("LELEKA_MEM_KAR_FILE") { + Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) + .expect("read-only KAR admission failed"), + None => { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") + } + } +} +/// The production startup sequence: plan (or refuse), then lock/guard the memfd, before any model byte is read. +fn start_governor(plan: &Plan, inherited: &InheritedKarArchive, budget_gib: usize) -> &'static Governor { + let governor = crate::memory_governor::startup( + &crate::memory_governor::StartArgs { + kv_resident: plan.resident, + gpu_budget_bytes: (budget_gib as u64) << 30, + kar_file_backed: Some(inherited.file_backed()), + kar_sparse_bytes: None, + expert_source_mapped: plan.experts_mapped, + prefix: plan.prefix_arg(), + prompt_cache: 6, + }, + crate::settings::process(), + ) + .unwrap_or_else(|e| panic!("memory plan refused: {}", e.message)); + crate::memory_governor::guard_archive(governor, inherited) + .unwrap_or_else(|e| panic!("memory guard refused: {}", e.message)); + governor +} +fn load_bank(binding: &mut ModelBinding, mapped: bool) { + let bank_stage = crate::memory_governor::begin("expert bank (resident copy or mappings)", None); + let bank = if mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() } + .expect("expert source load failed"); + crate::memory_governor::end(bank_stage, None); + crate::memory_governor::account( + "expert_bank", + if mapped { "file_mapped" } else { "resident" }, + if mapped { leleka_memory::Space::HostMapped } else { leleka_memory::Space::HostPinned }, + leleka_memory::When::Startup, + "routed experts of shard 0 (ResidentExpertSourceReport::charged_bytes)", + bank.charged_bytes, + ); + if !mapped { + crate::memory_governor::drop_file_cache(&[ + &required_path("LELEKA_STRA169_IQ3S_SHARD0"), + &required_path("LELEKA_STRA169_IQ3S_SHARD1"), + ]); + } +} +fn load(plan: &Plan) -> Loaded { + let artifact = pinned_artifact(); + let (tokenizer, eos) = pinned_tokenizer(&artifact); + let inherited = open_archive(); + let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); + let governor = start_governor(plan, &inherited, budget_gib); + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + load_bank(&mut binding, plan.experts_mapped); + guard(plan.abort_gib, "after the expert bank"); + Loaded { binding, _inherited: inherited, tokenizer, eos, governor, budget_gib } +} +fn stack_config(plan: &Plan) -> StackConfig { + let mut config = StackConfig::new(plan.max_context as i64); + config.capacity = plan.capacity; + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.kv_resident = plan.resident; + if plan.experts_mapped { + config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 15) as i32; + } + if let Some(arg) = plan.prefix_arg() { + let budget = match arg { + None => PrefixBudget::Auto, + Some(bytes) => PrefixBudget::Bytes(bytes), + }; + config.prefix = + Some(PrefixConfig { budget, block_tokens: 0, laptop: plan.experts_mapped, ..PrefixConfig::auto() }); + } + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + config +} + +/// The stack under measurement and what every scenario needs of it. +pub(super) struct Mem<'a, 'ctx> { + pub(super) stack: OriginalServeStack<'a, 'ctx>, + pub(super) context: &'a Rc>, + pub(super) governor: &'static Governor, + tokenizer: &'a Tokenizer, + pub(super) eos: u32, + pub(super) abort_gib: u64, + pub(super) max_context: usize, + pub(super) rng: Rng, + pub(super) system: Vec, + pub(super) failed: Vec, +} +impl Mem<'_, '_> { + pub(super) fn tok(&self, s: &str) -> Vec { + self.tokenizer.encode(s, true).expect("tokenization failed") + } + pub(super) fn filler(&mut self, kind: u8, tokens: usize) -> Vec { + filler(self.tokenizer, &mut self.rng, kind, tokens) + } + pub(super) fn serve( + &mut self, + prompt: &[u32], + max_new: usize, + cancel_probes: Option, + cancel_rounds: Option, + ) -> Result<(Vec, f64, f64, usize), ServeError> { + serve_one(&mut self.stack, prompt, max_new, self.eos, cancel_probes, cancel_rounds) + } + pub(super) fn guard(&self, what: &str) { + guard(self.abort_gib, what); + } + pub(super) fn census(&self) -> Census { + census(self.context.as_ref()) + } + pub(super) fn census_line(&self, tag: &str) { + eprintln!("MEM-CENSUS {tag} {}", serde_json::to_string(&self.census()).unwrap()); + } + /// A prompt of the system text, `user` and `size` tokens of filler of `kind`, ending in the assistant turn. + pub(super) fn prompt(&mut self, user: &str, kind: u8, size: usize) -> Vec { + let mut prompt = self.system.clone(); + prompt.extend(self.tok(user)); + prompt.extend(self.filler(kind, size)); + prompt.extend(self.tok("<|im_end|>\n<|im_start|>assistant\n")); + prompt + } + /// The same, with filler up to a prompt of about `target` tokens. + pub(super) fn prompt_for(&mut self, user: &str, kind: u8, target: usize) -> Vec { + let mut prompt = self.system.clone(); + prompt.extend(self.tok(user)); + let size = target.saturating_sub(prompt.len() + 8); + prompt.extend(self.filler(kind, size)); + prompt.extend(self.tok("<|im_end|>\n<|im_start|>assistant\n")); + prompt + } + fn scenario(&mut self, scenario: &str) { + match scenario { + "inventory" => self.inventory(), + "soak" => self.soak(), + "shed" => self.shed(), + "leak" => self.leak(), + "reader" => self.reader(), + other => panic!("LELEKA_MEM_SCENARIO: inventory | soak | shed | reader | leak, not {other}"), + } + } +} +fn new_mem<'a, 'ctx>( + plan: &Plan, + loaded: &'a Loaded, + stack: OriginalServeStack<'a, 'ctx>, + context: &'a Rc>, +) -> Mem<'a, 'ctx> { + let mut mem = Mem { + stack, + context, + governor: loaded.governor, + tokenizer: &loaded.tokenizer, + eos: loaded.eos, + abort_gib: plan.abort_gib, + max_context: plan.max_context, + rng: Rng(0x5eed_1234_abcd_0042), + system: Vec::new(), + failed: Vec::new(), + }; + let mut system = + mem.tok("<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search.\n"); + system.extend(mem.filler(0, 2000)); + system.extend(mem.tok("<|im_end|>\n")); + mem.system = system; + mem +} +/// Opens the stack, takes the idle measurements, runs the scenario and the closing measurements. +fn measure(plan: &Plan, loaded: &Loaded, context: &Rc>) -> Vec { + let config = stack_config(plan); + let stack = match OriginalServeStack::open(&loaded.binding, context.as_ref(), Rc::clone(context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + guard(plan.abort_gib, "after the stack opened"); + let governor = loaded.governor; + governor.sample_now(); + print_report("idle"); + eprintln!("MEM-CENSUS idle {}", serde_json::to_string(&census(context.as_ref())).unwrap()); + // the stack opens in the "plan -> open -> report" order production uses; also the residency of the memfd right now + let swapped = governor.residency_tick(); + eprintln!("MEM-ARCHIVE swapped_bytes={swapped}"); + let mut mem = new_mem(plan, loaded, stack, context); + mem.scenario(&plan.scenario); + guard(plan.abort_gib, "end"); + mem.census_line("end"); + eprintln!("MEM-RESULT scenario={} failed={:?}", plan.scenario, mem.failed); + mem.stack.close().expect("stack cleanup failed"); + mem.failed +} +pub(super) fn run() { + let _ = dbg_el(); + assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); + let plan = Plan::from_env(); + guard(plan.abort_gib, "before the load"); + let loaded = load(&plan); + let budget_gib = loaded.budget_gib; + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device 0 unavailable"); + let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); + crate::memory_governor::check_vram(loaded.governor, context.as_ref(), (budget_gib as u64) << 30) + .unwrap_or_else(|e| panic!("vram refused: {}", e.message)); + let failed = measure(&plan, &loaded, &context); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + assert!(failed.is_empty(), "memory smoke checks failed: {failed:?}"); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_probe.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_probe.rs new file mode 100644 index 00000000..7af75310 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_probe.rs @@ -0,0 +1,46 @@ +//! Model-free probe of the sealed KAR memfd under the governor's residency guard. +use super::*; + +/// One second of the probe: the memfd's swapped bytes, the cost of looking, and the swap counters since the last. +fn probe_second(governor: &Governor, t: u64, last_in: &mut Option<(u64, u64)>) { + let before = std::time::Instant::now(); + let swapped = governor.residency_tick(); + let facts = governor.probe(); + let (swp_in, swp_out) = (facts.pswpin.unwrap_or(0), facts.pswpout.unwrap_or(0)); + let delta = last_in.map(|(i, o)| (swp_in - i, swp_out - o)); + *last_in = Some((swp_in, swp_out)); + eprintln!( + "PROBE t={t} memfd_swapped_mib={} smaps_ms={:.0} avail_mib={} shmem_mib={} swap_used_mib={} \ + pswpin_pswpout_delta={delta:?}", + swapped >> 20, + before.elapsed().as_secs_f64() * 1e3, + facts.effective_available().unwrap_or(0) >> 20, + facts.meminfo.shmem.unwrap_or(0) >> 20, + (facts.meminfo.swap_total.unwrap_or(0) - facts.meminfo.swap_free.unwrap_or(0)) >> 20, + ); + guard(number("LELEKA_MEM_ABORT_GIB", 15) as u64, "probe"); + std::thread::sleep(std::time::Duration::from_secs(1)); +} +pub(super) fn run() { + assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); + let inherited = InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed"); + let governor = crate::memory_governor::install(false, crate::settings::process()).expect("governor"); + let started = std::time::Instant::now(); + let report = crate::memory_governor::guard_archive(governor, &inherited); + eprintln!( + "PROBE guard result: {:?} in {:.1} s", + report.as_ref().map(|_| "ok").map_err(|e| e.message.clone()), + started.elapsed().as_secs_f64() + ); + let secs = number("LELEKA_MEM_PROBE_SECS", 60); + let mut last_in = None; + for t in 0..secs { + probe_second(governor, t as u64, &mut last_in); + } + eprintln!("PROBE report {}", crate::memory_governor::report().unwrap_or_default()); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_reader.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_reader.rs new file mode 100644 index 00000000..9036d92b --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_reader.rs @@ -0,0 +1,130 @@ +//! The reader scenario: decode speed and the memfd's residency while a competing reader streams a big file +//! through the page cache (what the Original did when it read the KAR file next to the memfd): phase A without the +//! reader, B with it, C after. +use super::*; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +/// The knobs of the reader run. +struct Reader { + path: PathBuf, + gib: u64, + n: usize, + new_tokens: usize, +} +impl Reader { + fn from_env() -> Reader { + let path = PathBuf::from(text("LELEKA_MEM_READER_FILE", "")); + assert!(path.is_file(), "LELEKA_MEM_READER_FILE must name a big file"); + let gib = number("LELEKA_MEM_READER_GIB", 40) as u64; + let n = number("LELEKA_MEM_READER_REQS", 6); + let new_tokens = number("LELEKA_MEM_READER_NEW", 96); + Reader { path, gib, n, new_tokens } + } +} +/// Streams the file through the page cache until `gib` GiB were read, the file ends or `stop` is set. +fn spawn_reader( + path: PathBuf, + gib: u64, + stop: Arc, + read_bytes: Arc, +) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + use std::io::Read; + let mut file = std::fs::File::open(path).expect("reader file"); + let mut buf = vec![0u8; 16 << 20]; + while !stop.load(Ordering::Relaxed) && read_bytes.load(Ordering::Relaxed) < gib << 30 { + match file.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(k) => { + read_bytes.fetch_add(k as u64, Ordering::Relaxed); + } + } + } + }) +} +fn print_means(a: &[f64], b: &[f64], c: &[f64]) { + let mean = |v: &[f64]| v.iter().sum::() / v.len().max(1) as f64; + eprintln!( + "MEM-READER decode tok/s mean: A {:.2} B {:.2} C {:.2} (B/A {:.3})", + mean(a), + mean(b), + mean(c), + mean(b) / mean(a).max(1e-9) + ); +} +impl Mem<'_, '_> { + pub(super) fn reader(&mut self) { + let cfg = Reader::from_env(); + let prompt = self.prompt("<|im_start|>user\nExplain.\n", 1, 3000); + NO_STOP.store(true, Ordering::Relaxed); + let (mut a, mut b, mut c) = (Vec::new(), Vec::new(), Vec::new()); + self.reader_phase("A-no-reader", &prompt, &cfg, &mut a, &|| true); + let stop = Arc::new(AtomicBool::new(false)); + let read_bytes = Arc::new(AtomicU64::new(0)); + let reader = spawn_reader(cfg.path.clone(), cfg.gib, stop.clone(), read_bytes.clone()); + // B lasts until the reader has streamed its volume (or finished): a request every ~1-2 s, minutes of + // page-cache churn + let (rb, st, gib) = (read_bytes.clone(), stop.clone(), cfg.gib); + self.reader_phase("B-reader", &prompt, &cfg, &mut b, &move || { + rb.load(Ordering::Relaxed) >= gib << 30 || st.load(Ordering::Relaxed) + }); + stop.store(true, Ordering::Relaxed); + reader.join().expect("reader thread"); + eprintln!( + "MEM-READER the reader streamed {} GiB through the page cache", + read_bytes.load(Ordering::Relaxed) >> 30 + ); + self.reader_phase("C-after", &prompt, &cfg, &mut c, &|| true); + NO_STOP.store(false, Ordering::Relaxed); + print_means(&a, &b, &c); + print_report("reader-end"); + } + fn swap_counters(&self) -> (u64, u64) { + let f = self.governor.probe(); + (f.pswpin.unwrap_or(0), f.pswpout.unwrap_or(0)) + } + fn reader_phase( + &mut self, + label: &str, + prompt: &[u32], + cfg: &Reader, + rates: &mut Vec, + until: &dyn Fn() -> bool, + ) { + for i in 0..usize::MAX { + if i >= cfg.n && until() { + break; + } + if i >= 4 * cfg.n + 400 { + break; + } + self.reader_request(label, prompt, i, cfg.new_tokens, rates); + } + } + fn reader_request(&mut self, label: &str, prompt: &[u32], i: usize, new_tokens: usize, rates: &mut Vec) { + let (in0, out0) = self.swap_counters(); + let mut p = prompt.to_vec(); + p.extend(self.tok(&format!("<|im_start|>user\nvariant {label} {i}\n"))); + let r = self.serve(&p, new_tokens, None, None); + let swapped = self.governor.residency_tick(); + let (in1, out1) = self.swap_counters(); + self.guard("reader"); + match r { + Ok((out, prompt_ms, decode_ms, _)) => { + let rate = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 }; + rates.push(rate); + eprintln!( + "MEM-READER phase={label} i={i} prompt_ms={prompt_ms:.0} decode_ms={decode_ms:.0} new={} \ + decode_tok_s={rate:.2} memfd_swapped_mib={} pswpin+={} pswpout+={} avail_mib={}", + out.len(), + swapped >> 20, + in1 - in0, + out1 - out0, + crate::conversation::memory::available_memory().unwrap_or(0) >> 20 + ); + } + Err(e) => self.failed.push(format!("reader {label} {i}: {e:?}")), + } + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_shed.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_shed.rs new file mode 100644 index 00000000..6860327a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_shed.rs @@ -0,0 +1,180 @@ +//! The shed scenario: the prefix cache evicted, requests refused and the budget restored, driven by floors moved +//! next to the memory the host has now, so the real limit is never approached. +use super::*; +use std::time::Duration; + +fn available() -> u64 { + crate::conversation::memory::available_memory().unwrap_or(0) +} +impl Mem<'_, '_> { + fn shape(&self, n: usize) -> RequestShape { + RequestShape { prompt_tokens: n as u64, max_new_tokens: 8, max_context: self.max_context as u64 } + } + pub(super) fn shed(&mut self) { + let ballast_mib = self.shed_floors(); + self.shed_grow(); + let prompt = self.shed_evict(); + let ballast = self.shed_ballast(ballast_mib); + self.shed_reject(&prompt); + // 3. the pressure is over: three calm samples per step, budget restored, requests served and the cache refills + drop(ballast); + self.shed_recover(&prompt); + } + /// Moves the floors next to the memory the host has now; the real limits are never approached. Returns the + /// ballast to push the host with. + fn shed_floors(&self) -> usize { + let a0 = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); + let soft_below = (number("LELEKA_MEM_SOFT_BELOW_MIB", 1536) as u64) << 20; + let hard_below = (number("LELEKA_MEM_HARD_BELOW_MIB", 3072) as u64) << 20; + let ballast_mib = number("LELEKA_MEM_BALLAST_MIB", 3584); + assert!(a0 >= self.abort_gib << 30, "start with more than the guard"); + self.governor.set_floors(a0 - soft_below, a0 - hard_below).expect("floors"); + eprintln!( + "MEM-SHED start available_mib={} soft_mib={} hard_mib={}", + a0 >> 20, + (a0 - soft_below) >> 20, + (a0 - hard_below) >> 20 + ); + ballast_mib + } + /// 1. grow the prefix cache until the soft floor is crossed (or the budget is full) + fn shed_grow(&mut self) { + let mut max_used = 0usize; + let mut shed_seen = false; + for i in 0..number("LELEKA_MEM_FILL_MAX", 60) { + let Some((used, level)) = self.grow_once(i) else { break }; + max_used = max_used.max(used); + if level != Level::Normal { + shed_seen = true; + break; + } + } + if !shed_seen { + eprintln!( + "MEM-SHED the prefix cache reached its budget ({} MiB) without crossing the soft floor", + max_used >> 20 + ); + self.failed.push("shed level never reached by cache growth".into()); + } + } + /// One more session in the prefix cache; its bytes in use and the level afterwards, or None when the + /// request failed. + fn grow_once(&mut self, i: usize) -> Option<(usize, Level)> { + let prompt = self.prompt(&format!("<|im_start|>user\nShed {i}.\n"), (i % 2) as u8, 20_000); + if let Err(e) = self.serve(&prompt, 4, None, None) { + self.failed.push(format!("grow {i}: {e:?}")); + return None; + } + self.governor.sample_now(); + let used = self.stack.prefix_bytes(); + let level = self.governor.level(); + eprintln!( + "MEM-SHED grow i={i} level={} prefix_used_mib={} available_mib={}", + level.as_str(), + used >> 20, + available() >> 20 + ); + self.guard("growing the prefix cache"); + Some((used, level)) + } + /// The next request applies the directive: the cache evicts before it starts. Returns that prompt. + fn shed_evict(&mut self) -> Vec { + let prompt = self.prompt("<|im_start|>user\nafter shed\n", 0, 3000); + if self.governor.admit(&self.shape(prompt.len())) != Admission::Admit { + self.failed.push("shedding must still admit requests".into()); + } + let used_before = self.stack.prefix_bytes(); + let (avail_before, rss_before) = (available(), self.census().rss); + let _ = self.serve(&prompt, 4, None, None); + let used_after = self.stack.prefix_bytes(); + let (avail_after, rss_after) = (available(), self.census().rss); + eprintln!( + "MEM-SHED evicted: prefix {} MiB -> {} MiB (level {}); MemAvailable {} -> {} MiB, RSS {} -> {} MiB", + used_before >> 20, + used_after >> 20, + self.governor.level().as_str(), + avail_before >> 20, + avail_after >> 20, + rss_before >> 20, + rss_after >> 20 + ); + if used_after >= used_before && used_before > 0 { + self.failed.push("the prefix cache did not shrink under shed".into()); + } + prompt + } + /// 2. ballast pushes the host below the hard floor + fn shed_ballast(&self, ballast_mib: usize) -> Vec { + let mut ballast: Vec = Vec::new(); + let step = 256usize << 20; + while ballast.len() < ballast_mib << 20 && self.governor.level() != Level::Reject { + let at = ballast.len(); + ballast.resize(at + step, 1); + // touch every page so the allocation is resident + for i in (at..ballast.len()).step_by(4096) { + ballast[i] = (i >> 12) as u8; + } + self.governor.sample_now(); + self.guard("ballast"); + } + eprintln!( + "MEM-SHED ballast {} MiB level={} available_mib={}", + ballast.len() >> 20, + self.governor.level().as_str(), + available() >> 20 + ); + ballast + } + /// Requests are refused and everything is shed. + fn shed_reject(&mut self, prompt: &[u32]) { + match self.governor.admit(&self.shape(prompt.len())) { + Admission::Refuse(r) if r.status == 503 && r.code == "memory_pressure" => { + eprintln!("MEM-SHED refused: {} retry_after={}s", r.message, r.retry_after_secs) + } + other => self.failed.push(format!("no 503 at the hard floor: {other:?}")), + } + let _ = self.serve(prompt, 4, None, None); + if self.stack.prefix_bytes() != 0 { + self.failed.push(format!("the prefix cache still holds {} MiB at reject", self.stack.prefix_bytes() >> 20)); + } + print_report("reject"); + } + /// The baseline drifted while the test ran (mapped expert pages warmed up): re-centre the floors on what the + /// host has now, so the hysteresis margin (1 GiB above the soft floor) can be met; the recovery path itself is + /// what is under test. + fn recenter_floors(&self) { + std::thread::sleep(Duration::from_millis(500)); + let a_now = crate::conversation::memory::available_memory().expect("MemAvailable unknown"); + self.governor.set_floors(a_now - (2048u64 << 20), a_now - (3584u64 << 20)).expect("floors"); + } + fn shed_recover(&mut self, prompt: &[u32]) { + self.recenter_floors(); + for i in 0..14 { + std::thread::sleep(Duration::from_millis(300)); + self.governor.sample_now(); + if self.governor.level() == Level::Normal { + eprintln!("MEM-SHED recovered after {} samples", i + 1); + break; + } + } + if self.governor.level() != Level::Normal { + let level = self.governor.level().as_str(); + self.failed.push(format!("level stayed {level} after the ballast was freed")); + } + if self.governor.admit(&self.shape(prompt.len())) != Admission::Admit { + self.failed.push("requests are not admitted again after recovery".into()); + } + let r = self.serve(prompt, 4, None, None); + let restored = self.stack.prefix_budget_bytes(); + eprintln!( + "MEM-SHED after recovery: served={} prefix_budget_mib={} prefix_used_mib={}", + r.is_ok(), + restored >> 20, + self.stack.prefix_bytes() >> 20 + ); + if r.is_err() || restored < (1 << 30) { + self.failed.push("the prefix budget was not restored".into()); + } + print_report("recovered"); + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_soak.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_soak.rs new file mode 100644 index 00000000..d819d1a5 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_soak.rs @@ -0,0 +1,102 @@ +//! The soak scenario: mixed requests (cancels, refusals, long prompts, prefix-cache churn) judged flat after warm-up. +use super::traffic::Tally; +use super::*; + +/// The knobs of the soak. +struct Soak { + requests: usize, + big: Vec, + big_every: usize, + sessions_n: usize, + warmup: usize, +} +impl Soak { + fn from_env() -> Soak { + Soak { + requests: number("LELEKA_MEM_REQUESTS", 220), + big: list("LELEKA_MEM_BIG", "100000,180000"), + big_every: number("LELEKA_MEM_BIG_EVERY", 55), + sessions_n: number("LELEKA_MEM_SESSIONS", 6), + warmup: number("LELEKA_MEM_WARMUP", 30), + } + } + fn kind(&self, i: usize) -> &'static str { + if i > 0 && i % self.big_every == 0 { + "big" + } else if i % 11 == 7 { + "overlong" + } else if i % 7 == 3 { + "cancel" + } else { + "normal" + } + } +} +impl Mem<'_, '_> { + pub(super) fn soak(&mut self) { + let plan = Soak::from_env(); + let mut sessions = self.sessions(plan.sessions_n); + let mut series: Vec = Vec::new(); + let mut tally = Tally::default(); + let started = std::time::Instant::now(); + for i in 0..plan.requests { + let s = (self.rng.next() as usize) % plan.sessions_n; + let kind = plan.kind(i); + self.soak_request(&plan, kind, i, &mut sessions[s], &mut tally); + if self.stack.health().is_some() { + self.failed.push(format!("stack lost an owner at request {i}")); + break; + } + self.guard("soak"); + if i % 5 == 4 || kind == "big" { + self.governor.sample_now(); + series.push(self.census()); + } + if i % 20 == 19 { + self.print_progress(i, &tally, &series, started); + } + } + self.soak_result(&plan, &series, &tally); + } + fn soak_request(&mut self, plan: &Soak, kind: &str, i: usize, session: &mut Vec, t: &mut Tally) { + match kind { + "overlong" => self.overlong(i, &mut t.refused, true), + "big" => { + let target = plan.big[t.bigs % plan.big.len()]; + t.bigs += 1; + self.big(i, target, &mut t.served); + } + _ => { + let cap = 60_000.min(self.max_context.saturating_sub(6000)); + self.session_turn(kind, i, session, cap, t); + } + } + } + fn print_progress(&self, i: usize, t: &Tally, series: &[Census], started: std::time::Instant) { + eprintln!( + "MEM-SOAK i={} served={} cancelled={} refused={} big={} elapsed_s={:.0} census={} prefix={}", + i + 1, + t.served, + t.cancelled, + t.refused, + t.bigs, + started.elapsed().as_secs_f64(), + serde_json::to_string(series.last().unwrap()).unwrap(), + self.stack.prefix_metrics().unwrap_or_default() + ); + } + fn soak_result(&mut self, plan: &Soak, series: &[Census], t: &Tally) { + // the big prompts are not warm-up noise but they are rare: judge from the first quarter after warm-up + let tolerances = Tolerances { rss: 512 << 20, ..Tolerances::default() }; + let flat = check_flat(series, plan.warmup / 5, &tolerances); + eprintln!( + "MEM-SOAK-RESULT served={} cancelled={} refused={} big={}\n{flat}", + t.served, t.cancelled, t.refused, t.bigs + ); + eprintln!("MEM-SOAK-SERIES {}", serde_json::to_string(series).unwrap()); + print_report("soak-end"); + if !flat.ok { + self.failed.push("process memory not flat after warm-up".into()); + } + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_traffic.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_traffic.rs new file mode 100644 index 00000000..01ecbc36 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke_traffic.rs @@ -0,0 +1,103 @@ +//! The mixed traffic of the soak and the leak scenarios: sessions that grow by tool turns, big prompts, +//! unshared prompts, cancels and requests the governor must refuse. +use super::*; + +/// What the traffic has done so far. +#[derive(Default)] +pub(super) struct Tally { + pub(super) served: usize, + pub(super) cancelled: usize, + pub(super) refused: usize, + pub(super) bigs: usize, + pub(super) fresh: usize, +} +impl Mem<'_, '_> { + /// `n` sessions that share the system text and each start their own task. + pub(super) fn sessions(&mut self, n: usize) -> Vec> { + (0..n) + .map(|s| { + let mut p = self.system.clone(); + p.extend(self.tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests.\n"))); + p.extend(self.filler(1, 1500)); + p + }) + .collect() + } + /// A request that cannot fit the pinned K/V image: refused up front, nothing allocated; with `serve` the + /// engine is also asked and must refuse it as well. + pub(super) fn overlong(&mut self, i: usize, refused: &mut usize, serve: bool) { + let prompt_len = self.max_context + 16; + let shape = + RequestShape { prompt_tokens: prompt_len as u64, max_new_tokens: 16, max_context: self.max_context as u64 }; + match self.governor.admit(&shape) { + Admission::Refuse(r) if r.status == 400 => *refused += 1, + other => self.failed.push(format!("overlong {i} not refused with 400: {other:?}")), + } + if serve { + let prompt = vec![1u32; prompt_len]; + match self.serve(&prompt, 16, None, None) { + Err(ServeError::Refused(_)) => {} + other => self.failed.push(format!("overlong {i} reached the engine: {:?}", other.map(|o| o.0.len()))), + } + } + } + /// A prompt of about `target` tokens. + pub(super) fn big(&mut self, i: usize, target: usize, served: &mut usize) { + let prompt = self.prompt_for(&format!("<|im_start|>user\nBig {i}.\n"), 1, target); + match self.serve(&prompt, 8, None, None) { + Ok(_) => *served += 1, + Err(e) => self.failed.push(format!("big {i}: {e:?}")), + } + } + /// An unshared session: its own task text, 8k..30k tokens, never seen again. + pub(super) fn fresh(&mut self, req: usize, served: &mut usize) { + let size = 8000 + (self.rng.next() as usize % 22_000); + let mut prompt = self.tok(&format!( + "<|im_start|>system\nIndependent agent {req}.<|im_end|>\n<|im_start|>user\nUnshared task {req}.\n" + )); + let size = size.min(self.max_context.saturating_sub(2000)); + prompt.extend(self.filler((req % 2) as u8, size)); + prompt.extend(self.tok("<|im_end|>\n<|im_start|>assistant\n")); + match self.serve(&prompt, 12, None, None) { + Ok(_) => *served += 1, + Err(e) => self.failed.push(format!("fresh {req}: {e:?}")), + } + } + /// A cancelled request (in the prefill probes or after the first round); a cancel that did not happen is fine. + fn cancel_request(&mut self, i: usize, prompt: &[u32], cancelled: &mut usize) -> Result<(), ServeError> { + let r = if i % 2 == 0 { self.serve(prompt, 32, Some(3), None) } else { self.serve(prompt, 64, None, Some(1)) }; + match r { + Err(ServeError::Cancelled) => { + *cancelled += 1; + Ok(()) + } + Ok(_) => Ok(()), + Err(e) => Err(e), + } + } + /// The next turn of a session: a tool call and its response; `cancel` cuts the request short. + pub(super) fn session_turn(&mut self, kind: &str, i: usize, session: &mut Vec, cap: usize, t: &mut Tally) { + let grow = 300 + (self.rng.unit().powi(3) * 9000.0) as usize; + let mut next = std::mem::take(session); + next.extend(self.tok( + "shell {\"cmd\": \"cargo test\"}<|im_end|>\n<|im_start|>user\n\n", + )); + next.extend(self.filler((i % 2) as u8, grow)); + next.extend(self.tok("\n<|im_end|>\n<|im_start|>assistant\n")); + if next.len() > cap { + // keep sessions bounded: start over with a fresh task (prefix churn) + next = self.system.clone(); + next.extend(self.tok(&format!("<|im_start|>user\nTask {i}.\n"))); + next.extend(self.filler(1, 1500)); + } + let result = if kind == "cancel" { + self.cancel_request(i, &next, &mut t.cancelled) + } else { + self.serve(&next, 12, None, None).map(|_| t.served += 1) + }; + if let Err(e) = result { + self.failed.push(format!("{kind} {i}: {e:?}")); + } + *session = next; + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs index 37906aa7..fbbc0f4a 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs @@ -70,6 +70,23 @@ fn rss_mib() -> u64 { .map_or(0, |kb| kb >> 10) } +/// One line of deterministic code-like text. +fn code_line(a: u64, b: u64, c: u64, line: usize) -> String { + let first = format!(" let v{b} = table[{a}].checked_add({c}).ok_or(Error::Overflow)?; // step {line}\n"); + let second = format!(" if v{b} > limit_{a} {{ return Err(Error::Range({b})); }}\n"); + first + &second +} +/// One line of deterministic log-like text. +fn log_line(a: u64, b: u64, c: u64, line: usize) -> String { + format!( + "[{:02}:{:02}:{:02}] worker-{b} ok job={c} bytes={} path=src/mod_{a}/file_{line}.rs\n", + a % 24, + b % 60, + c % 60, + a * 31 + c + ) +} + /// Deterministic text of `kind` encoded to exactly `tokens` ids (code-like or log-like lines). fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec { let mut ids: Vec = Vec::with_capacity(tokens + 256); @@ -79,13 +96,8 @@ fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec< for _ in 0..24 { let (a, b, c) = (rng.next() % 997, rng.next() % 64, rng.next() % 9973); match kind { - 0 => chunk.push_str(&format!( - " let v{b} = table[{a}].checked_add({c}).ok_or(Error::Overflow)?; // step {line}\n if v{b} > limit_{a} {{ return Err(Error::Range({b})); }}\n" - )), - _ => chunk.push_str(&format!( - "[{:02}:{:02}:{:02}] worker-{b} ok job={c} bytes={} path=src/mod_{a}/file_{line}.rs\n", - a % 24, b % 60, c % 60, a * 31 + c - )), + 0 => chunk.push_str(&code_line(a, b, c, line)), + _ => chunk.push_str(&log_line(a, b, c, line)), } line += 1; } @@ -111,6 +123,46 @@ struct Served { reused: usize, } +/// The clock, the committed rounds and the cancel probes of one request. +struct Watch { + started: std::time::Instant, + first: std::cell::Cell>, + rounds: std::cell::Cell, + probes: std::cell::Cell, +} +impl Watch { + fn new() -> Watch { + Watch { + started: std::time::Instant::now(), + first: std::cell::Cell::new(None), + rounds: std::cell::Cell::new(0), + probes: std::cell::Cell::new(0), + } + } + fn on_round(&self) { + if self.first.get().is_none() { + self.first.set(Some(self.started.elapsed().as_secs_f64() * 1e3)); + } + self.rounds.set(self.rounds.get() + 1); + } + fn should_cancel(&self, cancel_probes: Option, cancel_rounds: Option) -> bool { + self.probes.set(self.probes.get() + 1); + cancel_probes.is_some_and(|n| self.probes.get() >= n) || cancel_rounds.is_some_and(|n| self.rounds.get() >= n) + } +} + +fn served_from(stack: &OriginalServeStack<'_, '_>, watch: &Watch, tokens: Vec) -> Served { + let (prompt_ms, decode_ms) = stack.last_timing(); + Served { + tokens, + ttft_ms: watch.first.get().unwrap_or(f64::NAN), + total_ms: watch.started.elapsed().as_secs_f64() * 1e3, + prompt_ms, + decode_ms, + reused: stack.reused_tokens(), + } +} + fn serve_one( stack: &mut OriginalServeStack<'_, '_>, prompt: &[u32], @@ -121,364 +173,34 @@ fn serve_one( ) -> Result { let request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, 0.0, vec![eos as i32]); - let started = std::time::Instant::now(); - let first = std::cell::Cell::new(None::); - let rounds = std::cell::Cell::new(0usize); - let probes = std::cell::Cell::new(0usize); + let watch = Watch::new(); let mut tokens = Vec::new(); let outcome = stack.serve( &request, &mut |round| { - if first.get().is_none() { - first.set(Some(started.elapsed().as_secs_f64() * 1e3)); - } - rounds.set(rounds.get() + 1); + watch.on_round(); tokens.extend_from_slice(round); Ok(()) }, - &mut || { - probes.set(probes.get() + 1); - cancel_probes.is_some_and(|n| probes.get() >= n) || cancel_rounds.is_some_and(|n| rounds.get() >= n) - }, + &mut || watch.should_cancel(cancel_probes, cancel_rounds), )?; assert_eq!(outcome.produced, tokens.len()); - let (prompt_ms, decode_ms) = stack.last_timing(); - Ok(Served { - tokens, - ttft_ms: first.get().unwrap_or(f64::NAN), - total_ms: started.elapsed().as_secs_f64() * 1e3, - prompt_ms, - decode_ms, - reused: stack.reused_tokens(), - }) + Ok(served_from(stack, &watch, tokens)) } fn ids(tokens: &[i32]) -> String { tokens.iter().map(|t| t.to_string()).collect::>().join(",") } +#[path = "backend_original_serve_prefix_smoke_extras.rs"] +mod extras; +#[path = "backend_original_serve_prefix_smoke_run.rs"] +mod run; +#[path = "backend_original_serve_prefix_smoke_workload.rs"] +mod workload; + #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; long prompts"] fn original_serve_prefix_cache_smoke() { - let _ = dbg_el(); - assert!(env::var("LELEKA_PFX_SMOKE").is_ok_and(|v| v == "yes"), "explicit prefix-cache smoke opt-in required"); - let mode = text("LELEKA_PFX_MODE", "prefix"); - let scenario = text("LELEKA_PFX_SCENARIO", "grid"); - let verify = text("LELEKA_PFX_VERIFY", "none"); - let (shared_n, sessions_n, turns_n) = - (number("LELEKA_PFX_SHARED", 8000), number("LELEKA_PFX_SESSIONS", 3), number("LELEKA_PFX_TURNS", 3)); - let (start_n, grow_n, end_n) = - (number("LELEKA_PFX_START", 2000), number("LELEKA_PFX_GROW", 2500), number("LELEKA_PFX_END", 40_000)); - let max_new = number("LELEKA_PFX_MAX_NEW", 16); - let capacity = number("LELEKA_PFX_CAPACITY", 2048); - let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); - let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); - - let laptop = env::var("LELEKA_PFX_LAPTOP").is_ok_and(|v| v == "yes"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); - let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") { - Some(path) if laptop => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) - .expect("read-only KAR admission failed"), - _ => { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") - } - }; - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - if laptop { - binding.load_mapped_expert_source().expect("mapped expert source load failed"); - if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { - let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); - leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); - eprintln!("PFX config: process geometry {cells} cells (experimental)"); - } - } else { - binding.load_resident_expert_source().expect("resident expert source load failed"); - } - let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", if laptop { 15 } else { 28 }); - let driver = Driver::load().expect("CUDA driver load failed"); - let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - - // ---- the workload (identical for every mode) ---- - let mut rng = Rng(0x5eed_1234_abcd_0001); - let tok = |s: &str, special: bool| tokenizer.encode(s, special).expect("tokenization failed"); - let t0 = std::time::Instant::now(); - let mut system = tok( - "<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search. Repository notes follow.\n", - true, - ); - system.extend(filler(&tokenizer, &mut rng, 0, shared_n.saturating_sub(system.len() + 4))); - system.extend(tok("<|im_end|>\n", true)); - let mut sessions: Vec = Vec::new(); - for s in 0..sessions_n { - let mut prompt = system.clone(); - prompt.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests in module {s}.\n"), true)); - prompt.extend(filler(&tokenizer, &mut rng, 1, start_n)); - prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n", true)); - sessions.push(Session { prompt, turn: 0 }); - } - // the order of requests and the size each turn adds - let mut order: Vec = Vec::new(); - let mut grow: Vec> = vec![Vec::new(); sessions_n]; - if scenario == "agent" { - // `turns_n` requests per session, random interleaving; tool outputs are heavy tailed and scaled so a session's - // last request is about `end_n` tokens long - let first_len = sessions[0].prompt.len(); - let total_grow = end_n.saturating_sub(first_len); - for g in grow.iter_mut() { - let raw: Vec = (1..turns_n).map(|_| 0.05 + rng.unit().powi(3) * 6.0).collect(); - let sum: f64 = raw.iter().sum(); - *g = raw.iter().map(|r| ((r / sum) * total_grow as f64) as usize).map(|x| x.max(64)).collect(); - } - let mut left = vec![turns_n; sessions_n]; - while left.iter().any(|&l| l > 0) { - let s = (rng.next() as usize) % sessions_n; - if left[s] > 0 { - left[s] -= 1; - order.push(s); - } - } - } else { - for g in grow.iter_mut() { - *g = vec![grow_n; turns_n.saturating_sub(1)]; - } - for _ in 0..turns_n { - order.extend(0..sessions_n); - } - } - eprintln!( - "PFX workload: mode={mode} scenario={scenario} sessions={sessions_n} turns={turns_n} shared={} first_prompt={} requests={} built_in={:.1}s", - system.len(), - sessions[0].prompt.len(), - order.len(), - t0.elapsed().as_secs_f64() - ); - - // ---- the stack ---- - let mut config = StackConfig::new(max_context as i64); - config.capacity = capacity; - config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); - config.kv_resident = resident; - if laptop { - config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32; - } - match mode.as_str() { - "prefix" => { - let budget = match text("LELEKA_PFX_MIB", "auto").as_str() { - "auto" => PrefixBudget::Auto, - other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_PFX_MIB: auto or MiB") << 20), - }; - config.prefix = Some(PrefixConfig { - budget, - block_tokens: number("LELEKA_PFX_BLOCK", 0), - laptop, - ..PrefixConfig::auto() - }); - } - "legacy" => {} - "off" => config.conversation = None, - other => panic!("LELEKA_PFX_MODE: legacy | prefix | off, not {other}"), - } - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - eprintln!( - "PFX stack: capacity={capacity} kv_resident={resident} max_context={max_context} expert tier {:?}", - config.expert_tier - ); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - eprintln!("PFX host memory after open: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); - - // ---- serve ---- - let mut failed: Vec = Vec::new(); - let mut decode_rates: Vec = Vec::new(); - let mut reused_total = 0usize; - let mut prompt_total = 0usize; - let mut ttft_sum = 0.0; - let last_of: Vec = (0..sessions_n).map(|s| order.iter().rposition(|&o| o == s).unwrap_or(0)).collect(); - // the previous prompt of each session, to attribute a request's tokens - for (i, &s) in order.iter().enumerate() { - if sessions[s].turn > 0 { - // the agent's next step: the (synthetic) reply, then a tool output - let t = sessions[s].turn; - let kind = (t % 2) as u8; - let size = grow[s][t - 1]; - let mut next = std::mem::take(&mut sessions[s].prompt); - next.extend(tok(&format!("shell {{\"cmd\": \"cargo test -p mod_{s} --lib\"}}<|im_end|>\n<|im_start|>user\n\n"), true)); - next.extend(filler(&tokenizer, &mut rng, kind, size)); - next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); - sessions[s].prompt = next; - } - sessions[s].turn += 1; - let prompt = sessions[s].prompt.clone(); - let served = serve_one(&mut stack, &prompt, max_new, eos, None, None) - .unwrap_or_else(|e| panic!("PFX request {i} failed: {e:?} health={:?}", stack.health())); - assert_eq!(stack.health(), None); - let n = prompt.len(); - let read = (n - 1).saturating_sub(served.reused); - let rate = if served.decode_ms > 0.0 { served.tokens.len() as f64 * 1e3 / served.decode_ms } else { 0.0 }; - decode_rates.push(rate); - reused_total += served.reused; - prompt_total += n - 1; - ttft_sum += served.ttft_ms; - eprintln!( - "PFX req={i} session={} turn={} n={n} reused={} read={read} ttft_ms={:.1} prompt_ms={:.1} decode_ms={:.1} decode_tok_s={rate:.1} total_ms={:.1} avail_mib={} rss_mib={} out={}", - (b'A' + s as u8) as char, - sessions[s].turn, - served.reused, - served.ttft_ms, - served.prompt_ms, - served.decode_ms, - served.total_ms, - mem_available_mib(), - rss_mib(), - ids(&served.tokens) - ); - let wants_check = match verify.as_str() { - "every" => served.reused > 0, - "last" => i == last_of[s], - _ => false, - }; - if wants_check && mode == "prefix" { - stack.prefix_bypass(true); - let full = serve_one(&mut stack, &prompt, max_new, eos, None, None) - .unwrap_or_else(|e| panic!("PFX verify {i} failed: {e:?} health={:?}", stack.health())); - stack.prefix_bypass(false); - let equal = full.tokens == served.tokens; - eprintln!( - "PFX-VERIFY req={i} session={} n={n} cached_reused={} equal={equal} ttft_cached_ms={:.1} ttft_full_ms={:.1} full_out={}", - (b'A' + s as u8) as char, - served.reused, - served.ttft_ms, - full.ttft_ms, - ids(&full.tokens) - ); - if !equal { - failed.push(format!("verify req {i}")); - // localise: where the ids first differ, and whether each arm is repeatable on its own - let at = served.tokens.iter().zip(&full.tokens).position(|(a, b)| a != b); - let cached_again = - serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat cached read failed"); - stack.prefix_bypass(true); - let full_again = - serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat full read failed"); - stack.prefix_bypass(false); - eprintln!( - "PFX-VERIFY-DIAG req={i} first_difference_at={at:?} cached_repeat_equal_cached={} (reused {}) full_repeat_equal_full={} cached_repeat_equal_full={}", - cached_again.tokens == served.tokens, - cached_again.reused, - full_again.tokens == full.tokens, - cached_again.tokens == full.tokens - ); - } - } - if let Some(line) = stack.prefix_metrics() { - eprintln!("PFX-STATS after req={i}: {line}"); - } - } - eprintln!( - "PFX-SUMMARY mode={mode} scenario={scenario} requests={} prompt_tokens={prompt_total} reused_tokens={reused_total} read_tokens={} reuse_pct={:.1} mean_ttft_ms={:.1} mean_decode_tok_s={:.2}", - order.len(), - prompt_total - reused_total, - 100.0 * reused_total as f64 / prompt_total.max(1) as f64, - ttft_sum / order.len().max(1) as f64, - decode_rates.iter().sum::() / decode_rates.len().max(1) as f64 - ); - - // ---- the pool protocol on the live cache ---- - if let Some(summary) = stack.prefix_summary(512) { - let json = serde_json::to_string(&summary).expect("summary json"); - eprintln!( - "PFX-POOL summary: namespace={} nodes={} blocks={} heads={} json_bytes={} truncated={}", - summary.namespace, - summary.nodes, - summary.blocks, - summary.heads.len(), - json.len(), - summary.truncated - ); - for s in 0..sessions_n { - let chain = crate::prefix_cache::chain( - &sessions[s].prompt.iter().map(|&t| t as i32).collect::>(), - summary.block_tokens as usize, - ); - let started = std::time::Instant::now(); - let from_summary = summary.match_tokens(&chain); - let query = stack.prefix_match(&chain).map_or(0, |m| m.cached_tokens); - eprintln!( - "PFX-POOL match session={} prompt={} blocks_hashed={} summary_match={from_summary} query_match={query} us={:.0}", - (b'A' + s as u8) as char, - sessions[s].prompt.len(), - chain.len(), - started.elapsed().as_secs_f64() * 1e6 - ); - } - } - - // ---- cancellation safety ---- - if env::var("LELEKA_PFX_CANCEL").is_ok_and(|v| v == "yes") && mode == "prefix" { - let s = 0usize; - let mut next = sessions[s].prompt.clone(); - next.extend(tok( - "shell {\"cmd\": \"ls\"}<|im_end|>\n<|im_start|>user\n\n", - true, - )); - next.extend(filler(&tokenizer, &mut rng, 1, 3 * capacity.min(2048))); - next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); - let cancelled_prefill = serve_one(&mut stack, &next, max_new, eos, Some(3), None); - let ok1 = matches!(cancelled_prefill, Err(ServeError::Cancelled)) && stack.health().is_none(); - eprintln!("PFX-CANCEL prefill cancelled={ok1}"); - let cancelled_decode = serve_one(&mut stack, &next, 64, eos, None, Some(1)); - let ok2 = matches!(cancelled_decode, Err(ServeError::Cancelled)) && stack.health().is_none(); - eprintln!("PFX-CANCEL decode cancelled={ok2}"); - let after = serve_one(&mut stack, &next, max_new, eos, None, None).expect("request after cancellation failed"); - stack.prefix_bypass(true); - let full = serve_one(&mut stack, &next, max_new, eos, None, None).expect("verification read failed"); - stack.prefix_bypass(false); - let equal = after.tokens == full.tokens; - eprintln!("PFX-CANCEL after reused={} equal_full={equal} out={}", after.reused, ids(&after.tokens)); - if !(ok1 && ok2 && equal) { - failed.push("cancel".into()); - } - // a switch to another session right after a cancelled request - let other = sessions[1 % sessions_n].prompt.clone(); - let switched = - serve_one(&mut stack, &other, max_new, eos, None, None).expect("switch after cancellation failed"); - eprintln!("PFX-CANCEL switch reused={} out={}", switched.reused, ids(&switched.tokens)); - } - if let Some(line) = stack.prefix_metrics() { - eprintln!("PFX-FINAL {line}"); - } - eprintln!("PFX host memory at end: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); - eprintln!("PFX-RESULT failed={failed:?}"); - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); - assert!(failed.is_empty(), "prefix-cache checks failed: {failed:?}"); + run::run(); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_extras.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_extras.rs new file mode 100644 index 00000000..79c77d7b --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_extras.rs @@ -0,0 +1,190 @@ +//! What the prefix-cache smoke does around the served requests: the per-request accounting, the verification +//! against a full read, the summary, the pool protocol on the live cache and the cancellation checks. +use super::run::Pfx; +use super::*; + +/// What the served requests added up to. +#[derive(Default)] +pub(super) struct Tally { + decode_rates: Vec, + reused_total: usize, + prompt_total: usize, + ttft_sum: f64, +} +/// The letter of session `s`. +fn letter(s: usize) -> char { + (b'A' + s as u8) as char +} +impl Pfx<'_, '_> { + /// Counts request `i` of session `s` and prints its `PFX` line. + pub(super) fn account(&mut self, i: usize, s: usize, prompt: &[u32], served: &Served) { + let n = prompt.len(); + let read = (n - 1).saturating_sub(served.reused); + let rate = if served.decode_ms > 0.0 { served.tokens.len() as f64 * 1e3 / served.decode_ms } else { 0.0 }; + let t = &mut self.tally; + t.decode_rates.push(rate); + t.reused_total += served.reused; + t.prompt_total += n - 1; + t.ttft_sum += served.ttft_ms; + eprintln!( + "PFX req={i} session={} turn={} n={n} reused={} read={read} ttft_ms={:.1} prompt_ms={:.1} \ + decode_ms={:.1} decode_tok_s={rate:.1} total_ms={:.1} avail_mib={} rss_mib={} out={}", + letter(s), + self.w.sessions[s].turn, + served.reused, + served.ttft_ms, + served.prompt_ms, + served.decode_ms, + served.total_ms, + mem_available_mib(), + rss_mib(), + ids(&served.tokens) + ); + } + /// Reads the same prompt again with the cache bypassed (a full read on the same chunk grid): the greedy ids + /// must be identical. + pub(super) fn verify(&mut self, i: usize, s: usize, prompt: &[u32], served: &Served, last: usize) { + let wants_check = match self.plan.verify.as_str() { + "every" => served.reused > 0, + "last" => i == last, + _ => false, + }; + if !(wants_check && self.plan.mode == "prefix") { + return; + } + self.stack.prefix_bypass(true); + let full = self + .serve(prompt, self.plan.max_new, None, None) + .unwrap_or_else(|e| panic!("PFX verify {i} failed: {e:?} health={:?}", self.stack.health())); + self.stack.prefix_bypass(false); + let equal = full.tokens == served.tokens; + eprintln!( + "PFX-VERIFY req={i} session={} n={} cached_reused={} equal={equal} ttft_cached_ms={:.1} \ + ttft_full_ms={:.1} full_out={}", + letter(s), + prompt.len(), + served.reused, + served.ttft_ms, + full.ttft_ms, + ids(&full.tokens) + ); + if !equal { + self.failed.push(format!("verify req {i}")); + self.diagnose(i, prompt, served, &full); + } + } + /// Localises a mismatch: where the ids first differ, and whether each arm is repeatable on its own. + fn diagnose(&mut self, i: usize, prompt: &[u32], served: &Served, full: &Served) { + let max_new = self.plan.max_new; + let at = served.tokens.iter().zip(&full.tokens).position(|(a, b)| a != b); + let cached_again = self.serve(prompt, max_new, None, None).expect("repeat cached read failed"); + self.stack.prefix_bypass(true); + let full_again = self.serve(prompt, max_new, None, None).expect("repeat full read failed"); + self.stack.prefix_bypass(false); + eprintln!( + "PFX-VERIFY-DIAG req={i} first_difference_at={at:?} cached_repeat_equal_cached={} (reused {}) \ + full_repeat_equal_full={} cached_repeat_equal_full={}", + cached_again.tokens == served.tokens, + cached_again.reused, + full_again.tokens == full.tokens, + cached_again.tokens == full.tokens + ); + } + pub(super) fn summary(&self) { + let t = &self.tally; + eprintln!( + "PFX-SUMMARY mode={} scenario={} requests={} prompt_tokens={} reused_tokens={} read_tokens={} \ + reuse_pct={:.1} mean_ttft_ms={:.1} mean_decode_tok_s={:.2}", + self.plan.mode, + self.plan.scenario, + self.w.order.len(), + t.prompt_total, + t.reused_total, + t.prompt_total - t.reused_total, + 100.0 * t.reused_total as f64 / t.prompt_total.max(1) as f64, + t.ttft_sum / self.w.order.len().max(1) as f64, + t.decode_rates.iter().sum::() / t.decode_rates.len().max(1) as f64 + ); + } + /// The pool protocol on the live cache. + pub(super) fn pool_protocol(&mut self) { + let Some(summary) = self.stack.prefix_summary(512) else { return }; + let json = serde_json::to_string(&summary).expect("summary json"); + eprintln!( + "PFX-POOL summary: namespace={} nodes={} blocks={} heads={} json_bytes={} truncated={}", + summary.namespace, + summary.nodes, + summary.blocks, + summary.heads.len(), + json.len(), + summary.truncated + ); + for s in 0..self.plan.sessions_n { + self.pool_match(s, &summary); + } + } + fn pool_match(&mut self, s: usize, summary: &crate::prefix_cache::PrefixSummary) { + let prompt = &self.w.sessions[s].prompt; + let chain = crate::prefix_cache::chain( + &prompt.iter().map(|&t| t as i32).collect::>(), + summary.block_tokens as usize, + ); + let started = std::time::Instant::now(); + let from_summary = summary.match_tokens(&chain); + let query = self.stack.prefix_match(&chain).map_or(0, |m| m.cached_tokens); + eprintln!( + "PFX-POOL match session={} prompt={} blocks_hashed={} summary_match={from_summary} \ + query_match={query} us={:.0}", + letter(s), + prompt.len(), + chain.len(), + started.elapsed().as_secs_f64() * 1e6 + ); + } + /// The prompt of the first session plus a tool output of three chunks. + fn cancel_prompt(&mut self) -> Vec { + let mut next = self.w.sessions[0].prompt.clone(); + next.extend(self.tok( + "shell {\"cmd\": \"ls\"}<|im_end|>\n<|im_start|>user\n\n", + true, + )); + next.extend(filler(self.tokenizer, &mut self.w.rng, 1, 3 * self.plan.capacity.min(2048))); + next.extend(self.tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); + next + } + /// Cancellation safety: a request cancelled during the prefill, one cancelled after the first round, then + /// the same prompt served and verified, and a switch to another session. + pub(super) fn cancellation(&mut self) { + if !(env::var("LELEKA_PFX_CANCEL").is_ok_and(|v| v == "yes") && self.plan.mode == "prefix") { + return; + } + let (max_new, eos) = (self.plan.max_new, self.eos); + let next = self.cancel_prompt(); + let cancelled_prefill = serve_one(&mut self.stack, &next, max_new, eos, Some(3), None); + let ok1 = matches!(cancelled_prefill, Err(ServeError::Cancelled)) && self.stack.health().is_none(); + eprintln!("PFX-CANCEL prefill cancelled={ok1}"); + let cancelled_decode = serve_one(&mut self.stack, &next, 64, eos, None, Some(1)); + let ok2 = matches!(cancelled_decode, Err(ServeError::Cancelled)) && self.stack.health().is_none(); + eprintln!("PFX-CANCEL decode cancelled={ok2}"); + let after = self.serve(&next, max_new, None, None).expect("request after cancellation failed"); + self.stack.prefix_bypass(true); + let full = self.serve(&next, max_new, None, None).expect("verification read failed"); + self.stack.prefix_bypass(false); + let equal = after.tokens == full.tokens; + eprintln!("PFX-CANCEL after reused={} equal_full={equal} out={}", after.reused, ids(&after.tokens)); + if !(ok1 && ok2 && equal) { + self.failed.push("cancel".into()); + } + // a switch to another session right after a cancelled request + let other = self.w.sessions[1 % self.plan.sessions_n].prompt.clone(); + let switched = self.serve(&other, max_new, None, None).expect("switch after cancellation failed"); + eprintln!("PFX-CANCEL switch reused={} out={}", switched.reused, ids(&switched.tokens)); + } + pub(super) fn finish(&self) { + if let Some(line) = self.stack.prefix_metrics() { + eprintln!("PFX-FINAL {line}"); + } + eprintln!("PFX host memory at end: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); + eprintln!("PFX-RESULT failed={:?}", self.failed); + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_run.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_run.rs new file mode 100644 index 00000000..a36d9556 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_run.rs @@ -0,0 +1,209 @@ +//! Loads the pinned model, opens the stack in the mode asked for and serves the scripted workload. +use super::extras::Tally; +use super::workload::{Plan, Workload}; +use super::*; + +/// The pinned tokenizer and EOS, the KAR archive and the binding with its expert source. +struct Pinned { + binding: ModelBinding, + _inherited: InheritedKarArchive, + tokenizer: Tokenizer, + eos: u32, +} +fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) { + let metadata = artifact.tokenizer(); + let tokenizer = Tokenizer::from_vocabulary( + &metadata.model, + &metadata.pre, + metadata.tokens.clone(), + metadata.merges.clone(), + metadata.token_types.clone(), + ) + .expect("verified tokenizer construction failed"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + (tokenizer, eos) +} +fn open_archive(laptop: bool) -> InheritedKarArchive { + let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); + match env::var_os("LELEKA_LAPTOP_KAR_FILE") { + Some(path) if laptop => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) + .expect("read-only KAR admission failed"), + _ => { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") + } + } +} +fn load_experts(binding: &mut ModelBinding, laptop: bool) { + if laptop { + binding.load_mapped_expert_source().expect("mapped expert source load failed"); + if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); + eprintln!("PFX config: process geometry {cells} cells (experimental)"); + } + } else { + binding.load_resident_expert_source().expect("resident expert source load failed"); + } +} +fn load(laptop: bool) -> Pinned { + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); + let (tokenizer, eos) = pinned_tokenizer(&artifact); + let inherited = open_archive(laptop); + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + load_experts(&mut binding, laptop); + Pinned { binding, _inherited: inherited, tokenizer, eos } +} +/// The cache the mode asks for: the prefix cache, the conversation cache of the Original, or none. +fn set_mode(config: &mut StackConfig, plan: &Plan) { + match plan.mode.as_str() { + "prefix" => { + let budget = match text("LELEKA_PFX_MIB", "auto").as_str() { + "auto" => PrefixBudget::Auto, + other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_PFX_MIB: auto or MiB") << 20), + }; + config.prefix = Some(PrefixConfig { + budget, + block_tokens: number("LELEKA_PFX_BLOCK", 0), + laptop: plan.laptop, + ..PrefixConfig::auto() + }); + } + "legacy" => {} + "off" => config.conversation = None, + other => panic!("LELEKA_PFX_MODE: legacy | prefix | off, not {other}"), + } +} +fn stack_config(plan: &Plan) -> StackConfig { + let mut config = StackConfig::new(plan.max_context as i64); + config.capacity = plan.capacity; + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.kv_resident = plan.resident; + if plan.laptop { + config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32; + } + set_mode(&mut config, plan); + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + eprintln!( + "PFX stack: capacity={} kv_resident={} max_context={} expert tier {:?}", + plan.capacity, plan.resident, plan.max_context, config.expert_tier + ); + config +} + +/// The stack under measurement, the workload and what has been counted so far. +pub(super) struct Pfx<'a, 'ctx> { + pub(super) stack: OriginalServeStack<'a, 'ctx>, + pub(super) tokenizer: &'a Tokenizer, + pub(super) eos: u32, + pub(super) plan: &'a Plan, + pub(super) w: Workload, + pub(super) failed: Vec, + pub(super) tally: Tally, +} +impl Pfx<'_, '_> { + pub(super) fn tok(&self, s: &str, special: bool) -> Vec { + self.tokenizer.encode(s, special).expect("tokenization failed") + } + pub(super) fn serve( + &mut self, + prompt: &[u32], + max_new: usize, + cancel_probes: Option, + cancel_rounds: Option, + ) -> Result { + serve_one(&mut self.stack, prompt, max_new, self.eos, cancel_probes, cancel_rounds) + } + /// The agent's next step for session `s`: the (synthetic) reply, then a tool output. + fn advance(&mut self, s: usize) { + if self.w.sessions[s].turn > 0 { + let t = self.w.sessions[s].turn; + let kind = (t % 2) as u8; + let size = self.w.grow[s][t - 1]; + let mut next = std::mem::take(&mut self.w.sessions[s].prompt); + next.extend(self.tok( + &format!( + "shell {{\"cmd\": \"cargo test -p mod_{s} --lib\"}}<|im_end|>\n\ + <|im_start|>user\n\n" + ), + true, + )); + next.extend(filler(self.tokenizer, &mut self.w.rng, kind, size)); + next.extend(self.tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); + self.w.sessions[s].prompt = next; + } + self.w.sessions[s].turn += 1; + } + fn serve_all(&mut self) { + let sessions_n = self.plan.sessions_n; + let order = self.w.order.clone(); + let last_of: Vec = (0..sessions_n).map(|s| order.iter().rposition(|&o| o == s).unwrap_or(0)).collect(); + // the previous prompt of each session, to attribute a request's tokens + for (i, &s) in order.iter().enumerate() { + self.advance(s); + let prompt = self.w.sessions[s].prompt.clone(); + let served = self + .serve(&prompt, self.plan.max_new, None, None) + .unwrap_or_else(|e| panic!("PFX request {i} failed: {e:?} health={:?}", self.stack.health())); + assert_eq!(self.stack.health(), None); + self.account(i, s, &prompt, &served); + self.verify(i, s, &prompt, &served, last_of[s]); + if let Some(line) = self.stack.prefix_metrics() { + eprintln!("PFX-STATS after req={i}: {line}"); + } + } + } +} +pub(super) fn run() { + let _ = dbg_el(); + assert!(env::var("LELEKA_PFX_SMOKE").is_ok_and(|v| v == "yes"), "explicit prefix-cache smoke opt-in required"); + let plan = Plan::from_env(); + let pinned = load(plan.laptop); + let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", if plan.laptop { 15 } else { 28 }); + let driver = Driver::load().expect("CUDA driver load failed"); + 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 failed = measure(&plan, &pinned, &context); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + assert!(failed.is_empty(), "prefix-cache checks failed: {failed:?}"); +} +/// Builds the workload, opens the stack, serves everything and runs the extras; returns the failed checks. +fn measure(plan: &Plan, pinned: &Pinned, context: &Rc>) -> Vec { + let w = workload::build(plan, &pinned.tokenizer); + let config = stack_config(plan); + let stack = match OriginalServeStack::open(&pinned.binding, context.as_ref(), Rc::clone(context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + eprintln!("PFX host memory after open: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); + let mut pfx = Pfx { + stack, + tokenizer: &pinned.tokenizer, + eos: pinned.eos, + plan, + w, + failed: Vec::new(), + tally: Tally::default(), + }; + pfx.serve_all(); + pfx.summary(); + pfx.pool_protocol(); + pfx.cancellation(); + pfx.finish(); + pfx.stack.close().expect("stack cleanup failed"); + pfx.failed +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_workload.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_workload.rs new file mode 100644 index 00000000..3baa8363 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke_workload.rs @@ -0,0 +1,131 @@ +//! The knobs and the scripted workload of the prefix-cache smoke (identical for every mode). +use super::*; + +/// What the operator asked for. +pub(super) struct Plan { + pub(super) mode: String, + pub(super) scenario: String, + pub(super) verify: String, + pub(super) shared_n: usize, + pub(super) sessions_n: usize, + pub(super) turns_n: usize, + start_n: usize, + grow_n: usize, + end_n: usize, + pub(super) max_new: usize, + pub(super) capacity: usize, + pub(super) max_context: usize, + pub(super) resident: usize, + pub(super) laptop: bool, +} +impl Plan { + pub(super) fn from_env() -> Plan { + let mode = text("LELEKA_PFX_MODE", "prefix"); + let scenario = text("LELEKA_PFX_SCENARIO", "grid"); + let verify = text("LELEKA_PFX_VERIFY", "none"); + let (shared_n, sessions_n, turns_n) = + (number("LELEKA_PFX_SHARED", 8000), number("LELEKA_PFX_SESSIONS", 3), number("LELEKA_PFX_TURNS", 3)); + let (start_n, grow_n, end_n) = + (number("LELEKA_PFX_START", 2000), number("LELEKA_PFX_GROW", 2500), number("LELEKA_PFX_END", 40_000)); + let max_new = number("LELEKA_PFX_MAX_NEW", 16); + let capacity = number("LELEKA_PFX_CAPACITY", 2048); + let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); + let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); + let laptop = env::var("LELEKA_PFX_LAPTOP").is_ok_and(|v| v == "yes"); + Plan { + mode, + scenario, + verify, + shared_n, + sessions_n, + turns_n, + start_n, + grow_n, + end_n, + max_new, + capacity, + max_context, + resident, + laptop, + } + } +} +/// The sessions, the order of their requests and the size each turn adds. +pub(super) struct Workload { + pub(super) rng: Rng, + pub(super) sessions: Vec, + pub(super) order: Vec, + pub(super) grow: Vec>, +} +/// `turns_n` requests per session, random interleaving; tool outputs are heavy tailed and scaled so a session's +/// last request is about `end_n` tokens long. +fn agent_order(plan: &Plan, rng: &mut Rng, first_len: usize) -> (Vec, Vec>) { + let (turns_n, sessions_n) = (plan.turns_n, plan.sessions_n); + let mut grow: Vec> = vec![Vec::new(); sessions_n]; + let total_grow = plan.end_n.saturating_sub(first_len); + for g in grow.iter_mut() { + let raw: Vec = (1..turns_n).map(|_| 0.05 + rng.unit().powi(3) * 6.0).collect(); + let sum: f64 = raw.iter().sum(); + *g = raw.iter().map(|r| ((r / sum) * total_grow as f64) as usize).map(|x| x.max(64)).collect(); + } + let mut order: Vec = Vec::new(); + let mut left = vec![turns_n; sessions_n]; + while left.iter().any(|&l| l > 0) { + let s = (rng.next() as usize) % sessions_n; + if left[s] > 0 { + left[s] -= 1; + order.push(s); + } + } + (order, grow) +} +/// `sessions_n` interleaved sessions, `turns_n` times, each turn adding `grow_n` tokens. +fn grid_order(plan: &Plan) -> (Vec, Vec>) { + let grow = vec![vec![plan.grow_n; plan.turns_n.saturating_sub(1)]; plan.sessions_n]; + let mut order: Vec = Vec::new(); + for _ in 0..plan.turns_n { + order.extend(0..plan.sessions_n); + } + (order, grow) +} +fn build_sessions(tokenizer: &Tokenizer, plan: &Plan, rng: &mut Rng, system: &[u32]) -> Vec { + let tok = |s: &str, special: bool| tokenizer.encode(s, special).expect("tokenization failed"); + let mut sessions: Vec = Vec::new(); + for s in 0..plan.sessions_n { + let mut prompt = system.to_vec(); + prompt.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests in module {s}.\n"), true)); + prompt.extend(filler(tokenizer, rng, 1, plan.start_n)); + prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n", true)); + sessions.push(Session { prompt, turn: 0 }); + } + sessions +} +pub(super) fn build(plan: &Plan, tokenizer: &Tokenizer) -> Workload { + let mut rng = Rng(0x5eed_1234_abcd_0001); + let tok = |s: &str, special: bool| tokenizer.encode(s, special).expect("tokenization failed"); + let t0 = std::time::Instant::now(); + let mut system = tok( + "<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search. \ + Repository notes follow.\n", + true, + ); + system.extend(filler(tokenizer, &mut rng, 0, plan.shared_n.saturating_sub(system.len() + 4))); + system.extend(tok("<|im_end|>\n", true)); + let sessions = build_sessions(tokenizer, plan, &mut rng, &system); + // the order of requests and the size each turn adds + let (order, grow) = + if plan.scenario == "agent" { agent_order(plan, &mut rng, sessions[0].prompt.len()) } else { grid_order(plan) }; + eprintln!( + "PFX workload: mode={} scenario={} sessions={} turns={} shared={} first_prompt={} requests={} \ + built_in={:.1}s", + plan.mode, + plan.scenario, + plan.sessions_n, + plan.turns_n, + system.len(), + sessions[0].prompt.len(), + order.len(), + t0.elapsed().as_secs_f64() + ); + Workload { rng, sessions, order, grow } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs index 7053abe3..edff9a37 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs @@ -65,407 +65,23 @@ fn report_timing(stack: &OriginalServeStack<'_, '_>, label: &str, produced: usiz } } +#[path = "backend_original_serve_smoke_stack.rs"] +mod smoke_stack; +use smoke_stack::*; +#[path = "backend_original_serve_smoke_conv.rs"] +mod smoke_conv; +#[path = "backend_original_serve_smoke_long.rs"] +mod smoke_long; +#[path = "backend_original_serve_smoke_main.rs"] +mod smoke_main; +use smoke_conv::*; +#[path = "backend_original_serve_smoke_coverage.rs"] +mod smoke_coverage; + #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"] fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { - let _ = dbg_el(); - assert!( - env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), - "explicit Original serve smoke opt-in required" - ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited KAR admission failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - eprintln!("DBG[{:.0}s] smoke: binding ready, loading resident expert source", dbg_el()); - let resident = binding.load_resident_expert_source().expect("resident expert source load failed"); - eprintln!("DBG[{:.0}s] smoke: resident expert source loaded: {resident:?}", dbg_el()); - let budget_gib: usize = - env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); - let driver = Driver::load().expect("CUDA driver load failed"); - 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(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); - if let Some(cells) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT").ok().and_then(|v| v.parse().ok()) { - config.kv_resident = cells; - } - // LELEKA_SMOKE_PROMPT_CACHE=0: every request reads its whole prompt (the first-request experiments) - if env::var("LELEKA_SMOKE_PROMPT_CACHE").is_ok_and(|v| v == "0") { - config.conversation = None; - } - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - eprintln!("DBG smoke: expert tier {:?}", config.expert_tier); - // With the tier on, adaptive swaps move experts between the GPU and the CPU between requests and the two - // round differently, so a repeated greedy request may legitimately differ: reported, not asserted. - let tier_on = config.expert_tier.enabled(); - let same = |label: &str, a: &[i32], b: &[i32]| { - if tier_on { - let first = a.iter().zip(b).position(|(x, y)| x != y); - eprintln!( - "DBG smoke: {label}: {} (expert tier on: residency changes between requests)", - match first { - None if a.len() == b.len() => "identical".to_owned(), - None => format!("lengths {} vs {}", a.len(), b.len()), - Some(i) => format!("first difference at token {i}"), - } - ); - } else { - assert_eq!(a, b, "{label}"); - } - }; - eprintln!( - "DBG[{:.0}s] smoke: opening serve stack (budget {budget_gib} GiB, capacity {})", - dbg_el(), - config.capacity - ); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - - eprintln!("DBG[{:.0}s] smoke: stack open", dbg_el()); - let short_prompt = tokenizer.encode(PROMPT, true).expect("short prompt tokenization failed"); - let prompt = tokenizer.encode(&[PROMPT; 6].join(" "), true).expect("prompt tokenization failed"); - assert!(prompt.len() >= 8, "the smoke prompt must exercise the batched read"); - eprintln!("DBG[{:.0}s] smoke: prompt ids ({}): {:?}", dbg_el(), prompt.len(), &prompt[..prompt.len().min(24)]); - - // 1. greedy, twice: the second request starts from a reset and must reproduce the first exactly - let mut runs: Vec> = Vec::new(); - for _ in 0..2 { - let mut tokens = Vec::new(); - let outcome = stack - .serve( - &request(&prompt, 24, None, eos), - &mut |round| { - tokens.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) - .unwrap_or_else(|e| panic!("greedy request failed: {e:?}")); - assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); - assert_eq!(outcome.produced, tokens.len()); - assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); - report_timing(&stack, "greedy", tokens.len()); - runs.push(tokens); - } - eprintln!("DBG[{:.0}s] smoke: greedy run0 tokens ({}): {:?}", dbg_el(), runs[0].len(), runs[0]); - eprintln!("DBG[{:.0}s] smoke: greedy run1 tokens ({}): {:?}", dbg_el(), runs[1].len(), runs[1]); - same("a reset must return to the empty prompt", &runs[0], &runs[1]); - assert_eq!(stack.health(), None); - - // 2. a sampled request with penalties completes - 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 mut sampled = Vec::new(); - stack - .serve( - &request(&prompt, 16, Some(&sampler), eos), - &mut |round| { - sampled.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) - .unwrap_or_else(|e| panic!("sampled request failed: {e:?}")); - eprintln!("DBG[{:.0}s] smoke: sampled tokens ({}): {:?}", dbg_el(), sampled.len(), sampled); - assert!(!sampled.is_empty()); - - // 3. cancellation after the first committed round returns Cancelled and leaves the stack usable - let emitted = std::cell::Cell::new(0usize); - let cancelled = stack.serve( - &request(&prompt, 64, None, eos), - &mut |round| { - emitted.set(emitted.get() + round.len()); - Ok(()) - }, - &mut || emitted.get() > 0, - ); - assert_eq!(cancelled.err(), Some(ServeError::Cancelled)); - assert_eq!(stack.health(), None); - let mut after = Vec::new(); - stack - .serve( - &request(&prompt, 24, None, eos), - &mut |round| { - after.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) - .unwrap_or_else(|e| panic!("request after a cancellation failed: {e:?}")); - same("a cancelled request must not disturb the next one", &after, &runs[0]); - - // 3b. parity corpus: every line of LELEKA_SMOKE_PROMPTS (text) is tokenized with the verified tokenizer, served greedily - // for LELEKA_SMOKE_MAX_NEW tokens (default 64) and printed as ids so the Original can be run on the same ids. - if let Some(path) = env::var_os("LELEKA_SMOKE_PROMPTS") { - let max_new: usize = env::var("LELEKA_SMOKE_MAX_NEW").ok().and_then(|v| v.parse().ok()).unwrap_or(64); - let text = std::fs::read_to_string(path).expect("prompt corpus unreadable"); - // 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); - // LELEKA_SMOKE_ARMS (see backend_original_serve_arms.rs): first-request A/B of the expert tier's policies; each - // prompt of LELEKA_SMOKE_ORDER (default: file order) is served once per arm from a first-request tier state, - // LELEKA_SMOKE_REPEAT times over the whole order. Replaces the plain corpus loop. - if let Ok(arms) = env::var("LELEKA_SMOKE_ARMS") { - let arms = super::original_serve_arms::parse_arms(&arms); - // LELEKA_SMOKE_PROMPT_IDS: a file of comma-separated token IDs, one prompt per line, instead of the text lines - let prompts: Vec> = match env::var_os("LELEKA_SMOKE_PROMPT_IDS") { - Some(ids) => std::fs::read_to_string(ids) - .expect("prompt id file unreadable") - .lines() - .filter(|l| !l.trim().is_empty()) - .map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect()) - .collect(), - None => text - .lines() - .filter(|l| !l.trim().is_empty()) - .map(|l| tokenizer.encode(l, true).expect("corpus tokenization failed")) - .collect(), - }; - let order: Vec = env::var("LELEKA_SMOKE_ORDER") - .map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_SMOKE_ORDER: indices")).collect()) - .unwrap_or_else(|_| (0..prompts.len()).collect()); - let min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0); - for rep in 0..repeat { - for (k, &index) in order.iter().enumerate() { - let ids = &prompts[index]; - if rep == 0 { - eprintln!( - "DBG corpus {index} prompt_ids ({}): {}", - ids.len(), - ids.iter().map(|t| t.to_string()).collect::>().join(",") - ); - } - for arm in super::original_serve_arms::arms_for(&arms, k + rep) { - let corpus_request = ServeRequest::new( - ids.iter().map(|&t| t as i32).collect(), - max_new, - None, - 7, - min_p, - crate::qwen_forward::original_serve_request::original_stop_tokens(eos), - ); - super::original_serve_arms::serve_arm( - &mut stack, - &arm, - &corpus_request, - &format!("p{index} rep{rep}"), - &format!("prompt={}", ids.len()), - ); - } - } - } - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); - return; - } - // LELEKA_SPEC_ARMS (see OriginalServeSettings::arms_from_environment): pass p of prompt i is served by arm (p + i) % arms, - // so a prompt meets every arm (LELEKA_SMOKE_REPEAT = arms x repetitions) in a rotated order. - let spec_arms = stack.spec_arms(); - for (index, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { - // `@file:PATH` stands for the whole content of that file (a source file to rewrite: code with its newlines) - let file_text; - let line = match line.trim().strip_prefix("@file:") { - Some(path) => { - file_text = std::fs::read_to_string(path.trim()).expect("@file prompt unreadable"); - file_text.as_str() - } - None => line, - }; - // 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\n\n\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::>().join(",") - ); - // LELEKA_SMOKE_FORCE_DIR=dir (quality gate, docs/quality-gate.md): `dir/c.truth` is the comma-separated - // token list of this prompt followed by the tokens another engine produced for it. The first - // LELEKA_SMOKE_FORCE_PASSES (default 1) passes of this prompt decode along that text (teacher forcing: the - // picks are replaced by the text's tokens, the logits and the `LELEKA_TRACE_LOGPROBS` rows are the port's own); - // later passes are free. A forced pass produces exactly the forced tokens. - let truth: Option> = env::var_os("LELEKA_SMOKE_FORCE_DIR").and_then(|dir| { - let file = std::path::Path::new(&dir).join(format!("c{index}.truth")); - let text = std::fs::read_to_string(&file).ok()?; - let sequence: Vec = - text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect(); - assert!( - sequence.len() > ids.len() && sequence[..ids.len()].iter().zip(&ids).all(|(a, &b)| *a == b as i32), - "{}: the forced sequence must start with the tokenized prompt and extend it", - file.display() - ); - Some(sequence) - }); - let forced_passes: usize = - env::var("LELEKA_SMOKE_FORCE_PASSES").ok().and_then(|v| v.parse().ok()).unwrap_or(1); - for pass in 0..repeat { - if !spec_arms.is_empty() { - assert!(stack.select_spec_arm(&spec_arms[(pass + index) % spec_arms.len()])); - } - let forced = truth.as_ref().filter(|_| pass < forced_passes); - crate::qwen_forward::quality_force::set(forced.cloned()); - eprintln!("DBG corpus {index} pass={pass} begin forced={}", forced.is_some()); - let max_new = forced.map_or(max_new, |t| t.len() - ids.len()); - let mut out = Vec::new(); - let min_p: f32 = stack - .spec_arm_min_p() - .unwrap_or_else(|| env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0)); - // 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, - crate::qwen_forward::original_serve_request::original_stop_tokens(eos), - ); - let started = std::time::Instant::now(); - let mut first: Option = None; - let served = stack.serve( - &corpus_request, - &mut |round| { - if first.is_none() { - first = Some(started.elapsed()); - } - out.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ); - let total = started.elapsed(); - crate::qwen_forward::quality_force::set(None); - if let (Some(t), Ok(_)) = (forced, &served) { - eprintln!( - "DBG corpus {index} pass={pass} forced: produced {} of {} forced tokens, stopped as forced: {}", - out.len(), - t.len() - ids.len(), - out.iter().zip(&t[ids.len()..]).all(|(a, b)| a == b) - ); - } - match served { - Ok(outcome) => { - if pass == 0 && spec_arms.is_empty() { - eprintln!( - "DBG corpus {index} output ({} tokens, rounds {}): {}", - out.len(), - outcome.rounds, - out.iter().map(|t| t.to_string()).collect::>().join(" ") - ); - } else { - eprintln!( - "DBG corpus {index} output pass={pass} arm={} ({} tokens, rounds {}): {}", - stack.spec_arm(), - out.len(), - outcome.rounds, - out.iter().map(|t| t.to_string()).collect::>().join(" ") - ); - } - let ttft = first.unwrap_or(total); - let decode_s = (total - ttft).as_secs_f64(); - let decode_tps = - if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 }; - eprintln!( - "DBG corpus {index} timing pass={pass} arm={} prompt={} produced={} rounds={} ttft_ms={:.1} total_ms={:.1} decode_tok_s={:.2}", - stack.spec_arm(), - ids.len(), - out.len(), - outcome.rounds, - ttft.as_secs_f64() * 1e3, - total.as_secs_f64() * 1e3, - decode_tps - ); - report_timing(&stack, &format!("corpus {index} pass {pass}"), out.len()); - } - Err(e) => eprintln!("DBG corpus {index} pass={pass} FAILED {e:?} health={:?}", stack.health()), - } - } - } - } - // 4. a short prompt (<= 64 tokens) takes the scalar draft-KV path of the Original; report instead of asserting - eprintln!("DBG[{:.0}s] smoke: short-prompt request ({} tokens)", dbg_el(), short_prompt.len()); - let mut short_out = Vec::new(); - match stack.serve( - &request(&short_prompt, 16, None, eos), - &mut |round| { - short_out.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) { - Ok(outcome) => eprintln!( - "DBG[{:.0}s] smoke: short prompt ok produced={} tokens={:?}", - dbg_el(), - outcome.produced, - short_out - ), - Err(e) => eprintln!("DBG[{:.0}s] smoke: short prompt FAILED {e:?} health={:?}", dbg_el(), stack.health()), - } - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + smoke_main::run(); } /// Long-context smoke of the streamed INT8 KV (`--kv int8 --kv-resident N`): one greedy request over a prompt @@ -490,289 +106,7 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; long prompt"] fn original_serve_long_context_streamed_kv_smoke() { - let _ = dbg_el(); - assert!( - env::var("LELEKA_ORIGINAL_SERVE_LONG_SMOKE").is_ok_and(|value| value == "yes"), - "explicit long-context serve smoke opt-in required" - ); - let number = |name: &str, default: usize| -> usize { - env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) - }; - // one prompt length, or a comma-separated list served in order on the same stack - let targets: Vec = env::var("LELEKA_ORIGINAL_SERVE_LONG_TOKENS") - .map(|v| { - v.split(',').map(|t| t.trim().parse().expect("LELEKA_ORIGINAL_SERVE_LONG_TOKENS must be counts")).collect() - }) - .unwrap_or_else(|_| vec![40_000]); - let target = targets.iter().copied().max().expect("at least one prompt length"); - let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); - let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 65_536); - let max_new = number("LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW", 32); - assert!( - targets.iter().all(|&t| t >= 64) && target + max_new + 8 <= max_context, - "the prompt and the answer must fit the ceiling" - ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited KAR admission failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - binding.load_resident_expert_source().expect("resident expert source load failed"); - let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); - let driver = Driver::load().expect("CUDA driver load failed"); - let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - - // the prompt: passcode, deterministic varied filler up to the target length, the question - const COLORS: [&str; 8] = ["amber", "blue", "crimson", "green", "grey", "ivory", "orange", "violet"]; - const THINGS: [&str; 8] = ["heron", "lantern", "barge", "orchard", "glacier", "market", "violin", "quarry"]; - const PLACES: [&str; 8] = ["harbour", "valley", "library", "bridge", "station", "garden", "tower", "village"]; - let head = tokenizer - .encode("Remember this: the secret passcode is 4817-QX. Below is a long log of unrelated notes.\n\n", true) - .expect("tokenization failed"); - let question = tokenizer - .encode("\n\nEnd of the notes. Question: what is the secret passcode given at the very beginning? Answer: the secret passcode is", false) - .expect("tokenization failed"); - // LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE: a natural document (e.g. source code) as the filler instead of the notes, and - // LELEKA_ORIGINAL_SERVE_LONG_QUESTION: the closing question for it - let question = match env::var("LELEKA_ORIGINAL_SERVE_LONG_QUESTION") { - Ok(q) => tokenizer.encode(&q, false).expect("tokenization failed"), - Err(_) => question, - }; - let budget = target.saturating_sub(head.len() + question.len()); - let mut filler: Vec = Vec::with_capacity(budget + 64); - let mut state = 0x2545_f491u64; - let mut note = 0usize; - if let Some(path) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE") { - let text = std::fs::read_to_string(path).expect("long text file unreadable"); - let ids = tokenizer.encode(&text, false).expect("tokenization failed"); - assert!(!ids.is_empty(), "empty long text file"); - while filler.len() < budget { - filler.extend_from_slice(&ids); - } - } - while filler.len() < budget { - let mut sentences = String::new(); - for _ in 0..64 { - state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - let pick = |shift: u32| (state >> shift) as usize % 8; - sentences.push_str(&format!( - "Note {note}: the {} {} near the {} was counted {} times. ", - COLORS[pick(20)], - THINGS[pick(30)], - PLACES[pick(40)], - (state >> 50) % 997 - )); - note += 1; - } - filler.extend(tokenizer.encode(&sentences, false).expect("tokenization failed")); - } - filler.truncate(budget); - // every shorter prompt takes a prefix of the same filler (what a single-length run builds) - let prompts: Vec> = targets - .iter() - .map(|&t| { - let budget = t.saturating_sub(head.len() + question.len()); - head.iter().chain(&filler[..budget]).chain(&question).copied().collect() - }) - .collect(); - - let mut config = StackConfig::new(max_context as i64); - config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); - config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); - config.kv_resident = resident; - // A prefill measurement: every request is read from the empty prompt unless - // LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION=yes keeps the stack's conversation cache. - if !env::var("LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION").is_ok_and(|v| v == "yes") { - config.conversation = None; - } - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - eprintln!("long-smoke capacity={} expert tier {:?}", config.capacity, config.expert_tier); - let repeat = number("LELEKA_ORIGINAL_SERVE_LONG_REPEAT", 1).max(1); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - for prompt in &prompts { - let prompt = prompt.as_slice(); - eprintln!("long-smoke prompt tokens={} kv-resident={resident} max-context={max_context}", prompt.len()); - // LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt.ids` (comma-separated) for the Original's - // `--tokens-file`, so both engines read the identical token sequence - if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") { - let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len())); - let text = prompt.iter().map(|t| t.to_string()).collect::>().join(","); - std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); - eprintln!("long-smoke prompt ids -> {}", path.display()); - } - // LELEKA_ORIGINAL_SERVE_LONG_ARMS (see backend_original_serve_arms.rs): the prompt once per arm from a first-request - // tier state, the order reversed on odd passes (`repeat` passes); replaces the plain passes below. - if let Ok(arms) = env::var("LELEKA_ORIGINAL_SERVE_LONG_ARMS") { - let arms = super::original_serve_arms::parse_arms(&arms); - for pass in 0..repeat { - for arm in super::original_serve_arms::arms_for(&arms, pass) { - super::original_serve_arms::serve_arm( - &mut stack, - &arm, - &request(prompt, max_new, None, eos), - &format!("long pass{pass}"), - &format!("prompt={}", prompt.len()), - ); - } - } - continue; - } - // LELEKA_SPEC_ARMS: pass p of the prompt is served by arm p % arms (the window policy A/B inside one load); - // LELEKA_SMOKE_MIN_P: the request's draft floor (default 0). - let spec_arms = stack.spec_arms(); - let spec_min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0); - // LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer.ids` (comma-separated) holds the tokens - // another engine answered to the N-token prompt; the request then decodes along that text (teacher forcing, see - // `quality_force`) for exactly that many tokens, with the port's own logits and `LELEKA_TRACE_LOGPROBS` rows. - let forced_answer: Option> = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR").and_then(|dir| { - let text = std::fs::read_to_string(PathBuf::from(dir).join(format!("answer{}.ids", prompt.len()))).ok()?; - Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect()) - }); - let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len()); - // LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process) - let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ") - .map(|v| { - v.split(',') - .filter_map(|t| { - let mut parts = t.trim().splitn(2, ':'); - Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0))) - }) - .collect() - }) - .unwrap_or_default(); - // LELEKA_QSA_LATE_SEQ=1,0,0,1: the QSA late-selection kernels per pass (paired A/B inside one process) - let late_seq: Vec = env::var("LELEKA_QSA_LATE_SEQ") - .map(|v| v.split(',').filter_map(|t| t.trim().parse().ok()).collect()) - .unwrap_or_default(); - for pass in 0..repeat { - if !late_seq.is_empty() { - let v = late_seq[pass % late_seq.len()]; - leleka_cuda_driver::set_qsa_late_override(v); - eprintln!("long-smoke pass={pass} qsa_late={v}"); - } - crate::qwen_forward::quality_force::set( - forced_answer - .as_ref() - .map(|answer| prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect()), - ); - if !stream_seq.is_empty() { - let (v, depth) = stream_seq[pass % stream_seq.len()]; - leleka_cuda_driver::compute_drain::set_issue_depth(depth); - // bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight - crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE - .store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed); - leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0); - eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}"); - } - if !spec_arms.is_empty() { - assert!(stack.select_spec_arm(&spec_arms[pass % spec_arms.len()])); - } - let started = std::time::Instant::now(); - let mut tokens = Vec::new(); - let long_request = ServeRequest::new( - prompt.iter().map(|&t| t as i32).collect(), - max_new, - None, - 7, - spec_min_p, - vec![eos as i32], - ); - let outcome = stack - .serve( - &long_request, - &mut |round| { - tokens.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) - .unwrap_or_else(|e| panic!("long-context request failed: {e:?} health={:?}", stack.health())); - crate::qwen_forward::quality_force::set(None); - assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); - assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); - assert_eq!(stack.health(), None); - let (prompt_ms, decode_ms) = stack.last_timing(); - eprintln!( - "long-smoke prefill pass={pass} arm={} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} decode_ms={decode_ms:.1}", - stack.spec_arm(), - prompt.len(), - (prompt.len() - 1) as f64 / (prompt_ms / 1e3).max(1e-9) - ); - let ids: Vec = tokens.iter().map(|&t| t as u32).collect(); - let text = tokenizer.decode(&ids).unwrap_or_default(); - eprintln!( - "long-smoke output ids ({}): {}", - ids.len(), - ids.iter().map(|t| t.to_string()).collect::>().join(",") - ); - eprintln!( - "long-smoke result pass={pass} prompt={} resident={resident} produced={} rounds={} wall_s={:.1} needle_found={} text={text:?}", - prompt.len(), - outcome.produced, - outcome.rounds, - started.elapsed().as_secs_f64(), - text.contains("4817") - ); - } - } - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); -} - -/// One greedy request; returns (tokens, time to the first committed round in ms, total ms, reused tokens). -fn timed( - stack: &mut OriginalServeStack<'_, '_>, - prompt: &[u32], - max_new: usize, - eos: u32, -) -> (Vec, f64, f64, usize) { - let started = std::time::Instant::now(); - let mut first: Option = None; - let mut tokens = Vec::new(); - let outcome = stack - .serve( - &request(prompt, max_new, None, eos), - &mut |round| { - first.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1e3); - tokens.extend_from_slice(round); - Ok(()) - }, - &mut || false, - ) - .unwrap_or_else(|e| { - eprintln!("CONV FAILED n={} error={e:?} health={:?}", prompt.len(), stack.health()); - panic!("conversation smoke request failed: {e:?}") - }); - assert_eq!(outcome.produced, tokens.len()); - (tokens, first.unwrap_or(f64::NAN), started.elapsed().as_secs_f64() * 1e3, stack.reused_tokens()) + smoke_long::run(); } /// The conversation cache on the real model: a ONE-token prompt as the first request (the fresh-resolver trap), @@ -786,255 +120,7 @@ fn timed( #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"] fn original_serve_conversation_smoke_resume_matches_a_full_read() { - let _ = dbg_el(); - assert!( - env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), - "explicit Original serve smoke opt-in required" - ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited KAR admission failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - binding.load_resident_expert_source().expect("resident expert source load failed"); - let budget_gib: usize = - env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); - let driver = Driver::load().expect("CUDA driver load failed"); - 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(8192); - 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); - let cache = env::var("LELEKA_CONVERSATION_CACHE").map_or(true, |v| v != "off"); - config.conversation = cache.then(crate::qwen_forward::original_serve_stack::ConversationConfig::original); - eprintln!("CONV cache={}", if cache { "on" } else { "off" }); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - let max_new: usize = env::var("LELEKA_CONVERSATION_MAX_NEW").ok().and_then(|v| v.parse().ok()).unwrap_or(48); - let repeat: usize = env::var("LELEKA_CONVERSATION_SYSTEM_REPEAT").ok().and_then(|v| v.parse().ok()).unwrap_or(120); - - // 0. the first request after open is ONE token (the streamed-KV resolver was never initialised) - let turn = tokenizer.encode("<|im_start|>", true).expect("turn token"); - assert_eq!(turn, [248_045], "<|im_start|> is the --turn-token"); - let (one, one_ttft, _, _) = timed(&mut stack, &turn, 4, eos); - eprintln!("CONV one-token prompt ok: {} tokens, ttft {one_ttft:.1} ms", one.len()); - - // 1. a chat request with a long system prompt - let system = format!("{PROMPT} ").repeat(repeat); - let first_text = format!( - "<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\nName three more European capitals.<|im_end|>\n<|im_start|>assistant\n" - ); - let first = tokenizer.encode(&first_text, true).expect("first prompt tokenization failed"); - let (reply, ttft_a, total_a, reused_a) = timed(&mut stack, &first, max_new, eos); - eprintln!("CONV A n={} reused={reused_a} ttft={ttft_a:.1}ms total={total_a:.1}ms out={reply:?}", first.len()); - - // 2. the next turn: the first prompt, the reply, a new user turn - let mut second = first.clone(); - second.extend(reply.iter().map(|&t| t as u32).filter(|&t| t != eos)); - let next_turn = "<|im_end|>\n<|im_start|>user\nAnd the capital of Spain?<|im_end|>\n<|im_start|>assistant\n"; - second.extend(tokenizer.encode(next_turn, true).expect("second turn")); - let (cached, ttft_b, total_b, reused_b) = timed(&mut stack, &second, max_new, eos); - eprintln!( - "CONV B(cache) n={} reused={reused_b} ttft={ttft_b:.1}ms total={total_b:.1}ms out={cached:?}", - second.len() - ); - if cache { - assert!( - reused_b > 0 || env::var_os("STRATA_CKPT_REREAD").is_some(), - "the second turn must resume from a checkpoint" - ); - } else { - assert_eq!(reused_b, 0, "nothing is reused with the cache off"); - } - assert_eq!(stack.health(), None); - - // 3. the same second request read from the empty prompt - stack.forget_conversation(); - let (full, ttft_f, total_f, reused_f) = timed(&mut stack, &second, max_new, eos); - eprintln!( - "CONV B(full) n={} reused={reused_f} ttft={ttft_f:.1}ms total={total_f:.1}ms out={full:?}", - second.len() - ); - assert_eq!(reused_f, 0); - eprintln!("CONV greedy equal: {} ttft cache/full: {ttft_b:.1}/{ttft_f:.1} ms", cached == full); - - // 4. a new chat with the same system prompt resumes from the root checkpoint taken by step 3 - let other_text = format!( - "<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\nWhat is the capital of Poland?<|im_end|>\n<|im_start|>assistant\n" - ); - let other = tokenizer.encode(&other_text, true).expect("other prompt"); - let (other_out, ttft_o, _, reused_o) = timed(&mut stack, &other, max_new.min(16), eos); - eprintln!("CONV C(root) n={} reused={reused_o} ttft={ttft_o:.1}ms out={other_out:?}", other.len()); - assert_eq!(stack.health(), None); - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); - assert_eq!(cached, full, "a resumed request must produce the tokens of a full read"); -} - -/// What one request of the coverage smoke returned. -struct Served { - tokens: Vec, - ttft: f64, - reused: usize, - /// Where the conversation cache placed the request (with `STRATA_CKPT_REREAD` it then read from 0). - resume: usize, -} - -/// One request with an optional sampler and cancellation (after `cancel_rounds` committed rounds, or after -/// `cancel_probes` calls of the cancel flag, which the prefill polls before and during every chunk). -fn serve_once( - stack: &mut OriginalServeStack<'_, '_>, - prompt: &[u32], - max_new: usize, - sampler: Option<&leleka_sampler_ref::SamplerParams>, - eos: u32, - cancel_rounds: Option, - cancel_probes: Option, -) -> Result { - let started = std::time::Instant::now(); - let first = std::cell::Cell::new(None::); - let rounds = std::cell::Cell::new(0usize); - let probes = std::cell::Cell::new(0usize); - let mut tokens = Vec::new(); - let result = stack.serve( - &request(prompt, max_new, sampler, eos), - &mut |round| { - if first.get().is_none() { - first.set(Some(started.elapsed().as_secs_f64() * 1e3)); - } - rounds.set(rounds.get() + 1); - tokens.extend_from_slice(round); - Ok(()) - }, - &mut || { - probes.set(probes.get() + 1); - cancel_rounds.is_some_and(|n| rounds.get() >= n) || cancel_probes.is_some_and(|n| probes.get() >= n) - }, - ); - result.map(|outcome| { - assert_eq!(outcome.produced, tokens.len()); - Served { - tokens, - ttft: first.get().unwrap_or(f64::NAN), - reused: stack.reused_tokens(), - resume: stack.resume_point(), - } - }) -} - -/// Opens the pinned binding and an Original serve stack with `conversation`, runs `body`, closes everything. -fn with_stack( - conversation: Option, - body: impl FnOnce(&mut OriginalServeStack<'_, '_>, &Tokenizer, u32), -) { - assert!( - env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), - "explicit Original serve smoke opt-in required" - ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("missing inherited sealed archive descriptor") - .parse() - .expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); - let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &metadata.model, - &metadata.pre, - metadata.tokens.clone(), - metadata.merges.clone(), - metadata.token_types.clone(), - ) - .expect("verified tokenizer construction failed"); - let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited KAR admission failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &required_path("LELEKA_STRA169_MTP_PACK"), - &required_path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual pinned KAR+MTP binding failed"); - binding.load_resident_expert_source().expect("resident expert source load failed"); - let budget_gib: usize = - env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); - let driver = Driver::load().expect("CUDA driver load failed"); - 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(16_384); - 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.conversation = conversation; - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - body(&mut stack, &tokenizer, eos); - stack.close().expect("stack cleanup failed"); - Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); -} - -/// Whether a request read from `read_from` (a restore, or `STRATA_CKPT_REREAD`'s re-read from 0 up to -/// `reread_to`) cuts its prompt into the same batched chunks as the same request read from 0 with the cache on, -/// from `read_from` on. Only then must the two produce the same tokens: the batched prefill's arithmetic depends -/// on how the prompt is split (a root boundary is only cut when reading from 0, a resume point is a boundary the -/// full read does not have), so different chunks may flip a near tie, with or without the cache. -fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option, every: usize, cache: bool) -> bool { - use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; - let options = PromptOptions { short_read: 64, force_batched: true, ..PromptOptions::original_mode17(16_384) }; - let options = if cache { - crate::qwen_forward::original_serve_stack::ConversationConfig { - prompt_cache_every: every, - ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() - } - .plan_options(options) - } else { - PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..options } - }; - let capacity = env::var("LELEKA_ORIGINAL_SERVE_CAPACITY").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); - let cuts = |resume: usize, reread_to: Option| -> Vec<(usize, usize)> { - PromptPlan::new(prompt, resume, reread_to, None, options, capacity) - .map(|plan| plan.filter(|a| a.path != PromptPath::FinalSeed).map(|a| (a.first, a.count)).collect()) - .unwrap_or_default() - }; - let full = cuts(0, None); - let read = cuts(resume, reread_to); - let from = read.first().map_or(prompt.len(), |a| a.0); - full.iter().filter(|a| a.0 >= from).copied().collect::>() == read - && full.iter().all(|a| a.0 >= from || a.0 + a.1 <= from) -} - -fn ids(tokens: &[i32]) -> String { - tokens.iter().map(|t| t.to_string()).collect::>().join(",") + smoke_conv::run_resume(); } /// Coverage of the conversation cache on the real model (`--prompt-cache-every` small so a ~4.8k-token prompt @@ -1054,194 +140,5 @@ fn ids(tokens: &[i32]) -> String { #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; no live-owner overlap"] fn original_serve_conversation_coverage_smoke() { - let _ = dbg_el(); - let cache = env::var("LELEKA_CONVERSATION_CACHE").map_or(true, |v| v != "off"); - let reread = env::var_os("STRATA_CKPT_REREAD").is_some(); - let every: usize = env::var("LELEKA_CONVERSATION_EVERY").ok().and_then(|v| v.parse().ok()).unwrap_or(2048); - let conversation = cache.then(|| crate::qwen_forward::original_serve_stack::ConversationConfig { - prompt_cache_every: every, - ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() - }); - let max_new: usize = env::var("LELEKA_CONVERSATION_MAX_NEW").ok().and_then(|v| v.parse().ok()).unwrap_or(48); - let repeat: usize = env::var("LELEKA_CONVERSATION_SYSTEM_REPEAT").ok().and_then(|v| v.parse().ok()).unwrap_or(250); - let cancel_probes: usize = - env::var("LELEKA_CONVERSATION_CANCEL_PROBES").ok().and_then(|v| v.parse().ok()).unwrap_or(4); - eprintln!( - "CONV cache={} reread={reread} every={every} max_new={max_new} repeat={repeat}", - if cache { "on" } else { "off" } - ); - let mut failed: Vec<&'static str> = Vec::new(); - with_stack(conversation, |stack, tokenizer, eos| { - let mut check = |name: &'static str, ok: bool| { - eprintln!("CONV-CHECK {name} {}", if ok { "ok" } else { "FAIL" }); - if !ok { - failed.push(name); - } - }; - let resumes = cache && !reread; - let mut strict = 0usize; - let encode = |text: &str| tokenizer.encode(text, true).expect("tokenization failed"); - let chat = |system: &str, turns: &[(&str, &str)], user: &str| { - let mut text = format!("<|im_start|>system\n{system}<|im_end|>\n"); - for (u, a) in turns { - text.push_str(&format!("<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n")); - } - text.push_str(&format!("<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n")); - text - }; - let greedy = |stack: &mut OriginalServeStack<'_, '_>, prompt: &[u32], what: &str| -> Served { - let served = serve_once(stack, prompt, max_new, None, eos, None, None) - .unwrap_or_else(|e| panic!("CONV {what} failed: {e:?} health={:?}", stack.health())); - eprintln!( - "CONV {what} n={} reused={} ttft={:.1}ms out={}", - prompt.len(), - served.reused, - served.ttft, - ids(&served.tokens) - ); - served - }; - let system = format!("{PROMPT} ").repeat(repeat); - - // 1. determinism: chat A read cold twice in this process - let a = encode(&chat(&system, &[], "Name three more European capitals.")); - let a1 = greedy(stack, &a, "A1(cold)"); - stack.forget_conversation(); - let a2 = greedy(stack, &a, "A2(cold)"); - eprintln!("CONV-DET A1 tokens={}", ids(&a1.tokens)); - eprintln!("CONV-DET A2 tokens={}", ids(&a2.tokens)); - check("determinism_same_process", a1.tokens == a2.tokens); - - // 2. periodic checkpoint: diverge inside the system prompt, past the 4096 periodic checkpoint - let cut = system.len() * 9 / 10; - let edited = format!("{} Note: this sentence was inserted. {}", &system[..cut], &system[cut..]); - let p = encode(&chat(&edited, &[], "Name three more European capitals.")); - let shared = p.iter().zip(&a).take_while(|(x, y)| x == y).count(); - let p_cached = greedy(stack, &p, "P(periodic)"); - let expected = (shared.min(p.len() - 1) / every) * every; - eprintln!("CONV P shared_prefix={shared} expected_resume={expected}"); - if resumes { - check("periodic_resume", every > 0 && p_cached.reused == expected && expected > 0); - } - stack.forget_conversation(); - let p_full = greedy(stack, &p, "P(full)"); - if same_chunks(&p, p_cached.resume, (reread && p_cached.resume > 0).then_some(p_cached.resume), every, cache) { - strict += usize::from(p_cached.resume > 0); - check("periodic_equal", p_cached.tokens == p_full.tokens); - } else { - eprintln!( - "CONV-INFO periodic_equal: different prefill chunks than the full read (equal={})", - p_cached.tokens == p_full.tokens - ); - } - - // 3. fallback: the follow-up edits the earlier user turn (it does NOT extend the previous prompt) - let reply = tokenizer - .decode(&p_full.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos).collect::>()) - .unwrap_or_default(); - let follow = encode(&chat( - &edited, - &[("Name three other European capitals.", reply.as_str())], - "And the capital of Spain?", - )); - let f_cached = greedy(stack, &follow, "F(root fallback)"); - if resumes { - // the edited user turn starts right after the root (the first turn boundary past the system prompt) - check("fallback_root", f_cached.reused > 4096 && f_cached.reused < p.len() - 8); - } - stack.forget_conversation(); - let f_full = greedy(stack, &follow, "F(full)"); - if same_chunks( - &follow, - f_cached.resume, - (reread && f_cached.resume > 0).then_some(f_cached.resume), - every, - cache, - ) { - strict += usize::from(f_cached.resume > 0); - check("fallback_equal", f_cached.tokens == f_full.tokens); - } else { - eprintln!( - "CONV-INFO fallback_equal: different prefill chunks than the full read (equal={})", - f_cached.tokens == f_full.tokens - ); - } - let unrelated = encode(&chat("You are a terse assistant.", &[], "What is the capital of Poland?")); - let u = greedy(stack, &unrelated, "U(unrelated)"); - check("unrelated_empty", u.reused == 0); - - // 4. sampled: a seeded sampled follow-up of U, resumed vs read from 0 - 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 mut q = unrelated.clone(); - q.extend(u.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos)); - q.extend(encode("<|im_end|>\n<|im_start|>user\nAnd of Hungary?<|im_end|>\n<|im_start|>assistant\n")); - let s_cached = - serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled resumed request failed"); - eprintln!("CONV S(sampled cache) n={} reused={} out={}", q.len(), s_cached.reused, ids(&s_cached.tokens)); - if resumes { - check("sampled_resume", s_cached.reused > 0); - } - stack.forget_conversation(); - let s_full = - serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled full request failed"); - eprintln!("CONV S(sampled full) n={} reused={} out={}", q.len(), s_full.reused, ids(&s_full.tokens)); - if same_chunks(&q, s_cached.resume, (reread && s_cached.resume > 0).then_some(s_cached.resume), every, cache) { - strict += usize::from(s_cached.resume > 0); - check("sampled_equal", s_cached.tokens == s_full.tokens); - } else { - eprintln!( - "CONV-INFO sampled_equal: different prefill chunks than the full read (equal={})", - s_cached.tokens == s_full.tokens - ); - } - - // 5. cancel in the decode phase after the first committed round, then the next request - let mut q2 = q.clone(); - q2.extend(s_full.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos)); - q2.extend(encode("<|im_end|>\n<|im_start|>user\nAnd of Austria?<|im_end|>\n<|im_start|>assistant\n")); - let cancelled = serve_once(stack, &q2, max_new, None, eos, Some(1), None); - check("cancel_decode_reports_cancelled", matches!(cancelled, Err(ServeError::Cancelled))); - check("cancel_decode_healthy", stack.health().is_none()); - let after = greedy(stack, &q2, "Q2(after decode cancel)"); - stack.forget_conversation(); - let q2_full = greedy(stack, &q2, "Q2(full)"); - if same_chunks(&q2, after.resume, (reread && after.resume > 0).then_some(after.resume), every, cache) { - strict += usize::from(after.resume > 0); - check("cancel_decode_equal", after.tokens == q2_full.tokens); - } else { - eprintln!( - "CONV-INFO cancel_decode_equal: different prefill chunks than the full read (equal={})", - after.tokens == q2_full.tokens - ); - } - - // 6. cancel during the prefill of the long prompt, then the same prompt again - stack.forget_conversation(); - let cancelled = serve_once(stack, &a, max_new, None, eos, None, Some(cancel_probes)); - check("cancel_prefill_reports_cancelled", matches!(cancelled, Err(ServeError::Cancelled))); - check("cancel_prefill_healthy", stack.health().is_none()); - let a3 = greedy(stack, &a, "A3(after prefill cancel)"); - check("cancel_prefill_equal_cold", a3.tokens == a1.tokens); - eprintln!("CONV-DET A3 tokens={}", ids(&a3.tokens)); - check("final_health", stack.health().is_none()); - eprintln!("CONV strict resumed comparisons: {strict}"); - if resumes { - check("some_resumed_comparison_is_strict", strict >= 1); - } - }); - eprintln!("CONV-SUMMARY failed={failed:?}"); - assert!(failed.is_empty(), "conversation coverage checks failed: {failed:?}"); + smoke_coverage::run(); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs new file mode 100644 index 00000000..a174df8a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs @@ -0,0 +1,237 @@ +//! The conversation cache on the real model: the resume smoke, and the requests, the timing and the chunk +//! comparison the coverage smoke shares. +use super::*; + +/// What one request of the conversation smokes returned. +pub(super) struct Served { + pub(super) tokens: Vec, + pub(super) ttft: f64, + pub(super) reused: usize, + /// Where the conversation cache placed the request (with `STRATA_CKPT_REREAD` it then read from 0). + pub(super) resume: usize, +} + +/// The clock, the committed rounds and the cancel probes of one request. +struct Watch { + started: std::time::Instant, + first: std::cell::Cell>, + rounds: std::cell::Cell, + probes: std::cell::Cell, +} +impl Watch { + fn new() -> Watch { + Watch { + started: std::time::Instant::now(), + first: std::cell::Cell::new(None), + rounds: std::cell::Cell::new(0), + probes: std::cell::Cell::new(0), + } + } + fn on_round(&self) { + if self.first.get().is_none() { + self.first.set(Some(self.started.elapsed().as_secs_f64() * 1e3)); + } + self.rounds.set(self.rounds.get() + 1); + } + fn should_cancel(&self, cancel_rounds: Option, cancel_probes: Option) -> bool { + self.probes.set(self.probes.get() + 1); + cancel_rounds.is_some_and(|n| self.rounds.get() >= n) || cancel_probes.is_some_and(|n| self.probes.get() >= n) + } +} + +/// One request with an optional sampler and cancellation (after `cancel_rounds` committed rounds, or after +/// `cancel_probes` calls of the cancel flag, which the prefill polls before and during every chunk). +pub(super) fn serve_once( + stack: &mut OriginalServeStack<'_, '_>, + prompt: &[u32], + max_new: usize, + sampler: Option<&leleka_sampler_ref::SamplerParams>, + eos: u32, + cancel_rounds: Option, + cancel_probes: Option, +) -> Result { + let watch = Watch::new(); + let mut tokens = Vec::new(); + let result = stack.serve( + &request(prompt, max_new, sampler, eos), + &mut |round| { + watch.on_round(); + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || watch.should_cancel(cancel_rounds, cancel_probes), + ); + result.map(|outcome| { + assert_eq!(outcome.produced, tokens.len()); + Served { + tokens, + ttft: watch.first.get().unwrap_or(f64::NAN), + reused: stack.reused_tokens(), + resume: stack.resume_point(), + } + }) +} + +/// Whether a request read from `read_from` (a restore, or `STRATA_CKPT_REREAD`'s re-read from 0 up to +/// `reread_to`) cuts its prompt into the same batched chunks as the same request read from 0 with the cache on, +/// from `read_from` on. Only then must the two produce the same tokens: the batched prefill's arithmetic depends +/// on how the prompt is split (a root boundary is only cut when reading from 0, a resume point is a boundary the +/// full read does not have), so different chunks may flip a near tie, with or without the cache. +pub(super) fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option, every: usize, cache: bool) -> bool { + use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; + let options = PromptOptions { short_read: 64, force_batched: true, ..PromptOptions::original_mode17(16_384) }; + let options = if cache { + crate::qwen_forward::original_serve_stack::ConversationConfig { + prompt_cache_every: every, + ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() + } + .plan_options(options) + } else { + PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..options } + }; + let capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024); + let cuts = |resume: usize, reread_to: Option| -> Vec<(usize, usize)> { + PromptPlan::new(prompt, resume, reread_to, None, options, capacity) + .map(|plan| plan.filter(|a| a.path != PromptPath::FinalSeed).map(|a| (a.first, a.count)).collect()) + .unwrap_or_default() + }; + let full = cuts(0, None); + let read = cuts(resume, reread_to); + let from = read.first().map_or(prompt.len(), |a| a.0); + full.iter().filter(|a| a.0 >= from).copied().collect::>() == read + && full.iter().all(|a| a.0 >= from || a.0 + a.1 <= from) +} + +/// One greedy request; returns (tokens, time to the first committed round in ms, total ms, reused tokens). +fn timed( + stack: &mut OriginalServeStack<'_, '_>, + prompt: &[u32], + max_new: usize, + eos: u32, +) -> (Vec, f64, f64, usize) { + let started = std::time::Instant::now(); + let mut first: Option = None; + let mut tokens = Vec::new(); + let outcome = stack + .serve( + &request(prompt, max_new, None, eos), + &mut |round| { + first.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1e3); + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) + .unwrap_or_else(|e| { + eprintln!("CONV FAILED n={} error={e:?} health={:?}", prompt.len(), stack.health()); + panic!("conversation smoke request failed: {e:?}") + }); + assert_eq!(outcome.produced, tokens.len()); + (tokens, first.unwrap_or(f64::NAN), started.elapsed().as_secs_f64() * 1e3, stack.reused_tokens()) +} + +/// The chat requests of the resume smoke on one stack. +struct Resume<'a, 'ctx> { + stack: OriginalServeStack<'a, 'ctx>, + tokenizer: &'a Tokenizer, + eos: u32, + cache: bool, + max_new: usize, +} +impl Resume<'_, '_> { + /// 0. the first request after open is ONE token (the streamed-KV resolver was never initialised) + fn one_token(&mut self) { + let turn = self.tokenizer.encode("<|im_start|>", true).expect("turn token"); + assert_eq!(turn, [248_045], "<|im_start|> is the --turn-token"); + let (one, one_ttft, _, _) = timed(&mut self.stack, &turn, 4, self.eos); + eprintln!("CONV one-token prompt ok: {} tokens, ttft {one_ttft:.1} ms", one.len()); + } + /// 1. a chat request with a long system prompt; returns the prompt and the reply + fn first_chat(&mut self, system: &str) -> (Vec, Vec) { + let first_text = format!( + "<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\nName three \ + more European capitals.<|im_end|>\n<|im_start|>assistant\n" + ); + let first = self.tokenizer.encode(&first_text, true).expect("first prompt tokenization failed"); + let (reply, ttft_a, total_a, reused_a) = timed(&mut self.stack, &first, self.max_new, self.eos); + eprintln!("CONV A n={} reused={reused_a} ttft={ttft_a:.1}ms total={total_a:.1}ms out={reply:?}", first.len()); + (first, reply) + } + /// 2. the next turn: the first prompt, the reply, a new user turn; returns the prompt, the tokens and the TTFT + fn second_turn(&mut self, first: &[u32], reply: &[i32]) -> (Vec, Vec, f64) { + let eos = self.eos; + let mut second = first.to_vec(); + second.extend(reply.iter().map(|&t| t as u32).filter(|&t| t != eos)); + let next_turn = "<|im_end|>\n<|im_start|>user\nAnd the capital of Spain?<|im_end|>\n<|im_start|>assistant\n"; + second.extend(self.tokenizer.encode(next_turn, true).expect("second turn")); + let (cached, ttft_b, total_b, reused_b) = timed(&mut self.stack, &second, self.max_new, eos); + eprintln!( + "CONV B(cache) n={} reused={reused_b} ttft={ttft_b:.1}ms total={total_b:.1}ms out={cached:?}", + second.len() + ); + if self.cache { + assert!( + reused_b > 0 || env::var_os("STRATA_CKPT_REREAD").is_some(), + "the second turn must resume from a checkpoint" + ); + } else { + assert_eq!(reused_b, 0, "nothing is reused with the cache off"); + } + assert_eq!(self.stack.health(), None); + (second, cached, ttft_b) + } + /// 3. the same second request read from the empty prompt + fn full_read(&mut self, second: &[u32], cached: &[i32], ttft_b: f64) -> Vec { + self.stack.forget_conversation(); + let (full, ttft_f, total_f, reused_f) = timed(&mut self.stack, second, self.max_new, self.eos); + eprintln!( + "CONV B(full) n={} reused={reused_f} ttft={ttft_f:.1}ms total={total_f:.1}ms out={full:?}", + second.len() + ); + assert_eq!(reused_f, 0); + eprintln!("CONV greedy equal: {} ttft cache/full: {ttft_b:.1}/{ttft_f:.1} ms", cached == full); + full + } + /// 4. a new chat with the same system prompt resumes from the root checkpoint taken by step 3 + fn root_resume(&mut self, system: &str) { + let other_text = format!( + "<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\nWhat is the capital of \ + Poland?<|im_end|>\n<|im_start|>assistant\n" + ); + let other = self.tokenizer.encode(&other_text, true).expect("other prompt"); + let (other_out, ttft_o, _, reused_o) = timed(&mut self.stack, &other, self.max_new.min(16), self.eos); + eprintln!("CONV C(root) n={} reused={reused_o} ttft={ttft_o:.1}ms out={other_out:?}", other.len()); + assert_eq!(self.stack.health(), None); + } +} +fn resume_config(cache: bool) -> StackConfig { + let mut config = StackConfig::new(8192); + config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024); + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.conversation = cache.then(crate::qwen_forward::original_serve_stack::ConversationConfig::original); + config +} +pub(super) fn run_resume() { + let _ = dbg_el(); + optin(); + let pinned = open_pinned(false); + let budget_gib: usize = env_or("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); + let (cached, full) = with_context(budget_gib, |context| { + let cache = env::var("LELEKA_CONVERSATION_CACHE").map_or(true, |v| v != "off"); + let config = resume_config(cache); + eprintln!("CONV cache={}", if cache { "on" } else { "off" }); + let stack = open_stack(&pinned.binding, context, config); + let max_new: usize = env_or("LELEKA_CONVERSATION_MAX_NEW", 48); + let repeat: usize = env_or("LELEKA_CONVERSATION_SYSTEM_REPEAT", 120); + let mut resume = Resume { stack, tokenizer: &pinned.tokenizer, eos: pinned.eos, cache, max_new }; + resume.one_token(); + let system = format!("{PROMPT} ").repeat(repeat); + let (first, reply) = resume.first_chat(&system); + let (second, cached, ttft_b) = resume.second_turn(&first, &reply); + let full = resume.full_read(&second, &cached, ttft_b); + resume.root_resume(&system); + resume.stack.close().expect("stack cleanup failed"); + (cached, full) + }); + assert_eq!(cached, full, "a resumed request must produce the tokens of a full read"); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_corpus.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_corpus.rs new file mode 100644 index 00000000..6993a8ac --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_corpus.rs @@ -0,0 +1,244 @@ +//! The parity corpus of the main smoke: every line of `LELEKA_SMOKE_PROMPTS` is tokenized with the verified +//! tokenizer, served greedily for `LELEKA_SMOKE_MAX_NEW` tokens (default 64) and printed as ids so the Original +//! can be run on the same ids. +use super::*; +use crate::qwen_forward::{original_serve_engine::ServeOutcome, original_serve_request::original_stop_tokens}; + +/// One corpus line: its ids and the forced text (teacher forcing) of the quality gate, if any. +struct Line { + index: usize, + ids: Vec, + truth: Option>, + forced_passes: usize, + max_new: usize, +} +/// One timed pass over a line. +struct Pass { + out: Vec, + first: Option, + total: std::time::Duration, + served: Result, +} +fn joined(items: &[T], separator: &str) -> String { + items.iter().map(|t| t.to_string()).collect::>().join(separator) +} +/// LELEKA_SMOKE_PROMPT_IDS: a file of comma-separated token IDs, one prompt per line, instead of the text lines +fn arm_prompts(tokenizer: &Tokenizer, text: &str) -> Vec> { + match env::var_os("LELEKA_SMOKE_PROMPT_IDS") { + Some(ids) => std::fs::read_to_string(ids) + .expect("prompt id file unreadable") + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect()) + .collect(), + None => text + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| tokenizer.encode(l, true).expect("corpus tokenization failed")) + .collect(), + } +} +fn arm_order(prompts: usize) -> Vec { + env::var("LELEKA_SMOKE_ORDER") + .map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_SMOKE_ORDER: indices")).collect()) + .unwrap_or_else(|_| (0..prompts).collect()) +} +/// LELEKA_SMOKE_FORCE_DIR=dir (quality gate, docs/quality-gate.md): `dir/c.truth` is the comma-separated +/// token list of this prompt followed by the tokens another engine produced for it. The first +/// LELEKA_SMOKE_FORCE_PASSES (default 1) passes of this prompt decode along that text (teacher forcing: the +/// picks are replaced by the text's tokens, the logits and the `LELEKA_TRACE_LOGPROBS` rows are the port's own); +/// later passes are free. A forced pass produces exactly the forced tokens. +fn forced_truth(index: usize, ids: &[u32]) -> Option> { + env::var_os("LELEKA_SMOKE_FORCE_DIR").and_then(|dir| { + let file = std::path::Path::new(&dir).join(format!("c{index}.truth")); + let text = std::fs::read_to_string(&file).ok()?; + let sequence: Vec = text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect(); + assert!( + sequence.len() > ids.len() && sequence[..ids.len()].iter().zip(ids).all(|(a, &b)| *a == b as i32), + "{}: the forced sequence must start with the tokenized prompt and extend it", + file.display() + ); + Some(sequence) + }) +} +impl Smoke<'_, '_> { + /// Runs the corpus when `LELEKA_SMOKE_PROMPTS` is set; true when it ran the arms, which ends the smoke. + pub(super) fn corpus(&mut self) -> bool { + let Some(path) = env::var_os("LELEKA_SMOKE_PROMPTS") else { return false }; + let max_new: usize = env_or("LELEKA_SMOKE_MAX_NEW", 64); + let text = std::fs::read_to_string(path).expect("prompt corpus unreadable"); + // LELEKA_SMOKE_REPEAT serves every prompt N times (default 1) so warm timings are visible next to the + // first request. + let repeat: usize = env_or("LELEKA_SMOKE_REPEAT", 1).max(1); + // LELEKA_SMOKE_ARMS (see backend_original_serve_arms.rs): first-request A/B of the expert tier's policies; each + // prompt of LELEKA_SMOKE_ORDER (default: file order) is served once per arm from a first-request tier state, + // LELEKA_SMOKE_REPEAT times over the whole order. Replaces the plain corpus loop. + if let Ok(arms) = env::var("LELEKA_SMOKE_ARMS") { + self.arms_corpus(&arms, &text, max_new, repeat); + return true; + } + self.plain_corpus(&text, max_new, repeat); + false + } + fn arms_corpus(&mut self, arms: &str, text: &str, max_new: usize, repeat: usize) { + let arms = original_serve_arms::parse_arms(arms); + let prompts = arm_prompts(self.tokenizer, text); + let order = arm_order(prompts.len()); + let min_p: f32 = env_or("LELEKA_SMOKE_MIN_P", 0.0); + for rep in 0..repeat { + for (k, &index) in order.iter().enumerate() { + if rep == 0 { + let ids = &prompts[index]; + eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), joined(ids, ",")); + } + self.arm_prompt(&arms, (index, prompts[index].as_slice()), (k + rep, rep), (max_new, min_p)); + } + } + } + /// Serves one prompt once per arm; `turn` is the position in the order plus the repetition. + fn arm_prompt( + &mut self, + arms: &[original_serve_arms::ArmSpec], + (index, ids): (usize, &[u32]), + (turn, rep): (usize, usize), + (max_new, min_p): (usize, f32), + ) { + for arm in original_serve_arms::arms_for(arms, turn) { + let stop = original_stop_tokens(self.eos); + let request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, None, 7, min_p, stop); + let tag = format!("p{index} rep{rep}"); + let note = format!("prompt={}", ids.len()); + original_serve_arms::serve_arm(&mut self.stack, &arm, &request, &tag, ¬e); + } + } + /// LELEKA_SPEC_ARMS (see OriginalServeSettings::arms_from_environment): pass p of prompt i is served by arm + /// (p + i) % arms, so a prompt meets every arm (LELEKA_SMOKE_REPEAT = arms x repetitions) in a rotated order. + fn plain_corpus(&mut self, text: &str, max_new: usize, repeat: usize) { + let spec_arms = self.stack.spec_arms(); + for (index, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { + let line = self.corpus_line(index, line, max_new); + for pass in 0..repeat { + self.corpus_pass(&line, pass, &spec_arms); + } + } + } + fn corpus_line(&self, index: usize, line: &str, max_new: usize) -> Line { + // `@file:PATH` stands for the whole content of that file (a source file to rewrite: code with its newlines) + let file_text; + let line = match line.trim().strip_prefix("@file:") { + Some(path) => { + file_text = std::fs::read_to_string(path.trim()).expect("@file prompt unreadable"); + file_text.as_str() + } + None => line, + }; + // 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\n\n\n\n", line.trim()) + } else { + line.to_owned() + }; + let ids = self.tokenizer.encode(&turn, true).expect("corpus tokenization failed"); + eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), joined(&ids, ",")); + let truth = forced_truth(index, &ids); + let forced_passes: usize = env_or("LELEKA_SMOKE_FORCE_PASSES", 1); + Line { index, ids, truth, forced_passes, max_new } + } + fn corpus_request(&self, ids: &[u32], max_new: usize) -> ServeRequest { + let min_p: f32 = self.stack.spec_arm_min_p().unwrap_or_else(|| env_or("LELEKA_SMOKE_MIN_P", 0.0)); + // 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 = agent_sampler(); + ServeRequest::new( + ids.iter().map(|&t| t as i32).collect(), + max_new, + sampled.then_some(&sampler), + 7, + min_p, + original_stop_tokens(self.eos), + ) + } + fn timed_serve(&mut self, request: &ServeRequest) -> Pass { + let started = std::time::Instant::now(); + let mut first: Option = None; + let mut out = Vec::new(); + let served = self.stack.serve( + request, + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); + Pass { out, first, total: started.elapsed(), served } + } + fn corpus_pass(&mut self, line: &Line, pass: usize, spec_arms: &[String]) { + let (index, ids) = (line.index, &line.ids); + if !spec_arms.is_empty() { + assert!(self.stack.select_spec_arm(&spec_arms[(pass + index) % spec_arms.len()])); + } + let forced = line.truth.as_ref().filter(|_| pass < line.forced_passes); + crate::qwen_forward::quality_force::set(forced.cloned()); + eprintln!("DBG corpus {index} pass={pass} begin forced={}", forced.is_some()); + let max_new = forced.map_or(line.max_new, |t| t.len() - ids.len()); + let request = self.corpus_request(ids, max_new); + let run = self.timed_serve(&request); + crate::qwen_forward::quality_force::set(None); + if let (Some(t), Ok(_)) = (forced, &run.served) { + eprintln!( + "DBG corpus {index} pass={pass} forced: produced {} of {} forced tokens, stopped as forced: {}", + run.out.len(), + t.len() - ids.len(), + run.out.iter().zip(&t[ids.len()..]).all(|(a, b)| a == b) + ); + } + self.report_pass(line, pass, spec_arms.is_empty(), &run); + } + fn report_pass(&self, line: &Line, pass: usize, no_spec_arms: bool, run: &Pass) { + let (index, out) = (line.index, &run.out); + let outcome = match &run.served { + Ok(outcome) => outcome, + Err(e) => { + eprintln!("DBG corpus {index} pass={pass} FAILED {e:?} health={:?}", self.stack.health()); + return; + } + }; + if pass == 0 && no_spec_arms { + let output = joined(out, " "); + eprintln!("DBG corpus {index} output ({} tokens, rounds {}): {output}", out.len(), outcome.rounds); + } else { + eprintln!( + "DBG corpus {index} output pass={pass} arm={} ({} tokens, rounds {}): {}", + self.stack.spec_arm(), + out.len(), + outcome.rounds, + joined(out, " ") + ); + } + self.report_timing_line(line, pass, run, outcome.rounds); + report_timing(&self.stack, &format!("corpus {index} pass {pass}"), out.len()); + } + fn report_timing_line(&self, line: &Line, pass: usize, run: &Pass, rounds: usize) { + let out = &run.out; + let ttft = run.first.unwrap_or(run.total); + let decode_s = (run.total - ttft).as_secs_f64(); + let decode_tps = if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 }; + eprintln!( + "DBG corpus {} timing pass={pass} arm={} prompt={} produced={} rounds={rounds} ttft_ms={:.1} \ + total_ms={:.1} decode_tok_s={:.2}", + line.index, + self.stack.spec_arm(), + line.ids.len(), + out.len(), + ttft.as_secs_f64() * 1e3, + run.total.as_secs_f64() * 1e3, + decode_tps + ); + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_coverage.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_coverage.rs new file mode 100644 index 00000000..1eb71f46 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_coverage.rs @@ -0,0 +1,231 @@ +//! Coverage of the conversation cache on the real model (documented on +//! `original_serve_conversation_coverage_smoke`): every resumed request is compared token for token with the +//! same request read from the empty prompt; every check prints a `CONV-CHECK name ok|FAIL` line. +use super::*; + +/// The knobs of the coverage smoke. +struct Knobs { + cache: bool, + reread: bool, + every: usize, + max_new: usize, + cancel_probes: usize, +} +impl Knobs { + fn from_env() -> Knobs { + let cache = env::var("LELEKA_CONVERSATION_CACHE").map_or(true, |v| v != "off"); + let every = env_or("LELEKA_CONVERSATION_EVERY", 2048); + Knobs { + cache, + reread: env::var_os("STRATA_CKPT_REREAD").is_some(), + every, + max_new: env_or("LELEKA_CONVERSATION_MAX_NEW", 48), + cancel_probes: env_or("LELEKA_CONVERSATION_CANCEL_PROBES", 4), + } + } +} +fn chat(system: &str, turns: &[(&str, &str)], user: &str) -> String { + let mut text = format!("<|im_start|>system\n{system}<|im_end|>\n"); + for (u, a) in turns { + text.push_str(&format!("<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n")); + } + text.push_str(&format!("<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n")); + text +} +/// The stack under test, the checks so far and the number of strict resumed comparisons. +struct Cov<'a, 'ctx> { + stack: OriginalServeStack<'a, 'ctx>, + tokenizer: &'a Tokenizer, + eos: u32, + knobs: Knobs, + failed: Vec<&'static str>, + strict: usize, +} +impl Cov<'_, '_> { + fn check(&mut self, name: &'static str, ok: bool) { + eprintln!("CONV-CHECK {name} {}", if ok { "ok" } else { "FAIL" }); + if !ok { + self.failed.push(name); + } + } + fn encode(&self, text: &str) -> Vec { + self.tokenizer.encode(text, true).expect("tokenization failed") + } + fn greedy(&mut self, prompt: &[u32], what: &str) -> Served { + let served = serve_once(&mut self.stack, prompt, self.knobs.max_new, None, self.eos, None, None) + .unwrap_or_else(|e| panic!("CONV {what} failed: {e:?} health={:?}", self.stack.health())); + eprintln!( + "CONV {what} n={} reused={} ttft={:.1}ms out={}", + prompt.len(), + served.reused, + served.ttft, + ids(&served.tokens) + ); + served + } + /// The tokens of the reply of a request without the EOS, to continue the prompt with. + fn reply_ids(&self, tokens: &[i32]) -> Vec { + tokens.iter().map(|&t| t as u32).filter(|&t| t != self.eos).collect() + } + /// Compares a resumed request with the same request read from 0 when both cut the prompt the same way. + fn compare(&mut self, name: &'static str, prompt: &[u32], cached: &Served, full: &Served) { + let Knobs { cache, reread, every, .. } = self.knobs; + let reread_to = (reread && cached.resume > 0).then_some(cached.resume); + if same_chunks(prompt, cached.resume, reread_to, every, cache) { + self.strict += usize::from(cached.resume > 0); + self.check(name, cached.tokens == full.tokens); + } else { + eprintln!( + "CONV-INFO {name}: different prefill chunks than the full read (equal={})", + cached.tokens == full.tokens + ); + } + } + fn resumes(&self) -> bool { + self.knobs.cache && !self.knobs.reread + } + /// 1. determinism: chat A read cold twice in this process + fn determinism(&mut self, system: &str) -> (Vec, Served) { + let a = self.encode(&chat(system, &[], "Name three more European capitals.")); + let a1 = self.greedy(&a, "A1(cold)"); + self.stack.forget_conversation(); + let a2 = self.greedy(&a, "A2(cold)"); + eprintln!("CONV-DET A1 tokens={}", ids(&a1.tokens)); + eprintln!("CONV-DET A2 tokens={}", ids(&a2.tokens)); + self.check("determinism_same_process", a1.tokens == a2.tokens); + (a, a1) + } + /// 2. periodic checkpoint: diverge inside the system prompt, past the 4096 periodic checkpoint; returns the + /// edited system prompt, the prompt and the tokens of its full read + fn periodic(&mut self, system: &str, a: &[u32]) -> (String, Vec, Served) { + let every = self.knobs.every; + let cut = system.len() * 9 / 10; + let edited = format!("{} Note: this sentence was inserted. {}", &system[..cut], &system[cut..]); + let p = self.encode(&chat(&edited, &[], "Name three more European capitals.")); + let shared = p.iter().zip(a).take_while(|(x, y)| x == y).count(); + let p_cached = self.greedy(&p, "P(periodic)"); + let expected = (shared.min(p.len() - 1) / every) * every; + eprintln!("CONV P shared_prefix={shared} expected_resume={expected}"); + if self.resumes() { + self.check("periodic_resume", every > 0 && p_cached.reused == expected && expected > 0); + } + self.stack.forget_conversation(); + let p_full = self.greedy(&p, "P(full)"); + self.compare("periodic_equal", &p, &p_cached, &p_full); + (edited, p, p_full) + } + /// 3. fallback: the follow-up edits the earlier user turn (it does NOT extend the previous prompt); then an + /// unrelated prompt starts empty. Returns the unrelated prompt and its reply. + fn fallback(&mut self, edited: &str, p: &[u32], p_full: &Served) -> (Vec, Served) { + let reply = self.tokenizer.decode(&self.reply_ids(&p_full.tokens)).unwrap_or_default(); + let follow = self.encode(&chat( + edited, + &[("Name three other European capitals.", reply.as_str())], + "And the capital of Spain?", + )); + let f_cached = self.greedy(&follow, "F(root fallback)"); + if self.resumes() { + // the edited user turn starts right after the root (the first turn boundary past the system prompt) + self.check("fallback_root", f_cached.reused > 4096 && f_cached.reused < p.len() - 8); + } + self.stack.forget_conversation(); + let f_full = self.greedy(&follow, "F(full)"); + self.compare("fallback_equal", &follow, &f_cached, &f_full); + let unrelated = self.encode(&chat("You are a terse assistant.", &[], "What is the capital of Poland?")); + let u = self.greedy(&unrelated, "U(unrelated)"); + self.check("unrelated_empty", u.reused == 0); + (unrelated, u) + } + /// 4. sampled: a seeded sampled follow-up of U, resumed vs read from 0; returns the prompt and the full read + fn sampled(&mut self, unrelated: &[u32], u: &Served) -> (Vec, Served) { + let sampler = agent_sampler(); + let (max_new, eos) = (self.knobs.max_new, self.eos); + let mut q = unrelated.to_vec(); + q.extend(self.reply_ids(&u.tokens)); + q.extend(self.encode("<|im_end|>\n<|im_start|>user\nAnd of Hungary?<|im_end|>\n<|im_start|>assistant\n")); + let s_cached = serve_once(&mut self.stack, &q, max_new, Some(&sampler), eos, None, None) + .expect("sampled resumed request failed"); + eprintln!("CONV S(sampled cache) n={} reused={} out={}", q.len(), s_cached.reused, ids(&s_cached.tokens)); + if self.resumes() { + self.check("sampled_resume", s_cached.reused > 0); + } + self.stack.forget_conversation(); + let s_full = serve_once(&mut self.stack, &q, max_new, Some(&sampler), eos, None, None) + .expect("sampled full request failed"); + eprintln!("CONV S(sampled full) n={} reused={} out={}", q.len(), s_full.reused, ids(&s_full.tokens)); + self.compare("sampled_equal", &q, &s_cached, &s_full); + (q, s_full) + } + /// 5. cancel in the decode phase after the first committed round, then the next request + fn cancel_decode(&mut self, q: &[u32], s_full: &Served) { + let mut q2 = q.to_vec(); + q2.extend(self.reply_ids(&s_full.tokens)); + q2.extend(self.encode("<|im_end|>\n<|im_start|>user\nAnd of Austria?<|im_end|>\n<|im_start|>assistant\n")); + let cancelled = serve_once(&mut self.stack, &q2, self.knobs.max_new, None, self.eos, Some(1), None); + self.check("cancel_decode_reports_cancelled", matches!(cancelled, Err(ServeError::Cancelled))); + self.check("cancel_decode_healthy", self.stack.health().is_none()); + let after = self.greedy(&q2, "Q2(after decode cancel)"); + self.stack.forget_conversation(); + let q2_full = self.greedy(&q2, "Q2(full)"); + self.compare("cancel_decode_equal", &q2, &after, &q2_full); + } + /// 6. cancel during the prefill of the long prompt, then the same prompt again + fn cancel_prefill(&mut self, a: &[u32], a1: &Served) { + self.stack.forget_conversation(); + let (max_new, eos, probes) = (self.knobs.max_new, self.eos, self.knobs.cancel_probes); + let cancelled = serve_once(&mut self.stack, a, max_new, None, eos, None, Some(probes)); + self.check("cancel_prefill_reports_cancelled", matches!(cancelled, Err(ServeError::Cancelled))); + self.check("cancel_prefill_healthy", self.stack.health().is_none()); + let a3 = self.greedy(a, "A3(after prefill cancel)"); + self.check("cancel_prefill_equal_cold", a3.tokens == a1.tokens); + eprintln!("CONV-DET A3 tokens={}", ids(&a3.tokens)); + self.check("final_health", self.stack.health().is_none()); + eprintln!("CONV strict resumed comparisons: {}", self.strict); + if self.resumes() { + self.check("some_resumed_comparison_is_strict", self.strict >= 1); + } + } + fn steps(&mut self, repeat: usize) { + let system = format!("{PROMPT} ").repeat(repeat); + let (a, a1) = self.determinism(&system); + let (edited, p, p_full) = self.periodic(&system, &a); + let (unrelated, u) = self.fallback(&edited, &p, &p_full); + let (q, s_full) = self.sampled(&unrelated, &u); + self.cancel_decode(&q, &s_full); + self.cancel_prefill(&a, &a1); + } +} +fn coverage_config(conversation: Option) -> StackConfig { + let mut config = StackConfig::new(16_384); + config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024); + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.conversation = conversation; + config +} +pub(super) fn run() { + let _ = dbg_el(); + let knobs = Knobs::from_env(); + let Knobs { cache, reread, every, max_new, .. } = knobs; + let conversation = cache.then(|| crate::qwen_forward::original_serve_stack::ConversationConfig { + prompt_cache_every: every, + ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() + }); + let repeat: usize = env_or("LELEKA_CONVERSATION_SYSTEM_REPEAT", 250); + eprintln!( + "CONV cache={} reread={reread} every={every} max_new={max_new} repeat={repeat}", + if cache { "on" } else { "off" } + ); + optin(); + let pinned = open_pinned(false); + let budget_gib: usize = env_or("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); + let failed = with_context(budget_gib, |context| { + let stack = open_stack(&pinned.binding, context, coverage_config(conversation)); + let mut cov = + Cov { stack, tokenizer: &pinned.tokenizer, eos: pinned.eos, knobs, failed: Vec::new(), strict: 0 }; + cov.steps(repeat); + cov.stack.close().expect("stack cleanup failed"); + cov.failed + }); + eprintln!("CONV-SUMMARY failed={failed:?}"); + assert!(failed.is_empty(), "conversation coverage checks failed: {failed:?}"); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_long.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_long.rs new file mode 100644 index 00000000..ad1552a8 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_long.rs @@ -0,0 +1,315 @@ +//! Long-context smoke of the streamed INT8 KV: one greedy request over a prompt far longer than the resident +//! window (documented on `original_serve_long_context_streamed_kv_smoke`). +use super::*; +use std::time::Instant; + +const COLORS: [&str; 8] = ["amber", "blue", "crimson", "green", "grey", "ivory", "orange", "violet"]; +const THINGS: [&str; 8] = ["heron", "lantern", "barge", "orchard", "glacier", "market", "violin", "quarry"]; +const PLACES: [&str; 8] = ["harbour", "valley", "library", "bridge", "station", "garden", "tower", "village"]; + +/// The knobs of the long smoke that decide the prompts and the ceiling. +struct Plan { + targets: Vec, + target: usize, + resident: usize, + max_context: usize, + max_new: usize, +} +impl Plan { + fn from_env() -> Plan { + // one prompt length, or a comma-separated list served in order on the same stack + let targets: Vec = env::var("LELEKA_ORIGINAL_SERVE_LONG_TOKENS") + .map(|v| { + v.split(',') + .map(|t| t.trim().parse().expect("LELEKA_ORIGINAL_SERVE_LONG_TOKENS must be counts")) + .collect() + }) + .unwrap_or_else(|_| vec![40_000]); + let target = targets.iter().copied().max().expect("at least one prompt length"); + let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); + let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 65_536); + let max_new = number("LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW", 32); + assert!( + targets.iter().all(|&t| t >= 64) && target + max_new + 8 <= max_context, + "the prompt and the answer must fit the ceiling" + ); + Plan { targets, target, resident, max_context, max_new } + } +} +/// 64 deterministic varied sentences; `state` and `note` advance. +fn notes(state: &mut u64, note: &mut usize) -> String { + let mut sentences = String::new(); + for _ in 0..64 { + *state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + let s = *state; + let pick = |shift: u32| (s >> shift) as usize % 8; + sentences.push_str(&format!( + "Note {}: the {} {} near the {} was counted {} times. ", + *note, + COLORS[pick(20)], + THINGS[pick(30)], + PLACES[pick(40)], + (s >> 50) % 997 + )); + *note += 1; + } + sentences +} +/// Deterministic varied filler of `budget` tokens, or the tokens of `LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE` repeated. +fn filler(tokenizer: &Tokenizer, budget: usize) -> Vec { + let mut filler: Vec = Vec::with_capacity(budget + 64); + let mut state = 0x2545_f491u64; + let mut note = 0usize; + if let Some(path) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE") { + let text = std::fs::read_to_string(path).expect("long text file unreadable"); + let ids = tokenizer.encode(&text, false).expect("tokenization failed"); + assert!(!ids.is_empty(), "empty long text file"); + while filler.len() < budget { + filler.extend_from_slice(&ids); + } + } + while filler.len() < budget { + let sentences = notes(&mut state, &mut note); + filler.extend(tokenizer.encode(&sentences, false).expect("tokenization failed")); + } + filler.truncate(budget); + filler +} +fn head_and_question(tokenizer: &Tokenizer) -> (Vec, Vec) { + let head = tokenizer + .encode("Remember this: the secret passcode is 4817-QX. Below is a long log of unrelated notes.\n\n", true) + .expect("tokenization failed"); + let question = tokenizer + .encode( + "\n\nEnd of the notes. Question: what is the secret passcode given at the very beginning? \ + Answer: the secret passcode is", + false, + ) + .expect("tokenization failed"); + // LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE: a natural document (e.g. source code) as the filler instead of the + // notes, and LELEKA_ORIGINAL_SERVE_LONG_QUESTION: the closing question for it + let question = match env::var("LELEKA_ORIGINAL_SERVE_LONG_QUESTION") { + Ok(q) => tokenizer.encode(&q, false).expect("tokenization failed"), + Err(_) => question, + }; + (head, question) +} +/// The prompt: passcode, deterministic varied filler up to the target length, the question. Every shorter prompt +/// takes a prefix of the same filler (what a single-length run builds). +fn build_prompts(tokenizer: &Tokenizer, plan: &Plan) -> Vec> { + let (head, question) = head_and_question(tokenizer); + let budget = plan.target.saturating_sub(head.len() + question.len()); + let filler = filler(tokenizer, budget); + plan.targets + .iter() + .map(|&t| { + let budget = t.saturating_sub(head.len() + question.len()); + head.iter().chain(&filler[..budget]).chain(&question).copied().collect() + }) + .collect() +} +fn long_config(plan: &Plan) -> StackConfig { + let mut config = StackConfig::new(plan.max_context as i64); + config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.kv_resident = plan.resident; + // A prefill measurement: every request is read from the empty prompt unless + // LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION=yes keeps the stack's conversation cache. + if !env::var("LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION").is_ok_and(|v| v == "yes") { + config.conversation = None; + } + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + eprintln!("long-smoke capacity={} expert tier {:?}", config.capacity, config.expert_tier); + config +} +/// LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt.ids` (comma-separated) for the Original's +/// `--tokens-file`, so both engines read the identical token sequence +fn write_prompt_ids(prompt: &[u32]) { + if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") { + let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len())); + let text = prompt.iter().map(|t| t.to_string()).collect::>().join(","); + std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + eprintln!("long-smoke prompt ids -> {}", path.display()); + } +} +/// What varies from pass to pass of one prompt. +struct Passes { + spec_arms: Vec, + spec_min_p: f32, + forced_answer: Option>, + max_new: usize, + stream_seq: Vec<(i8, usize)>, + late_seq: Vec, +} +impl Passes { + fn for_prompt(stack: &OriginalServeStack<'_, '_>, prompt: &[u32], max_new: usize) -> Passes { + // LELEKA_SPEC_ARMS: pass p of the prompt is served by arm p % arms (the window policy A/B inside one load); + // LELEKA_SMOKE_MIN_P: the request's draft floor (default 0). + let spec_arms = stack.spec_arms(); + let spec_min_p: f32 = env_or("LELEKA_SMOKE_MIN_P", 0.0); + let forced_answer = forced_answer(prompt); + let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len()); + // LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process) + let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ") + .map(|v| { + v.split(',') + .filter_map(|t| { + let mut parts = t.trim().splitn(2, ':'); + Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0))) + }) + .collect() + }) + .unwrap_or_default(); + // LELEKA_QSA_LATE_SEQ=1,0,0,1: the QSA late-selection kernels per pass (paired A/B inside one process) + let late_seq: Vec = env::var("LELEKA_QSA_LATE_SEQ") + .map(|v| v.split(',').filter_map(|t| t.trim().parse().ok()).collect()) + .unwrap_or_default(); + Passes { spec_arms, spec_min_p, forced_answer, max_new, stream_seq, late_seq } + } + fn late_override(&self, pass: usize) { + if !self.late_seq.is_empty() { + let v = self.late_seq[pass % self.late_seq.len()]; + leleka_cuda_driver::set_qsa_late_override(v); + eprintln!("long-smoke pass={pass} qsa_late={v}"); + } + } + fn stream_override(&self, pass: usize) { + if !self.stream_seq.is_empty() { + let (v, depth) = self.stream_seq[pass % self.stream_seq.len()]; + leleka_cuda_driver::compute_drain::set_issue_depth(depth); + // bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight + crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE + .store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed); + leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0); + eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}"); + } + } +} +/// LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer.ids` (comma-separated) +/// holds the tokens another engine answered to the N-token prompt; the request then decodes along that text +/// (teacher forcing, see `quality_force`) for exactly that many tokens, with the port's own logits and +/// `LELEKA_TRACE_LOGPROBS` rows. +fn forced_answer(prompt: &[u32]) -> Option> { + env::var_os("LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR").and_then(|dir| { + let text = std::fs::read_to_string(PathBuf::from(dir).join(format!("answer{}.ids", prompt.len()))).ok()?; + Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect()) + }) +} +/// The stack under test and the knobs of the run. +struct Long<'a, 'ctx> { + stack: OriginalServeStack<'a, 'ctx>, + tokenizer: &'a Tokenizer, + eos: u32, + plan: &'a Plan, + repeat: usize, +} +impl Long<'_, '_> { + /// LELEKA_ORIGINAL_SERVE_LONG_ARMS (see backend_original_serve_arms.rs): the prompt once per arm from a + /// first-request tier state, the order reversed on odd passes (`repeat` passes); replaces the plain passes. + fn arms(&mut self, arms: &str, prompt: &[u32]) { + let arms = original_serve_arms::parse_arms(arms); + for pass in 0..self.repeat { + for arm in original_serve_arms::arms_for(&arms, pass) { + original_serve_arms::serve_arm( + &mut self.stack, + &arm, + &request(prompt, self.plan.max_new, None, self.eos), + &format!("long pass{pass}"), + &format!("prompt={}", prompt.len()), + ); + } + } + } + fn report(&self, pass: usize, prompt: &[u32], tokens: &[i32], started: Instant, produced: (usize, usize)) { + let (prompt_ms, decode_ms) = self.stack.last_timing(); + eprintln!( + "long-smoke prefill pass={pass} arm={} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} \ + decode_ms={decode_ms:.1}", + self.stack.spec_arm(), + prompt.len(), + (prompt.len() - 1) as f64 / (prompt_ms / 1e3).max(1e-9) + ); + let token_ids: Vec = tokens.iter().map(|&t| t as u32).collect(); + let text = self.tokenizer.decode(&token_ids).unwrap_or_default(); + eprintln!("long-smoke output ids ({}): {}", token_ids.len(), ids(tokens)); + eprintln!( + "long-smoke result pass={pass} prompt={} resident={} produced={} rounds={} wall_s={:.1} needle_found={} \ + text={text:?}", + prompt.len(), + self.plan.resident, + produced.0, + produced.1, + started.elapsed().as_secs_f64(), + text.contains("4817") + ); + } + fn pass(&mut self, prompt: &[u32], pass: usize, passes: &Passes) { + passes.late_override(pass); + crate::qwen_forward::quality_force::set( + passes + .forced_answer + .as_ref() + .map(|answer| prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect()), + ); + passes.stream_override(pass); + if !passes.spec_arms.is_empty() { + assert!(self.stack.select_spec_arm(&passes.spec_arms[pass % passes.spec_arms.len()])); + } + let started = Instant::now(); + let long_request = ServeRequest::new( + prompt.iter().map(|&t| t as i32).collect(), + passes.max_new, + None, + 7, + passes.spec_min_p, + vec![self.eos as i32], + ); + let (result, tokens) = collect(&mut self.stack, &long_request); + let outcome = + result.unwrap_or_else(|e| panic!("long-context request failed: {e:?} health={:?}", self.stack.health())); + crate::qwen_forward::quality_force::set(None); + assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); + assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); + assert_eq!(self.stack.health(), None); + self.report(pass, prompt, &tokens, started, (outcome.produced, outcome.rounds)); + } + fn prompt(&mut self, prompt: &[u32]) { + eprintln!( + "long-smoke prompt tokens={} kv-resident={} max-context={}", + prompt.len(), + self.plan.resident, + self.plan.max_context + ); + write_prompt_ids(prompt); + if let Ok(arms) = env::var("LELEKA_ORIGINAL_SERVE_LONG_ARMS") { + self.arms(&arms, prompt); + return; + } + let passes = Passes::for_prompt(&self.stack, prompt, self.plan.max_new); + for pass in 0..self.repeat { + self.pass(prompt, pass, &passes); + } + } +} +pub(super) fn run() { + let _ = dbg_el(); + assert!( + env::var("LELEKA_ORIGINAL_SERVE_LONG_SMOKE").is_ok_and(|value| value == "yes"), + "explicit long-context serve smoke opt-in required" + ); + let plan = Plan::from_env(); + let pinned = open_pinned(false); + let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); + with_context(budget_gib, |context| { + let prompts = build_prompts(&pinned.tokenizer, &plan); + let config = long_config(&plan); + let repeat = number("LELEKA_ORIGINAL_SERVE_LONG_REPEAT", 1).max(1); + let stack = open_stack(&pinned.binding, context, config); + let mut long = Long { stack, tokenizer: &pinned.tokenizer, eos: pinned.eos, plan: &plan, repeat }; + for prompt in &prompts { + long.prompt(prompt); + } + long.stack.close().expect("stack cleanup failed"); + }); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_main.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_main.rs new file mode 100644 index 00000000..9413029d --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_main.rs @@ -0,0 +1,143 @@ +//! The main smoke: greedy twice across a reset, a sampled request, a cancellation, the optional parity corpus +//! and a short prompt on the scalar draft-KV path. +use super::*; + +#[path = "backend_original_serve_smoke_corpus.rs"] +mod corpus; + +/// The stack under test, with what every step needs of it. +struct Smoke<'a, 'ctx> { + stack: OriginalServeStack<'a, 'ctx>, + tokenizer: &'a Tokenizer, + eos: u32, + /// With the expert tier on, adaptive swaps move experts between the GPU and the CPU between requests and the + /// two round differently, so a repeated greedy request may legitimately differ: reported, not asserted. + tier_on: bool, +} +fn smoke_config() -> StackConfig { + let mut config = StackConfig::new(env_or("LELEKA_SMOKE_MAX_CONTEXT", 4096)); + config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024); + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + if let Some(cells) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT").ok().and_then(|v| v.parse().ok()) { + config.kv_resident = cells; + } + // LELEKA_SMOKE_PROMPT_CACHE=0: every request reads its whole prompt (the first-request experiments) + if env::var("LELEKA_SMOKE_PROMPT_CACHE").is_ok_and(|v| v == "0") { + config.conversation = None; + } + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + eprintln!("DBG smoke: expert tier {:?}", config.expert_tier); + config +} +impl Smoke<'_, '_> { + fn same(&self, label: &str, a: &[i32], b: &[i32]) { + if !self.tier_on { + assert_eq!(a, b, "{label}"); + return; + } + let first = a.iter().zip(b).position(|(x, y)| x != y); + eprintln!( + "DBG smoke: {label}: {} (expert tier on: residency changes between requests)", + match first { + None if a.len() == b.len() => "identical".to_owned(), + None => format!("lengths {} vs {}", a.len(), b.len()), + Some(i) => format!("first difference at token {i}"), + } + ); + } + /// 1. greedy, twice: the second request starts from a reset and must reproduce the first exactly + fn greedy_twice(&mut self, prompt: &[u32]) -> Vec> { + let mut runs: Vec> = Vec::new(); + for _ in 0..2 { + let (outcome, tokens) = collect(&mut self.stack, &request(prompt, 24, None, self.eos)); + let outcome = outcome.unwrap_or_else(|e| panic!("greedy request failed: {e:?}")); + assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); + assert_eq!(outcome.produced, tokens.len()); + assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); + report_timing(&self.stack, "greedy", tokens.len()); + runs.push(tokens); + } + eprintln!("DBG[{:.0}s] smoke: greedy run0 tokens ({}): {:?}", dbg_el(), runs[0].len(), runs[0]); + eprintln!("DBG[{:.0}s] smoke: greedy run1 tokens ({}): {:?}", dbg_el(), runs[1].len(), runs[1]); + self.same("a reset must return to the empty prompt", &runs[0], &runs[1]); + assert_eq!(self.stack.health(), None); + runs + } + /// 2. a sampled request with penalties completes + fn sampled(&mut self, prompt: &[u32]) { + let sampler = agent_sampler(); + let (result, sampled) = collect(&mut self.stack, &request(prompt, 16, Some(&sampler), self.eos)); + result.unwrap_or_else(|e| panic!("sampled request failed: {e:?}")); + eprintln!("DBG[{:.0}s] smoke: sampled tokens ({}): {:?}", dbg_el(), sampled.len(), sampled); + assert!(!sampled.is_empty()); + } + /// 3. cancellation after the first committed round returns Cancelled and leaves the stack usable + fn cancelled(&mut self, prompt: &[u32], first_run: &[i32]) { + let emitted = std::cell::Cell::new(0usize); + let cancelled = self.stack.serve( + &request(prompt, 64, None, self.eos), + &mut |round| { + emitted.set(emitted.get() + round.len()); + Ok(()) + }, + &mut || emitted.get() > 0, + ); + assert_eq!(cancelled.err(), Some(ServeError::Cancelled)); + assert_eq!(self.stack.health(), None); + let (result, after) = collect(&mut self.stack, &request(prompt, 24, None, self.eos)); + result.unwrap_or_else(|e| panic!("request after a cancellation failed: {e:?}")); + self.same("a cancelled request must not disturb the next one", &after, first_run); + } + /// 4. a short prompt (<= 64 tokens) takes the scalar draft-KV path of the Original; report instead of asserting + fn short_prompt(&mut self, short_prompt: &[u32]) { + eprintln!("DBG[{:.0}s] smoke: short-prompt request ({} tokens)", dbg_el(), short_prompt.len()); + let (result, short_out) = collect(&mut self.stack, &request(short_prompt, 16, None, self.eos)); + match result { + Ok(outcome) => eprintln!( + "DBG[{:.0}s] smoke: short prompt ok produced={} tokens={:?}", + dbg_el(), + outcome.produced, + short_out + ), + Err(e) => { + eprintln!("DBG[{:.0}s] smoke: short prompt FAILED {e:?} health={:?}", dbg_el(), self.stack.health()) + } + } + } + fn steps(&mut self, short_prompt: &[u32], prompt: &[u32]) { + let runs = self.greedy_twice(prompt); + self.sampled(prompt); + self.cancelled(prompt, &runs[0]); + // 3b. the parity corpus ends the smoke when it ran the arms + if self.corpus() { + return; + } + self.short_prompt(short_prompt); + } +} +pub(super) fn run() { + let _ = dbg_el(); + optin(); + let pinned = open_pinned(true); + let budget_gib: usize = env_or("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 28); + with_context(budget_gib, |context| { + let config = smoke_config(); + let tier_on = config.expert_tier.enabled(); + eprintln!( + "DBG[{:.0}s] smoke: opening serve stack (budget {budget_gib} GiB, capacity {})", + dbg_el(), + config.capacity + ); + let stack = open_stack(&pinned.binding, context, config); + let mut smoke = Smoke { stack, tokenizer: &pinned.tokenizer, eos: pinned.eos, tier_on }; + eprintln!("DBG[{:.0}s] smoke: stack open", dbg_el()); + let tokenizer = smoke.tokenizer; + let short_prompt = tokenizer.encode(PROMPT, true).expect("short prompt tokenization failed"); + let prompt = tokenizer.encode(&[PROMPT; 6].join(" "), true).expect("prompt tokenization failed"); + assert!(prompt.len() >= 8, "the smoke prompt must exercise the batched read"); + eprintln!("DBG[{:.0}s] smoke: prompt ids ({}): {:?}", dbg_el(), prompt.len(), &prompt[..prompt.len().min(24)]); + smoke.steps(&short_prompt, &prompt); + smoke.stack.close().expect("stack cleanup failed"); + }); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_stack.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_stack.rs new file mode 100644 index 00000000..e57c7c39 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_stack.rs @@ -0,0 +1,130 @@ +//! The pinned model, the Context and the Original serve stack the smokes of `backend_original_serve_smoke.rs` +//! run on, and the helpers they share. +use super::*; +use crate::qwen_forward::original_serve_engine::ServeOutcome; +use std::str::FromStr; + +/// The explicit opt-in of the smokes (one GPU, one load). +pub(super) fn optin() { + assert!( + env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), + "explicit Original serve smoke opt-in required" + ); +} +/// The value of `name` when it is set and parses, else `default`. +pub(super) fn env_or(name: &str, default: T) -> T { + env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) +} +/// The value of `name` as a count: unset is `default`, unparsable is a refusal. +pub(super) fn number(name: &str, default: usize) -> usize { + env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) +} +/// The tokens as comma-separated ids. +pub(super) fn ids(tokens: &[T]) -> String { + tokens.iter().map(|t| t.to_string()).collect::>().join(",") +} +/// A seeded agent-style sampler: temperature 0.7, top-k 20, top-p 0.95, repeat penalty 1.1 over 64. +pub(super) fn agent_sampler() -> leleka_sampler_ref::SamplerParams { + 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, + } +} +/// The pinned tokenizer, EOS, inherited archive and binding (with its resident expert source). +pub(super) struct Pinned { + pub(super) binding: ModelBinding, + pub(super) _inherited: InheritedKarArchive, + pub(super) tokenizer: Tokenizer, + pub(super) eos: u32, +} +fn pinned_artifact() -> Qwen4ExpArtifact { + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); + Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed") +} +fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) { + let metadata = artifact.tokenizer(); + let tokenizer = Tokenizer::from_vocabulary( + &metadata.model, + &metadata.pre, + metadata.tokens.clone(), + metadata.merges.clone(), + metadata.token_types.clone(), + ) + .expect("verified tokenizer construction failed"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + (tokenizer, eos) +} +/// `announce` prints the progress lines of the main smoke around the resident expert source load. +pub(super) fn open_pinned(announce: bool) -> Pinned { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let artifact = pinned_artifact(); + let (tokenizer, eos) = pinned_tokenizer(&artifact); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + if announce { + eprintln!("DBG[{:.0}s] smoke: binding ready, loading resident expert source", dbg_el()); + } + let resident = binding.load_resident_expert_source().expect("resident expert source load failed"); + if announce { + eprintln!("DBG[{:.0}s] smoke: resident expert source loaded: {resident:?}", dbg_el()); + } + Pinned { binding, _inherited: inherited, tokenizer, eos } +} +/// Creates a bounded Context on device 0, runs `body` on it and closes it. +pub(super) fn with_context(budget_gib: usize, body: impl FnOnce(&Rc>) -> R) -> R { + let driver = Driver::load().expect("CUDA driver load failed"); + 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 result = body(&context); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + result +} +pub(super) fn open_stack<'a, 'ctx>( + binding: &'a ModelBinding, + context: &'ctx Rc>, + config: StackConfig, +) -> OriginalServeStack<'a, 'ctx> { + match OriginalServeStack::open(binding, context.as_ref(), Rc::clone(context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + } +} +/// Serves `request` and collects the committed tokens; nothing cancels it. +pub(super) fn collect( + stack: &mut OriginalServeStack<'_, '_>, + request: &ServeRequest, +) -> (Result, Vec) { + let mut tokens = Vec::new(); + let result = stack.serve( + request, + &mut |round| { + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); + (result, tokens) +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs index 66992a32..9e04ab32 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs @@ -13,407 +13,28 @@ use std::{ #[path = "../../../../crates/gateway-text/src/prompt.rs"] #[allow(dead_code)] mod public_renderer; -const ARTIFACT_CAP: usize = 16 * 1024 * 1024; -static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { - ARTIFACT_BYTES - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { - current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP) - }) - .map(|_| ()) - .map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded")) -} -const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; -const CAP: u32 = 32; -fn path(name: &str) -> PathBuf { - env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path") -} -fn sha(bytes: &[u8]) -> String { - Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() -} -fn save(root: &std::path::Path, name: &str, value: &Value) { - let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed"); - assert!(bytes.len() <= 1024 * 1024); - reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow")) - .expect("whole public pair serialized budget exceeded"); - let mut f = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(root.join(name)) - .expect("fresh public pair output required"); - f.write_all(&bytes).unwrap(); - f.write_all(b"\n").unwrap(); - f.sync_data().unwrap(); -} -fn cache( - m: crate::qwen_forward::moe_weight_cache::WeightCacheCounters, - d: crate::qwen_forward::dense_weight_cache::DenseCacheCounters, -) -> CacheCounts { - CacheCounts { - expert_hits: m.hits, - expert_misses: m.misses, - expert_source_bytes: m.read_bytes, - expert_upload_bytes: m.upload_bytes, - expert_eviction_bytes: m.eviction_bytes, - dense_hits: d.hits, - dense_source_bytes: d.read_bytes, - dense_upload_bytes: d.upload_bytes, - } -} -fn cache_json(c: CacheCounts) -> Value { - json!({"expert_hits":c.expert_hits,"expert_misses":c.expert_misses,"expert_source_bytes":c.expert_source_bytes,"expert_upload_bytes":c.expert_upload_bytes,"expert_eviction_bytes":c.expert_eviction_bytes,"dense_hits":c.dense_hits,"dense_source_bytes":c.dense_source_bytes,"dense_upload_bytes":c.dense_upload_bytes}) -} -fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { - let instructions = "Use only the public document. Preserve the requested word order."; - for lines in 1..=64 { - let mut document = String::from( - "PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n", - ); - for index in 0..lines { - document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n")); - } - document.push_str("Return this public sequence once, without explanation: amber birch cedar delta elm fern grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc amber birch cedar delta elm fern."); - let prompt = public_renderer::render( - &[ - public_renderer::Message { - role: public_renderer::Role::System, - content: instructions, - reasoning: None, - parts: None, - }, - public_renderer::Message { - role: public_renderer::Role::User, - content: &document, - reasoning: None, - parts: None, - }, - ], - public_renderer::Effort::None, - ) - .expect("actual daemon public renderer refused"); - let req = GenerationRequest { - request_id: "public-paired-owner-generation".into(), - prompt, - max_output_tokens: CAP, - temperature_milli: 0, - sampling: Default::default(), - }; - let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame"); - if (193..=256).contains(&ids.len()) { - let canonical = json!({"model":"pinned-native-model","instructions":instructions,"input":document,"tools":[],"max_output_tokens":CAP,"temperature":0,"stream":true,"store":false}); - return (req, ids, canonical); - } - assert!( - ids.len() <= 256, - "public framing jumped past the predeclared193..256 intake; do not fit a token surrogate" - ); - } - panic!("public framed193..256 token request unavailable"); -} -struct Arm { - measurement: EvaluationMeasurement, - text: String, - usage: Usage, - reason: FinishReason, - request_wall: Duration, - first_text: Option, -} -impl Arm { - fn json(&self, phase: &str, policy: &str) -> Value { - let windows: Vec<_> = self.measurement.windows.iter().map(|w| json!({"draft_steps":w.draft_steps,"verified_ids":w.verified_ids,"verified_count":w.verified_count,"authoritative_eos":w.authoritative_eos,"accepted_non_eos_drafts":w.accepted_non_eos_drafts})).collect(); - json!({"phase":phase,"execution_policy":policy,"input_token_ids":self.measurement.input_token_ids,"output_token_ids":self.measurement.output_token_ids,"retained_prefix_tokens":self.measurement.retained_prefix_tokens,"prefill_ns":u64::try_from(self.measurement.prefill.as_nanos()).unwrap(),"decode_ns":u64::try_from(self.measurement.decode.as_nanos()).unwrap(),"request_wall_ns":u64::try_from(self.request_wall.as_nanos()).unwrap(),"first_text_ns":self.first_text.map(|d|u64::try_from(d.as_nanos()).unwrap()),"wall_boundary":"immediately before generate_mtp_resume through terminal, actual channel EOF and consumer join; excludes session teardown and helpers", "windows":windows,"cache_before":cache_json(self.measurement.cache_before),"cache_after":cache_json(self.measurement.cache_after),"completed":self.measurement.completed,"stopped":self.measurement.stopped,"terminal_published":self.measurement.terminal_published,"text":self.text,"usage":{"input_tokens":self.usage.input_tokens,"output_tokens":self.usage.output_tokens,"reused_input_tokens":self.usage.reused_input_tokens},"finish_reason":format!("{:?}",self.reason)}) - } - fn offered(&self) -> usize { - self.measurement.windows.iter().map(|w| w.draft_steps).sum() - } -} -struct Inputs<'a, 'ctx, 'driver> { - binding: &'a ModelBinding, - output: &'a OutputStage<'ctx, 'driver>, - kar: &'a mut KarPleCache<'ctx>, - moe: &'a mut MoeWeightCache<'ctx>, - dense: &'a DenseWeightCache<'ctx>, - tokenizer: &'a Tokenizer, - context: &'a Rc>, - eos: u32, - shared: Shared, -} -impl Inputs<'_, '_, '_> { - fn arm( - &mut self, - req: &GenerationRequest, - ids: &[u32], - execution: EvaluationExecution, - phase: &'static str, - ) -> Arm { - eprintln!( - "PUBLIC arm-start phase={phase} is_native_control={} allocated={} budget={}", - execution == EvaluationExecution::Native, - self.context.allocated_bytes(), - self.context.budget_bytes() - ); - // Fresh genuine target state and fresh actual decoder. No position reset, - // invented prefix, checkpoint reuse or cached-token count substitution. - let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); - let cancel = AtomicBool::new(false); - let (sink, mut stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); - let drain = thread::spawn(move || { - let mut text = String::new(); - let mut usage = None; - let mut terminal = None; - let mut first_text_at = None; - while let Some(event) = stream.recv().expect("pair stream missing terminal") { - match event { - GenerationEvent::TextDelta { text: delta } => { - if !delta.is_empty() && first_text_at.is_none() { - first_text_at = Some(Instant::now()); - } - assert!(text.len() + delta.len() <= FRAME_LIMIT); - text.push_str(&delta); - } - GenerationEvent::Usage(value) => { - assert!(usage.replace(value).is_none()); - } - GenerationEvent::Terminal(value) => { - assert!(terminal.replace(value).is_none()); - } - GenerationEvent::ToolCallDelta { .. } => { - panic!("text-only public pair emitted unexpected typed tool") - } - } - } - (text, usage, terminal, first_text_at) - }); - let before = cache(self.moe.counters(), self.dense.counters()); - let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); - let mut pending = None; - let request_started = Instant::now(); - let result = generate_mtp_resume( - Generation { - measurement: Some(&recorder), - execution, - binding: self.binding, - output: self.output, - kar_cache: Some(&mut *self.kar), - moe_cache: &mut *self.moe, - dense_cache: self.dense, - session: &mut session, - tokenizer: self.tokenizer, - sink: &sink, - cancel: &cancel, - shared: &self.shared, - context_tokens: 262144, - eos: self.eos, - mtp: true, - clock: SystemClock, - }, - ids, - req.max_output_tokens, - None, - &mut pending, - ); - let (reason, usage) = match result { - Ok(value) => value, - Err(failure) => { - let terminal = match failure { - GenerationFailure::Cancelled => GenerationTerminal::Cancelled, - GenerationFailure::Backend(error) => { - GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } - } - }; - let diagnostic = format!("{terminal:?}"); - let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); - drop(sink); - let joined = drain.join(); - let consumer_failed = joined.is_err(); - let (text, seen_usage, seen_terminal, first_text_at) = joined.unwrap_or_default(); - let request_wall = request_started.elapsed(); - let progress = recorder.borrow(); - let (output_ids, window_count, prefill_completed) = progress.diagnostic_progress(); - save( - &path("LELEKA_STRA169_PAIR_OUTPUT"), - "GENERATION-FAILURE.json", - &json!({"terminal":diagnostic,"terminal_published":published,"terminal_seen_matches":seen_terminal.as_ref()==Some(&terminal),"consumer_failed":consumer_failed,"usage_seen":seen_usage.map(|u|json!({"input_tokens":u.input_tokens,"output_tokens":u.output_tokens,"reused_input_tokens":u.reused_input_tokens})),"public_text":text,"text_bytes":text.len(),"actual_observed_output_ids":output_ids,"window_count":window_count,"prefill_completed":prefill_completed,"phase":phase,"request_wall_ns":u64::try_from(request_wall.as_nanos()).unwrap(),"first_text_ns":first_text_at.map(|at|u64::try_from(at.duration_since(request_started).as_nanos()).unwrap()),"allocated_at_failure":self.context.allocated_bytes(),"device_budget_bytes":self.context.budget_bytes(),"is_native_control":execution==EvaluationExecution::Native}), - ); - eprintln!("PUBLIC generation terminal={diagnostic}"); - panic!("actual public pair generation failed; bounded failure artifact retained"); - } - }; - let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; - let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); - drop(sink); - let (text, seen_usage, seen_terminal, first_text_at) = drain.join().expect("actual pair consumer failed"); - let request_wall = request_started.elapsed(); - let first_text = first_text_at.map(|at| at.duration_since(request_started)); - assert!(published && seen_terminal.as_ref() == Some(&terminal)); - assert!(seen_usage.as_ref() == Some(&usage)); - assert!(!cancel.load(Ordering::Acquire)); - assert!(self.shared.ready.load(Ordering::Acquire)); - assert!(!self.shared.shutdown.load(Ordering::Acquire)); - drop(pending); - drop(session); - let measured = recorder - .into_inner() - .finish( - before, - cache(self.moe.counters(), self.dense.counters()), - true, - matches!(reason, FinishReason::Stop), - published, - Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)), - ) - .expect("actual owner measurement refused"); - assert_eq!(measured.input_token_ids, ids); - assert_eq!(measured.retained_prefix_tokens, 0); - Arm { measurement: measured, text, usage, reason, request_wall, first_text } - } -} -fn metadata() -> Value { - let mut f = OpenOptions::new() - .read(true) - .custom_flags(0x20000 | 0x800) - .open(path("LELEKA_STRA169_PAIR_METADATA")) - .expect("ROOT public measurement metadata required"); - assert!(f.metadata().unwrap().is_file()); - let mut b = Vec::new(); - std::io::Read::by_ref(&mut f).take(16385).read_to_end(&mut b).unwrap(); - assert!(b.len() <= 16384); - assert_eq!( - sha(&b), - env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required") - ); - let value: Value = serde_json::from_slice(&b).unwrap(); - let o = value.as_object().expect("public metadata object required"); - for key in [ - "engine_source_sha256", - "evaluation_binary_sha256", - "gpu", - "driver", - "cuda", - "power_limit_w", - "clocks", - "context_tokens", - ] { - assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required"); - } - assert!(o.keys().all(|k| { - [ - "engine_source_sha256", - "evaluation_binary_sha256", - "gpu", - "driver", - "cuda", - "power_limit_w", - "clocks", - "context_tokens", - ] - .contains(&k.as_str()) - })); - assert_eq!(o["context_tokens"], json!(262144)); - value -} -const BASELINE_SHA: &str = "4d61ee949d37a738500c889f23f07310b6d75c7c8dfe5f50173eceafe1882fbe"; -struct Baseline { - input_ids: Vec, - output_ids: Vec, - text: String, -} -fn token_ids(value: &Value) -> Vec { - value - .as_array() - .expect("actual baseline token array missing") - .iter() - .map(|v| u32::try_from(v.as_u64().expect("baseline token is not u32")).unwrap()) - .collect() -} -fn baseline() -> Baseline { - // This is the retained completed Native arm, not the failed whole campaign. - // Root separately retains its source/model/request transfer provenance. - let mut f = OpenOptions::new() - .read(true) - .custom_flags(0x20000 | 0x800) - .open(path("LELEKA_STRA169_NATIVE_BASELINE")) - .expect("sealed retained Native baseline required"); - assert!(f.metadata().unwrap().is_file()); - let mut bytes = Vec::new(); - std::io::Read::by_ref(&mut f).take(65537).read_to_end(&mut bytes).unwrap(); - assert!(bytes.len() <= 65536); - assert_eq!(sha(&bytes), BASELINE_SHA); - let v: Value = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(v["phase"], json!("warm")); - assert_eq!(v["execution_policy"], json!("native64-same-dual-cache-retained-mtp-kv")); - assert_eq!(v["completed"], json!(true)); - assert_eq!(v["terminal_published"], json!(true)); - assert_eq!(v["stopped"], json!(false)); - assert_eq!(v["finish_reason"], json!("Length")); - assert_eq!(v["retained_prefix_tokens"], json!(0)); - assert_eq!(v["usage"], json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0})); - let input_ids = token_ids(&v["input_token_ids"]); - let output_ids = token_ids(&v["output_token_ids"]); - assert_eq!(input_ids.len(), 202); - assert_eq!(output_ids.len(), 32); - let text = v["text"].as_str().unwrap().to_owned(); - assert!(text.len() <= FRAME_LIMIT); - // Validate actual active window witnesses, excluding unused padding IDs. - let mut active = Vec::new(); - let mut offered = 0u64; - let mut accepted = 0u64; - for w in v["windows"].as_array().unwrap() { - let steps = w["draft_steps"].as_u64().unwrap(); - let count = usize::try_from(w["verified_count"].as_u64().unwrap()).unwrap(); - let ids = token_ids(&w["verified_ids"]); - assert_eq!(ids.len(), 4); - assert!((1..=4).contains(&steps) && (1..=4).contains(&count)); - assert!(u64::try_from(count).unwrap() <= steps); - assert_eq!(w["authoritative_eos"], json!(false)); - let matched = w["accepted_non_eos_drafts"].as_u64().unwrap(); - assert_eq!(matched, u64::try_from(count - 1).unwrap()); - active.extend_from_slice(&ids[..count]); - offered += steps; - accepted += matched; - } - assert_eq!(active.len(), 31); - assert_eq!(active, output_ids[..31]); - assert_eq!(offered, 31); - assert_eq!(accepted, 23); - Baseline { input_ids, output_ids, text } -} -fn checked_candidate_window_prefix(windows: &[WindowWitness], output_ids: &[u32]) -> (usize, usize) { - assert!(!output_ids.is_empty()); - let mut active = Vec::new(); - let mut offered = 0usize; - let mut accepted = 0usize; - for (index, w) in windows.iter().enumerate() { - assert!((1..=4).contains(&w.verified_count)); - assert!(!w.authoritative_eos); - assert_eq!(w.accepted_non_eos_drafts, w.verified_count - 1); - if w.draft_steps == 0 { - // generate_mtp_resume reserves one final public authoritative token - // outside the windows. Only its preceding single anchor can have - // no available draft capacity. Padding is never an output token. - assert_eq!(index + 1, windows.len()); - assert_eq!(w.verified_count, 1); - assert_eq!(w.accepted_non_eos_drafts, 0); - assert_eq!(active.len() + 1, output_ids.len() - 1); - } else { - assert!((1..=4).contains(&w.draft_steps)); - assert!(w.verified_count - 1 <= w.draft_steps); - } - active.extend_from_slice(&w.verified_ids[..w.verified_count]); - offered += w.draft_steps; - accepted += w.accepted_non_eos_drafts; - } - assert_eq!(active.len(), output_ids.len() - 1); - assert_eq!(active, output_ids[..active.len()]); - (offered, accepted) -} -fn candidate_windows(candidate: &Arm) -> (usize, usize) { - let counts = - checked_candidate_window_prefix(&candidate.measurement.windows, &candidate.measurement.output_token_ids); - assert_eq!(counts.0, candidate.offered()); - counts -} +// Files, request framing and counters shared with the one-load pair (native_down_public_pair.rs). +#[path = "native_down_pair_io.rs"] +mod pair_io; +use pair_io::*; +// The retained completed Native arm and the checks of the MTP window witnesses. +#[path = "native_down_pair_checks.rs"] +mod pair_checks; +use pair_checks::*; +// One actual owner generation on a fresh target/draft state. +#[path = "native_down_pair_arm.rs"] +mod pair_arm; +use pair_arm::*; +// The one loaded owner, its ordered teardown and the run of a proof on it. +#[path = "native_down_pair_owner.rs"] +mod pair_owner; +use pair_owner::*; +#[path = "native_down_pair_run.rs"] +mod pair_run; +use pair_run::*; +#[path = "native_down_pair_proofs.rs"] +mod pair_proofs; +use pair_proofs::*; #[test] fn cap_final_zero_draft_anchor_is_only_last_verified_prefix_before_final_public_token() { fn window(steps: usize, ids: [u32; 4], count: usize) -> WindowWitness { @@ -443,272 +64,29 @@ fn cap_final_zero_draft_anchor_is_only_last_verified_prefix_before_final_public_ catch_unwind(AssertUnwindSafe(|| checked_candidate_window_prefix(&[prefix, last], &outputs[..4]))).is_err() ); } + #[test] #[ignore = "ROOT candidate-only changed owner proof; retained Native is not replayed"] fn pinned_new_slowpaths_match_completed_public_output() { - assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); - let baseline = baseline(); - let hardware = metadata(); - let root = path("LELEKA_STRA169_PAIR_OUTPUT"); - assert!(root.is_absolute() && !root.exists()); - assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); - std::fs::create_dir(&root).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); - // Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3. - // Root runs only the new GDN full-products entry in this component cohort. - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); - assert!((3..=1048576).contains(&fd)); - // Observation only. Missing/invalid inherited FD defers capture refusal; - // the original later InheritedKarArchive gate remains authoritative. - let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); - let shard0_started = Instant::now(); - let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), - SHARD0, - observed_kar.as_ref(), - ) - .expect("pinned shard0 failed"); - let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); - drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); - let m = artifact.tokenizer(); - let tokenizer = - Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) - .expect("actual pinned tokenizer failed"); - let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); - let (req, ids, canonical) = request(&tokenizer); - assert_eq!(ids, baseline.input_ids); - assert_eq!(ids.len(), 202); - save( - &root, - "BASELINE-ADMISSION.json", - &json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1","retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1","actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_ids_match":true,"context_tokens":262144,"temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false,"baseline_campaign_succeeded":false}), - ); - save(&root, "PUBLIC-REQUEST.json", &canonical); - save( - &root, - "FRAME.json", - &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), - ); - let inherited = - InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &path("LELEKA_STRA169_MTP_PACK"), - &path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual KAR MTP binding failed"); - let mut profile_file = OpenOptions::new() - .read(true) - .custom_flags(0x20000) - .open(path("LELEKA_STRA169_EXPERT_PROFILE")) - .expect("ROOT pinned STRP profile required"); - assert!(profile_file.metadata().unwrap().is_file()); - assert_eq!(profile_file.metadata().unwrap().len(), 196_632); - let mut profile_bytes = Vec::new(); - profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); - assert_eq!(profile_bytes.len(), 196_632); - crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) - .expect("pure pinned profile admission failed before Driver"); - // Selected fresh binding only, before Driver/profile/session publication. - let bank_started = Instant::now(); - let bank_admission = binding - .adopt_resident_expert_capture(expert_capture) - .expect("actual resident expert RAM bank admission failed"); - let bank_load_ns = bank_started.elapsed().as_nanos(); - let r = bank_admission; - save( - &root, - "BANK-ADMISSION.json", - &json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":shard0_digest_capture_ns,"source_transport":"same-fd-full-sha-opaque-capture","report":json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true})}), - ); - // Reuse the already verified bound tokenizer; no long request or Native inference. - let driver = Driver::load().expect("actual CUDA driver failed"); - let driver_version = driver.version(); - let device = driver.device(0).unwrap(); - let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); - let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); - let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch(&binding, context.as_ref()).unwrap(); - let preload_started = Instant::now(); - let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input( - &binding, - context.as_ref(), - &profile_bytes, - ) - .unwrap(); - let preload_ns = preload_started.elapsed().as_nanos(); - drop(profile_file); - drop(profile_bytes); - // Only the changed direct Down proof shares this model load. - // The unchanged, previously qualified GDN helper is not repeated. - let mut direct_down_report = None; - let candidate = catch_unwind(AssertUnwindSafe(|| { - let mut proof_session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - direct_down_report = Some( - QwenForward::test_direct_down_on_loaded(&binding, &context, &mut proof_session, &mut kar, &mut moe, &dense) - .expect("actual original-first direct Down packet proof failed"), - ); - drop(proof_session); - let mut inputs = Inputs { - binding: &binding, - output: &output, - kar: &mut kar, - moe: &mut moe, - dense: &dense, - tokenizer: &tokenizer, - context: &context, - eos, - shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, - }; - crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); - inputs.arm( - &req, - &ids, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - "candidate-only-new-slowpaths-fixed-draft-selected-QSA-queued-target-shared-tail-pinned-profile-spill-router-scratch", - ) - })); - let disabled = crate::qwen_forward::oracle_capture::disable(&output); - let shared_tail_rows = moe.test_shared_tail_witness(); - let lru_witness = moe.test_lru_witness(); - let lru_metadata_bytes = moe.test_lru_metadata_bytes(); - let profile_witness = moe.test_profile_witness(); - let profile_json = profile_witness.as_ref().ok().map(|w| { - json!({ - "profile_sha256":"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", - "complete_pinned_experts":w.prefix,"pinned_bytes":w.pinned_bytes,"spill_bytes":w.spill_bytes, - "post_preload_source_read_bytes_including_shared":w.post_preload_read_bytes, - "post_preload_upload_bytes_including_shared":w.post_preload_upload_bytes, - "spill_reserve":w.spill_reserve,"largest_triplet":w.largest_triplet, - "metadata_bytes":w.metadata_bytes,"main_slot_limit":w.main_slot_limit, - "fixed_resident_upload_bytes_before_profile":w.fixed_resident_upload_bytes,"pinned_hits":w.pinned_hits,"spill_hits":w.spill_hits, - "spill_misses":w.spill_misses,"preload_read_bytes":w.preload_read_bytes, - "preload_upload_bytes":w.preload_upload_bytes,"preload_ns":preload_ns, - "preload_in_generation_timing":false,"normal_defaults_changed":false - }) - }); - let mtp_input_completions = moe.test_mtp_input_completions(); - let moe_closed = moe.close(); - let router_rows = dense.test_router_witness(); - let gr_batch_completions = dense.test_gr_batch_completions(); - let dense_closed = dense.close(); - drop(kar); - let compact_head_completions = output.test_compact_completions(); - drop(output); - let synchronized = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = match Rc::try_unwrap(context) { - Ok(c) => Some(c.close()), - Err(c) => { - drop(c); - None - } - }; - let bank_after = binding.resident_expert_source_report(); - drop(binding); - drop(inherited); - let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); - let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { - let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples - .iter() - .map(|sample| { - json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - }) - }) - .collect::>() - }); - save( - &root, - "OWNER-WALL.json", - &json!({"schema":1,"valid":owner_wall_profile.is_ok(), - "error":owner_wall_profile.as_ref().err(),"rows":profile_rows, - "metadata":hardware,"owner_output_directory":root, - "cache_before":candidate.as_ref().ok().map(|arm|cache_json(arm.measurement.cache_before)), - "cache_after":candidate.as_ref().ok().map(|arm|cache_json(arm.measurement.cache_after)), - "scope":"six fixed producer categories during actual owner generation; excludes loading, preload and helper", - "drained_after_all_attempted_teardown":true, - "counts":"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens", - "clock":"inclusive CPU owner wall with existing completion waits; not GPU service time", - "nested_totals_not_additive":true,"complete_request_accounting":false, - "overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has instrumentation overhead", - "additional_cuda_calls":0,"additional_tensor_reads":0, - "performance_acceptance":false}), - ); - if let Ok(Some(r)) = bank_after { - save( - &root, - "BANK-COPIES.json", - &json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true}), - ); - } - save( - &root, - "CLEANUP.json", - &json!({"oracle_disabled":disabled.is_ok(),"moe_closed":moe_closed.is_ok(),"dense_closed":dense_closed.is_ok(),"synchronized":synchronized.is_ok(),"allocated":allocated,"context_closed":matches!(&closed,Some(Ok(()))),"generation_succeeded":candidate.is_ok(),"actual_pinned_profile":profile_json,"actual_queued_shared_tail_rows":shared_tail_rows,"actual_mtp_input_completions":mtp_input_completions,"actual_compact_head_completions":compact_head_completions,"actual_gr_batch_inject_completions":gr_batch_completions,"actual_lru_index":{"victim_lookups":lru_witness.0,"metadata_updates":lru_witness.1,"removals":lru_witness.2,"metadata_bytes":lru_metadata_bytes.as_ref().ok().copied()},"actual_router_scratch_rows":router_rows.as_ref().ok(),"actual_router_scratch_reuses":router_rows.as_ref().ok().map(|rows| rows.saturating_sub(1))}), - ); - })); - let candidate = match candidate { - Ok(value) => value, - Err(primary) => resume_unwind(primary), - }; - if let Err(secondary) = cleanup_artifact { - resume_unwind(secondary); - } - save(&root, "CANDIDATE.json", &candidate.json("candidate-only", "integer-gu-native-down-retained-gr256-kv-only")); - assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); - assert_eq!(allocated, 0); - assert!(matches!(closed, Some(Ok(())))); - assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - direct_down_report.expect("loaded direct Down report missing").assert_after_teardown(); - assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), - "actual bounded pinned profile owner/hit witness missing" - ); - // Quality assertions follow every attempted teardown and preserve a primary - // generation panic/error. There is no Native call or historical timing ratio. - assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); - assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); - assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); - assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); - assert!( - lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, - "actual indexed lookup/update/removal path was not exercised" - ); - assert!( - lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), - "bounded actual index metadata charge missing" - ); - let (offered, accepted) = candidate_windows(&candidate); - let parity = candidate.measurement.output_token_ids == baseline.output_ids - && candidate.text == baseline.text - && matches!(candidate.reason, FinishReason::Length) - && candidate.usage.input_tokens == 202 - && candidate.usage.output_tokens == 32 - && candidate.usage.reused_input_tokens == 0; - save( - &root, - "QUALITY.json", - &json!({"scope":"one fresh candidate owner generation compared with retained completed actual Native arm; excludes historical paired timing","baseline_sha256":BASELINE_SHA,"model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware,"actual_cuda_driver_version":driver_version,"context_tokens":262144,"framed_tokens":ids.len(),"output_cap":CAP,"same_request_token_ids":true,"greedy_output_ids_text_finish_usage_equal":parity,"actual_pinned_profile":profile_json,"actual_queued_shared_tail_rows":shared_tail_rows,"actual_mtp_input_completions":mtp_input_completions,"actual_compact_head_completions":compact_head_completions,"actual_gr_batch_inject_completions":gr_batch_completions,"actual_lru_index":{"victim_lookups":lru_witness.0,"metadata_updates":lru_witness.1,"removals":lru_witness.2,"metadata_bytes":lru_metadata_bytes.as_ref().ok().copied()},"actual_router_scratch_rows":router_rows.as_ref().ok(),"actual_router_scratch_reuses":router_rows.as_ref().ok().map(|rows| rows.saturating_sub(1)),"actual_mtp_offered":offered,"actual_non_eos_drafts_accepted":accepted,"completed":candidate.measurement.completed,"terminal_published":candidate.measurement.terminal_published,"retained_prefix_tokens":candidate.measurement.retained_prefix_tokens,"cache_state":"fresh target+draft sessions after original-first changed direct Down layer0 helper; helper-warmed kernel/module/L0 scratch/KAR row-source/MoE expert-cache; actual generation cache_before measured after that helper; ranked prefix/preload separately reported, not cold hardware","historical_speed_ratio":null,"GateC":false,"GateD":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":allocated,"cleanup_complete":true}), - ); - assert!(candidate.measurement.completed && candidate.measurement.terminal_published); - assert_eq!(candidate.measurement.retained_prefix_tokens, 0); - assert!(offered > 0 && accepted > 0, "actual candidate must offer and accept MTP drafts"); - assert!(parity, "candidate differs from retained actual Native output/finish/Usage"); - eprintln!( - "PUBLIC candidate-only framed={} output={} offered={offered} accepted={accepted} parity=true allocated=0 historical_speed_ratio=null", - ids.len(), - candidate.measurement.output_token_ids.len() - ); + run(&DirectDown); +} + +#[test] +#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] +fn pinned_five_public_cases_one_loaded_owner() { + run(&FiveCase(Kind::OneLoadedOwner)); +} + +#[test] +#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] +fn pinned_five_public_cases_retained_qk_qsa_owner() { + run(&FiveCase(Kind::RetainedQkQsa)); +} + +#[test] +#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] +fn pinned_five_public_cases_resident_owners() { + run(&FiveCase(Kind::ResidentOwners)); } // Private framing only; Root owns the unchanged five-case consumer/caller. @@ -733,796 +111,5 @@ impl Inputs<'_, '_, '_> { } } -#[test] -#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] -fn pinned_five_public_cases_one_loaded_owner() { - assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); - let baseline = baseline(); - let hardware = metadata(); - let root = path("LELEKA_STRA169_PAIR_OUTPUT"); - assert!(root.is_absolute() && !root.exists()); - assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); - std::fs::create_dir(&root).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); - // Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3. - // Root runs only the new GDN full-products entry in this component cohort. - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); - assert!((3..=1048576).contains(&fd)); - // Observation only. Missing/invalid inherited FD defers capture refusal; - // the original later InheritedKarArchive gate remains authoritative. - let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); - let shard0_started = Instant::now(); - let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), - SHARD0, - observed_kar.as_ref(), - ) - .expect("pinned shard0 failed"); - let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); - drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); - let m = artifact.tokenizer(); - let tokenizer = - Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) - .expect("actual pinned tokenizer failed"); - let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); - let (req, ids, canonical) = request(&tokenizer); - assert_eq!(ids, baseline.input_ids); - assert_eq!(ids.len(), 202); - save( - &root, - "BASELINE-ADMISSION.json", - &json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1","retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1","actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_ids_match":true,"context_tokens":262144,"temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false,"baseline_campaign_succeeded":false}), - ); - save(&root, "PUBLIC-REQUEST.json", &canonical); - save( - &root, - "FRAME.json", - &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), - ); - let inherited = - InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &path("LELEKA_STRA169_MTP_PACK"), - &path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual KAR MTP binding failed"); - let mut profile_file = OpenOptions::new() - .read(true) - .custom_flags(0x20000) - .open(path("LELEKA_STRA169_EXPERT_PROFILE")) - .expect("ROOT pinned STRP profile required"); - assert!(profile_file.metadata().unwrap().is_file()); - assert_eq!(profile_file.metadata().unwrap().len(), 196_632); - let mut profile_bytes = Vec::new(); - profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); - assert_eq!(profile_bytes.len(), 196_632); - crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) - .expect("pure pinned profile admission failed before Driver"); - // Selected fresh binding only, before Driver/profile/session publication. - let bank_started = Instant::now(); - let bank_admission = binding - .adopt_resident_expert_capture(expert_capture) - .expect("actual resident expert RAM bank admission failed"); - let bank_load_ns = bank_started.elapsed().as_nanos(); - let r = bank_admission; - save( - &root, - "BANK-ADMISSION.json", - &json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":shard0_digest_capture_ns,"source_transport":"same-fd-full-sha-opaque-capture","report":json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true})}), - ); - // Reuse the already verified bound tokenizer; no long request or Native inference. - let driver = Driver::load().expect("actual CUDA driver failed"); - let driver_version = driver.version(); - let device = driver.device(0).unwrap(); - let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); - let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); - let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch(&binding, context.as_ref()).unwrap(); - let preload_started = Instant::now(); - let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( - &binding, - context.as_ref(), - &profile_bytes, - ) - .unwrap(); - let preload_ns = preload_started.elapsed().as_nanos(); - drop(profile_file); - drop(profile_bytes); - // Already qualified DirectDown/components are not replayed. Every case - // gets a fresh target/draft; one genuine weight/cache owner load is shared. - let candidate = catch_unwind(AssertUnwindSafe(|| { - let mut inputs = Inputs { - binding: &binding, - output: &output, - kar: &mut kar, - moe: &mut moe, - dense: &dense, - tokenizer: &tokenizer, - context: &context, - eos, - shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, - }; - crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); - let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - inputs.arm_five_public_cases(&case_manifest, &case_manifest_sha) - })); - let disabled = crate::qwen_forward::oracle_capture::disable(&output); - let shared_tail_rows = moe.test_shared_tail_witness(); - let lru_witness = moe.test_lru_witness(); - let lru_metadata_bytes = moe.test_lru_metadata_bytes(); - let profile_witness = moe.test_profile_witness(); - let profile_json = profile_witness.as_ref().ok().map(|w| { - json!({ - "profile_sha256":"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", - "complete_pinned_experts":w.prefix,"pinned_bytes":w.pinned_bytes,"spill_bytes":w.spill_bytes, - "post_preload_source_read_bytes_including_shared":w.post_preload_read_bytes, - "post_preload_upload_bytes_including_shared":w.post_preload_upload_bytes, - "spill_reserve":w.spill_reserve,"largest_triplet":w.largest_triplet, - "metadata_bytes":w.metadata_bytes,"main_slot_limit":w.main_slot_limit, - "fixed_resident_upload_bytes_before_profile":w.fixed_resident_upload_bytes,"pinned_hits":w.pinned_hits,"spill_hits":w.spill_hits, - "spill_misses":w.spill_misses,"preload_read_bytes":w.preload_read_bytes, - "preload_upload_bytes":w.preload_upload_bytes,"preload_ns":preload_ns, - "preload_in_generation_timing":false,"normal_defaults_changed":false - }) - }); - let mtp_input_completions = moe.test_mtp_input_completions(); - let moe_closed = moe.close(); - let router_rows = dense.test_router_witness(); - let gr_batch_completions = dense.test_gr_batch_completions(); - let dense_closed = dense.close(); - drop(kar); - let compact_head_completions = output.test_compact_completions(); - drop(output); - let synchronized = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = match Rc::try_unwrap(context) { - Ok(c) => Some(c.close()), - Err(c) => { - drop(c); - None - } - }; - let bank_after = binding.resident_expert_source_report(); - drop(binding); - drop(inherited); - let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); - let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { - let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples - .iter() - .map(|sample| { - json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - }) - }) - .collect::>() - }); - save( - &root, - "OWNER-WALL.json", - &json!({"schema":1,"valid":owner_wall_profile.is_ok(), - "error":owner_wall_profile.as_ref().err(),"rows":profile_rows, - "metadata":hardware,"owner_output_directory":root, - "cache_before":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"][0]["cache_before"].clone()), - "cache_after":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"].as_array().unwrap().last().unwrap()["cache_after"].clone()), - "scope":"six fixed producer categories during actual owner generation; excludes loading, preload and helper", - "drained_after_all_attempted_teardown":true, - "counts":"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens", - "clock":"inclusive CPU owner wall with existing completion waits; not GPU service time", - "nested_totals_not_additive":true,"complete_request_accounting":false, - "overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has instrumentation overhead", - "additional_cuda_calls":0,"additional_tensor_reads":0, - "performance_acceptance":false}), - ); - if let Ok(Some(r)) = bank_after { - save( - &root, - "BANK-COPIES.json", - &json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true}), - ); - } - save( - &root, - "CLEANUP.json", - &json!({"oracle_disabled":disabled.is_ok(),"moe_closed":moe_closed.is_ok(),"dense_closed":dense_closed.is_ok(),"synchronized":synchronized.is_ok(),"allocated":allocated,"context_closed":matches!(&closed,Some(Ok(()))),"generation_succeeded":candidate.is_ok(),"actual_pinned_profile":profile_json,"actual_queued_shared_tail_rows":shared_tail_rows,"actual_mtp_input_completions":mtp_input_completions,"actual_compact_head_completions":compact_head_completions,"actual_gr_batch_inject_completions":gr_batch_completions,"actual_lru_index":{"victim_lookups":lru_witness.0,"metadata_updates":lru_witness.1,"removals":lru_witness.2,"metadata_bytes":lru_metadata_bytes.as_ref().ok().copied()},"actual_router_scratch_rows":router_rows.as_ref().ok(),"actual_router_scratch_reuses":router_rows.as_ref().ok().map(|rows| rows.saturating_sub(1))}), - ); - })); - let candidate = match candidate { - Ok(value) => value, - Err(primary) => resume_unwind(primary), - }; - if let Err(secondary) = cleanup_artifact { - resume_unwind(secondary); - } - let five_json = candidate.json_after_teardown(); - save(&root, "FIVE-CASE.json", &five_json); - assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); - assert_eq!(allocated, 0); - assert!(matches!(closed, Some(Ok(())))); - assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), - "actual bounded pinned profile owner/hit witness missing" - ); - // Quality assertions follow every attempted teardown and preserve a primary - // generation panic/error. There is no Native call or historical timing ratio. - assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); - assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); - assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); - assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); - assert!( - lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, - "actual indexed lookup/update/removal path was not exercised" - ); - assert!( - lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), - "bounded actual index metadata charge missing" - ); - candidate.assert_after_teardown(); - let first = &five_json["cases"][0]; - assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); - let parity = token_ids(&first["output_token_ids"]) == baseline.output_ids - && first["text"].as_str() == Some(baseline.text.as_str()) - && first["finish_reason"] == json!("Length") - && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save( - &root, - "QUALITY.json", - &json!({"case1_retained_native_parity":parity, - "quality_against_original17":null,"requires_matching_original_five":true, - "changed_owner_policy":"digest-capture-queued-input-compact-head-GR-batch-1GiB-reusable-spill-floor", - "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, - "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, - "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, - "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), - ); - assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); - eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); -} - -#[test] -#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] -fn pinned_five_public_cases_retained_qk_qsa_owner() { - assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); - let baseline = baseline(); - let hardware = metadata(); - let root = path("LELEKA_STRA169_PAIR_OUTPUT"); - assert!(root.is_absolute() && !root.exists()); - assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); - std::fs::create_dir(&root).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); - // Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3. - // Root runs only the new GDN full-products entry in this component cohort. - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); - assert!((3..=1048576).contains(&fd)); - // Observation only. Missing/invalid inherited FD defers capture refusal; - // the original later InheritedKarArchive gate remains authoritative. - let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); - let shard0_started = Instant::now(); - let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), - SHARD0, - observed_kar.as_ref(), - ) - .expect("pinned shard0 failed"); - let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); - drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); - let m = artifact.tokenizer(); - let tokenizer = - Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) - .expect("actual pinned tokenizer failed"); - let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); - let (req, ids, canonical) = request(&tokenizer); - assert_eq!(ids, baseline.input_ids); - assert_eq!(ids.len(), 202); - save( - &root, - "BASELINE-ADMISSION.json", - &json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1","retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1","actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_ids_match":true,"context_tokens":262144,"temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false,"baseline_campaign_succeeded":false}), - ); - save(&root, "PUBLIC-REQUEST.json", &canonical); - save( - &root, - "FRAME.json", - &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), - ); - let inherited = - InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &path("LELEKA_STRA169_MTP_PACK"), - &path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual KAR MTP binding failed"); - let mut profile_file = OpenOptions::new() - .read(true) - .custom_flags(0x20000) - .open(path("LELEKA_STRA169_EXPERT_PROFILE")) - .expect("ROOT pinned STRP profile required"); - assert!(profile_file.metadata().unwrap().is_file()); - assert_eq!(profile_file.metadata().unwrap().len(), 196_632); - let mut profile_bytes = Vec::new(); - profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); - assert_eq!(profile_bytes.len(), 196_632); - crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) - .expect("pure pinned profile admission failed before Driver"); - // Selected fresh binding only, before Driver/profile/session publication. - let bank_started = Instant::now(); - let bank_admission = binding - .adopt_resident_expert_capture(expert_capture) - .expect("actual resident expert RAM bank admission failed"); - let bank_load_ns = bank_started.elapsed().as_nanos(); - let r = bank_admission; - save( - &root, - "BANK-ADMISSION.json", - &json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":shard0_digest_capture_ns,"source_transport":"same-fd-full-sha-opaque-capture","report":json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true})}), - ); - // Reuse the already verified bound tokenizer; no long request or Native inference. - let driver = Driver::load().expect("actual CUDA driver failed"); - let driver_version = driver.version(); - let device = driver.device(0).unwrap(); - let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); - let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); - let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention(&binding, context.as_ref()).unwrap(); - let preload_started = Instant::now(); - let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( - &binding, - context.as_ref(), - &profile_bytes, - ) - .unwrap(); - let preload_ns = preload_started.elapsed().as_nanos(); - drop(profile_file); - drop(profile_bytes); - // Already qualified DirectDown/components are not replayed. Every case - // gets a fresh target/draft; one genuine weight/cache owner load is shared. - let candidate = catch_unwind(AssertUnwindSafe(|| { - let mut inputs = Inputs { - binding: &binding, - output: &output, - kar: &mut kar, - moe: &mut moe, - dense: &dense, - tokenizer: &tokenizer, - context: &context, - eos, - shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, - }; - crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); - let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - fivecase_runtime::run_on_loaded_with_policy( - &mut inputs, - &case_manifest, - &case_manifest_sha, - "integer-gr256-streamed-spill-retained-qk40960-qsa108544", - ) - })); - let disabled = crate::qwen_forward::oracle_capture::disable(&output); - let shared_tail_rows = moe.test_shared_tail_witness(); - let lru_witness = moe.test_lru_witness(); - let lru_metadata_bytes = moe.test_lru_metadata_bytes(); - let profile_witness = moe.test_profile_witness(); - let profile_json = profile_witness.as_ref().ok().map(|w| { - json!({ - "profile_sha256":"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", - "complete_pinned_experts":w.prefix,"pinned_bytes":w.pinned_bytes,"spill_bytes":w.spill_bytes, - "post_preload_source_read_bytes_including_shared":w.post_preload_read_bytes, - "post_preload_upload_bytes_including_shared":w.post_preload_upload_bytes, - "spill_reserve":w.spill_reserve,"largest_triplet":w.largest_triplet, - "metadata_bytes":w.metadata_bytes,"main_slot_limit":w.main_slot_limit, - "fixed_resident_upload_bytes_before_profile":w.fixed_resident_upload_bytes,"pinned_hits":w.pinned_hits,"spill_hits":w.spill_hits, - "spill_misses":w.spill_misses,"preload_read_bytes":w.preload_read_bytes, - "preload_upload_bytes":w.preload_upload_bytes,"preload_ns":preload_ns, - "preload_in_generation_timing":false,"normal_defaults_changed":false - }) - }); - let mtp_input_completions = moe.test_mtp_input_completions(); - let moe_closed = moe.close(); - let router_rows = dense.test_router_witness(); - let gr_batch_completions = dense.test_gr_batch_completions(); - let retained_scratch_witness = dense.test_retained_scratch_witness(); - let dense_closed = dense.close(); - drop(kar); - let compact_head_completions = output.test_compact_completions(); - drop(output); - let synchronized = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = match Rc::try_unwrap(context) { - Ok(c) => Some(c.close()), - Err(c) => { - drop(c); - None - } - }; - let bank_after = binding.resident_expert_source_report(); - drop(binding); - drop(inherited); - let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); - let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { - let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples - .iter() - .map(|sample| { - json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - }) - }) - .collect::>() - }); - save( - &root, - "OWNER-WALL.json", - &json!({"schema":1,"valid":owner_wall_profile.is_ok(), - "error":owner_wall_profile.as_ref().err(),"rows":profile_rows, - "metadata":hardware,"owner_output_directory":root, - "cache_before":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"][0]["cache_before"].clone()), - "cache_after":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"].as_array().unwrap().last().unwrap()["cache_after"].clone()), - "scope":"six fixed producer categories during actual owner generation; excludes loading, preload and helper", - "drained_after_all_attempted_teardown":true, - "counts":"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens", - "clock":"inclusive CPU owner wall with existing completion waits; not GPU service time", - "nested_totals_not_additive":true,"complete_request_accounting":false, - "overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has instrumentation overhead", - "additional_cuda_calls":0,"additional_tensor_reads":0, - "performance_acceptance":false}), - ); - if let Ok(Some(r)) = bank_after { - save( - &root, - "BANK-COPIES.json", - &json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true}), - ); - } - save( - &root, - "CLEANUP.json", - &json!({"oracle_disabled":disabled.is_ok(),"moe_closed":moe_closed.is_ok(),"dense_closed":dense_closed.is_ok(),"synchronized":synchronized.is_ok(),"allocated":allocated,"context_closed":matches!(&closed,Some(Ok(()))),"generation_succeeded":candidate.is_ok(),"actual_pinned_profile":profile_json,"actual_retained_scratch":retained_scratch_witness.as_ref().ok().map(|(bytes,rows)| json!({"bytes":bytes,"completed_qsa_rows":rows})),"actual_queued_shared_tail_rows":shared_tail_rows,"actual_mtp_input_completions":mtp_input_completions,"actual_compact_head_completions":compact_head_completions,"actual_gr_batch_inject_completions":gr_batch_completions,"actual_lru_index":{"victim_lookups":lru_witness.0,"metadata_updates":lru_witness.1,"removals":lru_witness.2,"metadata_bytes":lru_metadata_bytes.as_ref().ok().copied()},"actual_router_scratch_rows":router_rows.as_ref().ok(),"actual_router_scratch_reuses":router_rows.as_ref().ok().map(|rows| rows.saturating_sub(1))}), - ); - })); - let candidate = match candidate { - Ok(value) => value, - Err(primary) => resume_unwind(primary), - }; - if let Err(secondary) = cleanup_artifact { - resume_unwind(secondary); - } - let five_json = candidate.json_after_teardown(); - save(&root, "FIVE-CASE.json", &five_json); - assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); - assert_eq!(allocated, 0); - assert!(matches!(closed, Some(Ok(())))); - assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), - "actual bounded pinned profile owner/hit witness missing" - ); - // Quality assertions follow every attempted teardown and preserve a primary - // generation panic/error. There is no Native call or historical timing ratio. - assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); - assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); - assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); - assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); - assert!( - lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, - "actual indexed lookup/update/removal path was not exercised" - ); - assert!( - lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), - "bounded actual index metadata charge missing" - ); - assert!( - retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), - "actual retained scratch owner rows absent" - ); - candidate.assert_after_teardown(); - let first = &five_json["cases"][0]; - assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); - let parity = token_ids(&first["output_token_ids"]) == baseline.output_ids - && first["text"].as_str() == Some(baseline.text.as_str()) - && first["finish_reason"] == json!("Length") - && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save( - &root, - "QUALITY.json", - &json!({"case1_retained_native_parity":parity, - "quality_against_original17":null,"requires_matching_original_five":true, - "changed_owner_policy":"digest-capture-queued-input-compact-head-GR-batch-1GiB-spill-retained-qk40960-qsa108544", - "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, - "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, - "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, - "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), - ); - assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); - eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); -} - -#[test] -#[ignore = "ROOT five public requests on one admitted owner; paired Original required"] -fn pinned_five_public_cases_resident_owners() { - assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); - let baseline = baseline(); - let hardware = metadata(); - let root = path("LELEKA_STRA169_PAIR_OUTPUT"); - assert!(root.is_absolute() && !root.exists()); - assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); - std::fs::create_dir(&root).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); - // Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3. - // Root runs only the new GDN full-products entry in this component cohort. - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); - assert!((3..=1048576).contains(&fd)); - // Observation only. Missing/invalid inherited FD defers capture refusal; - // the original later InheritedKarArchive gate remains authoritative. - let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); - let shard0_started = Instant::now(); - let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental( - &path("LELEKA_STRA169_IQ3S_SHARD0"), - SHARD0, - observed_kar.as_ref(), - ) - .expect("pinned shard0 failed"); - let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); - drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); - let m = artifact.tokenizer(); - let tokenizer = - Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) - .expect("actual pinned tokenizer failed"); - let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); - let (req, ids, canonical) = request(&tokenizer); - assert_eq!(ids, baseline.input_ids); - assert_eq!(ids.len(), 202); - save( - &root, - "BASELINE-ADMISSION.json", - &json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1","retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1","actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_ids_match":true,"context_tokens":262144,"temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false,"baseline_campaign_succeeded":false}), - ); - save(&root, "PUBLIC-REQUEST.json", &canonical); - save( - &root, - "FRAME.json", - &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), - ); - let inherited = - InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); - let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &path("LELEKA_STRA169_MTP_PACK"), - &path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual KAR MTP binding failed"); - let mut profile_file = OpenOptions::new() - .read(true) - .custom_flags(0x20000) - .open(path("LELEKA_STRA169_EXPERT_PROFILE")) - .expect("ROOT pinned STRP profile required"); - assert!(profile_file.metadata().unwrap().is_file()); - assert_eq!(profile_file.metadata().unwrap().len(), 196_632); - let mut profile_bytes = Vec::new(); - profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); - assert_eq!(profile_bytes.len(), 196_632); - crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) - .expect("pure pinned profile admission failed before Driver"); - // Selected fresh binding only, before Driver/profile/session publication. - let bank_started = Instant::now(); - let bank_admission = binding - .adopt_resident_expert_capture(expert_capture) - .expect("actual resident expert RAM bank admission failed"); - let bank_load_ns = bank_started.elapsed().as_nanos(); - let r = bank_admission; - save( - &root, - "BANK-ADMISSION.json", - &json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":shard0_digest_capture_ns,"source_transport":"same-fd-full-sha-opaque-capture","report":json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true})}), - ); - // Reuse the already verified bound tokenizer; no long request or Native inference. - let driver = Driver::load().expect("actual CUDA driver failed"); - let driver_version = driver.version(); - let device = driver.device(0).unwrap(); - let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); - let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); - let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(&binding, context.as_ref()) - .unwrap(); - let preload_started = Instant::now(); - let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( - &binding, - context.as_ref(), - &profile_bytes, - ) - .unwrap(); - let preload_ns = preload_started.elapsed().as_nanos(); - drop(profile_file); - drop(profile_bytes); - // Already qualified DirectDown/components are not replayed. Every case - // gets a fresh target/draft; one genuine weight/cache owner load is shared. - let candidate = catch_unwind(AssertUnwindSafe(|| { - let mut inputs = Inputs { - binding: &binding, - output: &output, - kar: &mut kar, - moe: &mut moe, - dense: &dense, - tokenizer: &tokenizer, - context: &context, - eos, - shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, - }; - crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); - let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - fivecase_runtime::run_on_loaded_with_policy( - &mut inputs, - &case_manifest, - &case_manifest_sha, - "integer-gr256-resident-owners-learned-main-shared192-gdn-journal-incremental-capture", - ) - })); - let disabled = crate::qwen_forward::oracle_capture::disable(&output); - let shared_tail_rows = moe.test_shared_tail_witness(); - let lru_witness = moe.test_lru_witness(); - let lru_metadata_bytes = moe.test_lru_metadata_bytes(); - let profile_witness = moe.learned_main_witness(&binding); - let shared_witness = moe.shared_permanent_witness(); - let profile_json = profile_witness.as_ref().ok().map(|w| { - json!({ - "policy":"learned-main-lru-shared192", "routed_matrices":w.routed_matrices, - "routed_bytes":w.routed_bytes,"shared_matrices":w.shared_matrices,"shared_bytes":w.shared_bytes, - "main_bytes":w.main_bytes,"main_slot_limit":w.main_slot_limit,"metadata_bytes":w.metadata_bytes, - "historical_prefix":w.historical_prefix,"historical_routed_preload_bytes":w.historical_routed_preload_bytes, - "age":w.age,"preload_ns":preload_ns,"normal_defaults_changed":false, - "shared_witness_valid":shared_witness.is_ok() - }) - }); - let mtp_input_completions = moe.test_mtp_input_completions(); - let moe_closed = moe.close(); - let router_rows = dense.test_router_witness(); - let gr_batch_completions = dense.test_gr_batch_completions(); - let retained_scratch_witness = dense.test_retained_scratch_witness(); - let dense_closed = dense.close(); - drop(kar); - let compact_head_completions = output.test_compact_completions(); - drop(output); - let synchronized = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = match Rc::try_unwrap(context) { - Ok(c) => Some(c.close()), - Err(c) => { - drop(c); - None - } - }; - let bank_after = binding.resident_expert_source_report(); - drop(binding); - drop(inherited); - let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); - let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { - let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples - .iter() - .map(|sample| { - json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - }) - }) - .collect::>() - }); - save( - &root, - "OWNER-WALL.json", - &json!({"schema":1,"valid":owner_wall_profile.is_ok(), - "error":owner_wall_profile.as_ref().err(),"rows":profile_rows, - "metadata":hardware,"owner_output_directory":root, - "cache_before":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"][0]["cache_before"].clone()), - "cache_after":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"].as_array().unwrap().last().unwrap()["cache_after"].clone()), - "scope":"six fixed producer categories during actual owner generation; excludes loading, preload and helper", - "drained_after_all_attempted_teardown":true, - "counts":"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens", - "clock":"inclusive CPU owner wall with existing completion waits; not GPU service time", - "nested_totals_not_additive":true,"complete_request_accounting":false, - "overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has instrumentation overhead", - "additional_cuda_calls":0,"additional_tensor_reads":0, - "performance_acceptance":false}), - ); - if let Ok(Some(r)) = bank_after { - save( - &root, - "BANK-COPIES.json", - &json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count,"source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes,"future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256,"completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes,"disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true}), - ); - } - save( - &root, - "CLEANUP.json", - &json!({"oracle_disabled":disabled.is_ok(),"moe_closed":moe_closed.is_ok(),"dense_closed":dense_closed.is_ok(),"synchronized":synchronized.is_ok(),"allocated":allocated,"context_closed":matches!(&closed,Some(Ok(()))),"generation_succeeded":candidate.is_ok(),"actual_pinned_profile":profile_json,"actual_retained_scratch":retained_scratch_witness.as_ref().ok().map(|(bytes,rows)| json!({"bytes":bytes,"completed_qsa_rows":rows})),"actual_queued_shared_tail_rows":shared_tail_rows,"actual_mtp_input_completions":mtp_input_completions,"actual_compact_head_completions":compact_head_completions,"actual_gr_batch_inject_completions":gr_batch_completions,"actual_lru_index":{"victim_lookups":lru_witness.0,"metadata_updates":lru_witness.1,"removals":lru_witness.2,"metadata_bytes":lru_metadata_bytes.as_ref().ok().copied()},"actual_router_scratch_rows":router_rows.as_ref().ok(),"actual_router_scratch_reuses":router_rows.as_ref().ok().map(|rows| rows.saturating_sub(1))}), - ); - })); - let candidate = match candidate { - Ok(value) => value, - Err(primary) => resume_unwind(primary), - }; - if let Err(secondary) = cleanup_artifact { - resume_unwind(secondary); - } - let five_json = candidate.json_after_teardown(); - save(&root, "FIVE-CASE.json", &five_json); - assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); - assert_eq!(allocated, 0); - assert!(matches!(closed, Some(Ok(())))); - assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - assert!( - profile_witness - .is_ok_and(|w| w.routed_matrices > 0 && w.shared_matrices == 192 && w.metadata_bytes <= 16 * 1024 * 1024), - "actual learned main owner witness missing" - ); - assert!(shared_witness.is_ok(), "actual shared owner role witness missing"); - // Quality assertions follow every attempted teardown and preserve a primary - // generation panic/error. There is no Native call or historical timing ratio. - assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); - assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); - assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); - assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); - assert!( - lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, - "actual indexed lookup/update/removal path was not exercised" - ); - assert!( - lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), - "bounded actual index metadata charge missing" - ); - assert!( - retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), - "actual retained scratch owner rows absent" - ); - candidate.assert_after_teardown(); - let first = &five_json["cases"][0]; - assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); - let parity = token_ids(&first["output_token_ids"]) == baseline.output_ids - && first["text"].as_str() == Some(baseline.text.as_str()) - && first["finish_reason"] == json!("Length") - && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save( - &root, - "QUALITY.json", - &json!({"case1_retained_native_parity":parity, - "quality_against_original17":null,"requires_matching_original_five":true, - "changed_owner_policy":"incremental-capture-learned-main-shared192-gdn-journal-qk40960-qsa108544", - "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, - "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, - "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, - "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), - ); - assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); - eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); -} - #[path = "native_down_adaptive_candidate_only.rs"] mod adaptive_slots; diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_arm.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_arm.rs new file mode 100644 index 00000000..fae0e82b --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_arm.rs @@ -0,0 +1,257 @@ +//! One actual owner generation on a fresh target/draft state: bounded stream consumer, failure artifact and the +//! measurement record of a completed arm. +use super::*; + +const WALL_BOUNDARY: &str = "immediately before generate_mtp_resume through terminal, actual channel EOF and \ + consumer join; excludes session teardown and helpers"; + +pub(super) struct Arm { + pub(super) measurement: EvaluationMeasurement, + pub(super) text: String, + pub(super) usage: Usage, + pub(super) reason: FinishReason, + pub(super) request_wall: Duration, + pub(super) first_text: Option, +} +fn window_json(w: &WindowWitness) -> Value { + json!({"draft_steps":w.draft_steps,"verified_ids":w.verified_ids,"verified_count":w.verified_count, + "authoritative_eos":w.authoritative_eos,"accepted_non_eos_drafts":w.accepted_non_eos_drafts}) +} +fn usage_json(u: &Usage) -> Value { + json!({"input_tokens":u.input_tokens,"output_tokens":u.output_tokens,"reused_input_tokens":u.reused_input_tokens}) +} +fn ns(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap() +} +impl Arm { + pub(super) fn json(&self, phase: &str, policy: &str) -> Value { + let m = &self.measurement; + let windows: Vec<_> = m.windows.iter().map(window_json).collect(); + json!({"phase":phase,"execution_policy":policy,"input_token_ids":m.input_token_ids, + "output_token_ids":m.output_token_ids,"retained_prefix_tokens":m.retained_prefix_tokens, + "prefill_ns":ns(m.prefill),"decode_ns":ns(m.decode),"request_wall_ns":ns(self.request_wall), + "first_text_ns":self.first_text.map(ns), + "wall_boundary":WALL_BOUNDARY, + "windows":windows,"cache_before":cache_json(m.cache_before),"cache_after":cache_json(m.cache_after), + "completed":m.completed,"stopped":m.stopped,"terminal_published":m.terminal_published, + "text":self.text,"usage":usage_json(&self.usage),"finish_reason":format!("{:?}",self.reason)}) + } + pub(super) fn offered(&self) -> usize { + self.measurement.windows.iter().map(|w| w.draft_steps).sum() + } +} +pub(super) struct Inputs<'a, 'ctx, 'driver> { + pub(super) binding: &'a ModelBinding, + pub(super) output: &'a OutputStage<'ctx, 'driver>, + pub(super) kar: &'a mut KarPleCache<'ctx>, + pub(super) moe: &'a mut MoeWeightCache<'ctx>, + pub(super) dense: &'a DenseWeightCache<'ctx>, + pub(super) tokenizer: &'a Tokenizer, + pub(super) context: &'a Rc>, + pub(super) eos: u32, + pub(super) shared: Shared, +} +type Drained = (String, Option, Option, Option); +fn drain_stream(mut stream: GenerationStream) -> Drained { + let mut text = String::new(); + let mut usage = None; + let mut terminal = None; + let mut first_text_at = None; + while let Some(event) = stream.recv().expect("pair stream missing terminal") { + match event { + GenerationEvent::TextDelta { text: delta } => { + if !delta.is_empty() && first_text_at.is_none() { + first_text_at = Some(Instant::now()); + } + assert!(text.len() + delta.len() <= FRAME_LIMIT); + text.push_str(&delta); + } + GenerationEvent::Usage(value) => { + assert!(usage.replace(value).is_none()); + } + GenerationEvent::Terminal(value) => { + assert!(terminal.replace(value).is_none()); + } + GenerationEvent::ToolCallDelta { .. } => { + panic!("text-only public pair emitted unexpected typed tool") + } + } + } + (text, usage, terminal, first_text_at) +} +/// The channel, its consumer thread, the measurement recorder and the request clock of one arm. +struct Running { + sink: GenerationSink, + drain: thread::JoinHandle, + recorder: std::cell::RefCell, + cancel: AtomicBool, + started: Instant, +} +impl Running { + fn open(ids: &[u32], max_output_tokens: u32) -> Self { + let cancel = AtomicBool::new(false); + let (sink, stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); + let drain = thread::spawn(move || drain_stream(stream)); + let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, max_output_tokens)); + Running { sink, drain, recorder, cancel, started: Instant::now() } + } +} +/// What the failure artifact records besides the progress of the recorder. +struct FailureFacts<'a> { + terminal: &'a GenerationTerminal, + published: bool, + consumer_failed: bool, + drained: &'a Drained, + request_wall: Duration, + started: Instant, + /// Allocated bytes, budget bytes and whether this was the Native control arm. + device: (usize, usize, bool), +} +fn failure_json(facts: &FailureFacts<'_>, progress: (&[u32], usize, bool), phase: &str) -> Value { + let (text, seen_usage, seen_terminal, first_text_at) = facts.drained; + json!({"terminal":format!("{:?}", facts.terminal),"terminal_published":facts.published, + "terminal_seen_matches":seen_terminal.as_ref()==Some(facts.terminal), + "consumer_failed":facts.consumer_failed,"usage_seen":seen_usage.as_ref().map(usage_json), + "public_text":text,"text_bytes":text.len(),"actual_observed_output_ids":progress.0, + "window_count":progress.1,"prefill_completed":progress.2,"phase":phase, + "request_wall_ns":ns(facts.request_wall), + "first_text_ns":first_text_at.map(|at|ns(at.duration_since(facts.started))), + "allocated_at_failure":facts.device.0,"device_budget_bytes":facts.device.1, + "is_native_control":facts.device.2}) +} +fn terminal_of(failure: GenerationFailure) -> GenerationTerminal { + match failure { + GenerationFailure::Cancelled => GenerationTerminal::Cancelled, + GenerationFailure::Backend(error) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } + } +} +impl<'ctx, 'driver> Inputs<'_, 'ctx, 'driver> { + fn announce(&self, phase: &str, execution: EvaluationExecution) { + eprintln!( + "PUBLIC arm-start phase={phase} is_native_control={} allocated={} budget={}", + execution == EvaluationExecution::Native, + self.context.allocated_bytes(), + self.context.budget_bytes() + ); + } + /// Publishes the terminal, joins the consumer and keeps a bounded artifact; never returns. + fn fail(&self, run: Running, failure: GenerationFailure, phase: &str, execution: EvaluationExecution) -> ! { + let terminal = terminal_of(failure); + let diagnostic = format!("{terminal:?}"); + let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok(); + drop(run.sink); + let joined = run.drain.join(); + let consumer_failed = joined.is_err(); + let drained = joined.unwrap_or_default(); + let request_wall = run.started.elapsed(); + let progress = run.recorder.borrow(); + let device = + (self.context.allocated_bytes(), self.context.budget_bytes(), execution == EvaluationExecution::Native); + let facts = FailureFacts { + terminal: &terminal, + published, + consumer_failed, + drained: &drained, + request_wall, + started: run.started, + device, + }; + let artifact = failure_json(&facts, progress.diagnostic_progress(), phase); + save(&path("LELEKA_STRA169_PAIR_OUTPUT"), "GENERATION-FAILURE.json", &artifact); + eprintln!("PUBLIC generation terminal={diagnostic}"); + panic!("actual public pair generation failed; bounded failure artifact retained"); + } + fn generation<'a>( + &'a mut self, + run: &'a Running, + session: &'a mut QwenSession<'ctx>, + execution: EvaluationExecution, + ) -> Generation<'a, 'ctx, 'driver, SystemClock> { + Generation { + measurement: Some(&run.recorder), + execution, + binding: self.binding, + output: self.output, + kar_cache: Some(&mut *self.kar), + moe_cache: &mut *self.moe, + dense_cache: self.dense, + session, + tokenizer: self.tokenizer, + sink: &run.sink, + cancel: &run.cancel, + shared: &self.shared, + context_tokens: 262144, + eos: self.eos, + mtp: true, + clock: SystemClock, + } + } + pub(super) fn arm( + &mut self, + req: &GenerationRequest, + ids: &[u32], + execution: EvaluationExecution, + phase: &'static str, + ) -> Arm { + self.announce(phase, execution); + // Fresh genuine target state and fresh actual decoder. No position reset, + // invented prefix, checkpoint reuse or cached-token count substitution. + let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); + let before = cache(self.moe.counters(), self.dense.counters()); + let run = Running::open(ids, req.max_output_tokens); + let mut pending = None; + let generation = self.generation(&run, &mut session, execution); + let result = generate_mtp_resume(generation, ids, req.max_output_tokens, None, &mut pending); + let (reason, usage) = match result { + Ok(value) => value, + Err(failure) => self.fail(run, failure, phase, execution), + }; + self.finish(run, (reason, usage), (pending, session), before, ids) + } + fn assert_ready(&self, cancel: &AtomicBool) { + assert!(!cancel.load(Ordering::Acquire)); + assert!(self.shared.ready.load(Ordering::Acquire)); + assert!(!self.shared.shutdown.load(Ordering::Acquire)); + } + fn measure( + &self, + recorder: std::cell::RefCell, + before: CacheCounts, + (reason, usage): (&FinishReason, &Usage), + published: bool, + ) -> EvaluationMeasurement { + let stopped = matches!(reason, FinishReason::Stop); + let usage_ids = Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)); + let after = cache(self.moe.counters(), self.dense.counters()); + recorder + .into_inner() + .finish(before, after, true, stopped, published, usage_ids) + .expect("actual owner measurement refused") + } + fn finish( + &self, + run: Running, + (reason, usage): (FinishReason, Usage), + (pending, session): (Option, QwenSession<'ctx>), + before: CacheCounts, + ids: &[u32], + ) -> Arm { + let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; + let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok(); + drop(run.sink); + let (text, seen_usage, seen_terminal, first_text_at) = run.drain.join().expect("actual pair consumer failed"); + let request_wall = run.started.elapsed(); + let first_text = first_text_at.map(|at| at.duration_since(run.started)); + assert!(published && seen_terminal.as_ref() == Some(&terminal)); + assert!(seen_usage.as_ref() == Some(&usage)); + self.assert_ready(&run.cancel); + drop(pending); + drop(session); + let measured = self.measure(run.recorder, before, (&reason, &usage), published); + assert_eq!(measured.input_token_ids, ids); + assert_eq!(measured.retained_prefix_tokens, 0); + Arm { measurement: measured, text, usage, reason, request_wall, first_text } + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_checks.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_checks.rs new file mode 100644 index 00000000..e5544a4a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_checks.rs @@ -0,0 +1,111 @@ +//! The retained completed Native arm and the checks of the MTP window witnesses of a candidate arm. +use super::*; + +pub(super) const BASELINE_SHA: &str = "4d61ee949d37a738500c889f23f07310b6d75c7c8dfe5f50173eceafe1882fbe"; +pub(super) struct Baseline { + pub(super) input_ids: Vec, + pub(super) output_ids: Vec, + pub(super) text: String, +} +pub(super) fn token_ids(value: &Value) -> Vec { + value + .as_array() + .expect("actual baseline token array missing") + .iter() + .map(|v| u32::try_from(v.as_u64().expect("baseline token is not u32")).unwrap()) + .collect() +} +fn assert_baseline_header(v: &Value) { + assert_eq!(v["phase"], json!("warm")); + assert_eq!(v["execution_policy"], json!("native64-same-dual-cache-retained-mtp-kv")); + assert_eq!(v["completed"], json!(true)); + assert_eq!(v["terminal_published"], json!(true)); + assert_eq!(v["stopped"], json!(false)); + assert_eq!(v["finish_reason"], json!("Length")); + assert_eq!(v["retained_prefix_tokens"], json!(0)); + assert_eq!(v["usage"], json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0})); +} +/// Checks one window witness of the baseline and appends its active ids; returns (offered, accepted). +fn baseline_window(w: &Value, active: &mut Vec) -> (u64, u64) { + let steps = w["draft_steps"].as_u64().unwrap(); + let count = usize::try_from(w["verified_count"].as_u64().unwrap()).unwrap(); + let ids = token_ids(&w["verified_ids"]); + assert_eq!(ids.len(), 4); + assert!((1..=4).contains(&steps) && (1..=4).contains(&count)); + assert!(u64::try_from(count).unwrap() <= steps); + assert_eq!(w["authoritative_eos"], json!(false)); + let matched = w["accepted_non_eos_drafts"].as_u64().unwrap(); + assert_eq!(matched, u64::try_from(count - 1).unwrap()); + active.extend_from_slice(&ids[..count]); + (steps, matched) +} +/// Validates the actual active window witnesses, excluding unused padding IDs. +fn assert_baseline_windows(windows: &Value, output_ids: &[u32]) { + let mut active = Vec::new(); + let mut offered = 0u64; + let mut accepted = 0u64; + for w in windows.as_array().unwrap() { + let (steps, matched) = baseline_window(w, &mut active); + offered += steps; + accepted += matched; + } + assert_eq!(active.len(), 31); + assert_eq!(active, output_ids[..31]); + assert_eq!(offered, 31); + assert_eq!(accepted, 23); +} +pub(super) fn baseline() -> Baseline { + // This is the retained completed Native arm, not the failed whole campaign. + // Root separately retains its source/model/request transfer provenance. + let bytes = sealed_bytes("LELEKA_STRA169_NATIVE_BASELINE", 65536, "sealed retained Native baseline required"); + assert_eq!(sha(&bytes), BASELINE_SHA); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_baseline_header(&v); + let input_ids = token_ids(&v["input_token_ids"]); + let output_ids = token_ids(&v["output_token_ids"]); + assert_eq!(input_ids.len(), 202); + assert_eq!(output_ids.len(), 32); + let text = v["text"].as_str().unwrap().to_owned(); + assert!(text.len() <= FRAME_LIMIT); + assert_baseline_windows(&v["windows"], &output_ids); + Baseline { input_ids, output_ids, text } +} +/// A window with no draft capacity is only the single anchor before the reserved final public token. +fn assert_zero_draft_anchor(w: &WindowWitness, index: usize, count: usize, active: usize, outputs: usize) { + // generate_mtp_resume reserves one final public authoritative token + // outside the windows. Only its preceding single anchor can have + // no available draft capacity. Padding is never an output token. + assert_eq!(index + 1, count); + assert_eq!(w.verified_count, 1); + assert_eq!(w.accepted_non_eos_drafts, 0); + assert_eq!(active + 1, outputs - 1); +} +pub(super) fn checked_candidate_window_prefix(windows: &[WindowWitness], output_ids: &[u32]) -> (usize, usize) { + assert!(!output_ids.is_empty()); + let mut active = Vec::new(); + let mut offered = 0usize; + let mut accepted = 0usize; + for (index, w) in windows.iter().enumerate() { + assert!((1..=4).contains(&w.verified_count)); + assert!(!w.authoritative_eos); + assert_eq!(w.accepted_non_eos_drafts, w.verified_count - 1); + if w.draft_steps == 0 { + assert_zero_draft_anchor(w, index, windows.len(), active.len(), output_ids.len()); + } else { + assert!((1..=4).contains(&w.draft_steps)); + assert!(w.verified_count - 1 <= w.draft_steps); + } + active.extend_from_slice(&w.verified_ids[..w.verified_count]); + offered += w.draft_steps; + accepted += w.accepted_non_eos_drafts; + } + assert_eq!(active.len(), output_ids.len() - 1); + assert_eq!(active, output_ids[..active.len()]); + (offered, accepted) +} +pub(super) fn candidate_windows(candidate: &Arm) -> (usize, usize) { + let counts = + checked_candidate_window_prefix(&candidate.measurement.windows, &candidate.measurement.output_token_ids); + assert_eq!(counts.0, candidate.offered()); + counts +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_io.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_io.rs new file mode 100644 index 00000000..519f7159 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_io.rs @@ -0,0 +1,149 @@ +//! Files, environment, request framing and counters shared by the PUBLIC pair proofs. +//! Included by `native_down_candidate_only.rs` and `native_down_public_pair.rs` (each owns its copy of the state). +use super::*; + +pub(super) const ARTIFACT_CAP: usize = 16 * 1024 * 1024; +pub(super) static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +pub(super) const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; +pub(super) const CAP: u32 = 32; +const INSTRUCTIONS: &str = "Use only the public document. Preserve the requested word order."; +const SEQUENCE: &str = "Return this public sequence once, without explanation: amber birch cedar delta elm fern \ + grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc \ + amber birch cedar delta elm fern."; +const METADATA_KEYS: [&str; 8] = [ + "engine_source_sha256", + "evaluation_binary_sha256", + "gpu", + "driver", + "cuda", + "power_limit_w", + "clocks", + "context_tokens", +]; + +pub(super) fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { + ARTIFACT_BYTES + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { + current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP) + }) + .map(|_| ()) + .map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded")) +} +pub(super) fn path(name: &str) -> PathBuf { + env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path") +} +pub(super) fn sha(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() +} +pub(super) fn save(root: &std::path::Path, name: &str, value: &Value) { + let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed"); + assert!(bytes.len() <= 1024 * 1024); + reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow")) + .expect("whole public pair serialized budget exceeded"); + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(root.join(name)) + .expect("fresh public pair output required"); + f.write_all(&bytes).unwrap(); + f.write_all(b"\n").unwrap(); + f.sync_data().unwrap(); +} +/// Reads a sealed regular file of at most `limit` bytes; `what` is the refusal message of the open. +pub(super) fn sealed_bytes(env_name: &str, limit: usize, what: &str) -> Vec { + let mut f = OpenOptions::new().read(true).custom_flags(0x20000 | 0x800).open(path(env_name)).expect(what); + assert!(f.metadata().unwrap().is_file()); + let mut bytes = Vec::new(); + std::io::Read::by_ref(&mut f).take(limit as u64 + 1).read_to_end(&mut bytes).unwrap(); + assert!(bytes.len() <= limit); + bytes +} +pub(super) fn cache( + m: crate::qwen_forward::moe_weight_cache::WeightCacheCounters, + d: crate::qwen_forward::dense_weight_cache::DenseCacheCounters, +) -> CacheCounts { + CacheCounts { + expert_hits: m.hits, + expert_misses: m.misses, + expert_source_bytes: m.read_bytes, + expert_upload_bytes: m.upload_bytes, + expert_eviction_bytes: m.eviction_bytes, + dense_hits: d.hits, + dense_source_bytes: d.read_bytes, + dense_upload_bytes: d.upload_bytes, + } +} +pub(super) fn cache_json(c: CacheCounts) -> Value { + json!({ + "expert_hits":c.expert_hits,"expert_misses":c.expert_misses,"expert_source_bytes":c.expert_source_bytes, + "expert_upload_bytes":c.expert_upload_bytes,"expert_eviction_bytes":c.expert_eviction_bytes, + "dense_hits":c.dense_hits,"dense_source_bytes":c.dense_source_bytes,"dense_upload_bytes":c.dense_upload_bytes + }) +} +fn document(lines: usize) -> String { + let mut document = + String::from("PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n"); + for index in 0..lines { + document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n")); + } + document.push_str(SEQUENCE); + document +} +fn render(document: &str) -> String { + let message = |role, content| public_renderer::Message { role, content, reasoning: None, parts: None }; + public_renderer::render( + &[message(public_renderer::Role::System, INSTRUCTIONS), message(public_renderer::Role::User, document)], + public_renderer::Effort::None, + ) + .expect("actual daemon public renderer refused") +} +fn canonical(document: &str) -> Value { + json!({"model":"pinned-native-model","instructions":INSTRUCTIONS,"input":document,"tools":[], + "max_output_tokens":CAP,"temperature":0,"stream":true,"store":false}) +} +pub(super) fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { + for lines in 1..=64 { + let document = document(lines); + let prompt = render(&document); + let req = GenerationRequest { + request_id: "public-paired-owner-generation".into(), + prompt, + max_output_tokens: CAP, + temperature_milli: 0, + sampling: Default::default(), + }; + let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame"); + if (193..=256).contains(&ids.len()) { + return (req, ids, canonical(&document)); + } + assert!( + ids.len() <= 256, + "public framing jumped past the predeclared193..256 intake; do not fit a token surrogate" + ); + } + panic!("public framed193..256 token request unavailable"); +} +pub(super) fn metadata() -> Value { + let b = sealed_bytes("LELEKA_STRA169_PAIR_METADATA", 16384, "ROOT public measurement metadata required"); + assert_eq!( + sha(&b), + env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required") + ); + let value: Value = serde_json::from_slice(&b).unwrap(); + let o = value.as_object().expect("public metadata object required"); + for key in METADATA_KEYS { + assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required"); + } + assert!(o.keys().all(|k| METADATA_KEYS.contains(&k.as_str()))); + assert_eq!(o["context_tokens"], json!(262144)); + value +} +/// The keys of `extra` added to the object `base`. +pub(super) fn merged(mut base: Value, extra: Value) -> Value { + let (Some(target), Some(source)) = (base.as_object_mut(), extra.as_object()) else { + panic!("JSON objects required") + }; + target.extend(source.iter().map(|(key, value)| (key.clone(), value.clone()))); + base +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_owner.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_owner.rs new file mode 100644 index 00000000..7b4a072c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_owner.rs @@ -0,0 +1,310 @@ +//! The one loaded owner of the PUBLIC candidate proofs: admission of the sealed inputs, the load, the ordered +//! teardown and the artifacts of it. The proofs differ only in the `Proof` hooks (`native_down_pair_proofs.rs`). +use super::*; +use crate::qwen_forward::owner_wall_profile::{self, Sample}; +use leleka_model_format::qwen4exp::{ProvisionalExpertSource, ResidentExpertSourceReport}; +use std::os::unix::fs::PermissionsExt; + +const PROFILE_LEN: usize = 196_632; + +/// One failed or passed assertion that is decided at teardown and asserted afterwards. +pub(super) type Check = (bool, &'static str); +pub(super) struct Case { + pub(super) req: GenerationRequest, + pub(super) ids: Vec, +} +/// What a proof reports of its cache owners: the profile JSON and the assertions on the witnesses. +pub(super) struct MoeFacts { + pub(super) json: Option, + pub(super) checks: Vec, +} +/// Borrowed state a generation needs besides the loaded owner. +pub(super) struct RunCtx<'a, 'ctx> { + pub(super) binding: &'a ModelBinding, + pub(super) tokenizer: &'a Tokenizer, + pub(super) context: &'a Rc>, + pub(super) eos: u32, + pub(super) case: &'a Case, +} +/// What the finished proof is judged on, after every attempted teardown. +pub(super) struct Finish { + pub(super) root: PathBuf, + pub(super) hardware: Value, + pub(super) baseline: Baseline, + pub(super) case: Case, + pub(super) driver_version: Value, + pub(super) report: R, + pub(super) recorded: Value, + pub(super) td: Teardown, +} +pub(super) trait Proof { + type Report; + /// Opens shard 0 with the incremental expert capture. + fn incremental_capture(&self) -> bool { + false + } + fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c>; + fn moe<'c>( + &self, + binding: &ModelBinding, + context: &'c leleka_cuda_driver::Context<'_>, + profile: &[u8], + ) -> MoeWeightCache<'c>; + fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> Self::Report; + fn moe_facts(&self, moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts; + fn dense_check(&self, _dense: &DenseWeightCache<'_>) -> Option { + None + } + /// The cache counters before the first and after the last request of the report. + fn cache_bounds(report: &Self::Report) -> (Value, Value); + /// Saves the report artifact; returns the JSON saved. + fn record(&self, root: &std::path::Path, report: &Self::Report) -> Value; + fn after_teardown(&self, _report: &mut Self::Report) {} + fn conclude(&self, finish: Finish); +} + +fn prepare_root() -> PathBuf { + let root = path("LELEKA_STRA169_PAIR_OUTPUT"); + assert!(root.is_absolute() && !root.exists()); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); + std::fs::create_dir(&root).unwrap(); + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); + root +} +fn inherited_fd() -> u32 { + // Existing identical GDN recurrence was qualified in cdb5ec8a and current15b3. + // Root runs only the new GDN full-products entry in this component cohort. + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); + assert!((3..=1048576).contains(&fd)); + fd +} +fn open_artifact(fd: u32, incremental: bool) -> (Qwen4ExpArtifact, ProvisionalExpertSource, u128) { + // Observation only. Missing/invalid inherited FD defers capture refusal; + // the original later InheritedKarArchive gate remains authoritative. + let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); + let shard0_started = Instant::now(); + let shard0_path = path("LELEKA_STRA169_IQ3S_SHARD0"); + let opened = if incremental { + Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental(&shard0_path, SHARD0, observed_kar.as_ref()) + } else { + Qwen4ExpArtifact::open_shard0_with_expert_capture(&shard0_path, SHARD0, observed_kar.as_ref()) + }; + let (shard0, capture) = opened.expect("pinned shard0 failed"); + let capture_ns = shard0_started.elapsed().as_nanos(); + drop(observed_kar); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); + (artifact, capture, capture_ns) +} +fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) { + let m = artifact.tokenizer(); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); + let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); + (tokenizer, eos) +} +fn renderer_sha() -> String { + sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")) +} +fn baseline_admission_json() -> Value { + json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1", + "retained_source_sha256":"ea8b6183c4f9bb5851054f908913d87b06c896c6408e8b737b97da77e3aba7e1", + "actual_baseline_phase":"warm","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE, + "renderer_source_sha256":renderer_sha(),"framed_ids_match":true,"context_tokens":262144, + "temperature_milli":0,"max_output_tokens":CAP,"historical_timing_used":false, + "baseline_campaign_succeeded":false}) +} +fn frame_json(case: &Case) -> Value { + json!({"renderer_source_sha256":renderer_sha(),"framed_prompt":case.req.prompt, + "framed_prompt_sha256":sha(case.req.prompt.as_bytes()),"input_token_ids":case.ids, + "framed_count":case.ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}) +} +fn admit_request(root: &std::path::Path, tokenizer: &Tokenizer, baseline: &Baseline) -> Case { + let (req, ids, canonical) = request(tokenizer); + assert_eq!(ids, baseline.input_ids); + assert_eq!(ids.len(), 202); + let case = Case { req, ids }; + save(root, "BASELINE-ADMISSION.json", &baseline_admission_json()); + save(root, "PUBLIC-REQUEST.json", &canonical); + save(root, "FRAME.json", &frame_json(&case)); + case +} +fn bind_model(artifact: Qwen4ExpArtifact, inherited: &InheritedKarArchive) -> ModelBinding { + ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + inherited, + &path("LELEKA_STRA169_MTP_PACK"), + &path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual KAR MTP binding failed") +} +pub(super) fn bank_json(r: &ResidentExpertSourceReport) -> Value { + json!({"source_bytes":r.source_bytes,"charged_bytes":r.charged_bytes,"bank_count":r.bank_count, + "source_cap_bytes":r.source_cap_bytes,"observed_mem_available_bytes":r.observed_mem_available_bytes, + "future_headroom_bytes":r.future_headroom_bytes,"shard0_sha256_bytes":r.shard0_sha256, + "completed_logical_copy_spans":r.copied_spans,"completed_logical_copy_bytes":r.copied_bytes, + "disk_io_claim":false,"raw_bytes_only_not_finite_certificate":true}) +} +fn adopt_bank(root: &std::path::Path, binding: &mut ModelBinding, capture: ProvisionalExpertSource, capture_ns: u128) { + // Selected fresh binding only, before Driver/profile/session publication. + let bank_started = Instant::now(); + let r = binding.adopt_resident_expert_capture(capture).expect("actual resident expert RAM bank admission failed"); + let bank_load_ns = bank_started.elapsed().as_nanos(); + save( + root, + "BANK-ADMISSION.json", + &json!({"load_ns":bank_load_ns,"shard0_digest_capture_ns":capture_ns, + "source_transport":"same-fd-full-sha-opaque-capture","report":bank_json(&r)}), + ); +} + +/// The sealed ranked expert profile: the open file stays until the caches have been built from its bytes. +pub(super) struct Profile { + file: std::fs::File, + bytes: Vec, +} +impl Profile { + fn open() -> Self { + let mut file = OpenOptions::new() + .read(true) + .custom_flags(0x20000) + .open(path("LELEKA_STRA169_EXPERT_PROFILE")) + .expect("ROOT pinned STRP profile required"); + assert!(file.metadata().unwrap().is_file()); + assert_eq!(file.metadata().unwrap().len(), PROFILE_LEN as u64); + let mut bytes = Vec::new(); + bytes.try_reserve_exact(PROFILE_LEN).expect("bounded profile allocation failed"); + Read::by_ref(&mut file).take(PROFILE_LEN as u64 + 1).read_to_end(&mut bytes).unwrap(); + assert_eq!(bytes.len(), PROFILE_LEN); + crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes) + .expect("pure pinned profile admission failed before Driver"); + Profile { file, bytes } + } + fn release(self) { + drop(self.file); + drop(self.bytes); + } +} + +/// Everything admitted on the host before the Driver is loaded. +pub(super) struct Host { + pub(super) root: PathBuf, + pub(super) hardware: Value, + pub(super) baseline: Baseline, + pub(super) tokenizer: Tokenizer, + pub(super) eos: u32, + pub(super) case: Case, + pub(super) binding: ModelBinding, + pub(super) inherited: InheritedKarArchive, + pub(super) profile: Profile, +} +impl Host { + pub(super) fn admit(proof: &impl Proof) -> Host { + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); + let baseline = baseline(); + let hardware = metadata(); + let root = prepare_root(); + let fd = inherited_fd(); + let (artifact, capture, capture_ns) = open_artifact(fd, proof.incremental_capture()); + let (tokenizer, eos) = pinned_tokenizer(&artifact); + let case = admit_request(&root, &tokenizer, &baseline); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); + let mut binding = bind_model(artifact, &inherited); + let profile = Profile::open(); + adopt_bank(&root, &mut binding, capture, capture_ns); + Host { root, hardware, baseline, tokenizer, eos, case, binding, inherited, profile } + } +} + +/// The loaded caches and output head of the one admitted owner. +pub(super) struct Owner<'ctx, 'driver> { + pub(super) output: OutputStage<'ctx, 'driver>, + pub(super) kar: KarPleCache<'ctx>, + pub(super) dense: DenseWeightCache<'ctx>, + pub(super) moe: MoeWeightCache<'ctx>, + preload_ns: u128, +} +/// The counters read from the caches before they are closed. +pub(super) struct OwnerCounters { + pub(super) shared_tail_rows: u64, + pub(super) lru: (u64, u64, u64), + pub(super) lru_metadata_bytes: Option, + pub(super) mtp_input: u64, + pub(super) router_rows: Option, + pub(super) gr_batch: u64, + pub(super) compact_head: u64, +} +/// What the ordered teardown of the owner established. +pub(super) struct Witnessed { + pub(super) oracle_disabled: bool, + pub(super) moe_closed: bool, + pub(super) dense_closed: bool, + pub(super) counters: OwnerCounters, + pub(super) facts: MoeFacts, + pub(super) dense_check: Option, +} +pub(super) struct Teardown { + pub(super) head: Witnessed, + pub(super) synchronized: bool, + pub(super) allocated: usize, + pub(super) context_closed: bool, + pub(super) bank_after: Option, + pub(super) owner_wall: Result<[Sample; 6], &'static str>, +} +impl<'ctx, 'driver> Owner<'ctx, 'driver> { + pub(super) fn load( + proof: &P, + binding: &ModelBinding, + context: &'ctx leleka_cuda_driver::Context<'driver>, + profile: Profile, + ) -> Self { + let output = OutputStage::load_compact(binding, context).unwrap(); + let kar = KarPleCache::new(context, binding.kar_ple_binding().unwrap()).unwrap(); + // Profile admission observes all eager Dense/QSA/router and MTP owners. + let dense = proof.dense(binding, context); + let preload_started = Instant::now(); + let moe = proof.moe(binding, context, &profile.bytes); + let preload_ns = preload_started.elapsed().as_nanos(); + profile.release(); + Owner { output, kar, dense, moe, preload_ns } + } + /// The borrowed inputs of the actual generation, with the owner wall profile armed. + pub(super) fn armed_inputs<'a>(&'a mut self, run: &RunCtx<'a, 'ctx>) -> Inputs<'a, 'ctx, 'driver> { + let inputs = Inputs { + binding: run.binding, + output: &self.output, + kar: &mut self.kar, + moe: &mut self.moe, + dense: &self.dense, + tokenizer: run.tokenizer, + context: run.context, + eos: run.eos, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, + }; + owner_wall_profile::arm().expect("actual owner wall profile admission failed"); + inputs + } + /// Witnesses, then closes the caches and the output head, in the order of the original proofs. + pub(super) fn teardown(self, proof: &P, binding: &ModelBinding) -> Witnessed { + let Owner { output, kar, dense, moe, preload_ns } = self; + let oracle_disabled = crate::qwen_forward::oracle_capture::disable(&output).is_ok(); + let shared_tail_rows = moe.test_shared_tail_witness(); + let lru = moe.test_lru_witness(); + let lru_metadata_bytes = moe.test_lru_metadata_bytes().ok(); + let facts = proof.moe_facts(&moe, binding, preload_ns); + let mtp_input = moe.test_mtp_input_completions(); + let moe_closed = moe.close().is_ok(); + let router_rows = dense.test_router_witness().ok(); + let gr_batch = dense.test_gr_batch_completions(); + let dense_check = proof.dense_check(&dense); + let dense_closed = dense.close().is_ok(); + drop(kar); + let compact_head = output.test_compact_completions(); + drop(output); + let counters = + OwnerCounters { shared_tail_rows, lru, lru_metadata_bytes, mtp_input, router_rows, gr_batch, compact_head }; + Witnessed { oracle_disabled, moe_closed, dense_closed, counters, facts, dense_check } + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs new file mode 100644 index 00000000..4daae209 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs @@ -0,0 +1,291 @@ +//! The four PUBLIC candidate proofs: they differ in the caches they load, in what they generate and in what +//! they conclude; the owner, the teardown and the artifacts are shared (`native_down_pair_run.rs`). +use super::*; +use crate::qwen_forward::moe_weight_cache::LearnedMainWitness; +use fivecase_runtime::FiveCaseReport; + +const METADATA_CAP: usize = 16 * 1024 * 1024; +const CASE_STATE: &str = "no replayed helper; actual per-case before/after counters; \ + same loaded owners but fresh target/draft each request"; +const DIRECT_STATE: &str = "fresh target+draft sessions after original-first changed direct Down layer0 helper; \ + helper-warmed kernel/module/L0 scratch/KAR row-source/MoE expert-cache; actual generation cache_before \ + measured after that helper; ranked prefix/preload separately reported, not cold hardware"; +const DIRECT_PHASE: &str = "candidate-only-new-slowpaths-fixed-draft-selected-QSA-queued-target-shared-tail-\ + pinned-profile-spill-router-scratch"; + +fn pinned_facts(moe: &MoeWeightCache<'_>, preload_ns: u128) -> MoeFacts { + let witness = moe.test_profile_witness(); + let json = witness.as_ref().ok().map(|w| { + json!({ + "profile_sha256":"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", + "complete_pinned_experts":w.prefix,"pinned_bytes":w.pinned_bytes,"spill_bytes":w.spill_bytes, + "post_preload_source_read_bytes_including_shared":w.post_preload_read_bytes, + "post_preload_upload_bytes_including_shared":w.post_preload_upload_bytes, + "spill_reserve":w.spill_reserve,"largest_triplet":w.largest_triplet, + "metadata_bytes":w.metadata_bytes,"main_slot_limit":w.main_slot_limit, + "fixed_resident_upload_bytes_before_profile":w.fixed_resident_upload_bytes, + "pinned_hits":w.pinned_hits,"spill_hits":w.spill_hits, + "spill_misses":w.spill_misses,"preload_read_bytes":w.preload_read_bytes, + "preload_upload_bytes":w.preload_upload_bytes,"preload_ns":preload_ns, + "preload_in_generation_timing":false,"normal_defaults_changed":false + }) + }); + let ok = witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= METADATA_CAP); + MoeFacts { json, checks: vec![(ok, "actual bounded pinned profile owner/hit witness missing")] } +} +fn learned_json(w: &LearnedMainWitness, shared_valid: bool, preload_ns: u128) -> Value { + json!({ + "policy":"learned-main-lru-shared192", "routed_matrices":w.routed_matrices, + "routed_bytes":w.routed_bytes,"shared_matrices":w.shared_matrices,"shared_bytes":w.shared_bytes, + "main_bytes":w.main_bytes,"main_slot_limit":w.main_slot_limit,"metadata_bytes":w.metadata_bytes, + "historical_prefix":w.historical_prefix,"historical_routed_preload_bytes":w.historical_routed_preload_bytes, + "age":w.age,"preload_ns":preload_ns,"normal_defaults_changed":false, + "shared_witness_valid":shared_valid + }) +} +fn learned_facts(moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts { + let witness = moe.learned_main_witness(binding); + let shared = moe.shared_permanent_witness(); + let json = witness.as_ref().ok().map(|w| learned_json(w, shared.is_ok(), preload_ns)); + let ok = + witness.is_ok_and(|w| w.routed_matrices > 0 && w.shared_matrices == 192 && w.metadata_bytes <= METADATA_CAP); + let checks = vec![ + (ok, "actual learned main owner witness missing"), + (shared.is_ok(), "actual shared owner role witness missing"), + ]; + MoeFacts { json, checks } +} + +/// The candidate-only proof: the changed direct Down packet proof, then one candidate arm +/// against the retained Native arm. +pub(super) struct DirectDown; +pub(super) struct Direct { + arm: Arm, + /// The teardown assertion of the loaded direct Down report. + down: Option>, +} +fn direct_parity(arm: &Arm, baseline: &Baseline) -> bool { + arm.measurement.output_token_ids == baseline.output_ids + && arm.text == baseline.text + && matches!(arm.reason, FinishReason::Length) + && arm.usage.input_tokens == 202 + && arm.usage.output_tokens == 32 + && arm.usage.reused_input_tokens == 0 +} +fn direct_head_json(f: &Finish, parity: bool, ids_len: usize) -> Value { + json!({"scope":"one fresh candidate owner generation compared with retained completed actual Native arm; \ + excludes historical paired timing","baseline_sha256":BASELINE_SHA,"model_digest":MODEL_DIGEST, + "profile":KAR_MTP_PROFILE,"hardware":f.hardware,"actual_cuda_driver_version":f.driver_version, + "context_tokens":262144,"framed_tokens":ids_len,"output_cap":CAP,"same_request_token_ids":true, + "greedy_output_ids_text_finish_usage_equal":parity,"actual_pinned_profile":f.td.head.facts.json}) +} +fn direct_tail_json(f: &Finish, offered: usize, accepted: usize) -> Value { + let m = &f.report.arm.measurement; + json!({"actual_mtp_offered":offered,"actual_non_eos_drafts_accepted":accepted,"completed":m.completed, + "terminal_published":m.terminal_published,"retained_prefix_tokens":m.retained_prefix_tokens, + "cache_state":DIRECT_STATE,"historical_speed_ratio":null,"GateC":false,"GateD":false, + "HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":f.td.allocated, + "cleanup_complete":true}) +} +impl Proof for DirectDown { + type Report = Direct; + fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c> { + DenseWeightCache::new_qsa_selected_router_gr_batch(binding, context).unwrap() + } + fn moe<'c>( + &self, + binding: &ModelBinding, + context: &'c leleka_cuda_driver::Context<'_>, + profile: &[u8], + ) -> MoeWeightCache<'c> { + MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input( + binding, context, profile, + ) + .unwrap() + } + fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> Direct { + // Only the changed direct Down proof shares this model load. + // The unchanged, previously qualified GDN helper is not repeated. + let mut session = QwenSession::for_binding_on_shared_device(run.binding, Rc::clone(run.context)); + let down = QwenForward::test_direct_down_on_loaded( + run.binding, + run.context, + &mut session, + &mut owner.kar, + &mut owner.moe, + &owner.dense, + ) + .expect("actual original-first direct Down packet proof failed"); + drop(session); + let execution = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr; + let arm = owner.armed_inputs(run).arm(&run.case.req, &run.case.ids, execution, DIRECT_PHASE); + Direct { arm, down: Some(Box::new(move || down.assert_after_teardown())) } + } + fn moe_facts(&self, moe: &MoeWeightCache<'_>, _binding: &ModelBinding, preload_ns: u128) -> MoeFacts { + pinned_facts(moe, preload_ns) + } + fn cache_bounds(report: &Direct) -> (Value, Value) { + (cache_json(report.arm.measurement.cache_before), cache_json(report.arm.measurement.cache_after)) + } + fn record(&self, root: &std::path::Path, report: &Direct) -> Value { + let json = report.arm.json("candidate-only", "integer-gu-native-down-retained-gr256-kv-only"); + save(root, "CANDIDATE.json", &json); + json + } + fn after_teardown(&self, report: &mut Direct) { + (report.down.take().expect("loaded direct Down report missing"))(); + } + fn conclude(&self, f: Finish) { + let arm = &f.report.arm; + let (offered, accepted) = candidate_windows(arm); + let parity = direct_parity(arm, &f.baseline); + let head = direct_head_json(&f, parity, f.case.ids.len()); + let quality = with_counters(merged(head, direct_tail_json(&f, offered, accepted)), &f.td); + save(&f.root, "QUALITY.json", &quality); + assert!(arm.measurement.completed && arm.measurement.terminal_published); + assert_eq!(arm.measurement.retained_prefix_tokens, 0); + assert!(offered > 0 && accepted > 0, "actual candidate must offer and accept MTP drafts"); + assert!(parity, "candidate differs from retained actual Native output/finish/Usage"); + eprintln!( + "PUBLIC candidate-only framed={} output={} offered={offered} accepted={accepted} parity=true allocated=0 \ + historical_speed_ratio=null", + f.case.ids.len(), + arm.measurement.output_token_ids.len() + ); + } +} + +/// The constructor name is 118 characters: it only fits a line of the limit when it starts at column 0. +#[rustfmt::skip] +fn resident_moe<'c>( + binding: &ModelBinding, + context: &'c leleka_cuda_driver::Context<'_>, + profile: &[u8], +) -> MoeWeightCache<'c> { + MoeWeightCache:: +new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( + binding, context, profile, + ) + .unwrap() +} + +/// Which owner policy the five public requests run on. +#[derive(Clone, Copy)] +pub(super) enum Kind { + OneLoadedOwner, + RetainedQkQsa, + ResidentOwners, +} +pub(super) struct FiveCase(pub(super) Kind); +impl FiveCase { + /// The policy the owner reports; `None` is the default of `fivecase_runtime`. + fn run_policy(&self) -> Option<&'static str> { + match self.0 { + Kind::OneLoadedOwner => None, + Kind::RetainedQkQsa => Some("integer-gr256-streamed-spill-retained-qk40960-qsa108544"), + Kind::ResidentOwners => { + Some("integer-gr256-resident-owners-learned-main-shared192-gdn-journal-incremental-capture") + } + } + } + fn changed_owner_policy(&self) -> &'static str { + match self.0 { + Kind::OneLoadedOwner => "digest-capture-queued-input-compact-head-GR-batch-1GiB-reusable-spill-floor", + Kind::RetainedQkQsa => { + "digest-capture-queued-input-compact-head-GR-batch-1GiB-spill-retained-qk40960-qsa108544" + } + Kind::ResidentOwners => "incremental-capture-learned-main-shared192-gdn-journal-qk40960-qsa108544", + } + } + fn quality_json(&self, f: &Finish, parity: bool) -> Value { + json!({"case1_retained_native_parity":parity, + "quality_against_original17":null,"requires_matching_original_five":true, + "changed_owner_policy":self.changed_owner_policy(), + "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":f.driver_version, + "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":f.hardware, + "allocated":f.td.allocated,"cleanup_complete":true,"same_request_case1":true, + "cache_state":CASE_STATE, + "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false, + "longcontext_170K":false}) + } +} +fn case1_parity(first: &Value, baseline: &Baseline) -> bool { + token_ids(&first["output_token_ids"]) == baseline.output_ids + && first["text"].as_str() == Some(baseline.text.as_str()) + && first["finish_reason"] == json!("Length") + && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}) +} +impl Proof for FiveCase { + type Report = FiveCaseReport; + fn incremental_capture(&self) -> bool { + matches!(self.0, Kind::ResidentOwners) + } + fn dense<'c>(&self, binding: &ModelBinding, context: &'c leleka_cuda_driver::Context<'_>) -> DenseWeightCache<'c> { + match self.0 { + Kind::OneLoadedOwner => DenseWeightCache::new_qsa_selected_router_gr_batch(binding, context), + Kind::RetainedQkQsa => DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention(binding, context), + Kind::ResidentOwners => { + DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(binding, context) + } + } + .unwrap() + } + fn moe<'c>( + &self, + binding: &ModelBinding, + context: &'c leleka_cuda_driver::Context<'_>, + profile: &[u8], + ) -> MoeWeightCache<'c> { + match self.0 { + Kind::ResidentOwners => resident_moe(binding, context, profile), + _ => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( + binding, context, profile, + ) + .unwrap(), + } + } + fn generate<'ctx>(&self, owner: &mut Owner<'ctx, '_>, run: &RunCtx<'_, 'ctx>) -> FiveCaseReport { + // Already qualified DirectDown/components are not replayed. Every case + // gets a fresh target/draft; one genuine weight/cache owner load is shared. + let mut inputs = owner.armed_inputs(run); + let (manifest, manifest_sha) = inputs.prepare_five_public_frames(); + match self.run_policy() { + None => inputs.arm_five_public_cases(&manifest, &manifest_sha), + Some(policy) => fivecase_runtime::run_on_loaded_with_policy(&mut inputs, &manifest, &manifest_sha, policy), + } + } + fn moe_facts(&self, moe: &MoeWeightCache<'_>, binding: &ModelBinding, preload_ns: u128) -> MoeFacts { + match self.0 { + Kind::ResidentOwners => learned_facts(moe, binding, preload_ns), + _ => pinned_facts(moe, preload_ns), + } + } + fn dense_check(&self, dense: &DenseWeightCache<'_>) -> Option { + let scratch = matches!(self.0, Kind::RetainedQkQsa).then(|| dense.test_retained_scratch_witness()); + scratch.map(|witness| { + ( + witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), + "actual retained scratch owner rows absent", + ) + }) + } + fn cache_bounds(report: &FiveCaseReport) -> (Value, Value) { + let json = report.json_after_teardown(); + let last = json["cases"].as_array().unwrap().last().unwrap(); + (json["cases"][0]["cache_before"].clone(), last["cache_after"].clone()) + } + fn record(&self, root: &std::path::Path, report: &FiveCaseReport) -> Value { + let json = report.json_after_teardown(); + save(root, "FIVE-CASE.json", &json); + json + } + fn conclude(&self, f: Finish) { + f.report.assert_after_teardown(); + let first = &f.recorded["cases"][0]; + assert_eq!(token_ids(&first["input_token_ids"]), f.baseline.input_ids); + let parity = case1_parity(first, &f.baseline); + save(&f.root, "QUALITY.json", &self.quality_json(&f, parity)); + assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); + eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_run.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_run.rs new file mode 100644 index 00000000..be19b50e --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_run.rs @@ -0,0 +1,140 @@ +//! Runs a `Proof` on the one loaded owner: generation, ordered teardown, the cleanup artifacts that survive a +//! failed generation, and the assertions that follow every attempted teardown. +use super::*; +use crate::qwen_forward::owner_wall_profile::{self, Sample}; + +const SCOPE: &str = + "six fixed producer categories during actual owner generation; excludes loading, preload and helper"; +const WALL_COUNTS: &str = + "attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens"; +const WALL_OVERHEAD: &str = "one Instant pair and bounded TLS accounting per armed invocation; \ + diagnostic run has instrumentation overhead"; + +fn counters_json(c: &OwnerCounters) -> Value { + json!({"actual_queued_shared_tail_rows":c.shared_tail_rows,"actual_mtp_input_completions":c.mtp_input, + "actual_compact_head_completions":c.compact_head,"actual_gr_batch_inject_completions":c.gr_batch, + "actual_lru_index":{"victim_lookups":c.lru.0,"metadata_updates":c.lru.1,"removals":c.lru.2, + "metadata_bytes":c.lru_metadata_bytes}, + "actual_router_scratch_rows":c.router_rows, + "actual_router_scratch_reuses":c.router_rows.map(|rows| rows.saturating_sub(1))}) +} +/// The witness keys of the teardown added to the object `base`. +pub(super) fn with_counters(base: Value, td: &Teardown) -> Value { + merged(base, counters_json(&td.head.counters)) +} +fn sample_json(sample: &Sample) -> Value { + json!({"label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns}) +} +fn owner_wall_json(root: &std::path::Path, hardware: &Value, td: &Teardown, bounds: Option<(Value, Value)>) -> Value { + let wall = &td.owner_wall; + let rows = wall.as_ref().ok().map(|samples| samples.iter().map(sample_json).collect::>()); + let (before, after) = bounds.unzip(); + json!({"schema":1,"valid":wall.is_ok(),"error":wall.as_ref().err(),"rows":rows, + "metadata":hardware,"owner_output_directory":root,"cache_before":before,"cache_after":after, + "scope":SCOPE,"drained_after_all_attempted_teardown":true,"counts":WALL_COUNTS, + "clock":"inclusive CPU owner wall with existing completion waits; not GPU service time", + "nested_totals_not_additive":true,"complete_request_accounting":false,"overhead":WALL_OVERHEAD, + "additional_cuda_calls":0,"additional_tensor_reads":0,"performance_acceptance":false}) +} +fn cleanup_json(td: &Teardown, generation_succeeded: bool) -> Value { + let h = &td.head; + let base = json!({"oracle_disabled":h.oracle_disabled,"moe_closed":h.moe_closed, + "dense_closed":h.dense_closed,"synchronized":td.synchronized,"allocated":td.allocated, + "context_closed":td.context_closed,"generation_succeeded":generation_succeeded, + "actual_pinned_profile":h.facts.json}); + with_counters(base, td) +} +/// The artifacts that are written even when the generation failed. +fn save_cleanup(root: &std::path::Path, hardware: &Value, td: &Teardown, report: Option<&P::Report>) { + let bounds = report.map(P::cache_bounds); + save(root, "OWNER-WALL.json", &owner_wall_json(root, hardware, td, bounds)); + if let Some(r) = &td.bank_after { + save(root, "BANK-COPIES.json", &bank_json(r)); + } + save(root, "CLEANUP.json", &cleanup_json(td, report.is_some())); +} +/// Synchronizes and closes the Context, then releases the binding and drains the owner wall profile. +fn seal( + head: Witnessed, + context: Rc>, + binding: ModelBinding, + inherited: InheritedKarArchive, +) -> Teardown { + let synchronized = context.synchronize().is_ok(); + let allocated = context.allocated_bytes(); + let closed = match Rc::try_unwrap(context) { + Ok(c) => Some(c.close()), + Err(c) => { + drop(c); + None + } + }; + let bank_after = binding.resident_expert_source_report().ok().flatten(); + drop(binding); + drop(inherited); + let owner_wall = owner_wall_profile::drain(); + let context_closed = matches!(&closed, Some(Ok(()))); + Teardown { head, synchronized, allocated, context_closed, bank_after, owner_wall } +} +fn assert_torn(td: &Teardown) { + let h = &td.head; + assert!(h.oracle_disabled && h.moe_closed && h.dense_closed && td.synchronized); + assert_eq!(td.allocated, 0); + assert!(td.context_closed); + assert!(td.owner_wall.is_ok(), "actual owner wall profile drain failed"); +} +/// Quality assertions follow every attempted teardown and preserve a primary +/// generation panic/error. There is no Native call or historical timing ratio. +fn assert_witnesses(h: &Witnessed) { + for (ok, message) in &h.facts.checks { + assert!(*ok, "{message}"); + } + let c = &h.counters; + assert!(c.gr_batch > 0, "actual retained GR batch injection did not complete"); + assert!(c.compact_head > 0, "actual compact full-vocabulary head did not complete"); + assert!(c.mtp_input > 0, "actual completed MTP input queue was not executed"); + assert!(c.shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(c.router_rows.is_some_and(|rows| rows > 1), "actual router scratch was not reused"); + assert!(c.lru.0 > 0 && c.lru.1 > 0 && c.lru.2 > 0, "actual indexed lookup/update/removal path was not exercised"); + assert!( + c.lru_metadata_bytes.is_some_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), + "bounded actual index metadata charge missing" + ); + if let Some((ok, message)) = &h.dense_check { + assert!(*ok, "{message}"); + } +} +/// Rethrows a generation panic first, then a cleanup panic, once the cleanup artifacts are written. +fn unwind_after_cleanup(candidate: std::thread::Result, cleanup: std::thread::Result<()>) -> R { + let report = match candidate { + Ok(value) => value, + Err(primary) => resume_unwind(primary), + }; + if let Err(secondary) = cleanup { + resume_unwind(secondary); + } + report +} +pub(super) fn run(proof: &P) { + let Host { root, hardware, baseline, tokenizer, eos, case, binding, inherited, profile } = Host::admit(proof); + // Reuse the already verified bound tokenizer; no long request or Native inference. + let driver = Driver::load().expect("actual CUDA driver failed"); + let driver_version = json!(driver.version()); + let device = driver.device(0).unwrap(); + let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); + let mut owner = Owner::load(proof, &binding, context.as_ref(), profile); + let ctx = RunCtx { binding: &binding, tokenizer: &tokenizer, context: &context, eos, case: &case }; + let candidate = catch_unwind(AssertUnwindSafe(|| proof.generate(&mut owner, &ctx))); + let head = owner.teardown(proof, &binding); + let td = seal(head, context, binding, inherited); + let cleanup = catch_unwind(AssertUnwindSafe(|| { + save_cleanup::

(&root, &hardware, &td, candidate.as_ref().ok()); + })); + let mut report = unwind_after_cleanup(candidate, cleanup); + let recorded = proof.record(&root, &report); + assert_torn(&td); + proof.after_teardown(&mut report); + assert_witnesses(&td.head); + proof.conclude(Finish { root, hardware, baseline, case, driver_version, report, recorded, td }); +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs index 4aa34697..6207a32d 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs @@ -14,452 +14,19 @@ mod long_public_preflight; #[path = "../../../../crates/gateway-text/src/prompt.rs"] #[allow(dead_code)] mod public_renderer; -const ARTIFACT_CAP: usize = 16 * 1024 * 1024; -static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { - ARTIFACT_BYTES - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { - current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP) - }) - .map(|_| ()) - .map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded")) -} -const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; -const CAP: u32 = 32; -fn path(name: &str) -> PathBuf { - env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path") -} -fn sha(bytes: &[u8]) -> String { - Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() -} -fn save(root: &std::path::Path, name: &str, value: &Value) { - let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed"); - assert!(bytes.len() <= 1024 * 1024); - reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow")) - .expect("whole public pair serialized budget exceeded"); - let mut f = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(root.join(name)) - .expect("fresh public pair output required"); - f.write_all(&bytes).unwrap(); - f.write_all(b"\n").unwrap(); - f.sync_data().unwrap(); -} -fn cache( - m: crate::qwen_forward::moe_weight_cache::WeightCacheCounters, - d: crate::qwen_forward::dense_weight_cache::DenseCacheCounters, -) -> CacheCounts { - CacheCounts { - expert_hits: m.hits, - expert_misses: m.misses, - expert_source_bytes: m.read_bytes, - expert_upload_bytes: m.upload_bytes, - expert_eviction_bytes: m.eviction_bytes, - dense_hits: d.hits, - dense_source_bytes: d.read_bytes, - dense_upload_bytes: d.upload_bytes, - } -} -fn cache_json(c: CacheCounts) -> Value { - json!({"expert_hits":c.expert_hits,"expert_misses":c.expert_misses,"expert_source_bytes":c.expert_source_bytes,"expert_upload_bytes":c.expert_upload_bytes,"expert_eviction_bytes":c.expert_eviction_bytes,"dense_hits":c.dense_hits,"dense_source_bytes":c.dense_source_bytes,"dense_upload_bytes":c.dense_upload_bytes}) -} -fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { - let instructions = "Use only the public document. Preserve the requested word order."; - for lines in 1..=64 { - let mut document = String::from( - "PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n", - ); - for index in 0..lines { - document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n")); - } - document.push_str("Return this public sequence once, without explanation: amber birch cedar delta elm fern grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc amber birch cedar delta elm fern."); - let prompt = public_renderer::render( - &[ - public_renderer::Message { - role: public_renderer::Role::System, - content: instructions, - reasoning: None, - parts: None, - }, - public_renderer::Message { - role: public_renderer::Role::User, - content: &document, - reasoning: None, - parts: None, - }, - ], - public_renderer::Effort::None, - ) - .expect("actual daemon public renderer refused"); - let req = GenerationRequest { - request_id: "public-paired-owner-generation".into(), - prompt, - max_output_tokens: CAP, - temperature_milli: 0, - sampling: Default::default(), - }; - let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame"); - if (193..=256).contains(&ids.len()) { - let canonical = json!({"model":"pinned-native-model","instructions":instructions,"input":document,"tools":[],"max_output_tokens":CAP,"temperature":0,"stream":true,"store":false}); - return (req, ids, canonical); - } - assert!( - ids.len() <= 256, - "public framing jumped past the predeclared193..256 intake; do not fit a token surrogate" - ); - } - panic!("public framed193..256 token request unavailable"); -} -struct Arm { - measurement: EvaluationMeasurement, - text: String, - usage: Usage, - reason: FinishReason, -} -impl Arm { - fn json(&self, phase: &str, policy: &str) -> Value { - let windows: Vec<_> = self.measurement.windows.iter().map(|w| json!({"draft_steps":w.draft_steps,"verified_ids":w.verified_ids,"verified_count":w.verified_count,"authoritative_eos":w.authoritative_eos,"accepted_non_eos_drafts":w.accepted_non_eos_drafts})).collect(); - json!({"phase":phase,"execution_policy":policy,"input_token_ids":self.measurement.input_token_ids,"output_token_ids":self.measurement.output_token_ids,"retained_prefix_tokens":self.measurement.retained_prefix_tokens,"prefill_ns":u64::try_from(self.measurement.prefill.as_nanos()).unwrap(),"decode_ns":u64::try_from(self.measurement.decode.as_nanos()).unwrap(),"windows":windows,"cache_before":cache_json(self.measurement.cache_before),"cache_after":cache_json(self.measurement.cache_after),"completed":self.measurement.completed,"stopped":self.measurement.stopped,"terminal_published":self.measurement.terminal_published,"text":self.text,"usage":{"input_tokens":self.usage.input_tokens,"output_tokens":self.usage.output_tokens,"reused_input_tokens":self.usage.reused_input_tokens},"finish_reason":format!("{:?}",self.reason)}) - } - fn offered(&self) -> usize { - self.measurement.windows.iter().map(|w| w.draft_steps).sum() - } -} -struct Inputs<'a, 'ctx, 'driver> { - binding: &'a ModelBinding, - output: &'a OutputStage<'ctx, 'driver>, - kar: &'a mut KarPleCache<'ctx>, - moe: &'a mut MoeWeightCache<'ctx>, - dense: &'a DenseWeightCache<'ctx>, - tokenizer: &'a Tokenizer, - context: &'a Rc>, - eos: u32, - shared: Shared, -} -impl Inputs<'_, '_, '_> { - fn arm( - &mut self, - req: &GenerationRequest, - ids: &[u32], - execution: EvaluationExecution, - phase: &'static str, - ) -> Arm { - eprintln!( - "PUBLIC arm-start phase={phase} is_native_control={} allocated={} budget={}", - execution == EvaluationExecution::Native, - self.context.allocated_bytes(), - self.context.budget_bytes() - ); - // Fresh genuine target state and fresh actual decoder. No position reset, - // invented prefix, checkpoint reuse or cached-token count substitution. - let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); - let cancel = AtomicBool::new(false); - let (sink, mut stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); - let drain = thread::spawn(move || { - let mut text = String::new(); - let mut usage = None; - let mut terminal = None; - while let Some(event) = stream.recv().expect("pair stream missing terminal") { - match event { - GenerationEvent::TextDelta { text: delta } => { - assert!(text.len() + delta.len() <= FRAME_LIMIT); - text.push_str(&delta); - } - GenerationEvent::Usage(value) => { - assert!(usage.replace(value).is_none()); - } - GenerationEvent::Terminal(value) => { - assert!(terminal.replace(value).is_none()); - } - GenerationEvent::ToolCallDelta { .. } => { - panic!("text-only public pair emitted unexpected typed tool") - } - } - } - (text, usage, terminal) - }); - let before = cache(self.moe.counters(), self.dense.counters()); - let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); - let mut pending = None; - let result = generate_mtp_resume( - Generation { - measurement: Some(&recorder), - execution, - binding: self.binding, - output: self.output, - kar_cache: Some(&mut *self.kar), - moe_cache: &mut *self.moe, - dense_cache: self.dense, - session: &mut session, - tokenizer: self.tokenizer, - sink: &sink, - cancel: &cancel, - shared: &self.shared, - context_tokens: 262144, - eos: self.eos, - mtp: true, - clock: SystemClock, - }, - ids, - req.max_output_tokens, - None, - &mut pending, - ); - let (reason, usage) = match result { - Ok(value) => value, - Err(failure) => { - let terminal = match failure { - GenerationFailure::Cancelled => GenerationTerminal::Cancelled, - GenerationFailure::Backend(error) => { - GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } - } - }; - let diagnostic = format!("{terminal:?}"); - let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); - drop(sink); - let joined = drain.join(); - let consumer_failed = joined.is_err(); - let (text, seen_usage, seen_terminal) = joined.unwrap_or_default(); - let progress = recorder.borrow(); - let (output_ids, window_count, prefill_completed) = progress.diagnostic_progress(); - save( - &path("LELEKA_STRA169_PAIR_OUTPUT"), - "GENERATION-FAILURE.json", - &json!({"terminal":diagnostic,"terminal_published":published,"terminal_seen_matches":seen_terminal.as_ref()==Some(&terminal),"consumer_failed":consumer_failed,"usage_seen":seen_usage.map(|u|json!({"input_tokens":u.input_tokens,"output_tokens":u.output_tokens,"reused_input_tokens":u.reused_input_tokens})),"public_text":text,"text_bytes":text.len(),"actual_observed_output_ids":output_ids,"window_count":window_count,"prefill_completed":prefill_completed,"phase":phase,"allocated_at_failure":self.context.allocated_bytes(),"device_budget_bytes":self.context.budget_bytes(),"is_native_control":execution==EvaluationExecution::Native}), - ); - eprintln!("PUBLIC generation terminal={diagnostic}"); - panic!("actual public pair generation failed; bounded failure artifact retained"); - } - }; - let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; - let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); - drop(sink); - let (text, seen_usage, seen_terminal) = drain.join().expect("actual pair consumer failed"); - assert!(published && seen_terminal.as_ref() == Some(&terminal)); - assert!(seen_usage.as_ref() == Some(&usage)); - drop(pending); - drop(session); - let measured = recorder - .into_inner() - .finish( - before, - cache(self.moe.counters(), self.dense.counters()), - true, - matches!(reason, FinishReason::Stop), - published, - Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)), - ) - .expect("actual owner measurement refused"); - assert_eq!(measured.input_token_ids, ids); - assert_eq!(measured.retained_prefix_tokens, 0); - Arm { measurement: measured, text, usage, reason } - } -} -fn metadata() -> Value { - let mut f = OpenOptions::new() - .read(true) - .custom_flags(0x20000 | 0x800) - .open(path("LELEKA_STRA169_PAIR_METADATA")) - .expect("ROOT public measurement metadata required"); - assert!(f.metadata().unwrap().is_file()); - let mut b = Vec::new(); - std::io::Read::by_ref(&mut f).take(16385).read_to_end(&mut b).unwrap(); - assert!(b.len() <= 16384); - assert_eq!( - sha(&b), - env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required") - ); - let value: Value = serde_json::from_slice(&b).unwrap(); - let o = value.as_object().expect("public metadata object required"); - for key in [ - "engine_source_sha256", - "evaluation_binary_sha256", - "gpu", - "driver", - "cuda", - "power_limit_w", - "clocks", - "context_tokens", - ] { - assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required"); - } - assert!(o.keys().all(|k| { - [ - "engine_source_sha256", - "evaluation_binary_sha256", - "gpu", - "driver", - "cuda", - "power_limit_w", - "clocks", - "context_tokens", - ] - .contains(&k.as_str()) - })); - assert_eq!(o["context_tokens"], json!(262144)); - value -} +// Files, request framing and counters shared with the candidate-only proofs (native_down_candidate_only.rs). +#[path = "native_down_pair_io.rs"] +mod pair_io; +use pair_io::*; +// One actual owner generation, and the run of the pair on the one loaded owner. +#[path = "native_down_public_pair_arm.rs"] +mod pair_arm; +use pair_arm::*; +#[path = "native_down_public_pair_run.rs"] +mod pair_run; + #[test] #[ignore = "ROOT one-load public paired owner generation; no serving overlap"] fn pinned_single_load_public_native_vs_native_down_outer256_pair() { - assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_NATIVE_DOWN_PAIR").as_deref(), Ok("yes")); - let hardware = metadata(); - let root = path("LELEKA_STRA169_PAIR_OUTPUT"); - assert!(root.is_absolute() && !root.exists()); - assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); - std::fs::create_dir(&root).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); - assert!((3..=1048576).contains(&fd)); - let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 failed"); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); - let m = artifact.tokenizer(); - let tokenizer = - Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) - .expect("actual pinned tokenizer failed"); - let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); - let (req, ids, canonical) = request(&tokenizer); - save(&root, "PUBLIC-REQUEST.json", &canonical); - save( - &root, - "FRAME.json", - &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), - ); - let inherited = - InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); - let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, - &inherited, - &path("LELEKA_STRA169_MTP_PACK"), - &path("LELEKA_STRA169_MTP_STAGING"), - ) - .expect("actual KAR MTP binding failed"); - // Actual shard-bound tokenizer was constructed before artifact moved into - // successful binding. No asset reopening or second whole-model hash scan. - let remaining = ARTIFACT_CAP - .checked_sub(ARTIFACT_BYTES.load(Ordering::Acquire)) - .expect("public pair budget accounting invalid"); - let (_, long_bytes) = long_public_preflight::produce_on_bound_tokenizer( - &tokenizer, - MODEL_DIGEST, - &root.join("long-preflight"), - remaining, - reserve_artifacts, - ) - .expect("actual public long preflight refused before CUDA initialization"); - eprintln!("PUBLIC long preflight serialized_bytes={long_bytes}; whole package cap={ARTIFACT_CAP}"); - let driver = Driver::load().expect("actual CUDA driver failed"); - let driver_version = driver.version(); - let device = driver.device(0).unwrap(); - let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); - let output = OutputStage::load(&binding, context.as_ref()).unwrap(); - let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv(&binding, context.as_ref()).unwrap(); - let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap(); - let pair = catch_unwind(AssertUnwindSafe(|| { - let mut inputs = Inputs { - binding: &binding, - output: &output, - kar: &mut kar, - moe: &mut moe, - dense: &dense, - tokenizer: &tokenizer, - context: &context, - eos, - shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, - }; - // Warm exact PUBLIC traffic once per policy; fresh numeric state every - // arm. Actual misses/uploads are still recorded, never called fully hot. - let warm_a = inputs.arm(&req, &ids, EvaluationExecution::Native, "warm-native64"); - save(&root, "WARM-NATIVE64.json", &warm_a.json("warm", "native64-same-dual-cache-retained-mtp-kv")); - let warm_b = inputs.arm( - &req, - &ids, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - "warm-nativeDown-retainedGR256", - ); - save( - &root, - "WARM-NATIVE-DOWN256.json", - &warm_b.json("warm", "integer-gu-native-down-retained-gr256-retained-mtp-kv"), - ); - let a = inputs.arm(&req, &ids, EvaluationExecution::Native, "measured-native64"); - save(&root, "MEASURED-NATIVE64.json", &a.json("measured", "native64-same-dual-cache-retained-mtp-kv")); - let b = inputs.arm( - &req, - &ids, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - "measured-nativeDown-retainedGR256", - ); - save( - &root, - "MEASURED-NATIVE-DOWN256.json", - &b.json("measured", "integer-gu-native-down-retained-gr256-retained-mtp-kv"), - ); - (warm_a, warm_b, a, b) - })); - let disabled = crate::qwen_forward::oracle_capture::disable(&output); - let moe_closed = moe.close(); - let dense_closed = dense.close(); - drop(kar); - drop(output); - let synchronized = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = match Rc::try_unwrap(context) { - Ok(c) => Some(c.close()), - Err(c) => { - drop(c); - None - } - }; - drop(binding); - drop(inherited); - save( - &root, - "CLEANUP.json", - &json!({"oracle_disabled":disabled.is_ok(),"moe_closed":moe_closed.is_ok(),"dense_closed":dense_closed.is_ok(),"synchronized":synchronized.is_ok(),"allocated":allocated,"context_closed":matches!(&closed,Some(Ok(()))),"generation_succeeded":pair.is_ok()}), - ); - let (warm_a, warm_b, a, b) = match pair { - Ok(value) => value, - Err(primary) => resume_unwind(primary), - }; - assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); - assert_eq!(allocated, 0); - assert!(matches!(closed, Some(Ok(())))); - let records = json!([ - warm_a.json("warm", "native64-same-dual-cache-retained-mtp-kv"), - warm_b.json("warm", "integer-gu-native-down-retained-gr256-retained-mtp-kv"), - a.json("measured", "native64-same-dual-cache-retained-mtp-kv"), - b.json("measured", "integer-gu-native-down-retained-gr256-retained-mtp-kv") - ]); - save(&root, "OWNER-MEASUREMENTS.json", &records); - let parity = warm_a.measurement.output_token_ids == a.measurement.output_token_ids - && warm_b.measurement.output_token_ids == b.measurement.output_token_ids - && warm_a.text == a.text - && warm_b.text == b.text - && warm_a.reason == a.reason - && warm_b.reason == b.reason - && warm_a.usage == a.usage - && warm_b.usage == b.usage - && a.measurement.output_token_ids == b.measurement.output_token_ids - && a.text == b.text - && a.reason == b.reason - && a.usage == b.usage; - let mtp = a.offered() > 0 && b.offered() > 0; - save( - &root, - "PAIR.json", - &json!({"scope":"actual public framed owner prefill/decode; excludes HTTP/daemon/tool-task and model load","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"device_budget_bytes":DEVICE_BUDGET,"context_tokens":262144,"hardware":hardware,"actual_cuda_driver_version":driver_version,"framed_tokens":ids.len(),"output_cap":CAP,"measured_order":["Native64","IntegerGU-nativeDown-retainedGR256"],"cache_state":"same loaded model/shared actual native-integer dual weight owner, retained MTP KV ring and counters; real MMQ transient reservation before packets; prewarmed PUBLIC request once each; fresh numeric target+draft each arm; not assumed all expert hits","greedy_output_ids_equal":parity,"actual_mtp_offered":{"baseline":a.offered(),"candidate":b.offered()},"actual_mtp_exercised":mtp,"natural_early_eos_or_no_draft_scope":!mtp,"baseline_prefill_ns":u64::try_from(a.measurement.prefill.as_nanos()).unwrap(),"candidate_prefill_ns":u64::try_from(b.measurement.prefill.as_nanos()).unwrap(),"baseline_decode_ns":u64::try_from(a.measurement.decode.as_nanos()).unwrap(),"candidate_decode_ns":u64::try_from(b.measurement.decode.as_nanos()).unwrap(),"single_descriptive_pair":true,"owner_prefill_ratio_if_equal_work":if parity && !b.measurement.prefill.is_zero() {Some(a.measurement.prefill.as_secs_f64()/b.measurement.prefill.as_secs_f64())}else{None},"owner_decode_ratio_if_equal_work":if parity && !b.measurement.decode.is_zero() {Some(a.measurement.decode.as_secs_f64()/b.measurement.decode.as_secs_f64())}else{None},"same_actual_device_context":true,"retained_mtp_kv_factory":true,"mmq_transient_reservation":true,"GateC":false,"GateD":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":0,"cleanup_complete":true}), - ); - assert!(parity, "actual PUBLIC output token/text/finish/Usage parity failed; no equal-work speed claim"); - eprintln!( - "PUBLIC native64/nativeDown-retainedGR256 owner pair recorded framed={} output={} actual_mtp={} allocated=0 GateC=false GateD=false HTTP=false longcontext=false", - ids.len(), - a.measurement.output_token_ids.len(), - mtp - ); + pair_run::run(); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_arm.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_arm.rs new file mode 100644 index 00000000..f644c40c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_arm.rs @@ -0,0 +1,224 @@ +//! One actual owner generation of the one-load PUBLIC pair on a fresh target/draft state: bounded stream +//! consumer, failure artifact and the measurement record of a completed arm. +use super::*; + +pub(super) struct Arm { + pub(super) measurement: EvaluationMeasurement, + pub(super) text: String, + pub(super) usage: Usage, + pub(super) reason: FinishReason, +} +fn window_json(w: &WindowWitness) -> Value { + json!({"draft_steps":w.draft_steps,"verified_ids":w.verified_ids,"verified_count":w.verified_count, + "authoritative_eos":w.authoritative_eos,"accepted_non_eos_drafts":w.accepted_non_eos_drafts}) +} +fn usage_json(u: &Usage) -> Value { + json!({"input_tokens":u.input_tokens,"output_tokens":u.output_tokens,"reused_input_tokens":u.reused_input_tokens}) +} +pub(super) fn ns(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap() +} +impl Arm { + pub(super) fn json(&self, phase: &str, policy: &str) -> Value { + let m = &self.measurement; + let windows: Vec<_> = m.windows.iter().map(window_json).collect(); + json!({"phase":phase,"execution_policy":policy,"input_token_ids":m.input_token_ids, + "output_token_ids":m.output_token_ids,"retained_prefix_tokens":m.retained_prefix_tokens, + "prefill_ns":ns(m.prefill),"decode_ns":ns(m.decode),"windows":windows, + "cache_before":cache_json(m.cache_before),"cache_after":cache_json(m.cache_after), + "completed":m.completed,"stopped":m.stopped,"terminal_published":m.terminal_published, + "text":self.text,"usage":usage_json(&self.usage),"finish_reason":format!("{:?}",self.reason)}) + } + pub(super) fn offered(&self) -> usize { + self.measurement.windows.iter().map(|w| w.draft_steps).sum() + } +} +pub(super) struct Inputs<'a, 'ctx, 'driver> { + pub(super) binding: &'a ModelBinding, + pub(super) output: &'a OutputStage<'ctx, 'driver>, + pub(super) kar: &'a mut KarPleCache<'ctx>, + pub(super) moe: &'a mut MoeWeightCache<'ctx>, + pub(super) dense: &'a DenseWeightCache<'ctx>, + pub(super) tokenizer: &'a Tokenizer, + pub(super) context: &'a Rc>, + pub(super) eos: u32, + pub(super) shared: Shared, +} +type Drained = (String, Option, Option); +fn drain_stream(mut stream: GenerationStream) -> Drained { + let mut text = String::new(); + let mut usage = None; + let mut terminal = None; + while let Some(event) = stream.recv().expect("pair stream missing terminal") { + match event { + GenerationEvent::TextDelta { text: delta } => { + assert!(text.len() + delta.len() <= FRAME_LIMIT); + text.push_str(&delta); + } + GenerationEvent::Usage(value) => { + assert!(usage.replace(value).is_none()); + } + GenerationEvent::Terminal(value) => { + assert!(terminal.replace(value).is_none()); + } + GenerationEvent::ToolCallDelta { .. } => { + panic!("text-only public pair emitted unexpected typed tool") + } + } + } + (text, usage, terminal) +} +/// The channel, its consumer thread, the measurement recorder and the cancel flag of one arm. +struct Running { + sink: GenerationSink, + drain: thread::JoinHandle, + recorder: std::cell::RefCell, + cancel: AtomicBool, +} +impl Running { + fn open(ids: &[u32], max_output_tokens: u32) -> Self { + let cancel = AtomicBool::new(false); + let (sink, stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); + let drain = thread::spawn(move || drain_stream(stream)); + let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, max_output_tokens)); + Running { sink, drain, recorder, cancel } + } +} +/// What the failure artifact records besides the progress of the recorder. +struct FailureFacts<'a> { + terminal: &'a GenerationTerminal, + published: bool, + consumer_failed: bool, + drained: &'a Drained, + /// Allocated bytes, budget bytes and whether this was the Native control arm. + device: (usize, usize, bool), +} +fn failure_json(facts: &FailureFacts<'_>, progress: (&[u32], usize, bool), phase: &str) -> Value { + let (text, seen_usage, seen_terminal) = facts.drained; + json!({"terminal":format!("{:?}", facts.terminal),"terminal_published":facts.published, + "terminal_seen_matches":seen_terminal.as_ref()==Some(facts.terminal), + "consumer_failed":facts.consumer_failed,"usage_seen":seen_usage.as_ref().map(usage_json), + "public_text":text,"text_bytes":text.len(),"actual_observed_output_ids":progress.0, + "window_count":progress.1,"prefill_completed":progress.2,"phase":phase, + "allocated_at_failure":facts.device.0,"device_budget_bytes":facts.device.1, + "is_native_control":facts.device.2}) +} +fn terminal_of(failure: GenerationFailure) -> GenerationTerminal { + match failure { + GenerationFailure::Cancelled => GenerationTerminal::Cancelled, + GenerationFailure::Backend(error) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } + } +} +impl<'ctx, 'driver> Inputs<'_, 'ctx, 'driver> { + fn announce(&self, phase: &str, execution: EvaluationExecution) { + eprintln!( + "PUBLIC arm-start phase={phase} is_native_control={} allocated={} budget={}", + execution == EvaluationExecution::Native, + self.context.allocated_bytes(), + self.context.budget_bytes() + ); + } + /// Publishes the terminal, joins the consumer and keeps a bounded artifact; never returns. + fn fail(&self, run: Running, failure: GenerationFailure, phase: &str, execution: EvaluationExecution) -> ! { + let terminal = terminal_of(failure); + let diagnostic = format!("{terminal:?}"); + let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok(); + drop(run.sink); + let joined = run.drain.join(); + let consumer_failed = joined.is_err(); + let drained = joined.unwrap_or_default(); + let progress = run.recorder.borrow(); + let native = execution == EvaluationExecution::Native; + let device = (self.context.allocated_bytes(), self.context.budget_bytes(), native); + let facts = FailureFacts { terminal: &terminal, published, consumer_failed, drained: &drained, device }; + let artifact = failure_json(&facts, progress.diagnostic_progress(), phase); + save(&path("LELEKA_STRA169_PAIR_OUTPUT"), "GENERATION-FAILURE.json", &artifact); + eprintln!("PUBLIC generation terminal={diagnostic}"); + panic!("actual public pair generation failed; bounded failure artifact retained"); + } + fn generation<'a>( + &'a mut self, + run: &'a Running, + session: &'a mut QwenSession<'ctx>, + execution: EvaluationExecution, + ) -> Generation<'a, 'ctx, 'driver, SystemClock> { + Generation { + measurement: Some(&run.recorder), + execution, + binding: self.binding, + output: self.output, + kar_cache: Some(&mut *self.kar), + moe_cache: &mut *self.moe, + dense_cache: self.dense, + session, + tokenizer: self.tokenizer, + sink: &run.sink, + cancel: &run.cancel, + shared: &self.shared, + context_tokens: 262144, + eos: self.eos, + mtp: true, + clock: SystemClock, + } + } + pub(super) fn arm( + &mut self, + req: &GenerationRequest, + ids: &[u32], + execution: EvaluationExecution, + phase: &'static str, + ) -> Arm { + self.announce(phase, execution); + // Fresh genuine target state and fresh actual decoder. No position reset, + // invented prefix, checkpoint reuse or cached-token count substitution. + let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); + let before = cache(self.moe.counters(), self.dense.counters()); + let run = Running::open(ids, req.max_output_tokens); + let mut pending = None; + let generation = self.generation(&run, &mut session, execution); + let result = generate_mtp_resume(generation, ids, req.max_output_tokens, None, &mut pending); + let (reason, usage) = match result { + Ok(value) => value, + Err(failure) => self.fail(run, failure, phase, execution), + }; + self.finish(run, (reason, usage), (pending, session), before, ids) + } + fn measure( + &self, + recorder: std::cell::RefCell, + before: CacheCounts, + (reason, usage): (&FinishReason, &Usage), + published: bool, + ) -> EvaluationMeasurement { + let stopped = matches!(reason, FinishReason::Stop); + let usage_ids = Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)); + let after = cache(self.moe.counters(), self.dense.counters()); + recorder + .into_inner() + .finish(before, after, true, stopped, published, usage_ids) + .expect("actual owner measurement refused") + } + fn finish( + &self, + run: Running, + (reason, usage): (FinishReason, Usage), + (pending, session): (Option, QwenSession<'ctx>), + before: CacheCounts, + ids: &[u32], + ) -> Arm { + let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; + let published = emit_terminal(&run.sink, terminal.clone(), &SystemClock).is_ok(); + drop(run.sink); + let (text, seen_usage, seen_terminal) = run.drain.join().expect("actual pair consumer failed"); + assert!(published && seen_terminal.as_ref() == Some(&terminal)); + assert!(seen_usage.as_ref() == Some(&usage)); + drop(pending); + drop(session); + let measured = self.measure(run.recorder, before, (&reason, &usage), published); + assert_eq!(measured.input_token_ids, ids); + assert_eq!(measured.retained_prefix_tokens, 0); + Arm { measurement: measured, text, usage, reason } + } +} diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_run.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_run.rs new file mode 100644 index 00000000..64239028 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair_run.rs @@ -0,0 +1,291 @@ +//! The one-load PUBLIC pair: sealed inputs, one owner load, four arms (two warm, two measured) and the artifacts. +use super::*; +use std::os::unix::fs::PermissionsExt; + +const NATIVE_POLICY: &str = "native64-same-dual-cache-retained-mtp-kv"; +const DOWN_POLICY: &str = "integer-gu-native-down-retained-gr256-retained-mtp-kv"; +const CACHE_STATE: &str = "same loaded model/shared actual native-integer dual weight owner, retained MTP KV ring \ + and counters; real MMQ transient reservation before packets; prewarmed PUBLIC request once each; fresh numeric \ + target+draft each arm; not assumed all expert hits"; +/// The phases, files and label of the two arms of one round. +struct Round { + label: &'static str, + native_phase: &'static str, + down_phase: &'static str, + native_file: &'static str, + down_file: &'static str, +} +const WARM: Round = Round { + label: "warm", + native_phase: "warm-native64", + down_phase: "warm-nativeDown-retainedGR256", + native_file: "WARM-NATIVE64.json", + down_file: "WARM-NATIVE-DOWN256.json", +}; +const MEASURED: Round = Round { + label: "measured", + native_phase: "measured-native64", + down_phase: "measured-nativeDown-retainedGR256", + native_file: "MEASURED-NATIVE64.json", + down_file: "MEASURED-NATIVE-DOWN256.json", +}; +/// The sealed request: its framed prompt and token ids. +struct Case { + req: GenerationRequest, + ids: Vec, +} +/// The four arms: warm and measured, Native64 and the candidate. +struct Pair { + warm_a: Arm, + warm_b: Arm, + a: Arm, + b: Arm, +} + +fn prepare_root() -> PathBuf { + let root = path("LELEKA_STRA169_PAIR_OUTPUT"); + assert!(root.is_absolute() && !root.exists()); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); + std::fs::create_dir(&root).unwrap(); + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); + root +} +fn inherited_fd() -> u32 { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); + assert!((3..=1048576).contains(&fd)); + fd +} +fn open_artifact() -> Qwen4ExpArtifact { + let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); + Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed") +} +fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) { + let m = artifact.tokenizer(); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); + let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); + (tokenizer, eos) +} +fn frame_json(case: &Case) -> Value { + json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")), + "framed_prompt":case.req.prompt,"framed_prompt_sha256":sha(case.req.prompt.as_bytes()), + "input_token_ids":case.ids,"framed_count":case.ids.len(),"model_digest":MODEL_DIGEST, + "max_output_tokens":CAP,"temperature_milli":0}) +} +fn admit_request(root: &std::path::Path, tokenizer: &Tokenizer) -> Case { + let (req, ids, canonical) = request(tokenizer); + let case = Case { req, ids }; + save(root, "PUBLIC-REQUEST.json", &canonical); + save(root, "FRAME.json", &frame_json(&case)); + case +} +fn bind_model(fd: u32, artifact: Qwen4ExpArtifact) -> (InheritedKarArchive, ModelBinding) { + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); + let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &path("LELEKA_STRA169_MTP_PACK"), + &path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual KAR MTP binding failed"); + (inherited, binding) +} +fn long_preflight(root: &std::path::Path, tokenizer: &Tokenizer) { + // Actual shard-bound tokenizer was constructed before artifact moved into + // successful binding. No asset reopening or second whole-model hash scan. + let remaining = ARTIFACT_CAP + .checked_sub(ARTIFACT_BYTES.load(Ordering::Acquire)) + .expect("public pair budget accounting invalid"); + let (_, long_bytes) = long_public_preflight::produce_on_bound_tokenizer( + tokenizer, + MODEL_DIGEST, + &root.join("long-preflight"), + remaining, + reserve_artifacts, + ) + .expect("actual public long preflight refused before CUDA initialization"); + eprintln!("PUBLIC long preflight serialized_bytes={long_bytes}; whole package cap={ARTIFACT_CAP}"); +} +/// Warm exact PUBLIC traffic once per policy; fresh numeric state every +/// arm. Actual misses/uploads are still recorded, never called fully hot. +fn round(inputs: &mut Inputs<'_, '_, '_>, root: &std::path::Path, case: &Case, round: &Round) -> (Arm, Arm) { + let native = inputs.arm(&case.req, &case.ids, EvaluationExecution::Native, round.native_phase); + save(root, round.native_file, &native.json(round.label, NATIVE_POLICY)); + let down = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr; + let candidate = inputs.arm(&case.req, &case.ids, down, round.down_phase); + save(root, round.down_file, &candidate.json(round.label, DOWN_POLICY)); + (native, candidate) +} +fn same_output(x: &Arm, y: &Arm) -> bool { + x.measurement.output_token_ids == y.measurement.output_token_ids + && x.text == y.text + && x.reason == y.reason + && x.usage == y.usage +} +fn ratio(parity: bool, numerator: Duration, denominator: Duration) -> Option { + if parity && !denominator.is_zero() { Some(numerator.as_secs_f64() / denominator.as_secs_f64()) } else { None } +} +fn pair_head_json(hardware: &Value, driver_version: &Value, framed_tokens: usize) -> Value { + json!({"scope":"actual public framed owner prefill/decode; excludes HTTP/daemon/tool-task and model load", + "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"device_budget_bytes":DEVICE_BUDGET, + "context_tokens":262144,"hardware":hardware,"actual_cuda_driver_version":driver_version, + "framed_tokens":framed_tokens,"output_cap":CAP, + "measured_order":["Native64","IntegerGU-nativeDown-retainedGR256"],"cache_state":CACHE_STATE}) +} +fn pair_timing_json(p: &Pair, parity: bool, mtp: bool) -> Value { + let (a, b) = (&p.a.measurement, &p.b.measurement); + json!({"greedy_output_ids_equal":parity, + "actual_mtp_offered":{"baseline":p.a.offered(),"candidate":p.b.offered()}, + "actual_mtp_exercised":mtp,"natural_early_eos_or_no_draft_scope":!mtp, + "baseline_prefill_ns":ns(a.prefill),"candidate_prefill_ns":ns(b.prefill), + "baseline_decode_ns":ns(a.decode),"candidate_decode_ns":ns(b.decode),"single_descriptive_pair":true, + "owner_prefill_ratio_if_equal_work":ratio(parity, a.prefill, b.prefill), + "owner_decode_ratio_if_equal_work":ratio(parity, a.decode, b.decode)}) +} +fn pair_flags_json() -> Value { + json!({"same_actual_device_context":true,"retained_mtp_kv_factory":true,"mmq_transient_reservation":true, + "GateC":false,"GateD":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":0, + "cleanup_complete":true}) +} +/// The loaded caches and output head of the one admitted owner. +struct Owner<'ctx, 'driver> { + output: OutputStage<'ctx, 'driver>, + kar: KarPleCache<'ctx>, + moe: MoeWeightCache<'ctx>, + dense: DenseWeightCache<'ctx>, +} +/// How the owner and its Context closed. +struct Closed { + oracle_disabled: bool, + moe_closed: bool, + dense_closed: bool, + synchronized: bool, + allocated: usize, + context_closed: bool, +} +impl<'ctx, 'driver> Owner<'ctx, 'driver> { + fn load(binding: &ModelBinding, context: &'ctx leleka_cuda_driver::Context<'driver>) -> Self { + let output = OutputStage::load(binding, context).unwrap(); + let kar = KarPleCache::new(context, binding.kar_ple_binding().unwrap()).unwrap(); + let moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv(binding, context).unwrap(); + let dense = DenseWeightCache::new(binding, context).unwrap(); + Owner { output, kar, moe, dense } + } + fn measure(&mut self, run: &RunCtx<'_, 'ctx>, root: &std::path::Path) -> Pair { + let mut inputs = Inputs { + binding: run.binding, + output: &self.output, + kar: &mut self.kar, + moe: &mut self.moe, + dense: &self.dense, + tokenizer: run.tokenizer, + context: run.context, + eos: run.eos, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, + }; + let (warm_a, warm_b) = round(&mut inputs, root, run.case, &WARM); + let (a, b) = round(&mut inputs, root, run.case, &MEASURED); + Pair { warm_a, warm_b, a, b } + } + fn close(self) -> (bool, bool, bool) { + let oracle_disabled = crate::qwen_forward::oracle_capture::disable(&self.output).is_ok(); + let moe_closed = self.moe.close().is_ok(); + let dense_closed = self.dense.close().is_ok(); + drop(self.kar); + drop(self.output); + (oracle_disabled, moe_closed, dense_closed) + } +} +/// Borrowed state the arms need besides the loaded owner. +struct RunCtx<'a, 'ctx> { + binding: &'a ModelBinding, + tokenizer: &'a Tokenizer, + context: &'a Rc>, + eos: u32, + case: &'a Case, +} +fn close_context(context: Rc>, owner: (bool, bool, bool)) -> Closed { + let synchronized = context.synchronize().is_ok(); + let allocated = context.allocated_bytes(); + let closed = match Rc::try_unwrap(context) { + Ok(c) => Some(c.close()), + Err(c) => { + drop(c); + None + } + }; + let context_closed = matches!(&closed, Some(Ok(()))); + Closed { + oracle_disabled: owner.0, + moe_closed: owner.1, + dense_closed: owner.2, + synchronized, + allocated, + context_closed, + } +} +fn save_cleanup(root: &std::path::Path, closed: &Closed, generation_succeeded: bool) { + save( + root, + "CLEANUP.json", + &json!({"oracle_disabled":closed.oracle_disabled,"moe_closed":closed.moe_closed, + "dense_closed":closed.dense_closed,"synchronized":closed.synchronized,"allocated":closed.allocated, + "context_closed":closed.context_closed,"generation_succeeded":generation_succeeded}), + ); +} +fn assert_closed(c: &Closed) { + assert!(c.oracle_disabled && c.moe_closed && c.dense_closed && c.synchronized); + assert_eq!(c.allocated, 0); + assert!(c.context_closed); +} +fn conclude(root: &std::path::Path, p: &Pair, hardware: &Value, driver_version: &Value, framed: usize) { + let records = json!([ + p.warm_a.json("warm", NATIVE_POLICY), + p.warm_b.json("warm", DOWN_POLICY), + p.a.json("measured", NATIVE_POLICY), + p.b.json("measured", DOWN_POLICY) + ]); + save(root, "OWNER-MEASUREMENTS.json", &records); + let parity = same_output(&p.warm_a, &p.a) && same_output(&p.warm_b, &p.b) && same_output(&p.a, &p.b); + let mtp = p.a.offered() > 0 && p.b.offered() > 0; + let pair = merged(pair_head_json(hardware, driver_version, framed), pair_timing_json(p, parity, mtp)); + save(root, "PAIR.json", &merged(pair, pair_flags_json())); + assert!(parity, "actual PUBLIC output token/text/finish/Usage parity failed; no equal-work speed claim"); + eprintln!( + "PUBLIC native64/nativeDown-retainedGR256 owner pair recorded framed={framed} output={} actual_mtp={mtp} \ + allocated=0 GateC=false GateD=false HTTP=false longcontext=false", + p.a.measurement.output_token_ids.len() + ); +} +pub(super) fn run() { + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_NATIVE_DOWN_PAIR").as_deref(), Ok("yes")); + let hardware = metadata(); + let root = prepare_root(); + let fd = inherited_fd(); + let artifact = open_artifact(); + let (tokenizer, eos) = pinned_tokenizer(&artifact); + let case = admit_request(&root, &tokenizer); + let (inherited, binding) = bind_model(fd, artifact); + long_preflight(&root, &tokenizer); + let driver = Driver::load().expect("actual CUDA driver failed"); + let driver_version = json!(driver.version()); + let device = driver.device(0).unwrap(); + let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); + let mut owner = Owner::load(&binding, context.as_ref()); + let run = RunCtx { binding: &binding, tokenizer: &tokenizer, context: &context, eos, case: &case }; + let pair = catch_unwind(AssertUnwindSafe(|| owner.measure(&run, &root))); + let owner_closed = owner.close(); + let closed = close_context(context, owner_closed); + drop(binding); + drop(inherited); + save_cleanup(&root, &closed, pair.is_ok()); + let pair = match pair { + Ok(value) => value, + Err(primary) => resume_unwind(primary), + }; + assert_closed(&closed); + conclude(&root, &pair, &hardware, &driver_version, case.ids.len()); +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/main.rs b/crates/native-cpu-expert/examples/kernel_ab/main.rs index 3fafb462..0242a9e3 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/main.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/main.rs @@ -97,970 +97,7 @@ fn main() -> ExitCode { // ------------------------------------------------------------------------------------------------ tests #[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - static COUNTER: AtomicUsize = AtomicUsize::new(0); - - struct TempDir(PathBuf); - impl TempDir { - fn new() -> Self { - let p = std::env::temp_dir().join(format!( - "kab1-test-{}-{}", - std::process::id(), - COUNTER.fetch_add(1, Ordering::SeqCst) - )); - fs::create_dir_all(&p).unwrap(); - Self(p) - } - } - impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } - } - - fn block_filled(len: usize, block: usize, seed: u8) -> Vec { - let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); - for at in (0..len).step_by(block) { - v[at] = 0x00; - v[at + 1] = 0x3c; // FP16 1.0 - } - v - } - - fn in_file(gu: i32, down: i32, rows: usize) -> Vec { - let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); - let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); - let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); - let mut b = Vec::new(); - for w in [ - IN_MAGIC, - 1, - gu as u32, - down as u32, - rows as u32, - H as u32, - FF as u32, - gsize as u32, - gsize as u32, - dsize as u32, - ] { - b.extend_from_slice(&w.to_le_bytes()); - } - b.resize(IN_HEADER, 0); - b.extend(block_filled(gsize, gb, 1)); - b.extend(block_filled(gsize, gb, 2)); - b.extend(block_filled(dsize, db, 3)); - for i in 0..rows * H { - b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); - } - b - } - - fn out_file(rows: usize, tree: u32) -> Vec { - let mut b = Vec::new(); - for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { - b.extend_from_slice(&w.to_le_bytes()); - } - for i in 0..rows * H { - b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); - } - b - } - - struct Spec { - gu: i32, - down: i32, - rows: usize, - tolerance: Option<&'static str>, - } - - /// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. - fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { - let mut cases = Vec::new(); - let mut files = Vec::new(); - for s in specs { - let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); - let mut inb = in_file(s.gu, s.down, s.rows); - mutate(&mut inb); - fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); - let mut entry = format!( - "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", - s.gu, - s.down, - s.rows, - if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, - s.tolerance.unwrap_or("null"), - sha_hex(&inb), - inb.len() - ); - files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); - for (k, tree) in TREES.iter().enumerate() { - let ob = out_file(s.rows, k as u32); - fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); - entry += &format!( - ", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \"out_cpp_{tree}_bytes\": {}", - sha_hex(&ob), - ob.len() - ); - files.push(format!( - "\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", - sha_hex(&ob), - ob.len() - )); - } - cases.push(entry + "}"); - } - let manifest = format!( - "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \"provenance\": {{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {{\"strata_cxx_flags\": \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}}}, \"cases\": [{}], \"files\": {{{}}}}}", - cases.join(", "), - files.join(", ") - ); - fs::write(dir.join("manifest.json"), manifest).unwrap(); - } - - fn two_cases() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] - } - - fn one_case() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] - } - - fn id(file: &str) -> String { - format!("case-42-42-r1.{file}") - } - - #[test] - fn a_good_directory_verifies() { - let t = TempDir::new(); - build(&t.0, &two_cases(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases.len(), 2); - assert_eq!(v.file_count, 2 * 3 + 1); - assert_eq!(v.manifest_sha256.len(), 64); - assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); - } - - #[test] - fn a_flipped_byte_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("in")); - let mut b = fs::read(&p).unwrap(); - b[IN_HEADER + 7] ^= 0x40; - fs::write(&p, b).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("sha256"), "{e}"); - } - - #[test] - fn a_truncated_file_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("cpp-avx2.out")); - let b = fs::read(&p).unwrap(); - fs::write(&p, &b[..b.len() - 4]).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); - assert!(e.reason.contains("length"), "{e}"); - } - - #[test] - fn a_wrong_magic_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[0] ^= 0xff); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("magic"), "{e}"); - } - - #[test] - fn a_wrong_version_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[4] = 2); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("version"), "{e}"); - } - - #[test] - fn a_byte_count_that_disagrees_with_the_format_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let wrong = (le32(b, 28) + 18).to_le_bytes(); - b[28..32].copy_from_slice(&wrong); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("format-derived"), "{e}"); - } - - #[test] - fn a_non_finite_fp16_header_is_refused() { - let t = TempDir::new(); - // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it - build(&t.0, &one_case(), |b| { - let at = IN_HEADER + 18 * 3; - b[at] = 0x00; - b[at + 1] = 0x7c; // FP16 +inf - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("non-finite FP16"), "{e}"); - } - - #[test] - fn a_non_finite_activation_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let at = b.len() - 4; - b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert!(e.reason.contains("non-finite activation"), "{e}"); - } - - #[test] - fn a_missing_manifest_is_incomplete_and_named() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::remove_file(t.0.join("manifest.json")).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.incomplete); - assert!(e.to_string().contains("manifest.json")); - } - - #[test] - fn an_extra_or_missing_file_refuses_the_directory() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::write(t.0.join("stray.txt"), b"x").unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); - fs::remove_file(t.0.join("stray.txt")).unwrap(); - fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); - } - - #[test] - fn an_absurd_length_is_refused_without_taking_a_buffer() { - // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists - let mut h = [0u8; IN_HEADER]; - h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); - h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); - BUFFERS.with(|c| c.set(0)); - assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // and through the file reader: manifest and file agree on a file whose header lies about its size - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); - BUFFERS.with(|c| c.set(0)); - let (m, _) = (fs::read(t.0.join("manifest.json")).unwrap(), 0); - let (_, cases, _) = parse_manifest(&parse_json(&m).unwrap()).unwrap(); - let e = read_case_in(&t.0, &cases[0]).err().unwrap(); - assert!(e.reason.contains("format-derived"), "{e}"); - assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); - // a manifest that declares an absurd length for a file is refused before a buffer too - let mut lying = cases[0].clone(); - lying.in_bytes = u64::MAX; - assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // the good path takes exactly one buffer per file - let g = TempDir::new(); - build(&g.0, &one_case(), |_| {}); - BUFFERS.with(|c| c.set(0)); - let (_, cases, _) = - parse_manifest(&parse_json(&fs::read(g.0.join("manifest.json")).unwrap()).unwrap()).unwrap(); - read_case_in(&g.0, &cases[0]).unwrap(); - assert_eq!(BUFFERS.with(Cell::get), 1); - } - - #[test] - fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { - let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; - let t = TempDir::new(); - build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); - for (bad, why) in [ - (ok.replace("0.003", "0"), "positive"), - (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), - (ok.replace("order-only difference", " "), "basis"), - (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), - ] { - let leaked: &'static str = Box::leak(bad.into_boxed_str()); - let d = TempDir::new(); - build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); - let e = verify_dir(&d.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.reason.contains(why), "{why}: {e}"); - } - } - - #[test] - fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { - let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); - assert_eq!( - j.get("a"), - Some(&Json::Arr(vec![ - Json::Num("1".into()), - Json::Num("-2.5e3".into()), - Json::Bool(true), - Json::Null, - Json::Str("x\n\u{e9}\u{1f600}".into()) - ])) - ); - assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); - for bad in [ - "{\"a\": 1, \"a\": 2}", - "{\"a\": 1,}", - "[1 2]", - "{\"a\": \"\\ud800\"}", - "{} x", - "", - "{\"a\": 01x}", - "\"\u{1}\"", - ] { - assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); - } - assert!(parse_json("[".repeat(40).as_bytes()).is_err()); - } - - #[test] - fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { - let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; - assert!(compare_bits(&a, &a, None).equal()); - let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; - let o = compare_bits(&neg0, &a, None); - assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); - let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; - assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); - let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; - assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); - let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; - assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); - assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); - } - - #[test] - fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); - let mut pool = DirectCpuPool::new(1).unwrap(); - let first = compute_case(&mut pool, &case).unwrap(); - let second = compute_case(&mut pool, &case).unwrap(); - assert_eq!(first.len(), H); - assert!( - first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), - "the same case twice must be bit-identical" - ); - let path = t.0.join("ours.rust-avx2.out"); - write_out(&path, 1, "avx2", &first).unwrap(); - let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); - assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); - let outcome = compare_bits(&back, &back, None); - let json = record_json(&RecordInput { - record_id: "kab1-synthetic-r".into(), - created_utc: "2026-10-28T20:00:00Z".into(), - run_started_utc: "2026-10-28T19:59:00Z".into(), - machine_role: "m\"1".into(), - cpu_model: "cpu".into(), - os: "os".into(), - ours_compiler: "rustc".into(), - ours_version: "rustc 1.99.0".into(), - ours_triple: "x86_64-unknown-linux-gnu".into(), - ours_flags: "f".into(), - tree: "avx2", - verified: &v, - case: &v.cases[0], - pin_cpu: 0, - sibling_idle: true, - outcome: &outcome, - }); - let rec = parse_json(json.as_bytes()).unwrap(); - for key in [ - "schema_version", - "level", - "record_id", - "created_utc", - "run_started_utc", - "machine", - "kernel", - "toolchain", - "case_id", - "input_sha256", - "kab1_manifest_sha256", - "tree", - "regime", - "pin", - "strata_upstream_commit", - "clock_calibration", - "rows", - "aa_noise_floor", - "equality", - ] { - assert!(rec.get(key).is_some(), "{key}"); - } - assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); - assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); - assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); - } - - // ---------------------------------------------------------------------------------------------------- alternation (STRA-318) - - #[test] - fn the_schedule_is_reproducible_from_the_seed() { - let procs = procs_for(&TREES); - let a = make_schedule(7, 1, 30, &procs); - assert_eq!(a, make_schedule(7, 1, 30, &procs)); - assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule"); - assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule"); - assert_eq!(a.len(), 30); - // the text round-trips through the file format and names the seed - let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a); - assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9")); - let back = parse_schedule(&text).unwrap(); - assert_eq!(back.iter().map(|r| r.1.clone()).collect::>(), a); - assert_eq!(back[0].0, 1); - assert_eq!(back[29].0, 30); - } - - #[test] - fn the_rotation_gives_every_process_every_position_within_a_block() { - let procs = procs_for(&TREES); - assert_eq!(procs.len(), 8); - let s = make_schedule(3, 1, 16, &procs); - for block in s.chunks(8) { - for round in block { - let mut names: Vec<_> = round.iter().map(Proc::name).collect(); - names.sort(); - assert_eq!(names.len(), 8); - names.dedup(); - assert_eq!(names.len(), 8, "every process exactly once per round"); - } - for pos in 0..8 { - let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect(); - assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds"); - } - } - // a host without AVX-512 has only the avx2 cells - assert_eq!(procs_for(&["avx2"]).len(), 4); - } - - #[test] - fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() { - let t = TempDir::new(); - let f = t.0.join("schedule.tsv"); - create_new_file(&f, b"x").unwrap(); - assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten")); - assert_eq!(fs::read(&f).unwrap(), b"x"); - let procs = procs_for(&TREES); - let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs)); - assert!(parse_schedule(&good).is_ok()); - assert!(parse_schedule("nope").is_err()); - assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process")); - assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow")); - // a round that names one process twice (and so lacks another) is refused - let dup = good - .lines() - .map(|l| { - if l.starts_with("2\t") { - l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) - } else { - l.to_owned() - } - }) - .collect::>() - .join("\n"); - assert!(parse_schedule(&dup).is_err()); - } - - /// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run. - #[test] - fn env_probe_child() { - if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) { - return; - } - for (k, v) in std::env::vars() { - if is_managed_name(&k) { - println!("PROBE {k}={v}"); - } - } - } - - /// The child side of the failure test. - #[test] - fn failing_child() { - if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) { - eprintln!("simulated kernel failure"); - std::process::exit(3); - } - } - - fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command { - let mut parent: Vec<(OsString, OsString)> = - std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect(); - parent.push(("KAB_TEST_CHILD".into(), mode.into())); - parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into()))); - let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell); - c.args(["--exact", test, "--nocapture", "--test-threads=1"]); - c - } - - #[test] - fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() { - let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' }); - assert_eq!( - cell, - vec![ - ("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), - ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), - ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()) - ] - ); - assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); - let out = run_cell( - &mut child( - "tests::env_probe_child", - "probe", - &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], - &cell, - ), - "rust-avx2-a", - ) - .unwrap(); - let text = String::from_utf8_lossy(&out.stdout); - // libtest prints "test ... " before the child's own output on the same line - let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); - probes.sort_unstable(); - assert_eq!( - probes, - vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], - "only the cell's variables survive:\n{text}" - ); - // the cpp avx512 cell sets nothing at all - let out = - run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a") - .unwrap(); - assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); - } - - #[test] - fn a_child_failure_is_reported_with_the_cell_named() { - let e = run_cell(&mut child("tests::failing_child", "fail", &[], &[]), "cpp-avx2-b").unwrap_err(); - assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}"); - assert!(e.contains("simulated kernel failure"), "{e}"); - let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err(); - assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}"); - } - - #[test] - fn the_time_command_line_is_the_one_of_kab_time() { - let v = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::>(); - let t = parse_time_args(&v(&[ - "--run-dir", - "D", - "--case", - "18-20-r1", - "--slices", - "50", - "--pin", - "9", - "--out", - "t.json", - ])) - .unwrap(); - assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None)); - let t = parse_time_args(&v(&[ - "--run-dir", - "D", - "--case", - "c", - "--slices", - "2", - "--pin", - "0", - "--out", - "o", - "--slice-ms", - "5", - "--regime", - "streamed", - "--llc-bytes", - "1000", - ])) - .unwrap(); - assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); - for bad in [ - v(&["--run-dir", "D", "--case", "c", "--slices", "0", "--pin", "0", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--regime", "both2"]), - v(&["--run-dir", "D", "--case", "../c", "--slices", "1", "--pin", "0", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--bogus", "1"]), - v(&["--run-dir", "D", "--run-dir", "E", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o"]), - ] { - assert!(parse_time_args(&bad).is_err(), "{bad:?}"); - } - let a = parse_alt_args(&v(&[ - "--run-dir", - "D", - "--case", - "c", - "--rounds", - "30", - "--batch", - "1", - "--pin", - "9", - "--schedule", - "s.tsv", - ])) - .unwrap(); - assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20)); - assert!( - parse_alt_args(&v(&[ - "--run-dir", - "D", - "--case", - "c", - "--rounds", - "30", - "--batch", - "0", - "--pin", - "9", - "--schedule", - "s" - ])) - .is_err() - ); - } - - #[test] - fn medians_percentiles_and_parsers_agree_with_the_reference_rules() { - assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference"); - assert_eq!(median_of(&[]), 0.0); - let v: Vec = (1..=21).map(f64::from).collect(); - assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0)); - assert_eq!(parse_cpu_list("2,18"), vec![2, 18]); - assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]); - assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); - assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); - assert_eq!(busy_fraction(None, Some((1, 1))), None); - // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain) - let ghz = core_ghz(); - assert!((0.3..12.0).contains(&ghz), "{ghz}"); - } - - #[test] - fn an_output_inside_a_git_checkout_is_detected() { - let t = TempDir::new(); - let inner = t.0.join("a/b"); - fs::create_dir_all(&inner).unwrap(); - assert!(!inside_git_checkout(&inner)); - fs::create_dir_all(t.0.join(".git")).unwrap(); - assert!(inside_git_checkout(&inner)); - assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv"))); - } - - fn json_regime(label: &str, k: usize, self_key: &str) -> String { - let slice = |g1: f64| { - format!( - "{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}" - ) - }; - format!( - "{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}", - slice(5.0), - slice(5.1), - slice(4.0) - ) - } - - /// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective environment. - fn proc_fixture(p: &Proc, env: &str) -> String { - let (self_key, detail) = if p.imp == Impl::Cpp { - ("selfcheck_bitwise_equal_compose_expert", "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \"iq256_gather_setting\": -1, \"strata_env\": {}}".to_owned()) - } else { - ( - "selfcheck_bitwise_equal_first_call", - format!( - "{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", - p.tree - ), - ) - }; - format!( - "{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}", - p.imp.name(), - p.tree, - "cd".repeat(32), - json_regime("RESIDENT", 1, self_key), - json_regime("STREAMED", 3, self_key) - ) - } - - #[test] - fn a_process_json_is_checked_against_the_cell_that_was_started() { - let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 }; - for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] { - let env = json_env(&cell_env(&p).into_iter().collect()); - let ok = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &expect).unwrap(); - assert_eq!(ok.regimes.len(), 2); - let r = &ok.regimes["STREAMED"]; - assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3)); - assert!( - (r.max_drift - 0.2).abs() < 1e-9, - "the dropped slice's 20 percent drift is the maximum: {}", - r.max_drift - ); - assert_eq!(ok.sibling_idle, Some(true)); - // the environment the process saw must be exactly the cell's - let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())])); - let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err(); - assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}"); - // wrong pin, wrong manifest, wrong input, wrong writer: each names the cell - for (bad_expect, what) in [ - (Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"), - (Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"), - (Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"), - ] { - let e = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &bad_expect).unwrap_err(); - assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}"); - } - let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..p }; - assert!( - parse_proc_json(&other, proc_fixture(&p, &env).as_bytes(), &expect).unwrap_err().contains("writer") - ); - } - } - - fn fake_proc(p: Proc, base: f64) -> ProcOut { - let regime = |k: usize| RegimeStat { - copies_k: k, - expert_bytes: 1_000_000, - llc_bytes: 1_000, - requested: 10, - dropped: 1, - median_ns: base, - median_cycles: base * 5.0, - ns: vec![base * 0.9, base, base * 1.1], - cycles: vec![base * 4.5, base * 5.0, base * 5.5], - max_drift: 0.01, - selfcheck: true, - }; - ProcOut { - proc: p, - regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]), - ghz_start: 5.0, - ghz_end: 5.1, - sibling_idle: Some(true), - final_unchanged: true, - output_sha: Some("ab".repeat(32)), - tree_text: format!("tree text of {}", p.name()), - cpu_model: Some("Test CPU".to_owned()), - } - } - - #[test] - fn round_records_have_the_schema_shape_and_keep_not_equal() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - let outcome = |bad: usize| Outcome { - compared: H, - mismatches: bad, - differing_bits: bad, - max_abs_error: 0.0, - first_mismatch: None, - }; - let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); - let ctx = BatchCtx { - verified: &v, - case: &v.cases[0], - pin: 9, - machine_role: "m".into(), - os: "os".into(), - cpu_model: "cpu".into(), - started_utc: "2026-10-28T20:00:00Z".into(), - rust_tool: Tool { - compiler: "rustc".into(), - version: "rustc 1.99.0".into(), - triple: "x86_64-unknown-linux-gnu".into(), - flags: "f".into(), - }, - batch: 2, - equality: &equality, - }; - let mut done: Vec = - procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); - done.reverse(); // the order of execution does not matter to the records - done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = - Some(false); - let files = round_records(&ctx, 31, &done).unwrap(); - assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); - let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); - assert_eq!(names.len(), 12); - assert!( - names.contains("r00031.ab.avx2.streamed.json") - && names.contains("r00031.aa-cpp.avx512.resident.json") - && names.contains("r00031.aa-rust.avx2.resident.json") - ); - for (name, json) in &files { - let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); - for key in [ - "schema_version", - "level", - "record_id", - "created_utc", - "run_started_utc", - "machine", - "kernel", - "toolchain", - "case_id", - "input_sha256", - "kab1_manifest_sha256", - "tree", - "regime", - "pin", - "strata_upstream_commit", - "clock_calibration", - "rows", - "aa_noise_floor", - "equality", - ] { - assert!(rec.get(key).is_some(), "{name}: {key}"); - } - assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL"); - assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); - assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256); - let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") }; - let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect(); - assert_eq!(units, ["ns", "cycles"]); - assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type"); - let regime = rec.str("regime").unwrap(); - assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}"); - assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER")); - let eq = rec.req("equality").unwrap(); - let tree = rec.req("tree").unwrap().str("ours").unwrap(); - let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" }; - assert_eq!(eq.str("verdict").unwrap(), want, "{name}"); - if want == "NOT_EQUAL" { - assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden"); - } - } - // the A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation on both - let ab = - parse_json(files.iter().find(|f| f.0 == "r00031.ab.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); - assert!( - ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a") - ); - assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc"); - let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()) - .unwrap(); - assert!( - aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b") - ); - assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); - // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b - for (name, json) in &files { - let rec = parse_json(json.as_bytes()).unwrap(); - let busy = name.contains(".aa-cpp.avx2."); - assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); - } - // a streamed set that differs between the two sides of a record is refused - let mut skewed = done.clone(); - skewed - .iter_mut() - .find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }) - .unwrap() - .regimes - .get_mut("STREAMED") - .unwrap() - .copies_k = 4; - assert!(round_records(&ctx, 31, &skewed).unwrap_err().contains("streamed set differs")); - // a missing process is named - assert!(round_records(&ctx, 31, &done[1..]).unwrap_err().contains("did not run")); - } - - #[test] - fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let out = TempDir::new(); - let file = out.0.join("t.json"); - let args: Vec = [ - "--run-dir", - t.0.to_str().unwrap(), - "--case", - "42-42-r1", - "--slices", - "40", - "--pin", - "0", - "--out", - file.to_str().unwrap(), - "--slice-ms", - "1", - "--llc-bytes", - "8000000", - ] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - // exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the loaded host's call) - let code = format!("{:?}", cmd_time(&args).unwrap()); - assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}"); - let text = fs::read_to_string(&file).unwrap(); - let j = parse_json(text.as_bytes()).unwrap(); - assert_eq!(j.str("writer").unwrap(), "rust"); - assert_eq!(j.str("format").unwrap(), "KAB1-time"); - assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap()); - assert_eq!(j.str("output_sha256").unwrap().len(), 64); - let tree = j.str("tree").unwrap().to_owned(); - let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' }; - if !code.contains("(0)") { - return; - } - let manifest = fs::read(t.0.join("manifest.json")).unwrap(); - let (_, _, cases, _) = read_manifest(&t.0).unwrap(); - let sha = sha_hex(&manifest); - let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 }; - // the test process runs unscrubbed (its effective environment is empty), so the runner's environment check refuses it ... - assert!(parse_proc_json(&p, text.as_bytes(), &expect).unwrap_err().contains("effective environment")); - // ... and accepts it once the recorded environment is the cell's - let want_env = json_env(&cell_env(&p).into_iter().collect()); - let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1); - let ok = parse_proc_json(&p, as_cell.as_bytes(), &expect).unwrap(); - for r in ["RESIDENT", "STREAMED"] { - let s = &ok.regimes[r]; - assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}"); - assert_eq!(s.requested, 40); - } - assert_eq!(ok.regimes["RESIDENT"].copies_k, 1); - assert!(ok.regimes["STREAMED"].copies_k >= 2); - assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family")); - // a lie about the pin is refused - assert!( - parse_proc_json(&p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }) - .unwrap_err() - .contains("pinned to CPU") - ); - } - - #[test] - fn utc_formatting_is_exact() { - assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); - assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); - assert!(is_utc(&now_utc())); - } -} +mod tests; mod gate_up_row_fn; #[allow(unused_imports)] diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests.rs b/crates/native-cpu-expert/examples/kernel_ab/tests.rs new file mode 100644 index 00000000..c72a8784 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests.rs @@ -0,0 +1,189 @@ +//! Tests of the KAB1 reader, the comparison, the record writer, the alternation runner and the timing mode; the +//! synthetic KAB1 directories they read are built here. +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +mod alternation; +mod reader; +mod timing; + +static COUNTER: AtomicUsize = AtomicUsize::new(0); + +struct TempDir(PathBuf); +impl TempDir { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "kab1-test-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + fs::create_dir_all(&p).unwrap(); + Self(p) + } +} +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// The keys every COMPONENT_KERNEL record carries. +const RECORD_KEYS: [&str; 19] = [ + "schema_version", + "level", + "record_id", + "created_utc", + "run_started_utc", + "machine", + "kernel", + "toolchain", + "case_id", + "input_sha256", + "kab1_manifest_sha256", + "tree", + "regime", + "pin", + "strata_upstream_commit", + "clock_calibration", + "rows", + "aa_noise_floor", + "equality", +]; +/// The provenance block of the synthetic manifest. +const PROVENANCE: &str = "{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \ + \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \ + \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {\"strata_cxx_flags\": \ + \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}"; + +fn assert_record_keys(rec: &Json, prefix: &str) { + for key in RECORD_KEYS { + assert!(rec.get(key).is_some(), "{prefix}{key}"); + } +} + +fn block_filled(len: usize, block: usize, seed: u8) -> Vec { + let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); + for at in (0..len).step_by(block) { + v[at] = 0x00; + v[at + 1] = 0x3c; // FP16 1.0 + } + v +} + +fn in_file(gu: i32, down: i32, rows: usize) -> Vec { + let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); + let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); + let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); + let mut b = Vec::new(); + for w in [ + IN_MAGIC, + 1, + gu as u32, + down as u32, + rows as u32, + H as u32, + FF as u32, + gsize as u32, + gsize as u32, + dsize as u32, + ] { + b.extend_from_slice(&w.to_le_bytes()); + } + b.resize(IN_HEADER, 0); + b.extend(block_filled(gsize, gb, 1)); + b.extend(block_filled(gsize, gb, 2)); + b.extend(block_filled(dsize, db, 3)); + for i in 0..rows * H { + b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); + } + b +} + +fn out_file(rows: usize, tree: u32) -> Vec { + let mut b = Vec::new(); + for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { + b.extend_from_slice(&w.to_le_bytes()); + } + for i in 0..rows * H { + b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); + } + b +} + +struct Spec { + gu: i32, + down: i32, + rows: usize, + tolerance: Option<&'static str>, +} + +/// The manifest entry of a case up to its input file (the output files follow). +fn case_entry(s: &Spec, id: &str, inb: &[u8]) -> String { + format!( + "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \ + \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", + s.gu, + s.down, + s.rows, + if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, + s.tolerance.unwrap_or("null"), + sha_hex(inb), + inb.len() + ) +} + +/// Writes the C++ output of every tree of a case and adds them to its manifest entry and to the file list. +fn write_outs(dir: &Path, id: &str, rows: usize, entry: &mut String, files: &mut Vec) { + for (k, tree) in TREES.iter().enumerate() { + let ob = out_file(rows, k as u32); + fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); + *entry += &format!( + ", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \ + \"out_cpp_{tree}_bytes\": {}", + sha_hex(&ob), + ob.len() + ); + files.push(format!( + "\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", + sha_hex(&ob), + ob.len() + )); + } +} + +/// Writes a case and returns its manifest entry; `mutate` edits the `.in` bytes before the manifest records their hash. +fn write_case(dir: &Path, s: &Spec, mutate: &impl Fn(&mut Vec), files: &mut Vec) -> String { + let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); + let mut inb = in_file(s.gu, s.down, s.rows); + mutate(&mut inb); + fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); + let mut entry = case_entry(s, &id, &inb); + files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); + write_outs(dir, &id, s.rows, &mut entry, files); + entry + "}" +} + +/// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. +fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { + let mut files = Vec::new(); + let cases: Vec = specs.iter().map(|s| write_case(dir, s, &mutate, &mut files)).collect(); + let manifest = format!( + "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \ + \"provenance\": {PROVENANCE}, \"cases\": [{}], \"files\": {{{}}}}}", + cases.join(", "), + files.join(", ") + ); + fs::write(dir.join("manifest.json"), manifest).unwrap(); +} + +fn two_cases() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] +} + +fn one_case() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] +} + +fn id(file: &str) -> String { + format!("case-42-42-r1.{file}") +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs new file mode 100644 index 00000000..9492953b --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs @@ -0,0 +1,149 @@ +//! The alternation runner (STRA-318): the schedule, its file, and the scrubbed environment of the cells. +use super::*; + +/// The test the environment test starts in a child process (`--exact`). +const PROBE_CHILD: &str = "tests::alternation::env_probe_child"; +/// The test the failure test starts in a child process (`--exact`). +const FAILING_CHILD: &str = "tests::alternation::failing_child"; + +#[test] +fn the_schedule_is_reproducible_from_the_seed() { + let procs = procs_for(&TREES); + let a = make_schedule(7, 1, 30, &procs); + assert_eq!(a, make_schedule(7, 1, 30, &procs)); + assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule"); + assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule"); + assert_eq!(a.len(), 30); + // the text round-trips through the file format and names the seed + let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a); + assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9")); + let back = parse_schedule(&text).unwrap(); + assert_eq!(back.iter().map(|r| r.1.clone()).collect::>(), a); + assert_eq!(back[0].0, 1); + assert_eq!(back[29].0, 30); +} + +#[test] +fn the_rotation_gives_every_process_every_position_within_a_block() { + let procs = procs_for(&TREES); + assert_eq!(procs.len(), 8); + let s = make_schedule(3, 1, 16, &procs); + for block in s.chunks(8) { + for round in block { + let mut names: Vec<_> = round.iter().map(Proc::name).collect(); + names.sort(); + assert_eq!(names.len(), 8); + names.dedup(); + assert_eq!(names.len(), 8, "every process exactly once per round"); + } + for pos in 0..8 { + let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect(); + assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds"); + } + } + // a host without AVX-512 has only the avx2 cells + assert_eq!(procs_for(&["avx2"]).len(), 4); +} + +#[test] +fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() { + let t = TempDir::new(); + let f = t.0.join("schedule.tsv"); + create_new_file(&f, b"x").unwrap(); + assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten")); + assert_eq!(fs::read(&f).unwrap(), b"x"); + let procs = procs_for(&TREES); + let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs)); + assert!(parse_schedule(&good).is_ok()); + assert!(parse_schedule("nope").is_err()); + assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process")); + assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow")); + // a round that names one process twice (and so lacks another) is refused + let dup = good + .lines() + .map(|l| { + if l.starts_with("2\t") { + l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) + } else { + l.to_owned() + } + }) + .collect::>() + .join("\n"); + assert!(parse_schedule(&dup).is_err()); +} + +/// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run. +#[test] +fn env_probe_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) { + return; + } + for (k, v) in std::env::vars() { + if is_managed_name(&k) { + println!("PROBE {k}={v}"); + } + } +} + +/// The child side of the failure test. +#[test] +fn failing_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) { + eprintln!("simulated kernel failure"); + std::process::exit(3); + } +} + +fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command { + let mut parent: Vec<(OsString, OsString)> = + std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect(); + parent.push(("KAB_TEST_CHILD".into(), mode.into())); + parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell); + c.args(["--exact", test, "--nocapture", "--test-threads=1"]); + c +} + +/// Only the variables of the cell survive in a child that was planted with Strata and Leleka variables. +fn only_the_cell_survives(cell: &[(String, String)]) { + let planted = [("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")]; + let out = run_cell(&mut child(PROBE_CHILD, "probe", &planted, cell), "rust-avx2-a").unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + // libtest prints "test ... " before the child's own output on the same line + let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); + probes.sort_unstable(); + assert_eq!( + probes, + vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], + "only the cell's variables survive:\n{text}" + ); +} + +#[test] +fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() { + let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' }); + assert_eq!( + cell, + vec![ + ("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), + ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), + ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()) + ] + ); + assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); + only_the_cell_survives(&cell); + // the cpp avx512 cell sets nothing at all + let mut cpp = child(PROBE_CHILD, "probe", &[("STRATA_X", "planted")], &[]); + let out = run_cell(&mut cpp, "cpp-avx512-a").unwrap(); + assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); +} + +#[test] +fn a_child_failure_is_reported_with_the_cell_named() { + let e = run_cell(&mut child(FAILING_CHILD, "fail", &[], &[]), "cpp-avx2-b").unwrap_err(); + assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}"); + assert!(e.contains("simulated kernel failure"), "{e}"); + let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err(); + assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}"); +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs new file mode 100644 index 00000000..c796b5e2 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs @@ -0,0 +1,283 @@ +//! The KAB1 reader: the rule that refuses the whole directory, the JSON reader, the comparison and our trees. +use super::*; + +#[test] +fn a_good_directory_verifies() { + let t = TempDir::new(); + build(&t.0, &two_cases(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases.len(), 2); + assert_eq!(v.file_count, 2 * 3 + 1); + assert_eq!(v.manifest_sha256.len(), 64); + assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); +} + +#[test] +fn a_flipped_byte_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("in")); + let mut b = fs::read(&p).unwrap(); + b[IN_HEADER + 7] ^= 0x40; + fs::write(&p, b).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("sha256"), "{e}"); +} + +#[test] +fn a_truncated_file_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("cpp-avx2.out")); + let b = fs::read(&p).unwrap(); + fs::write(&p, &b[..b.len() - 4]).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); + assert!(e.reason.contains("length"), "{e}"); +} + +#[test] +fn a_wrong_magic_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[0] ^= 0xff); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("magic"), "{e}"); +} + +#[test] +fn a_wrong_version_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[4] = 2); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("version"), "{e}"); +} + +#[test] +fn a_byte_count_that_disagrees_with_the_format_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let wrong = (le32(b, 28) + 18).to_le_bytes(); + b[28..32].copy_from_slice(&wrong); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("format-derived"), "{e}"); +} + +#[test] +fn a_non_finite_fp16_header_is_refused() { + let t = TempDir::new(); + // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it + build(&t.0, &one_case(), |b| { + let at = IN_HEADER + 18 * 3; + b[at] = 0x00; + b[at + 1] = 0x7c; // FP16 +inf + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("non-finite FP16"), "{e}"); +} + +#[test] +fn a_non_finite_activation_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let at = b.len() - 4; + b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert!(e.reason.contains("non-finite activation"), "{e}"); +} + +#[test] +fn a_missing_manifest_is_incomplete_and_named() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::remove_file(t.0.join("manifest.json")).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.incomplete); + assert!(e.to_string().contains("manifest.json")); +} + +#[test] +fn an_extra_or_missing_file_refuses_the_directory() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::write(t.0.join("stray.txt"), b"x").unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); + fs::remove_file(t.0.join("stray.txt")).unwrap(); + fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); +} + +/// A case whose input header says its gate bytes are 4 GiB - 16, in a directory of its own. +fn lying_header_directory() -> TempDir { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); + t +} + +/// The manifest cases of a synthetic directory. +fn manifest_cases(dir: &Path) -> Vec { + let (_, cases, _) = parse_manifest(&parse_json(&fs::read(dir.join("manifest.json")).unwrap()).unwrap()).unwrap(); + cases +} + +/// Through the file reader: manifest and file agree on a file whose header lies about its size, and a manifest that +/// declares an absurd length for a file is refused before a buffer too. +fn lying_header_through_the_reader() { + let t = lying_header_directory(); + BUFFERS.with(|c| c.set(0)); + let cases = manifest_cases(&t.0); + let e = read_case_in(&t.0, &cases[0]).err().unwrap(); + assert!(e.reason.contains("format-derived"), "{e}"); + assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); + let mut lying = cases[0].clone(); + lying.in_bytes = u64::MAX; + assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); + assert_eq!(BUFFERS.with(Cell::get), 0); +} + +#[test] +fn an_absurd_length_is_refused_without_taking_a_buffer() { + // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists + let mut h = [0u8; IN_HEADER]; + h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); + h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); + BUFFERS.with(|c| c.set(0)); + assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); + assert_eq!(BUFFERS.with(Cell::get), 0); + lying_header_through_the_reader(); + // the good path takes exactly one buffer per file + let g = TempDir::new(); + build(&g.0, &one_case(), |_| {}); + BUFFERS.with(|c| c.set(0)); + read_case_in(&g.0, &manifest_cases(&g.0)[0]).unwrap(); + assert_eq!(BUFFERS.with(Cell::get), 1); +} + +#[test] +fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { + let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only \ + difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; + let t = TempDir::new(); + build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); + for (bad, why) in [ + (ok.replace("0.003", "0"), "positive"), + (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), + (ok.replace("order-only difference", " "), "basis"), + (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), + ] { + let leaked: &'static str = Box::leak(bad.into_boxed_str()); + let d = TempDir::new(); + build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); + let e = verify_dir(&d.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.reason.contains(why), "{why}: {e}"); + } +} + +#[test] +fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { + let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); + assert_eq!( + j.get("a"), + Some(&Json::Arr(vec![ + Json::Num("1".into()), + Json::Num("-2.5e3".into()), + Json::Bool(true), + Json::Null, + Json::Str("x\n\u{e9}\u{1f600}".into()) + ])) + ); + assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); + for bad in [ + "{\"a\": 1, \"a\": 2}", + "{\"a\": 1,}", + "[1 2]", + "{\"a\": \"\\ud800\"}", + "{} x", + "", + "{\"a\": 01x}", + "\"\u{1}\"", + ] { + assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); + } + assert!(parse_json("[".repeat(40).as_bytes()).is_err()); +} + +#[test] +fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { + let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; + assert!(compare_bits(&a, &a, None).equal()); + let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; + let o = compare_bits(&neg0, &a, None); + assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); + let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; + assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); + let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; + assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); + let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; + assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); + assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); +} + +/// Runs the first case of a verified directory twice on one pool; the output of the first call. +fn run_case_twice(v: &Verified) -> Vec { + let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); + let mut pool = DirectCpuPool::new(1).unwrap(); + let first = compute_case(&mut pool, &case).unwrap(); + let second = compute_case(&mut pool, &case).unwrap(); + assert_eq!(first.len(), H); + assert!( + first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), + "the same case twice must be bit-identical" + ); + first +} + +/// The record of the comparison of our output with itself is well formed. +fn assert_synthetic_record(v: &Verified, outcome: &Outcome) { + let json = record_json(&RecordInput { + record_id: "kab1-synthetic-r".into(), + created_utc: "2026-10-28T20:00:00Z".into(), + run_started_utc: "2026-10-28T19:59:00Z".into(), + machine_role: "m\"1".into(), + cpu_model: "cpu".into(), + os: "os".into(), + ours_compiler: "rustc".into(), + ours_version: "rustc 1.99.0".into(), + ours_triple: "x86_64-unknown-linux-gnu".into(), + ours_flags: "f".into(), + tree: "avx2", + verified: v, + case: &v.cases[0], + pin_cpu: 0, + sibling_idle: true, + outcome, + }); + let rec = parse_json(json.as_bytes()).unwrap(); + assert_record_keys(&rec, ""); + assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); + assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); +} + +#[test] +fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let first = run_case_twice(&v); + let path = t.0.join("ours.rust-avx2.out"); + write_out(&path, 1, "avx2", &first).unwrap(); + let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); + assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); + assert_synthetic_record(&v, &compare_bits(&back, &back, None)); +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs new file mode 100644 index 00000000..9ceddb89 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs @@ -0,0 +1,373 @@ +//! The timing mode (STRA-318): the command lines, the statistics helpers, the process JSON and the round records. +use super::*; + +/// Command line words from one space-separated line. +fn words(line: &str) -> Vec { + line.split_whitespace().map(str::to_owned).collect() +} + +#[test] +fn the_time_command_line_is_the_one_of_kab_time() { + let t = parse_time_args(&words("--run-dir D --case 18-20-r1 --slices 50 --pin 9 --out t.json")).unwrap(); + assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None)); + let all = "--run-dir D --case c --slices 2 --pin 0 --out o --slice-ms 5 --regime streamed --llc-bytes 1000"; + let t = parse_time_args(&words(all)).unwrap(); + assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); + time_command_line_refusals(); + let a = parse_alt_args(&words("--run-dir D --case c --rounds 30 --batch 1 --pin 9 --schedule s.tsv")).unwrap(); + assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20)); + assert!(parse_alt_args(&words("--run-dir D --case c --rounds 30 --batch 0 --pin 9 --schedule s")).is_err()); +} + +fn time_command_line_refusals() { + for bad in [ + "--run-dir D --case c --slices 0 --pin 0 --out o", + "--run-dir D --case c --slices 1 --out o", + "--run-dir D --case c --slices 1 --pin 0 --out o --regime both2", + "--run-dir D --case ../c --slices 1 --pin 0 --out o", + "--run-dir D --case c --slices 1 --pin 0 --out o --bogus 1", + "--run-dir D --run-dir E --case c --slices 1 --pin 0 --out o", + ] { + assert!(parse_time_args(&words(bad)).is_err(), "{bad:?}"); + } +} + +#[test] +fn medians_percentiles_and_parsers_agree_with_the_reference_rules() { + assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference"); + assert_eq!(median_of(&[]), 0.0); + let v: Vec = (1..=21).map(f64::from).collect(); + assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0)); + assert_eq!(parse_cpu_list("2,18"), vec![2, 18]); + assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]); + assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); + assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); + assert_eq!(busy_fraction(None, Some((1, 1))), None); + // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the + // folded multiply chain) + let ghz = core_ghz(); + assert!((0.3..12.0).contains(&ghz), "{ghz}"); +} + +#[test] +fn an_output_inside_a_git_checkout_is_detected() { + let t = TempDir::new(); + let inner = t.0.join("a/b"); + fs::create_dir_all(&inner).unwrap(); + assert!(!inside_git_checkout(&inner)); + fs::create_dir_all(t.0.join(".git")).unwrap(); + assert!(inside_git_checkout(&inner)); + assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv"))); +} + +fn json_slice(g1: f64) -> String { + format!( + "{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \ + \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}" + ) +} + +fn json_regime(label: &str, k: usize, self_key: &str) -> String { + format!( + "{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \ + \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \ + \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}", + json_slice(5.0), + json_slice(5.1), + json_slice(4.0) + ) +} + +/// The `tree_detail` and the self-check key of a process JSON as the C++ writer (`imp` cpp) or this example writes it. +fn tree_detail(p: &Proc) -> (&'static str, String) { + if p.imp == Impl::Cpp { + ( + "selfcheck_bitwise_equal_compose_expert", + "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \ + \"iq256_gather_setting\": -1, \"strata_env\": {}}" + .to_owned(), + ) + } else { + ( + "selfcheck_bitwise_equal_first_call", + format!( + "{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \ + \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", + p.tree + ), + ) + } +} + +/// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective +/// environment. +fn proc_fixture(p: &Proc, env: &str) -> String { + let (self_key, detail) = tree_detail(p); + format!( + "{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \ + \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \ + \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \ + \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \ + \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}", + p.imp.name(), + p.tree, + "cd".repeat(32), + json_regime("RESIDENT", 1, self_key), + json_regime("STREAMED", 3, self_key) + ) +} + +/// A process JSON of the cell `p` parses, and the recorded drift, sibling and environment are checked. +fn assert_fixture_accepted(p: &Proc, env: &str, expect: &Expect) { + let ok = parse_proc_json(p, proc_fixture(p, env).as_bytes(), expect).unwrap(); + assert_eq!(ok.regimes.len(), 2); + let r = &ok.regimes["STREAMED"]; + assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3)); + assert!((r.max_drift - 0.2).abs() < 1e-9, "the dropped slice's 20 percent drift is the maximum: {}", r.max_drift); + assert_eq!(ok.sibling_idle, Some(true)); +} + +/// Wrong pin, wrong manifest, wrong input, wrong writer: each names the cell. +fn assert_fixture_refused(p: &Proc, env: &str, expect: &Expect) { + let bad_expects = [ + (Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"), + (Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"), + (Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"), + ]; + for (bad_expect, what) in bad_expects { + let e = parse_proc_json(p, proc_fixture(p, env).as_bytes(), &bad_expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}"); + } + let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..*p }; + assert!(parse_proc_json(&other, proc_fixture(p, env).as_bytes(), expect).unwrap_err().contains("writer")); +} + +#[test] +fn a_process_json_is_checked_against_the_cell_that_was_started() { + let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 }; + for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] { + let env = json_env(&cell_env(&p).into_iter().collect()); + assert_fixture_accepted(&p, &env, &expect); + // the environment the process saw must be exactly the cell's + let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())])); + let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}"); + assert_fixture_refused(&p, &env, &expect); + } +} + +fn fake_proc(p: Proc, base: f64) -> ProcOut { + let regime = |k: usize| RegimeStat { + copies_k: k, + expert_bytes: 1_000_000, + llc_bytes: 1_000, + requested: 10, + dropped: 1, + median_ns: base, + median_cycles: base * 5.0, + ns: vec![base * 0.9, base, base * 1.1], + cycles: vec![base * 4.5, base * 5.0, base * 5.5], + max_drift: 0.01, + selfcheck: true, + }; + ProcOut { + proc: p, + regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]), + ghz_start: 5.0, + ghz_end: 5.1, + sibling_idle: Some(true), + final_unchanged: true, + output_sha: Some("ab".repeat(32)), + tree_text: format!("tree text of {}", p.name()), + cpu_model: Some("Test CPU".to_owned()), + } +} + +fn outcome(bad: usize) -> Outcome { + Outcome { compared: H, mismatches: bad, differing_bits: bad, max_abs_error: 0.0, first_mismatch: None } +} + +fn rust_tool() -> Tool { + Tool { + compiler: "rustc".into(), + version: "rustc 1.99.0".into(), + triple: "x86_64-unknown-linux-gnu".into(), + flags: "f".into(), + } +} + +fn batch_ctx<'a>(v: &'a Verified, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> { + BatchCtx { + verified: v, + case: &v.cases[0], + pin: 9, + machine_role: "m".into(), + os: "os".into(), + cpu_model: "cpu".into(), + started_utc: "2026-10-28T20:00:00Z".into(), + rust_tool: rust_tool(), + batch: 2, + equality, + } +} + +/// Every process of the schedule, in the reverse order of execution; cpp-avx2-b saw a busy sibling. +fn finished_processes() -> Vec { + let mut done: Vec = + procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); + done.reverse(); // the order of execution does not matter to the records + done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = + Some(false); + done +} + +/// One round record file: the schema shape, the verdict and the carried mismatch count. +fn assert_round_file(name: &str, json: &str, v: &Verified) { + let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_record_keys(&rec, &format!("{name}: ")); + assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); + assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256); + let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") }; + let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect(); + assert_eq!(units, ["ns", "cycles"]); + assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type"); + let regime = rec.str("regime").unwrap(); + assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}"); + assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER")); + let eq = rec.req("equality").unwrap(); + let tree = rec.req("tree").unwrap().str("ours").unwrap(); + let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" }; + assert_eq!(eq.str("verdict").unwrap(), want, "{name}"); + if want == "NOT_EQUAL" { + assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden"); + } +} + +fn record_of(files: &[(String, String)], name: &str) -> Json { + parse_json(files.iter().find(|f| f.0 == name).unwrap().1.as_bytes()).unwrap() +} + +/// The A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation +/// on both, and the sibling belongs to the two processes of a record. +fn assert_slots(files: &[(String, String)]) { + let ab = record_of(files, "r00031.ab.avx512.resident.json"); + assert!(ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a")); + assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc"); + let aa = record_of(files, "r00031.aa-cpp.avx512.resident.json"); + assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b")); + assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); + // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of + // cpp-avx2-b + for (name, json) in files { + let rec = parse_json(json.as_bytes()).unwrap(); + let busy = name.contains(".aa-cpp.avx2."); + assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); + } +} + +#[test] +fn round_records_have_the_schema_shape_and_keep_not_equal() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); + let ctx = batch_ctx(&v, &equality); + let done = finished_processes(); + let files = round_records(&ctx, 31, &done).unwrap(); + assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); + let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); + assert_eq!(names.len(), 12); + assert!( + names.contains("r00031.ab.avx2.streamed.json") + && names.contains("r00031.aa-cpp.avx512.resident.json") + && names.contains("r00031.aa-rust.avx2.resident.json") + ); + for (name, json) in &files { + assert_round_file(name, json, &v); + } + assert_slots(&files); + assert_round_refusals(&ctx, &done); +} + +/// A streamed set that differs between the two sides of a record is refused, and so is a missing process. +fn assert_round_refusals(ctx: &BatchCtx<'_>, done: &[ProcOut]) { + let mut skewed = done.to_vec(); + skewed + .iter_mut() + .find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }) + .unwrap() + .regimes + .get_mut("STREAMED") + .unwrap() + .copies_k = 4; + assert!(round_records(ctx, 31, &skewed).unwrap_err().contains("streamed set differs")); + // a missing process is named + assert!(round_records(ctx, 31, &done[1..]).unwrap_err().contains("did not run")); +} + +/// The arguments of the Rust time mode on a synthetic directory (the paths may hold spaces). +fn rust_time_args(dir: &Path, file: &Path) -> Vec { + let mut args = words("--run-dir"); + args.push(dir.to_str().unwrap().to_owned()); + args.extend(words("--case 42-42-r1 --slices 40 --pin 0 --out")); + args.push(file.to_str().unwrap().to_owned()); + args.extend(words("--slice-ms 1 --llc-bytes 8000000")); + args +} + +/// The process JSON of the Rust time mode is accepted by the runner once its environment is the cell's. +fn assert_runner_accepts(t: &TempDir, text: &str, p: &Proc) { + let manifest = fs::read(t.0.join("manifest.json")).unwrap(); + let (_, _, cases, _) = read_manifest(&t.0).unwrap(); + let sha = sha_hex(&manifest); + let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 }; + // the test process runs unscrubbed (its effective environment is empty), so the runner's environment check + // refuses it ... + assert!(parse_proc_json(p, text.as_bytes(), &expect).unwrap_err().contains("effective environment")); + // ... and accepts it once the recorded environment is the cell's + let want_env = json_env(&cell_env(p).into_iter().collect()); + let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1); + let ok = parse_proc_json(p, as_cell.as_bytes(), &expect).unwrap(); + for r in ["RESIDENT", "STREAMED"] { + let s = &ok.regimes[r]; + assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}"); + assert_eq!(s.requested, 40); + } + assert_eq!(ok.regimes["RESIDENT"].copies_k, 1); + assert!(ok.regimes["STREAMED"].copies_k >= 2); + assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family")); + // a lie about the pin is refused + let lie = parse_proc_json(p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }); + assert!(lie.unwrap_err().contains("pinned to CPU")); +} + +#[test] +fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let out = TempDir::new(); + let file = out.0.join("t.json"); + // exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the + // loaded host's call) + let code = format!("{:?}", cmd_time(&rust_time_args(&t.0, &file)).unwrap()); + assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}"); + let text = fs::read_to_string(&file).unwrap(); + let j = parse_json(text.as_bytes()).unwrap(); + assert_eq!(j.str("writer").unwrap(), "rust"); + assert_eq!(j.str("format").unwrap(), "KAB1-time"); + assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap()); + assert_eq!(j.str("output_sha256").unwrap().len(), 64); + let tree = j.str("tree").unwrap().to_owned(); + let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' }; + if code.contains("(0)") { + assert_runner_accepts(&t, &text, &p); + } +} + +#[test] +fn utc_formatting_is_exact() { + assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); + assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); + assert!(is_utc(&now_utc())); +}