Files
leleka/crates/native-cpu-expert/examples/kernel_ab/read_case_in.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 b686f6ab75 STRA-338: rename the 854 mechanically named modules (impl_*, *_fn, *_<N>) after what they hold; mechanical_names census 854 -> 0
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>
2026-11-08 13:43:56 +01:00

257 lines
10 KiB
Rust

//! Moved out of the parent module by STRA-338: fn read_case_in, fn read_out, fn read_manifest, fn verify_dir, impl
//! Outcome, fn compare_bits ....
#[allow(unused_imports)]
use super::*;
mod record;
pub(super) use record::record_json;
/// Opens a data file and reads its length; a failure names `name`.
fn open_file(path: &Path, name: &str) -> Result<(File, u64), Refusal> {
let r = |reason: String| Refusal::new(name, reason);
let f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?;
let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
Ok((f, len))
}
fn read_header<const N: usize>(f: &mut File, name: &str) -> Result<[u8; N], Refusal> {
let mut hdr = [0u8; N];
f.read_exact(&mut hdr).map_err(|e| Refusal::new(name, format!("cannot read the header: {e}")))?;
Ok(hdr)
}
/// The whole file in one buffer: the already-read header `hdr` and the rest from `f`.
fn read_body(f: &mut File, hdr: &[u8], len: u64, name: &str) -> Result<Vec<u8>, Refusal> {
let r = |reason: String| Refusal::new(name, reason);
let mut blob = take_buffer(len as usize).map_err(r)?;
blob[..hdr.len()].copy_from_slice(hdr);
f.read_exact(&mut blob[hdr.len()..]).map_err(|e| r(format!("cannot read the body: {e}")))?;
Ok(blob)
}
/// The length of a case input against the manifest's and against the limits.
fn check_in_len(len: u64, c: &CaseEntry) -> Result<(), Refusal> {
let r = |reason: String| Refusal::new(&c.in_name, reason);
if len != c.in_bytes {
return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes)));
}
if len > MAX_FILE_BYTES || len < IN_HEADER as u64 {
return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}")));
}
Ok(())
}
/// The FP16 block headers of the three weight tensors and every activation must be finite.
fn check_case_values(case: &CaseIn, name: &str) -> Result<(), Refusal> {
let r = |reason: String| Refusal::new(name, reason);
let header = case.header;
let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3));
for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] {
if let Some(at) = fp16_finite(bytes, block) {
return Err(r(format!("non-finite FP16 block header in {role} at byte {at}")));
}
}
if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) {
return Err(r("non-finite activation".to_owned()));
}
Ok(())
}
/// The header's types and rows are the manifest case's.
fn header_matches(header: &InHeader, c: &CaseEntry) -> bool {
header.gu == c.gu && header.down == c.down && header.rows == c.rows
}
/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256,
/// FP16 headers and finite activations. Any failure names the file.
pub(super) fn read_case_in(dir: &Path, c: &CaseEntry) -> Result<CaseIn, Refusal> {
let name = c.in_name.as_str();
let r = |reason: String| Refusal::new(name, reason);
let (mut f, len) = open_file(&dir.join(name), name)?;
check_in_len(len, c)?;
let hdr = read_header::<IN_HEADER>(&mut f, name)?;
let header = validate_in_header(&hdr, len).map_err(r)?;
if !header_matches(&header, c) {
return Err(r("the header's types / rows differ from the manifest case".to_owned()));
}
let blob = read_body(&mut f, &hdr, len, name)?;
if sha_hex(&blob) != c.in_sha256 {
return Err(r("sha256 differs from the manifest".to_owned()));
}
let case = CaseIn { header, blob };
check_case_values(&case, name)?;
Ok(case)
}
/// The length of an `.out` file against the manifest's (a C++ file only) and against the limits.
fn check_out_len(len: u64, expect: Option<(&str, u64)>, name: &str) -> Result<(), Refusal> {
let r = |reason: String| Refusal::new(name, reason);
if let Some((_, bytes)) = expect
&& len != bytes
{
return Err(r(format!("length {len} differs from the manifest's {bytes}")));
}
if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 {
return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}")));
}
Ok(())
}
/// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none.
pub(super) fn read_out(
path: &Path,
name: &str,
rows: usize,
tree: &str,
expect: Option<(&str, u64)>,
) -> Result<Vec<u32>, Refusal> {
let r = |reason: String| Refusal::new(name, reason);
let (mut f, len) = open_file(path, name)?;
check_out_len(len, expect, name)?;
let hdr = read_header::<OUT_HEADER>(&mut f, name)?;
validate_out_header(&hdr, len, rows, tree).map_err(r)?;
let blob = read_body(&mut f, &hdr, len, name)?;
if let Some((sha, _)) = expect
&& sha_hex(&blob) != sha
{
return Err(r("sha256 differs from the manifest".to_owned()));
}
let bits = words_le(&blob[OUT_HEADER..]);
if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) {
return Err(r("non-finite value".to_owned()));
}
Ok(bits)
}
/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the
/// cases and the flat files table. A missing manifest is the `incomplete` refusal.
pub(super) fn read_manifest(dir: &Path) -> Result<(Vec<u8>, Provenance, Vec<CaseEntry>, FileTable), Refusal> {
let mpath = dir.join("manifest.json");
let mname = "manifest.json";
if !mpath.is_file() {
let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)");
r.incomplete = true;
return Err(r);
}
let r = |reason: String| Refusal::new(mname, reason);
let mut f = File::open(&mpath).map_err(|e| r(format!("cannot open: {e}")))?;
let mlen = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
if mlen > MAX_MANIFEST_BYTES {
return Err(r(format!("length {mlen} above the limit {MAX_MANIFEST_BYTES}")));
}
let mut mbytes = take_buffer(mlen as usize).map_err(r)?;
f.read_exact(&mut mbytes).map_err(|e| r(format!("cannot read: {e}")))?;
let manifest = parse_json(&mbytes).map_err(r)?;
let (provenance, cases, files) = parse_manifest(&manifest).map_err(r)?;
Ok((mbytes, provenance, cases, files))
}
/// The flat files table and the case entries must describe exactly the same files.
fn check_files_table(expected: &[(&str, &str, u64)], files: &FileTable) -> Result<(), Refusal> {
let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect();
table.sort_unstable();
if expected != table {
return Err(Refusal::new("manifest.json", "the flat files table and the case entries disagree".to_owned()));
}
Ok(())
}
/// Every file in the directory is named by the manifest.
fn check_listing(dir: &Path, names: &BTreeSet<&str>) -> Result<(), Refusal> {
let mname = "manifest.json";
let r = |reason: String| Refusal::new(mname, reason);
let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?;
for entry in listing {
let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?;
let n = entry.file_name().to_string_lossy().into_owned();
if n != mname && !names.contains(n.as_str()) {
return Err(Refusal::new(&n, "file is not in the manifest"));
}
}
Ok(())
}
/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole
/// directory.
pub(super) fn verify_dir(dir: &Path) -> Result<Verified, Refusal> {
let (mbytes, provenance, cases, files) = read_manifest(dir)?;
let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect();
expected.sort_unstable();
check_files_table(&expected, &files)?;
let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect();
check_listing(dir, &names)?;
let file_count = names.len() + 1;
for c in &cases {
read_case_in(dir, c)?;
for o in &c.outs {
read_out(&dir.join(&o.name), &o.name, c.rows, o.tree, Some((&o.sha256, o.bytes)))?;
}
}
Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count })
}
impl Outcome {
pub(super) fn equal(&self) -> bool {
self.mismatches == 0
}
}
/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value *
/// max|ref|` per value (the one metric the reader knows, `TOLERANCE_METRIC`).
pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Tolerance>) -> Outcome {
let scale = reference.iter().map(|b| f64::from(f32::from_bits(*b)).abs()).fold(0.0, f64::max);
let mut o = Outcome {
compared: reference.len(),
mismatches: 0,
differing_bits: 0,
max_abs_error: 0.0,
first_mismatch: None,
};
for (i, (a, b)) in ours.iter().zip(reference).enumerate() {
tally(&mut o, (i, *a, *b), tol, scale);
}
if ours.len() != reference.len() {
o.mismatches += ours.len().abs_diff(reference.len());
}
o
}
/// Counts one compared value `(index, ours, reference)` into the outcome.
fn tally(o: &mut Outcome, (i, a, b): (usize, u32, u32), tol: Option<&Tolerance>, scale: f64) {
let err = (f64::from(f32::from_bits(a)) - f64::from(f32::from_bits(b))).abs();
if a != b {
o.differing_bits += 1;
}
if err.is_finite() {
o.max_abs_error = o.max_abs_error.max(err);
}
let bad = match tol {
None => a != b,
Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater),
};
if bad {
o.mismatches += 1;
o.first_mismatch.get_or_insert((i, a, b));
}
}
// ---------------------------------------------------------------------------------------- record (hand-written JSON)
pub(super) fn jstr(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for c in s.chars() {
match c {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
'\r' => o.push_str("\\r"),
'\t' => o.push_str("\\t"),
c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
c => o.push(c),
}
}
o.push('"');
o
}