Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.
Add persistent KV-cache multi-turn chat to Phase 2 OS and Phase 1 --chat
Alexey Fateev2f3dc99224f5
diff --git a/01-qwen3-inference/README.md b/01-qwen3-inference/README.mdindex 93467f7..00d94e8 100644--- a/01-qwen3-inference/README.md+++ b/01-qwen3-inference/README.md@@ -1,10 +1,10 @@-# Phase 1: Qwen3-0.6B Inference in a 12 KB Pure x86-64 ELF+# Phase 1: Qwen3-0.6B Inference in a 13 KB Pure x86-64 ELFA complete inference engine for **Qwen/Qwen3-0.6B** written in **100% pure x86-64 NASM assembly** for Linux.-- **12,120 bytes** stripped static ELF executable (`.text` = 9,891 B, `.rodata` = 1,625 B).+- **13,528 bytes** stripped static ELF executable (`.text` = 10,990 B, `.rodata` = 1,943 B).- **Zero runtime dependencies:** no `gcc`, no `libc`, no `libm`, no dynamic linker, no `.so` files.-- **Full Qwen3 architecture:** GQA (`16Q / 8KV`, `head_dim = 128`), per-head QK-Norm (`RMSNorm` on Q and K before RoPE), split-half NeoX RoPE (`rope_theta = 1e6`), SwiGLU MLP, tied embeddings / LM head, KV-cache, greedy and temperature/top-p sampling.+- **Full Qwen3 architecture:** GQA (`16Q / 8KV`, `head_dim = 128`), per-head QK-Norm (`RMSNorm` on Q and K before RoPE), split-half NeoX RoPE (`rope_theta = 1e6`), SwiGLU MLP, tied embeddings / LM head, persistent multi-turn KV-cache (`--chat`), greedy and temperature/top-p sampling.- **Built-in BPE tokenizer in assembly:** Fibonacci-hashed open-addressing merge table (`524,288` slots, 100% token-exact match with HuggingFace `AutoTokenizer`), UTF-8 prompt encoding (English, Cyrillic, code, numbers), Qwen3 chat template (default no-think and `--think` reasoning mode), and raw `write()` streaming to stdout.- **AVX2 + FMA Q8_0 x FP32 matmul + zero-libc thread pool:** 4-row unrolled AVX2/FMA kernel, fused QKV and gate+up projections, and a raw Linux `clone()` + `futex()` thread pool with cache-line-isolated completion slots. **105.4 tok/s** peak decode and **154.3 tok/s** peak prefill on AMD EPYC 7642, bit-exact across `1T..47T`.@@ -49,7 +49,7 @@ python3 scripts/export_weights.py \--out models/qwen3-0.6b-q8_0.asmbin```-### 3. Build the 12 KB Pure x86-64 Binary+### 3. Build the 13 KB Pure x86-64 BinaryFrom the repository root:@@ -61,7 +61,7 @@ make checkExpected ELF inspection output:```text--rwxr-xr-x 1 user user 12120 build/asm-llm+-rwxr-xr-x 1 user user 13528 build/asm-llmbuild/asm-llm: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, strippedThere is no dynamic section in this file.```@@ -73,6 +73,9 @@ There is no dynamic section in this file../build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin \-p "Explain how a CPU cache works in 3 concise sentences." -n 128 -t 16+# Interactive multi-turn chat preserving KV-cache across turns (/clear, /think, /nothink, /quit)+./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin --chat -t 16+# Enable Qwen3 <think> reasoning mode./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin \-p "What is 17 * 23?" -n 512 -t 16 --think@@ -98,6 +101,7 @@ There is no dynamic section in this file.| `-n <int>` | `128` | Maximum generated tokens || `-t <int>` | `32` | Worker thread count (`clone()` + `futex()` pool) || `-c <int>` | `2048` | KV-cache context length |+| `--chat` | off | Interactive multi-turn chat via raw Linux `read(0)`/`write(1)` syscalls; preserves KV-cache across turns, supports `/clear` (`/new`, `/reset`), `/think`, `/nothink`, `/quit` (`/exit`, Ctrl-D), and prints `ctx=X/2048` || `--think` | off | Enable Qwen3 `<think>...</think>` reasoning mode || `--raw` | off | Skip Qwen3 chat template, encode prompt bytes directly || `--tokens <csv>` | none | Feed comma-separated token IDs directly |diff --git a/01-qwen3-inference/main.asm b/01-qwen3-inference/main.asmindex d066ebf..a48d020 100644--- a/01-qwen3-inference/main.asm+++ b/01-qwen3-inference/main.asm@@ -16,6 +16,7 @@ extern sys_closeextern sys_write_allextern sys_clock_nsextern sys_exit_group+extern str_lenextern str_eqextern parse_u64extern parse_f32@@ -52,7 +53,10 @@ _start:mov qword [rel opt_ctx_len], 2048mov dword [rel opt_think], 0mov dword [rel opt_raw], 0+ mov dword [rel opt_chat], 0+ mov dword [rel opt_has_prompt], 0mov dword [rel opt_print_toks], 0+ mov qword [rel g_chat_pos], 0mov qword [rel opt_tokens_csv], 0mov qword [rel opt_dump_logits], 0mov dword [rel opt_temp], 0 ; 0.0f = greedy argmax@@ -92,6 +96,7 @@ _start:jae .usagemov rax, [r13 + rbx*8]mov [rel opt_prompt], rax+ mov dword [rel opt_has_prompt], 1jmp .arg_next.chk_n:@@ -231,10 +236,19 @@ _start:lea rsi, [rel flg_ptoks]call str_eqtest eax, eax- jz .chk_help+ jz .chk_chatmov dword [rel opt_print_toks], 1jmp .arg_next+.chk_chat:+ mov rdi, r14+ lea rsi, [rel flg_chat]+ call str_eq+ test eax, eax+ jz .chk_help+ mov dword [rel opt_chat], 1+ jmp .arg_next+.chk_help:mov rdi, r14lea rsi, [rel flg_h]@@ -266,8 +280,13 @@ _start:mov rdi, [rel opt_threads]call tp_init- ; Build prompt tokens (either from --tokens CSV or BPE + Qwen3 chat template)lea rbp, [rel g_ctx]+ cmp dword [rel opt_chat], 0+ jne .enter_chat++ ; ========================================================================+ ; SINGLE-SHOT MODE (100% identical to original behavior)+ ; ========================================================================mov rax, [rel opt_tokens_csv]test rax, raxjnz .parse_csv_toks@@ -316,6 +335,227 @@ _start:.have_prompt:test r12, r12jz .err_prompt+ mov rdi, r12+ call run_tokens+ jmp .shutdown++ ; ========================================================================+ ; INTERACTIVE MULTI-TURN CHAT MODE (--chat, zero-libc raw stdin/stdout)+ ; ========================================================================+.enter_chat:+ mov edi, 2+ lea rsi, [rel msg_chat_help]+ call write_cstr++ ; If user also passed -p "...", run it as Turn 1 and keep its KV-cache+ cmp dword [rel opt_has_prompt], 0+ je .chat_loop+ mov rdi, [rel opt_prompt]+ mov rsi, [rbp + CTX_BUF_PROMPT]+ mov rdx, MAX_PROMPT_TOKENS+ mov ecx, [rel opt_raw]+ mov r8d, [rel opt_think]+ call tok_build_chat_prompt+ test rax, rax+ jz .chat_loop+ mov rdi, rax+ call run_tokens++.chat_loop:+ mov edi, 2+ lea rsi, [rel msg_chat_prompt]+ call write_cstr++ lea rdi, [rel g_line_buf]+ mov rsi, 4096+ call read_stdin_line+ test rax, rax+ js .shutdown ; EOF / Ctrl-D++ ; Trim leading spaces/tabs+ lea r12, [rel g_line_buf]+.trim_lead:+ mov al, [r12]+ cmp al, ' '+ je .adv_lead+ cmp al, 9+ je .adv_lead+ jmp .trim_tail+.adv_lead:+ inc r12+ jmp .trim_lead++.trim_tail:+ mov rdi, r12+ call str_len+ test rax, rax+ jz .chat_loop ; empty line+ lea rcx, [r12 + rax - 1]+.tt_lp:+ cmp rcx, r12+ jb .chk_chat_cmd+ mov al, [rcx]+ cmp al, ' '+ je .tt_chop+ cmp al, 9+ je .tt_chop+ jmp .chk_chat_cmd+.tt_chop:+ mov byte [rcx], 0+ dec rcx+ jmp .tt_lp++.chk_chat_cmd:+ ; /quit, /exit, exit+ mov rdi, r12+ lea rsi, [rel cmd_quit]+ call str_eq+ test eax, eax+ jnz .shutdown++ mov rdi, r12+ lea rsi, [rel cmd_exit_slash]+ call str_eq+ test eax, eax+ jnz .shutdown++ mov rdi, r12+ lea rsi, [rel cmd_exit]+ call str_eq+ test eax, eax+ jnz .shutdown++ ; /clear, /new, /reset+ mov rdi, r12+ lea rsi, [rel cmd_clear]+ call str_eq+ test eax, eax+ jnz .do_clear++ mov rdi, r12+ lea rsi, [rel cmd_new]+ call str_eq+ test eax, eax+ jnz .do_clear++ mov rdi, r12+ lea rsi, [rel cmd_reset]+ call str_eq+ test eax, eax+ jnz .do_clear++ ; /think+ mov rdi, r12+ lea rsi, [rel cmd_think]+ call str_eq+ test eax, eax+ jz .chk_cmd_nothink+ mov dword [rel opt_think], 1+ mov edi, 2+ lea rsi, [rel msg_think_on]+ call write_cstr+ jmp .chat_loop++.chk_cmd_nothink:+ mov rdi, r12+ lea rsi, [rel cmd_nothink]+ call str_eq+ test eax, eax+ jz .chat_infer+ mov dword [rel opt_think], 0+ mov edi, 2+ lea rsi, [rel msg_think_off]+ call write_cstr+ jmp .chat_loop++.do_clear:+ mov qword [rel g_chat_pos], 0+ mov edi, 2+ lea rsi, [rel msg_chat_cleared]+ call write_cstr+ mov edi, 2+ mov rsi, [rbp + CTX_MAX_SEQ]+ call write_u64+ mov edi, 2+ lea rsi, [rel msg_close_nl]+ call write_cstr+ jmp .chat_loop++.chat_infer:+ mov rdi, r12+ mov rsi, [rbp + CTX_BUF_PROMPT]+ mov rdx, MAX_PROMPT_TOKENS+ mov ecx, [rel opt_raw]+ mov r8d, [rel opt_think]+ call tok_build_chat_prompt+ test rax, rax+ jz .chat_loop+ mov rdi, rax+ call run_tokens+ jmp .chat_loop++.shutdown:+ call tp_shutdown+ call model_free+ xor edi, edi+ call sys_exit_group++.usage:+ mov edi, 2+ lea rsi, [rel msg_usage]+ call write_cstr+ mov edi, 1+ call sys_exit_group++.err_model:+ mov edi, 2+ lea rsi, [rel msg_err_model]+ call write_cstr+ mov edi, 2+ call sys_exit_group++.err_prompt:+ mov edi, 2+ lea rsi, [rel msg_err_prompt]+ call write_cstr+ mov edi, 3+ call sys_exit_group++; ============================================================================+; void run_tokens(uint64 n_prompt in rdi)+; Runs prefill (from g_chat_pos) + streaming decode + optional KV-cache close+; ============================================================================+run_tokens:+ push rbx+ push rbp+ push r12+ push r13+ push r14+ push r15+ sub rsp, 8 ; 6 pushes + 8 + ret(8) = 64 -> 16B aligned++ mov r12, rdi ; r12 = n_prompt+ lea rbp, [rel g_ctx]++ ; Multi-turn KV-cache bounds check (chat mode only)+ cmp dword [rel opt_chat], 0+ je .ctx_room_ok+ mov rax, [rel g_chat_pos]+ test rax, rax+ jz .ctx_room_ok+ lea rcx, [rax + r12 + 64]+ cmp rcx, [rbp + CTX_MAX_SEQ]+ jb .ctx_room_ok+ mov qword [rel g_chat_pos], 0+ mov edi, 2+ lea rsi, [rel msg_ctx_full]+ call write_cstr+.ctx_room_ok:+ mov rax, [rbp + CTX_MAX_SEQ]+ cmp r12, rax+ jbe .prompt_len_ok+ mov r12, rax+.prompt_len_ok:; Print PROMPT_TOKENS if requestedcmp dword [rel opt_print_toks], 0@@ -334,18 +574,20 @@ _start:call sys_clock_nsmov [rel tm_prefill_start], rax- xor r13d, r13d ; pos = 0+ mov r13, [rel g_chat_pos] ; pos = g_chat_pos+ xor ebx, ebx ; i = 0mov r14, [rbp + CTX_BUF_PROMPT].prefill_lp:- cmp r13, r12+ cmp rbx, r12jae .prefill_done- mov edi, [r14 + r13*4] ; token_id+ mov edi, [r14 + rbx*4] ; token_idmov rsi, r13 ; pos- lea rax, [r13 + 1]+ lea rax, [rbx + 1]xor edx, edxcmp rax, r12- sete dl ; compute_logits = (pos == n_prompt - 1)+ sete dl ; compute_logits = (i == n_prompt - 1)call transformer_forward+ inc rbxinc r13jmp .prefill_lp@@ -380,6 +622,7 @@ _start:call sys_clock_nsmov [rel tm_decode_start], rax+ mov dword [rsp], 0 ; last_tok_unfed = 0xor r15d, r15d ; n_gen = 0mov rbx, [rel opt_max_tok].decode_lp:@@ -401,7 +644,7 @@ _start:; Check if we reached max_tok or max_seqcmp r15, rbx- jae .decode_done+ jae .decode_done_unfedcmp r13, [rbp + CTX_MAX_SEQ]jae .decode_done@@ -416,6 +659,8 @@ _start:mov r14, raxjmp .decode_lp+.decode_done_unfed:+ mov dword [rsp], 1.decode_done:call sys_clock_nsmov [rel tm_decode_end], rax@@ -426,6 +671,40 @@ _start:mov edx, 1call sys_write_all+ ; In --chat mode, close assistant turn in KV-cache with <|im_end|> + \n+ cmp dword [rel opt_chat], 0+ je .after_kv_close++ cmp dword [rsp], 0+ je .close_eot+ cmp r13, [rbp + CTX_MAX_SEQ]+ jae .save_chat_pos+ mov rdi, r14+ mov rsi, r13+ xor edx, edx+ call transformer_forward+ inc r13++.close_eot:+ cmp dword [rel opt_raw], 0+ jne .save_chat_pos+ lea rax, [r13 + 2]+ cmp rax, [rbp + CTX_MAX_SEQ]+ jae .save_chat_pos+ mov edi, TOK_IM_END+ mov rsi, r13+ xor edx, edx+ call transformer_forward+ inc r13+ mov edi, TOK_NL+ mov rsi, r13+ xor edx, edx+ call transformer_forward+ inc r13+.save_chat_pos:+ mov [rel g_chat_pos], r13+.after_kv_close:+; Print GEN_TOKENS if requestedcmp dword [rel opt_print_toks], 0je .print_stats@@ -436,9 +715,7 @@ _start:mov rsi, r15call write_tok_csv_stderr- ; Print performance summary to stderr:- ; prefill: <n_prompt> tok in <ms> ms (<tok/s> tok/s)- ; decode : <n_gen> tok in <ms> ms (<tok/s> tok/s) [threads=<T>]+ ; Print performance summary to stderr.print_stats:; Prefill statsmov edi, 2@@ -453,6 +730,10 @@ _start:mov rax, [rel tm_prefill_end]sub rax, [rel tm_prefill_start]+ test rax, rax+ jnz .pf_nz+ mov rax, 1+.pf_nz:vcvtsi2sd xmm0, xmm0, rax ; dt_nsvdivsd xmm1, xmm0, [rel d_1e6] ; msvmovsd [rel tm_tmp], xmm0@@ -471,9 +752,7 @@ _start:lea rsi, [rel msg_tps_end]call write_cstr- ; Decode stats (note: forward passes during decode = max(n_gen - 1, 0),- ; or report n_gen tokens over decode wall time; wait: if n_gen > 1,- ; first token came from prefill and (n_gen - 1) forward passes ran in decode loop!)+ ; Decode statsmov edi, 2lea rsi, [rel msg_decode]call write_cstr@@ -498,7 +777,6 @@ _start:mov edi, 2lea rsi, [rel msg_ms_open]call write_cstr- ; Decode throughput = (n_gen > 1 ? n_gen - 1 : n_gen) / dt_decode_smov rax, r15cmp rax, 1jbe .dec_cnt_ok@@ -515,36 +793,88 @@ _start:mov edi, 2mov rsi, [rel opt_threads]call write_u64- mov edi, 2- lea rsi, [rel msg_close_nl]- call write_cstr-- ; Clean shutdown- call tp_shutdown- call model_free- xor edi, edi- call sys_exit_group-.usage:+ cmp dword [rel opt_chat], 0+ je .stats_close_singlemov edi, 2- lea rsi, [rel msg_usage]+ lea rsi, [rel msg_ctx_lbl]call write_cstr- mov edi, 1- call sys_exit_group--.err_model:mov edi, 2- lea rsi, [rel msg_err_model]+ mov rsi, r13+ call write_u64+ mov edi, 2+ lea rsi, [rel msg_slash]call write_cstrmov edi, 2- call sys_exit_group+ mov rsi, [rbp + CTX_MAX_SEQ]+ call write_u64+ mov edi, 2+ lea rsi, [rel msg_nl]+ mov edx, 1+ call sys_write_all+ jmp .rt_done-.err_prompt:+.stats_close_single:mov edi, 2- lea rsi, [rel msg_err_prompt]+ lea rsi, [rel msg_close_nl]call write_cstr- mov edi, 3- call sys_exit_group++.rt_done:+ add rsp, 8+ pop r15+ pop r14+ pop r13+ pop r12+ pop rbp+ pop rbx+ ret++; ----------------------------------------------------------------------------+; int64 read_stdin_line(char *buf in rdi, uint64 max_len in rsi)+; Raw Linux SYS_read(0, ...) line reader. Returns len >= 0, or -1 on EOF.+; ----------------------------------------------------------------------------+read_stdin_line:+ push rbx+ push r12+ push r13+ sub rsp, 16 ; 3 pushes (24) + 16 + ret(8) = 48 -> 16B aligned+ mov r12, rdi+ lea r13, [rsi - 1]+ xor ebx, ebx+.rd_lp:+ xor edi, edi ; fd = 0 (stdin)+ mov rsi, rsp+ mov edx, 1+ mov eax, SYS_read+ syscall+ cmp rax, -4 ; EINTR+ je .rd_lp+ test rax, rax+ jle .rd_eof+ movzx eax, byte [rsp]+ cmp al, 10 ; '\n'+ je .rd_done+ cmp al, 13 ; '\r'+ je .rd_lp+ cmp rbx, r13+ jae .rd_lp+ mov [r12 + rbx], al+ inc rbx+ jmp .rd_lp+.rd_eof:+ test rbx, rbx+ jnz .rd_done+ mov rax, -1+ jmp .rd_ret+.rd_done:+ mov byte [r12 + rbx], 0+ mov rax, rbx+.rd_ret:+ add rsp, 16+ pop r13+ pop r12+ pop rbx+ ret; ----------------------------------------------------------------------------; uint64 pick_next_token(void) -> rax@@ -620,12 +950,23 @@ flg_topp: db "--topp", 0flg_seed: db "--seed", 0flg_dump: db "--dump-logits", 0flg_ptoks: db "--print-tokens", 0+flg_chat: db "--chat", 0flg_h: db "-h", 0flg_help: db "--help", 0+cmd_quit: db "/quit", 0+cmd_exit_slash: db "/exit", 0+cmd_exit: db "exit", 0+cmd_clear: db "/clear", 0+cmd_new: db "/new", 0+cmd_reset: db "/reset", 0+cmd_think: db "/think", 0+cmd_nothink: db "/nothink", 0+def_prompt: db "Hello!", 0msg_nl: db 10msg_comma: db ","+msg_slash: db "/", 0msg_ptoks: db "PROMPT_TOKENS:", 0msg_gtoks: db "GEN_TOKENS:", 0msg_prefill: db "[asm-llm] prefill: ", 0@@ -634,7 +975,14 @@ msg_in: db " tok in ", 0msg_ms_open: db " ms (", 0msg_tps_end: db " tok/s)", 10, 0msg_tps_thr: db " tok/s, threads=", 0+msg_ctx_lbl: db ") ctx=", 0msg_close_nl: db ")", 10, 0+msg_chat_help: db "Interactive Multi-Turn Chat (/clear, /think, /nothink, /quit)", 10, 0+msg_chat_prompt: db 10, "asm-llm> ", 0+msg_chat_cleared: db "[chat] history cleared (ctx=0/", 0+msg_ctx_full: db "[chat] context full, resetting KV-cache", 10, 0+msg_think_on: db "[mode] think=1", 10, 0+msg_think_off: db "[mode] think=0", 10, 0msg_err_model: db "error: failed to load .asmbin model", 10, 0msg_err_prompt: db "error: empty prompt", 10, 0msg_usage:@@ -645,6 +993,7 @@ msg_usage:db " -n <max_tokens> Max generated tokens (default: 128)", 10db " -t <threads> Thread count (default: 32)", 10db " -c <ctx_len> Max context / KV cache length (default: 2048)", 10+ db " --chat Interactive multi-turn chat (preserves KV-cache)", 10db " --think Enable Qwen3 <think> reasoning mode", 10db " --raw Do not wrap prompt in Qwen3 chat template", 10db " --tokens <csv> Pass exact comma-separated token IDs", 10@@ -664,13 +1013,17 @@ opt_ctx_len: resq 1opt_tokens_csv: resq 1opt_dump_logits: resq 1opt_rng: resq 1+g_chat_pos: resq 1opt_temp: resd 1opt_topp: resd 1opt_think: resd 1opt_raw: resd 1+opt_chat: resd 1+opt_has_prompt: resd 1opt_print_toks: resd 1tm_prefill_start: resq 1tm_prefill_end: resq 1tm_decode_start: resq 1tm_decode_end: resq 1tm_tmp: resq 1+g_line_buf: resb 4096diff --git a/02-baremetal-os/README.md b/02-baremetal-os/README.mdindex 6df9930..791f960 100644--- a/02-baremetal-os/README.md+++ b/02-baremetal-os/README.md@@ -1,9 +1,9 @@-# Phase 2: Bare-Metal Bootable Qwen3-0.6B OS in 22 KB of Pure Assembly+# Phase 2: Bare-Metal Bootable Qwen3-0.6B OS in 23 KB of Pure AssemblyA standalone bootable x86-64 operating system that runs **Qwen/Qwen3-0.6B** directly on hardware or KVM with **no Linux, no Windows, no C, no Rust, and no libc**.-- **22,492 bytes** stripped static Multiboot 1 kernel (`build/asm-llm-os.elf`, `.text` = 15,559 B, `.rodata` = 2,548 B, `.bss` = 2.1 MiB `NOBITS`, zero dynamic dependencies).-- **85 ms cold boot** to interactive `asm-llm>` prompt with all SMP cores online and the 649 MiB model bound zero-copy from physical RAM.+- **23,132 bytes** stripped static Multiboot 1 kernel (`build/asm-llm-os.elf`, `.text` = 16,119 B, `.rodata` = 2,676 B, `.bss` = 2.1 MiB `NOBITS`, zero dynamic dependencies).+- **85 ms cold boot** to interactive `asm-llm>` multi-turn chat with persistent KV-cache across turns, all SMP cores online, and the 649 MiB model bound zero-copy from physical RAM.- **100% token-exact and byte-for-byte parity** with [Phase 1](../01-qwen3-inference/) across `1..32` vCPUs.- **100.1 tok/s** decode on QEMU KVM (AMD EPYC 7642, 32 vCPUs) and **55.4 tok/s** live on a **0 GB disk Proxmox VE VM** (Intel Xeon E5-2670 v3, 12 cores).@@ -42,7 +42,7 @@ make os-checkExpected output:```text--rwxr-xr-x 1 user user 22492 build/asm-llm-os.elf+-rwxr-xr-x 1 user user 23132 build/asm-llm-os.elfbuild/asm-llm-os.elf: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, strippedThere is no dynamic section in this file.```@@ -88,7 +88,7 @@ qemu-system-x86_64 -enable-kvm -cpu host -m 2G -smp 16 \### Option B: Bootable Hybrid BIOS+UEFI ISO-Packages the 22 KB kernel, GRUB2 Multiboot 1 config, and the 649 MiB `.asmbin` model into a single self-contained `~661 MiB` bootable ISO (`build/asm-llm-os.iso`):+Packages the 23 KB kernel, GRUB2 Multiboot 1 config, and the 649 MiB `.asmbin` model into a single self-contained `~661 MiB` bootable ISO (`build/asm-llm-os.iso`):```bashmake os-iso MODEL=models/qwen3-0.6b-q8_0.asmbin@@ -141,17 +141,20 @@ qm terminal 250----## Interactive REPL & Kernel Cmdline+## Interactive Multi-Turn Chat & Kernel Cmdline### Interactive Console (`asm-llm>`)-Both PS/2 keyboard (VGA) and COM1 serial (`115200 8N1`) are polled simultaneously. Type any prompt and press Enter, or use a built-in command:+By default, the bare-metal console runs in **multi-turn chat mode with persistent KV-cache**: each new user turn prefills only the new Qwen3 chat tokens starting at `g_chat_pos` without recomputing earlier turns, closes every assistant turn in the KV-cache with `<|im_end|>\n`, and displays live context usage (`ctx=X/2048`) in the decode stats line. When the KV-cache approaches `max_seq` (`pos + n_prompt + 64 >= max_seq`), it prints `[chat] context full, resetting KV-cache` and resets cleanly. If booted with `prompt="..."` and `shutdown=0`, the initial batch turn stays in the KV-cache so you can continue the same conversation in the REPL.++Both PS/2 keyboard (VGA) and COM1 serial (`115200 8N1`) are polled simultaneously. Type any message and press Enter, or use a built-in command:| Command | Action ||---|---|+| `/clear`, `/new`, `/reset` | Clear conversation history (`g_chat_pos = 0`, prints `ctx=0/2048`) || `/think` | Enable Qwen3 `<think>...</think>` reasoning mode || `/nothink` | Disable reasoning mode (direct answers, default) |-| `/bench` | Run built-in latency/throughput benchmark prompt |+| `/bench` | Reset KV-cache and run built-in latency/throughput benchmark prompt || `/halt` or `/quit` | Trigger clean ACPI S5 poweroff || `/help` | Show available console commands |@@ -161,12 +164,13 @@ Pass via QEMU `-append "..."`, `make os-run CMDLINE='...'`, or `make os-iso CMDL| Option | Default | Description ||---|---:|---|-| `prompt="..."` | *(none)* | Run a batch prompt immediately after boot |+| `prompt="..."` | *(none)* | Run a batch prompt immediately after boot (preserved in KV-cache if `shutdown=0`) || `max_tokens=N` | `128` | Maximum tokens to generate per prompt || `ctx=N` | `2048` | KV-cache context length || `threads=N` | `0` | Limit active SMP cores (`0` = all online cores) || `think=0\|1` | `0` | Enable or disable Qwen3 reasoning mode || `raw=0\|1` | `0` | Skip Qwen3 chat template |+| `single_turn=0\|1` | `0` | Disable multi-turn KV-cache retention (`0` = multi-turn chat by default) || `temp=F` | `0.0` | Sampling temperature (`0.0` = greedy) || `topp=F` | `0.95` | Top-p threshold || `seed=N` | `42` | PRNG seed |@@ -177,7 +181,7 @@ Pass via QEMU `-append "..."`, `make os-run CMDLINE='...'`, or `make os-iso CMDL## Architecture Overview-Phase 2 compiles the exact same `shared/math.asm`, `shared/matmul.asm`, `shared/tokenizer.asm`, and `shared/transformer.asm` with `-DBARE_METAL` and pairs them with 3,914 lines of bare-metal OS code:+Phase 2 compiles the exact same `shared/math.asm`, `shared/matmul.asm`, `shared/tokenizer.asm`, and `shared/transformer.asm` with `-DBARE_METAL` and pairs them with 4,058 lines of bare-metal OS code:- **Boot & Long Mode (`boot.asm`, `linker.ld`):** verifies Multiboot 1 magic (`0x2BADB002`), zeroes `.bss`, builds 4-level 2 MiB huge-page identity tables covering `0..4 GiB` (with `0xFE000000..0xFFFFFFFF` marked Strong Uncacheable for Local APIC MMIO), enters 64-bit Long Mode, installs a 32-entry exception IDT, verifies `XSAVE + AVX + AVX2 + FMA` via CPUID, and initializes `CR0`/`CR4`/`XCR0=7`/`MXCSR`.- **Zero-Copy Weights & Physical Arena (`runtime.asm`):** binds the `.asmbin` Multiboot module directly at its physical address (validating `"ASML"` magic) and carves the 449 MiB KV-cache + scratch arena from the largest usable Multiboot memory-map region, zeroing it with AVX2.diff --git a/02-baremetal-os/kernel.asm b/02-baremetal-os/kernel.asmindex 9f15bd5..a64362d 100644--- a/02-baremetal-os/kernel.asm+++ b/02-baremetal-os/kernel.asm@@ -97,8 +97,10 @@ kernel_main:mov qword [rel opt_req_threads], 0 ; 0 = all online SMP coresmov dword [rel opt_think], 0mov dword [rel opt_raw], 0+ mov dword [rel opt_single_turn], 0mov dword [rel opt_shutdown], 0mov dword [rel opt_print_toks], 0+ mov qword [rel g_chat_pos], 0mov dword [rel opt_temp], 0 ; 0.0f = greedy argmaxmov eax, 0x3F733333 ; 0.95fmov [rel opt_topp], eax@@ -282,6 +284,25 @@ kernel_main:test eax, eaxjnz .do_halt+ ; /clear, /new, /reset — reset multi-turn KV-cache history+ mov rdi, r12+ lea rsi, [rel cmd_clear]+ call str_eq+ test eax, eax+ jnz .do_clear++ mov rdi, r12+ lea rsi, [rel cmd_new]+ call str_eq+ test eax, eax+ jnz .do_clear++ mov rdi, r12+ lea rsi, [rel cmd_reset]+ call str_eq+ test eax, eax+ jnz .do_clear+; /thinkmov rdi, r12lea rsi, [rel cmd_think]@@ -296,6 +317,22 @@ kernel_main:call write_cstrjmp .repl_loop+.do_clear:+ mov qword [rel g_chat_pos], 0+ mov dil, VGA_ATTR_CYAN+ call vga_set_color+ mov edi, 1+ lea rsi, [rel msg_chat_cleared]+ call write_cstr+ lea rax, [rel g_ctx]+ mov edi, 1+ mov rsi, [rax + CTX_MAX_SEQ]+ call write_u64+ mov edi, 1+ lea rsi, [rel msg_close_nl]+ call write_cstr+ jmp .repl_loop+.chk_nothink:mov rdi, r12lea rsi, [rel cmd_nothink]@@ -317,11 +354,16 @@ kernel_main:test eax, eaxjz .chk_helpmov r13, [rel opt_max_tok]+ mov r14d, [rel opt_single_turn]mov qword [rel opt_max_tok], 64+ mov dword [rel opt_single_turn], 1+ mov qword [rel g_chat_pos], 0lea rdi, [rel bench_prompt]xor esi, esicall run_inferencemov [rel opt_max_tok], r13+ mov [rel opt_single_turn], r14d+ mov qword [rel g_chat_pos], 0jmp .repl_loop.chk_help:@@ -405,6 +447,31 @@ run_inference:test r12, r12jz .done+ ; Multi-turn KV-cache management+ cmp dword [rel opt_single_turn], 0+ je .chk_ctx_room+ mov qword [rel g_chat_pos], 0+ jmp .ctx_room_ok+.chk_ctx_room:+ mov rax, [rel g_chat_pos]+ test rax, rax+ jz .ctx_room_ok+ lea rcx, [rax + r12 + 64]+ cmp rcx, [rbp + CTX_MAX_SEQ]+ jb .ctx_room_ok+ mov qword [rel g_chat_pos], 0+ mov dil, VGA_ATTR_YELLOW+ call vga_set_color+ mov edi, 1+ lea rsi, [rel msg_ctx_full]+ call write_cstr+.ctx_room_ok:+ mov rax, [rbp + CTX_MAX_SEQ]+ cmp r12, rax+ jbe .prompt_len_ok+ mov r12, rax+.prompt_len_ok:+; Optional PROMPT_TOKENS output for automated exact verificationcmp dword [rel opt_print_toks], 0je .do_prefill@@ -415,23 +482,25 @@ run_inference:mov rsi, r12call write_tok_csv- ; --- PREFILL ---+ ; --- PREFILL (incremental from pos = g_chat_pos, preserving KV-cache!) ---.do_prefill:call timer_nsmov [rel tm_prefill_start], rax- xor r13d, r13d ; pos = 0+ mov r13, [rel g_chat_pos] ; pos = g_chat_pos+ xor ebx, ebx ; i = 0mov r14, [rbp + CTX_BUF_PROMPT].prefill_lp:- cmp r13, r12+ cmp rbx, r12jae .prefill_done- mov edi, [r14 + r13*4]+ mov edi, [r14 + rbx*4]mov rsi, r13- lea rax, [r13 + 1]+ lea rax, [rbx + 1]xor edx, edxcmp rax, r12- sete dl ; compute_logits = (pos == n_prompt - 1)+ sete dl ; compute_logits = (i == n_prompt - 1)call transformer_forward+ inc rbxinc r13jmp .prefill_lp@@ -454,6 +523,7 @@ run_inference:call timer_nsmov [rel tm_decode_start], rax+ mov dword [rsp], 0 ; last_tok_unfed = 0xor r15d, r15d ; n_gen = 0mov rbx, [rel opt_max_tok].decode_lp:@@ -472,7 +542,7 @@ run_inference:call tok_write_stdoutcmp r15, rbx- jae .decode_done+ jae .decode_done_unfedcmp r13, [rbp + CTX_MAX_SEQ]jae .decode_done@@ -486,6 +556,8 @@ run_inference:mov r14, raxjmp .decode_lp+.decode_done_unfed:+ mov dword [rsp], 1 ; r14 was emitted on max_tok hit, not yet forwarded.decode_done:call timer_nsmov [rel tm_decode_end], rax@@ -494,6 +566,46 @@ run_inference:lea rsi, [rel msg_nl]call write_cstr+ ; Close assistant turn in KV-cache for seamless Qwen3 multi-turn continuity+ cmp dword [rel opt_single_turn], 0+ jne .reset_chat_after++ ; If decode stopped at max_tokens, feed the last emitted token into KV-cache+ cmp dword [rsp], 0+ je .close_eot+ cmp r13, [rbp + CTX_MAX_SEQ]+ jae .save_chat_pos+ mov rdi, r14+ mov rsi, r13+ xor edx, edx ; compute_logits = 0+ call transformer_forward+ inc r13++.close_eot:+ ; Feed <|im_end|> (151645) and \n (198) so next turn's <|im_start|>user\n aligns exact+ cmp dword [rel opt_raw], 0+ jne .save_chat_pos+ lea rax, [r13 + 2]+ cmp rax, [rbp + CTX_MAX_SEQ]+ jae .save_chat_pos+ mov edi, TOK_IM_END+ mov rsi, r13+ xor edx, edx+ call transformer_forward+ inc r13+ mov edi, TOK_NL+ mov rsi, r13+ xor edx, edx+ call transformer_forward+ inc r13+.save_chat_pos:+ mov [rel g_chat_pos], r13+ jmp .after_kv_close++.reset_chat_after:+ mov qword [rel g_chat_pos], 0+.after_kv_close:+; Optional GEN_TOKENS output for automated exact verificationcmp dword [rel opt_print_toks], 0je .print_stats@@ -586,7 +698,19 @@ run_inference:mov rsi, [rel g_active_cores]call write_u64mov edi, 1- lea rsi, [rel msg_close_nl]+ lea rsi, [rel msg_ctx_lbl]+ call write_cstr+ mov edi, 1+ mov rsi, r13+ call write_u64+ mov edi, 1+ lea rsi, [rel msg_slash]+ call write_cstr+ mov edi, 1+ mov rsi, [rbp + CTX_MAX_SEQ]+ call write_u64+ mov edi, 1+ lea rsi, [rel msg_nl]call write_cstr; Optional boot-to-first-token line (batch mode)@@ -1131,7 +1255,7 @@ parse_cmdline:lea rsi, [rel key_seed]call str_eqtest eax, eax- jz .tok_lp+ jz .chk_single_turnlea rdi, [rel cmd_val_buf]call parse_u64test rax, rax@@ -1141,6 +1265,17 @@ parse_cmdline:mov [rel opt_rng], raxjmp .tok_lp+.chk_single_turn:+ lea rdi, [rel cmd_key_buf]+ lea rsi, [rel key_single_turn]+ call str_eq+ test eax, eax+ jz .tok_lp+ lea rdi, [rel cmd_val_buf]+ call parse_u64+ mov [rel opt_single_turn], eax+ jmp .tok_lp+.done:pop r13pop r12@@ -1171,8 +1306,10 @@ ban_mod_at: db " MiB @ 0x", 0ban_mod_ctx: db ", 28L, ctx=", 0msg_prompt_lbl: db "Prompt: ", 0-msg_repl_help: db "Interactive Bare-Metal REPL (/think, /nothink, /bench, /halt, /help)", 10, 0+msg_repl_help: db "Interactive Bare-Metal Chat (/clear, /think, /nothink, /bench, /halt, /help)", 10, 0msg_repl_prompt: db 10, "asm-llm> ", 0+msg_chat_cleared: db "[chat] history cleared (ctx=0/", 0+msg_ctx_full: db "[chat] context full, resetting KV-cache", 10, 0msg_think_on: db "[mode] think=1 (Qwen3 reasoning enabled)", 10, 0msg_think_off: db "[mode] think=0 (direct answer mode)", 10, 0msg_poweroff: db "Powering off bare-metal VM...", 10, 0@@ -1188,6 +1325,7 @@ msg_in: db " tok in ", 0msg_ms_open: db " ms (", 0msg_tps_end: db " tok/s)", 10, 0msg_tps_cores: db " tok/s, cores=", 0+msg_ctx_lbl: db ") ctx=", 0msg_close_nl: db ")", 10, 0msg_boot_ttft: db "[asm-llm-os] boot : ready ", 0msg_ttft_mid: db " ms | boot->1st-tok ", 0@@ -1199,6 +1337,9 @@ bench_prompt: db "Explain how a CPU cache works in 3 concise sentences.", 0cmd_halt: db "/halt", 0cmd_quit: db "/quit", 0cmd_exit: db "exit", 0+cmd_clear: db "/clear", 0+cmd_new: db "/new", 0+cmd_reset: db "/reset", 0cmd_think: db "/think", 0cmd_nothink: db "/nothink", 0cmd_bench: db "/bench", 0@@ -1215,6 +1356,7 @@ key_print_tokens: db "print_tokens", 0key_temp: db "temp", 0key_topp: db "topp", 0key_seed: db "seed", 0+key_single_turn: db "single_turn", 0msg_err_avx2: db "[FATAL] CPU lacks AVX2+FMA+XSAVE (use QEMU -cpu host)", 10, 0msg_err_mb: db "[FATAL] Invalid Multiboot 1 magic", 10, 0@@ -1232,6 +1374,7 @@ g_mod_start: resq 1g_mod_end: resq 1g_mod_size: resq 1g_active_cores: resq 1+g_chat_pos: resq 1opt_max_tok: resq 1opt_ctx_len: resq 1@@ -1241,6 +1384,7 @@ opt_temp: resd 1opt_topp: resd 1opt_think: resd 1opt_raw: resd 1+opt_single_turn: resd 1opt_shutdown: resd 1opt_print_toks: resd 1opt_has_prompt: resd 1diff --git a/README.md b/README.mdindex b16f08a..3cc9886 100644--- a/README.md+++ b/README.md@@ -3,14 +3,14 @@**Three complete LLM projects written in 100% pure x86-64 NASM assembly.**Zero C, zero C++, zero Rust, zero libc, zero libm, zero runtime dependencies.-Assembled directly with `nasm` and linked with `ld`. Every math kernel (`expf`, `sincosf`, `RMSNorm`, `RoPE`, `SiLU`, `Softmax`), AVX2+FMA GEMM/GEMV engine, BPE tokenizer, `clone()`/`futex()` thread pool, bare-metal SMP kernel, analytical backward pass, AdamW optimizer, and live Unicode Braille TUI is hand-written x86-64 assembly (`15,778` lines total across all three projects).+Assembled directly with `nasm` and linked with `ld`. Every math kernel (`expf`, `sincosf`, `RMSNorm`, `RoPE`, `SiLU`, `Softmax`), AVX2+FMA GEMM/GEMV engine, BPE tokenizer, `clone()`/`futex()` thread pool, bare-metal SMP kernel, analytical backward pass, AdamW optimizer, and live Unicode Braille TUI is hand-written x86-64 assembly (`16,275` lines total across all three projects).## The Trilogy| Project | Binary | Size | Deps | Key Numbers ||---|---|---:|---:|---|-| **[01-qwen3-inference/](01-qwen3-inference/)** | `build/asm-llm` | **12,120 B** | **0** | Static Linux ELF running `Qwen/Qwen3-0.6B` (Q8_0, built-in BPE tokenizer, GQA + QK-Norm + RoPE + SwiGLU). **105.4 tok/s** peak decode, **`1.000000000`** cosine vs Q8_0 ref, **64/64** exact greedy token match vs PyTorch FP32. |-| **[02-baremetal-os/](02-baremetal-os/)** | `build/asm-llm-os.elf` | **22,492 B** | **0** | Bootable bare-metal `Qwen3-0.6B` OS with no Linux or Windows. Multiboot 1 -> Long Mode -> AVX2/FMA -> ACPI/APIC SMP -> VGA + PS/2 + COM1 console. **85 ms** boot, **100.1 tok/s** KVM EPYC, **55.4 tok/s** live on Proxmox Xeon E5-2670 v3 with **0 GB** disk. |+| **[01-qwen3-inference/](01-qwen3-inference/)** | `build/asm-llm` | **13,528 B** | **0** | Static Linux ELF running `Qwen/Qwen3-0.6B` (Q8_0, built-in BPE tokenizer, GQA + QK-Norm + RoPE + SwiGLU, single-shot & `--chat` multi-turn KV-cache REPL). **105.4 tok/s** peak decode, **`1.000000000`** cosine vs Q8_0 ref, **64/64** exact greedy token match vs PyTorch FP32. |+| **[02-baremetal-os/](02-baremetal-os/)** | `build/asm-llm-os.elf` | **23,132 B** | **0** | Bootable bare-metal `Qwen3-0.6B` OS with no Linux or Windows. Multiboot 1 -> Long Mode -> AVX2/FMA -> ACPI/APIC SMP -> VGA + PS/2 + COM1 multi-turn KV-cache chat (`/clear`, `/think`, `/bench`). **85 ms** boot, **100.1 tok/s** KVM EPYC, **55.4 tok/s** live on Proxmox Xeon E5-2670 v3 with **0 GB** disk. || **[03-minigpt-train/](03-minigpt-train/)** | `build/asm-gpt-train` | **32,752 B** | **0** | From-scratch FP32 Mini-GPT trainer and sampler. Register-blocked `6x16` AVX2+FMA SGEMM, full analytical backward pass (**`1.0000000000`** cosine across all 21 gradient tensors vs PyTorch CPU), decoupled AdamW, **27,662 train tok/s**, live 80x24 Braille TUI, `val_loss 4.19 -> 1.51` on TinyShakespeare in 4 min. |---@@ -66,17 +66,19 @@ cd llm.asmmake all```-### 1. Run Qwen3-0.6B Inference in 12 KB (`01-qwen3-inference/`)+### 1. Run Qwen3-0.6B Inference in 13 KB (`01-qwen3-inference/`)```bashpython3 scripts/export_weights.py --model-dir models/qwen3-0.6b-bf16 --out models/qwen3-0.6b-q8_0.asmbinmake inference./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin -p "Explain how a CPU cache works in 3 concise sentences." -n 128 -t 16+# Or start an interactive multi-turn chat preserving the KV-cache across turns:+./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin --chat -t 16```Full step-by-step setup, model download, CLI flags, and benchmarks: **[01-qwen3-inference/README.md](01-qwen3-inference/README.md)**.-### 2. Boot Bare-Metal Qwen3-0.6B OS in 22 KB (`02-baremetal-os/`)+### 2. Boot Bare-Metal Qwen3-0.6B OS in 23 KB (`02-baremetal-os/`)```bashmake os@@ -119,15 +121,15 @@ llm.asm/│ ├── threads.asm # Zero-libc Linux clone() + futex() lock-free thread pool│ ├── tokenizer.asm # Fibonacci-hashed BPE encoder, UTF-8 decoder, Qwen3 chat template│ └── transformer.asm # Full 28-layer Qwen3 forward pass (mmap & bare-metal zero-copy)-├── 01-qwen3-inference/ # Phase 1: 12 KB static Linux ELF inference engine (865 lines)+├── 01-qwen3-inference/ # Phase 1: 13 KB static Linux ELF inference engine + --chat (1,218 lines)│ ├── README.md│ ├── main.asm│ └── test_math.asm-├── 02-baremetal-os/ # Phase 2: 22 KB bare-metal bootable LLM OS (3,914 lines)+├── 02-baremetal-os/ # Phase 2: 23 KB bare-metal bootable LLM OS (4,058 lines)│ ├── README.md│ ├── boot.asm # Multiboot 1 -> 4-level paging -> Long Mode -> AVX2/FMA -> IDT│ ├── drivers.asm # COM1 115200, 80x25 Color VGA, PS/2 keyboard, PIT+RDTSC, ACPI poweroff-│ ├── kernel.asm # Kernel entrypoint, CPUID banner, cmdline parser, interactive REPL+│ ├── kernel.asm # Kernel entrypoint, CPUID banner, cmdline parser, multi-turn chat REPL│ ├── linker.ld # Bare-metal linker script at 0x00100000│ ├── os_constants.inc # Hardware, Multiboot 1, Local APIC, and SMP constants│ ├── runtime.asm # Multiboot mmap bump allocator + bare-metal formatting runtimediff --git a/scripts/verify_os.py b/scripts/verify_os.pyindex faf71d8..dd37064 100755--- a/scripts/verify_os.py+++ b/scripts/verify_os.py@@ -47,7 +47,7 @@ def parse_os_output(raw_bytes: bytes):m_smp = re.search(r"SMP\s*:\s*(\d+)/(\d+)\s+x86-64 cores online", text)m_boot = re.search(r"\[asm-llm-os\] boot\s*:\s*ready\s+([0-9.]+)\s+ms\s*\|\s*boot->1st-tok\s+([0-9.]+)\s+ms", text)m_pf = re.search(r"\[asm-llm-os\] prefill:\s*(\d+)\s+tok in\s+([0-9.]+)\s+ms\s*\(([0-9.]+)\s+tok/s\)", text)- m_dec = re.search(r"\[asm-llm-os\] decode\s*:\s*(\d+)\s+tok in\s+([0-9.]+)\s+ms\s*\(([0-9.]+)\s+tok/s,\s*cores=(\d+)\)", text)+ m_dec = re.search(r"\[asm-llm-os\] decode\s*:\s*(\d+)\s+tok in\s+([0-9.]+)\s+ms\s*\(([0-9.]+)\s+tok/s,\s*cores=(\d+)\)(?:\s*ctx=(\d+)/(\d+))?", text)m_p = re.search(r"PROMPT_TOKENS:([0-9,]+)", text)m_g = re.search(r"GEN_TOKENS:([0-9,]+)", text)@@ -81,6 +81,8 @@ def parse_os_output(raw_bytes: bytes):"decode_ms": float(m_dec.group(2)) if m_dec else 0.0,"decode_tps": float(m_dec.group(3)) if m_dec else 0.0,"cores": int(m_dec.group(4)) if m_dec else 0,+ "ctx_used": int(m_dec.group(5)) if (m_dec and m_dec.group(5)) else 0,+ "ctx_max": int(m_dec.group(6)) if (m_dec and m_dec.group(6)) else 0,}@@ -174,6 +176,160 @@ def test_repl(model: str, smp: int = 16):proc.wait()+def test_multiturn_os(model: str, smp: int = 16):+ cmd = [+ "qemu-system-x86_64",+ "-enable-kvm", "-cpu", "host",+ "-m", "2G", "-smp", str(smp),+ "-kernel", OS_ELF,+ "-initrd", model,+ "-append", "max_tokens=64 think=0",+ "-nographic",+ ]+ proc = subprocess.Popen(+ cmd,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ bufsize=0,+ )+ buf = b""++ def read_until(marker: bytes, timeout: float = 30.0):+ nonlocal buf+ deadline = time.monotonic() + timeout+ while marker not in buf:+ rem = deadline - time.monotonic()+ if rem <= 0:+ proc.kill()+ raise TimeoutError(+ f"Timed out waiting for {marker!r}; got tail:\n{buf[-500:].decode('utf-8', 'replace')}"+ )+ r, _, _ = select.select([proc.stdout], [], [], min(rem, 0.25))+ if r:+ chunk = os.read(proc.stdout.fileno(), 4096)+ if not chunk:+ break+ buf += chunk++ def send_and_read(line: str) -> str:+ nonlocal buf+ proc.stdin.write((line + "\n").encode("utf-8"))+ proc.stdin.flush()+ read_until(b"asm-llm> ", timeout=30.0)+ part, buf = buf.split(b"asm-llm> ", 1)+ return part.decode("utf-8", errors="replace").strip()++ try:+ read_until(b"asm-llm> ", timeout=30.0)+ buf = buf.split(b"asm-llm> ", 1)[1]++ t1 = send_and_read("My name is Alex and my favorite number is 42. Reply with just OK.")+ t2 = send_and_read("What is my name and what is my favorite number?")+ t3 = send_and_read("/clear")+ t4 = send_and_read("What is my name?")++ proc.stdin.write(b"/halt\n")+ proc.stdin.flush()+ rest, _ = proc.communicate(timeout=15.0)+ shutdown_msg = (buf + rest).decode("utf-8", errors="replace").strip()++ c1 = re.search(r"ctx=(\d+)/(\d+)", t1)+ c2 = re.search(r"ctx=(\d+)/(\d+)", t2)+ c4 = re.search(r"ctx=(\d+)/(\d+)", t4)+ ctx1 = int(c1.group(1)) if c1 else 0+ ctx2 = int(c2.group(1)) if c2 else 0+ ctx4 = int(c4.group(1)) if c4 else 0++ ok = (+ proc.returncode == 0+ and "Alex" in t2+ and "42" in t2+ and "[chat] history cleared" in t3+ and "Alex" not in t4+ and ctx1 > 0+ and ctx2 > ctx1+ and ctx4 > 0+ and ctx4 < ctx2+ and "Powering off" in shutdown_msg+ )+ return {+ "ok": ok,+ "returncode": proc.returncode,+ "turn1": t1,+ "turn2": t2,+ "turn3_clear": t3,+ "turn4_after_clear": t4,+ "shutdown_msg": shutdown_msg,+ "ctx": (ctx1, ctx2, ctx4),+ }+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+++def test_multiturn_phase1(model: str, threads: int = 16):+ cmd = [+ PHASE1_BIN,+ "-m", model,+ "--chat",+ "-n", "64",+ "-t", str(threads),+ ]+ script_in = (+ "My name is Alex and my favorite number is 42. Reply with just OK.\n"+ "What is my name and what is my favorite number?\n"+ "/clear\n"+ "What is my name?\n"+ "/quit\n"+ ).encode("utf-8")+ res = subprocess.run(+ cmd,+ input=script_in,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=60,+ check=True,+ )+ transcript = res.stdout.decode("utf-8", errors="replace")+ parts = transcript.split("asm-llm> ")+ # parts[0] = banner, parts[1] = turn1, parts[2] = turn2, parts[3] = /clear, parts[4] = turn4, parts[5] = /quit+ t1 = parts[1].strip() if len(parts) > 1 else ""+ t2 = parts[2].strip() if len(parts) > 2 else ""+ t3 = parts[3].strip() if len(parts) > 3 else ""+ t4 = parts[4].strip() if len(parts) > 4 else ""++ c1 = re.search(r"ctx=(\d+)/(\d+)", t1)+ c2 = re.search(r"ctx=(\d+)/(\d+)", t2)+ c4 = re.search(r"ctx=(\d+)/(\d+)", t4)+ ctx1 = int(c1.group(1)) if c1 else 0+ ctx2 = int(c2.group(1)) if c2 else 0+ ctx4 = int(c4.group(1)) if c4 else 0++ ok = (+ res.returncode == 0+ and "Alex" in t2+ and "42" in t2+ and "[chat] history cleared" in t3+ and "Alex" not in t4+ and ctx1 > 0+ and ctx2 > ctx1+ and ctx4 > 0+ and ctx4 < ctx2+ )+ return {+ "ok": ok,+ "returncode": res.returncode,+ "turn1": t1,+ "turn2": t2,+ "turn3_clear": t3,+ "turn4_after_clear": t4,+ "ctx": (ctx1, ctx2, ctx4),+ "raw": transcript,+ }++def capture_vga_screenshot(model: str, out_dir: Path, smp: int = 16):from PIL import Image@@ -263,14 +419,33 @@ def main():ap.add_argument("--model", default=MODEL_DEFAULT)ap.add_argument("--run-dir", required=True)ap.add_argument("--only-vga", action="store_true")+ ap.add_argument("--only-chat", action="store_true")+ ap.add_argument("--max-threads", type=int, default=32)args = ap.parse_args()out_dir = Path(args.run_dir)out_dir.mkdir(parents=True, exist_ok=True)if args.only_vga:- png_path, size = capture_vga_screenshot(args.model, out_dir, smp=16)+ png_path, size = capture_vga_screenshot(args.model, out_dir, smp=min(16, args.max_threads))print(f"[PASS] Saved VGA screenshot: {png_path} ({size[0]}x{size[1]}, {png_path.stat().st_size} bytes)")return+ if args.only_chat:+ smp = min(16, args.max_threads)+ mt_os = test_multiturn_os(args.model, smp=smp)+ mt_p1 = test_multiturn_phase1(args.model, threads=smp)+ print(f"[{'PASS' if mt_os['ok'] else 'FAIL'}] Phase 2 Bare-Metal Multi-Turn Chat (smp={smp}, ctx={mt_os['ctx']})")+ print("--- OS Turn 1 ---\n" + mt_os["turn1"])+ print("--- OS Turn 2 (Memory Recall) ---\n" + mt_os["turn2"])+ print("--- OS /clear ---\n" + mt_os["turn3_clear"])+ print("--- OS Turn 4 (After /clear) ---\n" + mt_os["turn4_after_clear"])+ print(f"\n[{'PASS' if mt_p1['ok'] else 'FAIL'}] Phase 1 Linux --chat Multi-Turn (threads={smp}, ctx={mt_p1['ctx']})")+ print("--- P1 Turn 1 ---\n" + mt_p1["turn1"])+ print("--- P1 Turn 2 (Memory Recall) ---\n" + mt_p1["turn2"])+ print("--- P1 /clear ---\n" + mt_p1["turn3_clear"])+ print("--- P1 Turn 4 (After /clear) ---\n" + mt_p1["turn4_after_clear"])+ if not (mt_os["ok"] and mt_p1["ok"]):+ sys.exit(1)+ returnlog_path = out_dir / "report.log"lines = []@@ -292,9 +467,11 @@ def main():("Think-Mode-192", "What is 17 * 23?", 192, True),]all_parity_ok = True+ p1_threads = min(32, args.max_threads)+ os_smp = min(16, args.max_threads)for name, prompt, max_tok, think in prompts:- p1 = run_phase1(args.model, prompt, max_tok, think=think, threads=32)- os_res = run_os_batch(args.model, prompt, max_tok, smp=16, think=think, print_tokens=True)+ p1 = run_phase1(args.model, prompt, max_tok, think=think, threads=p1_threads)+ os_res = run_os_batch(args.model, prompt, max_tok, smp=os_smp, think=think, print_tokens=True)ptok_ok = (p1["prompt_tokens"] == os_res["prompt_tokens"]) and bool(p1["prompt_tokens"])gtok_ok = (p1["gen_tokens"] == os_res["gen_tokens"]) and bool(p1["gen_tokens"])text_ok = (p1["text"] == os_res["text"])@@ -317,12 +494,12 @@ def main():# 2. SMP Determinism & KVM Scaling Benchmark (1, 4, 8, 16, 24, 32 vCPUs)log("\n=== 2. BARE-METAL SMP SCALING & DETERMINISM BENCHMARK (QEMU KVM, AMD EPYC 7642) ===")bench_prompt = "Explain the difference between L1, L2, and L3 CPU caches and why cache locality matters."- ref_p1 = run_phase1(args.model, bench_prompt, 64, think=False, threads=32)+ ref_p1 = run_phase1(args.model, bench_prompt, 64, think=False, threads=p1_threads)log(f"Prompt: {bench_prompt!r} (34 prompt tok, 64 gen tok, greedy)")log(f"{'vCPUs':>5s} | {'Online':>6s} | {'Boot(ms)':>8s} | {'Boot->1st':>9s} | {'Prefill ms':>10s} | {'Prefill t/s':>11s} | {'Decode ms':>9s} | {'Decode t/s':>10s} | {'QEMU Wall':>9s} | Determinism")log("-" * 116)smp_all_ok = True- for smp in (1, 4, 8, 16, 24, 32):+ for smp in [s for s in (1, 4, 8, 16, 24, 32) if s <= args.max_threads]:r = run_os_batch(args.model, bench_prompt, 64, smp=smp, think=False, print_tokens=True, timeout_s=120)online_ok = (r["smp_online"] == smp)det_ok = (r["gen_tokens"] == ref_p1["gen_tokens"]) and (r["text"] == ref_p1["text"])@@ -334,26 +511,44 @@ def main():# 3. Interactive REPL Test (2 consecutive questions + /halt)log("\n=== 3. INTERACTIVE BARE-METAL REPL TEST (COM1 SERIAL, 2 TURNS + /halt) ===")- repl = test_repl(args.model, smp=16)+ repl = test_repl(args.model, smp=os_smp)repl_ok = (repl["returncode"] == 0 and "Paris" in repl["turn1"] and "56" in repl["turn2"] and "Powering off" in repl["shutdown_msg"])log(f"[{'PASS' if repl_ok else 'FAIL'}] REPL exit_code={repl['returncode']}")log("--- Turn 1 ---\n" + repl["turn1"].strip())log("--- Turn 2 ---\n" + repl["turn2"].strip())log("--- Shutdown ---\n" + repl["shutdown_msg"].strip())- # 4. VGA Screenshot Capture- log("\n=== 4. VGA TEXT MODE (0xB8000) SCREENSHOT CAPTURE ===")- png_path, size = capture_vga_screenshot(args.model, out_dir, smp=16)+ # 4. Multi-Turn KV-Cache Memory & /clear Tests (Phase 2 OS + Phase 1 --chat)+ log("\n=== 4. MULTI-TURN KV-CACHE MEMORY & /clear TESTS (PHASE 2 OS + PHASE 1 --chat) ===")+ mt_os = test_multiturn_os(args.model, smp=os_smp)+ log(f"[{'PASS' if mt_os['ok'] else 'FAIL'}] Phase 2 Bare-Metal Multi-Turn (smp={os_smp}, ctx={mt_os['ctx']})")+ log("--- OS Turn 1 ---\n" + mt_os["turn1"])+ log("--- OS Turn 2 (Memory Recall) ---\n" + mt_os["turn2"])+ log("--- OS /clear ---\n" + mt_os["turn3_clear"])+ log("--- OS Turn 4 (After /clear) ---\n" + mt_os["turn4_after_clear"])++ mt_p1 = test_multiturn_phase1(args.model, threads=os_smp)+ log(f"[{'PASS' if mt_p1['ok'] else 'FAIL'}] Phase 1 Linux --chat Multi-Turn (threads={os_smp}, ctx={mt_p1['ctx']})")+ log("--- P1 Turn 1 ---\n" + mt_p1["turn1"])+ log("--- P1 Turn 2 (Memory Recall) ---\n" + mt_p1["turn2"])+ log("--- P1 /clear ---\n" + mt_p1["turn3_clear"])+ log("--- P1 Turn 4 (After /clear) ---\n" + mt_p1["turn4_after_clear"])++ # 5. VGA Screenshot Capture+ log("\n=== 5. VGA TEXT MODE (0xB8000) SCREENSHOT CAPTURE ===")+ png_path, size = capture_vga_screenshot(args.model, out_dir, smp=os_smp)log(f"[PASS] Saved VGA screenshot: {png_path} ({size[0]}x{size[1]}, {png_path.stat().st_size} bytes)")log("\n=== SUMMARY ===")log(f"Parity vs Phase 1 (5 prompts): {'PASS' if all_parity_ok else 'FAIL'}")- log(f"SMP Determinism (1..32 vCPU) : {'PASS' if smp_all_ok else 'FAIL'}")+ log(f"SMP Determinism (<= {args.max_threads} vCPU) : {'PASS' if smp_all_ok else 'FAIL'}")log(f"Interactive REPL (2 turns) : {'PASS' if repl_ok else 'FAIL'}")+ log(f"Multi-Turn KV-Cache (OS) : {'PASS' if mt_os['ok'] else 'FAIL'}")+ log(f"Multi-Turn KV-Cache (Phase 1): {'PASS' if mt_p1['ok'] else 'FAIL'}")log(f"VGA Screenshot : PASS ({png_path})")log_path.write_text("\n".join(lines) + "\n")- if not (all_parity_ok and smp_all_ok and repl_ok):+ if not (all_parity_ok and smp_all_ok and repl_ok and mt_os["ok"] and mt_p1["ok"]):sys.exit(1)