Skip to content

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 SSE2=1 baseline build: run the bare-metal OS on any x86-64 CPU

sanbo8aa081d8e678
diff --git a/02-baremetal-os/boot.asm b/02-baremetal-os/boot.asm
index 4c944f4..b80e459 100644
--- a/02-baremetal-os/boot.asm
+++ b/02-baremetal-os/boot.asm
@@ -15,6 +15,10 @@
%include "os_constants.inc"
%include "isa.inc"
+%ifndef SSE2
+%define SSE2 0
+%endif
+
extern _bss_start
extern _bss_end
extern kernel_main
@@ -207,6 +211,13 @@ check_cpu_features:
mov edx, (1 << 9) | (1 << 19) | (1 << 26) | (1 << 28)
and ecx, edx
cmp ecx, edx
+%elif SSE2
+ ; EDX: bit 24 (FXSR), bit 26 (SSE2) -- the x86-64 baseline; nothing newer needed
+ mov eax, (1 << 24) | (1 << 26)
+ and edx, eax
+ cmp edx, eax
+%endif
+%if AVX1 || SSE2
jne .no
mov eax, 1
pop rbx
@@ -251,6 +262,12 @@ enable_avx_fpu:
or ax, 0x0002 ; set CR0.MP (bit 1)
mov cr0, rax
+%if SSE2
+ ; SSE2 baseline: no XSAVE / XCR0 / AVX state, only FXSAVE-style SSE enable
+ mov rax, cr4
+ or eax, (1 << 9) | (1 << 10) ; OSFXSR | OSXMMEXCPT
+ mov cr4, rax
+%else
mov rax, cr4
or eax, (1 << 9) | (1 << 10) | (1 << 18) ; OSFXSR | OSXMMEXCPT | OSXSAVE
mov cr4, rax
@@ -259,6 +276,7 @@ enable_avx_fpu:
xgetbv
or eax, 7 ; x87 (bit 0) | SSE (bit 1) | AVX (bit 2)
xsetbv
+%endif
fninit
ldmxcsr [rel default_mxcsr]
diff --git a/02-baremetal-os/kernel.asm b/02-baremetal-os/kernel.asm
index ebf3f1b..72b53a4 100644
--- a/02-baremetal-os/kernel.asm
+++ b/02-baremetal-os/kernel.asm
@@ -60,6 +60,13 @@ extern write_u64
extern write_f64_2dp
extern write_hex64_raw
+%ifndef SSE2
+%define SSE2 0
+%endif
+%if SSE2
+%include "sse2_compat.inc"
+%endif
+
section .text
global kernel_main
@@ -1417,6 +1424,8 @@ ban_title_post: db " in 100% Pure x86-64 Assembly", 10, 0
ban_cpu: db " CPU : ", 0
%if AVX1
ban_avx_tsc: db " (AVX1, ", 0
+%elif SSE2
+ban_avx_tsc: db " (SSE2, ", 0
%else
ban_avx_tsc: db " (AVX2+FMA, ", 0
%endif
@@ -1491,6 +1500,8 @@ key_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
+%elif SSE2
+msg_err_avx2: db "[FATAL] CPU lacks SSE2/FXSR (not an x86-64 CPU?)", 10, 0
%else
msg_err_avx2: db "[FATAL] CPU lacks AVX2+FMA+XSAVE (use QEMU -cpu host)", 10, 0
%endif
diff --git a/02-baremetal-os/runtime.asm b/02-baremetal-os/runtime.asm
index 91213ee..678f7b0 100644
--- a/02-baremetal-os/runtime.asm
+++ b/02-baremetal-os/runtime.asm
@@ -13,6 +13,12 @@ bits 64
default rel
%include "os_constants.inc"
+%ifndef SSE2
+%define SSE2 0
+%endif
+%if SSE2
+%include "sse2_compat.inc"
+%endif
extern _kernel_end
extern console_write
@@ -262,6 +268,22 @@ sys_mmap_anon:
shr r8, 20
mov [rel g_arena_used_mb], r8
+%if SSE2
+ ; SSE2 zeroing (64 bytes per iteration; rax is 64B aligned, rcx is 64B mult)
+ pxor xmm0, xmm0
+ mov r8, rax
+ mov r9, rcx
+.zero_lp:
+ test r9, r9
+ jz .zero_done
+ movdqa [r8], xmm0
+ movdqa [r8 + 16], xmm0
+ movdqa [r8 + 32], xmm0
+ movdqa [r8 + 48], xmm0
+ add r8, 64
+ sub r9, 64
+ jmp .zero_lp
+%else
; Fast AVX2 zeroing (64 bytes per iteration; rax is 64B aligned, rcx is 64B mult)
vxorps ymm0, ymm0, ymm0
mov r8, rax
@@ -274,8 +296,11 @@ sys_mmap_anon:
add r8, 64
sub r9, 64
jmp .zero_lp
+%endif
.zero_done:
+%if !SSE2
vzeroupper
+%endif
ret
.oom:
@@ -517,6 +542,9 @@ d_ten: dq 10.0
d_tenth: dq 0.1
d_100: dq 100.0
d_half: dq 0.5
+%if SSE2
+align 16
+%endif
d_signbit: dq 0x8000000000000000, 0
hex_digits: db "0123456789ABCDEF"
diff --git a/Makefile b/Makefile
index f16b791..b40dc80 100644
--- a/Makefile
+++ b/Makefile
@@ -31,14 +31,28 @@ BUILD := build
# Portable defaults (override on CLI, e.g. make inference FAST_Q8=0)
FAST_Q8 ?= 1
AVX1 ?= 0
+# SSE2=1: x86-64 BASELINE build of the bare-metal OS only (`make os`): no AVX/AVX2/FMA/F16C/
+# SSSE3 at all, so it runs on any x86-64 CPU (Core 2, Athlon 64/Phenom, ...). Implies
+# FAST_Q8=1 and uses shared/matmul_sse2.asm. The Linux phases are not ported:
+# make BUILD=build-sse2 SSE2=1 os
+SSE2 ?= 0
+ifeq ($(SSE2),1)
+FAST_Q8 := 1
+MATMUL_SRC := matmul_sse2
+ifeq ($(AVX1),1)
+$(error SSE2=1 and AVX1=1 are different baselines; pick one)
+endif
+else
+MATMUL_SRC := matmul
+endif
MODEL ?= models/qwen3-0.6b-q8_0.asmbin
DATA ?= data/tinyshakespeare.txt
SMP ?= 16
RAM ?= 2G
CMDLINE ?=
-# Stamp file tracks FAST_Q8 / AVX1 compile-time toggles so toggling rebuilds cleanly
-FAST_Q8_STAMP := $(BUILD)/.cfg_q8_$(FAST_Q8)_avx1_$(AVX1)
+# Stamp file tracks FAST_Q8 / AVX1 / SSE2 compile-time toggles so toggling rebuilds cleanly
+FAST_Q8_STAMP := $(BUILD)/.cfg_q8_$(FAST_Q8)_avx1_$(AVX1)_sse2_$(SSE2)
# --- Shared x86-64 NASM modules ---
SHARED_DIR := shared
@@ -71,7 +85,7 @@ OS_BUILD := $(BUILD)/os
OS_ELF64 := $(OS_BUILD)/asm-llm-os.elf64
OS_ELF := $(BUILD)/asm-llm-os.elf
OS_ISO := $(BUILD)/asm-llm-os.iso
-OS_AFLAGS := -f elf64 -DBARE_METAL -DFAST_Q8=$(FAST_Q8) -DAVX1=$(AVX1) -I$(SHARED_DIR)/ -I$(P2_DIR)/
+OS_AFLAGS := -f elf64 -DBARE_METAL -DFAST_Q8=$(FAST_Q8) -DAVX1=$(AVX1) -DSSE2=$(SSE2) -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 noexecstack
OS_OBJS := \
@@ -141,21 +155,21 @@ check: $(TARGET)
$(OS_BUILD):
mkdir -p $(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)
+$(OS_BUILD)/%.o: $(P2_DIR)/%.asm $(P2_DIR)/os_constants.inc $(SHARED_DIR)/constants.inc $(SHARED_DIR)/isa.inc $(SHARED_DIR)/sse2_compat.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
$(OS_BUILD)/fbcon.o: $(P2_DIR)/font8x8.inc
-$(OS_BUILD)/math.o: $(SHARED_DIR)/math.asm $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
+$(OS_BUILD)/math.o: $(SHARED_DIR)/math.asm $(SHARED_DIR)/isa.inc $(SHARED_DIR)/sse2_compat.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
-$(OS_BUILD)/matmul.o: $(SHARED_DIR)/matmul.asm $(SHARED_DIR)/isa.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
+$(OS_BUILD)/matmul.o: $(SHARED_DIR)/$(MATMUL_SRC).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)
$(NASM) $(OS_AFLAGS) $< -o $@
-$(OS_BUILD)/transformer.o: $(SHARED_DIR)/transformer.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
+$(OS_BUILD)/transformer.o: $(SHARED_DIR)/transformer.asm $(SHARED_DIR)/constants.inc $(SHARED_DIR)/sse2_compat.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
$(OS_ELF64): $(OS_OBJS) $(P2_DIR)/linker.ld
@@ -177,14 +191,21 @@ 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)
+# Scan built binaries for instructions outside the selected baseline.
+# AVX1=1: Phase 1 + Phase 2 binaries against the AVX1 (Sandy Bridge) profile
+# SSE2=1: the Phase 2 kernel against the x86-64 SSE2 profile
+# need-isa comes first, so a run without AVX1=1 / SSE2=1 stops before it rebuilds anything
+ifeq ($(SSE2),1)
+isa-check: need-isa $(OS_ELF)
+ python3 scripts/check_isa.py --profile sse2 $(OS_ELF)
+else
+isa-check: need-isa $(TARGET) $(OS_ELF)
+ python3 scripts/check_isa.py --profile avx1 $(TARGET) $(OS_ELF)
+endif
-.PHONY: need-avx1
-need-avx1:
- @test "$(AVX1)" = 1 || { echo "isa-check needs AVX1=1 (it scans the AVX1 binaries)" >&2; exit 2; }
+.PHONY: need-isa
+need-isa:
+ @test "$(AVX1)" = 1 -o "$(SSE2)" = 1 || { echo "isa-check needs AVX1=1 or SSE2=1 (it scans the AVX1 / SSE2 binaries)" >&2; exit 2; }
os-run: $(OS_ELF)
qemu-system-x86_64 -enable-kvm -cpu host -m $(RAM) -smp $(SMP) \
diff --git a/README.md b/README.md
index 6f5f541..5721c94 100644
--- a/README.md
+++ b/README.md
@@ -109,7 +109,7 @@ make all # Builds Phase 1 (asm-llm, test_math), Phase 2 (asm-llm-os.elf), Phas
<details>
<summary><b>System Requirements, Repository Layout &amp; Verification Summary</b></summary>
-- **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.
+- **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); `make BUILD=build-sse2 SSE2=1 os` builds the bare-metal OS for any x86-64 CPU, SSE2 only, checked by `scripts/check_isa.py --profile sse2`), `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.py
index 2fc2709..2ea9d89 100644
--- a/scripts/check_isa.py
+++ b/scripts/check_isa.py
@@ -1,9 +1,14 @@
#!/usr/bin/env python3
-"""Scan a built binary for instruction forms outside the AVX1 (Sandy Bridge) ISA.
+"""Scan a built binary for instruction forms outside a baseline ISA profile.
-Usage: python3 scripts/check_isa.py build/asm-llm [build/asm-llm-os.elf ...]
+Usage: python3 scripts/check_isa.py [--profile avx1|sse2] build/asm-llm [build/asm-llm-os.elf ...]
-Flags the forms listed below, not every possible extension:
+--profile avx1 (default): the AVX1 (Sandy Bridge) build, `make AVX1=1`.
+--profile sse2 : the x86-64 baseline build, `make SSE2=1 os`. Every VEX form, SSE3 and
+ later (SSSE3, SSE4.x, popcnt, crc32), XSAVE/XGETBV, BMI/ADX and
+ FMA/F16C are rejected; only SSE2 and older remain.
+
+avx1 profile: 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,
@@ -11,6 +16,7 @@ Flags the forms listed below, not every possible extension:
- 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).
+sse2 profile: a deny list over the mnemonics, so any v* instruction fails.
Exit status 1 if anything is found.
"""
@@ -31,6 +37,19 @@ ALWAYS_BAD = re.compile(
)
AVX512_REG = re.compile(r"\b(zmm\d+|k[0-7])\b")
+# sse2 profile: everything newer than SSE2, by mnemonic
+SSE2_DENY = re.compile(
+ r"^(v[a-z0-9]+|xgetbv|xsetbv|xsave\w*|xrstor\w*"
+ r"|haddp[sd]|hsubp[sd]|addsubp[sd]|movddup|movshdup|movsldup|lddqu|fisttp|monitor|mwait"
+ r"|pshufb|phadd\w*|phsub\w*|pmaddubsw|pmulhrsw|psign\w*|pabs[bwd]|palignr"
+ r"|blendp[sd]|blendvp[sd]|pblend\w*|round[ps][sd]|pmovsx\w*|pmovzx\w*"
+ r"|pm(in|ax)(sb|uw|ud|sd)|pextr[bdq]|pinsr[bdq]|ptest|pcmpeqq|pcmpgtq|pmulld|pmuldq|packusdw"
+ r"|dpp[sd]|insertps|extractps|movntdqa|popcnt|crc32|pcmp[ei]str\w*|mpsadbw|phminposuw"
+ r"|andn|bextr|blsi|blsmsk|blsr|bzhi|tzcnt|lzcnt|mulx|rorx|sarx|shlx|shrx|adcx|adox|pdep|pext"
+ r"|movbe|rdrand|rdseed|rd[fg]sbase|wr[fg]sbase|invpcid|clflushopt|clwb)$"
+)
+PREFIXES = {"lock", "rep", "repz", "repnz", "bnd", "notrack", "data16", "cs", "ds", "es"}
+
def disassemble(path):
head = subprocess.run(["objdump", "-f", path], capture_output=True, text=True, check=True).stdout
@@ -43,13 +62,25 @@ def disassemble(path):
).stdout
-def scan(path):
+def scan(path, profile="avx1"):
bad = []
+ count = 0
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()
+ if profile == "sse2":
+ # a prefix may be the first token: the instruction is the next one
+ while mnem in PREFIXES and ops:
+ mnem, _, ops = ops.partition(" ")
+ ops = ops.strip()
+ if mnem == "(bad)": # the 32-bit entry stub, decoded as 64-bit
+ continue
+ count += 1
+ if SSE2_DENY.match(mnem):
+ bad.append(f"{path}: {addr}: {mnem} {ops} [beyond SSE2]")
+ continue
reason = None
if ALWAYS_BAD.match(mnem):
reason = "FMA/F16C/AVX2/BMI or later"
@@ -61,15 +92,26 @@ def scan(path):
reason = "AVX2 register-source broadcast"
if reason:
bad.append(f"{path}: {addr}: {mnem} {ops} [{reason}]")
- return bad
+ return (bad, count) if profile == "sse2" else bad
def main():
- paths = sys.argv[1:] or ["build/asm-llm"]
+ args = sys.argv[1:]
+ profile = "avx1"
+ if args[:1] == ["--profile"]:
+ if len(args) < 2 or args[1] not in ("avx1", "sse2"):
+ sys.exit("usage: check_isa.py [--profile avx1|sse2] binary...")
+ profile = args[1]
+ args = args[2:]
+ paths = args or ["build/asm-llm"]
bad = []
for p in paths:
- found = scan(p)
- print(f"{p}: {len(found)} non-AVX1 instruction(s)")
+ if profile == "sse2":
+ found, count = scan(p, "sse2")
+ print(f"{p}: {count} instructions, {len(found)} beyond SSE2")
+ else:
+ found = scan(p)
+ print(f"{p}: {len(found)} non-AVX1 instruction(s)")
bad += found
for b in bad[:200]:
print(" " + b)
diff --git a/shared/math.asm b/shared/math.asm
index 1407fc7..fdc48b3 100644
--- a/shared/math.asm
+++ b/shared/math.asm
@@ -25,9 +25,34 @@ default rel
%include "isa.inc"
+%ifndef SSE2
+%define SSE2 0
+%endif
+%if SSE2
+%include "sse2_compat.inc"
+
+; HSUM4 v, t : v.lane0 = (v0+v1)+(v2+v3) (same adds, same order as 2x haddps)
+%macro HSUM4 2
+ movaps %2, %1
+ shufps %2, %2, 0xDD
+ shufps %1, %1, 0x88
+ addps %1, %2
+ movaps %2, %1
+ shufps %2, %2, 0x55
+ addss %1, %2
+%endmacro
+; BC4 xmm, const : broadcast a float32 constant to 4 lanes
+%macro BC4 2
+ movss %1, %2
+ shufps %1, %1, 0
+%endmacro
+%endif
+
section .text
+%if !SSE2
global fast_expf_avx2
+%endif
global fast_expf_scalar
global fast_sincos_f64
global fast_sincosf
@@ -49,6 +74,65 @@ global sample_top_p
; Safe for all finite x: x < -87.33654 -> 0.0f, x > 88.37626 clamped.
; Cody-Waite range reduction + degree-6 Taylor polynomial (~2e-7 rel error).
; ----------------------------------------------------------------------------
+%if SSE2
+; SSE2: 4-wide exp on xmm0 -> xmm0 (lane-wise, so an 8-float group = two calls).
+; Clobbers xmm0..xmm5 ONLY. Same constants / op order as fast_expf_avx2 with
+; FMA replaced by mul+add (two roundings).
+fast_expf_x4:
+ BC4 xmm4, [rel f_exp_lo]
+ movaps xmm5, xmm4
+ cmpleps xmm5, xmm0 ; mask = (exp_lo <= x) (GE_OS)
+ maxps xmm0, xmm4
+ BC4 xmm4, [rel f_exp_hi]
+ minps xmm0, xmm4
+
+ BC4 xmm4, [rel f_log2e]
+ movaps xmm1, xmm0
+ mulps xmm1, xmm4 ; x * log2e
+ cvtps2dq xmm2, xmm1 ; k_i = round_nearest_even
+ cvtdq2ps xmm1, xmm2 ; k_f
+
+ BC4 xmm4, [rel f_ln2_hi]
+ mulps xmm4, xmm1
+ subps xmm0, xmm4
+ BC4 xmm4, [rel f_ln2_lo]
+ mulps xmm4, xmm1
+ subps xmm0, xmm4 ; r
+
+ BC4 xmm3, [rel f_exp_c6]
+ BC4 xmm4, [rel f_exp_c5]
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+ BC4 xmm4, [rel f_exp_c4]
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+ BC4 xmm4, [rel f_exp_c3]
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+ BC4 xmm4, [rel f_exp_c2]
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+ BC4 xmm4, [rel f_one]
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+ mulps xmm3, xmm0
+ addps xmm3, xmm4
+
+ movd xmm4, [rel i_127]
+ pshufd xmm4, xmm4, 0
+ paddd xmm2, xmm4
+ pslld xmm2, 23 ; 2^k
+ movaps xmm0, xmm3
+ mulps xmm0, xmm2
+ andps xmm0, xmm5 ; flush underflowed lanes to 0.0
+ ret
+
+fast_expf_scalar:
+ shufps xmm0, xmm0, 0
+ call fast_expf_x4
+ ret
+
+%else
fast_expf_avx2:
vbroadcastss ymm4, [rel f_exp_lo]
vcmpps ymm5, ymm0, ymm4, 13 ; _CMP_GE_OS: mask = (x >= exp_lo)
@@ -108,6 +192,7 @@ fast_expf_scalar:
call fast_expf_avx2
ret
+%endif
; ----------------------------------------------------------------------------
; (xmm0=sin, xmm1=cos) = fast_sincos_f64(xmm0=angle_f64)
; Cody-Waite FP64 reduction by pi/2 + degree-11/10 Taylor polynomial.
@@ -117,8 +202,13 @@ fast_expf_scalar:
; ----------------------------------------------------------------------------
fast_sincos_f64:
vmulsd xmm1, xmm0, [rel d_inv_pio2]
+%if SSE2
+ cvtsd2si rax, xmm1 ; q = round-to-nearest-even(x * 2/pi) (MXCSR RNE)
+ cvtsi2sd xmm1, rax ; q_d (exact)
+%else
vroundsd xmm1, xmm1, xmm1, 0 ; q_d = round(x * 2/pi)
vcvtsd2si rax, xmm1 ; q = (int64)q_d
+%endif
; r = (x - q_d * pio2_hi) - q_d * pio2_lo
; (AVX1: pio2_hi has 31 significant bits, so q * pio2_hi stays exact
@@ -239,8 +329,13 @@ log_f64:
; ----------------------------------------------------------------------------
exp_f64:
vmulsd xmm1, xmm0, [rel d_log2e]
+%if SSE2
+ cvtsd2si rax, xmm1 ; k = round-to-nearest-even
+ cvtsi2sd xmm1, rax ; k_d (exact)
+%else
vroundsd xmm1, xmm1, xmm1, 0 ; k_d
vcvtsd2si rax, xmm1 ; k
+%endif
vmovsd xmm2, [rel d_ln2_hi]
VFNMADD231SD xmm0, xmm1, xmm2, xmm3
@@ -356,6 +451,46 @@ compute_rope_cs:
; out1 = x1 * cos - x2 * sin
; out2 = x2 * cos + x1 * sin
; ----------------------------------------------------------------------------
+%if SSE2
+rope_apply_avx2:
+ mov r9, r8
+ shr r9, 1 ; half_dim (elements)
+ shl r9, 2 ; half_bytes = half_dim * 4
+ lea r10, [r9 + r9] ; head_bytes = head_dim * 4
+.head_lp:
+ test rcx, rcx
+ jz .done
+ lea r11, [rdi + r9] ; x2_ptr = x1_ptr + half_bytes
+ xor eax, eax
+.dim_lp:
+ cmp rax, r9
+ jae .next_head
+ movups xmm0, [rdi + rax] ; x1
+ movups xmm1, [r11 + rax] ; x2
+ movups xmm2, [rsi + rax] ; cos
+ movups xmm3, [rdx + rax] ; sin
+ movaps xmm4, xmm0
+ mulps xmm4, xmm2 ; x1 * cos
+ movaps xmm6, xmm1
+ mulps xmm6, xmm3 ; x2 * sin
+ subps xmm4, xmm6
+ movaps xmm5, xmm1
+ mulps xmm5, xmm2 ; x2 * cos
+ movaps xmm6, xmm0
+ mulps xmm6, xmm3 ; x1 * sin
+ addps xmm5, xmm6
+ movups [rdi + rax], xmm4
+ movups [r11 + rax], xmm5
+ add rax, 16
+ jmp .dim_lp
+.next_head:
+ add rdi, r10
+ dec rcx
+ jmp .head_lp
+.done:
+ ret
+
+%else
rope_apply_avx2:
mov r9, r8
shr r9, 1 ; half_dim (elements)
@@ -388,11 +523,77 @@ rope_apply_avx2:
.done:
ret
+%endif
; ----------------------------------------------------------------------------
; void rmsnorm_avx2(float *out, const float *x, const float *w, uint64 n, float eps)
; rdi = out, rsi = x, rdx = w, rcx = n (multiple of 32), xmm0 = eps
; Supports in-place (out == x).
; ----------------------------------------------------------------------------
+%if SSE2
+rmsnorm_avx2:
+ xorps xmm1, xmm1
+ xorps xmm2, xmm2
+ xorps xmm3, xmm3
+ xorps xmm4, xmm4
+ xorps xmm5, xmm5
+ xorps xmm6, xmm6
+ xorps xmm7, xmm7
+ xorps xmm8, xmm8
+ shl rcx, 2 ; n_bytes = n * 4
+ xor eax, eax
+.ss_lp:
+ cmp rax, rcx
+ jae .ss_red
+%assign __o 0
+%assign __r 1
+%rep 8
+ movups xmm9, [rsi + rax + __o]
+ mulps xmm9, xmm9
+ addps xmm %+ __r, xmm9
+%assign __o __o + 16
+%assign __r __r + 1
+%endrep
+ add rax, 128
+ jmp .ss_lp
+.ss_red:
+ addps xmm1, xmm3 ; ymm1 += ymm2
+ addps xmm2, xmm4
+ addps xmm5, xmm7 ; ymm3 += ymm4
+ addps xmm6, xmm8
+ addps xmm1, xmm5 ; ymm1 += ymm3
+ addps xmm2, xmm6
+ addps xmm1, xmm2 ; lo + hi
+ HSUM4 xmm1, xmm2
+
+ mov r8, rcx
+ shr r8, 2 ; n
+ cvtsi2ss xmm2, r8
+ divss xmm1, xmm2 ; mean(x^2)
+ addss xmm1, xmm0 ; + eps
+ sqrtss xmm1, xmm1 ; rms
+ movss xmm2, [rel f_one]
+ divss xmm2, xmm1 ; inv_rms = 1.0 / rms
+ shufps xmm2, xmm2, 0
+
+ xor eax, eax
+.scale_lp:
+ cmp rax, rcx
+ jae .done
+%assign __o 0
+%rep 4
+ movups xmm3, [rsi + rax + __o]
+ mulps xmm3, xmm2
+ movups xmm4, [rdx + rax + __o]
+ mulps xmm3, xmm4
+ movups [rdi + rax + __o], xmm3
+%assign __o __o + 16
+%endrep
+ add rax, 64
+ jmp .scale_lp
+.done:
+ ret
+
+%else
rmsnorm_avx2:
vxorps ymm1, ymm1, ymm1
vxorps ymm2, ymm2, ymm2
@@ -450,10 +651,96 @@ rmsnorm_avx2:
.done:
ret
+%endif
; ----------------------------------------------------------------------------
; void softmax_avx2(float *x, uint64 n)
; rdi = x, rsi = n (arbitrary n >= 1)
; ----------------------------------------------------------------------------
+%if SSE2
+softmax_avx2:
+ push rbx
+ push r12
+ mov r12, rdi ; x
+ mov rbx, rsi ; n
+
+ movss xmm6, [r12]
+ mov rcx, 1
+.max_lp:
+ cmp rcx, rbx
+ jae .max_done
+ maxss xmm6, [r12 + rcx*4]
+ inc rcx
+ jmp .max_lp
+.max_done:
+ shufps xmm6, xmm6, 0 ; xmm6 = max_val (preserved by fast_expf_x4)
+ xorps xmm7, xmm7 ; xmm7 = sum accumulator, lanes 0..3
+ xorps xmm8, xmm8 ; xmm8 = sum accumulator, lanes 4..7
+ xor ecx, ecx
+
+.exp8_lp:
+ lea rax, [rcx + 8]
+ cmp rax, rbx
+ ja .exp1_lp
+ movups xmm0, [r12 + rcx*4]
+ subps xmm0, xmm6
+ call fast_expf_x4
+ movups [r12 + rcx*4], xmm0
+ addps xmm7, xmm0
+ movups xmm0, [r12 + rcx*4 + 16]
+ subps xmm0, xmm6
+ call fast_expf_x4
+ movups [r12 + rcx*4 + 16], xmm0
+ addps xmm8, xmm0
+ add rcx, 8
+ jmp .exp8_lp
+
+.exp1_lp:
+ addps xmm7, xmm8 ; lo + hi
+ HSUM4 xmm7, xmm8
+
+.tail_lp:
+ cmp rcx, rbx
+ jae .norm
+ movss xmm0, [r12 + rcx*4]
+ subss xmm0, xmm6
+ call fast_expf_scalar
+ movss [r12 + rcx*4], xmm0
+ addss xmm7, xmm0
+ inc rcx
+ jmp .tail_lp
+
+.norm:
+ movss xmm0, [rel f_one]
+ divss xmm0, xmm7 ; inv_sum
+ movaps xmm7, xmm0
+ shufps xmm7, xmm7, 0
+ xor ecx, ecx
+.norm8_lp:
+ lea rax, [rcx + 8]
+ cmp rax, rbx
+ ja .norm1_lp
+ movups xmm0, [r12 + rcx*4]
+ mulps xmm0, xmm7
+ movups [r12 + rcx*4], xmm0
+ movups xmm0, [r12 + rcx*4 + 16]
+ mulps xmm0, xmm7
+ movups [r12 + rcx*4 + 16], xmm0
+ add rcx, 8
+ jmp .norm8_lp
+.norm1_lp:
+ cmp rcx, rbx
+ jae .done
+ movss xmm0, [r12 + rcx*4]
+ mulss xmm0, xmm7
+ movss [r12 + rcx*4], xmm0
+ inc rcx
+ jmp .norm1_lp
+.done:
+ pop r12
+ pop rbx
+ ret
+
+%else
softmax_avx2:
push rbx
push r12
@@ -534,6 +821,7 @@ softmax_avx2:
pop rbx
ret
+%endif
; ----------------------------------------------------------------------------
; void silu_mul_avx2(float *gate_inout, const float *up, uint64 n)
; rdi = gate, rsi = up, rdx = n (multiple of 8)
@@ -542,6 +830,52 @@ softmax_avx2:
; num = (x < 0) ? e : 1.0 (via vblendvps on sign bit of x)
; out = (x * num / (1.0 + e)) * up
; ----------------------------------------------------------------------------
+%if SSE2
+silu_mul_avx2:
+ push rbx
+ push r12
+ push r13
+ mov r12, rdi ; gate
+ mov r13, rsi ; up
+ shl rdx, 2 ; n_bytes
+ mov rbx, rdx
+
+ movd xmm8, [rel i_abs_mask]
+ pshufd xmm8, xmm8, 0 ; 0x7FFFFFFF (preserved by fast_expf_x4)
+ movd xmm9, [rel i_sign_mask]
+ pshufd xmm9, xmm9, 0 ; 0x80000000
+ BC4 xmm10, [rel f_one] ; 1.0f
+
+ xor ecx, ecx
+.lp:
+ cmp rcx, rbx
+ jae .done
+ movups xmm6, [r12 + rcx] ; x = gate
+ movups xmm7, [r13 + rcx] ; up
+ movaps xmm0, xmm6
+ andps xmm0, xmm8 ; |x|
+ xorps xmm0, xmm9 ; -|x| <= 0
+ call fast_expf_x4 ; xmm0 = e = exp(-|x|) in [0, 1]
+ movdqa xmm1, xmm6
+ psrad xmm1, 31 ; mask = (x < 0)
+ movaps xmm2, xmm0
+ andps xmm2, xmm1 ; e where x < 0
+ andnps xmm1, xmm10 ; 1.0 where x >= 0
+ orps xmm1, xmm2 ; num = (x < 0) ? e : 1.0f
+ addps xmm0, xmm10 ; 1.0f + e
+ mulps xmm1, xmm6 ; x * num
+ divps xmm1, xmm0 ; silu(x)
+ mulps xmm1, xmm7 ; silu(x) * up
+ movups [r12 + rcx], xmm1
+ add rcx, 16
+ jmp .lp
+.done:
+ pop r13
+ pop r12
+ pop rbx
+ ret
+
+%else
silu_mul_avx2:
push rbx
push r12
@@ -583,10 +917,32 @@ silu_mul_avx2:
pop rbx
ret
+%endif
; ----------------------------------------------------------------------------
; void vec_add_avx2(float *dst, const float *src, uint64 n)
; rdi = dst, rsi = src, rdx = n (multiple of 32)
; ----------------------------------------------------------------------------
+%if SSE2
+vec_add_avx2:
+ shl rdx, 2
+ xor eax, eax
+.lp:
+ cmp rax, rdx
+ jae .done
+%assign __o 0
+%rep 8
+ movups xmm0, [rdi + rax + __o]
+ movups xmm1, [rsi + rax + __o]
+ addps xmm0, xmm1
+ movups [rdi + rax + __o], xmm0
+%assign __o __o + 16
+%endrep
+ add rax, 128
+ jmp .lp
+.done:
+ ret
+
+%else
vec_add_avx2:
shl rdx, 2
xor eax, eax
@@ -610,6 +966,7 @@ vec_add_avx2:
.done:
ret
+%endif
; ----------------------------------------------------------------------------
; uint64 argmax_f32(const float *x, uint64 n)
; rdi = x, rsi = n -> rax = index of maximum float (first index on tie)
@@ -619,6 +976,53 @@ argmax_f32:
cmp rsi, 8
jb .scalar_init
+%if SSE2
+ sub rsp, 64 ; 32B vals + 32B idxs
+ movups xmm0, [rdi] ; best_vals lanes 0..3
+ movups xmm10, [rdi + 16] ; best_vals lanes 4..7
+ movdqa xmm1, [rel i_iota8] ; best_idxs lanes 0..3
+ movdqa xmm11, [rel i_iota8 + 16] ; best_idxs lanes 4..7
+ movd xmm3, [rel i_eight]
+ pshufd xmm3, xmm3, 0 ; step = [8,8,8,8]
+ movdqa xmm2, xmm1
+ paddd xmm2, xmm3 ; cur_idxs = [8..11]
+ movdqa xmm12, xmm11
+ paddd xmm12, xmm3 ; cur_idxs = [12..15]
+ mov rcx, 8
+ mov rdx, rsi
+ and rdx, -8 ; n8 = n & ~7
+.v_lp:
+ cmp rcx, rdx
+ jae .v_red
+%macro ARGMAX_HALF 4 ; %1 = vals, %2 = idxs, %3 = cur idxs, %4 = byte offset
+ movups xmm4, [rdi + rcx*4 + %4]
+ movaps xmm5, %1
+ cmpltps xmm5, xmm4 ; best < x (strict >: first index wins ties)
+ movaps xmm6, xmm4
+ andps xmm6, xmm5
+ movaps xmm7, xmm5
+ andnps xmm7, %1
+ orps xmm7, xmm6
+ movaps %1, xmm7
+ movdqa xmm6, %3
+ pand xmm6, xmm5
+ movdqa xmm7, xmm5
+ pandn xmm7, %2
+ por xmm7, xmm6
+ movdqa %2, xmm7
+ paddd %3, xmm3
+%endmacro
+ ARGMAX_HALF xmm0, xmm1, xmm2, 0
+ ARGMAX_HALF xmm10, xmm11, xmm12, 16
+ add rcx, 8
+ jmp .v_lp
+
+.v_red:
+ movups [rsp], xmm0
+ movups [rsp + 16], xmm10
+ movdqu [rsp + 32], xmm1
+ movdqu [rsp + 48], xmm11
+%else
sub rsp, 64 ; 32B vals + 32B idxs
vmovups ymm0, [rdi] ; best_vals = x[0..7]
%if AVX1
@@ -655,6 +1059,7 @@ argmax_f32:
vcvttps2dq ymm1, ymm1
%endif
vmovdqu [rsp + 32], ymm1
+%endif
vmovss xmm0, [rsp] ; best_val
mov eax, [rsp + 32] ; best_idx (zero-extended)
mov r8d, 1
@@ -722,6 +1127,19 @@ sample_top_p:
; Scale logits[i] / temp -> probs[i]
vmovss xmm2, [rel f_one]
vdivss xmm2, xmm2, xmm0 ; inv_temp
+%if SSE2
+ shufps xmm2, xmm2, 0
+ xor eax, eax
+.sc_lp:
+ lea rcx, [rax + 4]
+ cmp rcx, r14
+ ja .sc_tail
+ movups xmm3, [r12 + rax*4]
+ mulps xmm3, xmm2
+ movups [r13 + rax*4], xmm3
+ add rax, 4
+ jmp .sc_lp
+%else
VBROADCASTSS_R ymm2, xmm2
xor eax, eax
.sc_lp:
@@ -733,6 +1151,7 @@ sample_top_p:
vmovups [r13 + rax*4], ymm3
add rax, 8
jmp .sc_lp
+%endif
.sc_tail:
cmp rax, r14
jae .do_sm
diff --git a/shared/matmul_sse2.asm b/shared/matmul_sse2.asm
new file mode 100644
index 0000000..268d3ce
--- /dev/null
+++ b/shared/matmul_sse2.asm
@@ -0,0 +1,621 @@
+; ============================================================================
+; matmul_sse2.asm — Q8_0 matmul kernels for the x86-64 BASELINE (SSE2 only)
+;
+; Drop-in replacement for matmul.asm when built with SSE2=1 (FAST_Q8=1 only).
+; No AVX, no AVX2, no FMA, no F16C, no SSSE3/SSE4: runs on any x86-64 CPU
+; (Core 2, Athlon 64 / Phenom, Atom, ...).
+;
+; Same weight layout, same exported symbols and the SAME arithmetic structure as
+; the AVX2 kernel in matmul.asm; the only numeric difference is that FMA becomes
+; mul+add (two roundings):
+; * the activation vector is quantized to Q8_0 once (quantize_x_q8_0),
+; * every 32-weight block gives 8 int32 lane sums (4 products per lane),
+; converted to float, scaled by (w_scale * x_scale) and accumulated into
+; 8 lanes (kept as xmm lo/hi pairs), then reduced in the same order.
+;
+; SSE2 has no pmaddubsw/pabsb/psignb, so the int8 dot uses pmaddwd on int16:
+; * quantize_x_q8_0 stores x as int16, split per 16 elements into an EVEN-
+; element vector and an ODD-element vector (q8_xw, 64 bytes per block);
+; * the weight bytes are split the same way with shifts:
+; even = (w << 8) >> 8 (arith) odd = w >> 8 (arith)
+; pmaddwd(even_w, even_x) + pmaddwd(odd_w, odd_x) = four products per lane,
+; exactly the grouping (elements 4j..4j+3) of the AVX kernels.
+; * fp16 block scales are converted with integer SSE2 ops (no F16C); the
+; conversion is exact for every 16-bit input (checked against vcvtph2ps).
+;
+; Functions (identical to matmul.asm):
+; matmul_set_fp16, quantize_x_q8_0, dequant_row_q8_0, matmul_q8_0_range,
+; dot_f32_avx2, saxpy_f32_avx2
+; ============================================================================
+
+bits 64
+default rel
+
+%ifndef SSE2
+%define SSE2 0
+%endif
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+%if !SSE2
+%error "matmul_sse2.asm is only for SSE2=1 builds"
+%endif
+%if !FAST_Q8
+%error "SSE2=1 supports only FAST_Q8=1 (INT8 x INT8 matmul path)"
+%endif
+
+%ifndef Q8_PREFETCH
+%define Q8_PREFETCH prefetcht0
+%endif
+
+%define Q8_MAX_K 16384
+
+section .text
+
+global matmul_set_fp16
+global quantize_x_q8_0
+global dequant_row_q8_0
+global matmul_q8_0_range
+global dot_f32_avx2
+global saxpy_f32_avx2
+
+; ----------------------------------------------------------------------------
+; H2F4 v, t1, t2
+; v = 4 x fp16 values, each zero-extended in a 32-bit lane -> 4 x float32.
+; Exact IEEE half->single for every input (normal, subnormal, zero, +-inf, NaN):
+; shifting the 15 magnitude bits into float position gives exponent e (half bias)
+; in a float with bias 127; multiplying by 2^112 re-biases it, and for half
+; subnormals (float denormals after the shift) the same multiply normalizes
+; them exactly (needs MXCSR.DAZ = 0, the kernel's default). Half inf/NaN
+; (exponent 31) get their float exponent forced to 255 afterwards.
+; Clobbers t1, t2.
+; ----------------------------------------------------------------------------
+%macro H2F4 3
+ movdqa %2, %1
+ pand %2, [rel h2f_8000]
+ pxor %1, %2 ; v = magnitude
+ pslld %2, 16 ; t1 = sign bit in place
+ movdqa %3, %1
+ pand %3, [rel h2f_7c00]
+ pcmpeqd %3, [rel h2f_7c00] ; t2 = (exp == 31) [inf / nan]
+ pand %3, [rel h2f_7f800000] ; t2 = exponent 255 for those lanes
+ pslld %1, 13
+ mulps %1, [rel h2f_2p112] ; rebias (and normalize subnormals)
+ por %1, %3
+ por %1, %2
+%endmacro
+
+; HSUM4 v, t : v.lane0 = (v0+v1)+(v2+v3) (same adds, same order as 2x haddps)
+%macro HSUM4 2
+ movaps %2, %1
+ shufps %2, %2, 0xDD ; (v1, v3, v1, v3)
+ shufps %1, %1, 0x88 ; (v0, v2, v0, v2)
+ addps %1, %2 ; (v0+v1, v2+v3, ...)
+ movaps %2, %1
+ shufps %2, %2, 0x55 ; lane0 = v2+v3
+ addss %1, %2
+%endmacro
+
+; ----------------------------------------------------------------------------
+; void matmul_set_fp16(uint64 is_fp16)
+; ----------------------------------------------------------------------------
+matmul_set_fp16:
+ xor eax, eax
+ test rdi, rdi
+ setnz al
+ mov [rel g_fp16_scales], eax
+ ret
+
+; ----------------------------------------------------------------------------
+; void dequant_row_q8_0(const void *row_ptr, float *out, uint64 K)
+; rdi = row_ptr, rsi = out, rdx = K (multiple of 32)
+; ----------------------------------------------------------------------------
+%macro DEQ16 1 ; %1 = byte offset of the 16-int8 chunk (0 / 16)
+ movdqu xmm0, [rdi + r9 + %1]
+ movdqa xmm1, xmm0
+ punpcklbw xmm0, xmm0
+ psraw xmm0, 8 ; elements 0..7 as int16
+ punpckhbw xmm1, xmm1
+ psraw xmm1, 8 ; elements 8..15 as int16
+ movdqa xmm2, xmm0
+ punpcklwd xmm0, xmm0
+ psrad xmm0, 16 ; elements 0..3 as int32
+ punpckhwd xmm2, xmm2
+ psrad xmm2, 16 ; elements 4..7
+ movdqa xmm3, xmm1
+ punpcklwd xmm1, xmm1
+ psrad xmm1, 16 ; elements 8..11
+ punpckhwd xmm3, xmm3
+ psrad xmm3, 16 ; elements 12..15
+ cvtdq2ps xmm0, xmm0
+ cvtdq2ps xmm2, xmm2
+ cvtdq2ps xmm1, xmm1
+ cvtdq2ps xmm3, xmm3
+ mulps xmm0, xmm4
+ mulps xmm2, xmm4
+ mulps xmm1, xmm4
+ mulps xmm3, xmm4
+ movups [rsi + r10 + (%1)*4], xmm0
+ movups [rsi + r10 + (%1)*4 + 16], xmm2
+ movups [rsi + r10 + (%1)*4 + 32], xmm1
+ movups [rsi + r10 + (%1)*4 + 48], xmm3
+%endmacro
+
+dequant_row_q8_0:
+ lea r8, [rdi + rdx] ; scales_ptr = row_ptr + K
+ mov rcx, rdx
+ shr rcx, 5 ; nb = K / 32
+ mov r11d, [rel g_fp16_scales]
+ xor eax, eax ; b = 0
+.lp:
+ cmp rax, rcx
+ jae .done
+ test r11d, r11d
+ jnz .sc_f16
+ movss xmm4, [r8 + rax*4] ; v1 fp32 scale[b]
+ jmp .sc_ok
+.sc_f16:
+ movzx r10d, word [r8 + rax*2] ; v2 fp16 scale[b]
+ movd xmm4, r10d
+ H2F4 xmm4, xmm5, xmm6
+.sc_ok:
+ shufps xmm4, xmm4, 0
+ mov r9, rax
+ shl r9, 5 ; b * 32 (q offset)
+ mov r10, rax
+ shl r10, 7 ; b * 128 (out offset)
+ DEQ16 0
+ DEQ16 16
+ inc rax
+ jmp .lp
+.done:
+ ret
+
+; ----------------------------------------------------------------------------
+; void quantize_x_q8_0(const float *x, uint64 K)
+; rdi = x (f32), rsi = K (multiple of 32, <= Q8_MAX_K)
+; q8_xw[b*64 ..] : int16, per block of 32 elements
+; [even elems 0..15 (8 x i16)][odd elems 0..15][even 16..31][odd 16..31]
+; q8_xs[b] : float32 scale = max_abs / 127.0f
+; ----------------------------------------------------------------------------
+quantize_x_q8_0:
+ mov rcx, rsi
+ shr rcx, 5 ; nb = K / 32
+ lea r9, [rel q8_xw]
+ lea r10, [rel q8_xs]
+
+ movaps xmm12, [rel q8_abs_mask4]
+ movss xmm13, [rel q8_inv_127]
+ movss xmm14, [rel q8_f127]
+ xorps xmm15, xmm15
+
+ xor eax, eax ; b = 0
+ xor r8d, r8d ; x byte offset (b * 128)
+ xor edx, edx ; xw byte offset (b * 64)
+.qlp:
+ cmp rax, rcx
+ jae .qdone
+
+ movups xmm0, [rdi + r8]
+ movups xmm1, [rdi + r8 + 16]
+ movups xmm2, [rdi + r8 + 32]
+ movups xmm3, [rdi + r8 + 48]
+ movups xmm4, [rdi + r8 + 64]
+ movups xmm5, [rdi + r8 + 80]
+ movups xmm6, [rdi + r8 + 96]
+ movups xmm7, [rdi + r8 + 112]
+
+ ; max |x| over the 32 floats
+ movaps xmm8, xmm0
+ andps xmm8, xmm12
+ movaps xmm9, xmm1
+ andps xmm9, xmm12
+ maxps xmm8, xmm9
+ movaps xmm9, xmm2
+ andps xmm9, xmm12
+ movaps xmm10, xmm3
+ andps xmm10, xmm12
+ maxps xmm9, xmm10
+ maxps xmm8, xmm9
+ movaps xmm9, xmm4
+ andps xmm9, xmm12
+ movaps xmm10, xmm5
+ andps xmm10, xmm12
+ maxps xmm9, xmm10
+ movaps xmm10, xmm6
+ andps xmm10, xmm12
+ movaps xmm11, xmm7
+ andps xmm11, xmm12
+ maxps xmm10, xmm11
+ maxps xmm9, xmm10
+ maxps xmm8, xmm9
+ movaps xmm9, xmm8
+ shufps xmm9, xmm9, 0x0E
+ maxps xmm8, xmm9
+ movaps xmm9, xmm8
+ shufps xmm9, xmm9, 0x01
+ maxss xmm8, xmm9 ; xmm8 = max_abs
+
+ movaps xmm9, xmm8
+ mulss xmm9, xmm13 ; scale_x = max_abs / 127.0f
+ movss [r10 + rax*4], xmm9
+
+ xorps xmm10, xmm10 ; inv_scale = 0.0f if max_abs == 0
+ ucomiss xmm8, xmm15
+ jbe .qinv_ok
+ movaps xmm10, xmm14
+ divss xmm10, xmm8 ; inv_scale = 127.0f / max_abs
+.qinv_ok:
+ shufps xmm10, xmm10, 0
+
+ mulps xmm0, xmm10
+ mulps xmm1, xmm10
+ mulps xmm2, xmm10
+ mulps xmm3, xmm10
+ mulps xmm4, xmm10
+ mulps xmm5, xmm10
+ mulps xmm6, xmm10
+ mulps xmm7, xmm10
+ cvtps2dq xmm0, xmm0
+ cvtps2dq xmm1, xmm1
+ cvtps2dq xmm2, xmm2
+ cvtps2dq xmm3, xmm3
+ cvtps2dq xmm4, xmm4
+ cvtps2dq xmm5, xmm5
+ cvtps2dq xmm6, xmm6
+ cvtps2dq xmm7, xmm7
+
+ ; split into even / odd elements, pack to int16
+ movaps xmm8, xmm0
+ shufps xmm8, xmm1, 0x88 ; e0 e2 e4 e6
+ movaps xmm9, xmm2
+ shufps xmm9, xmm3, 0x88 ; e8 e10 e12 e14
+ shufps xmm0, xmm1, 0xDD ; e1 e3 e5 e7
+ shufps xmm2, xmm3, 0xDD ; e9 e11 e13 e15
+ packssdw xmm8, xmm9 ; even 0..15
+ packssdw xmm0, xmm2 ; odd 0..15
+ movaps xmm10, xmm4
+ shufps xmm10, xmm5, 0x88
+ movaps xmm11, xmm6
+ shufps xmm11, xmm7, 0x88
+ shufps xmm4, xmm5, 0xDD
+ shufps xmm6, xmm7, 0xDD
+ packssdw xmm10, xmm11 ; even 16..31
+ packssdw xmm4, xmm6 ; odd 16..31
+
+ ; clamp to [-127, 127] (same final values as packsswb + pmaxsb(-127))
+ movdqa xmm1, [rel q8_m127w]
+ pmaxsw xmm8, xmm1
+ pmaxsw xmm0, xmm1
+ pmaxsw xmm10, xmm1
+ pmaxsw xmm4, xmm1
+ movdqa xmm1, [rel q8_p127w]
+ pminsw xmm8, xmm1
+ pminsw xmm0, xmm1
+ pminsw xmm10, xmm1
+ pminsw xmm4, xmm1
+
+ movdqa [r9 + rdx], xmm8
+ movdqa [r9 + rdx + 16], xmm0
+ movdqa [r9 + rdx + 32], xmm10
+ movdqa [r9 + rdx + 48], xmm4
+
+ add r8, 128
+ add rdx, 64
+ inc rax
+ jmp .qlp
+.qdone:
+ ret
+
+; ----------------------------------------------------------------------------
+; DOT32 lo, hi, off : lo/hi = 4 x float (int8x32 dot, 4 products per lane)
+; lo = elements 0..15 of the block, hi = elements 16..31
+; w = [rax + rbx + off], x = [r11 + rbx*2 + off*2] scratch: xmm8, xmm9
+; ----------------------------------------------------------------------------
+%macro DOT32 3
+ movdqu xmm8, [rax + rbx + %3]
+ movdqa xmm9, xmm8
+ psllw xmm8, 8
+ psraw xmm8, 8 ; even weights as int16
+ psraw xmm9, 8 ; odd weights as int16
+ pmaddwd xmm8, [r11 + rbx*2 + (%3)*2]
+ pmaddwd xmm9, [r11 + rbx*2 + (%3)*2 + 16]
+ paddd xmm8, xmm9
+ cvtdq2ps %1, xmm8
+ movdqu xmm8, [rax + rbx + %3 + 16]
+ movdqa xmm9, xmm8
+ psllw xmm8, 8
+ psraw xmm8, 8
+ psraw xmm9, 8
+ pmaddwd xmm8, [r11 + rbx*2 + (%3)*2 + 32]
+ pmaddwd xmm9, [r11 + rbx*2 + (%3)*2 + 48]
+ paddd xmm8, xmm9
+ cvtdq2ps %2, xmm8
+%endmacro
+
+; BLK accLo, accHi, off, pshufd-imm : acc += dot(block) * scale[lane]
+; xmm12 = 4 block scales (w_scale * x_scale), xmm10/xmm11 = scratch, xmm13 = broadcast
+%macro BLK 4
+ DOT32 xmm10, xmm11, %3
+ pshufd xmm13, xmm12, %4
+ mulps xmm10, xmm13
+ mulps xmm11, xmm13
+ addps %1, xmm10
+ addps %2, xmm11
+%endmacro
+
+; 4 blocks (128 weights = 2 cache lines); ymm0..3 of the AVX kernel == xmm0..7 here
+%macro INT8_1ROW_4BLK 0
+ Q8_PREFETCH [r8 + rbx]
+ Q8_PREFETCH [r8 + rbx + 64]
+ BLK xmm0, xmm1, 0, 0x00
+ BLK xmm2, xmm3, 32, 0x55
+ BLK xmm4, xmm5, 64, 0xAA
+ BLK xmm6, xmm7, 96, 0xFF
+%endmacro
+
+; row reduction: same add order as the AVX kernel, result -> [rdx]
+%macro ROW_REDUCE 0
+ addps xmm0, xmm2
+ addps xmm1, xmm3
+ addps xmm4, xmm6
+ addps xmm5, xmm7
+ addps xmm0, xmm4
+ addps xmm1, xmm5
+ HSUM4 xmm0, xmm8
+ HSUM4 xmm1, xmm9
+ addss xmm0, xmm1
+ movss [rdx], xmm0
+%endmacro
+
+%macro ZERO_ACC 0
+ xorps xmm0, xmm0
+ xorps xmm1, xmm1
+ xorps xmm2, xmm2
+ xorps xmm3, xmm3
+ xorps xmm4, xmm4
+ xorps xmm5, xmm5
+ xorps xmm6, xmm6
+ xorps xmm7, xmm7
+%endmacro
+
+; ----------------------------------------------------------------------------
+; void matmul_q8_0_range(const void *W, const float *x, float *out,
+; uint64 K, uint64 r0, uint64 r1)
+; rdi = W, rsi = x (unused: x was quantized by quantize_x_q8_0), rdx = out,
+; rcx = K, r8 = r0, r9 = r1
+; ----------------------------------------------------------------------------
+matmul_q8_0_range:
+ push rbx
+ push rbp
+ push r12
+ push r13
+ push r14
+ push r15
+
+ mov rsi, r9
+ sub rsi, r8 ; rsi = rows_left = r1 - r0
+ jle .exit
+
+ lea rdx, [rdx + r8 * 4] ; rdx = out_ptr = out + r0 * 4
+ lea r11, [rel q8_xw]
+ lea rbp, [rel q8_xs]
+ mov r15, rcx ; r15 = K
+ mov r13, rcx
+ and r13, -128 ; r13 = K_128 = K & ~127
+
+ cmp dword [rel g_fp16_scales], 0
+ jne .fast_fp16
+
+ ; ========================================================================
+ ; v1 FP32 scales: row_stride = K + (K >> 3)
+ ; ========================================================================
+ mov r14, rcx
+ shr r14, 3
+ add r14, rcx ; r14 = row_stride
+ mov rax, r8
+ imul rax, r14
+ add rax, rdi ; rax = w_cur = W + r0 * row_stride
+
+align 16
+.row_f32:
+ lea r12, [rax + r14] ; r12 = w_next
+ lea r8, [rax + r15] ; r8 = s_cur (fp32)
+ ZERO_ACC
+ xor ebx, ebx ; b_q: 0, 128, ...
+ xor r9d, r9d ; b_s: 0, 16, ...
+ test r13, r13
+ jz .tail_f32
+
+align 16
+.blk4_f32:
+ movups xmm12, [r8 + r9] ; 4x fp32 scale_w
+ mulps xmm12, [rbp + r9] ; * 4x fp32 scale_x
+ INT8_1ROW_4BLK
+ add rbx, 128
+ add r9, 16
+ cmp rbx, r13
+ jb .blk4_f32
+
+.tail_f32:
+ cmp rbx, r15
+ jae .red_f32
+ DOT32 xmm10, xmm11, 0
+ movss xmm13, [r8 + r9]
+ mulss xmm13, [rbp + r9]
+ shufps xmm13, xmm13, 0
+ mulps xmm10, xmm13
+ mulps xmm11, xmm13
+ addps xmm0, xmm10
+ addps xmm1, xmm11
+ add rbx, 32
+ add r9, 4
+ jmp .tail_f32
+
+.red_f32:
+ ROW_REDUCE
+ add rdx, 4
+ mov rax, r12
+ dec rsi
+ jnz .row_f32
+ jmp .exit
+
+ ; ========================================================================
+ ; v2 FP16 scales: row_stride = K + (K >> 4)
+ ; ========================================================================
+.fast_fp16:
+ mov r14, rcx
+ shr r14, 4
+ add r14, rcx ; r14 = row_stride
+ mov rax, r8
+ imul rax, r14
+ add rax, rdi ; rax = w_cur = W + r0 * row_stride
+
+align 16
+.row_f16:
+ lea r12, [rax + r14] ; r12 = w_next
+ lea r8, [rax + r15] ; r8 = s_cur (fp16)
+ ZERO_ACC
+ xor ebx, ebx
+ xor r9d, r9d ; b_s: 0, 8, ... (fp16 offset; xs = r9*2)
+ test r13, r13
+ jz .tail_f16
+
+align 16
+.blk4_f16:
+ movq xmm12, [r8 + r9] ; 4x fp16 scale_w
+ pxor xmm13, xmm13
+ punpcklwd xmm12, xmm13 ; -> 4 x 32-bit lanes
+ H2F4 xmm12, xmm8, xmm9
+ mulps xmm12, [rbp + r9*2] ; * 4x fp32 scale_x
+ INT8_1ROW_4BLK
+ add rbx, 128
+ add r9, 8
+ cmp rbx, r13
+ jb .blk4_f16
+
+.tail_f16:
+ cmp rbx, r15
+ jae .red_f16
+ DOT32 xmm10, xmm11, 0
+ movzx ecx, word [r8 + r9]
+ movd xmm13, ecx
+ H2F4 xmm13, xmm8, xmm9
+ mulss xmm13, [rbp + r9*2]
+ shufps xmm13, xmm13, 0
+ mulps xmm10, xmm13
+ mulps xmm11, xmm13
+ addps xmm0, xmm10
+ addps xmm1, xmm11
+ add rbx, 32
+ add r9, 2
+ jmp .tail_f16
+
+.red_f16:
+ ROW_REDUCE
+ add rdx, 4
+ mov rax, r12
+ dec rsi
+ jnz .row_f16
+
+.exit:
+ pop r15
+ pop r14
+ pop r13
+ pop r12
+ pop rbp
+ pop rbx
+ ret
+
+; ----------------------------------------------------------------------------
+; float dot_f32_avx2(const float *a, const float *b, uint64 n) -> xmm0
+; rdi = a, rsi = b, rdx = n (multiple of 32). Same 8-lane x 4-accumulator
+; structure and reduction order as the AVX kernel (xmm lo/hi pairs).
+; ----------------------------------------------------------------------------
+%macro DOTSTEP 2 ; %1 = byte offset, %2 = accumulator
+ movups xmm8, [rdi + rax + %1]
+ movups xmm9, [rsi + rax + %1]
+ mulps xmm8, xmm9
+ addps %2, xmm8
+%endmacro
+
+dot_f32_avx2:
+ ZERO_ACC
+ shl rdx, 2
+ xor eax, eax
+.dlp:
+ cmp rax, rdx
+ jae .dred
+ DOTSTEP 0, xmm0
+ DOTSTEP 16, xmm1
+ DOTSTEP 32, xmm2
+ DOTSTEP 48, xmm3
+ DOTSTEP 64, xmm4
+ DOTSTEP 80, xmm5
+ DOTSTEP 96, xmm6
+ DOTSTEP 112, xmm7
+ add rax, 128
+ jmp .dlp
+.dred:
+ addps xmm0, xmm2 ; ymm0 += ymm1
+ addps xmm1, xmm3
+ addps xmm4, xmm6 ; ymm2 += ymm3
+ addps xmm5, xmm7
+ addps xmm0, xmm4 ; ymm0 += ymm2
+ addps xmm1, xmm5
+ addps xmm0, xmm1 ; lo + hi
+ HSUM4 xmm0, xmm2
+ ret
+
+; ----------------------------------------------------------------------------
+; void saxpy_f32_avx2(float *dst, const float *src, uint64 n, float alpha)
+; rdi = dst, rsi = src, rdx = n (multiple of 32), xmm0 = alpha
+; dst[i] += alpha * src[i]
+; ----------------------------------------------------------------------------
+%macro SAXSTEP 1
+ movups xmm1, [rdi + rax + %1]
+ movups xmm2, [rsi + rax + %1]
+ mulps xmm2, xmm0
+ addps xmm1, xmm2
+ movups [rdi + rax + %1], xmm1
+%endmacro
+
+saxpy_f32_avx2:
+ shufps xmm0, xmm0, 0
+ shl rdx, 2
+ xor eax, eax
+.slp:
+ cmp rax, rdx
+ jae .sdone
+ SAXSTEP 0
+ SAXSTEP 16
+ SAXSTEP 32
+ SAXSTEP 48
+ SAXSTEP 64
+ SAXSTEP 80
+ SAXSTEP 96
+ SAXSTEP 112
+ add rax, 128
+ jmp .slp
+.sdone:
+ ret
+
+section .rodata
+align 16
+q8_abs_mask4: times 4 dd 0x7FFFFFFF
+q8_m127w: times 8 dw -127
+q8_p127w: times 8 dw 127
+h2f_8000: times 4 dd 0x00008000
+h2f_7c00: times 4 dd 0x00007C00
+h2f_7f800000: times 4 dd 0x7F800000
+h2f_2p112: times 4 dd 0x77800000 ; 2^112
+q8_f127: dd 127.0
+q8_inv_127: dd 0.007874015748031496 ; 1.0f / 127.0f
+
+section .bss
+alignb 64
+g_fp16_scales: resd 1
+alignb 64
+q8_xw: resb Q8_MAX_K * 2
+alignb 64
+q8_xs: resb (Q8_MAX_K / 32) * 4
diff --git a/shared/sse2_compat.inc b/shared/sse2_compat.inc
new file mode 100644
index 0000000..7699657
--- /dev/null
+++ b/shared/sse2_compat.inc
@@ -0,0 +1,154 @@
+; ============================================================================
+; sse2_compat.inc — VEX (AVX) scalar/xmm mnemonics -> plain SSE2 (x86-64 baseline)
+;
+; Included only when SSE2=1 (math.asm, kernel.asm, runtime.asm, transformer.asm).
+; NASM lets a multi-line macro replace an instruction name,
+; so existing scalar and 128-bit code assembles unchanged but emits legacy-SSE
+; encodings. The packed 256-bit (ymm) kernels are NOT handled here: they have
+; hand-written SSE2 versions under `%if SSE2` in matmul_sse2.asm / math.asm /
+; transformer.asm.
+;
+; Rules enforced at assembly time:
+; * 3-operand ops lower to `movaps d,a ; op d,b` (or `op d,a` when the op is
+; commutative and d==b). A non-commutative op with d==b!=a is an error
+; (it would need a scratch register) — fix the call site.
+; * Packed logic ops (xorps/andps/...) with a MEMORY operand need 16-byte
+; aligned memory in legacy SSE; keep such constants `align 16`.
+; Everything here is SSE2 or older (no SSE3 haddps, no SSE4.1 roundsd/blendv).
+; ============================================================================
+
+; ---- lowering helpers -------------------------------------------------------
+%macro __V3C 4 ; commutative: %1=sse op, %2=d, %3=a, %4=b
+ %ifidn %2,%3
+ %1 %2, %4
+ %elifidn %2,%4
+ %1 %2, %3
+ %else
+ movaps %2, %3
+ %1 %2, %4
+ %endif
+%endmacro
+
+%macro __V3N 4 ; non-commutative (and max/min: operand order matters)
+ %ifidn %2,%3
+ %1 %2, %4
+ %elifidn %2,%4
+ %error "sse2_compat: d==b!=a for a non-commutative op (needs a scratch register)"
+ %else
+ movaps %2, %3
+ %1 %2, %4
+ %endif
+%endmacro
+
+; ---- scalar float / double arithmetic ---------------------------------------
+%macro vaddss 3
+ __V3C addss, %1, %2, %3
+%endmacro
+%macro vaddsd 3
+ __V3C addsd, %1, %2, %3
+%endmacro
+%macro vmulss 3
+ __V3C mulss, %1, %2, %3
+%endmacro
+%macro vmulsd 3
+ __V3C mulsd, %1, %2, %3
+%endmacro
+%macro vsubss 3
+ __V3N subss, %1, %2, %3
+%endmacro
+%macro vsubsd 3
+ __V3N subsd, %1, %2, %3
+%endmacro
+%macro vdivss 3
+ __V3N divss, %1, %2, %3
+%endmacro
+%macro vdivsd 3
+ __V3N divsd, %1, %2, %3
+%endmacro
+%macro vmaxss 3
+ __V3N maxss, %1, %2, %3
+%endmacro
+
+%macro vsqrtss 3 ; d = sqrt(b); upper lanes are don't-care in this code base
+ sqrtss %1, %3
+%endmacro
+
+; ---- logic on registers/constants ------------------------------------------
+%macro vxorps 3
+ __V3C xorps, %1, %2, %3
+%endmacro
+%macro vxorpd 3
+ __V3C xorpd, %1, %2, %3
+%endmacro
+
+; ---- moves -------------------------------------------------------------------
+%macro vmovss 2
+ movss %1, %2
+%endmacro
+%macro vmovss 3 ; d = (a upper, b low)
+ %ifidn %1,%2
+ movss %1, %3
+ %else
+ movaps %1, %2
+ movss %1, %3
+ %endif
+%endmacro
+%macro vmovsd 2
+ movsd %1, %2
+%endmacro
+%macro vmovsd 3
+ %ifidn %1,%2
+ movsd %1, %3
+ %else
+ movaps %1, %2
+ movsd %1, %3
+ %endif
+%endmacro
+%macro vmovapd 2
+ movapd %1, %2
+%endmacro
+%macro vmovq 2
+ movq %1, %2
+%endmacro
+
+; ---- scalar FMA3 (math.asm's FP64 sin/cos/log/exp) -> mul+add ------------------
+; Two roundings instead of one: results differ from FMA hardware in the last bit,
+; well inside the documented accuracy of those routines.
+%macro vfmadd213sd 3 ; d = d*a + b
+ mulsd %1, %2
+ addsd %1, %3
+%endmacro
+%macro vfmadd231sd 3 ; d += a*b (a is clobbered)
+ mulsd %2, %3
+ addsd %1, %2
+%endmacro
+%macro vfnmadd231sd 3 ; d -= a*b (b is clobbered, must be a register)
+ mulsd %3, %2
+ subsd %1, %3
+%endmacro
+
+; ---- compare / convert --------------------------------------------------------
+%macro vucomiss 2
+ ucomiss %1, %2
+%endmacro
+%macro vucomisd 2
+ ucomisd %1, %2
+%endmacro
+%macro vcvtsi2sd 3 ; d = (double)int ; a is ignored (upper lanes unused)
+ cvtsi2sd %1, %3
+%endmacro
+%macro vcvtsi2ss 3
+ cvtsi2ss %1, %3
+%endmacro
+%macro vcvtss2sd 3
+ cvtss2sd %1, %3
+%endmacro
+%macro vcvtsd2ss 3
+ cvtsd2ss %1, %3
+%endmacro
+%macro vcvtsd2si 2 ; rounds per MXCSR (nearest-even), like the VEX form
+ cvtsd2si %1, %2
+%endmacro
+%macro vcvttsd2si 2
+ cvttsd2si %1, %2
+%endmacro
diff --git a/shared/transformer.asm b/shared/transformer.asm
index ca37711..5165f45 100644
--- a/shared/transformer.asm
+++ b/shared/transformer.asm
@@ -13,6 +13,12 @@ bits 64
default rel
%include "constants.inc"
+%ifndef SSE2
+%define SSE2 0
+%endif
+%if SSE2
+%include "sse2_compat.inc"
+%endif
%ifndef FAST_Q8
%define FAST_Q8 1
@@ -602,10 +608,21 @@ transformer_forward:
.kv_copy_lp:
cmp r9, r14
jae .kv_head_next
+%if SSE2
+ movups xmm0, [rsi + r9]
+ movups xmm2, [rsi + r9 + 16]
+ movups xmm1, [r8 + r9]
+ movups xmm3, [r8 + r9 + 16]
+ movups [rdi + r9], xmm0
+ movups [rdi + r9 + 16], xmm2
+ movups [rdx + r9], xmm1
+ movups [rdx + r9 + 16], xmm3
+%else
vmovups ymm0, [rsi + r9]
vmovups ymm1, [r8 + r9]
vmovups [rdi + r9], ymm0
vmovups [rdx + r9], ymm1
+%endif
add r9, 32
jmp .kv_copy_lp
.kv_head_next:
@@ -644,10 +661,21 @@ transformer_forward:
.kv_copy_lp:
cmp r9, rcx
jae .kv_copy_done
+%if SSE2
+ movups xmm0, [rsi + r9]
+ movups xmm2, [rsi + r9 + 16]
+ movups xmm1, [r8 + r9]
+ movups xmm3, [r8 + r9 + 16]
+ movups [rdi + r9], xmm0
+ movups [rdi + r9 + 16], xmm2
+ movups [rdx + r9], xmm1
+ movups [rdx + r9 + 16], xmm3
+%else
vmovups ymm0, [rsi + r9]
vmovups ymm1, [r8 + r9]
vmovups [rdi + r9], ymm0
vmovups [rdx + r9], ymm1
+%endif
add r9, 32
jmp .kv_copy_lp
.kv_copy_done:
@@ -715,12 +743,21 @@ transformer_forward:
mov rcx, [rbx + CTX_HEAD_DIM]
shl rcx, 2
+%if SSE2
+ xorps xmm0, xmm0
+%else
vxorps ymm0, ymm0, ymm0
+%endif
xor eax, eax
.zero_att:
cmp rax, rcx
jae .val_accum
+%if SSE2
+ movups [r14 + rax], xmm0
+ movups [r14 + rax + 16], xmm0
+%else
vmovups [r14 + rax], ymm0
+%endif
add rax, 32
jmp .zero_att
@@ -932,12 +969,21 @@ gqa_attn_range:
imul rax, rbp
mov r14, [rbx + CTX_BUF_ATT_OUT]
add r14, rax
+%if SSE2
+ xorps xmm0, xmm0
+%else
vxorps ymm0, ymm0, ymm0
+%endif
xor eax, eax
.z_lp:
cmp rax, rbp
jae .v_acc
+%if SSE2
+ movups [r14 + rax], xmm0
+ movups [r14 + rax + 16], xmm0
+%else
vmovups [r14 + rax], ymm0
+%endif
add rax, 32
jmp .z_lp