aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#250 (code only)
Apply it
git checkout -b patch-56bc83e92b86d990 4a375119f0f3479c7db7f179827ce558eed862b0 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/56bc83e92b86d990.patch | git am
Provenance
github-import 1
aien-dev/aienux
250
0975ea13352d83c9618ffdc75e1c3b32e4cb0ef7
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":250,"url":"https://github.com/aien-dev/aienux/pull/250","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:03Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.github/workflows/ck-kernel.yml b/.github/workflows/ck-kernel.yml index 750531c1..5b47ba3d 100644 --- a/.github/workflows/ck-kernel.yml +++ b/.github/workflows/ck-kernel.yml @@ -33,6 +33,7 @@ on: - 'scripts/ck_gates.sh' - 'scripts/qemu_ck_*.sh' - 'crates/aienos-fpu-probe/**' + - 'crates/aienos-infer-kernel/**' - 'scripts/lib_ck_m1_checks.sh' - '.github/workflows/ck-kernel.yml' pull_request: @@ -42,6 +43,7 @@ on: - 'scripts/ck_gates.sh' - 'scripts/qemu_ck_*.sh' - 'crates/aienos-fpu-probe/**' + - 'crates/aienos-infer-kernel/**' - 'scripts/lib_ck_m1_checks.sh' - '.github/workflows/ck-kernel.yml' @@ -98,11 +100,11 @@ jobs: mkdir -p "${RUNNER_TEMP}/ck-receipt/logs" cp -r /tmp/ck-gates-work.*/logs/* "${RUNNER_TEMP}/ck-receipt/logs/" 2>/dev/null || true [ "${rc}" = 0 ] || exit 1 - # FPU is not required: it needs the Rust target aarch64-unknown-none, which this + # 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). # 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" {print $1}') + required=$(sed -n "/^CK_GATE_TABLE='/,/^'/p" scripts/ck_gates.sh | awk -F'|' 'NF==3 && $2!="missing" && $1!="FPU" && $1!="INFER" {print $1}') [ -n "${required}" ] || { echo "could not read the gate table"; exit 1; } fail=0 for g in ${required}; do diff --git a/crates/aienos-infer-kernel/Cargo.lock b/crates/aienos-infer-kernel/Cargo.lock new file mode 100644 index 00000000..33a317fc --- /dev/null +++ b/crates/aienos-infer-kernel/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aienos-infer" +version = "0.1.0" + +[[package]] +name = "aienos-infer-kernel" +version = "0.1.0" +dependencies = [ + "aienos-infer", +] diff --git a/crates/aienos-infer-kernel/Cargo.toml b/crates/aienos-infer-kernel/Cargo.toml new file mode 100644 index 00000000..ba11cd04 --- /dev/null +++ b/crates/aienos-infer-kernel/Cargo.toml @@ -0,0 +1,25 @@ +# Standalone (not a member of the host workspace): built only for +# aarch64-unknown-none and linked into the C kernel image (CK_INFER_LIB). +[package] +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)." + +[lib] +crate-type = ["staticlib"] + +[dependencies] +aienos-infer = { path = "../aienos-infer" } + +[workspace] + +[profile.release] +panic = "abort" +opt-level = 2 +lto = false +codegen-units = 1 + +[profile.dev] +panic = "abort" diff --git a/crates/aienos-infer-kernel/src/lib.rs b/crates/aienos-infer-kernel/src/lib.rs new file mode 100644 index 00000000..cc348381 --- /dev/null +++ b/crates/aienos-infer-kernel/src/lib.rs @@ -0,0 +1,187 @@ +//! Kernel-side entry for native inference (aienos#34 lane 4, cut 1). +//! +//! 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. +//! +//! 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). +#![no_std] + +extern crate alloc; + +use alloc::vec::Vec; +use core::alloc::{GlobalAlloc, Layout}; +use core::cell::UnsafeCell; +use core::slice; + +use aienos_infer::{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`. +pub const OUT_WORDS: usize = 9; + +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() -> !; +} + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + // SAFETY: plain C function with no arguments, defined by the kernel. + unsafe { aienos_infer_panic() } +} + +struct Bump { + base: UnsafeCell<usize>, + end: UnsafeCell<usize>, + next: UnsafeCell<usize>, + last: UnsafeCell<usize>, // start of the newest block, 0 if none + peak: UnsafeCell<usize>, +} + +// SAFETY: used from one core with interrupts masked (documented above). +unsafe impl Sync for Bump {} + +#[global_allocator] +static HEAP: Bump = Bump { + base: UnsafeCell::new(0), + end: UnsafeCell::new(0), + next: UnsafeCell::new(0), + last: UnsafeCell::new(0), + peak: UnsafeCell::new(0), +}; + +unsafe impl GlobalAlloc for Bump { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let next = *self.next.get(); + let start = match next.checked_add(l.align() - 1) { + Some(v) => v & !(l.align() - 1), + None => return core::ptr::null_mut(), + }; + match start.checked_add(l.size()) { + Some(e) if e <= *self.end.get() && *self.base.get() != 0 => { + *self.next.get() = e; + *self.last.get() = start; + let used = e - *self.base.get(); + if used > *self.peak.get() { + *self.peak.get() = used; + } + start as *mut u8 + } + _ => core::ptr::null_mut(), + } + } + + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + if p as usize == *self.last.get() && p as usize + l.size() == *self.next.get() { + *self.next.get() = p as usize; + *self.last.get() = 0; + } + } + + unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 { + if p as usize == *self.last.get() && p as usize + l.size() == *self.next.get() { + if let Some(e) = (p as usize).checked_add(new_size) { + if e <= *self.end.get() { + *self.next.get() = e; + let used = e - *self.base.get(); + if used > *self.peak.get() { + *self.peak.get() = used; + } + return p; + } + } + return core::ptr::null_mut(); + } + let n = self.alloc(Layout::from_size_align_unchecked(new_size, l.align())); + if !n.is_null() { + core::ptr::copy_nonoverlapping(p, n, l.size().min(new_size)); + } + n + } +} + +/// Gives the allocator its region `[base, base+len)`. Call once, before +/// `aienos_infer_probe`. +/// +/// # Safety +/// The region must be writable RAM owned by the caller for the rest of the +/// run, 16-byte aligned, and not overlap the model bytes. +#[no_mangle] +pub unsafe extern "C" fn aienos_infer_heap_init(base: usize, len: usize) { + *HEAP.base.get() = base; + *HEAP.end.get() = base + len; + *HEAP.next.get() = base; + *HEAP.last.get() = 0; + *HEAP.peak.get() = 0; +} + +/// 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 { + let g = match Gguf::parse(bytes) { + Ok(g) => g, + Err(_) => return -2, + }; + out[0] = g.tensors().len() as u32; + let model = match Model::new(&g) { + Ok(m) => m, + Err(_) => return -3, + }; + let td = match g.tokenizer() { + Ok(t) => t, + Err(_) => return -4, + }; + let tok = match Tokenizer::new(&td) { + Ok(t) => t, + Err(_) => return -5, + }; + out[1] = tok.vocab_size() as u32; + let ids: Vec<u32> = match tok.encode_chat(PROMPT) { + Ok(v) => v, + Err(_) => return -6, + }; + 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; + 0 +} + +/// 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`). +/// +/// # 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. +#[no_mangle] +pub unsafe extern "C" fn aienos_infer_probe(model: *const u8, len: u64, out: *mut u32) -> 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); + rc +} diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 5694ae6e..4461e23c 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`, and `FPU` (C-only, from `scripts/qemu_ck_fpu_test.sh`, rows 124-128; 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-134; 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 @@ -531,3 +531,32 @@ runner is not known to have the Rust target); required list in `ck-kernel.yml` s | 126 | NEON `vaddq_f32` lanes = 11,22,33,44 via `core::arch::aarch64` | FPU | QEMU PASS (hardware NOT_RUN) | | 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) + +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: +`make -C native/kernel CK_INFER_LIB=<libaienos_infer_kernel.a>` (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). + +Ingest path: QEMU fw_cfg DMA (QEMU `docs/specs/fw_cfg.rst`, "Guest-side DMA Interface", qemu 8.2.2), model passed as +`-fw_cfg name=opt/aienos/model,file=<gguf>`, QEMU `-m 4096`; frames come from `ck_mm_frames_alloc`. The fw_cfg +window is found in the ACPI DSDT (QEMU0002) as in the artifact loader. The C kernel has no virtio-blk driver, so a +disk image would need a new driver; fw_cfg DMA needed none. The byte-wise data register was not used: the DMA read +of the whole file takes ~40 ms, the kernel's SHA-256 of it ~8.6 s under TCG. FP/SIMD is enabled +(`CPACR_EL1.FPEN = 0b11`) and DAIF is masked around the Rust unit, as in `core/fpu.c`. The gate is NOT_RUN (never +a silent pass) when the model file, cargo, the `aarch64-unknown-none` target, QEMU or AAVMF is missing; not +required in CI (the runner has neither the model nor the target). + +| # | check | gate | status | +|---|---|---|---| +| 129 | kernel ingests exactly the host file's size (fw_cfg size and ingest bytes = `stat`) | INFER | QEMU PASS (hardware NOT_RUN) | +| 130 | kernel-computed SHA-256 of the ingested bytes = host `sha256sum` = pinned model hash `3f5a2242...62dcc1` | INFER | QEMU PASS (hardware NOT_RUN) | +| 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) | diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 4ec3d82b..61860736 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -158,6 +158,23 @@ $(error CK_RUST_LIBS (FP probe, QEMU gate only) cannot be combined with CK_HARDW endif CK_EXTRA_CFLAGS += -DCK_FPU_PROBE=1 endif + +# Inference ingest probe (aienos#34 lane 4): CK_INFER_LIB=<path to +# libaienos_infer_kernel.a> links that Rust no_std staticlib (aienos-infer + +# bump allocator) and compiles core/infer.c (-DCK_INFER_PROBE=1): the kernel +# ingests a GGUF from QEMU fw_cfg and calls the Rust unit. C flags stay +# -mgeneral-regs-only. QEMU gate only; not combinable with CK_RUST_LIBS (two +# Rust staticlibs would duplicate compiler_builtins) nor hardware staging. +CK_INFER_LIB ?= +ifneq ($(strip $(CK_INFER_LIB)),) +ifneq ($(strip $(CK_HARDWARE_STAGING)),) +$(error CK_INFER_LIB (inference probe, QEMU gate only) cannot be combined with CK_HARDWARE_STAGING) +endif +ifneq ($(strip $(CK_RUST_LIBS)),) +$(error CK_INFER_LIB and CK_RUST_LIBS cannot be combined: two Rust staticlibs duplicate compiler_builtins) +endif +CK_EXTRA_CFLAGS += -DCK_INFER_PROBE=1 +endif ifneq ($(strip $(CK_QEMU_UNSAFE_DMA)),) ifneq ($(strip $(CK_HARDWARE_STAGING)),) $(error CK_QEMU_UNSAFE_DMA (unconfined DMA, QEMU debug only) cannot be combined with CK_HARDWARE_STAGING: no SMMU confinement means no DMA) @@ -346,7 +363,7 @@ CORE_C := $(BOOT)/efi_main.c \ $(KDIR)/core/acpi.c $(KDIR)/core/console.c $(KDIR)/core/fmt.c \ $(KDIR)/core/kmain.c $(KDIR)/core/handoff_check.c $(KDIR)/core/libc_min.c $(KDIR)/core/report.c \ $(KDIR)/core/smmu.c $(KDIR)/core/smmu_svc.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c \ - $(KDIR)/core/fpu.c $(KDIR)/core/m3.c $(KDIR)/core/entropy.c $(KDIR)/arch/rndr.c $(KDIR)/core/smp.c \ + $(KDIR)/core/fpu.c $(KDIR)/core/infer.c $(KDIR)/core/m3.c $(KDIR)/core/entropy.c $(KDIR)/arch/rndr.c $(KDIR)/core/smp.c \ $(KDIR)/mm/frames.c $(KDIR)/mm/heap.c $(KDIR)/mm/mmu.c $(KDIR)/mm/pt.c # P2 sealed-artifact loader: format/admission/receipt (artifact/), SHA-256 # (argus), Ed25519/SHA-512 (sig). Built into the core so every image carries @@ -451,6 +468,9 @@ ART_HDRS := $(wildcard $(NATIVE)/sig/*.h $(NATIVE)/argus/sha256.h $(KDIR)/svc/co $(ART_OBJS): KCFLAGS += $(ART_INC) $(ART_OBJS): $(ART_HDRS) +# core/infer.c uses the in-core SHA-256 (argus) to prove the ingested bytes. +$(KOBJ)/kernel/core/infer.o: KCFLAGS += -I$(NATIVE)/argus + $(OUT)/trust.stamp: FORCE @mkdir -p $(OUT) @echo '$(ART_TRUST_FLAGS)' | cmp -s - $@ || echo '$(ART_TRUST_FLAGS)' > $@ @@ -473,8 +493,12 @@ $(foreach s,$(STAGE_SRCS),$(eval $(call stage_rule,$(s)))) # fwcfg_check(elf): a default image (no CK_TEST_FWCFG_ARTIFACTS) must carry no # fw_cfg artifact code or strings; a test image must carry its announcement. +# The inference probe image (CK_INFER_LIB, aienos#34 lane 4) reads its model over +# fw_cfg by design: it must carry its own TEST-ONLY announcement instead. define fwcfg_check - @if [ "$(strip $(CK_TEST_FWCFG_ARTIFACTS))" = 1 ]; then \ + @if [ -n "$(strip $(CK_INFER_LIB))" ]; then \ + grep -aqF "TEST-ONLY QEMU fw_cfg model ingest" $(1) || { echo "inference probe image lacks its TEST-ONLY fw_cfg announcement"; rm -f $(1); exit 1; }; \ + elif [ "$(strip $(CK_TEST_FWCFG_ARTIFACTS))" = 1 ]; then \ grep -aqF "TEST-ONLY QEMU fw_cfg side channel" $(1) || { echo "test fw_cfg image lacks its TEST-ONLY announcement"; rm -f $(1); exit 1; }; \ else \ s=$$(grep -aoE "opt/aienos/artifacts|fw_cfg|QEMU0002" $(1) | sort -u | tr "\n" " "); \ @@ -561,14 +585,14 @@ define pe_image endef $(ELF): $(CORE_OBJS) $(BOOT)/image.ld - $(call link_image,$@,$(CORE_OBJS) $(CK_RUST_LIBS)) + $(call link_image,$@,$(CORE_OBJS) $(CK_RUST_LIBS) $(CK_INFER_LIB)) @s=$$($(KNM) $@ | grep -E ' [TtDdBbWwVv] ck_stage_(devices|security|store|quiesce)$$' || true); \ if [ -n "$$s" ]; then echo "core image defines stage symbols: $$s"; rm -f $@; exit 1; fi $(call fwcfg_check,$@) $(call smp_check,$@) $(FULL_ELF): $(CORE_OBJS) $(STAGE_BUILT) $(BOOT)/image.ld - $(call link_image,$@,$(CORE_OBJS) $(STAGE_LINK) $(CK_RUST_LIBS)) + $(call link_image,$@,$(CORE_OBJS) $(STAGE_LINK) $(CK_RUST_LIBS) $(CK_INFER_LIB)) @for s in ck_stage_devices ck_stage_security ck_stage_store ck_stage_quiesce ck_stage_disk_artifacts; do \ $(KNM) $@ | grep -qE " [TW] $$s$$" || { echo "full image lacks $$s"; rm -f $@; exit 1; }; done $(call fwcfg_check,$@) diff --git a/native/kernel/core/ck_internal.h b/native/kernel/core/ck_internal.h index b8175e14..333ec572 100644 --- a/native/kernel/core/ck_internal.h +++ b/native/kernel/core/ck_internal.h @@ -104,5 +104,6 @@ uint64_t ck_entropy_retries(void); * the smp: lines scripts/qemu_ck_smp_test.sh judges; never panics. */ void ck_smp_run(void); void ck_fpu_run(void); /* core/fpu.c: probe build only (CK_RUST_LIBS), else a no-op */ +void ck_infer_run(void); /* core/infer.c: probe build only (CK_INFER_LIB), else a no-op */ #endif diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c new file mode 100644 index 00000000..c26c4784 --- /dev/null +++ b/native/kernel/core/infer.c @@ -0,0 +1,259 @@ +/* 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). + * Only compiled into the probe build: Makefile CK_INFER_LIB=<.a> adds + * -DCK_INFER_PROBE=1; the default image carries none of this. + * + * Ingest path (the smallest that works today): QEMU fw_cfg. The C kernel has + * no virtio-blk driver (only NVMe store, virtio-net) and the C boot stub reads + * no files, but fw_cfg is already used by the TEST-ONLY artifact source + * (artifact_loader.c). The traditional byte-at-a-time data register would need + * ~8e8 trapped MMIO reads under TCG, so this uses the fw_cfg DMA interface: + * QEMU docs/specs/fw_cfg.rst, "Guest-side DMA Interface" (qemu 8.2.2, + * /usr/share/doc/qemu-system-data/specs/fw_cfg.rst.gz): feature bit 1 of key + * 0x0001 and the DMA address register (QEMU CFG signature) at Base + 16 (8 + * bytes, big endian); a FWCfgDmaAccess{control,length,address} in RAM, all + * big endian, control bit 1 = read, bit 3 = select (index in the upper 16 + * bits), bit 0 = error; control reads back 0 when done. The model is passed as + * -fw_cfg name=opt/aienos/model,file=<gguf>. QEMU only: a PASS says nothing + * about hardware. + * + * The fw_cfg MMIO base comes from the ACPI DSDT (device QEMU0002), as in the + * artifact loader; nothing is assumed. + * + * FP/SIMD: the Rust unit uses them (CPACR_EL1.FPEN = 0b11 here); it runs with + * every exception masked (DAIF) because the kernel saves no FP state, exactly + * as core/fpu.c does. */ +#include <stdint.h> +#include <stddef.h> + +#include "arch.h" +#include "ck_internal.h" + +#ifdef CK_INFER_PROBE +#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); + +#define CPACR_FPEN_SHIFT 20 +#define PAGE 4096ull +#define HEAP_BYTES (256ull << 20) /* bump-allocator region for the Rust unit */ +#define DMA_CHUNK (64ull << 20) /* fw_cfg DMA length is 32 bit; read in chunks */ +#define MODEL_FILE "opt/aienos/model" + +/* 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}; + +static volatile uint8_t *fwcfg; + +static uint32_t be32(const uint8_t *b) +{ + return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | (uint32_t)b[2] << 8 | b[3]; +} +static uint32_t le32(const uint8_t *b) +{ + return (uint32_t)b[3] << 24 | (uint32_t)b[2] << 16 | (uint32_t)b[1] << 8 | b[0]; +} +static uint64_t le64(const uint8_t *b) { return (uint64_t)le32(b + 4) << 32 | le32(b); } +static uint32_t bswap32(uint32_t v) { return __builtin_bswap32(v); } + +static void fw_select(uint16_t sel) +{ + *(volatile uint16_t *)(fwcfg + 8) = (uint16_t)((sel >> 8) | (sel << 8)); /* big endian */ + __asm__ volatile("dsb sy" ::: "memory"); +} +static void fw_read(uint8_t *out, uint64_t n) +{ + for (uint64_t i = 0; i < n; i++) + out[i] = fwcfg[0]; +} + +/* The fw_cfg MMIO window from the DSDT (device _HID "QEMU0002", then its + * _CRS Memory32Fixed descriptor 0x86 length 9). Same walk as the artifact + * loader's TEST-ONLY source. 0 if absent. */ +static uint64_t fwcfg_from_dsdt(const char **why) +{ + const uint8_t *fadt = ck_acpi_find("FACP"); + if (!fadt) { + *why = "no FADT"; + return 0; + } + uint32_t flen = le32(fadt + 4); + uint64_t dsdt = 0; + if (flen >= 148) + dsdt = le64(fadt + 140); + if (!dsdt && flen >= 44) + dsdt = le32(fadt + 40); + if (!dsdt || !ck_mm_mapped(dsdt, 36)) { + *why = "DSDT not mapped"; + return 0; + } + const uint8_t *d = (const uint8_t *)(uintptr_t)dsdt; + uint32_t len = le32(d + 4); + if (len < 36 || memcmp(d, "DSDT", 4) || !ck_mm_mapped(dsdt, len)) { + *why = "DSDT not mapped"; + return 0; + } + for (uint32_t i = 36; i + 9 <= len; i++) { + if (memcmp(d + i, "QEMU0002", 8)) + continue; + for (uint32_t j = i + 8; j + 12 <= len && j < i + 8 + 96; j++) + if (d[j] == 0x86 && d[j + 1] == 0x09 && d[j + 2] == 0x00) { + uint64_t base = le32(d + j + 4), size = le32(d + j + 8); + if (base && size >= 0x18) + return base; + } + } + *why = "no QEMU0002 device"; + return 0; +} + +/* File directory (key 0x0019): selector and size of MODEL_FILE, -1 if absent. */ +static int fw_find(uint16_t *sel, uint32_t *size) +{ + uint8_t b[64]; + fw_select(0x19); + fw_read(b, 4); + uint32_t n = be32(b); + for (uint32_t i = 0; i < n && i < 4096; i++) { + fw_read(b, 64); + b[63] = 0; + if (!memcmp(b + 8, MODEL_FILE, sizeof MODEL_FILE)) { + *sel = (uint16_t)(b[4] << 8 | b[5]); + *size = be32(b); + return 0; + } + } + return -1; +} + +struct fw_dma { + uint32_t control, length; + uint64_t address; +} __attribute__((aligned(16))); +static volatile struct fw_dma dma_desc; + +/* One DMA read of len bytes into pa. sel >= 0 selects that item first (offset + * 0); sel < 0 continues at the current offset. 0 on success. */ +static int fw_dma_read(int sel, uint64_t pa, uint32_t len) +{ + uint32_t ctl = 2u /* read */ | (sel >= 0 ? (8u | ((uint32_t)sel << 16)) : 0u); + dma_desc.control = bswap32(ctl); + dma_desc.length = bswap32(len); + dma_desc.address = __builtin_bswap64(pa); + __asm__ volatile("dsb sy" ::: "memory"); + *(volatile uint64_t *)(fwcfg + 16) = __builtin_bswap64((uint64_t)(uintptr_t)&dma_desc); + __asm__ volatile("dsb sy" ::: "memory"); + for (uint64_t spin = 0; spin < 1000000000ull; spin++) { + uint32_t c = bswap32(dma_desc.control); + if (c & 1u) + return -1; /* error bit */ + if (c == 0) + return 0; + } + return -2; +} + +/* The Rust unit's panic handler lands here: report and stop, never return. */ +__attribute__((noreturn)) void aienos_infer_panic(void) { ck_panic("infer: Rust unit panicked or ran out of heap"); } + +static void hex(char *out, const uint8_t *b, unsigned n) +{ + static const char d[] = "0123456789abcdef"; + for (unsigned i = 0; i < n; i++) { + out[2 * i] = d[b[i] >> 4]; + out[2 * i + 1] = d[b[i] & 15]; + } + out[2 * n] = 0; +} + +void ck_infer_run(void) +{ + const char *why = 0; + uint64_t base = fwcfg_from_dsdt(&why); + uint16_t sel = 0; + uint32_t size = 0; + if (base && !ck_mm_mmio_try_map(base, 0x18)) { + why = "fw_cfg window not mappable"; + base = 0; + } + if (base) { + uint8_t sig[4], feat[4]; + fwcfg = (volatile uint8_t *)(uintptr_t)base; + fw_select(0); + fw_read(sig, 4); + fw_select(1); + fw_read(feat, 4); + if (memcmp(sig, "QEMU", 4)) + why = "fw_cfg signature", base = 0; + else if (!(le32(feat) & 2u)) + why = "fw_cfg DMA interface not offered", base = 0; + else if (__builtin_bswap64(*(volatile uint64_t *)(fwcfg + 16)) != 0x51454d5520434647ull) + why = "fw_cfg DMA register signature", base = 0; + else if (fw_find(&sel, &size)) + why = "no " MODEL_FILE " fw_cfg file", base = 0; + } + if (!base) { + ck_printf("infer: ingest FAIL (%s)\nAIENOS_CK_INFER: FAIL\n", why); + return; + } + ck_puts("infer_source_mode: TEST-ONLY QEMU fw_cfg model ingest (CK_INFER_LIB=1); not the boot disk; never counts toward a PASS\n"); + ck_printf("infer: fw_cfg base=0x%llx dma=yes file=%s size=%u\n", (unsigned long long)base, + MODEL_FILE, size); + + 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", + (unsigned long long)mpages, (unsigned long long)(HEAP_BYTES / PAGE), + (unsigned long long)ck_mm_free_frames()); + return; + } + + uint64_t t0 = ck_time_us(); + int rc = 0; + for (uint64_t off = 0; off < size && !rc; off += DMA_CHUNK) { + uint64_t n = size - off < DMA_CHUNK ? size - off : DMA_CHUNK; + rc = fw_dma_read(off == 0 ? (int)sel : -1, mpa + off, (uint32_t)n); + } + uint64_t t1 = ck_time_us(); + if (rc) { + ck_printf("infer: ingest FAIL (fw_cfg DMA rc=%d)\nAIENOS_CK_INFER: FAIL\n", rc); + return; + } + ck_printf("infer: ingest bytes=%u dma_us=%llu\n", size, (unsigned long long)(t1 - t0)); + + sha256_ctx ctx; + uint8_t dg[SHA256_DIGEST_SIZE]; + char dh[2 * SHA256_DIGEST_SIZE + 1]; + sha256_init(&ctx); + sha256_update(&ctx, (const uint8_t *)(uintptr_t)mpa, size); + sha256_final(&ctx, dg); + 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}; + uint64_t v = ck_rd(cpacr_el1); + v |= 3ull << CPACR_FPEN_SHIFT; + ck_wr(cpacr_el1, v); + ck_isb(); + aienos_infer_heap_init((uintptr_t)hpa, HEAP_BYTES); + 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); + uint64_t t3 = ck_time_us(); + ck_wr(daif, daif); + + 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], + (unsigned long long)(t3 - t2)); + int ok = prc == 0; + for (unsigned i = 0; i < 4; i++) + ok = ok && out[2 + i] == expect_ids[i]; + ck_printf("AIENOS_CK_INFER: %s\n", ok ? "PASS" : "FAIL"); +} +#else +void ck_infer_run(void) {} +#endif diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c index 2d19c7a5..7382ac0d 100644 --- a/native/kernel/core/kmain.c +++ b/native/kernel/core/kmain.c @@ -141,6 +141,9 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) /* One FP/SIMD-enabled Rust unit (core/fpu.c), probe build only. */ ck_fpu_run(); + /* Ingest the GGUF over fw_cfg and call the Rust inference unit (core/infer.c), probe build only. */ + ck_infer_run(); + /* M3 isolation checks (core/m3.c), before any stage registers an IRQ. */ ck_m3_run(); diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index a65db5bf..16c7bc3f 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -7,11 +7,12 @@ # scripts/qemu_ck_net_test.sh, scripts/qemu_ck_artifact_test.sh, # scripts/qemu_ck_smp_test.sh, scripts/qemu_ck_store_crash_test.sh, # scripts/qemu_ck_disk_layout_test.sh, scripts/qemu_ck_continuity_test.sh, -# scripts/qemu_ck_recovery_test.sh, scripts/qemu_ck_fpu_test.sh), and prints +# scripts/qemu_ck_recovery_test.sh, scripts/qemu_ck_fpu_test.sh, +# scripts/qemu_ck_infer_test.sh), and prints # one line per gate: # AIENOS_CK_<gate>: PASS|FAIL|NOT_RUN [(reason)] # for M1 M3 SMMU NVME_SHUTDOWN P2_ARTIFACT M0_ROLLBACK M4_NVME M4_STORE M4_STORE_CRASH -# M4_CONTINUITY M4_RECOVERY ARGUS1_REVOKE KEYBOARD NET SMP DISK_LAYOUT FPU. Gates with no C +# M4_CONTINUITY M4_RECOVERY ARGUS1_REVOKE KEYBOARD NET SMP DISK_LAYOUT FPU INFER. Gates with no C # implementation print NOT_RUN (MISSING_IMPLEMENTATION: <reason>) and never # run anything. A missing child script, a child that reports NOT_RUN, a child # that prints no verdict line, or a PASS line contradicted by the child's exit @@ -49,6 +50,7 @@ set -uo pipefail # cont -> verdict line from scripts/qemu_ck_continuity_test.sh # recov -> verdict line from scripts/qemu_ck_recovery_test.sh # fpu -> verdict line from scripts/qemu_ck_fpu_test.sh (NOT_RUN without the Rust target) +# infer -> verdict line from scripts/qemu_ck_infer_test.sh (NOT_RUN without the model file or the Rust target) # missing -> NOT_RUN (MISSING_IMPLEMENTATION), never run, never PASS # =========================================================================== CK_GATE_TABLE=' @@ -69,8 +71,9 @@ NET|net|- SMP|smp|- DISK_LAYOUT|disk|- FPU|fpu|- +INFER|infer|- ' -CHILDREN=(boot store net artifact smp crash disk cont recov fpu) +CHILDREN=(boot store net artifact smp crash disk cont recov fpu infer) # =========================================================================== repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -118,6 +121,7 @@ set_default_children() { [cont]="${repo_root}/scripts/qemu_ck_continuity_test.sh" [recov]="${repo_root}/scripts/qemu_ck_recovery_test.sh" [fpu]="${repo_root}/scripts/qemu_ck_fpu_test.sh" + [infer]="${repo_root}/scripts/qemu_ck_infer_test.sh" ) } @@ -347,11 +351,11 @@ self_test() { } expect_missing_all() { local g - for g in P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD DISK_LAYOUT FPU; do expect "${g}" NOT_RUN; done # P2_ARTIFACT: no artifact child in A..G; M4_STORE_CRASH: no crash child in A..J and R; DISK_LAYOUT: no disk child in A..S + for g in P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD DISK_LAYOUT FPU INFER; do expect "${g}" NOT_RUN; done # P2_ARTIFACT: no artifact child in A..G; M4_STORE_CRASH: no crash child in A..J and R; DISK_LAYOUT: no disk child in A..S } scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT [NET_SCRIPT] [ARTIFACT_SCRIPT] [SMP_SCRIPT] [CRASH_SCRIPT] [DISK_SCRIPT] (absent: missing) scen="$1" - declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [fpu]="${tmp}/kids/no_fpu_child.sh") + declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [fpu]="${tmp}/kids/no_fpu_child.sh" [infer]="${tmp}/kids/no_infer_child.sh") run_children 2>/dev/null evaluate_table >"${tmp}/${scen}.out" } @@ -367,8 +371,8 @@ self_test() { "$(fake smpA 0 'PASS 3 secondary cores checked in' 'AIENOS_CK_SMP_MUTATION: FAIL' 'AIENOS_CK_SMP: PASS')" expect M1 PASS; expect M3 PASS; expect M4_NVME PASS; expect M4_STORE PASS; expect ARGUS1_REVOKE PASS; expect SMMU PASS; expect NVME_SHUTDOWN PASS; expect NET PASS; expect SMP PASS; expect_missing_all count_rows - [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/8/17" && ${overall} == NOT_ALL_GATES_PASS ]] \ - && ok "A: counts 9/0/8 of 17, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" + [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/9/18" && ${overall} == NOT_ALL_GATES_PASS ]] \ + && ok "A: counts 9/0/9 of 18, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" [[ "$(nvme_dma_mode)" == "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately" ]] && ok "A: confined DMA mode recorded from the store PASS lines" || bad "A: dma mode '$(nvme_dma_mode)'" grep -qxF "AIENOS_CK_M4_NVME: PASS (${M4_NVME_PASS_NOTE})" "${tmp}/A.out" \ && ok "A: M4_NVME PASS line carries the confined-mode note" || bad "A: M4_NVME PASS line lacks the note" @@ -376,7 +380,7 @@ self_test() { && ok "A: NET PASS line carries the QEMU slirp / SMMU fence note" || bad "A: NET PASS line lacks the note" grep -qx 'AIENOS_CK_KEYBOARD: NOT_RUN (MISSING_IMPLEMENTATION: no xHCI/USB HID keyboard driver in the C kernel)' "${tmp}/A.out" \ && ok "A: missing gate prints NOT_RUN (MISSING_IMPLEMENTATION: reason)" || bad "A: KEYBOARD line wrong" - [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 17 ]] && ok "A: exactly 17 verdict lines" || bad "A: verdict line count" + [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 18 ]] && ok "A: exactly 18 verdict lines" || bad "A: verdict line count" # B: boot FAIL; store script missing -> its three gates NOT_RUN, never PASS. scenario B "$(fake bootB 1 'FAIL kernel: alive' 'AIENOS_CK_M3: FAIL' 'AIENOS_CK_M1: FAIL')" "${tmp}/kids/does_not_exist.sh" @@ -489,10 +493,10 @@ self_test() { # Restore the clean-tree receipt as the one the checks below look at. write_receipt if command -v jq >/dev/null; then - jq -e '.physical == "NOT_RUN" and (.gates | length) == 17 and .verdict == "NOT_ALL_GATES_PASS" + jq -e '.physical == "NOT_RUN" and (.gates | length) == 18 and .verdict == "NOT_ALL_GATES_PASS" and ([.gates[] | select(.id == "M1")][0].verdict == "PASS") and ([.gates[] | select(.id == "ARGUS1_REVOKE")][0].verdict == "FAIL") - and (.children | length) == 10 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ + and (.children | length) == 11 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ && ok "receipt is valid JSON (jq) with expected fields" || bad "receipt JSON invalid or fields wrong" else echo "NOT_RUN jq not installed; JSON validity not machine-checked"; jq_skipped=1 @@ -505,18 +509,18 @@ self_test() { bad "an existing receipt was overwritten or the clash was not refused" fi - # The gate table parses: 17 rows, known sources, reasons only on missing rows. + # The gate table parses: 18 rows, known sources, reasons only on missing rows. local g s w rows=0 tbad=0 while IFS='|' read -r g s w; do [[ -n "${g}" ]] || continue rows=$((rows + 1)) case "${s}" in - boot|store|net|artifact|smp|crash|disk|cont|recov|fpu) [[ "${w}" == - ]] || tbad=1 ;; + boot|store|net|artifact|smp|crash|disk|cont|recov|fpu|infer) [[ "${w}" == - ]] || tbad=1 ;; missing) [[ -n "${w}" && "${w}" != - ]] || tbad=1 ;; *) tbad=1 ;; esac done <<<"${CK_GATE_TABLE}" - [[ ${tbad} == 0 && ${rows} == 17 ]] && ok "gate table: 17 rows well-formed" || bad "gate table malformed (${rows} rows)" + [[ ${tbad} == 0 && ${rows} == 18 ]] && ok "gate table: 18 rows well-formed" || bad "gate table malformed (${rows} rows)" # Dirty-tree refusal, end to end, on a private clone (never this tree). # Both runs stop before any child script (no QEMU). diff --git a/scripts/qemu_ck_infer_test.sh b/scripts/qemu_ck_infer_test.sh new file mode 100755 index 00000000..54f786d9 --- /dev/null +++ b/scripts/qemu_ck_infer_test.sh @@ -0,0 +1,241 @@ +#!/usr/bin/env bash +# Boot the AIENOS C kernel with the inference unit linked in (QEMU AArch64, +# UEFI/AAVMF, EL2 like Machine 1, -m 4096), let the kernel ingest the +# 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). +# 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. +# QEMU is not hardware: a PASS here qualifies nothing physical. +# +# FAIL when the script re-checks the serial lines itself and finds: the +# kernel did not ingest exactly the host file's size in bytes, the kernel's +# SHA-256 of the ingested bytes differs from the host's sha256sum (and, in the +# gate, the pinned model hash), no or several "infer: probe" lines, rc != 0, +# 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). +# +# 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. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +verdict_name=AIENOS_CK_INFER +model="${AIENOS_MODEL:-${HOME}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" +ref_file=crates/aienos-infer/tests/fixtures/ref_fr.txt +# Pinned model hash: evidence/config_a_reference_bundle.json and +# crates/aienos-infer/tests/fixtures/PROVENANCE.md. +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 + +# infer_check_log FILE WANT_SIZE WANT_SHA WANT_IDS("a b c d ...") PIN(1|0): +# 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 line rc ids_got first4 plen + ok() { echo "PASS $*"; } + bad() { echo "FAIL $*"; infer_failed=1; } + local re_fw='^infer: fw_cfg base=0x[0-9a-f]+ dma=yes file=opt/aienos/model size=([0-9]+)$' + 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 n sz + n="$(grep -cE "${re_fw}" "${f}" || true)" + if [[ "${n}" == 1 ]]; then + sz="$(sed -nE "s|${re_fw}|\\1|p" "${f}")" + [[ "${sz}" == "${want_size}" ]] && ok "fw_cfg file size ${sz} = host file size" || bad "fw_cfg file size ${sz}, host file is ${want_size}" + else bad "exactly one well-formed fw_cfg line (found ${n})"; fi + n="$(grep -cE "${re_in}" "${f}" || true)" + if [[ "${n}" == 1 ]]; then + sz="$(sed -nE "s|${re_in}|\\1|p" "${f}")" + [[ "${sz}" == "${want_size}" ]] && ok "kernel ingested ${sz} bytes = host file size" || bad "kernel ingested ${sz} bytes, host file is ${want_size}" + else bad "exactly one well-formed ingest line (found ${n})"; fi + n="$(grep -cE "${re_sha}" "${f}" || true)" + if [[ "${n}" == 1 ]]; then + sz="$(sed -nE "s|${re_sha}|\\1|p" "${f}")" + [[ "${sz}" == "${want_sha}" ]] && ok "kernel SHA-256 of the ingested bytes = host sha256sum" || bad "kernel SHA-256 ${sz} differs from host ${want_sha}" + if [[ "${pin}" == 1 ]]; then + [[ "${sz}" == "${pinned_sha}" ]] && ok "SHA-256 = pinned model hash" || bad "SHA-256 is not the pinned model hash" + fi + else bad "exactly one well-formed sha256 line (found ${n})"; fi + if [[ "$(grep -cE "${re_p}" "${f}" || true)" != 1 ]]; then + bad "exactly one well-formed infer: probe line" + else + line="$(grep -E "${re_p}" "${f}")" + local -a m; [[ "${line}" =~ ${re_p} ]]; m=("${BASH_REMATCH[@]}") + g() { echo "${m[$1]}"; } + rc="$(g 1)" + [[ "${rc}" == 0 ]] && ok "probe returned 0" || bad "probe returned ${rc}" + [[ "$(g 2)" == "${want_tensors}" ]] && ok "tensor count ${want_tensors}" || bad "tensor count $(g 2), expected ${want_tensors}" + [[ "$(g 3)" == "${want_vocab}" ]] && ok "vocab size ${want_vocab}" || bad "vocab size $(g 3), expected ${want_vocab}" + [[ "$(g 9)" == "${want_layers}" ]] && ok "layers ${want_layers}" || bad "layers $(g 9), expected ${want_layers}" + ids_got="$(g 4) $(g 5) $(g 6) $(g 7)" + first4="$(awk '{print $1,$2,$3,$4}' <<<"${want_ids}")" + [[ "${ids_got}" == "${first4}" ]] && ok "first four prompt ids ${ids_got}" || bad "first four prompt ids '${ids_got}', expected '${first4}'" + plen="$(wc -w <<<"${want_ids}")" + [[ "$(g 8)" == "${plen}" ]] && ok "prompt length ${plen} tokens" || bad "prompt length $(g 8), expected ${plen}" + 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 + 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 expected ids come from the golden reference, not from this script. +read_want_ids() { sed -n 's/^ids //p' "${ref_file}" | head -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)" + [[ "$(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; } + 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}"; } + st=0 + chk() { infer_failed=0; out="$(infer_check_log "$3" "${sz}" "${pinned_sha}" "${ids}" 1)"; 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" + sed 's/tensors=147/tensors=146/' "${tmp}/g" >"${tmp}/b"; chk wrong-tensors fail "${tmp}/b" "tensor count 146" + 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/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" + sed "s/sha256=${pinned_sha}/sha256=0${pinned_sha:1}/" "${tmp}/g" >"${tmp}/j"; chk wrong-sha fail "${tmp}/j" "kernel SHA-256" + 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)" + 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" + grep -v '^infer: probe' "${tmp}/g" >"${tmp}/m"; chk no-probe-line fail "${tmp}/m" "infer: probe line" + grep -v '^kernel: alive' "${tmp}/g" >"${tmp}/n"; chk not-alive fail "${tmp}/n" "never reached kernel: alive" + { 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" + [[ ${st} == 0 ]] && { echo "AIENOS_CK_INFER_SELF_TEST: PASS"; exit 0; } + echo "AIENOS_CK_INFER_SELF_TEST: FAIL"; exit 1 +fi + +negctl=0 +[[ "${1:-}" == --negative-control ]] && negctl=1 +if [[ ${negctl} == 1 ]]; then verdict_name=AIENOS_CK_INFER_NEGATIVE_CONTROL; fi + +notrun() { echo "NOT_RUN $*"; echo "${verdict_name}: NOT_RUN ($*)"; exit 2; } +[[ -r "${model}" ]] || notrun "model file ${model} not found" +[[ -r "${ref_file}" ]] || notrun "${ref_file} not found" +command -v qemu-system-aarch64 >/dev/null || notrun "qemu-system-aarch64 not installed" +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || notrun "AAVMF firmware not found" +command -v cargo >/dev/null || notrun "cargo not installed" +if ! rustc --print target-list 2>/dev/null | grep -qx aarch64-unknown-none \ + || ! [[ -d "$(rustc --print sysroot)/lib/rustlib/aarch64-unknown-none/lib" ]]; then + notrun "Rust target aarch64-unknown-none not installed (rustup target add aarch64-unknown-none)" +fi + +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +out="${repo_root}/target/native-kernel-infer" +lib="${repo_root}/target/infer-kernel/aarch64-unknown-none/release/libaienos_infer_kernel.a" +CARGO_TARGET_DIR="${repo_root}/target/infer-kernel" cargo build -q --release --target aarch64-unknown-none \ + --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 + +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 + 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 + fi +} +work="$(mktemp -d)" +cleanup() { rm -rf "${work}"; release_flag; } +trap cleanup EXIT + +use_model="${model}" +if [[ ${negctl} == 1 ]]; then + # Same bytes, first four (the GGUF magic "GGUF") overwritten: the header + # parser must refuse it. Host-side copy; the original is never touched. + use_model="${work}/corrupt.gguf" + cp "${model}" "${use_model}" + printf 'XXXX' | dd of="${use_model}" bs=1 count=4 conv=notrunc status=none +fi +want_size="$(stat -c %s "${use_model}")" +want_sha="$(sha256sum "${use_model}" | cut -d' ' -f1)" +want_ids="$(read_want_ids)" + +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${out}/BOOTAA64.EFI" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" +cp "${vars_fd}" "${work}/vars.fd" +log="${work}/serial.log" + +started=$(date +%s) +set +e +timeout "${AIENOS_QEMU_TIMEOUT:-900}" 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" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -fw_cfg name=opt/aienos/model,file="${use_model}" \ + -device ramfb -display none -nic none \ + -serial file:"${log}" -no-reboot +qemu_status=$? +set -e +elapsed=$(( $(date +%s) - started )) +release_flag + +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 +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 +grep -E '^infer: ' "${work}/serial.txt" || true +if [[ ${negctl} == 1 ]]; then + # The control passes only when the corrupted header is what made the gate fail. + if [[ ${infer_failed} == 1 ]] && grep -q '^infer: probe rc=-2 ' "${work}/serial.txt" \ + && grep -q '^FAIL probe returned -2' <<<"${results}" && grep -q "kernel: alive" "${work}/serial.txt"; then + echo "AIENOS_CK_INFER_NEGATIVE_CONTROL: PASS (corrupt GGUF magic -> probe rc=-2 -> gate FAIL)"; exit 0 + fi + echo "AIENOS_CK_INFER_NEGATIVE_CONTROL: FAIL (corrupt magic was not caught as probe rc=-2)"; exit 1 +fi +if [[ "${infer_failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial console ----"; cat "${work}/serial.txt" +fi +if [[ "${infer_failed}" == 0 ]]; then echo "AIENOS_CK_INFER: PASS"; exit 0; fi +echo "AIENOS_CK_INFER: FAIL"; exit 1