Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/0a486aa42a993ebd # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#878 (code only) closed derived `0a486aa42a993ebd` #878 Imported from GitHub aien-dev/aien-sovereign-core-mv#878 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `d3dec0eb18818808212bdf99db5c8612bcfcb9ef` · Head `8bf2dc4454c4323060c9bfa61cbf6aee95593026` ### Apply it ``` git checkout -b patch-0a486aa42a993ebd d3dec0eb18818808212bdf99db5c8612bcfcb9ef curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/0a486aa42a993ebd.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 878 8bf2dc4454c4323060c9bfa61cbf6aee95593026 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":878,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/878","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:10Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aien-inference-abi/src/qwen38_omega/prefill.rs b/crates/aien-inference-abi/src/qwen38_omega/prefill.rs index ff794b03..5ac20271 100644 --- a/crates/aien-inference-abi/src/qwen38_omega/prefill.rs +++ b/crates/aien-inference-abi/src/qwen38_omega/prefill.rs @@ -174,6 +174,37 @@ fn argmax(v: &[f32]) -> u32 { best as u32 } +/// CPU model of the graph's two-stage ARGMAX (omega a647b6a9 `omega_blackwell_codegen_dec.h` +/// ARGMAX, `omega_gpu_q36_graph.c` `rec_argmax`): stage 1, CTA `c` of `ceil(n / span)` takes +/// `v[c * span ..]` (the tail padded with `NEG_PAD` -1e30) and writes its largest value and the +/// lowest index holding it; stage 2 does the same over the partials (padded with -1e30), carrying +/// their indices. omega's SASS simulator checks the kernel against this rule on ties +/// (`tests/gpu_cmdlist_test.c` "sim argmax tie", the last-equal-index mutant caught). The tests +/// take it as the chip's argmax (DRA-87). +#[cfg(test)] +pub(crate) fn chip_argmax_model(v: &[f32], span: usize) -> u32 { + const NEG_PAD: f32 = -1e30; + let lowest_max = |vals: &[(f32, u32)]| { + let m = vals.iter().fold(f32::NEG_INFINITY, |m, &(x, _)| m.max(x)); + *vals + .iter() + .filter(|&&(x, _)| x == m) + .min_by_key(|&&(_, i)| i) + .expect("a CTA holds at least one value") + }; + let ctas = v.len().div_ceil(span); + let mut partials: Vec<(f32, u32)> = (0..ctas) + .map(|c| { + let vals: Vec<(f32, u32)> = (c * span..(c + 1) * span) + .map(|i| (v.get(i).copied().unwrap_or(NEG_PAD), i as u32)) + .collect(); + lowest_max(&vals) + }) + .collect(); + partials.resize(span.max(ctas), (NEG_PAD, u32::MAX)); + lowest_max(&partials).1 +} + /// Chunk lengths for `n` tokens: at most `chunk` each, none shorter than the DeltaNet prefill's /// minimum (the second to last chunk gives up tokens when the remainder would be too short). pub(super) fn chunk_lengths(n: usize, chunk: usize) -> Vec { @@ -290,12 +321,39 @@ impl Qwen38Omega { tokens: &[u32], chunk: usize, ) -> Result<(u32, Vec, PrefillStats), String> { + let (next, logits, st) = self.prefill_head(tokens, chunk, true)?; + Ok((next, logits.ok_or("prefill: no logits")?, st)) + } + + /// [`Self::prefill`] without the logits (DRA-87, a greedy first token): the 35B returns the + /// chip's argmax of the last token's head (the host rule: the largest logit, the first index + /// on a tie) and reads no logits back; other models take the host argmax of the head's + /// logits, as [`Self::prefill`] does. + pub fn prefill_token( + &mut self, + tokens: &[u32], + chunk: usize, + ) -> Result<(u32, PrefillStats), String> { + self.prefill_head(tokens, chunk, false) + .map(|(next, _, st)| (next, st)) + } + + fn prefill_head( + &mut self, + tokens: &[u32], + chunk: usize, + want_logits: bool, + ) -> Result<(u32, Option>, PrefillStats), String> { let t0 = Instant::now(); if self.is_moe() { // The 35B: chunks of the prompt through the chip as rows (L369, the decode step's kernels, // the state bit for bit as token by token); AIEN_Q36_PREFILL_CHUNK=0 feeds the decode // graph token by token (the old path). let chunk = q36_prefill_chunk()?; + let mut st = PrefillStats { + tokens: tokens.len(), + ..Default::default() + }; let mut next = 0u32; if chunk == 0 { for &t in tokens { @@ -304,21 +362,14 @@ impl Qwen38Omega { } else { let (n, chunks) = self.prefill_moe(tokens, chunk)?; next = n; - let logits = self.logits()?; - let st = PrefillStats { - tokens: tokens.len(), - chunks, - wall_ns: ns(t0), - ..Default::default() - }; - return Ok((next, logits, st)); + st.chunks = chunks; } - let logits = self.logits()?; - let st = PrefillStats { - tokens: tokens.len(), - wall_ns: ns(t0), - ..Default::default() + let logits = if want_logits { + Some(self.logits()?) + } else { + None }; + st.wall_ns = ns(t0); return Ok((next, logits, st)); } let (last, mut st) = self.prefill_rows(tokens, chunk, false)?; @@ -327,7 +378,27 @@ impl Qwen38Omega { let next = argmax(&logits); st.head_ns = ns(t); st.wall_ns = ns(t0); - Ok((next, logits, st)) + Ok((next, want_logits.then_some(logits), st)) + } + + /// Feeds `tokens` at head 0's next positions for their state only: no head, no residual read + /// back (a session's prompt rows before its snapshot point, DRA-65). The 35B: chunks of + /// [`q36_prefill_chunk`] through the chip prefill (L369, any length, the state bit for bit as + /// token by token; with 0 every token is stepped through the decode graph and the stats' + /// `chunks` is 0); other models: [`Self::prefill_rows`] with `chunk` (at least + /// [`q::GDN_PF_MIN_T`] tokens). Nothing to feed is a no-op. + pub fn prefill_state(&mut self, tokens: &[u32], chunk: usize) -> Result { + let t0 = Instant::now(); + if !self.is_moe() { + return self.prefill_rows(tokens, chunk, false).map(|(_, st)| st); + } + let chunks = q36_state(self, tokens, q36_prefill_chunk()?)?; + Ok(PrefillStats { + tokens: tokens.len(), + chunks, + wall_ns: ns(t0), + ..Default::default() + }) } /// The final norm and the bf16 lm_head on one residual row (`[hidden]`): `[vocab]` logits. @@ -361,19 +432,25 @@ impl Qwen38Omega { let n = tokens.len(); let (h, v) = (self.config.hidden, self.config.vocab); if self.is_moe() { - // As prefill: token by token through the decode graph; the rows are its residual x. + // The 35B's chip prefill (L369) keeps its rows in its own buffers, not in the decode + // graph's x, so the rows asked for come from decode steps: every token's when `all`; + // else the others go in as chunks ([`Self::prefill_state`]) and the last is stepped. + let (head, stepped) = if all || n == 0 { + (&tokens[..0], tokens) + } else { + tokens.split_at(n - 1) + }; + let chunks = self.prefill_state(head, chunk)?.chunks; let mut rows = Vec::with_capacity(if all { n * h } else { h }); - for (i, &t) in tokens.iter().enumerate() { + for &t in stepped { self.step(t)?; - if all || i + 1 == n { - rows.extend(self.residual()?); - } + rows.extend(self.residual()?); } - let _ = (chunk, v); return Ok(( rows, PrefillStats { tokens: n, + chunks, wall_ns: ns(t0), ..Default::default() }, @@ -581,18 +658,86 @@ impl Qwen38Omega { /// Prompt tokens per 35B prefill chunk (`AIEN_Q36_PREFILL_CHUNK`, default the graph's most, /// [`q::q36::PREFILL_MAX_ROWS`]); 0 = token by token through the decode graph. pub fn q36_prefill_chunk() -> Result { - match std::env::var("AIEN_Q36_PREFILL_CHUNK") { - Ok(v) => match v.parse::() { + parse_q36_chunk(std::env::var("AIEN_Q36_PREFILL_CHUNK").ok().as_deref()) +} + +fn parse_q36_chunk(v: Option<&str>) -> Result { + match v { + Some(v) => match v.parse::() { Ok(n) if n <= q::q36::PREFILL_MAX_ROWS => Ok(n), _ => Err(format!( "AIEN_Q36_PREFILL_CHUNK={v}: 0 (off) ..= {}", q::q36::PREFILL_MAX_ROWS )), }, - Err(_) => Ok(q::q36::PREFILL_MAX_ROWS), + None => Ok(q::q36::PREFILL_MAX_ROWS), + } +} + +/// The lengths of the 35B prefill's chunks for `n` tokens: whole chunks of `chunk` and the rest +/// last (the q36 prefill takes any length from 1, unlike the 27B's [`chunk_lengths`]). +pub fn q36_chunk_lengths(n: usize, chunk: usize) -> Vec { + if chunk == 0 { + return Vec::new(); + } + let mut out = vec![chunk; n / chunk]; + if n % chunk > 0 { + out.push(n % chunk); + } + out +} + +/// What the 35B's state feed drives: one decode step, or chip prefill chunks of `chunk` at head +/// 0's next positions without the head (the model; a recording fake in the session tests). +pub(crate) trait Q36Feed { + fn q36_step(&mut self, t: u32) -> Result<(), String>; + /// Returns the chunks run. + fn q36_chunks(&mut self, tokens: &[u32], chunk: usize) -> Result; +} + +impl Q36Feed for Qwen38Omega { + fn q36_step(&mut self, t: u32) -> Result<(), String> { + self.step(t).map(|_| ()) + } + + fn q36_chunks(&mut self, tokens: &[u32], chunk: usize) -> Result { + Ok(self.prefill_moe_head(0, tokens, chunk, false)?.1) } } +/// [`Qwen38Omega::prefill_state`] on the 35B: `c == 0` steps every token, else chunks of `c`. +/// Returns the chunks run (0 when stepped or nothing to feed). +pub(crate) fn q36_state(f: &mut F, tokens: &[u32], c: usize) -> Result { + if c == 0 { + for &t in tokens { + f.q36_step(t)?; + } + return Ok(0); + } + if tokens.is_empty() { + return Ok(0); + } + f.q36_chunks(tokens, c) +} + +/// Walks `tokens` in the chunks of [`q36_chunk_lengths`] from position `pos0`: `each(chunk, pos, +/// last)`. Returns the chunks walked and the position after the last token. +pub(crate) fn q36_chunk_walk( + tokens: &[u32], + chunk: usize, + pos0: usize, + mut each: impl FnMut(&[u32], usize, bool) -> Result<(), String>, +) -> Result<(usize, usize), String> { + let lengths = q36_chunk_lengths(tokens.len(), chunk); + let (mut at, mut pos) = (0, pos0); + for (i, &m) in lengths.iter().enumerate() { + each(&tokens[at..at + m], pos, i + 1 == lengths.len())?; + at += m; + pos += m; + } + Ok((lengths.len(), pos)) +} + impl Qwen38Omega { /// L369: fp8 GEMM weight bytes the 35B prefill has streamed so far on this graph (0 for other /// models); see `Graph::prefill_streamed`. @@ -646,9 +791,7 @@ impl Qwen38Omega { g.prefill_alloc(chunk).map_err(gpu("q36 prefill_alloc"))?; } let mut next = None; - let mut pos = pos0; - let n_chunks = tokens.len().div_ceil(chunk); - for (i, c) in tokens.chunks(chunk).enumerate() { + let (n_chunks, pos) = q36_chunk_walk(tokens, chunk, pos0, |c, pos, last| { let mut x = vec![0f32; c.len() * h]; for (row, &t) in x.chunks_mut(h).zip(c) { let t = t as usize; @@ -656,15 +799,14 @@ impl Qwen38Omega { *d = bf16_to_f32(b); } } - let last = i + 1 == n_chunks; let (tok, _) = g .prefill(head, &x, pos, last && want_token) .map_err(gpu("q36 prefill"))?; if last { next = tok; } - pos += c.len(); - } + Ok(()) + })?; *self.head_pos_mut(head)? = pos; Ok((next, n_chunks)) } @@ -691,8 +833,122 @@ mod tests { assert_eq!(chunk_lengths(131_072, 4096).len(), 32); } + /// DRA-65: the 35B chunk boundaries at the prompt lengths the window measures, at the served + /// chunk (128) and at a small one; every token in exactly one chunk, none longer than the cap. + #[test] + fn q36_chunks_at_the_boundaries() { + let cap = q::q36::PREFILL_MAX_ROWS; + assert_eq!(cap, 128); + let cases: [(usize, &[usize]); 4] = + [(1, &[1]), (127, &[127]), (128, &[128]), (129, &[128, 1])]; + for (n, want) in cases { + assert_eq!(q36_chunk_lengths(n, cap), want, "n {n}"); + } + assert_eq!(q36_chunk_lengths(2048, cap), vec![128; 16]); + assert_eq!(q36_chunk_lengths(8192, cap), vec![128; 64]); + assert_eq!(q36_chunk_lengths(8210, cap).len(), 65); + assert_eq!(q36_chunk_lengths(8210, cap)[64], 18); + assert!(q36_chunk_lengths(0, cap).is_empty()); + assert!(q36_chunk_lengths(5, 0).is_empty()); + for chunk in [1, 7, 64, cap] { + for n in [1, chunk - 1, chunk, chunk + 1, 2048, 8192] { + let c = q36_chunk_lengths(n, chunk); + assert_eq!(c.iter().sum::(), n, "n {n} chunk {chunk}"); + assert_eq!(c.len(), n.div_ceil(chunk), "n {n} chunk {chunk}"); + assert!( + c.iter().all(|&m| (1..=chunk).contains(&m)), + "n {n} chunk {chunk}: {c:?}" + ); + } + } + } + + #[test] + fn q36_chunk_switch_parses_off_default_and_cap() { + let cap = q::q36::PREFILL_MAX_ROWS; + assert_eq!(parse_q36_chunk(None), Ok(cap)); + assert_eq!(parse_q36_chunk(Some("0")), Ok(0)); + assert_eq!(parse_q36_chunk(Some("16")), Ok(16)); + assert_eq!(parse_q36_chunk(Some("128")), Ok(128)); + assert!(parse_q36_chunk(Some("129")).is_err()); + assert!(parse_q36_chunk(Some("x")).is_err()); + } + #[test] fn argmax_takes_the_first_maximum() { assert_eq!(argmax(&[0.0, 2.0, 1.0, 2.0]), 1); } + + /// DRA-87 tie rule: the chip's two-stage ARGMAX (its CPU model, 2048 values per CTA over the + /// 35B's 248320 logits: 122 CTAs, the last one padded) picks the same token as the host's + /// greedy draw (`tensor::sample_argmax`, strict `>`) and this file's `argmax`: the largest + /// logit, the lowest index on a tie, within a CTA, across CTAs and against -inf (the exact + /// head's masked rows). NaN is outside the rule (the paths differ on it; finite logits only). + /// A last-equal-index argmax (omega's ARGMAX mode-1 mutant) disagrees on the tie cases. + #[test] + fn chip_argmax_model_takes_the_host_rule() { + const V: usize = 248_320; + const SPAN: usize = 2048; + let rand = |seed: u64| -> Vec { + (0..V as u64) + .map(|i| { + let mut x = seed ^ i.wrapping_mul(0x9e37_79b9_7f4a_7c15); + x ^= x >> 33; + x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); + x ^= x >> 33; + ((x >> 40) % 64) as f32 * 0.25 - 8.0 + }) + .collect() + }; + let mut cases: Vec<(&str, Vec)> = + vec![("random, many ties", rand(1)), ("random", rand(2))]; + let mut v = vec![0.0f32; V]; + v[2047] = 3.0; + v[2048] = 3.0; + cases.push(("tie across a CTA edge", v)); + let mut v = vec![0.0f32; V]; + v[5] = 3.0; + v[200_000] = 3.0; + cases.push(("tie far apart", v)); + let mut v = vec![0.0f32; V]; + v[100] = 3.0; + v[101] = 3.0; + cases.push(("tie inside a CTA", v)); + cases.push(("all equal", vec![1.5f32; V])); + let mut v = vec![f32::NEG_INFINITY; V]; + for i in [7usize, 4096, 131_072, V - 1] { + v[i] = -2.0; + } + cases.push(("-inf masked, tied survivors", v)); + let mut v = vec![-1.0f32; V]; + v[V - 1] = 0.5; + cases.push(("max in the padded last CTA", v)); + let last_equal = |v: &[f32]| -> u32 { + let mut best = 0usize; + for (i, &x) in v.iter().enumerate() { + if x >= v[best] { + best = i; + } + } + best as u32 + }; + for (what, v) in &cases { + let host = crate::tensor::sample_argmax(v).0; + assert_eq!(chip_argmax_model(v, SPAN), host, "{what}"); + assert_eq!(argmax(v), host, "{what}"); + if what.contains("tie") || what.contains("equal") { + assert_ne!(last_equal(v), host, "{what}: the mutant must differ"); + } + } + // Small vocabularies: the same rule at a span of 8 (several CTAs, a padded tail). + for n in [1usize, 7, 8, 9, 63, 64, 65] { + for top in 0..n { + let mut v: Vec = (0..n).map(|i| (i % 3) as f32).collect(); + v[top] = 9.0; + v[n - 1 - (n - 1 - top) / 2] = 9.0; + let host = crate::tensor::sample_argmax(&v).0; + assert_eq!(chip_argmax_model(&v, 8), host, "n {n} top {top}"); + } + } + } } diff --git a/crates/aien-inference-abi/src/qwen38_omega/session.rs b/crates/aien-inference-abi/src/qwen38_omega/session.rs index 9611537a..d5297bb2 100644 --- a/crates/aien-inference-abi/src/qwen38_omega/session.rs +++ b/crates/aien-inference-abi/src/qwen38_omega/session.rs @@ -78,8 +78,10 @@ pub struct FeedStats { pub reuse: Option, /// Prompt tokens fed this turn (prompt length minus the reused prefix). pub fed: usize, - /// Of those, fed one at a time through the decode graph (pieces shorter than the prefill's - /// minimum). + /// Of those, fed one at a time through the decode graph: pieces shorter than the 27B + /// prefill's minimum, and on the 35B only with `AIEN_Q36_PREFILL_CHUNK=0` or a last piece + /// shorter than [`q::GDN_PF_MIN_T`] (DRA-65: the 35B's rows before the snapshot point go in + /// as chip prefill chunks at any length). pub stepped: usize, pub prefill: PrefillStats, pub restore_ns: u64, @@ -91,6 +93,24 @@ fn ns(t: Instant) -> u64 { t.elapsed().as_nanos() as u64 } +/// The snapshot point of `prompt` when the first `from` tokens are already fed: its last +/// `<|im_start|>` (the header of the turn being answered) at or past `from`. The session feeds +/// `prompt[from..k]` without the head, snapshots there, then feeds `prompt[k..]` with the head; +/// `None`: no such header, the whole rest goes in with the head and no snapshot is taken. +pub fn snapshot_point(prompt: &[u32], from: usize) -> Option { + prompt + .iter() + .rposition(|&t| t == IM_START) + .filter(|&k| k >= from) +} + +/// Whether a row piece of `len` tokens (no head) is stepped token by token rather than fed by +/// [`Qwen38Omega::prefill_state`]: only the 27B's pieces under its prefill minimum; the 35B's +/// chip prefill takes any length (DRA-65). +pub fn rows_by_steps(len: usize, moe: bool) -> bool { + !moe && len < q::GDN_PF_MIN_T +} + fn add(sum: &mut PrefillStats, s: &PrefillStats) { sum.tokens += s.tokens; sum.chunks += s.chunks; @@ -107,6 +127,162 @@ fn add(sum: &mut PrefillStats, s: &PrefillStats) { sum.head_ns += s.head_ns; } +/// Books one prefill call: the 35B with `AIEN_Q36_PREFILL_CHUNK=0` reports no chunks for tokens +/// it stepped through the decode graph, which count as stepped. +fn count(st: &mut FeedStats, s: &PrefillStats) { + if s.chunks == 0 && s.tokens > 0 { + st.stepped += s.tokens; + } else { + add(&mut st.prefill, s); + } +} + +/// What a prompt's feed hands back after its last token. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Head { + /// The logits (`[vocab]`): the reply's first token is drawn from them on the host. + Logits(Vec), + /// The graph's greedy token (DRA-87: the chip's argmax, no logits read back). + Token(u32), +} + +/// What a session feeds a prompt into: the model, or a recording fake in the tests. +pub(crate) trait PromptFeed { + fn is_moe(&self) -> bool; + /// One decode step: the graph's greedy token after it. + fn step_token(&mut self, t: u32) -> Result; + /// The rows before the snapshot point, for their state only ([`Qwen38Omega::prefill_state`]). + fn feed_state(&mut self, tokens: &[u32], chunk: usize) -> Result; + /// At least [`q::GDN_PF_MIN_T`] tokens with the head ([`Qwen38Omega::prefill`]): the logits. + fn feed_head( + &mut self, + tokens: &[u32], + chunk: usize, + ) -> Result<(Vec, PrefillStats), String>; + /// As [`Self::feed_head`], the greedy token instead of the logits + /// ([`Qwen38Omega::prefill_token`]). + fn feed_head_token( + &mut self, + tokens: &[u32], + chunk: usize, + ) -> Result<(u32, PrefillStats), String>; + fn last_logits(&mut self) -> Result, String>; +} + +impl PromptFeed for Qwen38Omega { + fn is_moe(&self) -> bool { + Qwen38Omega::is_moe(self) + } + + fn step_token(&mut self, t: u32) -> Result { + self.step(t).map(|(next, _)| next) + } + + fn feed_state(&mut self, tokens: &[u32], chunk: usize) -> Result { + self.prefill_state(tokens, chunk) + } + + fn feed_head( + &mut self, + tokens: &[u32], + chunk: usize, + ) -> Result<(Vec, PrefillStats), String> { + self.prefill(tokens, chunk) + .map(|(_, logits, s)| (logits, s)) + } + + fn feed_head_token( + &mut self, + tokens: &[u32], + chunk: usize, + ) -> Result<(u32, PrefillStats), String> { + self.prefill_token(tokens, chunk) + } + + fn last_logits(&mut self) -> Result, String> { + self.logits() + } +} + +/// Feeds `prompt[from..]` into a state holding `prompt[..from]`: the rows before the snapshot point +/// without the head, then `snap(m, k)` at that point (its ns, if it took one), then the rest with +/// the head. Returns the logits after the last token, or with `want_token` the graph's greedy +/// token after it. +fn feed_prompt( + m: &mut M, + prompt: &[u32], + from: usize, + chunk: usize, + want_token: bool, + st: &mut FeedStats, + mut snap: impl FnMut(&mut M, usize) -> Result, String>, +) -> Result { + let mut at = from; + // The snapshot point: the last turn header not yet inside the reused prefix. + if let Some(k) = snapshot_point(prompt, from) { + feed_rows(m, &prompt[from..k], chunk, st)?; + at = k; + if let Some(t) = snap(m, k)? { + st.snapshot_ns = t; + } + } + feed_last(m, &prompt[at..], chunk, want_token, st) +} + +/// Feeds `tokens` without the head (no residual read back). +fn feed_rows( + m: &mut M, + tokens: &[u32], + chunk: usize, + st: &mut FeedStats, +) -> Result<(), String> { + if rows_by_steps(tokens.len(), m.is_moe()) { + for &t in tokens { + m.step_token(t)?; + } + st.stepped += tokens.len(); + } else { + let s = m.feed_state(tokens, chunk)?; + count(st, &s); + } + Ok(()) +} + +/// Feeds `tokens` (at least one) and returns the logits after the last, or with `want_token` the +/// graph's greedy token after it (no logits read back). +fn feed_last( + m: &mut M, + tokens: &[u32], + chunk: usize, + want_token: bool, + st: &mut FeedStats, +) -> Result { + if tokens.is_empty() { + return Err("qwen38 session: nothing to feed".into()); + } + if tokens.len() >= q::GDN_PF_MIN_T { + let (head, s) = if want_token { + let (t, s) = m.feed_head_token(tokens, chunk)?; + (Head::Token(t), s) + } else { + let (logits, s) = m.feed_head(tokens, chunk)?; + (Head::Logits(logits), s) + }; + count(st, &s); + return Ok(head); + } + let mut next = 0; + for &t in tokens { + next = m.step_token(t)?; + } + st.stepped += tokens.len(); + if want_token { + Ok(Head::Token(next)) + } else { + m.last_logits().map(Head::Logits) + } +} + /// The resident model plus the token record of its live state and of its snapshot. #[derive(Debug)] pub struct Qwen38Session { @@ -163,14 +339,42 @@ impl Qwen38Session { /// Feeds `prompt` (reusing what [`plan_reuse`] allows) and returns the logits after its last /// token. On any error the live state is dropped (the snapshot, a host copy, stays valid). pub fn start(&mut self, prompt: &[u32]) -> Result<(Vec, FeedStats), String> { - let r = self.start_inner(prompt); + match self.start_head(prompt, false)? { + (Head::Logits(logits), st) => Ok((logits, st)), + (Head::Token(_), _) => { + Err("qwen38 session: a token where the logits were asked".into()) + } + } + } + + /// [`Self::start`] for a greedy reply (DRA-87): the graph's greedy token after the prompt's + /// last token (on the 35B the chip's argmax of the head, the host rule: the largest logit, + /// the first index on a tie) instead of its logits, so no logits are read back and no host + /// argmax runs for the reply's first token. + pub fn start_greedy(&mut self, prompt: &[u32]) -> Result<(u32, FeedStats), String> { + match self.start_head(prompt, true)? { + (Head::Token(t), st) => Ok((t, st)), + (Head::Logits(_), _) => Err("qwen38 session: logits where the token was asked".into()), + } + } + + fn start_head( + &mut self, + prompt: &[u32], + want_token: bool, + ) -> Result<(Head, FeedStats), String> { + let r = self.start_inner(prompt, want_token); if r.is_err() { self.history.clear(); } r } - fn start_inner(&mut self, prompt: &[u32]) -> Result<(Vec, FeedStats), String> { + fn start_inner( + &mut self, + prompt: &[u32], + want_token: bool, + ) -> Result<(Head, FeedStats), String> { let t0 = Instant::now(); if prompt.is_empty() { return Err("qwen38 session: empty prompt".into()); @@ -203,60 +407,28 @@ impl Qwen38Session { } let from = self.history.len(); st.fed = prompt.len() - from; - // The snapshot point: the last turn header not yet inside the reused prefix. - if let Some(k) = prompt - .iter() - .rposition(|&t| t == IM_START) - .filter(|&k| k >= from) - { - self.feed_rows(&prompt[from..k], &mut st)?; - if self.snap_tokens.as_deref() != Some(&prompt[..k]) && k > 0 { + let (snap, snap_tokens) = (&mut self.snap, &mut self.snap_tokens); + let head = feed_prompt( + &mut self.model, + prompt, + from, + self.chunk, + want_token, + &mut st, + |m, k| { + if k == 0 || snap_tokens.as_deref() == Some(&prompt[..k]) { + return Ok(None); + } let t = Instant::now(); - self.snap_tokens = None; - self.model.snapshot(&mut self.snap)?; - self.snap_tokens = Some(prompt[..k].to_vec()); - st.snapshot_ns = ns(t); - } - } - let rest = &prompt[self.history.len()..]; - let logits = self.feed_last(rest, &mut st)?; + *snap_tokens = None; + m.snapshot(snap)?; + *snap_tokens = Some(prompt[..k].to_vec()); + Ok(Some(ns(t))) + }, + )?; + self.history.extend_from_slice(&prompt[from..]); st.wall_ns = ns(t0); - Ok((logits, st)) - } - - /// Feeds `tokens` without the head (the residual rows are dropped). - fn feed_rows(&mut self, tokens: &[u32], st: &mut FeedStats) -> Result<(), String> { - if tokens.len() >= q::GDN_PF_MIN_T { - let (_, s) = self.model.prefill_rows(tokens, self.chunk, false)?; - add(&mut st.prefill, &s); - } else { - for &t in tokens { - self.model.step(t)?; - } - st.stepped += tokens.len(); - } - self.history.extend_from_slice(tokens); - Ok(()) - } - - /// Feeds `tokens` (at least one) and returns the logits after the last. - fn feed_last(&mut self, tokens: &[u32], st: &mut FeedStats) -> Result, String> { - if tokens.is_empty() { - return Err("qwen38 session: nothing to feed".into()); - } - let logits = if tokens.len() >= q::GDN_PF_MIN_T { - let (_, logits, s) = self.model.prefill(tokens, self.chunk)?; - add(&mut st.prefill, &s); - logits - } else { - for &t in tokens { - self.model.step(t)?; - } - st.stepped += tokens.len(); - self.model.logits()? - }; - self.history.extend_from_slice(tokens); - Ok(logits) + Ok((head, st)) } /// Feeds one reply token through the decode graph without reading the logits: the graph's @@ -298,6 +470,7 @@ impl Qwen38Session { #[cfg(test)] mod tests { use super::*; + use crate::qwen38_omega::prefill::{chip_argmax_model, q36_chunk_walk, q36_state, Q36Feed}; #[test] fn reuse_takes_the_longest_strict_prefix() { @@ -330,4 +503,338 @@ mod tests { Reuse::Snapshot(2) ); } + + /// A rendered single-turn prompt of `len` tokens whose answer header (`<|im_start|>` + /// assistant ... , 7 tokens with thinking off) closes it, plus an earlier user header at 0. + fn rendered(len: usize) -> Vec { + let mut p: Vec = (0..len as u32).map(|i| 1000 + i).collect(); + p[0] = IM_START; + if len > 7 { + p[len - 7] = IM_START; + } + p + } + + /// DRA-65: where start_inner splits a prompt at the lengths the chunk tests use: the rows + /// before the answer header (fed without the head, as 35B prefill chunks at any length), + /// the snapshot at the header, the header and what follows fed with the head. + #[test] + fn snapshot_point_splits_rows_and_last_piece() { + let cap = q::q36::PREFILL_MAX_ROWS; + for len in [1, cap - 1, cap, cap + 1, 2048, 8192] { + let p = rendered(len); + let k = snapshot_point(&p, 0).expect("a header"); + let want = if len > 7 { len - 7 } else { 0 }; + assert_eq!(k, want, "len {len}"); + assert_eq!(p[k], IM_START); + // The rows piece and the last piece cover the prompt once, the last starts at the header. + let (rows, last) = p.split_at(k); + assert_eq!(rows.len() + last.len(), len); + assert!(!last.is_empty() && last[0] == IM_START); + // The 35B never steps the rows piece; its chunks cover it. + assert!(!rows_by_steps(rows.len(), true)); + let c = super::super::prefill::q36_chunk_lengths(rows.len(), cap); + assert_eq!(c.iter().sum::(), rows.len(), "len {len}"); + } + // 2048: 2041 rows = 15 chunks of 128 + 121; the answer header's 7 tokens go in with the head. + let c = super::super::prefill::q36_chunk_lengths(2048 - 7, cap); + assert_eq!((c.len(), c[15]), (16, 121)); + } + + #[test] + fn snapshot_point_respects_the_reused_prefix() { + // Turn 2: the reused snapshot ends at turn 1's answer header (k1); the new answer header + // is past it, so the rows between are fed and the snapshot moves there. + let mut p = rendered(40); + let k1 = 33; + p.extend([2000, 2001, 2002, IM_START, 2003, 2004]); + assert_eq!(snapshot_point(&p, k1), Some(43)); + // The header right at the reused end: an empty rows piece, the same snapshot. + assert_eq!(snapshot_point(&p, 43), Some(43)); + // A live state past the last header: no snapshot, the rest goes in with the head. + assert_eq!(snapshot_point(&p, 44), None); + // No header at all. + assert_eq!(snapshot_point(&[5, 6, 7], 0), None); + } + + #[test] + fn only_short_27b_row_pieces_are_stepped() { + for len in [0, 1, 2, 3, 127, 128, 129, 8192] { + assert!(!rows_by_steps(len, true), "35B len {len}"); + } + assert!(rows_by_steps(2, false)); + assert!(!rows_by_steps(q::GDN_PF_MIN_T, false)); + } + + /// Records every token the feed path hands over, with the position it lands at and how + /// (`s` decode step, `r` state chunk, `h` chunk with the head), through the same routing as + /// the 35B: [`q36_state`] for the rows, [`q36_chunk_walk`] for every chunk run. Its "model": + /// the logits after the last token fed are a function of every (position, token) fed so far, + /// over 97 tokens and 5 levels (so the largest logit is always tied); the graph's greedy + /// token is the CPU model of the chip's two-stage ARGMAX over them ([`chip_argmax_model`]). + struct Fake { + c: usize, + pos: usize, + fed: Vec<(usize, u32, char)>, + chunks: Vec, + hash: u64, + /// Head reads: `L` logits after a head chunk, `T` token after a head chunk, `l` the last + /// step's logits. + heads: Vec, + } + + const FAKE_VOCAB: usize = 97; + + impl Fake { + fn new(c: usize, pos: usize) -> Self { + Self { + c, + pos, + fed: Vec::new(), + chunks: Vec::new(), + hash: 0x5eed, + heads: Vec::new(), + } + } + + fn take(&mut self, tokens: &[u32], pos: usize, how: char) -> Result<(), String> { + if pos != self.pos { + return Err(format!("fed at {pos}, the state is at {}", self.pos)); + } + for &t in tokens { + self.fed.push((self.pos, t, how)); + self.hash = (self.hash ^ ((self.pos as u64) << 32 | u64::from(t))) + .wrapping_mul(0x9e37_79b9_7f4a_7c15) + .rotate_left(29); + self.pos += 1; + } + Ok(()) + } + + fn walk(&mut self, tokens: &[u32], chunk: usize, how: char) -> Result { + let pos0 = self.pos; + let (n, end) = q36_chunk_walk(tokens, chunk, pos0, |c, pos, _| { + self.chunks.push(c.len()); + self.take(c, pos, how) + })?; + assert_eq!(end, self.pos); + Ok(n) + } + + fn logits(&self) -> Vec { + (0..FAKE_VOCAB as u64) + .map(|i| { + let x = (self.hash ^ i.wrapping_mul(0xff51_afd7_ed55_8ccd)) + .wrapping_mul(0xc4ce_b9fe_1a85_ec53); + ((x >> 59) % 5) as f32 + }) + .collect() + } + + fn chip_token(&self) -> u32 { + chip_argmax_model(&self.logits(), 8) + } + + fn head(&mut self, tokens: &[u32]) -> Result { + let mut chunks = 0; + if self.c == 0 { + for &t in tokens { + self.q36_step(t)?; + } + } else { + let c = self.c; + chunks = self.walk(tokens, c, 'h')?; + } + Ok(PrefillStats { + tokens: tokens.len(), + chunks, + ..Default::default() + }) + } + } + + impl Q36Feed for Fake { + fn q36_step(&mut self, t: u32) -> Result<(), String> { + let p = self.pos; + self.take(&[t], p, 's') + } + + fn q36_chunks(&mut self, tokens: &[u32], chunk: usize) -> Result { + self.walk(tokens, chunk, 'r') + } + } + + impl PromptFeed for Fake { + fn is_moe(&self) -> bool { + true + } + + fn step_token(&mut self, t: u32) -> Result { + self.q36_step(t)?; + Ok(self.chip_token()) + } + + fn feed_state(&mut self, tokens: &[u32], _chunk: usize) -> Result { + let c = self.c; + let chunks = q36_state(self, tokens, c)?; + Ok(PrefillStats { + tokens: tokens.len(), + chunks, + ..Default::default() + }) + } + + fn feed_head( + &mut self, + tokens: &[u32], + _chunk: usize, + ) -> Result<(Vec, PrefillStats), String> { + let s = self.head(tokens)?; + self.heads.push('L'); + Ok((self.logits(), s)) + } + + fn feed_head_token( + &mut self, + tokens: &[u32], + _chunk: usize, + ) -> Result<(u32, PrefillStats), String> { + let s = self.head(tokens)?; + self.heads.push('T'); + Ok((self.chip_token(), s)) + } + + fn last_logits(&mut self) -> Result, String> { + self.heads.push('l'); + Ok(self.logits()) + } + } + + /// DRA-65: through the session's feed path every prompt token past the reused prefix is fed + /// exactly once, in order, at its own position, across chunk boundaries and from a cached + /// prefix that ends mid-chunk; the snapshot is taken right after the rows; with chunking on + /// no row is stepped, with `AIEN_Q36_PREFILL_CHUNK=0` every token is. + #[test] + fn every_prompt_token_is_fed_once_in_order() { + let cap = q::q36::PREFILL_MAX_ROWS; + for c in [cap, 0] { + for len in [1, cap - 1, cap, cap + 1, 2 * cap + 3] { + // 61: a cached prefix ending mid-chunk; len - 3: a live state past the header. + for (from, want_token) in [0, 61, len.saturating_sub(3)] + .into_iter() + .flat_map(|f| [(f, false), (f, true)]) + { + if from >= len { + continue; + } + let p = rendered(len); + let mut f = Fake::new(c, from); + let mut st = FeedStats::default(); + let mut snaps = Vec::new(); + let r = feed_prompt(&mut f, &p, from, 512, want_token, &mut st, |m, k| { + snaps.push((k, m.pos)); + Ok(None) + }); + let at = format!("c {c} len {len} from {from} token {want_token}"); + r.unwrap_or_else(|e| panic!("{at}: {e}")); + let got: Vec<(usize, u32)> = f.fed.iter().map(|&(i, t, _)| (i, t)).collect(); + let want: Vec<(usize, u32)> = (from..len).map(|i| (i, p[i])).collect(); + assert_eq!(got, want, "{at}"); + let k = snapshot_point(&p, from); + assert_eq!( + snaps, + k.map(|k| (k, k)).into_iter().collect::>(), + "{at}" + ); + assert!(f.chunks.iter().all(|&m| m >= 1 && m <= cap), "{at}"); + if c == 0 { + assert!(f.fed.iter().all(|&(_, _, how)| how == 's'), "{at}"); + assert_eq!(st.stepped, len - from, "{at}"); + } else if let Some(k) = k { + let stepped_row = f.fed.iter().any(|&(i, _, how)| i < k && how == 's'); + assert!(!stepped_row, "{at}"); + } + } + } + } + } + + /// Feeds `p[from..]` into a fresh fake: what came back, the stats and the fake. + fn feed(p: &[u32], from: usize, c: usize, want_token: bool) -> (Head, FeedStats, Fake) { + let mut f = Fake::new(c, from); + let mut st = FeedStats::default(); + let h = feed_prompt(&mut f, p, from, 512, want_token, &mut st, |_, _| Ok(None)) + .unwrap_or_else(|e| panic!("from {from} c {c} token {want_token}: {e}")); + (h, st, f) + } + + /// DRA-87, the single door: `start_greedy`'s feed (`want_token`) gives as the reply's first + /// token exactly what `start`'s logits give the host's greedy draw (`sample_argmax`, the + /// first index on a tie; the fake's largest logit is always tied), with the same tokens fed + /// the same way and the same stats, and reads no logits: the head chunk returns its token + /// (`T`, never `L`), a short tail returns its last step's token (never `l`). `start` (the + /// flag off) is unchanged: it reads the logits once, exactly where it did. + #[test] + fn greedy_first_token_is_the_host_argmax_without_logits() { + let cap = q::q36::PREFILL_MAX_ROWS; + let min = q::GDN_PF_MIN_T; + let headerless = + |len: usize| -> Vec { (0..len as u32).map(|i| 3000 + i * 7).collect() }; + let mut prompts: Vec<(String, Vec)> = Vec::new(); + for len in [ + 1, + 2, + min - 1, + min, + min + 1, + 40, + cap - 1, + cap, + cap + 1, + 2 * cap + 3, + ] { + prompts.push((format!("rendered {len}"), rendered(len))); + prompts.push((format!("headerless {len}"), headerless(len))); + } + let mut ties = 0; + for c in [cap, 0] { + for (name, p) in &prompts { + for from in [0, 61, p.len().saturating_sub(3)] { + if from >= p.len() { + continue; + } + let at = format!("{name} c {c} from {from}"); + let (off, st_off, f_off) = feed(p, from, c, false); + let (on, st_on, f_on) = feed(p, from, c, true); + let Head::Logits(logits) = off else { + panic!("{at}: start gave a token") + }; + let Head::Token(tok) = on else { + panic!("{at}: start_greedy gave logits") + }; + let host = crate::tensor::sample_argmax(&logits).0; + assert_eq!(tok, host, "{at}"); + let top = logits.iter().cloned().fold(f32::MIN, f32::max); + if logits.iter().filter(|&&x| x == top).count() > 1 { + ties += 1; + } + assert_eq!(f_on.fed, f_off.fed, "{at}"); + assert_eq!(f_on.chunks, f_off.chunks, "{at}"); + assert_eq!( + (st_on.stepped, &st_on.prefill), + (st_off.stepped, &st_off.prefill), + "{at}" + ); + assert!( + f_on.heads.iter().all(|&h| h == 'T'), + "{at}: {:?}", + f_on.heads + ); + assert_eq!(f_off.heads.len(), 1, "{at}: {:?}", f_off.heads); + assert_eq!(f_on.heads.len(), usize::from(f_off.heads[0] == 'L'), "{at}"); + } + } + } + assert!(ties > 0, "the cases must hold ties at the largest logit"); + } } diff --git a/crates/aien-serve-http/src/qwen36_batch.rs b/crates/aien-serve-http/src/qwen36_batch.rs index 476f138a..ae331a7c 100644 --- a/crates/aien-serve-http/src/qwen36_batch.rs +++ b/crates/aien-serve-http/src/qwen36_batch.rs @@ -36,8 +36,8 @@ use crate::engine::{ }; use crate::omega_engine::{GpuLock, GPU_LOCK_PATH}; use crate::qwen38_engine::{ - admit_load, is_moe_dir, rss_bytes, CHIP_GREEDY_ENV, KEEP_FREE, LOAD_LOCK_WAIT, PREFILL_CHUNK, - REQUEST_LOCK_WAIT, + admit_load, is_moe_dir, rss_bytes, FirstToken, CHIP_GREEDY_ENV, KEEP_FREE, LOAD_LOCK_WAIT, + PREFILL_CHUNK, REQUEST_LOCK_WAIT, }; use crate::sampling::SamplingObserver; @@ -446,6 +446,7 @@ impl Qwen36BatchDoor { REQUEST_LOCK_WAIT, per_beat, std::env::var(CHIP_GREEDY_ENV).as_deref() != Ok("0"), + FirstToken::from_env(), )?; door.slot_bytes_measured = measured; door.slot_bytes_on_paper = on_paper; @@ -461,6 +462,7 @@ impl Qwen36BatchDoor { lock_wait: Duration, prompt_per_beat: usize, chip_greedy: bool, + first_token: FirstToken, ) -> Result { let slots = model.row_count(); if slots == 0 { @@ -487,6 +489,7 @@ impl Qwen36BatchDoor { pf_chunk: env_usize("AIEN_Q36_PREFILL_CHUNK", Q36_PREFILL_CHUNK).min(Q36_PREFILL_CHUNK), pf_min: env_usize("AIEN_Q36_PREFILL_MIN", Q36_PREFILL_MIN).max(1), chip_greedy, + first_token, beat: 0, }; std::thread::Builder::new() @@ -681,6 +684,9 @@ struct Scheduler { pf_min: usize, /// Greedy replies take the graph's token (`AIEN_SERVE_CHIP_GREEDY=0` turns it off). chip_greedy: bool, + /// DRA-87: a greedy row's first token from the graph's argmax at the end of its prompt + /// (`AIEN_SERVE_CHIP_FIRST_TOKEN=1`): its last prompt feed reads no logits. + first_token: FirstToken, beat: u64, } @@ -807,7 +813,9 @@ impl Scheduler { continue; } let (from, end) = (a.fed, a.fed + n); - let logits = end == plen; + let last = end == plen; + let chip_first = last && a.chip_greedy && self.first_token.chip(); + let logits = last && !chip_first; let t = Instant::now(); let r = self .model @@ -829,6 +837,9 @@ impl Scheduler { if logits { a.logits = o.logits; } + if chip_first { + a.chip_next = Some(self.first_token.emit(o.token)); + } chunked[k] = true; } Err(e) => { @@ -874,7 +885,8 @@ impl Scheduler { feed.push(RowFeed { row: a.row, token: a.job.prompt[a.fed], - logits: a.fed + 1 == plen, + logits: a.fed + 1 == plen + && !(a.chip_greedy && self.first_token.chip()), }); who.push(k); tests.push(row_test(&a.job.test)); @@ -916,6 +928,9 @@ impl Scheduler { if !a.prefilling() { a.prefill_ms = a.t_admit.elapsed().as_millis() as u64; a.t_decode = Instant::now(); + if a.chip_greedy && self.first_token.chip() { + a.chip_next = Some(self.first_token.emit(o.token)); + } } } else { a.next = None; diff --git a/crates/aien-serve-http/src/qwen36_batch/tests.rs b/crates/aien-serve-http/src/qwen36_batch/tests.rs index ead5418f..b362ad55 100644 --- a/crates/aien-serve-http/src/qwen36_batch/tests.rs +++ b/crates/aien-serve-http/src/qwen36_batch/tests.rs @@ -24,6 +24,8 @@ struct Fake { fed: Arc, /// The rows each step fed, in order. log: StepLog, + /// Logits read back (feeds that asked for them). + reads: Arc, } impl Fake { @@ -36,6 +38,7 @@ impl Fake { steps: 0, fed: Arc::clone(&fed), log: Arc::new(Mutex::new(Vec::new())), + reads: Arc::new(AtomicUsize::new(0)), }, fed, ) @@ -84,6 +87,9 @@ impl RowStep for Fake { *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64); *pos += 1; self.fed.fetch_add(1, Ordering::SeqCst); + if f.logits { + self.reads.fetch_add(1, Ordering::SeqCst); + } let logits: Vec = (0..VOCAB) .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) .collect(); @@ -126,11 +132,75 @@ fn door_with( Duration::from_secs(5), per_beat, chip_greedy, + FirstToken::Host, ) .unwrap(); (d, fed) } +/// DRA-87: a chip-greedy door with `first` and its fake's count of logits read back. +fn first_door(first: FirstToken) -> (Qwen36BatchDoor, Arc) { + let (f, _) = Fake::new(2, None); + let reads = Arc::clone(&f.reads); + let d = + Qwen36BatchDoor::with_stepper(f, 4096, lock_file(), Duration::from_secs(5), 4, true, first) + .unwrap(); + (d, reads) +} + +/// DRA-87, the batch door: with the chip's first token every greedy reply (prompts both under +/// `Q36_PREFILL_MIN`, fed token by token, and chunked through `prefill_row`) is word for word +/// the host-first-token reply and the request alone, and reads no logits at all (today: one read, +/// the prompt's last); a sampled reply still reads the logits every token, the same words as +/// with the flag off. The mutant (the slices' red arm) changes token 0, so this test can fail. +#[test] +fn chip_first_token_matches_the_host_and_reads_no_logits() { + let (host, host_reads) = first_door(FirstToken::Host); + let (chip, chip_reads) = first_door(FirstToken::Chip); + let (bad, _) = first_door(FirstToken::ChipMutant); + let mut long = prompts()[3].0.clone(); + long.extend((0..150u32).map(|k| (k * 13 + 5) % VOCAB as u32)); + let mut cases: Vec<(Vec, usize)> = prompts(); + cases.push((long, 6)); + for (p, n) in &cases { + let (h0, c0) = ( + host_reads.load(Ordering::SeqCst), + chip_reads.load(Ordering::SeqCst), + ); + let (hw, _) = run(&host, p, &greedy(*n)); + let (cw, co) = run(&chip, p, &greedy(*n)); + assert_eq!(cw, hw, "len {}", p.len()); + assert_eq!(cw, alone(p, *n), "len {}", p.len()); + assert_eq!(host_reads.load(Ordering::SeqCst) - h0, 1, "len {}", p.len()); + assert_eq!(chip_reads.load(Ordering::SeqCst) - c0, 0, "len {}", p.len()); + let rec = co.sampling.expect("sampling record"); + assert_eq!(rec.greedy_tokens, cw.len(), "len {}", p.len()); + let (bw, _) = run(&bad, p, &greedy(*n)); + assert_ne!( + bw[0], + hw[0], + "the mutant must move token 0 (len {})", + p.len() + ); + let sampled = GenerateParams { + temperature: 0.8, + top_p: 0.9, + seed: 7, + ..greedy(*n) + }; + let c1 = chip_reads.load(Ordering::SeqCst); + let (hs, _) = run(&host, p, &sampled); + let (cs, _) = run(&chip, p, &sampled); + assert_eq!(cs, hs, "sampled, len {}", p.len()); + assert_eq!( + chip_reads.load(Ordering::SeqCst) - c1, + *n, + "sampled, len {}", + p.len() + ); + } +} + fn greedy(n: usize) -> GenerateParams { GenerateParams { max_new_tokens: n, @@ -364,6 +434,7 @@ fn switched_door(rows: usize) -> Qwen36BatchDoor { Duration::from_secs(5), 4, true, + FirstToken::Host, ) .unwrap() } @@ -555,8 +626,16 @@ type StepLog = Arc>>>; fn logged_door(rows: usize) -> (Arc, StepLog) { let (f, _) = Fake::new(rows, None); let log = Arc::clone(&f.log); - let d = Qwen36BatchDoor::with_stepper(f, 4096, lock_file(), Duration::from_secs(5), 1, true) - .unwrap(); + let d = Qwen36BatchDoor::with_stepper( + f, + 4096, + lock_file(), + Duration::from_secs(5), + 1, + true, + FirstToken::Host, + ) + .unwrap(); (Arc::new(d), log) } @@ -776,8 +855,16 @@ fn a_reader_that_stops_reading_is_dropped_and_the_others_finish() { let (f, _) = Fake::new(2, None); let lock = lock_file(); let d = Arc::new( - Qwen36BatchDoor::with_stepper(f, 4096, lock.clone(), Duration::from_secs(5), 1, true) - .unwrap(), + Qwen36BatchDoor::with_stepper( + f, + 4096, + lock.clone(), + Duration::from_secs(5), + 1, + true, + FirstToken::Host, + ) + .unwrap(), ); let (release, hold) = mpsc::channel::<()>(); let stalled = { diff --git a/crates/aien-serve-http/src/qwen38_engine.rs b/crates/aien-serve-http/src/qwen38_engine.rs index d20bf6de..14d54426 100644 --- a/crates/aien-serve-http/src/qwen38_engine.rs +++ b/crates/aien-serve-http/src/qwen38_engine.rs @@ -51,6 +51,53 @@ pub const KEEP_FREE: u64 = 8 << 30; pub const Q36_OVERLAP_AB_ENV: &str = "AIEN_OMEGA_Q36_OVERLAP_AB"; /// 0: greedy replies read the logits and take the host argmax every token (L356: the chip's token otherwise). pub const CHIP_GREEDY_ENV: &str = "AIEN_SERVE_CHIP_GREEDY"; +/// DRA-87 (default off; 1 = on): a greedy reply that takes the chip's token (above) takes its +/// FIRST token from the chip too, the graph's argmax at the end of prefill, instead of the +/// prompt's last logits (993,280 B read back on the 35B) and a host argmax. Same rule as the +/// host's (the largest logit, the lowest index on a tie). Both doors read it once, at load. +pub const CHIP_FIRST_TOKEN_ENV: &str = "AIEN_SERVE_CHIP_FIRST_TOKEN"; +/// Test-only red arm for the DRA-87 chip slices (with [`CHIP_FIRST_TOKEN_ENV`]=1): the first +/// token is a neighbour of the chip's (one less; 1 for 0), so the golden token-0 gate must go +/// red. Never set in serving. +pub const FIRST_TOKEN_MUTANT_ENV: &str = "AIEN_Q36_TEST_FIRST_TOKEN_MUTANT"; + +/// Where a greedy reply's first token comes from (DRA-87). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FirstToken { + /// The prompt's last logits read back, the host's argmax (today). + Host, + /// The graph's argmax at the end of prefill. + Chip, + /// [`Self::Chip`] moved to a neighbouring token (one less; 1 for 0): the slices' red arm and + /// the tests' mutant. + ChipMutant, +} + +impl FirstToken { + /// [`CHIP_FIRST_TOKEN_ENV`] and [`FIRST_TOKEN_MUTANT_ENV`]. + pub fn from_env() -> Self { + match ( + std::env::var(CHIP_FIRST_TOKEN_ENV).as_deref() == Ok("1"), + std::env::var(FIRST_TOKEN_MUTANT_ENV).as_deref() == Ok("1"), + ) { + (false, _) => Self::Host, + (true, false) => Self::Chip, + (true, true) => Self::ChipMutant, + } + } + + pub fn chip(self) -> bool { + self != Self::Host + } + + /// The token emitted for the chip's first token `t`. + pub fn emit(self, t: u32) -> u32 { + match self { + Self::ChipMutant => t.checked_sub(1).unwrap_or(1), + _ => t, + } + } +} fn model_type(dir: &Path) -> Option { std::fs::read_to_string(dir.join("config.json")) @@ -124,6 +171,8 @@ pub struct Qwen38Door { max_context: usize, lock_path: PathBuf, lock_wait: Duration, + /// [`CHIP_FIRST_TOKEN_ENV`], read at load. + first_token: FirstToken, } impl Qwen38Door { @@ -181,8 +230,9 @@ impl Qwen38Door { "aien-serve-http: qwen38: {Q36_OVERLAP_AB_ENV}={}", std::env::var(Q36_OVERLAP_AB_ENV).unwrap_or_default() ); + let first_token = FirstToken::from_env(); eprintln!( - "aien-serve-http: qwen38 engine ready in {:.1} s: context {max_context} tokens, weights {:.2} GB resident, KV {:.2} GB, rss {:.2} GB, prefill chunk {PREFILL_CHUNK}, spin_us {:?}", + "aien-serve-http: qwen38 engine ready in {:.1} s: context {max_context} tokens, weights {:.2} GB resident, KV {:.2} GB, rss {:.2} GB, prefill chunk {PREFILL_CHUNK}, spin_us {:?}, first token {first_token:?}", t0.elapsed().as_secs_f64(), model.weight_bytes() as f64 / 1e9, model.kv_bytes() as f64 / 1e9, @@ -194,6 +244,7 @@ impl Qwen38Door { max_context, lock_path: PathBuf::from(GPU_LOCK_PATH), lock_wait: REQUEST_LOCK_WAIT, + first_token, }) } } @@ -233,17 +284,25 @@ impl Engine for Qwen38Door { // Greedy requests take the exact two-pass head (the same tokens, the logits read back are // -inf off its candidates); sampled ones need every logit. s.model_mut().set_exact_head_on(p.temperature <= 0.001); - let t0 = Instant::now(); - let (mut logits, fs) = s.start(prompt).map_err(EngineError::Failed)?; - let prefill_ms = t0.elapsed().as_millis() as u64; - let t1 = Instant::now(); let mut observer = SamplingObserver::new(p); // L356: a greedy reply takes the decode graph's own token (argmax on the chip, the // host rule) and skips the logits copy and host argmax per token. The first token comes - // from the prefill logits as before. AIEN_SERVE_CHIP_GREEDY=0: the host path throughout. + // from the prefill logits, or with AIEN_SERVE_CHIP_FIRST_TOKEN=1 (DRA-87) from the + // graph's argmax at the end of prefill (no logits read back). AIEN_SERVE_CHIP_GREEDY=0: + // the host path throughout. let chip_greedy = observer.is_greedy() && std::env::var(CHIP_GREEDY_ENV).as_deref() != Ok("0"); - let mut chip_next: Option = None; + let chip_first = chip_greedy && self.first_token.chip(); + let t0 = Instant::now(); + let (mut logits, mut chip_next, fs) = if chip_first { + let (t, fs) = s.start_greedy(prompt).map_err(EngineError::Failed)?; + (Vec::new(), Some(self.first_token.emit(t)), fs) + } else { + let (logits, fs) = s.start(prompt).map_err(EngineError::Failed)?; + (logits, None, fs) + }; + let prefill_ms = t0.elapsed().as_millis() as u64; + let t1 = Instant::now(); let (mut emitted, mut chip_ns) = (0usize, 0u64); let finish = loop { if emitted >= p.max_new_tokens || prompt.len() + emitted >= self.max_context { @@ -284,7 +343,7 @@ impl Engine for Qwen38Door { drop(lock); let pf = &fs.prefill; eprintln!( - "aien-serve-http: qwen38: lock wait {lock_wait_ms} ms, prompt {} tok, reuse {:?} ({reused} tok), fed {} ({} stepped), prefill {prefill_ms} ms (gemm chip {} ms, gdn chip {} ms, attn chip {} ms, host {} ms, restore {} ms, snapshot {} ms), decode {emitted} tok in {decode_ms} ms, graph chip {:.1} ms/token, wall {:.1} ms/token, chip greedy {chip_greedy}", + "aien-serve-http: qwen38: lock wait {lock_wait_ms} ms, prompt {} tok, reuse {:?} ({reused} tok), fed {} ({} stepped), prefill {prefill_ms} ms (gemm chip {} ms, gdn chip {} ms, attn chip {} ms, host {} ms, restore {} ms, snapshot {} ms), decode {emitted} tok in {decode_ms} ms, graph chip {:.1} ms/token, wall {:.1} ms/token, chip greedy {chip_greedy}, chip first token {chip_first}", prompt.len(), fs.reuse.unwrap_or(Reuse::Cold), fs.fed, diff --git a/evidence/dra65-prefill-20261031/README.md b/evidence/dra65-prefill-20261031/README.md new file mode 100644 index 00000000..a39da3ea --- /dev/null +++ b/evidence/dra65-prefill-20261031/README.md @@ -0,0 +1,190 @@ +# DRA-65: chunked prefill through the door (2026-10-31) + +Refs aien-dev/aien-sovereign-core-mv#856, Linear DRA-65. + +## Which door serves, and what still read prompts one token at a time (source, origin/main d3dec0eb) + +- Production 35B (last start 2026-10-30T18:49:06Z, `start-35b-batch.sh`, bin-19173f9e, `--batch-slots 8`) is the + **batch door**: `main.rs` sends `--batch-slots > 0` with a MoE dir to `Qwen36BatchDoor::load`. It already reads + prompts in chip chunks of 128 (L369; `qwen36_batch.rs` chunk block, BUILD.txt "L369 prefill (chunks of 128)"). + The Linear premise "the door reads prompts one token per beat" is **stale for the batch door**. What it still + steps token by token: a stretch shorter than `AIEN_Q36_PREFILL_MIN` (16) before the snapshot point, and the + answer header after the snapshot (~7 tokens), fed per token in the same beat. +- The **single door** (`Qwen38Door`, `--batch-slots 0`) read nearly the whole prompt one token per decode step: + `session.rs` feed_rows -> `prefill_rows` MoE branch -> `self.step(t)` per token (chunk ignored). Only the last + piece (`feed_last` -> `prefill`) was chunked. + +## Change (IMPLEMENTED) + +- `prefill.rs`: `Qwen38Omega::prefill_state(tokens, chunk)` feeds tokens for their state only; on the 35B as chip + prefill chunks of `AIEN_Q36_PREFILL_CHUNK` (default 128) at any length from 1. `AIEN_Q36_PREFILL_CHUNK=0` makes + the new binary feed EVERY prompt token through the decode graph, the answer-header piece included; the base + binary's default already chunked that last piece when it was >= 3 tokens, so the CHUNK=0 arm is slower than the + old production single door by about one header (`N[7*0.0201]` = 0.14 s), not equal to it. `prefill_rows` on + the 35B now chunks all but the last token and steps the last one for its + residual (the chip prefill keeps its rows in `pf.x`, not the decode graph's x, so `residual()` is only valid + after a step); `all=true` still steps every token (its rows are not exported by the chip prefill). + `q36_chunk_lengths` is the one chunk plan `prefill_moe_head` iterates. +- `session.rs`: `feed_rows` uses `prefill_state` (35B: never stepped); `snapshot_point` and `rows_by_steps` are + the pure split rules start_inner uses; off-mode tokens are counted in `FeedStats::stepped`. +- Signatures of `Qwen38Session::{start, advance, advance_greedy}` and `RowStep::{step_rows, prefill_row}` + unchanged. Batch door code unchanged (see "Next lever"). + +## 32-prompt set (pinned) + +`set32.json` = the merge train's concurrent-32 prompts (`evidence/q36-batch-20261021/prompts.txt`, max_tokens +`i==0 ? 24 : 8 + (i*7) % 41`), goldens = reference build **bin-5b726818** ("plain correct path: prompt fed token +by token, no speed levers"), each request alone, recorded 2026-10-21 (before this change). Prompt 0's ids equal +the host-oracle golden `evidence/q36-host-20261020/gen-chat-max-24.json`. `long-goldens.json` adds the 365 / +2486 / 8210-token prompts and **turn 2** of long-2048 (2528 tokens, three messages, `turn2.messages.json`) with +goldens from bin-16b0e6f8 (prompts token by token). The script sends turn 2 right after long-2048, so the door +restores the snapshot it took at long-2048's answer header after a chunked prefill (`plan_reuse` -> +`Reuse::Snapshot`). 36 cases in all. + +Provenance: both files name `source_dir` (the merge-train store); every case carries `ref_sha256` of its source +golden (`alone/.json`, `l369-long/.json`), and `long-goldens.json` carries the store's `done` receipt +text and sha256 (it names bin-16b0e6f8). `SHA256SUMS` pins every committed input; the script refuses to run if +one changed. + +Judge: exact id identity (the door returns no logit margins, so the 0.1-logit band cannot be judged through it). +Per case SAME / DIFF (a flip inside the common length, or more ids than the golden) / SHORT (a strict prefix: no +flip shown) / NO_IDS (HTTP error, missing or empty ids). Red PASS needs a DIFF and no SHORT/NO_IDS (else +INCONCLUSIVE); green PASS needs 36 SAME (NO_IDS -> INCONCLUSIVE, else FAIL). Green refuses to run without two red +PASS receipts with distinct labels for the same server binary sha256. + +## Host evidence (EXERCISED on host, not chip) + +`nice -n 19 taskset -c 0-9 cargo test -p aien-inference-abi --lib qwen38_omega`: 10 passed (chunk boundaries at +1, 127, 128, 129, 2048, 8192 and 8210; env switch 0/default/cap/129/garbage; snapshot point and rows/last split at +the same lengths and on turn 2; 35B rows never stepped; the feed path below). Negative control: `q36_chunk_lengths` +mutated to drop a remainder of 1 -> `q36_chunks_at_the_boundaries` FAILED, then restored. + +Feed path: `start_inner`'s feed is `session::feed_prompt` -> `feed_rows` / `feed_last` over the `PromptFeed` +trait, and the 35B's state feed is `prefill::q36_state` + `q36_chunk_walk` (the loop `prefill_moe_head` runs on +the chip) over `Q36Feed`; the model implements both. `every_prompt_token_is_fed_once_in_order` drives that same +code with a fake that records (position, token id, step/row chunk/head chunk) and refuses a chunk at a position +other than its own: lengths 1, 127, 128, 129, 259 (2*128+3), cached prefix 0, 61 (ends mid-chunk) and len-3 +(past the header), chunk 128 and 0. It asserts each token of `prompt[from..]` fed exactly once, in order, at its +position; the snapshot taken at the header right after the rows; chunks within 1..=128; no row stepped with +chunking, every token stepped with 0. Review Rev862's mutations, each applied alone and reverted: M4 +(`q36_state` drops the last row token) -> FAILED; M5 (`feed_rows` skips the first row token) -> FAILED; restored +-> 10 passed. What stays chip-only: the wrappers (`prefill_state`'s env read, the embed + `g.prefill` per chunk), +hence the window's prefill-only red arm (step 2). + +Script probes against a mock door (`/tmp/dra65mock/mock2.py`, `SPARK_WINDOW=w-test-2`): red with one turn-2 id +changed PASS rc 0; red on exact goldens FAIL rc 1; red on empty ids, short ids or HTTP 500 INCONCLUSIVE rc 2; green +with 0 or 1 red receipt, or with receipts of another binary sha, refused rc 2; green with two receipts: exact PASS +rc 0, one id changed FAIL rc 1, empty ids INCONCLUSIVE rc 2; time: exact RECORDED rc 0 (6/6 runs ok), HTTP 500 and +missing usage INCONCLUSIVE rc 2; no `SPARK_WINDOW` NOT_RUN rc 3. Every `golden.jsonl` / `time.jsonl` line and +receipt carried `window: w-test-2` and the binary sha. `run` guard, with `DRA65_TEST_LOCK` pointing at a scratch +lock (it never reaches the chip): no `SPARK_WINDOW` rc 3; lock held by another process rc 3 ("held by another +process"); `DRA65_LOCKED` spoofed without holding the lock rc 3 ("held by pid(s) ..., none an ancestor"); lock +free: taken, its flock(1) holder found among the script's ancestors, then rc 3 as the test lock demands. + +`run` end to end on host (review Rev862b; `nice -n 19 taskset -c 0-9 bash +evidence/dra65-prefill-20261031/hosttest/runtests.sh`, scratch lock under `/tmp/dra65-hosttest`, +`DRA65_TEST_PORT=18978`, BIN = `hosttest/fake-serve.sh`, a shell mock door that execs `hosttest/mock2.py`; test +mode (`DRA65_TEST_LOCK`) refuses an ELF BIN and skips the chip, model and live-port checks; board lines go to +`OUT/board.log`). L1 `run BIN OUT 1 2 3 4 5` started +under `taskset -c 5`: rc 0, steps 1-2 red PASS (35/36 same), steps 3-5 green PASS (36/36); every server pid == +its sid, 0 fds on the lock, `Cpus_allowed_list 0-9`; turn 2 matched `reuse Snapshot(2479) (2479 tok)`; lock free +and no process left after. Green step 4 alone on that OUT: rc 0 (reds from step receipts). `4 1 2` on an empty +OUT: NOT_RUN rc 3. Golden receipts without step receipts: `run 4` NOT_RUN rc 3, the probe itself refused rc 2. +Green probe without `DRA65_SERVER_LOG`: turn 2 NO_SNAP, FAIL rc 1; door that never logs the restore: FAIL rc 1. +Lease 45 s with a 30 s/request door: step INCONCLUSIVE rc 2 at 46 s ("probe stopped at the lease deadline"), +`lease_expired: true`, lock free. `expired` created mid-step: INCONCLUSIVE rc 2. SIGKILL of the run shell +mid-step: the watchdog TERMed the server group, server gone, lock free. TERM of the flock(1) holder: the +watchdog stopped the server group and the run shell, lock free. Not host-testable: the real server, the +nvidia-smi/model/18091 checks and the chip. + +Mutant 4 wiring (source, omega 474197e4f): `AIEN_Q36_TEST_MUTANT=4` -> `moe.rs` `graph_mutant()` -> +`test_set_mutant` on the main graph and (`rows.rs` wire) every row and stroke graph; in C mutant 4 swaps K_CN for +K_CN_M3 in the decode path and in `omega_gpu_q36_graph_prefill` (the chunk path), K_CN_R for K_CN_R_M3 in rows. +So the env mutant reaches the chunked prefill. It also breaks decode, so it cannot show the chunk path runs. The +prefill-only mutant does: `AIEN_OMEGA_Q36_PF_MUTANT` is read by `omega_gpu_q36_graph.c` L925 when the prefill +buffers are set up in the server process (header L146: 2 = every expert segment one row short); the decode graph +never reads it, and with `AIEN_Q36_PREFILL_CHUNK=0` the single door runs no chip prefill at all +(`prefill.rs` L298, `q36_state`). So PF_MUTANT=2 must be red with chunking and green with CHUNK=0. + +## Window (Main; chip gates NOT_RUN until then) + +Main opens a quiet exclusive window without the chip lock (marker, `spark-window open ... --gb10 none --quiet +exclusive --lease 20`), stops 18091 and Flint, and runs one lease's steps: +`spark-window run bash evidence/dra65-prefill-20261031/window-dra65.sh run BIN OUT STEP ...`, BIN = the server +binary built from this branch, OUT = one receipt root for every lease (step N writes `OUT/N/`). The 35B server's +chip reservation (`crates/aien-serve-http/src/chip_reservation.rs` L88-95) accepts `/tmp/aien-gb10.lock` only +when one of its ancestors holds it, and spark-window's holder never is; so the script takes `flock -n -o` on the +lock itself (flock(1) holds it and runs the script as its child; `-o` closes the fd before the exec, so no +descendant inherits the lock), checks in `/proc/locks` that the exclusive holder is its ancestor, and starts each +server as its own child, in its own session (`setsid`, pid file `OUT/.server..pid`), with +`AIEN_GB10_LOCK_HELD=1` and the affinity reset of the live start scripts (`taskset -c` over every online CPU, so a +core5/nice19 parent does not pin the 35B to one core; `nice` is inherited and cannot be lowered: do not start +`run` under `nice`). Exit 3 (NOT_RUN, chip untouched): no `SPARK_WINDOW`; the lock held by anyone else; a listener +on 18091, 18300, 18310 or the test port 18192; a compute app on the chip; BIN or the model missing; a green step +(3-5) not preceded by both red steps in the same run and without their passing step receipts in `OUT/1`, `OUT/2` +(rc 0, same bin_sha256, a lock holder, lease not expired); `$SPARK_WINDOW_DIR/expired` present; or the steps' +estimates longer than the lease has left. + +Lease: deadline = `held` + `lease` x `SPARK_LEASE_UNIT_S` (default 60). The server wait (at most 300 s), each probe +(`timeout` to the deadline) and every request (`curl -m` = min(1800 s, time left); none sent when no time is +left) are bounded by it. A watchdog in its own session stops the server's process group (TERM, KILL after 20 s) +and then the run shell at the deadline, or as soon as the run shell or the flock(1) holder dies (SIGKILL included); +the run shell's exit ends flock(1), which releases the lock. A step that ends after the deadline or with +`$SPARK_WINDOW_DIR/expired` present is INCONCLUSIVE rc 2, never PASS/RECORDED; a step that cannot fit its estimate +in the time left is not started (NOT_RUN rc 3). + +Servers: the live `start-35b.sh` flags (`--max-context 131072`) for the single door, `start-35b-batch.sh` +(`--max-context 49152 --batch-slots 8`) for the batch door, `--bind 127.0.0.1 --max-tokens-cap 16384 --thinking +off AIEN_Q36_STROKE=0`, plus the step's env. Each step writes `OUT/N/step-receipt.json` (window id, binary path +and sha256, door, env, est_s, server_ready_s, elapsed_s, rc, verdict, why, lease_expired, deadline, lock holder +pid, the probe's receipt) beside the probe's own receipts; `run` stops at the first step that does not exit 0, and +posts GPU-START/GPU-END lines on the board. The turn2 case also needs the door's snapshot-restore line in that +step's `server.log` for the turn2 request (single door `reuse Snapshot(` from `qwen38_engine.rs`, batch door +`tok (snapshot, row` from `qwen36_batch.rs`); without it the case is NO_SNAP: FAIL for green, INCONCLUSIVE for red. + +Estimated durations (MODELED, upper bounds at max_tokens; `window-dra65.sh plan` prints them), with decode +0.0201 s/token, chunked prompts 250 tok/s (8210 tokens at 196.8), stepped prompts 0.0201 s/token, +33 s start: +golden chunked `dec*(756 + 49 + 876) + 365/250. + 2486/250. + 8210/196.8` = 86.9 s -> 120 s with start; +golden all-stepped (step 3) `dec*(756 + 365 + 2486 + 8210 + 49 + 876)` = 256.1 s -> 289 s; time chunked +`3*(512/250. + 8210/196.8) + 6*256*dec` = 162.2 s -> 195 s; time all-stepped `dec*(3*(512 + 8210) + 6*256)` = +556.8 s -> 590 s (756 = the set's prompt tokens, 876 = its decode tokens 798 + 3*24 + 6; 49 = turn 2 past the +snapshot; 512 = planning size of long-512). 20-min leases: L1 = `run BIN OUT 1 2 3 4 5` +(`4*119.91 + 289.11` = 769 s), L2 = `6a 6b` (785 s), L3 = `6c 6d` (390 s). + +| step | door | server env | probe | expect | est_s | +|---|---|---|---|---|---| +| 1 | single | `AIEN_Q36_TEST_MUTANT=4` | golden red `mutant4` | PASS (red) | 120 | +| 2 | single | `AIEN_OMEGA_Q36_PF_MUTANT=2` | golden red `pf2` | PASS (red: the chunk path runs) | 120 | +| 3 | single | `AIEN_OMEGA_Q36_PF_MUTANT=2 AIEN_Q36_PREFILL_CHUNK=0` | golden green `pf2-chunk0` | PASS (the mutant lives on the chunk path only) | 289 | +| 4 | single | - | golden green `single` | PASS = 36/36 | 120 | +| 5 | batch | - | golden green `batch` | PASS = 36/36 | 120 | +| 6a | single | - | time `single` | RECORDED | 195 | +| 6b | single | `AIEN_Q36_PREFILL_CHUNK=0` (all token steps) | time `single-chunk0` | RECORDED | 590 | +| 6c | batch | - | time `batch` | RECORDED | 195 | +| 6d | batch | `AIEN_Q36_PREFILL_MIN=1` (chunks the answer header too) | time `batch-min1` | RECORDED | 195 | + +Green steps get `OUT/1/golden-receipt.json` and `OUT/2/golden-receipt.json` and refuse unless both are red PASS +of the same binary sha. Time steps: exit 0 only if all 6 runs have HTTP 200, a first content delta and usage; +receipts `time.jsonl`. TTFT = t_first - t0; e2e tok/s = completion_tokens / (t_end - t_first). Medians of the 3 +runs through Wolfram (`Median[{...}]`). Record `usage.prompt_tokens` of long-512 (the host has no tokenizer). +Target 1 compares e2e against chip-only decode from DRA-66's `chip_ns` in the same runs. + +## Predictions (MODELED, Wolfram) + +- Single door before: 1 token per decode step, 20.1 ms -> `N[1/0.0201]` = 49.75 tok/s; 512 tokens + `N[512*0.0201]` = 10.29 s; 8210 tokens `N[8210*0.0201]` = 165.0 s. +- Single door after, at the measured prefill-gate rates (250 tok/s at 2k, 196.8 at 8k): 512 tokens + `N[512/250.]` = 2.05 s; 8210 tokens `N[8210/196.8]` = 41.7 s. +- Target 2 (2,000 tok/s at 2k) needs `N[2000/250.]` = 8x the current chunked rate: not reachable by + chunking alone. + +## Next lever (batch and single door alike; omega kernel work, not host-testable) + +Expert bytes per 128-token chunk if every expert is read once per layer: `256*(3145728+384)*40` = 32,216,186,880 +B; at 273 GB/s `N[perChunk/273*^9]` = 0.118 s, i.e. a byte floor of `N[128/0.118...]` = 1,084.7 tok/s; the +measured 250 tok/s is `N[(128/250.)/0.118...]` = 4.34x above that floor, so the chunk is not bytes-bound. The +FLOP floor for 2,048 tokens at ~3e9 active parameters and 237.5 TFLOPS is `N[2*3*^9*2048/237.5*^12]` = 0.052 s. +The lever is compute efficiency of the prefill GEMMs: a tensor-core grouped expert GEMM (OMEGA.md bar C3) in +`omega_gpu_q36_graph_prefill`, then chunks above 128 (the 1024-row fp8 GEMM cap). The batch door's remaining +per-token stretches (< 16 before the snapshot, the ~7-token header) are an env A/B (`AIEN_Q36_PREFILL_MIN=1`, +step 4) because small-chunk chip cost is unmeasured. diff --git a/evidence/dra65-prefill-20261031/SHA256SUMS b/evidence/dra65-prefill-20261031/SHA256SUMS new file mode 100644 index 00000000..3c062f43 --- /dev/null +++ b/evidence/dra65-prefill-20261031/SHA256SUMS @@ -0,0 +1,8 @@ +7a171b54c2effda998d2884e3f6868b55123fa8ba779dcf2762dff4c64a1fa29 evidence/q36-batch-20261021/prompts.txt +d0bcb237803b0299d0a45ceb3bf1660628a369d286fcd82da617a7a31d5f2941 evidence/dra65-prefill-20261031/set32.json +05b01b70caa2b21d6c1051eeaebbb7e65d208bd988ff49b5b7a202d13a46fe89 evidence/dra65-prefill-20261031/long-goldens.json +3b27d724b10446308d0c0b0a68b72573cdb26e22f0d1994bde88880988bec8d3 evidence/dra65-prefill-20261031/long-512.txt +7a3661c1159cae61e2747eaf9047a6083367be1f643e386d9b80c27131ce7b3e evidence/dra65-prefill-20261031/turn2.messages.json +153a5f88932393b2be56fd81f8914d44218169c614ebc5b2753069c9a09bc3a1 evidence/merge-train/l369/long-256.txt +26a44c508412e213de876eb54bb90390426b086c887a68b90fa78f7470425ee3 evidence/merge-train/l369/long-2048.txt +2bcc84b25c418cba83df9546344fd4ae28962c314e03defe2aab62a8e6c8abb9 evidence/merge-train/l369/long-8192.txt diff --git a/evidence/dra65-prefill-20261031/hosttest/fake-serve.sh b/evidence/dra65-prefill-20261031/hosttest/fake-serve.sh new file mode 100755 index 00000000..599973d1 --- /dev/null +++ b/evidence/dra65-prefill-20261031/hosttest/fake-serve.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# dra65 mock door for the host check of window-dra65.sh run (never the real server) +port=; while [ $# -gt 0 ]; do [ "$1" = --port ] && port=$2; shift; done +M=exact +if [ "${AIEN_Q36_TEST_MUTANT:-}" = 4 ] || { [ "${AIEN_OMEGA_Q36_PF_MUTANT:-}" = 2 ] && [ "${AIEN_Q36_PREFILL_CHUNK:-128}" != 0 ]; }; then M=mut; fi +[ -n "${MOCK_M:-}" ] && M=$MOCK_M +echo "fake-serve pid $$ sid $(ps -o sid= -p $$ | tr -d " ") M=$M lock_fds=$(ls -l /proc/$$/fd | grep -c "$(basename "$DRA65_TEST_LOCK")") $(grep Cpus_allowed_list /proc/self/status)" >&2 +M=$M exec python3 "$(dirname "$0")/mock2.py" "$REPO" "$port" diff --git a/evidence/dra65-prefill-20261031/hosttest/mock2.py b/evidence/dra65-prefill-20261031/hosttest/mock2.py new file mode 100644 index 00000000..8bc52ecf --- /dev/null +++ b/evidence/dra65-prefill-20261031/hosttest/mock2.py @@ -0,0 +1,29 @@ +# dra65 mock door (host check of window-dra65.sh only): serves set32 goldens; M=exact|mut|nosnap|slow|slow1 +import json, os, sys, time, http.server +R=sys.argv[1]; D=R+'/evidence/dra65-prefill-20261031'; M=os.environ.get('M','exact') +g={p['user']:p['golden_ids'] for p in json.load(open(D+'/set32.json'))['prompts']} +for p in json.load(open(D+'/long-goldens.json'))['prompts']: + if 'file' in p: g[open(R+'/'+p['file']).read()]=p['golden_ids'] + else: g['TURN2']=p['golden_ids'] +class H(http.server.BaseHTTPRequestHandler): + def log_message(s,*a): pass + def out(s,code,b,ct='application/json'): + s.send_response(code); s.send_header('Content-Type',ct); s.send_header('Content-Length',str(len(b))); s.end_headers(); s.wfile.write(b) + def do_GET(s): s.out(200,json.dumps({'data':[{'id':'mock'}]}).encode()) + def do_POST(s): + q=json.loads(s.rfile.read(int(s.headers['Content-Length']))) + if M=='500': return s.out(500,b'{"error":"x"}') + msgs=q['messages']; key='TURN2' if len(msgs)==3 else msgs[0]['content']; ids=list(g.get(key,[1,2,3])) + if M=='slow': time.sleep(30) + if M=='slow1': time.sleep(0.25) + if M=='mut' and key=='TURN2': ids[2]+=1 + sys.stderr.write('aien-serve-http: qwen38: prompt 9 tok, reuse %s\n' % ('Snapshot(2479) (2479 tok)' if key=='TURN2' and M!='nosnap' else 'Cold (0 tok)')); sys.stderr.flush() + if M=='empty': ids=[] + if M=='short': ids=ids[:-1] + if q.get('stream'): + ev=[{'choices':[{'delta':{'content':'x'}}]}] + if M!='nousage': ev.append({'choices':[],'usage':{'prompt_tokens':9,'completion_tokens':len(ids)}}) + b=''.join('data: '+json.dumps(e)+'\n\n' for e in ev)+'data: [DONE]\n\n' + return s.out(200,b.encode(),'text/event-stream') + s.out(200,json.dumps({'choices':[{'message':{'content':'x'},'finish_reason':'stop'}],'usage':{'aien_token_ids':ids}}).encode()) +http.server.ThreadingHTTPServer(('127.0.0.1',int(sys.argv[2])),H).serve_forever() diff --git a/evidence/dra65-prefill-20261031/hosttest/runtests.sh b/evidence/dra65-prefill-20261031/hosttest/runtests.sh new file mode 100755 index 00000000..65810a14 --- /dev/null +++ b/evidence/dra65-prefill-20261031/hosttest/runtests.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Host check of window-dra65.sh run against the mock door (fake-serve.sh); scratch lock, never the chip. +# Run as: nice -n 19 taskset -c 0-9 bash evidence/dra65-prefill-20261031/hosttest/runtests.sh (ports 18978, 18979) +set -u +H=$(cd "$(dirname "$0")" && pwd) +S=$(cd "$H/.." && pwd)/window-dra65.sh # the canonical path the script re-execs itself under +export REPO; REPO=$(git -C "$H" rev-parse --show-toplevel) +T=${DRA65_HOSTTEST_DIR:-/tmp/dra65-hosttest}; rm -rf "$T"; mkdir -p "$T/win" +export SPARK_WINDOW=w-test-3 SPARK_WINDOW_DIR=$T/win DRA65_TEST_LOCK=$T/t3.lock DRA65_TEST_PORT=18978 +: > "$DRA65_TEST_LOCK" +B=$H/fake-serve.sh +win() { rm -f "$T/win/expired"; date -u +%FT%TZ > "$T/win/held"; echo "$1" > "$T/win/lease"; export SPARK_LEASE_UNIT_S=$2; } +lockfree() { flock -n "$DRA65_TEST_LOCK" true && echo lock=free || echo lock=HELD; } +left() { pgrep -f 'mock2.py|_watch' | grep -v $$ | wc -l; } +sr() { jq -c '{step, rc, verdict, why, lease_expired, v: .result.verdict, same: .result.same, no_snap: .result.no_snap}' "$1/step-receipt.json" 2>/dev/null || echo "no receipt $1"; } +t() { echo; echo "== $*"; } + +t "T1 L1 steps 1 2 3 4 5 (lease 20 min), under taskset -c 5" +win 20 60; taskset -c 5 bash "$S" run "$B" "$T/o1" 1 2 3 4 5 > "$T/t1.out" 2> "$T/t1.err"; echo "rc=$?" +for s in 1 2 3 4 5; do sr "$T/o1/$s"; done +grep -h fake-serve "$T"/o1/*/server.log | sed 's/pid [0-9]* sid [0-9]*/pid P sid P/' | sort | uniq -c +for s in 1 4; do echo "server pid==sid: $(grep -ho 'pid [0-9]* sid [0-9]*' "$T/o1/$s/server.log" | awk '{print ($2==$4)}')"; done +jq -c 'select(.id=="turn2") | {id, verdict, snapshot_log}' "$T/o1/4/golden.jsonl" +jq -c '{window, bin_sha256: .bin_sha256[0:12]}' "$T/o1/5/golden-receipt.json"; sleep 2; lockfree; echo "leftover=$(left)"; cat "$T/o1/board.log" + +t "T2 green 4 alone on o1 (reds from step receipts)"; win 20 60 +bash "$S" run "$B" "$T/o1" 4 > /dev/null 2> "$T/t2.err"; echo "rc=$?"; sr "$T/o1/4" +t "T3 order: 4 1 2 on empty o3"; bash "$S" run "$B" "$T/o3" 4 1 2 2>&1 >/dev/null | tail -n 1; echo "rc=${PIPESTATUS[0]}" +t "T4 golden receipts without step receipts (o4): run 4" +mkdir -p "$T/o4/1" "$T/o4/2"; cp "$T/o1/1/golden-receipt.json" "$T/o4/1/"; cp "$T/o1/2/golden-receipt.json" "$T/o4/2/" +bash "$S" run "$B" "$T/o4" 4 2>&1 >/dev/null | tail -n 1 +t "T4b probe green directly with those receipts (mock up on 18979)" +M=exact python3 "$H/mock2.py" "$REPO" 18979 2>/dev/null & mp=$!; sleep 1 +SHA=$(sha256sum < "$B" | cut -c1-64) +bash "$S" golden 18979 "$T/o4/g" green "$SHA" x "$T/o4/1/golden-receipt.json" "$T/o4/2/golden-receipt.json" > /dev/null 2> "$T/t4b.err"; echo "rc=$?"; cat "$T/t4b.err" +t "T4c same probe with o1's receipts (step receipts present) but no DRA65_SERVER_LOG -> turn2 NO_SNAP -> FAIL" +bash "$S" golden 18979 "$T/o4/g2" green "$SHA" x "$T/o1/1/golden-receipt.json" "$T/o1/2/golden-receipt.json" | jq -c '{verdict, same, no_snap}'; echo "rc=${PIPESTATUS[0]}" +kill $mp + +t "T5 nosnap door, step 4 on o1"; win 20 60 +MOCK_M=nosnap bash "$S" run "$B" "$T/o1" 4 > /dev/null 2>&1; echo "rc=$?"; sr "$T/o1/4" +jq -c 'select(.id=="turn2") | {id, verdict, snapshot_log}' "$T/o1/4/golden.jsonl" + +t "T6 deadline: slow door (30 s/request), lease 1 x 45 s, step 4"; win 1 45 +s0=$(date +%s); MOCK_M=slow bash "$S" run "$B" "$T/o1" 4 > /dev/null 2> "$T/t6.err"; echo "rc=$? after $(( $(date +%s) - s0 )) s" +sr "$T/o1/4"; sleep 2; lockfree; echo "leftover=$(left)"; tail -n 2 "$T/t6.err" + +t "T7 expired file appears mid-step (slow1 door), step 4"; win 20 60 +( sleep 4; touch "$T/win/expired" ) & MOCK_M=slow1 bash "$S" run "$B" "$T/o1" 4 > /dev/null 2>&1; echo "rc=$?"; sr "$T/o1/4"; wait + +t "T8 SIGKILL the run shell mid-step (slow door)"; win 20 60 +MOCK_M=slow bash "$S" run "$B" "$T/o8" 1 > /dev/null 2>&1 & sleep 6 +inner=$(pgrep -f "bash $S run $B $T/o8" | while read -r p; do [ "$(ps -o comm= -p "$p")" = bash ] && [ "$(ps -o comm= -p "$(ps -o ppid= -p "$p" | tr -d ' ')")" = flock ] && echo "$p"; done) +sp=$(cat $T/o8/.server.*.pid 2>/dev/null); echo "inner=$inner server=$sp"; kill -KILL "$inner"; sleep 4 +echo "server alive: $(kill -0 -- "-$sp" 2>/dev/null && echo yes || echo no)"; sleep 2; lockfree; echo "leftover=$(left)"; cat "$T/o8/watch.log"; wait + +t "T9 TERM the flock holder mid-step (slow door)"; win 20 60 +MOCK_M=slow bash "$S" run "$B" "$T/o9" 1 > /dev/null 2>&1 & sleep 6 +fl=$(pgrep -x flock | while read -r p; do grep -q "o9" "/proc/$p/cmdline" && echo "$p"; done); echo "flock=$fl"; kill -TERM "$fl"; sleep 25 +sleep 2; lockfree; echo "leftover=$(left)"; cat "$T/o9/watch.log"; wait diff --git a/evidence/dra65-prefill-20261031/long-512.txt b/evidence/dra65-prefill-20261031/long-512.txt new file mode 100644 index 00000000..1caa9cc9 --- /dev/null +++ b/evidence/dra65-prefill-20261031/long-512.txt @@ -0,0 +1 @@ +ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row ("LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIF \ No newline at end of file diff --git a/evidence/dra65-prefill-20261031/long-goldens.json b/evidence/dra65-prefill-20261031/long-goldens.json new file mode 100644 index 00000000..a2b68de9 --- /dev/null +++ b/evidence/dra65-prefill-20261031/long-goldens.json @@ -0,0 +1,133 @@ +{ + "about": "long-prompt and turn-2 goldens from reference build bin-16b0e6f8 (prompts token by token), each alone, 2026-10-21T22:11:19Z", + "source_dir": "~/.local/state/aien-q36/merge-train/refs/qwen3.6-35b-a3b-fp8-95a723d0/5b726818/", + "done_receipt": "l369-long/done", + "done_sha256": "f9435cbb8e39b9467a59d95f7f2e8282a3b92ed31ede7642c1f21673012c322e", + "done_text": "2026-10-21T22:11:19Z port 18091 model qwen3.6-35b-a3b-fp8 {\"build\":null} reference build bin-16b0e6f8 (live 18091, prompts token by token), each request alone; L387", + "prompts": [ + { + "name": "long-256", + "file": "evidence/merge-train/l369/long-256.txt", + "file_sha256": "153a5f88932393b2be56fd81f8914d44218169c614ebc5b2753069c9a09bc3a1", + "prompt_tokens": 365, + "golden_ids": [ + 760, + 1414, + 369, + 449, + 14991, + 1830, + 42724, + 279, + 61079, + 43555, + 2552, + 314, + 3050, + 8684, + 13753, + 364, + 279, + 41879, + 321, + 14791, + 923, + 5757, + 430, + 314 + ], + "max_tokens": 24, + "ref": "l369-long/long-256.json", + "ref_sha256": "0998d4c6d9734b24a282aac8bb0ca61c3ea832f0551033bb4dda7f1470ea523b" + }, + { + "name": "long-2048", + "file": "evidence/merge-train/l369/long-2048.txt", + "file_sha256": "26a44c508412e213de876eb54bb90390426b086c887a68b90fa78f7470425ee3", + "prompt_tokens": 2486, + "golden_ids": [ + 760, + 1414, + 369, + 264, + 10597, + 24332, + 42724, + 279, + 2790, + 314, + 264, + 2243, + 290, + 11540, + 9284, + 1785, + 364, + 264, + 81726, + 6297, + 3436, + 11, + 25471, + 1204 + ], + "max_tokens": 24, + "ref": "l369-long/long-2048.json", + "ref_sha256": "3dff923dc6932a1828d864b565a6c89e12805839ce80758370bd47081af3c3c9" + }, + { + "name": "long-8192", + "file": "evidence/merge-train/l369/long-8192.txt", + "file_sha256": "2bcc84b25c418cba83df9546344fd4ae28962c314e03defe2aab62a8e6c8abb9", + "prompt_tokens": 8210, + "golden_ids": [ + 760, + 1414, + 3447, + 264, + 10597, + 2790, + 364, + 264, + 81726, + 6297, + 1785, + 421, + 5004, + 264, + 328, + 27795, + 321, + 14519, + 1, + 16456, + 310, + 21640, + 321, + 25147 + ], + "max_tokens": 24, + "ref": "l369-long/long-8192.json", + "ref_sha256": "cdcef9435130dbff56628c3a6b01cf1824fd2f1feeeecd80de378cb054147cca" + }, + { + "name": "turn2", + "messages": "evidence/dra65-prefill-20261031/turn2.messages.json", + "file_sha256": "7a3661c1159cae61e2747eaf9047a6083367be1f643e386d9b80c27131ce7b3e", + "prompt_tokens": 2528, + "golden_ids": [ + 79852, + 6297, + 11540, + 9284, + 2790, + 13 + ], + "max_tokens": 16, + "ref": "l369-long/turn2.json", + "ref_sha256": "19fb7084e0df36faee9c574627d1ff9a10b059afc1884cd62963f14690e59cf4", + "after": "long-2048", + "about": "turn 2 of long-2048 (its golden reply as the assistant turn): run right after long-2048 so the door restores the snapshot taken at long-2048 answer header after a chunked prefill" + } + ] +} diff --git a/evidence/dra65-prefill-20261031/set32.json b/evidence/dra65-prefill-20261031/set32.json new file mode 100644 index 00000000..97744947 --- /dev/null +++ b/evidence/dra65-prefill-20261031/set32.json @@ -0,0 +1,1136 @@ +{ + "set": "dra65-32", + "about": "DRA-65 32-prompt set = the merge train concurrent-32 prompts (evidence/q36-batch-20261021/prompts.txt, ntok rule i==0?24:8+(i*7)%41); goldens = reference build bin-5b726818 (plain correct path: prompt fed token by token, no speed levers), each request alone, recorded 2026-10-21T02:44:22Z, imported to the merge-train store 2026-10-21T14:36:32Z; pre-DRA-65 by date", + "prompts_file": "evidence/q36-batch-20261021/prompts.txt", + "prompts_sha256": "7a171b54c2effda998d2884e3f6868b55123fa8ba779dcf2762dff4c64a1fa29", + "defaults": { + "temperature": 0, + "chat_template_kwargs": { + "enable_thinking": false + }, + "aien_return_token_ids": true + }, + "judge": "exact id identity per prompt (the door returns no logit margins, so the 0.1-logit band cannot be judged here: any flip is FAIL)", + "prompts": [ + { + "i": 0, + "user": "Write a C function that returns the larger of two ints.", + "max_tokens": 24, + "prompt_tokens": 24, + "golden_ids": [ + 71093, + 66, + 198, + 390, + 1866, + 1494, + 264, + 11, + 514, + 292, + 8, + 313, + 198, + 262, + 460, + 318, + 64, + 835, + 292, + 8, + 907, + 264, + 535, + 292 + ], + "finish": "length", + "ref_sha256": "1160441d7c54df52ee42250ae40cdc4b04671da9e1b6742fd10a25fbd400985f" + }, + { + "i": 1, + "user": "What is the capital of Australia? Answer in one sentence.", + "max_tokens": 15, + "prompt_tokens": 24, + "golden_ids": [ + 760, + 6511, + 314, + 8071, + 369, + 66463, + 13 + ], + "finish": "stop", + "ref_sha256": "d89145567b7eba7b4585ffe60941f5ef9c5d4b3106f15e2533f7f609a1d5185c" + }, + { + "i": 2, + "user": "Explain in two sentences why the sky is blue.", + "max_tokens": 22, + "prompt_tokens": 23, + "golden_ids": [ + 29108, + 4009, + 23716, + 8964, + 579, + 16078, + 321, + 369, + 35742, + 303, + 660, + 17425, + 539, + 660, + 279, + 43034, + 321, + 18167, + 303, + 279, + 3594, + 13 + ], + "finish": "length", + "ref_sha256": "0e3cd9ab0c23c929a9a6357a08e43228194ad04e92f4535016ba3a5197dc9bc0" + }, + { + "i": 3, + "user": "List five prime numbers greater than 100.", + "max_tokens": 29, + "prompt_tokens": 23, + "golden_ids": [ + 8160, + 513, + 4097, + 9944, + 4947, + 6826, + 1056, + 220, + 16, + 15, + 15, + 25, + 271, + 16, + 13, + 2972, + 16, + 15, + 16, + 332, + 198, + 17, + 13, + 2972, + 16, + 15, + 18, + 332, + 198 + ], + "finish": "length", + "ref_sha256": "9c10e0160d0ec6d3b686cf69f9928055936f979250ba2b3ff235655c95980803" + }, + { + "i": 4, + "user": "Translate to French: The train leaves at seven in the morning.", + "max_tokens": 36, + "prompt_tokens": 25, + "golden_ids": [ + 2229, + 5257, + 919, + 3656, + 33190, + 72491, + 3717, + 175926, + 13 + ], + "finish": "stop", + "ref_sha256": "3bdf30ac3ad47d0f37b51943bcf622772b94fd26a768e07c972b0fbc08dfd19d" + }, + { + "i": 5, + "user": "Write a haiku about a lighthouse in winter.", + "max_tokens": 43, + "prompt_tokens": 23, + "golden_ids": [ + 60187, + 16563, + 383, + 279, + 9506, + 11, + 198, + 3320, + 21682, + 14663, + 279, + 19088, + 6121, + 11, + 198, + 91986, + 337, + 2785, + 279, + 13071, + 13 + ], + "finish": "stop", + "ref_sha256": "3db756863a419713f68fb147da9182ed46c4d8252c7524aef2f602619f7dbe76" + }, + { + "i": 6, + "user": "What is 17 times 23? Show the steps.", + "max_tokens": 9, + "prompt_tokens": 26, + "golden_ids": [ + 1206, + 10724, + 393, + 16, + 22, + 1088, + 14695, + 220, + 17 + ], + "finish": "length", + "ref_sha256": "0dd734e6877fdb926c41be7ba2afcc86801d37a528882bd39b76f8e3c20dcaa2" + }, + { + "i": 7, + "user": "Give three tips for writing clear commit messages.", + "max_tokens": 16, + "prompt_tokens": 21, + "golden_ids": [ + 8160, + 513, + 2250, + 7326, + 10104, + 364, + 4237, + 2708, + 321, + 7139, + 5099, + 6397, + 25, + 271, + 16, + 13 + ], + "finish": "length", + "ref_sha256": "4194298c7d7b55c120180bae0e985afeaa478a2c4bb83f1ba5cbd836ed3a1097" + }, + { + "i": 8, + "user": "Write a Rust function that reverses a string.", + "max_tokens": 23, + "prompt_tokens": 22, + "golden_ids": [ + 71093, + 34602, + 198, + 9299, + 5003, + 9637, + 3773, + 1104, + 25, + 594, + 485, + 8, + 1411, + 894, + 313, + 198, + 262, + 274, + 82127, + 973, + 7055, + 973, + 16873 + ], + "finish": "length", + "ref_sha256": "cb4ce8306f3398464f0222f357f19045d2779ac88a72dd2fd2964ea1b3ba9e38" + }, + { + "i": 9, + "user": "Summarize the plot of Romeo and Juliet in three sentences.", + "max_tokens": 30, + "prompt_tokens": 25, + "golden_ids": [ + 11280, + 3777, + 31059, + 494, + 1115, + 49058, + 8259, + 11, + 67815, + 9503, + 4511, + 321, + 68613, + 7761, + 46805, + 11, + 40361, + 30774, + 1238, + 6236, + 506, + 264, + 4776, + 13, + 10643, + 10973, + 369, + 53507, + 948, + 67815 + ], + "finish": "length", + "ref_sha256": "2006031bcddb5bf56ee7b575a9e0c96a359eb7a92bedc9b7f2277f68f50a74fd" + }, + { + "i": 10, + "user": "What does a transformer's attention layer compute? Be brief.", + "max_tokens": 37, + "prompt_tokens": 24, + "golden_ids": [ + 2064, + 55288, + 264, + 35604, + 2542, + 314, + 869, + 22166, + 11, + 1332, + 279, + 13914, + 318, + 51319, + 11857, + 8, + 513, + 10521, + 539, + 279, + 23967, + 1881, + 3134, + 321, + 1328, + 22166, + 13 + ], + "finish": "stop", + "ref_sha256": "ee7a975635266296abbdbff1f987105ae4a6ea5f5e159d1f80d03fa1a9958eac" + }, + { + "i": 11, + "user": "Name the planets of the solar system in order from the Sun.", + "max_tokens": 44, + "prompt_tokens": 25, + "golden_ids": [ + 8160, + 513, + 279, + 7810, + 31784, + 314, + 279, + 12570, + 1785, + 303, + 1906, + 494, + 279, + 7806, + 25, + 271, + 16, + 13, + 2972, + 25863, + 24648, + 332, + 198, + 17, + 13, + 2972, + 53, + 36614, + 332, + 198, + 18, + 13, + 2972, + 42373, + 332, + 198, + 19, + 13, + 2972, + 44, + 1506, + 332, + 198, + 20 + ], + "finish": "length", + "ref_sha256": "5f7796407586354c677537bd952108b5c78f05976bb1c1983da9660ab463da3a" + }, + { + "i": 12, + "user": "Write a SQL query that counts orders per customer.", + "max_tokens": 10, + "prompt_tokens": 22, + "golden_ids": [ + 71093, + 3427, + 198, + 4703, + 5813, + 816, + 11, + 23241, + 27733, + 5574 + ], + "finish": "length", + "ref_sha256": "21649ba27a51bbe56a600c62a4e80e5950adcc2a6a2fe96927e3b722ff996117" + }, + { + "i": 13, + "user": "Why does ice float on water?", + "max_tokens": 17, + "prompt_tokens": 19, + "golden_ids": [ + 49604, + 46303, + 383, + 2919, + 1521, + 424, + 369, + 2972, + 1657, + 27044, + 332, + 1056, + 14058, + 2919, + 13, + 271, + 7732 + ], + "finish": "length", + "ref_sha256": "9115ce326ccb9ed8b594df270866729abc7dea04c8e0d7849183a1b6a4013b34" + }, + { + "i": 14, + "user": "Write a bash one-liner that counts lines in all .txt files in a folder.", + "max_tokens": 24, + "prompt_tokens": 30, + "golden_ids": [ + 71093, + 44675, + 198, + 3772, + 641, + 471, + 2721, + 17038, + 220, + 16, + 471, + 591, + 57129, + 8324, + 1, + 471, + 11411, + 25700, + 471, + 75, + 4535, + 478, + 735, + 9495 + ], + "finish": "length", + "ref_sha256": "2e8db9effc918a567c93ebc9a002215a7aca716003bc8c055a2f54ee62e7acbd" + }, + { + "i": 15, + "user": "Describe a bicycle gear system to a ten-year-old.", + "max_tokens": 31, + "prompt_tokens": 23, + "golden_ids": [ + 49338, + 488, + 513, + 19232, + 678, + 12591, + 685, + 264, + 2098, + 30239, + 23198, + 13, + 1049, + 725, + 2503, + 944, + 11, + 1245, + 30, + 4465, + 13795, + 2579, + 8545, + 11, + 321, + 488, + 3029, + 6992, + 2184, + 13569, + 13 + ], + "finish": "length", + "ref_sha256": "990ee87702c062286443413a43f7b211302ad3af15ec95bf84e0624e836c4d9f" + }, + { + "i": 16, + "user": "What is the difference between TCP and UDP? Two sentences.", + "max_tokens": 38, + "prompt_tokens": 24, + "golden_ids": [ + 48218, + 369, + 264, + 3511, + 33924, + 11176, + 421, + 34475, + 14294, + 11, + 11128, + 9403, + 314, + 795, + 1472, + 1412, + 15464, + 286, + 321, + 311, + 1405, + 2641, + 23038, + 13, + 733, + 12503, + 11, + 40986, + 369, + 264, + 3511, + 1657, + 11176, + 421, + 43195, + 4603, + 4478, + 321 + ], + "finish": "length", + "ref_sha256": "c6cc3038fc9751cd5f686e0c8bf9e96c268a2ba0d5794d4684ff8f1285857efe" + }, + { + "i": 17, + "user": "Write a limerick about a cat who learned to code.", + "max_tokens": 45, + "prompt_tokens": 25, + "golden_ids": [ + 32, + 7993, + 852, + 1362, + 913, + 383, + 264, + 13232, + 11, + 198, + 54, + 5356, + 1970, + 421, + 557, + 16724, + 430, + 264, + 57131, + 13, + 198, + 1465, + 7156, + 3438, + 440, + 264, + 3865, + 81, + 11, + 198, + 2939, + 8097, + 1396, + 27583, + 11, + 198, + 6820, + 551, + 725, + 279, + 11808, + 314, + 279, + 3421, + 13 + ], + "finish": "length", + "ref_sha256": "d3181419484825b2029340cf6af228cc2fc3dbae2207073c940bec8c0aec64ab" + }, + { + "i": 18, + "user": "Convert 100 degrees Fahrenheit to Celsius and explain the formula.", + "max_tokens": 11, + "prompt_tokens": 26, + "golden_ids": [ + 13962, + 12650, + 21134, + 198, + 332, + 16, + 15, + 15, + 11995, + 66401, + 369 + ], + "finish": "length", + "ref_sha256": "2e810d7ed4b007385e06b9f646225ecb46fa1af428e540dd989addfe51239f63" + }, + { + "i": 19, + "user": "Give a short definition of entropy in thermodynamics.", + "max_tokens": 18, + "prompt_tokens": 22, + "golden_ids": [ + 623, + 28868, + 76214, + 11, + 2972, + 47500, + 332, + 369, + 264, + 1528, + 709, + 421, + 10633, + 279, + 8122, + 314, + 18684, + 11 + ], + "finish": "length", + "ref_sha256": "df16bacb0096b417348b5b09202ec3036574e81b75dbe194b7051640e62c5b05" + }, + { + "i": 20, + "user": "Write a Python-free pseudocode for binary search.", + "max_tokens": 25, + "prompt_tokens": 22, + "golden_ids": [ + 8160, + 369, + 279, + 48939, + 42242, + 364, + 279, + 2972, + 20682, + 7304, + 332, + 11767, + 13, + 271, + 13962, + 2601, + 367, + 1255, + 198, + 9, + 256, + 561, + 1879, + 1287, + 1510 + ], + "finish": "length", + "ref_sha256": "76a00aef96743aae5f035055f92cbb0850ae3183b77edd04f201a5717c85fa92" + }, + { + "i": 21, + "user": "What are the three primary colors of light?", + "max_tokens": 32, + "prompt_tokens": 21, + "golden_ids": [ + 27775, + 383, + 279, + 15694, + 314, + 2972, + 698, + 3295, + 1829, + 25936, + 332, + 318, + 7949, + 16298, + 310, + 3000, + 7916, + 1040, + 6165, + 14864, + 11, + 7712, + 38685, + 11, + 321, + 6228, + 17188, + 681, + 279, + 2250, + 5839, + 7736 + ], + "finish": "length", + "ref_sha256": "8af1b096cf45a772446b309ec704e4ecf1a2d6f8b16a201ec4e5181a771f6aa4" + }, + { + "i": 22, + "user": "Suggest a name for a coffee shop run by robots, and say why.", + "max_tokens": 39, + "prompt_tokens": 28, + "golden_ids": [ + 8160, + 369, + 264, + 23032, + 364, + 264, + 803, + 11, + 3055, + 440, + 279, + 31626, + 4661, + 424, + 25, + 271, + 13962, + 2972, + 657, + 25, + 561, + 38989, + 291, + 20284, + 332, + 271, + 13962, + 2972, + 9930, + 411, + 803, + 4138, + 64700, + 271, + 16, + 13, + 220, + 2972, + 8864 + ], + "finish": "length", + "ref_sha256": "4af3e06ce741e8b6199a7a040cd3be9fb24f712be611e281d09cfdac63d6174a" + }, + { + "i": 23, + "user": "Explain what a hash map is in one paragraph.", + "max_tokens": 46, + "prompt_tokens": 23, + "golden_ids": [ + 32, + 5010, + 2336, + 369, + 264, + 795, + 5759, + 421, + 5004, + 449, + 66571, + 1287, + 7859, + 795, + 913, + 11, + 264, + 5759, + 421, + 628, + 2336, + 6679, + 310, + 2663, + 11, + 539, + 1608, + 264, + 5010, + 709, + 310, + 12204, + 449, + 1857, + 1083, + 449, + 1287, + 314, + 40718, + 466, + 15250, + 494, + 864, + 279, + 12321, + 869 + ], + "finish": "length", + "ref_sha256": "3ea511c6a6c81cb8d195187e8f8030e141edef306768c44944658a4f030162f2" + }, + { + "i": 24, + "user": "Write the first four lines of a sea shanty.", + "max_tokens": 12, + "prompt_tokens": 23, + "golden_ids": [ + 760, + 9662, + 424, + 1204, + 4577, + 3808, + 279, + 30065, + 11, + 198, + 760, + 16382 + ], + "finish": "length", + "ref_sha256": "14045453e1920ab5e473ab357dde290c7d2bb44e8c8a9584647ef541b235077c" + }, + { + "i": 25, + "user": "How many seconds are in a day? Show the multiplication.", + "max_tokens": 19, + "prompt_tokens": 24, + "golden_ids": [ + 1206, + 10724, + 279, + 1324, + 314, + 6283, + 303, + 264, + 1834, + 11, + 567, + 1387, + 1441, + 279, + 7896, + 314, + 854, + 2923, + 13909 + ], + "finish": "length", + "ref_sha256": "d0c0ac7e377f47eaa255866d0d387aefb51b9d2b2fedb7982798a0cfa4d4b44f" + }, + { + "i": 26, + "user": "What is the boiling point of water at the top of Mount Everest, roughly?", + "max_tokens": 26, + "prompt_tokens": 28, + "golden_ids": [ + 13962, + 59977, + 48704, + 2567, + 271, + 1206, + 7995, + 279, + 48161, + 1406, + 314, + 2919, + 506, + 279, + 1844, + 314, + 10113, + 83489, + 11, + 567, + 1902, + 3418, + 279, + 4864, + 1881, + 42900 + ], + "finish": "length", + "ref_sha256": "f2cd985dda2a49869a5cab6952577804225ce0dad8d36732c2bef342c6aba159" + }, + { + "i": 27, + "user": "Write a JavaScript function that checks whether a number is even.", + "max_tokens": 33, + "prompt_tokens": 24, + "golden_ids": [ + 71093, + 13670, + 198, + 1628, + 369, + 12777, + 7815, + 8, + 313, + 198, + 262, + 460, + 1572, + 984, + 220, + 17, + 1981, + 220, + 15, + 26, + 198, + 92, + 198, + 71093 + ], + "finish": "stop", + "ref_sha256": "c3d491b3023dd54ee733b536d7ee7f83516e95f9c43f2781000ff610813d6c36" + }, + { + "i": 28, + "user": "Explain photosynthesis in plain words.", + "max_tokens": 40, + "prompt_tokens": 20, + "golden_ids": [ + 37405, + 314, + 7022, + 71163, + 430, + 264, + 2972, + 981, + 10430, + 1817, + 332, + 421, + 10462, + 958, + 310, + 1236, + 836, + 1765, + 3487, + 13, + 271, + 8160, + 725, + 1204, + 424, + 4138, + 303, + 4145, + 7123, + 25, + 271, + 13962, + 10838, + 234, + 109, + 561, + 49453, + 198, + 2052, + 1720 + ], + "finish": "length", + "ref_sha256": "e6f92c8632513565cab6270765fb40f2d84db8d7b842471efdf8907789cd8179" + }, + { + "i": 29, + "user": "Give two reasons a bridge might use a suspension design.", + "max_tokens": 47, + "prompt_tokens": 23, + "golden_ids": [ + 8160, + 513, + 1330, + 5839, + 7715, + 264, + 13759, + 2493, + 958, + 264, + 23538, + 2790, + 25, + 271, + 13962, + 220, + 16, + 13, + 34791, + 310, + 11564, + 5546, + 26709, + 2924, + 198, + 90898, + 2558, + 37683, + 513, + 1968, + 40541, + 15873, + 364, + 25786, + 1546, + 6669, + 12497, + 314, + 2919, + 466, + 5365, + 82446, + 13, + 25215, + 22690, + 466, + 5157 + ], + "finish": "length", + "ref_sha256": "ca5f6f9e1cd0de542c8ca6c1c3a9adc8f1adfbd76b6b0209db49dd16eb631d68" + }, + { + "i": 30, + "user": "Write a polite email declining a meeting invitation.", + "max_tokens": 13, + "prompt_tokens": 21, + "golden_ids": [ + 12646, + 25, + 997, + 25, + 28107, + 80370, + 471, + 498, + 62394, + 31819, + 14, + 1851, + 60 + ], + "finish": "length", + "ref_sha256": "babd437d849e8ceca3ee5632b4e1e12327574cfa3ce5383e0c5d76e2023b3d64" + }, + { + "i": 31, + "user": "What is a mutex and when would you use one?", + "max_tokens": 20, + "prompt_tokens": 23, + "golden_ids": [ + 2, + 63979, + 318, + 49708, + 899, + 1326, + 8686, + 8, + 271, + 550, + 3437, + 2091, + 264, + 63979, + 30, + 271, + 32, + 2972, + 21670, + 332 + ], + "finish": "length", + "ref_sha256": "705bf4bdc3d0d99530c5a567ba128998c3b437a09dabc12bd4ba1fe396de5cc8" + } + ], + "source_dir": "~/.local/state/aien-q36/merge-train/refs/qwen3.6-35b-a3b-fp8-95a723d0/5b726818/", + "ref_note": "prompts[i].ref_sha256 = sha256 of source_dir/alone/.json" +} diff --git a/evidence/dra65-prefill-20261031/turn2.messages.json b/evidence/dra65-prefill-20261031/turn2.messages.json new file mode 100644 index 00000000..db731f47 --- /dev/null +++ b/evidence/dra65-prefill-20261031/turn2.messages.json @@ -0,0 +1 @@ +[{"role":"user","content":"ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row (\"LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied\"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIFIED). Line numbers move on that branch; the pin is the commit. This ADR adopts the same \"never restore the last prompt token\" rule (section 6.5) and the same warm-equals-cold test shape. Nothing else overlaps: that branch has no disk, no identity, no sharing across requests. ## Decision drivers 1. Correctness before speed: no byte is reused unless its identity proves compatibility, and validation happens before any allocation or copy. 2. The runtime mutex and the KV lock are never held across storage I/O. 3. Everything is bounded: queue depth, bytes in flight, recovery memory, disk quota including objects never looked up. 4. One record header for host and native, so tooling and tests read both; payloads differ by backend format and are never cross-loaded. 5. The native side keeps the single-command, bounce-buffered NVMe contract and the freestanding no_std rule. 6. Conversation history stays authoritative; the KV store is a cache that may be dropped at any time. ## 1. Versioned chunk identity ### 1.1 Units - A **chunk** is `chunk_tokens = chunk_blocks * block_size` consecutive positions of one sequence, aligned to a multiple of `chunk_tokens`. `chunk_blocks` is a setting fixed into the namespace (default 16 blocks; with the 16-token blocks of `model_dir.rs` that is 256 tokens (calc:ceaa1589), LMCache's default). A chunk is **full** when it holds `chunk_tokens` positions. The last chunk of a parked sequence may be **partial** (`token_count < chunk_tokens`); partial chunks are keyed with their exact token count and therefore only ever match an identical prefix of identical length. Only full chunks are prefix-share candidates. - Hash everywhere is SHA-256 (host: `sha2`, already in the lockfile; native: argus `sha256.h`, used by `store_v1.h`). blake3 is not used because native has no blake3. ### 1.2 Namespace id (binds everything that must be equal for bytes to be reusable) `namespace_id = SHA-256( \"AIEN-PKV-NS-V2\\0\" || fields )` (V1 until sc#504; the domain moved when field 14 started to bind the engine, section 1.2.2, so no V1 namespace can match) where `fields`, in this order, little-endian: | # | field | type | source | |---|---|---|---| | 1 | format_version | u16 = 1 | this ADR | | 2 | model_sha256 | [u8;32] | `ModelIdentity.model_sha256` decoded from hex (generation.rs:25) | | 3 | model_digest_kind | u8 len + bytes | `ModelIdentity.model_digest_kind` (generation.rs:26) | | 4 | model_id | u16 len + bytes | `ModelConfig.model_id` | | 5 | num_layers, num_kv_heads, head_dim, block_size | 4 x u32 | `ModelConfig` | | 6 | rope_theta | u32 (f32 bits) | `ModelConfig.rope_theta` | | 7 | rope_scaling | u8 tag (0 none, 1 llama3) then, if 1: factor f64 bits, low_freq_factor f64 bits, high_freq_factor f64 bits, original_max_position_embeddings u64 | `Llama3RopeScaling` (abi-core lib.rs:45-50) | | 8 | qk_norm | u8 | `ModelConfig.qk_norm` | | 9 | dtype | u8 (1 Fp4, 2 Fp8, 3 Bf16, 4 Fp16, 5 Fp32) | `KvDType` | | 10 | layout | 5 x u64 strides (head, token, kv_plane, layer, block) + u64 element_bytes | `KvLayout` (lib.rs:143-156) | | 11 | backend_format | u8 (1 = host paged pool v1; 2 = native f32 decode state v1) | section 2.3 | | 12 | chunk_tokens | u32 | setting | | 13 | sharing_namespace | u16 len + bytes | setting `AIEN_KV_STORE_NAMESPACE` (host); sealed Store uuid + identity class + subject id (native, section 9) | | 14 | compute_config_digest | [u8;32] | `ComputeConfig::digest_with_engine(engine)`, sections 1.2.1 and 1.2.2 (added by the review, C1 delta in section 12; binds the engine since sc#504) | Rationale: fields 2-8 cover \"which weights, which geometry, which RoPE\"; 9-11 cover \"which bytes\"; 13 is the authorization scope; 14 covers every other number that changes what the forward pass computes. Two runtimes with different `block_size` or `chunk_tokens` cannot share objects, by design: positions and chunk boundaries are part of identity. #### 1.2.1 Compute configuration digest (review finding 1) The review showed (VERIFIED by the orchestrator) that two model directories with the same weights digest and the same fields 1-13 but a different `rms_norm_eps` in `config.json` produce different K/V: the backend reads `weights.config.rms_norm_eps` for every RMSNorm (transformer_backend.rs:738, 1111, 1391, 1760) and the value comes from `config.json` (model_dir.rs:112, 239). The weights digest covers the safetensors bytes only, not `config.json`. `ComputeConfig::digest() = SHA-256(\"AIEN-PKV-CFG-V1\\0\" || ComputeConfig)` (namespace field 14 until sc#504; field 14 is now the V2 digest of section 1.2.2, which hashes the same nine fields first) where `ComputeConfig` is, little-endian and in this order: | # | field | type | source | |---|---|---|---| | 1 | num_heads | u32 | `ModelConfig.num_heads` | | 2 | hidden_dim | u64 | `ModelConfig.hidden_dim` | | 3 | intermediate_dim | u64 | `ModelConfig.intermediate_dim` | | 4 | vocab_size | u64 | `ModelConfig.vocab_size` | | 5 | rms_norm_eps | u32 (f32 bits) | `ModelConfig.rms_norm_eps` | | 6 | tie_word_embeddings | u8 | `ModelConfig.tie_word_embeddings` | | 7 | hidden_act | u8 (1 = silu) | `config.json` `hidden_act`; the loader refuses everything but silu (model_dir.rs:198-199, VERIFIED), so the byte is a constant today and exists so a future activation cannot alias | | 8 | arith_id | u8 len + bytes | `TensorBackend::name()` (backend.rs:131, VERIFIED trait method; implementations return `\"ReferenceCpuBackend\"` at backend.rs:509-511, `\"NativeCpuBackend (Rayon Multi-Core)\"` at mojo_backend.rs:242-244, and an availability-dependent string at omega_backend.rs:815-820, all VERIFIED) | | 9 | arith_epoch | u32 | a constant `KV_ARITH_EPOCH` in `aien-inference-abi`, bumped by any change that alters numeric results of the forward pass | Fields not listed and why (each is a decision, not an omission): `model_id` (field 4 of the namespace), `num_layers`, `num_kv_heads`, `head_dim`, `block_size`, `rope_theta`, `rope_scaling`, `qk_norm` (namespace fields 5-8), `max_sequence_length` (caps context, does not change a K/V value; the cap is applied to the restorable prefix, section 6.3), `eos_token_ids` (decides when to stop, not what is computed), `attention_bias` and `mlp_bias` (the loader refuses true, model_dir.rs:201-203, so they cannot vary). **Why the resolved `ModelConfig` and not a digest of the raw `config.json`** (INFERRED, decision): (a) the raw file carries fields that cannot change a K/V value (`torch_dtype`, `transformers_version`, `use_cache`, `initializer_range`; model_dir.rs:22-52 lists the\n\nIn one sentence, what is the text above about?"},{"role":"assistant","content":"The text is a technical specification detailing the design of a versioned chunk identity system for a KV cache store, defining how"},{"role":"user","content":"Now say it again in five words."}] diff --git a/evidence/dra65-prefill-20261031/window-dra65.sh b/evidence/dra65-prefill-20261031/window-dra65.sh new file mode 100755 index 00000000..3d22cdb9 --- /dev/null +++ b/evidence/dra65-prefill-20261031/window-dra65.sh @@ -0,0 +1,360 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DRA-65 chip window. Main opens `spark-window open ... --gb10 none --quiet exclusive --lease 20`, stops 18091 and +# Flint, then runs one lease's steps as +# spark-window run bash window-dra65.sh run BIN OUT STEP [STEP ...] +# BIN = the server binary built from this branch, OUT = a receipt root shared by every lease (step N writes +# OUT/N/). The server's chip reservation (aien-serve-http chip_reservation.rs) only accepts /tmp/aien-gb10.lock +# held by one of its ancestors, so this script takes `flock -n -o` on it itself (the lock stays in flock(1), an +# ancestor; no descendant inherits the fd) and starts every server as its child, in its own session +# (setsid, pid file OUT/.server..pid), with AIEN_GB10_LOCK_HELD=1 and the affinity reset of the live start scripts. +# Exit 3 = NOT_RUN, chip untouched: no SPARK_WINDOW, the lock held by someone else, a listener on +# 18091/18300/18310 or the test port, a compute app on the chip, the binary or model missing, a green step +# without passing red steps (listed before it, or their step receipts in OUT/1 and OUT/2), or the steps' +# estimated time longer than the lease has left. +# Lease: deadline = SPARK_WINDOW_DIR/held + lease * SPARK_LEASE_UNIT_S (default 60). Every server wait and +# probe is bounded by the time left (timeout, curl -m). A watchdog in its own session stops the server group +# at the deadline (and this script if it has not ended 40 s later), or at once when this script or the lock +# holder dies; the lock is then released. +# A step that ends after the deadline or with SPARK_WINDOW_DIR/expired present is INCONCLUSIVE (rc 2). +# window-dra65.sh plan (no window needed: the steps, their server env and estimated durations) +# Every receipt line carries the window id and the binary sha256. +# +# Probes (an already running server on PORT; `run` calls them, the host checks them against a mock door): +# window-dra65.sh golden PORT OUT red BIN_SHA256 LABEL +# window-dra65.sh golden PORT OUT green BIN_SHA256 LABEL RED_RECEIPT RED_RECEIPT [...] +# 36 cases (32-prompt set, 3 long prompts, turn 2 restoring the long-2048 snapshot) vs the pinned goldens. +# green refuses to run unless it is handed at least two red receipts (verdict PASS, distinct labels) of +# the same server binary sha256, each next to a step-receipt.json of `run` with rc 0, the same +# bin_sha256, a lock holder and the lease not expired: red before green. +# With DRA65_SERVER_LOG (set by `run`), turn2 also needs the door's snapshot-restore log line for that +# request (single: `reuse Snapshot(`, qwen38_engine.rs; batch: `tok (snapshot, row`, qwen36_batch.rs). +# window-dra65.sh time PORT OUT BIN_SHA256 LABEL +# TTFT and end-to-end tok/s, ~512 and 8210-token prompts, 3 runs each. +# Per case: SAME (ids equal), DIFF (a flip inside the common length, or more ids than the golden), +# SHORT (a strict prefix of the golden: no flip shown), NO_IDS (HTTP error, missing or empty ids), +# NO_SNAP (turn2 without the snapshot-restore log line). +# golden red: PASS = at least one DIFF and no NO_IDS/SHORT/NO_SNAP; those -> INCONCLUSIVE; else FAIL. +# golden green: PASS = all SAME; any NO_IDS -> INCONCLUSIVE; else (NO_SNAP included) FAIL. +# Exit 0 = PASS, 1 = FAIL, 2 = INCONCLUSIVE or refused, 3 = NOT_RUN, 4 = interrupted. time: 0 only if every run +# has HTTP 200, a first content delta and usage with completion_tokens > 0; else 2. `run` stops at the first +# step that does not exit 0 and returns its code. +set -uo pipefail +HERE=$(cd "$(dirname "$0")" && pwd); REPO=$(cd "$HERE/../.." && pwd); SELF=$HERE/$(basename "$0") +die() { echo "window-dra65: $*" >&2; exit 2; } +not_run() { echo "window-dra65: NOT_RUN: $*" >&2; exit 3; } +# left_s [CAP]: seconds to DRA65_DEADLINE (unset: CAP), at most CAP; returns 1 when none are left. +left_s() { + local cap=${1:-999999} l + if [ -n "${DRA65_DEADLINE:-}" ]; then l=$((DRA65_DEADLINE - $(date +%s))); [ "$l" -lt "$cap" ] || l=$cap; else l=$cap; fi + echo "$l"; [ "$l" -gt 0 ] +} + +# step -> door, server env, probe, estimated seconds. MODELED (Wolfram, README "Window"): decode 0.0201 s/token, +# chunked prompts 250 tok/s (8210: 196.8), stepped prompts 0.0201 s/token; upper bounds at max_tokens; each +# includes ~33 s server start. +step_def() { + ENVS=(); case $1 in + 1) DOOR=single; ENVS=(AIEN_Q36_TEST_MUTANT=4); PROBE="golden red mutant4"; EST=120 ;; + 2) DOOR=single; ENVS=(AIEN_OMEGA_Q36_PF_MUTANT=2); PROBE="golden red pf2"; EST=120 ;; + 3) DOOR=single; ENVS=(AIEN_OMEGA_Q36_PF_MUTANT=2 AIEN_Q36_PREFILL_CHUNK=0); PROBE="golden green pf2-chunk0"; EST=289 ;; + 4) DOOR=single; PROBE="golden green single"; EST=120 ;; + 5) DOOR=batch; PROBE="golden green batch"; EST=120 ;; + 6a) DOOR=single; PROBE="time single"; EST=195 ;; + 6b) DOOR=single; ENVS=(AIEN_Q36_PREFILL_CHUNK=0); PROBE="time single-chunk0"; EST=590 ;; + 6c) DOOR=batch; PROBE="time batch"; EST=195 ;; + 6d) DOOR=batch; ENVS=(AIEN_Q36_PREFILL_MIN=1); PROBE="time batch-min1"; EST=195 ;; + *) return 1 ;; + esac +} +# red_ok OUT STEP SHA: that red step's run receipt passed for this binary inside the lease. +red_ok() { + jq -e --arg b "$3" '.rc == 0 and .bin_sha256 == $b and (.lock_holder | length) > 0 and .lease_expired == false + and .result.case == "golden" and .result.expect == "red" and .result.verdict == "PASS"' "$1/$2/step-receipt.json" > /dev/null 2>&1 +} + +case ${1:-} in +plan) + printf '%-4s %-7s %-55s %-24s %s\n' step door "server env" probe est_s + for s in 1 2 3 4 5 6a 6b 6c 6d; do + step_def $s; printf '%-4s %-7s %-55s %-24s %s\n' $s $DOOR "${ENVS[*]:--}" "$PROBE" $EST + done + echo "Steps 1-2 (red) come first; 3-5 need them earlier in the same run or their step receipts in OUT/1 and OUT/2." + echo "20-min leases: L1 = run BIN OUT 1 2 3 4 5 (769 s), L2 = 6a 6b (785 s), L3 = 6c 6d (390 s)." + exit 0 ;; +_watch) # _watch MAIN HOLDER DEADLINE PIDFILE (own session; started by run) + M=$2; H=$3; DL=$4; PF=$5 + while kill -0 "$M" 2>/dev/null && kill -0 "$H" 2>/dev/null && [ "$(date +%s)" -lt "$DL" ]; do sleep 1; done + why="deadline"; kill -0 "$M" 2>/dev/null || why="run shell $M gone"; kill -0 "$H" 2>/dev/null || why="lock holder $H gone" + pg=$(cat "$PF" 2>/dev/null) + if [ -n "$pg" ] && kill -0 -- "-$pg" 2>/dev/null; then + echo "$(date -u +%FT%TZ) watchdog: $why: TERM server group $pg" + kill -TERM -- "-$pg" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$pg" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$pg" 2>/dev/null; rm -f "$PF" + fi + # At the deadline the run shell's own bounds (probe timeout, stop_server) end the step as INCONCLUSIVE and it + # exits: give it 40 s to write that receipt. Its exit ends flock(1), which releases the lock. + if [ "$why" = deadline ]; then for _ in $(seq 40); do kill -0 "$M" 2>/dev/null || break; sleep 1; done; fi + kill -0 "$M" 2>/dev/null && { echo "$(date -u +%FT%TZ) watchdog: $why: TERM run shell $M"; kill -TERM "$M"; } + exit 0 ;; +run) + [ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: run as 'spark-window run bash $0 run ...' inside a --quiet exclusive window" + [ $# -ge 4 ] || die "usage: run BIN OUT STEP [STEP ...]" + # DRA65_TEST_LOCK (host check only): another lock file; the binary must be a script (a mock door, never the + # ELF server), the chip and live-port checks are skipped and board lines go to OUT/board.log. + LOCK=${DRA65_TEST_LOCK:-/tmp/aien-gb10.lock}; TEST=${DRA65_TEST_LOCK:+1} + if [ "${DRA65_LOCKED:-}" != "$SPARK_WINDOW" ]; then + # flock(1) holds the lock in its own process (-o: closed before exec, so no descendant inherits it) and + # runs us as its child: the holder is an ancestor of this shell and of every server it starts. + DRA65_LOCKED=$SPARK_WINDOW flock -n -o -E 75 "$LOCK" bash "$SELF" "$@"; rc=$? + [ $rc = 75 ] && not_run "$LOCK is held by another process; this script takes it itself (open the window with --gb10 none)" + exit $rc + fi + BIN=$(readlink -f "$2"); OUT=$(readlink -m "$3"); shift 3; STEPS=("$@") + WIN=$SPARK_WINDOW + # 1. An exclusive flock on LOCK held by an ancestor of this shell (/proc/locks: "N: FLOCK ADVISORY WRITE pid maj:min:ino"). + ino=$(stat -c %i "$LOCK") || not_run "$LOCK missing" + holders=$(awk -v ino="$ino" '$2 == "FLOCK" && $4 == "WRITE" { split($6, a, ":"); if (a[3] == ino) print $5 }' /proc/locks | sort -u) + anc=" "; p=$$ + while [ "$p" -gt 1 ]; do anc="$anc$p "; p=$(awk '{print $4}' "/proc/$p/stat" 2>/dev/null) || break; done + HOLDER=; for h in $holders; do case "$anc" in *" $h "*) HOLDER=$h ;; esac; done + [ -n "$HOLDER" ] || not_run "$LOCK held by pid(s) '${holders}', none an ancestor of $$ ($anc)" + if [ -n "$TEST" ]; then + [ -x "$BIN" ] && [ "$(head -c 4 "$BIN" | od -An -c | tr -d ' ')" != '177ELF' ] \ + || not_run "test lock $LOCK held by ancestor $HOLDER; DRA65_TEST_LOCK only runs a script mock door, never the server binary" + fi + [ -x "$BIN" ] || not_run "binary $BIN missing" + SHA=$(sha256sum < "$BIN" | cut -c1-64) + # 2. Steps known; each green step after both red steps in this run, or their passing step receipts in OUT. + total=0; seen1=0; seen2=0 + for s in "${STEPS[@]}"; do + step_def "$s" || die "unknown step $s (see: $0 plan)" + [ -n "$TEST" ] && EST=5 + total=$((total + EST)) + case $s in + 1) seen1=1 ;; 2) seen2=1 ;; + 3|4|5) { [ $seen1 = 1 ] || red_ok "$OUT" 1 "$SHA"; } && { [ $seen2 = 1 ] || red_ok "$OUT" 2 "$SHA"; } \ + || not_run "green step $s needs red steps 1 and 2 before it in this run, or their passing step receipts in $OUT/1 and $OUT/2 for bin $SHA" ;; + esac + done + # 3. The lease has room for the steps' estimates. + lease=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/lease" 2>/dev/null); held=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/held" 2>/dev/null) + [ -n "$lease" ] && [ -n "$held" ] || not_run "no lease/held in SPARK_WINDOW_DIR='${SPARK_WINDOW_DIR:-}'" + [ -e "$SPARK_WINDOW_DIR/expired" ] && not_run "the lease has expired ($SPARK_WINDOW_DIR/expired)" + heldt=$(date -d "$held" +%s) || not_run "cannot read held time '$held'" + DEADLINE=$(( heldt + lease * ${SPARK_LEASE_UNIT_S:-60} )); export DRA65_DEADLINE=$DEADLINE + left=$(( DEADLINE - $(date +%s) )) + [ "$total" -le "$left" ] || not_run "steps ${STEPS[*]} estimate $total s, the lease has $left s left" + # 4. Live 35B, Flint and the chip idle; model, port, tools there. + PORT=${DRA65_TEST_PORT:-18192}; [ -n "$TEST" ] || PORT=18192 + MODEL=$HOME/models/qwen3.6-35b-a3b-fp8-95a723d0 + for t in curl jq ss flock setsid timeout sha256sum; do command -v $t > /dev/null || not_run "$t missing"; done + [ -z "$(ss -ltnH "sport = :$PORT")" ] || not_run "a listener is on $PORT" + if [ -z "$TEST" ]; then + command -v nvidia-smi > /dev/null || not_run "nvidia-smi missing" + for port in 18091 18300 18310; do [ -z "$(ss -ltnH "sport = :$port")" ] || not_run "a listener is on $port"; done + apps=$(nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv,noheader 2>&1) || not_run "nvidia-smi failed: $apps" + [ -z "$apps" ] || not_run "compute apps on the chip: $apps" + [ -f "$MODEL/config.json" ] || not_run "model $MODEL missing" + fi + mkdir -p "$OUT" || not_run "cannot create $OUT" + PIDF=$OUT/.server.$$.pid # per run: a previous run's watchdog never sees this run's server + log() { echo "$(date -u +%FT%TZ) $*" | tee -a "$OUT/run.log" >&2; } + board() { + if [ -n "$TEST" ]; then echo "$(date -u +%FT%TZ) DRA65Prefill: $*" >> "$OUT/board.log" + else echo "$(date -u +%FT%TZ) DRA65Prefill: $*" >> "$HOME/handoffs/BOARD.md"; fi + } + SERVER= + stop_server() { # TERM the server's process group (its own session), KILL after 20 s + [ -n "$SERVER" ] || return 0 + kill -TERM -- "-$SERVER" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$SERVER" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$SERVER" 2>/dev/null; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER= + } + # start_server LOG: DOOR and ENVS from step_def; the live start-35b(-batch).sh flags on a loopback test port. + start_server() { + local flags=(--max-context 131072) aff cpus lim l + [ "$DOOR" = batch ] && flags=(--max-context 49152 --batch-slots 8) + # As start-35b(-batch).sh: undo an inherited affinity (a core5/nice19 parent) so the server gets every core + # (test mode: cores 0-9, the host budget). + cpus=$(cat /sys/devices/system/cpu/online); [ -n "$TEST" ] && cpus=0-9 + aff=(taskset -c "$cpus"); "${aff[@]}" true 2> /dev/null || aff=() + # A background subshell is not a group leader, so setsid(1) does not fork: SERVER is the session and group id. + (cd "$(dirname "$BIN")" && exec setsid "${aff[@]}" env AIEN_GB10_LOCK_HELD=1 AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-$PORT.lock \ + AIEN_Q36_STROKE=0 "${ENVS[@]}" "$BIN" --engine omega --model-dir "$MODEL" --port $PORT --bind 127.0.0.1 \ + --max-tokens-cap 16384 --thinking off "${flags[@]}") > "$1" 2>&1 < /dev/null & + SERVER=$!; echo "$SERVER" > "$PIDF" + lim=$(left_s 300) || { log "no lease time left to start the server"; stop_server; return 1; } + for _ in $(seq "$lim"); do + kill -0 "$SERVER" 2>/dev/null || { log "server exited during load: $1"; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER=; return 1; } + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null && break; sleep 1 + done + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null || { log "server not healthy in $lim s"; stop_server; return 1; } + [ "$(ps -o sid= -p "$SERVER" | tr -d ' ')" = "$SERVER" ] || { log "server $SERVER is not its own session leader"; stop_server; return 1; } + l=$(ss -ltnH "sport = :$PORT" | awk '{print $4}') + if [ -z "$l" ] || echo "$l" | grep -qv '^127\.0\.0\.1:'; then log "listener check FAILED on $PORT: $l"; stop_server; return 1; fi + } + trap 'stop_server; board "GPU-END dra-65 window-dra65.sh window $WIN steps ${STEPS[*]} -> $OUT (rc ${RC:-?})"' EXIT + trap 'log "interrupted"; RC=4; exit 4' INT TERM + setsid bash "$SELF" _watch $$ "$HOLDER" "$DEADLINE" "$PIDF" >> "$OUT/watch.log" 2>&1 < /dev/null & + board "GPU-START dra-65 window-dra65.sh window $WIN steps ${STEPS[*]} (est $total s, lease left $left s; gb10 lock held by our pid $HOLDER; bin $SHA)" + log "window $WIN lock holder $HOLDER bin $BIN sha256 $SHA steps ${STEPS[*]} est $total s left $left s deadline $(date -u -d @$DEADLINE +%FT%TZ)" + RC=0 + for s in "${STEPS[@]}"; do + step_def "$s"; [ -n "$TEST" ] && EST=5 + D=$OUT/$s; mkdir -p "$D"; t0=$(date +%s); why= + log "step $s: $DOOR door, env '${ENVS[*]:-}', $PROBE, est $EST s" + if [ $((t0 + EST)) -gt "$DEADLINE" ]; then + ready=-1; RC=3; why="not started: est $EST s, $((DEADLINE - t0)) s left"; : > "$D/probe.out" + elif start_server "$D/server.log"; then + ready=$(( $(date +%s) - t0 )) + read -r kind a1 a2 <<<"$PROBE" + if [ "$kind" = golden ]; then + args=(golden $PORT "$D" "$a1" "$SHA" "$a2") + [ "$a1" = green ] && args+=("$OUT/1/golden-receipt.json" "$OUT/2/golden-receipt.json") + else + args=(time $PORT "$D" "$SHA" "$a1") + fi + if lim=$(left_s); then + DRA65_SERVER_LOG=$D/server.log timeout -k 10 "$lim" bash "$SELF" "${args[@]}" > "$D/probe.out"; RC=$? + case $RC in 124|137) RC=2; why="probe stopped at the lease deadline" ;; esac + else + RC=2; why="no lease time left for the probe" + fi + stop_server + else + ready=-1; RC=3; why="server did not come up" + fi + el=$(( $(date +%s) - t0 )); expired=false + if [ -e "$SPARK_WINDOW_DIR/expired" ] || [ "$(date +%s)" -ge "$DEADLINE" ]; then + expired=true; [ $RC = 3 ] || { RC=2; why="lease expired before the step ended${why:+ ($why)}"; } + fi + pj=$(tail -n 1 "$D/probe.out" 2>/dev/null | jq -c . 2>/dev/null); [ -n "$pj" ] || pj=null + case $RC in 0) v=$(jq -r '.verdict // "PASS"' <<<"$pj") ;; 1) v=FAIL ;; 2) v=INCONCLUSIVE ;; 3) v=NOT_RUN ;; *) v=INCONCLUSIVE ;; esac + jq -cn --arg s "$s" --arg w "$WIN" --arg b "$BIN" --arg h "$SHA" --arg d "$DOOR" --arg e "${ENVS[*]:-}" --arg p "$PROBE" \ + --argjson est $EST --argjson ready $ready --argjson el $el --argjson rc $RC --arg hold "$HOLDER" --arg at "$(date -u +%FT%TZ)" \ + --argjson probe "$pj" --argjson x $expired --arg v "$v" --arg why "$why" --argjson dl "$DEADLINE" \ + '{step:$s, window:$w, bin:$b, bin_sha256:$h, door:$d, env:$e, probe:$p, est_s:$est, server_ready_s:$ready, elapsed_s:$el, + rc:$rc, verdict:$v, why:$why, lease_expired:$x, deadline:$dl, lock_holder:$hold, at:$at, result:$probe}' \ + | tee "$D/step-receipt.json" + [ $RC = 0 ] || { log "step $s rc $RC ($v${why:+: $why}): stopping"; exit $RC; } + done + exit 0 ;; +esac + +[ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: the probes run from '$0 run' inside a window" +WIN=$SPARK_WINDOW +MODE=${1:-}; PORT=${2:-}; OUT=${3:-} +[ -n "$MODE" ] && [ -n "$PORT" ] && [ -n "$OUT" ] || die "usage: see the header" +URL=http://127.0.0.1:$PORT +(cd "$REPO" && sha256sum -c --quiet "$HERE/SHA256SUMS") || die "pinned inputs changed" +mkdir -p "$OUT" +MODEL=$(curl -s -m 10 "$URL/v1/models" | jq -r '.data[0].id // empty' 2>/dev/null) +[ -n "$MODEL" ] || die "no model on $URL" +DEF=$(jq -c .defaults "$HERE/set32.json") +SET=$HERE/set32.json; LONG=$HERE/long-goldens.json +req() { # [stream] + jq -cn --arg m "$MODEL" --argjson msg "$1" --argjson n "$2" --argjson d "$DEF" --argjson s "${3:-false}" \ + '$d + {model:$m, messages:$msg, max_tokens:$n} + (if $s then {stream:true, stream_options:{include_usage:true}} else {} end)' +} +user() { jq -cn --arg u "$1" '[{role:"user",content:$u}]'; } +# ask : prints the HTTP code (000 without lease time left) +ask() { + local m; m=$(left_s 1800) || { : > "$3"; echo 000; return; } + curl -s -m "$m" -o "$3" -w '%{http_code}' "$URL/v1/chat/completions" -H 'Content-Type: application/json' -d "$(req "$1" "$2")" +} +judge() { # : prints SAME|DIFF|SHORT|NO_IDS + local got; [ "$1" = 200 ] || { echo NO_IDS; return; } + got=$(jq -c '.usage.aien_token_ids | select(type == "array" and length > 0)' "$2" 2>/dev/null) + [ -n "$got" ] || { echo NO_IDS; return; } + jq -rn --argjson g "$got" --argjson w "$3" ' + ([$g, $w] | map(length) | min) as $m + | if $g == $w then "SAME" + elif ([range(0; $m) | select($g[.] != $w[.])] | length) > 0 then "DIFF" + elif ($g | length) > ($w | length) then "DIFF" + else "SHORT" end' +} + +case $MODE in +golden) + EXPECT=${4:-}; BIN=${5:-}; LABEL=${6:-} + case $EXPECT in red|green) ;; *) die "golden needs red|green";; esac + [[ $BIN =~ ^[0-9a-f]{64}$ ]] || die "BIN_SHA256 must be the server binary's sha256" + [ -n "$LABEL" ] || die "LABEL missing" + if [ "$EXPECT" = green ]; then + # A red receipt counts only next to run's step receipt for it: rc 0, same binary, lock held, lease not expired. + shift 6; reds=$(for r in "$@"; do + d=$(dirname "$r"); red_ok "$(dirname "$d")" "$(basename "$d")" "$BIN" || continue + jq -r --arg b "$BIN" 'select(.case == "golden" and .expect == "red" and .verdict == "PASS" and .bin_sha256 == $b) | .label' "$r" 2>/dev/null + done | sort -u | wc -l) + [ "$reds" -ge 2 ] || die "green refused: needs >= 2 red PASS receipts (distinct labels) for binary $BIN, each with a passing step-receipt.json of 'run', got $reds" + fi + : > "$OUT/golden.jsonl"; declare -A n=([SAME]=0 [DIFF]=0 [SHORT]=0 [NO_IDS]=0 [NO_SNAP]=0) + rec() { jq -cn --arg id "$1" --arg v "$2" --arg h "$3" --argjson w "$4" --arg win "$WIN" --arg b "$BIN" --arg sn "${6:-}" \ + --slurpfile r <(jq -c . "$5" 2>/dev/null || echo null) \ + '{id:$id, verdict:$v, http:$h, got:($r[0].usage.aien_token_ids // null), golden:$w, window:$win, bin_sha256:$b} + + (if $sn == "" then {} else {snapshot_log:$sn} end)' >> "$OUT/golden.jsonl"; } + for i in $(seq 0 31); do + u=$(jq -r ".prompts[$i].user" "$SET"); m=$(jq -r ".prompts[$i].max_tokens" "$SET"); w=$(jq -c ".prompts[$i].golden_ids" "$SET") + h=$(ask "$(user "$u")" "$m" "$OUT/p$i.raw"); v=$(judge "$h" "$OUT/p$i.raw" "$w"); n[$v]=$((n[$v]+1)); rec "p$i" "$v" "$h" "$w" "$OUT/p$i.raw" + done + # turn2 right after long-2048: the door restores the snapshot it took at long-2048's answer header; the + # server log lines written during the turn2 request must show it (single and batch door wording). + SLOG=${DRA65_SERVER_LOG:-} + for name in long-256 long-8192 long-2048 turn2; do + c=$(jq -c --arg n "$name" '.prompts[] | select(.name == $n)' "$LONG"); w=$(jq -c .golden_ids <<<"$c"); m=$(jq -r .max_tokens <<<"$c") + if [ "$name" = turn2 ]; then msg=$(jq -c . "$REPO/$(jq -r .messages <<<"$c")"); else msg=$(user "$(cat "$REPO/$(jq -r .file <<<"$c")")"); fi + before=0; [ -n "$SLOG" ] && before=$(wc -l < "$SLOG") + h=$(ask "$msg" "$m" "$OUT/$name.raw"); v=$(judge "$h" "$OUT/$name.raw" "$w"); sn= + if [ "$name" = turn2 ]; then + [ -n "$SLOG" ] && sn=$(tail -n "+$((before + 1))" "$SLOG" | grep -E 'reuse Snapshot\(|tok \(snapshot, row' | tail -n 1) + [ -n "$sn" ] || { sn="(none: ${SLOG:-no DRA65_SERVER_LOG})"; [ "$v" = NO_IDS ] || v=NO_SNAP; } + fi + n[$v]=$((n[$v]+1)); rec "$name" "$v" "$h" "$w" "$OUT/$name.raw" "$sn" + done + if [ "$EXPECT" = red ]; then + if [ $((n[NO_IDS] + n[SHORT] + n[NO_SNAP])) -gt 0 ]; then verdict=INCONCLUSIVE; rc=2 + elif [ "${n[DIFF]}" -gt 0 ]; then verdict=PASS; rc=0; else verdict=FAIL; rc=1; fi + else + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2 + elif [ "${n[SAME]}" -eq 36 ]; then verdict=PASS; rc=0; else verdict=FAIL; rc=1; fi + fi + jq -cn --arg e "$EXPECT" --arg v $verdict --arg b "$BIN" --arg l "$LABEL" --argjson s "${n[SAME]}" --argjson d "${n[DIFF]}" \ + --argjson sh "${n[SHORT]}" --argjson x "${n[NO_IDS]}" --argjson ns "${n[NO_SNAP]}" --arg port "$PORT" --arg at "$(date -u +%FT%TZ)" --arg win "$WIN" \ + '{case:"golden", expect:$e, verdict:$v, bin_sha256:$b, label:$l, window:$win, same:$s, diff:$d, short:$sh, no_ids:$x, no_snap:$ns, of:36, port:$port, at:$at}' \ + | tee "$OUT/golden-receipt.json" + exit $rc ;; +time) + BIN=${4:-}; LABEL=${5:-} + [[ $BIN =~ ^[0-9a-f]{64}$ ]] || die "BIN_SHA256 must be the server binary's sha256" + [ -n "$LABEL" ] || die "LABEL missing" + # TTFT = first content delta - t0 (client clock); e2e tok/s = completion_tokens / (t_end - t_first). + # Medians of the 3 runs go through Wolfram afterwards (README). + : > "$OUT/time.jsonl"; ok=1 + for name in long-512 long-8192; do + f=$HERE/$name.txt; [ -f "$f" ] || f=$REPO/evidence/merge-train/l369/$name.txt + for run in 1 2 3; do + o=$OUT/$name-r$run; : > "$o.sse"; t0=$(date +%s.%N); first="" + if m=$(left_s 1800); then + while IFS= read -r line; do + [ -z "$first" ] && [[ $line =~ ^data:.*\"content\":\ *\"[^\"] ]] && first=$(date +%s.%N) + printf '%s\n' "$line" >> "$o.sse" + done < <(curl -s -N -m "$m" -w '\nHTTP %{http_code}\n' "$URL/v1/chat/completions" -H 'Content-Type: application/json' \ + -d "$(req "$(user "$(cat "$f")")" 256 true)") + fi + t1=$(date +%s.%N) + code=$(grep -o '^HTTP [0-9]*' "$o.sse" | tail -n 1 | cut -c6-) + usage=$(grep '^data: {' "$o.sse" | sed 's/^data: //' | jq -c 'select(.usage != null) | .usage' 2>/dev/null | tail -n 1) + good=$(jq -n --arg c "${code:-}" --arg f "$first" --argjson u "${usage:-null}" \ + '$c == "200" and $f != "" and ($u | type) == "object" and (($u.completion_tokens // 0) > 0)') + [ "$good" = true ] || ok=0 + jq -cn --arg n "$name" --argjson r $run --arg b "$BIN" --arg l "$LABEL" --arg h "${code:-}" --arg t0 "$t0" --arg tf "$first" \ + --arg t1 "$t1" --argjson u "${usage:-null}" --argjson g "$good" --arg win "$WIN" \ + '{prompt:$n, run:$r, bin_sha256:$b, label:$l, window:$win, http:$h, ok:$g, t0:$t0, t_first:$tf, t_end:$t1, usage:$u}' | tee -a "$OUT/time.jsonl" + done + done + if [ $ok = 1 ]; then jq -cn --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" '{case:"time", verdict:"RECORDED", window:$win, bin_sha256:$b, label:$l}'; exit 0; fi + jq -cn --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" '{case:"time", verdict:"INCONCLUSIVE", window:$win, bin_sha256:$b, label:$l, why:"a run had no HTTP 200, no first content delta or no usage"}'; exit 2 ;; +*) die "mode plan|run|golden|time" ;; +esac diff --git a/evidence/dra87-first-token/window-dra87.sh b/evidence/dra87-first-token/window-dra87.sh new file mode 100755 index 00000000..9fe065b2 --- /dev/null +++ b/evidence/dra87-first-token/window-dra87.sh @@ -0,0 +1,366 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DRA-87 chip window (greedy token 0 from the chip argmax at the end of prefill, AIEN_SERVE_CHIP_FIRST_TOKEN). +# A copy of evidence/dra65-prefill-20261031/window-dra65.sh (same lock, lease, watchdog, golden and time probes, +# same pinned goldens and prompts, read from that directory); only the steps differ. Main opens +# `spark-window open ... --gb10 none --quiet exclusive --lease 20`, stops 18091 and Flint, then runs one lease's steps as +# spark-window run bash window-dra87.sh run BIN OUT STEP [STEP ...] +# BIN = the server binary built from this branch, OUT = a receipt root shared by every lease (step N writes +# OUT/N/). The server's chip reservation (aien-serve-http chip_reservation.rs) only accepts /tmp/aien-gb10.lock +# held by one of its ancestors, so this script takes `flock -n -o` on it itself (the lock stays in flock(1), an +# ancestor; no descendant inherits the fd) and starts every server as its child, in its own session +# (setsid, pid file OUT/.server..pid), with AIEN_GB10_LOCK_HELD=1 and the affinity reset of the live start scripts. +# Exit 3 = NOT_RUN, chip untouched: no SPARK_WINDOW, the lock held by someone else, a listener on +# 18091/18300/18310 or the test port, a compute app on the chip, the binary or model missing, a green step +# without passing red steps (listed before it, or their step receipts in OUT/1 and OUT/2), or the steps' +# estimated time longer than the lease has left. +# Lease: deadline = SPARK_WINDOW_DIR/held + lease * SPARK_LEASE_UNIT_S (default 60). Every server wait and +# probe is bounded by the time left (timeout, curl -m). A watchdog in its own session stops the server group +# at the deadline (and this script if it has not ended 40 s later), or at once when this script or the lock +# holder dies; the lock is then released. +# A step that ends after the deadline or with SPARK_WINDOW_DIR/expired present is INCONCLUSIVE (rc 2). +# window-dra87.sh plan (no window needed: the steps, their server env and estimated durations) +# Every receipt line carries the window id and the binary sha256. +# +# Probes (an already running server on PORT; `run` calls them, the host checks them against a mock door): +# window-dra87.sh golden PORT OUT red BIN_SHA256 LABEL +# window-dra87.sh golden PORT OUT green BIN_SHA256 LABEL RED_RECEIPT RED_RECEIPT [...] +# 36 cases (32-prompt set, 3 long prompts, turn 2 restoring the long-2048 snapshot) vs the pinned goldens. +# green refuses to run unless it is handed at least two red receipts (verdict PASS, distinct labels) of +# the same server binary sha256, each next to a step-receipt.json of `run` with rc 0, the same +# bin_sha256, a lock holder and the lease not expired: red before green. +# With DRA65_SERVER_LOG (set by `run`), turn2 also needs the door's snapshot-restore log line for that +# request (single: `reuse Snapshot(`, qwen38_engine.rs; batch: `tok (snapshot, row`, qwen36_batch.rs). +# window-dra87.sh time PORT OUT BIN_SHA256 LABEL +# TTFT and end-to-end tok/s, ~512 and 8210-token prompts, 3 runs each. +# Per case: SAME (ids equal), DIFF (a flip inside the common length, or more ids than the golden), +# SHORT (a strict prefix of the golden: no flip shown), NO_IDS (HTTP error, missing or empty ids), +# NO_SNAP (turn2 without the snapshot-restore log line). +# golden red: PASS = at least one DIFF and no NO_IDS/SHORT/NO_SNAP; those -> INCONCLUSIVE; else FAIL. +# golden green: PASS = all SAME; any NO_IDS -> INCONCLUSIVE; else (NO_SNAP included) FAIL. +# Exit 0 = PASS, 1 = FAIL, 2 = INCONCLUSIVE or refused, 3 = NOT_RUN, 4 = interrupted. time: 0 only if every run +# has HTTP 200, a first content delta and usage with completion_tokens > 0; else 2. `run` stops at the first +# step that does not exit 0 and returns its code. +set -uo pipefail +HERE=$(cd "$(dirname "$0")" && pwd); REPO=$(cd "$HERE/../.." && pwd); SELF=$HERE/$(basename "$0") +DATA=$REPO/evidence/dra65-prefill-20261031 # pinned goldens, prompts and their SHA256SUMS +die() { echo "window-dra87: $*" >&2; exit 2; } +not_run() { echo "window-dra87: NOT_RUN: $*" >&2; exit 3; } +# left_s [CAP]: seconds to DRA65_DEADLINE (unset: CAP), at most CAP; returns 1 when none are left. +left_s() { + local cap=${1:-999999} l + if [ -n "${DRA65_DEADLINE:-}" ]; then l=$((DRA65_DEADLINE - $(date +%s))); [ "$l" -lt "$cap" ] || l=$cap; else l=$cap; fi + echo "$l"; [ "$l" -gt 0 ] +} + +# step -> door, server env, probe, estimated seconds. MODELED (Wolfram, README "Window"): decode 0.0201 s/token, +# chunked prompts 250 tok/s (8210: 196.8), stepped prompts 0.0201 s/token; upper bounds at max_tokens; each +# includes ~33 s server start. +# DRA-87: F = AIEN_SERVE_CHIP_FIRST_TOKEN=1 (token 0 of a greedy reply from the chip argmax, no logits read); +# M = AIEN_Q36_TEST_FIRST_TOKEN_MUTANT=1 (with F: token 0 replaced by a neighbouring id, the red arm). +step_def() { + local F=AIEN_SERVE_CHIP_FIRST_TOKEN=1 M=AIEN_Q36_TEST_FIRST_TOKEN_MUTANT=1 + ENVS=(); case $1 in + 1) DOOR=single; ENVS=($F $M); PROBE="golden red first-mutant-single"; EST=120 ;; + 2) DOOR=batch; ENVS=($F $M); PROBE="golden red first-mutant-batch"; EST=120 ;; + 3) DOOR=single; ENVS=($F); PROBE="golden green first-single"; EST=120 ;; + 4) DOOR=batch; ENVS=($F); PROBE="golden green first-batch"; EST=120 ;; + 5) DOOR=batch; PROBE="golden green flag-off-batch"; EST=120 ;; + 6a) DOOR=single; PROBE="time single-off"; EST=195 ;; + 6b) DOOR=single; ENVS=($F); PROBE="time single-first"; EST=195 ;; + 6c) DOOR=batch; PROBE="time batch-off"; EST=195 ;; + 6d) DOOR=batch; ENVS=($F); PROBE="time batch-first"; EST=195 ;; + *) return 1 ;; + esac +} +# red_ok OUT STEP SHA: that red step's run receipt passed for this binary inside the lease. +red_ok() { + jq -e --arg b "$3" '.rc == 0 and .bin_sha256 == $b and (.lock_holder | length) > 0 and .lease_expired == false + and .result.case == "golden" and .result.expect == "red" and .result.verdict == "PASS"' "$1/$2/step-receipt.json" > /dev/null 2>&1 +} + +case ${1:-} in +plan) + printf '%-4s %-7s %-55s %-24s %s\n' step door "server env" probe est_s + for s in 1 2 3 4 5 6a 6b 6c 6d; do + step_def $s; printf '%-4s %-7s %-55s %-24s %s\n' $s $DOOR "${ENVS[*]:--}" "$PROBE" $EST + done + echo "Steps 1-2 (red) come first; 3-5 need them earlier in the same run or their step receipts in OUT/1 and OUT/2." + echo "20-min leases: L1 = run BIN OUT 1 2 3 4 5 (600 s), L2 = 6a 6b (390 s), L3 = 6c 6d (390 s)." + exit 0 ;; +_watch) # _watch MAIN HOLDER DEADLINE PIDFILE (own session; started by run) + M=$2; H=$3; DL=$4; PF=$5 + while kill -0 "$M" 2>/dev/null && kill -0 "$H" 2>/dev/null && [ "$(date +%s)" -lt "$DL" ]; do sleep 1; done + why="deadline"; kill -0 "$M" 2>/dev/null || why="run shell $M gone"; kill -0 "$H" 2>/dev/null || why="lock holder $H gone" + pg=$(cat "$PF" 2>/dev/null) + if [ -n "$pg" ] && kill -0 -- "-$pg" 2>/dev/null; then + echo "$(date -u +%FT%TZ) watchdog: $why: TERM server group $pg" + kill -TERM -- "-$pg" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$pg" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$pg" 2>/dev/null; rm -f "$PF" + fi + # At the deadline the run shell's own bounds (probe timeout, stop_server) end the step as INCONCLUSIVE and it + # exits: give it 40 s to write that receipt. Its exit ends flock(1), which releases the lock. + if [ "$why" = deadline ]; then for _ in $(seq 40); do kill -0 "$M" 2>/dev/null || break; sleep 1; done; fi + kill -0 "$M" 2>/dev/null && { echo "$(date -u +%FT%TZ) watchdog: $why: TERM run shell $M"; kill -TERM "$M"; } + exit 0 ;; +run) + [ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: run as 'spark-window run bash $0 run ...' inside a --quiet exclusive window" + [ $# -ge 4 ] || die "usage: run BIN OUT STEP [STEP ...]" + # DRA65_TEST_LOCK (host check only): another lock file; the binary must be a script (a mock door, never the + # ELF server), the chip and live-port checks are skipped and board lines go to OUT/board.log. + LOCK=${DRA65_TEST_LOCK:-/tmp/aien-gb10.lock}; TEST=${DRA65_TEST_LOCK:+1} + if [ "${DRA65_LOCKED:-}" != "$SPARK_WINDOW" ]; then + # flock(1) holds the lock in its own process (-o: closed before exec, so no descendant inherits it) and + # runs us as its child: the holder is an ancestor of this shell and of every server it starts. + DRA65_LOCKED=$SPARK_WINDOW flock -n -o -E 75 "$LOCK" bash "$SELF" "$@"; rc=$? + [ $rc = 75 ] && not_run "$LOCK is held by another process; this script takes it itself (open the window with --gb10 none)" + exit $rc + fi + BIN=$(readlink -f "$2"); OUT=$(readlink -m "$3"); shift 3; STEPS=("$@") + WIN=$SPARK_WINDOW + # 1. An exclusive flock on LOCK held by an ancestor of this shell (/proc/locks: "N: FLOCK ADVISORY WRITE pid maj:min:ino"). + ino=$(stat -c %i "$LOCK") || not_run "$LOCK missing" + holders=$(awk -v ino="$ino" '$2 == "FLOCK" && $4 == "WRITE" { split($6, a, ":"); if (a[3] == ino) print $5 }' /proc/locks | sort -u) + anc=" "; p=$$ + while [ "$p" -gt 1 ]; do anc="$anc$p "; p=$(awk '{print $4}' "/proc/$p/stat" 2>/dev/null) || break; done + HOLDER=; for h in $holders; do case "$anc" in *" $h "*) HOLDER=$h ;; esac; done + [ -n "$HOLDER" ] || not_run "$LOCK held by pid(s) '${holders}', none an ancestor of $$ ($anc)" + if [ -n "$TEST" ]; then + [ -x "$BIN" ] && [ "$(head -c 4 "$BIN" | od -An -c | tr -d ' ')" != '177ELF' ] \ + || not_run "test lock $LOCK held by ancestor $HOLDER; DRA65_TEST_LOCK only runs a script mock door, never the server binary" + fi + [ -x "$BIN" ] || not_run "binary $BIN missing" + SHA=$(sha256sum < "$BIN" | cut -c1-64) + # 2. Steps known; each green step after both red steps in this run, or their passing step receipts in OUT. + total=0; seen1=0; seen2=0 + for s in "${STEPS[@]}"; do + step_def "$s" || die "unknown step $s (see: $0 plan)" + [ -n "$TEST" ] && EST=5 + total=$((total + EST)) + case $s in + 1) seen1=1 ;; 2) seen2=1 ;; + 3|4|5) { [ $seen1 = 1 ] || red_ok "$OUT" 1 "$SHA"; } && { [ $seen2 = 1 ] || red_ok "$OUT" 2 "$SHA"; } \ + || not_run "green step $s needs red steps 1 and 2 before it in this run, or their passing step receipts in $OUT/1 and $OUT/2 for bin $SHA" ;; + esac + done + # 3. The lease has room for the steps' estimates. + lease=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/lease" 2>/dev/null); held=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/held" 2>/dev/null) + [ -n "$lease" ] && [ -n "$held" ] || not_run "no lease/held in SPARK_WINDOW_DIR='${SPARK_WINDOW_DIR:-}'" + [ -e "$SPARK_WINDOW_DIR/expired" ] && not_run "the lease has expired ($SPARK_WINDOW_DIR/expired)" + heldt=$(date -d "$held" +%s) || not_run "cannot read held time '$held'" + DEADLINE=$(( heldt + lease * ${SPARK_LEASE_UNIT_S:-60} )); export DRA65_DEADLINE=$DEADLINE + left=$(( DEADLINE - $(date +%s) )) + [ "$total" -le "$left" ] || not_run "steps ${STEPS[*]} estimate $total s, the lease has $left s left" + # 4. Live 35B, Flint and the chip idle; model, port, tools there. + PORT=${DRA65_TEST_PORT:-18192}; [ -n "$TEST" ] || PORT=18192 + MODEL=$HOME/models/qwen3.6-35b-a3b-fp8-95a723d0 + for t in curl jq ss flock setsid timeout sha256sum; do command -v $t > /dev/null || not_run "$t missing"; done + [ -z "$(ss -ltnH "sport = :$PORT")" ] || not_run "a listener is on $PORT" + if [ -z "$TEST" ]; then + command -v nvidia-smi > /dev/null || not_run "nvidia-smi missing" + for port in 18091 18300 18310; do [ -z "$(ss -ltnH "sport = :$port")" ] || not_run "a listener is on $port"; done + apps=$(nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv,noheader 2>&1) || not_run "nvidia-smi failed: $apps" + [ -z "$apps" ] || not_run "compute apps on the chip: $apps" + [ -f "$MODEL/config.json" ] || not_run "model $MODEL missing" + fi + mkdir -p "$OUT" || not_run "cannot create $OUT" + PIDF=$OUT/.server.$$.pid # per run: a previous run's watchdog never sees this run's server + log() { echo "$(date -u +%FT%TZ) $*" | tee -a "$OUT/run.log" >&2; } + board() { + if [ -n "$TEST" ]; then echo "$(date -u +%FT%TZ) Ttft87: $*" >> "$OUT/board.log" + else echo "$(date -u +%FT%TZ) Ttft87: $*" >> "$HOME/handoffs/BOARD.md"; fi + } + SERVER= + stop_server() { # TERM the server's process group (its own session), KILL after 20 s + [ -n "$SERVER" ] || return 0 + kill -TERM -- "-$SERVER" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$SERVER" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$SERVER" 2>/dev/null; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER= + } + # start_server LOG: DOOR and ENVS from step_def; the live start-35b(-batch).sh flags on a loopback test port. + start_server() { + local flags=(--max-context 131072) aff cpus lim l + [ "$DOOR" = batch ] && flags=(--max-context 49152 --batch-slots 8) + # As start-35b(-batch).sh: undo an inherited affinity (a core5/nice19 parent) so the server gets every core + # (test mode: cores 0-9, the host budget). + cpus=$(cat /sys/devices/system/cpu/online); [ -n "$TEST" ] && cpus=0-9 + aff=(taskset -c "$cpus"); "${aff[@]}" true 2> /dev/null || aff=() + # A background subshell is not a group leader, so setsid(1) does not fork: SERVER is the session and group id. + (cd "$(dirname "$BIN")" && exec setsid "${aff[@]}" env AIEN_GB10_LOCK_HELD=1 AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-$PORT.lock \ + AIEN_Q36_STROKE=0 "${ENVS[@]}" "$BIN" --engine omega --model-dir "$MODEL" --port $PORT --bind 127.0.0.1 \ + --max-tokens-cap 16384 --thinking off "${flags[@]}") > "$1" 2>&1 < /dev/null & + SERVER=$!; echo "$SERVER" > "$PIDF" + lim=$(left_s 300) || { log "no lease time left to start the server"; stop_server; return 1; } + for _ in $(seq "$lim"); do + kill -0 "$SERVER" 2>/dev/null || { log "server exited during load: $1"; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER=; return 1; } + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null && break; sleep 1 + done + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null || { log "server not healthy in $lim s"; stop_server; return 1; } + [ "$(ps -o sid= -p "$SERVER" | tr -d ' ')" = "$SERVER" ] || { log "server $SERVER is not its own session leader"; stop_server; return 1; } + l=$(ss -ltnH "sport = :$PORT" | awk '{print $4}') + if [ -z "$l" ] || echo "$l" | grep -qv '^127\.0\.0\.1:'; then log "listener check FAILED on $PORT: $l"; stop_server; return 1; fi + } + trap 'stop_server; board "GPU-END dra-87 window-dra87.sh window $WIN steps ${STEPS[*]} -> $OUT (rc ${RC:-?})"' EXIT + trap 'log "interrupted"; RC=4; exit 4' INT TERM + setsid bash "$SELF" _watch $$ "$HOLDER" "$DEADLINE" "$PIDF" >> "$OUT/watch.log" 2>&1 < /dev/null & + board "GPU-START dra-87 window-dra87.sh window $WIN steps ${STEPS[*]} (est $total s, lease left $left s; gb10 lock held by our pid $HOLDER; bin $SHA)" + log "window $WIN lock holder $HOLDER bin $BIN sha256 $SHA steps ${STEPS[*]} est $total s left $left s deadline $(date -u -d @$DEADLINE +%FT%TZ)" + RC=0 + for s in "${STEPS[@]}"; do + step_def "$s"; [ -n "$TEST" ] && EST=5 + D=$OUT/$s; mkdir -p "$D"; t0=$(date +%s); why= + log "step $s: $DOOR door, env '${ENVS[*]:-}', $PROBE, est $EST s" + if [ $((t0 + EST)) -gt "$DEADLINE" ]; then + ready=-1; RC=3; why="not started: est $EST s, $((DEADLINE - t0)) s left"; : > "$D/probe.out" + elif start_server "$D/server.log"; then + ready=$(( $(date +%s) - t0 )) + read -r kind a1 a2 <<<"$PROBE" + if [ "$kind" = golden ]; then + args=(golden $PORT "$D" "$a1" "$SHA" "$a2") + [ "$a1" = green ] && args+=("$OUT/1/golden-receipt.json" "$OUT/2/golden-receipt.json") + else + args=(time $PORT "$D" "$SHA" "$a1") + fi + if lim=$(left_s); then + DRA65_SERVER_LOG=$D/server.log timeout -k 10 "$lim" bash "$SELF" "${args[@]}" > "$D/probe.out"; RC=$? + case $RC in 124|137) RC=2; why="probe stopped at the lease deadline" ;; esac + else + RC=2; why="no lease time left for the probe" + fi + stop_server + else + ready=-1; RC=3; why="server did not come up" + fi + el=$(( $(date +%s) - t0 )); expired=false + if [ -e "$SPARK_WINDOW_DIR/expired" ] || [ "$(date +%s)" -ge "$DEADLINE" ]; then + expired=true; [ $RC = 3 ] || { RC=2; why="lease expired before the step ended${why:+ ($why)}"; } + fi + pj=$(tail -n 1 "$D/probe.out" 2>/dev/null | jq -c . 2>/dev/null); [ -n "$pj" ] || pj=null + case $RC in 0) v=$(jq -r '.verdict // "PASS"' <<<"$pj") ;; 1) v=FAIL ;; 2) v=INCONCLUSIVE ;; 3) v=NOT_RUN ;; *) v=INCONCLUSIVE ;; esac + jq -cn --arg s "$s" --arg w "$WIN" --arg b "$BIN" --arg h "$SHA" --arg d "$DOOR" --arg e "${ENVS[*]:-}" --arg p "$PROBE" \ + --argjson est $EST --argjson ready $ready --argjson el $el --argjson rc $RC --arg hold "$HOLDER" --arg at "$(date -u +%FT%TZ)" \ + --argjson probe "$pj" --argjson x $expired --arg v "$v" --arg why "$why" --argjson dl "$DEADLINE" \ + '{step:$s, window:$w, bin:$b, bin_sha256:$h, door:$d, env:$e, probe:$p, est_s:$est, server_ready_s:$ready, elapsed_s:$el, + rc:$rc, verdict:$v, why:$why, lease_expired:$x, deadline:$dl, lock_holder:$hold, at:$at, result:$probe}' \ + | tee "$D/step-receipt.json" + [ $RC = 0 ] || { log "step $s rc $RC ($v${why:+: $why}): stopping"; exit $RC; } + done + exit 0 ;; +esac + +[ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: the probes run from '$0 run' inside a window" +WIN=$SPARK_WINDOW +MODE=${1:-}; PORT=${2:-}; OUT=${3:-} +[ -n "$MODE" ] && [ -n "$PORT" ] && [ -n "$OUT" ] || die "usage: see the header" +URL=http://127.0.0.1:$PORT +(cd "$REPO" && sha256sum -c --quiet "$DATA/SHA256SUMS") || die "pinned inputs changed" +mkdir -p "$OUT" +MODEL=$(curl -s -m 10 "$URL/v1/models" | jq -r '.data[0].id // empty' 2>/dev/null) +[ -n "$MODEL" ] || die "no model on $URL" +DEF=$(jq -c .defaults "$DATA/set32.json") +SET=$DATA/set32.json; LONG=$DATA/long-goldens.json +req() { # [stream] + jq -cn --arg m "$MODEL" --argjson msg "$1" --argjson n "$2" --argjson d "$DEF" --argjson s "${3:-false}" \ + '$d + {model:$m, messages:$msg, max_tokens:$n} + (if $s then {stream:true, stream_options:{include_usage:true}} else {} end)' +} +user() { jq -cn --arg u "$1" '[{role:"user",content:$u}]'; } +# ask : prints the HTTP code (000 without lease time left) +ask() { + local m; m=$(left_s 1800) || { : > "$3"; echo 000; return; } + curl -s -m "$m" -o "$3" -w '%{http_code}' "$URL/v1/chat/completions" -H 'Content-Type: application/json' -d "$(req "$1" "$2")" +} +judge() { # : prints SAME|DIFF|SHORT|NO_IDS + local got; [ "$1" = 200 ] || { echo NO_IDS; return; } + got=$(jq -c '.usage.aien_token_ids | select(type == "array" and length > 0)' "$2" 2>/dev/null) + [ -n "$got" ] || { echo NO_IDS; return; } + jq -rn --argjson g "$got" --argjson w "$3" ' + ([$g, $w] | map(length) | min) as $m + | if $g == $w then "SAME" + elif ([range(0; $m) | select($g[.] != $w[.])] | length) > 0 then "DIFF" + elif ($g | length) > ($w | length) then "DIFF" + else "SHORT" end' +} + +case $MODE in +golden) + EXPECT=${4:-}; BIN=${5:-}; LABEL=${6:-} + case $EXPECT in red|green) ;; *) die "golden needs red|green";; esac + [[ $BIN =~ ^[0-9a-f]{64}$ ]] || die "BIN_SHA256 must be the server binary's sha256" + [ -n "$LABEL" ] || die "LABEL missing" + if [ "$EXPECT" = green ]; then + # A red receipt counts only next to run's step receipt for it: rc 0, same binary, lock held, lease not expired. + shift 6; reds=$(for r in "$@"; do + d=$(dirname "$r"); red_ok "$(dirname "$d")" "$(basename "$d")" "$BIN" || continue + jq -r --arg b "$BIN" 'select(.case == "golden" and .expect == "red" and .verdict == "PASS" and .bin_sha256 == $b) | .label' "$r" 2>/dev/null + done | sort -u | wc -l) + [ "$reds" -ge 2 ] || die "green refused: needs >= 2 red PASS receipts (distinct labels) for binary $BIN, each with a passing step-receipt.json of 'run', got $reds" + fi + : > "$OUT/golden.jsonl"; declare -A n=([SAME]=0 [DIFF]=0 [SHORT]=0 [NO_IDS]=0 [NO_SNAP]=0) + rec() { jq -cn --arg id "$1" --arg v "$2" --arg h "$3" --argjson w "$4" --arg win "$WIN" --arg b "$BIN" --arg sn "${6:-}" \ + --slurpfile r <(jq -c . "$5" 2>/dev/null || echo null) \ + '{id:$id, verdict:$v, http:$h, got:($r[0].usage.aien_token_ids // null), golden:$w, window:$win, bin_sha256:$b} + + (if $sn == "" then {} else {snapshot_log:$sn} end)' >> "$OUT/golden.jsonl"; } + for i in $(seq 0 31); do + u=$(jq -r ".prompts[$i].user" "$SET"); m=$(jq -r ".prompts[$i].max_tokens" "$SET"); w=$(jq -c ".prompts[$i].golden_ids" "$SET") + h=$(ask "$(user "$u")" "$m" "$OUT/p$i.raw"); v=$(judge "$h" "$OUT/p$i.raw" "$w"); n[$v]=$((n[$v]+1)); rec "p$i" "$v" "$h" "$w" "$OUT/p$i.raw" + done + # turn2 right after long-2048: the door restores the snapshot it took at long-2048's answer header; the + # server log lines written during the turn2 request must show it (single and batch door wording). + SLOG=${DRA65_SERVER_LOG:-} + for name in long-256 long-8192 long-2048 turn2; do + c=$(jq -c --arg n "$name" '.prompts[] | select(.name == $n)' "$LONG"); w=$(jq -c .golden_ids <<<"$c"); m=$(jq -r .max_tokens <<<"$c") + if [ "$name" = turn2 ]; then msg=$(jq -c . "$REPO/$(jq -r .messages <<<"$c")"); else msg=$(user "$(cat "$REPO/$(jq -r .file <<<"$c")")"); fi + before=0; [ -n "$SLOG" ] && before=$(wc -l < "$SLOG") + h=$(ask "$msg" "$m" "$OUT/$name.raw"); v=$(judge "$h" "$OUT/$name.raw" "$w"); sn= + if [ "$name" = turn2 ]; then + [ -n "$SLOG" ] && sn=$(tail -n "+$((before + 1))" "$SLOG" | grep -E 'reuse Snapshot\(|tok \(snapshot, row' | tail -n 1) + [ -n "$sn" ] || { sn="(none: ${SLOG:-no DRA65_SERVER_LOG})"; [ "$v" = NO_IDS ] || v=NO_SNAP; } + fi + n[$v]=$((n[$v]+1)); rec "$name" "$v" "$h" "$w" "$OUT/$name.raw" "$sn" + done + if [ "$EXPECT" = red ]; then + if [ $((n[NO_IDS] + n[SHORT] + n[NO_SNAP])) -gt 0 ]; then verdict=INCONCLUSIVE; rc=2 + elif [ "${n[DIFF]}" -gt 0 ]; then verdict=PASS; rc=0; else verdict=FAIL; rc=1; fi + else + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2 + elif [ "${n[SAME]}" -eq 36 ]; then verdict=PASS; rc=0; else verdict=FAIL; rc=1; fi + fi + jq -cn --arg e "$EXPECT" --arg v $verdict --arg b "$BIN" --arg l "$LABEL" --argjson s "${n[SAME]}" --argjson d "${n[DIFF]}" \ + --argjson sh "${n[SHORT]}" --argjson x "${n[NO_IDS]}" --argjson ns "${n[NO_SNAP]}" --arg port "$PORT" --arg at "$(date -u +%FT%TZ)" --arg win "$WIN" \ + '{case:"golden", expect:$e, verdict:$v, bin_sha256:$b, label:$l, window:$win, same:$s, diff:$d, short:$sh, no_ids:$x, no_snap:$ns, of:36, port:$port, at:$at}' \ + | tee "$OUT/golden-receipt.json" + exit $rc ;; +time) + BIN=${4:-}; LABEL=${5:-} + [[ $BIN =~ ^[0-9a-f]{64}$ ]] || die "BIN_SHA256 must be the server binary's sha256" + [ -n "$LABEL" ] || die "LABEL missing" + # TTFT = first content delta - t0 (client clock); e2e tok/s = completion_tokens / (t_end - t_first). + # Medians of the 3 runs go through Wolfram afterwards (README). + : > "$OUT/time.jsonl"; ok=1 + for name in long-512 long-8192; do + f=$DATA/$name.txt; [ -f "$f" ] || f=$REPO/evidence/merge-train/l369/$name.txt + for run in 1 2 3; do + o=$OUT/$name-r$run; : > "$o.sse"; t0=$(date +%s.%N); first="" + if m=$(left_s 1800); then + while IFS= read -r line; do + [ -z "$first" ] && [[ $line =~ ^data:.*\"content\":\ *\"[^\"] ]] && first=$(date +%s.%N) + printf '%s\n' "$line" >> "$o.sse" + done < <(curl -s -N -m "$m" -w '\nHTTP %{http_code}\n' "$URL/v1/chat/completions" -H 'Content-Type: application/json' \ + -d "$(req "$(user "$(cat "$f")")" 256 true)") + fi + t1=$(date +%s.%N) + code=$(grep -o '^HTTP [0-9]*' "$o.sse" | tail -n 1 | cut -c6-) + usage=$(grep '^data: {' "$o.sse" | sed 's/^data: //' | jq -c 'select(.usage != null) | .usage' 2>/dev/null | tail -n 1) + good=$(jq -n --arg c "${code:-}" --arg f "$first" --argjson u "${usage:-null}" \ + '$c == "200" and $f != "" and ($u | type) == "object" and (($u.completion_tokens // 0) > 0)') + [ "$good" = true ] || ok=0 + jq -cn --arg n "$name" --argjson r $run --arg b "$BIN" --arg l "$LABEL" --arg h "${code:-}" --arg t0 "$t0" --arg tf "$first" \ + --arg t1 "$t1" --argjson u "${usage:-null}" --argjson g "$good" --arg win "$WIN" \ + '{prompt:$n, run:$r, bin_sha256:$b, label:$l, window:$win, http:$h, ok:$g, t0:$t0, t_first:$tf, t_end:$t1, usage:$u}' | tee -a "$OUT/time.jsonl" + done + done + if [ $ok = 1 ]; then jq -cn --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" '{case:"time", verdict:"RECORDED", window:$win, bin_sha256:$b, label:$l}'; exit 0; fi + jq -cn --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" '{case:"time", verdict:"INCONCLUSIVE", window:$win, bin_sha256:$b, label:$l, why:"a run had no HTTP 200, no first content delta or no usage"}'; exit 2 ;; +*) die "mode plan|run|golden|time" ;; +esac ```