diff --git a/.github/workflows/ck-kernel.yml b/.github/workflows/ck-kernel.yml index 5b47ba3d..706fa575 100644 --- a/.github/workflows/ck-kernel.yml +++ b/.github/workflows/ck-kernel.yml @@ -101,7 +101,8 @@ jobs: cp -r /tmp/ck-gates-work.*/logs/* "${RUNNER_TEMP}/ck-receipt/logs/" 2>/dev/null || true [ "${rc}" = 0 ] || exit 1 # FPU and INFER are not required: they need the Rust target aarch64-unknown-none (and INFER the 800 MB model file), which this - # runner image is not known to have, so it prints NOT_RUN there (aienos#34 lane 0). + # runner image is not known to have, so it prints NOT_RUN there (aienos#34 lanes 0, 4 and 5; INFER now also + # requires the exact llama.cpp token sequence, "Paris" in the decoded text and a clean unload). # Every gate with a C implementation (source != missing in the # ck_gates.sh table) must be PASS. required=$(sed -n "/^CK_GATE_TABLE='/,/^'/p" scripts/ck_gates.sh | awk -F'|' 'NF==3 && $2!="missing" && $1!="FPU" && $1!="INFER" {print $1}') diff --git a/crates/aienos-infer-kernel/Cargo.toml b/crates/aienos-infer-kernel/Cargo.toml index ba11cd04..28c3231a 100644 --- a/crates/aienos-infer-kernel/Cargo.toml +++ b/crates/aienos-infer-kernel/Cargo.toml @@ -5,7 +5,7 @@ name = "aienos-infer-kernel" version = "0.1.0" edition = "2021" license = "Apache-2.0 WITH LLVM-exception" -description = "Links aienos-infer into the general-regs-only C kernel: bump allocator + ingest probe (aienos#34 lane 4)." +description = "Links aienos-infer into the general-regs-only C kernel: bump allocator, ingest, prefill + greedy decode (aienos#34 lanes 4-5)." [lib] crate-type = ["staticlib"] diff --git a/crates/aienos-infer-kernel/src/lib.rs b/crates/aienos-infer-kernel/src/lib.rs index cc348381..38055e0a 100644 --- a/crates/aienos-infer-kernel/src/lib.rs +++ b/crates/aienos-infer-kernel/src/lib.rs @@ -1,19 +1,28 @@ -//! Kernel-side entry for native inference (aienos#34 lane 4, cut 1). +//! Kernel-side entry for native inference (aienos#34 lane 4 cut 1 + lane 5 +//! cut 2). //! //! The C kernel (built -mgeneral-regs-only) hands this staticlib the Llama //! GGUF bytes it ingested into RAM; the unit parses the header with -//! `aienos_infer::Gguf`, binds the `Model`, tokenizes the fixed chat prompt -//! and reports what it found. No token generation yet. +//! `aienos_infer::Gguf`, binds the `Model`, tokenizes the fixed chat prompt, +//! runs prefill, greedy-decodes until `<|eot_id|>` (128009) or [`MAX_NEW`] +//! tokens and hands the ids, the decoded bytes and per-token timings back in +//! an [`InferResult`] for the kernel to print. The weights stay quantised in +//! the ingested bytes (Q4_K/Q6_K blocks are dequantised inside each dot +//! product by `aienos_infer`); only norms, the KV cache and activations live +//! on this unit's heap. //! //! Allocator: `aienos-infer` needs `alloc`. This crate installs a bump //! allocator over ONE region the kernel provides (`aienos_infer_heap_init`, //! a contiguous run of frames from `ck_mm_frames_alloc`). Allocation moves a //! cursor; `dealloc` only reclaims when the block is the newest one and //! `realloc` grows the newest block in place, otherwise memory is not -//! reused. That is enough for one load + one prompt; it is NOT a general -//! allocator. Single core, interrupts masked by the caller: no locking. -//! Exhaustion returns null, which Rust turns into a panic, which calls -//! `aienos_infer_panic` (the C kernel prints and stops; it never returns). +//! reused. The forward pass allocates nothing (`DecodeState` is sized up +//! front), so this is enough for one load + one generation; it is NOT a +//! general allocator. Single core, interrupts masked by the caller: no +//! locking. Exhaustion returns null, which Rust turns into a panic, which +//! calls `aienos_infer_panic` (the C kernel prints and stops; it never +//! returns). Unload: the kernel returns the region's frames and calls +//! `aienos_infer_heap_init(0, 0)`, after which every allocation fails closed. #![no_std] extern crate alloc; @@ -23,18 +32,55 @@ use core::alloc::{GlobalAlloc, Layout}; use core::cell::UnsafeCell; use core::slice; -use aienos_infer::{Gguf, Model, Tokenizer}; +use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer}; /// The fixed chat prompt (user turn) of the lane's golden reference. pub const PROMPT: &str = "What is the capital of France?"; -/// Words written to `out` by `aienos_infer_probe`. +/// `<|eot_id|>`: end of the assistant turn (tokenizer.ggml.eos_token_id of +/// the frozen model; `crates/aienos-infer/tests/forward.rs` asserts 128009). +pub const EOT: u32 = 128009; + +/// Generation stops after this many tokens if no EOT came first. +pub const MAX_NEW: usize = 16; + +/// KV-cache positions: the 17-token prompt plus [`MAX_NEW`], rounded up. +pub const KV_CAPACITY: usize = 64; + +/// Bytes of decoded text kept for the kernel to print. +pub const TEXT_BYTES: usize = 256; + +/// Words in [`InferResult::words`] (the cut-1 probe words). pub const OUT_WORDS: usize = 9; +/// What the kernel gets back. `#[repr(C)]`: the C side declares the same +/// struct (native/kernel/core/infer.c `struct infer_result`). +#[repr(C)] +pub struct InferResult { + /// [0] tensor count, [1] vocab size, [2..6] first four prompt ids, + /// [6] prompt token count, [7] layer count, [8] allocator peak in KiB. + pub words: [u32; OUT_WORDS], + /// Generated tokens (`tokens[..ntok]`), EOT included when it came. + pub ntok: u32, + pub tokens: [u32; MAX_NEW], + /// Microseconds of the forward pass that produced `tokens[i]`'s logits + /// for i >= 1 (`tok_us[0]` is 0: token 0 comes from the prefill). + pub tok_us: [u64; MAX_NEW], + /// Microseconds of the whole prefill (one forward per prompt token). + pub prefill_us: u64, + /// Decoded bytes of `tokens[..ntok]` (`text[..text_len]`, truncated to + /// [`TEXT_BYTES`]; control tokens decode to nothing). + pub text_len: u32, + pub text: [u8; TEXT_BYTES], +} + extern "C" { /// Provided by native/kernel/core/infer.c: prints a message and halts the /// kernel with a panic report. Never returns. fn aienos_infer_panic() -> !; + /// Kernel monotonic clock in microseconds (native/kernel/include/ck.h). + /// General-registers-only C: safe to call with FP state live. + fn ck_time_us() -> u64; } #[panic_handler] @@ -114,7 +160,9 @@ unsafe impl GlobalAlloc for Bump { } /// Gives the allocator its region `[base, base+len)`. Call once, before -/// `aienos_infer_probe`. +/// `aienos_infer_run`. Calling it again with `(0, 0)` after the kernel has +/// returned the frames forgets the region: every later allocation fails +/// closed (null -> panic) instead of touching freed memory. /// /// # Safety /// The region must be writable RAM owned by the caller for the rest of the @@ -129,13 +177,15 @@ pub unsafe extern "C" fn aienos_infer_heap_init(base: usize, len: usize) { } /// Error codes (negative): -1 null/short args, -2 GGUF parse, -3 model bind, -/// -4 tokenizer data, -5 tokenizer build, -6 encode, -7 fewer than 4 ids. -fn probe(bytes: &[u8], out: &mut [u32; OUT_WORDS]) -> i32 { +/// -4 tokenizer data, -5 tokenizer build, -6 encode, -7 fewer than 4 ids, +/// -8 prompt longer than the KV cache, -9 prefill, -10 decode forward, +/// -11 token-to-text decode. +fn run(bytes: &[u8], r: &mut InferResult) -> i32 { let g = match Gguf::parse(bytes) { Ok(g) => g, Err(_) => return -2, }; - out[0] = g.tensors().len() as u32; + r.words[0] = g.tensors().len() as u32; let model = match Model::new(&g) { Ok(m) => m, Err(_) => return -3, @@ -148,7 +198,7 @@ fn probe(bytes: &[u8], out: &mut [u32; OUT_WORDS]) -> i32 { Ok(t) => t, Err(_) => return -5, }; - out[1] = tok.vocab_size() as u32; + r.words[1] = tok.vocab_size() as u32; let ids: Vec = match tok.encode_chat(PROMPT) { Ok(v) => v, Err(_) => return -6, @@ -156,32 +206,79 @@ fn probe(bytes: &[u8], out: &mut [u32; OUT_WORDS]) -> i32 { if ids.len() < 4 { return -7; } - out[2..6].copy_from_slice(&ids[..4]); - out[6] = ids.len() as u32; - out[7] = model.params.block_count; + r.words[2..6].copy_from_slice(&ids[..4]); + r.words[6] = ids.len() as u32; + r.words[7] = model.params.block_count; + if ids.len() + MAX_NEW > KV_CAPACITY { + return -8; + } + + // Same path as the host test (crates/aienos-infer/tests/forward.rs): + // DecodeState + prefill + argmax + forward(t, true), f32 activations. + let mut st = DecodeState::new(&model, KV_CAPACITY); + // SAFETY: ck_time_us is a plain C function with no arguments. + let t0 = unsafe { ck_time_us() }; + if st.prefill(&model, &ids).is_err() { + return -9; + } + r.prefill_us = unsafe { ck_time_us() } - t0; + let mut n = 0usize; + loop { + let t = argmax(&st.logits); + r.tokens[n] = t; + n += 1; + if t == EOT || n == MAX_NEW { + break; + } + let t1 = unsafe { ck_time_us() }; + if st.forward(&model, t, true).is_err() { + r.ntok = n as u32; + return -10; + } + r.tok_us[n] = unsafe { ck_time_us() } - t1; + } + r.ntok = n as u32; + let text = match tok.decode(&r.tokens[..n]) { + Ok(v) => v, + Err(_) => return -11, + }; + let keep = text.len().min(TEXT_BYTES); + r.text[..keep].copy_from_slice(&text[..keep]); + r.text_len = keep as u32; 0 + // st, tok, model, g drop here: nothing of the model outlives this call. } -/// Parses the GGUF at `model[..len]`, binds the `Model`, tokenizes -/// [`PROMPT`] with the chat template and writes nine u32 words to `out`: -/// [0] tensor count, [1] vocab size, [2..6] first four prompt token ids, -/// [6] prompt token count, [7] layer count, [8] allocator peak, in KiB. -/// Words are only meaningful up to the stage that failed. Returns 0 on -/// success, a negative code otherwise (see `probe`). +/// Parses the GGUF at `model[..len]`, binds the `Model`, tokenizes [`PROMPT`] +/// with the chat template, runs prefill and greedy decode and fills `out`. +/// Fields are only meaningful up to the stage that failed. Returns 0 on +/// success, a negative code otherwise (see `run`). /// /// # Safety -/// `model` must point to `len` readable bytes and `out` to nine writable -/// u32. FP/SIMD must be enabled and interrupts masked (the kernel does not -/// save FP state). `aienos_infer_heap_init` must have been called. +/// `model` must point to `len` readable bytes and `out` to one writable +/// `InferResult`. FP/SIMD must be enabled and interrupts masked (the kernel +/// does not save FP state). `aienos_infer_heap_init` must have been called. #[no_mangle] -pub unsafe extern "C" fn aienos_infer_probe(model: *const u8, len: u64, out: *mut u32) -> i32 { +pub unsafe extern "C" fn aienos_infer_run( + model: *const u8, + len: u64, + out: *mut InferResult, +) -> i32 { if model.is_null() || out.is_null() || len == 0 || len > usize::MAX as u64 { return -1; } let bytes = slice::from_raw_parts(model, len as usize); - let mut w = [0u32; OUT_WORDS]; - let rc = probe(bytes, &mut w); - w[8] = (*HEAP.peak.get() / 1024) as u32; - core::ptr::copy_nonoverlapping(w.as_ptr(), out, OUT_WORDS); + let r = &mut *out; + *r = InferResult { + words: [0; OUT_WORDS], + ntok: 0, + tokens: [0; MAX_NEW], + tok_us: [0; MAX_NEW], + prefill_us: 0, + text_len: 0, + text: [0; TEXT_BYTES], + }; + let rc = run(bytes, r); + r.words[8] = (*HEAP.peak.get() / 1024) as u32; rc } diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 4461e23c..b3bef3d8 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -25,7 +25,7 @@ C gates (one line each from `ck_gates.sh`): `M1` and `M3` (from `scripts/qemu_ck_net_test.sh`; rows 102-106 and 110-112; the script now also checks the virtio-net SMMU fence (ACCESS_PLATFORM required, out-of-window device DMA refused), rows 102 and 110-112 are QEMU PASS on this branch from the committed forge log `evidence/ck_net_qemu_8bdbc2e46b85d04c422f9d2830c1c4b263e254b3cfecfe21ff0063c9e33c86e8.log`, hardware NOT_RUN), the kernel entropy rows 107-109 (M1 via `scripts/lib_ck_m1_checks.sh`, ARGUS1_REVOKE and M4_STORE via the Store gate boot 7), `DISK_LAYOUT` (C-only, from `scripts/qemu_ck_disk_layout_test.sh`, rows 118-123: QEMU PASS at 741b2b8 before the merge with main 8555049, rerun pending at the merged head; row 123 host test), and the NOT_RUN gates `SMP` (C-only, from `scripts/qemu_ck_smp_test.sh`, rows 113-117, NOT_RUN pending forge receipt), `M0_ROLLBACK`, `M4_STORE_CRASH` (now read from `scripts/qemu_ck_store_crash_test.sh`, rows 73-80; NOT_RUN until a forge receipt exists), -`M4_CONTINUITY`, `M4_RECOVERY`, `KEYBOARD`, `FPU` (C-only, from `scripts/qemu_ck_fpu_test.sh`, rows 124-128; QEMU PASS, hardware NOT_RUN), and `INFER` (C-only, from `scripts/qemu_ck_infer_test.sh`, rows 129-134; QEMU PASS, hardware NOT_RUN). +`M4_CONTINUITY`, `M4_RECOVERY`, `KEYBOARD`, `FPU` (C-only, from `scripts/qemu_ck_fpu_test.sh`, rows 124-128; QEMU PASS, hardware NOT_RUN), and `INFER` (C-only, from `scripts/qemu_ck_infer_test.sh`, rows 129-139; QEMU PASS, hardware NOT_RUN). `M4_NVME` and `SMMU` PASS in the SMMU-confined mode (default `make full` image, QEMU `iommu=smmuv3`). The unconfined bypass build @@ -532,13 +532,23 @@ runner is not known to have the Rust target); required list in `ck-kernel.yml` s | 127 | `CPACR_EL1.FPEN = 0b11` read back at EL1 after `ck_fpu_enable()` | FPU | QEMU PASS (hardware NOT_RUN) | | 128 | negative control: with FPEN cleared in `ck_fpu_enable()` the first FP instruction traps and the gate FAILs (kernel fault report, no result line); canned-log self-test (`--self-test`) rejects wrong dot/exp/NEON/rc/FPEN/missing lines | FPU | QEMU PASS (control killed; hardware NOT_RUN) | -## INFER: scripts/qemu_ck_infer_test.sh -> CK `INFER` (aienos#34 lane 4 cut 1, C-only, no Rust-kernel counterpart) +## INFER: scripts/qemu_ck_infer_test.sh -> CK `INFER` (aienos#34 lane 4 cut 1 + lane 5 cut 2, C-only, no Rust-kernel counterpart) The kernel ingests the 807,694,368-byte Llama-3.2-1B-Instruct Q4_K_M GGUF into its own RAM and calls the Rust crate `crates/aienos-infer` from C through `crates/aienos-infer-kernel` (a no_std staticlib: the `extern "C"` -entry `aienos_infer_probe` plus a documented bump allocator over one 256 MiB region). It parses the GGUF header, -binds the `Model`, tokenizes the fixed chat prompt "What is the capital of France?" and prints tensor count, -vocab size and the prompt ids. No token generation yet. QEMU-only probe image: +entry `aienos_infer_run` plus a documented bump allocator over one 256 MiB region). It parses the GGUF header, +binds the `Model`, tokenizes the fixed chat prompt "What is the capital of France?", runs prefill and greedy +decode until `<|eot_id|>` (128009) or 16 tokens on the same code path as the host test +(`crates/aienos-infer/tests/forward.rs`: `DecodeState`, `prefill`, `argmax`, `forward`), and hands ids, decoded +bytes and per-token microseconds (`ck_time_us`) back for the kernel to print (`infer: tokens=`, `infer: text=`, +`infer: tok_us=`, `infer: decode_tokens=N mean_tok_us=`). The weights stay quantised in the ingested bytes +(Q4_K/Q6_K dequantised per block inside each dot product); only norms, the KV cache (64 positions) and +activations live on the unit's heap. Unload: the unit keeps nothing past its return, the kernel forgets the heap +region (`aienos_infer_heap_init(0, 0)`: every later allocation fails closed) and returns every frame of the model +and the heap; `infer: unloaded heap_live_kib=.. frames_free_before=.. frames_free_after=..` must show the free-frame +count back at its pre-ingest value, and the kernel then continues to M3, the stages, the final report and the PSCI +reset. FP registers are left dirty after the unit (nothing else in the kernel reads them; EL0 traps on FP). +QEMU-only probe image: `make -C native/kernel CK_INFER_LIB=` (adds `-DCK_INFER_PROBE=1` for `core/infer.c`; refused together with `CK_RUST_LIBS` or `CK_HARDWARE_STAGING`). The default image is unchanged; the probe image must carry its own TEST-ONLY fw_cfg announcement (the default-image fw_cfg ban in `fwcfg_check` stays). @@ -559,4 +569,9 @@ required in CI (the runner has neither the model nor the target). | 131 | probe rc = 0; 147 tensors (`golden.rs:112`), vocab 128256, 16 layers | INFER | QEMU PASS (hardware NOT_RUN) | | 132 | first four prompt ids = 128000 128006 882 128007 and prompt length 17, both read from `crates/aienos-infer/tests/fixtures/ref_fr.txt` by the script | INFER | QEMU PASS (hardware NOT_RUN) | | 133 | kernel alive, no panic/fault, final report, QEMU exit 0 (PSCI reset); M1/M3 boot gate unchanged PASS | INFER | QEMU PASS (hardware NOT_RUN) | -| 134 | negative control: `--negative-control` overwrites the GGUF magic in a host copy -> probe rc=-2, every probe check FAILs, control prints PASS; `--self-test` canned logs reject 17 mutations, each by its own FAIL line | INFER | QEMU PASS (control caught; hardware NOT_RUN) | +| 134 | negative control: `--negative-control` overwrites the GGUF magic in a host copy -> probe rc=-2, every probe check FAILs, control prints PASS; `--self-test` canned logs reject 33 mutations, each by its own FAIL line | INFER | QEMU PASS (control caught; hardware NOT_RUN) | +| 135 | generated ids = the llama.cpp greedy sequence of `ref_fr.txt` "step" lines, exact: 791 6864 315 9822 374 12366 13 128009 (EOT included), read from the fixture by the script and also hard-coded in `core/infer.c` for the kernel verdict | INFER | QEMU PASS (hardware NOT_RUN) | +| 136 | decoded text contains "Paris" (`infer: text=The capital of France is Paris.`) | INFER | QEMU PASS (hardware NOT_RUN) | +| 137 | per-token timing line present: 7 decode forwards, mean > 0 us. First native CPU number: 40.40 s per decode token, prefill 553.9 s for 17 tokens, whole Rust call 837.8 s, under QEMU TCG single core (not hardware; host test on one Grace core is 0.59 s per forward) | INFER | QEMU PASS (hardware NOT_RUN) | +| 138 | clean unload: `infer: unloaded` line present before the final report, frame-return rc 0,0, free frames after = before the ingest (1021097 = 1021097; 262728 frames returned), kernel then reaches M3, stages, final report, PSCI reset (QEMU exit 0) | INFER | QEMU PASS (hardware NOT_RUN) | +| 139 | live control: the same serial log re-checked against a mutated expected-id list (second-to-last id + 1) must FAIL on the token check, else the gate FAILs; `--self-test` also covers wrong/short/swapped tokens, missing tokens/text/timing/unload lines, missing "Paris", leaked frames, refused frame return, unload after the final report | INFER | QEMU PASS (control caught; hardware NOT_RUN) | diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c index c26c4784..fa9e7c82 100644 --- a/native/kernel/core/infer.c +++ b/native/kernel/core/infer.c @@ -1,6 +1,8 @@ /* infer.c -- ingest the Llama-3.2-1B GGUF into kernel RAM and call the Rust * inference crate from the general-regs-only C kernel (aienos#34 lane 4, - * cut 1: header, model bind and prompt tokenization; no token generation). + * cut 1: header, model bind, prompt tokenization; aienos#34 lane 5 cut 2: + * prefill + greedy decode of the fixed prompt, decoded text, per-token + * timing, then a clean unload that returns every frame). * Only compiled into the probe build: Makefile CK_INFER_LIB=<.a> adds * -DCK_INFER_PROBE=1; the default image carries none of this. * @@ -34,7 +36,19 @@ #include "sha256.h" extern void aienos_infer_heap_init(uintptr_t base, uintptr_t len); -extern int32_t aienos_infer_probe(const uint8_t *model, uint64_t len, uint32_t *out); +/* Mirror of crates/aienos-infer-kernel/src/lib.rs `InferResult` (#[repr(C)]). */ +#define INFER_MAX_NEW 16 +#define INFER_TEXT_BYTES 256 +struct infer_result { + uint32_t words[9]; + uint32_t ntok; + uint32_t tokens[INFER_MAX_NEW]; + uint64_t tok_us[INFER_MAX_NEW]; + uint64_t prefill_us; + uint32_t text_len; + uint8_t text[INFER_TEXT_BYTES]; +}; +extern int32_t aienos_infer_run(const uint8_t *model, uint64_t len, struct infer_result *out); #define CPACR_FPEN_SHIFT 20 #define PAGE 4096ull @@ -44,6 +58,27 @@ extern int32_t aienos_infer_probe(const uint8_t *model, uint64_t len, uint32_t * /* The prompt's expected first four ids (crates/aienos-infer/tests/fixtures/ref_fr.txt). */ 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}; +/* 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]; +static void escape(char *out, const uint8_t *b, uint32_t n) +{ + static const char d[] = "0123456789abcdef"; + for (uint32_t i = 0; i < n; i++) { + if (b[i] >= 0x20 && b[i] < 0x7f && b[i] != 0x5c) { + *out++ = (char)b[i]; + } else { + *out++ = 0x5c; + *out++ = 0x78; + *out++ = d[b[i] >> 4]; + *out++ = d[b[i] & 15]; + } + } + *out = 0; +} static volatile uint8_t *fwcfg; @@ -202,6 +237,7 @@ void ck_infer_run(void) ck_printf("infer: fw_cfg base=0x%llx dma=yes file=%s size=%u\n", (unsigned long long)base, MODEL_FILE, size); + uint64_t frames_before = ck_mm_free_frames(); uint64_t mpages = ((uint64_t)size + PAGE - 1) / PAGE, mpa = 0, hpa = 0; if (ck_mm_frames_alloc(mpages, &mpa) || ck_mm_frames_alloc(HEAP_BYTES / PAGE, &hpa)) { ck_printf("infer: ingest FAIL (no frames: need %llu + %llu pages, %llu free)\nAIENOS_CK_INFER: FAIL\n", @@ -232,8 +268,11 @@ void ck_infer_run(void) hex(dh, dg, SHA256_DIGEST_SIZE); ck_printf("infer: sha256=%s sha_us=%llu\n", dh, (unsigned long long)(ck_time_us() - t1)); - /* FP/SIMD on, every exception masked for the Rust unit (see core/fpu.c). */ - uint32_t out[9] = {0}; + /* FP/SIMD on, every exception masked for the Rust unit (see core/fpu.c). + * The FP registers are left dirty afterwards (nothing else in the kernel + * reads them; EL0 traps on FP). */ + static struct infer_result res; /* ~0.5 KiB; static keeps it off the EL1 stack */ + memset(&res, 0, sizeof res); uint64_t v = ck_rd(cpacr_el1); v |= 3ull << CPACR_FPEN_SHIFT; ck_wr(cpacr_el1, v); @@ -242,9 +281,10 @@ void ck_infer_run(void) uint64_t daif = ck_rd(daif); __asm__ volatile("msr daifset, #0xf" ::: "memory"); uint64_t t2 = ck_time_us(); - int32_t prc = aienos_infer_probe((const uint8_t *)(uintptr_t)mpa, size, out); + int32_t prc = aienos_infer_run((const uint8_t *)(uintptr_t)mpa, size, &res); uint64_t t3 = ck_time_us(); ck_wr(daif, daif); + const uint32_t *out = res.words; ck_printf("infer: probe rc=%d tensors=%u vocab=%u ids=%u,%u,%u,%u prompt_len=%u layers=%u heap_peak_kib=%u probe_us=%llu\n", prc, out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7], out[8], @@ -252,6 +292,40 @@ void ck_infer_run(void) int ok = prc == 0; for (unsigned i = 0; i < 4; i++) ok = ok && out[2 + i] == expect_ids[i]; + + /* Generation lines: ids, per-token microseconds, decoded bytes. */ + uint32_t ntok = res.ntok <= INFER_MAX_NEW ? res.ntok : INFER_MAX_NEW; + ck_printf("infer: prefill_us=%llu prompt_len=%u", (unsigned long long)res.prefill_us, out[6]); + ck_printf("\ninfer: tokens="); + for (uint32_t i = 0; i < ntok; i++) + ck_printf("%s%u", i ? " " : "", res.tokens[i]); + ck_printf("\ninfer: tok_us="); + uint64_t sum = 0; + for (uint32_t i = 1; i < ntok; i++) { + ck_printf("%s%llu", i > 1 ? "," : "", (unsigned long long)res.tok_us[i]); + sum += res.tok_us[i]; + } + ck_printf("\ninfer: decode_tokens=%u mean_tok_us=%llu\n", ntok > 1 ? ntok - 1 : 0, + (unsigned long long)(ntok > 1 ? sum / (ntok - 1) : 0)); + uint32_t tl = res.text_len <= INFER_TEXT_BYTES ? res.text_len : INFER_TEXT_BYTES; + escape(esc, res.text, tl); + ck_printf("infer: text=%s\n", esc); + ok = ok && ntok == sizeof expect_gen / sizeof expect_gen[0]; + for (uint32_t i = 0; ok && i < ntok; i++) + ok = ok && res.tokens[i] == expect_gen[i]; + + /* Unload: the Rust unit kept nothing (its objects died at return); forget + * its heap region, then return every frame of the model and the heap. The + * free-frame count must come back to what it was before the ingest. */ + aienos_infer_heap_init(0, 0); + int f1 = ck_mm_frames_free(mpa, mpages), f2 = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); + uint64_t frames_after = ck_mm_free_frames(); + struct ck_mm_usage mu; + ck_mm_usage(&mu); + ck_printf("infer: unloaded heap_live_kib=%llu frames_free_before=%llu frames_free_after=%llu frames_returned=%llu rc=%d,%d\n", + (unsigned long long)((mu.heap_bytes - mu.heap_free) / 1024), (unsigned long long)frames_before, + (unsigned long long)frames_after, (unsigned long long)(mpages + HEAP_BYTES / PAGE), f1, f2); + ok = ok && f1 == 0 && f2 == 0 && frames_after == frames_before; ck_printf("AIENOS_CK_INFER: %s\n", ok ? "PASS" : "FAIL"); } #else diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index 16c7bc3f..89af5c3d 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -20,9 +20,13 @@ # in native/kernel/GATES.md. # # QEMU is an emulator: a PASS here qualifies nothing physical (the receipt -# says "physical": "NOT_RUN"). The child scripts take the machine quiet flag -# (~/workspace/.spark-quiet) themselves and report NOT_RUN while another run -# holds it; this script does not take it. +# says "physical": "NOT_RUN"). The child scripts serialise themselves: the +# FPU and INFER children take the QEMU gate lock (~/workspace/.qemu-gate-lock, +# exclusive create) and report NOT_RUN while another gate run holds it or +# while the machine quiet flag (~/workspace/.spark-quiet) exists, which they +# only read (no agent raises the quiet flag without Drake's approval); the +# older children still take the quiet flag themselves. This script takes +# neither. # # Usage: bash scripts/ck_gates.sh [--out DIR] # bash scripts/ck_gates.sh --self-test diff --git a/scripts/qemu_ck_fpu_test.sh b/scripts/qemu_ck_fpu_test.sh old mode 100644 new mode 100755 index 9c87a4fd..e5ab78df --- a/scripts/qemu_ck_fpu_test.sh +++ b/scripts/qemu_ck_fpu_test.sh @@ -6,7 +6,9 @@ # add) and printed its results (aienos#34 lane 0). # Last line: AIENOS_CK_FPU: PASS|FAIL|NOT_RUN (read by scripts/ck_gates.sh). # NOT_RUN (never a silent pass) when cargo, the aarch64-unknown-none Rust -# target, qemu or AAVMF is missing, or the machine quiet flag is held. +# target, qemu or AAVMF is missing, the QEMU gate lock (~/workspace/ +# .qemu-gate-lock) is held by another gate run, or the machine quiet flag +# (~/workspace/.spark-quiet) exists; this script never writes the quiet flag. # QEMU is not hardware: a PASS here qualifies nothing physical. # # FAIL when the script re-checks the serial lines itself and finds: no @@ -17,7 +19,8 @@ # # Usage: bash scripts/qemu_ck_fpu_test.sh the gate # bash scripts/qemu_ck_fpu_test.sh --self-test canned logs, no QEMU/build -# Environment: AIENOS_QEMU_TIMEOUT (180 s), AIENOS_QUIET_FLAG / AIENOS_QUIET_TAG, +# Environment: AIENOS_QEMU_TIMEOUT (180 s), AIENOS_GATE_LOCK / AIENOS_GATE_TAG, +# AIENOS_QUIET_FLAG (read only), # AIENOS_LOG_DIR, AIENOS_QEMU_VERBOSE. set -euo pipefail @@ -92,22 +95,31 @@ CARGO_TARGET_DIR="${repo_root}/target/fpu-probe" cargo build -q --release --targ --manifest-path crates/aienos-fpu-probe/Cargo.toml make -s -C native/kernel CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" CK_RUST_LIBS="${lib}" >/dev/null +# Machine-wide quiet flag: read only, never written here (Drake's rule: no +# agent raises it without approval). If someone holds it: NOT_RUN. quiet_flag="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}" -quiet_tag="${AIENOS_QUIET_TAG:-qemu_ck_fpu_test $$}" -if ! ( set -C; echo "${quiet_tag}" > "${quiet_flag}" ) 2>/dev/null; then +if [[ -e "${quiet_flag}" ]]; then echo "NOT_RUN quiet flag ${quiet_flag} is held: $(head -c 200 "${quiet_flag}" 2>/dev/null || true)" echo "${verdict_name}: NOT_RUN" exit 3 fi -own_flag=1 -release_flag() { - if [[ "${own_flag}" == 1 ]]; then - own_flag=0 - if [[ -f "${quiet_flag}" ]] && grep -qxF -- "${quiet_tag}" "${quiet_flag}"; then rm -f "${quiet_flag}"; fi +# One QEMU gate at a time: exclusive create (set -C) of the gate lock. +gate_lock="${AIENOS_GATE_LOCK:-${HOME}/workspace/.qemu-gate-lock}" +gate_tag="${AIENOS_GATE_TAG:-qemu_ck_fpu_test $$}" +if ! ( set -C; echo "${gate_tag}" > "${gate_lock}" ) 2>/dev/null; then + echo "NOT_RUN QEMU gate lock ${gate_lock} is held: $(head -c 200 "${gate_lock}" 2>/dev/null || true)" + echo "${verdict_name}: NOT_RUN" + exit 3 +fi +own_lock=1 +release_lock() { + if [[ "${own_lock}" == 1 ]]; then + own_lock=0 + if [[ -f "${gate_lock}" ]] && grep -qxF -- "${gate_tag}" "${gate_lock}"; then rm -f "${gate_lock}"; fi fi } work="$(mktemp -d)" -cleanup() { rm -rf "${work}"; release_flag; } +cleanup() { rm -rf "${work}"; release_lock; } trap cleanup EXIT mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" @@ -128,7 +140,7 @@ timeout "${AIENOS_QEMU_TIMEOUT:-180}" qemu-system-aarch64 \ qemu_status=$? set -e elapsed=$(( $(date +%s) - started )) -release_flag +release_lock tr -d '\r' <"${log}" >"${work}/serial.txt" [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial.txt" "${AIENOS_LOG_DIR}/qemu_ck_fpu_serial.log" diff --git a/scripts/qemu_ck_infer_test.sh b/scripts/qemu_ck_infer_test.sh index 54f786d9..a4958ae0 100755 --- a/scripts/qemu_ck_infer_test.sh +++ b/scripts/qemu_ck_infer_test.sh @@ -4,11 +4,17 @@ # Llama-3.2-1B-Instruct Q4_K_M GGUF (807,694,368 bytes) into its own RAM over # QEMU fw_cfg DMA, then check that the Rust crate crates/aienos-infer, called # from the general-regs-only C kernel through crates/aienos-infer-kernel, -# parsed the header, bound the model and tokenized the fixed chat prompt -# "What is the capital of France?" (aienos#34 lane 4, cut 1: no generation). +# parsed the header, bound the model, tokenized the fixed chat prompt +# "What is the capital of France?", ran prefill + greedy decode to the exact +# llama.cpp token sequence, decoded it to text containing "Paris", unloaded +# the model (every frame returned) and went on to its normal exit +# (aienos#34 lane 4 cut 1 + lane 5 cut 2). # Last line: AIENOS_CK_INFER: PASS|FAIL|NOT_RUN (read by scripts/ck_gates.sh). # NOT_RUN (never a silent pass) when the model file, cargo, the Rust target -# aarch64-unknown-none, qemu or AAVMF is missing, or the quiet flag is held. +# aarch64-unknown-none, qemu or AAVMF is missing, the QEMU gate lock +# (~/workspace/.qemu-gate-lock) is held by another gate run, or the machine +# quiet flag (~/workspace/.spark-quiet) exists. This script never creates or +# removes the quiet flag (Drake's rule: no agent raises it without approval). # QEMU is not hardware: a PASS here qualifies nothing physical. # # FAIL when the script re-checks the serial lines itself and finds: the @@ -18,17 +24,26 @@ # tensor count != 147, vocab != 128256, layers != 16, the first four prompt # ids differ from the first four of the "ids" line of # crates/aienos-infer/tests/fixtures/ref_fr.txt (128000 128006 882 128007), -# prompt length differs from that line's id count, a kernel PASS the script -# does not reproduce, a panic/fault report, no "kernel: alive", or a non-zero -# QEMU exit (PSCI reset = 0). +# prompt length differs from that line's id count, the generated ids differ +# from that fixture's "step" tokens (791 6864 315 9822 374 12366 13 128009, +# exact, no near-tie tolerance: same code path as the host test), the decoded +# text does not contain "Paris", no "infer: unloaded" line or free frames +# after the unload != before the ingest or a frame return refused, no +# per-token timing line, a kernel PASS the script does not reproduce, a +# panic/fault report, no "kernel: alive", no final report, or a non-zero +# QEMU exit (PSCI reset = 0). After the real run the script also re-checks +# the SAME serial log against a mutated expected-id list and requires that +# check to FAIL (a checker that cannot fail makes the gate FAIL). # # Usage: bash scripts/qemu_ck_infer_test.sh the gate # bash scripts/qemu_ck_infer_test.sh --negative-control corrupt the GGUF # magic; the gate checks must FAIL (rc=-2) -> prints # AIENOS_CK_INFER_NEGATIVE_CONTROL: PASS when they do # bash scripts/qemu_ck_infer_test.sh --self-test canned logs, no QEMU/build -# Environment: AIENOS_MODEL (the GGUF), AIENOS_QEMU_TIMEOUT (900 s), -# AIENOS_QUIET_FLAG / AIENOS_QUIET_TAG, AIENOS_LOG_DIR, AIENOS_QEMU_VERBOSE. +# Environment: AIENOS_MODEL (the GGUF), AIENOS_QEMU_TIMEOUT (3600 s: TCG runs +# the 25 forward passes at roughly 20-30 s each), AIENOS_GATE_LOCK / +# AIENOS_GATE_TAG, AIENOS_QUIET_FLAG (read only), AIENOS_LOG_DIR, +# AIENOS_QEMU_VERBOSE. set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -41,11 +56,12 @@ ref_file=crates/aienos-infer/tests/fixtures/ref_fr.txt pinned_sha=3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1 # Tensor count: crates/aienos-infer/tests/golden.rs:112; vocab/layers: golden.rs:61,56. want_tensors=147 want_vocab=128256 want_layers=16 +want_text=Paris -# infer_check_log FILE WANT_SIZE WANT_SHA WANT_IDS("a b c d ...") PIN(1|0): +# infer_check_log FILE WANT_SIZE WANT_SHA WANT_IDS("a b c d ...") PIN(1|0) WANT_GEN("t1 t2 ..."): # PASS/FAIL line per check; sets infer_failed=1 on failure. infer_check_log() { - local f="$1" want_size="$2" want_sha="$3" want_ids="$4" pin="$5" + local f="$1" want_size="$2" want_sha="$3" want_ids="$4" pin="$5" want_gen="$6" local line rc ids_got first4 plen ok() { echo "PASS $*"; } bad() { echo "FAIL $*"; infer_failed=1; } @@ -53,6 +69,10 @@ infer_check_log() { local re_in='^infer: ingest bytes=([0-9]+) dma_us=([0-9]+)$' local re_sha='^infer: sha256=([0-9a-f]{64}) sha_us=[0-9]+$' local re_p='^infer: probe rc=(-?[0-9]+) tensors=([0-9]+) vocab=([0-9]+) ids=([0-9]+),([0-9]+),([0-9]+),([0-9]+) prompt_len=([0-9]+) layers=([0-9]+) heap_peak_kib=([0-9]+) probe_us=[0-9]+$' + local re_tok='^infer: tokens=([0-9 ]*)$' + local re_tus='^infer: decode_tokens=([0-9]+) mean_tok_us=([0-9]+)$' + local re_txt='^infer: text=(.*)$' + local re_un='^infer: unloaded heap_live_kib=([0-9]+) frames_free_before=([0-9]+) frames_free_after=([0-9]+) frames_returned=([0-9]+) rc=(-?[0-9]+),(-?[0-9]+)$' local n sz n="$(grep -cE "${re_fw}" "${f}" || true)" if [[ "${n}" == 1 ]]; then @@ -91,25 +111,65 @@ infer_check_log() { local hp; hp="$(g 10)" (( hp > 0 && hp < 262144 )) && ok "allocator peak ${hp} KiB within the 256 MiB region" || bad "allocator peak ${hp} KiB outside (0, 262144)" fi + # Generated ids: exact match with the fixture's step tokens (EOT included). + if [[ "$(grep -cE "${re_tok}" "${f}" || true)" != 1 ]]; then + bad "exactly one well-formed infer: tokens line" + else + local got; got="$(sed -nE "s|${re_tok}|\\1|p" "${f}" | tr -s ' ' | sed 's/ *$//')" + [[ "${got}" == "${want_gen}" ]] && ok "generated ids '${got}' = llama.cpp greedy sequence" || bad "generated ids '${got}', expected '${want_gen}'" + fi + if [[ "$(grep -cE "${re_tus}" "${f}" || true)" != 1 ]]; then + bad "exactly one well-formed decode timing line" + else + line="$(grep -E "${re_tus}" "${f}")"; [[ "${line}" =~ ${re_tus} ]] + local nd="${BASH_REMATCH[1]}" mu="${BASH_REMATCH[2]}" + local want_nd=$(( $(wc -w <<<"${want_gen}") - 1 )) + [[ "${nd}" == "${want_nd}" && "${mu}" -gt 0 ]] && ok "decode timing: ${nd} forwards, mean ${mu} us per token (QEMU TCG, not hardware)" \ + || bad "decode timing line: ${nd} forwards (expected ${want_nd}), mean ${mu} us" + fi + if [[ "$(grep -cE "${re_txt}" "${f}" || true)" != 1 ]]; then + bad "exactly one infer: text line" + else + line="$(grep -E "${re_txt}" "${f}")" + grep -qF -- "${want_text}" <<<"${line#infer: text=}" && ok "decoded text contains '${want_text}': ${line#infer: text=}" || bad "decoded text lacks '${want_text}': ${line#infer: text=}" + fi + if [[ "$(grep -cE "${re_un}" "${f}" || true)" != 1 ]]; then + bad "exactly one well-formed infer: unloaded line" + else + line="$(grep -E "${re_un}" "${f}")"; [[ "${line}" =~ ${re_un} ]] + local fb="${BASH_REMATCH[2]}" fa="${BASH_REMATCH[3]}" r1="${BASH_REMATCH[5]}" r2="${BASH_REMATCH[6]}" + [[ "${fb}" == "${fa}" && "${fb}" -gt 0 && "${r1}" == 0 && "${r2}" == 0 ]] \ + && ok "unload returned every frame (free frames ${fa} = ${fb} before ingest), kernel heap live ${BASH_REMATCH[1]} KiB" \ + || bad "unload: free frames after ${fa} vs before ${fb}, frame-return rc ${r1},${r2}" + fi grep -qx 'AIENOS_CK_INFER: PASS' "${f}" && ok "kernel reported AIENOS_CK_INFER: PASS" || bad "kernel did not report AIENOS_CK_INFER: PASS" grep -q "kernel: alive" "${f}" && ok "kernel alive" || bad "kernel never reached kernel: alive" if grep -qE 'report_kind: (panic|fault)' "${f}"; then bad "panic or fault report"; else ok "no panic or fault"; fi grep -q '^report_kind: final' "${f}" && ok "kernel reached its final report" || bad "no final report" + # The unload line must come before the final report (unload, then the OS goes on). + if [[ "$(grep -nE "${re_un}" "${f}" | cut -d: -f1 | head -1)" -lt "$(grep -n '^report_kind: final' "${f}" | cut -d: -f1 | head -1)" ]] 2>/dev/null; then + ok "kernel continued to its final report after the unload" + else bad "unload line not before the final report"; fi } # The expected ids come from the golden reference, not from this script. read_want_ids() { sed -n 's/^ids //p' "${ref_file}" | head -1; } +read_want_gen() { awk '$1=="step"{printf "%s%s", (n++?" ":""), $3} END{print ""}' "${ref_file}"; } +# mutate_gen "a b c": the same list with the second-to-last id changed by one. +mutate_gen() { awk '{ $(NF-1) = $(NF-1) + 1; print }' <<<"$1"; } if [[ "${1:-}" == --self-test ]]; then tmp="$(mktemp -d)"; trap 'rm -rf "${tmp}"' EXIT [[ -r "${ref_file}" ]] || { echo "FAIL ${ref_file} missing"; echo "AIENOS_CK_INFER_SELF_TEST: FAIL"; exit 1; } - ids="$(read_want_ids)" + ids="$(read_want_ids)"; gen="$(read_want_gen)" [[ "$(wc -w <<<"${ids}")" == 17 && "$(awk '{print $1,$2,$3,$4}' <<<"${ids}")" == "128000 128006 882 128007" ]] \ && echo "PASS reference ids line parsed (17 ids, first four 128000 128006 882 128007)" || { echo "FAIL reference ids line"; echo "AIENOS_CK_INFER_SELF_TEST: FAIL"; exit 1; } + [[ "${gen}" == "791 6864 315 9822 374 12366 13 128009" ]] \ + && echo "PASS reference step tokens parsed (${gen})" || { echo "FAIL reference step tokens '${gen}'"; echo "AIENOS_CK_INFER_SELF_TEST: FAIL"; exit 1; } sz=807694368 - good() { printf 'kernel: alive\ninfer: fw_cfg base=0x9020000 dma=yes file=opt/aienos/model size=%s\ninfer: ingest bytes=%s dma_us=42340\ninfer: sha256=%s sha_us=8568801\ninfer: probe rc=0 tensors=147 vocab=128256 ids=128000,128006,882,128007 prompt_len=17 layers=16 heap_peak_kib=24695 probe_us=1116277\nAIENOS_CK_INFER: PASS\nreport_kind: final\n' "${sz}" "${sz}" "${pinned_sha}"; } + good() { printf 'kernel: alive\ninfer: fw_cfg base=0x9020000 dma=yes file=opt/aienos/model size=%s\ninfer: ingest bytes=%s dma_us=42340\ninfer: sha256=%s sha_us=8568801\ninfer: probe rc=0 tensors=147 vocab=128256 ids=128000,128006,882,128007 prompt_len=17 layers=16 heap_peak_kib=24695 probe_us=1116277\ninfer: prefill_us=400000000 prompt_len=17\ninfer: tokens=791 6864 315 9822 374 12366 13 128009\ninfer: tok_us=23000000,23000000,23000000,23000000,23000000,23000000,23000000\ninfer: decode_tokens=7 mean_tok_us=23000000\ninfer: text=The capital of France is Paris.\ninfer: unloaded heap_live_kib=1234 frames_free_before=900000 frames_free_after=900000 frames_returned=262705 rc=0,0\nAIENOS_CK_INFER: PASS\nreport_kind: final\n' "${sz}" "${sz}" "${pinned_sha}"; } st=0 - chk() { infer_failed=0; out="$(infer_check_log "$3" "${sz}" "${pinned_sha}" "${ids}" 1)"; grep -q '^FAIL' <<<"${out}" && infer_failed=1 + chk() { infer_failed=0; out="$(infer_check_log "$3" "${sz}" "${pinned_sha}" "${ids}" 1 "${gen}")"; grep -q '^FAIL' <<<"${out}" && infer_failed=1 if [[ "$2" == pass && ${infer_failed} == 0 ]] || [[ "$2" == fail && ${infer_failed} == 1 && -n "$4" ]] && { [[ "$2" == pass ]] || grep -q "^FAIL.*$4" <<<"${out}"; }; then echo "PASS self-test $1"; else echo "FAIL self-test $1"; st=1; fi; } good >"${tmp}/g"; chk good pass "${tmp}/g" sed 's/rc=0 /rc=-2 /' "${tmp}/g" >"${tmp}/a"; chk bad-header-rc fail "${tmp}/a" "probe returned -2" @@ -117,7 +177,7 @@ if [[ "${1:-}" == --self-test ]]; then sed 's/vocab=128256/vocab=128255/' "${tmp}/g" >"${tmp}/c"; chk wrong-vocab fail "${tmp}/c" "vocab size 128255" sed 's/ids=128000,/ids=128001,/' "${tmp}/g" >"${tmp}/d"; chk wrong-id0 fail "${tmp}/d" "first four prompt ids" sed 's/,128007 prompt_len/,128008 prompt_len/' "${tmp}/g" >"${tmp}/e"; chk wrong-id3 fail "${tmp}/e" "first four prompt ids" - sed 's/prompt_len=17/prompt_len=16/' "${tmp}/g" >"${tmp}/f"; chk wrong-prompt-len fail "${tmp}/f" "prompt length 16" + sed 's/prompt_len=17 layers/prompt_len=16 layers/' "${tmp}/g" >"${tmp}/f"; chk wrong-prompt-len fail "${tmp}/f" "prompt length 16" sed 's/layers=16/layers=15/' "${tmp}/g" >"${tmp}/h"; chk wrong-layers fail "${tmp}/h" "layers 15" sed 's/ingest bytes=807694368/ingest bytes=807694367/' "${tmp}/g" >"${tmp}/i"; chk short-ingest fail "${tmp}/i" "kernel ingested" sed 's/size=807694368/size=807694367/' "${tmp}/g" >"${tmp}/i2"; chk wrong-fwcfg-size fail "${tmp}/i2" "fw_cfg file size" @@ -125,7 +185,7 @@ if [[ "${1:-}" == --self-test ]]; then sed 's/heap_peak_kib=24695/heap_peak_kib=0/' "${tmp}/g" >"${tmp}/k"; chk zero-heap fail "${tmp}/k" "allocator peak" # a log whose sha equals the host value but is not the pinned model hash sed "s|${pinned_sha}|0${pinned_sha:1}|" "${tmp}/g" >"${tmp}/g2" - out="$(infer_check_log "${tmp}/g2" "${sz}" "0${pinned_sha:1}" "${ids}" 1)" + out="$(infer_check_log "${tmp}/g2" "${sz}" "0${pinned_sha:1}" "${ids}" 1 "${gen}")" grep -q '^FAIL SHA-256 is not the pinned' <<<"${out}" && ! grep -q '^FAIL kernel SHA-256' <<<"${out}" \ && echo "PASS self-test not-the-pinned-model" || { echo "FAIL self-test not-the-pinned-model"; st=1; } grep -v '^AIENOS_CK_INFER' "${tmp}/g" >"${tmp}/l"; chk no-kernel-verdict fail "${tmp}/l" "kernel did not report" @@ -134,6 +194,24 @@ if [[ "${1:-}" == --self-test ]]; then { cat "${tmp}/g"; echo "report_kind: fault"; } >"${tmp}/o"; chk fault fail "${tmp}/o" "panic or fault" grep -v '^report_kind: final' "${tmp}/g" >"${tmp}/p"; chk no-final fail "${tmp}/p" "no final report" { cat "${tmp}/g"; grep '^infer: probe' "${tmp}/g"; } >"${tmp}/q"; chk two-probe-lines fail "${tmp}/q" "infer: probe line" + # cut 2: generation, text, timing, unload + sed 's/tokens=791 6864 315 9822 374 12366 13 128009/tokens=791 6864 315 9822 374 12367 13 128009/' "${tmp}/g" >"${tmp}/r"; chk wrong-token fail "${tmp}/r" "generated ids" + sed 's/ 13 128009$/ 13/' "${tmp}/g" >"${tmp}/s"; chk short-tokens fail "${tmp}/s" "generated ids" + sed 's/tokens=791 6864/tokens=6864 791/' "${tmp}/g" >"${tmp}/s2"; chk swapped-tokens fail "${tmp}/s2" "generated ids" + grep -v '^infer: tokens=' "${tmp}/g" >"${tmp}/t"; chk no-tokens-line fail "${tmp}/t" "infer: tokens line" + sed 's/France is Paris\./France is Lyon./' "${tmp}/g" >"${tmp}/u"; chk missing-paris fail "${tmp}/u" "decoded text lacks" + grep -v '^infer: text=' "${tmp}/g" >"${tmp}/v"; chk no-text-line fail "${tmp}/v" "infer: text line" + grep -v '^infer: unloaded' "${tmp}/g" >"${tmp}/w"; chk no-unload-line fail "${tmp}/w" "infer: unloaded line" + sed 's/frames_free_after=900000/frames_free_after=899999/' "${tmp}/g" >"${tmp}/x"; chk frames-leaked fail "${tmp}/x" "unload: free frames" + sed 's/rc=0,0$/rc=0,-1/' "${tmp}/g" >"${tmp}/y"; chk frame-return-refused fail "${tmp}/y" "unload: free frames" + sed 's/decode_tokens=7 mean_tok_us=23000000/decode_tokens=6 mean_tok_us=23000000/' "${tmp}/g" >"${tmp}/z"; chk wrong-decode-count fail "${tmp}/z" "decode timing line" + sed 's/mean_tok_us=23000000/mean_tok_us=0/' "${tmp}/g" >"${tmp}/z2"; chk zero-tok-time fail "${tmp}/z2" "decode timing line" + grep -v '^infer: decode_tokens=' "${tmp}/g" >"${tmp}/z3"; chk no-timing-line fail "${tmp}/z3" "decode timing line" + # unload line after the final report: the OS did not continue after the unload + { grep -v '^infer: unloaded' "${tmp}/g"; grep '^infer: unloaded' "${tmp}/g"; } >"${tmp}/z4"; chk unload-after-final fail "${tmp}/z4" "not before the final report" + # the mutated expected list must make the good log FAIL (used as the live control) + infer_failed=0; out="$(infer_check_log "${tmp}/g" "${sz}" "${pinned_sha}" "${ids}" 1 "$(mutate_gen "${gen}")")" + grep -q '^FAIL generated ids' <<<"${out}" && echo "PASS self-test mutated-expected-list" || { echo "FAIL self-test mutated-expected-list"; st=1; } [[ ${st} == 0 ]] && { echo "AIENOS_CK_INFER_SELF_TEST: PASS"; exit 0; } echo "AIENOS_CK_INFER_SELF_TEST: FAIL"; exit 1 fi @@ -164,22 +242,31 @@ CARGO_TARGET_DIR="${repo_root}/target/infer-kernel" cargo build -q --release --t --manifest-path crates/aienos-infer-kernel/Cargo.toml make -s -C native/kernel CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" CK_INFER_LIB="${lib}" >/dev/null +# Machine-wide quiet flag: read only, never written here. If someone holds +# it, a CPU-heavy TCG run would disturb their measurement: NOT_RUN. quiet_flag="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}" -quiet_tag="${AIENOS_QUIET_TAG:-qemu_ck_infer_test $$}" -if ! ( set -C; echo "${quiet_tag}" > "${quiet_flag}" ) 2>/dev/null; then +if [[ -e "${quiet_flag}" ]]; then echo "NOT_RUN quiet flag ${quiet_flag} is held: $(head -c 200 "${quiet_flag}" 2>/dev/null || true)" echo "${verdict_name}: NOT_RUN" exit 3 fi -own_flag=1 -release_flag() { - if [[ "${own_flag}" == 1 ]]; then - own_flag=0 - if [[ -f "${quiet_flag}" ]] && grep -qxF -- "${quiet_tag}" "${quiet_flag}"; then rm -f "${quiet_flag}"; fi +# One QEMU gate at a time: exclusive create (set -C) of the gate lock. +gate_lock="${AIENOS_GATE_LOCK:-${HOME}/workspace/.qemu-gate-lock}" +gate_tag="${AIENOS_GATE_TAG:-qemu_ck_infer_test $$}" +if ! ( set -C; echo "${gate_tag}" > "${gate_lock}" ) 2>/dev/null; then + echo "NOT_RUN QEMU gate lock ${gate_lock} is held: $(head -c 200 "${gate_lock}" 2>/dev/null || true)" + echo "${verdict_name}: NOT_RUN" + exit 3 +fi +own_lock=1 +release_lock() { + if [[ "${own_lock}" == 1 ]]; then + own_lock=0 + if [[ -f "${gate_lock}" ]] && grep -qxF -- "${gate_tag}" "${gate_lock}"; then rm -f "${gate_lock}"; fi fi } work="$(mktemp -d)" -cleanup() { rm -rf "${work}"; release_flag; } +cleanup() { rm -rf "${work}"; release_lock; } trap cleanup EXIT use_model="${model}" @@ -193,6 +280,7 @@ fi want_size="$(stat -c %s "${use_model}")" want_sha="$(sha256sum "${use_model}" | cut -d' ' -f1)" want_ids="$(read_want_ids)" +want_gen="$(read_want_gen)" mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" @@ -202,7 +290,7 @@ log="${work}/serial.log" started=$(date +%s) set +e -timeout "${AIENOS_QEMU_TIMEOUT:-900}" qemu-system-aarch64 \ +timeout "${AIENOS_QEMU_TIMEOUT:-3600}" qemu-system-aarch64 \ -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 2 -m 4096 \ -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ -drive if=pflash,format=raw,file="${work}/vars.fd" \ @@ -214,14 +302,14 @@ timeout "${AIENOS_QEMU_TIMEOUT:-900}" qemu-system-aarch64 \ qemu_status=$? set -e elapsed=$(( $(date +%s) - started )) -release_flag +release_lock tr -d '\r' <"${log}" >"${work}/serial.txt" [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial.txt" "${AIENOS_LOG_DIR}/qemu_ck_infer_serial.log" echo "qemu exit ${qemu_status} after ${elapsed} s (commit ${commit:0:12})" infer_failed=0 -results="$(infer_check_log "${work}/serial.txt" "${want_size}" "${want_sha}" "${want_ids}" "$(( 1 - negctl ))")" || true +results="$(infer_check_log "${work}/serial.txt" "${want_size}" "${want_sha}" "${want_ids}" "$(( 1 - negctl ))" "${want_gen}")" || true grep -q '^FAIL' <<<"${results}" && infer_failed=1 printf '%s\n' "${results}" if [[ "${qemu_status}" == 0 ]]; then echo "PASS QEMU exit 0 (PSCI reset)"; else echo "FAIL QEMU exit ${qemu_status}"; infer_failed=1; fi @@ -234,6 +322,13 @@ if [[ ${negctl} == 1 ]]; then fi echo "AIENOS_CK_INFER_NEGATIVE_CONTROL: FAIL (corrupt magic was not caught as probe rc=-2)"; exit 1 fi +# Live control on the same serial log: a mutated expected-id list must FAIL. +mut="$(infer_check_log "${work}/serial.txt" "${want_size}" "${want_sha}" "${want_ids}" 1 "$(mutate_gen "${want_gen}")")" || true +if grep -q '^FAIL generated ids' <<<"${mut}"; then + echo "PASS control: mutated expected ids ($(mutate_gen "${want_gen}")) make the token check FAIL" +else + echo "FAIL control: the token check did not FAIL against a mutated expected list"; infer_failed=1 +fi if [[ "${infer_failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then echo "---- serial console ----"; cat "${work}/serial.txt" fi