git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
274 lines
11 KiB
Rust
274 lines
11 KiB
Rust
//! Moved out of the parent module by STRA-338: fn validate_in_header, fn validate_out_header, fn fp16_finite, fn
|
|
//! parse_manifest, fn case_files, impl CaseIn.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
/// The magic number and the version (1) that open both KAB1 headers.
|
|
fn check_magic_version(h: &[u8], magic: u32) -> Result<(), String> {
|
|
if le32(h, 0) != magic {
|
|
return Err(format!("wrong magic 0x{:08x}, expected 0x{magic:08x}", le32(h, 0)));
|
|
}
|
|
if le32(h, 4) != 1 {
|
|
return Err(format!("unsupported version {}, expected 1", le32(h, 4)));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Row count and the fixed model dimensions of an input header.
|
|
fn check_rows_dims(h: &[u8; IN_HEADER]) -> Result<usize, String> {
|
|
let rows = le32(h, 16) as usize;
|
|
if !(1..=MAX_ROWS).contains(&rows) {
|
|
return Err(format!("rows {rows} outside 1..={MAX_ROWS}"));
|
|
}
|
|
if le32(h, 20) as usize != H || le32(h, 24) as usize != FF {
|
|
return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24)));
|
|
}
|
|
Ok(rows)
|
|
}
|
|
|
|
/// The gate / up / down byte counts of an input header against the format-derived sizes.
|
|
fn check_byte_counts(h: &[u8; IN_HEADER], gsize: u64, dsize: u64) -> Result<(u64, u64, u64), String> {
|
|
let (g, u, d) = (le32(h, 28) as u64, le32(h, 32) as u64, le32(h, 36) as u64);
|
|
if g != gsize || u != gsize || d != dsize {
|
|
return Err(format!(
|
|
"byte counts gate/up/down {g}/{u}/{d} differ from the format-derived {gsize}/{gsize}/{dsize}"
|
|
));
|
|
}
|
|
Ok((g, u, d))
|
|
}
|
|
|
|
/// Pure: decides from 64 header bytes and the file length, allocates nothing.
|
|
pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result<InHeader, String> {
|
|
check_magic_version(h, IN_MAGIC)?;
|
|
let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32);
|
|
let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else {
|
|
return Err(format!("gate/up type {gu} is not in the KAB1 list"));
|
|
};
|
|
let Some(&(_, _, dq, db, _)) = down_row(down) else {
|
|
return Err(format!("down type {down} is not in the KAB1 list"));
|
|
};
|
|
let rows = check_rows_dims(h)?;
|
|
let gsize = (H / gq * gb * FF) as u64;
|
|
let dsize = (FF / dq * db * H) as u64;
|
|
let (g, u, d) = check_byte_counts(h, gsize, dsize)?;
|
|
if h[40..].iter().any(|b| *b != 0) {
|
|
return Err("header padding is not zero".to_owned());
|
|
}
|
|
let total = IN_HEADER as u64 + g + u + d + (rows * H * 4) as u64;
|
|
if total != file_len {
|
|
return Err(format!("file length {file_len} differs from the header-derived {total}"));
|
|
}
|
|
Ok(InHeader { gu, down, rows, gate: g as usize, up: u as usize, down_bytes: d as usize })
|
|
}
|
|
|
|
/// Pure: 20 bytes and the file length.
|
|
pub(super) fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> {
|
|
check_magic_version(h, OUT_MAGIC)?;
|
|
if le32(h, 8) as usize != rows || le32(h, 12) as usize != H {
|
|
return Err(format!("rows {} / n_embd {} differ from the case ({rows} / {H})", le32(h, 8), le32(h, 12)));
|
|
}
|
|
let tree_id = TREES.iter().position(|t| *t == tree).map_or(u32::MAX, |i| i as u32);
|
|
if le32(h, 16) != tree_id {
|
|
return Err(format!("tree id {} differs from the file name's tree {tree} ({tree_id})", le32(h, 16)));
|
|
}
|
|
let total = (OUT_HEADER + rows * H * 4) as u64;
|
|
if total != file_len {
|
|
return Err(format!("file length {file_len} differs from the header-derived {total}"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn fp16_finite(bytes: &[u8], block: usize) -> Option<usize> {
|
|
(0..bytes.len()).step_by(block).find(|&at| u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00)
|
|
}
|
|
|
|
pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec<CaseEntry>, FileTable), String> {
|
|
if m.str("format")? != "KAB1" || m.uint("version")? != 1 {
|
|
return Err("format is not KAB1 version 1".to_owned());
|
|
}
|
|
let (provenance, built) = parse_provenance(m)?;
|
|
let cases = parse_cases(m, built)?;
|
|
let files = parse_files(m)?;
|
|
check_case_hashes(&cases)?;
|
|
Ok((provenance, cases, files))
|
|
}
|
|
|
|
/// The provenance of the reference run and its build time (`built_at_utc`).
|
|
fn parse_provenance(m: &Json) -> Result<(Provenance, &str), String> {
|
|
let p = m.req("provenance")?;
|
|
let flags = p.req("flags")?;
|
|
let commit = p.str("engine_strata_pin")?;
|
|
if !is_hex(commit, 7, 40) {
|
|
return Err("provenance.engine_strata_pin is not a commit hash".to_owned());
|
|
}
|
|
let built = p.str("built_at_utc")?;
|
|
if !is_utc(built) {
|
|
return Err("provenance.built_at_utc is not a UTC timestamp".to_owned());
|
|
}
|
|
let avx512_ok = match p.get("avx512_ok") {
|
|
Some(Json::Bool(b)) => Some(*b),
|
|
_ => None,
|
|
};
|
|
Ok((provenance_of(m, (p, flags), commit, avx512_ok)?, built))
|
|
}
|
|
|
|
/// The provenance record from the manifest `m`, its `provenance` object and the `flags` object `(p, flags)`.
|
|
fn provenance_of(
|
|
m: &Json,
|
|
(p, flags): (&Json, &Json),
|
|
commit: &str,
|
|
avx512_ok: Option<bool>,
|
|
) -> Result<Provenance, String> {
|
|
Ok(Provenance {
|
|
run_id: m.str("run_id")?.to_owned(),
|
|
engine_strata_pin: commit.to_owned(),
|
|
compiler_id: p.str("compiler_id")?.to_owned(),
|
|
compiler_version: p.str("compiler_version")?.to_owned(),
|
|
target_triple: p.str("target_triple")?.to_owned(),
|
|
reference_flags: format!(
|
|
"strata_cxx_flags: {}; ggml_cpu_arch_flags: {}",
|
|
flags.str("strata_cxx_flags")?,
|
|
flags.str("ggml_cpu_arch_flags")?
|
|
),
|
|
avx512_ok,
|
|
})
|
|
}
|
|
|
|
fn parse_cases(m: &Json, built: &str) -> Result<Vec<CaseEntry>, String> {
|
|
let Json::Arr(cases_json) = m.req("cases")? else { return Err("cases is not an array".to_owned()) };
|
|
if cases_json.is_empty() || cases_json.len() > MAX_CASES {
|
|
return Err(format!("{} cases (1..={MAX_CASES} allowed)", cases_json.len()));
|
|
}
|
|
cases_json.iter().map(|c| parse_case(c, built)).collect()
|
|
}
|
|
|
|
fn parse_case(c: &Json, built: &str) -> Result<CaseEntry, String> {
|
|
let (id, rows, in_name) = case_identity(c)?;
|
|
let outs = parse_outs(c, &id)?;
|
|
let tolerance = parse_tolerance(c, &id, built)?;
|
|
let in_sha256 = c.str("in_sha256")?.to_owned();
|
|
let gu = c.uint("gu_type")? as i32;
|
|
let down = c.uint("down_type")? as i32;
|
|
Ok(CaseEntry { id, gu, down, rows, in_name, in_sha256, in_bytes: c.uint("in_bytes")?, outs, tolerance })
|
|
}
|
|
|
|
/// (id, rows, input file name) of a manifest case; the id must be plain and the file name derived from it.
|
|
fn case_identity(c: &Json) -> Result<(String, usize, String), String> {
|
|
let id = c.str("id")?.to_owned();
|
|
if !valid_id(&id) {
|
|
return Err(format!("case id {id:?} is not a plain identifier"));
|
|
}
|
|
let rows = c.uint("rows")? as usize;
|
|
let in_name = format!("case-{id}.in");
|
|
if c.str("in")? != in_name {
|
|
return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?));
|
|
}
|
|
Ok((id, rows, in_name))
|
|
}
|
|
|
|
/// The reference `.out` files of a case, one per tree.
|
|
fn parse_outs(c: &Json, id: &str) -> Result<Vec<OutRef>, String> {
|
|
let mut outs = Vec::new();
|
|
for tree in TREES {
|
|
let key = format!("out_cpp_{tree}");
|
|
let name = format!("case-{id}.cpp-{tree}.out");
|
|
if c.str(&key)? != name {
|
|
return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?));
|
|
}
|
|
outs.push(OutRef {
|
|
tree,
|
|
name,
|
|
sha256: c.str(&format!("{key}_sha256"))?.to_owned(),
|
|
bytes: c.uint(&format!("{key}_bytes"))?,
|
|
});
|
|
}
|
|
Ok(outs)
|
|
}
|
|
|
|
/// The tolerance of a case: `bitwise` needs a null, `tolerance` an object.
|
|
fn parse_tolerance(c: &Json, id: &str, built: &str) -> Result<Option<Tolerance>, String> {
|
|
match (c.str("equality")?, c.req("tolerance")?) {
|
|
("bitwise", Json::Null) => Ok(None),
|
|
("tolerance", t @ Json::Obj(_)) => tolerance_object(t, id, built).map(Some),
|
|
(other, _) => Err(format!(
|
|
"case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)"
|
|
)),
|
|
}
|
|
}
|
|
|
|
fn tolerance_object(t: &Json, id: &str, built: &str) -> Result<Tolerance, String> {
|
|
if t.str("metric")? != TOLERANCE_METRIC {
|
|
return Err(format!("case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", t.str("metric")?));
|
|
}
|
|
let value = tolerance_value(t, id)?;
|
|
let basis = t.str("basis")?.to_owned();
|
|
let written = t.str("basis_written_utc")?.to_owned();
|
|
if basis.trim().is_empty() || !is_utc(&written) {
|
|
return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc"));
|
|
}
|
|
if written.as_str() > built {
|
|
return Err(format!("case {id}: the tolerance basis was written {written}, after the reference run {built}"));
|
|
}
|
|
Ok(Tolerance { value, basis, basis_written_utc: written })
|
|
}
|
|
|
|
fn tolerance_value(t: &Json, id: &str) -> Result<f64, String> {
|
|
match t.req("value")? {
|
|
Json::Num(n) => n.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0),
|
|
_ => None,
|
|
}
|
|
.ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))
|
|
}
|
|
|
|
fn parse_files(m: &Json) -> Result<FileTable, String> {
|
|
let Json::Obj(files_json) = m.req("files")? else { return Err("files is not an object".to_owned()) };
|
|
let mut files = Vec::new();
|
|
for (name, v) in files_json {
|
|
let sha = v.str("sha256")?;
|
|
if !is_hex(sha, 64, 64) {
|
|
return Err(format!("files.{name}.sha256 is not a sha256"));
|
|
}
|
|
files.push((name.clone(), sha.to_owned(), v.uint("bytes")?));
|
|
}
|
|
Ok(files)
|
|
}
|
|
|
|
/// Case ids are unique and every sha256 of a case is 64 lowercase hex digits.
|
|
fn check_case_hashes(cases: &[CaseEntry]) -> Result<(), String> {
|
|
let mut seen = BTreeSet::new();
|
|
for c in cases {
|
|
if !seen.insert(c.id.clone()) {
|
|
return Err(format!("case id {} appears twice", c.id));
|
|
}
|
|
for sha in std::iter::once(&c.in_sha256).chain(c.outs.iter().map(|o| &o.sha256)) {
|
|
if !is_hex(sha, 64, 64) {
|
|
return Err(format!("case {}: a sha256 is not 64 lowercase hex digits", c.id));
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> {
|
|
let mut v = vec![(c.in_name.as_str(), c.in_sha256.as_str(), c.in_bytes)];
|
|
v.extend(c.outs.iter().map(|o| (o.name.as_str(), o.sha256.as_str(), o.bytes)));
|
|
v
|
|
}
|
|
impl CaseIn {
|
|
pub(super) fn gate(&self) -> &[u8] {
|
|
&self.blob[IN_HEADER..IN_HEADER + self.header.gate]
|
|
}
|
|
pub(super) fn up(&self) -> &[u8] {
|
|
let s = IN_HEADER + self.header.gate;
|
|
&self.blob[s..s + self.header.up]
|
|
}
|
|
pub(super) fn down(&self) -> &[u8] {
|
|
let s = IN_HEADER + self.header.gate + self.header.up;
|
|
&self.blob[s..s + self.header.down_bytes]
|
|
}
|
|
pub(super) fn input(&self) -> Vec<f32> {
|
|
words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect()
|
|
}
|
|
}
|