diff --git a/.crumb b/.crumb index 6af3466a..ff408632 100644 --- a/.crumb +++ b/.crumb @@ -21,39 +21,39 @@ "generated": { "children": [ { - "digest": "466c7583bcaac7482c12dae2af453909aa4eb917d288bc37d36f799e3b51612c", - "last_commit": "c31f632", + "digest": "8371189e943a695a50a5e06a13e1826dc479747bda53357bcdb98f632065156e", + "last_commit": "384171b", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "ff8f5dc4524c2dc667b2c3c6f14d4683daf9f0e0e02355eda4e6f62cece58337", - "last_commit": "c31f632", + "digest": "4415112fa64d6a11e562de8d452287e1e51ceb08362c2200d37f05016a2b741e", + "last_commit": "384171b", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { "digest": "10e9c2e0ebceb8e60113783dfa5c83ddaf7ef3fef3d700d6c489cae331117f11", - "last_commit": "c31f632", + "last_commit": "e12e6f6", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "e148d5bd0c19501efe0f07f59aae88ed1209904d1cf3e79bf9a1187877b8b11c", - "last_commit": "c31f632", + "digest": "ee6e3d66e3e3a4f85001de67fad6b5243b02c522a046f630b720feaf16d7822c", + "last_commit": "384171b", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:3d44c2b03d3fd9d35b31671a134f0e3c4e05239ccad677aaccd6bcf9738a89bb", - "compiled_at": "2026-10-14T02:20:15Z", + "children_root": "sha256:fcbf212859f600237624648892c23ea832edf50f1248e4c0f91c86cec675022b", + "compiled_at": "2026-10-14T02:42:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:9a8082b0c2fd3f3cd8e622a4d27de034908ded49b3d767b7ee347072f65ca723", + "digest": "sha256:47be77e2b25e75933a65368d45fcaaa1e9a0caf8b359ca31c286268a576ded35", "evidence_files": 156, "evidence_root": "sha256:cd53ab119be9de6ce28c4f5949b106c9622f1fe105611de3de21c3bce7932694", - "files": 3230, - "generated_at_commit": "7cd74cbbd0a45def4384618e7f82513c76021aad", - "source_tree": "sha256:91ba5ebfcbb5df23e9f032b6054c3cca0aa1e5840e43c79ea09a2327dcf7449a" + "files": 3240, + "generated_at_commit": "384171b3fd2b66f08e15ec67cf0fa5dd5935ec16", + "source_tree": "sha256:6992cec0e6bbbd9b95042afd90aa45f5e011fb5f9f7e45563e1da885c329df4a" }, "owner_lane": "", "provenance": { diff --git a/crates/.crumb b/crates/.crumb index 94d20035..1a5c3e87 100644 --- a/crates/.crumb +++ b/crates/.crumb @@ -84,7 +84,7 @@ }, { "digest": "ffb6a9a637e1eca1408280c4522ea52b283d740a90b8efad30350082900cbcdc", - "last_commit": "c31f632", + "last_commit": "e12e6f6", "name": "aienos-artifact", "purpose": "Directory crates/aienos-artifact. Purpose not yet described by a human." }, @@ -150,14 +150,14 @@ } ], "children_root": "sha256:743f1632e1cc07c03b57a67a7e3b5871a8de01492d9f1594e31c35f000f48313", - "compiled_at": "2026-10-14T02:20:15Z", + "compiled_at": "2026-10-14T02:42:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:466c7583bcaac7482c12dae2af453909aa4eb917d288bc37d36f799e3b51612c", + "digest": "sha256:8371189e943a695a50a5e06a13e1826dc479747bda53357bcdb98f632065156e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 248, - "generated_at_commit": "7cd74cbbd0a45def4384618e7f82513c76021aad", - "source_tree": "sha256:267f54c885d5c276cebae4cad7bdd26fbe31a4b421fc952fe765669b3056e2dd" + "files": 249, + "generated_at_commit": "384171b3fd2b66f08e15ec67cf0fa5dd5935ec16", + "source_tree": "sha256:526e5d230d67ee3aee04f6d9f405a4aee6a81adb1a1976503198f9de8085435f" }, "owner_lane": "", "provenance": { diff --git a/crates/aienos-infer/examples/model_probe.rs b/crates/aienos-infer/examples/model_probe.rs new file mode 100644 index 00000000..0f73a4c6 --- /dev/null +++ b/crates/aienos-infer/examples/model_probe.rs @@ -0,0 +1,141 @@ +//! PI5-8 host probe: can the engine's forward pass run an arbitrary llama-architecture GGUF, +//! and does it produce the same greedy tokens as llama.cpp? +//! +//! The prompt is given as token ids (the `ids` line printed by `tests/ref/llama_ref.c`), so the +//! engine's own tokenizer is NOT exercised: this judges only the weights loader, the quant paths +//! and the transformer forward pass. Greedy decode stops after the end-of-generation id (kept in +//! the output, like llama_ref) or after N tokens. +//! +//! usage: model_probe MODEL.gguf IDS_FILE N EOS_ID +//! IDS_FILE: text file whose first line is `ids ...` (or bare ids) +//! Env: AIENOS_DOT=sdot (dotprod int8 path when the CPU has it; default f32 scalar). +//! Output: one `key: value` line per fact, `step ` lines in llama_ref's style. + +#![allow(clippy::chunks_exact_to_as_chunks)] + +use aienos_infer::{argmax, DecodeState, DotProd, GgmlType, Gguf, Model}; +use std::collections::BTreeMap; +use std::time::Instant; + +fn main() { + let a: Vec = std::env::args().collect(); + if a.len() != 5 { + eprintln!("usage: model_probe MODEL.gguf IDS_FILE N EOS_ID"); + std::process::exit(2); + } + let bytes = std::fs::read(&a[1]).expect("read model"); + let line = std::fs::read_to_string(&a[2]).expect("read ids"); + let ids: Vec = line + .lines() + .next() + .unwrap_or("") + .split_whitespace() + .filter_map(|w| w.parse().ok()) + .collect(); + let n: usize = a[3].parse().expect("N"); + let eos: u32 = a[4].parse().expect("EOS_ID"); + let g = Gguf::parse(&bytes).expect("gguf"); + println!("arch: {}", g.architecture().unwrap_or("?")); + let mut hist: BTreeMap = BTreeMap::new(); + for t in g.tensors() { + let name = match t.ty { + GgmlType::Q4K => "Q4_K".to_string(), + GgmlType::Q6K => "Q6_K".to_string(), + GgmlType::F32 => "F32".to_string(), + GgmlType::F16 => "F16".to_string(), + GgmlType::BF16 => "BF16".to_string(), + other => format!("{other:?}"), + }; + *hist.entry(name).or_default() += 1; + } + println!("tensor_types: {hist:?}"); + let m = match Model::new(&g) { + Ok(m) => m, + Err(e) => { + println!("MODEL_REFUSED: {e:?}"); + std::process::exit(3); + } + }; + let p = &m.params; + println!( + "params: layers={} embd={} heads={} kv_heads={} ff={} vocab={} rope_base={} ctx={} tied_output={}", + p.block_count, p.embedding_length, p.head_count, p.head_count_kv, p.feed_forward_length, + p.vocab_size, p.rope_freq_base, p.context_length, g.tensor("output.weight").is_none() + ); + println!( + "gguf_eos_id: {:?} bos_id: {:?}", + g.u32_key("tokenizer.ggml.eos_token_id").ok(), + g.u32_key("tokenizer.ggml.bos_token_id").ok() + ); + println!("prompt_ids: {}", ids.len()); + let mut st = DecodeState::new(&m, ids.len() + n + 8); + st.dotprod = None; + if std::env::var("AIENOS_DOT") + .map(|v| v == "sdot") + .unwrap_or(false) + { + #[cfg(target_arch = "aarch64")] + { + st.dotprod = DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod")); + } + } + let _: Option = st.dotprod; + println!("dot: {}", if st.dotprod.is_some() { "sdot" } else { "f32" }); + let t0 = Instant::now(); + st.prefill(&m, &ids).expect("prefill"); + println!("prefill_us: {}", t0.elapsed().as_micros()); + // Optional: compare the first-position logits with llama.cpp's (f32 LE file written by llama_ref). + if let Ok(path) = std::env::var("AIENOS_LOGITS") { + let b = std::fs::read(&path).expect("read logits"); + let r: Vec = b + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + let e = &st.logits; + if r.len() == e.len() { + let (mut mx, mut se, mut dot, mut na, mut nb) = (0f64, 0f64, 0f64, 0f64, 0f64); + for (x, y) in r.iter().zip(e.iter()) { + let d = (*x as f64 - *y as f64).abs(); + mx = mx.max(d); + se += d * d; + dot += *x as f64 * *y as f64; + na += (*x as f64).powi(2); + nb += (*y as f64).powi(2); + } + let top = |v: &[f32]| { + v.iter() + .enumerate() + .fold( + (0usize, f32::MIN), + |a, (i, x)| if *x > a.1 { (i, *x) } else { a }, + ) + .0 + }; + println!("logits_vs_llama: n={} max_abs_diff={mx:.4} rms_diff={:.4} cosine={:.6} argmax_llama={} argmax_engine={}", r.len(), (se / r.len() as f64).sqrt(), dot / (na.sqrt() * nb.sqrt()), top(&r), top(e)); + } else { + println!( + "logits_vs_llama: SIZE MISMATCH llama={} engine={}", + r.len(), + e.len() + ); + } + } + let mut tok_us = Vec::new(); + for i in 0..n { + let t = argmax(&st.logits); + println!("step {i} {t}"); + if t == eos { + println!("eog"); + break; + } + if i + 1 == n { + break; + } + let t1 = Instant::now(); + st.forward(&m, t, true).expect("forward"); + tok_us.push(t1.elapsed().as_micros() as f64); + } + let mean = tok_us.iter().sum::() / tok_us.len().max(1) as f64; + println!("mean_tok_us: {mean:.1}"); + println!("tok_per_s: {:.3}", 1e6 / mean); +} diff --git a/docs/.crumb b/docs/.crumb index f595887a..832793a6 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:491e93c09b6185b662afda8b29d24bb3ee81bc2aed9009757fdf4674d197be31", - "compiled_at": "2026-10-14T02:20:15Z", + "compiled_at": "2026-10-14T02:42:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:ff8f5dc4524c2dc667b2c3c6f14d4683daf9f0e0e02355eda4e6f62cece58337", + "digest": "sha256:4415112fa64d6a11e562de8d452287e1e51ceb08362c2200d37f05016a2b741e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 84, - "generated_at_commit": "7cd74cbbd0a45def4384618e7f82513c76021aad", - "source_tree": "sha256:cc02a480ee7c60cb98ba0e9607abaad277a62d512867aebd1cc7bd93893a64c8" + "files": 87, + "generated_at_commit": "384171b3fd2b66f08e15ec67cf0fa5dd5935ec16", + "source_tree": "sha256:6afdbd5bf5f90e4a8d8496fdc81202d9b3e6471f24326042e5a03366ee0d3d85" }, "owner_lane": "", "provenance": { diff --git a/docs/native/PI5-8-MODEL-CHOICE.md b/docs/native/PI5-8-MODEL-CHOICE.md new file mode 100644 index 00000000..7d30fcce --- /dev/null +++ b/docs/native/PI5-8-MODEL-CHOICE.md @@ -0,0 +1,143 @@ +# PI5-8: choosing the open release model for the Pi 5 (decision PD4, settled by measurement) + +Scope: which Apache-2.0 or MIT model the AIENOS Pi 5 image should ship, measured on the same engine (`crates/aienos-infer`, +image `make pi5-infer`) and the same card that produced the PI5-6 numbers (docs/native/PI5-6-INFER-RUNS.md). +The Llama model used by PI5-6 stays an internal yardstick (Llama licence). It is not a candidate and is not named as the release model. + +## Result in one paragraph + +Of the three open candidates, **TinyLlama-1.1B-Chat-v1.0 (Apache-2.0)** and **h2o-danube3-500m-chat (Apache-2.0)** run on the +Pi with the engine's forward pass unchanged, match llama.cpp token for token on the short prompt, and fit the 784 MiB model partition. +**SmolLM2-1.7B-Instruct (Apache-2.0)** runs on the host but its Q4_K_M file (1,055,609,536 bytes) does not fit the partition (822,083,584 bytes), so it was not run on the Pi. +Recommendation: **TinyLlama-1.1B-Chat-v1.0 Q4_K_M** as the Pi release model (1.46 tok/s on the Pi), with +h2o-danube3-500m-chat as the fast fallback (3.23 tok/s, official GGUF from the publisher). **Neither runs end to end yet**: the engine's tokenizer, chat +template and stop token are Llama-3 only, so a small tokenizer change is needed before any open model can answer a typed prompt (section "What this does not prove"). + +## Ground truth read first + +| Fact | Where | +|---|---| +| Engine accepts only `general.architecture = llama` | `crates/aienos-infer/src/gguf.rs` `llama_params` | +| Weight types accepted: Q4_K, Q6_K, F32, F16, BF16; a weight row must be a multiple of 256 columns (K-quant block) | `crates/aienos-infer/src/model.rs` `Weight::bind` | +| Tokenizer: GPT-2 byte-level BPE with the Llama-3 pre-tokenizer only; chat template is Llama-3 only; stop token is the constant 128009 | `crates/aienos-infer/src/tokenizer.rs`, `crates/aienos-infer-kernel/src/lib.rs` (`EOT`) | +| Pi image fixes the golden prompt, the Llama-3 ids and the 64-position cache | `native/kernel/core/infer.c` (`expect_ids`, `expect_gen`, `SESS_KV`) | +| PI5-6 golden tokens came from llama.cpp 4a89937 via `crates/aienos-infer/tests/ref/llama_ref.c` (CPU, one thread, prints ids and greedy steps, writes first logits) | `crates/aienos-infer/tests/fixtures/PROVENANCE.md`, `docs/qualification/INT8-ACTIVATION-QUAL-v1.md` | +| llama.cpp on this Spark: `~/llama.cpp-build` (commit 4a89937, the same build), linked by `llama_ref.c` | measured here | +| Model partition `AIENOS-MODEL` (p3): 1,605,632 sectors = 822,083,584 bytes (784 MiB), raw, found through MODEL.MAP | PI5-6 doc; `lsblk` on the Pi | +| Why SmolLM2 "failed qualification" earlier | aien-architecture `CURRENT_EXECUTION_PLAN.md` lines 838 to 840 and 903: campaign v1 on the Linux host path (GB10), T2 wrong path, T3 cut at the 64-token limit, a daemon crash at warm-up (sovereign-core #236, not reproduced). That was a task-quality and daemon test of a different pipeline, not an engine load failure. Here SmolLM2 loads and matches llama.cpp on the host | + +Consequence: with the engine as it is, **no open model runs end to end**. Every open model needs its own tokenizer behaviour (TinyLlama and danube3 use +a SentencePiece vocabulary, SmolLM2 a different BPE pre-tokenizer) and its own chat template and stop token. The arithmetic part (loader, Q4_K and Q6_K +dot products, attention, RoPE, tied or separate output weights) is already generic across `llama`-architecture files. So the measurements below feed token ids +produced by llama.cpp's own tokenizer into the engine and judge only that part. + +## Shortlist + +All three are `llama` architecture and use only Q4_K, Q6_K and F32 tensors, so they need **no engine architecture work**. +Each needs the tokenizer and template work described above (shared between TinyLlama and danube3, which both use a 32000-entry SentencePiece vocabulary). + +| Model (file) | Licence (from the card I read) | Publisher of the file | Size bytes | Fits p3 (822,083,584) | Shape | +|---|---|---|---|---|---| +| TinyLlama-1.1B-Chat-v1.0, `tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf` | Apache-2.0 | TheBloke (well-known quantizer); base model by the TinyLlama project | 668,788,096 | yes (81 %) | 22 layers, embd 2048, 32 heads, 4 kv heads, ff 5632, vocab 32000, separate output weight | +| h2o-danube3-500m-chat, `h2o-danube3-500m-chat-Q4_K_M.gguf` | Apache-2.0 | h2oai (the model's own publisher) | 317,877,408 | yes (39 %) | 16 layers, embd 1536, 16 heads, 8 kv heads, ff 4096, vocab 32000, rope base 100000 | +| SmolLM2-1.7B-Instruct, `smollm2-1.7b-instruct-q4_k_m.gguf` | Apache-2.0 | HuggingFaceTB (the model's own publisher) | 1,055,609,536 | **no** (128 %) | 24 layers, embd 2048, 32 heads, 32 kv heads, ff 8192, vocab 49152, tied output weight | + +The one candidate that would need a **small, well-scoped engine change** is SmolLM2 (a different BPE pre-tokenizer, a ChatML template, stop token `<|im_end|>`, +and a model partition of at least 1.1 GiB). It was not built here. Models skipped on purpose (not run, reasons from memory and not checked here): SmolLM2-360M, SmolLM2-135M and Qwen2.5-0.5B, whose embedding widths (960, 576, 896 as I recall them) +are not multiples of 256, which the engine's K-quant blocks require; Qwen3-0.6B, whose publisher lists only `Qwen3-0.6B-Q8_0.gguf` (a type the engine rejects) and whose architecture, as I recall, adds per-head norms (a real engine change). The Qwen3-0.6B card also says `license: apache-2.0` and the repository has a LICENSE file (listing seen, file not read). + +### Licence evidence (the YAML header of each model card, read on 2026-10-13; none of these repositories ships a separate LICENSE file) +- TinyLlama base card: https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0 : `license: apache-2.0` +- TinyLlama GGUF card: https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF : `license: apache-2.0` (a third-party conversion of the Apache-2.0 model; the TinyLlama project publishes no GGUF of its own) +- danube3 base card: https://huggingface.co/h2oai/h2o-danube3-500m-chat : `license: apache-2.0` +- danube3 GGUF card: https://huggingface.co/h2oai/h2o-danube3-500m-chat-GGUF : `license: apache-2.0` +- SmolLM2 base card: https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct : `license: apache-2.0` +- SmolLM2 GGUF card: https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF : `license: apache-2.0` + +### Downloads (kept outside git, in `~/models/pi5-8-candidates/`; sha256 equals the LFS object id the publisher's file listing reports) +| File | URL | sha256 | +|---|---|---| +| tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf | https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf | `9fecc3b3cd76bba89d504f29b616eedf7da85b96540e490ca5824d3f7d2776a0` | +| h2o-danube3-500m-chat-Q4_K_M.gguf | https://huggingface.co/h2oai/h2o-danube3-500m-chat-GGUF/resolve/main/h2o-danube3-500m-chat-Q4_K_M.gguf | `021f78849c5670ecb2aa4cd7c5972eee0a3c9e41e33e5902c408a2ab989f0b43` | +| smollm2-1.7b-instruct-q4_k_m.gguf | https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF/resolve/main/smollm2-1.7b-instruct-q4_k_m.gguf | `decd2598bc2c8ed08c19adc3c8fdd461ee19ed5708679d1c54ef54a5a30d4f33` | + +Evidence excerpts: `docs/native/pi5-8/pi-kernel-log-lines.txt` (the kernel log lines of the three Pi boots). The measurement patch: `docs/native/pi5-8/measure-ids.patch` (applies cleanly to main with `git apply`). + +## Method + +- Prompts: the PI5-6 prompt ("What is the capital of France?") plus two longer ones (`scripts/pi5-8/prompt-long1.txt`, 35 to 45 ids, and `prompt-long2.txt`, 108 to 119 ids), wrapped in each model's chat template as I wrote it (TinyLlama: Zephyr style; danube3: `<|prompt|>...<|answer|>`; SmolLM2: ChatML without a system turn). + The TinyLlama GGUF carries no embedded template, so its Zephyr style template comes from the model card. 16 greedy tokens, stop at the stop token. +- Reference: `llama_ref` from `crates/aienos-infer/tests/ref/llama_ref.c`, linked to llama.cpp 4a89937, CPU only (`CUDA_VISIBLE_DEVICES` hidden), one thread. Its token ids are the prompt given to the engine. +- Host check: `scripts/pi5-8/host_golden.sh MODEL TEMPLATE EOS [N] [sdot]` runs the engine's own forward pass (`crates/aienos-infer/examples/model_probe.rs`) on the Spark in both arithmetic paths (f32, and the SDOT int8 path the Pi uses), and compares tokens and the first-position logits. +- Pi check: `docs/native/pi5-8/measure-ids.patch` (applied to a scratch copy, not to main) lets the Pi image take prompt ids and a stop token instead of text, raises the cache to 192 positions and runs five requests in one boot (short prompt three times for variance, then the two long prompts). `scripts/pi5-8/gen_measure_header.sh` turns the llama.cpp output into the header the image compiles in; `scripts/pi5-8/pi_run.sh` writes the model to p3, reads it back, runs `~/workspace/pi5/pi5-run.sh` with `KLOG=1` and a MODEL.MAP, then removes MODEL.MAP from the ESP. MODEL.MAP: one extent at LBA 9439232, same disk GUID as PI5-6. +- Scoring rule for the host table: exact token match is PASS. A mismatch counts as NOISE when, at the first differing step, llama.cpp's own top-1 minus top-2 logit gap is below 1.0 (the largest single-logit difference between the engine and llama.cpp on the Llama control was 0.90); a larger gap would be FAIL. The 1.0 threshold is my choice, not a published standard. + +## Host golden results (engine vs llama.cpp 4a89937, 16 tokens; Spark, 2026-10-13) + +Control: the PI5-6 Llama file on the same scripts gives PASS, PASS, PASS in SDOT (and PASS, NOISE, PASS in f32, first divergence at gap 0.039), with first-position logit rms difference 0.09 to 0.17. +That is the baseline noise level of this engine against llama.cpp. + +| Model | Path | short (id count) | long1 | long2 | logit rms diff vs llama.cpp (3 prompts) | +|---|---|---|---|---|---| +| TinyLlama | f32 | PASS (24) | NOISE (step 2, gap 0.0006) | NOISE (step 13, gap 0.118) | 0.099, 0.099, 0.149 | +| TinyLlama | SDOT | PASS | NOISE (step 10, gap 0.035) | NOISE (step 13, gap 0.118) | 0.104, 0.115, 0.134 | +| danube3-500m | f32 | PASS (20) | NOISE (step 0, gap 0.065) | NOISE (step 0, gap 0.110) | 0.180, 0.181, 0.326 | +| danube3-500m | SDOT | PASS | NOISE (step 0, gap 0.065) | PASS | 0.158, 0.222, 0.188 | +| SmolLM2-1.7B | f32 | PASS (16) | PASS | NOISE (step 8, gap 0.94) | 0.650, 0.506, 0.469 | +| SmolLM2-1.7B | SDOT | PASS | PASS | NOISE (step 1, gap 0.044) | 0.263, 0.262, 0.339 | + +Reading: TinyLlama is as close to llama.cpp as the Llama control is. danube3 is slightly further (rms 0.16 to 0.33). SmolLM2 in the f32 path is 3 to 6 times further than the control +(rms up to 0.65, one divergence at a gap of 0.94, just under my 1.0 line); the SDOT path is closer. I did not find the cause (UNKNOWN); it does not affect the Pi, which runs SDOT, but it is why SmolLM2 would need a closer look before it is trusted. +No FAIL under the scoring rule. Raw files: `/tmp/pi58-golden/[-sdot]/` on the Spark (not kept in git). + +## Pi results (real Raspberry Pi 5, SDOT path, `make pi5-infer` image plus the measurement patch) + +Each row is one boot. The three short requests are the variance sample (same prompt, same boot); long prompts are single requests. `mean_tok_us` is the kernel's per-token time exactly as PI5-6 defined it (decode steps after the first token). + +| | TinyLlama-1.1B-Chat Q4_K_M | danube3-500m-chat Q4_K_M | (internal yardstick, PI5-6 definition, re-run today) | +|---|---|---|---| +| Model bytes / sha256 matches the declared one | 668,788,096 / yes | 317,877,408 / yes | 807,694,368 / yes | +| p3 read back through Linux before the boot, sha256 equals the file | yes | yes | yes | +| Load (firmware reads p3) | 6.96 s | 3.31 s | 8.40 s | +| sha256 inside the kernel | 4.20 s | 2.07 s | 5.08 s | +| Short prompt, 3 requests, us per token | 683,917 / 684,024 / 683,980 | 309,842 / 309,893 / 309,866 | 832,559 (one request) | +| Short prompt tok/s, mean of 3 (spread) | **1.462** (1.4620 to 1.4622, 0.01 %) | **3.227** (3.2268 to 3.2274, 0.02 %) | 1.201 | +| Short prompt prefill | 15.30 s for 24 ids (0.64 s per id) | 5.51 s for 20 ids (0.28 s per id) | 11.14 s for 17 ids | +| long1 (ids), tok/s, prefill | 45 ids, 1.456, 28.69 s | 41 ids, 3.210, 11.29 s | | +| long2 (ids), tok/s, prefill | 119 ids, 1.438, 76.32 s | 113 ids, 3.159, 31.32 s | | +| Tokens equal to llama.cpp, short x3 | 3 of 3 match | 3 of 3 match | 3 of 3 (kernel's own check) | +| Tokens equal to llama.cpp, long1 / long2 | MISMATCH at step 10 (host SDOT NOISE, same tokens) / match | MISMATCH at step 0 (host SDOT NOISE, same tokens) / match | | +| Heap used by the session | 11.7 MiB | 19.8 MiB | 22.4 MiB | +| Evidence | `~/workspace/pi5-runs/pi5-8-tinyllama-a/kernel.log` | `~/workspace/pi5-runs/pi5-8-danube3-a/kernel.log` | `~/workspace/pi5-runs/pi5-8-restore/kernel.log` | + +On both models the Pi produced exactly the same token lists as the host SDOT run for all five requests, including the two near-tie mismatches (compare `golden=MISMATCH` lines with the host table): the Pi's arithmetic is the same as the host's SDOT arithmetic. +Variance between the three in-boot requests is under 0.03 %; I did not repeat whole boots (UNVERIFIED across boots: the PI5-6 load time of 8.4 s reproduced to 8.40 s on a second boot, a hint that load time is stable). + +Cost of a long prompt: prefill is the same per-token speed as decoding in this engine (no batching), so a 119-token prompt waits 76 s on TinyLlama and 31 s on danube3 before the first word. + +Log excerpt (TinyLlama, one request line): +``` +infer: measure req=0 name=short ids=24 prefill=24 prefill_us=15296424 produced=8 mean_tok_us=683917 tokens=1576 7483 310 3444 338 3681 29889 2 golden=match request_us=20084557 rc=3 +``` + +## Recommendation + +**TinyLlama-1.1B-Chat-v1.0 (Q4_K_M, Apache-2.0).** Engineering reasons: +1. It is faster on the Pi than the internal yardstick (1.46 against 1.20 tok/s) because it has fewer weights per token, loads in 7.0 s, and uses 81 % of the model partition, so nothing about the card layout changes. +2. Its forward pass on the Pi is as faithful to llama.cpp as the yardstick's (first-position logit rms difference 0.10 to 0.15 against 0.09 to 0.17), and the only mismatches are near-ties that the host reproduces exactly. +3. It needs no architecture work, only the tokenizer, template and stop-token work that every open model needs. +4. Its weakness is quality and age (1.1B, trained in 2023, Zephyr style chat tuning): expect plain, short answers. If quality matters more than speed, SmolLM2 is the next candidate, but it needs a larger partition (at least 1.1 GiB) and a tokenizer change. + +Fallback: **h2o-danube3-500m-chat**, 2.2 times faster again (3.23 tok/s), 318 MB, and its GGUF comes from the publisher itself (TinyLlama's comes from a third-party quantizer). Its first token differed from llama.cpp on one long prompt at a logit gap of 0.065, which is why I rank it second on fidelity, and the card gives no benchmark numbers I could use here. + +## What this does not prove (limits) +- The engine's own tokenizer was not run on any open model. Token ids came from llama.cpp. The release needs a SentencePiece tokenizer (shared by TinyLlama and danube3), a per-model chat template, and a per-model stop token in `aienos-infer` and `aienos-infer-kernel`. Not built in this task. +- Quality was not evaluated: only that the engine computes what llama.cpp computes. I did not read generated text for usefulness. +- Pi numbers are one boot per model; variance is in-boot only. The measurement patch changed the session limits (cache 192 positions, five requests) so absolute tok/s can differ slightly from a production image. +- SmolLM2 on the Pi: not run (does not fit p3). SmolLM2's f32 host path being further from llama.cpp than the control is unexplained (UNKNOWN). +- The cards state Apache-2.0; no separate LICENSE file exists in those repositories. Whether the training data (SlimPajama, StarCoderData, UltraChat, UltraFeedback for TinyLlama) carries obligations was not assessed. +- The SDOT int8 path was not compared bitwise with llama.cpp; only tokens and logits as above. + +## State left behind +p3 holds the PI5-6 yardstick again: written back at 02:18Z and read back through Linux, sha256 `3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1` equals the file. Because the restore command also launched one run with the unchanged PI5-6 image (my script had no write-only switch at that moment; the switch is in the committed script), the yardstick was re-measured the same day: 8 tokens identical to the golden list, 832,559 us per token (1.201 tok/s), `AIENOS_CK_INFER_SESSION: PASS`. +MODEL.MAP was removed from the ESP after every run (`model_map_removed` in each run output). The three downloaded GGUF files stay in `~/models/pi5-8-candidates/`, outside the repository. diff --git a/docs/native/pi5-8/measure-ids.patch b/docs/native/pi5-8/measure-ids.patch new file mode 100644 index 00000000..17899d26 --- /dev/null +++ b/docs/native/pi5-8/measure-ids.patch @@ -0,0 +1,172 @@ +diff --git a/crates/aienos-infer-kernel/src/session.rs b/crates/aienos-infer-kernel/src/session.rs +index b1dad4f..c4870bc 100644 +--- a/crates/aienos-infer-kernel/src/session.rs ++++ b/crates/aienos-infer-kernel/src/session.rs +@@ -20,6 +20,7 @@ + use alloc::vec::Vec; + use core::cell::UnsafeCell; + use core::slice; ++use core::sync::atomic::{AtomicU32, Ordering}; + + use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer}; + +@@ -93,6 +94,9 @@ struct Slot(UnsafeCell>); + unsafe impl Sync for Slot {} + static SLOT: Slot = Slot(UnsafeCell::new(None)); + ++/// PI5-8 measurement build only: end-of-generation id of the model under test (default: the Llama-3 EOT). ++static EOS: AtomicU32 = AtomicU32::new(EOT); ++ + fn slot() -> &'static mut Option { + // SAFETY: single-threaded by contract; no reference escapes a call. + unsafe { &mut *SLOT.0.get() } +@@ -253,7 +257,7 @@ pub unsafe extern "C" fn aienos_infer_session_step(token: *mut u32, us: *mut u64 + if !token.is_null() { + *token = t; + } +- if t == EOT || s.out.len() >= s.limits.max_new as usize { ++ if t == EOS.load(Ordering::Relaxed) || s.out.len() >= s.limits.max_new as usize { + s.done = true; + rc = STEP_LAST; + } else { +@@ -382,3 +386,38 @@ pub unsafe extern "C" fn aienos_infer_session_close() -> i32 { + *slot() = None; + 0 + } ++ ++/// PI5-8 measurement build only: set the end-of-generation token id. ++#[no_mangle] ++pub extern "C" fn aienos_infer_session_set_eos(id: u32) { ++ EOS.store(id, Ordering::Relaxed); ++} ++ ++/// PI5-8 measurement build only: start a request from token ids (the engine's tokenizer is bypassed; ++/// the ids come from llama.cpp). Same checks and effects as `aienos_infer_session_prompt`. ++/// ++/// # Safety ++/// `ids` must point to `n` readable u32s. Same execution contract as open. ++#[no_mangle] ++pub unsafe extern "C" fn aienos_infer_session_prompt_set_ids(ids: *const u32, n: u32) -> i32 { ++ let s = match slot() { ++ Some(s) => s, ++ None => return E_STATE, ++ }; ++ if ids.is_null() || n == 0 { ++ return E_ARG; ++ } ++ if heap_remaining() < s.limits.heap_reserve as usize { ++ return E_HEAP; ++ } ++ let v: Vec = slice::from_raw_parts(ids, n as usize).to_vec(); ++ if v.len() + s.limits.max_new as usize > s.limits.kv_capacity as usize { ++ return E_TOO_LONG; ++ } ++ s.st.reset(); ++ s.prompt = v; ++ s.fed = 0; ++ s.out = Vec::new(); ++ s.done = false; ++ s.prompt.len() as i32 ++} +diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c +index 4f25b37..db15f94 100644 +--- a/native/kernel/core/infer.c ++++ b/native/kernel/core/infer.c +@@ -91,6 +91,8 @@ extern int32_t aienos_infer_session_prompt_ids(uint32_t *out, uint32_t cap); + extern int32_t aienos_infer_session_text(const uint32_t *ids, uint32_t n, uint8_t *out, uint32_t cap); + extern int32_t aienos_infer_session_close(void); + extern void aienos_infer_heap_stats(uint64_t *used, uint64_t *peak); ++extern int32_t aienos_infer_session_prompt_set_ids(const uint32_t *ids, uint32_t n); ++extern void aienos_infer_session_set_eos(uint32_t id); + #define SESS_E_STATE (-12) + #define SESS_E_PROMPT_BYTES (-16) + #define SESS_STEP_DONE 0 +@@ -118,6 +120,10 @@ static const uint32_t expect_ids[4] = {128000, 128006, 882, 128007}; + /* The greedy reply llama.cpp produced for the same prompt ("step" lines of the + * same fixture): "The capital of France is Paris." then <|eot_id|>. */ + static const uint32_t expect_gen[8] = {791, 6864, 315, 9822, 374, 12366, 13, 128009}; ++#ifdef CK_PI5_MEASURE ++/* PI5-8 measurement build: prompt ids and llama.cpp expected tokens of the model under test (generated header). */ ++#include "pi5_measure.h" ++#endif + /* Decoded reply, escaped for one console line: printable ASCII other than + * backslash as is, everything else as \\xNN. 4 bytes per input byte + NUL. */ + static char esc[4 * INFER_TEXT_BYTES + 1]; +@@ -268,7 +274,11 @@ static void hex(char *out, const uint8_t *b, unsigned n) + /* Session limits of the probe: a 64-position cache, 16 generated tokens, a + * 256-byte prompt and 64 KiB of heap kept free (every prompt costs a few + * KiB that the bump allocator never gives back). */ ++#ifdef CK_PI5_MEASURE ++#define SESS_KV 192u ++#else + #define SESS_KV 64u ++#endif + #define SESS_MAX_NEW 16u + #define SESS_PROMPT_BYTES 256u + #define SESS_RESERVE (64u << 10) +@@ -342,6 +352,44 @@ static int session_request(unsigned which, const char *text, unsigned cancel_aft + return ok; + } + ++#ifdef CK_PI5_MEASURE ++/* PI5-8 measurement request q: prompt ids from the generated header, steps with a pet each, tokens compared with ++ * llama.cpp's greedy reply. One line per request: prefill and decode microseconds, tokens, match. */ ++static int measure_request(unsigned q) ++{ ++ const struct meas_req *r = &meas_reqs[q]; ++ uint64_t t0 = ck_time_us(), pre_us = 0, tok_us_sum = 0; ++ unsigned prefill = 0, produced = 0, last = 0; ++ int32_t ids = aienos_infer_session_prompt_set_ids(r->ids, r->nids); ++ if (ids < 0) { ++ ck_printf("infer: measure req=%u name=%s REFUSED rc=%d\n", q, r->name, ids); ++ return 0; ++ } ++ int32_t rc = 0; ++ for (;;) { ++ uint32_t t = 0; ++ uint64_t us = 0; ++ rc = aienos_infer_session_step(&t, &us); ++ pet(); ++ if (rc < 0 || rc == SESS_STEP_DONE) break; ++ if (rc == SESS_STEP_PREFILL) { prefill++; pre_us += us; continue; } ++ produced++; ++ tok_us_sum += us; ++ if (rc == SESS_STEP_LAST) { last = 1; break; } ++ } ++ static uint32_t toks[SESS_MAX_NEW]; ++ int32_t n = aienos_infer_session_tokens(toks, SESS_MAX_NEW); ++ int ok = rc >= 0 && n == (int32_t)produced && last && (unsigned)ids == prefill && produced == r->nexp; ++ for (unsigned i = 0; ok && i < r->nexp; i++) ok = ok && toks[i] == r->exp[i]; ++ uint64_t mean = produced > 1 ? tok_us_sum / (produced - 1) : 0; ++ ck_printf("infer: measure req=%u name=%s ids=%d prefill=%u prefill_us=%llu produced=%u mean_tok_us=%llu tokens=", q, r->name, ids, ++ prefill, (unsigned long long)pre_us, produced, (unsigned long long)mean); ++ for (unsigned i = 0; i < produced; i++) ck_printf("%s%u", i ? " " : "", toks[i]); ++ ck_printf(" golden=%s request_us=%llu rc=%d\n", ok ? "match" : "MISMATCH", (unsigned long long)(ck_time_us() - t0), rc); ++ return ok; ++} ++#endif ++ + /* The bounded session over the ingested model: open with explicit limits, + * a request cancelled during its prefill, the golden prompt run to its end + * through the step API (must equal the one-shot probe's reply), a second +@@ -369,6 +417,12 @@ static void session_run(uint64_t mpa, uint64_t msize) + if (ok) { + /* Cheap refusals: a second open, an over-long prompt, a step with no + * request pending. None of them touches the model. */ ++#ifdef CK_PI5_MEASURE ++ aienos_infer_session_set_eos(MEAS_EOS); ++ for (unsigned q = 0; q < MEAS_NREQ; q++) ok = measure_request(q) && ok; ++ if (0) ++#endif ++ { + static char longp[SESS_PROMPT_BYTES + 2]; + memset(longp, 'a', sizeof longp - 1); + longp[sizeof longp - 1] = 0; +@@ -382,6 +436,7 @@ static void session_run(uint64_t mpa, uint64_t msize) + ok = session_request(2, "What is the capital of France?", 0, expect_gen, + sizeof expect_gen / sizeof expect_gen[0], expect_ids) && ok; + ok = session_request(3, "Say hello.", 1, 0, 0, 0) && ok; ++ } + } + uint64_t used = 0, peak = 0; + aienos_infer_heap_stats(&used, &peak); diff --git a/docs/native/pi5-8/pi-kernel-log-lines.txt b/docs/native/pi5-8/pi-kernel-log-lines.txt new file mode 100644 index 00000000..caa973a9 --- /dev/null +++ b/docs/native/pi5-8/pi-kernel-log-lines.txt @@ -0,0 +1,44 @@ +## pi5-8-tinyllama-a (kernel.log lines) +model_map: ok len=668788096 extents=1 sector=512 disk=29ceb42de1b36445b340924422ebcae3 +model: reading 668788096 bytes in 1 extents, block_size=512 last_block=250347519 -> 0x1404a000 +model: base=0x1404a000 len=668788096 extents=1 read_us=6958249 declared_sha256=9fecc3b3cd76bba89d504f29b616eedf7da85b96540e490ca5824d3f7d2776a0 +cpu_features: dotprod=1 i8mm=0 bf16=0 fhm=0 fp16=1 sve=0 rndr=0 +infer: sha256=9fecc3b3cd76bba89d504f29b616eedf7da85b96540e490ca5824d3f7d2776a0 sha_us=4202964 +infer: dot_path=sdot cpu_dotprod=1 +infer: session open rc=0 tensors=201 vocab=32000 layers=22 kv_capacity=192 max_new=16 max_prompt_bytes=256 heap_reserve_kib=64 heap_used_kib=12014 open_us=47488 +infer: measure req=0 name=short ids=24 prefill=24 prefill_us=15296424 produced=8 mean_tok_us=683917 tokens=1576 7483 310 3444 338 3681 29889 2 golden=match request_us=20084557 rc=3 +infer: measure req=1 name=short ids=24 prefill=24 prefill_us=15296235 produced=8 mean_tok_us=684024 tokens=1576 7483 310 3444 338 3681 29889 2 golden=match request_us=20085135 rc=3 +infer: measure req=2 name=short ids=24 prefill=24 prefill_us=15296252 produced=8 mean_tok_us=683980 tokens=1576 7483 310 3444 338 3681 29889 2 golden=match request_us=20128237 rc=3 +infer: measure req=3 name=long1 ids=45 prefill=45 prefill_us=28693996 produced=16 mean_tok_us=686969 tokens=1576 14744 5692 7254 2645 278 2462 1363 278 6575 4366 9432 29879 1283 278 11563 golden=MISMATCH request_us=38999497 rc=3 +infer: measure req=4 name=long2 ids=119 prefill=119 prefill_us=76316053 produced=16 mean_tok_us=695546 tokens=29928 799 21886 29892 13 13 4806 27746 675 363 278 9055 297 13138 366 411 golden=match request_us=86750226 rc=3 +infer: session close rc=0 heap_used_kib=12015 heap_peak_kib=12015 frames_free_before=1636052 frames_free_after=1636052 rc=0 +AIENOS_CK_INFER_SESSION: FAIL + +## pi5-8-danube3-a (kernel.log lines) +model_map: ok len=317877408 extents=1 sector=512 disk=29ceb42de1b36445b340924422ebcae3 +model: reading 317877408 bytes in 1 extents, block_size=512 last_block=250347519 -> 0x28ef2000 +model: base=0x28ef2000 len=317877408 extents=1 read_us=3305807 declared_sha256=021f78849c5670ecb2aa4cd7c5972eee0a3c9e41e33e5902c408a2ab989f0b43 +cpu_features: dotprod=1 i8mm=0 bf16=0 fhm=0 fp16=1 sve=0 rndr=0 +infer: sha256=021f78849c5670ecb2aa4cd7c5972eee0a3c9e41e33e5902c408a2ab989f0b43 sha_us=2073031 +infer: dot_path=sdot cpu_dotprod=1 +infer: session open rc=0 tensors=147 vocab=32000 layers=16 kv_capacity=192 max_new=16 max_prompt_bytes=256 heap_reserve_kib=64 heap_used_kib=20263 open_us=21803 +infer: measure req=0 name=short ids=20 prefill=20 prefill_us=5510966 produced=8 mean_tok_us=309842 tokens=1014 5565 302 4843 349 5465 28723 2 golden=match request_us=7680584 rc=3 +infer: measure req=1 name=short ids=20 prefill=20 prefill_us=5510354 produced=8 mean_tok_us=309893 tokens=1014 5565 302 4843 349 5465 28723 2 golden=match request_us=7680329 rc=3 +infer: measure req=2 name=short ids=20 prefill=20 prefill_us=5511523 produced=8 mean_tok_us=309866 tokens=1014 5565 302 4843 349 5465 28723 2 golden=match request_us=7724662 rc=3 +infer: measure req=3 name=long1 ids=41 prefill=41 prefill_us=11288449 produced=16 mean_tok_us=311511 tokens=28740 28723 415 7212 8045 5045 1938 272 1370 1096 22950 349 20995 486 8887 13938 golden=MISMATCH request_us=15962102 rc=3 +infer: measure req=4 name=long2 ids=113 prefill=113 prefill_us=31324828 produced=16 mean_tok_us=316571 tokens=28737 28742 28719 7371 298 3934 369 368 28742 267 2461 7598 395 574 12602 4796 golden=match request_us=36074389 rc=3 +infer: session close rc=0 heap_used_kib=20264 heap_peak_kib=20264 frames_free_before=1721724 frames_free_after=1721724 rc=0 +AIENOS_CK_INFER_SESSION: FAIL + +## pi5-8-restore (kernel.log lines) +model_map: ok len=807694368 extents=1 sector=512 disk=29ceb42de1b36445b340924422ebcae3 +model: reading 807694368 bytes in 1 extents, block_size=512 last_block=250347519 -> 0xbbd2000 +model: base=0xbbd2000 len=807694368 extents=1 read_us=8399537 declared_sha256=3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1 +cpu_features: dotprod=1 i8mm=0 bf16=0 fhm=0 fp16=1 sve=0 rndr=0 +infer: sha256=3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1 sha_us=5077435 +infer: dot_path=sdot cpu_dotprod=1 +infer: session open rc=0 tensors=147 vocab=128256 layers=16 kv_capacity=64 max_new=16 max_prompt_bytes=256 heap_reserve_kib=64 heap_used_kib=22900 open_us=274252 +infer: session prompt=2 ids=17 steps=25 prefill=17 produced=8 last=yes prefill_us=11135404 mean_tok_us=832559 tokens=791 6864 315 9822 374 12366 13 128009 text=The capital of France is Paris. heap_used_kib=22901 request_us=16964153 rc=3 +infer: session close rc=0 heap_used_kib=22902 heap_peak_kib=24695 frames_free_before=1602139 frames_free_after=1602139 rc=0 +AIENOS_CK_INFER_SESSION: PASS + diff --git a/scripts/.crumb b/scripts/.crumb index 074bd6ce..1bfff038 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-14T02:20:15Z", + "compiled_at": "2026-10-14T02:42:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:e148d5bd0c19501efe0f07f59aae88ed1209904d1cf3e79bf9a1187877b8b11c", + "digest": "sha256:ee6e3d66e3e3a4f85001de67fad6b5243b02c522a046f630b720feaf16d7822c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 102, - "generated_at_commit": "7cd74cbbd0a45def4384618e7f82513c76021aad", - "source_tree": "sha256:4994ece1623fa0138f9791f115c93d61dc43e33840d2a8f578242c7ca32ec3e7" + "files": 108, + "generated_at_commit": "384171b3fd2b66f08e15ec67cf0fa5dd5935ec16", + "source_tree": "sha256:79826a61372ffaa6c49f90f9adc677b5dcae75287f6f78dfbfd824059494322b" }, "owner_lane": "", "provenance": { diff --git a/scripts/pi5-8/gen_measure_header.sh b/scripts/pi5-8/gen_measure_header.sh new file mode 100755 index 00000000..83cca99b --- /dev/null +++ b/scripts/pi5-8/gen_measure_header.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# PI5-8: turn host_golden.sh output (llama.cpp ids and greedy tokens) into the pi5_measure.h the measurement +# kernel build includes. Requests: the short prompt three times (variance), then the two long prompts. +# gen_measure_header.sh GOLDEN_DIR EOS_ID > pi5_measure.h +set -euo pipefail +d="${1:?golden dir}"; eos="${2:?eos id}" +echo "/* generated by scripts/pi5-8/gen_measure_header.sh from $d (llama.cpp reference) */" +echo "#define MEAS_EOS ${eos}u" +for p in short long1 long2; do + ids=$(head -1 "$d/$p.ref" | cut -d' ' -f2- | tr ' ' ',') + exp=$(awk '$1=="step"{printf "%s%su", (n++?",":""), $3}' "$d/$p.ref") + echo "static const uint32_t meas_${p}_ids[] = {${ids}};" + echo "static const uint32_t meas_${p}_exp[] = {${exp}};" +done +cat <<'EOT' +struct meas_req { const char *name; unsigned nids; const uint32_t *ids; unsigned nexp; const uint32_t *exp; }; +#define MEAS_N(a) ((unsigned)(sizeof(a) / sizeof((a)[0]))) +static const struct meas_req meas_reqs[] = { + {"short", MEAS_N(meas_short_ids), meas_short_ids, MEAS_N(meas_short_exp), meas_short_exp}, + {"short", MEAS_N(meas_short_ids), meas_short_ids, MEAS_N(meas_short_exp), meas_short_exp}, + {"short", MEAS_N(meas_short_ids), meas_short_ids, MEAS_N(meas_short_exp), meas_short_exp}, + {"long1", MEAS_N(meas_long1_ids), meas_long1_ids, MEAS_N(meas_long1_exp), meas_long1_exp}, + {"long2", MEAS_N(meas_long2_ids), meas_long2_ids, MEAS_N(meas_long2_exp), meas_long2_exp}, +}; +#define MEAS_NREQ MEAS_N(meas_reqs) +EOT diff --git a/scripts/pi5-8/host_golden.sh b/scripts/pi5-8/host_golden.sh new file mode 100755 index 00000000..d94ce635 --- /dev/null +++ b/scripts/pi5-8/host_golden.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# PI5-8 host golden check: the engine's forward pass vs llama.cpp, greedy tokens, one model, three prompts. +# host_golden.sh MODEL.gguf TEMPLATE EOS_ID [N=16] [sdot] +# TEMPLATE: llama3 | zephyr | danube | chatml sdot: use the dotprod int8 path (default: f32 scalar) +# llama.cpp is the build in $LLAMA (default ~/llama.cpp-build, commit 4a89937, the one PI5-6 used). +# Prompt ids come from llama.cpp's own tokenizer and are fed to the engine, so the engine's tokenizer +# is not judged here (see docs/native/PI5-8-MODEL-CHOICE.md, "Limits"). +# Files for the Pi image land in $OUT (default /tmp/pi58-golden/):

.ref holds the ids line +# and the llama.cpp steps,

.probe the engine's output,

.exp /

.got the compared "index id" lists. +set -euo pipefail +model="${1:?model}"; tpl="${2:?template}"; eos="${3:?eos id}"; n="${4:-16}"; dot="${5:-}" +here="$(cd "$(dirname "$0")" && pwd)"; repo="$(cd "$here/../.." && pwd)" +L="${LLAMA:-$HOME/llama.cpp-build}" +name="$(basename "$model" .gguf)"; out="${OUT:-/tmp/pi58-golden/$name${dot:+-$dot}}"; mkdir -p "$out" +ref="${out}/llama_ref" +[[ -x "$ref" ]] || gcc -O1 -o "$ref" "$repo/crates/aienos-infer/tests/ref/llama_ref.c" -I"$L/include" -I"$L/ggml/include" \ + -L"$L/build/bin" -lllama -lggml -lggml-base -Wl,-rpath,"$L/build/bin" +probe="$repo/target/release/examples/model_probe" +[[ -x "$probe" ]] || cargo build --release -p aienos-infer --example model_probe --manifest-path "$repo/Cargo.toml" +wrap() { + case "$tpl" in + llama3) printf '<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n%s<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n' "$1" ;; + zephyr) printf '<|user|>\n%s\n<|assistant|>\n' "$1" ;; + danube) printf '<|prompt|>%s<|answer|>' "$1" ;; + chatml) printf '<|im_start|>user\n%s<|im_end|>\n<|im_start|>assistant\n' "$1" ;; + *) echo "unknown template $tpl" >&2; exit 2 ;; + esac +} +# Exact token match = PASS. If the lists differ, look at the FIRST divergence: when llama.cpp's own top-1 minus top-2 +# logit gap there is below 1.0 (the largest single-logit difference seen between the engine and llama.cpp on the Llama +# control, 0.9), the two implementations may legitimately disagree (floats are summed in a different order, a near-tie +# flips): NOISE. A larger gap is FAIL. The 1.0 threshold is this script's own choice, not a published standard. +fail=0 +for p in short long1 long2; do + wrap "$(cat "$here/prompt-$p.txt")" > "$out/$p.prompt" + # read back with a sentinel so the template's trailing newlines survive command substitution + text="$(cat "$out/$p.prompt"; printf x)"; text="${text%x}" + # CPU only, as llama_ref.c intends (n_gpu_layers=0); hiding the GPU also stops a busy GPU from aborting the run + CUDA_VISIBLE_DEVICES="" "$ref" "$model" "$text" "$n" "$out/$p.logits" > "$out/$p.ref" 2>"$out/$p.ref.err" + AIENOS_DOT="$dot" AIENOS_LOGITS="$out/$p.logits" "$probe" "$model" "$out/$p.ref" "$n" "$eos" > "$out/$p.probe" + awk '$1=="step"{print $2,$3} $1=="eog"{print "eog"}' "$out/$p.ref" > "$out/$p.exp" + awk '$1=="step"{print $2,$3} $1=="eog"{print "eog"}' "$out/$p.probe" > "$out/$p.got" + ids_n=$(( $(head -1 "$out/$p.ref" | wc -w) - 1 )) + if cmp -s "$out/$p.exp" "$out/$p.got"; then + r=PASS + else + div=$(paste -d' ' "$out/$p.exp" "$out/$p.got" | awk 'NF==4 && $2!=$4 {print $1; exit}') + gap=$(awk -v s="$div" '$1=="step" && $2==s {print $4}' "$out/$p.ref") + if awk -v g="$gap" 'BEGIN{exit !(g<1.0)}'; then r="NOISE(first divergence step $div, llama.cpp gap $gap)" + else r="FAIL(first divergence step $div, llama.cpp gap $gap)"; fail=1; fi + fi + echo "golden $name prompt=$p ids=$ids_n tokens=$(grep -c '^step' "$out/$p.ref") dot=${dot:-f32} $r" + echo " $(grep logits_vs_llama "$out/$p.probe" || true)" + echo " llama.cpp: $(awk '$1=="step"{printf "%s ", $3}' "$out/$p.ref")" + [[ $r == PASS ]] || echo " engine: $(awk '$1=="step"{printf "%s ", $3}' "$out/$p.probe")" +done +exit $fail diff --git a/scripts/pi5-8/pi_run.sh b/scripts/pi5-8/pi_run.sh new file mode 100755 index 00000000..720273de --- /dev/null +++ b/scripts/pi5-8/pi_run.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# PI5-8: put one model on the card's raw AIENOS-MODEL partition (p3), run the measurement image once, clean up. +# pi_run.sh MODEL.gguf MODEL.MAP BOOTAA64.EFI TAG [--no-write | --write-only] +# --no-write: p3 already holds the model (only verify it); --write-only: write and verify p3, do not run. +# Steps: wait until no other Pi run is going (hold file + pi5-run processes), write the model to /dev/mmcblk0p3 on +# the hub and read it back (sha256 must equal the model's), run ~/workspace/pi5/pi5-run.sh with KLOG=1 and the +# map, then remove MODEL.MAP from the ESP (the harness does not). Evidence: ~/workspace/pi5-runs/TAG/. +# The hub is the house server: one ssh at a time, no fast retries, never `find /` on it. +set -euo pipefail +model="${1:?model}"; map="${2:?map}"; efi="${3:?efi}"; tag="${4:?tag}"; nowrite="${5:-}" +hold=/home/drakestapleton/.claude/jobs/9974574d/tmp/pi-hold +hs() { ssh -o BatchMode=yes -o ConnectTimeout=15 hub "$@"; } +until [[ ! -e "$hold" ]] && [[ -z "$(ps -eo pid,args | grep -E ' bash [^ ]*/pi5-run[^ ]*\.sh' | grep -v grep || true)" ]]; do sleep 30; done +size=$(stat -c %s "$model"); sha=$(sha256sum "$model" | cut -d' ' -f1) +if [[ "$nowrite" != --no-write ]]; then + echo "[$(date -u +%H:%M:%SZ)] writing $size bytes to p3" + hs 'sudo dd of=/dev/mmcblk0p3 bs=4M conv=fsync status=none' < "$model" + hs 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null' +fi +got=$(hs "sudo dd if=/dev/mmcblk0p3 bs=4M status=none | head -c ${size} | sha256sum" | cut -d' ' -f1) +echo "[$(date -u +%H:%M:%SZ)] p3 readback sha256=$got want=$sha" +[[ "$got" == "$sha" ]] || { echo "p3 readback MISMATCH; stopping"; exit 1; } +[[ "$nowrite" == --write-only ]] && { echo "write-only: p3 verified, no run"; exit 0; } +KLOG=1 MODEL_MAP="$map" "$HOME/workspace/pi5/pi5-run.sh" "$efi" "$tag" +hs 'set -e; sudo mount /dev/mmcblk0p1 /mnt/aienos; trap "sudo umount /mnt/aienos" EXIT; sudo rm -f /mnt/aienos/EFI/AIENOS/MODEL.MAP; sync; test ! -e /mnt/aienos/EFI/AIENOS/MODEL.MAP; echo model_map_removed' +echo "[$(date -u +%H:%M:%SZ)] done $tag" diff --git a/scripts/pi5-8/prompt-long1.txt b/scripts/pi5-8/prompt-long1.txt new file mode 100644 index 00000000..e15e07d2 --- /dev/null +++ b/scripts/pi5-8/prompt-long1.txt @@ -0,0 +1 @@ +Explain in three sentences why the sky looks blue during the day and red at sunset, and name the physical effect that causes it. \ No newline at end of file diff --git a/scripts/pi5-8/prompt-long2.txt b/scripts/pi5-8/prompt-long2.txt new file mode 100644 index 00000000..9d5fc812 --- /dev/null +++ b/scripts/pi5-8/prompt-long2.txt @@ -0,0 +1 @@ +Here is a short note from a customer: "I ordered a small wooden bookshelf three weeks ago and it arrived with one side panel cracked. I sent two emails and called once, but nobody has replied. I would like either a replacement panel or my money back, and I would like to know who is responsible for the delay." Please write a polite reply from the support team that apologises, says what will happen next, and asks for a photo of the damage. Keep it short. \ No newline at end of file diff --git a/scripts/pi5-8/prompt-short.txt b/scripts/pi5-8/prompt-short.txt new file mode 100644 index 00000000..510c6bfa --- /dev/null +++ b/scripts/pi5-8/prompt-short.txt @@ -0,0 +1 @@ +What is the capital of France? \ No newline at end of file