Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/native/kernel/core/infer.c # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / native / kernel / core / infer.c` 776 lines ยท 35010 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* infer.c -- ingest the Llama-3.2-1B GGUF into kernel RAM and call the Rust 18 * inference crate from the general-regs-only C kernel (aienos#34 lane 4, 19 * cut 1: header, model bind, prompt tokenization; aienos#34 lane 5 cut 2: 20 * prefill + greedy decode of the fixed prompt, decoded text, per-token 21 * timing, then a clean unload that returns every frame). 22 * Only compiled into the probe build: Makefile CK_INFER_LIB=<.a> adds 23 * -DCK_INFER_PROBE=1; the default image carries none of this. 24 * 25 * Ingest paths: (1) the boot disk, read by the UEFI stub through the 26 * firmware Block I/O driver before ExitBootServices and handed over in 27 * CHANDOF2 (native/boot/efi_model.c; the hardware path, lane 6); (2) QEMU 28 * fw_cfg, TEST-ONLY, when the stub found no MODEL.MAP. The C kernel has 29 * no virtio-blk driver (only NVMe store, virtio-net) and the C boot stub reads 30 * no files, but fw_cfg is already used by the TEST-ONLY artifact source 31 * (artifact_loader.c). The traditional byte-at-a-time data register would need 32 * ~8e8 trapped MMIO reads under TCG, so this uses the fw_cfg DMA interface: 33 * QEMU docs/specs/fw_cfg.rst, "Guest-side DMA Interface" (qemu 8.2.2, 34 * /usr/share/doc/qemu-system-data/specs/fw_cfg.rst.gz): feature bit 1 of key 35 * 0x0001 and the DMA address register (QEMU CFG signature) at Base + 16 (8 36 * bytes, big endian); a FWCfgDmaAccess{control,length,address} in RAM, all 37 * big endian, control bit 1 = read, bit 3 = select (index in the upper 16 38 * bits), bit 0 = error; control reads back 0 when done. The model is passed as 39 * -fw_cfg name=opt/aienos/model,file=. QEMU only: a PASS says nothing 40 * about hardware. 41 * 42 * The fw_cfg MMIO base comes from the ACPI DSDT (device QEMU0002), as in the 43 * artifact loader; nothing is assumed. 44 * 45 * FP/SIMD: the Rust unit uses them (CPACR_EL1.FPEN = 0b11 here); it runs with 46 * every exception masked (DAIF) because the kernel saves no FP state, exactly 47 * as core/fpu.c does. */ 48 #include 49 #include 50 51 #include "arch.h" 52 #include "ck_internal.h" 53 #include "cpufeat.h" 54 55 #ifdef CK_INFER_PROBE 56 #include "sha256.h" 57 #if defined(CK_INFER_DISK_ONLY) && !defined(CK_INFER_RESIDENT) && !defined(CK_PI5_INFER) 58 #error "CK_INFER_DISK_ONLY is the hardware service image (CK_SERVICE=1 + CK_INFER_LIB + CK_HARDWARE_STAGING) or the Pi one-shot image (CK_PI5_INFER) only" 59 #endif 60 61 extern void aienos_infer_heap_init(uintptr_t base, uintptr_t len); 62 /* crates/aienos-infer-kernel: record the CPU's dotprod feature (from the boot decode, 63 * core/cpufeat.c) and report whether the SDOT matvec path is then selected. */ 64 extern void aienos_infer_set_cpu_features(uint32_t dotprod); 65 extern uint32_t aienos_infer_dot_path(void); 66 67 /* Open the heap and tell the Rust unit what the CPU has. The feature comes from 68 * the kernel's own ID-register decode; the unit assumes nothing. */ 69 static void infer_heap_open(uintptr_t base, uintptr_t len) 70 { 71 aienos_infer_set_cpu_features(ck_cpufeat_boot()->dotprod); 72 aienos_infer_heap_init(base, len); 73 ck_printf("infer: dot_path=%s cpu_dotprod=%u\n", aienos_infer_dot_path() ? "sdot" : "scalar_f32", 74 ck_cpufeat_boot()->dotprod); 75 } 76 /* Mirror of crates/aienos-infer-kernel/src/lib.rs `InferResult` (#[repr(C)]). */ 77 #define INFER_MAX_NEW 16 78 #define INFER_TEXT_BYTES 256 79 struct infer_result { 80 uint32_t words[9]; 81 uint32_t ntok; 82 uint32_t tokens[INFER_MAX_NEW]; 83 uint64_t tok_us[INFER_MAX_NEW]; 84 uint64_t prefill_us; 85 uint32_t text_len; 86 uint8_t text[INFER_TEXT_BYTES]; 87 }; 88 extern int32_t aienos_infer_run(const uint8_t *model, uint64_t len, struct infer_result *out); 89 90 /* Bounded resident session (crates/aienos-infer-kernel/src/session.rs, 91 * native v1 P06): load once, accept a prompt, one step per call so the 92 * kernel can cancel between steps, decode, unload. Mirrors of SessionLimits 93 * and SessionInfo (#[repr(C)]). */ 94 struct infer_limits { 95 uint32_t kv_capacity, max_new, max_prompt_bytes, heap_reserve; 96 }; 97 struct infer_info { 98 uint32_t tensors, vocab, layers, heap_used_kib; 99 }; 100 extern int32_t aienos_infer_session_open(const uint8_t *model, uint64_t len, const struct infer_limits *l, 101 struct infer_info *info); 102 extern int32_t aienos_infer_session_prompt(const uint8_t *text, uint32_t len); 103 extern int32_t aienos_infer_session_step(uint32_t *token, uint64_t *us); 104 extern int32_t aienos_infer_session_cancel(void); 105 extern int32_t aienos_infer_session_tokens(uint32_t *out, uint32_t cap); 106 extern int32_t aienos_infer_session_prompt_ids(uint32_t *out, uint32_t cap); 107 extern int32_t aienos_infer_session_text(const uint32_t *ids, uint32_t n, uint8_t *out, uint32_t cap); 108 extern int32_t aienos_infer_session_close(void); 109 extern void aienos_infer_heap_stats(uint64_t *used, uint64_t *peak); 110 #define SESS_E_STATE (-12) 111 #define SESS_E_PROMPT_BYTES (-16) 112 #define SESS_STEP_DONE 0 113 #define SESS_STEP_PREFILL 1 114 #define SESS_STEP_TOKEN 2 115 #define SESS_STEP_LAST 3 116 117 #define CPACR_FPEN_SHIFT 20 118 #define PAGE 4096ull 119 #define HEAP_BYTES (256ull << 20) /* bump-allocator region for the Rust unit */ 120 #define PET_CHUNK (16ull << 20) /* bytes hashed between two watchdog pets */ 121 /* Pet the Pi PM watchdog (core/pi5.c, 15 s) from a long loop; no-op where there is none. */ 122 static void pet(void) 123 { 124 if (ck_pi5_stage) 125 ck_pi5_stage("infer"); 126 } 127 #ifndef CK_INFER_DISK_ONLY 128 #define DMA_CHUNK (64ull << 20) /* fw_cfg DMA length is 32 bit; read in chunks */ 129 #define MODEL_FILE "opt/aienos/model" 130 #endif 131 132 /* The prompt's expected first four ids (crates/aienos-infer/tests/fixtures/ref_fr.txt). */ 133 static const uint32_t expect_ids[4] = {128000, 128006, 882, 128007}; 134 /* The greedy reply llama.cpp produced for the same prompt ("step" lines of the 135 * same fixture): "The capital of France is Paris." then <|eot_id|>. */ 136 static const uint32_t expect_gen[8] = {791, 6864, 315, 9822, 374, 12366, 13, 128009}; 137 /* Decoded reply, escaped for one console line: printable ASCII other than 138 * backslash as is, everything else as \\xNN. 4 bytes per input byte + NUL. */ 139 static char esc[4 * INFER_TEXT_BYTES + 1]; 140 static void escape(char *out, const uint8_t *b, uint32_t n) 141 { 142 static const char d[] = "`0123456789abcdef`"; 143 for (uint32_t i = 0; i < n; i++) { 144 if (b[i] >= 0x20 && b[i] < 0x7f && b[i] != 0x5c) { 145 *out++ = (char)b[i]; 146 } else { 147 *out++ = 0x5c; 148 *out++ = 0x78; 149 *out++ = d[b[i] >> 4]; 150 *out++ = d[b[i] & 15]; 151 } 152 } 153 *out = 0; 154 } 155 156 #ifndef CK_INFER_DISK_ONLY 157 /* QEMU fw_cfg ingest (TEST-ONLY). Compiled out of the hardware service image 158 * (CK_INFER_DISK_ONLY, Makefile: CK_INFER_LIB + CK_HARDWARE_STAGING), whose 159 * only model source is the boot disk (MODEL.MAP). */ 160 static volatile uint8_t *fwcfg; 161 162 static uint32_t be32(const uint8_t *b) 163 { 164 return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | (uint32_t)b[2] << 8 | b[3]; 165 } 166 static uint32_t le32(const uint8_t *b) 167 { 168 return (uint32_t)b[3] << 24 | (uint32_t)b[2] << 16 | (uint32_t)b[1] << 8 | b[0]; 169 } 170 static uint64_t le64(const uint8_t *b) { return (uint64_t)le32(b + 4) << 32 | le32(b); } 171 static uint32_t bswap32(uint32_t v) { return __builtin_bswap32(v); } 172 173 static void fw_select(uint16_t sel) 174 { 175 *(volatile uint16_t *)(fwcfg + 8) = (uint16_t)((sel >> 8) | (sel << 8)); /* big endian */ 176 __asm__ volatile("dsb sy" ::: "memory"); 177 } 178 static void fw_read(uint8_t *out, uint64_t n) 179 { 180 for (uint64_t i = 0; i < n; i++) 181 out[i] = fwcfg[0]; 182 } 183 184 /* The fw_cfg MMIO window from the DSDT (device _HID "QEMU0002", then its 185 * _CRS Memory32Fixed descriptor 0x86 length 9). Same walk as the artifact 186 * loader's TEST-ONLY source. 0 if absent. */ 187 static uint64_t fwcfg_from_dsdt(const char **why) 188 { 189 const uint8_t *fadt = ck_acpi_find("FACP"); 190 if (!fadt) { 191 *why = "no FADT"; 192 return 0; 193 } 194 uint32_t flen = le32(fadt + 4); 195 uint64_t dsdt = 0; 196 if (flen >= 148) 197 dsdt = le64(fadt + 140); 198 if (!dsdt && flen >= 44) 199 dsdt = le32(fadt + 40); 200 if (!dsdt || !ck_mm_mapped(dsdt, 36)) { 201 *why = "DSDT not mapped"; 202 return 0; 203 } 204 const uint8_t *d = (const uint8_t *)(uintptr_t)dsdt; 205 uint32_t len = le32(d + 4); 206 if (len < 36 || memcmp(d, "DSDT", 4) || !ck_mm_mapped(dsdt, len)) { 207 *why = "DSDT not mapped"; 208 return 0; 209 } 210 for (uint32_t i = 36; i + 9 <= len; i++) { 211 if (memcmp(d + i, "QEMU0002", 8)) 212 continue; 213 for (uint32_t j = i + 8; j + 12 <= len && j < i + 8 + 96; j++) 214 if (d[j] == 0x86 && d[j + 1] == 0x09 && d[j + 2] == 0x00) { 215 uint64_t base = le32(d + j + 4), size = le32(d + j + 8); 216 if (base && size >= 0x18) 217 return base; 218 } 219 } 220 *why = "no QEMU0002 device"; 221 return 0; 222 } 223 224 /* File directory (key 0x0019): selector and size of MODEL_FILE, -1 if absent. */ 225 static int fw_find(uint16_t *sel, uint32_t *size) 226 { 227 uint8_t b[64]; 228 fw_select(0x19); 229 fw_read(b, 4); 230 uint32_t n = be32(b); 231 for (uint32_t i = 0; i < n && i < 4096; i++) { 232 fw_read(b, 64); 233 b[63] = 0; 234 if (!memcmp(b + 8, MODEL_FILE, sizeof MODEL_FILE)) { 235 *sel = (uint16_t)(b[4] << 8 | b[5]); 236 *size = be32(b); 237 return 0; 238 } 239 } 240 return -1; 241 } 242 243 struct fw_dma { 244 uint32_t control, length; 245 uint64_t address; 246 } __attribute__((aligned(16))); 247 static volatile struct fw_dma dma_desc; 248 249 /* One DMA read of len bytes into pa. sel >= 0 selects that item first (offset 250 * 0); sel < 0 continues at the current offset. 0 on success. */ 251 static int fw_dma_read(int sel, uint64_t pa, uint32_t len) 252 { 253 uint32_t ctl = 2u /* read */ | (sel >= 0 ? (8u | ((uint32_t)sel << 16)) : 0u); 254 dma_desc.control = bswap32(ctl); 255 dma_desc.length = bswap32(len); 256 dma_desc.address = __builtin_bswap64(pa); 257 __asm__ volatile("dsb sy" ::: "memory"); 258 *(volatile uint64_t *)(fwcfg + 16) = __builtin_bswap64((uint64_t)(uintptr_t)&dma_desc); 259 __asm__ volatile("dsb sy" ::: "memory"); 260 for (uint64_t spin = 0; spin < 1000000000ull; spin++) { 261 uint32_t c = bswap32(dma_desc.control); 262 if (c & 1u) 263 return -1; /* error bit */ 264 if (c == 0) 265 return 0; 266 } 267 return -2; 268 } 269 #endif /* !CK_INFER_DISK_ONLY */ 270 271 /* The Rust unit's panic handler lands here: report and stop, never return. */ 272 __attribute__((noreturn)) void aienos_infer_panic(void) { ck_panic("infer: Rust unit panicked or ran out of heap"); } 273 274 static void hex(char *out, const uint8_t *b, unsigned n) 275 { 276 static const char d[] = "`0123456789abcdef`"; 277 for (unsigned i = 0; i < n; i++) { 278 out[2 * i] = d[b[i] >> 4]; 279 out[2 * i + 1] = d[b[i] & 15]; 280 } 281 out[2 * n] = 0; 282 } 283 284 /* Session limits of the probe: a 64-position cache, 16 generated tokens, a 285 * 256-byte prompt and 64 KiB of heap kept free (every prompt costs a few 286 * KiB that the bump allocator never gives back). */ 287 #define SESS_KV 64u 288 #define SESS_MAX_NEW 16u 289 #define SESS_PROMPT_BYTES 256u 290 #define SESS_RESERVE (64u << 10) 291 292 /* One request: prompt, then steps until done or until `cancel_after` steps, 293 * then cancel. Prints one line per request. Returns 1 when the request 294 * behaved (count of produced tokens as expected, no error), 0 otherwise. 295 * `expect`/`nexpect`: the exact token list a complete reply must equal. */ 296 static int session_request(unsigned which, const char *text, unsigned cancel_after, const uint32_t *expect, 297 unsigned nexpect, const uint32_t *expect_head) 298 { 299 uint64_t t0 = ck_time_us(), used = 0, peak = 0, pre_us = 0, tok_us_sum = 0; 300 unsigned steps = 0, prefill = 0, produced = 0, last = 0; 301 int32_t ids = aienos_infer_session_prompt((const uint8_t *)text, (uint32_t)strlen(text)); 302 if (ids < 0) { 303 ck_printf("infer: session prompt=%u REFUSED rc=%d\n", which, ids); 304 return 0; 305 } 306 /* The chat template the tokenizer built: the first four prompt ids must be the golden ones (the one-shot 307 * probe checked the same four, expect_ids; the Pi image skips the probe, so the session path checks them). */ 308 int head_ok = 1; 309 if (expect_head) { 310 uint32_t head[4] = {0, 0, 0, 0}; 311 int32_t hn = aienos_infer_session_prompt_ids(head, 4); 312 head_ok = hn >= 4; 313 for (unsigned i = 0; head_ok && i < 4; i++) head_ok = head[i] == expect_head[i]; 314 ck_printf("infer: session prompt=%u prompt_head=%u,%u,%u,%u expect=%s\n", which, head[0], head[1], head[2], head[3], 315 head_ok ? "match" : "MISMATCH"); 316 } 317 int32_t rc = 0; 318 for (;;) { 319 if (cancel_after && steps == cancel_after) break; 320 uint32_t t = 0; 321 uint64_t us = 0; 322 rc = aienos_infer_session_step(&t, &us); 323 pet(); 324 if (rc < 0 || rc == SESS_STEP_DONE) break; 325 steps++; 326 if (rc == SESS_STEP_PREFILL) { prefill++; pre_us += us; continue; } 327 produced++; 328 tok_us_sum += us; 329 if (rc == SESS_STEP_LAST) { last = 1; break; } 330 } 331 static uint32_t toks[SESS_MAX_NEW]; 332 static uint8_t text_out[INFER_TEXT_BYTES]; 333 int32_t n = aienos_infer_session_tokens(toks, SESS_MAX_NEW); 334 int ok = rc >= 0 && n == (int32_t)produced; 335 if (cancel_after) { 336 int32_t c = aienos_infer_session_cancel(); 337 ok = ok && c == (int32_t)produced && steps == cancel_after; 338 /* After a cancel the next step must do nothing. */ 339 ok = ok && aienos_infer_session_step(0, 0) == SESS_STEP_DONE; 340 aienos_infer_heap_stats(&used, &peak); 341 ck_printf("infer: session prompt=%u ids=%d cancel_after_steps=%u steps=%u prefill=%u produced=%u idle_step=%s heap_used_kib=%llu rc=%d\n", 342 which, ids, cancel_after, steps, prefill, produced, "done", (unsigned long long)(used / 1024), rc); 343 return ok; 344 } 345 ok = ok && head_ok; 346 ok = ok && last && (unsigned)ids == prefill && produced == nexpect; 347 for (unsigned i = 0; ok && i < nexpect; i++) ok = ok && toks[i] == expect[i]; 348 int32_t tl = aienos_infer_session_text(toks, (uint32_t)produced, text_out, INFER_TEXT_BYTES); 349 ok = ok && tl >= 0; 350 escape(esc, text_out, tl > 0 ? (uint32_t)tl : 0); 351 aienos_infer_heap_stats(&used, &peak); 352 ck_printf("infer: session prompt=%u ids=%d steps=%u prefill=%u produced=%u last=%s prefill_us=%llu mean_tok_us=%llu tokens=", 353 which, ids, steps, prefill, produced, last ? "yes" : "no", (unsigned long long)pre_us, 354 (unsigned long long)(produced > 1 ? tok_us_sum / (produced - 1) : 0)); 355 for (unsigned i = 0; i < produced; i++) ck_printf("%s%u", i ? " " : "", toks[i]); 356 ck_printf(" text=%s heap_used_kib=%llu request_us=%llu rc=%d\n", esc, (unsigned long long)(used / 1024), 357 (unsigned long long)(ck_time_us() - t0), rc); 358 return ok; 359 } 360 361 /* The bounded session over the ingested model: open with explicit limits, 362 * a request cancelled during its prefill, the golden prompt run to its end 363 * through the step API (must equal the one-shot probe's reply), a second 364 * cancelled request after a completed one, the cheap refusals, close, and 365 * the heap region returned. Prints AIENOS_CK_INFER_SESSION: PASS|FAIL. */ 366 static void session_run(uint64_t mpa, uint64_t msize) 367 { 368 uint64_t hpa = 0, frames_before = ck_mm_free_frames(); 369 if (ck_mm_frames_alloc(HEAP_BYTES / PAGE, &hpa)) { 370 ck_printf("infer: session FAIL (no frames for the heap)\nAIENOS_CK_INFER_SESSION: FAIL\n"); 371 return; 372 } 373 infer_heap_open((uintptr_t)hpa, HEAP_BYTES); 374 uint64_t daif = ck_rd(daif); 375 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 376 377 struct infer_limits lim = { SESS_KV, SESS_MAX_NEW, SESS_PROMPT_BYTES, SESS_RESERVE }; 378 struct infer_info info = { 0, 0, 0, 0 }; 379 uint64_t t0 = ck_time_us(); 380 int32_t rc = aienos_infer_session_open((const uint8_t *)(uintptr_t)mpa, msize, &lim, &info); 381 ck_printf("infer: session open rc=%d tensors=%u vocab=%u layers=%u kv_capacity=%u max_new=%u max_prompt_bytes=%u heap_reserve_kib=%u heap_used_kib=%u open_us=%llu\n", 382 rc, info.tensors, info.vocab, info.layers, lim.kv_capacity, lim.max_new, lim.max_prompt_bytes, 383 lim.heap_reserve >> 10, info.heap_used_kib, (unsigned long long)(ck_time_us() - t0)); 384 int ok = rc == 0; 385 if (ok) { 386 /* Cheap refusals: a second open, an over-long prompt, a step with no 387 * request pending. None of them touches the model. */ 388 static char longp[SESS_PROMPT_BYTES + 2]; 389 memset(longp, 'a', sizeof longp - 1); 390 longp[sizeof longp - 1] = 0; 391 int32_t r_open = aienos_infer_session_open((const uint8_t *)(uintptr_t)mpa, msize, &lim, &info); 392 int32_t r_bytes = aienos_infer_session_prompt((const uint8_t *)longp, (uint32_t)strlen(longp)); 393 int32_t r_idle = aienos_infer_session_step(0, 0); 394 ck_printf("infer: session refusals open_twice=%d prompt_bytes=%d step_idle=%d\n", r_open, r_bytes, r_idle); 395 ok = ok && r_open == SESS_E_STATE && r_bytes == SESS_E_PROMPT_BYTES && r_idle == SESS_STEP_DONE; 396 397 ok = session_request(1, "Say hello.", 3, 0, 0, 0) && ok; 398 ok = session_request(2, "What is the capital of France?", 0, expect_gen, 399 sizeof expect_gen / sizeof expect_gen[0], expect_ids) && ok; 400 ok = session_request(3, "Say hello.", 1, 0, 0, 0) && ok; 401 } 402 uint64_t used = 0, peak = 0; 403 aienos_infer_heap_stats(&used, &peak); 404 int32_t crc = aienos_infer_session_close(); 405 ok = ok && crc == 0 && aienos_infer_session_close() == SESS_E_STATE; 406 ck_wr(daif, daif); 407 aienos_infer_heap_init(0, 0); 408 int f = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); 409 uint64_t frames_after = ck_mm_free_frames(); 410 ok = ok && f == 0 && frames_after == frames_before; 411 ck_printf("infer: session close rc=%d heap_used_kib=%llu heap_peak_kib=%llu frames_free_before=%llu frames_free_after=%llu rc=%d\n", 412 crc, (unsigned long long)(used / 1024), (unsigned long long)(peak / 1024), 413 (unsigned long long)frames_before, (unsigned long long)frames_after, f); 414 ck_printf("AIENOS_CK_INFER_SESSION: %s\n", ok ? "PASS" : "FAIL"); 415 } 416 417 #ifdef CK_INFER_RESIDENT 418 /* Resident mode (native v1 P06, CK_SERVICE images built with CK_INFER_LIB): 419 * the ingested model and one bounded session stay open from boot to the 420 * lifecycle stop order. */ 421 static struct { 422 int open; 423 uint64_t mpa, msize, mpages, hpa, frames_before; 424 } g_res; 425 426 static uint8_t g_model_sha[SHA256_DIGEST_SIZE]; /* digest of the ingested model, set by ck_infer_run before resident_open */ 427 428 const uint8_t *ck_infer_model_sha256(void) { return g_res.open ? g_model_sha : 0; } 429 430 int ck_infer_resident(void) { return g_res.open; } 431 432 static void resident_open(uint64_t mpa, uint64_t msize, uint64_t mpages, uint64_t hpa, uint64_t frames_before) 433 { 434 uint64_t v = ck_rd(cpacr_el1); 435 v |= 3ull << CPACR_FPEN_SHIFT; 436 ck_wr(cpacr_el1, v); 437 ck_isb(); 438 infer_heap_open((uintptr_t)hpa, HEAP_BYTES); 439 struct infer_limits lim = { CK_INFER_RES_KV, CK_INFER_RES_MAX_NEW, CK_INFER_RES_PROMPT_BYTES, CK_INFER_RES_RESERVE }; 440 struct infer_info info = { 0, 0, 0, 0 }; 441 uint64_t t0 = ck_time_us(), daif = ck_rd(daif); 442 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 443 int32_t rc = aienos_infer_session_open((const uint8_t *)(uintptr_t)mpa, msize, &lim, &info); 444 ck_wr(daif, daif); 445 ck_printf("infer: resident open rc=%d tensors=%u vocab=%u layers=%u kv_capacity=%u max_new=%u max_prompt_bytes=%u heap_reserve_kib=%u heap_used_kib=%u open_us=%llu\n", 446 rc, info.tensors, info.vocab, info.layers, lim.kv_capacity, lim.max_new, lim.max_prompt_bytes, 447 lim.heap_reserve >> 10, info.heap_used_kib, (unsigned long long)(ck_time_us() - t0)); 448 if (rc != 0) { 449 aienos_infer_heap_init(0, 0); 450 ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); 451 if (mpages) ck_mm_frames_free(mpa, mpages); 452 ck_puts("infer: resident FAIL (session did not open; frames returned)\n"); 453 return; 454 } 455 g_res.open = 1; 456 g_res.mpa = mpa; 457 g_res.msize = msize; 458 g_res.mpages = mpages; 459 g_res.hpa = hpa; 460 g_res.frames_before = frames_before; 461 } 462 463 int ck_infer_prompt(const char *text, size_t len, int (*cancel_poll)(void), struct ck_infer_reply *r) 464 { 465 if (!g_res.open) return SESS_E_STATE; 466 memset(r, 0, sizeof *r); 467 uint64_t t0 = ck_time_us(), daif = ck_rd(daif); 468 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 469 int32_t ids = aienos_infer_session_prompt((const uint8_t *)text, (uint32_t)len); 470 ck_wr(daif, daif); 471 if (ids < 0) return ids; 472 r->prompt_ids = (uint32_t)ids; 473 { 474 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 475 (void)aienos_infer_session_prompt_ids(r->prompt_head, 4); 476 ck_wr(daif, daif); 477 } 478 int32_t rc = 0; 479 for (;;) { 480 uint32_t t = 0; 481 uint64_t us = 0; 482 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 483 rc = aienos_infer_session_step(&t, &us); 484 ck_wr(daif, daif); 485 pet(); /* the Pi PM watchdog (15 s) is petted per step; no-op on every other board */ 486 if (rc < 0 || rc == SESS_STEP_DONE) break; 487 r->steps++; 488 if (rc != SESS_STEP_PREFILL) r->produced++; 489 if (rc == SESS_STEP_LAST) break; 490 if (cancel_poll && cancel_poll()) { 491 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 492 aienos_infer_session_cancel(); 493 ck_wr(daif, daif); 494 r->cancelled = 1; 495 break; 496 } 497 } 498 r->rc = rc; 499 r->us = ck_time_us() - t0; 500 if (rc < 0) return rc; 501 if (!r->cancelled) { 502 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 503 int32_t n = aienos_infer_session_tokens(r->ids, CK_INFER_REPLY_IDS); 504 int32_t tl = aienos_infer_session_text(r->ids, n > 0 && n <= CK_INFER_REPLY_IDS ? (uint32_t)n : 0, r->text, 505 CK_INFER_REPLY_TEXT); 506 ck_wr(daif, daif); 507 if (n < 0) return n; 508 if (tl < 0) return tl; 509 r->produced = (uint32_t)n; 510 r->text_len = (uint32_t)tl; 511 /* A completed request is consumed: the session is idle for the next prompt. */ 512 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 513 aienos_infer_session_cancel(); 514 ck_wr(daif, daif); 515 } 516 return 0; 517 } 518 519 void ck_infer_resident_close(void) 520 { 521 if (!g_res.open) return; 522 uint64_t daif = ck_rd(daif), used = 0, peak = 0; 523 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 524 aienos_infer_heap_stats(&used, &peak); 525 int32_t crc = aienos_infer_session_close(); 526 ck_wr(daif, daif); 527 aienos_infer_heap_init(0, 0); 528 int f2 = ck_mm_frames_free(g_res.hpa, HEAP_BYTES / PAGE); 529 int f1 = g_res.mpages ? ck_mm_frames_free(g_res.mpa, g_res.mpages) : 0; 530 uint64_t frames_after = ck_mm_free_frames(); 531 struct ck_mm_usage mu; 532 ck_mm_usage(&mu); 533 g_res.open = 0; 534 ck_printf("infer: resident close rc=%d heap_used_kib=%llu heap_peak_kib=%llu\n", crc, (unsigned long long)(used / 1024), 535 (unsigned long long)(peak / 1024)); 536 ck_printf("infer: unloaded heap_live_kib=%llu frames_free_before=%llu frames_free_after=%llu frames_returned=%llu rc=%d,%d\n", 537 (unsigned long long)((mu.heap_bytes - mu.heap_free) / 1024), (unsigned long long)g_res.frames_before, 538 (unsigned long long)frames_after, (unsigned long long)(g_res.mpages + HEAP_BYTES / PAGE), f1, f2); 539 } 540 #endif /* CK_INFER_RESIDENT */ 541 542 void ck_infer_run(void) 543 { 544 /* Source 1, the boot disk: the UEFI stub read the model through the 545 * firmware's Block I/O driver before ExitBootServices and recorded it in 546 * CHANDOF2 (native/boot/efi_model.c, native/boot/model_map.h). The bytes 547 * live in EfiLoaderData the frame allocator never hands out (mm/mmu.c 548 * reserves the range). This is the path that exists on hardware. 549 * Source 2, QEMU fw_cfg: TEST-ONLY, below, when the stub found no map; 550 * compiled out of the hardware service image (CK_INFER_DISK_ONLY). */ 551 const struct ck_handoff *h = ck_handoff_get(); 552 int from_disk = h && (h->model_flags & CK_HANDOFF_MODEL_PRESENT); 553 #ifdef CK_INFER_DISK_ONLY 554 uint32_t size = 0; 555 if (!from_disk) { 556 ck_puts("infer: ingest REFUSED (no boot-disk model: MODEL.MAP absent or refused by the stub; " 557 "this image has no other model source)\n"); 558 return; 559 } 560 #else 561 const char *why = 0; 562 uint64_t base = from_disk ? 0 : fwcfg_from_dsdt(&why); 563 uint16_t sel = 0; 564 uint32_t size = 0; 565 if (!from_disk) { 566 if (base && !ck_mm_mmio_try_map(base, 0x18)) { 567 why = "fw_cfg window not mappable"; 568 base = 0; 569 } 570 if (base) { 571 uint8_t sig[4], feat[4]; 572 fwcfg = (volatile uint8_t *)(uintptr_t)base; 573 fw_select(0); 574 fw_read(sig, 4); 575 fw_select(1); 576 fw_read(feat, 4); 577 if (memcmp(sig, "QEMU", 4)) 578 why = "fw_cfg signature", base = 0; 579 else if (!(le32(feat) & 2u)) 580 why = "fw_cfg DMA interface not offered", base = 0; 581 else if (__builtin_bswap64(*(volatile uint64_t *)(fwcfg + 16)) != 0x51454d5520434647ull) 582 why = "fw_cfg DMA register signature", base = 0; 583 else if (fw_find(&sel, &size)) 584 why = "no " MODEL_FILE " fw_cfg file", base = 0; 585 } 586 if (!base) { 587 ck_printf("infer: ingest FAIL (%s)\nAIENOS_CK_INFER: FAIL\n", why); 588 return; 589 } 590 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"); 591 ck_printf("infer: fw_cfg base=0x%llx dma=yes file=%s size=%u\n", (unsigned long long)base, 592 MODEL_FILE, size); 593 594 } 595 #endif /* CK_INFER_DISK_ONLY */ 596 uint64_t msize = from_disk ? h->model_len : (uint64_t)size; 597 uint64_t mpa = from_disk ? h->model_base : 0, hpa = 0, mpages = 0; 598 if (from_disk) { 599 ck_puts("infer_source_mode: boot-disk model (MODEL.MAP read by the UEFI stub through the firmware's Block I/O before ExitBootServices); the path that exists on hardware\n"); 600 ck_printf("infer: disk base=0x%llx size=%llu extents=%u read_us=%llu block_size=%u\n", 601 (unsigned long long)mpa, (unsigned long long)msize, h->model_extents, 602 (unsigned long long)h->model_read_us, h->model_block_size); 603 if (!ck_mm_mapped(mpa, msize)) { 604 ck_puts("infer: ingest FAIL (disk model range not mapped)\nAIENOS_CK_INFER: FAIL\n"); 605 return; 606 } 607 } 608 609 uint64_t frames_before = ck_mm_free_frames(); 610 if (!from_disk) { 611 mpages = (msize + PAGE - 1) / PAGE; 612 if (ck_mm_frames_alloc(mpages, &mpa)) { 613 ck_printf("infer: ingest FAIL (no frames: need %llu + %llu pages, %llu free)\nAIENOS_CK_INFER: FAIL\n", 614 (unsigned long long)mpages, (unsigned long long)(HEAP_BYTES / PAGE), 615 (unsigned long long)ck_mm_free_frames()); 616 return; 617 } 618 } 619 if (ck_mm_frames_alloc(HEAP_BYTES / PAGE, &hpa)) { 620 if (mpages) 621 ck_mm_frames_free(mpa, mpages); 622 ck_printf("infer: ingest FAIL (no frames for the %llu-page heap, %llu free)\nAIENOS_CK_INFER: FAIL\n", 623 (unsigned long long)(HEAP_BYTES / PAGE), (unsigned long long)ck_mm_free_frames()); 624 return; 625 } 626 627 #ifndef CK_INFER_DISK_ONLY 628 if (!from_disk) { 629 uint64_t t0 = ck_time_us(); 630 int rc = 0; 631 for (uint64_t off = 0; off < msize && !rc; off += DMA_CHUNK) { 632 uint64_t n = msize - off < DMA_CHUNK ? msize - off : DMA_CHUNK; 633 rc = fw_dma_read(off == 0 ? (int)sel : -1, mpa + off, (uint32_t)n); 634 } 635 if (rc) { 636 ck_printf("infer: ingest FAIL (fw_cfg DMA rc=%d)\nAIENOS_CK_INFER: FAIL\n", rc); 637 return; 638 } 639 ck_printf("infer: ingest bytes=%llu dma_us=%llu\n", (unsigned long long)msize, 640 (unsigned long long)(ck_time_us() - t0)); 641 } 642 #endif 643 644 uint64_t t1 = ck_time_us(); 645 sha256_ctx ctx; 646 uint8_t dg[SHA256_DIGEST_SIZE]; 647 char dh[2 * SHA256_DIGEST_SIZE + 1]; 648 sha256_init(&ctx); 649 /* 16 MiB pieces, a watchdog pet between them: on the Pi the 15 s PM watchdog is petted only at boot 650 * stages (core/pi5.c), and hashing the whole model is longer than that. ck_pi5_stage is weak (absent 651 * on every other board). */ 652 for (uint64_t o = 0; o < msize; o += PET_CHUNK) { 653 uint64_t n = msize - o < PET_CHUNK ? msize - o : PET_CHUNK; 654 sha256_update(&ctx, (const uint8_t *)(uintptr_t)(mpa + o), n); 655 pet(); 656 } 657 sha256_final(&ctx, dg); 658 hex(dh, dg, SHA256_DIGEST_SIZE); 659 ck_printf("infer: sha256=%s sha_us=%llu\n", dh, (unsigned long long)(ck_time_us() - t1)); 660 if (from_disk && memcmp(dg, h->model_sha256, SHA256_DIGEST_SIZE) != 0) { 661 /* The bytes the firmware read are not the declared model: a wrong 662 * LBA, a short read or a stale file. Refuse to decode. */ 663 hex(dh, h->model_sha256, SHA256_DIGEST_SIZE); 664 ck_printf("infer: sha256 mismatch declared=%s\nAIENOS_CK_INFER: FAIL\n", dh); 665 ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); 666 return; 667 } 668 669 #ifdef CK_INFER_RESIDENT 670 /* Service image: the model stays resident for the lifecycle's prompt verb 671 * (core/lifecycle.c); the one-shot probe and session_run below are the 672 * QEMU probe image's regression, not the service's job. */ 673 memcpy(g_model_sha, dg, sizeof dg); 674 resident_open(mpa, msize, mpages, hpa, frames_before); 675 return; 676 #endif 677 678 #ifdef CK_PI5_INFER 679 /* Pi image: the one-shot probe is one call of many seconds with interrupts masked and cannot pet the 680 * 15 s PM watchdog (core/pi5.c). The session below runs the same golden prompt one step at a time 681 * with a pet per step, and is judged against the same llama.cpp token list (expect_gen). */ 682 ck_puts("infer: one-shot probe skipped on the Pi image (watchdog); the session below runs the golden prompt step by step\n"); 683 { 684 uint64_t v = ck_rd(cpacr_el1); 685 v |= 3ull << CPACR_FPEN_SHIFT; 686 ck_wr(cpacr_el1, v); 687 ck_isb(); 688 } 689 int f2 = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); 690 #else 691 /* FP/SIMD on, every exception masked for the Rust unit (see core/fpu.c). 692 * The FP registers are left dirty afterwards (nothing else in the kernel 693 * reads them; EL0 traps on FP). */ 694 static struct infer_result res; /* ~0.5 KiB; static keeps it off the EL1 stack */ 695 memset(&res, 0, sizeof res); 696 uint64_t v = ck_rd(cpacr_el1); 697 v |= 3ull << CPACR_FPEN_SHIFT; 698 ck_wr(cpacr_el1, v); 699 ck_isb(); 700 infer_heap_open((uintptr_t)hpa, HEAP_BYTES); 701 uint64_t daif = ck_rd(daif); 702 __asm__ volatile("msr daifset, #0xf" ::: "memory"); 703 uint64_t t2 = ck_time_us(); 704 int32_t prc = aienos_infer_run((const uint8_t *)(uintptr_t)mpa, msize, &res); 705 uint64_t t3 = ck_time_us(); 706 ck_wr(daif, daif); 707 const uint32_t *out = res.words; 708 709 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", 710 prc, out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7], out[8], 711 (unsigned long long)(t3 - t2)); 712 int ok = prc == 0; 713 for (unsigned i = 0; i < 4; i++) 714 ok = ok && out[2 + i] == expect_ids[i]; 715 716 /* Generation lines: ids, per-token microseconds, decoded bytes. */ 717 uint32_t ntok = res.ntok <= INFER_MAX_NEW ? res.ntok : INFER_MAX_NEW; 718 ck_printf("infer: prefill_us=%llu prompt_len=%u", (unsigned long long)res.prefill_us, out[6]); 719 ck_printf("\ninfer: tokens="); 720 for (uint32_t i = 0; i < ntok; i++) 721 ck_printf("%s%u", i ? " " : "", res.tokens[i]); 722 ck_printf("\ninfer: tok_us="); 723 uint64_t sum = 0; 724 for (uint32_t i = 1; i < ntok; i++) { 725 ck_printf("%s%llu", i > 1 ? "," : "", (unsigned long long)res.tok_us[i]); 726 sum += res.tok_us[i]; 727 } 728 ck_printf("\ninfer: decode_tokens=%u mean_tok_us=%llu\n", ntok > 1 ? ntok - 1 : 0, 729 (unsigned long long)(ntok > 1 ? sum / (ntok - 1) : 0)); 730 uint32_t tl = res.text_len <= INFER_TEXT_BYTES ? res.text_len : INFER_TEXT_BYTES; 731 escape(esc, res.text, tl); 732 ck_printf("infer: text=%s\n", esc); 733 ok = ok && ntok == sizeof expect_gen / sizeof expect_gen[0]; 734 for (uint32_t i = 0; ok && i < ntok; i++) 735 ok = ok && res.tokens[i] == expect_gen[i]; 736 737 /* Unload the one-shot unit: it kept nothing (its objects died at return); 738 * forget its heap region and return the heap frames. The model stays for 739 * the session below. */ 740 aienos_infer_heap_init(0, 0); 741 int f2 = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); 742 ck_printf("AIENOS_CK_INFER: %s\n", ok ? "PASS" : "FAIL"); 743 #endif /* CK_PI5_INFER */ 744 745 /* Bounded session on the same model bytes, its own fresh heap region. */ 746 session_run(mpa, msize); 747 748 /* Return the model's frames when it came over fw_cfg (the disk model stays 749 * in LoaderData, never a frame). The free-frame count must come back to 750 * what it was before the ingest. */ 751 int f1 = mpages ? ck_mm_frames_free(mpa, mpages) : 0; 752 uint64_t frames_after = ck_mm_free_frames(); 753 struct ck_mm_usage mu; 754 ck_mm_usage(&mu); 755 ck_printf("infer: unloaded heap_live_kib=%llu frames_free_before=%llu frames_free_after=%llu frames_returned=%llu rc=%d,%d\n", 756 (unsigned long long)((mu.heap_bytes - mu.heap_free) / 1024), (unsigned long long)frames_before, 757 (unsigned long long)frames_after, (unsigned long long)(mpages + HEAP_BYTES / PAGE), f1, f2); 758 if (!(f1 == 0 && f2 == 0 && frames_after == frames_before)) 759 ck_puts("infer: frames NOT returned\nAIENOS_CK_INFER: FAIL\n"); 760 } 761 #else 762 void ck_infer_run(void) {} 763 #endif 764 765 #ifndef CK_INFER_RESIDENT 766 /* No resident session: the diagnostic image, the QEMU probe image and a 767 * service image built without CK_INFER_LIB (every hardware image today). */ 768 int ck_infer_resident(void) { return 0; } 769 int ck_infer_prompt(const char *text, size_t len, int (*cancel_poll)(void), struct ck_infer_reply *r) 770 { 771 (void)text; (void)len; (void)cancel_poll; (void)r; 772 return -12; /* no session in this image */ 773 } 774 void ck_infer_resident_close(void) {} 775 const uint8_t *ck_infer_model_sha256(void) { return 0; } 776 #endif