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.

Fix #9, #10, #38: auto-detect CPUs and adaptive spin/yield barriers

Alexey Fateev66c4ed50addc
diff --git a/01-qwen3-inference/main.asm b/01-qwen3-inference/main.asm
index f0fe890..ef09f6d 100644
--- a/01-qwen3-inference/main.asm
+++ b/01-qwen3-inference/main.asm
@@ -49,7 +49,7 @@ _start:
lea rax, [rel def_prompt]
mov [rel opt_prompt], rax
mov qword [rel opt_max_tok], 128
- mov qword [rel opt_threads], 32
+ mov qword [rel opt_threads], 0 ; 0 = auto-detect available CPUs
mov qword [rel opt_ctx_len], 2048
mov dword [rel opt_think], 0
mov dword [rel opt_raw], 0
@@ -282,6 +282,7 @@ _start:
; Start thread pool
mov rdi, [rel opt_threads]
call tp_init
+ mov [rel opt_threads], rax
lea rbp, [rel g_ctx]
cmp dword [rel opt_chat], 0
@@ -994,7 +995,7 @@ msg_usage:
db " -m <path> Path to .asmbin model (required)", 10
db " -p <prompt> Prompt text (default: Hello!)", 10
db " -n <max_tokens> Max generated tokens (default: 128)", 10
- db " -t <threads> Thread count (default: 32)", 10
+ db " -t <threads> Thread count (default: auto)", 10
db " -c <ctx_len> Max context / KV cache length (default: 2048)", 10
db " --chat Interactive multi-turn chat (preserves KV-cache)", 10
db " --think Enable Qwen3 <think> reasoning mode", 10
diff --git a/03-minigpt-train/main.asm b/03-minigpt-train/main.asm
index 4c8f125..f308340 100644
--- a/03-minigpt-train/main.asm
+++ b/03-minigpt-train/main.asm
@@ -96,7 +96,7 @@ _start:
mov qword [rel opt_dump_debug], 0
lea rax, [rel def_prompt]
mov [rel opt_prompt], rax
- mov qword [rel opt_threads], 16
+ mov qword [rel opt_threads], 0 ; 0 = auto-detect available CPUs
mov qword [rel opt_eval_every], 100
mov qword [rel opt_eval_batches], 20
mov qword [rel opt_log_every], 50
@@ -283,6 +283,7 @@ _start:
; Initialize thread pool
mov rdi, [rel opt_threads]
call tp_init
+ mov [rel opt_threads], rax
; ========================================================================
; SAMPLE-ONLY MODE (--load <ckpt> --sample-only [--prompt "..."])
@@ -1904,7 +1905,7 @@ msg_usage:
db " --grad-clip <float> Global L2 gradient clip (default: 1.0)", 10
db " --warmup <N> Warmup steps (default: min(100, steps/10))", 10
db " --seed <uint> PRNG seed (default: 42)", 10
- db " -t <threads> CPU thread count (default: 16)", 10
+ db " -t <threads> CPU thread count (default: auto)", 10
db " --eval-every <K> Val loss eval interval (default: 100)", 10
db " --eval-batches <K> Val eval batch count (default: 20)", 10
db " --log-every <K> Step log interval (default: 50)", 10
diff --git a/03-minigpt-train/sgemm.asm b/03-minigpt-train/sgemm.asm
index f96f729..ef69cf8 100644
--- a/03-minigpt-train/sgemm.asm
+++ b/03-minigpt-train/sgemm.asm
@@ -27,9 +27,16 @@ default rel
%include "train_constants.inc"
-%define SPIN_LIMIT 200000
+%define SPIN_LIMIT_FAST 200000
+%define SPIN_LIMIT_CONTEND 128
+%define WAIT_SPIN_FAST 8000
+%define WAIT_SPIN_CONTEND 64
+%define WAIT_SPIN_RETRY 32
+%define CONTEND_LATCH_YIELDS 8
+%define DEFAULT_MAX_THREADS 16
extern sys_mmap_anon
+extern sys_detect_cpus
section .text
@@ -46,13 +53,37 @@ global tp_sgemm_nt
; ============================================================================
; ----------------------------------------------------------------------------
-; void tp_init(uint64 n_threads)
+; uint64 tp_init(uint64 n_threads)
+; rdi = requested total thread count (0 = auto; clamped to [1, MAX_THREADS])
+; Returns actual thread count in rax.
; ----------------------------------------------------------------------------
tp_init:
push rbx
push r12
push r13
+ mov r12, rdi ; save requested n_threads (0 = auto)
+ call sys_detect_cpus
+ mov r13, rax ; avail_cpus
+
+ test r12, r12
+ jnz .chk_min
+ ; Auto default: min(16, max(1, avail_cpus - 1)) to leave 1 OS headroom core
+ mov rdi, r13
+ cmp rdi, 1
+ jbe .auto_one
+ dec rdi
+ jmp .auto_cap
+.auto_one:
+ mov rdi, 1
+.auto_cap:
+ cmp rdi, DEFAULT_MAX_THREADS
+ jle .chk_max
+ mov rdi, DEFAULT_MAX_THREADS
+ jmp .chk_max
+
+.chk_min:
+ mov rdi, r12
cmp rdi, 1
jge .chk_max
mov rdi, 1
@@ -65,6 +96,7 @@ tp_init:
mov dword [rel tp_gen], 0
mov dword [rel tp_stop], 0
mov dword [rel tp_waiters], 0
+ mov dword [rel tp_yields], 0
lea rax, [rel tp_done_arr]
xor ecx, ecx
@@ -79,13 +111,13 @@ tp_init:
.clr_done:
cmp rdi, 1
- jle .done
+ jle .set_spin
mov r12, rdi
mov rbx, 1
.spawn_lp:
cmp rbx, r12
- jae .done
+ jae .set_spin
mov rdi, WORKER_STACK_SIZE
call sys_mmap_anon
@@ -111,7 +143,18 @@ tp_init:
.spawn_fail:
mov [rel tp_n_threads], rbx
+.set_spin:
+ mov rax, [rel tp_n_threads]
+ cmp rax, r13
+ jb .spin_fast
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ mov dword [rel tp_wait_spin], WAIT_SPIN_CONTEND
+ jmp .done
+.spin_fast:
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_FAST
+ mov dword [rel tp_wait_spin], WAIT_SPIN_FAST
.done:
+ mov rax, [rel tp_n_threads]
pop r13
pop r12
pop rbx
@@ -123,7 +166,9 @@ tp_init:
xor r13d, r13d ; my_gen = 0
.worker_wait:
- mov ecx, SPIN_LIMIT
+ mov ecx, [rel tp_worker_spin]
+ test ecx, ecx
+ jz .enter_futex
.spin_lp:
mov eax, [rel tp_gen]
cmp eax, r13d
@@ -132,6 +177,7 @@ tp_init:
dec ecx
jnz .spin_lp
+.enter_futex:
lock inc dword [rel tp_waiters]
mov eax, [rel tp_gen]
cmp eax, r13d
@@ -246,19 +292,36 @@ tp_run:
; Wait for workers 1 .. n_threads - 1
lea rdi, [rel tp_done_arr]
- mov rcx, 1
+ mov r8, 1
+ mov r9d, [rel tp_wait_spin]
.wait_tid:
- cmp rcx, rbx
+ cmp r8, rbx
jae .done
- mov rdx, rcx
+ mov rdx, r8
shl rdx, 6
.spin_tid:
cmp dword [rdi + rdx], r12d
je .next_tid
+ test r9d, r9d
+ jz .yield_tid
pause
+ dec r9d
+ jmp .spin_tid
+.yield_tid:
+ cmp dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ je .do_yield
+ inc dword [rel tp_yields]
+ cmp dword [rel tp_yields], CONTEND_LATCH_YIELDS
+ jb .do_yield
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ mov dword [rel tp_wait_spin], WAIT_SPIN_CONTEND
+.do_yield:
+ mov eax, SYS_sched_yield
+ syscall
+ mov r9d, WAIT_SPIN_RETRY
jmp .spin_tid
.next_tid:
- inc rcx
+ inc r8
jmp .wait_tid
.done:
@@ -926,9 +989,12 @@ sgemm_worker:
; ============================================================================
section .bss
alignb 64
-tp_gen: resd 1
-tp_stop: resd 1
-tp_n_threads: resq 1
+tp_gen: resd 1
+tp_stop: resd 1
+tp_worker_spin: resd 1
+tp_wait_spin: resd 1
+tp_yields: resd 1
+tp_n_threads: resq 1
tp_fn: resq 1
tp_arg: resq 1
diff --git a/shared/constants.inc b/shared/constants.inc
index e82809c..4bf5401 100644
--- a/shared/constants.inc
+++ b/shared/constants.inc
@@ -10,9 +10,11 @@
%define SYS_fstat 5
%define SYS_mmap 9
%define SYS_munmap 11
+%define SYS_sched_yield 24
%define SYS_clone 56
%define SYS_exit 60
%define SYS_futex 202
+%define SYS_sched_getaffinity 204
%define SYS_clock_gettime 228
%define SYS_exit_group 231
%define SYS_openat 257
diff --git a/shared/syscalls.asm b/shared/syscalls.asm
index d11fa00..799a63b 100644
--- a/shared/syscalls.asm
+++ b/shared/syscalls.asm
@@ -20,6 +20,9 @@ global sys_munmap
global sys_write_all
global sys_clock_ns
global sys_exit_group
+%ifndef BARE_METAL
+global sys_detect_cpus
+%endif
global str_len
global str_eq
global parse_u64
@@ -170,6 +173,56 @@ sys_exit_group:
syscall
hlt
+%ifndef BARE_METAL
+; ----------------------------------------------------------------------------
+; uint64 sys_detect_cpus(void)
+; Queries Linux sched_getaffinity(0, 128, buf) and counts allowed CPUs.
+; Returns >= 1 in rax (falls back to 1 on error).
+; ----------------------------------------------------------------------------
+sys_detect_cpus:
+ sub rsp, 136 ; 128B cpumask + 8B align (16B aligned)
+ xor edi, edi ; pid = 0 (calling thread)
+ mov esi, 128 ; cpusetsize = 128 bytes
+ mov rdx, rsp
+ mov eax, SYS_sched_getaffinity
+ syscall
+ test rax, rax
+ jle .fallback
+
+ cmp rax, 128
+ jle .len_ok
+ mov eax, 128
+.len_ok:
+ xor ecx, ecx ; cpu count
+ xor r8d, r8d ; byte index
+.byte_lp:
+ cmp r8, rax
+ jae .cnt_done
+ movzx edx, byte [rsp + r8]
+.bit_lp:
+ test edx, edx
+ jz .bit_next
+ lea r9d, [edx - 1]
+ and edx, r9d
+ inc ecx
+ jmp .bit_lp
+.bit_next:
+ inc r8
+ jmp .byte_lp
+
+.cnt_done:
+ test ecx, ecx
+ jz .fallback
+ mov eax, ecx
+ add rsp, 136
+ ret
+
+.fallback:
+ mov eax, 1
+ add rsp, 136
+ ret
+%endif
+
; ----------------------------------------------------------------------------
; uint64 str_len(const char *s)
; ----------------------------------------------------------------------------
diff --git a/shared/threads.asm b/shared/threads.asm
index ffd9b52..e6a3cbd 100644
--- a/shared/threads.asm
+++ b/shared/threads.asm
@@ -22,9 +22,16 @@ default rel
%define FAST_Q8 1
%endif
-%define SPIN_LIMIT 200000
+%define SPIN_LIMIT_FAST 200000
+%define SPIN_LIMIT_CONTEND 128
+%define WAIT_SPIN_FAST 8000
+%define WAIT_SPIN_CONTEND 64
+%define WAIT_SPIN_RETRY 32
+%define CONTEND_LATCH_YIELDS 8
+%define DEFAULT_MAX_THREADS 32
extern sys_mmap_anon
+extern sys_detect_cpus
extern matmul_q8_0_range
%if FAST_Q8
extern quantize_x_q8_0
@@ -41,14 +48,37 @@ global tp_gqa_attn
%endif
; ----------------------------------------------------------------------------
-; void tp_init(uint64 n_threads)
-; rdi = requested total thread count (clamped to [1, MAX_THREADS])
+; uint64 tp_init(uint64 n_threads)
+; rdi = requested total thread count (0 = auto; clamped to [1, MAX_THREADS])
+; Returns actual thread count in rax.
; ----------------------------------------------------------------------------
tp_init:
push rbx
push r12
push r13
+ mov r12, rdi ; save requested n_threads (0 = auto)
+ call sys_detect_cpus
+ mov r13, rax ; avail_cpus
+
+ test r12, r12
+ jnz .chk_min
+ ; Auto default: min(32, max(1, avail_cpus - 1)) to leave 1 OS headroom core
+ mov rdi, r13
+ cmp rdi, 1
+ jbe .auto_one
+ dec rdi
+ jmp .auto_cap
+.auto_one:
+ mov rdi, 1
+.auto_cap:
+ cmp rdi, DEFAULT_MAX_THREADS
+ jle .chk_max
+ mov rdi, DEFAULT_MAX_THREADS
+ jmp .chk_max
+
+.chk_min:
+ mov rdi, r12
cmp rdi, 1
jge .chk_max
mov rdi, 1
@@ -61,6 +91,7 @@ tp_init:
mov dword [rel tp_gen], 0
mov dword [rel tp_stop], 0
mov dword [rel tp_waiters], 0
+ mov dword [rel tp_yields], 0
; Clear per-worker completion slots
lea rax, [rel tp_done_arr]
@@ -76,13 +107,13 @@ tp_init:
.clr_done:
cmp rdi, 1
- jle .done
+ jle .set_spin
mov r12, rdi ; total threads
mov rbx, 1 ; worker tid = 1 .. n_threads - 1
.spawn_lp:
cmp rbx, r12
- jae .done
+ jae .set_spin
mov rdi, WORKER_STACK_SIZE
call sys_mmap_anon
@@ -108,7 +139,18 @@ tp_init:
.spawn_fail:
mov [rel tp_n_threads], rbx
+.set_spin:
+ mov rax, [rel tp_n_threads]
+ cmp rax, r13
+ jb .spin_fast
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ mov dword [rel tp_wait_spin], WAIT_SPIN_CONTEND
+ jmp .done
+.spin_fast:
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_FAST
+ mov dword [rel tp_wait_spin], WAIT_SPIN_FAST
.done:
+ mov rax, [rel tp_n_threads]
pop r13
pop r12
pop rbx
@@ -123,7 +165,9 @@ tp_init:
xor r13d, r13d ; r13d = my_gen = 0
.worker_wait:
- mov ecx, SPIN_LIMIT
+ mov ecx, [rel tp_worker_spin]
+ test ecx, ecx
+ jz .enter_futex
.spin_lp:
mov eax, [rel tp_gen]
cmp eax, r13d
@@ -132,6 +176,7 @@ tp_init:
dec ecx
jnz .spin_lp
+.enter_futex:
lock inc dword [rel tp_waiters]
mov eax, [rel tp_gen]
cmp eax, r13d
@@ -347,19 +392,36 @@ tp_matmul_q8_0:
.wait_workers:
; Wait for each worker tid = 1 .. n_threads-1 to store new_gen in its cache line
lea rdi, [rel tp_done_arr]
- mov rcx, 1
+ mov r8, 1
+ mov r9d, [rel tp_wait_spin]
.wait_tid:
- cmp rcx, rbx
+ cmp r8, rbx
jae .all_done
- mov rdx, rcx
+ mov rdx, r8
shl rdx, 6 ; tid * 64
.spin_tid:
cmp dword [rdi + rdx], r12d
je .next_tid
+ test r9d, r9d
+ jz .yield_tid
pause
+ dec r9d
+ jmp .spin_tid
+.yield_tid:
+ cmp dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ je .do_yield
+ inc dword [rel tp_yields]
+ cmp dword [rel tp_yields], CONTEND_LATCH_YIELDS
+ jb .do_yield
+ mov dword [rel tp_worker_spin], SPIN_LIMIT_CONTEND
+ mov dword [rel tp_wait_spin], WAIT_SPIN_CONTEND
+.do_yield:
+ mov eax, SYS_sched_yield
+ syscall
+ mov r9d, WAIT_SPIN_RETRY
jmp .spin_tid
.next_tid:
- inc rcx
+ inc r8
jmp .wait_tid
.all_done:
@@ -421,9 +483,12 @@ tp_gqa_attn:
section .bss
alignb 64
-tp_gen: resd 1
-tp_stop: resd 1
-tp_n_threads: resq 1
+tp_gen: resd 1
+tp_stop: resd 1
+tp_worker_spin: resd 1
+tp_wait_spin: resd 1
+tp_yields: resd 1
+tp_n_threads: resq 1
tp_W: resq 1
tp_x: resq 1
tp_out: resq 1