Merge branch 'claude/quality-gate' into claude/port-gpu-bringup
This commit is contained in:
@@ -427,8 +427,9 @@ mod runner {
|
||||
sampler.as_ref(),
|
||||
clock_seed(),
|
||||
spec_min_p,
|
||||
vec![eos as i32],
|
||||
crate::qwen_forward::original_serve_request::original_stop_tokens(eos),
|
||||
);
|
||||
let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(eos);
|
||||
let cancelled = || cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed();
|
||||
let start = Instant::now();
|
||||
let mut utf8 = Utf8Pending::default();
|
||||
@@ -441,8 +442,8 @@ mod runner {
|
||||
generated_ids.extend_from_slice(tokens);
|
||||
let mut deliver = |token: i32| -> Result<(), GenerationFailure> {
|
||||
count += 1;
|
||||
if token as u32 == eos {
|
||||
// the authoritative EOS counts as an output token and carries no text
|
||||
if stop_tokens.contains(&token) {
|
||||
// the authoritative EOS (<|im_end|> or <|endoftext|>) counts as an output token and carries no text
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = tokenizer
|
||||
|
||||
@@ -138,7 +138,7 @@ fn original_serve_laptop_bench() {
|
||||
for rep in 0..repeat {
|
||||
for (k, &index) in order.iter().enumerate() {
|
||||
for arm in super::original_serve_arms::arms_for(&arms, k + rep) {
|
||||
let request = ServeRequest::new(prompts[index].clone(), max_new, None, 7, spec_min_p, vec![eos as i32]);
|
||||
let request = ServeRequest::new(prompts[index].clone(), max_new, None, 7, spec_min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos));
|
||||
super::original_serve_arms::serve_arm(&mut stack, &arm, &request, &format!("p{} rep{rep}", index + 1), &format!("prompt={}", prompts[index].len()));
|
||||
}
|
||||
}
|
||||
@@ -149,7 +149,7 @@ fn original_serve_laptop_bench() {
|
||||
}
|
||||
for pass in 0..repeat {
|
||||
for (index, ids) in prompts.iter().enumerate() {
|
||||
let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, vec![eos as i32]);
|
||||
let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos));
|
||||
let mut out = Vec::new();
|
||||
let begun = std::time::Instant::now();
|
||||
let mut first = None;
|
||||
|
||||
@@ -39,7 +39,7 @@ fn required_path(name: &str) -> PathBuf {
|
||||
}
|
||||
|
||||
fn request(prompt: &[u32], max_new: usize, sampler: Option<&leleka_sampler_ref::SamplerParams>, eos: u32) -> ServeRequest {
|
||||
ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, sampler, 7, 0.0, vec![eos as i32])
|
||||
ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, sampler, 7, 0.0, crate::qwen_forward::original_serve_request::original_stop_tokens(eos))
|
||||
}
|
||||
|
||||
fn report_timing(stack: &OriginalServeStack<'_, '_>, label: &str, produced: usize) {
|
||||
@@ -226,7 +226,7 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(","));
|
||||
}
|
||||
for arm in super::original_serve_arms::arms_for(&arms, k + rep) {
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, None, 7, min_p, vec![eos as i32]);
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, None, 7, min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos));
|
||||
super::original_serve_arms::serve_arm(&mut stack, &arm, &corpus_request, &format!("p{index} rep{rep}"), &format!("prompt={}", ids.len()));
|
||||
}
|
||||
}
|
||||
@@ -246,7 +246,27 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
};
|
||||
let ids = tokenizer.encode(&turn, true).expect("corpus tokenization failed");
|
||||
eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(","));
|
||||
// LELEKA_SMOKE_FORCE_DIR=dir (quality gate, docs/quality-gate.md): `dir/c<index>.truth` is the comma-separated
|
||||
// token list of this prompt followed by the tokens another engine produced for it. The first
|
||||
// LELEKA_SMOKE_FORCE_PASSES (default 1) passes of this prompt decode along that text (teacher forcing: the
|
||||
// picks are replaced by the text's tokens, the logits and the `LELEKA_TRACE_LOGPROBS` rows are the port's own);
|
||||
// later passes are free. A forced pass produces exactly the forced tokens.
|
||||
let truth: Option<Vec<i32>> = env::var_os("LELEKA_SMOKE_FORCE_DIR").and_then(|dir| {
|
||||
let file = std::path::Path::new(&dir).join(format!("c{index}.truth"));
|
||||
let text = std::fs::read_to_string(&file).ok()?;
|
||||
let sequence: Vec<i32> = text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect();
|
||||
assert!(
|
||||
sequence.len() > ids.len() && sequence[..ids.len()].iter().zip(&ids).all(|(a, &b)| *a == b as i32),
|
||||
"{}: the forced sequence must start with the tokenized prompt and extend it", file.display()
|
||||
);
|
||||
Some(sequence)
|
||||
});
|
||||
let forced_passes: usize = env::var("LELEKA_SMOKE_FORCE_PASSES").ok().and_then(|v| v.parse().ok()).unwrap_or(1);
|
||||
for pass in 0..repeat {
|
||||
let forced = truth.as_ref().filter(|_| pass < forced_passes);
|
||||
crate::qwen_forward::quality_force::set(forced.cloned());
|
||||
eprintln!("DBG corpus {index} pass={pass} begin forced={}", forced.is_some());
|
||||
let max_new = forced.map_or(max_new, |t| t.len() - ids.len());
|
||||
let mut out = Vec::new();
|
||||
let min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0);
|
||||
// LELEKA_SMOKE_SAMPLED=1: the corpus is served with the sampling head and a penalty window (an agent-style
|
||||
@@ -256,7 +276,7 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
top_k: 20, top_p: 0.95, min_p: 0.0, temperature: 0.7, min_keep: 1, penalty_last_n: 64, penalty_repeat: 1.1,
|
||||
penalty_freq: 0.0, penalty_present: 0.0, seed: 1234, counter: 0, greedy: false,
|
||||
};
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, sampled.then_some(&sampler), 7, min_p, vec![eos as i32]);
|
||||
let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, sampled.then_some(&sampler), 7, min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos));
|
||||
let started = std::time::Instant::now();
|
||||
let mut first: Option<std::time::Duration> = None;
|
||||
let served = stack.serve(&corpus_request, &mut |round| {
|
||||
@@ -265,6 +285,11 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
Ok(())
|
||||
}, &mut || false);
|
||||
let total = started.elapsed();
|
||||
crate::qwen_forward::quality_force::set(None);
|
||||
if let (Some(t), Ok(_)) = (forced, &served) {
|
||||
eprintln!("DBG corpus {index} pass={pass} forced: produced {} of {} forced tokens, stopped as forced: {}", out.len(), t.len() - ids.len(),
|
||||
out.iter().zip(&t[ids.len()..]).all(|(a, b)| a == b));
|
||||
}
|
||||
match served {
|
||||
Ok(outcome) => {
|
||||
if pass == 0 {
|
||||
@@ -455,7 +480,18 @@ fn original_serve_long_context_streamed_kv_smoke() {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer<N>.ids` (comma-separated) holds the tokens
|
||||
// another engine answered to the N-token prompt; the request then decodes along that text (teacher forcing, see
|
||||
// `quality_force`) for exactly that many tokens, with the port's own logits and `LELEKA_TRACE_LOGPROBS` rows.
|
||||
let forced_answer: Option<Vec<i32>> = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR").and_then(|dir| {
|
||||
let text = std::fs::read_to_string(PathBuf::from(dir).join(format!("answer{}.ids", prompt.len()))).ok()?;
|
||||
Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect())
|
||||
});
|
||||
let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len());
|
||||
for pass in 0..repeat {
|
||||
crate::qwen_forward::quality_force::set(forced_answer.as_ref().map(|answer| {
|
||||
prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect()
|
||||
}));
|
||||
let started = std::time::Instant::now();
|
||||
let mut tokens = Vec::new();
|
||||
let outcome = stack
|
||||
@@ -464,6 +500,7 @@ fn original_serve_long_context_streamed_kv_smoke() {
|
||||
Ok(())
|
||||
}, &mut || false)
|
||||
.unwrap_or_else(|e| panic!("long-context request failed: {e:?} health={:?}", stack.health()));
|
||||
crate::qwen_forward::quality_force::set(None);
|
||||
assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round");
|
||||
assert!(tokens.iter().all(|&t| (0..248_320).contains(&t)));
|
||||
assert_eq!(stack.health(), None);
|
||||
|
||||
@@ -91,6 +91,9 @@ mod original_mtp_full_owner;
|
||||
mod original_mtp_verified_adapter;
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
mod original_serve_native;
|
||||
// Teacher forcing for the quality gate (docs/quality-gate.md): nothing installs a sequence outside the smoke.
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod quality_force;
|
||||
|
||||
// The routed-expert tier of the Original verifier window (all-CPU pool over the pinned mapped weights).
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
|
||||
@@ -154,7 +154,11 @@ where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx
|
||||
let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t
|
||||
&&result.selection.position()==position as u64;
|
||||
if !ok {self.failed=true;return Err(Error::IdentityMismatch);}
|
||||
let ids=result.selection.ids().to_vec();
|
||||
let mut ids=result.selection.ids().to_vec();
|
||||
// Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks
|
||||
// the controller verifies drafts against and commits next are the forced text's tokens.
|
||||
let forced_differ=super::quality_force::apply(position,&mut ids);
|
||||
if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");}
|
||||
// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
|
||||
if let Some(k)=trace_logprobs() {
|
||||
let mut line:Vec<u8>=Vec::new();
|
||||
|
||||
@@ -14,6 +14,16 @@ use super::{
|
||||
};
|
||||
use leleka_cuda_driver::{SamplerParams, SamplerPath};
|
||||
|
||||
/// `<|endoftext|>`: the Original's `--eos-ids` default is {248044, 248046}; the GGUF's `tokenizer.ggml.eos_token_id` is only 248046
|
||||
/// (`<|im_end|>`), so a request that stops on the metadata id alone runs on past an `<|endoftext|>` (quality gate, docs/quality-gate.md).
|
||||
pub(crate) const ENDOFTEXT_TOKEN: i32 = 248_044;
|
||||
|
||||
/// The stop set of a request on the Original serve path: generate.cpp's `eos_ids` ({248044, 248046}) plus the model's own EOS id.
|
||||
pub(crate) fn original_stop_tokens(eos: u32) -> Vec<i32> {
|
||||
let eos = eos as i32;
|
||||
if eos == ENDOFTEXT_TOKEN { vec![eos] } else { vec![eos, ENDOFTEXT_TOKEN] }
|
||||
}
|
||||
|
||||
/// Cells a request keeps free beyond `n + max_new`: the last verify window may overshoot by up to this.
|
||||
pub(in crate::qwen_forward) const CONTEXT_SLACK: usize = 8;
|
||||
|
||||
@@ -187,6 +197,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stop_set_is_the_originals_endoftext_and_im_end() {
|
||||
assert_eq!(original_stop_tokens(248_046), vec![248_046, 248_044]);
|
||||
assert_eq!(original_stop_tokens(248_044), vec![248_044]);
|
||||
assert!(original_stop_tokens(248_046).contains(&ENDOFTEXT_TOKEN), "generate.cpp stops on <|endoftext|> as well");
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
fresh: bool,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Teacher forcing for the model quality gate (`docs/quality-gate.md`). Off unless a test installs a sequence.
|
||||
//!
|
||||
//! With a sequence installed (the full token list of a request: its prompt followed by the tokens another engine
|
||||
//! produced) every verify window's picks are replaced by the sequence's tokens, so the engine decodes along that
|
||||
//! text instead of its own. Window row `r` at absolute position `p` has consumed token `p + r` and predicts token
|
||||
//! `p + r + 1`; the pick is `sequence[p + r + 1]` while the sequence reaches that far, and the engine's own argmax
|
||||
//! after it. The speculative controller still verifies drafts against these picks, so acceptance, the stop token and
|
||||
//! the length limit follow the forced text. The logits (and `LELEKA_TRACE_LOGPROBS` rows) of every row are the
|
||||
//! engine's own; only the token that is committed next is replaced.
|
||||
//!
|
||||
//! Production code never installs a sequence: the only caller is the Original serve smoke
|
||||
//! (`LELEKA_SMOKE_FORCE_DIR`), and with nothing installed [`apply`] is one uncontended lock and an empty check.
|
||||
use std::sync::Mutex;
|
||||
|
||||
static FORCED: Mutex<Option<Vec<i32>>> = Mutex::new(None);
|
||||
|
||||
/// Install (or, with `None`, remove) the forced sequence: prompt followed by the tokens to force.
|
||||
pub(crate) fn set(sequence: Option<Vec<i32>>) {
|
||||
*FORCED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = sequence;
|
||||
}
|
||||
|
||||
/// Replace the picks `ids[r]` of a window that starts at absolute `position` by the forced tokens. Returns how many
|
||||
/// picks were replaced by a token different from the engine's own (the places where the engine disagrees).
|
||||
pub(crate) fn apply(position: i64, ids: &mut [i32]) -> usize {
|
||||
let guard = FORCED.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let Some(sequence) = guard.as_ref() else { return 0 };
|
||||
let Ok(first) = usize::try_from(position) else { return 0 };
|
||||
let mut changed = 0;
|
||||
for (row, pick) in ids.iter_mut().enumerate() {
|
||||
if let Some(&forced) = sequence.get(first + row + 1) {
|
||||
if *pick != forced {
|
||||
changed += 1;
|
||||
}
|
||||
*pick = forced;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// One test touches the process-wide sequence (the harness runs tests on several threads).
|
||||
#[test]
|
||||
fn forcing_replaces_picks_by_absolute_position_and_stops_at_the_sequence_end() {
|
||||
set(None);
|
||||
let mut free = [5, 6, 7];
|
||||
assert_eq!(apply(10, &mut free), 0);
|
||||
assert_eq!(free, [5, 6, 7]);
|
||||
|
||||
// sequence: positions 0..=6; a window at position 3 predicts tokens at 4, 5, 6, 7
|
||||
set(Some(vec![100, 101, 102, 103, 104, 105, 106]));
|
||||
let mut ids = [104, 9, 9, 9];
|
||||
assert_eq!(apply(3, &mut ids), 2, "rows 1 and 2 differ, row 3 is past the sequence");
|
||||
assert_eq!(ids, [104, 105, 106, 9], "the engine's own pick stands past the end of the sequence");
|
||||
|
||||
let mut agree = [101, 102];
|
||||
assert_eq!(apply(0, &mut agree), 0);
|
||||
assert_eq!(agree, [101, 102]);
|
||||
|
||||
let mut beyond = [1, 2];
|
||||
assert_eq!(apply(50, &mut beyond), 0);
|
||||
assert_eq!(beyond, [1, 2]);
|
||||
set(None);
|
||||
let mut after = [3];
|
||||
assert_eq!(apply(0, &mut after), 0);
|
||||
assert_eq!(after, [3]);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ For a private Hugging Face repository, set `HF_TOKEN` in the process environment
|
||||
|
||||
For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` runs fetch, source verification, experimental KAR-2 preparation, and archive verification in one command. On rerun it hashes the source shards and verifies the archive payload, provenance, and level count before reusing the file. A damaged or mismatched archive fails closed and is never overwritten automatically. This preview is limited to 64 MiB of GGUF input; the embedded `qwen-iq3-s` manifest is deliberately rejected before download. It does not provide full-model conversion or an approved serving artifact.
|
||||
|
||||
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` is the opt-in, uncapped experimental path. It fetches and verifies source shards, prepares a bounded-memory KAR-2 archive if absent, independently verifies the new archive and provenance, and rehashes all sources plus the archive before reuse. It prints actual archive bytes and accounted bits per weight. Use a model volume with enough capacity for the GGUF shards, temporary sections, and final archive. Streamed policy v4 splits any tensor too large for KAR-2's 32-bit plane stride into adjacent records and records their parent mapping and per-part source/F32 hashes in provenance. The 51,200,245,760-element `per_layer_token_embd.weight` becomes two records of 32,000,000,000 and 19,200,245,760 elements. A complete level-2 archive measured 55,295,529,472 bytes (51.50 GiB, 66.13% of the source GGUF bytes); see [build validation](build-validation.md). Its maximum tensor relative L2 error was 0.68008092. Model-level quality and serving approval remain pending.
|
||||
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` is the opt-in, uncapped experimental path. It fetches and verifies source shards, prepares a bounded-memory KAR-2 archive if absent, independently verifies the new archive and provenance, and rehashes all sources plus the archive before reuse. It prints actual archive bytes and accounted bits per weight. Use a model volume with enough capacity for the GGUF shards, temporary sections, and final archive. Streamed policy v4 splits any tensor too large for KAR-2's 32-bit plane stride into adjacent records and records their parent mapping and per-part source/F32 hashes in provenance. The 51,200,245,760-element `per_layer_token_embd.weight` becomes two records of 32,000,000,000 and 19,200,245,760 elements. A complete level-2 archive measured 55,295,529,472 bytes (51.50 GiB, 66.13% of the source GGUF bytes); see [build validation](build-validation.md). Its maximum tensor relative L2 error was 0.68008092. Model-level quality and serving approval remain pending. First measurement, Original only (6 prompts, <= 128 tokens, teacher-forced; [quality gate](quality-gate.md) section 6): KAR level-2 PLE against the GGUF PLE changes the top-1 log-probability by p99 0.34 nats (max 0.54) and the argmax at 3.4 % of positions, about 1.6 times the Original's own configuration-to-configuration spread, with no collapse; this is not the model-quality gate.
|
||||
|
||||
`model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes one bounded nested tensor from the archive and prints an FNV-1a checksum of the F32 output. On Linux, compare `output_fnv1a64` with the same field from `strata-kar-gpu-smoke FILE.kar TENSOR LEVEL ITERATIONS`. This checks CPU and CUDA reconstruction byte for byte on a fixture; it is not a full-model quality gate.
|
||||
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
# Model quality gate: the Rust/CUDA port (Original mode17 serve path) against the unmodified Original
|
||||
|
||||
Status: measured on the RTX 5090 (driver 595.99.02, CUDA 13.2.86), 2026-10-17/18. Branch `claude/quality-gate` (port = `claude/port-gpu-bringup`
|
||||
6b94e7c, seed on by default, + the stop-set fix below). Model: Qwen3.8-Flash-Next IQ3_S, KAR level-2 PLE, MTP pack `data/mtp-rt`.
|
||||
Original = `stra169-ladder/build-sm120/strata` (sha256 714deada...), the build behind jobs 809/980; the `numerics-orig` build (diagnostic dump
|
||||
patches compiled in) reproduces it bit for bit on the reads (arm R6: all 612 rows, difference exactly 0).
|
||||
|
||||
**Pending at the time of writing (queued behind other agents' jobs, run `q_analyze.py` and `q_ladder.py` when they finish):**
|
||||
`9968-quality-orig-retrieval-read` (Original log-probabilities along its 100k/180k answers), `9969-quality-port-retrieval-fixed` (port after the stop-set
|
||||
fix, free and forced along those answers: section R of the report) and `9970-quality-ladder-p1` (layer-by-layer localisation of the one outlier row, section 9.2).
|
||||
Everything else in this document is measured.
|
||||
|
||||
## 1. Method
|
||||
|
||||
**Teacher forcing, both directions.** A *path* is the prompt followed by the tokens an engine produced. Both engines are made to decode along
|
||||
the same path and log the top-16 log-probabilities of every row.
|
||||
|
||||
* Original: `--serve` requests `GEN 1 <path>` with `--short-read 4096 --prompt-cache 0`, so the whole path goes through the verify windows
|
||||
and `STRATA_LOGPOS` / `STRATA_LOGPOS_TOPK=16` log every row (the only mode in which the Original exposes log-probabilities). Reference arm
|
||||
**R1** = the port's configuration family: spec 4 + suffix 3, `--spec-min-p 0.5`, 2048 per-layer slots from the placeholder profile,
|
||||
`--pcie-frac 0.55`, int8 KV, KAR PLE L2, tier **static** (`--adapt-every 0`: placement independent of copy timing).
|
||||
* Port: `LELEKA_SMOKE_FORCE_DIR` (new, `quality_force.rs`): the smoke replaces the picks of every verify window by the tokens of the path
|
||||
(the controller still verifies drafts against them, so acceptance, stop and length follow the path); logits and `LELEKA_TRACE_LOGPROBS`
|
||||
rows stay the port's own. Pass 0 of every corpus prompt is forced along the Original's job-809 pass-0 tokens, pass 1 is free.
|
||||
A row is *valid* when the window's consumed tokens equal the path up to it (rows after a rejected draft token are skipped).
|
||||
The hook is off unless a test installs a sequence (unit test `quality_force::tests`).
|
||||
* Corpus: `~/work/gpu-runs/prompts.txt` (6 prompts, 612 generated-region rows on the Original paths O0-O5; p2 is 90 tokens ending in the stop
|
||||
token, p5 is 10).
|
||||
* Per position: `dmax16` = max over the tokens present in both top-16 lists of |lp_a - lp_b| (the tail tokens dominate it);
|
||||
`d_top1` = |difference of the log-probability of the reference's argmax token|; `flip` = argmax differs, with the reference's top1-top2
|
||||
margin at that row. d_top1 is what decides tokens; dmax16 is reported because the task asked for it.
|
||||
|
||||
**Gate (pass criterion tied to the Original's own envelope).** The Original is compared with itself under every configuration change that is
|
||||
known to alter its outputs; the largest deviation it shows against its own reference is the tolerance:
|
||||
|
||||
| tolerance (Original vs its own R1, section 2) | value |
|
||||
| --- | --- |
|
||||
| d_top1 p99 | <= 0.22 nats |
|
||||
| d_top1 max | <= 0.43 nats |
|
||||
| dmax16 p99 | <= 2.05 nats (max 5.2) |
|
||||
| argmax-flip rate | <= 2.8 % of rows |
|
||||
| Original margin at every flip | <= 0.49 nats |
|
||||
| stop: forced run stops exactly where the path stops, stop token rank 1 | required |
|
||||
|
||||
A port arm passes when it stays inside; a single row outside is listed and explained, not averaged away.
|
||||
|
||||
## 2. The Original's own envelope (teacher-forced reads of O0-O5, 612 rows per arm, generated region)
|
||||
|
||||
| arm | dmax16 med / p99 / max | d_top1 med / p99 / max | flips | Original margin at the flips |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| R1 read twice in one process | 0 / 0 / 0 | 0 / 0 / 0 | 0 | bitwise deterministic |
|
||||
| R6 numerics-orig build | 0 / 0 / 0 | 0 / 0 / 0 | 0 | bitwise identical to the unmodified build |
|
||||
| R1 with `pcie_frac=0` (request key) | 0.395 / 1.75 / 5.21 | 0.001 / 0.177 / 0.329 | 11 (1.8 %) | <= 0.34 |
|
||||
| R2 near-empty VRAM tier (2 slots/layer: experts on the CPU) | 0.453 / 1.95 / 4.05 | 0.001 / 0.189 / 0.279 | 10 (1.6 %) | <= 0.23 |
|
||||
| R3 verify window `--spec 2` (shape of the windows) | 0.396 / 1.71 / 4.48 | 0.001 / 0.209 / 0.286 | 15 (2.5 %) | <= 0.41 |
|
||||
| R4 adaptive tier, first reads | 0 / 1.0 / 1.6 | 0 / 0.045 / 0.178 | 1 | 0.10 |
|
||||
| R4 adaptive tier, repeat 1 / repeat 2 of the same reads | 0.43 / 1.5 / 2.9 ; 0.42 / 2.0 / 4.2 | 0.001 / 0.18 / 0.39 ; 0.001 / 0.22 / 0.43 | 15 (2.5 %) ; 17 (2.8 %) | <= 0.49 ; <= 0.41 |
|
||||
| prompt read batched vs through windows (prompts 0, 1, 2 of job 9967; first <= 40 generated tokens, 104 rows) | 0.557 / 2.15 / 2.94 | 0.010 / 0.238 / 0.254 | 5 (4.8 %) | <= 0.25 |
|
||||
| GGUF PLE instead of KAR L2 (not an envelope member, section 6) | 0.62 / 2.86 / 4.38 | 0.001 / 0.34 / 0.54 | 21 (3.4 %) | <= 0.43 |
|
||||
|
||||
Pooled over the five non-identical envelope arms (3060 rows): d_top1 median 0.001, p99 0.197, max 0.433, dmax16 p99 1.83, flips 2.22 %.
|
||||
The Original's greedy sequences move accordingly (first differing token of each arm against its job-809 pass 0; `=` identical):
|
||||
|
||||
| Original arm | p0 | p1 | p2 | p3 | p4 | p5 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| F1 batched prompt, static, spec_min_p 0.5 / 0 / 0.8 | 25 / 4 / 4 | 2 / 2 / 2 | = / = / = | 98 / 60 / 75 | 10 / 77 / 10 | = |
|
||||
| R1 static | 6 | 2 | **4** | 28 | 10 | = |
|
||||
| R2 near-CPU | 4 | 2 | **4** | 28 | = | = |
|
||||
| R3 `--spec 2` | 6 | 2 | **4** | 10 | 77 | 2 |
|
||||
| R4 adaptive | 6 | = | **4** | 28 | 77 | = |
|
||||
| R5 GGUF PLE | 4 | 2 | **4** | 10 | 10 | = |
|
||||
| from the decode-parity jobs (orig-dec-A, A35, AD, AU, S, SP) | 4-99 | 4-8 | 2-35 | 2-100 | 10-77 | 8-35 |
|
||||
|
||||
## 3. The port against the Original (section B/C/V/V2 of `q_analyze.py`)
|
||||
|
||||
Port arms (forced pass 0 along the Original's pass-0 tokens, 612 rows each, reference = R1):
|
||||
|
||||
| port arm | d_top1 med / p99 / max | dmax16 p99 / max | flips | largest Original margin at a flip |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| P1 static tier, seed off | 0.001 / 0.176 / **1.152** | 1.84 / 3.34 | 10 (1.6 %) | 0.56 |
|
||||
| P5 static tier, seed ON | 0.001 / 0.191 / **1.022** | 2.32 / 4.53 | 10 (1.6 %) | 0.41 |
|
||||
| P2 adaptive tier, seed off | 0.001 / 0.202 / **0.836** | 2.14 / 4.28 | 11 (1.8 %) | 0.41 |
|
||||
| P6 adaptive tier + seed ON (the new default) | 0.001 / 0.235 / **0.974** | 1.98 / 3.19 | 14 (2.3 %) | 0.41 |
|
||||
| P3 tier off (all experts on the CPU pool: dense path alone) | 0.001 / 0.206 / **0.720** | 2.19 / 3.44 | 19 (3.1 %) | 0.41 |
|
||||
| P4 static, `--pcie-frac 0` | 0.001 / 0.198 / **1.361** | 2.12 / 4.94 | 15 (2.5 %) | 0.41 |
|
||||
| port vs port: P2 / P3 / P4 / P5 / P6 against P1 | p99 0.15-0.21, max 0.29-0.52 | 1.7-2.0 / 2.6-4.9 | 1.6-2.9 % | |
|
||||
|
||||
Pooled over the six port arms (3672 rows): d_top1 median 0.001, p99 **0.210** (Original pool 0.197), flips **2.15 %** (2.22 %), dmax16 p99 2.07
|
||||
(1.83). Without one row, the pooled d_top1 max is 0.417 (Original 0.433) and the flip rate 1.99 %.
|
||||
The port's own envelope (arms against P1) is the same size as the Original's: p99 0.189, max 0.518, flips 2.19 %.
|
||||
|
||||
**The one row outside the tolerance** is the same in every port arm (the bold maxima): corpus prompt 1, generated token 2, position 66, whose
|
||||
input token is `<think>` (248068). Original (windows read, batched-prompt read, near-CPU, GGUF, all configurations): 198 at -0.51..-0.74 over
|
||||
271 at -0.65..-0.92, except two configurations that put 271 first (R3 by 0.03, R4 repeat 1 by 0.45); port: 271 at -0.21..-0.35, 198 at
|
||||
-1.23..-1.66 in all six arms, including the all-CPU-experts arm. So the port's value lies 0.3-0.7 nats beyond the Original's most extreme
|
||||
configuration (d_top1 up to 1.36 against the R1 value). All other 3671 pooled port rows are inside the envelope. Localisation: section 8.
|
||||
|
||||
**Verdict of section 3:** the port's deviation distribution equals the Original's self-deviation (pooled medians, p99 within +6 %, flip rate 2.15 % vs 2.22 %,
|
||||
flip margins <= 0.41 except one 0.56 whose port margin is 0.02, i.e. a coin flip in both engines); one row (above) is outside and not yet explained
|
||||
at layer level. No evidence of a systematic numerical error in the dense path, the KAR PLE source, the expert paths (CPU, VRAM static, adaptive, PCIe 0)
|
||||
or the speculative window shapes.
|
||||
|
||||
## 4. Open question 1: corpus prompt 2 (diverges at token 4; the Original stops at 90, the port runs to 128)
|
||||
|
||||
Near tie, not a defect.
|
||||
|
||||
* The Original diverges from its own job-809 pass 0 on prompt 2 at **token 4** in every windows-read configuration (R1, R2, R3, R4, R5: row 2 of
|
||||
section 2). Its teacher-forced read of its own path puts token 449 behind token 264 by 0.149 nats (R1), 0.26 (R2); the batched-prompt read of job 9967
|
||||
gives 449 (-1.059) over 264 (-1.139) by 0.080, the windows read 264 (-1.010) over 449 (-1.158).
|
||||
* The port at that row (all six arms): 264 at -0.95..-1.03, 449 at -1.22..-1.28, i.e. the windows-read ordering, within 0.22 nats of the Original's.
|
||||
* Teacher-forced along the Original's 90 tokens the port produced exactly 90 tokens and stopped on the stop token in every arm
|
||||
(probe job and all six arms: `produced 90 of 90 forced tokens, stopped as forced`); the stop token is rank 1 at the last row in all six arms with log-probability
|
||||
-0.06..-0.22 (Original -0.09). So the 90-vs-128 difference is the consequence of the near-tie at token 4 (a different text), not of the stop handling.
|
||||
* d_top1 over the 90 rows of prompt 2: median 0.002, p99 0.145-0.176, max 0.15-0.21; no flip against R1 except one of margin 0.09 (seed arm).
|
||||
|
||||
## 5. Open question 2: the other divergences (job 809 table)
|
||||
|
||||
Every first divergence of every port arm (section D of the report) is a near tie in the engine that picked the other token: the Original's margin at
|
||||
the divergence row is 0.05-0.25 (one 0.56: prompt 4 token 121, port margin 0.02); the port's margin 0.00-0.43. Divergence indices of the port's free
|
||||
run against the Original's job-809 pass 0 (identical = `=`): P1 static 19 / = / 4 / 100 / 121 / =; P5 4 / = / 4 / 10 / 10 / =; P2 adaptive 4 / = / 4 / 10 / 77 / 2;
|
||||
P6 4 / = / 4 / 100 / 77 / 7; P3 CPU 4 / = / 4 / 10 / 10 / 2; P4 4 / = / 4 / 10 / 77 / 2 (the earlier job-809 numbers 6 / 4 / 28 / 77 / 7 are the same kind).
|
||||
The Original's own arms diverge at 2-100 on the same prompts (section 2). The indices carry no signal beyond "an early near tie flips with any rounding change".
|
||||
|
||||
## 6. KAR level-2 PLE against GGUF PLE in the Original (context for the "KAR model quality" status)
|
||||
|
||||
Same reads (static tier, windows), Original with `--ple-kar` level 2 versus without (PLE from the GGUF shard 2):
|
||||
|
||||
* Teacher-forced on the 6 KAR-generated paths (612 rows): d_top1 median 0.001, p99 0.34, max 0.54; flips 21 (3.4 %), margins <= 0.43;
|
||||
on all 17 paths (1841 rows) p99 0.36, max 0.73, flips 3.7 %. The mean NLL of the KAR run's own tokens is 0.2536 (KAR) vs 0.2638 (GGUF) nats/token,
|
||||
a +0.010 difference that includes the bias of scoring KAR's own text.
|
||||
* Free greedy sequences (6 prompts x 128, both through the windows, static tier): GGUF vs KAR first differ at tokens 4 / 75 / 93 / 10 / 79 / = (identical on the 10-token prompt),
|
||||
the same range as the Original against itself in section 2.
|
||||
* This is ~1.6x the Original's other envelope arms (d_top1 p99 0.34 vs 0.19-0.22, flips 3.4 % vs 1.6-2.8 %): KAR L2 PLE is a real but small numerical
|
||||
perturbation of the same order as a change of the verify-window shape; not a quality collapse on these 6 prompts. It is no benchmark: 6 prompts,
|
||||
<= 128 tokens each, no perplexity, no tool-call or long-context test. The status in `docs/model-assets.md` stays "pending"; this is only
|
||||
the first number for it.
|
||||
|
||||
## 7. Open question 3: 16,000-token prompt, chunk 8192 against 2048
|
||||
|
||||
Logits after the 16,000-token prompt (`prefill-708/prompt16000.ids`), rows 15999-16001 (predicting 271, 248068, then 198 vs 271). Original: batched prefill
|
||||
at the stated chunk, the last prompt token and the answer through the verify windows (`--turn-token` = the last prompt token). Port: static tier, seed off,
|
||||
free run (first three tokens identical at both chunks).
|
||||
|
||||
| chunk | engine | lp(198) | lp(271) | margin 198-271 | argmax @16001 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 2048 | Original | -0.687 | -0.699 | +0.011 | 198 |
|
||||
| 2048 | port | -0.523 | -0.898 | +0.375 | 198 |
|
||||
| 8192 | Original | -0.556 | -0.853 | +0.297 | 198 |
|
||||
| 8192 | port | -0.821 | -0.580 | -0.242 | 271 |
|
||||
|
||||
* The Original itself moves by 0.15 nats per token between its chunks 2048 and 8192 (margin spread 0.29); the port by 0.30 per token (spread 0.62).
|
||||
The port's distance to the Original at the same chunk is 0.16-0.27 nats (lp(198)/lp(271)), inside the envelope (d_top1 max 0.43).
|
||||
* The answer differs only because the Original is at +0.30 and the port at -0.24 on a 0.25-nat near tie; at chunk 2048 both pick 198.
|
||||
* Verdict: rounding of the same size as the Original's own chunk dependence (the port is somewhat more chunk-sensitive on this one row; a single
|
||||
sample). Not a defect; switching the default chunk is still a deliberate answer-changing decision, as that doc says.
|
||||
The first rows 15999 and 16000 agree within 0.02 nats at both chunks.
|
||||
|
||||
## 8. Seed and adaptive tier: explicit verdict
|
||||
|
||||
`LELEKA_ORIGINAL_SERVE_SEED` (prompt-routing seed, default on since 6b94e7c) and the adaptive tier change only the expert placement.
|
||||
Teacher-forced, 612 rows per arm, reference R1:
|
||||
|
||||
| arm | d_top1 p99 / max | flips | verdict |
|
||||
| --- | --- | --- | --- |
|
||||
| static, seed off (P1) | 0.176 / 1.15 (the one row) | 1.6 % | baseline |
|
||||
| static, seed ON (P5) | 0.191 / 1.02 (the one row) | 1.6 % | same as P1; P5 vs P1: p99 0.146, max 0.447, flips 1.6 % |
|
||||
| adaptive, seed off (P2) | 0.202 / 0.84 | 1.8 % | inside |
|
||||
| adaptive + seed ON, the shipped default (P6) | 0.235 / 0.97 | 2.3 % | p99 +7 % over the Original's 0.219 (R4 repeat 2), flips inside; P6 vs P1: p99 0.187, max 0.291 |
|
||||
|
||||
**Seed: PASS.** It moves the port's distribution by no more than the placement changes the Original and the port already show against
|
||||
themselves (P5 against P1 is smaller than P2/P3/P4 against P1), and it adds no row outside the envelope. Adaptive on/off: PASS likewise (P2, P6).
|
||||
|
||||
## 9. Defects found and fixed
|
||||
|
||||
1. **Stop set (fixed, `97227d8`).** `generate.cpp` stops on `<|endoftext|>` (248044) and `<|im_end|>` (248046) (`--eos-ids`); the port's serve
|
||||
backend, the smokes and the laptop probe used the GGUF `tokenizer.ggml.eos_token_id` alone = 248046. Evidence from the 100k/180k retrieval run (job 9966,
|
||||
before): after the answer `...**4817-QX**.` the model emits `<|endoftext|>`; the Original stops (83 and 63 tokens), the port went on emitting
|
||||
`<|im_start|>` until `max_new` (87 tokens at 100k, where it later hit `<|im_end|>`; **600 tokens at 180k**). After: `original_stop_tokens()` returns
|
||||
{eos, 248044} for the request and the text sink; unit test `the_stop_set_is_the_originals_endoftext_and_im_end`. After-evidence (job 9969)
|
||||
is in section 10 if the queue has run it.
|
||||
2. **Outlier row `<think>` at position 66 of prompt 1 (open).** A 1.1-nat disagreement on a 0.4-nat near tie, in all configurations of the port and
|
||||
outside every configuration of the Original; the other special-token row (`</think>` input, position 68) agrees to 0.000 but is a 0.99-confidence row,
|
||||
so it does not test the hypothesis. Hypothesis: the input handling of special token ids (embedding / PLE hash row of 248068). Job 9970
|
||||
(`9970-quality-ladder-p1.sh`, `q_ladder.py`) dumps the residual after every layer half in both engines for that path and reports the first frame at which the row departs.
|
||||
|
||||
## 10. Long-context retrieval at 100k and 180k tokens (same ids as jobs 915/916: `long-180k/prompt{100000,180000}.ids`, needle `4817-QX`)
|
||||
|
||||
Port (job 9966, integrated defaults: adaptive tier + seed, chunk 8192, int8 KV streamed, 600 new tokens) against the Original (job 9964, static tier,
|
||||
`--prefill 8192`, same KV streaming, `GEN 600`):
|
||||
|
||||
| prompt | engine | answer | tokens | first differing token |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 100k | Original | "...<think>...Remember this: the secret passcode is 4817-QX...</think> The secret passcode is **4817-QX**." then stop | 83 | |
|
||||
| 100k | port | same wording until token 61 (one word differs), same final answer, then `<|endoftext|><|im_start|>x3<|im_end|>` | 87 | 61 |
|
||||
| 180k | Original | same structure, passcode **4817-QX**, stop | 63 | |
|
||||
| 180k | port | passcode **4817-QX**, then `<|endoftext|>` and 500+ junk tokens (the stop-set defect) | 600 | 30 |
|
||||
|
||||
Both engines retrieve the passcode at 100k and 180k; the wording diverges at token 61 / 30 (a different word choice inside the same sentence). The first 5 tokens are
|
||||
identical, as are all tokens before the divergence. The teacher-forced comparison at the divergence (the Original reading its own 83/63-token answers
|
||||
behind the batched prompt: job 9968; the port forced along them: job 9969) is queued; its table is `q_analyze.py` section R once the data exist.
|
||||
|
||||
## 11. Rerun
|
||||
|
||||
```
|
||||
# data and requests (server): scripts/quality/q_prep.py builds cases/ and force/ from the job-809 Original log and the port logs
|
||||
# Original: holder jobs scripts/quality/jobs/991..995, 9964, 9967, 9968 (orig_run in q-common.sh); port: 9216-9218, 9966, 9969, 9970, 9973
|
||||
python3 scripts/quality/q_analyze.py ~/work/gpu-runs/quality --md report.md # envelope, port arms, divergences, EOS, verdict, long prompt
|
||||
python3 scripts/quality/q_ladder.py ~/work/gpu-runs/quality/ladder 66 # layer-level localisation of one row
|
||||
```
|
||||
|
||||
Binaries: port test exe built in WSL from `claude/quality-gate` (`q-4`, sha256 8618cc61...). Everything under `scripts/quality/` is offline analysis or holder
|
||||
jobs; nothing there runs in production serving.
|
||||
|
||||
## 12. Caveats
|
||||
|
||||
* The Original's logprobs exist only for rows read through the verify windows; the prompt part of R1 therefore goes through windows too (the real flow
|
||||
reads it batched). Prompts 0-2 were re-read with the batched path (job 9967) and agree with the windows read within d_top1 0.25.
|
||||
* Single token path per prompt, 6 prompts, 10-128 tokens: 612 rows per arm; p99 is the 6th largest value. Tolerances are the maximum over 5 Original arms,
|
||||
which is itself a small-sample bound.
|
||||
* The expert placement of the port and of the Original differ (different sets resident), which both sides' envelopes include.
|
||||
@@ -0,0 +1,10 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job: the port teacher-forced along the Original's pass-0 tokens (pass 0) and free (pass 1), top-16 logprobs per window row.
|
||||
# P1 static tier, prompt-routing seed OFF (the plain profile start; the Original's R1 configuration family);
|
||||
# P5 static tier, seed ON (LELEKA_ORIGINAL_SERVE_SEED default since 6b94e7c).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
port_run P1-static $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off
|
||||
port_run P5-static-seed $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=on
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,8 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job: P2 adaptive tier, seed off; P6 adaptive tier + seed ON (the new default configuration).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
port_run P2-adaptive $PORT_TIER LELEKA_ORIGINAL_SERVE_SEED=off
|
||||
port_run P6-adaptive-seed $PORT_TIER LELEKA_ORIGINAL_SERVE_SEED=on
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,9 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job: P3 = VRAM tier off (all routed experts on the CPU pool: the dense path in isolation), P4 = static tier, seed off,
|
||||
# --pcie-frac 0 (a different expert placement path).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
port_run P3-tieroff
|
||||
port_run P4-static-pcie0 $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,11 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 0: does the teacher-forcing hook work on the real model? Two corpus prompts (the JSON one that the Original stops at
|
||||
# 90 tokens, and the 10-token one), pass 0 forced along the Original's pass-0 tokens, pass 1 free; static tier.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
P=$Q/probe; rm -rf $P; mkdir -p $P/force
|
||||
sed -n '3p;6p' $G/prompts.txt > $P/prompts.txt
|
||||
cp $Q/force/c2.truth $P/force/c0.truth; cp $Q/force/c5.truth $P/force/c1.truth
|
||||
port_run P0-probe LELEKA_SMOKE_PROMPTS=$P/prompts.txt LELEKA_SMOKE_FORCE_DIR=$P/force $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,15 @@
|
||||
set -uo pipefail
|
||||
# Quality gate (docs/quality-gate.md), job 1: the unmodified Original, teacher-forced reads of 17 token paths (the Original's
|
||||
# own pass 0 and 1, the port's static and adaptive paths) through the verify windows, top-16 logprobs per row (STRATA_LOGPOS),
|
||||
# then six free 128-token requests. Arm R1 = the port's configuration (spec 4 + suffix 3, 2048 per-layer slots from the
|
||||
# placeholder profile, pcie 0.55, int8 KV, KAR PLE L2) with the tier STATIC (placement independent of copy timing); the last
|
||||
# six reads repeat O0..O5 in the same process (within-process determinism). Arm R2 = a near-empty VRAM tier (2 slots per layer).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $ORIG_BIN
|
||||
COMMON="--prefill 2048 --max-context 4096 --short-read 4096 --prompt-cache 0"
|
||||
REPEAT=O0:pcie_frac=0.55,O1:pcie_frac=0.55,O2:pcie_frac=0.55,O3:pcie_frac=0.55,O4:pcie_frac=0.55,O5:pcie_frac=0.55
|
||||
PCIE0=O0:pcie_frac=0,O1:pcie_frac=0,O2:pcie_frac=0,O3:pcie_frac=0,O4:pcie_frac=0,O5:pcie_frac=0
|
||||
orig_run R1-static $ALL17,$REPEAT,$PCIE0 6 spec_min_p=0.5 $COMMON $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
orig_run R2-nearcpu $ALL17 6 spec_min_p=0.5 $COMMON $(kar_args) --expert-cache 96 --expert-cache-per-layer --adapt-every 0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,11 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 2: the Original's own run-to-run / configuration envelope. R3: verify window width (--spec 2 instead of 4);
|
||||
# R4: the adaptive VRAM tier (default; placement follows copy timing, so repeated reads of the same path may differ).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
COMMON="--prefill 2048 --max-context 4096 --short-read 4096 --prompt-cache 0"
|
||||
REPEAT=O0:pcie_frac=0.55,O1:pcie_frac=0.55,O2:pcie_frac=0.55,O3:pcie_frac=0.55,O4:pcie_frac=0.55,O5:pcie_frac=0.55
|
||||
orig_run R3-spec2 $ALL17 6 spec_min_p=0.5 $COMMON $(kar_args) --spec 2 --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
orig_run R4-adaptive $ALL17,$REPEAT,$REPEAT 6 spec_min_p=0.5 $COMMON $(kar_args) --expert-cache 2048 --expert-cache-per-layer
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,11 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 3: R5 = the Original with the GGUF PLE source instead of KAR level 2 (the context for the KAR model-quality
|
||||
# status of docs/model-assets.md); F1 = the Original's default prompt flow (batched prompt read, short-read 64) free-running the
|
||||
# corpus at three speculation draft floors (spec_min_p 0.5 = the 809 configuration, 0, 0.8), tier static.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
COMMON="--prefill 2048 --max-context 4096 --prompt-cache 0"
|
||||
orig_run R5-gguf $ALL17 6 spec_min_p=0.5 $COMMON --short-read 4096 --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
orig_run F1-default "" 6 "spec_min_p=0.5/spec_min_p=0/spec_min_p=0.8" $COMMON $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,12 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 4: the Original's own logits after the 16,000-token prompt (prefill-708/prompt16000.ids) at --prefill 8192 and
|
||||
# 2048. The request is the prompt plus the three tokens 271,248068,198; --turn-token is the prompt's last token (369), so the
|
||||
# prompt is read batched up to the last prompt token and only the final rows go through the verify windows, where STRATA_LOGPOS
|
||||
# logs them: rows 15999..16001 predict generated tokens 0..2 (position 16001 is the near tie). Read twice (second: restored checkpoint).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
LONG="--max-context 20480 --kv-resident 20480 --turn-token $(cat $Q/L16.turn) --prompt-cache 1 --prompt-cache-root 0 --prompt-cache-every 0"
|
||||
orig_run L-c8192 L16,L16 0 "" --prefill 8192 $LONG $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
orig_run L-c2048 L16,L16 0 "" --prefill 2048 $LONG $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,10 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 5: R1's configuration with the numerics-orig build of the Original (diagnostic dump patches compiled in,
|
||||
# unused here): the same teacher-forced reads must reproduce R1 (stra169-ladder build) row for row.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
export ORIG_BIN=$HOME/work/numerics-orig/build/strata; sha256sum $ORIG_BIN
|
||||
COMMON="--prefill 2048 --max-context 4096 --short-read 4096 --prompt-cache 0"
|
||||
orig_run R6-numbin O0,O1,O2,O3,O4,O5,S0,S2,S3 0 "" $COMMON $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,33 @@
|
||||
set -uo pipefail
|
||||
# Quality gate: long-context retrieval (needle: "the secret passcode is 4817-QX") at 100k and 180k tokens on the unmodified Original, same token ids
|
||||
# as jobs 915/916 (long-180k/prompt{100000,180000}.ids). Phase 1: free greedy answer of 600 tokens per prompt (batched prefill chunk 8192, int8 KV
|
||||
# streamed, tier static). Writes long-force/answer<N>.ids (first K<=100 tokens) for the port and ret2.txt (the teacher-forced read request: job 9965, only queued if the engines' answers differ).
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
L=$G/long-180k; F=$Q/long-force; mkdir -p $F
|
||||
T=$(python3 -c "print(open('$L/prompt100000.ids').read().strip().split(',')[-1])")
|
||||
python3 - $L $Q/ret1.txt <<'PY'
|
||||
import sys
|
||||
L, out = sys.argv[1:3]
|
||||
open(out, "w").write("".join(f"GEN 600 {open(f'{L}/prompt{n}.ids').read().strip()}\n" for n in (100000, 180000)) + "QUIT\n")
|
||||
PY
|
||||
COMMON="--prefill 8192 --max-context 262144 --kv-resident 20480 --prompt-cache 1 --prompt-cache-root 0 --prompt-cache-every 0 --turn-token $T --short-read 128 --expert-cache 2048 --expert-cache-per-layer --adapt-every 0"
|
||||
orig_serve RET-orig-free $Q/ret1.txt $COMMON $(kar_args)
|
||||
python3 - $L $Q/runs/RET-orig-free/out.txt $T $F $Q/ret2.txt <<'PY'
|
||||
import sys
|
||||
L, out, T, F, req = sys.argv[1:6]; T = int(T)
|
||||
seqs, cur = [], []
|
||||
for line in open(out):
|
||||
if line.startswith("T "): cur.append(int(line.split()[1]))
|
||||
elif line.startswith("DONE"): seqs.append(cur); cur = []
|
||||
lines = []
|
||||
for n, ans in zip((100000, 180000), seqs):
|
||||
k = min(100, len(ans), next((j for j, x in enumerate(ans) if x == T), 10**9))
|
||||
open(f"{F}/answer{n}.ids", "w").write(",".join(map(str, ans[:k])))
|
||||
open(f"{F}/answer{n}.full", "w").write(",".join(map(str, ans)))
|
||||
print(n, "answer tokens", len(ans), "forced K", k)
|
||||
lines.append("GEN 1 " + open(f"{L}/prompt{n}.ids").read().strip() + "," + ",".join(map(str, ans[:k])))
|
||||
open(req, "w").write("\n".join(lines) + "\nQUIT\n")
|
||||
PY
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,26 @@
|
||||
set -uo pipefail
|
||||
# Quality gate: the port's long-context retrieval at 100k and 180k (same prompts as jobs 915/916), 600 new tokens, integrated defaults
|
||||
# (adaptive tier + prompt-routing seed), chunk 8192, windows traced (top-16). Then, if its first K tokens differ from the Original's (job 9964),
|
||||
# a second process teacher-forced along the Original's first K answer tokens.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
LONGENV="LELEKA_ORIGINAL_SERVE_LONG_TOKENS=100000,180000 LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=600 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192"
|
||||
port_long RET-port-free $PORT_TIER $LONGENV
|
||||
python3 - $Q/runs/RET-port-free/port.log $Q/long-force > $Q/ret-port-diff.txt <<'PY'
|
||||
import re, sys
|
||||
log, F = sys.argv[1:3]
|
||||
outs = [[int(x) for x in m[1].split(",") if x] for m in (re.match(r"long-smoke output ids \(\d+\): ([0-9,]*)", l) for l in open(log, errors="replace")) if m]
|
||||
differ = False
|
||||
for n, o in zip((100000, 180000), outs):
|
||||
try: a = [int(x) for x in open(f"{F}/answer{n}.ids").read().split(",")]
|
||||
except OSError: print(n, "no Original answer yet"); differ = True; continue
|
||||
same = o[: len(a)] == a
|
||||
print(n, "port tokens", len(o), "first K", len(a), "identical" if same else "DIFFERENT"); differ |= not same
|
||||
print("FORCE" if differ else "SKIP")
|
||||
PY
|
||||
cat $Q/ret-port-diff.txt
|
||||
if tail -1 $Q/ret-port-diff.txt | grep -q FORCE; then
|
||||
port_long RET-port-forced $PORT_TIER $LONGENV LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR=$Q/long-force
|
||||
fi
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,23 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job: the Original's logits for the first generated tokens of corpus prompts 1, 2 and 0 (the Original diverges from itself at token 2 / 4 / 6 there) with the prompt read by the BATCHED path
|
||||
# (the path of a real request; the other reads put the whole path through the verify windows). Per prompt one process:
|
||||
# path = prompt + up to 40 of the Original's pass-0 tokens, --turn-token = the prompt's last token (absent from those 40), so the prompt
|
||||
# is read batched up to its last token and the generated part goes through the windows (--short-read 40), where STRATA_LOGPOS logs it.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
for i in 1 2 0; do
|
||||
T=$(python3 - $Q $i <<'PY'
|
||||
import sys, json
|
||||
q, i = sys.argv[1], int(sys.argv[2])
|
||||
meta = json.load(open(f"{q}/cases/meta.json"))[f"O{i}"]
|
||||
ids = [int(x) for x in open(f"{q}/cases/O{i}.ids").read().split(",")]
|
||||
n = meta["n_prompt"]; t = ids[n - 1]; gen = ids[n:]
|
||||
k = min(40, next((j for j, x in enumerate(gen) if x == t), 40))
|
||||
open(f"{q}/cases/B{i}.ids", "w").write(",".join(map(str, ids[: n + k])))
|
||||
print(t)
|
||||
PY
|
||||
)
|
||||
orig_run B$i-batched B$i 0 "" --prefill 2048 --max-context 4096 --short-read 40 --turn-token $T --prompt-cache 1 --prompt-cache-root 0 --prompt-cache-every 0 $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
done
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,29 @@
|
||||
set -uo pipefail
|
||||
# Quality gate: phase 2 of the retrieval check (job 9964 gave the Original's answers: 83 tokens at 100k, 63 at 180k; the port's differ from token 61 / 30).
|
||||
# Per prompt two requests in one process: (1) the bare prompt (batched prefill chunk 8192; --turn-token = its last token, so a checkpoint is kept at
|
||||
# the last prompt token), (2) prompt + the Original's whole answer (<=120 tokens): it resumes from that checkpoint and the answer goes through the verify
|
||||
# windows (--short-read 128), where STRATA_LOGPOS logs top-16 per row. Writes long-force/answer<N>.ids (the whole answer) for the port's forced run.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
L=$G/long-180k; F=$Q/long-force
|
||||
T=$(python3 -c "print(open('$L/prompt100000.ids').read().strip().split(',')[-1])")
|
||||
python3 - $L $Q/runs/RET-orig-free/out.txt $F $Q/ret3.txt <<'PY'
|
||||
import sys
|
||||
L, out, F, req = sys.argv[1:5]
|
||||
seqs, cur = [], []
|
||||
for line in open(out):
|
||||
if line.startswith("T "): cur.append(int(line.split()[1]))
|
||||
elif line.startswith("DONE"): seqs.append(cur); cur = []
|
||||
lines = []
|
||||
for n, ans in zip((100000, 180000), seqs):
|
||||
ans = ans[:120]
|
||||
open(f"{F}/answer{n}.ids", "w").write(",".join(map(str, ans)))
|
||||
ids = open(f"{L}/prompt{n}.ids").read().strip()
|
||||
lines += [f"GEN 1 {ids}", f"GEN 1 {ids}," + ",".join(map(str, ans))]
|
||||
print(n, "answer tokens forced", len(ans))
|
||||
open(req, "w").write("\n".join(lines) + "\nQUIT\n")
|
||||
PY
|
||||
orig_serve RET-orig-read $Q/ret3.txt --prefill 8192 --max-context 262144 --kv-resident 20480 --prompt-cache 2 --prompt-cache-root 0 --prompt-cache-every 0 --turn-token $T --short-read 128 --expert-cache 2048 --expert-cache-per-layer --adapt-every 0 $(kar_args)
|
||||
grep -E "^RESUME|^REUSED" $Q/runs/RET-orig-read/out.txt | tr "\n" " "
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,11 @@
|
||||
set -uo pipefail
|
||||
# Quality gate: the port's retrieval at 100k / 180k AFTER the stop-set fix (<|endoftext|> now stops like the Original's eos_ids {248044, 248046}):
|
||||
# a free run (600 new tokens allowed; compare with RET-port-free of job 9966, which ran 600 tokens at 180k), then a run teacher-forced along the
|
||||
# Original's answers (long-force/answer<N>.ids from job 9968), top-16 logprobs per window row.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
LONGENV="LELEKA_ORIGINAL_SERVE_LONG_TOKENS=100000,180000 LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=600 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192"
|
||||
port_long RET-port-fixed $PORT_TIER $LONGENV
|
||||
port_long RET-port-forced $PORT_TIER $LONGENV LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR=$Q/long-force
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,24 @@
|
||||
set -uo pipefail
|
||||
# Quality gate: where does the one outlier row (prompt 1, generated token 2, input token <think> 248068, position 66) leave the Original?
|
||||
# Both engines dump the residual after every layer half ("ladder": 96 frames x rows x 4*2560 f32) for the same path B1 (prompt 1 + its first 22 Original tokens):
|
||||
# the port teacher-forced (static tier, seed off, LELEKA_TRACE_RESIDUAL/LADDER), the numerics-orig build of the Original through the verify windows
|
||||
# (STRATA_NUM_RESID_DIR / STRATA_NUM_LADDER, same configuration as R1). Compared offline by q_ladder.py.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
D=$Q/ladder; rm -rf $D; mkdir -p $D/port $D/orig $D/force
|
||||
sed -n '2p' $G/prompts.txt > $D/prompts.txt
|
||||
cp $Q/cases/B1.ids $D/force/c0.truth
|
||||
port_env
|
||||
echo "=== port ladder"; date -u +%FT%TZ
|
||||
env LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$D/prompts.txt LELEKA_SMOKE_MAX_NEW=128 LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=1 \
|
||||
LELEKA_SMOKE_FORCE_DIR=$D/force LELEKA_SMOKE_FORCE_PASSES=1 $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off \
|
||||
LELEKA_TRACE_RESIDUAL=$D/port LELEKA_TRACE_LADDER=1 LELEKA_TRACE_PLE=1 \
|
||||
$BIN --ignored --test-threads=1 --nocapture original_serve_smoke_prompt_decode 2>&1 \
|
||||
| grep -a -E '^[0-9]+ |^DBG (corpus|logprobs|residual|forced)|test result|panicked|FAILED' > $D/port.log
|
||||
echo "rc=${PIPESTATUS[0]}"; date -u +%FT%TZ
|
||||
grep -a -c "DBG residual window" $D/port.log; ls $D/port | wc -l
|
||||
export ORIG_BIN=$HOME/work/numerics-orig/build/strata STRATA_NUM_RESID_DIR=$D/orig STRATA_NUM_LADDER=1
|
||||
orig_run ladder-orig B1 0 "" --prefill 2048 --max-context 4096 --short-read 4096 --prompt-cache 0 $(kar_args) --expert-cache 2048 --expert-cache-per-layer --adapt-every 0
|
||||
ls $D/orig | wc -l; du -sh $D
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,8 @@
|
||||
set -uo pipefail
|
||||
# Quality gate job 8: the port's logits after the 16,000-token prompt at prefill chunks 8192 and 2048 (static tier), windows traced.
|
||||
source ~/work/gpu-runs/quality/q-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header; sha256sum $BIN
|
||||
port_long PL-c8192 $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CAPACITY=8192
|
||||
port_long PL-c2048 $PORT_TIER LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CAPACITY=2048
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,89 @@
|
||||
# Sourced by the 99x-quality-*.sh holder jobs (docs/quality-gate.md). Defines orig_run (the unmodified Original,
|
||||
# teacher-forced reads + free requests) and port_run (the port's Original-serve smoke, forced pass + free pass).
|
||||
# Layout: $Q = ~/work/gpu-runs/quality (cases/, force/, runs/<label>/); scripts are copied there by the operator.
|
||||
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
|
||||
A=$HOME/leleka-gates/assets
|
||||
G=$HOME/work/gpu-runs
|
||||
Q=$G/quality
|
||||
PH=$G/baseline/profile.bin
|
||||
ORIG_BIN=${ORIG_BIN:-$HOME/leleka-gates/stra169-ladder/build-sm120/strata}
|
||||
ALL17=O0,O1,O2,O3,O4,O5,Ob0,Ob3,Ob4,S0,S2,S3,A0,A2,A3,A4,A5
|
||||
mkdir -p $G/mtp-staging-own; chmod 700 $G/mtp-staging-own $Q/runs 2>/dev/null; mkdir -p $Q/runs
|
||||
mem_ok() { local avail; avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"; [ "$avail" -ge ${1:-60} ]; }
|
||||
header() { date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader; }
|
||||
|
||||
# orig_run LABEL READS FREE FREEKEYS ORIGINAL-FLAGS...
|
||||
# READS: comma list of case names (q_mkreqs.py SPEC); FREE: number of free 128-token requests; FREEKEYS: request keys for them.
|
||||
# Flags: everything after the four arguments is appended to the common Original flags (put --ple-kar/--ple-kar-level
|
||||
# choices and the expert tier there). STRATA_LOGPOS rows land in runs/LABEL/logpos (top-16 per row).
|
||||
orig_run() {
|
||||
local label=$1 reads=$2 free=$3 keys=$4; shift 4
|
||||
local d=$Q/runs/$label; rm -rf $d; mkdir -p $d
|
||||
python3 $Q/q_mkreqs.py $Q/cases $d/reqs.txt --read "$reads" --free $free --free-keys "$keys" > /dev/null || return 1
|
||||
echo "=== original $label: $* | reads=$reads free=$free keys=$keys bin=$(basename $(dirname $(dirname $ORIG_BIN)))/$(basename $(dirname $ORIG_BIN))"; date -u +%FT%TZ
|
||||
STRATA_LOGPOS=$d/logpos STRATA_LOGPOS_TOPK=16 $ORIG_BIN \
|
||||
--pack $A/data/iq3_s --native $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf \
|
||||
--ple-gguf $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf \
|
||||
--serve --mtp $A/data/mtp-rt --kv int8 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-profile $PH --pcie-frac 0.55 \
|
||||
"$@" < $d/reqs.txt > $d/out.txt 2> $d/err.txt
|
||||
echo "rc=$? original=$label"; date -u +%FT%TZ
|
||||
echo "requests: $(grep -c '^DONE' $d/out.txt) done, $(grep -c '^ERR' $d/out.txt) errors, logpos rows $(wc -l < $d/logpos 2>/dev/null)"
|
||||
grep -m3 '^ERR' $d/out.txt
|
||||
grep -E "strata serve: (decode expert cache|prompt)" $d/err.txt | tail -3 | cut -c1-200
|
||||
}
|
||||
# the Original's KAR PLE level 2 through the holder's sealed memfd (no second page cache of the 52 GB file)
|
||||
kar_args() { echo "--ple-kar ${KAR_PATH:-/proc/self/fd/${LELEKA_STRA169_KAR_FD:-0}} --ple-kar-level 2"; }
|
||||
|
||||
# port_run LABEL [ENV=V ...]: the port's smoke corpus (6 prompts, 2 passes): pass 0 is teacher-forced along the Original's
|
||||
# pass-0 tokens ($Q/force/c<i>.truth), pass 1 is free; every window's top-16 logprobs are traced.
|
||||
BIN=${BIN:-$HOME/work/leleka-quality-bin/q-4}
|
||||
port_env() {
|
||||
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
|
||||
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
|
||||
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
|
||||
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
|
||||
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_GRAPH_EXEC_REUSE=off LELEKA_BRINGUP_TRACE=1 LELEKA_TRACE_LOGPROBS=16
|
||||
}
|
||||
PORT_TIER="LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$PH"
|
||||
port_run() {
|
||||
local label=$1; shift
|
||||
local d=$Q/runs/$label; rm -rf $d; mkdir -p $d
|
||||
port_env
|
||||
echo "=== port $label: $*"; date -u +%FT%TZ
|
||||
env LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$G/prompts.txt LELEKA_SMOKE_MAX_NEW=128 LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=2 \
|
||||
LELEKA_SMOKE_FORCE_DIR=$Q/force LELEKA_SMOKE_FORCE_PASSES=1 "$@" \
|
||||
$BIN --ignored --test-threads=1 --nocapture original_serve_smoke_prompt_decode 2>&1 \
|
||||
| grep -a -E '^[0-9]+ |^DBG (corpus|logprobs|forced|timing|smoke)|smoke: (greedy|sampled|short)|expert cache|test result|panicked|FAILED' > $d/port.log
|
||||
echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ
|
||||
grep -a -E 'DBG corpus [0-9]+ pass=[0-9]+ forced:|test result|panicked' $d/port.log | cut -c1-200
|
||||
}
|
||||
|
||||
# port_long LABEL [ENV=V ...]: the port's long-context smoke on the 16,000-token prompt (prefill-708/prompt16000.ids is its own prompt),
|
||||
# 4 generated tokens, windows traced (top-16 per row). LELEKA_ORIGINAL_SERVE_CAPACITY selects the prefill chunk.
|
||||
port_long() {
|
||||
local label=$1; shift
|
||||
local d=$Q/runs/$label; rm -rf $d; mkdir -p $d
|
||||
port_env
|
||||
echo "=== port-long $label: $*"; date -u +%FT%TZ
|
||||
env LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes LELEKA_ORIGINAL_SERVE_LONG_TOKENS=16000 LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=4 \
|
||||
LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=20480 "$@" \
|
||||
$BIN --ignored --test-threads=1 --nocapture original_serve_long_context_streamed_kv_smoke 2>&1 \
|
||||
| grep -a -E '^[0-9]+ |^DBG logprobs|long-smoke|test result|panicked|FAILED' > $d/port.log
|
||||
echo "rc=${PIPESTATUS[0]} port-long=$label"; date -u +%FT%TZ
|
||||
grep -a -E 'long-smoke (prefill|output ids)|test result|panicked' $d/port.log | cut -c1-200
|
||||
}
|
||||
|
||||
# orig_serve LABEL REQFILE ORIGINAL-FLAGS...: like orig_run with a ready request file (runs/LABEL/reqs.txt); same common flags.
|
||||
orig_serve() {
|
||||
local label=$1 reqs=$2; shift 2
|
||||
local d=$Q/runs/$label; rm -rf $d; mkdir -p $d; cp $reqs $d/reqs.txt
|
||||
echo "=== original $label: $*"; date -u +%FT%TZ
|
||||
STRATA_LOGPOS=$d/logpos STRATA_LOGPOS_TOPK=16 $ORIG_BIN \
|
||||
--pack $A/data/iq3_s --native $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf \
|
||||
--ple-gguf $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf \
|
||||
--serve --mtp $A/data/mtp-rt --kv int8 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-profile $PH --pcie-frac 0.55 \
|
||||
"$@" < $d/reqs.txt > $d/out.txt 2> $d/err.txt
|
||||
echo "rc=$? original=$label"; date -u +%FT%TZ
|
||||
grep -E "^DONE|^ERR" $d/out.txt | cut -c1-200
|
||||
grep -E "strata serve: prompt" $d/err.txt | tail -3 | cut -c1-220
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Model quality gate report (docs/quality-gate.md): Original vs port, with the Original's own envelope.
|
||||
|
||||
usage: q_analyze.py QUALITY_DIR [--md OUT.md] [--json OUT.json]
|
||||
|
||||
QUALITY_DIR (default ~/work/gpu-runs/quality) holds cases/ (token paths), runs/<label>/ written by the 99x-quality-*.sh jobs.
|
||||
Everything is computed from the logged top-k log-probabilities; nothing here runs a model.
|
||||
Definitions (per position, generated region = rows that predict a generated token):
|
||||
dmax max over the tokens present in BOTH top-k lists of |lp_a - lp_b| (nats)
|
||||
flip argmax differs; its Original margin is top1-top2 of the reference engine's row (nats)
|
||||
"""
|
||||
import json, os, sys, glob, statistics
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from q_lib import *
|
||||
|
||||
def fmt(x, nd=3):
|
||||
return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else f"{x:.{nd}f}"
|
||||
|
||||
def gen_range(meta, name, total):
|
||||
n_prompt = meta[name]["n_prompt"]
|
||||
return n_prompt - 1, total - 2 # rows predicting generated tokens: last prompt token .. second to last token
|
||||
|
||||
class Q:
|
||||
def __init__(self, d):
|
||||
self.d = d
|
||||
self.cases = os.path.join(d, "cases")
|
||||
self.meta = json.load(open(os.path.join(self.cases, "meta.json")))
|
||||
for f in glob.glob(os.path.join(self.cases, "B*.ids")): # batched-prompt reads: prompt i + its first generated tokens
|
||||
n = os.path.basename(f)[:-4]
|
||||
if n[1:].isdigit() and f"O{n[1:]}" in self.meta: self.meta[n] = dict(self.meta[f"O{n[1:]}"], source="batched-prompt read")
|
||||
self.paths = {n: load_case(self.cases, n) for n in self.meta}
|
||||
self.reads = {} # run -> {label: (case, keys, rows)}
|
||||
for rd in sorted(glob.glob(os.path.join(d, "runs", "*"))):
|
||||
if os.path.exists(os.path.join(rd, "logpos")) and os.path.exists(os.path.join(rd, "reqs.txt.names")):
|
||||
try: self.reads[os.path.basename(rd)] = orig_reads(rd, self.cases)
|
||||
except Exception as e: print("skip", rd, e, file=sys.stderr)
|
||||
self.ports = {} # run -> parsed runs
|
||||
for pl in sorted(glob.glob(os.path.join(d, "runs", "*", "port.log"))):
|
||||
runs = parse_port_log(pl)
|
||||
if runs: self.ports[os.path.basename(os.path.dirname(pl))] = runs
|
||||
|
||||
def path_rows(self, run, case, keys=None, k=0):
|
||||
"""Rows of the k-th read of `case` (with the given key list, [] = no keys) in an Original run."""
|
||||
want = [s for s in self.reads.get(run, {}).items() if s[1][0] == case and s[1][1] == (keys or [])]
|
||||
return want[k][1][2] if len(want) > k else None
|
||||
|
||||
def stats_over(q, ref_run, ref_keys, other_get, cases, region="gen"):
|
||||
rows = []
|
||||
for c in cases:
|
||||
ref = q.path_rows(ref_run, c, ref_keys)
|
||||
oth = other_get(c)
|
||||
if ref is None or oth is None: continue
|
||||
total = len(q.paths[c]); lo, hi = gen_range(q.meta, c, total)
|
||||
if region == "gen": rows += [dict(r, case=c) for r in compare(ref, oth, lo, hi)]
|
||||
else: rows += [dict(r, case=c) for r in compare(ref, oth, 0, lo - 1)]
|
||||
return rows
|
||||
|
||||
def row_line(label, s):
|
||||
f = lambda k, m: fmt(s[k][m])
|
||||
return (f"| {label} | {s['n']} | {f('dmax','median')} / {f('dmax','p99')} / {f('dmax','max')} | "
|
||||
f"{f('d_top1','median')} / {f('d_top1','p99')} / {f('d_top1','max')} | {f('d_target','p99')} | "
|
||||
f"{s['flips']} ({s['flips'] / max(s['n'], 1) * 100:.1f}%) | {', '.join(map(str, s['flip_margins'])) or '-'} |")
|
||||
|
||||
HEAD = ("| arm | rows | dmax16 med / p99 / max | d_top1 med / p99 / max | d_target p99 | argmax flips | reference margin at each flip |\n"
|
||||
"|---|---|---|---|---|---|---|")
|
||||
|
||||
|
||||
def out_sequences(path):
|
||||
"""Generated tokens per request of an Original out.txt (T lines up to each DONE) and its stop reason."""
|
||||
seqs, cur = [], []
|
||||
for line in open(path, errors="replace"):
|
||||
if line.startswith("T "): cur.append(int(line.split()[1]))
|
||||
elif line.startswith("DONE"): seqs.append((cur, line.split()[5] if len(line.split()) > 5 else "?")); cur = []
|
||||
return seqs
|
||||
|
||||
def first_diff(a, b):
|
||||
n = next((i for i in range(min(len(a), len(b))) if a[i] != b[i]), None)
|
||||
if n is not None: return str(n)
|
||||
return "=" if len(a) == len(b) else f"len {len(a)}/{len(b)}"
|
||||
|
||||
def free_requests(q, run):
|
||||
"""{(prompt, rep): tokens} of the free requests of an Original run (labels `free:p:rep`)."""
|
||||
names = [n for n in open(os.path.join(q.d, "runs", run, "reqs.txt.names")).read().split(chr(10)) if n]
|
||||
seqs = out_sequences(os.path.join(q.d, "runs", run, "out.txt"))
|
||||
out = {}
|
||||
for n, (toks, why) in zip(names, seqs):
|
||||
if n.startswith("free:"):
|
||||
_, p, rep = n.split(":"); out[(int(p), int(rep))] = (toks, why)
|
||||
return out
|
||||
|
||||
def main(argv):
|
||||
d = os.path.expanduser(argv[0]) if argv else os.path.expanduser("~/work/gpu-runs/quality")
|
||||
md_out = argv[argv.index("--md") + 1] if "--md" in argv else None
|
||||
json_out = argv[argv.index("--json") + 1] if "--json" in argv else None
|
||||
q = Q(d); out = []; result = {}
|
||||
O = [f"O{i}" for i in range(6)]
|
||||
ref_run = "R1-static"
|
||||
out.append(f"# Quality gate analysis ({d})\n")
|
||||
out.append(f"Original runs with reads: {', '.join(q.reads)}; port runs: {', '.join(q.ports)}\n")
|
||||
|
||||
# ---- A. the Original's own envelope on its own paths O0..O5 ------------------------------------------
|
||||
out.append("## A. Original vs Original (teacher-forced reads of the Original's own pass-0 paths, generated region)\n")
|
||||
out.append(HEAD)
|
||||
env = {}
|
||||
def arm(label, run, keys, k=0):
|
||||
rows = stats_over(q, ref_run, [], lambda c: q.path_rows(run, c, keys, k), O)
|
||||
if rows: env[label] = summary(rows); out.append(row_line(label, env[label]))
|
||||
return rows
|
||||
if ref_run in q.reads:
|
||||
arm("R1 repeated in the same process (same config)", ref_run, ["pcie_frac=0.55"])
|
||||
arm("R1 with pcie_frac=0 (request key)", ref_run, ["pcie_frac=0"])
|
||||
for run, text in [("R2-nearcpu", "expert tier 2 slots/layer (near-CPU experts)"), ("R3-spec2", "verify window --spec 2"),
|
||||
("R4-adaptive", "adaptive tier, first reads"), ("R6-numbin", "numerics-orig build")]:
|
||||
if run in q.reads: arm(f"{run}: {text}", run, [])
|
||||
if "R4-adaptive" in q.reads:
|
||||
arm("R4-adaptive: repeat 1 of O0..O5", "R4-adaptive", ["pcie_frac=0.55"], 0)
|
||||
arm("R4-adaptive: repeat 2 of O0..O5", "R4-adaptive", ["pcie_frac=0.55"], 1)
|
||||
out.append("")
|
||||
|
||||
# ---- A2. prompt path: batched prompt read vs the windows-read reference ---------------------------------
|
||||
brows = []
|
||||
for i in range(5):
|
||||
run = f"B{i}-batched"
|
||||
if run in q.reads and f"B{i}" in q.meta:
|
||||
ref = q.path_rows(ref_run, f"O{i}", []); oth = q.path_rows(run, f"B{i}", [])
|
||||
if ref and oth:
|
||||
lo = q.meta[f"O{i}"]["n_prompt"] - 1
|
||||
brows += [dict(r, case=f"O{i}") for r in compare(ref, oth, lo, len(q.paths[f"B{i}"]) - 2)]
|
||||
if brows:
|
||||
env["prompt read batched vs through windows (prompts 0-4, first <=40 generated tokens)"] = summary(brows)
|
||||
out.append(row_line("prompt read batched vs through windows (prompts 0-4, first <=40 generated tokens)", env["prompt read batched vs through windows (prompts 0-4, first <=40 generated tokens)"]))
|
||||
out.append("")
|
||||
# ---- E. KAR vs GGUF PLE ---------------------------------------------------------------------------
|
||||
if "R5-gguf" in q.reads:
|
||||
out.append("## E. KAR level-2 PLE vs GGUF PLE in the Original (same reads, static tier)\n")
|
||||
out.append(HEAD)
|
||||
allc = sorted(q.meta)
|
||||
for label, cs in [("O0..O5 (Original paths)", O), ("all 17 paths", allc)]:
|
||||
rows = stats_over(q, ref_run, [], lambda c: q.path_rows("R5-gguf", c, []), cs)
|
||||
if rows:
|
||||
s = summary(rows); out.append(row_line("GGUF PLE vs KAR L2: " + label, s))
|
||||
result["kar_vs_gguf_" + label] = s
|
||||
nll = {}
|
||||
for run in (ref_run, "R5-gguf"):
|
||||
v = []
|
||||
for c in O:
|
||||
rows = q.path_rows(run, c, [])
|
||||
if rows is None: continue
|
||||
lo, hi = gen_range(q.meta, c, len(q.paths[c]))
|
||||
v += [-rows[p].lp_target for p in range(lo, hi + 1) if p in rows]
|
||||
nll[run] = (statistics.mean(v), len(v)) if v else None
|
||||
out.append(f"\nMean NLL of the Original's own tokens (O0..O5 generated region): KAR L2 {nll.get(ref_run)}, GGUF {nll.get('R5-gguf')} (nats/token, rows).\n")
|
||||
|
||||
# ---- S. greedy sequences: first differing token index against the Original's job-809 pass 0 ------------
|
||||
base = q.paths and {i: q.paths[f"O{i}"][q.meta[f"O{i}"]["n_prompt"]:] for i in range(6)}
|
||||
arms = {}
|
||||
for run in sorted(q.reads):
|
||||
fr = free_requests(q, run)
|
||||
for rep in sorted({k[1] for k in fr}):
|
||||
arms[f"{run}" + (f" set {rep}" if rep else "")] = {p: fr[(p, rep)][0] for p in range(6) if (p, rep) in fr}
|
||||
oph = os.path.expanduser("~/work/gpu-runs/round-profile")
|
||||
for tag in ("orig-ph", "orig-dec-A", "orig-dec-A35", "orig-dec-AD", "orig-dec-AU", "orig-dec-S", "orig-dec-SP"):
|
||||
f = os.path.join(d, "external", tag + ".out") if os.path.exists(os.path.join(d, "external", tag + ".out")) else os.path.join(oph, tag, "out.txt")
|
||||
if os.path.exists(f):
|
||||
s = out_sequences(f)
|
||||
arms[tag + " pass 0"] = {p: s[2 * p][0] for p in range(6)}; arms[tag + " pass 1"] = {p: s[2 * p + 1][0] for p in range(6)}
|
||||
out.append("## S. Original greedy sequences: first differing token index vs the job-809 pass 0 ('=' identical)" + chr(10))
|
||||
out.append("| Original arm | " + " | ".join(f"p{i}" for i in range(6)) + " |" + chr(10) + "|---|" + "---|" * 6)
|
||||
for arm, seqs in arms.items():
|
||||
out.append(f"| {arm} | " + " | ".join(first_diff(base[p], seqs[p]) if p in seqs else "-" for p in range(6)) + " |")
|
||||
out.append("")
|
||||
import q_port
|
||||
if q.ports:
|
||||
per = q_port.port_vs_original(q, out, result, ref_run, HEAD, row_line)
|
||||
q_port.per_prompt(q, out, per, row_line, HEAD)
|
||||
q_port.port_envelope(q, out, result, HEAD, row_line)
|
||||
q_port.batched_reference(q, out, result, HEAD, row_line)
|
||||
q_port.divergence(q, out, ref_run)
|
||||
q_port.eos_section(q, out, ref_run)
|
||||
q_port.verdict(q, out, env, result)
|
||||
q_port.pooled(q, out, result, ref_run)
|
||||
q_port.long_section(q, out, result)
|
||||
q_port.retrieval_section(q, out, result)
|
||||
open_md ="\n".join(out)
|
||||
print(open_md)
|
||||
if md_out: open(md_out, "w").write(open_md + "\n")
|
||||
if json_out: json.dump({"envelope": env, **result}, open(json_out, "w"), indent=1, default=str)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Layer-by-layer comparison of the port's and the Original's residual stream on one token path (docs/quality-gate.md).
|
||||
|
||||
usage: q_ladder.py LADDER_DIR TARGET_POS [CASE_IDS_FILE]
|
||||
|
||||
LADDER_DIR holds what job 9970 wrote: port.log (the port's `DBG residual window seq= first= rows= inputs=[..]` lines) and port/l_win*.f32,
|
||||
orig/l_win*.f32 plus ../runs/ladder-orig/err.txt (the Original's `NUMRESID seq= pos0= T= tokens=` lines). A dump is
|
||||
[96 frames][rows][4*2560] f32, frame = 2*layer + half. For every position both engines computed on the path, the relative L2 distance
|
||||
|port - orig| / |orig| per frame is formed; the report lists, per frame, the value at TARGET_POS next to the median over all other positions.
|
||||
"""
|
||||
import array, math, os, re, statistics, sys
|
||||
|
||||
W = 4 * 2560
|
||||
|
||||
|
||||
def rd(path):
|
||||
a = array.array("f")
|
||||
with open(path, "rb") as f:
|
||||
a.frombytes(f.read())
|
||||
return a
|
||||
|
||||
|
||||
def windows_port(log):
|
||||
out = []
|
||||
for line in open(log, errors="replace"):
|
||||
m = re.match(r"DBG residual window seq=(\d+) first=(\d+) rows=(\d+) inputs=\[([0-9, ]+)\]", line)
|
||||
if m:
|
||||
out.append((int(m[2]), [int(x) for x in m[4].split(",")], int(m[1])))
|
||||
return out
|
||||
|
||||
|
||||
def windows_orig(err):
|
||||
out = []
|
||||
for line in open(err, errors="replace"):
|
||||
m = re.match(r"NUMRESID seq=(\d+) pos0=(\d+) T=(\d+) tokens=([0-9,]+)", line)
|
||||
if m:
|
||||
out.append((int(m[2]), [int(x) for x in m[4].split(",")], int(m[1])))
|
||||
return out
|
||||
|
||||
|
||||
def valid(wins, truth):
|
||||
out = {}
|
||||
for wi, (p0, toks, _) in enumerate(wins):
|
||||
for k in range(len(toks)):
|
||||
if p0 + k < len(truth) and toks[: k + 1] == truth[p0: p0 + k + 1]:
|
||||
out.setdefault(p0 + k, (wi, k))
|
||||
else:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def main(argv):
|
||||
d, target = argv[0], int(argv[1])
|
||||
truth = [int(x) for x in open(argv[2] if len(argv) > 2 else os.path.join(d, "..", "cases", "B1.ids")).read().strip().split(",")]
|
||||
pw = windows_port(os.path.join(d, "port.log"))
|
||||
ow = windows_orig(os.path.join(d, "..", "runs", "ladder-orig", "err.txt"))
|
||||
pv, ov = valid(pw, truth), valid(ow, truth)
|
||||
common = sorted(set(pv) & set(ov))
|
||||
print(f"port windows {len(pw)}, Original windows {len(ow)}, rows on the path: port {len(pv)} Original {len(ov)} common {len(common)}")
|
||||
cache = {}
|
||||
|
||||
def frames(path):
|
||||
if path not in cache:
|
||||
cache[path] = rd(path)
|
||||
return cache[path]
|
||||
|
||||
rel = {} # pos -> [96 relL2]
|
||||
for pos in common:
|
||||
(pwi, pk), (owi, ok) = pv[pos], ov[pos]
|
||||
pl = os.path.join(d, "port", f"l_win{pw[pwi][2]:05d}_pos{pw[pwi][0]}.f32")
|
||||
ol = os.path.join(d, "orig", f"l_win{ow[owi][2]:05d}_pos{ow[owi][0]}.f32")
|
||||
if not (os.path.exists(pl) and os.path.exists(ol)):
|
||||
continue
|
||||
pT, oT = len(pw[pwi][1]), len(ow[owi][1])
|
||||
a, b = frames(pl), frames(ol)
|
||||
row = []
|
||||
for fr in range(96):
|
||||
x = a[(fr * pT + pk) * W: (fr * pT + pk + 1) * W]
|
||||
y = b[(fr * oT + ok) * W: (fr * oT + ok + 1) * W]
|
||||
num = sum((u - v) ** 2 for u, v in zip(x, y))
|
||||
den = sum(v * v for v in y)
|
||||
row.append(math.sqrt(num / den) if den else float("nan"))
|
||||
rel[pos] = row
|
||||
if len(cache) > 4:
|
||||
cache.pop(next(iter(cache)))
|
||||
if target not in rel:
|
||||
print("target position not compared; positions:", sorted(rel)[:5], "...", sorted(rel)[-5:])
|
||||
return
|
||||
others = [p for p in rel if p != target]
|
||||
print(f"positions compared {len(rel)} (target {target}, input token {truth[target]}); relL2 per frame (frame = 2*layer+half)")
|
||||
print("frame layer.half target median(others) ratio rank among rows")
|
||||
first = None
|
||||
for fr in range(96):
|
||||
med = statistics.median(rel[p][fr] for p in others)
|
||||
t = rel[target][fr]
|
||||
rank = 1 + sum(1 for p in others if rel[p][fr] > t)
|
||||
ratio = t / med if med else float("nan")
|
||||
if first is None and ratio > 3 and fr > 0:
|
||||
first = fr
|
||||
if fr < 8 or fr % 8 == 0 or fr == 95 or (first is not None and fr <= first + 2):
|
||||
print(f"{fr:4d} {fr // 2:2d}.{fr % 2} {t:.3e} {med:.3e} {ratio:6.2f} {rank}/{len(rel)}")
|
||||
print("first frame with target > 3x the median of the other rows:", first)
|
||||
worst = sorted(((statistics.mean(rel[p][8:]), p) for p in rel), reverse=True)[:5]
|
||||
print("rows with the largest mean relL2 over frames 8..95:", [(p, f"{v:.3f}") for v, p in worst])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Parsers and metrics of the model quality gate (docs/quality-gate.md). Offline analysis only; no runtime use.
|
||||
|
||||
A *row* is one engine's output at one position of one token path: the top-k log-probabilities of the next token given the
|
||||
tokens up to and including `pos`. Both engines print them in the same tab-separated form (verify.cpp `window_logprobs`):
|
||||
pos target lp(target) top1 lp(top1) match lp(extra) lp(target without extra) id:lp ... (descending)
|
||||
"""
|
||||
import json, math, os, re, statistics
|
||||
|
||||
class Row:
|
||||
__slots__ = ("pos", "target", "lp_target", "topk")
|
||||
def __init__(self, pos, target, lp_target, topk):
|
||||
self.pos, self.target, self.lp_target, self.topk = pos, target, lp_target, topk # topk: [(id, lp)] descending
|
||||
@property
|
||||
def top1(self): return self.topk[0][0]
|
||||
@property
|
||||
def margin(self): return self.topk[0][1] - self.topk[1][1]
|
||||
def lp(self, token):
|
||||
for t, v in self.topk:
|
||||
if t == token: return v
|
||||
return None
|
||||
def rank(self, token):
|
||||
for i, (t, _) in enumerate(self.topk):
|
||||
if t == token: return i + 1
|
||||
return None
|
||||
|
||||
def parse_row(line):
|
||||
f = line.rstrip("\n").split("\t")
|
||||
if len(f) < 9 or not f[0].lstrip("-").isdigit(): return None
|
||||
topk = [(int(a.split(":")[0]), float(a.split(":")[1])) for a in f[8:] if ":" in a]
|
||||
if len(topk) < 2: return None
|
||||
return Row(int(f[0]), int(f[1]), float(f[2]), topk)
|
||||
|
||||
def load_orig_logpos(run_dir):
|
||||
"""The Original's STRATA_LOGPOS file as one {pos: Row} dict per request, in request order (a request starts when the
|
||||
position does not increase)."""
|
||||
segments, prev = [], None
|
||||
for line in open(os.path.join(run_dir, "logpos"), errors="replace"):
|
||||
row = parse_row(line)
|
||||
if row is None: continue
|
||||
if prev is None or row.pos <= prev: segments.append({})
|
||||
prev = row.pos
|
||||
segments[-1][row.pos] = row
|
||||
names = [n for n in open(os.path.join(run_dir, "reqs.txt.names")).read().split("\n") if n]
|
||||
return segments, names
|
||||
|
||||
def load_case(cases_dir, name):
|
||||
return [int(x) for x in open(os.path.join(cases_dir, name + ".ids")).read().strip().split(",")]
|
||||
|
||||
def orig_reads(run_dir, cases_dir):
|
||||
"""{label: (case name, request keys, {pos: Row})} for the teacher-forced read requests of an Original run; repeated labels
|
||||
get a '#k' suffix. Rows of the read requests only."""
|
||||
segments, names = load_orig_logpos(run_dir)
|
||||
out, seen = {}, {}
|
||||
for seg, label in zip(segments, names):
|
||||
if not label.startswith("read:"): continue
|
||||
spec = label[5:]
|
||||
case = spec.split(":")[0]
|
||||
k = seen.get(spec, 0); seen[spec] = k + 1
|
||||
out[spec + ("" if k == 0 else f"#{k}")] = (case, spec.split(":")[1:], seg)
|
||||
return out
|
||||
|
||||
def parse_port_log(path):
|
||||
"""The port smoke log -> list of runs {index, pass, forced, windows:[(position, inputs, [Row])], output:[ids] or None}.
|
||||
Rows are attached to the window announced by the preceding `DBG logprobs window` line."""
|
||||
runs, cur, win = [], None, None
|
||||
for line in open(path, errors="replace"):
|
||||
m = re.match(r"DBG corpus (\d+) pass=(\d+) begin forced=(true|false)", line)
|
||||
if m:
|
||||
cur = {"index": int(m[1]), "pass": int(m[2]), "forced": m[3] == "true", "windows": [], "output": None, "notes": []}
|
||||
runs.append(cur); win = None; continue
|
||||
if cur is None: continue
|
||||
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\] argmax_ids=\[([0-9, -]*)\]", line)
|
||||
if m:
|
||||
win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], [])
|
||||
cur["windows"].append(win); continue
|
||||
m = re.match(r"DBG corpus (\d+) output(?: pass=(\d+))? \((\d+) tokens, rounds (\d+)\): ([0-9 ]*)", line)
|
||||
if m and int(m[1]) == cur["index"] and int(m[2] or 0) == cur["pass"]:
|
||||
cur["output"] = [int(x) for x in m[5].split()]; continue
|
||||
if line.startswith("DBG corpus") and "forced:" in line: cur["notes"].append(line.strip()); continue
|
||||
row = parse_row(line)
|
||||
if row is not None and win is not None and len(win[2]) < len(win[1]):
|
||||
win[2].append(row)
|
||||
return runs
|
||||
|
||||
def valid_rows(windows, truth):
|
||||
"""{pos: Row} of the rows whose consumed tokens (the window's inputs up to the row) equal the token path `truth`
|
||||
(the first occurrence of a position wins). A row after a rejected draft token is conditioned on text that is not on
|
||||
the path and is skipped."""
|
||||
out = {}
|
||||
for position, inputs, rows in windows:
|
||||
for r, row in enumerate(rows):
|
||||
if position + r >= len(truth) or inputs[: r + 1] != truth[position : position + r + 1]: break
|
||||
out.setdefault(position + r, row)
|
||||
return out
|
||||
|
||||
def compare(ref, other, first_pos=0, last_pos=10**9):
|
||||
"""Per common position of two {pos: Row} dicts, in [first_pos, last_pos]."""
|
||||
res = []
|
||||
for pos in sorted(set(ref) & set(other)):
|
||||
if not first_pos <= pos <= last_pos: continue
|
||||
a, b = ref[pos], other[pos]
|
||||
common = [t for t, _ in a.topk if b.lp(t) is not None]
|
||||
dmax = max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan"))
|
||||
d1 = abs(a.topk[0][1] - b.lp(a.top1)) if b.lp(a.top1) is not None else float("nan")
|
||||
res.append({"pos": pos, "dmax": dmax, "ncommon": len(common), "flip": a.top1 != b.top1,
|
||||
"ref_margin": a.margin, "other_margin": b.margin, "ref_top1": a.top1, "other_top1": b.top1,
|
||||
"other_rank_of_ref_top1": b.rank(a.top1), "ref_rank_of_other_top1": a.rank(b.top1),
|
||||
"d_target": abs(a.lp_target - b.lp_target), "d_top1": d1})
|
||||
return res
|
||||
|
||||
def quantile(values, q):
|
||||
v = sorted(x for x in values if not math.isnan(x))
|
||||
if not v: return float("nan")
|
||||
k = (len(v) - 1) * q; lo, hi = int(math.floor(k)), int(math.ceil(k))
|
||||
return v[lo] + (v[hi] - v[lo]) * (k - lo)
|
||||
|
||||
def _qs(v):
|
||||
v = [x for x in v if not math.isnan(x)]
|
||||
return {"median": quantile(v, .5), "p90": quantile(v, .9), "p99": quantile(v, .99), "max": max(v, default=float("nan"))}
|
||||
|
||||
def summary(rows):
|
||||
"""Distribution of the three per-position deviations: dmax (max over the common top-k, the tail included), d_top1 (the
|
||||
reference's argmax token) and d_target (the token on the path); plus the argmax flips and the reference margin at each."""
|
||||
flips = [r for r in rows if r["flip"]]
|
||||
return {"n": len(rows), "dmax": _qs([r["dmax"] for r in rows]), "d_top1": _qs([r["d_top1"] for r in rows]),
|
||||
"d_target": _qs([r["d_target"] for r in rows]), "flips": len(flips),
|
||||
"flip_margins": sorted(round(r["ref_margin"], 3) for r in flips),
|
||||
"flip_pos": [(r.get("case"), r["pos"], round(r["ref_margin"], 3), round(r["other_margin"], 3)) for r in flips]}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Request file for one Original `--serve` process of the quality gate (docs/quality-gate.md).
|
||||
|
||||
usage: q_mkreqs.py CASES_DIR OUT --read SPEC[,SPEC...] [--free N] [--free-keys SET[/SET...]]
|
||||
|
||||
SPEC is a case name (CASES_DIR/<name>.ids) optionally followed by `:key=value[:key=value]` request keys of the Original's
|
||||
serve protocol (e.g. `O0:pcie_frac=0`). Each becomes `GEN 1 <ids>`: the whole sequence (prompt and the tokens another
|
||||
run produced) is read once and, with STRATA_LOGPOS set, every row's log-probabilities are logged (teacher forcing).
|
||||
`--free N` then adds a free greedy request of 128 tokens for each of the first N corpus prompts (O0..O<N-1> prompts,
|
||||
cut to n_prompt); --free-keys gives one SET of request keys (`k=v,k=v`) per pass over the N prompts, passes separated
|
||||
by '/' (e.g. `spec_min_p=0.5/spec_min_p=0`).
|
||||
OUT.names lists one label per request, in order, for the analysis.
|
||||
"""
|
||||
import json, sys
|
||||
|
||||
def main(argv):
|
||||
cases, out = argv[0], argv[1]
|
||||
read, free, keysets = [], 0, [[]]
|
||||
i = 2
|
||||
while i < len(argv):
|
||||
if argv[i] == "--read": read = [s for s in argv[i + 1].split(",") if s]; i += 2
|
||||
elif argv[i] == "--free": free = int(argv[i + 1]); i += 2
|
||||
elif argv[i] == "--free-keys": keysets = [[k for k in s.split(",") if k] for s in argv[i + 1].split("/")]; i += 2
|
||||
else: raise SystemExit("bad option " + argv[i])
|
||||
meta = json.load(open(cases + "/meta.json"))
|
||||
lines, names = [], []
|
||||
for spec in read:
|
||||
name, *kv = spec.split(":")
|
||||
ids = open(f"{cases}/{name}.ids").read().strip()
|
||||
lines.append(" ".join(["GEN 1"] + kv + [ids])); names.append("read:" + spec)
|
||||
for rep, keys in enumerate(keysets):
|
||||
for p in range(free):
|
||||
ids = open(f"{cases}/O{p}.ids").read().strip().split(",")[: meta[f"O{p}"]["n_prompt"]]
|
||||
lines.append(" ".join(["GEN 128"] + keys + [",".join(ids)])); names.append(f"free:{p}:{rep}")
|
||||
lines.append("QUIT")
|
||||
open(out, "w").write("\n".join(lines) + "\n")
|
||||
open(out + ".names", "w").write("\n".join(names) + "\n")
|
||||
print(len(names), "requests ->", out)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,394 @@
|
||||
"""Port sections of the quality-gate report (see q_analyze.py): port vs Original, port envelope, divergence positions, verdict."""
|
||||
import math
|
||||
from q_lib import compare, summary, valid_rows, load_case
|
||||
|
||||
EOS = 248046
|
||||
|
||||
|
||||
def fmt(x, nd=3):
|
||||
return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else f"{x:.{nd}f}"
|
||||
|
||||
|
||||
def gen_rng(q, case):
|
||||
return q.meta[case]["n_prompt"] - 1, len(q.paths[case]) - 2
|
||||
|
||||
|
||||
def forced_rows(q, run, i):
|
||||
"""Rows of the port's forced pass for corpus prompt i, valid on the Original's pass-0 path O<i>."""
|
||||
truth = q.paths[f"O{i}"]
|
||||
for r in q.ports.get(run, []):
|
||||
if r["index"] == i and r["pass"] == 0 and r["forced"]:
|
||||
return valid_rows(r["windows"], truth), r
|
||||
return None, None
|
||||
|
||||
|
||||
def free_rows(q, run, i):
|
||||
"""(rows, run record, path) of the port's free pass: rows valid on its own output path."""
|
||||
for r in q.ports.get(run, []):
|
||||
if r["index"] == i and r["pass"] == 1 and not r["forced"] and r["output"] is not None:
|
||||
prompt = q.paths[f"O{i}"][: q.meta[f"O{i}"]["n_prompt"]]
|
||||
path = prompt + r["output"]
|
||||
return valid_rows(r["windows"], path), r, path
|
||||
return None, None, None
|
||||
|
||||
|
||||
def port_vs_original(q, out, result, ref_run, head, row_line):
|
||||
out.append("## B. Port vs Original, teacher-forced along the Original's pass-0 greedy tokens\n")
|
||||
out.append("Reference rows: the Original's R1 reads (static tier, the port's configuration family); the port's rows are its own "
|
||||
"verify-window top-16 at every position of the forced path (rows after a rejected draft token are not on the path and are skipped).\n")
|
||||
out.append(head)
|
||||
per = {}
|
||||
for run in q.ports:
|
||||
rows = []
|
||||
for i in range(6):
|
||||
fr, rec = forced_rows(q, run, i)
|
||||
ref = q.path_rows(ref_run, f"O{i}", [])
|
||||
if fr is None or ref is None:
|
||||
continue
|
||||
lo, hi = gen_rng(q, f"O{i}")
|
||||
rr = [dict(r, case=f"O{i}") for r in compare(ref, fr, lo, hi)]
|
||||
per[(run, i)] = rr
|
||||
rows += rr
|
||||
if rows:
|
||||
s = summary(rows)
|
||||
result["port_vs_orig_" + run] = s
|
||||
out.append(row_line(f"{run} vs R1", s))
|
||||
out.append("")
|
||||
return per
|
||||
|
||||
|
||||
def per_prompt(q, out, per, row_line, head):
|
||||
out.append("### B2. Per prompt (forced pass; each port run vs R1)\n")
|
||||
cols = head.split("\n")[0].split("| rows |")[1].strip("| ")
|
||||
out.append("| port run | prompt | forced-pass completion | " + cols + " |")
|
||||
out.append("|---|---|---|" + "---|" * (cols.count("|") + 1))
|
||||
for (run, i), rows in sorted(per.items()):
|
||||
s = summary(rows)
|
||||
_, rec = forced_rows(q, run, i)
|
||||
note = "; ".join(n.split("forced:")[1].strip() for n in rec["notes"] if "forced:" in n) or "-"
|
||||
line = row_line(f"{run} p{i}", s).split("|")
|
||||
out.append(f"| {run} | p{i} | {note} | " + "|".join(line[3:]))
|
||||
out.append("")
|
||||
|
||||
|
||||
def port_envelope(q, out, result, head, row_line):
|
||||
out.append("## C. Port vs port (same forced path, different configuration)\n")
|
||||
out.append(head)
|
||||
runs = list(q.ports)
|
||||
base = "P1-static" if "P1-static" in runs else (runs[0] if runs else None)
|
||||
for run in runs:
|
||||
if run == base:
|
||||
continue
|
||||
rows = []
|
||||
for i in range(6):
|
||||
a, _ = forced_rows(q, base, i)
|
||||
b, _ = forced_rows(q, run, i)
|
||||
if a is None or b is None:
|
||||
continue
|
||||
lo, hi = gen_rng(q, f"O{i}")
|
||||
rows += [dict(r, case=f"O{i}") for r in compare(a, b, lo, hi)]
|
||||
if rows:
|
||||
s = summary(rows)
|
||||
result["port_env_" + run] = s
|
||||
out.append(row_line(f"{run} vs {base}", s))
|
||||
out.append("")
|
||||
|
||||
|
||||
def divergence(q, out, ref_run):
|
||||
out.append("## D. Where the port's free run leaves the Original's pass-0 tokens\n")
|
||||
out.append("t* = first generated token that differs. Both engines' rows at t* are conditioned on the same text (the common prefix): "
|
||||
"the Original's R1 read of its own path and the port's free-pass row. margin = top1 - top2 logprob of that engine's row.\n")
|
||||
out.append("| port run | prompt | t* | Original token (lp; port's lp and rank) | port token (lp; Original's lp and rank) | Original margin | port margin | reading |")
|
||||
out.append("|---|---|---|---|---|---|---|---|")
|
||||
for run in q.ports:
|
||||
for i in range(6):
|
||||
fr, rec, path = free_rows(q, run, i)
|
||||
if fr is None:
|
||||
continue
|
||||
n_p = q.meta[f"O{i}"]["n_prompt"]
|
||||
orig = q.paths[f"O{i}"][n_p:]
|
||||
mine = path[n_p:]
|
||||
t = next((k for k in range(min(len(orig), len(mine))) if orig[k] != mine[k]), None)
|
||||
if t is None:
|
||||
out.append(f"| {run} | p{i} | none | identical for {min(len(orig), len(mine))} tokens | lengths {len(orig)}/{len(mine)} | | | "
|
||||
f"{'same length' if len(orig) == len(mine) else 'LENGTH DIFFERS'} |")
|
||||
continue
|
||||
pos = n_p - 1 + t
|
||||
o = q.path_rows(ref_run, f"O{i}", [])
|
||||
if o is None or pos not in o or pos not in fr:
|
||||
out.append(f"| {run} | p{i} | {t} | row missing | | | | |")
|
||||
continue
|
||||
ro, rp = o[pos], fr[pos]
|
||||
ot, pt = orig[t], mine[t]
|
||||
out.append(f"| {run} | p{i} | {t} | {ot} ({fmt(ro.lp(ot))}; port {fmt(rp.lp(ot))}, rank {rp.rank(ot) or '>16'}) | "
|
||||
f"{pt} ({fmt(rp.lp(pt))}; Original {fmt(ro.lp(pt))}, rank {ro.rank(pt) or '>16'}) | {fmt(ro.margin)} | {fmt(rp.margin)} | "
|
||||
f"{'near tie in both engines' if max(ro.margin, rp.margin) <= 0.5 else 'CHECK'} |")
|
||||
out.append("")
|
||||
|
||||
|
||||
def eos_section(q, out, ref_run):
|
||||
out.append("## E2. Stop token (<|im_end|> 248046) at the end of the Original's paths\n")
|
||||
out.append("| prompt | generated | Original R1: lp / rank of the stop token at the last row | port forced pass: lp / rank | forced pass produced |")
|
||||
out.append("|---|---|---|---|---|")
|
||||
for i in (2, 5):
|
||||
c = f"O{i}"
|
||||
last = len(q.paths[c]) - 2
|
||||
o = q.path_rows(ref_run, c, [])
|
||||
if o is None or last not in o:
|
||||
continue
|
||||
cells, stops = [], []
|
||||
for run in q.ports:
|
||||
fr, rec = forced_rows(q, run, i)
|
||||
if fr and last in fr:
|
||||
cells.append(f"{run}: {fmt(fr[last].lp(EOS))} / {fr[last].rank(EOS) or '>16'}")
|
||||
if rec:
|
||||
stops.append(f"{run}: " + ("; ".join(n.split('forced:')[1].strip() for n in rec['notes'] if 'forced:' in n) or "-"))
|
||||
out.append(f"| p{i} | {len(q.paths[c]) - q.meta[c]['n_prompt']} | {fmt(o[last].lp(EOS))} / {o[last].rank(EOS) or '>16'} | "
|
||||
f"{'; '.join(cells)} | {'; '.join(stops)} |")
|
||||
out.append("")
|
||||
|
||||
|
||||
def verdict(q, out, env, result):
|
||||
arms = [v for k, v in env.items() if v["d_top1"]["max"] > 0 and "first reads" not in k]
|
||||
if not arms:
|
||||
return
|
||||
t = {"d_top1_p99": max(a["d_top1"]["p99"] for a in arms), "d_top1_max": max(a["d_top1"]["max"] for a in arms),
|
||||
"dmax_p99": max(a["dmax"]["p99"] for a in arms), "dmax_max": max(a["dmax"]["max"] for a in arms),
|
||||
"flip_rate": max(a["flips"] / a["n"] for a in arms), "flip_margin": max((m for a in arms for m in a["flip_margins"]), default=0.0)}
|
||||
result["tolerances"] = t
|
||||
out.append("## V. Gate and verdict\n")
|
||||
out.append("Tolerances = the largest value the Original shows against ITS OWN reference (R1) over the non-identical envelope arms of section A "
|
||||
"(pcie_frac, near-empty tier, window width, repeated adaptive reads): "
|
||||
f"d_top1 p99 <= {fmt(t['d_top1_p99'])}, d_top1 max <= {fmt(t['d_top1_max'])}, dmax16 p99 <= {fmt(t['dmax_p99'])}, "
|
||||
f"dmax16 max <= {fmt(t['dmax_max'])}, argmax-flip rate <= {t['flip_rate'] * 100:.2f}%, Original margin at every flip <= {fmt(t['flip_margin'])}.\n")
|
||||
out.append("| port arm | d_top1 p99 | d_top1 max | dmax16 p99 | dmax16 max | flip rate | max flip margin | result |")
|
||||
out.append("|---|---|---|---|---|---|---|---|")
|
||||
names = ["top1 p99", "top1 max", "dmax p99", "dmax max", "flip rate", "flip margin"]
|
||||
for k, s in result.items():
|
||||
if not k.startswith("port_vs_orig_"):
|
||||
continue
|
||||
fr = s["flips"] / s["n"]
|
||||
fm = max(s["flip_margins"], default=0.0)
|
||||
checks = [s["d_top1"]["p99"] <= t["d_top1_p99"], s["d_top1"]["max"] <= t["d_top1_max"], s["dmax"]["p99"] <= t["dmax_p99"],
|
||||
s["dmax"]["max"] <= t["dmax_max"], fr <= t["flip_rate"], fm <= t["flip_margin"]]
|
||||
res = "PASS" if all(checks) else "FAIL (" + ", ".join(n for n, c in zip(names, checks) if not c) + ")"
|
||||
out.append(f"| {k[13:]} | {fmt(s['d_top1']['p99'])} | {fmt(s['d_top1']['max'])} | {fmt(s['dmax']['p99'])} | {fmt(s['dmax']['max'])} | "
|
||||
f"{fr * 100:.2f}% | {fmt(fm)} | {res} |")
|
||||
out.append("")
|
||||
|
||||
|
||||
def batched_reference(q, out, result, head, row_line):
|
||||
"""Port (forced pass) vs the Original's batched-prompt reads B<i> (first <=40 generated tokens of prompts 0..4)."""
|
||||
rows_by_run = {}
|
||||
for run in q.ports:
|
||||
rows = []
|
||||
for i in range(5):
|
||||
b = q.path_rows(f"B{i}-batched", f"B{i}", [])
|
||||
fr, _ = forced_rows(q, run, i)
|
||||
if not b or fr is None:
|
||||
continue
|
||||
lo = q.meta[f"O{i}"]["n_prompt"] - 1
|
||||
rows += [dict(r, case=f"O{i}") for r in compare(b, fr, lo, len(q.paths[f"B{i}"]) - 2)]
|
||||
if rows:
|
||||
rows_by_run[run] = rows
|
||||
if not rows_by_run:
|
||||
return
|
||||
out.append("## B3. Port vs the Original with the prompt read the same (batched) way\n")
|
||||
out.append("Original rows: the first <=40 generated tokens of prompts 0-4 read with the batched prompt path "
|
||||
"(job 9963); the port's rows: its forced pass (batched prefill), same positions.\n")
|
||||
out.append(head)
|
||||
for run, rows in rows_by_run.items():
|
||||
s = summary(rows)
|
||||
result["port_vs_batched_" + run] = s
|
||||
out.append(row_line(f"{run} vs Original (batched prompt)", s))
|
||||
out.append("")
|
||||
|
||||
|
||||
def parse_long_port(path, prompt):
|
||||
"""{pos: Row} of the port's rows that lie on its own path (prompt + its output) in a long-context log: a row after a draft token that
|
||||
was rejected is conditioned on text that is not on the path and is skipped."""
|
||||
import re
|
||||
from q_lib import parse_row, valid_rows
|
||||
windows, win, output = [], None, None
|
||||
for line in open(path, errors="replace"):
|
||||
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\]", line)
|
||||
if m:
|
||||
win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], [])
|
||||
windows.append(win)
|
||||
continue
|
||||
m = re.match(r"long-smoke output ids \(\d+\): ([0-9,]*)", line)
|
||||
if m and output is None:
|
||||
output = [int(x) for x in m[1].split(",") if x]
|
||||
continue
|
||||
r = parse_row(line)
|
||||
if r is not None and win is not None and len(win[2]) < len(win[1]):
|
||||
win[2].append(r)
|
||||
return valid_rows(windows, prompt + (output or []))
|
||||
|
||||
|
||||
def long_section(q, out, result):
|
||||
import glob
|
||||
import os
|
||||
from q_lib import orig_reads
|
||||
chunks = [2048, 4096, 6144, 8192]
|
||||
orig = {}
|
||||
for c in chunks:
|
||||
run = f"L-c{c}"
|
||||
if run in q.reads:
|
||||
reads = q.reads[run]
|
||||
first = [v for k, v in reads.items() if k == "L16"]
|
||||
if first:
|
||||
orig[c] = first[0][2]
|
||||
port = {}
|
||||
for c in chunks:
|
||||
p = os.path.join(q.d, "runs", f"PL-c{c}", "port.log")
|
||||
if os.path.exists(p):
|
||||
port[c] = parse_long_port(p, load_case(q.cases, "L16")[:16000])
|
||||
if not orig and not port:
|
||||
return
|
||||
out.append("## L. 16,000-token prompt: logits at the three generated positions, by prefill chunk\n")
|
||||
out.append("Rows 15999, 16000, 16001 predict generated tokens 0, 1, 2 (271, 248068, then 198 vs 271: the near tie). lp = log-probability; margin = lp(198) - lp(271).\n")
|
||||
out.append("| chunk | engine | lp(271) @15999 | lp(248068) @16000 | lp(198) @16001 | lp(271) @16001 | margin 198-271 | argmax @16001 |")
|
||||
out.append("|---|---|---|---|---|---|---|---|")
|
||||
for c in chunks:
|
||||
for name, src in (("Original", orig), ("port", port)):
|
||||
if c not in src:
|
||||
continue
|
||||
r = src[c]
|
||||
if not all(p in r for p in (15999, 16000, 16001)):
|
||||
continue
|
||||
a, b, d = r[15999], r[16000], r[16001]
|
||||
l198, l271 = d.lp(198), d.lp(271)
|
||||
out.append(f"| {c} | {name} | {fmt(a.lp(271))} | {fmt(b.lp(248068))} | {fmt(l198)} | {fmt(l271)} | "
|
||||
f"{fmt(None if l198 is None or l271 is None else l198 - l271)} | {d.top1} |")
|
||||
out.append("")
|
||||
out.append("| chunk | port - Original @15999 (top1) | @16000 (top1) | @16001 lp(198) | @16001 lp(271) |\n|---|---|---|---|---|")
|
||||
for c in chunks:
|
||||
if c in orig and c in port and all(p in orig[c] and p in port[c] for p in (15999, 16000, 16001)):
|
||||
o, p = orig[c], port[c]
|
||||
out.append(f"| {c} | {fmt(p[15999].lp(271) - o[15999].lp(271))} | {fmt(p[16000].lp(248068) - o[16000].lp(248068))} | "
|
||||
f"{fmt(p[16001].lp(198) - o[16001].lp(198))} | {fmt(p[16001].lp(271) - o[16001].lp(271))} |")
|
||||
out.append("")
|
||||
# chunk sensitivity of each engine: lp(198)-lp(271) spread over the chunk sizes
|
||||
for name, src in (("Original", orig), ("port", port)):
|
||||
vals = {c: src[c][16001].lp(198) - src[c][16001].lp(271) for c in chunks if c in src and 16001 in src[c]
|
||||
and src[c][16001].lp(198) is not None and src[c][16001].lp(271) is not None}
|
||||
if vals:
|
||||
out.append(f"{name}: lp(198) - lp(271) at 16001 by chunk: " + ", ".join(f"{c}: {v:+.3f}" for c, v in sorted(vals.items()))
|
||||
+ f" (spread {max(vals.values()) - min(vals.values()):.3f} nats)\n")
|
||||
|
||||
|
||||
def pooled(q, out, result, ref_run="R1-static"):
|
||||
"""Pooled comparison: all non-identical Original envelope arms vs all port arms (same reference rows, same positions)."""
|
||||
from q_lib import compare
|
||||
cases = [f"O{i}" for i in range(6)]
|
||||
env_arms = [("R1-static", ["pcie_frac=0"], 0), ("R2-nearcpu", [], 0), ("R3-spec2", [], 0),
|
||||
("R4-adaptive", ["pcie_frac=0.55"], 0), ("R4-adaptive", ["pcie_frac=0.55"], 1)]
|
||||
env_rows, port_rows, pp_rows = [], [], []
|
||||
for run, keys, k in env_arms:
|
||||
for c in cases:
|
||||
ref, oth = q.path_rows(ref_run, c, []), q.path_rows(run, c, keys, k)
|
||||
if ref and oth:
|
||||
lo, hi = q.meta[c]["n_prompt"] - 1, len(q.paths[c]) - 2
|
||||
env_rows += [dict(r, case=c) for r in compare(ref, oth, lo, hi)]
|
||||
base = "P1-static" if "P1-static" in q.ports else None
|
||||
for run in q.ports:
|
||||
for i in range(6):
|
||||
fr, _ = forced_rows(q, run, i)
|
||||
ref = q.path_rows(ref_run, f"O{i}", [])
|
||||
if fr is None or ref is None:
|
||||
continue
|
||||
lo, hi = gen_rng(q, f"O{i}")
|
||||
port_rows += [dict(r, case=f"O{i}") for r in compare(ref, fr, lo, hi)]
|
||||
if base and run != base:
|
||||
a, _ = forced_rows(q, base, i)
|
||||
if a is not None:
|
||||
pp_rows += [dict(r, case=f"O{i}") for r in compare(a, fr, lo, hi)]
|
||||
if not env_rows or not port_rows:
|
||||
return
|
||||
out.append("## V2. Pooled over arms\n")
|
||||
out.append("| pool | rows | d_top1 median | d_top1 p99 | d_top1 max | dmax16 p99 | flip rate | largest Original margin at a flip |\n|---|---|---|---|---|---|---|---|")
|
||||
def line(label, rows):
|
||||
s = summary(rows)
|
||||
out.append(f"| {label} | {s['n']} | {fmt(s['d_top1']['median'])} | {fmt(s['d_top1']['p99'])} | {fmt(s['d_top1']['max'])} | {fmt(s['dmax']['p99'])} | "
|
||||
f"{s['flips'] / s['n'] * 100:.2f}% | {fmt(max(s['flip_margins'], default=0.0))} |")
|
||||
return s
|
||||
result["pool_original"] = line("Original arms vs R1 (pcie 0, near-CPU tier, --spec 2, adaptive repeats 1-2)", env_rows)
|
||||
result["pool_port"] = line(f"port arms vs R1 ({', '.join(q.ports)})", port_rows)
|
||||
worst = max(port_rows, key=lambda r: r["d_top1"])
|
||||
rest = [r for r in port_rows if not (r["case"] == worst["case"] and r["pos"] == worst["pos"])]
|
||||
result["pool_port_wo_worst"] = line(f"same without the worst row ({worst['case']} position {worst['pos']}, d_top1 {worst['d_top1']:.2f}) in every arm", rest)
|
||||
if pp_rows:
|
||||
result["pool_port_port"] = line(f"port arms vs {base} (port's own envelope)", pp_rows)
|
||||
out.append("")
|
||||
|
||||
|
||||
def parse_long_multi(path):
|
||||
"""[(prompt_tokens, windows, output)] of a port long-smoke log with several prompts."""
|
||||
import re
|
||||
from q_lib import parse_row
|
||||
segs, cur, win = [], None, None
|
||||
for line in open(path, errors="replace"):
|
||||
m = re.match(r"long-smoke prompt tokens=(\d+)", line)
|
||||
if m:
|
||||
cur = {"n": int(m[1]), "windows": [], "output": None}
|
||||
segs.append(cur)
|
||||
win = None
|
||||
continue
|
||||
if cur is None:
|
||||
continue
|
||||
m = re.match(r"DBG logprobs window position=(\d+) inputs=\[([0-9, -]*)\]", line)
|
||||
if m:
|
||||
win = (int(m[1]), [int(x) for x in m[2].split(",") if x.strip()], [])
|
||||
cur["windows"].append(win)
|
||||
continue
|
||||
m = re.match(r"long-smoke output ids \(\d+\): ([0-9,]*)", line)
|
||||
if m and cur["output"] is None:
|
||||
cur["output"] = [int(x) for x in m[1].split(",") if x]
|
||||
continue
|
||||
r = parse_row(line)
|
||||
if r is not None and win is not None and len(win[2]) < len(win[1]):
|
||||
win[2].append(r)
|
||||
return segs
|
||||
|
||||
|
||||
def retrieval_section(q, out, result):
|
||||
"""Teacher-forced comparison on the first <=120 tokens of the Original's 100k / 180k answers, and the divergence rows."""
|
||||
import os
|
||||
from q_lib import orig_reads
|
||||
run = "RET-orig-read"
|
||||
pf = os.path.join(q.d, "runs", "RET-port-forced", "port.log")
|
||||
if run not in q.reads or not os.path.exists(pf):
|
||||
return
|
||||
import re
|
||||
reqs = [n for n in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if n and n != "QUIT"]
|
||||
from q_lib import load_orig_logpos
|
||||
segs, _ = load_orig_logpos(os.path.join(q.d, "runs", run))
|
||||
# only the answer reads log rows (the batched prompt reads do not): segments are 100k+answer, 180k+answer
|
||||
orig = {100000: segs[0] if segs else None, 180000: segs[1] if len(segs) > 1 else None}
|
||||
ports = {s["n"]: s for s in parse_long_multi(pf)}
|
||||
out.append("## R. Long-context retrieval: teacher-forced along the Original's answers\n")
|
||||
out.append("Original: prompt read batched (chunk 8192), the answer through the verify windows; port: forced pass, int8 KV streamed, chunk 8192. Rows from the last prompt token on.\n")
|
||||
out.append("| prompt | answer tokens forced | rows compared | d_top1 med / p99 / max | dmax16 p99 / max | flips | Original margin at the flips | stop token lp/rank (Original; port) |")
|
||||
out.append("|---|---|---|---|---|---|---|---|")
|
||||
for n in (100000, 180000):
|
||||
o, p = orig.get(n), ports.get(n)
|
||||
if not o or not p:
|
||||
continue
|
||||
ans = [int(x) for x in open(os.path.join(q.d, "long-force", f"answer{n}.ids")).read().split(",")] if os.path.exists(os.path.join(q.d, "long-force", f"answer{n}.ids")) else []
|
||||
# the path: prompt ids from the long-180k dir are not in cases; take them from the Original request line
|
||||
line = [l for l in open(os.path.join(q.d, "runs", run, "reqs.txt")).read().split("\n") if l.startswith("GEN 1 ")][1 if n == 100000 else 3]
|
||||
path = [int(x) for x in line[len("GEN 1 "):].split(",")]
|
||||
rows = valid_rows(p["windows"], path)
|
||||
lo, hi = n - 1, len(path) - 2
|
||||
cmp_ = compare(o, rows, lo, hi)
|
||||
if not cmp_:
|
||||
continue
|
||||
s = summary(cmp_)
|
||||
result[f"retrieval_{n}"] = s
|
||||
stop = len(path) - 2
|
||||
eos = (o.get(stop), rows.get(stop))
|
||||
cell = " ; ".join(f"{fmt(r.lp(path[-1])) if r else '-'} / {r.rank(path[-1]) if r else '-'}" for r in eos)
|
||||
out.append(f"| {n} | {len(path) - n} | {s['n']} | {fmt(s['d_top1']['median'])} / {fmt(s['d_top1']['p99'])} / {fmt(s['d_top1']['max'])} | "
|
||||
f"{fmt(s['dmax']['p99'])} / {fmt(s['dmax']['max'])} | {s['flips']} | {', '.join(map(str, s['flip_margins'])) or '-'} | {cell} |")
|
||||
out.append("")
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline data preparation for the quality gate (docs/quality-gate.md). Runs on the GPU server, writes only under OUT.
|
||||
|
||||
usage: q_prep.py OUT [--orig-out FILE] [--requests FILE] [--port-log TAG=FILE[@ARM] ...] [--free-run TAG=RUNDIR ...]
|
||||
|
||||
Writes, for the six-prompt corpus of ~/work/gpu-runs/prompts.txt:
|
||||
OUT/cases/<name>.ids comma-separated token ids: the prompt followed by one engine's greedy tokens
|
||||
OUT/cases/meta.json {name: {"n_prompt": N, "prompt": i, "source": ...}}
|
||||
OUT/force/c<i>.truth the Original's pass-0 sequence per prompt (what the port is teacher-forced along)
|
||||
Names: O<i> Original pass 0, Ob<i> Original pass 1 (when it differs), and <tag><i> for every --port-log NAME=FILE
|
||||
(the tag is the part before '='; sequences identical to an earlier one are not written twice).
|
||||
"""
|
||||
import json, os, re, sys
|
||||
|
||||
def orig_sequences(path):
|
||||
toks, cur = [], []
|
||||
for line in open(path):
|
||||
if line.startswith("T "):
|
||||
cur.append(int(line.split()[1]))
|
||||
elif line.startswith("DONE"):
|
||||
toks.append(cur); cur = []
|
||||
return toks
|
||||
|
||||
def prompts(path):
|
||||
out = []
|
||||
for line in open(path):
|
||||
m = re.match(r"GEN \d+ ([0-9,]+)\s*$", line)
|
||||
if m: out.append([int(x) for x in m[1].split(",")])
|
||||
return out[::2] # every prompt is requested twice (two passes)
|
||||
|
||||
def port_sequences(path, arm=None):
|
||||
"""Pass-0 outputs of the port's corpus log; with ARM only the section after '=== arm ARM:' (job 805 style logs)."""
|
||||
seqs = {}
|
||||
inside = arm is None
|
||||
for line in open(path, errors="replace"):
|
||||
if arm is not None and line.startswith("=== arm "):
|
||||
inside = line.startswith(f"=== arm {arm}:")
|
||||
if not inside: continue
|
||||
m = re.match(r"DBG corpus (\d+) output \((\d+) tokens, rounds \d+\): ([0-9 ]+)", line)
|
||||
if m: seqs[int(m[1])] = [int(x) for x in m[3].split()]
|
||||
return seqs
|
||||
|
||||
def main(argv):
|
||||
out = argv[0]; opts = argv[1:]
|
||||
orig = os.path.expanduser("~/work/gpu-runs/round-profile/orig-ph/out.txt")
|
||||
reqs = os.path.expanduser("~/work/gpu-runs/round-profile/original-requests.txt")
|
||||
ports, frees = [], []
|
||||
i = 0
|
||||
while i < len(opts):
|
||||
if opts[i] == "--orig-out": orig = opts[i + 1]; i += 2
|
||||
elif opts[i] == "--requests": reqs = opts[i + 1]; i += 2
|
||||
elif opts[i] == "--free-run": tag, f = opts[i + 1].split("=", 1); frees.append((tag, f)); i += 2
|
||||
elif opts[i] == "--port-log": tag, f = opts[i + 1].split("=", 1); ports.append((tag, f)); i += 2
|
||||
else: raise SystemExit("bad option " + opts[i])
|
||||
os.makedirs(out + "/cases", exist_ok=True); os.makedirs(out + "/force", exist_ok=True)
|
||||
P = prompts(reqs); O = orig_sequences(orig)
|
||||
assert len(P) == 6 and len(O) == 12, (len(P), len(O))
|
||||
meta, seen = {}, {}
|
||||
def add(name, prompt_index, prompt, tokens, source):
|
||||
key = tuple(prompt + tokens)
|
||||
if key in seen:
|
||||
return
|
||||
seen[key] = name
|
||||
open(f"{out}/cases/{name}.ids", "w").write(",".join(map(str, key)))
|
||||
meta[name] = {"n_prompt": len(prompt), "prompt": prompt_index, "source": source, "n_generated": len(tokens)}
|
||||
for i, p in enumerate(P):
|
||||
add(f"O{i}", i, p, O[2 * i], "Original pass 0 (" + orig + ")")
|
||||
open(f"{out}/force/c{i}.truth", "w").write(",".join(map(str, p + O[2 * i])))
|
||||
for i, p in enumerate(P):
|
||||
add(f"Ob{i}", i, p, O[2 * i + 1], "Original pass 1")
|
||||
for tag, f in ports:
|
||||
f, _, arm = f.partition("@")
|
||||
seqs = port_sequences(f, arm or None)
|
||||
for i, p in enumerate(P):
|
||||
if i in seqs: add(f"{tag}{i}", i, p, seqs[i], "port " + f)
|
||||
for tag, run in frees: # the free requests (labels free:<p>:<rep>) of an Original run written by q-common.sh orig_run
|
||||
names = [n for n in open(run + "/reqs.txt.names").read().split(chr(10)) if n]
|
||||
seqs = orig_sequences(run + "/out.txt")
|
||||
for n, toks in zip(names, seqs):
|
||||
if n.startswith("free:") and n.endswith(":0"):
|
||||
p = int(n.split(":")[1]); add(f"{tag}{p}", p, P[p], toks, "Original free run " + run)
|
||||
json.dump(meta, open(out + "/cases/meta.json", "w"), indent=1)
|
||||
print(sorted(meta), "->", out)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
Reference in New Issue
Block a user