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 AVX1=1 build for Sandy Bridge / Ivy Bridge (no AVX2, FMA, F16C)
ruledicaprio55c63c03071e
diff --git a/01-qwen3-inference/README.md b/01-qwen3-inference/README.mdindex bf413e3..0ae6fde 100644--- a/01-qwen3-inference/README.md+++ b/01-qwen3-inference/README.md@@ -12,7 +12,7 @@ A complete inference engine for **Qwen/Qwen3-0.6B** written in **100% pure x86-6## Prerequisites-- Linux x86-64 CPU with **AVX2 + FMA + F16C** (Intel Haswell / AMD Excavator or newer; no AVX-512 or VNNI required).+- Linux x86-64 CPU with **AVX2 + FMA + F16C** (Intel Haswell / AMD Excavator or newer; no AVX-512 or VNNI required), or AVX + SSE4.1 only with `make inference AVX1=1` (Sandy / Ivy Bridge; see [AVX1 build](#avx1-build-for-sandy-bridge--ivy-bridge-avx11)).- Build tools:```bashsudo apt install nasm binutils@@ -215,6 +215,24 @@ Head-to-head decode comparison on **AMD EPYC 7642** (47C online, 256 MiB L3, DDR---+## AVX1 build for Sandy Bridge / Ivy Bridge (`AVX1=1`)++Phases 1 and 2 (`FAST_Q8=1`) can be built for CPUs without AVX2, FMA and F16C:++```bash+make inference os AVX1=1+make isa-check AVX1=1 # objdump scan of the AVX1 binaries for the AVX2 / FMA / F16C / BMI forms listed in scripts/check_isa.py+python3 scripts/test_math.py build/test_math # after make test-math AVX1=1+```++- INT8xINT8 Q8_0 kernel runs each 32-byte block as two VEX-128 halves (`vpsignb` / `vpabsb` / `vpmaddubsw` / `vpmaddwd`), halves summed in int32 before the fp32 scale.+- FMA becomes `vmulps` + `vaddps` (`shared/isa.inc` macros); fp16 block scales are converted in software (exact for all 63,488 finite halves, subnormals included), so `.asmbin` v2 and v1 both work.+- AVX2-only integer ops elsewhere (`expf` exponent rebuild, `argmax` indices, broadcasts) use 128-bit or fp32 equivalents. The bare-metal kernel checks CPUID for AVX + SSSE3 + SSE4.1 + XSAVE instead of AVX2 + FMA + F16C.+- `test_math.py` covers the matmul with K = 160: one 128-byte 4-block body and one 32-byte tail, for v1 and v2 scales, in every build mode.+- Results do not depend on the thread count. They are not bit-exact against the AVX2 build: without FMA a multiply and an add round twice, and `FAST_Q8=1` re-quantizes activations to int8, so greedy text can part from the AVX2 build's after some tokens.+- `AVX1=1` covers `FAST_Q8=1` only; `AVX1=1 FAST_Q8=0` stops with an error, and so does `make train AVX1=1` (Phase 3 keeps AVX2 + FMA).+- Verified under `qemu-x86_64 -cpu SandyBridge` (full Linux ELF forward pass) and `qemu-system-x86_64 -accel tcg -cpu SandyBridge -smp 2` (OS boots, all APs online, chat answers); the stock build stops there with SIGILL / `[FATAL] CPU lacks AVX2+FMA+XSAVE`.+## Live Generation Samples (`build/asm-llm`, `-t 32`)**1. Technical explanation:**diff --git a/01-qwen3-inference/main.asm b/01-qwen3-inference/main.asmindex ef09f6d..0f0ffe7 100644--- a/01-qwen3-inference/main.asm+++ b/01-qwen3-inference/main.asm@@ -9,6 +9,7 @@ bits 64default rel%include "constants.inc"+%include "isa.inc"extern g_ctxextern sys_openat_wr@@ -990,7 +991,11 @@ 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:+%if AVX1+ db "asm-llm (pure x86-64 AVX1 Qwen3-0.6B Q8_0, zero libc)", 10+%elsedb "asm-llm (pure x86-64 AVX2/FMA Qwen3-0.6B Q8_0, zero libc)", 10+%endifdb "Usage: asm-llm -m <model.asmbin> [options]", 10db " -m <path> Path to .asmbin model (required)", 10db " -p <prompt> Prompt text (default: Hello!)", 10diff --git a/01-qwen3-inference/test_math.asm b/01-qwen3-inference/test_math.asmindex 825add9..f0227b0 100644--- a/01-qwen3-inference/test_math.asm+++ b/01-qwen3-inference/test_math.asm@@ -7,8 +7,9 @@; to stdout:; stdin : [64 floats for exp] [64 floats for sincos] [128 floats x + 128 floats w for rmsnorm]; [64 floats gate + 64 floats up for silu_mul]-; [64 floats x_vec + 8x64 Q8_0 v1 fp32-scale rows (8*72=576B)-; + 8x64 Q8_0 v2 fp16-scale rows (8*68=544B)]+; [160 floats x_vec + 8x160 Q8_0 v1 fp32-scale rows (8*180=1440B)+; + 8x160 Q8_0 v2 fp16-scale rows (8*170=1360B)]+; K = 160 = one 128-byte 4-block body plus one 32-byte tail block; stdout: [64 exp_out] [64 sin_out] [64 cos_out] [64 rope_inv_freq f64 (512B)]; [128 rmsnorm_out] [64 silu_out] [8 matmul_v1_out] [8 matmul_v2_out]; ============================================================================@@ -22,7 +23,7 @@ default rel%define FAST_Q8 1%endif-%define IN_TOTAL_BYTES (2304 + 576 + 544)+%define IN_TOTAL_BYTES (2048 + 640 + 1440 + 1360)extern sys_write_allextern sys_exit_group@@ -124,10 +125,10 @@ _start:mov rdx, 64call silu_mul_avx2- ; 6. matmul_q8_0_range (8 rows x 64 cols): v1 fp32 scales + v2 fp16 scales+ ; 6. matmul_q8_0_range (8 rows x 160 cols): v1 fp32 scales + v2 fp16 scales%if FAST_Q8lea rdi, [rel in_mm_x]- mov rsi, 64+ mov rsi, 160call quantize_x_q8_0%endifxor edi, edi@@ -135,7 +136,7 @@ _start:lea rdi, [rel in_mm_w]lea rsi, [rel in_mm_x]lea rdx, [rel out_mm]- mov rcx, 64 ; K+ mov rcx, 160 ; Kxor r8d, r8d ; r0 = 0mov r9, 8 ; r1 = 8call matmul_q8_0_range@@ -145,7 +146,7 @@ _start:lea rdi, [rel in_mm_w16]lea rsi, [rel in_mm_x]lea rdx, [rel out_mm16]- mov rcx, 64 ; K+ mov rcx, 160 ; Kxor r8d, r8d ; r0 = 0mov r9, 8 ; r1 = 8call matmul_q8_0_range@@ -208,9 +209,9 @@ in_rms_x: resb 512 ; 128 f32in_rms_w: resb 512 ; 128 f32in_gate: resb 256 ; 64 f32in_up: resb 256 ; 64 f32-in_mm_x: resb 256 ; 64 f32-in_mm_w: resb 576 ; 8 * (64 + 8) v1 fp32 scales-in_mm_w16: resb 544 ; 8 * (64 + 4) v2 fp16 scales+in_mm_x: resb 640 ; 160 f32+in_mm_w: resb 1440 ; 8 * (160 + 20) v1 fp32 scales+in_mm_w16: resb 1360 ; 8 * (160 + 10) v2 fp16 scalesalignb 64out_exp: resb 256diff --git a/02-baremetal-os/README.md b/02-baremetal-os/README.mdindex ab9ec35..e56759b 100644--- a/02-baremetal-os/README.md+++ b/02-baremetal-os/README.md@@ -17,7 +17,7 @@ A standalone bootable x86-64 operating system that runs **Qwen/Qwen3-0.6B** dire## Prerequisites-- x86-64 CPU with **AVX2 + FMA + F16C**.+- x86-64 CPU with **AVX2 + FMA + F16C**, or AVX + SSE4.1 only with `make os AVX1=1` (Sandy / Ivy Bridge; see [Phase 1: AVX1 build](../01-qwen3-inference/README.md#avx1-build-for-sandy-bridge--ivy-bridge-avx11)).- Core build & QEMU KVM:```bashsudo apt install nasm binutils qemu-system-x86diff --git a/02-baremetal-os/boot.asm b/02-baremetal-os/boot.asmindex 9034434..db1a7fc 100644--- a/02-baremetal-os/boot.asm+++ b/02-baremetal-os/boot.asm@@ -8,11 +8,12 @@; for Local APIC MMIO), enables PAE + EFER.LME + CR0.PG, loads 64-bit GDT,; and far-jumps to 64-bit Long Mode.; 3. 64-bit long_mode_start records initial RDTSC, installs minimal exception-; IDT, verifies CPUID AVX2+FMA, enables SSE/AVX/OSXSAVE/XCR0=7/MXCSR, and+; IDT, verifies CPUID (AVX2+FMA+F16C, or AVX+SSSE3+SSE4.1 with AVX1=1), enables SSE/AVX/OSXSAVE/XCR0=7/MXCSR, and; enters kernel_main.; ============================================================================%include "os_constants.inc"+%include "isa.inc"extern _bss_startextern _bss_end@@ -170,7 +171,7 @@ long_mode_start:; Build & load minimal 32-entry exception IDT (catches any CPU fault cleanly)call idt_setup_and_load- ; Check CPUID for XSAVE + AVX + FMA + AVX2+ ; Check CPUID for XSAVE + AVX + FMA + AVX2 (AVX1=1: XSAVE + AVX + SSSE3 + SSE4.1)call check_cpu_featuresmov [rel g_has_avx2_fma], eaxtest eax, eax@@ -187,12 +188,23 @@ long_mode_start:jmp .halt_forever; -----------------------------------------------------------------------------; uint32 check_cpu_features(void) -> eax = 1 if XSAVE+AVX+FMA+AVX2 supported+; uint32 check_cpu_features(void) -> eax = 1 if XSAVE+AVX+FMA+F16C+AVX2 supported+; (AVX1=1: XSAVE+AVX+SSSE3+SSE4.1); ----------------------------------------------------------------------------check_cpu_features:push rbxmov eax, 1cpuid+%if AVX1+ ; AVX1 build: ECX bit 9 (SSSE3), bit 19 (SSE4.1), bit 26 (XSAVE), bit 28 (AVX)+ mov edx, (1 << 9) | (1 << 19) | (1 << 26) | (1 << 28)+ and ecx, edx+ cmp ecx, edx+ jne .no+ mov eax, 1+ pop rbx+ ret+%endif; ECX: bit 12 (FMA), bit 26 (XSAVE), bit 28 (AVX), bit 29 (F16C)mov edx, (1 << 12) | (1 << 26) | (1 << 28) | (1 << 29)and ecx, edxdiff --git a/02-baremetal-os/kernel.asm b/02-baremetal-os/kernel.asmindex f64052b..a163967 100644--- a/02-baremetal-os/kernel.asm+++ b/02-baremetal-os/kernel.asm@@ -14,6 +14,7 @@ default rel%include "constants.inc"%include "os_constants.inc"+%include "isa.inc"extern g_ctxextern g_mb_magic@@ -1412,7 +1413,11 @@ ban_line: db "============================================================ban_title_pre: db " asm-llm OS v2.0 | Bare-Metal ", 0ban_title_post: db " in 100% Pure x86-64 Assembly", 10, 0ban_cpu: db " CPU : ", 0+%if AVX1+ban_avx_tsc: db " (AVX1, ", 0+%elseban_avx_tsc: db " (AVX2+FMA, ", 0+%endifban_mhz_nl: db " MHz)", 10, 0ban_smp: db " SMP : ", 0ban_smp_tail: db " x86-64 cores online (APIC INIT-SIPI-SIPI, lock-free)", 10, 0@@ -1482,7 +1487,11 @@ key_topp: db "topp", 0key_seed: db "seed", 0key_single_turn: db "single_turn", 0+%if AVX1+msg_err_avx2: db "[FATAL] CPU lacks AVX+SSSE3+SSE4.1+XSAVE (use QEMU -cpu host)", 10, 0+%elsemsg_err_avx2: db "[FATAL] CPU lacks AVX2+FMA+XSAVE (use QEMU -cpu host)", 10, 0+%endifmsg_err_mb: db "[FATAL] Invalid Multiboot 1 magic", 10, 0msg_err_mod: db "[FATAL] Missing .asmbin Multiboot module (pass -initrd model.asmbin)", 10, 0msg_err_magic: db "[FATAL] Invalid .asmbin magic (expected ASML)", 10, 0diff --git a/Makefile b/Makefileindex 76990a8..38dd2fb 100644--- a/Makefile+++ b/Makefile@@ -30,18 +30,19 @@ BUILD := build# Portable defaults (override on CLI, e.g. make inference FAST_Q8=0)FAST_Q8 ?= 1+AVX1 ?= 0MODEL ?= models/qwen3-0.6b-q8_0.asmbinDATA ?= data/tinyshakespeare.txtSMP ?= 16RAM ?= 2GCMDLINE ?=-# Stamp file tracks FAST_Q8 compile-time toggle so toggling rebuilds cleanly-FAST_Q8_STAMP := $(BUILD)/.fast_q8_$(FAST_Q8)+# Stamp file tracks FAST_Q8 / AVX1 compile-time toggles so toggling rebuilds cleanly+FAST_Q8_STAMP := $(BUILD)/.cfg_q8_$(FAST_Q8)_avx1_$(AVX1)# --- Shared x86-64 NASM modules ---SHARED_DIR := shared-AFLAGS := -f elf64 -DFAST_Q8=$(FAST_Q8) -I$(SHARED_DIR)/+AFLAGS := -f elf64 -DFAST_Q8=$(FAST_Q8) -DAVX1=$(AVX1) -I$(SHARED_DIR)/# --- Phase 1: Qwen3-0.6B Linux Inference Engine (12 KB static ELF) ---P1_DIR := 01-qwen3-inference@@ -70,7 +71,7 @@ OS_BUILD := $(BUILD)/osOS_ELF64 := $(OS_BUILD)/asm-llm-os.elf64OS_ELF := $(BUILD)/asm-llm-os.elfOS_ISO := $(BUILD)/asm-llm-os.iso-OS_AFLAGS := -f elf64 -DBARE_METAL -DFAST_Q8=$(FAST_Q8) -I$(SHARED_DIR)/ -I$(P2_DIR)/+OS_AFLAGS := -f elf64 -DBARE_METAL -DFAST_Q8=$(FAST_Q8) -DAVX1=$(AVX1) -I$(SHARED_DIR)/ -I$(P2_DIR)/OS_LDFLAGS := -m elf_x86_64 -T $(P2_DIR)/linker.ld --gc-sections -s -z max-page-size=0x1000 -z noexecstackOS_OBJS := \@@ -99,7 +100,7 @@ TRAIN_OBJS := \$(TRAIN_BUILD)/tui.o \$(TRAIN_BUILD)/main.o-.PHONY: all inference test-math check os os-check os-iso os-run train train-check check-all clean+.PHONY: all inference test-math check os os-check os-iso os-run isa-check train train-check check-all cleanall: inference $(TEST) os train@@ -112,12 +113,12 @@ $(BUILD):mkdir -p $(BUILD)$(FAST_Q8_STAMP): | $(BUILD)- rm -f $(BUILD)/.fast_q8_* && touch $@+ rm -f $(BUILD)/.cfg_* $(BUILD)/.fast_q8_* && touch $@-$(BUILD)/%.o: $(SHARED_DIR)/%.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(BUILD)+$(BUILD)/%.o: $(SHARED_DIR)/%.asm $(SHARED_DIR)/constants.inc $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(BUILD)$(NASM) $(AFLAGS) $< -o $@-$(BUILD)/main.o: $(P1_DIR)/main.asm $(SHARED_DIR)/constants.inc | $(BUILD)+$(BUILD)/main.o: $(P1_DIR)/main.asm $(SHARED_DIR)/constants.inc $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(BUILD)$(NASM) $(AFLAGS) $< -o $@$(BUILD)/test_math.o: $(P1_DIR)/test_math.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(BUILD)@@ -139,13 +140,13 @@ check: $(TARGET)$(OS_BUILD):mkdir -p $(OS_BUILD)-$(OS_BUILD)/%.o: $(P2_DIR)/%.asm $(P2_DIR)/os_constants.inc $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(OS_BUILD)+$(OS_BUILD)/%.o: $(P2_DIR)/%.asm $(P2_DIR)/os_constants.inc $(SHARED_DIR)/constants.inc $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(OS_BUILD)$(NASM) $(OS_AFLAGS) $< -o $@-$(OS_BUILD)/math.o: $(SHARED_DIR)/math.asm | $(OS_BUILD)+$(OS_BUILD)/math.o: $(SHARED_DIR)/math.asm $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(OS_BUILD)$(NASM) $(OS_AFLAGS) $< -o $@-$(OS_BUILD)/matmul.o: $(SHARED_DIR)/matmul.asm $(FAST_Q8_STAMP) | $(OS_BUILD)+$(OS_BUILD)/matmul.o: $(SHARED_DIR)/matmul.asm $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(OS_BUILD)$(NASM) $(OS_AFLAGS) $< -o $@$(OS_BUILD)/tokenizer.o: $(SHARED_DIR)/tokenizer.asm $(SHARED_DIR)/constants.inc | $(OS_BUILD)@@ -173,6 +174,15 @@ os-check: $(OS_ELF)os-iso: $(OS_ELF)bash scripts/mkiso.sh "$(OS_ELF)" "$(MODEL)" "$(OS_ISO)" '$(CMDLINE)'+# Scan built Phase 1 / Phase 2 binaries for instructions outside AVX1 (use with AVX1=1)+# need-avx1 comes first, so a run without AVX1=1 stops before it rebuilds anything+isa-check: need-avx1 $(TARGET) $(OS_ELF)+ python3 scripts/check_isa.py $(TARGET) $(OS_ELF)++.PHONY: need-avx1+need-avx1:+ @test "$(AVX1)" = 1 || { echo "isa-check needs AVX1=1 (it scans the AVX1 binaries)" >&2; exit 2; }+os-run: $(OS_ELF)qemu-system-x86_64 -enable-kvm -cpu host -m $(RAM) -smp $(SMP) \-kernel $(OS_ELF) -initrd "$(MODEL)" \@@ -190,6 +200,12 @@ $(TRAIN_TARGET): $(TRAIN_OBJS)train: $(TRAIN_TARGET)+# Phase 3 has its own AVX2 + FMA kernels; an AVX1 math.o would make a mixed, untested trainer+$(TRAIN_TARGET): | avx1-guard+.PHONY: avx1-guard+avx1-guard:+ @test "$(AVX1)" != 1 || { echo "Phase 3 (train) has no AVX1 build; build it without AVX1=1" >&2; exit 2; }+train-check: $(TRAIN_TARGET)ls -la $(TRAIN_TARGET)file $(TRAIN_TARGET)diff --git a/README.md b/README.mdindex 0970bd8..cd7dbeb 100644--- a/README.md+++ b/README.md@@ -108,7 +108,7 @@ make all # Builds Phase 1 (asm-llm, test_math), Phase 2 (asm-llm-os.elf), Phas<details><summary><b>System Requirements, Repository Layout & Verification Summary</b></summary>-- **Requirements:** x86-64 CPU with **AVX2 + FMA + F16C**, `nasm`, and GNU `binutils` (`ld`, `objcopy`). Phase 2 ISOs use `grub-mkrescue` (`grub-pc-bin`, `grub-efi-amd64-bin`, `mtools`, `xorriso`) and `qemu-system-x86_64` (KVM). Phase 4 requires AMD SVM + NPT (`nested=1`) and kernel headers; Phase 5 targets Linux `6.12` (`CONFIG_BPF_LSM=y`). Python (`numpy`, optional `torch`/`transformers`) is only used for offline weight export and reference harnesses.+- **Requirements:** x86-64 CPU with **AVX2 + FMA + F16C** (Phases 1–2 also build for AVX + SSE4.1 only with `AVX1=1`, Sandy / Ivy Bridge: [details](01-qwen3-inference/README.md#avx1-build-for-sandy-bridge--ivy-bridge-avx11)), `nasm`, and GNU `binutils` (`ld`, `objcopy`). Phase 2 ISOs use `grub-mkrescue` (`grub-pc-bin`, `grub-efi-amd64-bin`, `mtools`, `xorriso`) and `qemu-system-x86_64` (KVM). Phase 4 requires AMD SVM + NPT (`nested=1`) and kernel headers; Phase 5 targets Linux `6.12` (`CONFIG_BPF_LSM=y`). Python (`numpy`, optional `torch`/`transformers`) is only used for offline weight export and reference harnesses.- **Repository Map:** [`shared/`](shared/) (3,857-line shared NASM core reused across Phases 1–3), [`01-qwen3-inference/`](01-qwen3-inference/), [`02-baremetal-os/`](02-baremetal-os/), [`03-minigpt-train/`](03-minigpt-train/), [`04-ring1-kernel-surgeon/`](04-ring1-kernel-surgeon/), [`05-ebpf-jev/`](05-ebpf-jev/), [`scripts/`](scripts/), [`assets/`](assets/), [`Makefile`](Makefile).- **Verification Highlights:**- **Phase 1:** `FAST_Q8=1` matches PyTorch FP32 `Qwen3-0.6B` (`cosine = 0.9996517`, `64/64` exact greedy tokens; `FAST_Q8=0` hits `1.000000000` vs Python Q8_0), deterministic across `1T..40T`.diff --git a/scripts/check_isa.py b/scripts/check_isa.pynew file mode 100644index 0000000..2fc2709--- /dev/null+++ b/scripts/check_isa.py@@ -0,0 +1,80 @@+#!/usr/bin/env python3+"""Scan a built binary for instruction forms outside the AVX1 (Sandy Bridge) ISA.++Usage: python3 scripts/check_isa.py build/asm-llm [build/asm-llm-os.elf ...]++Flags the forms listed below, not every possible extension:+ - FMA and F16C;+ - AVX2: 256-bit integer ops (vp* on ymm, vmovntdqa / vmpsadbw on ymm),+ vpbroadcast*, register-source vbroadcastss/sd, lane-crossing permutes,+ gathers, variable shifts, masked moves, vpblendd;+ - AVX-512: any zmm or mask (k0..k7) register;+ - BMI1/BMI2/LZCNT and other post-Sandy-Bridge scalar extensions+ (movbe, rdrand, rdseed, adcx/adox, rd/wr fs/gs base, invpcid, clflushopt, clwb).+Exit status 1 if anything is found.+"""++import re+import subprocess+import sys++AVX1_YMM_VP_OK = {"vpermilps", "vpermilpd", "vperm2f128", "vptest"}+AVX2_ON_YMM = {"vmovntdqa", "vmpsadbw"}+ALWAYS_BAD = re.compile(+ r"^(vfn?m(add|sub)(sub)?\d{3}[ps][sd]|vfmaddsub\d{3}p[sd]|vfmsubadd\d{3}p[sd]"+ r"|vcvtph2ps|vcvtps2ph"+ r"|vpbroadcast[bwdq]|vbroadcasti128|vinserti128|vextracti128|vperm2i128"+ r"|vpermd|vpermq|vpermps|vpermpd|vp?gather\w+|vpmaskmov[dq]"+ r"|vps[lr]lv[dq]|vpsravd|vpblendd"+ r"|andn|bextr|blsi|blsmsk|blsr|bzhi|mulx|pdep|pext|rorx|sarx|shlx|shrx|lzcnt|tzcnt"+ r"|movbe|rdrand|rdseed|adcx|adox|rd[fg]sbase|wr[fg]sbase|invpcid|clflushopt|clwb)$"+)+AVX512_REG = re.compile(r"\b(zmm\d+|k[0-7])\b")+++def disassemble(path):+ head = subprocess.run(["objdump", "-f", path], capture_output=True, text=True, check=True).stdout+ # The Multiboot kernel is an ELF32 wrapper around 64-bit code: decode it as x86-64.+ # Its small 32-bit entry stub may decode as noise; it holds no SIMD code.+ arch = ["-m", "i386:x86-64"] if "elf32" in head else []+ return subprocess.run(+ ["objdump", "-d", "-M", "intel", *arch, "--no-show-raw-insn", path],+ capture_output=True, text=True, check=True,+ ).stdout+++def scan(path):+ bad = []+ for line in disassemble(path).splitlines():+ m = re.match(r"\s*([0-9a-f]+):\s+(\S+)\s*(.*)", line)+ if not m:+ continue+ addr, mnem, ops = m.groups()+ reason = None+ if ALWAYS_BAD.match(mnem):+ reason = "FMA/F16C/AVX2/BMI or later"+ elif AVX512_REG.search(ops):+ reason = "AVX-512 register"+ elif "ymm" in ops and (mnem in AVX2_ON_YMM or (mnem.startswith("vp") and mnem not in AVX1_YMM_VP_OK)):+ reason = "AVX2 256-bit integer"+ elif mnem in ("vbroadcastss", "vbroadcastsd") and re.search(r",\s*xmm\d+\s*$", ops):+ reason = "AVX2 register-source broadcast"+ if reason:+ bad.append(f"{path}: {addr}: {mnem} {ops} [{reason}]")+ return bad+++def main():+ paths = sys.argv[1:] or ["build/asm-llm"]+ bad = []+ for p in paths:+ found = scan(p)+ print(f"{p}: {len(found)} non-AVX1 instruction(s)")+ bad += found+ for b in bad[:200]:+ print(" " + b)+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ main()diff --git a/scripts/test_math.py b/scripts/test_math.pyindex 2d5b3fa..b070f51 100644--- a/scripts/test_math.py+++ b/scripts/test_math.py@@ -34,18 +34,20 @@ def main():])in_up = rng.normal(0.0, 2.0, size=64).astype(np.float32)- # 5. matmul Q8_0 (8 rows x 64 cols): v1 fp32 scales + v2 fp16 scales- in_mm_x = rng.normal(0.0, 1.5, size=64).astype(np.float32)- w_f32 = rng.normal(0.0, 0.5, size=(8, 64)).astype(np.float32)- wb = w_f32.reshape(8, 2, 32)+ # 5. matmul Q8_0 (8 rows x 160 cols): v1 fp32 scales + v2 fp16 scales+ # K = 160 runs one 128-byte 4-block body and one 32-byte tail block+ K, NB = 160, 5+ in_mm_x = rng.normal(0.0, 1.5, size=K).astype(np.float32)+ w_f32 = rng.normal(0.0, 0.5, size=(8, K)).astype(np.float32)+ wb = w_f32.reshape(8, NB, 32)ws = (np.max(np.abs(wb), axis=2) / np.float32(127.0)).astype(np.float32)wq = np.clip(np.rint(wb / ws[:, :, None]), -127, 127).astype(np.int8)- in_mm_w = np.concatenate([wq.reshape(8, 64).view(np.uint8), ws.astype("<f4").view(np.uint8).reshape(8, 8)], axis=1).tobytes()+ in_mm_w = np.concatenate([wq.reshape(8, K).view(np.uint8), ws.astype("<f4").view(np.uint8).reshape(8, NB * 4)], axis=1).tobytes()ws16 = ws.astype(np.float16)ws16_f32 = ws16.astype(np.float32)wq16 = np.clip(np.rint(wb / ws16_f32[:, :, None]), -127, 127).astype(np.int8)- in_mm_w16 = np.concatenate([wq16.reshape(8, 64).view(np.uint8), ws16.astype("<f2").view(np.uint8).reshape(8, 4)], axis=1).tobytes()+ in_mm_w16 = np.concatenate([wq16.reshape(8, K).view(np.uint8), ws16.astype("<f2").view(np.uint8).reshape(8, NB * 2)], axis=1).tobytes()payload = (in_exp.tobytes()@@ -102,7 +104,7 @@ def main():], dtype=np.float64)rel_silu = np.max(np.abs(out_silu.astype(np.float64) - ref_silu) / np.maximum(np.abs(ref_silu), 1.0))- xb = in_mm_x.reshape(2, 32).astype(np.float32)+ xb = in_mm_x.reshape(NB, 32).astype(np.float32)ref_mm_f32 = np.sum(np.einsum("mnb,nb->mn", wq.astype(np.float32), xb) * ws, axis=1).astype(np.float32)ref_mm16_f32 = np.sum(np.einsum("mnb,nb->mn", wq16.astype(np.float32), xb) * ws16_f32, axis=1).astype(np.float32)diff --git a/shared/isa.inc b/shared/isa.incnew file mode 100644index 0000000..681788c--- /dev/null+++ b/shared/isa.inc@@ -0,0 +1,118 @@+; ============================================================================+; isa.inc — ISA selection helpers (AVX2+FMA+F16C default, AVX1 fallback)+;+; AVX1=0 (default): unchanged code paths, AVX2 + FMA + F16C.+; AVX1=1 : AVX (256-bit float) + VEX-128 SSSE3/SSE4.1 integer only.+; No FMA, no F16C, no AVX2. Targets Sandy Bridge / Ivy Bridge+; (Xeon E5-26xx v1/v2). Tested on Sandy Bridge only.+;+; FMA helpers: with AVX1=1 a fused a*b+c becomes a separate multiply and add+; (two roundings instead of one). 231-forms need an explicit scratch register.+; ============================================================================++%ifndef ISA_INC+%define ISA_INC++%ifndef AVX1+%define AVX1 0+%endif++; dst = dst + a * b (scratch = tmp, may alias a)+%macro VFMADD231PS 4+%if AVX1+ vmulps %4, %2, %3+ vaddps %1, %1, %4+%else+ vfmadd231ps %1, %2, %3+%endif+%endmacro++; dst = dst - a * b (scratch = tmp, may alias a)+%macro VFNMADD231PS 4+%if AVX1+ vmulps %4, %2, %3+ vsubps %1, %1, %4+%else+ vfnmadd231ps %1, %2, %3+%endif+%endmacro++; dst = dst * a + b (no scratch needed)+%macro VFMADD213PS 3+%if AVX1+ vmulps %1, %1, %2+ vaddps %1, %1, %3+%else+ vfmadd213ps %1, %2, %3+%endif+%endmacro++; Scalar double variants+%macro VFMADD231SD 4+%if AVX1+ vmulsd %4, %2, %3+ vaddsd %1, %1, %4+%else+ vfmadd231sd %1, %2, %3+%endif+%endmacro++%macro VFNMADD231SD 4+%if AVX1+ vmulsd %4, %2, %3+ vsubsd %1, %1, %4+%else+ vfnmadd231sd %1, %2, %3+%endif+%endmacro++%macro VFMADD213SD 3+%if AVX1+ vmulsd %1, %1, %2+ vaddsd %1, %1, %3+%else+ vfmadd213sd %1, %2, %3+%endif+%endmacro++; Software fp16 -> fp32 for 4 halves in the low 64 bits of an xmm register+; (replacement for F16C vcvtph2ps xmm, xmm). Exact for zero, subnormal and+; normal halves (shift into fp32 position, then scale by 2^112, which also+; turns fp16 subnormals into the right normal fp32 value). Inf/NaN are not+; produced; Q8_0 block scales never hold them.+; %1 = xmm in/out, %2 = xmm scratch+; Needs 16-byte constants f16_sign_mask (4x 0x00008000) and f16_magic+; (4x 0x77800000 = 2^112) in the including file.+%macro CVTPH2PS_SW 2+ vpmovzxwd %1, %1 ; 4x u16 -> 4x u32 (SSE4.1)+ vpand %2, %1, [rel f16_sign_mask] ; sign bit+ vpxor %1, %1, %2 ; |h|+ vpslld %1, %1, 13 ; exponent + mantissa -> fp32 slots+ vpslld %2, %2, 16 ; sign -> bit 31+ vmulps %1, %1, [rel f16_magic] ; rebias exponent by 2^112+ vorps %1, %1, %2+%endmacro++; fp16 -> fp32 of 4 halves in the low 64 bits of %1 (in place).+; F16C when AVX1=0, exact software path when AVX1=1. %2 = xmm scratch.+%macro CVTPH2PS4 2+%if AVX1+ CVTPH2PS_SW %1, %2+%else+ vcvtph2ps %1, %1+%endif+%endmacro++; Broadcast lane 0 of an xmm register to all 8 lanes of its own ymm register+; (AVX2 has vbroadcastss ymm, xmm; AVX1 only allows a memory source).+; %1 = ymmN, %2 = xmmN (same register number)+%macro VBROADCASTSS_R 2+%if AVX1+ vshufps %2, %2, %2, 0+ vinsertf128 %1, %1, %2, 1+%else+ vbroadcastss %1, %2+%endif+%endmacro++%endifdiff --git a/shared/math.asm b/shared/math.asmindex e507863..1407fc7 100644--- a/shared/math.asm+++ b/shared/math.asm@@ -4,7 +4,8 @@; Functions:; fast_expf_avx2 : ymm0 -> ymm0 (8x float32 exp, ~2e-7 rel err, safe clamp); fast_expf_scalar : xmm0 -> xmm0 (scalar float32 exp)-; fast_sincos_f64 : xmm0 (f64) -> xmm0 (sin f64), xmm1 (cos f64) (~1e-13 err)+; fast_sincos_f64 : xmm0 (f64) -> xmm0 (sin f64), xmm1 (cos f64) (~1e-13 err;+; AVX1=1: same while |x| < ~6.6e6, see the function); fast_sincosf : xmm0 (f32) -> xmm0 (sin f32), xmm1 (cos f32) (~1e-7 err); log_f64 : xmm0 (f64 > 0) -> xmm0 (ln f64, ~1e-12 err); exp_f64 : xmm0 (f64) -> xmm0 (exp f64, ~1e-12 err)@@ -22,6 +23,8 @@bits 64default rel+%include "isa.inc"+section .textglobal fast_expf_avx2@@ -60,28 +63,39 @@ fast_expf_avx2:; Cody-Waite range reduction: r = (x - k_f*ln2_hi) - k_f*ln2_lovbroadcastss ymm4, [rel f_ln2_hi]- vfnmadd231ps ymm0, ymm1, ymm4+ VFNMADD231PS ymm0, ymm1, ymm4, ymm3vbroadcastss ymm4, [rel f_ln2_lo]- vfnmadd231ps ymm0, ymm1, ymm4+ VFNMADD231PS ymm0, ymm1, ymm4, ymm3; Horner degree-6: 1 + r*(1 + r*(c2 + r*(c3 + r*(c4 + r*(c5 + r*c6)))))vbroadcastss ymm3, [rel f_exp_c6]vbroadcastss ymm4, [rel f_exp_c5]- vfmadd213ps ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4vbroadcastss ymm4, [rel f_exp_c4]- vfmadd213ps ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4vbroadcastss ymm4, [rel f_exp_c3]- vfmadd213ps ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4vbroadcastss ymm4, [rel f_exp_c2]- vfmadd213ps ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4vbroadcastss ymm4, [rel f_one]- vfmadd213ps ymm3, ymm0, ymm4- vfmadd213ps ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4+ VFMADD213PS ymm3, ymm0, ymm4; Reconstruct 2^k via IEEE-754 exponent shift: (k + 127) << 23+%if AVX1+ ; ymm1 (k_f) is dead here; split the integer exponent math into halves+ vmovdqa xmm4, [rel i_127x4]+ vextractf128 xmm1, ymm2, 1+ vpaddd xmm2, xmm2, xmm4+ vpaddd xmm1, xmm1, xmm4+ vpslld xmm2, xmm2, 23+ vpslld xmm1, xmm1, 23+ vinsertf128 ymm2, ymm2, xmm1, 1+%elsevpbroadcastd ymm4, [rel i_127]vpaddd ymm2, ymm2, ymm4vpslld ymm2, ymm2, 23+%endifvmulps ymm0, ymm3, ymm2vandps ymm0, ymm0, ymm5 ; flush underflowed lanes to 0.0ret@@ -90,14 +104,15 @@ fast_expf_avx2:; xmm0 = fast_expf_scalar(xmm0); ----------------------------------------------------------------------------fast_expf_scalar:- vbroadcastss ymm0, xmm0+ VBROADCASTSS_R ymm0, xmm0call fast_expf_avx2ret; ----------------------------------------------------------------------------; (xmm0=sin, xmm1=cos) = fast_sincos_f64(xmm0=angle_f64); Cody-Waite FP64 reduction by pi/2 + degree-11/10 Taylor polynomial.-; Accuracy: < 1e-13 across [-1e7, +1e7].+; Accuracy: < 1e-13 across [-1e7, +1e7] (AVX1=1, no FMA: across about +-6.6e6,+; where q * pio2_hi stays exact).; Clobbers rax, xmm0..xmm5.; ----------------------------------------------------------------------------fast_sincos_f64:@@ -106,29 +121,32 @@ fast_sincos_f64:vcvtsd2si rax, xmm1 ; q = (int64)q_d; r = (x - q_d * pio2_hi) - q_d * pio2_lo+ ; (AVX1: pio2_hi has 31 significant bits, so q * pio2_hi stays exact+ ; without FMA while |q| < 2^22, i.e. |angle| < ~6.6e6 rad; RoPE angles+ ; are pos * inv_freq < max_seq_len)vmovsd xmm2, [rel d_pio2_hi]- vfnmadd231sd xmm0, xmm1, xmm2+ VFNMADD231SD xmm0, xmm1, xmm2, xmm3vmovsd xmm2, [rel d_pio2_lo]- vfnmadd231sd xmm0, xmm1, xmm2 ; xmm0 = r in [-pi/4, +pi/4]+ VFNMADD231SD xmm0, xmm1, xmm2, xmm3 ; xmm0 = r in [-pi/4, +pi/4]vmulsd xmm2, xmm0, xmm0 ; xmm2 = r^2; sin(r) = r * (1 + r2*(s1 + r2*(s2 + r2*(s3 + r2*(s4 + r2*s5)))))vmovsd xmm3, [rel d_sin_s5]- vfmadd213sd xmm3, xmm2, [rel d_sin_s4]- vfmadd213sd xmm3, xmm2, [rel d_sin_s3]- vfmadd213sd xmm3, xmm2, [rel d_sin_s2]- vfmadd213sd xmm3, xmm2, [rel d_sin_s1]- vfmadd213sd xmm3, xmm2, [rel d_one]+ VFMADD213SD xmm3, xmm2, [rel d_sin_s4]+ VFMADD213SD xmm3, xmm2, [rel d_sin_s3]+ VFMADD213SD xmm3, xmm2, [rel d_sin_s2]+ VFMADD213SD xmm3, xmm2, [rel d_sin_s1]+ VFMADD213SD xmm3, xmm2, [rel d_one]vmulsd xmm3, xmm3, xmm0 ; xmm3 = sin(r); cos(r) = 1 + r2*(c1 + r2*(c2 + r2*(c3 + r2*(c4 + r2*c5))))vmovsd xmm4, [rel d_cos_c5]- vfmadd213sd xmm4, xmm2, [rel d_cos_c4]- vfmadd213sd xmm4, xmm2, [rel d_cos_c3]- vfmadd213sd xmm4, xmm2, [rel d_cos_c2]- vfmadd213sd xmm4, xmm2, [rel d_cos_c1]- vfmadd213sd xmm4, xmm2, [rel d_one] ; xmm4 = cos(r)+ VFMADD213SD xmm4, xmm2, [rel d_cos_c4]+ VFMADD213SD xmm4, xmm2, [rel d_cos_c3]+ VFMADD213SD xmm4, xmm2, [rel d_cos_c2]+ VFMADD213SD xmm4, xmm2, [rel d_cos_c1]+ VFMADD213SD xmm4, xmm2, [rel d_one] ; xmm4 = cos(r); Quadrant selection based on q & 3and eax, 3@@ -201,17 +219,17 @@ log_f64:; Horner: 1 + u^2*(1/3 + u^2*(1/5 + u^2*(1/7 + u^2*(1/9 + u^2*(1/11 + u^2/13)))))vmovsd xmm3, [rel d_inv13]- vfmadd213sd xmm3, xmm2, [rel d_inv11]- vfmadd213sd xmm3, xmm2, [rel d_inv9]- vfmadd213sd xmm3, xmm2, [rel d_inv7]- vfmadd213sd xmm3, xmm2, [rel d_inv5]- vfmadd213sd xmm3, xmm2, [rel d_inv3]- vfmadd213sd xmm3, xmm2, [rel d_one]+ VFMADD213SD xmm3, xmm2, [rel d_inv11]+ VFMADD213SD xmm3, xmm2, [rel d_inv9]+ VFMADD213SD xmm3, xmm2, [rel d_inv7]+ VFMADD213SD xmm3, xmm2, [rel d_inv5]+ VFMADD213SD xmm3, xmm2, [rel d_inv3]+ VFMADD213SD xmm3, xmm2, [rel d_one]vmulsd xmm3, xmm3, xmm0vaddsd xmm3, xmm3, xmm3 ; 2 * u * poly = ln(m)vcvtsi2sd xmm4, xmm4, rcx ; (double)e- vfmadd231sd xmm3, xmm4, [rel d_ln2_full]+ VFMADD231SD xmm3, xmm4, [rel d_ln2_full], xmm4vmovapd xmm0, xmm3ret@@ -225,22 +243,22 @@ exp_f64:vcvtsd2si rax, xmm1 ; kvmovsd xmm2, [rel d_ln2_hi]- vfnmadd231sd xmm0, xmm1, xmm2+ VFNMADD231SD xmm0, xmm1, xmm2, xmm3vmovsd xmm2, [rel d_ln2_lo]- vfnmadd231sd xmm0, xmm1, xmm2 ; r in [-ln2/2, ln2/2]+ VFNMADD231SD xmm0, xmm1, xmm2, xmm3 ; r in [-ln2/2, ln2/2]; Degree-10 Hornervmovsd xmm3, [rel d_e10]- vfmadd213sd xmm3, xmm0, [rel d_e9]- vfmadd213sd xmm3, xmm0, [rel d_e8]- vfmadd213sd xmm3, xmm0, [rel d_e7]- vfmadd213sd xmm3, xmm0, [rel d_e6]- vfmadd213sd xmm3, xmm0, [rel d_e5]- vfmadd213sd xmm3, xmm0, [rel d_e4]- vfmadd213sd xmm3, xmm0, [rel d_e3]- vfmadd213sd xmm3, xmm0, [rel d_half]- vfmadd213sd xmm3, xmm0, [rel d_one]- vfmadd213sd xmm3, xmm0, [rel d_one]+ VFMADD213SD xmm3, xmm0, [rel d_e9]+ VFMADD213SD xmm3, xmm0, [rel d_e8]+ VFMADD213SD xmm3, xmm0, [rel d_e7]+ VFMADD213SD xmm3, xmm0, [rel d_e6]+ VFMADD213SD xmm3, xmm0, [rel d_e5]+ VFMADD213SD xmm3, xmm0, [rel d_e4]+ VFMADD213SD xmm3, xmm0, [rel d_e3]+ VFMADD213SD xmm3, xmm0, [rel d_half]+ VFMADD213SD xmm3, xmm0, [rel d_one]+ VFMADD213SD xmm3, xmm0, [rel d_one]add rax, 1023shl rax, 52@@ -356,9 +374,9 @@ rope_apply_avx2:vmovups ymm2, [rsi + rax] ; cosvmovups ymm3, [rdx + rax] ; sinvmulps ymm4, ymm0, ymm2 ; x1 * cos- vfnmadd231ps ymm4, ymm1, ymm3 ; x1 * cos - x2 * sin+ VFNMADD231PS ymm4, ymm1, ymm3, ymm6 ; x1 * cos - x2 * sinvmulps ymm5, ymm1, ymm2 ; x2 * cos- vfmadd231ps ymm5, ymm0, ymm3 ; x2 * cos + x1 * sin+ VFMADD231PS ymm5, ymm0, ymm3, ymm7 ; x2 * cos + x1 * sinvmovups [rdi + rax], ymm4vmovups [r11 + rax], ymm5add rax, 32@@ -389,10 +407,10 @@ rmsnorm_avx2:vmovups ymm6, [rsi + rax + 32]vmovups ymm7, [rsi + rax + 64]vmovups ymm8, [rsi + rax + 96]- vfmadd231ps ymm1, ymm5, ymm5- vfmadd231ps ymm2, ymm6, ymm6- vfmadd231ps ymm3, ymm7, ymm7- vfmadd231ps ymm4, ymm8, ymm8+ VFMADD231PS ymm1, ymm5, ymm5, ymm5+ VFMADD231PS ymm2, ymm6, ymm6, ymm6+ VFMADD231PS ymm3, ymm7, ymm7, ymm7+ VFMADD231PS ymm4, ymm8, ymm8, ymm8add rax, 128jmp .ss_lp.ss_red:@@ -413,7 +431,7 @@ rmsnorm_avx2:vsqrtss xmm1, xmm1, xmm1 ; rmsvmovss xmm2, [rel f_one]vdivss xmm1, xmm2, xmm1 ; inv_rms = 1.0 / rms- vbroadcastss ymm1, xmm1+ VBROADCASTSS_R ymm1, xmm1xor eax, eax.scale_lp:@@ -452,7 +470,7 @@ softmax_avx2:inc rcxjmp .max_lp.max_done:- vbroadcastss ymm6, xmm6 ; ymm6 = max_val (preserved across fast_expf_avx2)+ VBROADCASTSS_R ymm6, xmm6 ; ymm6 = max_val (preserved across fast_expf_avx2)vxorps ymm7, ymm7, ymm7 ; ymm7 = sum accumulator (preserved!)xor ecx, ecx ; index i@@ -492,7 +510,7 @@ softmax_avx2:.norm:vmovss xmm0, [rel f_one]vdivss xmm7, xmm0, xmm7 ; inv_sum- vbroadcastss ymm7, xmm7+ VBROADCASTSS_R ymm7, xmm7xor ecx, ecx.norm8_lp:lea rax, [rcx + 8]@@ -533,8 +551,13 @@ silu_mul_avx2:shl rdx, 2 ; n_bytesmov rbx, rdx+%if AVX1+ vbroadcastss ymm8, [rel i_abs_mask] ; 0x7FFFFFFF (preserved across fast_expf_avx2!)+ vbroadcastss ymm9, [rel i_sign_mask]; 0x80000000+%elsevpbroadcastd ymm8, [rel i_abs_mask] ; 0x7FFFFFFF (preserved across fast_expf_avx2!)vpbroadcastd ymm9, [rel i_sign_mask]; 0x80000000+%endifvbroadcastss ymm10, [rel f_one] ; 1.0fxor ecx, ecx@@ -598,9 +621,16 @@ argmax_f32:sub rsp, 64 ; 32B vals + 32B idxsvmovups ymm0, [rdi] ; best_vals = x[0..7]+%if AVX1+ ; indices tracked as fp32: exact while n < 2^24 (16,777,216)+ vmovaps ymm1, [rel f_iota8] ; best_idxs = [0..7]+ vbroadcastss ymm3, [rel f_eight] ; step = [8..8]+ vaddps ymm2, ymm1, ymm3 ; cur_idxs = [8..15]+%elsevmovdqa ymm1, [rel i_iota8] ; best_idxs = [0..7]vpbroadcastd ymm3, [rel i_eight] ; step = [8..8]vpaddd ymm2, ymm1, ymm3 ; cur_idxs = [8..15]+%endifmov rcx, 8mov rdx, rsiand rdx, -8 ; n8 = n & ~7@@ -611,12 +641,19 @@ argmax_f32:vcmpps ymm5, ymm4, ymm0, 14 ; _CMP_GT_OS: strict > preserves first indexvblendvps ymm0, ymm0, ymm4, ymm5vblendvps ymm1, ymm1, ymm2, ymm5+%if AVX1+ vaddps ymm2, ymm2, ymm3+%elsevpaddd ymm2, ymm2, ymm3+%endifadd rcx, 8jmp .v_lp.v_red:vmovups [rsp], ymm0+%if AVX1+ vcvttps2dq ymm1, ymm1+%endifvmovdqu [rsp + 32], ymm1vmovss xmm0, [rsp] ; best_valmov eax, [rsp + 32] ; best_idx (zero-extended)@@ -685,7 +722,7 @@ sample_top_p:; Scale logits[i] / temp -> probs[i]vmovss xmm2, [rel f_one]vdivss xmm2, xmm2, xmm0 ; inv_temp- vbroadcastss ymm2, xmm2+ VBROADCASTSS_R ymm2, xmm2xor eax, eax.sc_lp:lea rcx, [rax + 8]@@ -810,6 +847,13 @@ section .rodataalign 32i_iota8: dd 0, 1, 2, 3, 4, 5, 6, 7i_eight: dd 8+%if AVX1+align 32+f_iota8: dd 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0+f_eight: dd 8.0+align 16+i_127x4: times 4 dd 127+%endif; Float32 constantsf_one: dd 1.0f_exp_hi: dd 88.3762626647949diff --git a/shared/matmul.asm b/shared/matmul.asmindex 28ff2fd..913ec76 100644--- a/shared/matmul.asm+++ b/shared/matmul.asm@@ -19,6 +19,9 @@; Auto-detects v1 (fp32) and v2 (fp16) scales.; FAST_Q8=0 (legacy) : Q8_0 x FP32 AVX2+FMA exact FP32-activation matmul,; auto-detects v1 (fp32) and v2 (fp16) scales.+; AVX1=1 : FAST_Q8=1 kernel on AVX + VEX-128 SSSE3/SSE4.1 only+; (Sandy/Ivy Bridge): two 16-byte halves per Q8_0+; block, separate mul+add, software fp16 scales.;; Functions:; matmul_set_fp16 : (uint64 is_fp16)@@ -37,6 +40,12 @@ default rel%define FAST_Q8 1%endif+%include "isa.inc"++%if AVX1 && !FAST_Q8+%error "AVX1=1 is implemented for FAST_Q8=1 only"+%endif+%ifndef Q8_PREFETCH%define Q8_PREFETCH prefetcht0%endif@@ -86,18 +95,28 @@ dequant_row_q8_0:.sc_f16:movzx r10d, word [r8 + rax*2] ; v2 fp16 scale[b]vmovd xmm4, r10d- vcvtph2ps xmm4, xmm4- vbroadcastss ymm4, xmm4+ CVTPH2PS4 xmm4, xmm5+ VBROADCASTSS_R ymm4, xmm4.sc_ok:mov r9, raxshl r9, 5 ; b * 32 (q offset)mov r10, raxshl r10, 7 ; b * 128 (out offset)+%if AVX1+%assign i 0+%rep 4+ vpmovsxbd xmm %+ i, dword [rdi + r9 + i*8]+ vpmovsxbd xmm5, dword [rdi + r9 + i*8 + 4]+ vinsertf128 ymm %+ i, ymm %+ i, xmm5, 1+%assign i i+1+%endrep+%elsevpmovsxbd ymm0, qword [rdi + r9]vpmovsxbd ymm1, qword [rdi + r9 + 8]vpmovsxbd ymm2, qword [rdi + r9 + 16]vpmovsxbd ymm3, qword [rdi + r9 + 24]+%endifvcvtdq2ps ymm0, ymm0vcvtdq2ps ymm1, ymm1vcvtdq2ps ymm2, ymm2@@ -130,12 +149,20 @@ quantize_x_q8_0:lea r9, [rel q8_xq]lea r10, [rel q8_xs]+%if AVX1+ vbroadcastss ymm12, [rel q8_abs_mask]+%elsevpbroadcastd ymm12, [rel q8_abs_mask]+%endifvmovss xmm13, [rel q8_inv_127]vmovss xmm14, [rel q8_f127]vxorps xmm15, xmm15, xmm15+%if AVX1+ vmovdqa xmm10, [rel q8_min_i8x16]+%elsevmovdqa ymm11, [rel q8_pack_perm]vpbroadcastb ymm10, [rel q8_min_i8]+%endifxor eax, eax ; b = 0xor r8d, r8d ; x byte offset (b * 128)@@ -172,7 +199,7 @@ quantize_x_q8_0:jbe .qinv_okvdivss xmm6, xmm14, xmm4 ; inv_scale = 127.0f / max_abs.qinv_ok:- vbroadcastss ymm6, xmm6+ VBROADCASTSS_R ymm6, xmm6vmulps ymm0, ymm0, ymm6vmulps ymm1, ymm1, ymm6@@ -184,6 +211,23 @@ quantize_x_q8_0:vcvtps2dq ymm2, ymm2vcvtps2dq ymm3, ymm3+%if AVX1+ ; 128-bit packs keep linear order, no cross-lane permute needed+ vextractf128 xmm4, ymm0, 1+ vextractf128 xmm5, ymm1, 1+ vextractf128 xmm6, ymm2, 1+ vextractf128 xmm7, ymm3, 1+ vpackssdw xmm0, xmm0, xmm4 ; [0..7]+ vpackssdw xmm1, xmm1, xmm5 ; [8..15]+ vpackssdw xmm2, xmm2, xmm6 ; [16..23]+ vpackssdw xmm3, xmm3, xmm7 ; [24..31]+ vpacksswb xmm0, xmm0, xmm1 ; [0..15]+ vpacksswb xmm2, xmm2, xmm3 ; [16..31]+ vpmaxsb xmm0, xmm0, xmm10 ; clamp >= -127+ vpmaxsb xmm2, xmm2, xmm10+ vmovdqa [r9 + rdx], xmm0+ vmovdqa [r9 + rdx + 16], xmm2+%elsevpackssdw ymm0, ymm0, ymm1vpackssdw ymm2, ymm2, ymm3vpacksswb ymm0, ymm0, ymm2@@ -191,6 +235,7 @@ quantize_x_q8_0:vpmaxsb ymm0, ymm0, ymm10 ; clamp >= -127 (prevents -128 overflow)vmovdqa [r9 + rdx], ymm0 ; q8_xq[b*32 .. b*32+31]+%endifadd r8, 128add rdx, 32@@ -199,6 +244,39 @@ quantize_x_q8_0:.qdone:ret+; AVX1 variant: one Q8_0 block (32 B) as two 16-byte halves.+; %1 = byte offset of the block, %2 = vpermilps imm selecting its scale+; from xmm12, %3 = xmm accumulator, %4..%7 = xmm scratch.+; Both halves are summed in int32 (exact) before the single fp32 scale.+%macro INT8_BLK_AVX1 7+ vmovdqa %4, [r11 + rbx + %1] ; x int8 [0..15]+ vmovdqa %5, [r11 + rbx + %1 + 16] ; x int8 [16..31]+ vmovdqu %6, [rax + rbx + %1] ; w int8 [0..15]+ vmovdqu %7, [rax + rbx + %1 + 16] ; w int8 [16..31]+ vpsignb %6, %6, %4 ; w * sign(x)+ vpsignb %7, %7, %5+ vpabsb %4, %4 ; |x|+ vpabsb %5, %5+ vpmaddubsw %6, %4, %6+ vpmaddubsw %7, %5, %7+ vpmaddwd %6, %6, xmm15+ vpmaddwd %7, %7, xmm15+ vpaddd %6, %6, %7+ vcvtdq2ps %6, %6+ vpermilps %4, xmm12, %2+ vmulps %6, %6, %4+ vaddps %3, %3, %6+%endmacro++%macro INT8_1ROW_4BLK_AVX1 0+ Q8_PREFETCH [r8 + rbx]+ Q8_PREFETCH [r8 + rbx + 64]+ INT8_BLK_AVX1 0, 0x00, xmm0, xmm4, xmm5, xmm6, xmm7+ INT8_BLK_AVX1 32, 0x55, xmm1, xmm8, xmm9, xmm10, xmm11+ INT8_BLK_AVX1 64, 0xAA, xmm2, xmm4, xmm5, xmm6, xmm7+ INT8_BLK_AVX1 96, 0xFF, xmm3, xmm8, xmm9, xmm10, xmm11+%endmacro+; Macro: 1-row x 4-block (128 bytes = 2 cache lines) INT8xINT8 AVX2 body.; Preconditions:; rax = w (current row), r8 = s_cur = w + K (scales of current row)@@ -277,7 +355,11 @@ matmul_q8_0_range:jle .exitlea rdx, [rdx + r8 * 4] ; rdx = out_ptr = out + r0 * 4+%if AVX1+ vmovdqa xmm15, [rel q8_one16x8] ; 8x int16(1)+%elsevpbroadcastw ymm15, [rel q8_one16] ; 16x int16(1)+%endiflea r11, [rel q8_xq]lea rbp, [rel q8_xs]mov r15, rcx ; r15 = K@@ -315,9 +397,13 @@ align 16.blk4_f32:vmovups xmm12, [r8 + r9] ; 4x fp32 scale_wvmulps xmm12, xmm12, [rbp + r9] ; * 4x fp32 scale_x+%if AVX1+ INT8_1ROW_4BLK_AVX1+%elsevinsertf128 ymm12, ymm12, xmm12, 1INT8_1ROW_4BLK+%endifadd rbx, 128add r9, 16@@ -327,6 +413,11 @@ align 16.tail_f32:cmp rbx, r15jae .red_f32+%if AVX1+ vmovss xmm12, [r8 + r9]+ vmulss xmm12, xmm12, [rbp + r9]+ INT8_BLK_AVX1 0, 0x00, xmm0, xmm4, xmm5, xmm6, xmm7+%elsevmovdqa ymm4, [r11 + rbx]vpabsb ymm5, ymm4vmovdqu ymm6, [rax + rbx]@@ -338,11 +429,19 @@ align 16vmulss xmm8, xmm8, [rbp + r9]vbroadcastss ymm8, xmm8vfmadd231ps ymm0, ymm6, ymm8+%endifadd rbx, 32add r9, 4jmp .tail_f32.red_f32:+%if AVX1+ vaddps xmm0, xmm0, xmm1+ vaddps xmm2, xmm2, xmm3+ vaddps xmm0, xmm0, xmm2+ vhaddps xmm0, xmm0, xmm0+ vhaddps xmm0, xmm0, xmm0+%elsevaddps ymm0, ymm0, ymm1vaddps ymm2, ymm2, ymm3vaddps ymm0, ymm0, ymm2@@ -350,6 +449,7 @@ align 16vhaddps ymm0, ymm0, ymm0vextractf128 xmm1, ymm0, 1vaddss xmm0, xmm0, xmm1+%endifvmovss [rdx], xmm0add rdx, 4mov rax, r12@@ -385,11 +485,15 @@ align 16align 16.blk4_f16:vmovq xmm12, qword [r8 + r9] ; 4x fp16 scale_w- vcvtph2ps xmm12, xmm12 ; -> 4x fp32+ CVTPH2PS4 xmm12, xmm13 ; -> 4x fp32vmulps xmm12, xmm12, [rbp + r9*2] ; * 4x fp32 scale_x+%if AVX1+ INT8_1ROW_4BLK_AVX1+%elsevinsertf128 ymm12, ymm12, xmm12, 1INT8_1ROW_4BLK+%endifadd rbx, 128add r9, 8@@ -399,6 +503,13 @@ align 16.tail_f16:cmp rbx, r15jae .red_f16+%if AVX1+ movzx ecx, word [r8 + r9]+ vmovd xmm12, ecx+ CVTPH2PS4 xmm12, xmm13+ vmulss xmm12, xmm12, [rbp + r9*2]+ INT8_BLK_AVX1 0, 0x00, xmm0, xmm4, xmm5, xmm6, xmm7+%elsevmovdqa ymm4, [r11 + rbx]vpabsb ymm5, ymm4vmovdqu ymm6, [rax + rbx]@@ -412,11 +523,19 @@ align 16vmulss xmm8, xmm8, [rbp + r9*2]vbroadcastss ymm8, xmm8vfmadd231ps ymm0, ymm6, ymm8+%endifadd rbx, 32add r9, 2jmp .tail_f16.red_f16:+%if AVX1+ vaddps xmm0, xmm0, xmm1+ vaddps xmm2, xmm2, xmm3+ vaddps xmm0, xmm0, xmm2+ vhaddps xmm0, xmm0, xmm0+ vhaddps xmm0, xmm0, xmm0+%elsevaddps ymm0, ymm0, ymm1vaddps ymm2, ymm2, ymm3vaddps ymm0, ymm0, ymm2@@ -424,6 +543,7 @@ align 16vhaddps ymm0, ymm0, ymm0vextractf128 xmm1, ymm0, 1vaddss xmm0, xmm0, xmm1+%endifvmovss [rdx], xmm0add rdx, 4mov rax, r12@@ -564,11 +684,11 @@ matmul_q8_0_range:movzx ebx, word [rdi + r14*2]vmovd xmm9, ebxvcvtph2ps xmm9, xmm9- vbroadcastss ymm9, xmm9+ VBROADCASTSS_R ymm9, xmm9movzx ebx, word [r8 + r14*2]vmovd xmm13, ebxvcvtph2ps xmm13, xmm13- vbroadcastss ymm13, xmm13+ VBROADCASTSS_R ymm13, xmm13.s01_ok:vfmadd231ps ymm0, ymm8, ymm9vfmadd231ps ymm1, ymm12, ymm13@@ -611,11 +731,11 @@ matmul_q8_0_range:movzx ebx, word [r9 + r14*2]vmovd xmm9, ebxvcvtph2ps xmm9, xmm9- vbroadcastss ymm9, xmm9+ VBROADCASTSS_R ymm9, xmm9movzx ebx, word [r10 + r14*2]vmovd xmm13, ebxvcvtph2ps xmm13, xmm13- vbroadcastss ymm13, xmm13+ VBROADCASTSS_R ymm13, xmm13.s23_ok:vfmadd231ps ymm2, ymm8, ymm9vfmadd231ps ymm3, ymm12, ymm13@@ -674,7 +794,7 @@ matmul_q8_0_range:movzx ebx, word [rdi + r14*2]vmovd xmm12, ebxvcvtph2ps xmm12, xmm12- vbroadcastss ymm12, xmm12+ VBROADCASTSS_R ymm12, xmm12.s1_ok:vfmadd231ps ymm0, ymm8, ymm12@@ -726,10 +846,10 @@ dot_f32_avx2:vmovups ymm5, [rdi + rax + 32]vmovups ymm6, [rdi + rax + 64]vmovups ymm7, [rdi + rax + 96]- vfmadd231ps ymm0, ymm4, [rsi + rax]- vfmadd231ps ymm1, ymm5, [rsi + rax + 32]- vfmadd231ps ymm2, ymm6, [rsi + rax + 64]- vfmadd231ps ymm3, ymm7, [rsi + rax + 96]+ VFMADD231PS ymm0, ymm4, [rsi + rax], ymm4+ VFMADD231PS ymm1, ymm5, [rsi + rax + 32], ymm5+ VFMADD231PS ymm2, ymm6, [rsi + rax + 64], ymm6+ VFMADD231PS ymm3, ymm7, [rsi + rax + 96], ymm7add rax, 128jmp .lp.red:@@ -748,7 +868,7 @@ dot_f32_avx2:; dst[i] += alpha * src[i]; ----------------------------------------------------------------------------saxpy_f32_avx2:- vbroadcastss ymm0, xmm0+ VBROADCASTSS_R ymm0, xmm0shl rdx, 2xor eax, eax.lp:@@ -758,10 +878,10 @@ saxpy_f32_avx2:vmovups ymm2, [rdi + rax + 32]vmovups ymm3, [rdi + rax + 64]vmovups ymm4, [rdi + rax + 96]- vfmadd231ps ymm1, ymm0, [rsi + rax]- vfmadd231ps ymm2, ymm0, [rsi + rax + 32]- vfmadd231ps ymm3, ymm0, [rsi + rax + 64]- vfmadd231ps ymm4, ymm0, [rsi + rax + 96]+ VFMADD231PS ymm1, ymm0, [rsi + rax], ymm5+ VFMADD231PS ymm2, ymm0, [rsi + rax + 32], ymm6+ VFMADD231PS ymm3, ymm0, [rsi + rax + 64], ymm7+ VFMADD231PS ymm4, ymm0, [rsi + rax + 96], ymm8vmovups [rdi + rax], ymm1vmovups [rdi + rax + 32], ymm2vmovups [rdi + rax + 64], ymm3@@ -780,6 +900,18 @@ q8_f127: dd 127.0q8_inv_127: dd 0.007874015748031496 ; 1.0f / 127.0fq8_one16: dw 1q8_min_i8: db -127+%if AVX1+align 16+q8_one16x8: times 8 dw 1+q8_min_i8x16: times 16 db -127+%endif+%endif++%if AVX1+section .rodata+align 16+f16_sign_mask: times 4 dd 0x00008000+f16_magic: times 4 dd 0x77800000 ; 2^112%endifsection .bss