diff --git a/.gitignore b/.gitignore index fd0ce970e..086a01172 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,157 @@ build/qual-runs/ /omega tests/test_omega_numeric .crumb.local + +# CUDA++ files, linked in by tools/cudapp-link.sh (see cudapp.files) +/src/omega_blackwell_codegen_attn.c +/src/omega_blackwell_codegen_attn.h +/src/omega_blackwell_codegen_bf16.c +/src/omega_blackwell_codegen_bf16.h +/src/omega_blackwell_codegen.c +/src/omega_blackwell_codegen_dec.c +/src/omega_blackwell_codegen_dec.h +/src/omega_blackwell_codegen_gemm.c +/src/omega_blackwell_codegen_gemm.h +/src/omega_blackwell_codegen.h +/src/omega_blackwell_codegen_moe2.c +/src/omega_blackwell_codegen_moe2.h +/src/omega_blackwell_codegen_moe.c +/src/omega_blackwell_codegen_moe.h +/src/omega_blackwell_codegen_pattn.c +/src/omega_blackwell_codegen_pattn.h +/src/omega_blackwell_codegen_pf.c +/src/omega_blackwell_codegen_pf.h +/src/omega_blackwell_codegen_pfhost.c +/src/omega_blackwell_codegen_pfhost.h +/src/omega_blackwell_codegen_qg.c +/src/omega_blackwell_codegen_qg.h +/src/omega_blackwell_codegen_qmma.c +/src/omega_blackwell_codegen_qmma.h +/src/omega_blackwell_codegen_router.c +/src/omega_blackwell_codegen_router.h +/src/omega_blackwell_codegen_tc2.c +/src/omega_blackwell_codegen_tc2.h +/src/omega_blackwell_codegen_tc.c +/src/omega_blackwell_codegen_tc.h +/src/omega_blackwell_codegen_tern.c +/src/omega_blackwell_codegen_tern.h +/src/omega_blackwell_encoder.c +/src/omega_blackwell_encoder.h +/src/omega_blackwell_engine.c +/src/omega_blackwell_engine.h +/src/omega_blackwell_matmul.c +/src/omega_blackwell_matmul.h +/src/omega_blackwell_qmd.c +/src/omega_blackwell_qmd.h +/src/omega_blackwell_realize.c +/src/omega_blackwell_realize.h +/src/omega_blackwell_submit.c +/src/omega_blackwell_submit.h +/src/omega_bw_em.h +/src/omega_bw_em_q.h +/src/omega_bw_reconv.h +/src/omega_gpu_attention_api.c +/src/omega_gpu_attention_api.h +/src/omega_gpu_bf16_gemv_api.c +/src/omega_gpu_bf16_gemv_api.h +/src/omega_gpu_cmdlist.c +/src/omega_gpu_cmdlist.h +/src/omega_gpu_code_alloc.h +/src/omega_gpu_decode_attn_api.c +/src/omega_gpu_decode_attn_api.h +/src/omega_gpu_decode_graph.c +/src/omega_gpu_decode_graph.h +/src/omega_gpu_elementwise_api.c +/src/omega_gpu_elementwise_api.h +/src/omega_gpu_engine.c +/src/omega_gpu_engine.h +/src/omega_gpu_fmt.c +/src/omega_gpu_fmt.h +/src/omega_gpu_fp8_api.c +/src/omega_gpu_fp8_api.h +/src/omega_gpu_fp8gemm_api.c +/src/omega_gpu_fp8gemm_api.h +/src/omega_gpu_fp8_pack.c +/src/omega_gpu_hostmath.c +/src/omega_gpu_hostmath.h +/src/omega_gpu_matmul_api.c +/src/omega_gpu_matmul_api.h +/src/omega_gpu_mem_cached.c +/src/omega_gpu_mem_cached.h +/src/omega_gpu_moe_api.c +/src/omega_gpu_moe_api.h +/src/omega_gpu_pfgemm.c +/src/omega_gpu_pfhost.c +/src/omega_gpu_pfhost.h +/src/omega_gpu_platform.c +/src/omega_gpu_platform.h +/src/omega_gpu_platform_linux.c +/src/omega_gpu_platform_linux.h +/src/omega_gpu_prefill_attn_api.c +/src/omega_gpu_prefill_attn_api.h +/src/omega_gpu_prefill.c +/src/omega_gpu_prefill.h +/src/omega_gpu_router_api.c +/src/omega_gpu_router_api.h +/src/omega_gpu_serving.c +/src/omega_gpu_serving.h +/src/omega_gpu_session.c +/src/omega_gpu_session.h +/src/omega_gpu_tcgemm_api.c +/src/omega_gpu_tcgemm_api.h +/src/omega_gpu_tern_api.c +/src/omega_gpu_tern_api.h +/src/omega_gpu_wait.c +/src/omega_gpu_wait.h +/tests/bw_hmma_model.h +/tests/bw_qmma_model.h +/tests/bw_warp_sim.h +/tests/bw_warp_sim_k.h +/tests/bw_warp_sim_pa.h +/tests/bw_warp_sim_tc.h +/tests/fake_m16_native.c +/tests/fake_m16_native.h +/tests/gpu_attention_test.c +/tests/gpu_bf16_gemv_test.c +/tests/gpu_cmdlist_test.c +/tests/gpu_decode_attn_test.c +/tests/gpu_decode_graph_test.c +/tests/gpu_elementwise_test.c +/tests/gpu_fp8_api_test.c +/tests/gpu_fp8gemm_test.c +/tests/gpu_gpr_boundary_test.c +/tests/gpu_l2_reuse_test.c +/tests/gpu_l2_stale_test.c +/tests/gpu_launch_cost_test.c +/tests/gpu_lmhead_fp8_study.c +/tests/gpu_matmul_api_test.c +/tests/gpu_matmul_r4_receipt.c +/tests/gpu_moe_window_test.c +/tests/gpu_pfgemm_test.c +/tests/gpu_pfhost_test.c +/tests/gpu_pf_mem_test.c +/tests/gpu_prefill_attn_test.c +/tests/gpu_qgemm_test.c +/tests/gpu_qmma_probe_test.c +/tests/gpu_reconv_test.c +/tests/gpu_router_test.c +/tests/gpu_serving_alloc_count_test.c +/tests/gpu_session_probe.c +/tests/gpu_tcgemm_test.c +/tests/gpu_tc_peak_test.c +/tests/gpu_tc_probe_test.c +/tests/test_omega_blackwell_engine.c +/tests/test_omega_codegen_freestanding.c +/tests/test_omega_gpu_code_alloc.c +/tests/test_omega_gpu_engine.c +/tests/test_omega_gpu_engine_compile.c +/tests/test_omega_gpu_engine_gb10.c +/tests/test_omega_gpu_platform.c +/tests/test_omega_gpu_platform_linux.c +/tests/test_omega_gpu_session_platform.c +/tests/test_omega_gpu_wait.c +/mk/omega-gpu-engine.mk +/mk/omega-gpu-code-alloc.mk +/mk/omega-gpu-wait.mk +/tools/gpu_engine_mutations.sh +/tools/gpu_engine_backend_mutations.sh diff --git a/Makefile b/Makefile index 3551fea3f..8c5856001 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,15 @@ CC ?= gcc .DEFAULT_GOAL := all PHYSICS_DIR ?= ../physics OUT_DIR ?= build +# CUDA++ (aien-dev/CUDAplusplus, MIT) holds the GPU toolchain, runtime and libraries since 2026-10-21. +# They are linked in from CUDAPP_DIR at cudapp.lock before anything else is read (tools/cudapp-link.sh). +# Default: a CUDA++ checkout next to omega if there is one, else build/cudapp (cloned at cudapp.lock on first use). +CUDAPP_DIR ?= $(if $(wildcard ../CUDAplusplus/src),../CUDAplusplus,build/cudapp) +GPU_PROD_TARGET ?= build/omegatool +CUDAPP_LINK := $(shell tools/cudapp-link.sh "$(CUDAPP_DIR)" >&2 || echo FAIL) +ifneq ($(CUDAPP_LINK),) +$(error CUDA++ files could not be linked from CUDAPP_DIR=$(CUDAPP_DIR); see the cudapp-link message above) +endif -include mk/*.mk PHYSICS_LOCK_CHECK ?= 1 @@ -75,7 +84,7 @@ LEARNER = $(OUT_DIR)/crumbline-learner .PHONY: all clean check-physics-lock crumbline-learner test-crumbline test-m19 test test-m5 test-m6 test-m7 test-m8 test-m9 test-m10 test-m11 test-m12 test-m13 test-m14 test-m15 test-m17 test-r3 test-i11-wake-merge test-action-graph test-state-projection test-capability-query test-capability-graph test-skillroute-compose test-semantic-comm test-cognitive-routing test-sem-incremental test-branch-reuse test-jspace-prod test-plan-reuse test-cortex -all: check-physics-lock $(TARGET) +all: check-physics-lock check-cudapp-shared $(TARGET) check-physics-lock: @if [ "$(PHYSICS_LOCK_CHECK)" != "0" ]; then \ @@ -2604,3 +2613,11 @@ $(GPU_LAUNCH_COST_TEST): tests/gpu_launch_cost_test.c src/omega_gpu_fp8_api.h sr GPU_L2_REUSE_TEST = $(OUT_DIR)/gpu_l2_reuse_test $(GPU_L2_REUSE_TEST): tests/gpu_l2_reuse_test.c src/omega_gpu_fp8_api.h src/omega_gpu_cmdlist.h $(OUT_DIR)/libomega_gpu.a $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_l2_reuse_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + +# The shared base (CUDA++ tools/extract/shared.txt): files both repositories need. Omega owns them and +# builds only its own copies; the pinned CUDA++ must hold byte-identical copies, or this fails. +CUDAPP_SHARED = src/sha256.c src/sha256.h src/omega_types.h src/omega_vector.c src/omega_vector.h \ + src/omega_core.c src/omega_core.h src/omega_canonical.c src/omega_canonical.h tools/mutation_runner.sh +.PHONY: check-cudapp-shared +check-cudapp-shared: + @for f in $(CUDAPP_SHARED); do cmp -s "$$f" "$(CUDAPP_DIR)/$$f" || { echo "error: $$f differs from CUDAPP_DIR=$(CUDAPP_DIR)/$$f (shared base drift: change both, then move cudapp.lock)" >&2; exit 1; }; done diff --git a/README.md b/README.md index 87f91fbf1..a3b25993e 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ The live status is owned by [aien-architecture](https://github.com/aien-spark/ai ## How this fits with the other repositories +**CUDA++** ([aien-dev/CUDAplusplus](https://github.com/aien-dev/CUDAplusplus), MIT) is the GPU half of the Omega runtime: the sm_121 toolchain, the GPU runtime, the GPU libraries and the driver client, split out of this repository with their history on 2026-10-21 so anyone can use them. Omega builds them at the commit in `cudapp.lock`: `make` links each file listed in `cudapp.files` from a CUDA++ checkout (`../CUDAplusplus` if it exists, else `build/cudapp`, cloned on first use) by `tools/cudapp-link.sh`, so every rule and script here works unchanged. Change those files in CUDA++, then move `cudapp.lock`. Nine shared files (`CUDAPP_SHARED` in the Makefile) live in both repositories; `make check-cudapp-shared` fails if they differ. + [aienos](https://github.com/aien-spark/aienos) is the kernel Omega is meant to run on. [physics](https://github.com/aien-spark/physics) provides FORGE machine realization and the GB10 native path (pinned in `physics.lock`). [aien-architecture](https://github.com/aien-spark/aien-architecture) owns status and sequencing. ARGUS-0/1 (a defensive plane) is implemented in aienos (`native/argus`, pinned by `argus.lock`); Omega only carries the opt-in `RX_ARGUS` hooks (`src/runtime/rx_argus.c`) and receipts in `evidence/ARGUS/`. Physics Zero exists here as a host benchmark apparatus and learner (`src/physics0/`, `tests/physics0/`, `mk/physics0-learner.mk`, `docs/physics0/`, receipts in `evidence/physics0/`), with its specifications in the physics repository. DIRAC-0 is a specification in aien-architecture plus an oracle source in `research/dirac-oracle/` that has never been built or run. The Evolution Arena is a plan only. ## Standing rules @@ -35,7 +37,7 @@ Language rule: Rust is scaffolding, Omega is the destination, and C or assembly ## Build and verify -Needs gcc and make on an AArch64 Linux host: CI runs the host suites on `ubuntu-24.04-arm`, and `test-realize` compiles with `-march=armv8.6-a+dotprod+i8mm+sve`. Host suites need no GPU and no physics checkout: +Needs gcc and make on an AArch64 Linux host: CI runs the host suites on `ubuntu-24.04-arm`, and `test-realize` compiles with `-march=armv8.6-a+dotprod+i8mm+sve`. Host suites need no GPU and no physics checkout (several compile CUDA++ files, which `make` links in first; see above): ```bash make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-compiler-quick # compiler, quick suite diff --git a/cudapp.files b/cudapp.files new file mode 100644 index 000000000..ea4bc04bf --- /dev/null +++ b/cudapp.files @@ -0,0 +1,154 @@ +# Files that live in CUDA++ (aien-dev/CUDAplusplus, MIT) since 2026-10-21. tools/cudapp-link.sh links each +# one from the pinned CUDA++ checkout (CUDAPP_DIR at cudapp.lock) into this tree; .gitignore lists them. +src/omega_blackwell_codegen_attn.c +src/omega_blackwell_codegen_attn.h +src/omega_blackwell_codegen_bf16.c +src/omega_blackwell_codegen_bf16.h +src/omega_blackwell_codegen.c +src/omega_blackwell_codegen_dec.c +src/omega_blackwell_codegen_dec.h +src/omega_blackwell_codegen_gemm.c +src/omega_blackwell_codegen_gemm.h +src/omega_blackwell_codegen.h +src/omega_blackwell_codegen_moe2.c +src/omega_blackwell_codegen_moe2.h +src/omega_blackwell_codegen_moe.c +src/omega_blackwell_codegen_moe.h +src/omega_blackwell_codegen_pattn.c +src/omega_blackwell_codegen_pattn.h +src/omega_blackwell_codegen_pf.c +src/omega_blackwell_codegen_pf.h +src/omega_blackwell_codegen_pfhost.c +src/omega_blackwell_codegen_pfhost.h +src/omega_blackwell_codegen_qg.c +src/omega_blackwell_codegen_qg.h +src/omega_blackwell_codegen_qmma.c +src/omega_blackwell_codegen_qmma.h +src/omega_blackwell_codegen_router.c +src/omega_blackwell_codegen_router.h +src/omega_blackwell_codegen_tc2.c +src/omega_blackwell_codegen_tc2.h +src/omega_blackwell_codegen_tc.c +src/omega_blackwell_codegen_tc.h +src/omega_blackwell_codegen_tern.c +src/omega_blackwell_codegen_tern.h +src/omega_blackwell_encoder.c +src/omega_blackwell_encoder.h +src/omega_blackwell_engine.c +src/omega_blackwell_engine.h +src/omega_blackwell_matmul.c +src/omega_blackwell_matmul.h +src/omega_blackwell_qmd.c +src/omega_blackwell_qmd.h +src/omega_blackwell_realize.c +src/omega_blackwell_realize.h +src/omega_blackwell_submit.c +src/omega_blackwell_submit.h +src/omega_bw_em.h +src/omega_bw_em_q.h +src/omega_bw_reconv.h +src/omega_gpu_attention_api.c +src/omega_gpu_attention_api.h +src/omega_gpu_bf16_gemv_api.c +src/omega_gpu_bf16_gemv_api.h +src/omega_gpu_cmdlist.c +src/omega_gpu_cmdlist.h +src/omega_gpu_code_alloc.h +src/omega_gpu_decode_attn_api.c +src/omega_gpu_decode_attn_api.h +src/omega_gpu_decode_graph.c +src/omega_gpu_decode_graph.h +src/omega_gpu_elementwise_api.c +src/omega_gpu_elementwise_api.h +src/omega_gpu_engine.c +src/omega_gpu_engine.h +src/omega_gpu_fmt.c +src/omega_gpu_fmt.h +src/omega_gpu_fp8_api.c +src/omega_gpu_fp8_api.h +src/omega_gpu_fp8gemm_api.c +src/omega_gpu_fp8gemm_api.h +src/omega_gpu_fp8_pack.c +src/omega_gpu_hostmath.c +src/omega_gpu_hostmath.h +src/omega_gpu_matmul_api.c +src/omega_gpu_matmul_api.h +src/omega_gpu_mem_cached.c +src/omega_gpu_mem_cached.h +src/omega_gpu_moe_api.c +src/omega_gpu_moe_api.h +src/omega_gpu_pfgemm.c +src/omega_gpu_pfhost.c +src/omega_gpu_pfhost.h +src/omega_gpu_platform.c +src/omega_gpu_platform.h +src/omega_gpu_platform_linux.c +src/omega_gpu_platform_linux.h +src/omega_gpu_prefill_attn_api.c +src/omega_gpu_prefill_attn_api.h +src/omega_gpu_prefill.c +src/omega_gpu_prefill.h +src/omega_gpu_router_api.c +src/omega_gpu_router_api.h +src/omega_gpu_serving.c +src/omega_gpu_serving.h +src/omega_gpu_session.c +src/omega_gpu_session.h +src/omega_gpu_tcgemm_api.c +src/omega_gpu_tcgemm_api.h +src/omega_gpu_tern_api.c +src/omega_gpu_tern_api.h +src/omega_gpu_wait.c +src/omega_gpu_wait.h +tests/bw_hmma_model.h +tests/bw_qmma_model.h +tests/bw_warp_sim.h +tests/bw_warp_sim_k.h +tests/bw_warp_sim_pa.h +tests/bw_warp_sim_tc.h +tests/fake_m16_native.c +tests/fake_m16_native.h +tests/gpu_attention_test.c +tests/gpu_bf16_gemv_test.c +tests/gpu_cmdlist_test.c +tests/gpu_decode_attn_test.c +tests/gpu_decode_graph_test.c +tests/gpu_elementwise_test.c +tests/gpu_fp8_api_test.c +tests/gpu_fp8gemm_test.c +tests/gpu_gpr_boundary_test.c +tests/gpu_l2_reuse_test.c +tests/gpu_l2_stale_test.c +tests/gpu_launch_cost_test.c +tests/gpu_lmhead_fp8_study.c +tests/gpu_matmul_api_test.c +tests/gpu_matmul_r4_receipt.c +tests/gpu_moe_window_test.c +tests/gpu_pfgemm_test.c +tests/gpu_pfhost_test.c +tests/gpu_pf_mem_test.c +tests/gpu_prefill_attn_test.c +tests/gpu_qgemm_test.c +tests/gpu_qmma_probe_test.c +tests/gpu_reconv_test.c +tests/gpu_router_test.c +tests/gpu_serving_alloc_count_test.c +tests/gpu_session_probe.c +tests/gpu_tcgemm_test.c +tests/gpu_tc_peak_test.c +tests/gpu_tc_probe_test.c +tests/test_omega_blackwell_engine.c +tests/test_omega_codegen_freestanding.c +tests/test_omega_gpu_code_alloc.c +tests/test_omega_gpu_engine.c +tests/test_omega_gpu_engine_compile.c +tests/test_omega_gpu_engine_gb10.c +tests/test_omega_gpu_platform.c +tests/test_omega_gpu_platform_linux.c +tests/test_omega_gpu_session_platform.c +tests/test_omega_gpu_wait.c +mk/omega-gpu-engine.mk +mk/omega-gpu-code-alloc.mk +mk/omega-gpu-wait.mk +tools/gpu_engine_mutations.sh +tools/gpu_engine_backend_mutations.sh diff --git a/cudapp.lock b/cudapp.lock new file mode 100644 index 000000000..64641c86c --- /dev/null +++ b/cudapp.lock @@ -0,0 +1 @@ +8f0b645dbc859f1b63868cec77880621aa70b42d diff --git a/mk/omega-gpu-code-alloc.mk b/mk/omega-gpu-code-alloc.mk deleted file mode 100644 index 3b217c32d..000000000 --- a/mk/omega-gpu-code-alloc.mk +++ /dev/null @@ -1,18 +0,0 @@ -# GPU code buffer sizing (src/omega_gpu_code_alloc.h): the 2 KB instruction prefetch tail after every -# kernel (omega#323). Host only: no device, no physics headers. Three parts: the size rule, a NO_TAIL -# mutant that must fail it, and a source scan that refuses the page-only code sizing idioms the six -# variable-size upload sites and five fixed-size sites used before. -CODE_ALLOC_SCAN_SRC := src/*.c src/runtime/*.c -CODE_ALLOC_SCAN_RE := code_size \+ 0x[fF]{3}|session_alloc\([^,]*code_size|alloc[a-z_]*\([^,]*, *(0x[0-9a-fA-F]+|OMEGA_DS_MAX_CODE_BYTES), *&[a-z_>.-]*code_mem\) -.PHONY: test-gpu-code-alloc -build/test_omega_gpu_code_alloc: tests/test_omega_gpu_code_alloc.c src/omega_gpu_code_alloc.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -o $@ tests/test_omega_gpu_code_alloc.c -test-gpu-code-alloc: build/test_omega_gpu_code_alloc - ./build/test_omega_gpu_code_alloc - @gcc -std=gnu11 -O2 -Wall -Wextra -Werror -DOMEGA_GPU_CODE_ALLOC_MUTANT_NO_TAIL -Isrc -o build/test_omega_gpu_code_alloc_no_tail tests/test_omega_gpu_code_alloc.c - @if ./build/test_omega_gpu_code_alloc_no_tail >build/test_omega_gpu_code_alloc_no_tail.log 2>&1; then echo "MUTANT SURVIVED: NO_TAIL"; exit 1; fi - @echo "NO_TAIL mutant: killed ($$(grep -c '^FAIL:' build/test_omega_gpu_code_alloc_no_tail.log) failing checks)" - @if grep -nE '$(CODE_ALLOC_SCAN_RE)' $(CODE_ALLOC_SCAN_SRC); then echo "code buffer sized without the prefetch tail (use omega_gpu_code_alloc_bytes)"; exit 1; fi - @echo "source scan: no page-only code sizing" - @echo "OMEGA_GPU_CODE_ALLOC_GATE PASS" diff --git a/mk/omega-gpu-engine.mk b/mk/omega-gpu-engine.mk deleted file mode 100644 index db63683e4..000000000 --- a/mk/omega-gpu-engine.mk +++ /dev/null @@ -1,231 +0,0 @@ -# Omega GPU Engine (docs/numeric/OMEGA_GPU_ENGINE.md). Picked up by -# `-include mk/*.mk`. Host only: opens no device; needs no physics headers except the two A3b1 targets, not -# part of `all` or `test`. -# test-gpu-engine-compile header + core compile, enum names, refusals, no-op backend (A2/A3a) -# test-gpu-engine the engine core against a fake backend (every state and failure) -# test-gpu-engine-backend-compile syntax-checks src/omega_blackwell_engine.c (A3b1): -c only, no link, no device -# test-gpu-engine-prod-build production build of build/omegatool at the physics pin: links only, opens no device -# test-gpu-engine-mutants removes each protection from src/omega_gpu_engine.c in a scratch -# copy; the host test must fail each one (exit nonzero on a survivor) -# test-gpu-engine-sim (A3b2) the REAL engine core + Blackwell backend + vector wrapper against a simulated driver -# (tests/fake_m16_native.c); host only, no device, no physics C sources -# test-gpu-engine-backend-mutants (A3b2) one mutant per protection in the backend and the vector wrapper -# test-gpu-engine-gb10-compile (A3b2) compile-only check of tests/test_omega_gpu_engine_gb10.c (Phase B chip test, never run here) -# gpu-engine-freestanding (native v1 P07 cut A) the portable GPU files built -ffreestanding with -# OMEGA_GPU_NO_POSIX: no Linux header, no errno, no clock, no libc beyond mem*/str* -# test-codegen-freestanding (cut A.2) codegen hosted vs freestanding byte-identical, bounded code buffers -# test-gpu-engine-freestanding the engine contract test and the platform contract test linked against -# those freestanding objects (host runner, opens no device) -.PHONY: test-gpu-engine-compile test-gpu-engine test-gpu-engine-mutants test-gpu-engine-backend-compile test-gpu-engine-prod-build test-gpu-engine-sim test-gpu-engine-backend-mutants test-gpu-engine-gb10-compile gpu-engine-freestanding test-gpu-engine-freestanding -build/test_omega_gpu_engine_compile: tests/test_omega_gpu_engine_compile.c src/omega_gpu_engine.c src/omega_gpu_engine.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/test_omega_gpu_engine_compile.c src/omega_gpu_engine.c -test-gpu-engine-compile: build/test_omega_gpu_engine_compile - ./build/test_omega_gpu_engine_compile - -build/test_omega_gpu_engine: tests/test_omega_gpu_engine.c src/omega_gpu_engine.c src/omega_gpu_engine.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/test_omega_gpu_engine.c src/omega_gpu_engine.c -test-gpu-engine: build/test_omega_gpu_engine - ./build/test_omega_gpu_engine - -test-gpu-engine-mutants: - sh tools/gpu_engine_mutations.sh - -# A3b1: the Blackwell backend includes physics headers (m16_native.h, nvrm.h), so it -# uses the same physics -I paths as the top-level Makefile CFLAGS (Makefile lines 9-14). -GPU_ENGINE_PHYS_INC = -I$(PHYSICS_DIR)/m16 -I$(PHYSICS_DIR)/nvrm \ - -I$(PHYSICS_DIR)/third_party/nvidia-open-580.173.02/src/common/sdk/nvidia/inc \ - -I$(PHYSICS_DIR)/third_party/nvidia-open-580.173.02/kernel-open/common/inc \ - -I$(PHYSICS_DIR)/third_party/nvidia-open-580.173.02/kernel-open/nvidia-uvm \ - -I$(PHYSICS_DIR)/third_party/nvidia-open-580.173.02/src/nvidia/arch/nvalloc/unix/include - -build/omega_blackwell_engine_syntax.o: src/omega_blackwell_engine.c src/omega_blackwell_engine.h src/omega_gpu_engine.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc $(GPU_ENGINE_PHYS_INC) -c -o $@ src/omega_blackwell_engine.c -test-gpu-engine-backend-compile: build/omega_blackwell_engine_syntax.o - -# Links only, opens no device. Uses the real m16_native and nvrm sources at the physics pin. -test-gpu-engine-prod-build: - $(MAKE) build/omegatool - -# A3b2: simulated-driver host test. Links the sources of the Makefile RX_COMPOSE_GPU_SRCS list (plus the -# three core files the vector builder needs) with tests/fake_m16_native.c in place of the physics -# m16_native.c and nvrm.c. Opens no device. -GPU_ENGINE_SIM_SRCS = src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_qmd.c src/omega_blackwell_realize.c src/omega_vector.c src/omega_validate.c \ - src/omega_core.c src/omega_canonical.c src/sha256.c - -build/test_omega_blackwell_engine: tests/test_omega_blackwell_engine.c tests/fake_m16_native.c tests/fake_m16_native.h \ - $(GPU_ENGINE_SIM_SRCS) src/omega_gpu_engine.h src/omega_blackwell_engine.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -ffunction-sections -fdata-sections \ - -Isrc -Itests $(GPU_ENGINE_PHYS_INC) -o $@ tests/test_omega_blackwell_engine.c tests/fake_m16_native.c \ - $(GPU_ENGINE_SIM_SRCS) -Wl,--gc-sections -lm -test-gpu-engine-sim: build/test_omega_blackwell_engine - ./build/test_omega_blackwell_engine - -# One mutant per backend and vector-wrapper protection; the sim test must fail each one. -test-gpu-engine-backend-mutants: - PHYSICS_DIR="$(PHYSICS_DIR)" sh tools/gpu_engine_backend_mutations.sh - -# Phase B chip test, compile only here. Never run in Phase A. -build/test_omega_gpu_engine_gb10.o: tests/test_omega_gpu_engine_gb10.c src/omega_gpu_engine.h src/omega_blackwell_engine.h src/omega_blackwell_submit.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -pthread -Isrc $(GPU_ENGINE_PHYS_INC) -c -o $@ tests/test_omega_gpu_engine_gb10.c -test-gpu-engine-gb10-compile: build/test_omega_gpu_engine_gb10.o - -# Measurement (sc#277): driver allocations and frees made by the REAL session + matmul + attention -# APIs while serving a Qwen3-4B-shaped sequence, against the simulated driver. Host only, no device. -# Prints MEASURE lines; asserts only bookkeeping. Links no physics C sources, only its headers. -GPU_SERVE_ALLOC_SRCS = src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c \ - src/omega_gpu_wait.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c src/sha256.c -build/gpu_serving_alloc_count_test: tests/gpu_serving_alloc_count_test.c tests/fake_m16_native.c tests/fake_m16_native.h $(GPU_SERVE_ALLOC_SRCS) - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -ffp-contract=off -Isrc -Itests $(GPU_ENGINE_PHYS_INC) \ - -o $@ tests/gpu_serving_alloc_count_test.c tests/fake_m16_native.c $(GPU_SERVE_ALLOC_SRCS) -lm -.PHONY: test-gpu-serving-alloc -test-gpu-serving-alloc: build/gpu_serving_alloc_count_test - ./build/gpu_serving_alloc_count_test plain - ./build/gpu_serving_alloc_count_test reserve - ./build/gpu_serving_alloc_count_test bounds - ./build/gpu_serving_alloc_count_test bounds-block - ./build/gpu_serving_alloc_count_test rollback - ./build/gpu_serving_alloc_count_test sweep - ./build/gpu_serving_alloc_count_test pin - ./build/gpu_serving_alloc_count_test seal-bare - ./build/gpu_serving_alloc_count_test update - @if ./build/gpu_serving_alloc_count_test sweep-skip >build/gpu_serving_alloc_count_sweep_skip.log 2>&1; then echo "RED RUN PASSED: zero allocations over the row sweep do not need prepare + seal"; exit 1; fi - @if [ "$$(grep -c "^FAIL" build/gpu_serving_alloc_count_sweep_skip.log)" -lt 1 ]; then echo "sweep-skip exited nonzero without a FAIL check (crash, not the red assertion)"; exit 1; fi - @grep -E "^MEASURE sweep" build/gpu_serving_alloc_count_sweep_skip.log | sed "s/^/sweep-skip (control): /" - @if ./build/gpu_serving_alloc_count_test reserve-skip >build/gpu_serving_alloc_count_skip.log 2>&1; then echo "RED RUN PASSED: the zero-allocation assertion does not need the reservation call"; exit 1; fi - @if [ "$$(grep -c "^FAIL" build/gpu_serving_alloc_count_skip.log)" -lt 1 ]; then echo "reserve-skip exited nonzero without a FAIL check (crash, not the red assertion)"; exit 1; fi - @echo "reserve-skip (no reservation call): fails as required ($$(grep -c "^FAIL" build/gpu_serving_alloc_count_skip.log) failing checks)" - -# native v1 P07 cut A (aienos#286 cut A, aien-architecture#190): the freestanding link target. -# Each file below is compiled with no hosted headers available (-ffreestanding, -fno-builtin, -# OMEGA_GPU_NO_POSIX) and the partial link of all of them may leave only the mem*/str* symbols -# undefined. Any other undefined symbol (errno, clock_gettime, printf, malloc, pthread_*, nvrm_*, -# m16_*) fails the target. This proves the first-compute PATH links without Linux headers or -# runtime symbols; it proves nothing about device ownership (NOT_RUN until cut B runs on the Spark). -GPU_FS_DIR = build/gpu_fs -GPU_FS_CFLAGS = -std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -fno-builtin -fno-stack-protector \ - -U_FORTIFY_SOURCE -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY -Isrc -# P07 cut C (session part): the persistent session, the matmul and attention APIs, the serving reservation and the -# bounded wait join the link. Their machine comes from an installed OmegaGpuPlatform; the Linux reference -# (src/omega_gpu_platform_linux.c) is deliberately NOT in this list. Still outside it: the elementwise API, the -# numeric launchers, the vector executor, the resident runtime (docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md). -GPU_FS_SRCS = src/omega_gpu_engine.c src/omega_gpu_platform.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_blackwell_realize.c src/sha256.c \ - src/omega_gpu_session.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c \ - src/omega_gpu_serving.c src/omega_gpu_wait.c -GPU_FS_HDRS = src/omega_gpu_engine.h src/omega_gpu_platform.h src/omega_blackwell_codegen.h src/omega_blackwell_matmul.h \ - src/omega_gpu_session.h src/omega_gpu_fmt.h src/omega_gpu_matmul_api.h src/omega_gpu_attention_api.h \ - src/omega_gpu_serving.h src/omega_gpu_wait.h -GPU_FS_OBJS = $(patsubst src/%.c,$(GPU_FS_DIR)/%.o,$(GPU_FS_SRCS)) -GPU_FS_LINK = $(GPU_FS_DIR)/omega_gpu_freestanding.o -GPU_FS_ALLOWED = memcpy|memmove|memset|memcmp|strlen|strcmp - -$(GPU_FS_DIR)/%.o: src/%.c $(GPU_FS_HDRS) - @mkdir -p $(GPU_FS_DIR) - gcc $(GPU_FS_CFLAGS) -c -o $@ $< - -$(GPU_FS_LINK): $(GPU_FS_OBJS) - gcc -r -nostdlib -o $@ $(GPU_FS_OBJS) - @bad=$$(nm -u $@ | awk '{print $$NF}' | grep -Ev '^(_GLOBAL_OFFSET_TABLE_|($(GPU_FS_ALLOWED)))$$' || true); \ - if [ -n "$$bad" ]; then echo "freestanding GPU link still needs: $$bad"; rm -f $@; exit 1; fi - @echo "freestanding GPU link ($(words $(GPU_FS_SRCS)) files): only $$(nm -u $@ | awk '{print $$NF}' | grep -Ev '^_GLOBAL_OFFSET_TABLE_$$' | sort -u | tr '\n' ' ')undefined" -gpu-engine-freestanding: $(GPU_FS_LINK) - -build/test_omega_gpu_engine_freestanding: tests/test_omega_gpu_engine.c $(GPU_FS_DIR)/omega_gpu_engine.o src/omega_gpu_engine.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_NUMERIC_CPU_ONLY -DOMEGA_GPU_NO_POSIX \ - -o $@ tests/test_omega_gpu_engine.c $(GPU_FS_DIR)/omega_gpu_engine.o -build/test_omega_gpu_platform: tests/test_omega_gpu_platform.c $(GPU_FS_DIR)/omega_gpu_platform.o src/omega_gpu_platform.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -o $@ tests/test_omega_gpu_platform.c $(GPU_FS_DIR)/omega_gpu_platform.o -test-gpu-engine-freestanding: $(GPU_FS_LINK) build/test_omega_gpu_engine_freestanding build/test_omega_gpu_platform - ./build/test_omega_gpu_engine_freestanding - ./build/test_omega_gpu_platform - -# native v1 P07 cut A.2 (aienos#286): code generation joins the freestanding link above with a caller-owned -# code buffer (omega_blackwell_kernel_encode_into, no allocator). The same test source is built hosted (the -# allocating generators) and freestanding (the *_prog generators into a caller buffer); their instruction -# stream dumps of every fixture must be byte-identical (cmp). The freestanding run then checks the bounded -# buffer contract, the golden-word fixture verifiers on the freestanding object and the bf16 rounding path on -# all 2^32 inputs. The allowlist control links a malloc caller into the freestanding object and requires the -# nm -u check to refuse it (a check that can never fail proves nothing). -.PHONY: test-codegen-freestanding test-gpu-fs-allowlist-control -CODEGEN_FS_TEST_DEPS = tests/test_omega_codegen_freestanding.c src/omega_blackwell_codegen.h src/omega_blackwell_matmul.h -build/test_codegen_hosted: $(CODEGEN_FS_TEST_DEPS) src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/sha256.c - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -o $@ tests/test_omega_codegen_freestanding.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/sha256.c -build/test_codegen_freestanding: $(CODEGEN_FS_TEST_DEPS) $(GPU_FS_LINK) - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_GPU_NO_POSIX -o $@ tests/test_omega_codegen_freestanding.c \ - $(GPU_FS_DIR)/omega_blackwell_codegen.o $(GPU_FS_DIR)/omega_blackwell_matmul.o $(GPU_FS_DIR)/sha256.o -test-codegen-freestanding: build/test_codegen_hosted build/test_codegen_freestanding test-gpu-fs-allowlist-control - ./build/test_codegen_hosted --dump > build/codegen_dump_hosted.txt - ./build/test_codegen_freestanding --dump > build/codegen_dump_freestanding.txt - cmp build/codegen_dump_hosted.txt build/codegen_dump_freestanding.txt - @echo "codegen dumps byte-identical: $$(grep -c '^fixture ' build/codegen_dump_hosted.txt) fixtures, $$(grep -v -E '^(fixture|digest) ' build/codegen_dump_hosted.txt | tr -d '\n' | wc -c | awk '{print $$1/2}') code bytes" - ./build/test_codegen_freestanding - -test-gpu-fs-allowlist-control: $(GPU_FS_LINK) - @mkdir -p $(GPU_FS_DIR)/control - printf 'void *malloc(unsigned long);\nvoid *omega_gpu_fs_control(void) { return malloc(16); }\n' > $(GPU_FS_DIR)/control/canary.c - gcc $(GPU_FS_CFLAGS) -c -o $(GPU_FS_DIR)/control/canary.o $(GPU_FS_DIR)/control/canary.c - gcc -r -nostdlib -o $(GPU_FS_DIR)/control/with_canary.o $(GPU_FS_OBJS) $(GPU_FS_DIR)/control/canary.o - @bad=$$(nm -u $(GPU_FS_DIR)/control/with_canary.o | awk '{print $$NF}' | grep -Ev '^(_GLOBAL_OFFSET_TABLE_|($(GPU_FS_ALLOWED)))$$' || true); \ - if [ "$$bad" != "malloc" ]; then echo "allowlist control: expected exactly malloc refused, got '$$bad'"; exit 1; fi; \ - echo "allowlist control: a malloc caller is refused by the nm -u check (as required)" - -# native v1 P07 cut C, session part (aienos#286): the portable session over OmegaGpuPlatform. -# - test_omega_gpu_session_platform links the FREESTANDING partial-link object and drives it through a fake -# platform: install refusals, no default platform, typed GPU-uncached buffers, polling only, cancel before and -# after submit, timeout (latch + park, nothing released), stale handle after close/reopen, reservation refusal. -# - test_omega_gpu_platform_linux drives the Linux REFERENCE platform (reference only) on the simulated driver: -# same driver calls in the same order as before cut C, its refusals, and a marker that never lands. -# - the mutants prove the session test can fail: each one breaks one rule in a copy of the session and the test -# must report FAIL for it. -.PHONY: test-gpu-session-platform test-gpu-session-mutants -build/test_omega_gpu_session_platform: tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_GPU_NO_POSIX -o $@ tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) -GPU_LINUX_REF_SRCS = src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_blackwell_qmd.c -# omega #459: the command list over the reference (near-full ring with the #457 L2 invalidate prefix pending) needs the -# cached allocation, the command list and the codegen behind its nop kernel. -GPU_LINUX_REF_CMDLIST_SRCS = src/omega_gpu_mem_cached.c src/omega_gpu_cmdlist.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_realize.c src/sha256.c -build/test_omega_gpu_platform_linux: tests/test_omega_gpu_platform_linux.c tests/fake_m16_native.c tests/fake_m16_native.h $(GPU_LINUX_REF_SRCS) $(GPU_FS_HDRS) src/omega_gpu_platform_linux.h \ - src/omega_gpu_cmdlist.h src/omega_gpu_mem_cached.h $(GPU_LINUX_REF_CMDLIST_SRCS) - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -Isrc -Itests $(GPU_ENGINE_PHYS_INC) \ - -o $@ tests/test_omega_gpu_platform_linux.c tests/fake_m16_native.c $(GPU_LINUX_REF_SRCS) $(GPU_LINUX_REF_CMDLIST_SRCS) -lm -test-gpu-session-platform: build/test_omega_gpu_session_platform build/test_omega_gpu_platform_linux test-gpu-session-mutants - ./build/test_omega_gpu_session_platform - ./build/test_omega_gpu_platform_linux - -GPU_SESSION_MUT_DIR = build/gpu_session_mut -test-gpu-session-mutants: $(GPU_FS_LINK) - @mkdir -p $(GPU_SESSION_MUT_DIR) - @set -e; killed=0; \ - smut() { name=$$1; script=$$2; \ - sed -e "$$script" src/omega_gpu_session.c > $(GPU_SESSION_MUT_DIR)/$$name.c; \ - if cmp -s src/omega_gpu_session.c $(GPU_SESSION_MUT_DIR)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ - gcc $(GPU_FS_CFLAGS) -c -o $(GPU_SESSION_MUT_DIR)/$$name.o $(GPU_SESSION_MUT_DIR)/$$name.c; \ - objs=$$(echo $(GPU_FS_OBJS) | tr ' ' '\n' | grep -v '/omega_gpu_session.o$$' | tr '\n' ' '); \ - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_GPU_NO_POSIX -o $(GPU_SESSION_MUT_DIR)/$$name \ - tests/test_omega_gpu_session_platform.c $$objs $(GPU_SESSION_MUT_DIR)/$$name.o; \ - if ./$(GPU_SESSION_MUT_DIR)/$$name > $(GPU_SESSION_MUT_DIR)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ - echo "mutant $$name killed: $$(grep -c '^FAIL' $(GPU_SESSION_MUT_DIR)/$$name.log) case(s) failed"; killed=$$((killed+1)); }; \ - smut release-when-latched 's|if (LOAD(g_blocked)) {$$|if (0) {|'; \ - smut ignore-cancel 's|if (LOAD(g_cancel)) return WAIT_CANCELLED;|;|g'; \ - smut no-latch-on-timeout 's|latch(w == WAIT_TIMED_OUT|omega_gpu_session_set_error(w == WAIT_TIMED_OUT|'; \ - smut stale-not-counted 's|else { BUMP(g_stats.stale_refusals, 1u); fail_plat("dma_free", rc); }|else {}|'; \ - smut marker-not-polled 's|RIGHTS_MARKER, PAGE|RIGHTS_DATA, PAGE|'; \ - smut close-while-latched 's|if (g_open \&\& !LOAD(g_blocked) \&\& p) {|if (g_open \&\& p) {|; s|if (!LOAD(g_blocked)) { /\* a hook|if (1) { /* a hook|'; \ - echo "test-gpu-session-mutants: $$killed of 6 mutants killed" diff --git a/mk/omega-gpu-wait.mk b/mk/omega-gpu-wait.mk deleted file mode 100644 index 42e5ed25b..000000000 --- a/mk/omega-gpu-wait.mk +++ /dev/null @@ -1,25 +0,0 @@ -# Shared GPU completion wait primitive (src/omega_gpu_wait.c): host unit test with -# fake memory and a fake clock, plus a naive wall-clock mutant that must be -# caught. Picked up by `-include mk/*.mk`. Host only: opens no device, needs no -# physics headers, takes no chip lock. -.PHONY: test-gpu-wait -build/test_omega_gpu_wait: tests/test_omega_gpu_wait.c src/omega_gpu_wait.c src/omega_gpu_wait.h - @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc -o $@ tests/test_omega_gpu_wait.c src/omega_gpu_wait.c -test-gpu-wait: build/test_omega_gpu_wait - ./build/test_omega_gpu_wait - -# Real-code mutants: src/omega_gpu_wait.c carries one-line compile-flag mutants. -# Each flagged build of the real primitive must FAIL the suite; the unflagged -# build must PASS. A mutant that does not compile is an error, not a kill. -GPU_WAIT_MUTANTS := OMEGA_GPU_WAIT_MUTANT_STALL_NO_RESET OMEGA_GPU_WAIT_MUTANT_PROGRESS_EXTENDS_HARD OMEGA_GPU_WAIT_MUTANT_NO_READ_BARRIER -.PHONY: test-gpu-wait-mutants -test-gpu-wait-mutants: build/test_omega_gpu_wait - @./build/test_omega_gpu_wait >/dev/null || { echo "unflagged build FAILED"; exit 1; } - @echo "unflagged: PASS" - @set -e; for m in $(GPU_WAIT_MUTANTS); do \ - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -D$$m -Isrc -o build/test_omega_gpu_wait_$$m tests/test_omega_gpu_wait.c src/omega_gpu_wait.c; \ - if ./build/test_omega_gpu_wait_$$m >build/test_omega_gpu_wait_$$m.log 2>&1; then echo "MUTANT SURVIVED: $$m"; exit 1; fi; \ - echo "$$m: killed ($$(grep -c 'FAIL' build/test_omega_gpu_wait_$$m.log) failing checks)"; \ - done - @echo "OMEGA_GPU_WAIT_MUTANTS PASS" diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c deleted file mode 100644 index b09fa1e54..000000000 --- a/src/omega_blackwell_codegen.c +++ /dev/null @@ -1,2539 +0,0 @@ -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_submit.h" -#include "sha256.h" -#include -/* native v1 P07 cut A.2 (aienos#286, docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md): with OMEGA_GPU_NO_POSIX this file - * builds -ffreestanding. Code generation then runs only through the allocation-free entry points - * (omega_blackwell_kernel_encode_into: the caller supplies the code buffer and its capacity); the allocating - * generators, their diagnostics and the printing variation self-test exist only in the hosted build. */ -#ifndef OMEGA_GPU_NO_POSIX -#include -#include -#define BW_DIAG(...) fprintf(stderr, __VA_ARGS__) -#else -#define BW_DIAG(...) ((void)0) -#endif - -void omega_bw_ir_init(BlackwellIRProgram *prog) { - if (!prog) return; - memset(prog, 0, sizeof(*prog)); -} - -int omega_bw_ir_alloc_vreg(BlackwellIRProgram *prog) { - if (!prog || prog->regalloc.num_vregs >= BW_MAX_VREGS) return -1; - int v = prog->regalloc.num_vregs++; - prog->regalloc.intervals[v].vreg = v; - prog->regalloc.intervals[v].first_def = -1; - prog->regalloc.intervals[v].last_use = -1; - prog->regalloc.intervals[v].phys_reg = -1; - prog->regalloc.intervals[v].bundle_size = 1; - prog->regalloc.intervals[v].is_pair = false; - prog->regalloc.intervals[v].is_quad = false; - prog->regalloc.intervals[v].active = false; - prog->regalloc.vreg_to_phys[v] = -1; - return v; -} - -int omega_bw_ir_alloc_vreg64(BlackwellIRProgram *prog) { - if (!prog || prog->regalloc.num_vregs >= BW_MAX_VREGS) return -1; - int v = prog->regalloc.num_vregs++; - prog->regalloc.intervals[v].vreg = v; - prog->regalloc.intervals[v].first_def = -1; - prog->regalloc.intervals[v].last_use = -1; - prog->regalloc.intervals[v].phys_reg = -1; - prog->regalloc.intervals[v].bundle_size = 2; - prog->regalloc.intervals[v].is_pair = true; - prog->regalloc.intervals[v].is_quad = false; - prog->regalloc.intervals[v].active = false; - prog->regalloc.vreg_to_phys[v] = -1; - return v; -} - -int omega_bw_ir_alloc_vreg128(BlackwellIRProgram *prog) { - if (!prog || prog->regalloc.num_vregs >= BW_MAX_VREGS) return -1; - int v = prog->regalloc.num_vregs++; - prog->regalloc.intervals[v].vreg = v; - prog->regalloc.intervals[v].first_def = -1; - prog->regalloc.intervals[v].last_use = -1; - prog->regalloc.intervals[v].phys_reg = -1; - prog->regalloc.intervals[v].bundle_size = 4; - prog->regalloc.intervals[v].is_pair = false; - prog->regalloc.intervals[v].is_quad = true; - prog->regalloc.intervals[v].active = false; - prog->regalloc.vreg_to_phys[v] = -1; - return v; -} - -int omega_bw_ir_alloc_uvreg(BlackwellIRProgram *prog) { - if (!prog || prog->regalloc.num_uvregs >= BW_MAX_UVREGS) return -1; - int uv = prog->regalloc.num_uvregs++; - prog->regalloc.uintervals[uv].vreg = uv; - prog->regalloc.uintervals[uv].first_def = -1; - prog->regalloc.uintervals[uv].last_use = -1; - prog->regalloc.uintervals[uv].phys_reg = -1; - prog->regalloc.uintervals[uv].is_pair = false; - prog->regalloc.uintervals[uv].active = false; - prog->regalloc.uvreg_to_phys[uv] = -1; - return uv; -} - -int omega_bw_ir_alloc_uvreg64(BlackwellIRProgram *prog) { - if (!prog || prog->regalloc.num_uvregs >= BW_MAX_UVREGS) return -1; - int uv = prog->regalloc.num_uvregs++; - prog->regalloc.uintervals[uv].vreg = uv; - prog->regalloc.uintervals[uv].first_def = -1; - prog->regalloc.uintervals[uv].last_use = -1; - prog->regalloc.uintervals[uv].phys_reg = -1; - prog->regalloc.uintervals[uv].is_pair = true; - prog->regalloc.uintervals[uv].active = false; - prog->regalloc.uvreg_to_phys[uv] = -1; - return uv; -} - -int omega_bw_ir_append(BlackwellIRProgram *prog, const BlackwellIRInsn *insn) { - if (!prog || !insn || prog->count >= BW_MAX_IR_INSNS) return -1; - int idx = (int)prog->count++; - prog->insns[idx] = *insn; - - /* Update live-interval def/use tracking */ - if (insn->dst_vreg >= 0 && insn->dst_vreg < prog->regalloc.num_vregs) { - if (!insn->is_uniform) { - OmegaLiveInterval *iv = &prog->regalloc.intervals[insn->dst_vreg]; - if (iv->first_def < 0) iv->first_def = idx; - if (idx > iv->last_use) iv->last_use = idx; - } - } - if (insn->src1_vreg >= 0 && insn->src1_vreg < prog->regalloc.num_vregs) { - OmegaLiveInterval *iv = &prog->regalloc.intervals[insn->src1_vreg]; - if (iv->first_def < 0) iv->first_def = idx; - if (idx > iv->last_use) iv->last_use = idx; - } - if (insn->src2_vreg >= 0 && insn->src2_vreg < prog->regalloc.num_vregs) { - OmegaLiveInterval *iv = &prog->regalloc.intervals[insn->src2_vreg]; - if (iv->first_def < 0) iv->first_def = idx; - if (idx > iv->last_use) iv->last_use = idx; - } - if (insn->src3_vreg >= 0 && insn->src3_vreg < prog->regalloc.num_vregs) { - OmegaLiveInterval *iv = &prog->regalloc.intervals[insn->src3_vreg]; - if (iv->first_def < 0) iv->first_def = idx; - if (idx > iv->last_use) iv->last_use = idx; - } - - /* Uniform register def/use tracking */ - if (insn->is_uniform && insn->dst_vreg >= 0 && insn->dst_vreg < prog->regalloc.num_uvregs) { - OmegaLiveInterval *uiv = &prog->regalloc.uintervals[insn->dst_vreg]; - if (uiv->first_def < 0) uiv->first_def = idx; - if (idx > uiv->last_use) uiv->last_use = idx; - } - if (insn->ureg >= 0 && insn->ureg < prog->regalloc.num_uvregs) { - OmegaLiveInterval *uiv = &prog->regalloc.uintervals[insn->ureg]; - if (uiv->first_def < 0) uiv->first_def = idx; - if (idx > uiv->last_use) uiv->last_use = idx; - } - - return idx; -} - -int omega_bw_regalloc_solve(BlackwellIRProgram *prog) { - if (!prog) return -1; - OmegaRegAlloc *ra = &prog->regalloc; - - /* - * Bounded deterministic linear-scan register allocator. - * Computes genuine live intervals across virtual registers and assigns - * available physical GPRs (R2..R127) and UGPRs (UR4..UR31). - * Enforces even-alignment and dual-register reservation for 64-bit pairs. - */ - bool gpr_busy[BW_PHYS_GPR_MAX]; - memset(gpr_busy, 0, sizeof(gpr_busy)); - - int max_phys_used = BW_PHYS_GPR_START; - - /* Sort virtual register indices chronologically by first_def (Poletto & Sarkar Linear Scan) */ - int order[BW_MAX_VREGS]; - int count = 0; - for (int v = 0; v < ra->num_vregs; v++) { - if (ra->intervals[v].first_def >= 0) { - order[count++] = v; - } else { - ra->intervals[v].phys_reg = BW_PHYS_GPR_START; - ra->vreg_to_phys[v] = ra->intervals[v].phys_reg; - } - } - for (int i = 0; i < count - 1; i++) { - for (int j = i + 1; j < count; j++) { - if (ra->intervals[order[i]].first_def > ra->intervals[order[j]].first_def) { - int tmp = order[i]; - order[i] = order[j]; - order[j] = tmp; - } - } - } - - for (int idx = 0; idx < count; idx++) { - int v = order[idx]; - OmegaLiveInterval *iv = &ra->intervals[v]; - - /* Free physical registers whose virtual live intervals have ended */ - for (int p = 0; p < ra->num_vregs; p++) { - if (ra->intervals[p].active && ra->intervals[p].last_use < iv->first_def) { - int freed = ra->intervals[p].phys_reg; - if (freed >= 0 && freed < BW_PHYS_GPR_MAX) { - uint32_t bsize = ra->intervals[p].bundle_size ? ra->intervals[p].bundle_size : (ra->intervals[p].is_pair ? 2 : (ra->intervals[p].is_quad ? 4 : 1)); - for (uint32_t k = 0; k < bsize && (freed + (int)k) < BW_PHYS_GPR_MAX; k++) { - gpr_busy[freed + k] = false; - } - } - ra->intervals[p].active = false; - } - } - - /* Find lowest available physical register */ - int assigned = -1; - uint32_t bsize = iv->bundle_size ? iv->bundle_size : (iv->is_pair ? 2 : (iv->is_quad ? 4 : 1)); - if (bsize == 4) { - /* 128-bit quad requires 4-alignment and 4 contiguous free registers */ - int start = (BW_PHYS_GPR_START + 3) & ~3; - for (int p = start; p <= BW_PHYS_GPR_MAX - 4; p += 4) { - if (!gpr_busy[p] && !gpr_busy[p + 1] && !gpr_busy[p + 2] && !gpr_busy[p + 3]) { - assigned = p; - for (int k = 0; k < 4; k++) gpr_busy[p + k] = true; - break; - } - } - } else if (bsize == 2) { - /* 64-bit pair requires even alignment and contiguous free registers */ - int start = (BW_PHYS_GPR_START + 1) & ~1; - for (int p = start; p <= BW_PHYS_GPR_MAX - 2; p += 2) { - if (!gpr_busy[p] && !gpr_busy[p + 1]) { - assigned = p; - gpr_busy[p] = true; - gpr_busy[p + 1] = true; - break; - } - } - } else { - for (int p = BW_PHYS_GPR_START; p < BW_PHYS_GPR_MAX; p++) { - if (!gpr_busy[p]) { - assigned = p; - gpr_busy[p] = true; - break; - } - } - } - - if (assigned < 0) { - /* Hardware register capacity exceeded: fail closed loudly */ - return -1; - } - - iv->phys_reg = assigned; - iv->active = true; - ra->vreg_to_phys[v] = assigned; - - int top = assigned + (int)bsize - 1; - if (top > max_phys_used) { - max_phys_used = top; - } - } - ra->peak_gpr_usage = (uint32_t)(max_phys_used + 1); - - /* Allocate uniform registers */ - int cur_u = BW_PHYS_UGPR_START; - for (int uv = 0; uv < ra->num_uvregs; uv++) { - OmegaLiveInterval *uiv = &ra->uintervals[uv]; - if (uiv->is_pair) { - if (cur_u % 2 != 0) cur_u++; - if (cur_u + 1 >= BW_PHYS_UGPR_MAX) return -1; - uiv->phys_reg = cur_u; - ra->uvreg_to_phys[uv] = cur_u; - cur_u += 2; - } else { - if (cur_u >= BW_PHYS_UGPR_MAX) return -1; - uiv->phys_reg = cur_u; - ra->uvreg_to_phys[uv] = cur_u++; - } - } - ra->peak_ugpr_usage = (uint32_t)cur_u; - - return 0; -} - -static int encode_single_insn(const BlackwellIRInsn *insn, const OmegaRegAlloc *ra, uint32_t w[4]) { - memset(w, 0, 16); - - int dst = (insn->dst_vreg >= 0) ? (ra->vreg_to_phys[insn->dst_vreg] + insn->dst_subreg) : 0; - int src1 = (insn->src1_vreg >= 0) ? (ra->vreg_to_phys[insn->src1_vreg] + insn->src1_subreg) : 0; - int src2 = (insn->src2_vreg >= 0) ? (ra->vreg_to_phys[insn->src2_vreg] + insn->src2_subreg) : 0; - int src3 = (insn->src3_vreg >= 0) ? (ra->vreg_to_phys[insn->src3_vreg] + insn->src3_subreg) : 0xff; /* Default to RZ (0xff) */ - int ureg = (insn->ureg >= 0) ? ra->uvreg_to_phys[insn->ureg] : 0; - - if (insn->is_uniform && insn->dst_vreg >= 0) { - dst = ra->uvreg_to_phys[insn->dst_vreg]; - } - - switch (insn->op) { - case BW_IR_NOP: - w[0] = 0x00007918; - w[1] = 0x00000000; - w[2] = 0x00000000; - w[3] = insn->control ? insn->control : 0x000fc000; /* control: a timed pause (fragment matmul) */ - break; - - case BW_IR_MOV_RZ: - /* MOV Rd, RZ */ - w[0] = 0x7202 | ((uint32_t)(dst & 0xff) << 16); - w[1] = 0x000000ff; - w[2] = 0x00000f00; - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_MOV_IMM: - /* MOV Rd, imm32 */ - w[0] = 0x7802 | ((uint32_t)(dst & 0xff) << 16); - w[1] = insn->imm; - w[2] = 0x00000f00; - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_S2R: - /* S2R Rd, SR */ - w[0] = 0x7919 | ((uint32_t)(dst & 0xff) << 16); - w[1] = 0x0; - w[2] = (insn->imm & 0xff) << 8; - w[3] = insn->control ? insn->control : 0x000e2200; - break; - - case BW_IR_LDC: - /* LDC Rd, c[0x0][imm] */ - w[0] = 0xff007b82 | ((uint32_t)(dst & 0xff) << 16); - w[1] = (insn->imm << 6) & 0x00ffff00; - w[2] = 0x00000800; - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_LDC64: - /* LDC.64 Rd:Rd+1, c[0x0][imm] */ - w[0] = 0xff007b82 | ((uint32_t)(dst & 0xff) << 16); - w[1] = (insn->imm << 6) & 0x00ffff00; - w[2] = 0x00000a00; - w[3] = insn->control ? insn->control : 0x000e2200; - break; - - case BW_IR_LDCU: - /* LDCU URd, c[0x0][imm] */ - w[0] = 0xff0077ac | ((uint32_t)(dst & 0xff) << 16); - w[1] = (insn->imm << 5) & 0x00ffff00; - w[2] = 0x08000800; - w[3] = insn->control ? insn->control : 0x000e2200; - break; - - case BW_IR_LDCU64: - /* LDCU.64 URd:URd+1, c[0x0][imm] */ - w[0] = 0xff0077ac | ((uint32_t)(dst & 0xff) << 16); - w[1] = (insn->imm << 5) & 0x00ffff00; - w[2] = 0x08000a00; - w[3] = insn->control ? insn->control : 0x000e6e00; - break; - - case BW_IR_IMAD: - if (insn->src2_vreg >= 0) { - /* Register-register: IMAD Rd, Ra, Rb, Rc (0x7224) */ - w[0] = 0x7224 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x078e0200 | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - } else if (insn->is_uniform && insn->ureg >= 0) { - /* Uniform register multiplier: IMAD Rd, Ra, URb, Rc (0x7c24) */ - w[0] = 0x7c24 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0f8e0200 | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - } else { - /* Immediate multiplier: IMAD Rd, Ra, imm, Rc (0x7824) */ - w[0] = 0x7824 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = insn->imm; - w[2] = 0x078e0200 | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - } - break; - - case BW_IR_IMAD_WIDE: - /* IMAD.WIDE.U32 Rd:Rd+1, Ra, imm, Rc:Rc+1 */ - w[0] = 0x7825 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = insn->imm; - w[2] = 0x078e0000 | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fcc00; - break; - - case BW_IR_ISETP_GE: - if (insn->is_uniform && insn->ureg >= 0) { - w[0] = 0x7c0c | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0bf06070; - w[3] = 0x002fda00; - } else { - w[0] = 0x780c | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = insn->imm; - w[2] = 0x03f06270; - w[3] = 0x001fda00; - } - break; - - case BW_IR_LDG_E: - /* LDG.E Rd, desc[URd][Ra.64] */ - w[0] = 0x7981 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0c1e1900; - w[3] = insn->control ? insn->control : 0x000f2200; - break; - - case BW_IR_STG_E: { - /* STG.E desc[URd][Ra.64+imm], Rb. imm = signed 24-bit byte offset at bits 40..63 (w[1] bits - * 8..31), as for LDG; words from nvcc 13.0.88 -arch=sm_121 (omega_blackwell_verify_codegen_fixtures_fragmm, - * 2026-10-12: STG.E desc[UR4][R4.64+0x4], R9 = 0x0000040904007986 0x000fe8000c101904). */ - int32_t off = (int32_t)insn->imm; - if (off < -(1 << 23) || off >= (1 << 23)) return -1; - w[0] = 0x7986 | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff) | (((uint32_t)off & 0xffffffU) << 8); - w[2] = 0x0c101900 | (uint32_t)(ureg & 0xff); - w[3] = insn->control ? insn->control : 0x000fe200; - break; - } - - case BW_IR_STG_EF: - /* STG.E.MMIO.GPU. Uncached store, meant to be visible without a fence. */ - w[0] = 0x7986 | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x0c111900 | (uint32_t)(ureg & 0xff); - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_IADD3: - /* IADD3 Rd, PT, PT, Ra, Rb, Rc */ - w[0] = 0x7210 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x07ffe0ff; - w[3] = 0x010fca00; - break; - - case BW_IR_HMMA_F16: - case BW_IR_HMMA_BF16: { - /* HMMA.16816.F32[.BF16] Rd, Ra, Rb, Rc */ - w[0] = 0x723c | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - uint32_t prec_bit = (insn->op == BW_IR_HMMA_BF16) ? 0x00040000 : 0x00000000; - w[2] = (uint32_t)(src3 & 0xff) | (0x18 << 8) | prec_bit; - w[3] = insn->control ? insn->control : 0x000fe200; - break; - } - - case BW_IR_SHF_R: - /* SHF.R.U32.HI Rd, RZ, imm, Ra */ - w[0] = 0x7819U | ((uint32_t)(dst & 0xff) << 16) | (0xffU << 24); - w[1] = (uint32_t)insn->imm; - w[2] = 0x00011600 | (uint32_t)(src1 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - break; - - case BW_IR_LOP3_AND: - /* LOP3.LUT Rd, Ra, imm, RZ, 0xc0, !PT */ - w[0] = 0x7812U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)insn->imm; - w[2] = 0x078ec0ff; - w[3] = insn->control ? insn->control : 0x001fca00; - break; - - case BW_IR_LDG_E_64: - case BW_IR_LDG_E_128: { - /* LDG.E.64 / LDG.E.128 Rd, desc[URd][Ra.64+imm]. imm = signed 24-bit byte offset at - * bits 40..63 (w[1] bits 8..31); size field in w[2] bits 9..11 (32 = 4, 64 = 5, 128 = 6). - * Words from nvcc 13.0.88 -arch=sm_121 (omega_blackwell_verify_codegen_fixtures_fragmm). */ - int32_t off = (int32_t)insn->imm; - if (off < -(1 << 23) || off >= (1 << 23)) return -1; - w[0] = 0x7981U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff) | (((uint32_t)off & 0xffffffU) << 8); - w[2] = insn->op == BW_IR_LDG_E_64 ? 0x0c1e1b00U : 0x0c1e1d00U; - w[3] = insn->control ? insn->control : 0x000f2200; - break; - } - - case BW_IR_LDG_E_U16: - /* LDG.E.U16 Rd, desc[URd][Ra.64] */ - w[0] = 0x7981U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0c1e1500; - w[3] = insn->control ? insn->control : 0x000f2200; - break; - - case BW_IR_LDG_STRONG_SYS: - /* LDG.E.STRONG.SYS. Same shape as LDG.E; w[2] carries the - * system-scope bits (0x0c1e1900 -> 0x0c1f5900). */ - w[0] = 0x7981 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0c1f5900; - w[3] = insn->control ? insn->control : 0x000f2200; - break; - - case BW_IR_LDG_MMIO: - /* LDG.E.EF. Drop the cached line, then load. */ - w[0] = 0x7981 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(ureg & 0xff); - w[2] = 0x0c0e1900; - w[3] = insn->control ? insn->control : 0x000f2200; - break; - - case BW_IR_STG_STRONG_SYS: - w[0] = 0x7986 | ((uint32_t)(src1 & 0xff) << 24); - if (insn->predicate_p0) { - uint32_t pred = insn->predicate_not ? 0x8u : 0x0u; - w[0] = (w[0] & ~0xF000u) | (pred << 12); - } - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x0c115900 | (uint32_t)(ureg & 0xff); - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_MEMBAR_ALL_SYS: - w[0] = 0x00007992; - w[1] = 0x00000000; - w[2] = 0x0000b000; - w[3] = insn->control ? insn->control : 0x000fec00; - break; - - case BW_IR_MEMBAR_SC_SYS: - w[0] = 0x00007992; - w[1] = 0x00000000; - w[2] = 0x00003000; - w[3] = insn->control ? insn->control : 0x000fec00; - break; - - case BW_IR_CCTL_IVALL: - w[0] = 0xff00798f; - w[1] = 0x00000000; - w[2] = 0x02000000; - w[3] = insn->control ? insn->control : 0x000fe800; - break; - - case BW_IR_ATOMG_ADD_STRONG_SYS: - w[0] = 0x79a8 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff) | 0x80000000u; - w[2] = 0x081f5100 | (uint32_t)(ureg & 0xff); - w[3] = insn->control ? insn->control : 0x00321e00; - break; - - case BW_IR_ATOMG_EXCH_STRONG_SYS: - w[0] = 0x79a8 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff) | 0x80000000u; - w[2] = 0x0c1f5100 | (uint32_t)(ureg & 0xff); - w[3] = insn->control ? insn->control : 0x00321e00; - break; - - case BW_IR_ISETP_GE_U32: - /* ISETP.GE.U32.AND P0, PT, Ra, Rb, PT. Checked with nvdisasm -b SM121. */ - w[0] = 0x720c | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x03f06070; - w[3] = insn->control ? insn->control : 0x001fda00; - break; - - case BW_IR_LOP3_XOR: - /* LOP3.LUT Rd, Ra, Rb, RZ, 0x3c, !PT. Checked with nvdisasm -b SM121. */ - w[0] = 0x7212 | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x078e3cff; - w[3] = insn->control ? insn->control : 0x001fca00; - break; - - case BW_IR_FADD: - /* FADD Rd, Ra, Rb */ - w[0] = 0x7221U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x00000000; - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FSUB: - /* FSUB Rd, Ra, Rb (FADD Rd, Ra, -Rb) */ - w[0] = 0x7221U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff) | 0x80000000U; - w[2] = 0x00000000; - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FMUL: - /* FMUL Rd, Ra, Rb */ - w[0] = 0x7220U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x00400000; - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FFMA: - /* FFMA Rd, Ra, Rb, Rc */ - w[0] = 0x7223U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FSETP: - /* FSETP.cond.AND P0, PT, Ra, Rb, PT */ - w[0] = 0x720bU | ((uint32_t)(dst & 0x7) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = insn->imm ? insn->imm : 0x03f06000; /* Default GE condition */ - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FSEL: - /* FSEL Rd, Ra, Rb, P0 */ - w[0] = 0x7208U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = (uint32_t)(src3 & 0x7); - w[3] = insn->control ? insn->control : 0x000fca00; - break; - - case BW_IR_FMNMX_MIN: - /* FMNMX Rd, Ra, Rb, PT (minimum) */ - w[0] = 0x7209U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x03800000; - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_FMNMX_MAX: - /* FMNMX Rd, Ra, Rb, !PT (maximum) */ - w[0] = 0x7209U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x07800000; - w[3] = insn->control ? insn->control : 0x004fc400; - break; - - case BW_IR_I2FP: - /* I2FP.F32.S32 Rd, Ra */ - w[0] = 0x7245U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x00201400; - w[3] = insn->control ? insn->control : 0x004fe200; - break; - - case BW_IR_F2I: - /* F2I.TRUNC.NTZ Rd, Ra */ - w[0] = 0x7305U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x0020f100; - w[3] = insn->control ? insn->control : 0x004e2200; - break; - - case BW_IR_MUFU_RCP: - /* MUFU.RCP Rd, Ra */ - w[0] = 0x7308U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x00001000; - w[3] = insn->control ? insn->control : 0x000e2400; - break; - - case BW_IR_MUFU_RSQ: - /* MUFU.RSQ Rd, Ra */ - w[0] = 0x7308U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x00001400; - w[3] = insn->control ? insn->control : 0x000e2400; - break; - - case BW_IR_SHFL_DOWN: - /* SHFL.DOWN PT, Rd, Ra, offset, 0x1f */ - w[0] = 0x7f89U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = 0x08001f00U | (((uint32_t)insn->imm & 0x1f) << 21); - w[2] = 0x000e0000; - w[3] = insn->control ? insn->control : 0x000e2400; - break; - - case BW_IR_LDS: - /* LDS Rd, [Ra] */ - w[0] = 0x7984U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = 0x00000000; - w[2] = (uint32_t)(insn->imm & 0xffff); - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_STS: - /* STS [Ra], Rb */ - w[0] = 0x7388U | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = (uint32_t)(insn->imm & 0xffff); - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - case BW_IR_EXIT: - w[0] = insn->predicate_p0 ? 0x0000094d : 0x0000794d; - w[1] = 0x00000000; - w[2] = 0x03800000; - w[3] = 0x000fea00; - break; - - case BW_IR_BRA: { - /* sm_121 BRA. Distance is (target - this) - 1, split across the - * low six bits at instruction bits 18..23 and the rest at bit 34. - * Predicate bits 12..15: 7 = always, 0 = @P0, 8 = @!P0. - * A zero delta with no predicate keeps the self-branch word the - * existing kernels already emit after EXIT. */ - int32_t delta = (int32_t)insn->imm; - int32_t rel = delta - 1; - uint32_t pred_field = 0x7u; - if (insn->predicate_p0) - pred_field = insn->predicate_not ? 0x8u : 0x0u; - w[0] = 0x947u | (pred_field << 12) | (((uint32_t)rel & 0x3fu) << 18); - w[1] = (uint32_t)(rel >> 6) << 2; - w[2] = (rel < 0) ? 0x0383ffffu : 0x03800000u; - if (insn->control) - w[3] = insn->control; - else if (delta == 0 && !insn->predicate_p0) - w[3] = 0x000fc000u; - else - w[3] = 0x000fea00u; - break; - } - - case BW_IR_BSSY: { - /* BSSY.RECONVERGENT Bn, target (omega #308). nvcc 13.0.88 -arch=sm_121: - * [0070] BSSY.RECONVERGENT B0, 0x140 ; 0x000000c000007945 0x000fe20003800200 - * opcode 0x945 (NAK sm70_encode.rs:4165), barrier id at bits 16..19 (set_bar_dst - * 16..20), guard predicate at bits 12..15 like BRA, relative byte offset - * target - (this + 16) at bit 32 (NAK: field 34.. in 4-byte units), the cond - * predicate PT at bits 87..89 (0x0380 << 16 in w[2]) and bit 73 (0x200 in w[2]), - * which the disassembler prints as .RECONVERGENT; nvcc sets it on every BSSY/BSYNC - * for sm_121 and Mesa NAK does not. We follow nvcc. The target is the instruction - * after the matching BSYNC, so the delta is at least 2; smaller is refused. */ - int32_t delta = (int32_t)insn->imm; - if (delta < 2 || insn->bar_reg >= BW_RECONV_MAX_BAR) return -1; - uint32_t pred_field = 0x7u; - if (insn->predicate_p0) - pred_field = insn->predicate_not ? 0x8u : 0x0u; - w[0] = 0x945u | (pred_field << 12) | ((uint32_t)insn->bar_reg << 16); - w[1] = (uint32_t)(delta - 1) * 16u; - w[2] = 0x03800200u; - w[3] = insn->control ? insn->control : 0x000fe200u; - break; - } - - case BW_IR_BSYNC: { - /* BSYNC.RECONVERGENT Bn: [0130] BSYNC.RECONVERGENT B0 ; 0x0000000000007941 0x000fea0003800200 - * opcode 0x941 (NAK sm70_encode.rs:4179), barrier id bits 16..19, cond PT, bit 73. */ - if (insn->bar_reg >= BW_RECONV_MAX_BAR) return -1; - uint32_t pred_field = 0x7u; - if (insn->predicate_p0) - pred_field = insn->predicate_not ? 0x8u : 0x0u; - w[0] = 0x941u | (pred_field << 12) | ((uint32_t)insn->bar_reg << 16); - w[1] = 0; - w[2] = 0x03800200u; - w[3] = insn->control ? insn->control : 0x000fea00u; - break; - } - - case BW_IR_MUFU_EX2: - /* MUFU.EX2 Rd, Ra. nvdisasm 13.0 -b SM121: 0x7308 with sub-op 0x0800 decodes - * "MUFU.EX2 R2, R4" (RCP is 0x1000, RSQ 0x1400 above). */ - w[0] = 0x7308U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x00000800; - w[3] = insn->control ? insn->control : 0x000e2400; - break; - - case BW_IR_BAR_SYNC: - /* BAR.SYNC.DEFER_BLOCKING 0x0: the exact words src/omega_numeric.c:885 runs on - * the chip (nvdisasm: "BAR.SYNC.DEFER_BLOCKING 0x0"). No registers. */ - w[0] = 0x00007b1dU; - w[1] = 0x00000000; - w[2] = 0x00010000; - w[3] = insn->control ? insn->control : 0x000fec00; - break; - - case BW_IR_LDS128: { - /* LDS.128 Rd..Rd+3, [Ra+imm]. nvcc 13.0.88 -arch=sm_121 words (fixtures below): - * LDS.128 R4, [R20] ; 0x0000000014047984 0x000fe80000000c00 - * LDS.128 R8, [R20+0x40] ; 0x0000400014087984 0x000e280000000c00 - * imm = byte offset at w[1] bits 8..31; size field 6 (128) at w[2] bits 9..11. */ - if (insn->imm >= (1u << 23)) return -1; - w[0] = 0x7984U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (insn->imm & 0xffffffU) << 8; - w[2] = 0x00000c00U; - w[3] = insn->control ? insn->control : 0x000fe800; - break; - } - - case BW_IR_LDS32: - /* LDS Rd, [Ra+URZ] (32-bit), the src/omega_numeric.c:886 form. */ - w[0] = 0x7984U | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = 0x000000ff; - w[2] = 0x08000800; - w[3] = insn->control ? insn->control : 0x000e2800; - break; - - case BW_IR_STS32: - /* STS [Ra+URZ], Rb (32-bit), the src/omega_numeric.c:884 form. */ - w[0] = 0x7988U | ((uint32_t)(src1 & 0xff) << 24); - w[1] = (uint32_t)(src2 & 0xff); - w[2] = 0x080008ffU; - w[3] = insn->control ? insn->control : 0x000fe200; - break; - - /* Prime race cut (2026-10-05). An absent operand is RZ for these three ops. */ - case BW_IR_LOP3_LUT: { - /* LOP3.LUT Rd, Ra, Rb, Rc, imm8, !PT. LOP3_XOR above is this form with Rc = RZ, LUT 0x3c. */ - uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; - uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; - w[0] = 0x7212U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); - w[1] = b; - w[2] = 0x078e0000U | ((insn->imm & 0xffU) << 8) | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - break; - } - - case BW_IR_SHF_L_U32: { - /* SHF.L.U32 Rd, Ra, Rb, Rc: register-amount form (0x7219) of SHF_R's 0x7819, with the - * .R (w[2] bit 12) and .HI (bit 16) flags clear. Rc is the funnel high word (RZ). */ - uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; - uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; - w[0] = 0x7219U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); - w[1] = b; - w[2] = 0x00000600U | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - break; - } - - case BW_IR_IMAD_HI_U32: { - /* IMAD.HI.U32 Rd, Ra, Rb, Rc: opcode 0x227 with the IMAD.WIDE.U32 modifier word. */ - uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; - uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; - w[0] = 0x7227U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); - w[1] = b; - w[2] = 0x078e0000U | (uint32_t)(src3 & 0xff); - w[3] = insn->control ? insn->control : 0x001fca00; - break; - } - - default: - return -1; - } - return 0; -} - -/* Prime race cut (2026-10-05): golden words for LOP3_LUT, SHF_L_U32 and IMAD_HI_U32. - * Each expected (w0, w1, w2) is the low 96 bits of an instruction nvcc 13.0.88 emitted - * for sm_121 (nvcc -arch=sm_121 -cubin, cuobjdump -sass; source and dump in - * bench/prime_race/tests/encoding_oracle.md). Control words (w3) are scheduler output and - * not compared. nvcc is an offline oracle only; nothing here links CUDA. 0 = all good. */ -int omega_blackwell_verify_codegen_fixtures_intops(void) { - OmegaRegAlloc ra; - memset(&ra, 0, sizeof(ra)); - static const int phys[] = { 0, 2, 6, 7, 9, 11, 13 }; - for (int i = 0; i < (int)(sizeof phys / sizeof phys[0]); i++) ra.vreg_to_phys[i] = phys[i]; - enum { R0 = 0, R2, R6, R7, R9, R11, R13, RZ = -1 }; - static const struct { - BlackwellIROpcode op; int d, a, b, c; uint32_t imm; uint32_t w0, w1, w2; const char *text; - } fx[] = { - { BW_IR_LOP3_LUT, R9, R7, R0, RZ, 0xfc, 0x07097212U, 0x00000000U, 0x078efcffU, "LOP3.LUT R9, R7, R0, RZ, 0xfc, !PT" }, - { BW_IR_LOP3_LUT, R11, R6, R7, R0, 0x78, 0x060b7212U, 0x00000007U, 0x078e7800U, "LOP3.LUT R11, R6, R7, R0, 0x78, !PT" }, - { BW_IR_LOP3_LUT, R13, R6, R7, R0, 0x10, 0x060d7212U, 0x00000007U, 0x078e1000U, "LOP3.LUT R13, R6, R7, R0, 0x10, !PT" }, - { BW_IR_LOP3_LUT, R7, RZ, R9, RZ, 0x33, 0xff077212U, 0x00000009U, 0x078e33ffU, "LOP3.LUT R7, RZ, R9, RZ, 0x33, !PT" }, - { BW_IR_SHF_L_U32, R7, R9, R2, RZ, 0, 0x09077219U, 0x00000002U, 0x000006ffU, "SHF.L.U32 R7, R9, R2, RZ" }, - { BW_IR_SHF_L_U32, R7, R0, R7, RZ, 0, 0x00077219U, 0x00000007U, 0x000006ffU, "SHF.L.U32 R7, R0, R7, RZ" }, - { BW_IR_IMAD_HI_U32, R9, R9, R0, R6, 0, 0x09097227U, 0x00000000U, 0x078e0006U, "IMAD.HI.U32 R9, R9, R0, R6" }, - { BW_IR_IMAD_HI_U32, R7, R0, R7, RZ, 0, 0x00077227U, 0x00000007U, 0x078e00ffU, "IMAD.HI.U32 R7, R0, R7, RZ" }, - }; - for (int i = 0; i < (int)(sizeof fx / sizeof fx[0]); i++) { - BlackwellIRInsn in; - memset(&in, 0, sizeof in); - in.op = fx[i].op; in.dst_vreg = fx[i].d; in.src1_vreg = fx[i].a; in.src2_vreg = fx[i].b; - in.src3_vreg = fx[i].c; in.ureg = -1; in.imm = fx[i].imm; - uint32_t w[4]; - if (encode_single_insn(&in, &ra, w) != 0) return -(2 * i + 1); - if (w[0] != fx[i].w0 || w[1] != fx[i].w1 || w[2] != fx[i].w2) return -(2 * i + 2); - } - return 0; -} - -int omega_blackwell_encode_one(const BlackwellIRInsn *insn, uint32_t w[4]) { - if (!insn || !w) return -1; - OmegaRegAlloc ra; - memset(&ra, 0, sizeof ra); - for (int i = 0; i < BW_MAX_VREGS; i++) ra.vreg_to_phys[i] = i; - for (int i = 0; i < BW_MAX_UVREGS; i++) ra.uvreg_to_phys[i] = i; - return encode_single_insn(insn, &ra, w); -} - -/* omega #328: golden words for the fragment-major matmul. Oracle: nvcc 13.0.88 -arch=sm_121 - * -cubin -O3, cuobjdump -sass, on a kernel with uint2 / uint4 loads at immediate offsets and a - * dependent mma.m16n8k16 bf16 chain (source and dump sealed in - * ~/workspace/investigations/2026-10-07-qwen3-decode-matmul/oracle/frag_plain.{cu,sass}): - * LDG.E.64 R2, desc[UR8][R30.64] ; 0x000000081e027981 0x000ea8000c1e1b00 - * LDG.E.64 R28, desc[UR8][R30.64+0x100] ; 0x000100081e1c7981 0x000ee8000c1e1b00 - * LDG.E.128 R8, desc[UR8][R32.64] ; 0x0000000820087981 0x000ea8000c1e1d00 - * LDG.E.128 R20, desc[UR8][R32.64+0x1000] ; 0x0010000820147981 0x000e9e000c1e1d00 - * HMMA.16816.F32.BF16 R8, R12, R6, R8 ; 0x000000060c08723c 0x010fe20000041808 - * NOP ; 0x0000000000007918 0x000fdc0000000000 - * The dependent HMMA chain nvcc emits is HMMA (stall 15) then NOP (stall 14): 29 cycles from - * one HMMA to the next that reads its accumulator. w3 is compared for the NOP only (it is the - * whole point of that instruction). 0 = all good. */ -int omega_blackwell_verify_codegen_fixtures_fragmm(void) { - static const struct { - BlackwellIROpcode op; int d, a, b, c, u; uint32_t imm, control; uint32_t w0, w1, w2, w3; const char *text; - } fx[] = { - { BW_IR_LDG_E_64, 2, 30, -1, -1, 8, 0, 0, 0x1e027981U, 0x00000008U, 0x0c1e1b00U, 0, "LDG.E.64 R2, desc[UR8][R30.64]" }, - { BW_IR_LDG_E_64, 28, 30, -1, -1, 8, 0x100, 0, 0x1e1c7981U, 0x00010008U, 0x0c1e1b00U, 0, "LDG.E.64 R28, desc[UR8][R30.64+0x100]" }, - { BW_IR_LDG_E_128, 8, 32, -1, -1, 8, 0, 0, 0x20087981U, 0x00000008U, 0x0c1e1d00U, 0, "LDG.E.128 R8, desc[UR8][R32.64]" }, - { BW_IR_LDG_E_128, 20, 32, -1, -1, 8, 0x1000, 0, 0x20147981U, 0x00100008U, 0x0c1e1d00U, 0, "LDG.E.128 R20, desc[UR8][R32.64+0x1000]" }, - { BW_IR_HMMA_BF16, 8, 12, 6, 8, -1, 0, 0, 0x0c08723cU, 0x00000006U, 0x00041808U, 0, "HMMA.16816.F32.BF16 R8, R12, R6, R8" }, - { BW_IR_NOP, -1, -1, -1, -1, -1, 0, 0x000fdc00U, 0x00007918U, 0, 0, 0x000fdc00U, "NOP (stall 14)" }, - /* LDS.128 with an immediate offset (attention batched loads, 2026-10-12): nvcc 13.0.88 -arch=sm_121 on - * float4 shared reads at register + constant offsets (fixture source in the omega speed/attention-batched-loads PR) */ - { BW_IR_LDS128, 4, 20, -1, -1, -1, 0, 0, 0x14047984U, 0x00000000U, 0x00000c00U, 0, "LDS.128 R4, [R20]" }, - { BW_IR_LDS128, 8, 20, -1, -1, -1, 0x40, 0, 0x14087984U, 0x00004000U, 0x00000c00U, 0, "LDS.128 R8, [R20+0x40]" }, - { BW_IR_LDS128, 12, 20, -1, -1, -1, 0x100, 0, 0x140c7984U, 0x00010000U, 0x00000c00U, 0, "LDS.128 R12, [R20+0x100]" }, - /* STG.E with an immediate offset (blocked prefill matmul, 2026-10-12): nvcc 13.0.88 -arch=sm_121 on float stores - * at register + constant offsets (~/.claude/jobs/ade3c837/tmp/stg-oracle/stg.cu); the second word is the - * offset-free STG word with UR4 */ - { BW_IR_STG_E, -1, 4, 8, -1, 4, 0, 0, 0x04007986U, 0x00000008U, 0x0c101904U, 0, "STG.E desc[UR4][R4.64], R8" }, - { BW_IR_STG_E, -1, 4, 9, -1, 4, 0x4, 0, 0x04007986U, 0x00000409U, 0x0c101904U, 0, "STG.E desc[UR4][R4.64+0x4], R9" }, - { BW_IR_STG_E, -1, 4, 10, -1, 4, 0x4000, 0, 0x04007986U, 0x0040000aU, 0x0c101904U, 0, "STG.E desc[UR4][R4.64+0x4000], R10" }, - { BW_IR_STG_E, -1, 6, 11, -1, 4, 0xfff00000u, 0, 0x06007986U, 0xf000000bU, 0x0c101904U, 0, "STG.E desc[UR4][R6.64+-0x100000], R11" }, - }; - for (int i = 0; i < (int)(sizeof fx / sizeof fx[0]); i++) { - BlackwellIRInsn in; - memset(&in, 0, sizeof in); - in.op = fx[i].op; in.dst_vreg = fx[i].d; in.src1_vreg = fx[i].a; in.src2_vreg = fx[i].b; - in.src3_vreg = fx[i].c; in.ureg = fx[i].u; in.imm = fx[i].imm; in.control = fx[i].control; - uint32_t w[4]; - if (omega_blackwell_encode_one(&in, w) != 0) return -(2 * i + 1); - if (w[0] != fx[i].w0 || w[1] != fx[i].w1 || w[2] != fx[i].w2 || (fx[i].w3 && w[3] != fx[i].w3)) return -(2 * i + 2); - } - /* offsets outside the signed 24-bit field are refused, not wrapped */ - BlackwellIRInsn big; - memset(&big, 0, sizeof big); - big.op = BW_IR_LDG_E_64; big.dst_vreg = 2; big.src1_vreg = 30; big.src2_vreg = -1; big.src3_vreg = -1; big.ureg = 8; - big.imm = 1u << 23; - uint32_t w[4]; - if (omega_blackwell_encode_one(&big, w) == 0) return -100; - big.imm = (uint32_t)-(1 << 23); - if (omega_blackwell_encode_one(&big, w) != 0) return -101; - return 0; -} - -/* omega #308: BSSY / BSYNC golden words. Oracle: nvcc 13.0.88 -arch=sm_121 -cubin -O3 on the - * kernels in docs/gpu-reconvergence-308.md, cuobjdump -sass (low 64-bit word, then high; the - * top 23 bits of the high word are the control word and are not compared here): - * k_loop [0070] BSSY.RECONVERGENT B0, 0x140 ; 0x000000c000007945 0x000fe20003800200 (delta 13) - * k_nested [0070] BSSY.RECONVERGENT B0, 0x300 ; 0x0000028000007945 0x000fe20003800200 (delta 41) - * k_break [0070] BSSY.RECONVERGENT B0, 0x110 ; 0x0000009000007945 0x000fe20003800200 (delta 10) - * k_loop [0130] BSYNC.RECONVERGENT B0 ; 0x0000000000007941 0x000fea0003800200 - * Barrier ids other than B0 and the predicated forms are decoded by tools/reconv_nvdisasm_check.sh - * (nvdisasm -b SM121 text), not by this table. */ -int omega_blackwell_verify_codegen_fixtures_reconv(void) { - static const struct { BlackwellIROpcode op; int delta; int bar; uint32_t w0, w1, w2; } fx[] = { - { BW_IR_BSSY, 13, 0, 0x00007945U, 0x000000c0U, 0x03800200U }, - { BW_IR_BSSY, 41, 0, 0x00007945U, 0x00000280U, 0x03800200U }, - { BW_IR_BSSY, 10, 0, 0x00007945U, 0x00000090U, 0x03800200U }, - { BW_IR_BSYNC, 0, 0, 0x00007941U, 0x00000000U, 0x03800200U }, - }; - for (int i = 0; i < (int)(sizeof fx / sizeof fx[0]); i++) { - BlackwellIRInsn in; - memset(&in, 0, sizeof in); - in.op = fx[i].op; in.dst_vreg = -1; in.src1_vreg = -1; in.src2_vreg = -1; in.src3_vreg = -1; in.ureg = -1; - in.imm = (uint32_t)fx[i].delta; in.bar_reg = (uint8_t)fx[i].bar; - uint32_t w[4]; - if (omega_blackwell_encode_one(&in, w) != 0) return -(2 * i + 1); - if (w[0] != fx[i].w0 || w[1] != fx[i].w1 || w[2] != fx[i].w2) return -(2 * i + 2); - /* control word defaults mirror nvcc's: BSSY 0x000fe200, BSYNC 0x000fea00 */ - if (w[3] != (fx[i].op == BW_IR_BSSY ? 0x000fe200U : 0x000fea00U)) return -(2 * i + 2); - } - /* refusals: a BSSY must name a later instruction (delta >= 2), barrier ids stop at B15 */ - BlackwellIRInsn bad; uint32_t w[4]; - memset(&bad, 0, sizeof bad); bad.op = BW_IR_BSSY; bad.dst_vreg = bad.src1_vreg = bad.src2_vreg = bad.src3_vreg = bad.ureg = -1; - bad.imm = 1; bad.bar_reg = 0; - if (omega_blackwell_encode_one(&bad, w) == 0) return -101; - bad.imm = (uint32_t)-3; - if (omega_blackwell_encode_one(&bad, w) == 0) return -102; - bad.imm = 5; bad.bar_reg = 16; - if (omega_blackwell_encode_one(&bad, w) == 0) return -103; - bad.op = BW_IR_BSYNC; bad.imm = 0; bad.bar_reg = 16; - if (omega_blackwell_encode_one(&bad, w) == 0) return -104; - bad.bar_reg = 15; - if (omega_blackwell_encode_one(&bad, w) != 0 || w[0] != (0x00007941U | (15U << 16))) return -105; - return 0; -} - -/* FB-1 cut 4: word-level fixtures for the four additive ops (checked against the - * nvdisasm decodes recorded in docs/numeric/FB1_CUT4_ELEMENTWISE.md). 0 = all good. */ -int omega_blackwell_verify_codegen_fixtures_fb1cut4(void) { - OmegaRegAlloc ra; - memset(&ra, 0, sizeof(ra)); - ra.vreg_to_phys[0] = 2; /* R2 */ - ra.vreg_to_phys[1] = 4; /* R4 */ - ra.vreg_to_phys[2] = 9; /* R9 */ - ra.vreg_to_phys[3] = 10; /* R10 */ - ra.vreg_to_phys[4] = 8; /* R8 */ - uint32_t w[4]; - - /* MUFU.EX2 R2, R4 */ - BlackwellIRInsn ex2 = { .op = BW_IR_MUFU_EX2, .dst_vreg = 0, .src1_vreg = 1 }; - if (encode_single_insn(&ex2, &ra, w) != 0) return -1; - if (w[0] != 0x00027308U || w[1] != 4 || w[2] != 0x00000800U) return -2; - /* BAR.SYNC.DEFER_BLOCKING 0x0 */ - BlackwellIRInsn bar = { .op = BW_IR_BAR_SYNC }; - if (encode_single_insn(&bar, &ra, w) != 0) return -3; - if (w[0] != 0x00007b1dU || w[1] != 0 || w[2] != 0x00010000U || w[3] != 0x000fec00U) return -4; - /* LDS R9, [R10+URZ] */ - BlackwellIRInsn lds = { .op = BW_IR_LDS32, .dst_vreg = 2, .src1_vreg = 3 }; - if (encode_single_insn(&lds, &ra, w) != 0) return -5; - if (w[0] != 0x0a097984U || w[1] != 0xff || w[2] != 0x08000800U) return -6; - /* STS [R8+URZ], R2 */ - BlackwellIRInsn sts = { .op = BW_IR_STS32, .src1_vreg = 4, .src2_vreg = 0 }; - if (encode_single_insn(&sts, &ra, w) != 0) return -7; - if (w[0] != 0x08007988U || w[1] != 2 || w[2] != 0x080008ffU) return -8; - return 0; -} - -int omega_bw_encode_program(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t max_len, size_t *out_len) { - if (!prog || !code_buf || !out_len) return -1; - - size_t padded_insns = (prog->count + 7) & ~7ULL; - if (padded_insns < 32) padded_insns = 32; - - size_t req_bytes = padded_insns * 16; - if (max_len < req_bytes) return -1; - - uint8_t *p = code_buf; - for (size_t i = 0; i < padded_insns; i++) { - uint32_t w[4]; - if (i < prog->count) { - if (encode_single_insn(&prog->insns[i], &prog->regalloc, w) != 0) { - return -1; - } - } else { - /* Pad with NOP */ - w[0] = 0x00007918; - w[1] = 0x00000000; - w[2] = 0x00000000; - w[3] = 0x000fc000; - } - - p[0] = (uint8_t)(w[0] & 0xff); - p[1] = (uint8_t)((w[0] >> 8) & 0xff); - p[2] = (uint8_t)((w[0] >> 16) & 0xff); - p[3] = (uint8_t)((w[0] >> 24) & 0xff); - - p[4] = (uint8_t)(w[1] & 0xff); - p[5] = (uint8_t)((w[1] >> 8) & 0xff); - p[6] = (uint8_t)((w[1] >> 16) & 0xff); - p[7] = (uint8_t)((w[1] >> 24) & 0xff); - - p[8] = (uint8_t)(w[2] & 0xff); - p[9] = (uint8_t)((w[2] >> 8) & 0xff); - p[10] = (uint8_t)((w[2] >> 16) & 0xff); - p[11] = (uint8_t)((w[2] >> 24) & 0xff); - - p[12] = (uint8_t)(w[3] & 0xff); - p[13] = (uint8_t)((w[3] >> 8) & 0xff); - p[14] = (uint8_t)((w[3] >> 16) & 0xff); - p[15] = (uint8_t)((w[3] >> 24) & 0xff); - - p += 16; - } - - *out_len = req_bytes; - return 0; -} - -int omega_blackwell_codegen_matmul_i32_prog(const OmegaMatMulSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - - /* Fail closed loudly if K exceeds bounded unroll limit */ - if (spec->k > 32) { - BW_DIAG("ERROR: MatMul integer codegen exceeds bounded unroll limit (K=%u > 32)\n", spec->k); - return -1; - } - - omega_bw_ir_init(prog); - - /* 1. Allocate virtual registers */ - /* 64-bit base pointers */ - int v_ptr_a = omega_bw_ir_alloc_vreg64(prog); - int v_ptr_b = omega_bw_ir_alloc_vreg64(prog); - int v_ptr_c = omega_bw_ir_alloc_vreg64(prog); - int uv_desc = omega_bw_ir_alloc_uvreg64(prog); - - /* 32-bit CTA / Thread indexing */ - int v_ctaid_x = omega_bw_ir_alloc_vreg(prog); - int v_ctaid_y = omega_bw_ir_alloc_vreg(prog); - int v_tid_x = omega_bw_ir_alloc_vreg(prog); - int v_tid_y = omega_bw_ir_alloc_vreg(prog); - - /* 2D Coordinates & loop invariants */ - int v_col = omega_bw_ir_alloc_vreg(prog); - int v_row = omega_bw_ir_alloc_vreg(prog); - int v_row_k = omega_bw_ir_alloc_vreg(prog); - int v_const_1 = omega_bw_ir_alloc_vreg(prog); - int v_acc = omega_bw_ir_alloc_vreg(prog); - - /* Working registers for memory address and operands */ - int v_idx_a = omega_bw_ir_alloc_vreg(prog); - int v_off_a = omega_bw_ir_alloc_vreg64(prog); - int v_val_a = omega_bw_ir_alloc_vreg(prog); - - int v_idx_b = omega_bw_ir_alloc_vreg(prog); - int v_off_b = omega_bw_ir_alloc_vreg64(prog); - int v_val_b = omega_bw_ir_alloc_vreg(prog); - - int v_idx_c = omega_bw_ir_alloc_vreg(prog); - int v_off_c = omega_bw_ir_alloc_vreg64(prog); - - if (v_off_c < 0) return -1; - - /* 2. Load 64-bit global memory descriptor into uniform register pair */ - /* LDCU.64 uv_desc, c[0x0][0x358] */ - BlackwellIRInsn insn_desc = { .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true }; - omega_bw_ir_append(prog, &insn_desc); - - /* 3. Load 64-bit base pointers from Constant Bank 0 */ - /* LDC.64 v_ptr_a, c[0x0][0x380] */ - BlackwellIRInsn insn_ptra = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380 }; - omega_bw_ir_append(prog, &insn_ptra); - - /* LDC.64 v_ptr_b, c[0x0][0x388] */ - BlackwellIRInsn insn_ptrb = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388 }; - omega_bw_ir_append(prog, &insn_ptrb); - - /* LDC.64 v_ptr_c, c[0x0][0x390] */ - BlackwellIRInsn insn_ptrc = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390 }; - omega_bw_ir_append(prog, &insn_ptrc); - - /* 4. Query 2D CTA and Thread coordinates */ - /* S2R v_ctaid_x, SR_CTAID.X */ - BlackwellIRInsn insn_ctax = { .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X }; - omega_bw_ir_append(prog, &insn_ctax); - - /* S2R v_ctaid_y, SR_CTAID.Y */ - BlackwellIRInsn insn_ctay = { .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y }; - omega_bw_ir_append(prog, &insn_ctay); - - /* S2R v_tid_x, SR_TID.X */ - BlackwellIRInsn insn_tidx = { .op = BW_IR_S2R, .dst_vreg = v_tid_x, .imm = BW_SR_TID_X }; - omega_bw_ir_append(prog, &insn_tidx); - - /* S2R v_tid_y, SR_TID.Y */ - BlackwellIRInsn insn_tidy = { .op = BW_IR_S2R, .dst_vreg = v_tid_y, .imm = BW_SR_TID_Y }; - omega_bw_ir_append(prog, &insn_tidy); - - /* 5. Compute 2D (row, col) coordinates */ - /* Standard 16x16 tile threads: col = ctaid_x * 16 + tid_x */ - BlackwellIRInsn insn_col = { .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = 16, .src3_vreg = v_tid_x }; - omega_bw_ir_append(prog, &insn_col); - - /* row = ctaid_y * 16 + tid_y */ - BlackwellIRInsn insn_row = { .op = BW_IR_IMAD, .dst_vreg = v_row, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16, .src3_vreg = v_tid_y }; - omega_bw_ir_append(prog, &insn_row); - - /* 6. Precompute row base index: v_row_k = v_row * K + RZ */ - BlackwellIRInsn insn_row_k = { .op = BW_IR_IMAD, .dst_vreg = v_row_k, .src1_vreg = v_row, .src2_vreg = -1, .imm = spec->k, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_row_k); - - /* 7. Initialize v_const_1 = 1 for immediate linear indexing */ - BlackwellIRInsn insn_c1 = { .op = BW_IR_MOV_IMM, .dst_vreg = v_const_1, .imm = 1 }; - omega_bw_ir_append(prog, &insn_c1); - - /* 8. Initialize accumulator to zero: MOV v_acc, RZ */ - BlackwellIRInsn insn_init_acc = { .op = BW_IR_MOV_RZ, .dst_vreg = v_acc }; - omega_bw_ir_append(prog, &insn_init_acc); - - /* 9. Synthesize inner accumulation loop across K iterations */ - for (uint32_t step = 0; step < spec->k; step++) { - /* A[row, step]: idx_a = v_row_k + step = v_const_1 * step + v_row_k */ - BlackwellIRInsn insn_idxa = { .op = BW_IR_IMAD, .dst_vreg = v_idx_a, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = step, .src3_vreg = v_row_k }; - omega_bw_ir_append(prog, &insn_idxa); - - /* off_a = v_ptr_a + idx_a * 4 */ - BlackwellIRInsn insn_offa = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off_a, .src1_vreg = v_idx_a, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_a }; - omega_bw_ir_append(prog, &insn_offa); - - /* Load A[row, step]: LDG.E v_val_a, desc[uv_desc][v_off_a.64] */ - BlackwellIRInsn insn_lda = { .op = BW_IR_LDG_E, .dst_vreg = v_val_a, .src1_vreg = v_off_a, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x001ea800 }; - omega_bw_ir_append(prog, &insn_lda); - - /* B[step, col]: idx_b = step * N + col = v_const_1 * (step * N) + v_col */ - uint32_t step_n = step * spec->n; - BlackwellIRInsn insn_idxb = { .op = BW_IR_IMAD, .dst_vreg = v_idx_b, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = step_n, .src3_vreg = v_col }; - omega_bw_ir_append(prog, &insn_idxb); - - /* off_b = v_ptr_b + idx_b * 4 */ - BlackwellIRInsn insn_offb = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off_b, .src1_vreg = v_idx_b, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_b }; - omega_bw_ir_append(prog, &insn_offb); - - /* Load B[step, col]: LDG.E v_val_b, desc[uv_desc][v_off_b.64] */ - BlackwellIRInsn insn_ldb = { .op = BW_IR_LDG_E, .dst_vreg = v_val_b, .src1_vreg = v_off_b, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x002ea800 }; - omega_bw_ir_append(prog, &insn_ldb); - - /* Multiply and accumulate: IMAD v_acc, v_val_a, v_val_b, v_acc */ - BlackwellIRInsn insn_acc = { .op = BW_IR_IMAD, .dst_vreg = v_acc, .src1_vreg = v_val_a, .src2_vreg = v_val_b, .src3_vreg = v_acc, .control = 0x004fca00 }; - omega_bw_ir_append(prog, &insn_acc); - } - - /* 10. Compute output index: idx_c = row * N + col */ - BlackwellIRInsn insn_idxc = { .op = BW_IR_IMAD, .dst_vreg = v_idx_c, .src1_vreg = v_row, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_col }; - omega_bw_ir_append(prog, &insn_idxc); - - /* off_c = v_ptr_c + idx_c * 4 */ - BlackwellIRInsn insn_offc = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off_c, .src1_vreg = v_idx_c, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c }; - omega_bw_ir_append(prog, &insn_offc); - - /* Store C[row, col]: STG.E desc[uv_desc][v_off_c.64], v_acc */ - BlackwellIRInsn insn_stc = { .op = BW_IR_STG_E, .src1_vreg = v_off_c, .src2_vreg = v_acc, .src3_vreg = -1, .ureg = uv_desc }; - omega_bw_ir_append(prog, &insn_stc); - - /* 11. Kernel termination */ - BlackwellIRInsn insn_exit = { .op = BW_IR_EXIT, .predicate_p0 = false }; - omega_bw_ir_append(prog, &insn_exit); - - BlackwellIRInsn insn_bra = { .op = BW_IR_BRA }; - omega_bw_ir_append(prog, &insn_bra); - - /* 12. Solve bounded deterministic register allocation */ - if (omega_bw_regalloc_solve(prog) != 0) { - return -1; - } - return 0; -} - -/* ---- native v1 P07 cut A.2: allocation-free kernel encoding --------------------------------- - * The one place a solved IR program becomes a kernel. Hosted and freestanding builds both encode - * through it, so the two produce the same bytes for the same program (make test-codegen-freestanding - * compares them). */ -size_t omega_bw_program_code_bytes(const BlackwellIRProgram *prog) { - if (!prog) return 0; - size_t padded_insns = (prog->count + 7) & ~(size_t)7; - if (padded_insns < 32) padded_insns = 32; - return padded_insns * 16; -} - -int omega_blackwell_kernel_encode_into(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t code_cap, - OmegaBlackwellKernel *kernel) { - if (!kernel) return -1; - memset(kernel, 0, sizeof *kernel); - if (!prog || !code_buf) return -1; - size_t need = omega_bw_program_code_bytes(prog); - if (code_cap < need) return OMEGA_BW_CODE_BUFFER_TOO_SMALL; /* refused before any byte is written */ - size_t emitted_size = 0; - if (omega_bw_encode_program(prog, code_buf, code_cap, &emitted_size) != 0) return -1; - kernel->code = code_buf; - kernel->code_size = emitted_size; - kernel->insn_count = emitted_size / 16; - kernel->gpr_count = prog->regalloc.peak_gpr_usage; - kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; - sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX -/* Hosted only: the allocating generators keep their names, caps and behavior. Each builds the program, - * mallocs max_bytes (the cap each generator always had) and encodes through omega_blackwell_kernel_encode_into; - * omega_blackwell_kernel_free releases the buffer. */ -static int bw_kernel_alloc_encode(const BlackwellIRProgram *prog, size_t max_bytes, OmegaBlackwellKernel *kernel) { - uint8_t *buf = (uint8_t *)malloc(max_bytes); - if (!buf) { kernel->code = NULL; return -1; } - if (omega_blackwell_kernel_encode_into(prog, buf, max_bytes, kernel) != 0) { - free(buf); - kernel->code = NULL; - return -1; - } - return 0; -} - -int omega_blackwell_codegen_matmul_i32(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - BlackwellIRProgram prog; - if (omega_blackwell_codegen_matmul_i32_prog(spec, &prog) != 0) return -1; - /* 13. the code buffer is exactly the padded program (the i32 generator never had a fixed cap) */ - return bw_kernel_alloc_encode(&prog, omega_bw_program_code_bytes(&prog), kernel); -} -#endif - -int omega_blackwell_codegen_matmul_tensor_prog(const OmegaMatMulSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; - if (spec->m % 16 != 0 || spec->n % 8 != 0 || spec->k != 16) { - BW_DIAG("ERROR: MatMul tensor codegen requires M multiple of 16, N multiple of 8, K=16 (got %ux%ux%u)\n", - spec->m, spec->k, spec->n); - return -1; - } - - omega_bw_ir_init(prog); - - /* 1. Allocate virtual registers */ - /* 64-bit base pointers */ - int v_ptr_a = omega_bw_ir_alloc_vreg64(prog); - int v_ptr_b = omega_bw_ir_alloc_vreg64(prog); - int v_ptr_c = omega_bw_ir_alloc_vreg64(prog); - int uv_desc = omega_bw_ir_alloc_uvreg64(prog); - - /* 32-bit CTA / Thread indexing */ - int v_tid = omega_bw_ir_alloc_vreg(prog); - int v_ctaid_x = omega_bw_ir_alloc_vreg(prog); - int v_ctaid_y = omega_bw_ir_alloc_vreg(prog); - - /* Tile and thread coordinates */ - int v_group_id = omega_bw_ir_alloc_vreg(prog); - int v_tid_in_grp = omega_bw_ir_alloc_vreg(prog); - int v_row_base = omega_bw_ir_alloc_vreg(prog); - int v_col_base = omega_bw_ir_alloc_vreg(prog); - int v_r0 = omega_bw_ir_alloc_vreg(prog); - int v_r1 = omega_bw_ir_alloc_vreg(prog); - int v_col_b = omega_bw_ir_alloc_vreg(prog); - int v_tid_col2 = omega_bw_ir_alloc_vreg(prog); - int v_const_1 = omega_bw_ir_alloc_vreg(prog); - - /* Bundles for HMMA */ - int v_ra = omega_bw_ir_alloc_vreg128(prog); /* Quad: Ra[0]..Ra[3] */ - int v_rb = omega_bw_ir_alloc_vreg64(prog); /* Pair: Rb[0]..Rb[1] */ - int v_rd = omega_bw_ir_alloc_vreg128(prog); /* Quad: Rd[0]..Rd[3] */ - - /* Scratch registers for indexing and loads */ - int v_idx = omega_bw_ir_alloc_vreg(prog); - int v_off = omega_bw_ir_alloc_vreg64(prog); - int v_b_tmp0 = omega_bw_ir_alloc_vreg(prog); - int v_b_tmp1 = omega_bw_ir_alloc_vreg(prog); - - if (v_b_tmp1 < 0) return -1; - - /* 2. Load 64-bit global memory descriptor into uniform register pair */ - /* LDCU.64 uv_desc, c[0x0][0x358] */ - BlackwellIRInsn insn_desc = { .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true }; - omega_bw_ir_append(prog, &insn_desc); - - /* 3. Load 64-bit base pointers from Constant Bank 0 */ - /* LDC.64 v_ptr_a, c[0x0][0x380] */ - BlackwellIRInsn insn_ptra = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380 }; - omega_bw_ir_append(prog, &insn_ptra); - - /* LDC.64 v_ptr_b, c[0x0][0x388] */ - BlackwellIRInsn insn_ptrb = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388 }; - omega_bw_ir_append(prog, &insn_ptrb); - - /* LDC.64 v_ptr_c, c[0x0][0x390] */ - BlackwellIRInsn insn_ptrc = { .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390 }; - omega_bw_ir_append(prog, &insn_ptrc); - - /* 4. Query Special Registers */ - /* S2R v_tid, SR_TID.X */ - BlackwellIRInsn insn_tidx = { .op = BW_IR_S2R, .dst_vreg = v_tid, .imm = BW_SR_TID_X }; - omega_bw_ir_append(prog, &insn_tidx); - - /* S2R v_ctaid_x, SR_CTAID.X */ - BlackwellIRInsn insn_cta_x = { .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X }; - omega_bw_ir_append(prog, &insn_cta_x); - - /* S2R v_ctaid_y, SR_CTAID.Y */ - BlackwellIRInsn insn_cta_y = { .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y }; - omega_bw_ir_append(prog, &insn_cta_y); - - /* 5. Set up constant 1 */ - BlackwellIRInsn insn_c1 = { .op = BW_IR_MOV_IMM, .dst_vreg = v_const_1, .imm = 1 }; - omega_bw_ir_append(prog, &insn_c1); - - /* 6. Extract warp-level tile and thread coordinates */ - /* group_id = tid >> 2 */ - BlackwellIRInsn insn_grp = { .op = BW_IR_SHF_R, .dst_vreg = v_group_id, .src1_vreg = v_tid, .imm = 2 }; - omega_bw_ir_append(prog, &insn_grp); - - /* tid_in_grp = tid & 3 */ - BlackwellIRInsn insn_tig = { .op = BW_IR_LOP3_AND, .dst_vreg = v_tid_in_grp, .src1_vreg = v_tid, .imm = 3 }; - omega_bw_ir_append(prog, &insn_tig); - - /* row_base = ctaid_y * 16 */ - BlackwellIRInsn insn_rbase = { .op = BW_IR_IMAD, .dst_vreg = v_row_base, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_rbase); - - /* col_base = ctaid_x * 8 */ - BlackwellIRInsn insn_cbase = { .op = BW_IR_IMAD, .dst_vreg = v_col_base, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = 8, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_cbase); - - /* r0 = row_base + group_id */ - BlackwellIRInsn insn_r0 = { .op = BW_IR_IADD3, .dst_vreg = v_r0, .src1_vreg = v_row_base, .src2_vreg = v_group_id, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_r0); - - /* r1 = r0 + 8 */ - BlackwellIRInsn insn_r1 = { .op = BW_IR_IMAD, .dst_vreg = v_r1, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 8, .src3_vreg = v_r0 }; - omega_bw_ir_append(prog, &insn_r1); - - /* col_b = col_base + group_id */ - BlackwellIRInsn insn_colb = { .op = BW_IR_IADD3, .dst_vreg = v_col_b, .src1_vreg = v_col_base, .src2_vreg = v_group_id, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_colb); - - /* tid_col2 = tid_in_grp * 2 */ - BlackwellIRInsn insn_tcol2 = { .op = BW_IR_IMAD, .dst_vreg = v_tid_col2, .src1_vreg = v_tid_in_grp, .src2_vreg = -1, .imm = 2, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_tcol2); - - /* 7. Load A fragments (16x16 row-major, 2 bytes/element, row stride 32 bytes) */ - /* Pair 0: a0, a1 at r0 * 32 + tid_col2 * 2 */ - BlackwellIRInsn insn_a0_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = 32, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_a0_idx1); - BlackwellIRInsn insn_a0_idx2 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = 2, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a0_idx2); - BlackwellIRInsn insn_a0_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 1, .src3_vreg = v_ptr_a }; - omega_bw_ir_append(prog, &insn_a0_off); - BlackwellIRInsn insn_lda0 = { .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 0, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x001ea800 }; - omega_bw_ir_append(prog, &insn_lda0); - - /* Pair 1: a2, a3 at r1 * 32 + tid_col2 * 2 */ - BlackwellIRInsn insn_a1_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = 32, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_a1_idx1); - BlackwellIRInsn insn_a1_idx2 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = 2, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a1_idx2); - BlackwellIRInsn insn_a1_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 1, .src3_vreg = v_ptr_a }; - omega_bw_ir_append(prog, &insn_a1_off); - BlackwellIRInsn insn_lda1 = { .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 1, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x001ea800 }; - omega_bw_ir_append(prog, &insn_lda1); - - /* Pair 2: a4, a5 at r0 * 32 + tid_col2 * 2 + 16 */ - BlackwellIRInsn insn_a2_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = 32, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_a2_idx1); - BlackwellIRInsn insn_a2_idx2 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = 2, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a2_idx2); - BlackwellIRInsn insn_a2_idx3 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a2_idx3); - BlackwellIRInsn insn_a2_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 1, .src3_vreg = v_ptr_a }; - omega_bw_ir_append(prog, &insn_a2_off); - BlackwellIRInsn insn_lda2 = { .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 2, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x001ea800 }; - omega_bw_ir_append(prog, &insn_lda2); - - /* Pair 3: a6, a7 at r1 * 32 + tid_col2 * 2 + 16 */ - BlackwellIRInsn insn_a3_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = 32, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_a3_idx1); - BlackwellIRInsn insn_a3_idx2 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = 2, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a3_idx2); - BlackwellIRInsn insn_a3_idx3 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_a3_idx3); - BlackwellIRInsn insn_a3_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 1, .src3_vreg = v_ptr_a }; - omega_bw_ir_append(prog, &insn_a3_off); - BlackwellIRInsn insn_lda3 = { .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 3, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x001ea800 }; - omega_bw_ir_append(prog, &insn_lda3); - - /* 8. Load and pack B fragments (16xN row-major, 2 bytes/element) */ - /* b0 at tid_col2 * N + col_b */ - BlackwellIRInsn insn_b0_idx = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_col_b }; - omega_bw_ir_append(prog, &insn_b0_idx); - BlackwellIRInsn insn_b0_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b }; - omega_bw_ir_append(prog, &insn_b0_off); - BlackwellIRInsn insn_ldb0 = { .op = BW_IR_LDG_E_U16, .dst_vreg = v_b_tmp0, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x002ea800 }; - omega_bw_ir_append(prog, &insn_ldb0); - - /* b1 at (tid_col2 + 1) * N + col_b = b0_idx + N */ - BlackwellIRInsn insn_b1_idx = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_b1_idx); - BlackwellIRInsn insn_b1_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b }; - omega_bw_ir_append(prog, &insn_b1_off); - BlackwellIRInsn insn_ldb1 = { .op = BW_IR_LDG_E_U16, .dst_vreg = v_b_tmp1, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x002ea800 }; - omega_bw_ir_append(prog, &insn_ldb1); - - /* Pack Rb[0] = (b1 << 16) | b0 (wait on barrier 2) */ - BlackwellIRInsn insn_pack_b0 = { .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 0, .src1_vreg = v_b_tmp1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b_tmp0, .control = 0x004fca00 }; - omega_bw_ir_append(prog, &insn_pack_b0); - - /* b2 at (tid_col2 + 8) * N + col_b */ - BlackwellIRInsn insn_b2_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tid_col2, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_col_b }; - omega_bw_ir_append(prog, &insn_b2_idx1); - BlackwellIRInsn insn_b2_idx2 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 8 * spec->n, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_b2_idx2); - BlackwellIRInsn insn_b2_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b }; - omega_bw_ir_append(prog, &insn_b2_off); - BlackwellIRInsn insn_ldb2 = { .op = BW_IR_LDG_E_U16, .dst_vreg = v_b_tmp0, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x002ea800 }; - omega_bw_ir_append(prog, &insn_ldb2); - - /* b3 at (tid_col2 + 9) * N + col_b = b2_idx + N */ - BlackwellIRInsn insn_b3_idx = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_b3_idx); - BlackwellIRInsn insn_b3_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b }; - omega_bw_ir_append(prog, &insn_b3_off); - BlackwellIRInsn insn_ldb3 = { .op = BW_IR_LDG_E_U16, .dst_vreg = v_b_tmp1, .src1_vreg = v_off, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = 0x002ea800 }; - omega_bw_ir_append(prog, &insn_ldb3); - - /* Pack Rb[1] = (b3 << 16) | b2 (wait on barrier 2) */ - BlackwellIRInsn insn_pack_b1 = { .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 1, .src1_vreg = v_b_tmp1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b_tmp0, .control = 0x004fca00 }; - omega_bw_ir_append(prog, &insn_pack_b1); - - /* 9. Execute HMMA Tensor Core instruction (wait on barrier 1 for A loads) */ - BlackwellIROpcode mma_op = (spec->precision == OMEGA_MATMUL_PRECISION_BF16) ? BW_IR_HMMA_BF16 : BW_IR_HMMA_F16; - BlackwellIRInsn insn_hmma = { - .op = mma_op, - .dst_vreg = v_rd, - .dst_subreg = 0, - .src1_vreg = v_ra, - .src1_subreg = 0, - .src2_vreg = v_rb, - .src2_subreg = 0, - .src3_vreg = -1, /* RZ accumulator input */ - .control = 0x002fca00 /* Wait on barrier 1 */ - }; - omega_bw_ir_append(prog, &insn_hmma); - - /* 10. Store C output fragments (16xN row-major, 4 bytes/float element) */ - /* d0: row r0, col col_base + tid_col2 + 0 */ - BlackwellIRInsn insn_d0_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_col_base }; - omega_bw_ir_append(prog, &insn_d0_idx1); - BlackwellIRInsn insn_d0_idx2 = { .op = BW_IR_IADD3, .dst_vreg = v_idx, .src1_vreg = v_idx, .src2_vreg = v_tid_col2, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_d0_idx2); - BlackwellIRInsn insn_d0_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c }; - omega_bw_ir_append(prog, &insn_d0_off); - BlackwellIRInsn insn_std0 = { .op = BW_IR_STG_E, .src1_vreg = v_off, .src2_vreg = v_rd, .src2_subreg = 0, .ureg = uv_desc, .control = 0x000fe200 }; - omega_bw_ir_append(prog, &insn_std0); - - /* d1: row r0, col col_base + tid_col2 + 1 */ - BlackwellIRInsn insn_d1_idx = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 1, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_d1_idx); - BlackwellIRInsn insn_d1_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c }; - omega_bw_ir_append(prog, &insn_d1_off); - BlackwellIRInsn insn_std1 = { .op = BW_IR_STG_E, .src1_vreg = v_off, .src2_vreg = v_rd, .src2_subreg = 1, .ureg = uv_desc, .control = 0x000fe200 }; - omega_bw_ir_append(prog, &insn_std1); - - /* d2: row r1, col col_base + tid_col2 + 0 */ - BlackwellIRInsn insn_d2_idx1 = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = spec->n, .src3_vreg = v_col_base }; - omega_bw_ir_append(prog, &insn_d2_idx1); - BlackwellIRInsn insn_d2_idx2 = { .op = BW_IR_IADD3, .dst_vreg = v_idx, .src1_vreg = v_idx, .src2_vreg = v_tid_col2, .src3_vreg = -1 }; - omega_bw_ir_append(prog, &insn_d2_idx2); - BlackwellIRInsn insn_d2_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c }; - omega_bw_ir_append(prog, &insn_d2_off); - BlackwellIRInsn insn_std2 = { .op = BW_IR_STG_E, .src1_vreg = v_off, .src2_vreg = v_rd, .src2_subreg = 2, .ureg = uv_desc, .control = 0x000fe200 }; - omega_bw_ir_append(prog, &insn_std2); - - /* d3: row r1, col col_base + tid_col2 + 1 */ - BlackwellIRInsn insn_d3_idx = { .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_const_1, .src2_vreg = -1, .imm = 1, .src3_vreg = v_idx }; - omega_bw_ir_append(prog, &insn_d3_idx); - BlackwellIRInsn insn_d3_off = { .op = BW_IR_IMAD_WIDE, .dst_vreg = v_off, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c }; - omega_bw_ir_append(prog, &insn_d3_off); - BlackwellIRInsn insn_std3 = { .op = BW_IR_STG_E, .src1_vreg = v_off, .src2_vreg = v_rd, .src2_subreg = 3, .ureg = uv_desc, .control = 0x000fe200 }; - omega_bw_ir_append(prog, &insn_std3); - - /* 11. Program Exit */ - BlackwellIRInsn insn_exit = { .op = BW_IR_EXIT }; - omega_bw_ir_append(prog, &insn_exit); - BlackwellIRInsn insn_bra = { .op = BW_IR_BRA }; - omega_bw_ir_append(prog, &insn_bra); - - /* 12. Run bounded register allocation */ - if (omega_bw_regalloc_solve(prog) != 0) { - return -1; - } - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_matmul_tensor(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - BlackwellIRProgram prog; - if (omega_blackwell_codegen_matmul_tensor_prog(spec, &prog) != 0) { - return -1; - } - - return bw_kernel_alloc_encode(&prog, OMEGA_BW_CODE_CAP_SMALL, kernel); -} -#endif - -/* ---- FB-1 cut 1b: looped tensor matmul ------------------------------------------ - * - * Control words (bundle bits 105..125, decoded from the chip-proven kernel and from - * the vendor compiler's SASS for an equivalent HMMA loop on this chip, 2026-10-04): - * stall = bits 9..12 of w[3], yield = 13, write barrier = 14..16, read barrier = - * 17..19, wait mask = 20..25. 7 in a barrier field means "none". - * LDG (A) 0x001ea800 stall 4, yield, sets SB2 - * LDG.U16 (B) 0x002ea800 stall 4, yield, sets SB2 - * pack IMAD 0x004fca00 stall 5, waits SB2 (every outstanding load has landed) - * HMMA 0x002fca00 stall 5 (fixed latency: the vendor compiler sets no - * write barrier on HMMA either; consumers wait by stall count) - * STG 0x0007e200 stall 1, yield, read barrier SB3 (the store may read its - * data/address registers late; the next writer waits SB3) - * wait SB3 mask bit 23 (0x00800000) on the first instruction that overwrites a - * register a store reads: the C pointer advance. - * Loop-carried registers are kept live to the end of their loop (keep_alive) because - * the allocator is a straight-line linear scan and knows nothing about back edges. - */ -static void bw_keep_alive(BlackwellIRProgram *prog, int from_idx, int to_idx, int last_idx) { - /* every vreg first defined in [from_idx, to_idx) stays live until last_idx */ - for (int v = 0; v < prog->regalloc.num_vregs; v++) { - OmegaLiveInterval *iv = &prog->regalloc.intervals[v]; - if (iv->first_def >= from_idx && iv->first_def < to_idx && iv->last_use < last_idx) - iv->last_use = last_idx; - } -} - -#define BW_APPEND(prog, ...) do { BlackwellIRInsn _i = { __VA_ARGS__ }; if (omega_bw_ir_append((prog), &_i) < 0) return -1; } while (0) - -int omega_blackwell_codegen_matmul_tensor_loop_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, - int mutant, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; - if (spec->m % 16 != 0 || spec->n % 8 != 0 || spec->k % 16 != 0) { - BW_DIAG("ERROR: looped MatMul tensor codegen requires M%%16, N%%8, K%%16 (got %ux%ux%u)\n", - spec->m, spec->k, spec->n); - return -1; - } - const uint32_t K = spec->k, N = spec->n, NT = N / 8, KSTEPS = K / 16; - if (grid_x == 0 || grid_x > NT) return -1; - /* every immediate below must fit 32 bits: 32 * N (B row-block stride in bytes) is the largest */ - if ((uint64_t)N * 32u > 0xffffffffull || (uint64_t)grid_x * 32u > 0xffffffffull) return -1; - if (mutant && KSTEPS < 2) return -1; - - omega_bw_ir_init(prog); - - int v_ptr_a = omega_bw_ir_alloc_vreg64(prog), v_ptr_b = omega_bw_ir_alloc_vreg64(prog), v_ptr_c = omega_bw_ir_alloc_vreg64(prog); - int uv_desc = omega_bw_ir_alloc_uvreg64(prog); - int v_tid = omega_bw_ir_alloc_vreg(prog), v_ctaid_x = omega_bw_ir_alloc_vreg(prog), v_ctaid_y = omega_bw_ir_alloc_vreg(prog); - int v_group = omega_bw_ir_alloc_vreg(prog), v_tig = omega_bw_ir_alloc_vreg(prog), v_tcol2 = omega_bw_ir_alloc_vreg(prog); - int v_r0 = omega_bw_ir_alloc_vreg(prog), v_r1 = omega_bw_ir_alloc_vreg(prog), v_c1 = omega_bw_ir_alloc_vreg(prog); - int v_idx = omega_bw_ir_alloc_vreg(prog), v_col = omega_bw_ir_alloc_vreg(prog), v_cnt = omega_bw_ir_alloc_vreg(prog); - int v_pa0 = omega_bw_ir_alloc_vreg64(prog), v_pa1 = omega_bw_ir_alloc_vreg64(prog), v_pbcol = omega_bw_ir_alloc_vreg64(prog); - int v_pc0 = omega_bw_ir_alloc_vreg64(prog), v_pc1 = omega_bw_ir_alloc_vreg64(prog); - int v_pa0c = omega_bw_ir_alloc_vreg64(prog), v_pa1c = omega_bw_ir_alloc_vreg64(prog), v_pbc = omega_bw_ir_alloc_vreg64(prog); - int v_ta2 = omega_bw_ir_alloc_vreg64(prog), v_ta3 = omega_bw_ir_alloc_vreg64(prog); - int v_tb1 = omega_bw_ir_alloc_vreg64(prog), v_tb2 = omega_bw_ir_alloc_vreg64(prog), v_tb3 = omega_bw_ir_alloc_vreg64(prog); - int v_tc1 = omega_bw_ir_alloc_vreg64(prog), v_tc3 = omega_bw_ir_alloc_vreg64(prog); - int v_ra = omega_bw_ir_alloc_vreg128(prog), v_rb = omega_bw_ir_alloc_vreg64(prog), v_rd = omega_bw_ir_alloc_vreg128(prog); - int v_b0 = omega_bw_ir_alloc_vreg(prog), v_b1 = omega_bw_ir_alloc_vreg(prog); - if (v_b1 < 0 || uv_desc < 0) return -1; - - const uint32_t CTRL_LDA = 0x001ea800u, CTRL_LDB = 0x002ea800u, CTRL_PACK = 0x004fca00u; - const uint32_t CTRL_HMMA = 0x002fca00u, CTRL_STG_RDBAR3 = 0x0007e200u, CTRL_IMADW_WAIT3 = 0x009fcc00u; - const uint32_t CTRL_MOVRZ_WAIT3 = 0x008fe200u; - - /* prologue: descriptor, pointers, ids */ - BW_APPEND(prog, .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_tid, .imm = BW_SR_TID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_c1, .imm = 1); - BW_APPEND(prog, .op = BW_IR_SHF_R, .dst_vreg = v_group, .src1_vreg = v_tid, .imm = 2); - BW_APPEND(prog, .op = BW_IR_LOP3_AND, .dst_vreg = v_tig, .src1_vreg = v_tid, .imm = 3); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_tcol2, .src1_vreg = v_tig, .src2_vreg = -1, .imm = 2, .src3_vreg = -1); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r0, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16, .src3_vreg = v_group); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 8, .src3_vreg = v_r0); - /* pa0 = A + (r0*K + tcol2)*2 ; pa1 likewise with r1 (A row-major, K bf16 per row) */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = K, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_a); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = K, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_a); - /* col = ctaid_x (first column tile of this CTA) */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); - /* pbcol = B + (tcol2*N + col*8 + group)*2 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_tcol2, .src2_vreg = -1, .imm = N, .src3_vreg = v_group); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 2, .src3_vreg = v_ptr_b); - /* pc0 = C + (r0*N + col*8 + tcol2)*4 ; pc1 with r1 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - - /* ---- column-tile loop ---- */ - const int L_col = (int)prog->count; - /* accumulator = 0 (the first write waits SB3: the previous tile's stores may still read it) */ - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 0, .control = CTRL_MOVRZ_WAIT3); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 1); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 2); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 3); - /* K cursors start at the row/column bases (IMAD.WIDE with imm 0 is a 64-bit copy) */ - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa0); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa1); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_cnt, .imm = mutant ? KSTEPS - 1 : KSTEPS); - - /* ---- K loop: one 16x16 A fragment and one 16x8 B fragment per step ---- */ - const int L_k = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_ta2, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_pa0c); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_ta3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16, .src3_vreg = v_pa1c); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 2u * N, .src3_vreg = v_pbc); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb2, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 16u * N, .src3_vreg = v_pbc); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tb3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 18u * N, .src3_vreg = v_pbc); - /* A: a0,a1 at (r0, kk+tcol2) ; a2,a3 at (r1, ...) ; a4,a5 at (r0, +8) ; a6,a7 at (r1, +8) */ - BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 0, .src1_vreg = v_pa0c, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); - BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 1, .src1_vreg = v_pa1c, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); - BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 2, .src1_vreg = v_ta2, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); - BW_APPEND(prog, .op = BW_IR_LDG_E, .dst_vreg = v_ra, .dst_subreg = 3, .src1_vreg = v_ta3, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDA); - /* B: rows kk+tcol2, +1, +8, +9 at column col*8+group */ - BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b0, .src1_vreg = v_pbc, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); - BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b1, .src1_vreg = v_tb1, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 0, .src1_vreg = v_b1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b0, .control = CTRL_PACK); - BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b0, .src1_vreg = v_tb2, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); - BW_APPEND(prog, .op = BW_IR_LDG_E_U16, .dst_vreg = v_b1, .src1_vreg = v_tb3, .src2_vreg = -1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_LDB); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_rb, .dst_subreg = 1, .src1_vreg = v_b1, .src2_vreg = -1, .imm = 0x10000, .src3_vreg = v_b0, .control = CTRL_PACK); - /* rd += ra * rb (accumulate in place) */ - BW_APPEND(prog, .op = (spec->precision == OMEGA_MATMUL_PRECISION_BF16) ? BW_IR_HMMA_BF16 : BW_IR_HMMA_F16, - .dst_vreg = v_rd, .dst_subreg = 0, .src1_vreg = v_ra, .src1_subreg = 0, .src2_vreg = v_rb, .src2_subreg = 0, - .src3_vreg = v_rd, .src3_subreg = 0, .control = CTRL_HMMA); - /* advance K: A by 16 bf16 (32 bytes), B by 16 rows (32 N bytes); every load above has landed (packs waited SB2) */ - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa0c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32, .src3_vreg = v_pa0c); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa1c, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32, .src3_vreg = v_pa1c); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 32u * N, .src3_vreg = v_pbc); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_cnt, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0xffffffffu, .src3_vreg = v_cnt); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_cnt, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_k - here), .predicate_p0 = true); - } - const int L_k_end = (int)prog->count - 1; - - /* ---- store the 16x8 tile: d0 (r0, c), d1 (r0, c+1), d2 (r1, c), d3 (r1, c+1) ---- */ - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc0); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc1); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc0, .src2_vreg = v_rd, .src2_subreg = 0, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc1, .src2_vreg = v_rd, .src2_subreg = 1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc1, .src2_vreg = v_rd, .src2_subreg = 2, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc3, .src2_vreg = v_rd, .src2_subreg = 3, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - /* next column tile of this CTA: col += grid_x ; B by grid_x*8 bf16 ; C by grid_x*8 f32 (waits SB3 first) */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x, .src3_vreg = v_col); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc0, .control = CTRL_IMADW_WAIT3); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc1); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 16u, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_col, .src2_vreg = -1, .imm = NT, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_col - here), .predicate_p0 = true, .predicate_not = true); - } - const int L_col_end = (int)prog->count - 1; - BW_APPEND(prog, .op = BW_IR_EXIT); - BW_APPEND(prog, .op = BW_IR_BRA); - - /* loop-carried values live to the end of their loop */ - bw_keep_alive(prog, 0, L_col, L_col_end); - bw_keep_alive(prog, L_col, L_k, L_k_end); - /* K-loop temporaries too: a load's address pair must never be recycled by a - * later instruction of the same iteration (the load may read it late). */ - bw_keep_alive(prog, L_k, L_k_end, L_k_end); - /* the accumulator is read by the stores after the K loop */ - if (prog->regalloc.intervals[v_rd].last_use < L_col_end) prog->regalloc.intervals[v_rd].last_use = L_col_end; - - return omega_bw_regalloc_solve(prog); -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_matmul_tensor_loop(const OmegaMatMulSpec *spec, uint32_t grid_x, - int mutant, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - BlackwellIRProgram prog; - if (omega_blackwell_codegen_matmul_tensor_loop_prog(spec, grid_x, mutant, &prog) != 0) return -1; - return bw_kernel_alloc_encode(&prog, OMEGA_BW_CODE_CAP_SMALL, kernel); -} -#endif - -/* ---- omega #328: fragment-major tensor matmul ---------------------------------------- - * - * The looped kernel above reads B as four scattered 2-byte loads per K step and waits for - * them before the next step (pack waits SB2), so each warp has one 256-byte step in flight; - * at m = 1 on GB10 that streams the weights at about 28 GB/s (omega #328 measurement). - * Here A and B arrive in the order HMMA.16816 consumes them (omega_matmul_frag_pack_a / _b): - * A block (mt, ks): 512 bytes, lane L at L*16: a0..a7, one LDG.E.128 per step; - * B block (nt, ks): 256 bytes, lane L at L*8: b0..b3, one LDG.E.64 per step; - * consecutive K steps of one tile are adjacent, so a warp streams its column tile. Each loop - * pass issues `unroll` steps of loads at immediate offsets (A on SB2, B on SB4), then runs the HMMA - * chain: every HMMA waits SB2 and SB4 (stall 15) and a NOP (stall 14) follows it, the 29 cycles nvcc - * puts between dependent HMMA.16816 (omega_blackwell_verify_codegen_fixtures_fragmm). - * The cursors advance only after the chain, when every load has landed (the HMMAs waited - * SB2 and SB4), as in the looped kernel. Stores, the column-tile loop and the C layout (row-major - * f32) are the looped kernel's. */ -/* A loads set SB2 and B loads SB4 (nvcc spreads loads over several scoreboards too); at the - * product unroll of 4 that is 4 loads per scoreboard per pass. The scoreboard depth is not - * documented to us; splitting did not make unroll 8 complete (omega_matmul_frag_unroll). */ -#define BW_FRAG_CTRL_LDG_A 0x000ea800u /* stall 4, yield, sets SB2 (nvcc word) */ -#define BW_FRAG_CTRL_LDG_B 0x000f2800u /* stall 4, yield, sets SB4 (nvcc word) */ -#define BW_FRAG_CTRL_HMMA 0x014fde00u /* stall 15, waits SB2 and SB4 (nvcc: dependent HMMA chain) */ -#define BW_FRAG_CTRL_NOP 0x000fdc00u /* stall 14 (nvcc, between dependent HMMAs) */ - -static void bw_live_until(BlackwellIRProgram *prog, int vreg, int last_idx) { - if (prog->regalloc.intervals[vreg].last_use < last_idx) prog->regalloc.intervals[vreg].last_use = last_idx; -} - -int omega_blackwell_codegen_matmul_frag_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - int mutant, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; - if (spec->m % 16 != 0 || spec->n % 8 != 0 || spec->k % 16 != 0) return -1; - if (unroll != 1 && unroll != 2 && unroll != 4 && unroll != 8) return -1; - const uint32_t K = spec->k, N = spec->n, NT = N / 8, KS = K / 16; - if (KS % unroll != 0) return -1; - const uint32_t ITERS = KS / unroll; - if (grid_x == 0 || grid_x > NT) return -1; - if (mutant && ITERS < 2) return -1; - /* every index and immediate below must fit 32 bits (rows up to OMEGA_BW_MATMUL_MAX_M) */ - if ((uint64_t)NT * KS * 32u > 0xffffffffull || (uint64_t)(OMEGA_BW_MATMUL_MAX_M / 16u) * KS * 32u > 0xffffffffull || - (uint64_t)grid_x * KS * 256u > 0xffffffffull || (uint64_t)N * 32u > 0xffffffffull || - (uint64_t)OMEGA_BW_MATMUL_MAX_M * N > 0xffffffffull) - return -1; - - omega_bw_ir_init(prog); - int v_ptr_a = omega_bw_ir_alloc_vreg64(prog), v_ptr_b = omega_bw_ir_alloc_vreg64(prog), v_ptr_c = omega_bw_ir_alloc_vreg64(prog); - int uv_desc = omega_bw_ir_alloc_uvreg64(prog); - int v_tid = omega_bw_ir_alloc_vreg(prog), v_ctaid_x = omega_bw_ir_alloc_vreg(prog), v_ctaid_y = omega_bw_ir_alloc_vreg(prog); - int v_group = omega_bw_ir_alloc_vreg(prog), v_tig = omega_bw_ir_alloc_vreg(prog), v_tcol2 = omega_bw_ir_alloc_vreg(prog); - int v_r0 = omega_bw_ir_alloc_vreg(prog), v_r1 = omega_bw_ir_alloc_vreg(prog), v_c1 = omega_bw_ir_alloc_vreg(prog); - int v_idx = omega_bw_ir_alloc_vreg(prog), v_col = omega_bw_ir_alloc_vreg(prog), v_cnt = omega_bw_ir_alloc_vreg(prog); - int v_pa = omega_bw_ir_alloc_vreg64(prog), v_pbcol = omega_bw_ir_alloc_vreg64(prog); - int v_pc0 = omega_bw_ir_alloc_vreg64(prog), v_pc1 = omega_bw_ir_alloc_vreg64(prog); - int v_pac = omega_bw_ir_alloc_vreg64(prog), v_pbc = omega_bw_ir_alloc_vreg64(prog); - int v_tc1 = omega_bw_ir_alloc_vreg64(prog), v_tc3 = omega_bw_ir_alloc_vreg64(prog); - int v_rd = omega_bw_ir_alloc_vreg128(prog); - int v_ra[8], v_rb[8]; - for (uint32_t u = 0; u < unroll; u++) { v_ra[u] = omega_bw_ir_alloc_vreg128(prog); v_rb[u] = omega_bw_ir_alloc_vreg64(prog); } - if (v_rb[unroll - 1] < 0 || v_ra[unroll - 1] < 0 || uv_desc < 0) return -1; - - const uint32_t CTRL_STG_RDBAR3 = 0x0007e200u, CTRL_IMADW_WAIT3 = 0x009fcc00u, CTRL_MOVRZ_WAIT3 = 0x008fe200u; - - /* prologue: descriptor, pointers, ids (as the looped kernel) */ - BW_APPEND(prog, .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_tid, .imm = BW_SR_TID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_c1, .imm = 1); - BW_APPEND(prog, .op = BW_IR_SHF_R, .dst_vreg = v_group, .src1_vreg = v_tid, .imm = 2); - BW_APPEND(prog, .op = BW_IR_LOP3_AND, .dst_vreg = v_tig, .src1_vreg = v_tid, .imm = 3); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_tcol2, .src1_vreg = v_tig, .src2_vreg = -1, .imm = 2, .src3_vreg = -1); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r0, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16, .src3_vreg = v_group); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 8, .src3_vreg = v_r0); - /* pa = A + (ctaid_y * KS * 32 + tid) * 16: this CTA's row tile, this lane's 16 bytes of step 0 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = KS * 32u, .src3_vreg = v_tid); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 16, .src3_vreg = v_ptr_a); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); - /* pbcol = B + (col * KS * 32 + tid) * 8: column tile col, this lane's 8 bytes of step 0 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = KS * 32u, .src3_vreg = v_tid); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 8, .src3_vreg = v_ptr_b); - /* pc0 = C + (r0*N + col*8 + tcol2)*4 ; pc1 with r1 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - - /* ---- column-tile loop ---- */ - const int L_col = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 0, .control = CTRL_MOVRZ_WAIT3); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 1); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 2); - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd, .dst_subreg = 3); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pac, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_cnt, .imm = mutant ? ITERS - 1 : ITERS); - - /* ---- K loop: `unroll` steps of loads, then the HMMA chain ---- */ - const int L_k = (int)prog->count; - for (uint32_t u = 0; u < unroll; u++) { - BW_APPEND(prog, .op = BW_IR_LDG_E_128, .dst_vreg = v_ra[u], .src1_vreg = v_pac, .src2_vreg = -1, .src3_vreg = -1, - .ureg = uv_desc, .imm = u * 512u, .control = BW_FRAG_CTRL_LDG_A); - BW_APPEND(prog, .op = BW_IR_LDG_E_64, .dst_vreg = v_rb[u], .src1_vreg = v_pbc, .src2_vreg = -1, .src3_vreg = -1, - .ureg = uv_desc, .imm = u * 256u, .control = BW_FRAG_CTRL_LDG_B); - } - const BlackwellIROpcode hmma = (spec->precision == OMEGA_MATMUL_PRECISION_BF16) ? BW_IR_HMMA_BF16 : BW_IR_HMMA_F16; - for (uint32_t u = 0; u < unroll; u++) { - BW_APPEND(prog, .op = hmma, .dst_vreg = v_rd, .src1_vreg = v_ra[u], .src2_vreg = v_rb[u], .src3_vreg = v_rd, - .control = BW_FRAG_CTRL_HMMA); - BW_APPEND(prog, .op = BW_IR_NOP, .dst_vreg = -1, .src1_vreg = -1, .src2_vreg = -1, .src3_vreg = -1, .ureg = -1, - .control = BW_FRAG_CTRL_NOP); - } - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pac, .src1_vreg = v_c1, .src2_vreg = -1, .imm = unroll * 512u, .src3_vreg = v_pac); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = unroll * 256u, .src3_vreg = v_pbc); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_cnt, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0xffffffffu, .src3_vreg = v_cnt); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_cnt, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_k - here), .predicate_p0 = true); - } - const int L_k_end = (int)prog->count - 1; - - /* ---- store the 16x8 tile (as the looped kernel) ---- */ - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc0); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_tc3, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 4, .src3_vreg = v_pc1); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc0, .src2_vreg = v_rd, .src2_subreg = 0, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc1, .src2_vreg = v_rd, .src2_subreg = 1, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc1, .src2_vreg = v_rd, .src2_subreg = 2, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_tc3, .src2_vreg = v_rd, .src2_subreg = 3, .src3_vreg = -1, .ureg = uv_desc, .control = CTRL_STG_RDBAR3); - /* next column tile: col += grid_x ; C by grid_x*8 f32 (waits SB3 first) ; B by grid_x tiles of KS*256 bytes */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x, .src3_vreg = v_col); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc0, .control = CTRL_IMADW_WAIT3); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * 32u, .src3_vreg = v_pc1); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * KS * 256u, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_col, .src2_vreg = -1, .imm = NT, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_col - here), .predicate_p0 = true, .predicate_not = true); - } - const int L_col_end = (int)prog->count - 1; - BW_APPEND(prog, .op = BW_IR_EXIT); - BW_APPEND(prog, .op = BW_IR_BRA); - - /* Loop-carried values live to the end of their loop (the allocator knows no back edges). - * Only these are read in a later pass than the one that wrote them; prologue temporaries - * are dead before the first loop and may be reused. K-loop temporaries (fragments) are - * kept to the end of the pass, as in the looped kernel. */ - const int col_carried[] = { v_c1, v_col, v_pa, v_pbcol, v_pc0, v_pc1, v_rd }; - for (size_t i = 0; i < sizeof col_carried / sizeof col_carried[0]; i++) bw_live_until(prog, col_carried[i], L_col_end); - const int k_carried[] = { v_pac, v_pbc, v_cnt }; - for (size_t i = 0; i < sizeof k_carried / sizeof k_carried[0]; i++) bw_live_until(prog, k_carried[i], L_k_end); - bw_keep_alive(prog, L_k, L_k_end, L_k_end); - return omega_bw_regalloc_solve(prog); -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_matmul_frag(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - int mutant, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - BlackwellIRProgram prog; - if (omega_blackwell_codegen_matmul_frag_prog(spec, grid_x, unroll, mutant, &prog) != 0) return -1; - return bw_kernel_alloc_encode(&prog, OMEGA_BW_CODE_CAP_SMALL, kernel); -} -#endif - -/* Capped at 4: unroll 8 (72 registers, 16 loads per pass) never completed on the GB10, with all - * loads on SB2 and again with A on SB2 and B on SB4 (2026-10-07 07:50Z and 07:54Z, omega #328), - * while unroll 4 (48 registers) ran every Qwen3 decode shape correctly. Cause UNKNOWN; the next - * experiment is the unroll-4 kernel launched with 72 declared registers (one variable). */ -/* ---- 2026-10-12: row/column-blocked fragment kernel (prefill rows) ------------------------ - * - * The kernel above gives one warp one 16x8 output tile: every B fragment is streamed once per row - * tile and every A fragment once per column tile, so at m = 128 on GB10 the three Qwen3-8B prefill - * shapes move about 4.7 GB per call at the DRAM rate (128x4096x24576: 20.9 ms, 2026-10-12 baseline). - * Here one warp owns RT row tiles x CT column tiles (RT*CT accumulators) over all of K: per K step - * it loads RT A fragments and CT B fragments and runs RT*CT HMMAs, so each loaded fragment feeds - * RT (B) or CT (A) tensor ops. Same packing, grid rules and C layout as the kernel above: the A - * fragments of row tile i sit at +i*KS*512 bytes, the B fragments of column tile j at +j*KS*256, - * both immediate offsets of the same cursors; the C tile (i, j) is at +i*16*N*4 + j*32 bytes from - * the two row pointers (STG.E immediate offsets, fixtures in omega_blackwell_verify_codegen_fixtures_fragmm). - * Loads per pass stay at or under 8 (unroll*(RT+CT)), the count the proven unroll-4 kernel issues; - * unroll 8 of that kernel (16 loads per pass) never completed on the GB10 and the cause is UNKNOWN, - * so this kernel does not go past that envelope. The HMMA chain keeps the dependent-chain control - * words (stall 15 then NOP stall 14) although the RT*CT accumulators are independent: a longer stall - * is never wrong, and the loads dominate the pass. CTA = one warp, as above; a grid of - * (grid_x, row blocks); column blocks advance by grid_x per pass of the column loop. */ -/* The C store offset of the last tile (rt-1, ct-1) is a signed 24-bit STG immediate; for wide N (lm_head, - * 151936 columns) rt > 1 does not fit. Shared by the generator below and omega_matmul_frag_block_shape. */ -static int frag_block_store_fits(uint32_t rt, uint32_t ct, uint32_t n) { - return (uint64_t)(rt - 1) * 16u * n * 4u + (uint64_t)(ct - 1) * 32u + 4u < (1ull << 23); -} - -int omega_blackwell_codegen_matmul_frag_block_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - uint32_t rt, uint32_t ct, int mutant, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; - if (spec->m % 16 != 0 || spec->n % 8 != 0 || spec->k % 16 != 0) return -1; - if (rt != 1 && rt != 2 && rt != 4 && rt != 8) return -1; - if (ct != 1 && ct != 2 && ct != 4) return -1; - if (rt * ct > 16 || rt * ct < 2) return -1; /* 1x1 is the kernel above */ - if (unroll != 1 && unroll != 2) return -1; - if (unroll * (rt + ct) > 8) return -1; - const uint32_t K = spec->k, N = spec->n, NT = N / 8, KS = K / 16; - if (KS % unroll != 0 || NT % ct != 0) return -1; - const uint32_t ITERS = KS / unroll, NB = NT / ct; - if (grid_x == 0 || grid_x > NB) return -1; - if (mutant && ITERS < 2) return -1; - /* every index and immediate below must fit: 32 bits for the index arithmetic, signed 24 bits for - * the load/store offsets (rows up to OMEGA_BW_MATMUL_MAX_M) */ - if ((uint64_t)NT * KS * 32u > 0xffffffffull || (uint64_t)(OMEGA_BW_MATMUL_MAX_M / 16u) * KS * 32u > 0xffffffffull || - (uint64_t)grid_x * ct * KS * 256u > 0xffffffffull || (uint64_t)N * 32u > 0xffffffffull || - (uint64_t)OMEGA_BW_MATMUL_MAX_M * N > 0xffffffffull) - return -1; - if ((uint64_t)(rt - 1) * KS * 512u + (unroll - 1) * 512u >= (1ull << 23) || - (uint64_t)(ct - 1) * KS * 256u + (unroll - 1) * 256u >= (1ull << 23) || - !frag_block_store_fits(rt, ct, N)) - return -1; - - omega_bw_ir_init(prog); - int v_ptr_a = omega_bw_ir_alloc_vreg64(prog), v_ptr_b = omega_bw_ir_alloc_vreg64(prog), v_ptr_c = omega_bw_ir_alloc_vreg64(prog); - int uv_desc = omega_bw_ir_alloc_uvreg64(prog); - int v_tid = omega_bw_ir_alloc_vreg(prog), v_ctaid_x = omega_bw_ir_alloc_vreg(prog), v_ctaid_y = omega_bw_ir_alloc_vreg(prog); - int v_group = omega_bw_ir_alloc_vreg(prog), v_tig = omega_bw_ir_alloc_vreg(prog), v_tcol2 = omega_bw_ir_alloc_vreg(prog); - int v_r0 = omega_bw_ir_alloc_vreg(prog), v_r1 = omega_bw_ir_alloc_vreg(prog), v_c1 = omega_bw_ir_alloc_vreg(prog); - int v_idx = omega_bw_ir_alloc_vreg(prog), v_col = omega_bw_ir_alloc_vreg(prog), v_cnt = omega_bw_ir_alloc_vreg(prog); - int v_pa = omega_bw_ir_alloc_vreg64(prog), v_pbcol = omega_bw_ir_alloc_vreg64(prog); - int v_pc0 = omega_bw_ir_alloc_vreg64(prog), v_pc1 = omega_bw_ir_alloc_vreg64(prog); - int v_pac = omega_bw_ir_alloc_vreg64(prog), v_pbc = omega_bw_ir_alloc_vreg64(prog); - int v_rd[16], v_ra[2][8], v_rb[2][4]; - for (uint32_t t = 0; t < rt * ct; t++) v_rd[t] = omega_bw_ir_alloc_vreg128(prog); - for (uint32_t u = 0; u < unroll; u++) { - for (uint32_t i = 0; i < rt; i++) v_ra[u][i] = omega_bw_ir_alloc_vreg128(prog); - for (uint32_t j = 0; j < ct; j++) v_rb[u][j] = omega_bw_ir_alloc_vreg64(prog); - } - if (v_rb[unroll - 1][ct - 1] < 0 || v_ra[unroll - 1][rt - 1] < 0 || v_rd[rt * ct - 1] < 0 || uv_desc < 0) return -1; - - const uint32_t CTRL_STG_RDBAR3 = 0x0007e200u, CTRL_IMADW_WAIT3 = 0x009fcc00u, CTRL_MOVRZ_WAIT3 = 0x008fe200u; - - /* prologue: descriptor, pointers, ids (as the kernel above; a CTA's row block is rt row tiles) */ - BW_APPEND(prog, .op = BW_IR_LDCU64, .dst_vreg = uv_desc, .imm = 0x358, .is_uniform = true); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_a, .imm = 0x380); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_b, .imm = 0x388); - BW_APPEND(prog, .op = BW_IR_LDC64, .dst_vreg = v_ptr_c, .imm = 0x390); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_tid, .imm = BW_SR_TID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_x, .imm = BW_SR_CTAID_X); - BW_APPEND(prog, .op = BW_IR_S2R, .dst_vreg = v_ctaid_y, .imm = BW_SR_CTAID_Y); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_c1, .imm = 1); - BW_APPEND(prog, .op = BW_IR_SHF_R, .dst_vreg = v_group, .src1_vreg = v_tid, .imm = 2); - BW_APPEND(prog, .op = BW_IR_LOP3_AND, .dst_vreg = v_tig, .src1_vreg = v_tid, .imm = 3); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_tcol2, .src1_vreg = v_tig, .src2_vreg = -1, .imm = 2, .src3_vreg = -1); - /* r0 = ctaid_y * 16 * rt + group: row of this lane in row tile 0 of the block; r1 = r0 + 8 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r0, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = 16u * rt, .src3_vreg = v_group); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_r1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 8, .src3_vreg = v_r0); - /* pa = A + (ctaid_y * rt * KS * 32 + tid) * 16: row tile 0 of this block, this lane's 16 bytes of step 0 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_ctaid_y, .src2_vreg = -1, .imm = rt * KS * 32u, .src3_vreg = v_tid); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pa, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 16, .src3_vreg = v_ptr_a); - /* col = ctaid_x * ct: first column tile of this CTA's first column block */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_ctaid_x, .src2_vreg = -1, .imm = ct, .src3_vreg = -1); - /* pbcol = B + (col * KS * 32 + tid) * 8: column tile col, this lane's 8 bytes of step 0 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = KS * 32u, .src3_vreg = v_tid); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 8, .src3_vreg = v_ptr_b); - /* pc0 = C + (r0*N + col*8 + tcol2)*4 ; pc1 with r1 */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r0, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_r1, .src2_vreg = -1, .imm = N, .src3_vreg = v_tcol2); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_idx, .src1_vreg = v_col, .src2_vreg = -1, .imm = 8, .src3_vreg = v_idx); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_idx, .src2_vreg = -1, .imm = 4, .src3_vreg = v_ptr_c); - - /* ---- column-block loop: zero the rt*ct accumulators (the first MOV waits SB3: the previous - * block's stores have read them), rewind the K cursors ---- */ - const int L_col = (int)prog->count; - for (uint32_t t = 0; t < rt * ct; t++) - for (uint32_t s = 0; s < 4; s++) - BW_APPEND(prog, .op = BW_IR_MOV_RZ, .dst_vreg = v_rd[t], .dst_subreg = (int)s, - .control = (t == 0 && s == 0) ? CTRL_MOVRZ_WAIT3 : 0); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pac, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pa); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_MOV_IMM, .dst_vreg = v_cnt, .imm = mutant ? ITERS - 1 : ITERS); - - /* ---- K loop: `unroll` steps of (rt A + ct B) loads, then the rt*ct*unroll HMMAs ---- */ - const int L_k = (int)prog->count; - for (uint32_t u = 0; u < unroll; u++) { - for (uint32_t i = 0; i < rt; i++) - BW_APPEND(prog, .op = BW_IR_LDG_E_128, .dst_vreg = v_ra[u][i], .src1_vreg = v_pac, .src2_vreg = -1, .src3_vreg = -1, - .ureg = uv_desc, .imm = u * 512u + i * KS * 512u, .control = BW_FRAG_CTRL_LDG_A); - for (uint32_t j = 0; j < ct; j++) - BW_APPEND(prog, .op = BW_IR_LDG_E_64, .dst_vreg = v_rb[u][j], .src1_vreg = v_pbc, .src2_vreg = -1, .src3_vreg = -1, - .ureg = uv_desc, .imm = u * 256u + j * KS * 256u, .control = BW_FRAG_CTRL_LDG_B); - } - const BlackwellIROpcode hmma = (spec->precision == OMEGA_MATMUL_PRECISION_BF16) ? BW_IR_HMMA_BF16 : BW_IR_HMMA_F16; - for (uint32_t u = 0; u < unroll; u++) - for (uint32_t i = 0; i < rt; i++) - for (uint32_t j = 0; j < ct; j++) { - const int rd = v_rd[i * ct + j]; - BW_APPEND(prog, .op = hmma, .dst_vreg = rd, .src1_vreg = v_ra[u][i], .src2_vreg = v_rb[u][j], .src3_vreg = rd, - .control = BW_FRAG_CTRL_HMMA); - BW_APPEND(prog, .op = BW_IR_NOP, .dst_vreg = -1, .src1_vreg = -1, .src2_vreg = -1, .src3_vreg = -1, .ureg = -1, - .control = BW_FRAG_CTRL_NOP); - } - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pac, .src1_vreg = v_c1, .src2_vreg = -1, .imm = unroll * 512u, .src3_vreg = v_pac); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbc, .src1_vreg = v_c1, .src2_vreg = -1, .imm = unroll * 256u, .src3_vreg = v_pbc); - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_cnt, .src1_vreg = v_c1, .src2_vreg = -1, .imm = 0xffffffffu, .src3_vreg = v_cnt); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_cnt, .src2_vreg = -1, .imm = 1, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_k - here), .predicate_p0 = true); - } - const int L_k_end = (int)prog->count - 1; - - /* ---- store the rt*ct tiles: tile (i, j) at +i*16*N*4 + j*32 bytes from pc0 (rows r0) and pc1 (rows r1) ---- */ - for (uint32_t i = 0; i < rt; i++) - for (uint32_t j = 0; j < ct; j++) { - const int rd = v_rd[i * ct + j]; - const uint32_t off = i * 16u * N * 4u + j * 32u; - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc0, .src2_vreg = rd, .src2_subreg = 0, .src3_vreg = -1, .ureg = uv_desc, .imm = off, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc0, .src2_vreg = rd, .src2_subreg = 1, .src3_vreg = -1, .ureg = uv_desc, .imm = off + 4u, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc1, .src2_vreg = rd, .src2_subreg = 2, .src3_vreg = -1, .ureg = uv_desc, .imm = off, .control = CTRL_STG_RDBAR3); - BW_APPEND(prog, .op = BW_IR_STG_E, .src1_vreg = v_pc1, .src2_vreg = rd, .src2_subreg = 3, .src3_vreg = -1, .ureg = uv_desc, .imm = off + 4u, .control = CTRL_STG_RDBAR3); - } - /* next column block: col += grid_x*ct ; C by grid_x*ct*8 f32 (waits SB3 first) ; B by grid_x*ct tiles of KS*256 bytes */ - BW_APPEND(prog, .op = BW_IR_IMAD, .dst_vreg = v_col, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * ct, .src3_vreg = v_col); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc0, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * ct * 32u, .src3_vreg = v_pc0, .control = CTRL_IMADW_WAIT3); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pc1, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * ct * 32u, .src3_vreg = v_pc1); - BW_APPEND(prog, .op = BW_IR_IMAD_WIDE, .dst_vreg = v_pbcol, .src1_vreg = v_c1, .src2_vreg = -1, .imm = grid_x * ct * KS * 256u, .src3_vreg = v_pbcol); - BW_APPEND(prog, .op = BW_IR_ISETP_GE, .dst_vreg = -1, .src1_vreg = v_col, .src2_vreg = -1, .imm = NT, .src3_vreg = -1); - { - int here = (int)prog->count; - BW_APPEND(prog, .op = BW_IR_BRA, .imm = (uint32_t)(int32_t)(L_col - here), .predicate_p0 = true, .predicate_not = true); - } - const int L_col_end = (int)prog->count - 1; - BW_APPEND(prog, .op = BW_IR_EXIT); - BW_APPEND(prog, .op = BW_IR_BRA); - - /* loop-carried values live to the end of their loop (as the kernel above) */ - const int col_carried[] = { v_c1, v_col, v_pa, v_pbcol, v_pc0, v_pc1 }; - for (size_t i = 0; i < sizeof col_carried / sizeof col_carried[0]; i++) bw_live_until(prog, col_carried[i], L_col_end); - for (uint32_t t = 0; t < rt * ct; t++) bw_live_until(prog, v_rd[t], L_col_end); - const int k_carried[] = { v_pac, v_pbc, v_cnt }; - for (size_t i = 0; i < sizeof k_carried / sizeof k_carried[0]; i++) bw_live_until(prog, k_carried[i], L_k_end); - bw_keep_alive(prog, L_k, L_k_end, L_k_end); - return omega_bw_regalloc_solve(prog); -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_matmul_frag_block(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - uint32_t rt, uint32_t ct, int mutant, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - BlackwellIRProgram prog; - if (omega_blackwell_codegen_matmul_frag_block_prog(spec, grid_x, unroll, rt, ct, mutant, &prog) != 0) return -1; - return bw_kernel_alloc_encode(&prog, OMEGA_BW_CODE_CAP_MAX, kernel); -} -#endif - -/* The row and column tiles one warp owns in the blocked kernel: the largest of 4, 2, 1 dividing the - * row tiles (rt), and for rt > 1 the largest of 4, 2, 1 dividing the column tiles (ct); rt = ct = 1 - * is the single-tile kernel (decode rows). An rt whose last C tile's store offset does not fit the - * 24-bit immediate (frag_block_store_fits: wide N such as lm_head) steps down, to 1 at the end. */ -void omega_matmul_frag_block_shape(uint32_t mt, uint32_t nt, uint32_t *rt, uint32_t *ct) { - uint32_t r = mt % 4u == 0 ? 4u : mt % 2u == 0 ? 2u : 1u, c = 1u; - for (; r > 1; r /= 2u) { - c = nt % 4u == 0 ? 4u : nt % 2u == 0 ? 2u : 1u; - if (frag_block_store_fits(r, c, nt * 8u)) break; - } - *rt = r; - *ct = r > 1 ? c : 1u; -} - -/* loads per pass at or under 8 (see the kernel comment): unroll 2 only when 2*(rt+ct) fits and KS is even */ -uint32_t omega_matmul_frag_block_unroll(uint32_t kp, uint32_t rt, uint32_t ct) { - const uint32_t ks = kp / 16u; - return (ks % 2u == 0 && 2u * (rt + ct) <= 8u) ? 2u : 1u; -} - -uint32_t omega_matmul_frag_unroll(uint32_t kp) { - const uint32_t ks = kp / 16u; - return ks % 4u == 0 ? 4u : ks % 2u == 0 ? 2u : 1u; -} - -/* A block (mt, ks) holds rows 16mt..16mt+15 and columns 16ks..16ks+15 as 256 bf16 at element - * (mt*KS + ks)*256; inside the block, element (rr, cc) sits at lane*8 + e with lane = (rr%8)*4 + (cc%8)/2 - * and e = (cc/8)*4 + (rr/8)*2 + cc%2 (the HMMA.16816 A fragment order, header comment). The 256-entry - * table makes the pack a tile loop with no per-element division (2026-10-12: the per-element form with - * six divisions and a conversion call per element was ~2.5 ms per MB of activations at m = 128). */ -static uint16_t g_frag_a_tab[256]; -static void frag_a_tab_init(void) { - if (g_frag_a_tab[255]) return; - for (uint32_t rr = 0; rr < 16; rr++) - for (uint32_t cc = 0; cc < 16; cc++) - g_frag_a_tab[rr * 16 + cc] = (uint16_t)((((rr & 7u) * 4u + ((cc & 7u) >> 1)) * 8u) + (cc >> 3) * 4u + (rr >> 3) * 2u + (cc & 1u)); -} -/* bit for bit what the compiler's (__bf16)f cast gives (gpu_matmul_api_test checks it against - * omega_fp32_to_bf16 on ties, denormals, inf and NaN payloads): round to nearest even, a NaN keeps - * its top payload bits and is made quiet. gcc 13 on aarch64 emits the cast as a call to the - * soft-float routine __truncsfbf2 per element, which was most of the packing cost. */ -static inline uint16_t frag_f32_to_bf16(float f) { - uint32_t u; - memcpy(&u, &f, 4); - if ((u & 0x7f800000u) == 0x7f800000u) return (uint16_t)((u >> 16) | ((u & 0x007fffffu) ? 0x0040u : 0u)); - return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); -} -#define FRAG_PACK_A_BODY(LOAD) \ - do { \ - const uint32_t KS = kp / 16u; \ - frag_a_tab_init(); \ - memset(dst, 0, (size_t)mp * kp * sizeof *dst); \ - for (uint32_t mt = 0; mt < (m + 15u) / 16u; mt++) { \ - const uint32_t r1 = m - mt * 16u < 16u ? m - mt * 16u : 16u; \ - for (uint32_t ks = 0; ks < (k + 15u) / 16u; ks++) { \ - const uint32_t c1 = k - ks * 16u < 16u ? k - ks * 16u : 16u; \ - uint16_t *blk = dst + ((size_t)mt * KS + ks) * 256u; \ - for (uint32_t rr = 0; rr < r1; rr++) { \ - const uint16_t *tab = g_frag_a_tab + rr * 16u; \ - const size_t src = (size_t)(mt * 16u + rr) * k + ks * 16u; \ - for (uint32_t cc = 0; cc < c1; cc++) blk[tab[cc]] = LOAD(a[src + cc]); \ - } \ - } \ - } \ - } while (0) -#define FRAG_ID(x) (x) -void omega_matmul_frag_pack_a(const uint16_t *a, uint32_t m, uint32_t k, uint32_t mp, uint32_t kp, uint16_t *dst) { - FRAG_PACK_A_BODY(FRAG_ID); -} -void omega_matmul_frag_pack_a_f32(const float *a, uint32_t m, uint32_t k, uint32_t mp, uint32_t kp, uint16_t *dst) { - FRAG_PACK_A_BODY(frag_f32_to_bf16); -} - -/* Row 0 only, every column of every K block (zeros past k): for a one-row call whose buffer already - * holds zeros in rows 1..15 of every block from an earlier full pack of the same width. */ -#define FRAG_PACK_A_ROW0_BODY(LOAD) \ - do { \ - const uint32_t KS = kp / 16u; \ - frag_a_tab_init(); \ - const uint16_t *tab = g_frag_a_tab; \ - for (uint32_t ks = 0; ks < KS; ks++) { \ - uint16_t *blk = dst + (size_t)ks * 256u; \ - const uint32_t c0 = ks * 16u, c1 = k - c0 < 16u ? k - c0 : 16u; \ - for (uint32_t cc = 0; cc < c1; cc++) blk[tab[cc]] = LOAD(a[c0 + cc]); \ - for (uint32_t cc = c1; cc < 16u; cc++) blk[tab[cc]] = 0; \ - } \ - } while (0) -void omega_matmul_frag_pack_a_row0(const uint16_t *a, uint32_t k, uint32_t kp, uint16_t *dst) { - FRAG_PACK_A_ROW0_BODY(FRAG_ID); -} -size_t omega_matmul_result_sentinels(float *cd, uint32_t m, uint32_t n, uint32_t np, float poison, int set) { - /* one word per 16 x 8 fragment tile that holds a real output word: the tile's last real row and column */ - size_t count = 0; - if (m == 0 || n == 0) return 0; - const uint32_t mt = (m + 15u) / 16u, nt = (n + 7u) / 8u; - for (uint32_t ti = 0; ti < mt; ti++) { - uint32_t r = ti * 16u + 15u; if (r >= m) r = m - 1u; - float *row = cd + (size_t)r * np; - for (uint32_t tj = 0; tj < nt; tj++) { - uint32_t c = tj * 8u + 7u; if (c >= n) c = n - 1u; - if (set) { row[c] = poison; count++; } - else if (row[c] == poison) count++; - } - } - return count; -} - -void omega_matmul_frag_pack_a_row0_f32(const float *a, uint32_t k, uint32_t kp, uint16_t *dst) { - FRAG_PACK_A_ROW0_BODY(frag_f32_to_bf16); -} - -void omega_matmul_frag_pack_b(const uint16_t *b, uint32_t k, uint32_t n, uint32_t kp, - uint32_t nt0, uint32_t nt1, uint16_t *dst) { - const uint32_t KS = kp / 16u; - memset(dst, 0, (size_t)(nt1 - nt0) * KS * 128u * sizeof *dst); - for (uint32_t row = 0; row < k; row++) { - const uint32_t ks = row / 16u, rr = row % 16u, khi = rr / 8u, tig = (rr % 8u) / 2u, lo = rr % 2u; - const uint16_t *src = &b[(size_t)row * n]; - for (uint32_t nt = nt0; nt < nt1; nt++) { - const uint32_t c0 = nt * 8u; - for (uint32_t group = 0; group < 8u && c0 + group < n; group++) { - const size_t lane = group * 4u + tig; - dst[(((size_t)(nt - nt0) * KS + ks) * 32u + lane) * 4u + khi * 2u + lo] = src[c0 + group]; - } - } - } -} - -int omega_blackwell_verify_codegen_fixtures(void) { - OmegaRegAlloc ra; - memset(&ra, 0, sizeof(ra)); - ra.vreg_to_phys[0] = 2; - ra.vreg_to_phys[1] = 4; - ra.vreg_to_phys[2] = 6; - ra.vreg_to_phys[3] = 7; - ra.uvreg_to_phys[0] = 4; - - uint32_t w[4]; - - /* 1. MOV R7, RZ */ - BlackwellIRInsn insn_mov_rz = { .op = BW_IR_MOV_RZ, .dst_vreg = 3 }; - if (encode_single_insn(&insn_mov_rz, &ra, w) != 0) return -1; - if (w[0] != (0x7202 | (7 << 16)) || w[1] != 0xff || w[2] != 0x00000f00) return -2; - - /* 2. MOV R2, 1 */ - BlackwellIRInsn insn_mov_imm = { .op = BW_IR_MOV_IMM, .dst_vreg = 0, .imm = 1 }; - if (encode_single_insn(&insn_mov_imm, &ra, w) != 0) return -3; - if (w[0] != (0x7802 | (2 << 16)) || w[1] != 1 || w[2] != 0x00000f00) return -4; - - /* 3. Register-Register IMAD: IMAD R7, R2, R6, R7 */ - BlackwellIRInsn insn_imad_rr = { .op = BW_IR_IMAD, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 2, .src3_vreg = 3 }; - if (encode_single_insn(&insn_imad_rr, &ra, w) != 0) return -5; - if (w[0] != (0x7224 | (7 << 16) | (2 << 24)) || w[1] != 6 || w[2] != (0x078e0200 | 7)) return -6; - - /* 4. Immediate IMAD: IMAD R6, R2, 16, RZ */ - BlackwellIRInsn insn_imad_imm = { .op = BW_IR_IMAD, .dst_vreg = 2, .src1_vreg = 0, .src2_vreg = -1, .imm = 16, .src3_vreg = -1 }; - if (encode_single_insn(&insn_imad_imm, &ra, w) != 0) return -7; - if (w[0] != (0x7824 | (6 << 16) | (2 << 24)) || w[1] != 16 || w[2] != 0x078e02ff) return -8; - - /* 5. IMAD.WIDE: IMAD.WIDE R4, R2, 4, R4 */ - BlackwellIRInsn insn_imad_wide = { .op = BW_IR_IMAD_WIDE, .dst_vreg = 1, .src1_vreg = 0, .imm = 4, .src3_vreg = 1 }; - if (encode_single_insn(&insn_imad_wide, &ra, w) != 0) return -9; - if (w[0] != (0x7825 | (4 << 16) | (2 << 24)) || w[1] != 4 || w[2] != (0x078e0000 | 4)) return -10; - - /* 6. LDC.64 R4, c[0x0][0x380] */ - BlackwellIRInsn insn_ldc64 = { .op = BW_IR_LDC64, .dst_vreg = 1, .imm = 0x380 }; - if (encode_single_insn(&insn_ldc64, &ra, w) != 0) return -11; - if (w[0] != (0xff007b82 | (4 << 16)) || w[1] != ((0x380 << 6) & 0x00ffff00) || w[2] != 0x00000a00) return -12; - - /* 7. LDCU.64 UR4, c[0x0][0x358] */ - BlackwellIRInsn insn_ldcu64 = { .op = BW_IR_LDCU64, .dst_vreg = 0, .imm = 0x358, .is_uniform = true }; - if (encode_single_insn(&insn_ldcu64, &ra, w) != 0) return -13; - if (w[0] != (0xff0077ac | (4 << 16)) || w[1] != ((0x358 << 5) & 0x00ffff00) || w[2] != 0x08000a00) return -14; - - /* 8. LDG.E R2, desc[UR4][R4.64] */ - BlackwellIRInsn insn_ldg = { .op = BW_IR_LDG_E, .dst_vreg = 0, .src1_vreg = 1, .ureg = 0 }; - if (encode_single_insn(&insn_ldg, &ra, w) != 0) return -15; - if (w[0] != (0x7981 | (2 << 16) | (4 << 24)) || w[1] != 4 || w[2] != 0x0c1e1900) return -16; - - /* 9. STG.E desc[UR4][R4.64], R7 */ - BlackwellIRInsn insn_stg = { .op = BW_IR_STG_E, .src1_vreg = 1, .src2_vreg = 3, .ureg = 0 }; - if (encode_single_insn(&insn_stg, &ra, w) != 0) return -17; - if (w[0] != (0x7986 | (4 << 24)) || w[1] != 7 || w[2] != (0x0c101900 | 4)) return -18; - - /* 10. S2R R2, SR_CTAID.X */ - BlackwellIRInsn insn_s2r = { .op = BW_IR_S2R, .dst_vreg = 0, .imm = BW_SR_CTAID_X }; - if (encode_single_insn(&insn_s2r, &ra, w) != 0) return -19; - if (w[0] != (0x7919 | (2 << 16)) || w[2] != (BW_SR_CTAID_X << 8)) return -20; - - /* 11. HMMA.16816.F32 R4, R4, R2, RZ */ - BlackwellIRInsn insn_hmma_f16 = { .op = BW_IR_HMMA_F16, .dst_vreg = 1, .src1_vreg = 1, .src2_vreg = 0, .src3_vreg = -1 }; - if (encode_single_insn(&insn_hmma_f16, &ra, w) != 0) return -21; - if (w[0] != 0x0404723c || w[1] != 0x00000002 || w[2] != 0x000018ff || w[3] != 0x000fe200) return -22; - - /* 12. HMMA.16816.F32.BF16 R4, R4, R2, RZ */ - BlackwellIRInsn insn_hmma_bf16 = { .op = BW_IR_HMMA_BF16, .dst_vreg = 1, .src1_vreg = 1, .src2_vreg = 0, .src3_vreg = -1 }; - uint32_t w_bf16[4]; - if (encode_single_insn(&insn_hmma_bf16, &ra, w_bf16) != 0) return -23; - if (w_bf16[0] != 0x0404723c || w_bf16[1] != 0x00000002 || w_bf16[2] != 0x000418ff || w_bf16[3] != 0x000fe200) return -24; - - /* 13. Differential Invariant: w[2] bit 18 toggles strictly between FP16 and BF16 */ - if ((w[2] ^ w_bf16[2]) != 0x00040000) return -25; - if (w[0] != w_bf16[0] || w[1] != w_bf16[1] || w[3] != w_bf16[3]) return -26; - - /* 14. SHF.R.U32.HI R4, RZ, 2, R2 */ - BlackwellIRInsn insn_shf = { .op = BW_IR_SHF_R, .dst_vreg = 1, .src1_vreg = 0, .imm = 2 }; - if (encode_single_insn(&insn_shf, &ra, w) != 0) return -27; - if (w[0] != 0xff047819 || w[1] != 2 || w[2] != 0x00011602 || w[3] != 0x001fca00) return -28; - - /* 15. LOP3.LUT R4, R2, 3, RZ, 0xc0, !PT */ - BlackwellIRInsn insn_lop3 = { .op = BW_IR_LOP3_AND, .dst_vreg = 1, .src1_vreg = 0, .imm = 3 }; - if (encode_single_insn(&insn_lop3, &ra, w) != 0) return -29; - if (w[0] != 0x02047812 || w[1] != 3 || w[2] != 0x078ec0ff || w[3] != 0x001fca00) return -30; - - /* 16. LDG.E.U16 R2, desc[UR4][R4.64] */ - BlackwellIRInsn insn_ldg16 = { .op = BW_IR_LDG_E_U16, .dst_vreg = 0, .src1_vreg = 1, .ureg = 0 }; - if (encode_single_insn(&insn_ldg16, &ra, w) != 0) return -31; - if (w[0] != 0x04027981 || w[1] != 4 || w[2] != 0x0c1e1500 || w[3] != 0x000f2200) return -32; - - /* A zero-delta branch stays the self-branch the matmul kernels already emit. */ - BlackwellIRInsn insn_bra0 = { .op = BW_IR_BRA }; - if (encode_single_insn(&insn_bra0, &ra, w) != 0) return -33; - if (w[0] != 0x00fc7947 || w[1] != 0xfffffffc || w[2] != 0x0383ffff || w[3] != 0x000fc000) return -34; - - BlackwellIRInsn insn_ge = { .op = BW_IR_ISETP_GE_U32, .src1_vreg = 1, .src2_vreg = 2 }; - if (encode_single_insn(&insn_ge, &ra, w) != 0) return -35; - if (w[0] != (0x720c | (4 << 24)) || w[1] != 6 || w[2] != 0x03f06070) return -36; - - BlackwellIRInsn insn_xor = { .op = BW_IR_LOP3_XOR, .dst_vreg = 1, .src1_vreg = 0, .src2_vreg = 2 }; - if (encode_single_insn(&insn_xor, &ra, w) != 0) return -37; - if (w[0] != (0x7212 | (4 << 16) | (2 << 24)) || w[1] != 6 || w[2] != 0x078e3cff) return -38; - - BlackwellIRInsn insn_ldg_ss = { .op = BW_IR_LDG_STRONG_SYS, .dst_vreg = 0, .src1_vreg = 1, .ureg = 0 }; - if (encode_single_insn(&insn_ldg_ss, &ra, w) != 0) return -39; - if (w[0] != (0x7981 | (2 << 16) | (4 << 24)) || w[1] != 4 || w[2] != 0x0c1f5900) return -40; - /* 17. FADD R7, R2, R4 */ - BlackwellIRInsn insn_fadd = { .op = BW_IR_FADD, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1 }; - if (encode_single_insn(&insn_fadd, &ra, w) != 0) return -133; - if (w[0] != 0x02077221 || w[1] != 4 || w[2] != 0 || w[3] != 0x004fc400) return -134; - - /* 18. FSUB R7, R2, R4 (negated src2) */ - BlackwellIRInsn insn_fsub = { .op = BW_IR_FSUB, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1 }; - if (encode_single_insn(&insn_fsub, &ra, w) != 0) return -135; - if (w[0] != 0x02077221 || w[1] != 0x80000004 || w[2] != 0 || w[3] != 0x004fc400) return -136; - - /* 19. FMUL R7, R2, R4 */ - BlackwellIRInsn insn_fmul = { .op = BW_IR_FMUL, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1 }; - if (encode_single_insn(&insn_fmul, &ra, w) != 0) return -137; - if (w[0] != 0x02077220 || w[1] != 4 || w[2] != 0x00400000 || w[3] != 0x004fc400) return -138; - - /* 20. FFMA R7, R2, R4, R6 */ - BlackwellIRInsn insn_ffma = { .op = BW_IR_FFMA, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1, .src3_vreg = 2 }; - if (encode_single_insn(&insn_ffma, &ra, w) != 0) return -139; - if (w[0] != 0x02077223 || w[1] != 4 || w[2] != 6 || w[3] != 0x004fc400) return -140; - - /* 21. FMNMX_MIN R7, R2, R4 */ - BlackwellIRInsn insn_min = { .op = BW_IR_FMNMX_MIN, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1 }; - if (encode_single_insn(&insn_min, &ra, w) != 0) return -141; - if (w[0] != 0x02077209 || w[1] != 4 || w[2] != 0x03800000 || w[3] != 0x004fc400) return -142; - - /* 22. FMNMX_MAX R7, R2, R4 */ - BlackwellIRInsn insn_max = { .op = BW_IR_FMNMX_MAX, .dst_vreg = 3, .src1_vreg = 0, .src2_vreg = 1 }; - if (encode_single_insn(&insn_max, &ra, w) != 0) return -143; - if (w[0] != 0x02077209 || w[1] != 4 || w[2] != 0x07800000 || w[3] != 0x004fc400) return -144; - - /* 23. I2FP R7, R2 */ - BlackwellIRInsn insn_i2f = { .op = BW_IR_I2FP, .dst_vreg = 3, .src1_vreg = 0 }; - if (encode_single_insn(&insn_i2f, &ra, w) != 0) return -145; - if (w[0] != 0x00077245 || w[1] != 2 || w[2] != 0x00201400 || w[3] != 0x004fe200) return -146; - - /* 24. F2I R7, R2 */ - BlackwellIRInsn insn_f2i = { .op = BW_IR_F2I, .dst_vreg = 3, .src1_vreg = 0 }; - if (encode_single_insn(&insn_f2i, &ra, w) != 0) return -147; - if (w[0] != 0x00077305 || w[1] != 2 || w[2] != 0x0020f100 || w[3] != 0x004e2200) return -148; - - /* 25. MUFU_RCP R7, R2 */ - BlackwellIRInsn insn_mufu_rcp = { .op = BW_IR_MUFU_RCP, .dst_vreg = 3, .src1_vreg = 0 }; - if (encode_single_insn(&insn_mufu_rcp, &ra, w) != 0) return -149; - if (w[0] != 0x00077308 || w[1] != 2 || w[2] != 0x00001000 || w[3] != 0x000e2400) return -150; - - /* 26. MUFU_RSQ R7, R2 */ - BlackwellIRInsn insn_mufu_rsq = { .op = BW_IR_MUFU_RSQ, .dst_vreg = 3, .src1_vreg = 0 }; - if (encode_single_insn(&insn_mufu_rsq, &ra, w) != 0) return -151; - if (w[0] != 0x00077308 || w[1] != 2 || w[2] != 0x00001400 || w[3] != 0x000e2400) return -152; - - /* 27. SHFL_DOWN R7, R2, 16 */ - BlackwellIRInsn insn_shfl = { .op = BW_IR_SHFL_DOWN, .dst_vreg = 3, .src1_vreg = 0, .imm = 16 }; - if (encode_single_insn(&insn_shfl, &ra, w) != 0) return -153; - if (w[0] != 0x02077f89 || w[1] != 0x0a001f00 || w[2] != 0x000e0000 || w[3] != 0x000e2400) return -154; - - /* 28. LDS R7, [R2] */ - BlackwellIRInsn insn_lds = { .op = BW_IR_LDS, .dst_vreg = 3, .src1_vreg = 0, .imm = 0 }; - if (encode_single_insn(&insn_lds, &ra, w) != 0) return -155; - if (w[0] != 0x02077984 || w[1] != 0 || w[2] != 0 || w[3] != 0x000fe200) return -156; - - /* 29. STS [R2], R4 */ - BlackwellIRInsn insn_sts = { .op = BW_IR_STS, .src1_vreg = 0, .src2_vreg = 1, .imm = 0 }; - if (encode_single_insn(&insn_sts, &ra, w) != 0) return -157; - if (w[0] != 0x02007388 || w[1] != 4 || w[2] != 0 || w[3] != 0x000fe200) return -158; - - return 0; -} - -int omega_blackwell_test_regalloc_bounds(void) { - BlackwellIRProgram prog; - omega_bw_ir_init(&prog); - - int v0 = omega_bw_ir_alloc_vreg64(&prog); - int v1 = omega_bw_ir_alloc_vreg(&prog); - int v2 = omega_bw_ir_alloc_vreg64(&prog); - int v3 = omega_bw_ir_alloc_vreg128(&prog); /* Test 128-bit quad allocation */ - - BlackwellIRInsn i0 = { .op = BW_IR_LDC64, .dst_vreg = v0, .imm = 0x380 }; - omega_bw_ir_append(&prog, &i0); - BlackwellIRInsn i1 = { .op = BW_IR_MOV_IMM, .dst_vreg = v1, .imm = 10 }; - omega_bw_ir_append(&prog, &i1); - BlackwellIRInsn i2 = { .op = BW_IR_LDC64, .dst_vreg = v2, .imm = 0x388 }; - omega_bw_ir_append(&prog, &i2); - BlackwellIRInsn i3 = { .op = BW_IR_HMMA_F16, .dst_vreg = v3, .src1_vreg = v3, .src2_vreg = v0, .src3_vreg = -1 }; - omega_bw_ir_append(&prog, &i3); - /* i4 uses v1, v2, v3 simultaneously so all intervals are concurrently active */ - int v_sink = omega_bw_ir_alloc_vreg(&prog); - BlackwellIRInsn i4 = { .op = BW_IR_IADD3, .dst_vreg = v_sink, .src1_vreg = v1, .src2_vreg = v2, .src3_vreg = v3 }; - omega_bw_ir_append(&prog, &i4); - - if (omega_bw_regalloc_solve(&prog) != 0) return -1; - - int phys_v0 = prog.regalloc.vreg_to_phys[v0]; - int phys_v1 = prog.regalloc.vreg_to_phys[v1]; - int phys_v2 = prog.regalloc.vreg_to_phys[v2]; - int phys_v3 = prog.regalloc.vreg_to_phys[v3]; - - if (phys_v0 % 2 != 0) return -2; - if (phys_v2 % 2 != 0) return -3; - if (phys_v3 % 4 != 0) return -4; /* 4-alignment for 128-bit quad */ - if (phys_v1 == phys_v0 || phys_v1 == phys_v0 + 1) return -5; - if (phys_v2 == phys_v0 || phys_v2 == phys_v0 + 1) return -6; - for (int k = 0; k < 4; k++) { - if (phys_v3 + k == phys_v0 || phys_v3 + k == phys_v0 + 1) return -7; - if (phys_v3 + k == phys_v2 || phys_v3 + k == phys_v2 + 1) return -8; - if (phys_v3 + k == phys_v1) return -9; - } - - /* Test bounds refusal: intentionally attempt to allocate more registers than hardware capacity */ - BlackwellIRProgram overflow_prog; - omega_bw_ir_init(&overflow_prog); - for (int i = 0; i < BW_PHYS_GPR_MAX + 5; i++) { - int v = omega_bw_ir_alloc_vreg(&overflow_prog); - if (v < 0) break; - BlackwellIRInsn insn = { .op = BW_IR_MOV_IMM, .dst_vreg = v, .imm = (uint32_t)i }; - omega_bw_ir_append(&overflow_prog, &insn); - } - for (size_t i = 0; i < overflow_prog.count; i++) { - for (int v = 0; v < overflow_prog.regalloc.num_vregs; v++) { - overflow_prog.regalloc.intervals[v].last_use = (int)overflow_prog.count - 1; - } - } - if (omega_bw_regalloc_solve(&overflow_prog) == 0) { - return -6; - } - - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX /* prints: hosted only (the freestanding build has no stdio) */ -int omega_blackwell_test_codegen_variation(void) { - OmegaMatMulSpec spec1, spec2; - if (omega_matmul_spec_init(&spec1, 16, 16, 16, OMEGA_MATMUL_PRECISION_INT32) != 0) { - printf("FAIL: spec1 init failed\n"); - return -1; - } - if (omega_matmul_spec_init(&spec2, 32, 16, 64, OMEGA_MATMUL_PRECISION_INT32) != 0) { - printf("FAIL: spec2 init failed\n"); - return -1; - } - - OmegaBlackwellKernel k1, k2; - memset(&k1, 0, sizeof(k1)); - memset(&k2, 0, sizeof(k2)); - - if (omega_blackwell_codegen_matmul(&spec1, &k1) != 0) { - printf("FAIL: k1 codegen failed\n"); - return -1; - } - if (omega_blackwell_codegen_matmul(&spec2, &k2) != 0) { - printf("FAIL: k2 codegen failed\n"); - omega_blackwell_kernel_free(&k1); - return -1; - } - - OmegaBlackwellRealizationIdentity id1, id2; - omega_blackwell_bind_matmul_realization(&spec1, &k1, &id1); - omega_blackwell_bind_matmul_realization(&spec2, &k2, &id2); - - printf("================================================================================\n"); - printf(" OMEGA BLACKWELL CODEGEN VARIATION DEMONSTRATION (GATE 7 STAGE-1)\n"); - printf("================================================================================\n"); - printf("Config 1: 16x16x16 INT32\n"); - printf(" Instructions: %zu (%zu bytes, %u GPRs, %u UGPRs)\n", k1.insn_count, k1.code_size, k1.gpr_count, k1.uniform_gpr_count); - printf(" Spec ID: "); - for (int i = 0; i < 16; i++) printf("%02x", spec1.spec_id[i]); - printf("...\n"); - printf(" Code Digest: "); - for (int i = 0; i < 16; i++) printf("%02x", k1.code_digest[i]); - printf("...\n"); - printf(" Realization: "); - for (int i = 0; i < 16; i++) printf("%02x", id1.realization_id[i]); - printf("...\n\n"); - - printf("Config 2: 32x16x64 INT32\n"); - printf(" Instructions: %zu (%zu bytes, %u GPRs, %u UGPRs)\n", k2.insn_count, k2.code_size, k2.gpr_count, k2.uniform_gpr_count); - printf(" Spec ID: "); - for (int i = 0; i < 16; i++) printf("%02x", spec2.spec_id[i]); - printf("...\n"); - printf(" Code Digest: "); - for (int i = 0; i < 16; i++) printf("%02x", k2.code_digest[i]); - printf("...\n"); - printf(" Realization: "); - for (int i = 0; i < 16; i++) printf("%02x", id2.realization_id[i]); - printf("...\n"); - printf("================================================================================\n"); - - /* Validation checks */ - if (memcmp(spec1.spec_id, spec2.spec_id, 32) == 0) { - printf("FAIL: spec IDs match (expected distinct)\n"); - return -2; - } - if (memcmp(k1.code_digest, k2.code_digest, 32) == 0) { - printf("FAIL: code digests match (expected distinct)\n"); - return -3; - } - if (memcmp(id1.realization_id, id2.realization_id, 32) == 0) { - printf("FAIL: realization IDs match (expected distinct)\n"); - return -4; - } - - printf("PASS: Dynamic codegen variation verified (distinct specifications, code digests, and realization IDs).\n"); - - omega_blackwell_kernel_free(&k1); - omega_blackwell_kernel_free(&k2); - return 0; -} -#endif - -/* Declared registers: peak + 2 rounded up to 8 (see omega_blackwell_codegen.h for the chip evidence). */ -uint32_t omega_bw_gpr_declared(uint32_t peak) { return ((peak + 2u + 7u) / 8u) * 8u; } -int omega_bw_gpr_declared_ok(uint32_t declared, uint32_t peak) { return declared % 8u == 0u && declared >= peak + 2u; } diff --git a/src/omega_blackwell_codegen.h b/src/omega_blackwell_codegen.h deleted file mode 100644 index cc36e237d..000000000 --- a/src/omega_blackwell_codegen.h +++ /dev/null @@ -1,333 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_H -#define OMEGA_BLACKWELL_CODEGEN_H - -#include -#include -#include -#include "omega_blackwell_matmul.h" - -#define BW_MAX_IR_INSNS 1024 /* cut K: the four-head hd 128 attention kernel is ~700 instructions */ -#define BW_MAX_VREGS 256 -#define BW_MAX_UVREGS 32 -#define BW_PHYS_GPR_START 2 /* Reserve R0, R1 */ -#define BW_PHYS_GPR_MAX 128 -#define BW_PHYS_UGPR_START 4 /* Reserve UR0-UR3 */ -#define BW_PHYS_UGPR_MAX 32 - -/* Minimal Blackwell IR Opcodes for Stage 1 & Stage 2 */ -typedef enum { - BW_IR_NOP = 0, - BW_IR_MOV_RZ, /* MOV Rd, RZ (zero initialization) */ - BW_IR_MOV_IMM, /* MOV Rd, imm32 */ - BW_IR_S2R, /* S2R Rd, SR */ - BW_IR_LDC, /* LDC Rd, c[bank][offset] */ - BW_IR_LDC64, /* LDC.64 Rd:Rd+1, c[bank][offset] */ - BW_IR_LDCU, /* LDCU URd, c[bank][offset] */ - BW_IR_LDCU64, /* LDCU.64 URd:URd+1, c[bank][offset] */ - BW_IR_IMAD, /* IMAD Rd, Ra, Rb/imm, Rc (multiply-add) */ - BW_IR_IMAD_WIDE, /* IMAD.WIDE.U32 Rd:Rd+1, Ra, imm, Rc:Rc+1 */ - BW_IR_ISETP_GE, /* ISETP.GE P0, PT, Ra, Rb/imm, PT */ - BW_IR_LDG_E, /* LDG.E Rd, desc[URd][Ra.64] */ - BW_IR_STG_E, /* STG.E desc[URd][Ra.64], Rb */ - BW_IR_STG_EF, /* STG.E.EF: evict the line so the other side can see it */ - BW_IR_IADD3, /* IADD3 Rd, PT, PT, Ra, Rb, Rc */ - BW_IR_HMMA_F16, /* HMMA.16816.F32 Rd, Ra, Rb, Rc (FP16 input, FP32 accumulator) */ - BW_IR_HMMA_BF16, /* HMMA.16816.F32.BF16 Rd, Ra, Rb, Rc (BF16 input, FP32 accumulator) */ - BW_IR_SHF_R, /* SHF.R.U32.HI Rd, RZ, imm, Ra */ - BW_IR_LOP3_AND, /* LOP3.LUT Rd, Ra, imm, RZ, 0xc0, !PT (Bitwise AND) */ - BW_IR_LDG_E_U16, /* LDG.E.U16 Rd, desc[URd][Ra.64] */ - /* System-scope ordering. Encodings checked against the sm_121 disassembler. - * A host build of these opcodes is not a graphics-chip result. */ - BW_IR_LDG_STRONG_SYS, - BW_IR_LDG_MMIO, /* LDG.E.MMIO.GPU: do not keep a stale cached copy */ - BW_IR_STG_STRONG_SYS, - BW_IR_MEMBAR_ALL_SYS, - BW_IR_MEMBAR_SC_SYS, - BW_IR_CCTL_IVALL, - BW_IR_ATOMG_ADD_STRONG_SYS, - BW_IR_ATOMG_EXCH_STRONG_SYS, - BW_IR_ISETP_GE_U32, /* ISETP.GE.U32.AND P0, PT, Ra, Rb, PT */ - BW_IR_LOP3_XOR, /* LOP3.LUT Rd, Ra, Rb, RZ, 0x3c, !PT */ - BW_IR_FADD, /* FADD Rd, Ra, Rb */ - BW_IR_FSUB, /* FSUB Rd, Ra, Rb (FADD Rd, Ra, -Rb) */ - BW_IR_FMUL, /* FMUL Rd, Ra, Rb */ - BW_IR_FFMA, /* FFMA Rd, Ra, Rb, Rc (Rd = Ra * Rb + Rc) */ - BW_IR_FSETP, /* FSETP.cond.AND P0, PT, Ra, Rb, PT */ - BW_IR_FSEL, /* FSEL Rd, Ra, Rb, P0 */ - BW_IR_FMNMX_MIN, /* FMNMX Rd, Ra, Rb, PT (minimum) */ - BW_IR_FMNMX_MAX, /* FMNMX Rd, Ra, Rb, !PT (maximum) */ - BW_IR_I2FP, /* I2FP.F32.S32 Rd, Ra */ - BW_IR_F2I, /* F2I.TRUNC.NTZ Rd, Ra */ - BW_IR_MUFU_RCP, /* MUFU.RCP Rd, Ra */ - BW_IR_MUFU_RSQ, /* MUFU.RSQ Rd, Ra */ - BW_IR_SHFL_DOWN, /* SHFL.DOWN PT, Rd, Ra, offset, 0x1f */ - BW_IR_LDS, /* LDS Rd, [Ra] */ - BW_IR_STS, /* STS [Ra], Rb */ - BW_IR_EXIT, /* EXIT */ - BW_IR_BRA, /* BRA. imm = signed instruction delta; predicate_p0 / predicate_not select @P0 or @!P0 */ - /* FB-1 cut 4 (2026-10-04), additive. Encodings decoded with nvdisasm 13.0 -b SM121 - * (tools/divsqrt_nvdisasm_check.sh method); the BAR/LDS/STS words are the ones - * src/omega_numeric.c:884-886 runs on the chip (LDS_STS op, 148/148 specs PASS). */ - BW_IR_MUFU_EX2, /* MUFU.EX2 Rd, Ra (2^x, approximate: PTX ex2.approx.f32 bound 2^-22.5 rel) */ - BW_IR_BAR_SYNC, /* BAR.SYNC.DEFER_BLOCKING 0x0 (CTA barrier 0; the QMD declares 1 barrier) */ - BW_IR_LDS32, /* LDS Rd, [Ra+URZ] 32-bit shared load (BW_IR_LDS encodes LDS.U8: byte) */ - BW_IR_STS32, /* STS [Ra+URZ], Rb 32-bit shared store (BW_IR_STS encodes STS.U8: byte) */ - /* Prime race cut (2026-10-05), additive, general integer ops. Words derived from the - * register forms of LOP3_XOR / SHF_R / IMAD and matched word for word against - * nvcc 13.0.88 -arch=sm_121 -cubin + cuobjdump -sass (offline oracle only; see - * omega_blackwell_verify_codegen_fixtures_intops). For these three ops an operand - * vreg of -1 encodes RZ (not R0). */ - BW_IR_LOP3_LUT, /* LOP3.LUT Rd, Ra, Rb, Rc, imm8, !PT: Rd = LUT(Ra, Rb, Rc). imm & 0xff is the - * truth table over Ra = 0xf0, Rb = 0xcc, Rc = 0xaa (a|b = 0xfc, ~(a|b) = 0x03) */ - BW_IR_SHF_L_U32, /* SHF.L.U32 Rd, Ra, Rb, RZ: Rd = Ra << Rb, register amount (the form nvcc emits - * for PTX shl.b32). Amounts >= 32 are NOT chip-verified: callers keep Rb < 32 */ - BW_IR_IMAD_HI_U32, /* IMAD.HI.U32 Rd, Ra, Rb, Rc: Rd = hi32(Ra * Rb) + Rc mod 2^32 (nvcc emits this - * word for __umulhi(a, b) + c) */ - /* Structured warp reconvergence (omega #308, 2026-10-05), additive. Words matched against - * nvcc 13.0.88 -arch=sm_121 output (BSSY.RECONVERGENT / BSYNC.RECONVERGENT; the oracle - * kernels are listed in docs/gpu-reconvergence-308.md) and the Mesa NAK encoder - * (sm70_encode.rs OpBSSy 0x945 / OpBSync 0x941, barrier register at bits 16..19). - * bar_reg selects B0..B15. BSSY arms the barrier for the lanes executing it and names - * the join point; BSYNC waits for every armed lane that has not exited, then the warp - * continues as one. imm of BSSY = signed instruction delta to the join point (the - * instruction after the BSYNC), like BW_IR_BRA; the encoder refuses deltas < 1. */ - BW_IR_BSSY, - BW_IR_BSYNC, - /* Fragment-major matmul (omega #328, 2026-10-07), additive. Words matched against nvcc 13.0.88 - * -arch=sm_121 (omega_blackwell_verify_codegen_fixtures_fragmm). imm = signed byte offset, - * -2^23 .. 2^23-1; dst is a register pair (64) or an aligned quad (128). */ - BW_IR_LDG_E_64, /* LDG.E.64 Rd:Rd+1, desc[URd][Ra.64+imm] */ - BW_IR_LDG_E_128, /* LDG.E.128 Rd..Rd+3, desc[URd][Ra.64+imm] */ - /* Batched attention loads (2026-10-12). Words matched against nvcc 13.0.88 -arch=sm_121 - * (omega_blackwell_verify_codegen_fixtures_fragmm). imm = unsigned byte offset < 2^23; dst an aligned quad. */ - BW_IR_LDS128 /* LDS.128 Rd..Rd+3, [Ra+imm] */ -} BlackwellIROpcode; - -/* Barrier (reconvergence) registers: the sm_121 BSSY/BSYNC words carry a 4-bit barrier id - * (NAK sm70_encode.rs set_bar_dst(16..20)), so B0..B15 are encodable. How many the chip - * provides is not documented to us; chip tests nest to BW_RECONV_CHIP_TESTED_DEPTH. */ -#define BW_RECONV_MAX_BAR 16 - -/* Special Register Identifiers */ -typedef enum { - BW_SR_TID_X = 0x21, - BW_SR_TID_Y = 0x22, - BW_SR_CTAID_X = 0x25, - BW_SR_CTAID_Y = 0x26 -} BlackwellSR; - -/* IR Instruction Node */ -typedef struct { - BlackwellIROpcode op; - int dst_vreg; /* Virtual destination register (-1 if none) */ - int src1_vreg; /* Virtual source 1 register (-1 if none) */ - int src2_vreg; /* Virtual source 2 register (-1 if none / immediate mode) */ - int src3_vreg; /* Virtual source 3 register (-1 if none / RZ) */ - int ureg; /* Uniform register (-1 if none) */ - uint32_t imm; /* Immediate value / constant bank offset / SR code. - * For BW_IR_BRA: signed instruction delta (target minus - * this instruction). 0 branches to itself. */ - uint32_t control; /* Bundle control word */ - bool is_uniform; /* True if targets/uses uniform registers */ - bool predicate_p0; /* True if predicated on P0 */ - bool predicate_not; /* With predicate_p0, encode @!P0 */ - uint8_t dst_subreg; /* Subregister offset (0..3) within register bundle */ - uint8_t src1_subreg; - uint8_t src2_subreg; - uint8_t src3_subreg; - uint8_t bar_reg; /* BW_IR_BSSY / BW_IR_BSYNC: barrier register B0..B15 */ -} BlackwellIRInsn; - -/* Live Interval for Bounded Linear Register Allocation */ -typedef struct { - int vreg; - int first_def; - int last_use; - int phys_reg; - uint32_t bundle_size; /* 1: scalar (32-bit), 2: pair (64-bit), 4: quad (128-bit) */ - bool is_pair; /* True if 64-bit register pair (requires even-aligned R_2k) */ - bool is_quad; /* True if 128-bit register quad (requires 4-aligned R_4k) */ - bool active; -} OmegaLiveInterval; - -/* Register Allocator State */ -typedef struct { - int num_vregs; - int num_uvregs; - OmegaLiveInterval intervals[BW_MAX_VREGS]; - OmegaLiveInterval uintervals[BW_MAX_UVREGS]; - int vreg_to_phys[BW_MAX_VREGS]; - int uvreg_to_phys[BW_MAX_UVREGS]; - uint32_t peak_gpr_usage; - uint32_t peak_ugpr_usage; -} OmegaRegAlloc; - -/* IR Program */ -typedef struct { - BlackwellIRInsn insns[BW_MAX_IR_INSNS]; - size_t count; - OmegaRegAlloc regalloc; -} BlackwellIRProgram; - -/* Initializes IR program */ -void omega_bw_ir_init(BlackwellIRProgram *prog); - -/* Appends an instruction node to IR program */ -int omega_bw_ir_append(BlackwellIRProgram *prog, const BlackwellIRInsn *insn); - -/* Allocates a new 32-bit virtual general-purpose register */ -int omega_bw_ir_alloc_vreg(BlackwellIRProgram *prog); - -/* Allocates a new 64-bit aligned virtual register pair (for 64-bit memory addresses or HMMA B matrix) */ -int omega_bw_ir_alloc_vreg64(BlackwellIRProgram *prog); - -/* Allocates a new 128-bit aligned virtual register quad (for HMMA accumulator and A matrix) */ -int omega_bw_ir_alloc_vreg128(BlackwellIRProgram *prog); - -/* Allocates a new 32-bit virtual uniform register */ -int omega_bw_ir_alloc_uvreg(BlackwellIRProgram *prog); - -/* Allocates a new 64-bit aligned virtual uniform register pair */ -int omega_bw_ir_alloc_uvreg64(BlackwellIRProgram *prog); - -/* Solves bounded deterministic live-interval register allocation */ -int omega_bw_regalloc_solve(BlackwellIRProgram *prog); - -/* Encodes scheduled IR program into 128-bit sm_121 machine code */ -int omega_bw_encode_program(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t max_len, size_t *out_len); - -/* ---- native v1 P07 cut A.2: allocation-free code generation (aienos#286) ---------------------------- - * The freestanding build (OMEGA_GPU_NO_POSIX, make gpu-engine-freestanding) has no allocator: the caller - * supplies the code buffer and its capacity. Build the program with one of the *_prog generators, then - * encode it with omega_blackwell_kernel_encode_into. The hosted allocating generators below encode through - * the same function, so both builds emit the same bytes (make test-codegen-freestanding). - * - * omega_bw_program_code_bytes: the exact bytes the encoder writes for prog (padded to 8 instructions, - * at least 32), 0 for NULL. - * omega_blackwell_kernel_encode_into: zeroes *kernel, then encodes prog into code_buf. Refuses with - * OMEGA_BW_CODE_BUFFER_TOO_SMALL, writing no byte of code_buf, when code_cap is below - * omega_bw_program_code_bytes(prog); -1 for NULL arguments or an instruction the encoder rejects. On - * success kernel->code points INTO the caller's buffer: the kernel owns nothing, the caller keeps - * code_buf alive as long as the kernel is used and never passes such a kernel to - * omega_blackwell_kernel_free (which exists only in the hosted build). */ -#define OMEGA_BW_CODE_BUFFER_TOO_SMALL (-2) -#define OMEGA_BW_CODE_CAP_SMALL 4096u /* cap of the tensor, tensor_loop and frag generators */ -#define OMEGA_BW_CODE_CAP_MAX ((size_t)BW_MAX_IR_INSNS * 16u) /* cap of frag_block; no program encodes past it */ -size_t omega_bw_program_code_bytes(const BlackwellIRProgram *prog); -int omega_blackwell_kernel_encode_into(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t code_cap, - OmegaBlackwellKernel *kernel); -/* The integer generator's program (K <= 32); the allocating omega_blackwell_codegen_matmul_i32 encodes it. */ -int omega_blackwell_codegen_matmul_i32_prog(const OmegaMatMulSpec *spec, BlackwellIRProgram *prog); - -/* The allocating generators (omega_blackwell_codegen_matmul_i32, _tensor, _tensor_loop, _frag, _frag_block), - * omega_blackwell_codegen_matmul, omega_blackwell_kernel_free and omega_blackwell_test_codegen_variation exist - * only in the hosted build. */ - -/* Top-level dynamic code generator for integer matrix multiplication */ -int omega_blackwell_codegen_matmul_i32(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel); - -/* Dynamic sm_121 Tensor Core code generator (FP16 & BF16 via HMMA.16816) */ -int omega_blackwell_codegen_matmul_tensor_prog(const OmegaMatMulSpec *spec, BlackwellIRProgram *prog); -int omega_blackwell_codegen_matmul_tensor(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel); - -/* FB-1 cut 1b: looped Tensor Core matmul. One warp per CTA. CTA (x, y) owns row - * tile y (16 rows) and column tiles x, x + grid_x, x + 2 grid_x, ... (8 columns - * each); the whole K dimension is accumulated in the HMMA accumulator on the - * chip (no host K slicing). Requires M % 16 == 0, N % 8 == 0, K % 16 == 0 and - * 1 <= grid_x <= N / 8. The kernel does not depend on M (rows come from - * CTAID.Y), so one kernel serves every row count of a (K, N, grid_x) triple. - * Uses only instructions already present in the chip-proven single-tile kernel - * plus the predicated backward BRA and ISETP.GE this IR already encodes. - * mutant != 0 drops the last K step (test oracle: the wrong kernel must be - * caught by the parity test; never set in production). */ -int omega_blackwell_codegen_matmul_tensor_loop_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, - int mutant, BlackwellIRProgram *prog); -int omega_blackwell_codegen_matmul_tensor_loop(const OmegaMatMulSpec *spec, uint32_t grid_x, - int mutant, OmegaBlackwellKernel *kernel); - -/* omega #328: fragment-major tensor matmul. Same grid, C layout (row-major f32) and argument - * words as the looped kernel; A and B are in fragment order instead of row-major: - * A (mp x kp, from omega_matmul_frag_pack_a): block (mt, ks) of 256 bf16 at ((mt*KS + ks)*32 - * + lane)*8, lane = group*4 + tig, holding A[r][c], A[r][c+1], A[r+8][c], A[r+8][c+1], - * A[r][c+8], A[r][c+9], A[r+8][c+8], A[r+8][c+9] with r = 16mt + group, c = 16ks + 2tig; - * B (kp x np, from omega_matmul_frag_pack_b): block (nt, ks) of 128 bf16 at ((nt*KS + ks)*32 - * + lane)*4 holding B[k][j], B[k+1][j], B[k+8][j], B[k+9][j] with k = 16ks + 2tig, - * j = 8nt + group; KS = kp / 16, entries outside the real matrix are zero. - * One LDG.E.128 (A) and one LDG.E.64 (B) per K step; `unroll` (1, 2, 4 or 8, dividing KS) - * steps of loads are issued before the HMMA chain. mutant != 0 drops the last pass (test - * oracle only). Each tile occupies 16*kp (A) and 8*kp (B) elements, so a row-tile offset into - * A is the same in bytes as for row-major A. */ -int omega_blackwell_codegen_matmul_frag_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - int mutant, BlackwellIRProgram *prog); -int omega_blackwell_codegen_matmul_frag(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - int mutant, OmegaBlackwellKernel *kernel); -/* The largest of 4, 2, 1 that divides kp / 16 (unroll 8 is generated for experiments only: it - * did not complete on the GB10, see the definition). */ -uint32_t omega_matmul_frag_unroll(uint32_t kp); -/* 2026-10-12: blocked fragment kernel for prefill rows. One warp owns rt row tiles x ct column tiles - * (rt in 1, 2, 4, 8; ct in 1, 2, 4; 2 <= rt*ct <= 16; unroll 1 or 2 with unroll*(rt+ct) <= 8; nt % ct == 0; - * grid_x <= nt/ct). Same packing, argument words and C layout as the single-tile kernel; a CTA's - * row block is rt row tiles (grid_y = row tiles / rt). mutant != 0 drops the last K pass. */ -int omega_blackwell_codegen_matmul_frag_block_prog(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - uint32_t rt, uint32_t ct, int mutant, BlackwellIRProgram *prog); -int omega_blackwell_codegen_matmul_frag_block(const OmegaMatMulSpec *spec, uint32_t grid_x, uint32_t unroll, - uint32_t rt, uint32_t ct, int mutant, OmegaBlackwellKernel *kernel); -/* rt, ct for mt row tiles and nt column tiles (1, 1 = the single-tile kernel), and the unroll the API uses */ -void omega_matmul_frag_block_shape(uint32_t mt, uint32_t nt, uint32_t *rt, uint32_t *ct); -uint32_t omega_matmul_frag_block_unroll(uint32_t kp, uint32_t rt, uint32_t ct); - -/* Registers to declare in the QMD for a kernel whose allocator peak (OmegaLiveInterval count, regalloc.peak_gpr_usage) - * is `peak`: peak + 2, rounded up to a multiple of 8 (the session raises anything below 64 to 64). - * Chip evidence (OWN-30B, 2026-10-13): the fp8 grouped GEMM (lane 8, 8 rows) with peak 103 declared 104 (= peak + 1 - * rounded up, the earlier rule) hung the chip in 7 of 7 runs; the same program declared 112 ran every gate. Earlier - * evidence: peak 64 declared 64 faulted (Xid 13 Out Of Range Register). Declared >= peak + 2 has run everywhere else - * (router peak 46 declared 48). The exact minimum is UNKNOWN (declarations are multiples of 8); the rule is INFERRED. */ -uint32_t omega_bw_gpr_declared(uint32_t peak); -/* 1 iff `declared` is a legal declaration for `peak`: a multiple of 8 and >= peak + 2. Launchers refuse otherwise. */ -int omega_bw_gpr_declared_ok(uint32_t declared, uint32_t peak); -/* a: m x k row-major. dst: mp x kp elements, fully written (zero padding). */ -void omega_matmul_frag_pack_a(const uint16_t *a, uint32_t m, uint32_t k, uint32_t mp, uint32_t kp, uint16_t *dst); -/* the same from f32 rows, converted to bf16 as omega_fp32_to_bf16 does (one pass, no staging copy) */ -void omega_matmul_frag_pack_a_f32(const float *a, uint32_t m, uint32_t k, uint32_t mp, uint32_t kp, uint16_t *dst); -/* Row 0 of a one-row call into a buffer whose rows 1..15 already hold zeros for this kp (every column, - * zeros past k); the caller tracks that the zeros are there (omega_gpu_matmul_api.c, m = 1 path). */ -void omega_matmul_frag_pack_a_row0(const uint16_t *a, uint32_t k, uint32_t kp, uint16_t *dst); -void omega_matmul_frag_pack_a_row0_f32(const float *a, uint32_t k, uint32_t kp, uint16_t *dst); -/* Result sentinels (host side of the poison check): one word per 16 x 8 fragment tile that holds a real - * output word, at the tile's last real row and column, in the row-major m x np result. set != 0 writes - * poison into every sentinel and returns their count; set == 0 returns how many still hold poison. The - * kernel's epilogue stores a fragment tile as one straight-line run of STG.E words, so a tile whose - * sentinel survived was never stored. */ -size_t omega_matmul_result_sentinels(float *cd, uint32_t m, uint32_t n, uint32_t np, float poison, int set); -/* b: k x n row-major. dst: the column tiles [nt0, nt1), (nt1 - nt0) * kp * 8 elements, fully - * written; it is the part of the packed tensor starting at element nt0 * kp * 8. */ -void omega_matmul_frag_pack_b(const uint16_t *b, uint32_t k, uint32_t n, uint32_t kp, - uint32_t nt0, uint32_t nt1, uint16_t *dst); - -/* Unit test for instruction encoding bitfield fixtures (Gate 3) */ -int omega_blackwell_verify_codegen_fixtures(void); - -/* FB-1 cut 4: fixtures for MUFU_EX2, BAR_SYNC, LDS32, STS32 (0 = pass) */ -int omega_blackwell_verify_codegen_fixtures_fb1cut4(void); - -/* Prime race cut: golden words for LOP3_LUT, SHF_L_U32, IMAD_HI_U32 (0 = pass) */ -int omega_blackwell_verify_codegen_fixtures_intops(void); - -/* omega #328: golden words for LDG.E.64 / LDG.E.128 with offsets and the timed NOP (0 = pass) */ -int omega_blackwell_verify_codegen_fixtures_fragmm(void); - -/* omega #308: golden words for BSSY / BSYNC (nvcc 13.0.88 sm_121 oracle), plus the - * encoder's refusals (negative delta, barrier id > 15). 0 = pass. */ -int omega_blackwell_verify_codegen_fixtures_reconv(void); - -/* omega #308: encodes one instruction with a given physical register map of - * identity (vreg n -> Rn) so offline tools can disassemble single words. 0 = ok. */ -int omega_blackwell_encode_one(const BlackwellIRInsn *insn, uint32_t w[4]); - -/* Unit test for bounded register allocation live intervals and bounds enforcement (Gate 4) */ -int omega_blackwell_test_regalloc_bounds(void); - -/* Stage-1 dynamic codegen variation demonstration between 16x16x16 and 32x16x64 (Gate 7) */ -int omega_blackwell_test_codegen_variation(void); - -#endif /* OMEGA_BLACKWELL_CODEGEN_H */ diff --git a/src/omega_blackwell_codegen_attn.c b/src/omega_blackwell_codegen_attn.c deleted file mode 100644 index 37a67d8df..000000000 --- a/src/omega_blackwell_codegen_attn.c +++ /dev/null @@ -1,549 +0,0 @@ -/* - * omega_blackwell_codegen_attn.c: the one-launch decode attention kernel (see the header). Emitter rules follow - * omega_blackwell_codegen_moe.c (control words, read barrier on every load, loop live ranges). - */ -#include "omega_blackwell_codegen_attn.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn i; memset(&i, 0, sizeof i); - i.op = op; i.dst_vreg = NOREG; i.src1_vreg = NOREG; i.src2_vreg = NOREG; i.src3_vreg = NOREG; i.ureg = NOREG; - return i; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -/* operand with subregister */ -typedef struct { int v; unsigned s; } Op; -static Op R(int v) { Op o = { v, 0 }; return o; } -static Op S(int v, unsigned s) { Op o = { v, s }; return o; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, Op d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; emit(e, i, K_FIXED); } -/* d = a * imm + c */ -static void imadi(Em *e, Op d, Op a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } -static void shrs(Em *e, int d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, uint32_t imm) { shrs(e, d, R(a), imm); } -static void andi(Em *e, Op d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, Op d, Op a, Op b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; emit(e, i, K_FIXED); } -static void iadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, BlackwellIROpcode op, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, BlackwellIROpcode op, int addr64, Op val, int udesc) { BlackwellIRInsn i = I0(op); i.src1_vreg = addr64; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.ureg = udesc; emit(e, i, K_STORE); } -static void atom_add(Em *e, int d, int addr64, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_ATOMG_ADD_STRONG_SYS); i.dst_vreg = d; i.src1_vreg = addr64; i.src2_vreg = val; i.ureg = udesc; emit(e, i, K_VAR); } -static void membar(Em *e) { emit(e, I0(BW_IR_MEMBAR_ALL_SYS), K_FIXED); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void lds32(Em *e, Op d, int addr, int first) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = addr; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, Op val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fop(Em *e, BlackwellIROpcode op, Op d, Op a, Op b, Op c) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; - i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; i.src3_vreg = c.v; i.src3_subreg = (uint8_t)c.s; emit(e, i, K_FIXED); -} -static void fadd(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FADD, d, a, b, R(NOREG)); } -static void fsub(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FSUB, d, a, b, R(NOREG)); } -static void fmul(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMUL, d, a, b, R(NOREG)); } -static void ffma(Em *e, Op d, Op a, Op b, Op c) { fop(e, BW_IR_FFMA, d, a, b, c); } -static void fmaxx(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MAX, d, a, b, R(NOREG)); } -static void mufu(Em *e, BlackwellIROpcode op, Op d, Op a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; emit(e, i, K_VAR); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void exit_k(Em *e) { emit(e, I0(BW_IR_EXIT), K_EXIT); } -static void tail(Em *e) { - exit_k(e); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - -/* A region only some lanes of a warp execute: BSSY ... @P0 BRA join ... BSYNC. P0 true = skip. */ -typedef struct { int bssy, bra; } Region; -static Region region_skip_if_p0(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } -static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } - -/* bf16 round-to-nearest-even of f32 x into the low 16 bits of d: r = x + 0x7fff + ((x >> 16) & 1); d = r >> 16 */ -static void bf16_of(Em *e, int d, Op x, int c7fff, int t) { - shrs(e, t, x, 16); - andi(e, R(t), R(t), 1u); - iadd(e, t, t, c7fff); - fop(e, BW_IR_IADD3, R(d), x, R(t), R(NOREG)); /* IADD3 d = x + t */ - shr(e, d, d, 16); -} - -static const uint32_t NEG_BIG = 0xF149F2CAu; /* -1e30f */ - -int omega_blackwell_codegen_decode_attn_prog(const OmegaDecodeAttnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->depth < 1 || spec->depth > OMEGA_DATTN_MAX_DEPTH || spec->mutant < 0 || spec->mutant > 4) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - const uint32_t D = spec->depth; - const int MUT = spec->mutant; - - /* ---- arguments and identities ---- */ - int udesc = UV64(e); - int pqkv = V64(e), pkc = V64(e), pvc = V64(e), prope = V64(e), pqn = V64(e), pkn = V64(e); - int pos = V(e), per = V(e), splits = V(e), kvs = V(e), eps = V(e), qks = V(e); - /* pout, ppart, pcnt, oscale are loaded from the constant bank in the epilogue (register pressure: the chip allocator has 128) */ - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), zero = V(e), c7fff = V(e), c16 = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pqkv, OMEGA_DATTN_ARG_QKV); ldc64(e, pkc, OMEGA_DATTN_ARG_KC); ldc64(e, pvc, OMEGA_DATTN_ARG_VC); - ldc64(e, prope, OMEGA_DATTN_ARG_ROPE); ldc64(e, pqn, OMEGA_DATTN_ARG_QN); ldc64(e, pkn, OMEGA_DATTN_ARG_KN); - ldc32(e, pos, OMEGA_DATTN_ARG_POS); ldc32(e, per, OMEGA_DATTN_ARG_PER_SPLIT); ldc32(e, splits, OMEGA_DATTN_ARG_SPLITS); - ldc32(e, kvs, OMEGA_DATTN_ARG_KV_STRIDE); ldc32(e, eps, OMEGA_DATTN_ARG_EPS); - ldc32(e, qks, OMEGA_DATTN_ARG_QK_SCALE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); movrz(e, R(zero)); movi(e, c7fff, 0x7fffu); movi(e, c16, 16); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - - /* range of this CTA: base = cx * per; end = min(base + per, pos + 1) */ - int base = V(e), bend = V(e), ctx = V(e), t1 = V(e), t2 = V(e), end = V(e), endm1 = V(e), negendm1 = V(e), splitsm1 = V(e), cyk = V(e); - imadr(e, base, cx, per, NOREG); - imadi(e, R(bend), R(base), 1u, per); - imadi(e, R(ctx), R(pos), 1u, one); - imadi(e, R(t1), R(ctx), 0xffffffffu, bend); /* t1 = bend - ctx */ - imadi(e, R(t2), R(t1), 0xffffffffu, NOREG); /* t2 = ctx - bend */ - shr(e, t2, t2, 31); /* 1 when bend > ctx */ - imadr(e, t2, t2, t1, NOREG); /* t2 = over * (bend - ctx) */ - imadi(e, R(end), R(t2), 0xffffffffu, bend); /* end = bend - t2 */ - imadi(e, R(endm1), R(one), 0xffffffffu, end); - imadi(e, R(negendm1), R(endm1), 0xffffffffu, NOREG); - imadi(e, R(splitsm1), R(one), 0xffffffffu, splits); - imadr(e, cyk, cy, kvs, NOREG); /* byte offset of this KV head's plane */ - - /* ---- prologue: q' for the 8 heads of the group (warp = head) ---- */ - int q4 = V128(e), w4 = V128(e), pt4 = V128(e), cos4 = V128(e), sin4 = V128(e), k4 = V128(e), v4 = V128(e); - int sq = V(e), ts = V(e), rs = V(e), a0 = V(e), a1 = V(e), a2 = V(e), a3 = V(e), ad64 = V64(e), rope64 = V64(e), sgn = V(e), pl = V(e); - if (e->err) return -1; - imadi(e, R(t1), R(cy), 8u, warp); /* q head index */ - imadi(e, R(t1), R(t1), 512u, NOREG); - imadi(e, R(t1), R(lane), 16u, t1); - imadw(e, ad64, t1, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, q4, ad64, 0, udesc, 1); - imadw(e, ad64, lane, 16u, pqn); - ldg_wide(e, BW_IR_LDG_E_128, w4, ad64, 0, udesc, 0); - /* rope row for this lane: cos/sin index = lane & 15 (dims 4i..4i+3 for lanes < 16, dims 64 + 4(i-16) above) */ - andi(e, R(t2), R(lane), 15u); - imadi(e, R(t2), R(t2), 16u, NOREG); - imadi(e, R(t2), R(pos), OMEGA_DATTN_ROPE_ROW_BYTES, t2); - imadw(e, rope64, t2, 1u, prope); - ldg_wide(e, BW_IR_LDG_E_128, cos4, rope64, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, sin4, rope64, 256, udesc, 0); - /* sign of the sin term: lanes < 16 take q[d] * cos - q[d+64] * sin, lanes >= 16 take q[d] * cos + q[d-64] * sin */ - imadi(e, R(sgn), R(one), 0xfffffff0u, lane); /* lane - 16 */ - shr(e, sgn, sgn, 31); - imadi(e, R(sgn), R(sgn), 0x80000000u, NOREG); - for (unsigned i = 0; i < 4; i++) xorr(e, S(sin4, i), S(sin4, i), R(sgn)); - xorr(e, R(pl), R(lane), R(c16)); /* partner lane */ - - /* RMSNorm of the quad's head: sum of squares over the warp, broadcast through shared memory */ - fmul(e, R(sq), S(q4, 0), S(q4, 0)); - for (unsigned i = 1; i < 4; i++) ffma(e, R(sq), S(q4, i), S(q4, i), R(sq)); - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, ts, sq, o); fadd(e, R(sq), R(sq), R(ts)); } - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_DATTN_SM_L, a0); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); sts32(e, a0, R(sq)); region_end(e, r); } - bar_sync(e); - lds32(e, R(sq), a0, 1); - movi(e, ts, 0x3c000000u); /* 1/128 */ - ffma(e, R(rs), R(sq), R(ts), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); - for (unsigned i = 0; i < 4; i++) { fmul(e, S(q4, i), S(q4, i), R(rs)); fmul(e, S(q4, i), S(q4, i), S(w4, i)); } - /* stage, read the partner half, rotate */ - imadi(e, R(a0), R(warp), 512u, NOREG); imadi(e, R(a0), R(lane), 16u, a0); /* SM_Q + warp*512 + lane*16 (SM_Q = 0) */ - imadi(e, R(a1), R(one), 4u, a0); imadi(e, R(a2), R(one), 8u, a0); imadi(e, R(a3), R(one), 12u, a0); - sts32(e, a0, S(q4, 0)); sts32(e, a1, S(q4, 1)); sts32(e, a2, S(q4, 2)); sts32(e, a3, S(q4, 3)); - bar_sync(e); - imadi(e, R(t2), R(warp), 512u, NOREG); imadi(e, R(t2), R(pl), 16u, t2); - lds128(e, pt4, t2, 0, 1); - if (MUT != 1) for (unsigned i = 0; i < 4; i++) { fmul(e, R(ts), S(q4, i), S(cos4, i)); ffma(e, S(q4, i), S(pt4, i), S(sin4, i), R(ts)); } - for (unsigned i = 0; i < 4; i++) fmul(e, S(q4, i), S(q4, i), R(qks)); - bar_sync(e); /* every partner read done before q' overwrites the staging */ - sts32(e, a0, S(q4, 0)); sts32(e, a1, S(q4, 1)); sts32(e, a2, S(q4, 2)); sts32(e, a3, S(q4, 3)); - - /* ---- the new token's K (norm + rope) and V, bf16 into the cache by the CTA that owns `pos` ---- */ - imadi(e, R(t1), R(cy), 512u, NOREG); imadi(e, R(t1), R(lane), 16u, t1); - imadi(e, R(t1), R(one), 32u * 128u * 4u, t1); /* k block of qkv */ - imadw(e, ad64, t1, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, k4, ad64, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, v4, ad64, 4u * 128u * 4u, udesc, 0); /* v block follows the 4 k heads */ - imadw(e, ad64, lane, 16u, pkn); - ldg_wide(e, BW_IR_LDG_E_128, w4, ad64, 0, udesc, 0); - fmul(e, R(sq), S(k4, 0), S(k4, 0)); - for (unsigned i = 1; i < 4; i++) ffma(e, R(sq), S(k4, i), S(k4, i), R(sq)); - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, ts, sq, o); fadd(e, R(sq), R(sq), R(ts)); } - imadi(e, R(a1), R(warp), 4u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN_SM_L, a1); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); sts32(e, a1, R(sq)); region_end(e, r); } - bar_sync(e); - lds32(e, R(sq), a1, 1); - movi(e, ts, 0x3c000000u); - ffma(e, R(rs), R(sq), R(ts), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); - for (unsigned i = 0; i < 4; i++) { fmul(e, S(k4, i), S(k4, i), R(rs)); fmul(e, S(k4, i), S(k4, i), S(w4, i)); } - imadi(e, R(a1), R(lane), 16u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN_SM_K, a1); - imadi(e, R(a2), R(one), 4u, a1); imadi(e, R(a3), R(one), 8u, a1); imadi(e, R(t2), R(one), 12u, a1); - sts32(e, a1, S(k4, 0)); sts32(e, a2, S(k4, 1)); sts32(e, a3, S(k4, 2)); sts32(e, t2, S(k4, 3)); /* every warp writes the same words */ - bar_sync(e); - imadi(e, R(t2), R(pl), 16u, NOREG); imadi(e, R(t2), R(one), OMEGA_DATTN_SM_K, t2); - lds128(e, pt4, t2, 0, 1); - if (MUT != 1) for (unsigned i = 0; i < 4; i++) { fmul(e, R(ts), S(k4, i), S(cos4, i)); ffma(e, S(k4, i), S(pt4, i), S(sin4, i), R(ts)); } - /* bf16 words: k4 -> (a2, a3), v4 -> (sq, ts) */ - { - int h0 = V(e), h1 = V(e), tb = V(e); - bf16_of(e, h0, S(k4, 0), c7fff, tb); bf16_of(e, h1, S(k4, 1), c7fff, tb); imadi(e, R(a2), R(h1), 65536u, h0); - bf16_of(e, h0, S(k4, 2), c7fff, tb); bf16_of(e, h1, S(k4, 3), c7fff, tb); imadi(e, R(a3), R(h1), 65536u, h0); - bf16_of(e, h0, S(v4, 0), c7fff, tb); bf16_of(e, h1, S(v4, 1), c7fff, tb); imadi(e, R(sq), R(h1), 65536u, h0); - bf16_of(e, h0, S(v4, 2), c7fff, tb); bf16_of(e, h1, S(v4, 3), c7fff, tb); imadi(e, R(ts), R(h1), 65536u, h0); - } - /* cache row address of position pos for this lane */ - imadi(e, R(t1), R(pos), OMEGA_DATTN_ROW_BYTES, cyk); imadi(e, R(t1), R(lane), 8u, t1); /* 4 bf16 = 8 bytes per lane */ - /* key = (splits - 1 - cx) + warp: zero only for warp 0 of the last split */ - imadi(e, R(t2), R(cx), 0xffffffffu, splitsm1); - if (MUT != 3) { - int ka = V64(e), kb = V64(e), key = V(e); - imadi(e, R(key), R(t2), 1u, warp); - isetp_ge_u32(e, key, one); - int b1 = bra_if_p0_fwd(e); - imadw(e, ka, t1, 1u, pkc); imadw(e, kb, one, 4u, ka); - stg(e, BW_IR_STG_E, ka, R(a2), udesc); stg(e, BW_IR_STG_E, kb, R(a3), udesc); - patch_bra(e, b1, here(e)); - xorr(e, R(key), R(warp), R(one)); imadi(e, R(key), R(t2), 1u, key); - isetp_ge_u32(e, key, one); - int b2 = bra_if_p0_fwd(e); - imadw(e, ka, t1, 1u, pvc); imadw(e, kb, one, 4u, ka); - stg(e, BW_IR_STG_E, ka, R(sq), udesc); stg(e, BW_IR_STG_E, kb, R(ts), udesc); - patch_bra(e, b2, here(e)); - } - membar(e); - bar_sync(e); - - /* ---- running state ---- */ - int acc[8], m[8], l[8], sc[8], dl[8], wd[8], mn = V(e); - for (unsigned h = 0; h < 8; h++) { acc[h] = V128(e); m[h] = V(e); l[h] = V(e); sc[h] = V(e); dl[h] = V(e); wd[h] = V(e); } - int kq[OMEGA_DATTN_MAX_DEPTH], vq[OMEGA_DATTN_MAX_DEPTH]; - for (uint32_t d = 0; d < D; d++) { kq[d] = V128(e); vq[d] = V64(e); } - int qa4 = V128(e), qb4 = V128(e); - int cb = V(e), tpos = V(e), over = V(e), krow = V64(e), kpf = V64(e), qoff = V(e), j = V(e), sa = V(e), smS = V(e); - int n = V(e), vrow = V64(e), vpf = V64(e), pa = V(e), i = V(e), dsum = V(e), lane8 = V(e), negwarp = V(e), ccnt = V(e); - if (e->err) return -1; - for (unsigned h = 0; h < 8; h++) { for (unsigned q = 0; q < 4; q++) movrz(e, S(acc[h], q)); movi(e, m[h], NEG_BIG); movrz(e, R(l[h])); } - movi(e, smS, OMEGA_DATTN_SM_S); - imadi(e, R(lane8), R(lane), 8u, NOREG); - if (MUT == 2) imadi(e, R(lane8), R(one), OMEGA_DATTN_ROW_BYTES, lane8); - imadi(e, R(negwarp), R(warp), 0xffffffffu, NOREG); - movi(e, ccnt, 16); - mov(e, R(cb), R(base)); - - /* ---- chunk loop ---- */ - const int L_chunk = here(e); - loop_begin(e); - isetp_ge_u32(e, cb, end); - const int bra_done = bra_if_p0_fwd(e); - /* score pass: thread = position cb + tid, clamped to end - 1 (clamped lanes compute a score nobody reads) */ - imadi(e, R(tpos), R(cb), 1u, tid); - imadi(e, R(over), R(tpos), 0xffffffffu, endm1); /* endm1 - tpos */ - shr(e, over, over, 31); /* 1 when tpos > endm1 */ - imadi(e, R(t1), R(tpos), 1u, negendm1); /* tpos - endm1 */ - imadr(e, t1, over, t1, NOREG); - imadi(e, R(t1), R(t1), 0xffffffffu, tpos); /* clamped position */ - imadi(e, R(t1), R(t1), OMEGA_DATTN_ROW_BYTES, cyk); - imadw(e, krow, t1, 1u, pkc); - for (unsigned h = 0; h < 8; h++) movrz(e, R(sc[h])); - for (uint32_t d = 0; d < D; d++) ldg_wide(e, BW_IR_LDG_E_128, kq[d], krow, d * 16u, udesc, d == 0); - imadw(e, kpf, one, D * 16u, krow); - movrz(e, R(qoff)); movrz(e, R(j)); - const int L_q = here(e); - loop_begin(e); - isetp_ge_u32(e, j, ccnt); - const int bra_qend = bra_if_p0_fwd(e); - for (unsigned w = 0; w < 4; w++) { imadi(e, R(wd[2 * w]), S(kq[0], w), 65536u, NOREG); andi(e, R(wd[2 * w + 1]), S(kq[0], w), 0xffff0000u); } - for (unsigned h = 0; h < 8; h++) { - lds128(e, qa4, qoff, h * 512u, 1); lds128(e, qb4, qoff, h * 512u + 16u, 0); - for (unsigned q = 0; q < 4; q++) ffma(e, R(sc[h]), R(wd[q]), S(qa4, q), R(sc[h])); - for (unsigned q = 0; q < 4; q++) ffma(e, R(sc[h]), R(wd[4 + q]), S(qb4, q), R(sc[h])); - } - for (uint32_t d = 0; d + 1 < D; d++) for (unsigned w = 0; w < 4; w++) mov(e, S(kq[d], w), S(kq[d + 1], w)); - ldg_wide(e, BW_IR_LDG_E_128, kq[D - 1], kpf, 0, udesc, 1); - imadw(e, kpf, one, 16u, kpf); - imadi(e, R(qoff), R(one), 32u, qoff); - imadi(e, R(j), R(one), 1u, j); - bra(e, L_q); - loop_end(e); - patch_bra(e, bra_qend, here(e)); - imadi(e, R(sa), R(tid), 32u, smS); - for (unsigned h = 0; h < 8; h++) { imadi(e, R(t1), R(one), h * 4u, sa); sts32(e, t1, R(sc[h])); } - bar_sync(e); - /* V pass: this warp's positions cb + warp + 8 i, i < n = max(0, ceil((min(end, cb + 256) - cb - warp) / 8)) */ - imadi(e, R(t1), R(one), OMEGA_DATTN_CHUNK, cb); /* cb + 256 */ - imadi(e, R(t2), R(t1), 0xffffffffu, end); /* end - (cb + 256) */ - shr(e, over, t2, 31); /* 1 when the chunk is cut short by end */ - imadr(e, t2, over, t2, t1); /* cend = min(end, cb + 256) */ - imadi(e, R(t1), R(cb), 0xffffffffu, t2); /* cend - cb */ - imadi(e, R(t1), R(t1), 1u, negwarp); /* x = end - cb - warp */ - shr(e, over, t1, 31); - imadi(e, R(n), R(one), 7u, t1); - shr(e, n, n, 3); - imadr(e, t2, over, n, NOREG); - imadi(e, R(n), R(t2), 0xffffffffu, n); - imadi(e, R(t1), R(cb), 1u, warp); - imadi(e, R(t1), R(t1), OMEGA_DATTN_ROW_BYTES, lane8); - imadi(e, R(t1), R(t1), 1u, cyk); - imadw(e, vrow, t1, 1u, pvc); - for (uint32_t d = 0; d < D; d++) ldg_wide(e, BW_IR_LDG_E_64, vq[d], vrow, d * 8u * OMEGA_DATTN_ROW_BYTES, udesc, d == 0); - imadw(e, vpf, one, D * 8u * OMEGA_DATTN_ROW_BYTES, vrow); - imadi(e, R(pa), R(warp), 32u, smS); - movrz(e, R(i)); - const int L_v = here(e); - loop_begin(e); - isetp_ge_u32(e, i, n); - const int bra_vend = bra_if_p0_fwd(e); - imadi(e, R(wd[0]), S(vq[0], 0), 65536u, NOREG); andi(e, R(wd[1]), S(vq[0], 0), 0xffff0000u); - imadi(e, R(wd[2]), S(vq[0], 1), 65536u, NOREG); andi(e, R(wd[3]), S(vq[0], 1), 0xffff0000u); - lds128(e, qa4, pa, 0, 1); lds128(e, qb4, pa, 16, 0); - for (unsigned h = 0; h < 8; h++) { fmaxx(e, R(mn), R(m[h]), h < 4 ? S(qa4, h) : S(qb4, h - 4)); fsub(e, R(dl[h]), R(m[h]), R(mn)); mov(e, R(m[h]), R(mn)); } /* dl <= 0; exactly +0 when the max stayed */ - fadd(e, R(dsum), R(dl[0]), R(dl[1])); - for (unsigned h = 2; h < 8; h++) fadd(e, R(dsum), R(dsum), R(dl[h])); - isetp_ge_u32(e, one, dsum); /* 1 >= bits(dsum): no head's max moved (dsum is +0); a negative dsum has the sign bit */ - const int bra_nores = bra_if_p0_fwd(e); - for (unsigned h = 0; h < 8; h++) mufu(e, BW_IR_MUFU_EX2, R(dl[h]), R(dl[h])); - for (unsigned h = 0; h < 8; h++) { for (unsigned q = 0; q < 4; q++) fmul(e, S(acc[h], q), S(acc[h], q), R(dl[h])); fmul(e, R(l[h]), R(l[h]), R(dl[h])); } - patch_bra(e, bra_nores, here(e)); - for (unsigned h = 0; h < 8; h++) { fsub(e, R(dl[h]), h < 4 ? S(qa4, h) : S(qb4, h - 4), R(m[h])); mufu(e, BW_IR_MUFU_EX2, R(dl[h]), R(dl[h])); } - for (unsigned h = 0; h < 8; h++) { for (unsigned q = 0; q < 4; q++) ffma(e, S(acc[h], q), R(dl[h]), R(wd[q]), S(acc[h], q)); fadd(e, R(l[h]), R(l[h]), R(dl[h])); } - for (uint32_t d = 0; d + 1 < D; d++) for (unsigned w = 0; w < 2; w++) mov(e, S(vq[d], w), S(vq[d + 1], w)); - ldg_wide(e, BW_IR_LDG_E_64, vq[D - 1], vpf, 0, udesc, 1); - imadw(e, vpf, one, 8u * OMEGA_DATTN_ROW_BYTES, vpf); - imadi(e, R(pa), R(one), 8u * 32u, pa); - imadi(e, R(i), R(one), 1u, i); - bra(e, L_v); - loop_end(e); - patch_bra(e, bra_vend, here(e)); - bar_sync(e); /* the next score pass overwrites s[][] */ - imadi(e, R(cb), R(one), OMEGA_DATTN_CHUNK, cb); - bra(e, L_chunk); - loop_end(e); - patch_bra(e, bra_done, here(e)); - - /* ---- epilogue: combine the warps, write the partial ---- */ - int ep[8], ea[8], eb[8]; - for (unsigned h = 0; h < 8; h++) { ep[h] = V(e); ea[h] = V(e); eb[h] = V(e); } - int pout = V64(e), ppart = V64(e), pcnt = V64(e), oscale = V(e); - if (e->err) return -1; - ldc64(e, pout, OMEGA_DATTN_ARG_OUT); ldc64(e, ppart, OMEGA_DATTN_ARG_PART); ldc64(e, pcnt, OMEGA_DATTN_ARG_CNT); ldc32(e, oscale, OMEGA_DATTN_ARG_OUT_SCALE); - /* per-warp maxes to shared: lane 0 of warp w writes m[h] at SM_M + w*32 + h*4 */ - imadi(e, R(a0), R(warp), 32u, NOREG); imadi(e, R(a0), R(one), OMEGA_DATTN_SM_M, a0); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); for (unsigned h = 0; h < 8; h++) { imadi(e, R(t1), R(one), h * 4u, a0); sts32(e, t1, R(m[h])); } region_end(e, r); } - bar_sync(e); - /* lanes 0..7 of every warp: M[lane] = max over the 8 warps; lanes of warp 0 write it at SM_M + 256 + lane*4 */ - movi(e, ccnt, 8); - isetp_ge_u32(e, lane, ccnt); - { - Region r = region_skip_if_p0(e); - imadi(e, R(a1), R(lane), 4u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN_SM_M, a1); - for (unsigned w = 0; w < 8; w++) { imadi(e, R(t1), R(one), w * 32u, a1); lds32(e, R(ep[w]), t1, w == 0); } - for (unsigned w = 1; w < 8; w++) fmaxx(e, R(ep[0]), R(ep[0]), R(ep[w])); - imadi(e, R(t1), R(one), 256u, a1); - sts32(e, t1, R(ep[0])); - region_end(e, r); - } - bar_sync(e); - movi(e, t1, OMEGA_DATTN_SM_M + 256u); - lds128(e, qa4, t1, 0, 1); lds128(e, qb4, t1, 16, 0); - for (unsigned h = 0; h < 8; h++) { fsub(e, R(ea[h]), R(m[h]), h < 4 ? S(qa4, h) : S(qb4, h - 4)); mufu(e, BW_IR_MUFU_EX2, R(ea[h]), R(ea[h])); } - for (unsigned h = 0; h < 8; h++) { for (unsigned q = 0; q < 4; q++) fmul(e, S(acc[h], q), S(acc[h], q), R(ea[h])); fmul(e, R(l[h]), R(l[h]), R(ea[h])); } - /* per-warp l to shared, then the partial's m and l by threads 0..7 */ - imadi(e, R(a0), R(warp), 32u, NOREG); imadi(e, R(a0), R(one), OMEGA_DATTN_SM_L, a0); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); for (unsigned h = 0; h < 8; h++) { imadi(e, R(t1), R(one), h * 4u, a0); sts32(e, t1, R(l[h])); } region_end(e, r); } - bar_sync(e); - int pp = V64(e), pa64 = V64(e), pb64 = V64(e); - imadr(e, t2, cy, splits, cx); - imadi(e, R(t2), R(t2), OMEGA_DATTN_PARTIAL_WORDS * 4u, NOREG); - imadw(e, pp, t2, 1u, ppart); - isetp_ge_u32(e, tid, ccnt); /* tid >= 8 skips */ - { - Region r = region_skip_if_p0(e); - imadi(e, R(a1), R(tid), 4u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN_SM_L, a1); - for (unsigned w = 0; w < 8; w++) { imadi(e, R(t1), R(one), w * 32u, a1); lds32(e, R(ep[w]), t1, w == 0); } - for (unsigned w = 1; w < 8; w++) fadd(e, R(ep[0]), R(ep[0]), R(ep[w])); - imadi(e, R(t1), R(tid), 4u, NOREG); imadi(e, R(t1), R(one), OMEGA_DATTN_SM_M + 256u, t1); - lds32(e, R(ep[1]), t1, 1); - imadw(e, pa64, tid, 4u, pp); - stg(e, BW_IR_STG_E, pa64, R(ep[1]), udesc); /* m[h] */ - imadw(e, pb64, one, 32u, pa64); - stg(e, BW_IR_STG_E, pb64, R(ep[0]), udesc); /* l[h] */ - region_end(e, r); - } - /* acc: 4 rounds of 2 heads through the s[][] region: r[w][h'][128]; the 8 store and 8 load addresses computed once */ - imadi(e, R(a0), R(warp), 1024u, NOREG); imadi(e, R(a0), R(lane), 16u, a0); imadi(e, R(a0), R(one), OMEGA_DATTN_SM_S, a0); - imadi(e, R(a1), R(tid), 4u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN_SM_S, a1); - for (unsigned q = 0; q < 8; q++) imadi(e, R(eb[q]), R(one), (q / 4u) * 512u + (q % 4u) * 4u, a0); - for (unsigned w = 0; w < 8; w++) imadi(e, R(ea[w]), R(one), w * 1024u, a1); - imadw(e, pa64, tid, 4u, pp); - for (unsigned rd = 0; rd < 4; rd++) { - for (unsigned hh = 0; hh < 2; hh++) for (unsigned q = 0; q < 4; q++) sts32(e, eb[hh * 4 + q], S(acc[2 * rd + hh], q)); - bar_sync(e); - for (unsigned w = 0; w < 8; w++) lds32(e, R(ep[w]), ea[w], w == 0); - for (unsigned w = 1; w < 8; w++) fadd(e, R(ep[0]), R(ep[0]), R(ep[w])); - imadw(e, pb64, one, 64u + rd * 1024u, pa64); - stg(e, BW_IR_STG_E, pb64, R(ep[0]), udesc); - bar_sync(e); - } - /* publish, count, the last CTA combines */ - membar(e); - bar_sync(e); - movi(e, t1, OMEGA_DATTN_SM_FLAG); - isetp_ge_u32(e, tid, one); - { - Region r = region_skip_if_p0(e); - imadw(e, pb64, cy, 4u, pcnt); - atom_add(e, ep[0], pb64, one, udesc); - sts32(e, t1, R(ep[0])); - region_end(e, r); - } - bar_sync(e); - lds32(e, R(ep[0]), t1, 1); - isetp_ge_u32(e, ep[0], splitsm1); - const int bra_last = bra_if_p0_fwd(e); - exit_k(e); - patch_bra(e, bra_last, here(e)); - /* combine: thread tid, outputs o = tid + 256 r (head o >> 7, dim o & 127), r = 0..3 */ - int ho = V(e), oidx = V(e), ma = V64(e), la = V64(e), aa = V64(e), num = V(e), den = V(e), mx = V(e), s_i = V(e), rr = V(e); - if (e->err) return -1; - shr(e, ho, tid, 7); - mov(e, R(oidx), R(tid)); - movrz(e, R(rr)); - movi(e, ccnt, 4); - imadr(e, t2, cy, splits, NOREG); - imadi(e, R(t2), R(t2), OMEGA_DATTN_PARTIAL_WORDS * 4u, NOREG); /* byte offset of partials[cy][0] */ - const int L_r = here(e); - loop_begin(e); - isetp_ge_u32(e, rr, ccnt); - const int bra_rend = bra_if_p0_fwd(e); - imadi(e, R(t1), R(ho), 4u, t2); imadw(e, ma, t1, 1u, ppart); - imadw(e, la, one, 32u, ma); - imadi(e, R(t1), R(oidx), 4u, t2); imadw(e, aa, t1, 1u, ppart); imadw(e, aa, one, 64u, aa); - movrz(e, R(num)); movrz(e, R(den)); movi(e, mx, NEG_BIG); movrz(e, R(s_i)); - const int L_s = here(e); - loop_begin(e); - isetp_ge_u32(e, s_i, splits); - const int bra_send = bra_if_p0_fwd(e); - ldg32(e, BW_IR_LDG_STRONG_SYS, ep[0], ma, udesc, 1); - ldg32(e, BW_IR_LDG_STRONG_SYS, ep[1], la, udesc, 0); - ldg32(e, BW_IR_LDG_STRONG_SYS, ep[2], aa, udesc, 0); - if (MUT != 4) { - fmaxx(e, R(ep[3]), R(mx), R(ep[0])); - fsub(e, R(ep[4]), R(mx), R(ep[3])); mufu(e, BW_IR_MUFU_EX2, R(ep[4]), R(ep[4])); - fsub(e, R(ep[5]), R(ep[0]), R(ep[3])); mufu(e, BW_IR_MUFU_EX2, R(ep[5]), R(ep[5])); - mov(e, R(mx), R(ep[3])); - fmul(e, R(num), R(num), R(ep[4])); fmul(e, R(den), R(den), R(ep[4])); - } else { - movi(e, ep[5], 0x3f800000u); - } - ffma(e, R(num), R(ep[5]), R(ep[2]), R(num)); - ffma(e, R(den), R(ep[5]), R(ep[1]), R(den)); - imadw(e, ma, one, OMEGA_DATTN_PARTIAL_WORDS * 4u, ma); - imadw(e, la, one, OMEGA_DATTN_PARTIAL_WORDS * 4u, la); - imadw(e, aa, one, OMEGA_DATTN_PARTIAL_WORDS * 4u, aa); - imadi(e, R(s_i), R(one), 1u, s_i); - bra(e, L_s); - loop_end(e); - patch_bra(e, bra_send, here(e)); - mufu(e, BW_IR_MUFU_RCP, R(den), R(den)); - fmul(e, R(num), R(num), R(den)); - fmul(e, R(num), R(num), R(oscale)); - imadi(e, R(t1), R(cy), 1024u, oidx); - imadw(e, pb64, t1, 4u, pout); - stg(e, BW_IR_STG_E, pb64, R(num), udesc); - imadi(e, R(ho), R(one), 2u, ho); - imadi(e, R(oidx), R(one), 256u, oidx); - imadi(e, R(rr), R(one), 1u, rr); - bra(e, L_r); - loop_end(e); - patch_bra(e, bra_rend, here(e)); - /* thread 0 resets the counter for the next launch (every other CTA of this head has already added) */ - isetp_ge_u32(e, tid, one); - { Region r = region_skip_if_p0(e); imadw(e, pb64, cy, 4u, pcnt); stg(e, BW_IR_STG_STRONG_SYS, pb64, R(zero), udesc); region_end(e, r); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_decode_attn_prog_stats(const OmegaDecodeAttnSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_decode_attn_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} diff --git a/src/omega_blackwell_codegen_attn.h b/src/omega_blackwell_codegen_attn.h deleted file mode 100644 index 102a3f2e5..000000000 --- a/src/omega_blackwell_codegen_attn.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_ATTN_H -#define OMEGA_BLACKWELL_CODEGEN_ATTN_H -/* - * omega_blackwell_codegen_attn: decode attention for Qwen3-30B-A3B in ONE launch per layer (OWN-30B cut 8, - * 2026-10-13). Grouped-query attention with 8 query heads per KV head, head_dim 128, per-head RMSNorm on q - * and k, rotary embedding from a host-built cos/sin table, the new token's K/V appended to a GPU-resident - * bf16 cache inside the kernel, softmax over the whole context, output ready for o_proj (scaled by - * `out_scale`, so it can be the x' row of the FP8 GEMV without a host round trip). - * - * Grid: (splits, kv_heads). CTA (cx, cy) handles KV head cy and the positions [cx*per_split, min(+per_split, - * pos+1)) of the context; the host picks splits = ceil((pos+1)/per_split), so no CTA is empty. 8 warps = 256 - * threads per CTA (fixed: warp h = query head h of the group in the prologue, lane = position in the score pass). - * - * Per CTA: - * prologue warp h: q[cy*8+h] (f32 quad per lane) -> RMSNorm(q_norm, eps) -> RoPE(table[pos]) -> * qk_scale, - * staged in shared memory as q'[h][128]. Every warp also computes k_new = RoPE(RMSNorm(k[cy])) - * and v_new; the CTA whose range holds `pos` (the last split) writes them as bf16 into the cache at - * [cy][pos] (warp 0 K, warp 1 V), then MEMBAR + BAR.SYNC, so its own stream reads them back. - * chunks of 256 positions: score pass (thread = position: the bf16 K row streamed in 16 quads with a - * `depth`-deep prefetch, 8 dot products against q' from shared memory, scores to shared s[t][8]); - * V pass (warp w: positions w, w+8, ...; lane = 4 dims; online softmax per warp: running max, - * alpha = EX2(m_old - m_new) applied only when the max moved (warp-uniform branch), p = EX2(s - m), - * acc += p * v, l += p). - * epilogue warps combine (m, l, acc) through shared memory and write the CTA partial - * {m[8], l[8], acc[8][128]} to partials[cy][cx]; then one ATOMG.ADD on counters[cy]; the last CTA - * of the KV head combines the partials with the usual max rescale and writes out[(cy*8+h)*128+d] - * * out_scale, and resets the counter. - * - * Numbers (f32 on the chip, double in the host reference, tolerances in tests/gpu_decode_attn_test.c): - * scores in log2 units: q' already carries (1/sqrt(128)) * log2(e), so p = EX2(s - m) = exp((q.k)/sqrt(d) - M). - * bf16 K/V are widened by a 16-bit shift; the new K/V are rounded to bf16 round-to-nearest-even before storing - * (the reference rounds the same way, so the attention of the new token sees the stored value). - * - * The host simulator (tests/bw_warp_sim_k.h) runs this kernel at 8 warps; a simulator pass is never a chip result. - */ -#include "omega_blackwell_codegen.h" -#include - -#define OMEGA_DATTN_HEAD_DIM 128u -#define OMEGA_DATTN_Q_PER_KV 8u -#define OMEGA_DATTN_WARPS 8u -#define OMEGA_DATTN_CHUNK 256u /* positions per score pass = threads per CTA */ -#define OMEGA_DATTN_ROW_BYTES 256u /* one bf16 K or V row */ -#define OMEGA_DATTN_ROPE_ROW_BYTES 512u /* cos[64] then sin[64], f32 */ -#define OMEGA_DATTN_PARTIAL_WORDS 1040u /* m[8], l[8], acc[8][128] */ -#define OMEGA_DATTN_MAX_DEPTH 4u -/* bytes past the last row of a K or V plane the prefetch may touch (clamped reads of the last rows) */ -#define OMEGA_DATTN_PLANE_SLACK (OMEGA_DATTN_MAX_DEPTH * 8u * OMEGA_DATTN_ROW_BYTES + 64u) - -/* constant bank: every address at 0x380 + 8n, then the scalars */ -#define OMEGA_DATTN_ARG_QKV 0x380u /* f32 [32*128 q | 4*128 k | 4*128 v] */ -#define OMEGA_DATTN_ARG_KC 0x388u /* bf16 K cache base: [kv_head][max_pos][128], kv_stride bytes per head */ -#define OMEGA_DATTN_ARG_VC 0x390u /* bf16 V cache base, same layout */ -#define OMEGA_DATTN_ARG_ROPE 0x398u /* f32 [max_pos][cos 64 | sin 64] */ -#define OMEGA_DATTN_ARG_QN 0x3a0u /* f32 [128] q_norm weight */ -#define OMEGA_DATTN_ARG_KN 0x3a8u /* f32 [128] k_norm weight */ -#define OMEGA_DATTN_ARG_OUT 0x3b0u /* f32 [32][128] */ -#define OMEGA_DATTN_ARG_PART 0x3b8u /* f32 [kv_heads][splits][1040] */ -#define OMEGA_DATTN_ARG_CNT 0x3c0u /* u32 [kv_heads], zero before the launch */ -#define OMEGA_DATTN_ARG_POS 0x3c8u /* u32 position of the new token; context = pos + 1 */ -#define OMEGA_DATTN_ARG_PER_SPLIT 0x3ccu /* u32 positions per CTA (multiple of 256) */ -#define OMEGA_DATTN_ARG_SPLITS 0x3d0u /* u32 = grid_x */ -#define OMEGA_DATTN_ARG_KV_STRIDE 0x3d4u /* u32 bytes per KV head plane */ -#define OMEGA_DATTN_ARG_EPS 0x3d8u /* f32 rms eps */ -#define OMEGA_DATTN_ARG_OUT_SCALE 0x3dcu /* f32 multiplier on the output (2^64 for the FP8 GEMV x' row, 1 otherwise) */ -#define OMEGA_DATTN_ARG_QK_SCALE 0x3e0u /* f32 (1/sqrt(128)) * log2(e) */ -#define OMEGA_DATTN_ARGS_WORDS 25u - -/* shared memory map (bytes) */ -#define OMEGA_DATTN_SM_Q 0u /* q'[8][128] f32: 4096 */ -#define OMEGA_DATTN_SM_S 4096u /* s[256][8] f32: 8192; reused as the reduce buffer r[8 warps][256] */ -#define OMEGA_DATTN_SM_M 12288u /* m[8 warps][8] then the head maxes M[8]: 256 + 32 */ -#define OMEGA_DATTN_SM_L 12576u /* l[8 warps][8]: 256 */ -#define OMEGA_DATTN_SM_FLAG 12832u /* the atomic's old value: 16 */ -#define OMEGA_DATTN_SM_K 12864u /* k_new[128] f32 staging: 512 */ -#define OMEGA_DATTN_SHARED_BYTES 13376u - -typedef struct { - uint32_t depth; /* prefetch depth of the K and V streams, 1..4 */ - int mutant; /* TEST ONLY. 0 none; 1 no RoPE on q and k; 2 V read one position late; 3 the new K/V are not - * written to the cache; 4 the cross-split combine ignores the max (differs only when splits > 1). */ -} OmegaDecodeAttnSpec; - -/* Builds the IR program (register-allocated) into *prog. 0 ok, -1 refused (depth 0 or > 4, mutant outside 0..4, - * or the program outgrew BW_MAX_IR_INSNS / BW_MAX_VREGS). */ -int omega_blackwell_codegen_decode_attn_prog(const OmegaDecodeAttnSpec *spec, BlackwellIRProgram *prog); -/* Instruction and peak-register counts of the program (host, no device). */ -int omega_decode_attn_prog_stats(const OmegaDecodeAttnSpec *spec, uint32_t *insns, uint32_t *gprs); - -#endif diff --git a/src/omega_blackwell_codegen_bf16.c b/src/omega_blackwell_codegen_bf16.c deleted file mode 100644 index 08125e6c6..000000000 --- a/src/omega_blackwell_codegen_bf16.c +++ /dev/null @@ -1,262 +0,0 @@ -/* omega_blackwell_codegen_bf16.c: bf16 streaming GEMV kernel (the lm_head), OWN-30B 2026-10-13. See the header. - * The emitter helpers below are copies of omega_blackwell_codegen_moe.c's (same chip-learned scheduling rules: every - * instruction waits on everything still pending; variable-latency results go through scoreboard 0, stores set the read - * barrier 1, uniform loads scoreboard 2; fixed-latency producers stall 6; ISETP stalls 14 before a predicated branch; - * loads of one iteration are issued back to back so a warp has all of them in flight at once). */ -#include "omega_blackwell_codegen_bf16.h" -#ifndef OMEGA_GPU_NO_POSIX -#include -#endif -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - /* Loads read their address operands late (the read barrier SB_RD): a later instruction must not overwrite an - * in-flight load's address register. Every load sets SB_RD and the next load of a batch waits on it (cheap: - * the operand read, not the data). Found on the chip: the deep k=2048 kernel hung when the allocator reused a - * dead scale address register as the next load's destination (evidence OWN30B-FP8-GEMV-c4006391). */ - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - /* a further load of the same group: waits on nothing, joins the counting scoreboard */ - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; /* BAR.SYNC after the STS: the attention kernel's chip-proven pattern */ - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } - -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c */ -static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -/* a forward branch whose target is patched when known: returns the instruction index */ -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} - -/* Loops: a value defined before the loop and read inside it stays live until the back-branch - * (the linear-scan allocator knows no back edges; same rule as the elementwise emitter). */ -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - - -static int spec_ok(const OmegaBf16GemvSpec *s) { - if (!s) return 0; - if (s->rows != 1 && s->rows != 2 && s->rows != 4) return 0; - if (s->warps < 1 || s->warps > 32) return 0; - if (s->k == 0 || s->k > OMEGA_BF16_MAX_K || s->k % 256u || s->k % (32u * s->warps)) return 0; - if (s->k > 512u * s->warps) return 0; /* at most 16 staging rounds */ - uint32_t ks = s->k / 256u; - if (s->depth == 0 || s->depth > 16 || ks % s->depth || s->rows * s->depth > 16u) return 0; - if (s->mutant < 0 || s->mutant > 3) return 0; - if ((uint64_t)(s->rows - 1) * s->k * 2u + 512u * s->depth >= (1u << 23)) return 0; /* 24-bit signed LDG immediate */ - return 1; -} -uint32_t omega_bf16_gemv_steps(const OmegaBf16GemvSpec *spec) { return spec_ok(spec) ? spec->k / 256u : 0; } -uint32_t omega_bf16_gemv_shared_bytes(const OmegaBf16GemvSpec *spec) { return spec_ok(spec) ? spec->k * 4u : 0u; } - -int omega_blackwell_codegen_bf16_gemv_prog(const OmegaBf16GemvSpec *spec, BlackwellIRProgram *prog) { - if (!spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, R = spec->rows, W = spec->warps, D = spec->depth, KS = K / 256u; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue ---- */ - int udesc = UV64(e), pwb = V64(e), px = V64(e), py = V64(e), rgn = V(e), stride = V(e); - int tid = V(e), cx = V(e), warp = V(e), lane = V(e), one = V(e); - int wlane = V(e), rg = V(e), xl0 = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pwb, OMEGA_BF16_ARG_W); ldc64(e, px, OMEGA_BF16_ARG_X); ldc64(e, py, OMEGA_BF16_ARG_Y); - ldc32(e, rgn, OMEGA_BF16_ARG_RG); ldc32(e, stride, OMEGA_BF16_ARG_STRIDE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31); - imadi(e, wlane, lane, 0, 16, NOREG); /* byte offset of this lane's chunk in a row step */ - imadi(e, rg, cx, 0, W, warp); /* first row group of this warp */ - imadi(e, xl0, lane, 0, 32, NOREG); /* this lane's x chunk (8 floats) of step 0, shared byte offset */ - - /* ---- stage x (k floats) in shared memory: one 32-bit word per thread per round ---- */ - { - const uint32_t rounds = K / (32u * W); - int pxt = V64(e), sa0 = V(e), sa = V(e), pxs[16], xst[16]; - for (uint32_t j = 0; j < rounds; j++) { pxs[j] = V64(e); xst[j] = V(e); } - if (e->err) return -1; - imadw(e, pxt, tid, 4, px); - imadi(e, sa0, tid, 0, 4, NOREG); - for (uint32_t j = 0; j < rounds; j++) imadw(e, pxs[j], one, j * 128u * W, pxt); - for (uint32_t j = 0; j < rounds; j++) ldg32(e, xst[j], pxs[j], udesc, j == 0); - for (uint32_t j = 0; j < rounds; j++) { imadi(e, sa, one, 0, j * 128u * W, sa0); sts32(e, sa, xst[j]); } - bar_sync(e); - } - - int pw = V64(e), pwr = V64(e), xl = V(e), cnt = V(e), pyr = V64(e), pya = V64(e), t = V(e), f = V(e); - int acc[4], wq[4][16], xq[2]; - for (uint32_t r = 0; r < R; r++) { acc[r] = V(e); for (uint32_t s = 0; s < D; s++) wq[r][s] = V128(e); } - xq[0] = V128(e); xq[1] = V128(e); - if (e->err) return -1; - - /* ---- row-group loop ---- */ - const int L_rg = here(e); - loop_begin(e); - isetp_ge_u32(e, rg, rgn); - const int bra_end = bra_if_p0_fwd(e); - imadw(e, pwr, rg, R * K * 2u, pwb); imadw(e, pw, wlane, 1, pwr); - imadi(e, xl, xl0, 0, 1, NOREG); - for (uint32_t r = 0; r < R; r++) movrz(e, acc[r]); - movi(e, cnt, KS / D); - - /* ---- K loop: D steps per iteration, every load issued before any use ---- */ - const int L_k = here(e); - loop_begin(e); - { - int first = 1; - for (uint32_t s = 0; s < D; s++) for (uint32_t r = 0; r < R; r++) { ldg_wide(e, BW_IR_LDG_E_128, wq[r][s], pw, r * K * 2u + s * OMEGA_BF16_STEP_BYTES, udesc, first); first = 0; } - } - for (uint32_t s = 0; s < D; s++) { - const uint32_t xoff = spec->mutant == 2 ? 0u : s * 1024u; - lds128(e, xq[0], xl, xoff, 1); lds128(e, xq[1], xl, xoff + 16u, 0); - for (uint32_t r = 0; r < R; r++) { - const uint32_t words = spec->mutant == 3 ? 3u : 4u; - for (uint32_t word = 0; word < words; word++) { - const int q = xq[word >> 1]; const unsigned sub = (word & 1u) * 2u; - /* low half = element 2 word, high half = element 2 word + 1 */ - imadi(e, f, wq[r][s], word, 65536u, NOREG); - ffma(e, acc[r], f, q, spec->mutant == 1 ? sub + 1u : sub, acc[r]); - andi(e, f, wq[r][s], word, 0xffff0000u); - ffma(e, acc[r], f, q, spec->mutant == 1 ? sub : sub + 1u, acc[r]); - } - } - } - imadw(e, pw, one, D * OMEGA_BF16_STEP_BYTES, pw); - imadi(e, xl, one, 0, spec->mutant == 2 ? 0u : D * 1024u, xl); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_k); - loop_end(e); - - /* ---- warp reduction, lane 0 stores ---- */ - for (uint32_t r = 0; r < R; r++) - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[r], o); fadd(e, acc[r], acc[r], t); } - imadw(e, pyr, rg, R * 4u, py); - isetp_ge_u32(e, lane, one); - const int at_bssy = bssy_fwd(e); - const int bra_skip = bra_if_p0_fwd(e); - for (uint32_t r = 0; r < R; r++) { imadw(e, pya, one, r * 4u, pyr); stg(e, pya, 0, acc[r], udesc); } - const int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - imadi(e, rg, stride, 0, 1, rg); - bra(e, L_rg); - loop_end(e); - const int L_end = here(e); - patch_bra(e, bra_end, L_end); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_bf16_gemv_prog_stats(const OmegaBf16GemvSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_bf16_gemv_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_bf16_gemv(const OmegaBf16GemvSpec *spec, OmegaBlackwellKernel *kernel) { - if (!kernel) return -1; - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog) return -1; - int rc = omega_blackwell_codegen_bf16_gemv_prog(spec, prog); - size_t need = rc == 0 ? omega_bw_program_code_bytes(prog) : 0; - uint8_t *buf = need ? malloc(need) : NULL; - if (!buf) { free(prog); return -1; } - rc = omega_blackwell_kernel_encode_into(prog, buf, need, kernel); - free(prog); - if (rc != 0) { free(buf); return -1; } - return 0; -} -#endif diff --git a/src/omega_blackwell_codegen_bf16.h b/src/omega_blackwell_codegen_bf16.h deleted file mode 100644 index c7a22cdfd..000000000 --- a/src/omega_blackwell_codegen_bf16.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_BF16_H -#define OMEGA_BLACKWELL_CODEGEN_BF16_H -/* - * omega_blackwell_codegen_bf16: bf16 streaming GEMV (the lm_head: vocab x hidden, bf16 weights, f32 x and y) for the - * OWN-30B lane (2026-10-13). New file; it mirrors the structure of omega_blackwell_codegen_moe.c (the FP8 GEMV) with - * no scales and no group table. - * - * y[r] = sum_c W[r][c] * x[c], W bf16 row-major [n][k], x f32 [k], y f32 [n], f32 accumulate. - * - * bf16 -> f32 is exact and free: element 2i of a 32-bit weight word is (word << 16), element 2i+1 is - * (word & 0xFFFF0000). Thread mapping (as the FP8 kernel): a CTA has `warps` warps; warp w of CTA cx handles row - * groups rg = cx * warps + w, rg + stride, ... < RG (RG = n / rows, a row group is `rows` consecutive rows). Per K - * step a warp reads 512 contiguous bytes of each of its rows (lane L: one LDG.E.128 = 8 bf16 at byte 16 L); the CTA - * stages the whole x row in shared memory once (k * 4 bytes, one BAR.SYNC) and every loop iteration issues the loads - * of `depth` K steps of all its rows before using any of them. Per lane the 8 x depth x rows products of a row - * accumulate in one FFMA chain (element order: step, word, low half, high half), then a SHFL.DOWN tree (16,8,4,2,1) - * and lane 0 stores. - * - * Constant bank 0 argument words (cbank + 0x380): - * 0x380 w u64 weights base (row r at w + r * k * 2) - * 0x388 x u64 x row (f32, k) - * 0x390 y u64 y (f32, n) - * 0x398 RG u32 row groups (n / rows) - * 0x39c stride u32 row groups per warp iteration (grid_x * warps) - * Grid: grid_x CTAs, grid_y = 1. The kernel does not depend on n or the grid: one kernel per (k, rows, warps, depth, - * mutant) serves every n. - * - * mutant (tests only): 1 pairs the two halves of every word with the wrong x (low half takes the high half's x and - * back), 2 never advances the x pointer (every step uses step 0's x: wrong whenever KS >= 2), 3 drops the last word - * of each lane chunk. Each must be caught by the parity test. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_BF16_MAX_K 16384u -#define OMEGA_BF16_ARG_W 0x380u -#define OMEGA_BF16_ARG_X 0x388u -#define OMEGA_BF16_ARG_Y 0x390u -#define OMEGA_BF16_ARG_RG 0x398u -#define OMEGA_BF16_ARG_STRIDE 0x39cu -#define OMEGA_BF16_ARGS_WORDS 8u -#define OMEGA_BF16_STEP_BYTES 512u /* weight bytes per row per K step (32 lanes x 16) */ - -typedef struct { - uint32_t k; /* multiple of 256 (one step) and of 32 * warps (exact staging rounds), <= OMEGA_BF16_MAX_K */ - uint32_t rows; /* rows per warp: 1, 2 or 4 */ - uint32_t warps; /* 1 .. 32 (the host simulator runs up to 8) */ - uint32_t depth; /* K steps per loop iteration: divides k / 256; rows * depth <= 16 */ - int mutant; /* 0 production; 1, 2, 3 as above */ -} OmegaBf16GemvSpec; - -int omega_blackwell_codegen_bf16_gemv_prog(const OmegaBf16GemvSpec *spec, BlackwellIRProgram *prog); -int omega_blackwell_codegen_bf16_gemv(const OmegaBf16GemvSpec *spec, OmegaBlackwellKernel *kernel); -/* K steps: k / 256 (0 when refused). */ -uint32_t omega_bf16_gemv_steps(const OmegaBf16GemvSpec *spec); -/* Shared bytes the launch declares: k * 4. */ -uint32_t omega_bf16_gemv_shared_bytes(const OmegaBf16GemvSpec *spec); -int omega_bf16_gemv_prog_stats(const OmegaBf16GemvSpec *spec, uint32_t *insns, uint32_t *gprs); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_dec.c b/src/omega_blackwell_codegen_dec.c deleted file mode 100644 index b2ec67d7f..000000000 --- a/src/omega_blackwell_codegen_dec.c +++ /dev/null @@ -1,368 +0,0 @@ -/* - * omega_blackwell_codegen_dec.c: decode glue kernels (see the header). The emitter helpers are the router's - * (omega_blackwell_codegen_router.c): control words, read barrier on every load, loop live ranges, lane-0 regions. - */ -#include "omega_blackwell_codegen_dec.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn i; memset(&i, 0, sizeof i); - i.op = op; i.dst_vreg = NOREG; i.src1_vreg = NOREG; i.src2_vreg = NOREG; i.src3_vreg = NOREG; i.ureg = NOREG; - return i; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -typedef struct { int v; unsigned s; } Op; -static Op R(int v) { Op o = { v, 0 }; return o; } -static Op S(int v, unsigned s) { Op o = { v, s }; return o; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, Op d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; emit(e, i, K_FIXED); } -static void imadi(Em *e, Op d, Op a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } -static void shr(Em *e, int d, int a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, Op d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, Op d, Op a, Op b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; emit(e, i, K_FIXED); } -static void lop3(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut; emit(e, i, K_FIXED); } -static void ldg(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void stg(Em *e, int addr64, Op val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, Op val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fop(Em *e, BlackwellIROpcode op, Op d, Op a, Op b, Op c) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; - i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; i.src3_vreg = c.v; i.src3_subreg = (uint8_t)c.s; emit(e, i, K_FIXED); -} -static void fadd(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FADD, d, a, b, R(NOREG)); } -static void fmul(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMUL, d, a, b, R(NOREG)); } -static void ffma(Em *e, Op d, Op a, Op b, Op c) { fop(e, BW_IR_FFMA, d, a, b, c); } -static void fmaxx(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MAX, d, a, b, R(NOREG)); } -static void fminn(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MIN, d, a, b, R(NOREG)); } -static void mufu(Em *e, BlackwellIROpcode op, Op d, Op a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; emit(e, i, K_VAR); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void exit_k(Em *e) { emit(e, I0(BW_IR_EXIT), K_EXIT); } -static void tail(Em *e) { - exit_k(e); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} -typedef struct { int bssy, bra; } Region; -static Region region_skip_if_p0(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } -static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } -static void ne_of(Em *e, int ne, Op a, Op b, int t, int t2) { - xorr(e, R(t), a, b); - imadi(e, R(t2), R(t), 0xffffffffu, NOREG); - lop3(e, t, t, t2, NOREG, 0xfcu); - shr(e, ne, t, 31); -} -static void warp_sum(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fadd(e, R(v), R(v), R(t)); } } -static void warp_max(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fmaxx(e, R(v), R(v), R(t)); } } -static void warp_min(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fminn(e, R(v), R(v), R(t)); } } -static void lane0_sts(Em *e, int lane, int one, int addr, Op v) { - isetp_ge_u32(e, lane, one); - Region r = region_skip_if_p0(e); sts32(e, addr, v); region_end(e, r); -} -/* the 8 per-warp partials at shared [base]: reduce with op (0 sum, 1 max, 2 min) into d (every thread) */ -static void cta_reduce8(Em *e, int d, uint32_t base, int op, int a0) { - int q0 = V128(e), q1 = V128(e); - if (e->err) return; - movi(e, a0, base); - lds128(e, q0, a0, 0, 1); lds128(e, q1, a0, 16, 0); - mov(e, R(d), S(q0, 0)); - for (unsigned i = 1; i < 8; i++) { - Op s = i < 4 ? S(q0, i) : S(q1, i - 4); - if (op == 0) fadd(e, R(d), R(d), s); else if (op == 1) fmaxx(e, R(d), R(d), s); else fminn(e, R(d), R(d), s); - } -} - -static const uint32_t C_INV2048 = 0x3A000000u; /* 1/2048 */ -static const uint32_t C_NLOG2E = 0xBFB8AA3Bu; /* -1.4426950f */ -static const uint32_t C_ONE = 0x3F800000u; -static const uint32_t C_2P23 = 0x4B000000u; - -static int gen_axpy(Em *e, const OmegaDecSpec *sp) { - if (sp->stride == 0 || sp->stride % OMEGA_DEC_THREADS) return -1; - int udesc = UV64(e), px = V64(e), pa = V64(e), iters = V(e), tid = V(e), cta = V(e), gid = V(e), it = V(e), one = V(e); - int xa = V64(e), aa = V64(e), xv = V(e), av = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, px, OMEGA_DEC_AXPY_X); ldc64(e, pa, OMEGA_DEC_AXPY_A); ldc32(e, iters, OMEGA_DEC_AXPY_ITERS); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadi(e, R(gid), R(cta), OMEGA_DEC_THREADS, tid); - imadw(e, xa, gid, 4u, px); imadw(e, aa, gid, 4u, pa); - movrz(e, R(it)); movi(e, one, 1); - const int L = here(e); - loop_begin(e); - isetp_ge_u32(e, it, iters); - const int done = bra_if_p0_fwd(e); - ldg(e, BW_IR_LDG_E, xv, xa, 0, udesc, 1); ldg(e, BW_IR_LDG_E, av, aa, 0, udesc, 0); - fadd(e, R(xv), R(xv), R(av)); - stg(e, xa, R(xv), udesc); - imadw(e, xa, one, sp->stride * 4u, xa); imadw(e, aa, one, sp->stride * 4u, aa); - imadi(e, R(it), R(one), 1u, it); - bra(e, L); - loop_end(e); - patch_bra(e, done, here(e)); - tail(e); - return e->err; -} - -static int gen_res(Em *e, const OmegaDecSpec *sp) { - const uint32_t M = sp->mode; - if (M == 0 || M > 7 || ((M & OMEGA_DEC_RES_ADD) && (M & OMEGA_DEC_RES_COMBINE))) return -1; - int udesc = UV64(e), px = V64(e), pa = V64(e), pw = V64(e), pnw = V64(e), py = V64(e), eps = V(e), scale = V(e); - int tid = V(e), warp = V(e), lane = V(e), one = V(e), toff = V(e), t = V(e), t2 = V(e), a0 = V(e); - int xa = V64(e), xq0 = V128(e), xq1 = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, px, OMEGA_DEC_RES_X); ldc64(e, pa, OMEGA_DEC_RES_A); ldc64(e, pw, OMEGA_DEC_RES_W); ldc64(e, pnw, OMEGA_DEC_RES_NW); ldc64(e, py, OMEGA_DEC_RES_Y); - ldc32(e, eps, OMEGA_DEC_RES_EPS); ldc32(e, scale, OMEGA_DEC_RES_SCALE); - s2r(e, tid, BW_SR_TID_X); - movi(e, one, 1); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - imadi(e, R(toff), R(tid), 32u, NOREG); - imadw(e, xa, toff, 1u, px); - ldg(e, BW_IR_LDG_E_128, xq0, xa, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, xq1, xa, 16, udesc, 0); - Op x[8]; - for (unsigned i = 0; i < 8; i++) x[i] = i < 4 ? S(xq0, i) : S(xq1, i - 4); - if (M & OMEGA_DEC_RES_ADD) { - int aa = V64(e), aq0 = V128(e), aq1 = V128(e); - if (e->err) return -1; - imadw(e, aa, toff, 1u, pa); - ldg(e, BW_IR_LDG_E_128, aq0, aa, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, aq1, aa, 16, udesc, 0); - for (unsigned i = 0; i < 8; i++) fadd(e, x[i], x[i], i < 4 ? S(aq0, i) : S(aq1, i - 4)); - } - if (M & OMEGA_DEC_RES_COMBINE) { - int wq0 = V128(e), wq1 = V128(e), da = V64(e), dq0 = V128(e), dq1 = V128(e), m[8]; - for (unsigned i = 0; i < 8; i++) m[i] = V(e); - if (e->err) return -1; - ldg(e, BW_IR_LDG_E_128, wq0, pw, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, wq1, pw, 16, udesc, 0); - imadw(e, da, toff, 1u, pa); - const unsigned G = sp->mutant == 2 ? 7u : 8u; - for (unsigned g = 0; g < G; g++) { - ldg(e, BW_IR_LDG_E_128, dq0, da, g * OMEGA_DEC_HIDDEN * 4u, udesc, 1); ldg(e, BW_IR_LDG_E_128, dq1, da, g * OMEGA_DEC_HIDDEN * 4u + 16u, udesc, 0); - Op w = g < 4 ? S(wq0, g) : S(wq1, g - 4); - for (unsigned i = 0; i < 8; i++) { - Op d = i < 4 ? S(dq0, i) : S(dq1, i - 4); - if (g == 0) fmul(e, R(m[i]), w, d); - else { fmul(e, R(t), w, d); fadd(e, R(m[i]), R(m[i]), R(t)); } - } - } - for (unsigned i = 0; i < 8; i++) fadd(e, x[i], x[i], R(m[i])); - } - if (M & (OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_COMBINE)) { - int sa = V64(e); - if (e->err) return -1; - for (unsigned i = 0; i < 8; i++) { if (i == 0) imadw(e, sa, toff, 1u, px); else imadw(e, sa, one, 4u, sa); stg(e, sa, x[i], udesc); } - } - if (M & OMEGA_DEC_RES_NORM) { - int sq = V(e), rs = V(e), na = V64(e), nq0 = V128(e), nq1 = V128(e), ya = V64(e), yv = V(e); - if (e->err) return -1; - imadw(e, na, toff, 1u, pnw); - ldg(e, BW_IR_LDG_E_128, nq0, na, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, nq1, na, 16, udesc, 0); - fmul(e, R(sq), x[0], x[0]); - for (unsigned i = 1; i < 8; i++) ffma(e, R(sq), x[i], x[i], R(sq)); - warp_sum(e, sq, t); - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_DEC_SM_RED, a0); - lane0_sts(e, lane, one, a0, R(sq)); - bar_sync(e); - cta_reduce8(e, sq, OMEGA_DEC_SM_RED, 0, a0); - movi(e, t2, C_INV2048); - ffma(e, R(rs), R(sq), R(t2), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); - imadw(e, ya, toff, 1u, py); - for (unsigned i = 0; i < 8; i++) { - fmul(e, R(yv), x[i], R(rs)); - if (sp->mutant != 1) fmul(e, R(yv), R(yv), i < 4 ? S(nq0, i) : S(nq1, i - 4)); - fmul(e, R(yv), R(yv), R(scale)); - if (i) imadw(e, ya, one, 4u, ya); - stg(e, ya, R(yv), udesc); - } - } - tail(e); - return e->err; -} - -static int gen_swiglu(Em *e, const OmegaDecSpec *sp) { - int udesc = UV64(e), pgu = V64(e), pact = V64(e), scale = V(e), tid = V(e), cx = V(e), cy = V(e), c = V(e), gi = V(e), ai = V(e); - int ga = V64(e), ua = V64(e), aa = V64(e), gv = V(e), uv = V(e), t = V(e), cst = V(e), ui = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pgu, OMEGA_DEC_SW_GU); ldc64(e, pact, OMEGA_DEC_SW_ACT); ldc32(e, scale, OMEGA_DEC_SW_SCALE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - imadi(e, R(c), R(cx), OMEGA_DEC_THREADS, tid); - imadi(e, R(gi), R(cy), 2u * OMEGA_DEC_INTER, c); - imadi(e, R(ai), R(cy), OMEGA_DEC_INTER, c); - /* the up half sits INTER floats after the gate: its own address (the 32-bit LDG.E encoding carries no immediate - * offset, omega_blackwell_codegen.c BW_IR_LDG_E; the warp simulator caught the dropped offset, 2026-10-13) */ - movi(e, cst, sp->mutant == 1 ? OMEGA_DEC_INTER - 1u : OMEGA_DEC_INTER); - imadi(e, R(ui), R(cst), 1u, gi); - imadw(e, ga, gi, 4u, pgu); - imadw(e, ua, ui, 4u, pgu); - imadw(e, aa, ai, 4u, pact); - ldg(e, BW_IR_LDG_E, gv, ga, 0, udesc, 1); - ldg(e, BW_IR_LDG_E, uv, ua, 0, udesc, 0); - movi(e, cst, C_NLOG2E); - fmul(e, R(t), R(gv), R(cst)); - mufu(e, BW_IR_MUFU_EX2, R(t), R(t)); - movi(e, cst, C_ONE); - fadd(e, R(t), R(t), R(cst)); - mufu(e, BW_IR_MUFU_RCP, R(t), R(t)); - fmul(e, R(t), R(gv), R(t)); - fmul(e, R(t), R(t), R(uv)); - fmul(e, R(t), R(t), R(scale)); - stg(e, aa, R(t), udesc); - tail(e); - return e->err; -} - -static int gen_argmax(Em *e, const OmegaDecSpec *sp) { - const int indexed = sp->mode == 1; - int udesc = UV64(e), pv = V64(e), pi = V64(e), pov = V64(e), poi = V64(e); - int tid = V(e), cta = V(e), warp = V(e), lane = V(e), one = V(e), gid = V(e), off = V(e), t = V(e), t2 = V(e), a0 = V(e); - int va = V64(e), vq0 = V128(e), vq1 = V128(e), iq0 = 0, iq1 = 0, m = V(e), mx = V(e), ne = V(e), cand = V(e), best = V(e), c2p23 = V(e), idx = V(e); - if (indexed) { iq0 = V128(e); iq1 = V128(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pv, OMEGA_DEC_AM_V); ldc64(e, pi, OMEGA_DEC_AM_I); ldc64(e, pov, OMEGA_DEC_AM_OV); ldc64(e, poi, OMEGA_DEC_AM_OI); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); movi(e, c2p23, C_2P23); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - imadi(e, R(gid), R(cta), OMEGA_DEC_THREADS, tid); - imadi(e, R(off), R(gid), 32u, NOREG); - imadw(e, va, off, 1u, pv); - ldg(e, BW_IR_LDG_E_128, vq0, va, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, vq1, va, 16, udesc, 0); - if (indexed) { - imadw(e, va, off, 1u, pi); - ldg(e, BW_IR_LDG_E_128, iq0, va, 0, udesc, 0); ldg(e, BW_IR_LDG_E_128, iq1, va, 16, udesc, 0); - } - Op v[8]; - for (unsigned j = 0; j < 8; j++) v[j] = j < 4 ? S(vq0, j) : S(vq1, j - 4); - const unsigned J = sp->mutant == 1 ? 7u : 8u; - mov(e, R(m), v[0]); - for (unsigned j = 1; j < J; j++) fmaxx(e, R(m), R(m), v[j]); - warp_max(e, m, t); - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_DEC_SM_RED, a0); - lane0_sts(e, lane, one, a0, R(m)); - bar_sync(e); - cta_reduce8(e, mx, OMEGA_DEC_SM_RED, 1, a0); - /* lowest index holding mx: candidate float bits 0x4B000000 | idx, lifted by 0x30000000 where v != mx */ - for (unsigned j = 0; j < J; j++) { - if (indexed) mov(e, R(idx), j < 4 ? S(iq0, j) : S(iq1, j - 4)); - else imadi(e, R(idx), R(gid), 8u, NOREG), imadi(e, R(idx), R(one), j, idx); - lop3(e, idx, idx, c2p23, NOREG, 0xfcu); - ne_of(e, ne, v[j], R(mx), t, t2); - imadi(e, R(cand), R(ne), 0x30000000u, idx); - if (j == 0) mov(e, R(best), R(cand)); else fminn(e, R(best), R(best), R(cand)); - } - warp_min(e, best, t); - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_DEC_SM_RED2, a0); - lane0_sts(e, lane, one, a0, R(best)); - bar_sync(e); - cta_reduce8(e, best, OMEGA_DEC_SM_RED2, 2, a0); - andi(e, R(best), R(best), 0x7fffffu); - isetp_ge_u32(e, tid, one); - { - Region r = region_skip_if_p0(e); - int oa = V64(e); - if (e->err) return -1; - imadw(e, oa, cta, 4u, pov); stg(e, oa, R(mx), udesc); - imadw(e, oa, cta, 4u, poi); stg(e, oa, R(best), udesc); - region_end(e, r); - } - tail(e); - return e->err; -} - -int omega_blackwell_codegen_dec_prog(const OmegaDecSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - int rc; - switch (spec->kind) { - case OMEGA_DEC_AXPY: rc = gen_axpy(&em, spec); break; - case OMEGA_DEC_RES: rc = gen_res(&em, spec); break; - case OMEGA_DEC_SWIGLU: rc = gen_swiglu(&em, spec); break; - case OMEGA_DEC_ARGMAX: rc = gen_argmax(&em, spec); break; - default: return -1; - } - if (rc != 0 || em.err || em.depth != 0) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_dec_prog_stats(const OmegaDecSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_dec_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} diff --git a/src/omega_blackwell_codegen_dec.h b/src/omega_blackwell_codegen_dec.h deleted file mode 100644 index 0ea33231e..000000000 --- a/src/omega_blackwell_codegen_dec.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_DEC_H -#define OMEGA_BLACKWELL_CODEGEN_DEC_H -/* - * omega_blackwell_codegen_dec: the small glue kernels that keep a Qwen3-30B decode token on the chip (OWN-30B W-L2, - * 2026-10-13). Before them the host did the residual adds, the input RMSNorm, SwiGLU, the expert combine and the - * argmax between launches; with them a whole token is one command list (omega_gpu_cmdlist.h). - * - * AXPY x[i] += a[i] in place over iters * stride elements (grid-stride, uniform trip count). Chip test only: a - * chain of these in one list catches overlapping grids (a lost increment). - * RES one CTA of 256 threads over the 2048-wide residual row, 8 values per thread. Mode bits: - * ADD x += a (a = o_proj output) - * COMBINE x += sum_g w[g] * d[g] (g = 0..7, as the host: m = w0*d0, then m = m + w_g*d_g, x = x + m) - * NORM y = x * RSQ(mean(x^2) + eps) * nw * scale (scale 2^64 = the FP8 GEMV x' row, 1 = plain) - * x is written back when ADD or COMBINE is set. - * SWIGLU act[g][c] = silu(gu[g][c]) * gu[g][768 + c] * scale, g = ctaid.y (8 experts), c = ctaid.x * 256 + tid - * (grid 3 x 8). silu(v) = v * RCP(1 + EX2(-v * log2 e)). - * ARGMAX CTA c reads 2048 values v[c*2048 + 8*tid + j] (and indices, or the identity index), writes the max and the - * lowest index holding it to out_v[c], out_i[c]. Two launches give the greedy token of 151936 logits - * (75 CTAs, then 1 CTA over the 75 partials padded with -1e30). The lowest-index rule is the host's - * sample_argmax (strict >). Max by FMNMX, the index by the router's trick (float 2^23 + idx, lifted when the - * value differs from the max, FMNMX.MIN). No FSETP / FSEL. - * - * Constant bank: addresses at 0x380 + 8n, then scalars (offsets below). Every load carries the read barrier, as in the - * other OWN-30B emitters. - */ -#include "omega_blackwell_codegen.h" -#include - -typedef enum { OMEGA_DEC_AXPY = 1, OMEGA_DEC_RES = 2, OMEGA_DEC_SWIGLU = 3, OMEGA_DEC_ARGMAX = 4 } OmegaDecKind; - -#define OMEGA_DEC_RES_ADD 1u -#define OMEGA_DEC_RES_COMBINE 2u -#define OMEGA_DEC_RES_NORM 4u - -#define OMEGA_DEC_HIDDEN 2048u -#define OMEGA_DEC_THREADS 256u -#define OMEGA_DEC_TOPK 8u -#define OMEGA_DEC_INTER 768u -#define OMEGA_DEC_ARGMAX_SPAN 2048u /* values per ARGMAX CTA */ - -/* AXPY args */ -#define OMEGA_DEC_AXPY_X 0x380u -#define OMEGA_DEC_AXPY_A 0x388u -#define OMEGA_DEC_AXPY_ITERS 0x390u -#define OMEGA_DEC_AXPY_WORDS 5u -/* RES args */ -#define OMEGA_DEC_RES_X 0x380u /* f32 [2048] residual, read and (ADD/COMBINE) written */ -#define OMEGA_DEC_RES_A 0x388u /* ADD: f32 [2048]; COMBINE: f32 [8][2048] down outputs */ -#define OMEGA_DEC_RES_W 0x390u /* COMBINE: f32 [8] routing weights */ -#define OMEGA_DEC_RES_NW 0x398u /* NORM: f32 [2048] norm weight */ -#define OMEGA_DEC_RES_Y 0x3a0u /* NORM: f32 [2048] output */ -#define OMEGA_DEC_RES_EPS 0x3a8u -#define OMEGA_DEC_RES_SCALE 0x3acu -#define OMEGA_DEC_RES_WORDS 12u -/* SWIGLU args */ -#define OMEGA_DEC_SW_GU 0x380u /* f32 [8][1536] gate|up */ -#define OMEGA_DEC_SW_ACT 0x388u /* f32 [8][768] */ -#define OMEGA_DEC_SW_SCALE 0x390u -#define OMEGA_DEC_SW_WORDS 5u -/* ARGMAX args */ -#define OMEGA_DEC_AM_V 0x380u /* f32 values, CTA c reads [c*2048, +2048) */ -#define OMEGA_DEC_AM_I 0x388u /* u32 indices (indexed spec), same layout */ -#define OMEGA_DEC_AM_OV 0x390u /* f32 [ctas] */ -#define OMEGA_DEC_AM_OI 0x398u /* u32 [ctas] */ -#define OMEGA_DEC_AM_WORDS 8u - -#define OMEGA_DEC_SM_RED 0u /* 8 per-warp partials */ -#define OMEGA_DEC_SM_RED2 64u -#define OMEGA_DEC_SHARED_BYTES 128u - -typedef struct { - OmegaDecKind kind; - uint32_t mode; /* RES mode bits; ARGMAX: 1 = indexed (indices loaded), 0 = identity */ - uint32_t stride; /* AXPY: elements per iteration (grid_x * 256) */ - int mutant; /* TEST ONLY. RES: 1 = norm without the weight; 2 = COMBINE skips expert 7. - SWIGLU: 1 = up half read at +767. ARGMAX: 1 = last equal index instead of first. 0 none */ -} OmegaDecSpec; - -int omega_blackwell_codegen_dec_prog(const OmegaDecSpec *spec, BlackwellIRProgram *prog); -int omega_dec_prog_stats(const OmegaDecSpec *spec, uint32_t *insns, uint32_t *gprs); - -#endif diff --git a/src/omega_blackwell_codegen_gemm.c b/src/omega_blackwell_codegen_gemm.c deleted file mode 100644 index b804ce0da..000000000 --- a/src/omega_blackwell_codegen_gemm.c +++ /dev/null @@ -1,343 +0,0 @@ -/* omega_blackwell_codegen_gemm.c: FP8 e4m3 block-scaled grouped GEMM for prefill (OWN-30B builder F item 26). See the - * header for the contract. The emitter helpers are copies of omega_blackwell_codegen_moe.c's (same chip-learned - * scheduling rules) plus one addition: weight and scale prefetch loads use scoreboards 3 (buffer A) and 4 (buffer B) - * and are waited for only by the step that decodes them, so the next step's weights stream while this step computes. */ -#include "omega_blackwell_codegen_gemm.h" -#ifndef OMEGA_GPU_NO_POSIX -#include -#endif -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending, held; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - /* Loads read their address operands late (the read barrier SB_RD): a later instruction must not overwrite an - * in-flight load's address register. Every load sets SB_RD and the next load of a batch waits on it (cheap: - * the operand read, not the data). Found on the chip: the deep k=2048 kernel hung when the allocator reused a - * dead scale address register as the next load's destination (evidence OWN30B-FP8-GEMV-c4006391). */ - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - /* a further load of the same group: waits on nothing, joins the counting scoreboard */ - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; /* BAR.SYNC after the STS: the attention kernel's chip-proven pattern */ - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c */ -static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -/* a forward branch whose target is patched when known: returns the instruction index */ -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} - -/* Loops: a value defined before the loop and read inside it stays live until the back-branch - * (the linear-scan allocator knows no back edges; same rule as the elementwise emitter). */ -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - - -/* A weight/scale prefetch load: scoreboard `sb` (3 or 4) is held, not waited for, until consume() */ -static void ldw_pf(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, unsigned sb) { - BlackwellIRInsn in = I0(op); in.dst_vreg = d; in.src1_vreg = addr64; in.imm = imm; in.ureg = udesc; - in.control = CW(4, sb, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; - e->pending |= 1u << SB_RD; e->held |= 1u << sb; - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} -static void consume(Em *e, unsigned sb) { e->pending |= e->held & (1u << sb); e->held &= ~(1u << sb); } - -static int log2u(uint32_t v) { int l = 0; while ((1u << l) < v) l++; return (1u << l) == v ? l : -1; } - -static int spec_ok(const OmegaFp8GemmSpec *s) { - if (!s) return 0; - if (s->lane_bytes != 8 && s->lane_bytes != 16) return 0; - if (s->mt == 0 || (s->mt & (s->mt - 1)) || s->mt * 128u * s->lane_bytes > OMEGA_GEMM_MAX_SHARED) return 0; - if (s->warps < 1 || s->warps > 32 || (s->warps & (s->warps - 1)) || (s->mt * s->lane_bytes) % s->warps) return 0; /* power-of-two warps: the staging words per thread are whole */ - if (s->k == 0 || s->k > 16384u || s->k % 128u || s->k % (32u * s->lane_bytes)) return 0; - uint32_t ks = s->k / (32u * s->lane_bytes); - if (ks % 2u && ks > 3u) return 0; /* odd step counts are fully unrolled: at most 3 */ - if (s->mutant < 0 || s->mutant > 3) return 0; - return 1; -} -uint32_t omega_fp8gemm_steps(const OmegaFp8GemmSpec *spec) { return spec_ok(spec) ? spec->k / (32u * spec->lane_bytes) : 0; } -uint32_t omega_fp8gemm_shared_bytes(const OmegaFp8GemmSpec *spec) { return spec_ok(spec) ? spec->mt * 128u * spec->lane_bytes : 0u; } - -/* e4m3 byte i of word w -> f32 bits (value * 2^-120): ((b & 0x7F) << 20) | ((b & 0x80) << 24) */ -static void decode_byte(Em *e, int f, int wq, unsigned word, unsigned i, int u, int a, int s) { - const uint32_t M = 0x07F00000u; - if (i < 3) imadi(e, u, wq, word, 1u << (20u - 8u * i), NOREG); - else shr(e, u, wq, word, 4); - andi(e, a, u, 0, M); - andi(e, s, wq, word, 0x80u << (8u * i)); - if (i < 3) imadi(e, f, s, 0, 1u << (24u - 8u * i), a); - else imadi(e, f, s, 0, 1u, a); -} - -int omega_blackwell_codegen_fp8gemm_prog(const OmegaFp8GemmSpec *spec, BlackwellIRProgram *prog) { - if (!spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, LB = spec->lane_bytes, MT = spec->mt, W = spec->warps; - const uint32_t KS = K / (32u * LB), BPS = 32u * LB / 128u, LPB = 128u / LB, KB = K / 128u, WORDS = LB / 4u; - const uint32_t U = KS % 2u == 0 ? 2u : KS; /* K steps per loop iteration (the A/B register sets alternate) */ - const uint32_t NJ = MT * LB / W, ROWW = 32u * LB, T = 32u * W; /* staging words per thread, rows per staging j, words per row slab */ - const int log2lpb = log2u(LPB), log2mt = log2u(MT), log2roww = log2u(ROWW); - const BlackwellIROpcode ldw = LB == 16 ? BW_IR_LDG_E_128 : BW_IR_LDG_E_64; - if (log2lpb < 0 || log2mt < 0 || log2roww < 0) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue ---- */ - int udesc = UV64(e), pseg = V64(e), px = V64(e), py = V64(e), nreg = V(e), stride = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), tent = V64(e); - int wbase = V64(e), sbase = V64(e), rc = V64(e), row0 = V(e), cnt = V(e), tpass = V(e), passes = V(e); - int wlane = V(e), slane = V(e), xl = V(e), nm1 = V(e), ysn = V(e), mrow = V(e), off4 = V(e), sa0 = V(e), base = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pseg, OMEGA_GEMM_ARG_SEG); ldc64(e, px, OMEGA_GEMM_ARG_X); ldc64(e, py, OMEGA_GEMM_ARG_Y); - ldc32(e, nreg, OMEGA_GEMM_ARG_N); ldc32(e, stride, OMEGA_GEMM_ARG_STRIDE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31); - imadw(e, tent, cy, OMEGA_GEMM_SEG_BYTES, pseg); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, sbase, tent, 8, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, rc, tent, 16, udesc, 0); - imadi(e, row0, rc, 0, 1, NOREG); imadi(e, cnt, rc, 1, 1, NOREG); - imadi(e, tpass, one, 0, MT - 1u, cnt); shr(e, passes, tpass, 0, (uint32_t)log2mt); - imadi(e, wlane, lane, 0, LB, NOREG); - shr(e, slane, lane, 0, (uint32_t)log2lpb); imadi(e, slane, slane, 0, 4, NOREG); - imadi(e, xl, lane, 0, 16, NOREG); - imadi(e, nm1, one, 0, 0xffffffffu, nreg); - imadi(e, ysn, nreg, 0, 4, NOREG); - shr(e, mrow, tid, 0, (uint32_t)log2roww); - andi(e, off4, tid, 0, ROWW - 1u); imadi(e, off4, off4, 0, 4, NOREG); - imadi(e, sa0, tid, 0, 4, NOREG); - imadi(e, base, cx, 0, W, NOREG); - - /* loop-wide registers */ - int rg = V(e), over = V(e), t1 = V(e), d = V(e), tmp = V(e), rgc = V(e), lo = V(e); - int pw = V64(e), ps = V64(e), pyrg = V64(e), rowp = V(e), rem = V(e), pc = V(e); - int xrp = V64(e), xs = V64(e), pwc = V64(e), psc = V64(e), cntk = V(e), pyr = V64(e), pya = V64(e), t = V(e), tq = V(e), fl = V(e), sv = V(e); - int acc[16], dot[16], xq[4], wq[2], sc[2], fr[4], u = V(e), a = V(e), sg = V(e), onef = V(e), dum = V(e); - for (uint32_t m = 0; m < MT; m++) { acc[m] = V(e); dot[m] = V(e); } - for (int q = 0; q < 4; q++) xq[q] = V128(e); - for (int b = 0; b < 2; b++) { wq[b] = LB == 16 ? V128(e) : V64(e); sc[b] = V(e); } - for (int i = 0; i < 4; i++) fr[i] = V(e); - if (e->err) return -1; - - /* ---- weight-row loop (uniform per CTA) ---- */ - const int L_rg = here(e); - loop_begin(e); - isetp_ge_u32(e, base, nreg); - const int bra_end = bra_if_p0_fwd(e); - imadi(e, rg, base, 0, 1, warp); - imadi(e, t1, rg, 0, 0xffffffffu, nm1); shr(e, over, t1, 0, 31); /* over = (rg > n - 1) */ - imadi(e, d, nm1, 0, 0xffffffffu, rg); /* rg - (n - 1) */ - imadr(e, tmp, over, d, NOREG); imadi(e, rgc, tmp, 0, 0xffffffffu, rg); /* rg clamped to n - 1 */ - imadw(e, pw, rgc, K, wbase); imadw(e, pw, wlane, 1, pw); - shr(e, tmp, rgc, 0, 7); - imadw(e, ps, tmp, KB * 4u, sbase); imadw(e, ps, slane, 1, ps); - imadw(e, pyrg, rg, 4, py); - imadi(e, lo, over, 0, 1, lane); - imadi(e, rowp, row0, 0, 1, NOREG); imadi(e, rem, cnt, 0, 1, NOREG); imadi(e, pc, passes, 0, 1, NOREG); - - /* ---- pass loop: MT rows of x per pass ---- */ - const int L_pass = here(e); - loop_begin(e); - imadi(e, t, rowp, 0, 1, mrow); imadw(e, xrp, t, K * 4u, px); imadw(e, xrp, off4, 1, xrp); - imadw(e, xs, one, 0, xrp); - imadw(e, pwc, one, 0, pw); imadw(e, psc, one, 0, ps); - for (uint32_t m = 0; m < MT; m++) movrz(e, acc[m]); - ldw_pf(e, ldw, wq[0], pwc, 0, udesc, 3); - ldw_pf(e, BW_IR_LDG_E, sc[0], psc, 0, udesc, 3); - movi(e, cntk, KS / U); - - /* ---- K loop: U steps per iteration ---- */ - const int L_k = here(e); - loop_begin(e); - for (uint32_t us = 0; us < U; us++) { - const int cur = (int)(us & 1u), nxt = 1 - cur; - const unsigned sbc = cur ? 4u : 3u, sbn = nxt ? 4u : 3u; - /* addresses first (fixed-latency ops would otherwise wait for the loads below), then loads back to back; the - * staging words go in rounds of 4 so the temporaries stay few */ - const int last = us + 1 == U, prefetch = !last || KS > U; - int pwn = -1, psn = -1; - if (prefetch) { pwn = V64(e); psn = V64(e); } - int sa = V(e); - if (e->err) return -1; - if (prefetch && !last) { - imadw(e, pwn, one, (us + 1) * 32u * LB, pwc); imadw(e, psn, one, spec->mutant == 2 ? 0u : (us + 1) * BPS * 4u, psc); - } else if (prefetch) { /* the next iteration's step 0; the last iteration re-reads its own step (harmless, drained after the loop) */ - int nf = V(e), inc = V(e), inc2 = V(e); - if (e->err) return -1; - imadi(e, nf, one, 0, 0xfffffffeu, cntk); /* cntk - 2 */ - shr(e, nf, nf, 0, 31); /* 1 iff cntk == 1 (the last iteration) */ - imadi(e, nf, nf, 0, 0xffffffffu, one); /* 1 iff another iteration follows */ - imadi(e, inc, nf, 0, U * 32u * LB, NOREG); imadi(e, inc2, nf, 0, spec->mutant == 2 ? 0u : U * BPS * 4u, NOREG); - imadw(e, pwn, inc, 1, pwc); imadw(e, psn, inc2, 1, psc); - } - for (uint32_t j0 = 0; j0 < NJ; j0 += 4) { - const uint32_t nj = NJ - j0 < 4 ? NJ - j0 : 4; - int xv[4], xa[4]; - for (uint32_t q = 0; q < nj; q++) { xv[q] = V(e); xa[q] = V64(e); } - if (e->err) return -1; - for (uint32_t q = 0; q < nj; q++) { const uint32_t pos = (j0 + q) * T; imadw(e, xa[q], one, ((pos / ROWW) * K + pos % ROWW) * 4u, xs); } - for (uint32_t q = 0; q < nj; q++) ldg32(e, xv[q], xa[q], udesc, q == 0); - if (prefetch && j0 == 0) { - ldw_pf(e, ldw, wq[nxt], pwn, 0, udesc, sbn); - ldw_pf(e, BW_IR_LDG_E, sc[nxt], psn, 0, udesc, sbn); - } - for (uint32_t q = 0; q < nj; q++) { imadi(e, sa, one, 0, (j0 + q) * T * 4u, sa0); sts32(e, sa, xv[q]); } - } - bar_sync(e); - consume(e, sbc); - /* compute */ - for (uint32_t m = 0; m < MT; m++) movrz(e, dot[m]); - for (uint32_t word = 0; word < WORDS; word++) { - for (unsigned i = 0; i < 4; i++) decode_byte(e, fr[i], wq[cur], word, i, u, a, sg); - for (uint32_t m0 = 0; m0 < MT; m0 += 4) { - const uint32_t nb = MT - m0 < 4 ? MT - m0 : 4; - for (uint32_t q = 0; q < nb; q++) { - const uint32_t m = m0 + q, mm = spec->mutant == 3 ? (m ^ 1u) % MT : m; - lds128(e, xq[q], xl, mm * ROWW * 4u + word * 512u, q == 0); - } - for (uint32_t q = 0; q < nb; q++) for (unsigned i = 0; i < 4; i++) ffma(e, dot[m0 + q], fr[i], xq[q], i, dot[m0 + q]); - } - } - if (spec->mutant == 1) { movi(e, onef, 0x3f800000u); ffma(e, dum, sc[cur], onef, 0, onef); } /* scales dropped, but the scale load stays consumed */ - for (uint32_t m = 0; m < MT; m++) { - if (spec->mutant == 1) ffma(e, acc[m], dot[m], onef, 0, acc[m]); - else ffma(e, acc[m], dot[m], sc[cur], 0, acc[m]); - } - bar_sync(e); - imadw(e, xs, one, ROWW * 4u, xs); - } - imadw(e, pwc, one, U * 32u * LB, pwc); - imadw(e, psc, one, spec->mutant == 2 ? 0u : U * BPS * 4u, psc); - imadi(e, cntk, one, 0, 0xffffffffu, cntk); - isetp_ge_u32(e, cntk, one); - bra_if_p0(e, L_k); - loop_end(e); - consume(e, 3); consume(e, 4); - - /* ---- reduce and store, per row of the pass ---- */ - for (uint32_t m = 0; m < MT; m++) - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[m], o); fadd(e, acc[m], acc[m], t); } - imadr(e, tq, rowp, ysn, NOREG); imadw(e, pyr, tq, 1, pyrg); - for (uint32_t m = 0; m < MT; m++) { - imadi(e, tq, one, 0, (uint32_t)(0u - 1u - m), rem); shr(e, fl, tq, 0, 31); /* 1 iff m >= rem: past this segment's rows */ - imadi(e, sv, fl, 0, 1, lo); - isetp_ge_u32(e, sv, one); - const int at_bssy = bssy_fwd(e); - const int bra_skip = bra_if_p0_fwd(e); - imadw(e, pya, ysn, m, pyr); stg(e, pya, 0, acc[m], udesc); - const int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - } - imadi(e, rowp, one, 0, MT, rowp); imadi(e, rem, one, 0, (uint32_t)(0u - MT), rem); - imadi(e, pc, one, 0, 0xffffffffu, pc); - isetp_ge_u32(e, pc, one); - bra_if_p0(e, L_pass); - loop_end(e); - - imadi(e, base, stride, 0, 1, base); - bra(e, L_rg); - loop_end(e); - const int L_end = here(e); - patch_bra(e, bra_end, L_end); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_fp8gemm_prog_stats(const OmegaFp8GemmSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_fp8gemm_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} diff --git a/src/omega_blackwell_codegen_gemm.h b/src/omega_blackwell_codegen_gemm.h deleted file mode 100644 index 7bcfba2cc..000000000 --- a/src/omega_blackwell_codegen_gemm.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_GEMM_H -#define OMEGA_BLACKWELL_CODEGEN_GEMM_H -/* - * omega_blackwell_codegen_gemm: FP8 e4m3 block-128-scaled grouped GEMM for PREFILL (OWN-30B, 2026-10-13, builder F - * item 26). New file; it mirrors omega_blackwell_codegen_moe.c (the FP8 GEMV) so that its result is bit-identical to - * that GEMV on the same row. - * - * for every segment g (one expert, `cnt` rows of x'): y[row0 + i][r] = sum_c W_g[r][c] * x'[row0 + i][c] * S_g[r/128][c/128] - * - * Each distinct expert's weights are streamed once per pass of MT rows (one pass for the typical expert: 4 rows at 64 - * tokens), not once per token. A warp owns one weight row r and keeps MT f32 accumulators; per K step the lane decodes - * its LB weight bytes once (the GEMV's exact bit trick) and FFMAs them into the MT rows' dot products, then - * acc[m] = fma(dot[m], S', acc[m]) once per 128-block exactly as the GEMV, then the same SHFL.DOWN tree. - * - * x' rows arrive PRE-PERMUTED by the host (omega_gpu_fp8gemm_api): for a row, column c = s*32*LB + L*LB + w*4 + e - * (K step s, lane L, word w, element e) sits at index s*32*LB + (w*32 + L)*4 + e, scaled by 2^64 as the GEMV. The CTA - * stages one K step of MT rows (MT*32*LB*4 <= 16384 bytes: the QMD shared-memory limit of omega_blackwell_qmd.h) in - * shared memory, so every lane reads its 4 columns of every row with one conflict-free LDS.128. Per step: stage, - * BAR.SYNC, compute, BAR.SYNC. The weights and scales of step s+1 are loaded before step s computes (two register - * sets, scoreboards 3 and 4 held until the step that uses them). - * - * Segment table (device, 32 bytes per segment, ctaid.y = segment): { w_va u64, s_va u64, row0 u32, cnt u32, pad[8] }. - * Constant bank 0 argument words (cbank + 0x380): - * 0x380 seg u64 segment table - * 0x388 xp u64 permuted x' rows, f32, k per row; MT padding rows must follow the last segment - * 0x390 y u64 y rows (f32, n each), row i = sorted row i - * 0x398 n u32 output rows per segment (weight rows) - * 0x39c stride u32 weight rows per warp iteration (grid_x * warps) - * Grid: grid_x CTAs per segment (each CTA: `warps` weight rows per iteration), grid_y = segments. All warps of a CTA - * execute the same trip counts (rows past n are clamped to n-1 and not stored; rows past cnt in the last pass read - * padding and are not stored), so the CTA barriers are uniform. - * - * mutant (tests only): 1 drops the block scale (acc += dot), 2 never advances the scale pointer (wrong when KS >= 2), - * 3 reads the neighbouring row's x (m ^ 1) for every row. Each must be caught. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GEMM_ARG_SEG 0x380u -#define OMEGA_GEMM_ARG_X 0x388u -#define OMEGA_GEMM_ARG_Y 0x390u -#define OMEGA_GEMM_ARG_N 0x398u -#define OMEGA_GEMM_ARG_STRIDE 0x39cu -#define OMEGA_GEMM_ARGS_WORDS 8u -#define OMEGA_GEMM_SEG_BYTES 32u -#define OMEGA_GEMM_MAX_SHARED 16384u - -typedef struct { - uint32_t k; /* multiple of 128 and of 32 * lane_bytes; <= 16384 */ - uint32_t lane_bytes; /* 8 or 16 (the GEMV's choice: 16 when k % 512 == 0, else 8) */ - uint32_t mt; /* rows per pass: a power of two, mt * 128 * lane_bytes <= 16384 */ - uint32_t warps; /* warps % lane_bytes == 0, (mt * lane_bytes) % warps == 0, 1 .. 32 (host simulator: build with -DWS_MAX_THREADS=512) */ - int mutant; -} OmegaFp8GemmSpec; - -int omega_blackwell_codegen_fp8gemm_prog(const OmegaFp8GemmSpec *spec, BlackwellIRProgram *prog); -uint32_t omega_fp8gemm_shared_bytes(const OmegaFp8GemmSpec *spec); /* 0 when refused */ -uint32_t omega_fp8gemm_steps(const OmegaFp8GemmSpec *spec); -int omega_fp8gemm_prog_stats(const OmegaFp8GemmSpec *spec, uint32_t *insns, uint32_t *gprs); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_moe.c b/src/omega_blackwell_codegen_moe.c deleted file mode 100644 index 14d9d5c4f..000000000 --- a/src/omega_blackwell_codegen_moe.c +++ /dev/null @@ -1,328 +0,0 @@ -/* omega_blackwell_codegen_moe.c: FP8 e4m3 block-scaled GEMV kernel (OWN-30B Cut 6 / Cut 5). - * See the header for the contract and the argument words. - * - * Scheduling: the same chip-learned rules as omega_gpu_elementwise_api.c (every instruction - * waits on everything still pending; variable-latency results go through scoreboard 0, stores - * set the read barrier 1, uniform loads scoreboard 2; fixed-latency producers stall 6; ISETP - * stalls 14 before a predicated branch). Loads of one K step are issued back to back (all set - * SB0, only the first waits), so a warp has every load of the step in flight at once. - */ -#include "omega_blackwell_codegen_moe.h" -#ifndef OMEGA_GPU_NO_POSIX -#include -#endif -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - /* Loads read their address operands late (the read barrier SB_RD): a later instruction must not overwrite an - * in-flight load's address register. Every load sets SB_RD and the next load of a batch waits on it (cheap: - * the operand read, not the data). Found on the chip: the deep k=2048 kernel hung when the allocator reused a - * dead scale address register as the next load's destination (evidence OWN30B-FP8-GEMV-c4006391). */ - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - /* a further load of the same group: waits on nothing, joins the counting scoreboard */ - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; /* BAR.SYNC after the STS: the attention kernel's chip-proven pattern */ - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c */ -static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -/* a forward branch whose target is patched when known: returns the instruction index */ -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} - -/* Loops: a value defined before the loop and read inside it stays live until the back-branch - * (the linear-scan allocator knows no back edges; same rule as the elementwise emitter). */ -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - -static int log2u(uint32_t v) { int l = 0; while ((1u << l) < v) l++; return (1u << l) == v ? l : -1; } - -static int spec_ok(const OmegaFp8GemvSpec *s) { - if (!s) return 0; - if (s->lane_bytes != 8 && s->lane_bytes != 16) return 0; /* LDG.E (32-bit) carries no immediate offset: no 4-byte lanes */ - if (s->rows != 1 && s->rows != 2 && s->rows != 4 && s->rows != 8) return 0; - if (s->warps < 1 || s->warps > 32) return 0; /* threads_x = 32 * warps <= 1024 */ - if (s->k == 0 || s->k > OMEGA_FP8_MAX_K || s->k % OMEGA_FP8_BLOCK || s->k % (32u * s->lane_bytes)) return 0; - if (s->mutant < 0 || s->mutant > 3) return 0; - if (s->depth) { /* deep kernel: staging rounds (32-bit words, one per thread per round) must be exact and few */ - uint32_t ks = s->k / (32u * s->lane_bytes); - if (s->depth > 16 || ks % s->depth || s->rows * s->depth * s->lane_bytes > 128u) return 0; /* <= 128 weight bytes per lane per iteration: instruction and register budgets */ - if (s->k > 512u * s->warps) return 0; /* at most 16 staging rounds; a partial last round is clamped */ - } - /* row offsets of a step must fit the 24-bit signed LDG immediate */ - if ((uint64_t)(s->rows - 1) * s->k + s->lane_bytes >= (1u << 23)) return 0; - return 1; -} - -uint32_t omega_fp8_gemv_steps(const OmegaFp8GemvSpec *spec) { return spec_ok(spec) ? spec->k / (32u * spec->lane_bytes) : 0; } -uint32_t omega_fp8_gemv_shared_bytes(const OmegaFp8GemvSpec *spec) { return spec_ok(spec) && spec->depth ? spec->k * 4u + 16u : 0u; } /* + one dummy slot for the clamped threads of a partial round */ - -/* e4m3 byte i of word w -> f32 bits (value * 2^-120): ((b & 0x7F) << 20) | ((b & 0x80) << 24) */ -static void decode_byte(Em *e, int f, int wq, unsigned word, unsigned i, int u, int a, int s) { - const uint32_t M = 0x07F00000u; - if (i < 3) imadi(e, u, wq, word, 1u << (20u - 8u * i), NOREG); /* b at bits 20..27 */ - else shr(e, u, wq, word, 4); - andi(e, a, u, 0, M); - andi(e, s, wq, word, 0x80u << (8u * i)); - if (i < 3) imadi(e, f, s, 0, 1u << (24u - 8u * i), a); /* sign to bit 31, plus the magnitude */ - else imadi(e, f, s, 0, 1u, a); -} - -int omega_blackwell_codegen_fp8_gemv_prog(const OmegaFp8GemvSpec *spec, BlackwellIRProgram *prog) { - if (!spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, LB = spec->lane_bytes, R = spec->rows, W = spec->warps; - const uint32_t KS = K / (32u * LB), BPS = 32u * LB / OMEGA_FP8_BLOCK, LPB = OMEGA_FP8_BLOCK / LB, KB = K / OMEGA_FP8_BLOCK; - const int log2lpb = log2u(LPB), log2rows_per_block = log2u(OMEGA_FP8_BLOCK / R); - const uint32_t WORDS = LB / 4u; - const BlackwellIROpcode ldw = LB == 16 ? BW_IR_LDG_E_128 : BW_IR_LDG_E_64; - if (log2lpb < 0 || log2rows_per_block < 0) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue ---- */ - int udesc = UV64(e), ptab = V64(e), px = V64(e), py = V64(e); - int rgn = V(e), xs = V(e), ys = V(e), stride = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), gidx = V(e); - int tent = V64(e), wbase = V64(e), sbase = V64(e), off = V(e), xrow = V64(e), yrow = V64(e), xlane = V64(e); - int wlane = V(e), slane = V(e), rg = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ptab, OMEGA_FP8_ARG_TAB); ldc64(e, px, OMEGA_FP8_ARG_X); ldc64(e, py, OMEGA_FP8_ARG_Y); - ldc32(e, rgn, OMEGA_FP8_ARG_RG); ldc32(e, xs, OMEGA_FP8_ARG_XSTRIDE); ldc32(e, ys, OMEGA_FP8_ARG_YSTRIDE); ldc32(e, stride, OMEGA_FP8_ARG_STRIDE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31); - if (spec->mutant == 3) xorr(e, gidx, cy, one); else imadi(e, gidx, cy, 0, 1, NOREG); - imadw(e, tent, gidx, 16, ptab); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, sbase, tent, 8, udesc, 0); - imadr(e, off, cy, xs, NOREG); imadw(e, xrow, off, 1, px); - imadr(e, off, cy, ys, NOREG); imadw(e, yrow, off, 1, py); - imadw(e, xlane, lane, LB * 4u, xrow); /* this lane's x' chunk of step 0 */ - imadi(e, wlane, lane, 0, LB, NOREG); /* byte offset of this lane's chunk in a row */ - shr(e, slane, lane, 0, (uint32_t)log2lpb); imadi(e, slane, slane, 0, 4, NOREG); /* scale word of this lane in a step */ - imadi(e, rg, cx, 0, W, warp); /* first row group of this warp */ - - const uint32_t D = spec->depth ? spec->depth : 1u; /* K steps per loop iteration */ - const int deep = spec->depth != 0; - int pw = V64(e), ps = V64(e), pxc = V64(e), pyr = V64(e), pya = V64(e), srg = V(e), cnt = V(e); - int acc[8], wq[8][16], xq[4], sc[16], psd[16], xl = -1, xl0 = -1; - /* xq[word]: the 4 x floats of weight word `word` (one 16-byte quad each); wq[r][s]: row r, step s of the iteration */ - for (uint32_t r = 0; r < R; r++) { acc[r] = V(e); for (uint32_t s = 0; s < D; s++) wq[r][s] = LB == 16 ? V128(e) : V64(e); } - for (uint32_t q = 0; q < WORDS; q++) xq[q] = V128(e); - for (uint32_t s = 0; s < D; s++) { sc[s] = V(e); psd[s] = V64(e); } - int dot = V(e), u = V(e), a = V(e), sg = V(e), f = V(e), t = V(e); - if (e->err) return -1; - - if (deep) { - /* ---- stage this group's x' row in shared memory (k floats), one 32-bit word per thread per round ---- */ - const uint32_t rounds = (K + 32u * W - 1u) / (32u * W); - int pxt = V64(e), sa0 = V(e), sa = V(e), sap = V(e), pxs[16], xst[16], kq = V(e), over = V(e), tq = V(e), qs = V(e), qg = V(e); - for (uint32_t j = 0; j < rounds; j++) { pxs[j] = V64(e); xst[j] = V(e); } - xl = V(e); xl0 = V(e); - if (e->err) return -1; - imadw(e, pxt, tid, 4, xrow); - imadi(e, sa0, tid, 0, 4, NOREG); - for (uint32_t j = 0; j < rounds; j++) imadw(e, pxs[j], one, j * 128u * W, pxt); - if (K % (32u * W)) { - /* partial last round: word q = tid + j * 32 W may pass K. over = (q >= K) as 0/1 = (K - 1 - q) >> 31; - * the load is clamped to x[K - 1] and the store to the dummy slot K (never read). */ - const uint32_t j = rounds - 1u; - imadi(e, kq, tid, 0, 1, NOREG); imadi(e, kq, one, 0, j * 32u * W, kq); /* q */ - imadi(e, tq, kq, 0, 0xffffffffu, NOREG); imadi(e, tq, one, 0, K - 1u, tq); /* K - 1 - q */ - shr(e, over, tq, 0, 31); /* 1 iff q >= K */ - imadi(e, tq, kq, 0, 1, NOREG); imadi(e, tq, one, 0, (uint32_t)(0u - K), tq); /* q - K */ - imadr(e, qs, over, tq, NOREG); imadi(e, qs, qs, 0, 0xffffffffu, kq); /* q - over * (q - K): K when over */ - imadi(e, qg, tq, 0, 1, NOREG); imadi(e, qg, one, 0, 1, qg); /* q - K + 1 */ - imadr(e, qg, over, qg, NOREG); imadi(e, qg, qg, 0, 0xffffffffu, kq); /* K - 1 when over */ - imadw(e, pxs[j], qg, 4, xrow); - imadi(e, sap, qs, 0, 4, NOREG); - } - for (uint32_t j = 0; j < rounds; j++) ldg32(e, xst[j], pxs[j], udesc, j == 0); - for (uint32_t j = 0; j < rounds; j++) { - if (K % (32u * W) && j == rounds - 1u) { sts32(e, sap, xst[j]); continue; } - imadi(e, sa, one, 0, j * 128u * W, sa0); sts32(e, sa, xst[j]); - } - bar_sync(e); - imadi(e, xl0, lane, 0, LB * 4u, NOREG); /* this lane's x' chunk of step 0, shared byte offset */ - } - - /* ---- row-group loop ---- */ - const int L_rg = here(e); - loop_begin(e); - isetp_ge_u32(e, rg, rgn); - const int bra_end = bra_if_p0_fwd(e); - imadw(e, pw, rg, R * K, wbase); imadw(e, pw, wlane, 1, pw); - shr(e, srg, rg, 0, (uint32_t)log2rows_per_block); - imadw(e, ps, srg, KB * 4u, sbase); imadw(e, ps, slane, 1, ps); - if (!deep) imadw(e, pxc, one, 0, xlane); else imadi(e, xl, xl0, 0, 1, NOREG); - for (uint32_t r = 0; r < R; r++) movrz(e, acc[r]); - movi(e, cnt, KS / D); - - /* ---- K loop: D steps per iteration, every load of the iteration issued before any use ---- */ - const int L_k = here(e); - loop_begin(e); - { - int first = 1; - if (!deep) { for (uint32_t q = 0; q < WORDS; q++) { ldg_wide(e, BW_IR_LDG_E_128, xq[q], pxc, q * 16u, udesc, first); first = 0; } } - for (uint32_t s = 0; s < D; s++) imadw(e, psd[s], one, spec->mutant == 2 ? 0u : s * BPS * 4u, ps); - for (uint32_t s = 0; s < D; s++) for (uint32_t r = 0; r < R; r++) { ldg_wide(e, ldw, wq[r][s], pw, r * K + s * 32u * LB, udesc, first); first = 0; } - for (uint32_t s = 0; s < D; s++) ldg32(e, sc[s], psd[s], udesc, 0); - } - for (uint32_t s = 0; s < D; s++) { - if (deep) { int first = 1; for (uint32_t q = 0; q < WORDS; q++) { lds128(e, xq[q], xl, s * 128u * LB + q * 16u, first); first = 0; } } - for (uint32_t r = 0; r < R; r++) { - movrz(e, dot); - for (uint32_t word = 0; word < WORDS; word++) - for (unsigned i = 0; i < 4; i++) { - decode_byte(e, f, wq[r][s], word, i, u, a, sg); - ffma(e, dot, f, xq[word], i, dot); - } - if (spec->mutant == 1) fadd(e, acc[r], acc[r], dot); - else ffma(e, acc[r], dot, sc[s], 0, acc[r]); - } - } - imadw(e, pw, one, D * 32u * LB, pw); - if (!deep) imadw(e, pxc, one, 32u * LB * 4u, pxc); - imadw(e, ps, one, spec->mutant == 2 ? 0u : D * BPS * 4u, ps); - if (deep) imadi(e, xl, one, 0, D * 128u * LB, xl); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_k); - loop_end(e); - - /* ---- warp reduction, lane 0 stores ---- */ - for (uint32_t r = 0; r < R; r++) - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[r], o); fadd(e, acc[r], acc[r], t); } - imadw(e, pyr, rg, R * 4u, yrow); - isetp_ge_u32(e, lane, one); - const int at_bssy = bssy_fwd(e); - const int bra_skip = bra_if_p0_fwd(e); - for (uint32_t r = 0; r < R; r++) { imadw(e, pya, one, r * 4u, pyr); stg(e, pya, 0, acc[r], udesc); } /* STG.E with immediate 0 only (the chip-proven form) */ - const int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - imadi(e, rg, stride, 0, 1, rg); - bra(e, L_rg); - loop_end(e); - const int L_end = here(e); - patch_bra(e, bra_end, L_end); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_fp8_gemv_prog_stats(const OmegaFp8GemvSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; /* 1024 insns: too big for a stack frame in a test loop */ - if (omega_blackwell_codegen_fp8_gemv_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_fp8_gemv(const OmegaFp8GemvSpec *spec, OmegaBlackwellKernel *kernel) { - if (!kernel) return -1; - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog) return -1; - int rc = omega_blackwell_codegen_fp8_gemv_prog(spec, prog); - size_t need = rc == 0 ? omega_bw_program_code_bytes(prog) : 0; - uint8_t *buf = need ? malloc(need) : NULL; - if (!buf) { free(prog); return -1; } - rc = omega_blackwell_kernel_encode_into(prog, buf, need, kernel); - free(prog); - if (rc != 0) { free(buf); return -1; } - return 0; /* kernel->code points into buf; omega_blackwell_kernel_free releases it */ -} -#endif diff --git a/src/omega_blackwell_codegen_moe.h b/src/omega_blackwell_codegen_moe.h deleted file mode 100644 index 4140f2fc7..000000000 --- a/src/omega_blackwell_codegen_moe.h +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_MOE_H -#define OMEGA_BLACKWELL_CODEGEN_MOE_H -/* - * omega_blackwell_codegen_moe: FP8 (e4m3) GEMV kernel family for the OWN-30B MoE lane - * (Cut 6 + Cut 5, 2026-10-13). New file: nothing in omega_blackwell_codegen.{c,h} changes. - * - * One kernel: y[g][r] = sum_k W_g[r][k] * x[g or 0][k] * S_g[r/128][k/128], m = 1 (decode), for - * G groups (experts) in one launch. Weights are e4m3 bytes in the checkpoint's row-major - * [n][k] order (n output rows, k input columns), scales are the checkpoint's 128 x 128 - * `weight_scale_inv` grid, stored on the device as f32 (times 2^OMEGA_FP8_SCALE_EXP, see below). - * - * Numeric scheme (hand-checked bit arithmetic, proven exhaustively in tests/gpu_fp8_api_test.c): - * f32 bits ((b & 0x7F) << 20) | ((b & 0x80) << 24) equal e4m3(b) * 2^-120 exactly, for normals, - * subnormals and both zeros (bf16 field exponent 0 with the 3 mantissa bits shifted reproduces - * 2^-6 * 0.M). The e4m3 NaN codes 0x7F / 0xFF decode wrong (a finite number): the upload refuses - * them. The 2^120 is folded on the host: x' = x * 2^OMEGA_FP8_X_EXP and S' = S * 2^OMEGA_FP8_SCALE_EXP - * (64 + 56 = 120), chosen so that every product w' * x' is a normal f32 for any practical x. - * The kernel accumulates in f32: per lane, a dot of lane_bytes weights (FFMA chain), then - * acc_r = fma(dot, S', acc_r) once per 128-block, then a warp reduction (SHFL.DOWN) per row. - * - * Thread mapping: a CTA has `warps` warps (threads_x = 32 * warps, threads_y = 1); warp w of CTA - * (cx, cy) handles group cy and row groups rg = cx * warps + w, rg + stride, ... < RG (RG = n / rows, - * stride = grid_x * warps, both launch arguments). A row group is `rows` consecutive rows, inside - * one 128-row scale block (rows divides 128). Per K step a warp reads 32 * lane_bytes contiguous - * bytes of each of its rows (lane L: bytes [L * lane_bytes, +lane_bytes)), the same lane_bytes - * floats of x', and one scale word per lane (the block of its chunk; 128 / lane_bytes lanes share - * it). Step count KS = k / (32 * lane_bytes) is baked into the kernel; k must be a multiple of - * 32 * lane_bytes and of 128. - * - * Constant bank 0 argument words (cbank + 0x380, as the other APIs): - * 0x380 tab u64 group table: entry g at tab + 16 g = { w_va u64, s_va u64 } - * 0x388 x u64 x' rows (f32, k each; row g at x + g * x_stride) - * 0x390 y u64 y rows (f32, n each; row g at y + g * y_stride) - * 0x398 RG u32 row groups per group (n / rows) - * 0x39c x_stride u32 bytes between x rows (0: one x row shared by every group) - * 0x3a0 y_stride u32 bytes between y rows - * 0x3a4 stride u32 row groups per warp iteration (grid_x * warps) - * Grid: grid_x CTAs per group, grid_y = groups. The kernel does not depend on n, RG, the strides - * or the grid, so one kernel per (k, lane_bytes, rows, warps, mutant) serves every n and G. - * - * Only lane 0 of a warp stores (R words per row group) inside a BSSY/BSYNC region; the warp is - * whole again for the next row group's SHFLs. - * - * mutant (tests only, never production): 1 drops the block scale (acc += dot), 2 never advances the - * scale pointer (every K step uses the step-0 block: wrong whenever KS >= 2), 3 reads the group - * table entry of group cy ^ 1 (swapped bases). Each must be caught by the parity test. - * - * Instruction encodings: every IR op used here already exists in omega_blackwell_codegen.h; no new - * encodings were added. ISETP_GE (immediate) and IADD3 carry fixed control words in the encoder, - * so this generator uses ISETP_GE_U32 (register) and IMAD for adds instead. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_FP8_X_EXP 64 /* x' = x * 2^64 (host, exact) */ -#define OMEGA_FP8_SCALE_EXP 56 /* S' = S * 2^56 (host, exact for every finite bf16 scale below 2^72) */ -#define OMEGA_FP8_BLOCK 128u /* scale block (rows and columns) */ -#define OMEGA_FP8_MAX_K 16384u -#define OMEGA_FP8_MAX_GROUPS 64u /* group table entries per launch buffer (8 experts today) */ - -/* argument word offsets */ -#define OMEGA_FP8_ARG_TAB 0x380u -#define OMEGA_FP8_ARG_X 0x388u -#define OMEGA_FP8_ARG_Y 0x390u -#define OMEGA_FP8_ARG_RG 0x398u -#define OMEGA_FP8_ARG_XSTRIDE 0x39cu -#define OMEGA_FP8_ARG_YSTRIDE 0x3a0u -#define OMEGA_FP8_ARG_STRIDE 0x3a4u -#define OMEGA_FP8_ARGS_WORDS 10u - -typedef struct { - uint32_t k; /* input columns: multiple of 128 and of 32 * lane_bytes, <= OMEGA_FP8_MAX_K */ - uint32_t lane_bytes; /* 8 or 16 weight bytes per lane per step (LDG.E.64 / LDG.E.128); k must be a multiple of 256 */ - uint32_t rows; /* rows per warp: 1, 2, 4 or 8 */ - uint32_t warps; /* warps per CTA: 1 .. 32 (the host simulator runs up to 8) */ - uint32_t depth; /* 0: one K step per loop iteration, x read from global memory each step. - * D >= 1: "deep" kernel: the CTA stages its group's x' row in shared memory once - * (k * 4 bytes, BAR.SYNC), then every loop iteration issues the weight and scale - * loads of D consecutive K steps before using any of them (D x more bytes in - * flight per warp); x comes from shared memory (LDS.128). Needs KS % D == 0, - * rows * D * lane_bytes <= 128, k % (32 * warps) == 0 and k <= 512 * warps (staging rounds). */ - int mutant; /* 0 production; 1, 2, 3 as above */ -} OmegaFp8GemvSpec; - -/* 0 on success (prog solved and register-allocated), -1 on a refused spec or an allocator failure. */ -int omega_blackwell_codegen_fp8_gemv_prog(const OmegaFp8GemvSpec *spec, BlackwellIRProgram *prog); - -/* Hosted build: allocate and encode (omega_blackwell_kernel_free releases). */ -int omega_blackwell_codegen_fp8_gemv(const OmegaFp8GemvSpec *spec, OmegaBlackwellKernel *kernel); - -/* K steps the kernel runs: k / (32 * lane_bytes). 0 when the spec is refused. */ -uint32_t omega_fp8_gemv_steps(const OmegaFp8GemvSpec *spec); - -/* Shared memory bytes the launch must declare: k * 4 for a deep kernel, 0 otherwise. */ -uint32_t omega_fp8_gemv_shared_bytes(const OmegaFp8GemvSpec *spec); - -/* The IR instruction count and peak GPR count of the solved program (for budgets in tests). */ -int omega_fp8_gemv_prog_stats(const OmegaFp8GemvSpec *spec, uint32_t *insns, uint32_t *gprs); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_moe2.c b/src/omega_blackwell_codegen_moe2.c deleted file mode 100644 index 967822300..000000000 --- a/src/omega_blackwell_codegen_moe2.c +++ /dev/null @@ -1,342 +0,0 @@ -/* omega_blackwell_codegen_moe2.c: FP8 e4m3 block-scaled GEMV, variant 2 (row-pipelined). See the header. - * - * Scheduling: variant 1's chip-learned rules (every instruction waits on everything pending; variable-latency - * results through scoreboard 0, every load sets the read barrier 1 and the next load of a batch waits on it, - * uniform loads scoreboard 2; fixed-latency producers stall 6; ISETP stalls 14 before a predicated branch), - * plus one new rule: the loads of the NEXT row group land through scoreboard 3 (SB_B), which no instruction - * waits on except the register moves that take the set over (K_MOVB). The emitter's `pending` mask therefore - * never carries SB_B: the arithmetic of the current row group runs with the next one's loads in flight. - * Hazards covered: (1) the moves read set B before the next loads into B are issued (program order, fixed - * latency); (2) the address registers of a batch are protected by SB_RD as in variant 1; (3) every load that - * was issued is consumed by a move before EXIT (loads are issued iff the row group exists, and the loop runs - * exactly over the existing row groups). */ -#include "omega_blackwell_codegen_moe2.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define SB_B 3u -#define NOREG (-1) -#define MAX_LOOPS 4 -#define MAX_KS 16u -#define MAX_ROWS 8u - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC, K_LDB, K_LDB_MORE, K_MOVB }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - /* next-row-group loads: data on SB_B (not auto-waited), address operands on SB_RD (waited by the next instruction) */ - case K_LDB: in.control = CW(4, SB_B, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_LDB_MORE: in.control = CW(4, SB_B, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending = 1u << SB_RD; break; - /* the first move of set B into set A: the one wait on SB_B */ - case K_MOVB: in.control = CW(6, SB_NONE, SB_NONE, wait | (1u << SB_B)); e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -/* d[dsub] = s[ssub] (IMAD d = s * 1 + RZ, sub-register destination); kind K_MOVB for the first move of a set */ -static void movsub(Em *e, int d, unsigned dsub, int s, unsigned ssub, int kind) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = s; i.src1_subreg = (uint8_t)ssub; i.imm = 1; emit(e, i, kind); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int kind) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, kind); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int kind) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, kind); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, K_VAR); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c */ -static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} - -/* Loops: a value defined before the loop and read inside it stays live until the back-branch - * (the linear-scan allocator knows no back edges; same rule as variant 1). */ -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - -static int log2u(uint32_t v) { int l = 0; while ((1u << l) < v) l++; return (1u << l) == v ? l : -1; } - -int omega_fp8_gemv2_spec_ok(const OmegaFp8GemvSpec *s) { - if (!s) return 0; - if (s->lane_bytes != 8 && s->lane_bytes != 16) return 0; - if (s->rows != 1 && s->rows != 2 && s->rows != 4 && s->rows != 8) return 0; - if (s->warps < 1 || s->warps > 32) return 0; - if (s->k == 0 || s->k > OMEGA_FP8_MAX_K || s->k % OMEGA_FP8_BLOCK || s->k % (32u * s->lane_bytes)) return 0; - if (s->mutant < 0 || s->mutant > 3) return 0; - const uint32_t ks = s->k / (32u * s->lane_bytes); - if (ks > MAX_KS || s->rows * ks * s->lane_bytes > 128u) return 0; /* whole row group per register set */ - if (s->k > 512u * s->warps) return 0; /* at most 16 staging rounds */ - if ((uint64_t)(s->rows - 1) * s->k + s->lane_bytes >= (1u << 23)) return 0; - return 1; -} - -/* k * 4 for the staged row, plus one 16-byte dummy slot only when the last staging round is partial (clamped threads store there): - * k = 4096 at 16 warps is exact and lands on the QMD cap of 16384 bytes (chip: 16400 was refused, receipt OWN30B-FP8-GEMV-V2 r1). */ -uint32_t omega_fp8_gemv2_shared_bytes(const OmegaFp8GemvSpec *spec) { - if (!omega_fp8_gemv2_spec_ok(spec)) return 0u; - return spec->k * 4u + (spec->k % (32u * spec->warps) ? 16u : 0u); -} - -/* e4m3 byte i of word w -> f32 bits (value * 2^-120): ((b & 0x7F) << 20) | ((b & 0x80) << 24). Variant 1's sequence. */ -static void decode_byte(Em *e, int f, int wq, unsigned word, unsigned i, int u, int a, int s) { - const uint32_t M = 0x07F00000u; - if (i < 3) imadi(e, u, wq, word, 1u << (20u - 8u * i), NOREG); - else shr(e, u, wq, word, 4); - andi(e, a, u, 0, M); - andi(e, s, wq, word, 0x80u << (8u * i)); - if (i < 3) imadi(e, f, s, 0, 1u << (24u - 8u * i), a); - else imadi(e, f, s, 0, 1u, a); -} - -typedef struct { - int w[MAX_ROWS][MAX_KS]; /* weight bytes: row r, step s (quad or pair) */ - int sc[MAX_KS]; /* scale word per step */ -} RegSet; - -int omega_blackwell_codegen_fp8_gemv2_prog(const OmegaFp8GemvSpec *spec, BlackwellIRProgram *prog) { - if (!omega_fp8_gemv2_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, LB = spec->lane_bytes, R = spec->rows, W = spec->warps; - const uint32_t KS = K / (32u * LB), BPS = 32u * LB / OMEGA_FP8_BLOCK, LPB = OMEGA_FP8_BLOCK / LB, KB = K / OMEGA_FP8_BLOCK; - const int log2lpb = log2u(LPB), log2rows_per_block = log2u(OMEGA_FP8_BLOCK / R); - const uint32_t WORDS = LB / 4u; - const BlackwellIROpcode ldw = LB == 16 ? BW_IR_LDG_E_128 : BW_IR_LDG_E_64; - if (log2lpb < 0 || log2rows_per_block < 0) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue (variant 1's) ---- */ - int udesc = UV64(e), ptab = V64(e), px = V64(e), py = V64(e); - int rgn = V(e), xs = V(e), ys = V(e), stride = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), gidx = V(e); - int tent = V64(e), wbase = V64(e), sbase = V64(e), off = V(e), xrow = V64(e), yrow = V64(e); - int wlane = V(e), slane = V(e), rgl = V(e), rgc = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ptab, OMEGA_FP8_ARG_TAB); ldc64(e, px, OMEGA_FP8_ARG_X); ldc64(e, py, OMEGA_FP8_ARG_Y); - ldc32(e, rgn, OMEGA_FP8_ARG_RG); ldc32(e, xs, OMEGA_FP8_ARG_XSTRIDE); ldc32(e, ys, OMEGA_FP8_ARG_YSTRIDE); ldc32(e, stride, OMEGA_FP8_ARG_STRIDE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31); - if (spec->mutant == 3) xorr(e, gidx, cy, one); else imadi(e, gidx, cy, 0, 1, NOREG); - imadw(e, tent, gidx, 16, ptab); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, K_VAR); - ldg_wide(e, BW_IR_LDG_E_64, sbase, tent, 8, udesc, K_VAR_MORE); - imadr(e, off, cy, xs, NOREG); imadw(e, xrow, off, 1, px); - imadr(e, off, cy, ys, NOREG); imadw(e, yrow, off, 1, py); - imadi(e, wlane, lane, 0, LB, NOREG); /* byte offset of this lane's chunk in a row */ - shr(e, slane, lane, 0, (uint32_t)log2lpb); imadi(e, slane, slane, 0, 4, NOREG); /* scale word of this lane in a step */ - imadi(e, rgl, cx, 0, W, warp); /* first row group of this warp: the load cursor */ - imadi(e, rgc, rgl, 0, 1, NOREG); /* the compute cursor */ - - /* ---- registers: two sets, x quad, accumulators, temporaries ---- */ - RegSet A, B; - int acc[MAX_ROWS], dot[MAX_ROWS], xq = V128(e); - for (uint32_t r = 0; r < R; r++) { acc[r] = V(e); dot[r] = V(e); for (uint32_t s = 0; s < KS; s++) { A.w[r][s] = LB == 16 ? V128(e) : V64(e); B.w[r][s] = LB == 16 ? V128(e) : V64(e); } } - for (uint32_t s = 0; s < KS; s++) { A.sc[s] = V(e); B.sc[s] = V(e); } - int pw = V64(e), ps = V64(e), psd = V64(e), pyr = V64(e), pya = V64(e), srg = V(e), xl0 = V(e); - int u = V(e), a = V(e), sg = V(e), f = V(e), t = V(e); - if (e->err) return -1; - - /* ---- stage this group's x' row in shared memory (k floats), one 32-bit word per thread per round (variant 1 deep) ---- */ - { - const uint32_t rounds = (K + 32u * W - 1u) / (32u * W); - int pxt = V64(e), sa0 = V(e), sa = V(e), sap = V(e), pxs[16], xst[16], kq = V(e), over = V(e), tq = V(e), qs = V(e), qg = V(e); - for (uint32_t j = 0; j < rounds; j++) { pxs[j] = V64(e); xst[j] = V(e); } - if (e->err) return -1; - imadw(e, pxt, tid, 4, xrow); - imadi(e, sa0, tid, 0, 4, NOREG); - for (uint32_t j = 0; j < rounds; j++) imadw(e, pxs[j], one, j * 128u * W, pxt); - if (K % (32u * W)) { - const uint32_t j = rounds - 1u; - imadi(e, kq, tid, 0, 1, NOREG); imadi(e, kq, one, 0, j * 32u * W, kq); /* q */ - imadi(e, tq, kq, 0, 0xffffffffu, NOREG); imadi(e, tq, one, 0, K - 1u, tq); /* K - 1 - q */ - shr(e, over, tq, 0, 31); /* 1 iff q >= K */ - imadi(e, tq, kq, 0, 1, NOREG); imadi(e, tq, one, 0, (uint32_t)(0u - K), tq); /* q - K */ - imadr(e, qs, over, tq, NOREG); imadi(e, qs, qs, 0, 0xffffffffu, kq); /* K when over, else q */ - imadi(e, qg, tq, 0, 1, NOREG); imadi(e, qg, one, 0, 1, qg); /* q - K + 1 */ - imadr(e, qg, over, qg, NOREG); imadi(e, qg, qg, 0, 0xffffffffu, kq); /* K - 1 when over, else q */ - imadw(e, pxs[j], qg, 4, xrow); - imadi(e, sap, qs, 0, 4, NOREG); - } - for (uint32_t j = 0; j < rounds; j++) ldg32(e, xst[j], pxs[j], udesc, j == 0 ? K_VAR : K_VAR_MORE); - for (uint32_t j = 0; j < rounds; j++) { - if (K % (32u * W) && j == rounds - 1u) { sts32(e, sap, xst[j]); continue; } - imadi(e, sa, one, 0, j * 128u * W, sa0); sts32(e, sa, xst[j]); - } - bar_sync(e); - imadi(e, xl0, lane, 0, LB * 4u, NOREG); /* this lane's x' chunk of step 0, shared byte offset */ - } - - /* ---- the loads of one row group into set B (rows * KS weight loads, then KS scale words) ---- */ -#define ISSUE_B() do { \ - imadw(e, pw, rgl, R * K, wbase); imadw(e, pw, wlane, 1, pw); \ - shr(e, srg, rgl, 0, (uint32_t)log2rows_per_block); \ - imadw(e, ps, srg, KB * 4u, sbase); imadw(e, ps, slane, 1, ps); \ - int kind = K_LDB; \ - for (uint32_t s_ = 0; s_ < KS; s_++) for (uint32_t r_ = 0; r_ < R; r_++) { ldg_wide(e, ldw, B.w[r_][s_], pw, r_ * K + s_ * 32u * LB, udesc, kind); kind = K_LDB_MORE; } \ - for (uint32_t s_ = 0; s_ < KS; s_++) { \ - if (s_ == 0) ldg32(e, B.sc[0], ps, udesc, kind); \ - else { imadw(e, psd, one, spec->mutant == 2 ? 0u : s_ * BPS * 4u, ps); ldg32(e, B.sc[s_], psd, udesc, K_LDB_MORE); } \ - kind = K_LDB_MORE; \ - } \ - imadi(e, rgl, stride, 0, 1, rgl); \ - } while (0) - - /* ---- prologue: nothing to do, or the first row group's loads ---- */ - isetp_ge_u32(e, rgl, rgn); - const int bra_none = bra_if_p0_fwd(e); - ISSUE_B(); - - /* ---- row-group loop: take set B over, issue the next row group into B, compute set A, reduce, store ---- */ - const int L_rg = here(e); - loop_begin(e); - { - int kind = K_MOVB; - for (uint32_t s = 0; s < KS; s++) for (uint32_t r = 0; r < R; r++) for (uint32_t q = 0; q < WORDS; q++) { movsub(e, A.w[r][s], q, B.w[r][s], q, kind); kind = K_FIXED; } - for (uint32_t s = 0; s < KS; s++) movsub(e, A.sc[s], 0, B.sc[s], 0, K_FIXED); - } - isetp_ge_u32(e, rgl, rgn); - const int bra_skip_issue = bra_if_p0_fwd(e); - ISSUE_B(); - const int L_compute = here(e); - patch_bra(e, bra_skip_issue, L_compute); - for (uint32_t r = 0; r < R; r++) movrz(e, acc[r]); - for (uint32_t s = 0; s < KS; s++) { - for (uint32_t r = 0; r < R; r++) movrz(e, dot[r]); - for (uint32_t word = 0; word < WORDS; word++) { - lds128(e, xq, xl0, s * 128u * LB + word * 16u); - for (uint32_t r = 0; r < R; r++) - for (unsigned i = 0; i < 4; i++) { - decode_byte(e, f, A.w[r][s], word, i, u, a, sg); - ffma(e, dot[r], f, xq, i, dot[r]); - } - } - for (uint32_t r = 0; r < R; r++) { - if (spec->mutant == 1) fadd(e, acc[r], acc[r], dot[r]); - else ffma(e, acc[r], dot[r], A.sc[s], 0, acc[r]); - } - } - /* warp reduction, lane 0 stores (variant 1's sequence) */ - for (uint32_t r = 0; r < R; r++) - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[r], o); fadd(e, acc[r], acc[r], t); } - imadw(e, pyr, rgc, R * 4u, yrow); - isetp_ge_u32(e, lane, one); - const int at_bssy = bssy_fwd(e); - const int bra_skip = bra_if_p0_fwd(e); - for (uint32_t r = 0; r < R; r++) { imadw(e, pya, one, r * 4u, pyr); stg(e, pya, 0, acc[r], udesc); } - const int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - imadi(e, rgc, stride, 0, 1, rgc); - isetp_ge_u32(e, rgc, rgn); - const int bra_done = bra_if_p0_fwd(e); - bra(e, L_rg); - loop_end(e); -#undef ISSUE_B - const int L_end = here(e); - patch_bra(e, bra_none, L_end); - patch_bra(e, bra_done, L_end); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_fp8_gemv2_prog_stats(const OmegaFp8GemvSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; /* 1024 insns: too big for a stack frame in a test loop */ - if (omega_blackwell_codegen_fp8_gemv2_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} - -#ifndef OMEGA_GPU_NO_POSIX -#include -int omega_blackwell_codegen_fp8_gemv2(const OmegaFp8GemvSpec *spec, OmegaBlackwellKernel *kernel) { - if (!kernel) return -1; - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog) return -1; - int rc = omega_blackwell_codegen_fp8_gemv2_prog(spec, prog); - size_t need = rc == 0 ? omega_bw_program_code_bytes(prog) : 0; - uint8_t *buf = need ? malloc(need) : NULL; - if (!buf) { free(prog); return -1; } - rc = omega_blackwell_kernel_encode_into(prog, buf, need, kernel); - free(prog); - if (rc != 0) { free(buf); return -1; } - return 0; /* kernel->code points into buf; omega_blackwell_kernel_free releases it */ -} -#endif diff --git a/src/omega_blackwell_codegen_moe2.h b/src/omega_blackwell_codegen_moe2.h deleted file mode 100644 index ab32d3d97..000000000 --- a/src/omega_blackwell_codegen_moe2.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_MOE2_H -#define OMEGA_BLACKWELL_CODEGEN_MOE2_H -/* - * omega_blackwell_codegen_moe2: FP8 (e4m3) block-scaled GEMV, variant 2 ("row-pipelined"), OWN-30B - * W-L2c (2026-10-14). New file: omega_blackwell_codegen_moe.{c,h} (variant 1) are untouched; the API - * (omega_gpu_fp8_api.c) selects the variant (omega_gpu_fp8_set_variant / AIEN_OMEGA_FP8_GEMV=2). - * - * Same contract as variant 1 (same OmegaFp8GemvSpec, argument words, grid, thread mapping, lane - * mapping, group table, x' / S' folding, mutants) and the SAME ARITHMETIC ORDER per output row: - * per lane, per K step: dot = FFMA chain over its lane_bytes weights (word 0..W-1, byte 0..3); - * acc_r = fma(dot, S'_step, acc_r) in K order; then SHFL.DOWN 16, 8, 4, 2, 1 with FADD. - * so y is bit-identical to variant 1 for every input (checked by the simulator battery and on the chip). - * - * What changes is only WHEN the loads are issued (bytes in flight per warp): - * - a warp's unit of work is a whole row group (rows x k bytes): every weight load and scale load of - * the row group is issued back to back (rows * KS LDG.E.64/128 + KS scale words per lane); - * - two register sets: while the warp decodes and multiplies row group i (set A), the loads of row - * group i + stride (set B) are already in flight on their own scoreboard (SB3). Set A is filled by - * register moves from set B after a single wait on SB3, so the arithmetic never waits on the loads - * of the next row group (variant 1 waits for every load of a step before using any of them, and has - * nothing in flight while it computes); - * - x' (the activation row, shared by every row of the group) is staged once per CTA in shared memory - * (variant 1's deep-kernel staging, BAR.SYNC) and read per word with LDS.128 (4 registers), so the - * global loads a lane keeps in flight are weights and scales only. - * Register sets: 2 x (rows * KS * lane_bytes / 4 + KS) registers, plus ~30. The spec is refused unless - * rows * KS * lane_bytes <= 128 (instruction and register budgets) and k <= 512 * warps (staging rounds). - * The register-file rule (32 * warps * declared <= 65536) is checked by the API as for variant 1; the - * intended shapes are 16 warps per CTA (two CTAs per SM) at the OWN-30B widths k = 768, 2048, 4096. - * - * spec->depth is ignored (the whole row group is always in flight); spec->mutant 1, 2, 3 as variant 1. - */ -#include -#include "omega_blackwell_codegen_moe.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* 0 on success (prog solved and register-allocated), -1 on a refused spec or an allocator failure. */ -int omega_blackwell_codegen_fp8_gemv2_prog(const OmegaFp8GemvSpec *spec, BlackwellIRProgram *prog); - -/* 1 if the spec is one this variant builds (shape rules above), 0 otherwise. */ -int omega_fp8_gemv2_spec_ok(const OmegaFp8GemvSpec *spec); - -/* Shared memory bytes the launch must declare: k * 4 (the staged x' row) + 16 (a dummy slot, only when the last staging round is partial). 0 when refused. */ -uint32_t omega_fp8_gemv2_shared_bytes(const OmegaFp8GemvSpec *spec); - -/* Hosted build: allocate and encode (omega_blackwell_kernel_free releases). */ -int omega_blackwell_codegen_fp8_gemv2(const OmegaFp8GemvSpec *spec, OmegaBlackwellKernel *kernel); - -/* The IR instruction count and peak GPR count of the solved program (for budgets in tests). */ -int omega_fp8_gemv2_prog_stats(const OmegaFp8GemvSpec *spec, uint32_t *insns, uint32_t *gprs); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_pattn.c b/src/omega_blackwell_codegen_pattn.c deleted file mode 100644 index 676f84998..000000000 --- a/src/omega_blackwell_codegen_pattn.c +++ /dev/null @@ -1,558 +0,0 @@ -/* - * omega_blackwell_codegen_pattn.c: causal prefill attention on tensor cores (see the header). - * Emitter rules are those of omega_blackwell_codegen_attn.c / omega_blackwell_codegen_tc.c (control words, the read - * barrier on every load, held scoreboards 3/4 for prefetch loads, loop live ranges, HMMA spacing: >= 4 independent - * HMMAs at stall 8 between dependent ones, stall 15 + NOP 14 before a non-HMMA reader of an HMMA result). - * The prologue's per-head RMSNorm + RoPE is the decode kernel's instruction sequence (omega_blackwell_codegen_attn.c, - * prologue), so the appended K rows match the decode kernel bit for bit on the same chip. - */ -#include "omega_blackwell_codegen_pattn.h" -#include "omega_blackwell_codegen_tc.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending, held; - int err; - int open_start[MAX_LOOPS]; - int depth; - uint32_t placeholders; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn i; memset(&i, 0, sizeof i); - i.op = op; i.dst_vreg = NOREG; i.src1_vreg = NOREG; i.src2_vreg = NOREG; i.src3_vreg = NOREG; i.ureg = NOREG; - return i; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -typedef struct { int v; unsigned s; } Op; -static Op R(int v) { Op o = { v, 0 }; return o; } -static Op S(int v, unsigned s) { Op o = { v, s }; return o; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, Op d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, Op d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; emit(e, i, K_FIXED); } -/* d = a * imm + c */ -static void imadi(Em *e, Op d, Op a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } -static void shrs(Em *e, int d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, uint32_t imm) { shrs(e, d, R(a), imm); } -static void andi(Em *e, Op d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, Op d, Op a, Op b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; emit(e, i, K_FIXED); } -static void fop(Em *e, BlackwellIROpcode op, Op d, Op a, Op b, Op c) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; - i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; i.src3_vreg = c.v; i.src3_subreg = (uint8_t)c.s; emit(e, i, K_FIXED); -} -static void iadd(Em *e, int d, int a, int b) { fop(e, BW_IR_IADD3, R(d), R(a), R(b), R(NOREG)); } -static void iaddo(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_IADD3, d, a, b, R(NOREG)); } -static void fadd(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FADD, d, a, b, R(NOREG)); } -static void fsub(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FSUB, d, a, b, R(NOREG)); } -static void fmul(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMUL, d, a, b, R(NOREG)); } -static void ffma(Em *e, Op d, Op a, Op b, Op c) { fop(e, BW_IR_FFMA, d, a, b, c); } -static void fmaxx(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MAX, d, a, b, R(NOREG)); } -static void mufu(Em *e, BlackwellIROpcode op, Op d, Op a, int first) { BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void stg(Em *e, int addr64, uint32_t imm, Op val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.imm = imm; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.ureg = udesc; emit(e, i, K_STORE); } -static void membar(Em *e) { emit(e, I0(BW_IR_MEMBAR_ALL_SYS), K_FIXED); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void lds32(Em *e, Op d, int addr, int first) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = addr; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, Op val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -/* SHFL.BFLY placeholder (omega_blackwell_codegen_tc.h), patched after encoding */ -static void shfl_bfly(Em *e, int d, int a, uint32_t lanes) { shfl_down(e, d, a, OMEGA_TC_MARK_BFLY | (lanes & 31u)); e->placeholders++; } -/* F2FP.BF16.F32.PACK_AB placeholder: d = bf16_rn(hi) << 16 | bf16_rn(lo) */ -static void f2fp(Em *e, Op d, Op hi, Op lo) { - BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = hi.v; i.src1_subreg = (uint8_t)hi.s; - i.src2_vreg = lo.v; i.src2_subreg = (uint8_t)lo.s; i.imm = OMEGA_TC_MARK_F2FP; emit(e, i, K_FIXED); e->placeholders++; -} -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} -typedef struct { int bssy, bra; } Region; -static Region region_skip_if_p0(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } -static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } - -/* HMMA.16816.F32.BF16 d = a * b + c; b is the register pair at b + bsub (0 or 2); c NOREG = RZ */ -static void hmma(Em *e, int d, int a, int b, unsigned bsub, int c, uint32_t stall) { - BlackwellIRInsn i = I0(BW_IR_HMMA_BF16); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; - i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; - if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; -} -static void nop(Em *e, uint32_t stall) { - BlackwellIRInsn i = I0(BW_IR_NOP); i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; - if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; -} -/* a prefetch LDS.128: scoreboard sb (3 or 4) is held, not waited for, until consume() */ -static void lds_pf(Em *e, int d, int addr, uint32_t imm, unsigned sb) { - BlackwellIRInsn in = I0(BW_IR_LDS128); in.dst_vreg = d; in.src1_vreg = addr; in.imm = imm; - in.control = CW(4, sb, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; - e->pending |= 1u << SB_RD; e->held |= 1u << sb; - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} -static void consume(Em *e, unsigned sb) { e->pending |= e->held & (1u << sb); e->held &= ~(1u << sb); } - -/* bf16 round-to-nearest-even of f32 x into the low 16 bits of d (the decode kernel's sequence) */ -static void bf16_of(Em *e, int d, Op x, int c7fff, int t) { - shrs(e, t, x, 16); - andi(e, R(t), R(t), 1u); - iadd(e, t, t, c7fff); - fop(e, BW_IR_IADD3, R(d), x, R(t), R(NOREG)); - shr(e, d, d, 16); -} -/* two bf16 of x[q0], x[q0+1] packed (element q0 low) */ -static void bf16_pair(Em *e, Op d, int x4, unsigned q0, int c7fff, int h0, int h1, int tb) { - bf16_of(e, h0, S(x4, q0), c7fff, tb); bf16_of(e, h1, S(x4, q0 + 1), c7fff, tb); imadi(e, d, R(h1), 65536u, h0); -} - -/* shared memory map */ -#define SM_K 0u /* main loop: K block, [s 8][jp 2][lane 32][16 B] */ -#define SM_V 8192u /* main loop: V block, [kq 2][np 8][lane 32][16 B] */ -#define SM_Q 0u /* prologue: Q fragments of 2 tiles, [tile 2][s 8][lane 32][16 B] */ -#define SM_X 8192u /* prologue: per-warp f32 [128] partner staging */ -#define SM_N 12288u /* prologue: per-warp sum of squares */ -static const uint32_t NEG_BIG = 0xF149F2CAu; /* -1e30f */ - -/* The decode kernel's RMSNorm + RoPE of the quad x4 (dims 4*lane .. +3) of one head, in place. sin4 carries the - * sign already (lanes < 16 negative). Two CTA barriers (every warp runs the same number of items). */ -typedef struct { int lane, one, eps, snw, sxl, sxp, sq, ts, rs, a1, pt4; } NR; -static void norm_rope(Em *e, const NR *n, int x4, int w4, int cos4, int sin4, int rope) { - fmul(e, R(n->sq), S(x4, 0), S(x4, 0)); - for (unsigned i = 1; i < 4; i++) ffma(e, R(n->sq), S(x4, i), S(x4, i), R(n->sq)); - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, n->ts, n->sq, o); fadd(e, R(n->sq), R(n->sq), R(n->ts)); } - isetp_ge_u32(e, n->lane, n->one); - { Region r = region_skip_if_p0(e); sts32(e, n->snw, R(n->sq)); region_end(e, r); } - bar_sync(e); - lds32(e, R(n->sq), n->snw, 1); - movi(e, R(n->ts), 0x3c000000u); /* 1/128 */ - ffma(e, R(n->rs), R(n->sq), R(n->ts), R(n->eps)); - mufu(e, BW_IR_MUFU_RSQ, R(n->rs), R(n->rs), 1); - for (unsigned i = 0; i < 4; i++) { fmul(e, S(x4, i), S(x4, i), R(n->rs)); fmul(e, S(x4, i), S(x4, i), S(w4, i)); } - sts32(e, n->sxl, S(x4, 0)); - for (unsigned i = 1; i < 4; i++) { imadi(e, R(n->a1), R(n->one), 4u * i, n->sxl); sts32(e, n->a1, S(x4, i)); } - bar_sync(e); - lds128(e, n->pt4, n->sxp, 0, 1); - if (rope) for (unsigned i = 0; i < 4; i++) { fmul(e, R(n->ts), S(x4, i), S(cos4, i)); ffma(e, S(x4, i), S(n->pt4, i), S(sin4, i), R(n->ts)); } -} - -int omega_pattn_spec_ok(const OmegaPrefillAttnSpec *s) { - return s && (s->warps == 4u || s->warps == 8u) && s->mutant >= 0 && s->mutant <= 4 && s->mode <= OMEGA_PATTN_MODE_ATTEND && (s->mirror == 0 || (s->mirror == 1 && s->mode == OMEGA_PATTN_MODE_APPEND)); -} - -int omega_blackwell_codegen_prefill_attn_prog(const OmegaPrefillAttnSpec *spec, BlackwellIRProgram *prog) { - if (!omega_pattn_spec_ok(spec) || !prog) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - const uint32_t W = spec->warps, T = 32u * W, LW = W == 8u ? 3u : 2u; - const uint32_t NKU = 512u / T, NVU = 256u / T, ROUNDS = W / 4u; - const int MUT = spec->mutant; - - /* ---- arguments and identities ---- */ - int udesc = UV64(e); - int pqkv = V64(e), pkc = V64(e), pvc = V64(e), prope = V64(e), pqn = V64(e), pkn = V64(e); - int pos0 = V(e), mc = V(e), kvs = V(e), eps = V(e), qks = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), zero = V(e), c7fff = V(e), c16 = V(e); - int cyk = V(e), nk = V(e), t1 = V(e), t2 = V(e), cxw = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pqkv, OMEGA_PATTN_ARG_QKV); ldc64(e, pkc, OMEGA_PATTN_ARG_KC); ldc64(e, pvc, OMEGA_PATTN_ARG_VC); - ldc64(e, prope, OMEGA_PATTN_ARG_ROPE); ldc64(e, pqn, OMEGA_PATTN_ARG_QN); ldc64(e, pkn, OMEGA_PATTN_ARG_KN); - ldc32(e, pos0, OMEGA_PATTN_ARG_POS0); ldc32(e, mc, OMEGA_PATTN_ARG_MC); ldc32(e, kvs, OMEGA_PATTN_ARG_KV_STRIDE); - ldc32(e, eps, OMEGA_PATTN_ARG_EPS); ldc32(e, qks, OMEGA_PATTN_ARG_QK_SCALE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, R(one), 1); movrz(e, R(zero)); movi(e, R(c7fff), 0x7fffu); movi(e, R(c16), 16); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - imadr(e, cyk, cy, kvs, NOREG); /* byte offset of this KV head's plane */ - imadi(e, R(cxw), R(cx), W, NOREG); /* first chunk token of the CTA */ - /* nk = min(cxw + W, mc) = hi + over * (mc - hi), over = 1 when hi > mc */ - imadi(e, R(t2), R(one), W, cxw); /* hi */ - imadi(e, R(t1), R(t2), 0xffffffffu, mc); /* mc - hi */ - { int ov = V(e); if (e->err) return -1; - shr(e, ov, t1, 31); imadr(e, nk, ov, t1, t2); } - - /* ---- per-lane prologue constants ---- */ - NR n; memset(&n, 0, sizeof n); - n.lane = lane; n.one = one; n.eps = eps; - n.snw = V(e); n.sxl = V(e); n.sxp = V(e); n.sq = V(e); n.ts = V(e); n.rs = V(e); n.a1 = V(e); n.pt4 = V128(e); - int sgn = V(e), ropel = V(e), ad64 = V64(e), rope64 = V64(e), cos4 = V128(e), sin4 = V128(e), tokc = V(e), item = V(e), cnt = V(e); - int h0 = V(e), h1 = V(e), tb = V(e), w0 = V(e), w1 = V(e), w2 = V(e), w3 = V(e); - if (e->err) return -1; - imadi(e, R(n.snw), R(warp), 4u, NOREG); imadi(e, R(n.snw), R(one), SM_N, n.snw); - imadi(e, R(t1), R(warp), 512u, NOREG); imadi(e, R(t1), R(one), SM_X, t1); - imadi(e, R(n.sxl), R(lane), 16u, t1); - { int pl = V(e); if (e->err) return -1; - xorr(e, R(pl), R(lane), R(c16)); imadi(e, R(n.sxp), R(pl), 16u, t1); } - imadi(e, R(sgn), R(one), 0xfffffff0u, lane); shr(e, sgn, sgn, 31); imadi(e, R(sgn), R(sgn), 0x80000000u, NOREG); - andi(e, R(ropel), R(lane), 15u); imadi(e, R(ropel), R(ropel), 16u, NOREG); - - /* loads one token's rope row (position pos0 + tokc) with the sign on sin */ - #define ROPE_LOAD() do { iadd(e, t2, pos0, tokc); imadi(e, R(t2), R(t2), OMEGA_DATTN_ROPE_ROW_BYTES_PA, ropel); imadw(e, rope64, t2, 1u, prope); \ - ldg_wide(e, BW_IR_LDG_E_128, cos4, rope64, 0, udesc, 0); ldg_wide(e, BW_IR_LDG_E_128, sin4, rope64, 256, udesc, 0); } while (0) - #define OMEGA_DATTN_ROPE_ROW_BYTES_PA 512u - /* tokc = min(item + base, lim) for a token index t1 = item + base: tokc = t1 + over * (lim - t1) */ - #define CLAMP_TOK(tok, lim) do { int _d = V(e), _o = V(e); if (e->err) return -1; \ - imadi(e, R(_d), R(tok), 0xffffffffu, lim); shr(e, _o, _d, 31); imadr(e, tokc, _o, _d, tok); } while (0) - - /* ---- K/V append: chunk tokens 0 .. nk-1 (every CTA, identical bits); APPEND mode: only cxw .. nk-1 (one per warp); - * ATTEND mode: none (the APPEND launch wrote them) ---- */ - const bool APPEND = spec->mode == OMEGA_PATTN_MODE_APPEND; - if (spec->mode != OMEGA_PATTN_MODE_ATTEND) { - int kw4 = V128(e), k4 = V128(e), v4 = V128(e), nkm1 = V(e); - if (e->err) return -1; - imadw(e, ad64, lane, 16u, pkn); - ldg_wide(e, BW_IR_LDG_E_128, kw4, ad64, 0, udesc, 1); - imadi(e, R(nkm1), R(one), 0xffffffffu, nk); - if (APPEND) { movi(e, R(cnt), 1u); iadd(e, item, warp, cxw); } - else { imadi(e, R(cnt), R(one), W - 1u, nk); shr(e, cnt, cnt, LW); /* ceil(nk / W) >= 1 */ - mov(e, R(item), R(warp)); } - const int L_k = here(e); - loop_begin(e); - CLAMP_TOK(item, nkm1); - imadi(e, R(t1), R(tokc), OMEGA_PATTN_QKV_WORDS * 4u, NOREG); imadi(e, R(t1), R(cy), 512u, t1); imadi(e, R(t1), R(lane), 16u, t1); - imadi(e, R(t1), R(one), 32u * 128u * 4u, t1); - imadw(e, ad64, t1, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, k4, ad64, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, v4, ad64, 4u * 128u * 4u, udesc, 0); - ROPE_LOAD(); - for (unsigned i = 0; i < 4; i++) xorr(e, S(sin4, i), S(sin4, i), R(sgn)); - norm_rope(e, &n, k4, kw4, cos4, sin4, MUT != 1); - bf16_pair(e, R(w0), k4, 0, c7fff, h0, h1, tb); bf16_pair(e, R(w1), k4, 2, c7fff, h0, h1, tb); - bf16_pair(e, R(w2), v4, 0, c7fff, h0, h1, tb); bf16_pair(e, R(w3), v4, 2, c7fff, h0, h1, tb); - if (MUT != 3) { - int ka = V64(e); if (e->err) return -1; - isetp_ge_u32(e, item, nk); - const int b = bra_if_p0_fwd(e); - iadd(e, t1, pos0, item); imadi(e, R(t1), R(t1), 256u, cyk); imadi(e, R(t1), R(lane), 8u, t1); - imadw(e, ka, t1, 1u, pkc); stg(e, ka, 0, R(w0), udesc); stg(e, ka, 4, R(w1), udesc); - imadw(e, ka, t1, 1u, pvc); stg(e, ka, 0, R(w2), udesc); stg(e, ka, 4, R(w3), udesc); - if (spec->mirror) { /* the same words into the mirror planes */ - int pk2 = V64(e), pv2 = V64(e), kvs2 = V(e); if (e->err) return -1; - ldc64(e, pk2, OMEGA_PATTN_ARG_KC2); ldc64(e, pv2, OMEGA_PATTN_ARG_VC2); ldc32(e, kvs2, OMEGA_PATTN_ARG_KV_STRIDE2); - imadr(e, t2, cy, kvs2, NOREG); - iadd(e, t1, pos0, item); imadi(e, R(t1), R(t1), 256u, t2); imadi(e, R(t1), R(lane), 8u, t1); - imadw(e, ka, t1, 1u, pk2); stg(e, ka, 0, R(w0), udesc); stg(e, ka, 4, R(w1), udesc); - imadw(e, ka, t1, 1u, pv2); stg(e, ka, 0, R(w2), udesc); stg(e, ka, 4, R(w3), udesc); - } - patch_bra(e, b, here(e)); - } - imadi(e, R(item), R(one), W, item); - imadi(e, R(cnt), R(one), 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_k); - loop_end(e); - membar(e); - if (APPEND) { - (void)h0; - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog) != 0 ? -1 : 0; - } - bar_sync(e); - } - - /* ---- Q fragments: rounds of 2 tiles (4 tokens) through shared memory ---- */ - int q[8]; - for (unsigned s = 0; s < 8; s++) q[s] = V128(e); - { - int qw4 = V128(e), x4 = V128(e), qlane = V(e), rr = V(e), cr = V(e), mcm1 = V(e), qbase = V(e), jt = V(e), hh = V(e); - if (e->err) return -1; - for (unsigned s = 0; s < 8; s++) for (unsigned k = 0; k < 4; k++) movrz(e, S(q[s], k)); /* defined before the rounds loop */ - imadw(e, ad64, lane, 16u, pqn); - ldg_wide(e, BW_IR_LDG_E_128, qw4, ad64, 0, udesc, 1); - imadi(e, R(mcm1), R(one), 0xffffffffu, mc); - /* lane part of the fragment address: (lane>>2)*512 + (lane&1)*32 + ((lane>>1)&1)*8 */ - shr(e, t1, lane, 2); imadi(e, R(qlane), R(t1), 512u, NOREG); - andi(e, R(t1), R(lane), 1u); imadi(e, R(qlane), R(t1), 32u, qlane); - shr(e, t1, lane, 1); andi(e, R(t1), R(t1), 1u); imadi(e, R(qlane), R(t1), 8u, qlane); - /* this warp's fragment base: tile (warp>>1)&1 of the round */ - shr(e, t1, warp, 1); andi(e, R(t1), R(t1), 1u); imadi(e, R(qbase), R(t1), 4096u, NOREG); imadi(e, R(qbase), R(lane), 16u, qbase); - movrz(e, R(rr)); movi(e, R(cr), ROUNDS); - const int L_r = here(e); - loop_begin(e); - mov(e, R(item), R(warp)); movi(e, R(cnt), 32u / W); - const int L_i = here(e); - loop_begin(e); - shr(e, jt, item, 3); andi(e, R(hh), R(item), 7u); - imadi(e, R(t1), R(rr), 4u, jt); iadd(e, t1, t1, cxw); /* chunk token */ - { int tk = V(e); if (e->err) return -1; mov(e, R(tk), R(t1)); CLAMP_TOK(tk, mcm1); } - imadi(e, R(t1), R(cy), 8u, hh); imadi(e, R(t1), R(t1), 512u, NOREG); - imadi(e, R(t1), R(tokc), OMEGA_PATTN_QKV_WORDS * 4u, t1); imadi(e, R(t1), R(lane), 16u, t1); - imadw(e, ad64, t1, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, x4, ad64, 0, udesc, 1); - ROPE_LOAD(); - for (unsigned i = 0; i < 4; i++) xorr(e, S(sin4, i), S(sin4, i), R(sgn)); - norm_rope(e, &n, x4, qw4, cos4, sin4, MUT != 1); - for (unsigned i = 0; i < 4; i++) fmul(e, S(x4, i), S(x4, i), R(qks)); - bf16_pair(e, R(w0), x4, 0, c7fff, h0, h1, tb); bf16_pair(e, R(w1), x4, 2, c7fff, h0, h1, tb); - /* dst = qlane + (jt>>1)*4096 + h*64 + (jt&1)*4 */ - shr(e, t1, jt, 1); imadi(e, R(t1), R(t1), 4096u, qlane); imadi(e, R(t1), R(hh), 64u, t1); - andi(e, R(t2), R(jt), 1u); imadi(e, R(t1), R(t2), 4u, t1); - sts32(e, t1, R(w0)); imadi(e, R(t2), R(one), 16u, t1); sts32(e, t2, R(w1)); - imadi(e, R(item), R(one), W, item); - imadi(e, R(cnt), R(one), 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_i); - loop_end(e); - bar_sync(e); - /* the round's warps (warp>>2 == rr; every warp when W = 4) load their 8 fragments */ - int skip = -1; - if (W == 8u) { shr(e, t1, warp, 2); xorr(e, R(t1), R(t1), R(rr)); isetp_ge_u32(e, t1, one); skip = bra_if_p0_fwd(e); } - for (unsigned s = 0; s < 8; s++) lds128(e, q[s], qbase, s * 512u, s == 0); - if (skip >= 0) { nop(e, 1); patch_bra(e, skip, here(e)); } - bar_sync(e); - imadi(e, R(rr), R(one), 1u, rr); - imadi(e, R(cr), R(one), 0xffffffffu, cr); - isetp_ge_u32(e, cr, one); - bra_if_p0(e, L_r); - loop_end(e); - } - #undef ROPE_LOAD - #undef CLAMP_TOK - - /* ---- main loop state ---- */ - int o[8], sc[4], kf[2][2], pp[2], vf[4]; - for (unsigned i = 0; i < 8; i++) o[i] = V128(e); - int mA = V(e), mB = V(e), lA = V(e), lB = V(e), dqa = V(e), gK = V64(e), gV = V64(e), sKb = V(e), sVb = V(e); - int lane16 = V(e), vfb = V(e), negc = V(e), tokA = V(e); - if (e->err) return -1; - { - int a = V(e), c = V(e), tq = V(e); if (e->err) return -1; - shr(e, t1, warp, 1); imadi(e, R(tokA), R(t1), 2u, cxw); /* the tile's first chunk token */ - iadd(e, dqa, pos0, tokA); /* row-A position - kb (kb = 0) */ - /* blocks: kend = pos0 + nk - 1; nblk = kend / 32 + 1 */ - iadd(e, t1, pos0, nk); imadi(e, R(t1), R(one), 0xffffffffu, t1); shr(e, t1, t1, 5); imadi(e, R(cnt), R(one), 1u, t1); - shr(e, a, tid, 4); andi(e, R(c), R(tid), 15u); - /* staging pointers */ - imadw(e, gK, cyk, 1u, pkc); imadw(e, gK, a, 256u, gK); imadi(e, R(t1), R(c), 16u, NOREG); imadw(e, gK, t1, 1u, gK); - imadw(e, gV, cyk, 1u, pvc); imadw(e, gV, a, 512u, gV); imadw(e, gV, t1, 1u, gV); - /* sKb = (c>>1)*1024 + (a&7)*64 + ((a>>3)&1)*8 + (c&1)*4 */ - shr(e, t1, c, 1); imadi(e, R(sKb), R(t1), 1024u, NOREG); - andi(e, R(t1), R(a), 7u); imadi(e, R(sKb), R(t1), 64u, sKb); - shr(e, t1, a, 3); andi(e, R(t1), R(t1), 1u); imadi(e, R(sKb), R(t1), 8u, sKb); - andi(e, R(t2), R(c), 1u); imadi(e, R(sKb), R(t2), 4u, sKb); - /* sVb = SM_V + ((a>>3)*8 + (c>>1))*512 + (a&3)*16 + ((c&1)*2 + ((a>>2)&1))*4 */ - shr(e, t1, a, 3); shr(e, tq, c, 1); imadi(e, R(t1), R(t1), 8u, tq); imadi(e, R(sVb), R(t1), 512u, NOREG); - andi(e, R(t1), R(a), 3u); imadi(e, R(sVb), R(t1), 16u, sVb); - shr(e, t1, a, 2); andi(e, R(t1), R(t1), 1u); imadi(e, R(t1), R(t2), 2u, t1); imadi(e, R(sVb), R(t1), 4u, sVb); - imadi(e, R(sVb), R(one), SM_V, sVb); - imadi(e, R(lane16), R(lane), 16u, NOREG); - andi(e, R(t1), R(warp), 1u); imadi(e, R(vfb), R(t1), 2048u, lane16); imadi(e, R(vfb), R(one), SM_V, vfb); - } - for (unsigned i = 0; i < 8; i++) for (unsigned k = 0; k < 4; k++) movrz(e, S(o[i], k)); - movi(e, R(negc), NEG_BIG); mov(e, R(mA), R(negc)); mov(e, R(mB), R(negc)); movrz(e, R(lA)); movrz(e, R(lB)); - - int kq4[4], va4[2], vb4[2]; - for (unsigned i = 0; i < NKU; i++) kq4[i] = V128(e); - for (unsigned i = 0; i < NVU; i++) { va4[i] = V128(e); vb4[i] = V128(e); } - int ev = V(e), od = V(e), sa = V(e), mxA = V(e), mxB = V(e), alA = V(e), alB = V(e), sh = V(e); - for (unsigned j = 0; j < 4; j++) sc[j] = V128(e); - for (unsigned b = 0; b < 2; b++) { kf[b][0] = V128(e); kf[b][1] = V128(e); pp[b] = V128(e); } - for (unsigned i = 0; i < 4; i++) vf[i] = V128(e); - if (e->err) return -1; - - const int L_m = here(e); - loop_begin(e); - bar_sync(e); /* every warp is done with the previous block (or the prologue) */ - /* ---- stage the block: K units (key a + i*2W, 16-byte chunk c), V units (key pair a + i*2W) ---- */ - for (unsigned i = 0; i < NKU; i++) ldg_wide(e, BW_IR_LDG_E_128, kq4[i], gK, i * 2u * W * 256u, udesc, i == 0); - if (NKU * 4u + NVU * 8u > 16u) { /* W = 4: K first, then V (register budget) */ - for (unsigned i = 0; i < NKU; i++) for (unsigned k = 0; k < 4; k++) { - uint32_t ci = W == 4u ? (i >> 1) * 512u + (i & 1u) * 8u : i * 512u; - imadi(e, R(sa), R(one), ci + 16u * k, sKb); sts32(e, sa, S(kq4[i], k)); - } - } - for (unsigned i = 0; i < NVU; i++) { - ldg_wide(e, BW_IR_LDG_E_128, va4[i], gV, i * 2u * W * 512u, udesc, NKU * 4u + NVU * 8u > 16u && i == 0); - ldg_wide(e, BW_IR_LDG_E_128, vb4[i], gV, i * 2u * W * 512u + 256u, udesc, 0); - } - if (NKU * 4u + NVU * 8u <= 16u) { - for (unsigned i = 0; i < NKU; i++) for (unsigned k = 0; k < 4; k++) { - uint32_t ci = W == 4u ? (i >> 1) * 512u + (i & 1u) * 8u : i * 512u; - imadi(e, R(sa), R(one), ci + 16u * k, sKb); sts32(e, sa, S(kq4[i], k)); - } - } - for (unsigned i = 0; i < NVU; i++) for (unsigned k = 0; k < 4; k++) { - andi(e, R(t1), S(va4[i], k), 0xffffu); imadi(e, R(ev), S(vb4[i], k), 65536u, t1); - shrs(e, t1, S(va4[i], k), 16); andi(e, R(t2), S(vb4[i], k), 0xffff0000u); iadd(e, od, t1, t2); - imadi(e, R(sa), R(one), i * 4096u + (2u * k) * 64u, sVb); sts32(e, sa, R(ev)); - imadi(e, R(sa), R(one), i * 4096u + (2u * k + 1u) * 64u, sVb); sts32(e, sa, R(od)); - } - bar_sync(e); - - /* ---- S = Q K^T: 8 k-steps x 4 n-tiles, K fragments double-buffered on scoreboards 3/4 ---- */ - lds_pf(e, kf[0][0], lane16, SM_K + 0u, 3); lds_pf(e, kf[0][1], lane16, SM_K + 512u, 3); - consume(e, 3); - for (unsigned s = 0; s < 8; s++) { - const unsigned cur = s & 1u, nx = cur ^ 1u, sbn = 3u + nx; - if (s < 7) { lds_pf(e, kf[nx][0], lane16, SM_K + (s + 1u) * 1024u, sbn); lds_pf(e, kf[nx][1], lane16, SM_K + (s + 1u) * 1024u + 512u, sbn); } - hmma(e, sc[0], q[s], kf[cur][0], 0, s ? sc[0] : NOREG, 8); - hmma(e, sc[1], q[s], kf[cur][0], 2, s ? sc[1] : NOREG, 8); - hmma(e, sc[2], q[s], kf[cur][1], 0, s ? sc[2] : NOREG, 8); - hmma(e, sc[3], q[s], kf[cur][1], 2, s ? sc[3] : NOREG, 8); - if (s < 7) consume(e, sbn); - } - nop(e, 15); nop(e, 14); - - /* ---- causal mask: key kb + 8j + 2t + (e&1) > row position (row A for e < 2, A + 1 for e >= 2) ---- */ - if (MUT != 2) { - imadi(e, R(t1), R(one), 0xffffffe1u, dqa); shr(e, t1, t1, 31); /* 1 when kb + 31 > row-A position */ - isetp_ge_u32(e, zero, t1); - const int b = bra_if_p0_fwd(e); - int dql = V(e); if (e->err) return -1; - shr(e, t2, lane16, 3); andi(e, R(t2), R(t2), 6u); imadi(e, R(dql), R(t2), 0xffffffffu, dqa); /* dqa - 2t */ - for (unsigned j = 0; j < 4; j++) for (unsigned k = 0; k < 4; k++) { - int32_t cst = (k >= 2 ? 1 : 0) - 8 * (int32_t)j - (int32_t)(k & 1u); - imadi(e, R(t1), R(one), (uint32_t)cst, dql); shr(e, t1, t1, 31); imadi(e, R(t1), R(t1), NEG_BIG, NOREG); - fadd(e, S(sc[j], k), S(sc[j], k), R(t1)); - } - patch_bra(e, b, here(e)); - } - - /* ---- online softmax (log2 units) ---- */ - fmaxx(e, R(mxA), S(sc[0], 0), S(sc[0], 1)); fmaxx(e, R(mxB), S(sc[0], 2), S(sc[0], 3)); - for (unsigned j = 1; j < 4; j++) { - fmaxx(e, R(mxA), R(mxA), S(sc[j], 0)); fmaxx(e, R(mxA), R(mxA), S(sc[j], 1)); - fmaxx(e, R(mxB), R(mxB), S(sc[j], 2)); fmaxx(e, R(mxB), R(mxB), S(sc[j], 3)); - } - shfl_bfly(e, sh, mxA, 1); fmaxx(e, R(mxA), R(mxA), R(sh)); shfl_bfly(e, sh, mxA, 2); fmaxx(e, R(mxA), R(mxA), R(sh)); - shfl_bfly(e, sh, mxB, 1); fmaxx(e, R(mxB), R(mxB), R(sh)); shfl_bfly(e, sh, mxB, 2); fmaxx(e, R(mxB), R(mxB), R(sh)); - fmaxx(e, R(mxA), R(mxA), R(mA)); fmaxx(e, R(mxB), R(mxB), R(mB)); - fsub(e, R(alA), R(mA), R(mxA)); fsub(e, R(alB), R(mB), R(mxB)); - mov(e, R(mA), R(mxA)); mov(e, R(mB), R(mxB)); - for (unsigned j = 0; j < 4; j++) for (unsigned k = 0; k < 4; k++) fsub(e, S(sc[j], k), S(sc[j], k), R(k < 2 ? mA : mB)); - mufu(e, BW_IR_MUFU_EX2, R(alA), R(alA), 1); mufu(e, BW_IR_MUFU_EX2, R(alB), R(alB), 0); - for (unsigned j = 0; j < 4; j++) for (unsigned k = 0; k < 4; k++) mufu(e, BW_IR_MUFU_EX2, S(sc[j], k), S(sc[j], k), 0); - fmul(e, R(lA), R(lA), R(alA)); fmul(e, R(lB), R(lB), R(alB)); - for (unsigned j = 0; j < 4; j++) for (unsigned k = 0; k < 4; k++) fadd(e, R(k < 2 ? lA : lB), R(k < 2 ? lA : lB), S(sc[j], k)); - if (MUT != 4) for (unsigned i = 0; i < 8; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? alA : alB)); - for (unsigned b = 0; b < 2; b++) { - f2fp(e, S(pp[b], 0), S(sc[2 * b], 1), S(sc[2 * b], 0)); f2fp(e, S(pp[b], 1), S(sc[2 * b], 3), S(sc[2 * b], 2)); - f2fp(e, S(pp[b], 2), S(sc[2 * b + 1], 1), S(sc[2 * b + 1], 0)); f2fp(e, S(pp[b], 3), S(sc[2 * b + 1], 3), S(sc[2 * b + 1], 2)); - } - - /* ---- O += P V: 2 k-steps (16 keys) x 8 n-tiles of this warp's 64 dims ---- */ - for (unsigned kq = 0; kq < 2; kq++) { - for (unsigned np = 0; np < 4; np++) lds128(e, vf[np], vfb, kq * 4096u + np * 512u, np == 0); - for (unsigned np = 0; np < 4; np++) { hmma(e, o[2 * np], pp[kq], vf[np], 0, o[2 * np], 8); hmma(e, o[2 * np + 1], pp[kq], vf[np], 2, o[2 * np + 1], 8); } - } - imadw(e, gK, one, 8192u, gK); imadw(e, gV, one, 8192u, gV); - imadi(e, R(dqa), R(one), 0xffffffe0u, dqa); - imadi(e, R(cnt), R(one), 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_m); - loop_end(e); - - /* ---- epilogue ---- */ - nop(e, 15); nop(e, 14); - { - int pout = V64(e), osc = V(e), po = V64(e), g = V(e), tq = V(e), etid = V(e), ecx = V(e), ecy = V(e), emc = V(e), ewarp = V(e), elane = V(e), etok = V(e); - if (e->err) return -1; - ldc64(e, pout, OMEGA_PATTN_ARG_OUT); ldc32(e, osc, OMEGA_PATTN_ARG_OUT_SCALE); ldc32(e, emc, OMEGA_PATTN_ARG_MC); - s2r(e, etid, BW_SR_TID_X); s2r(e, ecx, BW_SR_CTAID_X); s2r(e, ecy, BW_SR_CTAID_Y); - shr(e, ewarp, etid, 5); andi(e, R(elane), R(etid), 31u); - shr(e, t1, ewarp, 1); imadi(e, R(t1), R(t1), 2u, NOREG); imadi(e, R(etok), R(ecx), W, t1); - shfl_bfly(e, sh, lA, 1); fadd(e, R(lA), R(lA), R(sh)); shfl_bfly(e, sh, lA, 2); fadd(e, R(lA), R(lA), R(sh)); - shfl_bfly(e, sh, lB, 1); fadd(e, R(lB), R(lB), R(sh)); shfl_bfly(e, sh, lB, 2); fadd(e, R(lB), R(lB), R(sh)); - mufu(e, BW_IR_MUFU_RCP, R(lA), R(lA), 1); mufu(e, BW_IR_MUFU_RCP, R(lB), R(lB), 0); - fmul(e, R(lA), R(lA), R(osc)); fmul(e, R(lB), R(lB), R(osc)); - for (unsigned i = 0; i < 8; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? lA : lB)); - /* out + ((tokA*32 + cy*8 + g)*128 + (warp&1)*64 + 2t)*4 */ - shr(e, g, elane, 2); andi(e, R(tq), R(elane), 3u); - imadi(e, R(t1), R(etok), 32u, NOREG); imadi(e, R(t1), R(ecy), 8u, t1); iadd(e, t1, t1, g); imadi(e, R(t1), R(t1), 512u, NOREG); - andi(e, R(t2), R(ewarp), 1u); imadi(e, R(t1), R(t2), 256u, t1); imadi(e, R(t1), R(tq), 8u, t1); - imadw(e, po, t1, 1u, pout); - for (unsigned row = 0; row < 2; row++) { - imadi(e, R(t1), R(one), row, etok); - isetp_ge_u32(e, t1, emc); - const int b = bra_if_p0_fwd(e); - for (unsigned i = 0; i < 8; i++) { stg(e, po, row * 16384u + i * 32u, S(o[i], 2 * row), udesc); stg(e, po, row * 16384u + i * 32u + 4u, S(o[i], 2 * row + 1), udesc); } - patch_bra(e, b, here(e)); - } - } - (void)iaddo; (void)h0; - tail(e); - if (e->err) return -1; - if (omega_bw_regalloc_solve(prog) != 0) return -1; - return 0; -} - -int omega_prefill_attn_prog_stats(const OmegaPrefillAttnSpec *spec, uint32_t *insns, uint32_t *gprs, uint32_t *placeholders) { - static BlackwellIRProgram p; - if (omega_blackwell_codegen_prefill_attn_prog(spec, &p) != 0) return -1; - if (insns) *insns = (uint32_t)p.count; - if (gprs) *gprs = p.regalloc.peak_gpr_usage; - if (placeholders) { - uint32_t n = 0; - for (size_t i = 0; i < p.count; i++) { - const BlackwellIRInsn *in = &p.insns[i]; - if ((in->op == BW_IR_SHFL_DOWN && (in->imm & OMEGA_TC_MARK_BFLY)) || (in->op == BW_IR_FMNMX_MAX && in->imm == OMEGA_TC_MARK_F2FP)) n++; - } - *placeholders = n; - } - return 0; -} diff --git a/src/omega_blackwell_codegen_pattn.h b/src/omega_blackwell_codegen_pattn.h deleted file mode 100644 index 09add123e..000000000 --- a/src/omega_blackwell_codegen_pattn.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_PATTN_H -#define OMEGA_BLACKWELL_CODEGEN_PATTN_H -/* - * omega_blackwell_codegen_pattn: causal prefill attention for Qwen3-30B-A3B on tensor cores (OWN-30B L1 attention, - * 2026-10-13). One launch per chunk of up to 64 consecutive tokens of one layer. New file; uses the opcodes of - * omega_blackwell_codegen.h plus the SHFL.BFLY and F2FP.BF16.F32.PACK_AB placeholders of omega_blackwell_codegen_tc.h - * (patched after encoding with omega_tc_patch_code). - * - * Grid (ceil(mc / W), 4): CTA (cx, cy) serves KV head cy and the chunk tokens cx*W .. cx*W+W-1 (W = warps, 4 or 8). - * Row tile = 16 query rows = 2 tokens x the 8 query heads of the group: row g (0..7) = token 2*tile, head cy*8+g; - * row g+8 = token 2*tile+1, same head. Warp w: tile w/2, output dims 64*(w%2) .. +63 (two warps share a tile and - * both compute its scores; each keeps half of O: 8 HMMA n-tiles = 32 f32 registers). - * - * Prologue (all warps, CTA barriers; uniform trip counts): - * K/V append: every CTA computes K = bf16(RoPE(RMSNorm(k) * k_norm)) and V = bf16(v) for the chunk tokens - * 0 .. nk-1 (nk = min(cx*W + W, mc)) with the decode kernel's exact instruction sequence (quad per lane, - * SHFL.DOWN sum, lane 0's sum through shared memory, RSQ, partner half through shared memory) and stores them - * into the cache rows pos0 + t. CTAs write identical bits to the rows they share. MEMBAR.SYS + BAR.SYNC, then - * the CTA reads its own rows back from the cache. - * Q: q' = bf16(RoPE(RMSNorm(q) * q_norm) * qk_scale) per (token, head) item, staged in shared memory in HMMA - * A-fragment order (2 tiles per round), then each warp loads its 8 fragments (32 registers) for the whole run. - * Main loop over key blocks of 32 (kb = 0, 32, .. <= kend = pos0 + nk - 1): - * stage K (fragment-major, B of S = Q K^T) and V (transposed pairs, B of O = P V) of the block in shared memory - * (16 KB), S = Q K^T (8 k-steps x 4 n-tiles, HMMA.16816.F32.BF16), causal mask (key > row position: s += -1e30, - * skipped when the whole block is at or below the tile's first token), online softmax in log2 units (EX2), O - * rescaled by alpha = EX2(m_old - m_new), P packed to bf16 (F2FP), O += P V (2 k-steps x 8 n-tiles). - * Epilogue: l summed over the quad (SHFL.BFLY), out = O * RCP(l) * out_scale for tokens < mc. - * Split modes (spec.mode, 2026-10-13 cut 3): an APPEND launch then an ATTEND launch over the same mc tokens do the - * fused kernel's work with no redundant appends, so one pair of launches can cover a whole prompt (grid ceil(mc/W) x 4) - * instead of 64-token chunks of 8 x 4 CTAs. The appended rows are the same instruction sequence (identical bits). - * - * The host simulator (tests/bw_warp_sim_pa.h) runs the kernel with the chip-exact HMMA model; EX2/RSQ/RCP are - * exact there and approximate on the chip. A simulator pass is never a chip result. - */ -#include "omega_blackwell_codegen.h" -#include - -#define OMEGA_PATTN_CHUNK 64u /* tokens per launch */ -#define OMEGA_PATTN_KEYS 32u /* keys per main-loop block */ -#define OMEGA_PATTN_QKV_WORDS 5120u /* f32 per token row of the fused q|k|v projection */ -#define OMEGA_PATTN_OUT_WORDS 4096u /* f32 per token row of the output (32 heads x 128) */ -#define OMEGA_PATTN_SHARED_BYTES 16384u /* the QMD cap (omega_blackwell_qmd.h) */ - -/* constant bank 0 at 0x380 */ -#define OMEGA_PATTN_ARG_QKV 0x380u /* f32 [64][5120]: row t = chunk token t (position pos0 + t) */ -#define OMEGA_PATTN_ARG_KC 0x388u /* bf16 K plane base [kv_head][max_pos][128] */ -#define OMEGA_PATTN_ARG_VC 0x390u /* bf16 V plane base */ -#define OMEGA_PATTN_ARG_ROPE 0x398u /* f32 [max_pos][cos 64 | sin 64] */ -#define OMEGA_PATTN_ARG_QN 0x3a0u /* f32 [128] q_norm */ -#define OMEGA_PATTN_ARG_KN 0x3a8u /* f32 [128] k_norm */ -#define OMEGA_PATTN_ARG_OUT 0x3b0u /* f32 [64][4096] */ -#define OMEGA_PATTN_ARG_POS0 0x3b8u /* u32 position of chunk token 0 */ -#define OMEGA_PATTN_ARG_MC 0x3bcu /* u32 tokens in this chunk, 1..64 */ -#define OMEGA_PATTN_ARG_KV_STRIDE 0x3c0u /* u32 bytes per KV head plane (max_pos * 256) */ -#define OMEGA_PATTN_ARG_EPS 0x3c4u /* f32 */ -#define OMEGA_PATTN_ARG_OUT_SCALE 0x3c8u /* f32 */ -#define OMEGA_PATTN_ARG_QK_SCALE 0x3ccu /* f32 (1/sqrt(128)) * log2(e) */ -#define OMEGA_PATTN_ARG_KC2 0x3d0u /* APPEND with spec.mirror: second K plane base (GPU-cached mirror) */ -#define OMEGA_PATTN_ARG_VC2 0x3d8u /* second V plane base */ -#define OMEGA_PATTN_ARG_KV_STRIDE2 0x3e0u /* u32 bytes per KV head plane of the mirror */ -#define OMEGA_PATTN_ARGS_WORDS 25u - -typedef struct { - uint32_t warps; /* 4 or 8 (tokens per CTA) */ - int mutant; /* TEST ONLY. 0 none; 1 no RoPE on q and k; 2 no causal mask; 3 the new K/V are not written; - * 4 O is never rescaled by alpha. Each must be caught by the gates. */ - uint32_t mode; /* OMEGA_PATTN_MODE_*: 0 fused (append + attend, chunks of <= 64 tokens); - * 1 append only: CTA (cx, cy) appends just its own tokens cx*W .. cx*W+W-1 (< mc), then exits; - * 2 attend only: no append (a mode-1 launch over the same tokens ran before), any mc >= 1. */ - uint32_t mirror; /* APPEND only: 1 also stores each new row into the mirror planes (ARG_KC2 / VC2 / KV_STRIDE2), e.g. a - * GPU-cached copy of the layer's K/V that the ATTEND launch then reads instead of the uncached cache */ -} OmegaPrefillAttnSpec; -#define OMEGA_PATTN_MODE_FUSED 0u -#define OMEGA_PATTN_MODE_APPEND 1u -#define OMEGA_PATTN_MODE_ATTEND 2u - -int omega_pattn_spec_ok(const OmegaPrefillAttnSpec *spec); -/* Builds the register-allocated IR program. 0 ok, -1 refused or over BW_MAX_IR_INSNS / BW_MAX_VREGS. */ -int omega_blackwell_codegen_prefill_attn_prog(const OmegaPrefillAttnSpec *spec, BlackwellIRProgram *prog); -/* Instruction, peak-register and placeholder counts (host, no device). */ -int omega_prefill_attn_prog_stats(const OmegaPrefillAttnSpec *spec, uint32_t *insns, uint32_t *gprs, uint32_t *placeholders); - -#endif diff --git a/src/omega_blackwell_codegen_pf.c b/src/omega_blackwell_codegen_pf.c deleted file mode 100644 index 78e1d6b33..000000000 --- a/src/omega_blackwell_codegen_pf.c +++ /dev/null @@ -1,22 +0,0 @@ -/* omega_blackwell_codegen_pf.c: device-resident prefill helper kernels (OWN-30B T3b). See the header. */ -#include "omega_blackwell_codegen_pf.h" -#include "omega_bw_em.h" - -int omega_blackwell_codegen_pf_copy_prog(BlackwellIRProgram *prog) { - if (!prog) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), pd = V64(e), ps = V64(e), units = V(e), tid = V(e), cta = V(e), i = V(e), v = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, pd, 0x380); ldc64(e, ps, 0x388); ldc32(e, units, 0x390); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadi(e, i, cta, 0, OMEGA_PF_COPY_THREADS, tid); - isetp_ge_u32(e, i, units); - { BlackwellIRInsn x = I0(BW_IR_EXIT); x.predicate_p0 = true; emit(e, x, K_EXIT); } - imadw(e, ps, i, 16u, ps); imadw(e, pd, i, 16u, pd); - ldg_wide(e, BW_IR_LDG_E_128, v, ps, 0, udesc, 1); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = pd; st.src2_vreg = v; st.src2_subreg = (uint8_t)q; st.imm = 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_pf.h b/src/omega_blackwell_codegen_pf.h deleted file mode 100644 index 74236c80c..000000000 --- a/src/omega_blackwell_codegen_pf.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_PF_H -#define OMEGA_BLACKWELL_CODEGEN_PF_H -/* - * omega_blackwell_codegen_pf: small device-resident kernels for the OWN-30B one-pass prefill (T3b, 2026-10-13). New file. - * - * copy: dst[i] = src[i] for i < units (16-byte units). One thread per unit, grid_x = ceil(units / threads). - * Arguments (cbank + 0x380): dst u64, src u64, units u32. Used to fill GPU-cached (device-private) buffers from an - * uncached staging buffer and to read them back: every write to a cached buffer is a GPU write, so the GPU L2 can never - * hold a stale line of it (nvos.h:1116, omega_gpu_devmem.h). - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif -#define OMEGA_PF_COPY_THREADS 256u -int omega_blackwell_codegen_pf_copy_prog(BlackwellIRProgram *prog); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_pfhost.c b/src/omega_blackwell_codegen_pfhost.c deleted file mode 100644 index a272585b6..000000000 --- a/src/omega_blackwell_codegen_pfhost.c +++ /dev/null @@ -1,145 +0,0 @@ -/* omega_blackwell_codegen_pfhost.c: router logits and MoE combine for the whole-prompt prefill (W-L1G-D). See the header. */ -#include "omega_blackwell_codegen_pfhost.h" -#include "omega_bw_em.h" - -static void fmul_s(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; emit(e, i, K_FIXED); -} -static void fadd_s(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; emit(e, i, K_FIXED); -} -/* d[dsub] = a[asub] * b[bsub] + d[dsub] (the mutant's fused form) */ -static void ffma_s(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; - i.src3_vreg = d; i.src3_subreg = (uint8_t)dsub; emit(e, i, K_FIXED); -} -/* acc[asub] += a[asub2] * b[bsub] as FMUL then FADD (bit-identical to the host's a * b then +), or FFMA for mutant 1 */ -static void mul_add(Em *e, int fused, int acc, unsigned accsub, int a, unsigned asub, int b, unsigned bsub, int prod) { - if (fused) { ffma_s(e, acc, accsub, a, asub, b, bsub); return; } - fmul_s(e, prod, 0, a, asub, b, bsub); - fadd_s(e, acc, accsub, acc, accsub, prod, 0); -} - -/* ======================= router logits ======================= */ -int omega_rl_spec_ok(const OmegaRlSpec *s) { - if (!s) return 0; - if (s->k < 128u || s->k > 16384u || s->k % 128u) return 0; - if (s->e < 32u || s->e > 1024u || s->e % 32u) return 0; - if (s->t < 1u || s->t > 16u) return 0; - if (s->t % (s->e / 32u)) return 0; /* tile rows per pass = warps */ - if ((uint64_t)(s->k / 4u + 1u) * s->e * 16u > 0x7fffffffu) return 0; - return s->mutant >= 0 && s->mutant <= 2; -} -uint32_t omega_rl_shared_bytes(const OmegaRlSpec *s) { return omega_rl_spec_ok(s) ? s->t * 512u : 0u; } - -int omega_blackwell_codegen_rl_prog(const OmegaRlSpec *spec, BlackwellIRProgram *prog) { - if (!omega_rl_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, E = spec->e, T = spec->t, W = E / 32u, PASSES = T / W, GB = E * 16u; - const uint32_t CHUNKS = spec->mutant == 2 ? K / 128u - 1u : K / 128u; - const int fused = spec->mutant == 1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), px = V64(e), pw = V64(e), pl = V64(e), tid = V(e), cta = V(e), warp = V(e), lane = V(e), one = V(e); - int row = V(e), ssa = V(e), tmp = V(e), cntc = V(e), cnti = V(e), lsa = V(e), prod = V(e); - int rA = V128(e), rB = V128(e); - int acc[16], vq[4], g[16]; - for (uint32_t t = 0; t < T; t++) acc[t] = V(e); - for (uint32_t i = 0; i < 4; i++) vq[i] = V128(e); - for (uint32_t p = 0; p < PASSES; p++) g[p] = V128(e); - if (e->err) return -1; - if (CHUNKS == 0) return -1; - - ldcu64(e, udesc, 0x358); ldc64(e, px, 0x380); ldc64(e, pw, 0x388); ldc64(e, pl, 0x390); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31u); - imadi(e, row, cta, 0, T, warp); /* first tile row this thread stages */ - imadw(e, px, row, K * 4u, px); imadw(e, px, lane, 16u, px); - imadi(e, ssa, warp, 0, 512u, NOREG); imadi(e, ssa, lane, 0, 16u, ssa); - imadw(e, pw, tid, 16u, pw); - imadi(e, tmp, cta, 0, T * E, tid); imadw(e, pl, tmp, 4u, pl); - for (uint32_t t = 0; t < T; t++) movi(e, acc[t], 0x80000000u); /* -0.0: Rust's f32 sum starts there */ - ldw_pf(e, BW_IR_LDG_E_128, rA, pw, 0u, udesc, 3u); /* group 0 */ - movi(e, cntc, CHUNKS); - - #define COMPUTE(rv, immoff) do { \ - for (uint32_t b0 = 0; b0 < T; b0 += 4u) { \ - const uint32_t nb = T - b0 < 4u ? T - b0 : 4u; \ - for (uint32_t i = 0; i < nb; i++) lds128(e, vq[i], lsa, (b0 + i) * 512u + (immoff), i == 0); \ - for (uint32_t i = 0; i < nb; i++) for (unsigned q = 0; q < 4; q++) mul_add(e, fused, acc[b0 + i], 0, rv, q, vq[i], q, prod); \ - } } while (0) - - const int L_c = here(e); - loop_begin(e); - bar_sync(e); /* every reader of the previous tile is done */ - for (uint32_t p = 0; p < PASSES; p++) ldg_wide(e, BW_IR_LDG_E_128, g[p], px, p * W * K * 4u, udesc, p == 0); - for (uint32_t p = 0; p < PASSES; p++) for (unsigned q = 0; q < 4; q++) { - imadi(e, tmp, one, 0, p * W * 512u + 4u * q, ssa); - BlackwellIRInsn st = I0(BW_IR_STS32); st.src1_vreg = tmp; st.src2_vreg = g[p]; st.src2_subreg = (uint8_t)q; emit(e, st, K_STORE); - } - bar_sync(e); - imadw(e, px, one, 512u, px); - movi(e, lsa, 0); - movi(e, cnti, 16u); /* 128 k per chunk, 8 per iteration */ - const int L_i = here(e); - loop_begin(e); - consume(e, 3u); - ldw_pf(e, BW_IR_LDG_E_128, rB, pw, GB, udesc, 3u); - COMPUTE(rA, 0u); - consume(e, 3u); - ldw_pf(e, BW_IR_LDG_E_128, rA, pw, 2u * GB, udesc, 3u); - COMPUTE(rB, 16u); - imadw(e, pw, one, 2u * GB, pw); - imadi(e, lsa, one, 0, 32u, lsa); - imadi(e, cnti, one, 0, 0xffffffffu, cnti); - isetp_ge_u32(e, cnti, one); - bra_if_p0(e, L_i); - loop_end(e); - imadi(e, cntc, one, 0, 0xffffffffu, cntc); - isetp_ge_u32(e, cntc, one); - bra_if_p0(e, L_c); - loop_end(e); - #undef COMPUTE - consume(e, 3u); /* the last prefetch (the pad group) */ - for (uint32_t t = 0; t < T; t++) stg(e, pl, t * E * 4u, acc[t], udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ======================= MoE weighted combine ======================= */ -int omega_mc_spec_ok(const OmegaMcSpec *s) { - if (!s) return 0; - if (s->h < 128u || s->h > 4096u || s->h % 128u) return 0; - if (s->top_k < 4u || s->top_k > 16u || s->top_k % 4u) return 0; - return s->mutant >= 0 && s->mutant <= 2; -} - -int omega_blackwell_codegen_mc_prog(const OmegaMcSpec *spec, BlackwellIRProgram *prog) { - if (!omega_mc_spec_ok(spec) || !prog) return -1; - const uint32_t H = spec->h, KS = spec->top_k, NQ = KS / 4u; - const uint32_t USED = spec->mutant == 2 ? KS - 1u : KS; - const int fused = spec->mutant == 1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), pd = V64(e), pi = V64(e), pw = V64(e), po = V64(e), tid = V(e), cta = V(e), off = V(e), prod = V(e), accq = V128(e); - int idx[4], wt[4], v[16], pa[16]; - for (uint32_t q = 0; q < NQ; q++) { idx[q] = V128(e); wt[q] = V128(e); } - for (uint32_t s = 0; s < KS; s++) { v[s] = V128(e); pa[s] = V64(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, pd, 0x380); ldc64(e, pi, 0x388); ldc64(e, pw, 0x390); ldc64(e, po, 0x398); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadw(e, pi, cta, KS * 4u, pi); imadw(e, pw, cta, KS * 4u, pw); - for (uint32_t q = 0; q < NQ; q++) ldg_wide(e, BW_IR_LDG_E_128, idx[q], pi, 16u * q, udesc, q == 0); - for (uint32_t q = 0; q < NQ; q++) ldg_wide(e, BW_IR_LDG_E_128, wt[q], pw, 16u * q, udesc, 0); - for (uint32_t s = 0; s < KS; s++) { imadi(e, off, idx[s / 4u], s % 4u, H / 4u, tid); imadw(e, pa[s], off, 16u, pd); } - for (uint32_t s = 0; s < KS; s++) ldg_wide(e, BW_IR_LDG_E_128, v[s], pa[s], 0u, udesc, s == 0); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = accq; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - for (uint32_t s = 0; s < USED; s++) for (unsigned q = 0; q < 4; q++) mul_add(e, fused, accq, q, wt[s / 4u], s % 4u, v[s], q, prod); - imadi(e, off, cta, 0, H / 4u, tid); imadw(e, po, off, 16u, po); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = po; st.src2_vreg = accq; st.src2_subreg = (uint8_t)q; st.imm = 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_pfhost.h b/src/omega_blackwell_codegen_pfhost.h deleted file mode 100644 index 3f9545151..000000000 --- a/src/omega_blackwell_codegen_pfhost.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_PFHOST_H -#define OMEGA_BLACKWELL_CODEGEN_PFHOST_H -/* - * omega_blackwell_codegen_pfhost: the whole-prompt prefill's former host work on the chip (OWN-30B W-L1G-D, 2026-10-14). New file. - * Both kernels reproduce a host loop of the Rust driver (sc qwen3_moe_omega_prefill.rs) BIT FOR BIT: every product is an FMUL - * and every sum an FADD (never FFMA), in the host's summation order, so the results equal the host's f32 results exactly. - * - * ---- router logits (rl) ---- - * logits[r][ex] = (((-0.0 + w[ex][0] * x[r][0]) + w[ex][1] * x[r][1]) + ...) + w[ex][k-1] * x[r][k-1] - * i.e. Rust `router[ex].iter().zip(x[r]).map(|(a, b)| a * b).sum::()` (a sequential fold from -0.0). - * Weights in the PACKED layout R4: wq[g][ex][q] = w[ex][4g + q] (g = 0 .. k/4 - 1), f32, then ONE extra group of e * 4 floats - * (any value: the last prefetch reads it, the result never uses it). Total (k/4 + 1) * e * 16 bytes. - * x: f32 rows of k (row stride k). Rows 0 .. ceil(rows / t) * t - 1 must be readable (the last CTA reads whole tiles). - * logits: f32 rows of e; rows 0 .. ceil(rows / t) * t - 1 are written (rows >= rows hold garbage). - * One CTA per t rows (ctaid.x), e threads: thread ex owns expert ex and t accumulators. Per 128-wide chunk of k the CTA stages - * the t x 128 activation tile in shared memory (t * 512 bytes), then walks it four k at a time: one LDG.128 of wq (prefetched one - * group ahead), one LDS.128 broadcast per row, 4 FMUL + 4 FADD per row. - * Arguments (cbank 0x380): x u64, wq u64, logits u64. - * mutant (tests only): 1 = FFMA (fused) instead of FMUL + FADD, 2 = the last 128-wide chunk of k is skipped. - * - * ---- MoE weighted combine (mc) ---- - * out[r][c] = (((+0.0 + wt[r][0] * down[inv[r][0]][c]) + wt[r][1] * down[inv[r][1]][c]) + ...) (slots 0 .. top_k - 1) - * i.e. the driver's combine_rows accumulator (`acc = 0.0; acc += wts[gi] * d` in slot order); the host adds out to x. - * down: f32 rows of h (the down GEMM's sorted rows); inv, wt: u32 / f32 [rows][top_k] (row stride top_k, 16-byte aligned rows); - * out: f32 rows of h. One CTA per row, h / 4 threads, 4 columns each (LDG.128 per slot). - * Arguments (cbank 0x380): down u64, inv u64, wt u64, out u64. - * mutant (tests only): 1 = FFMA instead of FMUL + FADD, 2 = the last slot is skipped. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif -typedef struct { uint32_t k, e, t; int mutant; } OmegaRlSpec; -#define OMEGA_RL_ARGS_WORDS 6u -int omega_rl_spec_ok(const OmegaRlSpec *s); -uint32_t omega_rl_shared_bytes(const OmegaRlSpec *s); -int omega_blackwell_codegen_rl_prog(const OmegaRlSpec *s, BlackwellIRProgram *prog); - -typedef struct { uint32_t h, top_k; int mutant; } OmegaMcSpec; -#define OMEGA_MC_ARGS_WORDS 8u -int omega_mc_spec_ok(const OmegaMcSpec *s); -int omega_blackwell_codegen_mc_prog(const OmegaMcSpec *s, BlackwellIRProgram *prog); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_qg.c b/src/omega_blackwell_codegen_qg.c deleted file mode 100644 index 4d1e84c17..000000000 --- a/src/omega_blackwell_codegen_qg.c +++ /dev/null @@ -1,270 +0,0 @@ -/* omega_blackwell_codegen_qg.c: native FP8 prefill kernels (W-L1G). See the header. */ -#include "omega_blackwell_codegen_qg.h" -#include "omega_bw_em.h" -#include "omega_bw_em_q.h" - -static void fmul_r(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; emit(e, i, K_FIXED); -} -static void fmax_r(Em *e, int d, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; emit(e, i, K_FIXED); -} - -int omega_pq_spec_ok(const OmegaPqSpec *s) { - return s && s->k >= 128u && s->k <= 4096u && s->k % 128u == 0 && s->in_type <= OMEGA_QG_IN_BF16 && s->mutant >= 0 && s->mutant <= 2; -} - -int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *spec, BlackwellIRProgram *prog) { - if (!omega_pq_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, KB = K / 128u; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), px = V64(e), pq = V64(e), ps = V64(e), tid = V(e), row = V(e), warp = V(e); - int v = V128(e), w = V64(e), a = V128(e), m = V(e), t = V(e), fl = V(e), E = V(e), M = V(e), c = V(e), k1 = V(e), kneg = V(e), k262 = V(e); - int sb = V(e), ib = V(e), d0 = V(e), d1 = V(e), word = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, px, 0x380); ldc64(e, pq, 0x388); ldc64(e, ps, 0x390); - s2r(e, tid, BW_SR_TID_X); s2r(e, row, BW_SR_CTAID_X); - shr(e, warp, tid, 0, 5); - if (spec->in_type == OMEGA_QG_IN_F32) { imadw(e, px, row, K * 4u, px); imadw(e, px, tid, 16u, px); ldg_wide(e, BW_IR_LDG_E_128, v, px, 0, udesc, 1); } - else { imadw(e, px, row, K * 2u, px); imadw(e, px, tid, 8u, px); ldg_wide(e, BW_IR_LDG_E_64, w, px, 0, udesc, 1); } - imadw(e, pq, row, K, pq); imadw(e, pq, tid, 4u, pq); - imadw(e, ps, row, KB * 4u, ps); imadw(e, ps, warp, 4u, ps); - movi(e, fl, 0x0d800000u); /* 2^-100 */ - movi(e, k1, 0x001fffffu); - movi(e, kneg, 0xfc000000u); /* -8 << 23 */ - movi(e, k262, 0x83000000u); /* 262 << 23 */ - if (spec->in_type == OMEGA_QG_IN_BF16) { /* bf16 pairs -> f32: element 2j in the low half of word j */ - for (unsigned j = 0; j < 2; j++) { - BlackwellIRInsn lo = I0(BW_IR_IMAD); lo.dst_vreg = v; lo.dst_subreg = (uint8_t)(2u * j); lo.src1_vreg = w; lo.src1_subreg = (uint8_t)j; lo.imm = 65536u; lo.src3_vreg = NOREG; emit(e, lo, K_FIXED); - BlackwellIRInsn hi = I0(BW_IR_LOP3_AND); hi.dst_vreg = v; hi.dst_subreg = (uint8_t)(2u * j + 1u); hi.src1_vreg = w; hi.src1_subreg = (uint8_t)j; hi.imm = 0xffff0000u; emit(e, hi, K_FIXED); - } - } - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn an = I0(BW_IR_LOP3_AND); an.dst_vreg = a; an.dst_subreg = (uint8_t)q; an.src1_vreg = v; an.src1_subreg = (uint8_t)q; an.imm = 0x7fffffffu; emit(e, an, K_FIXED); } - fmax_r(e, m, a, 0, a, 1); fmax_r(e, m, m, 0, a, 2); fmax_r(e, m, m, 0, a, 3); fmax_r(e, m, m, 0, fl, 0); - if (spec->mutant != 1) for (uint32_t l = 16; l >= 1; l >>= 1) { shfl_bfly(e, t, m, l); fmax_r(e, m, m, 0, t, 0); } - shr(e, E, m, 0, 23); - andi(e, M, m, 0, 0x007fffffu); - if (spec->mutant == 2) movi(e, c, 0); - else { imadi(e, c, M, 0, 1u, k1); shr(e, c, c, 0, 23); } - iadd(e, E, E, c); /* E + c */ - imadi(e, sb, E, 0, 1u << 23, kneg); /* scale bits (E + c - 8) << 23 */ - imadi(e, ib, E, 0, 0xff800000u, k262); /* inv bits (262 - E - c) << 23 */ - for (unsigned q = 0; q < 4; q++) fmul_r(e, v, q, v, q, ib, 0); - f2e4(e, d0, v, 1, v, 0); - f2e4(e, d1, v, 3, v, 2); - imadi(e, word, d1, 0, 65536u, d0); - stg(e, pq, 0, word, udesc); - stg(e, ps, 0, sb, udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ======================= grouped GEMM on QMMA (see the header) ======================= */ -int omega_qg_spec_ok(const OmegaQgSpec *s) { - if (!s) return 0; - if (s->k < 128u || s->k > 16384u || s->k % 128u) return 0; - if (s->rt != 4) return 0; /* rt 8 needs more than 128 registers and 17408 shared bytes (QMD cap 16384) */ - if (s->warps != 8 && s->warps != 16) return 0; - if (s->epi > OMEGA_QG_EPI_SWIGLU || s->direct > 1 || s->wait > 120u) return 0; - if (s->epi == OMEGA_QG_EPI_SWIGLU && s->n % 256u) return 0; /* gate and up halves start on a 128-row scale block */ - if (s->n == 0 || s->n % (s->warps * 16u) || (uint64_t)s->n * 4u * 16u * s->rt >= (1u << 23)) return 0; - if ((16u * s->rt * 4u) % (32u * s->warps)) return 0; /* whole 16-byte staging slots per thread */ - if (s->mutant < 0 || s->mutant > 4) return 0; - return 1; -} -uint32_t omega_qg_shared_bytes(const OmegaQgSpec *s) { return omega_qg_spec_ok(s) ? 2u * (16u * s->rt * 64u + 16u * s->rt * 4u) : 0u; } -uint32_t omega_qg_span(const OmegaQgSpec *s) { return omega_qg_spec_ok(s) ? s->warps * 16u : 0u; } - -static void ffma_s(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub, int c, unsigned csub) { - BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; - i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; i.src3_subreg = (uint8_t)csub; emit(e, i, K_FIXED); -} -static void mufu_q(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); } - -int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *spec, BlackwellIRProgram *prog) { - if (!omega_qg_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, RT = spec->rt, W = spec->warps, T = 32u * W; - const uint32_t BM = 16u * RT, KB = K / 128u, SPAN = W * 16u, NJ = BM * 4u / T, ABUF = BM * 64u, BUF = ABUF + BM * 4u; - const uint32_t NS = spec->epi == OMEGA_QG_EPI_SWIGLU ? 2u : 1u; /* scale rows per warp: gate + up block, or one block */ - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - int udesc = UV64(e), ptab = V64(e), pidx = V64(e), px = V64(e), pxs = V64(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), g = V(e), tq = V(e), one = V(e), tent = V64(e); - int wbase = V64(e), sbase = V64(e), rc = V64(e), row0 = V(e), n0w = V(e), tmp = V(e), tmp2 = V(e), rb = V(e), la = V(e), lsa = V(e); - int pw[2] = { V64(e), V64(e) }, ps[2] = { V64(e), NS > 1 ? V64(e) : NOREG }; - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ptab, 0x380); if (!spec->direct) ldc64(e, pidx, 0x388); ldc64(e, px, 0x390); ldc64(e, pxs, 0x3a0); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); andi(e, lane, tid, 0, 31); shr(e, g, lane, 0, 2); andi(e, tq, lane, 0, 3); - imadw(e, tent, cy, OMEGA_QG_TILE_BYTES, ptab); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, sbase, tent, 8, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, rc, tent, 16, udesc, 0); - imadi(e, row0, rc, 0, 1, NOREG); - imadi(e, n0w, cx, 0, SPAN, NOREG); imadi(e, tmp, warp, 0, 16u, NOREG); iadd(e, n0w, n0w, tmp); - /* weight rows of the GEMV tensor (original order): F32 rows n0w + g (+ 8 for column tile 1); SWIGLU gate rows n0w / 2 + g, up rows n / 2 later */ - if (NS > 1) shr(e, rb, n0w, 0, 1); else imadi(e, rb, n0w, 0, 1u, NOREG); - iadd(e, tmp, rb, g); imadw(e, pw[0], tmp, K, wbase); imadi(e, tmp2, tq, 0, 16u, NOREG); imadw(e, pw[0], tmp2, 1, pw[0]); - imadi(e, tmp, one, 0, NS > 1 ? spec->n / 2u : 8u, NOREG); imadw(e, pw[1], tmp, K, pw[0]); - /* scales [n / 128][KB] f32 * 2^56 (omega_gpu_fp8_api.h): the block of row rb (and of rb + n / 2) */ - shr(e, tmp, rb, 0, 7); imadw(e, ps[0], tmp, KB * 4u, sbase); - if (NS > 1) { imadi(e, tmp, one, 0, spec->n / 2u, rb); shr(e, tmp, tmp, 0, 7); imadw(e, ps[1], tmp, KB * 4u, sbase); } - imadi(e, la, lane, 0, 16u, NOREG); - imadi(e, lsa, g, 0, 16u, NOREG); - - /* staging: slot = tid + jj T -> row r = slot / 4, 16-byte segment t4 = tid % 4 of the 64-byte chunk */ - int gx[4], gs[4], sa[4], ssa[4]; - for (uint32_t jj = 0; jj < NJ; jj++) { gx[jj] = V64(e); gs[jj] = V64(e); sa[jj] = V(e); ssa[jj] = V(e); } - int r = V(e), sidx = V64(e), srow = V(e), t4 = V(e), hi = V(e), gg = V(e), ti = V(e); - if (e->err) return -1; - andi(e, t4, tid, 0, 3); - for (uint32_t jj = 0; jj < NJ; jj++) { - shr(e, r, tid, 0, 2); imadi(e, r, one, 0, jj * T / 4u, r); - iadd(e, tmp, row0, r); - if (spec->direct) imadi(e, srow, tmp, 0, 1u, NOREG); - else { imadw(e, sidx, tmp, 4u, pidx); ldg32(e, srow, sidx, udesc, 1); } - imadw(e, gx[jj], srow, K, px); imadi(e, tmp2, t4, 0, 16u, NOREG); imadw(e, gx[jj], tmp2, 1, gx[jj]); - imadw(e, gs[jj], srow, KB * 4u, pxs); - /* A slot: i * 1024 + (gg * 4 + t4) * 16 + 4 hi, i = r / 16, gg = r % 8, hi = (r / 8) % 2 */ - shr(e, ti, r, 0, 4); andi(e, gg, r, 0, 7); shr(e, hi, r, 0, 3); andi(e, hi, hi, 0, 1); - imadi(e, tmp, gg, 0, 4u, t4); imadi(e, tmp, tmp, 0, 16u, NOREG); imadi(e, tmp, ti, 0, 1024u, tmp); imadi(e, sa[jj], hi, 0, 4u, tmp); - /* scale slot: ABUF + ((i / 2) * 8 + gg) * 16 + 4 * ((i % 2) * 2 + hi) */ - shr(e, tmp, ti, 0, 1); imadi(e, tmp, tmp, 0, 8u, gg); imadi(e, tmp, tmp, 0, 16u, NOREG); - andi(e, tmp2, ti, 0, 1); imadi(e, tmp2, tmp2, 0, 2u, hi); imadi(e, ssa[jj], tmp2, 0, 4u, tmp); - } - - int acc[16], wa[2], wb[2], tq2[2], aq = V128(e), sap = V128(e), sc = V128(e), stgr[4], scv[4], cntk = V(e), onef1 = V(e), c2m56 = V(e); - int rr[2] = { V(e), NS > 1 ? V(e) : NOREG }, rrn[2] = { V(e), NS > 1 ? V(e) : NOREG }; - for (uint32_t x = 0; x < RT * 2u; x++) acc[x] = V128(e); - for (uint32_t j = 0; j < 2; j++) { wa[j] = V128(e); wb[j] = V128(e); tq2[j] = V128(e); } - for (uint32_t jj = 0; jj < NJ; jj++) { stgr[jj] = V128(e); scv[jj] = V(e); } - if (e->err) return -1; - movi(e, onef1, 0x3f800000u); - movi(e, c2m56, 0x23800000u); /* 2^-56: undoes the GEMV tensor's scale fold exactly (sw * 2^-56 is the checkpoint bf16 scale) */ - - #define ISSUE(wset, sb, xoff, woff, with_scale) do { \ - for (uint32_t jj = 0; jj < NJ; jj++) { ldw_pf(e, BW_IR_LDG_E_128, stgr[jj], gx[jj], (xoff), udesc, (sb)); ldw_pf(e, BW_IR_LDG_E, scv[jj], gs[jj], 0u, udesc, (sb)); } \ - for (uint32_t j = 0; j < 2; j++) ldw_pf(e, BW_IR_LDG_E_128, (wset)[j], pw[j], (woff), udesc, (sb)); \ - if (with_scale) for (uint32_t s = 0; s < NS; s++) ldw_pf(e, BW_IR_LDG_E, rrn[s], ps[s], 0u, udesc, (sb)); } while (0) - #define STAGE(buf) do { for (uint32_t jj = 0; jj < NJ; jj++) { static const uint32_t off[4] = { 0, 8, 512, 520 }; \ - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STS32); imadi(e, tmp, one, 0, (buf) + off[q], sa[jj]); \ - st.src1_vreg = tmp; st.src2_vreg = stgr[jj]; st.src2_subreg = (uint8_t)q; emit(e, st, K_STORE); } \ - { BlackwellIRInsn st = I0(BW_IR_STS32); imadi(e, tmp, one, 0, (buf) + ABUF, ssa[jj]); st.src1_vreg = tmp; st.src2_vreg = scv[jj]; emit(e, st, K_STORE); } } \ - bar_sync(e); } while (0) - #define COMPUTE(buf, wset, odd) do { \ - for (uint32_t i = 0; i < RT; i++) { \ - const uint32_t ii = spec->mutant == 3 ? (i ^ 1u) : i; \ - if ((i & 1u) == 0) lds128(e, sap, lsa, (buf) + ABUF + (i / 2u) * 128u, 1); \ - lds128(e, aq, la, (buf) + (ii * 2u) * 512u, 1); \ - for (uint32_t j = 0; j < 2; j++) qmma_s(e, tq2[j], aq, (wset)[j], 0, NOREG, 2); \ - if (!(spec->mutant == 4 && (odd))) { lds128(e, aq, la, (buf) + (ii * 2u + 1u) * 512u, 1); \ - for (uint32_t j = 0; j < 2; j++) qmma_s(e, tq2[j], aq, (wset)[j], 2, tq2[j], 2); } \ - for (uint32_t h = 0; h < 2; h++) for (uint32_t j = 0; j < 2; j++) { \ - BlackwellIRInsn m = I0(BW_IR_FMUL); m.dst_vreg = sc; m.dst_subreg = (uint8_t)(2u * h + j); \ - m.src1_vreg = sap; m.src1_subreg = (uint8_t)(2u * (i & 1u) + h); m.src2_vreg = rr[NS > 1 ? j : 0]; \ - if (spec->mutant == 1) { m.src1_vreg = onef1; m.src1_subreg = 0; } /* drops sa: s = 1.0 * sw */ \ - emit(e, m, K_FIXED); } \ - { uint32_t wl = spec->wait; while (wl > 0) { uint32_t st = wl > 15u ? 15u : wl; nop(e, st); wl -= st; } } \ - for (uint32_t j = 0; j < 2; j++) for (unsigned q = 0; q < 4; q++) { const uint32_t x = i * 2u + j; \ - ffma_s(e, acc[x], q, tq2[j], q, sc, 2u * (q >> 1) + j, acc[x], q); } \ - } } while (0) - - for (uint32_t x = 0; x < RT * 2u; x++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = acc[x]; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - ISSUE(wa, 3u, 0u, 0u, 1); - consume(e, 3); - for (uint32_t s = 0; s < NS; s++) fmul_r(e, rr[s], 0, rrn[s], 0, c2m56, 0); - STAGE(0u); - movi(e, cntk, KB); - - const int L_k = here(e); - loop_begin(e); - ISSUE(wb, 4u, 64u, 64u, 0); - consume(e, 3); - COMPUTE(0u, wa, 0); - consume(e, 4); - STAGE(BUF); - { int nf = V(e), inc = V(e); if (e->err) return -1; - imadi(e, nf, one, 0, 0xfffffffeu, cntk); shr(e, nf, nf, 0, 31); imadi(e, nf, nf, 0, 0xffffffffu, one); - for (uint32_t jj = 0; jj < NJ; jj++) { imadw(e, gx[jj], nf, 128u, gx[jj]); imadw(e, gs[jj], nf, 4u, gs[jj]); } - for (uint32_t j = 0; j < 2; j++) imadw(e, pw[j], nf, 128u, pw[j]); - imadi(e, inc, nf, 0, spec->mutant == 2 ? 0u : 4u, NOREG); for (uint32_t s = 0; s < NS; s++) imadw(e, ps[s], inc, 1, ps[s]); - } - ISSUE(wa, 3u, 0u, 0u, 1); - COMPUTE(BUF, wb, 1); - consume(e, 3); - STAGE(0u); - for (uint32_t s = 0; s < NS; s++) fmul_r(e, rr[s], 0, rrn[s], 0, c2m56, 0); - imadi(e, cntk, one, 0, 0xffffffffu, cntk); - isetp_ge_u32(e, cntk, one); - bra_if_p0(e, L_k); - loop_end(e); - #undef ISSUE - #undef STAGE - #undef COMPUTE - - /* ---- epilogue (as omega_blackwell_codegen_tc2.c, natural SwiGLU order, no extra scale) ---- */ - int g2 = V(e), cnt2 = V(e), rrow = V(e), onee = V(e), pyr = V64(e); - { - int tid2 = V(e), cx2 = V(e), cy2 = V(e), lane2 = V(e), tq3 = V(e), tab2 = V64(e), ten2 = V64(e), rc2 = V64(e), py2 = V64(e), n2 = V(e), nw2 = V(e), r02 = V(e); - if (e->err) return -1; - ldc64(e, tab2, 0x380); ldc64(e, py2, 0x398); ldc32(e, n2, 0x3a8); - s2r(e, tid2, BW_SR_TID_X); s2r(e, cx2, BW_SR_CTAID_X); s2r(e, cy2, BW_SR_CTAID_Y); - imadw(e, ten2, cy2, OMEGA_QG_TILE_BYTES, tab2); - ldg_wide(e, BW_IR_LDG_E_64, rc2, ten2, 16, udesc, 1); - andi(e, lane2, tid2, 0, 31); shr(e, g2, lane2, 0, 2); andi(e, tq3, lane2, 0, 3); - imadi(e, r02, rc2, 0, 1, NOREG); imadi(e, cnt2, rc2, 1, 1, NOREG); movi(e, onee, 1); - shr(e, tmp, tid2, 0, 5); imadi(e, tmp, tmp, 0, 16u, NOREG); imadi(e, nw2, cx2, 0, SPAN, tmp); - if (spec->epi == OMEGA_QG_EPI_F32) { - iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, nw2); imadi(e, tmp2, tq3, 0, 2u, NOREG); iadd(e, tmp, tmp, tmp2); imadw(e, pyr, tmp, 4u, py2); - } else { - iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, NOREG); imadw(e, pyr, tmp, 1u, py2); - shr(e, tmp, nw2, 0, 1); imadi(e, tmp2, tq3, 0, 2u, tmp); imadw(e, pyr, tmp2, 2u, pyr); - } - } - int kf = NOREG, onef = NOREG, c125 = NOREG, tg = NOREG, tex = NOREG, o0 = NOREG, o1 = NOREG, pk = NOREG; - if (spec->epi == OMEGA_QG_EPI_SWIGLU) { - kf = V(e); onef = V(e); c125 = V(e); tg = V(e); tex = V(e); o0 = V(e); o1 = V(e); pk = V(e); - if (e->err) return -1; - movi(e, kf, 0xbfb8aa3bu); movi(e, onef, 0x3f800000u); - movi(e, c125, 0x42fa0000u); /* 125.0f: caps t so 1 / (2^t + 1) stays a normal f32 (the chip flushes subnormal MUFU.RCP results: hardware, evidence OWN30B-L1G-SWIGLU-DIAG-ca29218e) */ - } - if (e->err) return -1; - const uint32_t ystride = spec->epi == OMEGA_QG_EPI_F32 ? spec->n * 4u : spec->n; - int skips[16]; uint32_t nskip = 0; - const int at_bssy = bssy_fwd(e); - for (uint32_t i = 0; i < RT; i++) for (uint32_t h = 0; h < 2; h++) { - const uint32_t roff = (16u * i + 8u * h) * ystride; - imadi(e, rrow, onee, 0, 16u * i + 8u * h, g2); - isetp_ge_u32(e, rrow, cnt2); - skips[nskip++] = bra_if_p0_fwd(e); - if (spec->epi == OMEGA_QG_EPI_F32) { - for (uint32_t j = 0; j < 2; j++) for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = pyr; st.src2_vreg = acc[i * 2 + j]; st.src2_subreg = (uint8_t)(2u * h + q); st.imm = roff + j * 32u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - } else { - const int G = acc[i * 2], U = acc[i * 2 + 1]; - for (unsigned q = 0; q < 2; q++) { - const int o = q ? o1 : o0; const unsigned sub = 2u * h + q; - fmul_r(e, tg, 0, G, sub, kf, 0); - { BlackwellIRInsn mn = I0(BW_IR_FMNMX_MIN); mn.dst_vreg = tg; mn.src1_vreg = tg; mn.src2_vreg = c125; emit(e, mn, K_FIXED); } - mufu_q(e, BW_IR_MUFU_EX2, tex, tg); - fadd(e, tex, tex, onef); - mufu_q(e, BW_IR_MUFU_RCP, tex, tex); - fmul_r(e, o, 0, G, sub, tex, 0); - fmul_r(e, o, 0, o, 0, U, sub); - } - f2fp_pack(e, pk, o1, o0); - stg(e, pyr, roff, pk, udesc); - } - } - { const int at_bsync = here(e); - bsync(e); - for (uint32_t q = 0; q < nskip; q++) patch_bra(e, skips[q], at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_qg.h b/src/omega_blackwell_codegen_qg.h deleted file mode 100644 index daf96304d..000000000 --- a/src/omega_blackwell_codegen_qg.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_QG_H -#define OMEGA_BLACKWELL_CODEGEN_QG_H -/* - * omega_blackwell_codegen_qg: native FP8 prefill kernels (OWN-30B L1 GEMM, W-L1G, 2026-10-14). New file. - * - * ---- activation quantiser (pq) ---- - * Per row r and 128-wide group b of k: amax = max(max_j |x[r][128b + j]|, 2^-100) - * E = biased f32 exponent of amax, M = its 23 mantissa bits, c = (M + 0x1fffff) >> 23 (1 when amax / 2^(E-127) > 1.75) - * scale = 2^(E - 135 + c) (the smallest power of two with amax / scale <= 448), inv = 2^(135 - E - c) - * q[r][128b + j] = e4m3_rne_satfinite(x * inv) (FMUL by a power of two: exact for every result that can be nonzero) - * s[r][b] = scale (f32) - * Power-of-two scales instead of amax / 448 (stated deviation from the usual dynamic scheme): the GEMM's scale products - * stay exact and no reciprocal is needed; e4m3 precision is uniform over its normal range, so at most the subnormal tail - * of a group loses one bit. - * Layout: x f32 or bf16 rows of k (row stride k elements); q e4m3 rows of k bytes; s f32 [rows][k / 128]. - * One CTA per row (ctaid.x = row), 32 * (k / 128) threads: warp b = group b, lane l = elements 4l .. 4l+3. - * Arguments (cbank 0x380): x u64, q u64, s u64. - * mutant (tests only): 1 skips the butterfly (lane-local amax), 2 uses c = 0. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif -enum { OMEGA_QG_IN_F32 = 0, OMEGA_QG_IN_BF16 = 1 }; -typedef struct { uint32_t k, in_type; int mutant; } OmegaPqSpec; -#define OMEGA_PQ_ARGS_WORDS 6u -int omega_pq_spec_ok(const OmegaPqSpec *s); -int omega_blackwell_codegen_pq_prog(const OmegaPqSpec *s, BlackwellIRProgram *prog); - -/* ---- grouped GEMM on QMMA (qgemm) ---- - * y[row][c] = sum_kb sum_{h in 0,1} fma-promoted( T(row, c, kb, h) * (sa[src(row)][kb] * sw[c][kb]) ) - * where T is two chained QMMA steps from zero over the 64-byte chunk h of block kb: T = Q(v1, C = Q(v0, C = 0)), and after each - * chunk acc = fma(T, sa * sw, acc) in f32 (sa a power of two, so sa * sw is exact). Step v of chunk h: lane t's 16 bytes - * 64h + 16t .. +15 of both the activation row and the weight row; bytes 8v .. 8v+3 are logical k 4t .. 4t+3 of the QMMA and - * bytes 8v+4 .. 8v+7 logical k 16+4t .. 16+4t+3 (A and B alike, so no K permutation is stored anywhere). - * Weights: read IN PLACE from an omega_gpu_fp8_api tensor (no second copy): e4m3 rows of k in checkpoint order, scales - * [n / 128][KB] f32 * 2^56 per expert; the kernel uses sw = S * 2^-56 (exact: the checkpoint bf16 scale). Activations: e4m3 rows of k (xq) + f32 scales - * [rows][KB] (xs), the quantiser's output. Output F32: y f32 rows of n (warp columns n0w .. n0w+15). SWIGLU (n = 2I, gate rows - * 0 .. I-1 then up rows I .. 2I-1, as the checkpoint): column tile 0 of a warp is gate rows n0w / 2 .. +7, tile 1 the up rows I later; act[row][n0w / 2 + 2t + q] = bf16_rn(g * rcp(2^min(-g log2 e, 125) + 1) * u), no extra scale - * (the cap keeps the reciprocal normal: for g < -86.6 the result is g * 2^-125 * u instead of a flushed or subnormal value). - * Tile entry (32 bytes): { w_va u64, s_va u64, row0 u32, cnt u32 (1 .. 16 rt), pad u64 }; rows past cnt are not stored. - * Constant bank 0x380: tiles, rowidx (ignored when direct), xq, y, xs (u64 each), n u32 at 0x3a8. - * Grid: n / (warps * 16) x tiles; 32 * warps threads; shared 2 * (16 rt * 64 + 16 rt * 4) bytes. - * mutant (tests only): 1 drops sa (uses sw only), 2 never advances the sw pointer, 3 row tile i reads tile i^1, 4 drops step 1 - * of every odd chunk. */ -enum { OMEGA_QG_EPI_F32 = 0, OMEGA_QG_EPI_SWIGLU = 1 }; -typedef struct { - uint32_t k; /* multiple of 128, 128 .. 16384 */ - uint32_t rt; /* row tiles of 16: 4 (8 exceeds 128 registers and the 16384-byte QMD shared cap) */ - uint32_t warps; /* 8 or 16 */ - uint32_t epi; /* OMEGA_QG_EPI_* */ - uint32_t direct; /* 1: no row index */ - uint32_t n; /* output width (weight rows), multiple of warps * 16 */ - uint32_t wait; /* stall cycles between a row tile's last QMMA and the first FFMA reading its result */ - int mutant; -} OmegaQgSpec; -#define OMEGA_QG_ARGS_WORDS 11u -#define OMEGA_QG_TILE_BYTES 32u -int omega_qg_spec_ok(const OmegaQgSpec *s); -uint32_t omega_qg_shared_bytes(const OmegaQgSpec *s); -uint32_t omega_qg_span(const OmegaQgSpec *s); -int omega_blackwell_codegen_qgemm_prog(const OmegaQgSpec *s, BlackwellIRProgram *prog); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_qmma.c b/src/omega_blackwell_codegen_qmma.c deleted file mode 100644 index 7616015ee..000000000 --- a/src/omega_blackwell_codegen_qmma.c +++ /dev/null @@ -1,137 +0,0 @@ -/* omega_blackwell_codegen_qmma.c: QMMA.16832.F32.E4M3.E4M3 placeholder, patch, probe and peak kernels (W-L1G). See the header. */ -#include "omega_blackwell_codegen_qmma.h" -#include "omega_bw_em.h" -#include "omega_bw_em_q.h" -#include "omega_gpu_fmt.h" - -static uint32_t rd32q(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } -static void wr32q(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } - -int omega_qmma_is_mark(const BlackwellIRInsn *in) { return in && in->op == BW_IR_HMMA_BF16 && in->imm == OMEGA_QMMA_MARK; } - -int omega_qmma_patch_code(const BlackwellIRProgram *prog, uint8_t *code, size_t len) { - if (!prog || !code || len < prog->count * 16u) return -1; - int n = 0; - for (size_t i = 0; i < prog->count; i++) { - if (prog->insns[i].op == BW_IR_FMNMX_MAX && prog->insns[i].imm == OMEGA_QMMA_MARK_F2E4) { - uint8_t *w = code + i * 16u; uint32_t w0 = rd32q(w), w1 = rd32q(w + 4), w2 = rd32q(w + 8); - if ((w0 & 0xffffu) != 0x7209u || (w1 & 0xffffff00u) != 0 || w2 != 0x07800000u) return -1; - wr32q(w, (w0 & 0xffff0000u) | 0x723eu); wr32q(w + 8, 0x048070ffu); n++; continue; - } - if (!omega_qmma_is_mark(&prog->insns[i])) continue; - uint8_t *w = code + i * 16u; - uint32_t w0 = rd32q(w), w1 = rd32q(w + 4), w2 = rd32q(w + 8); - if ((w0 & 0xffffu) != 0x723cu || (w1 & 0xffffff00u) != 0 || (w2 & 0xffffff00u) != 0x00041800u) return -1; - wr32q(w, (w0 & 0xffff0000u) | 0x727au); - wr32q(w + 8, (w2 & 0xffu) | 0x00002c00u); - n++; - } - return n; -} - -int omega_qmma_patch_selftest(char *msg, size_t msgn) { - static BlackwellIRProgram p; static uint8_t buf[64 * 16]; size_t len = 0; - omega_bw_ir_init(&p); - Em em; memset(&em, 0, sizeof em); em.p = &p; Em *e = &em; - int udesc = UV64(e), py = V64(e), a = V128(e), b = V64(e), c = V128(e); - if (e->err) { omega_gpu_fmt(msg, msgn, "vregs"); return -1; } - ldcu64(e, udesc, 0x358); ldc64(e, py, 0x380); - ldg_wide(e, BW_IR_LDG_E_128, a, py, 0, udesc, 1); ldg_wide(e, BW_IR_LDG_E_64, b, py, 16, udesc, 0); ldg_wide(e, BW_IR_LDG_E_128, c, py, 32, udesc, 0); - qmma(e, c, a, b, c, 15); nop(e, 15); - { int f = V(e); if (e->err) { omega_gpu_fmt(msg, msgn, "vregs"); return -1; } f2e4(e, f, c, 0, c, 1); stg(e, py, 64, f, udesc); } - hmma(e, c, a, b, c, 15); nop(e, 15); - for (unsigned q = 0; q < 4; q++) stg(e, py, 4u * q, c, udesc); - tail(e); - if (e->err || omega_bw_regalloc_solve(&p) != 0 || omega_bw_encode_program(&p, buf, sizeof buf, &len) != 0) { omega_gpu_fmt(msg, msgn, "build/encode failed"); return -1; } - int np = omega_qmma_patch_code(&p, buf, len); - if (np != 2) { omega_gpu_fmt(msg, msgn, "patched %d placeholders, expected 2", np); return -1; } - int seenq = 0, seenh = 0, seenf = 0; - for (size_t i = 0; i < p.count; i++) { - if (p.insns[i].op == BW_IR_FMNMX_MAX) { const uint8_t *w = buf + i * 16u; uint32_t w0 = rd32q(w), w1 = rd32q(w + 4), w2 = rd32q(w + 8); - if ((w0 & 0xffffu) != 0x723eu || (w1 & 0xffffff00u) != 0 || w2 != 0x048070ffu) { omega_gpu_fmt(msg, msgn, "F2FP.E4M3 word %zu: %08x %08x %08x", i, w0, w1, w2); return -1; } seenf++; continue; } - if (p.insns[i].op != BW_IR_HMMA_BF16) continue; - const uint8_t *w = buf + i * 16u; uint32_t w0 = rd32q(w), w1 = rd32q(w + 4), w2 = rd32q(w + 8); - if (omega_qmma_is_mark(&p.insns[i])) { - /* oracle 0x0414727a 0x0000000c 0x00002c14 with registers masked */ - if ((w0 & 0xffffu) != 0x727au || (w1 & 0xffffff00u) != 0 || (w2 & 0xffffff00u) != 0x00002c00u) { omega_gpu_fmt(msg, msgn, "QMMA word %zu: %08x %08x %08x", i, w0, w1, w2); return -1; } - seenq++; - } else { - if ((w0 & 0xffffu) != 0x723cu || (w2 & 0xffffff00u) != 0x00041800u) { omega_gpu_fmt(msg, msgn, "HMMA word %zu changed: %08x %08x", i, w0, w2); return -1; } - seenh++; - } - } - if (seenq != 1 || seenh != 1 || seenf != 1) { omega_gpu_fmt(msg, msgn, "saw %d QMMA, %d HMMA", seenq, seenh); return -1; } - omega_gpu_fmt(msg, msgn, "QMMA.16832.F32.E4M3.E4M3 and F2FP.SATFINITE.E4M3.F32.PACK_AB_MERGE_C match the oracle bits, HMMA untouched"); - return 0; -} - -int omega_blackwell_codegen_qmma_probe_prog(int mutant, uint32_t wait_nops, BlackwellIRProgram *prog) { - if (!prog || mutant < 0 || mutant > 1 || wait_nops > 16) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), pin = V64(e), pout = V64(e), tid = V(e), cx = V(e), pa = V64(e), po = V64(e), pcase = V64(e), pb = V64(e); - int a = V128(e), b = V64(e), c = V128(e), d = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, 0x380); ldc64(e, pout, 0x388); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - imadw(e, pcase, cx, 1280u, pin); imadw(e, pa, tid, 16, pcase); imadw(e, pb, tid, 8, pcase); - imadw(e, po, cx, 512u, pout); imadw(e, po, tid, 16, po); - ldg_wide(e, BW_IR_LDG_E_128, a, pa, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, c, pa, 768, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, b, pb, 512, udesc, 0); - qmma(e, d, a, b, mutant == 1 ? NOREG : c, 15); - for (uint32_t i = 0; i < wait_nops; i++) nop(e, 15); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = po; i.src2_vreg = d; i.src2_subreg = (uint8_t)q; i.imm = 4u * q; i.ureg = udesc; emit(e, i, K_STORE); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_blackwell_codegen_qmma_peak_prog(uint32_t iters, uint32_t chains, uint32_t stall, uint32_t threads, BlackwellIRProgram *prog) { - if (!prog || iters == 0 || chains == 0 || chains > 16 || stall == 0 || stall > 15 || threads == 0 || threads % 32 || threads > 1024) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), py = V64(e), tid = V(e), cta = V(e), one = V(e), cnt = V(e), a = V128(e), b = V64(e), acc[16]; - for (uint32_t c = 0; c < chains; c++) acc[c] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, py, 0x380); s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn m = I0(BW_IR_MOV_IMM); m.dst_vreg = a; m.dst_subreg = (uint8_t)q; m.imm = 0x38383838u; emit(e, m, K_FIXED); } - for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn m = I0(BW_IR_MOV_IMM); m.dst_vreg = b; m.dst_subreg = (uint8_t)q; m.imm = 0x38383838u; emit(e, m, K_FIXED); } - for (uint32_t c = 0; c < chains; c++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = acc[c]; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - movi(e, cnt, iters); - const int L = here(e); - loop_begin(e); - for (uint32_t c = 0; c < chains; c++) qmma(e, acc[c], a, b, acc[c], stall); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L); - loop_end(e); - nop(e, 15); nop(e, 15); nop(e, 15); nop(e, 15); - { int t = V(e); if (e->err) return -1; - imadi(e, t, cta, 0, threads, tid); imadw(e, py, t, 16u * chains, py); - for (uint32_t c = 0; c < chains; c++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = py; st.src2_vreg = acc[c]; st.src2_subreg = (uint8_t)q; st.imm = c * 16u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_blackwell_codegen_f2e4_probe_prog(BlackwellIRProgram *prog) { - if (!prog) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), px = V64(e), py = V64(e), tid = V(e), cx = V(e), gi = V(e), x = V64(e), d = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, px, 0x380); ldc64(e, py, 0x388); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - imadi(e, gi, cx, 0, 128u, tid); - imadw(e, px, gi, 8u, px); imadw(e, py, gi, 4u, py); - ldg_wide(e, BW_IR_LDG_E_64, x, px, 0, udesc, 1); - f2e4(e, d, x, 0, x, 1); - stg(e, py, 0, d, udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_qmma.h b/src/omega_blackwell_codegen_qmma.h deleted file mode 100644 index 75daaaaef..000000000 --- a/src/omega_blackwell_codegen_qmma.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_QMMA_H -#define OMEGA_BLACKWELL_CODEGEN_QMMA_H -/* - * omega_blackwell_codegen_qmma: native FP8 tensor-core op QMMA.16832.F32.E4M3.E4M3 (OWN-30B L1 GEMM, W-L1G, 2026-10-14). New file. - * - * Encoding (the shared encoder lacks it): emitted as BW_IR_HMMA_BF16 with imm = OMEGA_QMMA_MARK and patched after encoding. - * Oracle (nvcc 13.0.88 -arch=sm_121, investigations/2026-10-14-qmma-oracle/oracle.sass, C a real register): - * QMMA.16832.F32.E4M3.E4M3 R20, R4, R12, R20 = 0x0000000c0414727a / 0x004fe20000002c14 - * HMMA.16816.F32.BF16 R8, R12, R6, R8 = 0x000000060c08723c / ...00041808 (encoder fixture) - * Same register slots (Rd 16..23, Ra 24..31 of word 0, Rb word 1, Rc low byte of word 2); the patch sets the opcode low - * bits 0x723c -> 0x727a and word 2 bits 0x00041800 -> 0x00002c00, keeping Rc. - * - * Fragment layout (INFERRED from the PTX ISA m16n8k32 8-bit figures, which Context7 does not return: DOCS SILENT there; - * the chip probe checks it on exact integer cases). Lane L, g = L / 4, t = L % 4; byte j of a register is element j: - * A 16x32: reg0 = A[g][4t..4t+3] reg1 = A[g+8][4t..4t+3] reg2 = A[g][16+4t..] reg3 = A[g+8][16+4t..] - * B 32x8: reg0 = B[4t..4t+3][g] reg1 = B[16+4t..16+4t+3][g] - * C/D f32: as HMMA.16816 (c0,c1 = C[g][2t, 2t+1], c2,c3 = C[g+8][2t, 2t+1]). - * - * Probe kernel: as omega_blackwell_codegen_tc_probe_prog (same 1280-byte case: A quads, B pairs, C quads; 512-byte D), - * one QMMA per warp; mutant 1 drops C. - * Peak kernel: as omega_blackwell_codegen_tc_peak_prog with QMMA (A = B = e4m3 1.0 = 0x38): every stored value 32 * iters. - */ -#include -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif -#define OMEGA_QMMA_MARK 0x51303832u -/* F2FP.SATFINITE.E4M3.F32.PACK_AB_MERGE_C Rd, Ra, Rb, RZ: emitted as BW_IR_FMNMX_MAX with imm OMEGA_QMMA_MARK_F2E4; the patch sets - * opcode 0x7209 -> 0x723e and word 2 0x07800000 -> 0x048070ff (oracle investigations/2026-10-14-qmma-oracle/cvt.sass: - * F2FP.SATFINITE.E4M3.F32.PACK_AB_MERGE_C R7, R7, R0, RZ = 0x000000000707723e / 0x004fca00048070ff). Result low 16 bits: - * e4m3(Ra) << 8 | e4m3(Rb) (INFERRED from the chip-verified bf16 PACK_AB; the cvt probe checks), high 16 bits 0. */ -#define OMEGA_QMMA_MARK_F2E4 0x46453433u -int omega_qmma_is_mark(const BlackwellIRInsn *in); -/* patch every QMMA placeholder in the encoded code (one 16-byte word per IR instruction); returns the number patched, - * or -1 when a marked word does not hold the expected HMMA bits */ -int omega_qmma_patch_code(const BlackwellIRProgram *prog, uint8_t *code, size_t len); -/* encoder self-test against the oracle words (register fields excluded); 0 = pass */ -int omega_qmma_patch_selftest(char *msg, size_t msgn); -int omega_blackwell_codegen_qmma_probe_prog(int mutant, uint32_t wait_nops, BlackwellIRProgram *prog); -int omega_blackwell_codegen_qmma_peak_prog(uint32_t iters, uint32_t chains, uint32_t stall, uint32_t threads, BlackwellIRProgram *prog); -/* convert probe: thread i converts the f32 pair at arg0 + 8i (Ra = first, Rb = second) and stores the u32 result at arg1 + 4i */ -int omega_blackwell_codegen_f2e4_probe_prog(BlackwellIRProgram *prog); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_router.c b/src/omega_blackwell_codegen_router.c deleted file mode 100644 index 31e21331d..000000000 --- a/src/omega_blackwell_codegen_router.c +++ /dev/null @@ -1,405 +0,0 @@ -/* - * omega_blackwell_codegen_router.c: the one-launch MoE router kernel (see the header). Emitter rules follow - * omega_blackwell_codegen_attn.c / omega_blackwell_codegen_moe.c (control words, read barrier on every load, - * loop live ranges). - */ -#include "omega_blackwell_codegen_router.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn i; memset(&i, 0, sizeof i); - i.op = op; i.dst_vreg = NOREG; i.src1_vreg = NOREG; i.src2_vreg = NOREG; i.src3_vreg = NOREG; i.ureg = NOREG; - return i; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -/* operand with subregister */ -typedef struct { int v; unsigned s; } Op; -static Op R(int v) { Op o = { v, 0 }; return o; } -static Op S(int v, unsigned s) { Op o = { v, s }; return o; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, Op d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; emit(e, i, K_FIXED); } -/* d = a * imm + c */ -static void imadi(Em *e, Op d, Op a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } -static void shrs(Em *e, int d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, uint32_t imm) { shrs(e, d, R(a), imm); } -static void andi(Em *e, Op d, Op a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.imm = imm; emit(e, i, K_FIXED); } -static void xorr(Em *e, Op d, Op a, Op b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void stg(Em *e, BlackwellIROpcode op, int addr64, Op val, int udesc) { BlackwellIRInsn i = I0(op); i.src1_vreg = addr64; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void lds32(Em *e, Op d, int addr, int first) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = addr; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, Op val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fop(Em *e, BlackwellIROpcode op, Op d, Op a, Op b, Op c) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; - i.src2_vreg = b.v; i.src2_subreg = (uint8_t)b.s; i.src3_vreg = c.v; i.src3_subreg = (uint8_t)c.s; emit(e, i, K_FIXED); -} -static void fadd(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FADD, d, a, b, R(NOREG)); } -static void fsub(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FSUB, d, a, b, R(NOREG)); } -static void fmul(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMUL, d, a, b, R(NOREG)); } -static void ffma(Em *e, Op d, Op a, Op b, Op c) { fop(e, BW_IR_FFMA, d, a, b, c); } -static void fmaxx(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MAX, d, a, b, R(NOREG)); } -static void mufu(Em *e, BlackwellIROpcode op, Op d, Op a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d.v; i.dst_subreg = (uint8_t)d.s; i.src1_vreg = a.v; i.src1_subreg = (uint8_t)a.s; emit(e, i, K_VAR); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void exit_k(Em *e) { emit(e, I0(BW_IR_EXIT), K_EXIT); } -static void tail(Em *e) { - exit_k(e); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - -/* A region only some lanes of a warp execute: BSSY ... @P0 BRA join ... BSYNC. P0 true = skip. */ -typedef struct { int bssy, bra; } Region; -static Region region_skip_if_p0(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } -static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } - -static void fminn(Em *e, Op d, Op a, Op b) { fop(e, BW_IR_FMNMX_MIN, d, a, b, R(NOREG)); } -/* d = LUT(a, b, c) with the LOP3 truth table (a = 0xf0, b = 0xcc, c = 0xaa); vreg -1 encodes RZ */ -static void lop3(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut; emit(e, i, K_FIXED); } -/* ne = (a != b) as 0/1: t = a ^ b; ne = (t | -t) >> 31 */ -static void ne_of(Em *e, int ne, Op a, Op b, int t, int t2) { - xorr(e, R(t), a, b); - imadi(e, R(t2), R(t), 0xffffffffu, NOREG); - lop3(e, t, t, t2, NOREG, 0xfcu); - shr(e, ne, t, 31); -} -/* warp reductions: the total lands in lane 0 */ -static void warp_sum(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fadd(e, R(v), R(v), R(t)); } } -static void warp_max(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fmaxx(e, R(v), R(v), R(t)); } } -static void warp_min(Em *e, int v, int t) { for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, v, o); fminn(e, R(v), R(v), R(t)); } } -/* lane 0 of every warp stores v to shared [addr] (the warps write identical words when the value is uniform) */ -static void lane0_sts(Em *e, int lane, int one, int addr, Op v) { - isetp_ge_u32(e, lane, one); - Region r = region_skip_if_p0(e); sts32(e, addr, v); region_end(e, r); -} - -static const uint32_t NEG_BIG = 0xF149F2CAu; /* -1e30f */ -static const uint32_t C_2P23 = 0x4B000000u; /* 8388608.0f; also the OR mask that turns a small integer n into the float 2^23 + n */ -static const uint32_t C_LOG2E = 0x3FB8AA3Bu; /* 1.4426950f */ -static const uint32_t C_INV2048 = 0x3A000000u; /* 1/2048 */ - -int omega_blackwell_codegen_router_prog(const OmegaRouterSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog) return -1; - const uint32_t W = spec->warps, D = spec->depth; - const int MUT = spec->mutant; - if ((W != 8 && W != 16 && W != 32) || (D != 1 && D != 2 && D != 4 && D != 8) || MUT < 0 || MUT > 4) return -1; - const uint32_t E = 64u / W; /* x values per thread: 8, 4 or 2 */ - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - /* ---- arguments and identities ---- */ - int udesc = UV64(e); - int px = V64(e), pgate = V64(e), pnorm = V64(e), pxout = V64(e); - int eps = V(e), oscale = V(e); - int tid = V(e), warp = V(e), lane = V(e), one = V(e), zero = V(e), c2p23 = V(e), cneg = V(e), ts = V(e), t1 = V(e), t2 = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, px, OMEGA_ROUTER_ARG_X); ldc64(e, pgate, OMEGA_ROUTER_ARG_GATE); ldc64(e, pnorm, OMEGA_ROUTER_ARG_NORM); ldc64(e, pxout, OMEGA_ROUTER_ARG_XOUT); - ldc32(e, eps, OMEGA_ROUTER_ARG_EPS); ldc32(e, oscale, OMEGA_ROUTER_ARG_OUT_SCALE); - s2r(e, tid, BW_SR_TID_X); - movi(e, one, 1); movrz(e, R(zero)); movi(e, c2p23, C_2P23); movi(e, cneg, NEG_BIG); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - - /* ---- phase 1: RMSNorm ---- */ - int toff = V(e), xa = V64(e), wa = V64(e), sq = V(e), rs = V(e), a0 = V(e); - int xq[2], wq[2]; - Op xe[8], we[8]; - imadi(e, R(toff), R(tid), E * 4u, NOREG); - imadw(e, xa, toff, 1u, px); imadw(e, wa, toff, 1u, pnorm); - if (E == 2) { - xq[0] = V64(e); wq[0] = V64(e); - ldg_wide(e, BW_IR_LDG_E_64, xq[0], xa, 0, udesc, 1); ldg_wide(e, BW_IR_LDG_E_64, wq[0], wa, 0, udesc, 0); - for (unsigned i = 0; i < 2; i++) { xe[i] = S(xq[0], i); we[i] = S(wq[0], i); } - } else { - for (unsigned q = 0; q < E / 4; q++) { xq[q] = V128(e); wq[q] = V128(e); } - for (unsigned q = 0; q < E / 4; q++) ldg_wide(e, BW_IR_LDG_E_128, xq[q], xa, q * 16u, udesc, q == 0); - for (unsigned q = 0; q < E / 4; q++) ldg_wide(e, BW_IR_LDG_E_128, wq[q], wa, q * 16u, udesc, 0); - for (unsigned i = 0; i < E; i++) { xe[i] = S(xq[i / 4], i % 4); we[i] = S(wq[i / 4], i % 4); } - } - if (e->err) return -1; - fmul(e, R(sq), xe[0], xe[0]); - for (unsigned i = 1; i < E; i++) ffma(e, R(sq), xe[i], xe[i], R(sq)); - warp_sum(e, sq, ts); - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_ROUTER_SM_RED, a0); - lane0_sts(e, lane, one, a0, R(sq)); - bar_sync(e); - /* every thread sums the W partials (quads of 4) */ - { - int rq0 = V128(e), rq1 = V128(e); - movi(e, a0, OMEGA_ROUTER_SM_RED); - for (uint32_t q = 0; q < W / 4; q += 2) { - lds128(e, rq0, a0, q * 16u, 1); - if (q + 1 < W / 4) lds128(e, rq1, a0, (q + 1) * 16u, 0); - for (unsigned i = 0; i < 4; i++) { if (q == 0 && i == 0) mov(e, R(sq), S(rq0, 0)); else fadd(e, R(sq), R(sq), S(rq0, i)); } - if (q + 1 < W / 4) for (unsigned i = 0; i < 4; i++) fadd(e, R(sq), R(sq), S(rq1, i)); - } - } - movi(e, ts, C_INV2048); - ffma(e, R(rs), R(sq), R(ts), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); - /* xn = x * r * w -> shared [toff + 4i]; x' = xn * out_scale -> xout */ - { - int xo = V64(e); - imadw(e, xo, toff, 1u, pxout); - for (unsigned i = 0; i < E; i++) { - fmul(e, xe[i], xe[i], R(rs)); - if (MUT != 1) fmul(e, xe[i], xe[i], we[i]); - imadi(e, R(a0), R(one), OMEGA_ROUTER_SM_XN + i * 4u, toff); - sts32(e, a0, xe[i]); - fmul(e, R(ts), xe[i], R(oscale)); - if (i) imadw(e, xo, one, 4u, xo); - stg(e, BW_IR_STG_E, xo, R(ts), udesc); - } - } - bar_sync(e); - - /* ---- phase 2: logits, warp w -> experts w, w + W, ... ---- */ - int c128 = V(e), ex = V(e), lane16 = V(e), lane32 = V(e), gl = V64(e), rowa = V64(e), la = V(e); - int acc[4], lo = V(e), hi = V(e), xs0 = V128(e), xs1 = V128(e), ld[8]; - for (unsigned i = 0; i < 4; i++) acc[i] = V(e); - for (uint32_t d = 0; d < D; d++) ld[d] = V128(e); - if (e->err) return -1; - movi(e, c128, OMEGA_ROUTER_EXPERTS); - mov(e, R(ex), R(warp)); - imadi(e, R(lane16), R(lane), 16u, NOREG); - imadi(e, R(lane32), R(lane), 32u, NOREG); - imadw(e, gl, lane16, 1u, pgate); - const int L_e = here(e); - loop_begin(e); - isetp_ge_u32(e, ex, c128); - const int bra_edone = bra_if_p0_fwd(e); - imadw(e, rowa, ex, OMEGA_ROUTER_ROW_BYTES, gl); - for (unsigned i = 0; i < 4; i++) movrz(e, R(acc[i])); - for (uint32_t b = 0; b < OMEGA_ROUTER_STEPS / D; b++) { - for (uint32_t d = 0; d < D; d++) ldg_wide(e, BW_IR_LDG_E_128, ld[d], rowa, (b * D + d) * 512u, udesc, d == 0); - for (uint32_t d = 0; d < D; d++) { - const uint32_t s = b * D + d; - lds128(e, xs0, lane32, OMEGA_ROUTER_SM_XN + s * 1024u, 1); - lds128(e, xs1, lane32, OMEGA_ROUTER_SM_XN + s * 1024u + 16u, 0); - for (unsigned w = 0; w < 4; w++) { - imadi(e, R(lo), S(ld[d], w), 65536u, NOREG); - andi(e, R(hi), S(ld[d], w), 0xffff0000u); - Op x0 = w < 2 ? S(xs0, 2 * w) : S(xs1, 2 * (w - 2)), x1 = w < 2 ? S(xs0, 2 * w + 1) : S(xs1, 2 * (w - 2) + 1); - ffma(e, R(acc[w]), R(lo), x0, R(acc[w])); - ffma(e, R(acc[w]), R(hi), x1, R(acc[w])); - } - } - } - fadd(e, R(acc[0]), R(acc[0]), R(acc[1])); fadd(e, R(acc[2]), R(acc[2]), R(acc[3])); fadd(e, R(acc[0]), R(acc[0]), R(acc[2])); - warp_sum(e, acc[0], ts); - imadi(e, R(la), R(ex), 4u, NOREG); imadi(e, R(la), R(one), OMEGA_ROUTER_SM_LOGIT, la); - lane0_sts(e, lane, one, la, R(acc[0])); - imadi(e, R(ex), R(one), W, ex); - bra(e, L_e); - loop_end(e); - patch_bra(e, bra_edone, here(e)); - bar_sync(e); - - /* ---- phase 3: top-8 (every warp, uniform barriers) ---- */ - int vq = V128(e), lane4 = V(e), ej[4], fj[4], lm = V(e), mr = V(e), lc = V(e), cj = V(e), ne = V(e), ci = V(e), cm = V(e); - int bc = V(e), bc4 = V(e), r = V(e), c8 = V(e), sa = V(e); - for (unsigned j = 0; j < 4; j++) { ej[j] = V(e); fj[j] = V(e); } - if (e->err) return -1; - lds128(e, vq, lane16, OMEGA_ROUTER_SM_LOGIT, 1); - imadi(e, R(lane4), R(lane), 4u, NOREG); - for (unsigned j = 0; j < 4; j++) { - imadi(e, R(ej[j]), R(one), j, lane4); - lop3(e, fj[j], ej[j], c2p23, NOREG, 0xfcu); /* bits 0x4B000000 | ej = the float 2^23 + ej: monotonic in ej, never zero */ - } - movi(e, bc, OMEGA_ROUTER_SM_BC); movi(e, bc4, OMEGA_ROUTER_SM_BC + 4u); - movrz(e, R(r)); movi(e, c8, OMEGA_ROUTER_TOPK); - const int L_r = here(e); - loop_begin(e); - isetp_ge_u32(e, r, c8); - const int bra_rdone = bra_if_p0_fwd(e); - /* the round's max */ - fmaxx(e, R(lm), S(vq, 0), S(vq, 1)); fmaxx(e, R(lm), R(lm), S(vq, 2)); fmaxx(e, R(lm), R(lm), S(vq, 3)); - warp_max(e, lm, ts); - lane0_sts(e, lane, one, bc, R(lm)); - bar_sync(e); - lds32(e, R(mr), bc, 1); - /* lowest index holding it: candidate = 2^23 + ej when equal, else lifted by 0x30000000 (about 6e35, still positive) */ - for (unsigned j = 0; j < 4; j++) { - ne_of(e, ne, S(vq, j), R(mr), t1, t2); - imadi(e, R(cj), R(ne), 0x30000000u, fj[j]); - if (j == 0) mov(e, R(lc), R(cj)); else fminn(e, R(lc), R(lc), R(cj)); - } - warp_min(e, lc, ts); - imadi(e, R(sa), R(r), 4u, NOREG); imadi(e, R(sa), R(one), OMEGA_ROUTER_SM_SELV, sa); - isetp_ge_u32(e, lane, one); - { Region rg = region_skip_if_p0(e); sts32(e, bc4, R(lc)); sts32(e, sa, R(mr)); region_end(e, rg); } - bar_sync(e); - lds32(e, R(ci), bc4, 1); - andi(e, R(ci), R(ci), 0x7fu); /* the chosen expert id: the low bits of 2^23 + ej */ - imadi(e, R(sa), R(r), 4u, NOREG); imadi(e, R(sa), R(one), OMEGA_ROUTER_SM_SEL, sa); - lane0_sts(e, lane, one, sa, R(ci)); - if (MUT == 2) xorr(e, R(cm), R(ci), R(one)); else mov(e, R(cm), R(ci)); - /* mask the winner: v = min(v, ne ? +1e30 : -1e30) */ - for (unsigned j = 0; j < 4; j++) { - ne_of(e, ne, R(ej[j]), R(cm), t1, t2); - imadi(e, R(cj), R(ne), 0x80000000u, cneg); - fminn(e, S(vq, j), S(vq, j), R(cj)); - } - imadi(e, R(r), R(one), 1u, r); - bra(e, L_r); - loop_end(e); - patch_bra(e, bra_rdone, here(e)); - bar_sync(e); - /* full 128-way softmax sum (den when norm_topk_prob is off): original logits from shared, l_0 = selv[0] */ - int full = V(e), m0 = V(e), cl2e = V(e); - if (e->err) return -1; - movi(e, cl2e, C_LOG2E); - lds128(e, vq, lane16, OMEGA_ROUTER_SM_LOGIT, 1); - movi(e, sa, OMEGA_ROUTER_SM_SELV); - lds32(e, R(m0), sa, 0); - for (unsigned j = 0; j < 4; j++) { - fsub(e, R(ts), S(vq, j), R(m0)); fmul(e, R(ts), R(ts), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(ts), R(ts)); - if (j == 0) mov(e, R(full), R(ts)); else fadd(e, R(full), R(full), R(ts)); - } - warp_sum(e, full, ts); - lane0_sts(e, lane, one, bc, R(full)); - bar_sync(e); - lds32(e, R(full), bc, 1); - - /* ---- epilogue: warp 0 only ---- */ - isetp_ge_u32(e, warp, one); - const int bra_tail = bra_if_p0_fwd(e); - int pids = V64(e), pwts = V64(e), pdgu = V64(e), pddn = V64(e), ptgu = V64(e), ptdn = V64(e), ntk = V(e); - int sv0 = V128(e), sv1 = V128(e), er[8], s8 = V(e), den = V(e), wa64 = V64(e); - for (unsigned i = 0; i < 8; i++) er[i] = V(e); - if (e->err) return -1; - ldc64(e, pids, OMEGA_ROUTER_ARG_IDS); ldc64(e, pwts, OMEGA_ROUTER_ARG_WTS); - ldc64(e, pdgu, OMEGA_ROUTER_ARG_DIR_GU); ldc64(e, pddn, OMEGA_ROUTER_ARG_DIR_DN); - ldc64(e, ptgu, OMEGA_ROUTER_ARG_TAB_GU); ldc64(e, ptdn, OMEGA_ROUTER_ARG_TAB_DN); - ldc32(e, ntk, OMEGA_ROUTER_ARG_NORM_TOPK); - movi(e, sa, OMEGA_ROUTER_SM_SELV); - lds128(e, sv0, sa, 0, 1); lds128(e, sv1, sa, 16, 0); - for (unsigned i = 0; i < 8; i++) { - Op v = i < 4 ? S(sv0, i) : S(sv1, i - 4); - fsub(e, R(er[i]), v, S(sv0, 0)); fmul(e, R(er[i]), R(er[i]), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(er[i]), R(er[i])); - } - fadd(e, R(s8), R(er[0]), R(er[1])); - for (unsigned i = 2; i < 8; i++) fadd(e, R(s8), R(s8), R(er[i])); - /* den = (s8 - full) * float(ntk) + full */ - lop3(e, t1, ntk, c2p23, NOREG, 0xfcu); fsub(e, R(t1), R(t1), R(c2p23)); - fsub(e, R(t2), R(s8), R(full)); - ffma(e, R(den), R(t2), R(t1), R(full)); - if (MUT == 4) movi(e, den, 0x3f800000u); else mufu(e, BW_IR_MUFU_RCP, R(den), R(den)); - for (unsigned i = 0; i < 8; i++) fmul(e, R(er[i]), R(er[i]), R(den)); - /* lane 0: the 8 weights */ - isetp_ge_u32(e, lane, one); - { - Region rg = region_skip_if_p0(e); - for (unsigned i = 0; i < 8; i++) { imadw(e, wa64, one, i * 4u, pwts); stg(e, BW_IR_STG_E, wa64, R(er[i]), udesc); } - region_end(e, rg); - } - /* lanes 0..7: id_g and the two directory entries of id_g into the two group tables */ - isetp_ge_u32(e, lane, c8); - { - Region rg = region_skip_if_p0(e); - int si = V(e), da = V64(e), q0 = V64(e), q1 = V64(e), ta = V64(e), tb = V64(e); - if (e->err) return -1; - imadi(e, R(sa), R(lane), 4u, NOREG); imadi(e, R(sa), R(one), OMEGA_ROUTER_SM_SEL, sa); - lds32(e, R(si), sa, 1); - imadw(e, da, lane, 4u, pids); - stg(e, BW_IR_STG_E, da, R(si), udesc); - if (MUT == 3) xorr(e, R(si), R(si), R(one)); - for (unsigned which = 0; which < 2; which++) { - imadw(e, da, si, 16u, which == 0 ? pdgu : pddn); - ldg_wide(e, BW_IR_LDG_E_64, q0, da, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, q1, da, 8, udesc, 0); - imadw(e, ta, lane, 16u, which == 0 ? ptgu : ptdn); - stg(e, BW_IR_STG_E, ta, S(q0, 0), udesc); - imadw(e, tb, one, 4u, ta); stg(e, BW_IR_STG_E, tb, S(q0, 1), udesc); - imadw(e, tb, one, 8u, ta); stg(e, BW_IR_STG_E, tb, S(q1, 0), udesc); - imadw(e, tb, one, 12u, ta); stg(e, BW_IR_STG_E, tb, S(q1, 1), udesc); - } - region_end(e, rg); - } - patch_bra(e, bra_tail, here(e)); - tail(e); - (void)zero; - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_router_prog_stats(const OmegaRouterSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_router_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} diff --git a/src/omega_blackwell_codegen_router.h b/src/omega_blackwell_codegen_router.h deleted file mode 100644 index 2b2b62f8d..000000000 --- a/src/omega_blackwell_codegen_router.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_ROUTER_H -#define OMEGA_BLACKWELL_CODEGEN_ROUTER_H -/* - * omega_blackwell_codegen_router: the MoE router of Qwen3-30B-A3B in ONE launch per layer (OWN-30B cut 8 item 2, - * 2026-10-13). RMSNorm of the residual row, router logits (128 experts x 2048, bf16 weights), softmax, top-8, - * renormalisation per config.json `norm_topk_prob` (true for this checkpoint: the 8 weights are the softmax of - * the 8 selected logits; with the flag off they are the full 128-way softmax probabilities of the selected - * experts), and the outputs the next launch needs without a host round trip: - * - x'[2048] f32 = RMSNorm(x) * out_scale (2^64 makes it the x' row of the grouped FP8 gate+up GEMV); - * - the grouped GEMV's group tables: entry g = directory[id_g] for the gate+up and the down tensors, each - * directory a device table of 128 x {w_va u64, s_va u64} built once per layer from the resident FP8 tensors; - * - ids[8] u32 and weights[8] f32 (descending by logit) for the host combine. - * - * Grid 1 x 1, `warps` warps (8, 16 or 32). Per CTA: - * phase 1 thread t: E = 64 / warps consecutive x values and norm weights; sum of squares reduced per warp - * (SHFL.DOWN) and across warps through shared memory; r = RSQ(ss / 2048 + eps); xn = x * r * w staged - * in shared memory (f32 [2048]) and stored * out_scale to x'. - * phase 2 warp w computes the logits of experts w, w + warps, ...: lane L streams bytes [L*16, +16) of each - * 256-column step of the expert's bf16 row (8 steps, `depth` of them in flight), widens the bf16 pairs - * by shift / mask, FFMAs against xn from shared memory (LDS.128), warp-reduces, lane 0 stores the - * logit to shared memory. - * phase 3 every warp redundantly (uniform barriers): lane L holds logits 4L..4L+3; 8 rounds of argmax: warp max - * by FMNMX.MAX, then the lowest index among the lanes holding that value (an integer "not equal" flag - * lifts the index candidates of the others above every real index, FMNMX.MIN picks the winner), the - * winner's logit is masked to -1e30. Selected logits and ids go to shared memory. Then the full - * 128-way softmax sum (for norm_topk_prob = false) and the weights e_r = EX2((l_r - l_0) * log2 e) / - * den, den = sum of the 8 (flag on) or of all 128 (flag off). - * epilogue warp 0: lane 0 stores the 8 weights; lanes 0..7 store id_g and copy the two directory entries of - * id_g into the two group tables (4 x STG.E each). - * - * Only ops the attention and FP8 kernels already run on the chip are used (no FSETP / FSEL; the simulator does - * not model them either). The host simulator (tests/bw_warp_sim_k.h) runs the 8-warp kernel. - */ -#include "omega_blackwell_codegen.h" -#include - -#define OMEGA_ROUTER_HIDDEN 2048u -#define OMEGA_ROUTER_EXPERTS 128u -#define OMEGA_ROUTER_TOPK 8u -#define OMEGA_ROUTER_STEPS 8u /* 256 bf16 columns per step */ -#define OMEGA_ROUTER_ROW_BYTES (OMEGA_ROUTER_HIDDEN * 2u) -#define OMEGA_ROUTER_DIR_BYTES (OMEGA_ROUTER_EXPERTS * 16u) -#define OMEGA_ROUTER_TAB_BYTES (OMEGA_ROUTER_TOPK * 16u) - -/* constant bank: addresses at 0x380 + 8n, then the scalars */ -#define OMEGA_ROUTER_ARG_X 0x380u /* f32 [2048] residual row */ -#define OMEGA_ROUTER_ARG_GATE 0x388u /* bf16 [128][2048] router weight */ -#define OMEGA_ROUTER_ARG_NORM 0x390u /* f32 [2048] post_attention_layernorm weight */ -#define OMEGA_ROUTER_ARG_XOUT 0x398u /* f32 [2048] x' = RMSNorm(x) * out_scale */ -#define OMEGA_ROUTER_ARG_IDS 0x3a0u /* u32 [8] */ -#define OMEGA_ROUTER_ARG_WTS 0x3a8u /* f32 [8] */ -#define OMEGA_ROUTER_ARG_DIR_GU 0x3b0u /* u64 [128][2] gate+up directory {w_va, s_va} */ -#define OMEGA_ROUTER_ARG_DIR_DN 0x3b8u /* u64 [128][2] down directory */ -#define OMEGA_ROUTER_ARG_TAB_GU 0x3c0u /* u64 [8][2] group table written for the gate+up launch */ -#define OMEGA_ROUTER_ARG_TAB_DN 0x3c8u /* u64 [8][2] group table written for the down launch */ -#define OMEGA_ROUTER_ARG_EPS 0x3d0u /* f32 rms eps */ -#define OMEGA_ROUTER_ARG_OUT_SCALE 0x3d4u /* f32 */ -#define OMEGA_ROUTER_ARG_NORM_TOPK 0x3d8u /* u32 0 or 1 (config.json norm_topk_prob) */ -#define OMEGA_ROUTER_ARGS_WORDS 23u - -/* shared memory map (bytes) */ -#define OMEGA_ROUTER_SM_XN 0u /* xn[2048] f32: 8192 */ -#define OMEGA_ROUTER_SM_LOGIT 8192u /* logits[128] f32: 512 */ -#define OMEGA_ROUTER_SM_RED 8704u /* per-warp partial sums [32]: 128 */ -#define OMEGA_ROUTER_SM_BC 8832u /* broadcast words: 16 */ -#define OMEGA_ROUTER_SM_SEL 8848u /* selected ids u32 [8]: 32 */ -#define OMEGA_ROUTER_SM_SELV 8880u /* selected logits f32 [8]: 32 */ -#define OMEGA_ROUTER_SHARED_BYTES 8912u - -typedef struct { - uint32_t warps; /* 8, 16 or 32 */ - uint32_t depth; /* weight steps in flight per warp: 1, 2, 4 or 8 */ - int mutant; /* TEST ONLY. 0 none; 1 RMSNorm without the weight; 2 the mask after each argmax round removes - * expert id ^ 1 (the winner can be picked again); 3 the directory entries copied are those of - * id ^ 1; 4 the weights are not normalised (den = 1). */ -} OmegaRouterSpec; - -/* Builds the register-allocated IR program into *prog. 0 ok, -1 refused. */ -int omega_blackwell_codegen_router_prog(const OmegaRouterSpec *spec, BlackwellIRProgram *prog); -/* Instruction and peak-register counts (host, no device). */ -int omega_router_prog_stats(const OmegaRouterSpec *spec, uint32_t *insns, uint32_t *gprs); - -#endif diff --git a/src/omega_blackwell_codegen_tc.c b/src/omega_blackwell_codegen_tc.c deleted file mode 100644 index 1b7f55dfd..000000000 --- a/src/omega_blackwell_codegen_tc.c +++ /dev/null @@ -1,341 +0,0 @@ -/* omega_blackwell_codegen_tc.c: tensor-core kernels for the OWN-30B one-pass prefill (T3). See the header. - * The emitter helpers below are copied from omega_blackwell_codegen_gemm.c (same chip-learned scheduling rules: every load - * sets the read barrier SB1 and the next load waits on it; prefetch loads hold scoreboards 3/4 until consumed). - * HMMA scheduling is taken from nvcc 13.0.88 -arch=sm_121 output (oracle sealed in - * ~/workspace/investigations/2026-10-13-t3-mma-oracle/oracle.{cu,sass}): - * independent HMMA.16816.F32.BF16 back to back: control 0x000ff000 / 0x020ff000 (stall 8, no barriers); - * a consumer of an HMMA result (dependent HMMA, store): HMMA stall 15 then NOP stall 13..14 (about 29 cycles), as - * omega_blackwell_verify_codegen_fixtures_fragmm records. */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_bw_em.h" -#include "omega_gpu_fmt.h" - -int omega_blackwell_codegen_tc_probe_prog(int mutant, BlackwellIRProgram *prog) { - if (!prog || mutant < 0 || mutant > 1) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - int udesc = UV64(e), pin = V64(e), pout = V64(e), tid = V(e), cx = V(e), pa = V64(e), po = V64(e); - int a = V128(e), b = V64(e), c = V128(e), d = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, 0x380); ldc64(e, pout, 0x388); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - int pcase = V64(e), pb = V64(e); if (e->err) return -1; - imadw(e, pcase, cx, OMEGA_TC_PROBE_IN_BYTES, pin); imadw(e, pa, tid, 16, pcase); imadw(e, pb, tid, 8, pcase); - imadw(e, po, cx, OMEGA_TC_PROBE_OUT_BYTES, pout); imadw(e, po, tid, 16, po); - ldg_wide(e, BW_IR_LDG_E_128, a, pa, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, c, pa, 768, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, b, pb, 512, udesc, 0); - /* wait for every load, then one HMMA, then 29 cycles before the stores read d */ - hmma(e, d, a, b, mutant == 1 ? NOREG : c, 15); - nop(e, 14); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = po; i.src2_vreg = d; i.src2_subreg = (uint8_t)q; i.imm = 4u * q; i.ureg = udesc; emit(e, i, K_STORE); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ======================= grouped FP8 GEMM on tensor cores (see the header) ======================= */ - -int omega_tcgemm_spec_ok(const OmegaTcGemmSpec *s) { - if (!s) return 0; - if (s->k < 128u || s->k > 16384u || s->k % 128u) return 0; - if (s->rt != 1 && s->rt != 2 && s->rt != 4) return 0; - if (s->ct != 1 && s->ct != 2 && s->ct != 4) return 0; - if (s->rt * s->ct < 4u) return 0; /* >= 4 independent HMMAs between dependent ones (8 cycles each, nvcc's 29-cycle rule) */ - if (s->warps != 1 && s->warps != 2 && s->warps != 4 && s->warps != 8) return 0; - if ((16u * s->rt * 8u) % (32u * s->warps)) return 0; /* whole LDG.128 staging slots per thread */ - if (s->mutant < 0 || s->mutant > 4 || (s->mutant == 3 && s->rt < 2)) return 0; - return 1; -} -uint32_t omega_tcgemm_shared_bytes(const OmegaTcGemmSpec *s) { return omega_tcgemm_spec_ok(s) ? 2u * 16u * s->rt * 128u : 0u; } -uint32_t omega_tcgemm_span(const OmegaTcGemmSpec *s) { return omega_tcgemm_spec_ok(s) ? s->warps * 8u * s->ct : 0u; } - -static uint16_t bf16_rne(float f) { - uint32_t u; memcpy(&u, &f, 4); - if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x40u); /* NaN stays NaN */ - u += 0x7fffu + ((u >> 16) & 1u); - return (uint16_t)(u >> 16); -} -void omega_tcgemm_permute_x(const float *x, uint32_t k, uint16_t *out) { - static const unsigned ord[4] = { 0, 2, 1, 3 }; - for (uint32_t q = 0; q + 4 <= k; q += 4) - for (unsigned i = 0; i < 4; i++) out[q + i] = bf16_rne(x[q + ord[i]] * 18446744073709551616.0f); -} -uint16_t omega_tcgemm_w_bf16(uint8_t c) { return (uint16_t)(((c & 0x7Fu) << 4) | ((c & 0x80u) << 8)); } - -/* one e4m3 word (bytes b0..b3) -> B register pair: lo = (bf(b0), bf(b2)), hi = (bf(b1), bf(b3)) */ -static void decode_word(Em *e, int bpair, int wq, unsigned word, int m, int s, int t) { - andi(e, m, wq, word, 0x007F007Fu); andi(e, s, wq, word, 0x00800080u); - imadi(e, t, m, 0, 16u, NOREG); - { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = bpair; i.dst_subreg = 0; i.src1_vreg = s; i.imm = 256u; i.src3_vreg = t; emit(e, i, K_FIXED); } - andi(e, m, wq, word, 0x7F007F00u); andi(e, s, wq, word, 0x80008000u); - shr(e, t, m, 0, 4); - { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = bpair; i.dst_subreg = 1; i.src1_vreg = t; i.src2_vreg = s; emit(e, i, K_FIXED); } -} - -int omega_blackwell_codegen_tcgemm_prog(const OmegaTcGemmSpec *spec, BlackwellIRProgram *prog) { - if (!omega_tcgemm_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, RT = spec->rt, CT = spec->ct, W = spec->warps, T = 32u * W; - const uint32_t AQN = RT * CT >= 8u ? 1u : 2u; /* A fragments in flight: one for the 8-tile shapes keeps peak <= 126 */ - const uint32_t BM = 16u * RT, KB = K / 128u, SPAN = W * 8u * CT, NJ = BM * 8u / T, BUF = BM * 128u; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - (void)lop3; - - /* ---- prologue: arguments, ids, tile entry ---- */ - int udesc = UV64(e), ptab = V64(e), pidx = V64(e), px = V64(e), py = V64(e), nreg = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), g = V(e), tq = V(e), one = V(e), tent = V64(e); - int wbase = V64(e), sbase = V64(e), rc = V64(e), row0 = V(e), cnt = V(e); - int n0w = V(e), tmp = V(e), tmp2 = V(e), pw = V64(e), ps = V64(e), la = V(e), ysn = V(e), pyr = V64(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ptab, OMEGA_TCGEMM_ARG_TILES); ldc64(e, pidx, OMEGA_TCGEMM_ARG_ROWIDX); ldc64(e, px, OMEGA_TCGEMM_ARG_X); ldc64(e, py, OMEGA_TCGEMM_ARG_Y); - ldc32(e, nreg, OMEGA_TCGEMM_ARG_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); andi(e, lane, tid, 0, 31); shr(e, g, lane, 0, 2); andi(e, tq, lane, 0, 3); - imadw(e, tent, cy, OMEGA_TCGEMM_TILE_BYTES, ptab); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, sbase, tent, 8, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, rc, tent, 16, udesc, 0); - imadi(e, row0, rc, 0, 1, NOREG); imadi(e, cnt, rc, 1, 1, NOREG); - /* this warp's first weight row; weight pointer row (n0w + g), byte 16 t; scale row block n0w / 128 */ - imadi(e, n0w, cx, 0, SPAN, NOREG); imadi(e, tmp, warp, 0, 8u * CT, NOREG); iadd(e, n0w, n0w, tmp); - iadd(e, tmp, n0w, g); imadw(e, pw, tmp, K, wbase); imadi(e, tmp2, tq, 0, 16u, NOREG); imadw(e, pw, tmp2, 1, pw); - shr(e, tmp, n0w, 0, 7); imadw(e, ps, tmp, KB * 4u, sbase); - imadi(e, la, lane, 0, 16u, NOREG); - imadi(e, ysn, nreg, 0, 4u, NOREG); - /* output pointer: y + ((row0 + g) * n + n0w + 2t) * 4 */ - iadd(e, tmp, row0, g); imadr(e, tmp, tmp, nreg, n0w); imadi(e, tmp2, tq, 0, 2u, NOREG); iadd(e, tmp, tmp, tmp2); imadw(e, pyr, tmp, 4u, py); - - /* ---- staging assignment: slot = tid + jj * T -> row r = slot / 8, words w0 = 4 * (tid % 8) of the 64-element chunk ---- */ - int gx[8], sa[8]; - for (uint32_t jj = 0; jj < NJ; jj++) { gx[jj] = V64(e); sa[jj] = V(e); } - int r = V(e), sidx = V64(e), srow = V(e), w0b = V(e), ts = V(e), s0 = V(e); - if (e->err) return -1; - andi(e, tmp, tid, 0, 7); - imadi(e, w0b, tmp, 0, 16u, NOREG); /* byte offset of word w0 in the row chunk: 4 words * 4 bytes */ - shr(e, ts, tmp, 0, 1); /* t of these words = w0 / 8 */ - andi(e, s0, tid, 0, 1); imadi(e, s0, s0, 0, 2u, NOREG); /* s0 = (w0 % 8) / 2 */ - for (uint32_t jj = 0; jj < NJ; jj++) { - shr(e, r, tid, 0, 3); imadi(e, r, one, 0, jj * T / 8u, r); - iadd(e, tmp, row0, r); imadw(e, sidx, tmp, 4u, pidx); - ldg32(e, srow, sidx, udesc, 1); - imadw(e, gx[jj], srow, K * 2u, px); imadw(e, gx[jj], w0b, 1, gx[jj]); - /* shared byte address ((i*4 + s0)*32 + g'*4 + t)*16 + h*4 with i = r/16, g' = r%8, h = (r/8)%2 */ - shr(e, tmp, r, 0, 4); imadi(e, tmp, tmp, 0, 4u, s0); imadi(e, tmp, tmp, 0, 32u, ts); - andi(e, tmp2, r, 0, 7); imadi(e, tmp2, tmp2, 0, 4u, tmp); imadi(e, sa[jj], tmp2, 0, 16u, NOREG); - shr(e, tmp2, r, 0, 3); andi(e, tmp2, tmp2, 0, 1); imadi(e, sa[jj], tmp2, 0, 4u, sa[jj]); - } - - /* ---- loop-wide registers ---- */ - int acc[16], tm[16], wa[4], wb[4], bp[4], aq[2], stg[8], sc = V(e), scur = V(e), cntk = V(e), dm = V(e), ds = V(e), dt = V(e), sv = V(e), onef = V(e); - for (uint32_t x = 0; x < RT * CT; x++) { acc[x] = V128(e); tm[x] = V128(e); } - for (uint32_t j = 0; j < CT; j++) { wa[j] = V128(e); wb[j] = V128(e); bp[j] = V64(e); } - for (uint32_t q = 0; q < AQN; q++) aq[q] = V128(e); - for (uint32_t jj = 0; jj < NJ; jj++) stg[jj] = V128(e); - if (e->err) return -1; - - /* issue the loads of one chunk: activations into stg (row chunk at gx + xoff), weights into wset (pw + woff) */ - #define ISSUE(wset, sb, xoff, woff, with_scale) do { \ - for (uint32_t jj = 0; jj < NJ; jj++) ldw_pf(e, BW_IR_LDG_E_128, stg[jj], gx[jj], (xoff), udesc, (sb)); \ - for (uint32_t j = 0; j < CT; j++) ldw_pf(e, BW_IR_LDG_E_128, (wset)[j], pw, (woff) + j * 8u * K, udesc, (sb)); \ - if (with_scale) ldw_pf(e, BW_IR_LDG_E, sc, ps, 0, udesc, (sb)); } while (0) - /* stage stg into buffer `buf` (byte offset): words w0, w0+1 -> s0 pair 0/1, w0+2, w0+3 -> s0+1 */ - #define STAGE(buf) do { for (uint32_t jj = 0; jj < NJ; jj++) { static const uint32_t off[4] = { 0, 8, 512, 520 }; \ - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STS32); imadi(e, tmp, one, 0, (buf) + off[q], sa[jj]); \ - st.src1_vreg = tmp; st.src2_vreg = stg[jj]; st.src2_subreg = (uint8_t)q; emit(e, st, K_STORE); } } bar_sync(e); } while (0) - - /* compute one 64-element chunk from shared buffer `buf` with weight set wset; first: the first chunk of a block */ - #define COMPUTE(buf, wset, first, odd) do { \ - for (uint32_t s = 0; s < 4; s++) { \ - if (spec->mutant == 4 && (odd) && s == 3) break; \ - for (uint32_t j = 0; j < CT; j++) decode_word(e, bp[j], (wset)[j], s, dm, ds, dt); \ - for (uint32_t i0 = 0; i0 < RT; i0 += AQN) { \ - const uint32_t nb = RT - i0 < AQN ? RT - i0 : AQN; \ - for (uint32_t q = 0; q < nb; q++) { uint32_t i = i0 + q, ii = spec->mutant == 3 ? (i ^ 1u) : i; \ - lds128(e, aq[q], la, (buf) + (ii * 4u + s) * 512u, q == 0); } \ - for (uint32_t q = 0; q < nb; q++) for (uint32_t j = 0; j < CT; j++) { uint32_t x = (i0 + q) * CT + j; \ - hmma(e, tm[x], aq[q], bp[j], ((first) && s == 0) ? NOREG : tm[x], 8); } \ - } \ - } } while (0) - - /* chunk 0 of block 0: activations to buffer 0, weights to set A, scale of block 0 */ - for (uint32_t x = 0; x < RT * CT; x++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = acc[x]; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - ISSUE(wa, 3u, 0u, 0u, 1); - consume(e, 3); - STAGE(0u); - movi(e, cntk, KB); - if (spec->mutant == 1) movi(e, onef, 0x3f800000u); - - /* ---- K loop: one 128-wide block (two chunks) per iteration ---- */ - const int L_k = here(e); - loop_begin(e); - ISSUE(wb, 4u, 128u, 64u, 0); /* chunk 2kb+1 */ - consume(e, 3); - imadi(e, scur, sc, 0, 1u, NOREG); /* keep this block's scale: the next block's load reuses sc */ - COMPUTE(0u, wa, 1, 0); - consume(e, 4); - STAGE(BUF); - { /* chunk 2kb+2 (the next block's first chunk); the last iteration re-reads its own chunk (harmless, drained below) */ - int nf = V(e), inc = V(e); if (e->err) return -1; - imadi(e, nf, one, 0, 0xfffffffeu, cntk); shr(e, nf, nf, 0, 31); imadi(e, nf, nf, 0, 0xffffffffu, one); - for (uint32_t jj = 0; jj < NJ; jj++) imadw(e, gx[jj], nf, 256u, gx[jj]); - imadw(e, pw, nf, 128u, pw); - imadi(e, inc, nf, 0, spec->mutant == 2 ? 0u : 4u, NOREG); imadw(e, ps, inc, 1, ps); - } - ISSUE(wa, 3u, 0u, 0u, 1); - COMPUTE(BUF, wb, 0, 1); - nop(e, 15); nop(e, 14); /* the last HMMAs' results settle before the FFMAs read them */ - for (uint32_t x = 0; x < RT * CT; x++) for (unsigned q = 0; q < 4; q++) { - BlackwellIRInsn f = I0(BW_IR_FFMA); f.dst_vreg = acc[x]; f.dst_subreg = (uint8_t)q; f.src1_vreg = tm[x]; f.src1_subreg = (uint8_t)q; - f.src2_vreg = spec->mutant == 1 ? onef : scur; f.src3_vreg = acc[x]; f.src3_subreg = (uint8_t)q; emit(e, f, K_FIXED); - } - consume(e, 3); - STAGE(0u); - imadi(e, cntk, one, 0, 0xffffffffu, cntk); - isetp_ge_u32(e, cntk, one); - bra_if_p0(e, L_k); - loop_end(e); - #undef ISSUE - #undef STAGE - #undef COMPUTE - - /* ---- store: row tile i, half h (rows 16i + 8h + g) when < cnt; columns n0w + 8j + 2t (+1) ---- */ - int rr = V(e), pya = V64(e); - if (e->err) return -1; - for (uint32_t i = 0; i < RT; i++) for (uint32_t h = 0; h < 2; h++) { - imadi(e, rr, one, 0, 16u * i + 8u * h, g); - imadi(e, sv, rr, 0, 1u, NOREG); - isetp_ge_u32(e, sv, cnt); - const int at_bssy = bssy_fwd(e); - const int bra_skip = bra_if_p0_fwd(e); - imadi(e, tmp, ysn, 0, 16u * i + 8u * h, NOREG); imadw(e, pya, tmp, 1, pyr); - for (uint32_t j = 0; j < CT; j++) for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = pya; st.src2_vreg = acc[i * CT + j]; st.src2_subreg = (uint8_t)(2u * h + q); st.imm = j * 32u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - const int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ---------------------------------------------------------------- placeholder opcodes (header: OMEGA_TC_MARK_*) */ - -static uint32_t rd32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } -static void wr32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } -int omega_tc_patch_code(const BlackwellIRProgram *prog, uint8_t *code, size_t len) { - if (!prog || !code || len < prog->count * 16u) return -1; - int n = 0; - for (size_t i = 0; i < prog->count; i++) { - const BlackwellIRInsn *in = &prog->insns[i]; uint8_t *w = code + i * 16u; - if (in->op == BW_IR_SHFL_DOWN && (in->imm & OMEGA_TC_MARK_BFLY)) { - uint32_t w0 = rd32(w), w1 = rd32(w + 4); - if ((w0 & 0xffffu) != 0x7f89u || (w1 & 0xfc0000ffu) != 0x08000000u || (w1 & 0x0000ff00u) != 0x1f00u) return -1; - wr32(w + 4, w1 | 0x04000000u); n++; - } else if (in->op == BW_IR_FMNMX_MAX && in->imm == OMEGA_TC_MARK_F2FP) { - uint32_t w0 = rd32(w), w1 = rd32(w + 4), w2 = rd32(w + 8); - if ((w0 & 0xffffu) != 0x7209u || (w1 & 0xffffff00u) != 0 || w2 != 0x07800000u) return -1; - wr32(w, (w0 & 0xffff0000u) | 0x723eu); wr32(w + 8, 0x000010ffu); n++; - } - } - return n; -} - -int omega_tc_patch_selftest(char *msg, size_t msgn) { - static BlackwellIRProgram p; static uint8_t buf[64 * 16]; size_t len = 0; - omega_bw_ir_init(&p); - Em em; memset(&em, 0, sizeof em); em.p = &p; Em *e = &em; - int udesc = UV64(e), py = V64(e), tid = V(e), a = V(e), b = V(e), c = V(e), d = V(e); - if (e->err) { omega_gpu_fmt(msg, msgn, "vregs"); return -1; } - ldcu64(e, udesc, 0x358); ldc64(e, py, 0x380); s2r(e, tid, BW_SR_TID_X); - shfl_bfly(e, a, tid, 1); shfl_bfly(e, b, a, 2); shfl_down(e, c, b, 1); - f2fp_pack(e, d, a, c); - imadw(e, py, tid, 4u, py); stg(e, py, 0, d, udesc); stg(e, py, 128, b, udesc); - tail(e); - if (e->err || omega_bw_regalloc_solve(&p) != 0 || omega_bw_encode_program(&p, buf, sizeof buf, &len) != 0) { omega_gpu_fmt(msg, msgn, "build/encode failed"); return -1; } - int np = omega_tc_patch_code(&p, buf, len); - if (np != 3) { omega_gpu_fmt(msg, msgn, "patched %d placeholders, expected 3", np); return -1; } - int seen = 0; - for (size_t i = 0; i < p.count; i++) { - const uint8_t *w = buf + i * 16u; uint32_t w0 = rd32(w), w1 = rd32(w + 4), w2 = rd32(w + 8); - const BlackwellIRInsn *in = &p.insns[i]; - if (in->op == BW_IR_SHFL_DOWN) { - /* oracle words with the register bytes (16..31 of word 0) masked: BFLY lane 1 0x0c201f00, lane 2 0x0c401f00; DOWN 1 0x08201f00 */ - uint32_t lane = in->imm & 31u, want = ((in->imm & OMEGA_TC_MARK_BFLY) ? 0x0c001f00u : 0x08001f00u) | lane << 21; - if ((w0 & 0xffffu) != 0x7f89u || w1 != want || w2 != 0x000e0000u) { omega_gpu_fmt(msg, msgn, "SHFL word %zu: %08x %08x %08x", i, w0, w1, w2); return -1; } - seen++; - } else if (in->op == BW_IR_FMNMX_MAX) { - if ((w0 & 0xffffu) != 0x723eu || (w1 & 0xffffff00u) != 0 || w2 != 0x000010ffu) { omega_gpu_fmt(msg, msgn, "F2FP word %zu: %08x %08x %08x", i, w0, w1, w2); return -1; } - seen++; - } - } - if (seen != 4) { omega_gpu_fmt(msg, msgn, "saw %d of 4 checked words", seen); return -1; } - omega_gpu_fmt(msg, msgn, "SHFL.BFLY x2, SHFL.DOWN x1, F2FP.BF16.F32.PACK_AB x1 match the oracle bits"); - return 0; -} - -int omega_blackwell_codegen_tc_peak_prog(uint32_t iters, uint32_t chains, uint32_t stall, uint32_t threads, BlackwellIRProgram *prog) { - if (!prog || iters == 0 || chains == 0 || chains > 16 || stall == 0 || stall > 15 || threads == 0 || threads % 32 || threads > 1024) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), py = V64(e), tid = V(e), cta = V(e), one = V(e), cnt = V(e), a = V128(e), b = V64(e), acc[16]; - for (uint32_t c = 0; c < chains; c++) acc[c] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, py, 0x380); s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn m = I0(BW_IR_MOV_IMM); m.dst_vreg = a; m.dst_subreg = (uint8_t)q; m.imm = 0x3f803f80u; emit(e, m, K_FIXED); } - for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn m = I0(BW_IR_MOV_IMM); m.dst_vreg = b; m.dst_subreg = (uint8_t)q; m.imm = 0x3f803f80u; emit(e, m, K_FIXED); } - for (uint32_t c = 0; c < chains; c++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = acc[c]; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - movi(e, cnt, iters); - const int L = here(e); - loop_begin(e); - for (uint32_t c = 0; c < chains; c++) hmma(e, acc[c], a, b, acc[c], stall); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L); - loop_end(e); - nop(e, 15); nop(e, 15); - { int t = V(e); if (e->err) return -1; - imadi(e, t, cta, 0, threads, tid); imadw(e, py, t, 16u * chains, py); - for (uint32_t c = 0; c < chains; c++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = py; st.src2_vreg = acc[c]; st.src2_subreg = (uint8_t)q; st.imm = c * 16u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_blackwell_codegen_tc_bw_prog(uint32_t iters, uint32_t groups, uint32_t threads, BlackwellIRProgram *prog) { - if (!prog || iters == 0 || groups == 0 || threads == 0 || threads % 32 || threads > 1024) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), px = V64(e), py = V64(e), tid = V(e), cta = V(e), one = V(e), cnt = V(e), grp = V(e), t = V(e), acc = V(e), ld[8]; - for (int q = 0; q < 8; q++) ld[q] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); ldc64(e, px, 0x380); ldc64(e, py, 0x388); s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); movrz(e, acc); - /* grp = cta % groups (cta - (cta / groups) * groups via the unsigned high multiply is not needed: groups is 1 or the grid) */ - if (groups == 1) movrz(e, grp); else imadi(e, grp, cta, 0, 1u, NOREG); - imadw(e, px, grp, iters * threads * 128u, px); - imadi(e, t, tid, 0, 16u, NOREG); imadw(e, px, t, 1, px); - movi(e, cnt, iters); - const int L = here(e); - loop_begin(e); - for (int q = 0; q < 8; q++) ldg_wide(e, BW_IR_LDG_E_128, ld[q], px, (uint32_t)q * threads * 16u, udesc, q == 0); - for (int q = 0; q < 8; q++) for (unsigned s = 0; s < 4; s++) { BlackwellIRInsn x = I0(BW_IR_LOP3_XOR); x.dst_vreg = acc; x.src1_vreg = acc; x.src2_vreg = ld[q]; x.src2_subreg = (uint8_t)s; emit(e, x, K_FIXED); } - imadw(e, px, one, threads * 128u, px); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L); - loop_end(e); - imadi(e, t, cta, 0, threads, tid); imadw(e, py, t, 4u, py); - stg(e, py, 0, acc, udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_tc.h b/src/omega_blackwell_codegen_tc.h deleted file mode 100644 index cc5c8e563..000000000 --- a/src/omega_blackwell_codegen_tc.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_TC_H -#define OMEGA_BLACKWELL_CODEGEN_TC_H -/* - * omega_blackwell_codegen_tc: tensor-core (HMMA.16816.F32.BF16) kernels for the OWN-30B one-pass prefill (T3, 2026-10-13). - * New file. Uses only opcodes the encoder already has and fixture-tests (omega_blackwell_codegen.h). - * - * HMMA.16816 fragment layout (lane L, g = L / 4, t = L % 4; register q holds element 2q in its low half, 2q+1 high): - * A 16x16 (row-major M x K): a0,a1 = A[g][2t, 2t+1] a2,a3 = A[g+8][2t, 2t+1] a4,a5 = A[g][2t+8, 2t+9] a6,a7 = A[g+8][2t+8, 2t+9] - * B 16x8 (K x N): b0,b1 = B[2t, 2t+1][g] b2,b3 = B[2t+8, 2t+9][g] - * C/D 16x8 f32: c0,c1 = C[g][2t, 2t+1] c2,c3 = C[g+8][2t, 2t+1] - * (PTX ISA mma.m16n8k16 fragment figures; the fragment-major matmul of omega_blackwell_codegen.h packs to the same order and - * is chip-proven.) - * - * ---- probe kernel (characterisation of the chip's HMMA arithmetic) ---- - * One warp per CTA, ctaid.x = case. Per case, at in + case * 1280: A quads [32 lanes][4 u32] (512 B), B pairs [32][2] (256 B), - * C quads [32][4] f32 (512 B). Output at out + case * 512: D quads [32][4] f32. Arguments: 0x380 in u64, 0x388 out u64. - * D = A * B + C with one HMMA.16816.F32.BF16. mutant 1 (tests only): C is replaced by RZ (must be caught when C != 0). - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_TC_PROBE_IN_BYTES 1280u -#define OMEGA_TC_PROBE_OUT_BYTES 512u -int omega_blackwell_codegen_tc_probe_prog(int mutant, BlackwellIRProgram *prog); - -/* ---- grouped FP8 GEMM on tensor cores (cut 1: e4m3 weights decoded to bf16 in registers, HMMA.16816.F32.BF16) ---- - * y[row0 + r][c] = sum_kb S'[c/128][kb] * ( sum_{k in kb} w(W[c][k]) * x(X[rowidx[row0 + r]][k]) ) - * w(e) = e4m3 value * 2^-120 as bf16 bits ((e & 0x7F) << 4 | (e & 0x80) << 8: exact, subnormal codes become bf16 subnormals, - * which the HMMA honours: evidence OWN30B-T3-HMMA-MODEL), x = bf16(x * 2^64), S' = scale * 2^56 (the FP8 GEMV's fold, so - * the true value is recovered). Per 128-wide K block: 8 HMMA steps into a zeroed temporary, then acc = fma(tmp, S', acc). - * - * Physical K order. Within every aligned group of 4 elements (k = 4q .. 4q+3) the activations are STORED as - * [x(4q), x(4q+2), x(4q+1), x(4q+3)] (bf16, row-major otherwise): omega_tcgemm_permute_x. Weights stay in checkpoint order. - * HMMA step (chunk c of 64 elements, s = 0..3) consumes the 16 elements c*64 + 16t + 4s + j (t = 0..3 lane%4, j = 0..3); - * lane t's weight bytes j = 0,2 form B register 0 and j = 1,3 register 1, so one e4m3 word decodes into both B registers - * with 8 integer ops, and the matching activation words arrive in order. The fused 16-term HMMA sum does not depend on the - * order of its terms (tests/bw_hmma_model.h), so the result depends only on the step grouping above. - * - * Tile table (device, ctaid.y = tile, 32 bytes each, the FP8 GEMM's segment entry): { w_va u64, s_va u64, row0 u32, cnt u32, - * pad[8] } with 1 <= cnt <= 16*rt; rows row0 .. row0+cnt-1 of the sorted row space belong to one expert. - * rowidx (device u32): sorted row -> source row of X; entries row0 .. row0 + 16*rt - 1 must be readable for every tile (the - * host pads with valid rows; rows past cnt are computed and not stored). - * Constant bank 0 (cbank + 0x380): tiles u64, rowidx u64, x u64 (bf16 rows of k), y u64 (f32 rows of n), n u32. - * Grid: grid_x = n / (warps * 8 * ct) (exact), grid_y = tiles. CTA: 32 * warps threads; shared 2 * 16 * rt * 128 bytes. - * mutant (tests only): 1 drops the block scale, 2 never advances the scale pointer, 3 row tile i reads tile i^1 (rt >= 2), - * 4 drops the last 64-element chunk of every 128 block. Each must be caught. */ -typedef struct { - uint32_t k; /* multiple of 128, 128 .. 16384 */ - uint32_t rt; /* row tiles (16 rows) per CTA: 1, 2 or 4 */ - uint32_t ct; /* column tiles (8 weight rows) per warp: 1, 2 or 4; rt * ct >= 4 */ - uint32_t warps; /* 1, 2, 4 or 8; (16 * rt * 8) % (32 * warps) == 0 */ - int mutant; -} OmegaTcGemmSpec; -#define OMEGA_TCGEMM_ARG_TILES 0x380u -#define OMEGA_TCGEMM_ARG_ROWIDX 0x388u -#define OMEGA_TCGEMM_ARG_X 0x390u -#define OMEGA_TCGEMM_ARG_Y 0x398u -#define OMEGA_TCGEMM_ARG_N 0x3a0u -#define OMEGA_TCGEMM_ARGS_WORDS 9u -#define OMEGA_TCGEMM_TILE_BYTES 32u -int omega_tcgemm_spec_ok(const OmegaTcGemmSpec *spec); -uint32_t omega_tcgemm_shared_bytes(const OmegaTcGemmSpec *spec); -uint32_t omega_tcgemm_span(const OmegaTcGemmSpec *spec); /* weight rows per CTA */ -int omega_blackwell_codegen_tcgemm_prog(const OmegaTcGemmSpec *spec, BlackwellIRProgram *prog); -/* x (k values) -> the stored bf16 row: RNE bf16 of x * 2^64 in the (0,2,1,3) group order */ -void omega_tcgemm_permute_x(const float *x, uint32_t k, uint16_t *out); -/* e4m3 code -> the bf16 bits the kernel feeds the HMMA (value * 2^-120) */ -uint16_t omega_tcgemm_w_bf16(uint8_t code); - -/* tensor-core peak microbenchmark: each thread runs `iters` x `chains` HMMA.16816.F32.BF16 (A = B = 1.0, C chained per - * accumulator, `stall` cycles between issues), then stores its chains x 4 accumulators at out (arg 0x380) + (ctaid * threads + - * tid) * 16 * chains. Every stored value must be 16 * iters (a hazard on a chained accumulator shows as a wrong value). */ -int omega_blackwell_codegen_tc_peak_prog(uint32_t iters, uint32_t chains, uint32_t stall, uint32_t threads, BlackwellIRProgram *prog); - -/* read-bandwidth probe: CTA c streams region (c % groups) of iters * threads * 128 bytes (8 LDG.128 per thread per iteration, - * XOR-folded) from arg 0x380 and stores one word per thread at arg 0x388 + (c * threads + tid) * 4. groups = grid: every - * CTA distinct (DRAM); groups = 1: every CTA the same bytes (shows any cache reuse of these buffers). */ -int omega_blackwell_codegen_tc_bw_prog(uint32_t iters, uint32_t groups, uint32_t threads, BlackwellIRProgram *prog); - -/* ---- opcodes the shared encoder lacks, emitted as same-footprint placeholders and patched after encoding ---- - * SHFL.BFLY PT, Rd, Ra, lane, 0x1f: a BW_IR_SHFL_DOWN whose imm carries OMEGA_TC_MARK_BFLY; the patch sets bit 26 of word 1 - * (nvcc 13.0.88 sm_121 oracle, investigations/2026-10-13-t3-mma-oracle/attn/fa_ops.sass: SHFL.BFLY PT, R5, R0, 0x1, 0x1f = - * 0x0c201f0000057f89 / 0x004e2800000e0000; the shared encoder's SHFL.DOWN word 1 is 0x08001f00 | lane << 21). - * F2FP.BF16.F32.PACK_AB Rd, Ra, Rb (Rd = bf16_rn(Ra) << 16 | bf16_rn(Rb)): a BW_IR_FMNMX_MAX whose imm is OMEGA_TC_MARK_F2FP; - * the patch rewrites the opcode to 0x723e and word 2 to 0x000010ff (oracle: F2FP.BF16.F32.PACK_AB R9, R3, R0 = - * 0x000000000309723e / 0x000fe200000010ff; registers stay at Rd 16..23, Ra 24..31, Rb 32..39 as FMNMX). F2FP needs no - * scoreboard in the oracle (fixed latency), as FMNMX. */ -#define OMEGA_TC_MARK_BFLY 0x80000000u -#define OMEGA_TC_MARK_F2FP 0x46320000u -/* patch the encoded code (len bytes, one 16-byte word per IR instruction); returns the number patched or -1 on a word that - * does not hold the expected placeholder bits */ -int omega_tc_patch_code(const BlackwellIRProgram *prog, uint8_t *code, size_t len); -/* encoder self-test: placeholders encoded and patched against the oracle words (register fields excluded); 0 = pass */ -int omega_tc_patch_selftest(char *msg, size_t msgn); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_tc2.c b/src/omega_blackwell_codegen_tc2.c deleted file mode 100644 index 7bbe6bbec..000000000 --- a/src/omega_blackwell_codegen_tc2.c +++ /dev/null @@ -1,229 +0,0 @@ -/* omega_blackwell_codegen_tc2.c: tensor-core grouped FP8 GEMM v2 (OWN-30B T3b). See the header. The K loop, staging and - * decode are cut 1's (omega_blackwell_codegen_tc.c, chip gate OWN30B-T3-TCGEMM-6d2803ec) with the scale folded through the - * accumulator and the v2 epilogues. */ -#include "omega_blackwell_codegen_tc2.h" -#include "omega_bw_em.h" - -int omega_tc2_spec_ok(const OmegaTc2Spec *s) { - if (!s) return 0; - if (s->k < 128u || s->k > 16384u || s->k % 128u) return 0; - if (s->rt != 2 && s->rt != 4 && s->rt != 8) return 0; - if (s->ct != 2) return 0; /* the ratio table pairs the warp's two column tiles (one LDG.64) */ - if (s->rt * s->ct < 4u) return 0; - if (s->warps != 4 && s->warps != 8 && s->warps != 16) return 0; - if (s->aqn != 1 && s->aqn != 2) return 0; - if (s->epi > OMEGA_TC2_EPI_SWIGLU || (s->epi == OMEGA_TC2_EPI_SWIGLU && s->ct != 2)) return 0; - if (s->direct > 1) return 0; - if (s->n == 0 || s->n % (s->warps * 8u * s->ct) || (uint64_t)s->n * 4u * 16u * s->rt >= (1u << 23)) return 0; - if ((16u * s->rt * 8u) % (32u * s->warps)) return 0; /* whole LDG.128 staging slots per thread */ - if (s->mutant < 0 || s->mutant > 4 || (s->mutant == 3 && s->rt < 2)) return 0; - return 1; -} -uint32_t omega_tc2_shared_bytes(const OmegaTc2Spec *s) { return omega_tc2_spec_ok(s) ? 2u * 16u * s->rt * 128u : 0u; } -uint32_t omega_tc2_span(const OmegaTc2Spec *s) { return omega_tc2_spec_ok(s) ? s->warps * 8u * s->ct : 0u; } - -/* one e4m3 word (bytes b0..b3) -> B register pair: lo = (bf(b0), bf(b2)), hi = (bf(b1), bf(b3)) (cut 1) */ -static void decode_word(Em *e, int bpair, int wq, unsigned word, int m, int s, int t) { - andi(e, m, wq, word, 0x007F007Fu); andi(e, s, wq, word, 0x00800080u); - imadi(e, t, m, 0, 16u, NOREG); - { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = bpair; i.dst_subreg = 0; i.src1_vreg = s; i.imm = 256u; i.src3_vreg = t; emit(e, i, K_FIXED); } - andi(e, m, wq, word, 0x7F007F00u); andi(e, s, wq, word, 0x80008000u); - shr(e, t, m, 0, 4); - { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = bpair; i.dst_subreg = 1; i.src1_vreg = t; i.src2_vreg = s; emit(e, i, K_FIXED); } -} -static void fmul_s(Em *e, int d, unsigned dsub, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.dst_subreg = (uint8_t)dsub; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; emit(e, i, K_FIXED); -} -static void mufu(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); } - -int omega_blackwell_codegen_tc2_prog(const OmegaTc2Spec *spec, BlackwellIRProgram *prog) { - if (!omega_tc2_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, RT = spec->rt, CT = spec->ct, W = spec->warps, T = 32u * W, AQN = spec->aqn; - const uint32_t BM = 16u * RT, KB = K / 128u, SPAN = W * 8u * CT, NJ = BM * 8u / T, BUF = BM * 128u; - const uint32_t RSTRIDE = (KB + 1u) * 8u; /* bytes per 16-row group pair of the ratio table */ - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue: arguments, ids, tile entry ---- */ - int udesc = UV64(e), ptab = V64(e), pidx = V64(e), px = V64(e), py = V64(e), nreg = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), g = V(e), tq = V(e), one = V(e), tent = V64(e); - int wbase = V64(e), rbase = V64(e), rc = V64(e), row0 = V(e); - int n0w = V(e), tmp = V(e), tmp2 = V(e), pw = V64(e), pr = V64(e), la = V(e), pyr = V64(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ptab, 0x380); if (!spec->direct) ldc64(e, pidx, 0x388); ldc64(e, px, 0x390); ldc64(e, py, 0x398); - ldc32(e, nreg, 0x3a0); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); andi(e, lane, tid, 0, 31); shr(e, g, lane, 0, 2); andi(e, tq, lane, 0, 3); - imadw(e, tent, cy, OMEGA_TC2_TILE_BYTES, ptab); - ldg_wide(e, BW_IR_LDG_E_64, wbase, tent, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, rbase, tent, 8, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, rc, tent, 16, udesc, 0); - imadi(e, row0, rc, 0, 1, NOREG); - /* this warp's first weight row n0w; weight pointer row (n0w + g), byte 16 t; ratio row group n0w / 8 */ - imadi(e, n0w, cx, 0, SPAN, NOREG); imadi(e, tmp, warp, 0, 8u * CT, NOREG); iadd(e, n0w, n0w, tmp); - iadd(e, tmp, n0w, g); imadw(e, pw, tmp, K, wbase); imadi(e, tmp2, tq, 0, 16u, NOREG); imadw(e, pw, tmp2, 1, pw); - shr(e, tmp, n0w, 0, 4); imadw(e, pr, tmp, RSTRIDE, rbase); - imadi(e, la, lane, 0, 16u, NOREG); - - /* ---- staging assignment: slot = tid + jj * T -> row r = slot / 8, words w0 = 4 * (tid % 8) of the 64-element chunk ---- */ - int gx[8], sa[8]; - for (uint32_t jj = 0; jj < NJ; jj++) { gx[jj] = V64(e); sa[jj] = V(e); } - int r = V(e), sidx = V64(e), srow = V(e), w0b = V(e), ts = V(e), s0 = V(e); - if (e->err) return -1; - andi(e, tmp, tid, 0, 7); - imadi(e, w0b, tmp, 0, 16u, NOREG); - shr(e, ts, tmp, 0, 1); - andi(e, s0, tid, 0, 1); imadi(e, s0, s0, 0, 2u, NOREG); - for (uint32_t jj = 0; jj < NJ; jj++) { - shr(e, r, tid, 0, 3); imadi(e, r, one, 0, jj * T / 8u, r); - iadd(e, tmp, row0, r); - if (spec->direct) imadi(e, srow, tmp, 0, 1u, NOREG); - else { imadw(e, sidx, tmp, 4u, pidx); ldg32(e, srow, sidx, udesc, 1); } - imadw(e, gx[jj], srow, K * 2u, px); imadw(e, gx[jj], w0b, 1, gx[jj]); - shr(e, tmp, r, 0, 4); imadi(e, tmp, tmp, 0, 4u, s0); imadi(e, tmp, tmp, 0, 32u, ts); - andi(e, tmp2, r, 0, 7); imadi(e, tmp2, tmp2, 0, 4u, tmp); imadi(e, sa[jj], tmp2, 0, 16u, NOREG); - shr(e, tmp2, r, 0, 3); andi(e, tmp2, tmp2, 0, 1); imadi(e, sa[jj], tmp2, 0, 4u, sa[jj]); - } - - /* ---- loop-wide registers ---- */ - int acc[16], wa[2], wb[2], bp[2], aq[2], stgr[8], rr = V64(e), cntk = V(e), dm = V(e), ds = V(e), dt = V(e); - for (uint32_t x = 0; x < RT * CT; x++) acc[x] = V128(e); - for (uint32_t j = 0; j < CT; j++) { wa[j] = V128(e); wb[j] = V128(e); bp[j] = V64(e); } - for (uint32_t q = 0; q < AQN; q++) aq[q] = V128(e); - for (uint32_t jj = 0; jj < NJ; jj++) stgr[jj] = V128(e); - if (e->err) return -1; - - #define ISSUE(wset, sb, xoff, woff, with_ratio) do { \ - for (uint32_t jj = 0; jj < NJ; jj++) ldw_pf(e, BW_IR_LDG_E_128, stgr[jj], gx[jj], (xoff), udesc, (sb)); \ - for (uint32_t j = 0; j < CT; j++) ldw_pf(e, BW_IR_LDG_E_128, (wset)[j], pw, (woff) + j * 8u * K, udesc, (sb)); \ - if (with_ratio) ldw_pf(e, BW_IR_LDG_E_64, rr, pr, 0u, udesc, (sb)); } while (0) - #define STAGE(buf) do { for (uint32_t jj = 0; jj < NJ; jj++) { static const uint32_t off[4] = { 0, 8, 512, 520 }; \ - for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn st = I0(BW_IR_STS32); imadi(e, tmp, one, 0, (buf) + off[q], sa[jj]); \ - st.src1_vreg = tmp; st.src2_vreg = stgr[jj]; st.src2_subreg = (uint8_t)q; emit(e, st, K_STORE); } } bar_sync(e); } while (0) - #define COMPUTE(buf, wset, odd) do { \ - for (uint32_t s = 0; s < 4; s++) { \ - if (spec->mutant == 4 && (odd) && s == 3) break; \ - for (uint32_t j = 0; j < CT; j++) decode_word(e, bp[j], (wset)[j], s, dm, ds, dt); \ - for (uint32_t i0 = 0; i0 < RT; i0 += AQN) { \ - const uint32_t nb = RT - i0 < AQN ? RT - i0 : AQN; \ - for (uint32_t q = 0; q < nb; q++) { uint32_t i = i0 + q, ii = spec->mutant == 3 ? (i ^ 1u) : i; \ - lds128(e, aq[q], la, (buf) + (ii * 4u + s) * 512u, q == 0); } \ - for (uint32_t q = 0; q < nb; q++) for (uint32_t j = 0; j < CT; j++) { uint32_t x = (i0 + q) * CT + j; \ - hmma(e, acc[x], aq[q], bp[j], acc[x], 8); } \ - } \ - } } while (0) - /* acc *= rr[j] (all four quads of every tile of column tile j); the HMMA results must have settled first */ - #define RESCALE() do { nop(e, 15); nop(e, 14); \ - for (uint32_t x = 0; x < RT * CT; x++) for (unsigned q = 0; q < 4; q++) fmul_s(e, acc[x], q, acc[x], q, rr, x % CT); } while (0) - - for (uint32_t x = 0; x < RT * CT; x++) for (unsigned q = 0; q < 4; q++) { BlackwellIRInsn mz = I0(BW_IR_MOV_RZ); mz.dst_vreg = acc[x]; mz.dst_subreg = (uint8_t)q; emit(e, mz, K_FIXED); } - ISSUE(wa, 3u, 0u, 0u, 1); - consume(e, 3); - STAGE(0u); - movi(e, cntk, KB); - - /* ---- K loop: one 128-wide block (two chunks) per iteration ---- */ - const int L_k = here(e); - loop_begin(e); - ISSUE(wb, 4u, 128u, 64u, 0); /* chunk 2kb+1 */ - consume(e, 3); - if (spec->mutant != 1) RESCALE(); /* acc = acc * R[kb] (R[0] = 1) */ - COMPUTE(0u, wa, 0); - consume(e, 4); - STAGE(BUF); - { /* chunk 2kb+2 (the next block's first chunk) and R[kb+1]; the last iteration re-reads its own (harmless) */ - int nf = V(e), inc = V(e); if (e->err) return -1; - imadi(e, nf, one, 0, 0xfffffffeu, cntk); shr(e, nf, nf, 0, 31); imadi(e, nf, nf, 0, 0xffffffffu, one); - for (uint32_t jj = 0; jj < NJ; jj++) imadw(e, gx[jj], nf, 256u, gx[jj]); - imadw(e, pw, nf, 128u, pw); - imadi(e, inc, nf, 0, spec->mutant == 2 ? 0u : 8u, NOREG); imadw(e, pr, inc, 1, pr); - } - ISSUE(wa, 3u, 0u, 0u, 1); - COMPUTE(BUF, wb, 1); - consume(e, 3); - STAGE(0u); - imadi(e, cntk, one, 0, 0xffffffffu, cntk); - isetp_ge_u32(e, cntk, one); - bra_if_p0(e, L_k); - loop_end(e); - #undef ISSUE - #undef STAGE - #undef COMPUTE - - /* ---- final scale R[KB] (pr points at R[KB-1]) ---- */ - ldg_wide(e, BW_IR_LDG_E_64, rr, pr, 8u, udesc, 1); - RESCALE(); - #undef RESCALE - int g2 = V(e), cnt2 = V(e), rrow = V(e), onee = V(e); - /* ---- epilogue addressing, recomputed in fresh registers (nothing of it stays live through the K loop) ---- */ - { - int tid2 = V(e), cx2 = V(e), cy2 = V(e), lane2 = V(e), tq2 = V(e), tab2 = V64(e), ten2 = V64(e), rc2 = V64(e), py2 = V64(e), n2 = V(e), nw2 = V(e), r02 = V(e); - if (e->err) return -1; - ldc64(e, tab2, 0x380); ldc64(e, py2, 0x398); ldc32(e, n2, 0x3a0); - s2r(e, tid2, BW_SR_TID_X); s2r(e, cx2, BW_SR_CTAID_X); s2r(e, cy2, BW_SR_CTAID_Y); - imadw(e, ten2, cy2, OMEGA_TC2_TILE_BYTES, tab2); - ldg_wide(e, BW_IR_LDG_E_64, rc2, ten2, 16, udesc, 1); - andi(e, lane2, tid2, 0, 31); shr(e, g2, lane2, 0, 2); andi(e, tq2, lane2, 0, 3); - imadi(e, r02, rc2, 0, 1, NOREG); imadi(e, cnt2, rc2, 1, 1, NOREG); movi(e, onee, 1); - shr(e, tmp, tid2, 0, 5); imadi(e, tmp, tmp, 0, 8u * CT, NOREG); imadi(e, nw2, cx2, 0, SPAN, tmp); - if (spec->epi == OMEGA_TC2_EPI_F32) { - - /* y + ((row0 + g) * n + n0w + 2t) * 4 */ - iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, nw2); imadi(e, tmp2, tq2, 0, 2u, NOREG); iadd(e, tmp, tmp, tmp2); imadw(e, pyr, tmp, 4u, py2); - } else { - - /* act + (row0 + g) * n + (n0w / 2 + 2t) * 2 */ - iadd(e, tmp, r02, g2); imadr(e, tmp, tmp, n2, NOREG); imadw(e, pyr, tmp, 1u, py2); - shr(e, tmp, nw2, 0, 1); imadi(e, tmp2, tq2, 0, 2u, tmp); imadw(e, pyr, tmp2, 2u, pyr); - } - } - - /* ---- store: rows 16i + 8h + g of the tile only when < cnt (a partial tile must not touch the next expert's rows) ---- */ - int kf = NOREG, p64 = NOREG, onef = NOREG, tg = NOREG, tex = NOREG, o0 = NOREG, o1 = NOREG, pk = NOREG; - if (spec->epi == OMEGA_TC2_EPI_SWIGLU) { - kf = V(e); p64 = V(e); onef = V(e); tg = V(e); tex = V(e); o0 = V(e); o1 = V(e); pk = V(e); - if (e->err) return -1; - movi(e, kf, 0xbfb8aa3bu); /* -log2(e) as f32 (-1.4426950409f) */ - movi(e, onef, 0x3f800000u); /* 1.0f */ - movi(e, p64, 0x5f800000u); /* 2^64: the stored-activation scale of the next GEMM */ - } - if (e->err) return -1; - const uint32_t ystride = spec->epi == OMEGA_TC2_EPI_F32 ? spec->n * 4u : spec->n; - /* rows grow with (i, h): a lane whose row reaches cnt jumps to the one BSYNC after the last store */ - int skips[2 * 8]; uint32_t nskip = 0; - const int at_bssy = bssy_fwd(e); - for (uint32_t i = 0; i < RT; i++) for (uint32_t h = 0; h < 2; h++) { - const uint32_t roff = (16u * i + 8u * h) * ystride; - imadi(e, rrow, onee, 0, 16u * i + 8u * h, g2); - isetp_ge_u32(e, rrow, cnt2); - skips[nskip++] = bra_if_p0_fwd(e); - if (spec->epi == OMEGA_TC2_EPI_F32) { - for (uint32_t j = 0; j < CT; j++) for (unsigned q = 0; q < 2; q++) { BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = pyr; st.src2_vreg = acc[i * CT + j]; st.src2_subreg = (uint8_t)(2u * h + q); st.imm = roff + j * 32u + 4u * q; st.ureg = udesc; emit(e, st, K_STORE); } - } else { - /* act = silu(g) * u * 2^64 (the next GEMM reads activations stored * 2^64) */ - const int G = acc[i * 2], U = acc[i * 2 + 1]; - for (unsigned q = 0; q < 2; q++) { - const int o = q ? o1 : o0; const unsigned sub = 2u * h + q; - fmul_s(e, tg, 0, G, sub, kf, 0); - mufu(e, BW_IR_MUFU_EX2, tex, tg); - fadd(e, tex, tex, onef); - mufu(e, BW_IR_MUFU_RCP, tex, tex); - fmul_s(e, o, 0, G, sub, tex, 0); - fmul_s(e, o, 0, o, 0, U, sub); - fmul_s(e, o, 0, o, 0, p64, 0); - } - f2fp_pack(e, pk, o1, o0); - stg(e, pyr, roff, pk, udesc); - } - } - { const int at_bsync = here(e); - bsync(e); - for (uint32_t q = 0; q < nskip; q++) patch_bra(e, skips[q], at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} diff --git a/src/omega_blackwell_codegen_tc2.h b/src/omega_blackwell_codegen_tc2.h deleted file mode 100644 index 4710fa943..000000000 --- a/src/omega_blackwell_codegen_tc2.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_TC2_H -#define OMEGA_BLACKWELL_CODEGEN_TC2_H -/* - * omega_blackwell_codegen_tc2: tensor-core grouped FP8 GEMM v2 for the device-resident prefill (OWN-30B T3b, 2026-10-13). - * New file. Same fragment layout, weight decode, activation storage ((0,2,1,3)-permuted bf16 * 2^64) and A staging as - * cut 1 (omega_blackwell_codegen_tc.h); differences: - * - big tiles: up to 16 warps x 16 columns x 128 rows (rt 8, ct 2: 64 accumulator registers per lane); - * - the block scale is folded through the accumulator chain: per 128-wide K block kb, acc = acc * R[kb], then the 8 HMMA - * steps accumulate straight into acc (no temporary); after the last block acc = acc * R[KB]. R is a per-expert f32 - * table per 8-row group g of the PHYSICAL weight rows: R[g][0] = 1, R[g][kb] = S'[kb-1] / S'[kb] (RN), R[g][KB] = - * S'[KB-1], where S' = scale_inv * 2^56 of the 128-block holding the group's source rows. Stored as pairs - * [n/16][KB+1][2] (the warp's two column tiles side by side, one LDG.64 per block: plain LDG.E has no immediate offset); - * - rows >= cnt of a partial tile are not stored (one BSSY, forward jumps, one BSYNC); - * - epilogue F32: y[row][c] f32 rows of n; epilogue SWIGLU (ct = 2): column tile 0 of each warp is gate, tile 1 up (the - * upload interleaves gate and up rows in groups of 8), the lane computes a = g / (1 + ex2(g * -log2e)) * u * 2^64 - * (MUFU.EX2, FADD, MUFU.RCP, FMUL, FMUL, FMUL x 2^64, in that order; MUFU flushes a subnormal result to +-0, so for - * g in (-88.72, -87.34), where 1 / (2^t + 1) is subnormal, the activation is +-0: PTX ISA 9.7.3.13 ftz, chip-observed in - * evidence OWN30B-L1G-PFGEMM-SWIGLU-FTZ-df9bd9c4) and stores bf16x2 (F2FP RN) at act column n0w/2 + 2t of the - * act row (n/2 bf16): with the upload's (0,2,1,3) output-row permutation the act row is directly the next GEMM's - * stored activation row; - * - direct rows (no row index): the source row of sorted row r is r itself (the down GEMM reading the act rows). - * - * Tile table entry (32 bytes, ctaid.y): { w_va u64 (expert's n x k e4m3), r_va u64 (expert's (n/8) x (KB+1) f32), row0 u32, - * cnt u32 (1 .. 16*rt), pad u64 }. Rows row0 .. row0 + 16*rt - 1 of the row index must be readable (host pads). - * Constant bank 0 (cbank + 0x380): tiles u64, rowidx u64 (ignored when direct), x u64, y u64, n u32. - * Grid: grid_x = n / span (span = warps * 8 * ct), grid_y = tiles; CTA 32 * warps threads, shared 2 * 16 * rt * 128 bytes. - * mutant (tests only): 1 skips the per-block ratio multiply, 2 never advances the ratio pointer, 3 row tile i reads tile - * i^1, 4 drops the last 16-element step of every 128 block. - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif -enum { OMEGA_TC2_EPI_F32 = 0, OMEGA_TC2_EPI_SWIGLU = 1 }; -typedef struct { - uint32_t k; /* multiple of 128, 128 .. 16384 */ - uint32_t rt; /* row tiles of 16 per CTA: 2, 4 or 8 */ - uint32_t ct; /* column tiles of 8 per warp: 2 (the paired ratio load) */ - uint32_t warps; /* 4, 8 or 16 */ - uint32_t aqn; /* A fragments in flight: 1 or 2 */ - uint32_t epi; /* OMEGA_TC2_EPI_* */ - uint32_t direct; /* 1: no row index */ - uint32_t n; /* output width (weight rows), a multiple of span; fixes the store offsets */ - int mutant; -} OmegaTc2Spec; -#define OMEGA_TC2_ARGS_WORDS 9u -#define OMEGA_TC2_TILE_BYTES 32u -int omega_tc2_spec_ok(const OmegaTc2Spec *s); -uint32_t omega_tc2_shared_bytes(const OmegaTc2Spec *s); -uint32_t omega_tc2_span(const OmegaTc2Spec *s); -int omega_blackwell_codegen_tc2_prog(const OmegaTc2Spec *s, BlackwellIRProgram *prog); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_codegen_tern.c b/src/omega_blackwell_codegen_tern.c deleted file mode 100644 index 370564e89..000000000 --- a/src/omega_blackwell_codegen_tern.c +++ /dev/null @@ -1,420 +0,0 @@ -/* omega_blackwell_codegen_tern.c: KT1 W2A8 ternary GEMV kernel, ternary engine stage T0 (2026-10-15). See the header. - * The emitter helpers are copies of omega_blackwell_codegen_bf16.c's (same chip-learned scheduling rules: every - * instruction waits on everything still pending; variable-latency results go through scoreboard 0, stores set the read - * barrier 1, uniform loads scoreboard 2; ISETP stalls 14 before a predicated branch; - * the loads of one iteration are issued back to back so a warp has all of them in flight at once). One change: the - * fixed-latency stall is no longer 6 on every instruction; tern_schedule_stalls sets each one from the physical register - * dependencies so every user still sits >= 6 cycles behind its producer (see the pass). */ -#include "omega_blackwell_codegen_tern.h" -#include - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a[asub] * imm + c (c NOREG = RZ) */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c (register form) */ -static void imadr(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fmul(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void i2f(Em *e, int d, int a) { BlackwellIRInsn i = I0(BW_IR_I2FP); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} -/* predicated region: lanes with P0 set skip to the join (bra_if_p0 inside BSSY .. BSYNC, the bf16 store pattern) */ -typedef struct { int bssy, bra; } Region; -static Region region_begin(Em *e) { Region r; r.bssy = bssy_fwd(e); r.bra = bra_if_p0_fwd(e); return r; } -static void region_end(Em *e, Region r) { int at = here(e); bsync(e); patch_bra(e, r.bra, at); patch_bra(e, r.bssy, at + 1); } - -uint32_t omega_tern_gemv_chunks(const OmegaTernGemvSpec *s) { - if (!s || s->k == 0) return 0; - return (s->k + OMEGA_TERN_CHUNK_MAX - 1u) / OMEGA_TERN_CHUNK_MAX; -} - -int omega_tern_gemv_spec_ok(const OmegaTernGemvSpec *s) { - if (!s) return 0; - if (s->k == 0 || s->k > OMEGA_TERN_MAX_K || s->k % 256u) return 0; - const uint32_t nch = omega_tern_gemv_chunks(s); - if (s->k % (256u * nch)) return 0; - if (s->layout == OMEGA_TERN_LAYOUT_ROWMAJOR) { if (s->rows != 1 && s->rows != 2 && s->rows != 4) return 0; } - else if (s->layout == OMEGA_TERN_LAYOUT_BLOCK) { if (s->rows != 2 && s->rows != 4) return 0; } - else return 0; - if (s->warps < 1 || s->warps > 32) return 0; - const uint32_t ksc = s->k / nch / 256u; - if (s->depth == 0 || s->depth > 16 || ksc % s->depth || s->rows * s->depth > 16u) return 0; - if (s->epi != OMEGA_TERN_EPI_I32 && s->epi != OMEGA_TERN_EPI_F32) return 0; - if (s->epi == OMEGA_TERN_EPI_F32 && nch != 1) return 0; - if (s->mutant < 0 || s->mutant > 3) return 0; - return 1; -} -uint32_t omega_tern_gemv_steps(const OmegaTernGemvSpec *s) { return omega_tern_gemv_spec_ok(s) ? s->k / 256u : 0; } -uint32_t omega_tern_gemv_shared_bytes(const OmegaTernGemvSpec *s) { - return omega_tern_gemv_spec_ok(s) ? (s->k / omega_tern_gemv_chunks(s)) * 2u : 0; -} - -uint64_t omega_tern_word_offset(uint32_t layout, uint32_t R, uint32_t k, uint32_t r, uint32_t c) { - const uint64_t kw = k / 16u; - if (layout == OMEGA_TERN_LAYOUT_ROWMAJOR) return ((uint64_t)r * kw + c) * 4u; - const uint64_t blk = r / (2u * R), j = r % (2u * R); - return blk * 2u * R * kw * 4u + (uint64_t)c * 2u * R * 4u + j * 4u; -} - - -/* ---- dependency-driven stall counts (after register allocation) ---- - * The copied emitter gives every fixed-latency instruction stall 6, which keeps any user >= 6 cycles behind its - * producer but also makes independent instructions wait 6 cycles each. The repository's chip-proven rule is the - * distance, not the per-instruction count: a fixed-latency producer stalls >= 5 cycles before its consumer (we keep 6; - * omega_gpu_elementwise_api.c:13). This pass walks the program in order on physical registers and gives each - * instruction the smallest stall that keeps the next instruction >= OMEGA_TERN_FIXED_LAT cycles behind every - * fixed-latency write it reads or overwrites. Before a control instruction (BRA, EXIT, BSSY, BSYNC, BAR) or a branch - * target every fixed-latency write has completed, so straight-line timing never spans a jump. Instructions that are not - * fixed latency keep at least their emitted stall (loads, ISETP 14 before a predicated branch, the scoreboard rules); - * their wait masks are untouched. Hardware can only add cycles, which only lengthens every distance. */ -static int tern_fixed(BlackwellIROpcode op) { - switch (op) { - case BW_IR_IMAD: case BW_IR_IMAD_WIDE: case BW_IR_SHF_R: case BW_IR_LOP3_AND: case BW_IR_MOV_IMM: case BW_IR_MOV_RZ: - case BW_IR_FMUL: case BW_IR_I2FP: return 1; - default: return 0; - } -} -static int tern_control(BlackwellIROpcode op) { - return op == BW_IR_BRA || op == BW_IR_EXIT || op == BW_IR_BSSY || op == BW_IR_BSYNC || op == BW_IR_BAR_SYNC; -} -/* physical registers an operand covers: [*lo, *lo + *cnt) */ -static void tern_span(const BlackwellIRProgram *p, int v, int *lo, int *cnt) { - *lo = -1; *cnt = 0; - if (v < 0 || v >= p->regalloc.num_vregs) return; - const int ph = p->regalloc.vreg_to_phys[v]; - if (ph < 0) return; - *lo = ph; *cnt = (int)(p->regalloc.intervals[v].bundle_size ? p->regalloc.intervals[v].bundle_size : 1u); -} -static int tern_schedule_stalls(BlackwellIRProgram *p) { - static uint8_t target[BW_MAX_IR_INSNS + 1]; - uint64_t ready[BW_MAX_VREGS + 8]; - const size_t n = p->count; - memset(target, 0, sizeof target); - memset(ready, 0, sizeof ready); - for (size_t i = 0; i < n; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - if (in->op == BW_IR_BRA || in->op == BW_IR_BSSY) { - const long t = (long)i + (long)(int32_t)in->imm; - if (t < 0 || t > (long)n) return -1; - target[t] = 1; - } - } - uint64_t T = 0, all = 0; - for (size_t i = 0; i < n; i++) { - BlackwellIRInsn *in = &p->insns[i]; - const uint32_t s_emit = (in->control >> 9) & 0xfu; - if (tern_fixed(in->op)) { - int lo, c; tern_span(p, in->dst_vreg, &lo, &c); - for (int k = 0; k < c; k++) { if (lo + k >= BW_MAX_VREGS + 8) return -1; ready[lo + k] = T + OMEGA_TERN_FIXED_LAT; } - if (c && T + OMEGA_TERN_FIXED_LAT > all) all = T + OMEGA_TERN_FIXED_LAT; - } - uint64_t need = T + (tern_fixed(in->op) ? 1u : s_emit); - if (i + 1 < n) { - const BlackwellIRInsn *nx = &p->insns[i + 1]; - const int ops[4] = { nx->dst_vreg, nx->src1_vreg, nx->src2_vreg, nx->src3_vreg }; - for (int q = 0; q < 4; q++) { - int lo, c; tern_span(p, ops[q], &lo, &c); - for (int k = 0; k < c; k++) if (ready[lo + k] > need) need = ready[lo + k]; - } - if ((tern_control(nx->op) || target[i + 1]) && all > need) need = all; - } - const uint64_t s = need - T; - if (s > 15 || (s == 0 && (tern_fixed(in->op) || s_emit != 0))) return -1; /* stall 0 only where emitted (the final self-branch) */ - if (tern_fixed(in->op) || s > s_emit) in->control = (in->control & ~(0xfu << 9)) | ((uint32_t)s << 9); - T = need; - } - return 0; -} -int omega_blackwell_codegen_tern_gemv_prog(const OmegaTernGemvSpec *spec, BlackwellIRProgram *prog) { - if (!omega_tern_gemv_spec_ok(spec) || !prog) return -1; - const uint32_t K = spec->k, R = spec->rows, W = spec->warps, D = spec->depth, TH = 32u * W; - const uint32_t NCH = omega_tern_gemv_chunks(spec), KC = K / NCH, KSC = KC / 256u, KWC = KC / 16u; - const int block = spec->layout == OMEGA_TERN_LAYOUT_BLOCK, f32 = spec->epi == OMEGA_TERN_EPI_F32; - const uint32_t row_bytes = K / 4u; /* packed bytes per row (whole k) */ - const uint32_t step_bytes = block ? 128u * R : 64u; /* bytes a lane's weight pointer advances per K step */ - const uint32_t chunk_bytes = block ? KC * R / 2u : KC / 4u; /* ... and per chunk */ - const uint32_t npairs = spec->mutant == 3 ? 7u : 8u; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - Em *e = &em; - - /* ---- prologue ---- */ - int udesc = UV64(e), pwb = V64(e), px = V64(e), py = V64(e), ureg = V(e), stride = V(e), negn = V(e); - int tid = V(e), cx = V(e), warp = V(e), lane = V(e), h = V(e), l = V(e), one = V(e), t = V(e), nzl1 = V(e); - int u0 = V(e), u = V(e), xl = V(e), hR = V(e), lo = V(e), pl = V64(e), k0 = V(e); - int pws = NOREG, pas = NOREG, asv = NOREG, nb[3] = { NOREG, NOREG, NOREG }; - int chc = NOREG, mul = NOREG, prev = NOREG; - if (f32) { pws = V64(e); pas = V64(e); asv = V(e); for (int i = 0; i < 3; i++) nb[i] = V(e); } - if (NCH > 1) { chc = V(e); mul = V(e); prev = V(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pwb, OMEGA_TERN_ARG_W); ldc64(e, px, OMEGA_TERN_ARG_X); ldc64(e, py, OMEGA_TERN_ARG_Y); - ldc32(e, ureg, OMEGA_TERN_ARG_U); ldc32(e, stride, OMEGA_TERN_ARG_STRIDE); ldc32(e, negn, OMEGA_TERN_ARG_NEGN); - if (f32) { - ldc64(e, pws, OMEGA_TERN_ARG_WS); ldc64(e, pas, OMEGA_TERN_ARG_AS); - for (int i = 0; i < 3; i++) ldc32(e, nb[i], OMEGA_TERN_ARG_NEGB + 4u * (uint32_t)i); - } - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - movi(e, one, 1); - shr(e, warp, tid, 0, 5); - andi(e, lane, tid, 0, 31); - shr(e, h, lane, 0, 4); - andi(e, l, lane, 0, 15); - imadi(e, t, l, 0, 0xffffffffu, NOREG); /* -l */ - shr(e, t, t, 0, 31); /* 1 if l > 0 */ - imadi(e, nzl1, t, 0, 1, one); /* (l > 0) + 1 */ - imadi(e, u0, cx, 0, W, warp); /* first unit of this warp */ - imadi(e, xl, l, 0, 32, NOREG); /* shared byte offset of word c = l */ - imadi(e, hR, h, 0, R, NOREG); - if (block) { imadi(e, lo, l, 0, 8u * R, NOREG); imadi(e, lo, h, 0, 4u * R, lo); } - else { imadi(e, lo, l, 0, 4u, NOREG); imadi(e, lo, h, 0, R * row_bytes, lo); } - imadw(e, pl, lo, 1, pwb); /* this lane's weight pointer in unit 0, chunk 0 */ - movi(e, k0, 0x80008000u); - if (f32) ldg32(e, asv, pas, udesc, 1); - if (NCH > 1) { movi(e, chc, NCH); movrz(e, mul); } - - /* ---- chunk loop (NCH > 1 only for k > OMEGA_TERN_CHUNK_MAX): x staged per chunk, y accumulated in place ---- */ - const int L_c = here(e); - if (NCH > 1) { loop_begin(e); bar_sync(e); } - - /* ---- stage x: per word c of the chunk, X_j = x[16c+j] * 65536 + x[16c+j+8] (j < 8), 32 bytes ---- */ - { - const uint32_t rounds = (KWC + TH - 1) / TH; - int c = V(e), kwr = V(e), rc = V(e), pxa = V64(e), xq = V128(e), sb = V(e), va = V(e), vb = V(e), X = V(e), sad = V(e); - if (e->err) return -1; - movi(e, kwr, KWC); - imadi(e, c, tid, 0, 1, NOREG); - movi(e, rc, rounds); - const int L_s = here(e); - loop_begin(e); - isetp_ge_u32(e, c, kwr); - Region rg = region_begin(e); - imadw(e, pxa, c, 16u, px); - ldg_wide(e, BW_IR_LDG_E_128, xq, pxa, 0, udesc, 1); - imadi(e, sb, c, 0, 32u, NOREG); - for (uint32_t j = 0; j < 8; j++) { - const unsigned sh = 8u * (j & 3u); - int src[2] = { va, vb }; const unsigned sub[2] = { j >> 2, 2u + (j >> 2) }; - for (int q = 0; q < 2; q++) { - if (sh) { shr(e, src[q], xq, sub[q], sh); andi(e, src[q], src[q], 0, 0xffu); } - else andi(e, src[q], xq, sub[q], 0xffu); - andi(e, t, src[q], 0, 0x80u); - imadi(e, src[q], t, 0, 0xfffffffeu, src[q]); /* byte - 2 * (byte & 0x80): sign extension */ - } - imadi(e, X, va, 0, 65536u, vb); - if (spec->mutant == 1) imadi(e, X, X, 0, 0xffffffffu, NOREG); /* flipped planes: plus acts as minus */ - imadi(e, sad, one, 0, 4u * j, sb); - sts32(e, sad, X); - } - region_end(e, rg); - imadi(e, c, one, 0, TH, c); - imadi(e, rc, one, 0, 0xffffffffu, rc); - isetp_ge_u32(e, rc, one); - bra_if_p0(e, L_s); - loop_end(e); - bar_sync(e); - } - - /* ---- per-unit registers ---- */ - int rowbase = V(e), pw = V64(e), xlc = V(e), cnt = V(e); - int T[4], wq[16], wr[4][16], wa[4][16], xs[8], Ut[4], P[4], M[4], ap[4], am[4]; - int row = V(e), okr = V(e), skip = V(e), yv = V(e), f = V(e), wsv = V(e), pya = V64(e), pwsa = V64(e), sum = V(e); - for (uint32_t r = 0; r < R; r++) { T[r] = V(e); Ut[r] = V(e); P[r] = V(e); M[r] = V(e); ap[r] = V(e); am[r] = V(e); } - if (block) { for (uint32_t d = 0; d < D; d++) wq[d] = R == 4 ? V128(e) : V64(e); } - else for (uint32_t r = 0; r < R; r++) for (uint32_t d = 0; d < D; d++) { wr[r][d] = V(e); wa[r][d] = V64(e); } - for (uint32_t i = 0; i < (D <= 4u ? 2u * D : 2u); i++) xs[i] = V128(e); - if (e->err) return -1; - - /* ---- unit loop ---- */ - imadi(e, u, u0, 0, 1, NOREG); - const int L_u = here(e); - loop_begin(e); - isetp_ge_u32(e, u, ureg); - const int bra_end = bra_if_p0_fwd(e); - imadi(e, rowbase, u, 0, 2u * R, hR); - imadw(e, pw, u, 2u * R * row_bytes, pl); - imadi(e, xlc, xl, 0, 1, NOREG); - for (uint32_t r = 0; r < R; r++) movrz(e, T[r]); - movi(e, cnt, KSC / D); - - /* ---- K loop: D steps per iteration, every weight load issued before any use ---- - * Rows are interleaved stage by stage (shift, two masks, two multiply-adds for every row before the next pair) so - * independent work sits between each producer and its user; tern_schedule_stalls then sets every stall from the - * real register dependencies. For D <= 4 the staged x of all D steps is read from shared memory together with the - * weight loads (one wait per iteration); above that per step as before. */ - const int lds_up = D <= 4u; - const int L_k = here(e); - loop_begin(e); - if (block) { - for (uint32_t d = 0; d < D; d++) ldg_wide(e, R == 4 ? BW_IR_LDG_E_128 : BW_IR_LDG_E_64, wq[d], pw, d * step_bytes, udesc, d == 0); - } else { - for (uint32_t r = 0; r < R; r++) for (uint32_t d = 0; d < D; d++) imadw(e, wa[r][d], one, r * row_bytes + d * step_bytes, pw); - int first = 1; - for (uint32_t r = 0; r < R; r++) for (uint32_t d = 0; d < D; d++) { ldg32(e, wr[r][d], wa[r][d], udesc, first); first = 0; } - } - if (lds_up) for (uint32_t d = 0; d < D; d++) for (uint32_t i = 0; i < 2; i++) lds128(e, xs[2u * d + i], xlc, d * 512u + 16u * i, 0); - for (uint32_t d = 0; d < D; d++) { - const int *xd = lds_up ? &xs[2u * d] : xs; - if (!lds_up) for (uint32_t i = 0; i < 2; i++) lds128(e, xs[i], xlc, d * 512u + 16u * i, i == 0); - for (uint32_t j = 0; j < npairs; j++) { - for (uint32_t r = 0; r < R && j; r++) shr(e, Ut[r], block ? wq[d] : wr[r][d], block ? r : 0u, 2u * j); - for (uint32_t r = 0; r < R; r++) andi(e, P[r], j ? Ut[r] : (block ? wq[d] : wr[r][d]), j ? 0u : (block ? r : 0u), 0x00010001u); - for (uint32_t r = 0; r < R; r++) andi(e, M[r], j ? Ut[r] : (block ? wq[d] : wr[r][d]), j ? 0u : (block ? r : 0u), 0x00020002u); - for (uint32_t r = 0; r < R; r++) imadr(e, ap[r], P[r], xd[j >> 2], j & 3u, j == 0 ? k0 : ap[r]); /* + P * X_j */ - for (uint32_t r = 0; r < R; r++) imadr(e, am[r], M[r], xd[j >> 2], j & 3u, j == 0 ? k0 : am[r]); /* + M * X_j (minus bits one higher) */ - } - for (uint32_t r = 0; r < R; r++) shr(e, P[r], ap[r], 0, 16); /* 2^15 + plus dot of this word */ - for (uint32_t r = 0; r < R; r++) shr(e, M[r], am[r], 0, 17); /* 2^14 + minus dot of this word */ - for (uint32_t r = 0; r < R; r++) imadi(e, T[r], P[r], 0, 1, T[r]); - for (uint32_t r = 0; r < R; r++) imadi(e, T[r], M[r], 0, 0xffffffffu, T[r]); - } - imadw(e, pw, one, D * step_bytes, pw); - imadi(e, xlc, one, 0, D * 512u, xlc); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, L_k); - loop_end(e); - - /* ---- half-warp reduction (lanes 0 and 16 hold the sums), lane l == 0 stores rows < n ---- */ - for (uint32_t r = 0; r < R; r++) - for (uint32_t o = 8; o >= 1; o /= 2) { shfl_down(e, t, T[r], o); imadi(e, T[r], t, 0, 1, T[r]); } - for (uint32_t r = 0; r < R; r++) { - imadi(e, row, one, 0, r, rowbase); - imadi(e, okr, row, 0, 1, negn); - shr(e, okr, okr, 0, 31); /* 1 if row < n */ - imadi(e, skip, okr, 0, 0xffffffffu, nzl1); /* (l > 0) + 1 - (row < n): 0 only for a store */ - isetp_ge_u32(e, skip, one); - Region rg = region_begin(e); - imadi(e, yv, one, 0, 0u - KSC * (1u << 18), T[r]); /* y = T - KSC * 2^18 (mod 2^32, exact) */ - imadw(e, pya, row, 4u, py); - if (NCH > 1) { ldg32(e, prev, pya, udesc, 1); imadr(e, yv, prev, mul, 0, yv); } /* + earlier chunks */ - if (f32) { - for (int i = 0; i < 3; i++) { - imadi(e, t, row, 0, 1, nb[i]); - shr(e, t, t, 0, 31); /* 1 if row < b_i */ - if (i == 0) imadi(e, sum, t, 0, 1, NOREG); else imadi(e, sum, t, 0, 1, sum); - } - imadw(e, pwsa, sum, 4u, pws); /* ws_rev[boundaries above row] = w_scale[seg] */ - ldg32(e, wsv, pwsa, udesc, 1); - i2f(e, f, yv); - fmul(e, f, f, asv); - fmul(e, f, f, wsv); - stg(e, pya, 0, f, udesc); - } else stg(e, pya, 0, yv, udesc); - region_end(e, rg); - } - imadi(e, u, stride, 0, 1, u); - bra(e, L_u); - loop_end(e); - patch_bra(e, bra_end, here(e)); - - if (NCH > 1) { - imadw(e, px, one, KC, px); - imadw(e, pl, one, chunk_bytes, pl); - imadi(e, mul, one, 0, 1, NOREG); - imadi(e, chc, one, 0, 0xffffffffu, chc); - isetp_ge_u32(e, chc, one); - bra_if_p0(e, L_c); - loop_end(e); - } - tail(e); - if (e->err) return -1; - if (omega_bw_regalloc_solve(prog) != 0) return -1; - return tern_schedule_stalls(prog); -} - -int omega_tern_gemv_prog_stats(const OmegaTernGemvSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_tern_gemv_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} diff --git a/src/omega_blackwell_codegen_tern.h b/src/omega_blackwell_codegen_tern.h deleted file mode 100644 index 3fdf221e8..000000000 --- a/src/omega_blackwell_codegen_tern.h +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_TERN_H -#define OMEGA_BLACKWELL_CODEGEN_TERN_H -/* - * omega_blackwell_codegen_tern: KT1, the W2A8 ternary GEMV (m = 1) for the BitNet b1.58 lane (ternary engine design - * stage T0, 2026-10-15). New file; same emitter rules as omega_blackwell_codegen_bf16.c (every instruction waits on - * everything still pending, loads of one iteration issued back to back). - * - * y[r] = sum_c W[r][c] * x[c], W in {-1, 0, +1} (omega's 2-bit trit code), x int8, y int32, EXACT - * (the contract of oma_rz_oracle, src/algebra/realize_common.h). Optional f32 epilogue (below). - * - * Trit code (src/algebra/oma_trit.h): bit0 = plus plane, bit1 = minus plane, 0b11 invalid (the uploader refuses it). - * A 32-bit word holds 16 trits of one row, columns 16c .. 16c+15, trit i at bits 2i, 2i+1. - * - * Packed layouts (the uploader writes whichever the tensor was created with; n is padded with zero rows to a multiple - * of 8, kw = k / 16 words per row): - * OMEGA_TERN_LAYOUT_ROWMAJOR (0): word c of row r at byte (r * kw + c) * 4. - * OMEGA_TERN_LAYOUT_BLOCK (1): rows in blocks of 2R (R = spec.rows, 2 or 4); in block b, word c of block row j - * (j = h * R + i, h = 0/1) at byte b * 2R * kw * 4 + c * 2R * 4 + j * 4. One - * LDG.64 / LDG.128 gives a lane word c of R rows; a warp's step is 2R * 64 contiguous bytes. - * - * Thread mapping: a warp is two half-warps of 16 lanes (h = lane >> 4, l = lane & 15). Unit u = 2R consecutive rows; - * half h owns rows u * 2R + h * R + i (i < R). Per K step s (KS = k / 256 steps) lane l reads word c = 16 s + l of each of - * its rows. Warp w of CTA cx handles units cx * warps + w, + stride, ... < U (U = padded n / 2R). - * - * Arithmetic (exact, integer only; IMAD low 32 bits): the CTA stages x in shared memory as, per word c and pair - * j < 8, X_j = x[16c+j] * 65536 + x[16c+j+8] (signed): 32 bytes per c, 2 bytes per column. For a weight word W and - * pair j: U = W >> 2j, P = U & 0x00010001 (plus bits of trits j and j+8 at bits 0 and 16), M = U & 0x00020002 (minus - * bits at 1 and 17). accp += P * X_j, accm += M * X_j, both from K0 = 2^31 + 2^15. Mod 2^32 the high half of accp - * collects HP = sum (p_j x_j + p_{j+8} x_{j+8}) and its low half |LP| <= 1024 never borrows, so accp >> 16 (logical) is - * exactly 2^15 + HP; likewise accm >> 17 is exactly 2^14 + HM. Each lane adds (2^15 + HP) - (2^14 + HM) = 2^14 + dot - * per word to an int32 total T; a SHFL.DOWN tree (8, 4, 2, 1) sums its half; y = T - KSC * 2^18 (mod 2^32, exact - * because |y| <= 128 * k < 2^31). - * - * Shared memory: the launch descriptor allows at most OMEGA_BW_QMD_MAX_SHARED_BYTES (16 KiB) per CTA, so x is staged - * in chunks of at most OMEGA_TERN_CHUNK_MAX = 8192 columns (k <= 8192: one chunk; 8192 < k <= 16384: two equal chunks, - * k % 512 == 0). With two chunks each lane l == 0 adds the earlier chunk's int32 y it stored itself (same thread, same - * address, program order); the f32 epilogue is refused there. - * - * Epilogue: - * OMEGA_TERN_EPI_I32 (0): y int32. - * OMEGA_TERN_EPI_F32 (1): y f32 = ((float)y_int * a_scale) * w_scale[seg(r)], two round-to-nearest FMULs in that order. - * a_scale: one f32 device word (the activation dequantisation step, 1 / s_a; the producer writes it). - * seg(r) = number of boundaries b0 <= b1 <= b2 that are <= r (the API passes -b_i). w_scale: 4 f32 device words - * stored REVERSED (ws_rev[i] = w_scale[3 - i]) so the address is ws_rev + 4 * (count of boundaries above r). - * Per output segment, explicit boundaries (q|k|v: 2560, 3200, 3840): never ws_idx = r / (n / segments). - * - * Constant bank 0 argument words (cbank + 0x380): - * 0x380 w u64 packed weights 0x388 x u64 int8 x row (16-byte aligned, k bytes) - * 0x390 y u64 y (n words) 0x398 ws u64 w_scale reversed (f32 [4], EPI_F32) - * 0x3a0 as u64 a_scale (f32 word, EPI_F32) - * 0x3a8 U u32 units 0x3ac stride u32 units per warp iteration (grid_x * warps) - * 0x3b0 negn u32 -n (store rows < n) 0x3b4, 0x3b8, 0x3bc: -b0, -b1, -b2 - * - * mutant (tests only): 1 flips the planes (the staged X_j are negated: plus acts as minus, y becomes -y), 2 is host-side only - * (the API maps segments as ws_idx = r / (n / segments)), 3 drops pair j = 7 (trits 7 and 15 of every word). - */ -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_TERN_MAX_K 16384u -#define OMEGA_TERN_CHUNK_MAX 8192u -/* Cycles every user stays behind a fixed-latency producer (chip-proven rule: >= 5; omega_gpu_elementwise_api.c:13). - * The generator sets each stall from the register dependencies after allocation (tern_schedule_stalls). */ -#define OMEGA_TERN_FIXED_LAT 6u -#define OMEGA_TERN_LAYOUT_ROWMAJOR 0 -#define OMEGA_TERN_LAYOUT_BLOCK 1 -#define OMEGA_TERN_EPI_I32 0 -#define OMEGA_TERN_EPI_F32 1 -#define OMEGA_TERN_ARG_W 0x380u -#define OMEGA_TERN_ARG_X 0x388u -#define OMEGA_TERN_ARG_Y 0x390u -#define OMEGA_TERN_ARG_WS 0x398u -#define OMEGA_TERN_ARG_AS 0x3a0u -#define OMEGA_TERN_ARG_U 0x3a8u -#define OMEGA_TERN_ARG_STRIDE 0x3acu -#define OMEGA_TERN_ARG_NEGN 0x3b0u -#define OMEGA_TERN_ARG_NEGB 0x3b4u -#define OMEGA_TERN_ARGS_WORDS 16u -#define OMEGA_TERN_ROW_PAD 8u - -typedef struct { - uint32_t k; /* multiple of 256 (512 above 8192), <= OMEGA_TERN_MAX_K */ - uint32_t layout; /* OMEGA_TERN_LAYOUT_* */ - uint32_t rows; /* rows per half-warp R: row-major 1, 2, 4; block 2, 4 */ - uint32_t warps; /* 1 .. 32 */ - uint32_t depth; /* K steps per loop iteration: divides chunk / 256; rows * depth <= 16 */ - uint32_t epi; /* OMEGA_TERN_EPI_* */ - int mutant; /* 0 production; 1, 3 kernel mutants (2 is host-side, kernel identical to 0) */ -} OmegaTernGemvSpec; - -int omega_blackwell_codegen_tern_gemv_prog(const OmegaTernGemvSpec *spec, BlackwellIRProgram *prog); -int omega_tern_gemv_spec_ok(const OmegaTernGemvSpec *spec); -uint32_t omega_tern_gemv_steps(const OmegaTernGemvSpec *spec); /* k / 256 (0 when refused) */ -uint32_t omega_tern_gemv_shared_bytes(const OmegaTernGemvSpec *spec); /* 2 * chunk width */ -uint32_t omega_tern_gemv_chunks(const OmegaTernGemvSpec *spec); /* x chunks: 1 for k <= 8192, else 2 */ -int omega_tern_gemv_prog_stats(const OmegaTernGemvSpec *spec, uint32_t *insns, uint32_t *gprs); - -/* Byte offset of word c of padded row r in a packed tensor (layout, R = rows for the block layout). */ -uint64_t omega_tern_word_offset(uint32_t layout, uint32_t R, uint32_t k, uint32_t r, uint32_t c); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_blackwell_encoder.c b/src/omega_blackwell_encoder.c deleted file mode 100644 index dd039e891..000000000 --- a/src/omega_blackwell_encoder.c +++ /dev/null @@ -1,110 +0,0 @@ -#include "omega_blackwell_encoder.h" -#include "sha256.h" -#include - -/* - * Bit-for-bit verified sm_121 instruction sequence for unsigned 32-bit vector addition. - * Emits 32 instructions (512 bytes), aligned to 128 bytes. - */ -static const BlackwellInstruction VECADD_INSTRUCTIONS[OMEGA_BW_VECADD_INSN_COUNT] = { - /* 0000 */ { { 0xff017b82, 0x0000df00, 0x00000800, 0x000fe200 }, "LDC R1, c[0x0][0x37c]" }, - /* 0010 */ { { 0x00097919, 0x00000000, 0x00002500, 0x000e2200 }, "S2R R9, SR_CTAID.X" }, - /* 0020 */ { { 0xff0477ac, 0x00006c00, 0x08000800, 0x000e2200 }, "LDCU UR4, c[0x0][0x360]" }, - /* 0030 */ { { 0x00007919, 0x00000000, 0x00002100, 0x000e2200 }, "S2R R0, SR_TID.X" }, - /* 0040 */ { { 0xff0577ac, 0x00007300, 0x08000800, 0x000e6200 }, "LDCU UR5, c[0x0][0x398]" }, - /* 0050 */ { { 0x09097c24, 0x00000004, 0x0f8e0200, 0x001fca00 }, "IMAD R9, R9, UR4, R0" }, - /* 0060 */ { { 0x09007c0c, 0x00000005, 0x0bf06070, 0x002fda00 }, "ISETP.GE.U32.AND P0, PT, R9, UR5, PT" }, - /* 0070 */ { { 0x0000094d, 0x00000000, 0x03800000, 0x000fea00 }, "@P0 EXIT" }, - /* 0080 */ { { 0xff027b82, 0x0000e000, 0x00000a00, 0x000e2200 }, "LDC.64 R2, c[0x0][0x380]" }, - /* 0090 */ { { 0xff0477ac, 0x00006b00, 0x08000a00, 0x000e6e00 }, "LDCU.64 UR4, c[0x0][0x358]" }, - /* 00a0 */ { { 0xff047b82, 0x0000e200, 0x00000a00, 0x000eb000 }, "LDC.64 R4, c[0x0][0x388]" }, - /* 00b0 */ { { 0xff067b82, 0x0000e400, 0x00000a00, 0x000ee200 }, "LDC.64 R6, c[0x0][0x390]" }, - /* 00c0 */ { { 0x09027825, 0x00000004, 0x078e0002, 0x001fcc00 }, "IMAD.WIDE.U32 R2, R9, 0x4, R2" }, - /* 00d0 */ { { 0x02027981, 0x00000004, 0x0c1e1900, 0x002f2200 }, "LDG.E R2, desc[UR4][R2.64]" }, - /* 00e0 */ { { 0x09047825, 0x00000004, 0x078e0004, 0x004fcc00 }, "IMAD.WIDE.U32 R4, R9, 0x4, R4" }, - /* 00f0 */ { { 0x04057981, 0x00000004, 0x0c1e1900, 0x000f2200 }, "LDG.E R5, desc[UR4][R4.64]" }, - /* 0100 */ { { 0x09067825, 0x00000004, 0x078e0006, 0x008fe200 }, "IMAD.WIDE.U32 R6, R9, 0x4, R6" }, - /* 0110 */ { { 0x02097210, 0x00000005, 0x07ffe0ff, 0x010fca00 }, "IADD3 R9, PT, PT, R2, R5, RZ" }, - /* 0120 */ { { 0x06007986, 0x00000009, 0x0c101904, 0x000fe200 }, "STG.E desc[UR4][R6.64], R9" }, - /* 0130 */ { { 0x0000794d, 0x00000000, 0x03800000, 0x000fea00 }, "EXIT" }, - /* 0140 */ { { 0x00fc7947, 0xfffffffc, 0x0383ffff, 0x000fc000 }, "BRA (.L_x_0)" }, - /* 0150 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 0160 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 0170 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 0180 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 0190 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01a0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01b0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01c0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01d0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01e0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, - /* 01f0 */ { { 0x00007918, 0x00000000, 0x00000000, 0x000fc000 }, "NOP" }, -}; - -int omega_blackwell_encode_vecadd(uint8_t *code_buf, size_t max_len, size_t *out_len) { - if (!code_buf || max_len < OMEGA_BW_VECADD_CODE_SIZE) return -1; - - uint8_t *p = code_buf; - for (size_t i = 0; i < OMEGA_BW_VECADD_INSN_COUNT; i++) { - for (int w = 0; w < 4; w++) { - uint32_t val = VECADD_INSTRUCTIONS[i].w[w]; - p[0] = (uint8_t)(val & 0xFF); - p[1] = (uint8_t)((val >> 8) & 0xFF); - p[2] = (uint8_t)((val >> 16) & 0xFF); - p[3] = (uint8_t)((val >> 24) & 0xFF); - p += 4; - } - } - - if (out_len) *out_len = OMEGA_BW_VECADD_CODE_SIZE; - return 0; -} - -int omega_blackwell_compute_code_digest(const uint8_t *code_buf, size_t len, uint8_t *out_digest) { - if (!code_buf || len == 0 || !out_digest) return -1; - sha256_ctx ctx; - sha256_init(&ctx); - sha256_update(&ctx, code_buf, len); - sha256_final(&ctx, out_digest); - return 0; -} - -int omega_blackwell_verify_encoder_fixtures(void) { - uint8_t code_buf[OMEGA_BW_VECADD_CODE_SIZE]; - size_t out_len = 0; - if (omega_blackwell_encode_vecadd(code_buf, sizeof(code_buf), &out_len) != 0) { - return -1; - } - if (out_len != OMEGA_BW_VECADD_CODE_SIZE) { - return -1; - } - - uint8_t digest[32]; - if (omega_blackwell_compute_code_digest(code_buf, out_len, digest) != 0) { - return -1; - } - - static const char HEXDIGITS[] = "0123456789abcdef"; - char hex[65]; - for (int i = 0; i < 32; i++) { /* no sprintf: this file is part of the freestanding link target */ - hex[i * 2] = HEXDIGITS[digest[i] >> 4]; - hex[i * 2 + 1] = HEXDIGITS[digest[i] & 0x0f]; - } - hex[64] = 0; - - if (strcmp(hex, OMEGA_BW_VECADD_EXPECTED_SHA256) != 0) { - return -1; - } - - /* Verify critical instruction patterns: */ - /* 1. S2R R9, SR_CTAID.X */ - if (VECADD_INSTRUCTIONS[1].w[0] != 0x00097919) return -1; - /* 2. S2R R0, SR_TID.X */ - if (VECADD_INSTRUCTIONS[3].w[0] != 0x00007919) return -1; - /* 3. IADD3 R9, PT, PT, R2, R5, RZ */ - if (VECADD_INSTRUCTIONS[17].w[0] != 0x02097210) return -1; - /* 4. STG.E desc[UR4][R6.64], R9 */ - if (VECADD_INSTRUCTIONS[18].w[0] != 0x06007986) return -1; - - return 0; -} diff --git a/src/omega_blackwell_encoder.h b/src/omega_blackwell_encoder.h deleted file mode 100644 index 524e29df6..000000000 --- a/src/omega_blackwell_encoder.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef OMEGA_BLACKWELL_ENCODER_H -#define OMEGA_BLACKWELL_ENCODER_H - -#include -#include -#include - -#define OMEGA_BW_INSTRUCTION_BYTES 16 -#define OMEGA_BW_VECADD_INSN_COUNT 32 -#define OMEGA_BW_VECADD_CODE_SIZE (OMEGA_BW_VECADD_INSN_COUNT * OMEGA_BW_INSTRUCTION_BYTES) /* 512 bytes */ -#define OMEGA_BW_VECADD_EXPECTED_SHA256 "39f3dfdfc529a75a8274a27900acf4e7382b7f280a211e0412c51609f44b62a1" - -typedef struct { - uint32_t w[4]; - const char *mnemonic; -} BlackwellInstruction; - -/* Minimal sovereign encoder: emits 512-byte Blackwell sm_121 vector add machine code */ -int omega_blackwell_encode_vecadd(uint8_t *code_buf, size_t max_len, size_t *out_len); - -/* Computes SHA-256 digest of emitted machine code */ -int omega_blackwell_compute_code_digest(const uint8_t *code_buf, size_t len, uint8_t *out_digest); - -/* Verifies encoder instruction fixtures against reference bit-for-bit disassembled words */ -int omega_blackwell_verify_encoder_fixtures(void); - -#endif /* OMEGA_BLACKWELL_ENCODER_H */ diff --git a/src/omega_blackwell_engine.c b/src/omega_blackwell_engine.c deleted file mode 100644 index 32f0cd596..000000000 --- a/src/omega_blackwell_engine.c +++ /dev/null @@ -1,663 +0,0 @@ -/* - * Omega GPU Engine, Blackwell GB10 backend (cut A3b1). See - * src/omega_blackwell_engine.h and docs/numeric/OMEGA_GPU_ENGINE.md. - * - * This file is the backend function table (OmegaGpuBackend) that the engine - * core in src/omega_gpu_engine.c drives. The core owns the state machine, the - * poison comparison, the uncertain-completion block and the cleanup order. - * This file owns only the device calls. Each callback below says which lines of - * the launcher it was lifted from. "SUB@676f16f" means - * omega_blackwell_execute_vector in src/omega_blackwell_submit.c at commit - * 676f16f (the file before this cut). "ASTRA" means the first cut by GPT-6 - * Astra, src/omega_blackwell_engine.c at commit 21392ee on branch - * fix/omega-gpu-engine-first-cut. - * - * Roles. SCRATCH is the backend's own and holds four device buffers: the large - * pushbuffer (0x10000), the driver/argument constant bank (0x1000), the marker - * page (0x1000) and the QMD page (0x10000), the same sizes as SUB@676f16f - * lines 50, 59, 63, 64. PROGRAM, INPUT_A, INPUT_B and OUTPUT are page rounded - * with a 0x1000 minimum (SUB@676f16f lines 55-56, 58-62). - * - * L2 flush. The core has no separate callback for it, so build() emits the L2 - * flush and the second release marker (payload 0x46464646 at marker page + 0x10) - * inside the pushbuffer unless the job sets NO_C3, exactly as divsqrt does in - * src/omega_numeric_divsqrt_gb10.c:1145-1152. The wait_marker2 callback waits - * for that marker. The CPU side of the visibility rule (dsb sy before readback) - * is the barrier callback (divsqrt line 1171). - * - * One run at a time. The context is one static object because a retained run - * (uncertain completion, nothing freed, nothing closed) must keep its device - * memory reachable for the life of the process, and because the native context - * is about 225 KiB (Nvrm in physics/nvrm/nvrm.h). A second open while a run is - * active fails with DEVICE_OPEN. - * - * NOT_RUN: this file has not been compiled or executed by its author. - */ -#include "omega_blackwell_engine.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include "m16_native.h" - -#include -#include -#include -#include -#include -#include -#include - -#define BE_PB_CAP 1024u /* pushbuffer words, SUB@676f16f line 131 (uint32_t pb[1024]) */ -#define BE_PAGE 0x1000u -#define BE_PB_BYTES 0x10000u /* SUB@676f16f line 50 */ -#define BE_QMD_BYTES 0x10000u /* SUB@676f16f line 64 */ -#define BE_SEM_OFFSET 0x2000u /* sem_va = qmd page + 0x2000, SUB@676f16f line 99 */ -#define BE_MARKER2_OFFSET 0x10u /* divsqrt line 1113 and 1152 */ -#define BE_MARKER2_PAYLOAD 0x46464646u /* divsqrt line 1152 */ - -typedef struct { - M16NativeContext m; - NvrmMem pb; /* SCRATCH part 1: large pushbuffer */ - NvrmMem cbank; /* SCRATCH part 2 */ - NvrmMem marker; /* SCRATCH part 3 */ - NvrmMem qmd; /* SCRATCH part 4 (QMD0, QMD1, semaphore) */ - NvrmMem buf[OMEGA_GPU_BUF_ROLE_COUNT]; /* PROGRAM, INPUT_A, INPUT_B, OUTPUT (SCRATCH slot unused) */ - int native_open; /* m16_native_open was attempted this run */ - int pb_replaced; /* m.pb_mem now points at the large pushbuffer */ - int c3; /* L2 flush and second marker are in the pushbuffer */ - volatile uint32_t *hmarker; /* NULL until build zeroes it; NULL again once SCRATCH is freed */ - volatile uint32_t *hmarker2; - volatile uint32_t *hsem; - uint32_t pb_words[BE_PB_CAP]; - size_t pb_len; - int pb_overflow; - int last_rc; /* raw driver code of the most recent callback */ - char text[OMEGA_GPU_ENGINE_DRV_TEXT_BYTES]; /* backend's own message, "" when none */ - OmegaBlackwellEngineRunInfo info; -} BeCtx; - -static BeCtx g_be; -static atomic_flag g_busy = ATOMIC_FLAG_INIT; - -static uint64_t now_ns(void) -{ - struct timespec t; - if (clock_gettime(CLOCK_MONOTONIC, &t) != 0) return 0u; - return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; -} - -/* Bounded copy that never reads past a NUL and always terminates. */ -static void copy_text(char *dst, size_t cap, const char *src) -{ - size_t i = 0; - if (cap == 0) return; - while (i + 1u < cap && src[i] != '\0') { - dst[i] = src[i]; - i++; - } - dst[i] = '\0'; -} - -static void note(BeCtx *c, const char *msg) -{ - copy_text(c->text, sizeof c->text, msg); -} - -/* Start of every callback that can fail: forget the previous callback's code and text. */ -static void begin(BeCtx *c) -{ - c->last_rc = 0; - c->text[0] = '\0'; -} - -/* ---- allocation helpers ------------------------------------------------ */ - -/* Allocates and checks one device buffer. The post-allocation checks (CPU - * mapping present, size at least what was asked, 256-byte aligned GPU address) - * come from ASTRA checked_alloc. Returns 0 or non-zero. */ -static int alloc_checked(BeCtx *c, uint64_t bytes, NvrmMem *m) -{ - int rc; - memset(m, 0, sizeof *m); - /* GB10: the CPU rewrites pushbuffers and reads markers/outputs; GPU-cacheable system memory is not - * coherent with CPU mappings (nvos.h:1117-1118). All engine buffers are GPU-uncached until the - * allocator default is flipped (hive idea I36). */ - rc = nvrm_alloc_gpu_uncached(&c->m.rm, bytes, m); - if (rc != 0) { - c->last_rc = rc; - memset(m, 0, sizeof *m); - return rc; - } - if (!m->cpu || m->size < bytes || (m->va & 255u) != 0) { - note(c, "allocation failed its own checks (CPU mapping, size or 256-byte alignment)"); - (void)nvrm_free(&c->m.rm, m); - memset(m, 0, sizeof *m); - return -1; - } - return 0; -} - -/* Page rounding with a 0x1000 minimum, SUB@676f16f lines 55-56. Non-zero if bytes is 0 or overflows. */ -static int round_pages(size_t bytes, uint64_t *out) -{ - uint64_t v; - if (bytes == 0 || (uint64_t)bytes > UINT64_MAX - (BE_PAGE - 1u)) return -1; - v = ((uint64_t)bytes + (BE_PAGE - 1u)) & ~(uint64_t)(BE_PAGE - 1u); - if (v < BE_PAGE) v = BE_PAGE; - *out = v; - return 0; -} - -static NvrmMem *role_mem(BeCtx *c, int role) -{ - if (role < (int)OMEGA_GPU_BUF_PROGRAM || role >= (int)OMEGA_GPU_BUF_ROLE_COUNT) return NULL; - return &c->buf[role]; -} - -/* Frees the four SCRATCH buffers, every one even if an earlier one fails. - * Returns 0, or the first non-zero nvrm_free code. */ -static int release_scratch(BeCtx *c) -{ - NvrmMem *parts[4]; - int first = 0; - size_t i; - parts[0] = &c->qmd; - parts[1] = &c->marker; - parts[2] = &c->cbank; - parts[3] = &c->pb; - /* The marker and semaphore words live in these buffers: stop reading them first. */ - c->hmarker = NULL; - c->hmarker2 = NULL; - c->hsem = NULL; - for (i = 0; i < 4u; i++) { - int rc = nvrm_free(&c->m.rm, parts[i]); /* a zeroed NvrmMem is a no-op (nvrm.h) */ - if (rc != 0 && first == 0) first = rc; - } - if (c->pb_replaced) { - memset(&c->m.pb_mem, 0, sizeof c->m.pb_mem); - c->pb_replaced = 0; - } - return first; -} - -/* ---- pushbuffer helpers ------------------------------------------------ */ - -static void pb_put(BeCtx *c, uint32_t w) -{ - if (c->pb_len < BE_PB_CAP) c->pb_words[c->pb_len++] = w; - else c->pb_overflow = 1; -} - -static void pb_copy(BeCtx *c, const uint32_t *w, size_t n) -{ - size_t i; - for (i = 0; i < n; i++) pb_put(c, w[i]); -} - -/* Compute class and engine setup methods, SUB@676f16f lines 12-16 (also in divsqrt as SETUP). */ -static const uint32_t BE_SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - -/* ---- callbacks --------------------------------------------------------- */ - -/* Opens the RM client. Resets every bit of the context first so an open - * failure never reports values from an earlier run (ASTRA did memset(&ctx) at - * the same point). The busy flag stays set until be_close. */ -static int be_open_device(void *ctx) -{ - BeCtx *c = (BeCtx *)ctx; - int rc; - if (atomic_flag_test_and_set(&g_busy)) return -1; /* another run is active; touch nothing */ - memset(c, 0, sizeof *c); - c->native_open = 1; - rc = m16_native_open(&c->m); /* SUB@676f16f line 45 */ - if (rc != 0) { - c->last_rc = rc; - atomic_flag_clear(&g_busy); /* native open already cleaned up after itself (m16_native.c:15-21) */ - return rc; - } - return 0; -} - -static int be_create_channel(void *ctx) -{ - BeCtx *c = (BeCtx *)ctx; - int rc; - begin(c); - rc = m16_native_create_channel(&c->m); /* SUB@676f16f line 46 */ - c->last_rc = rc; - return rc; -} - -static int be_alloc(void *ctx, int role, size_t bytes) -{ - BeCtx *c = (BeCtx *)ctx; - NvrmMem *m; - uint64_t sz; - begin(c); - if (role == (int)OMEGA_GPU_BUF_SCRATCH) { - if (alloc_checked(c, BE_PB_BYTES, &c->pb) != 0 || - alloc_checked(c, BE_PAGE, &c->cbank) != 0 || - alloc_checked(c, BE_PAGE, &c->marker) != 0 || - alloc_checked(c, BE_QMD_BYTES, &c->qmd) != 0) { - int rc = c->last_rc ? c->last_rc : -1; - int saved_errno = errno; /* the core reads errno right after this callback */ - char keep[OMEGA_GPU_ENGINE_DRV_TEXT_BYTES]; - copy_text(keep, sizeof keep, c->text); - (void)release_scratch(c); /* the core does not free a role whose alloc failed */ - copy_text(c->text, sizeof c->text, keep); - c->last_rc = rc; - errno = saved_errno; - return rc; - } - c->m.pb_mem = c->pb; /* the unified method stream needs the large ring, SUB@676f16f lines 49-51 */ - c->pb_replaced = 1; - return 0; - } - m = role_mem(c, role); - if (!m) { - note(c, "alloc: unknown buffer role"); - return -1; - } - if (round_pages(bytes, &sz) != 0) { - note(c, "alloc: byte count is zero or too large"); - return -1; - } - return alloc_checked(c, sz, m); -} - -static int be_copy_in(void *ctx, int role, const void *src, size_t bytes) -{ - BeCtx *c = (BeCtx *)ctx; - NvrmMem *m; - begin(c); - m = role_mem(c, role); - if (!m || !m->cpu || !src || (uint64_t)bytes > m->size) { - note(c, "copy_in: bad role, buffer or length"); - return -1; - } - memcpy(m->cpu, src, bytes); /* SUB@676f16f lines 74-76 (code via the encoder, inputs via memcpy) */ - return 0; -} - -static int be_fill_poison(void *ctx, const uint32_t *words, size_t count) -{ - BeCtx *c = (BeCtx *)ctx; - NvrmMem *out = &c->buf[OMEGA_GPU_BUF_OUTPUT]; - begin(c); - if (!out->cpu || !words || (uint64_t)count * 4u > out->size) { - note(c, "fill_poison: no output buffer or length too large"); - return -1; - } - memcpy(out->cpu, words, count * 4u); /* SUB@676f16f lines 77-80: pre-fill the device output */ - return 0; -} - -/* Descriptors, QMDs and the whole pushbuffer. Lifted from SUB@676f16f lines - * 83-194 and, for the C3 tail, divsqrt lines 1145-1152. Zeroes the marker and - * semaphore words and issues dsb sy (SUB@676f16f lines 124-128). Does not submit. */ -static int be_build(void *ctx, const OmegaGpuJob *job) -{ - BeCtx *c = (BeCtx *)ctx; - const NvrmMem *code = &c->buf[OMEGA_GPU_BUF_PROGRAM]; - const NvrmMem *a = &c->buf[OMEGA_GPU_BUF_INPUT_A]; - const NvrmMem *b = &c->buf[OMEGA_GPU_BUF_INPUT_B]; - const NvrmMem *out = &c->buf[OMEGA_GPU_BUF_OUTPUT]; - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - uint32_t cbank_args[OMEGA_BW_CBANK_ARGS_WORDS]; - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS]; - uint32_t qmd1_words[OMEGA_BW_QMD_WORDS]; - OmegaBlackwellQmdConfig cfg; - uint64_t qmd0_va, qmd1_va, sem_va, marker_va, marker2_va, need; - uint32_t n; - int rc; - - begin(c); - if (!job || job->layout != (int)OMEGA_GPU_LAYOUT_VECTOR_1D) { - note(c, "build: only the VECTOR_1D layout is supported"); - return -1; - } - n = job->element_count; - /* (n + 63) / 64 must not overflow; ASTRA refused n above UINT32_MAX - 63 as well. */ - if (n == 0 || n > UINT32_MAX - 63u) { - note(c, "build: element count is zero or too large"); - return -1; - } - need = (uint64_t)n * 4u; - if (!code->cpu || !a->cpu || !b->cpu || !out->cpu || !c->pb.cpu || !c->cbank.cpu || - !c->marker.cpu || !c->qmd.cpu || a->size < need || b->size < need || out->size < need) { - note(c, "build: a buffer is missing or too small"); - return -1; - } - c->c3 = (job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0; - - qmd0_va = c->qmd.va; - qmd1_va = c->qmd.va + 0x1000; - sem_va = c->qmd.va + BE_SEM_OFFSET; - marker_va = c->marker.va; - marker2_va = c->marker.va + BE_MARKER2_OFFSET; - - memset(&cfg, 0, sizeof cfg); - cfg.code_va = code->va; - cfg.cbank_va = c->cbank.va; - cfg.scratch_va = c->qmd.va + 0x4000; /* SUB@676f16f line 100 */ - cfg.sem_va = sem_va; - cfg.qmd0_va = qmd0_va; - cfg.qmd1_va = qmd1_va; - cfg.num_elements = n; - cfg.threads_per_block = 64; - cfg.grid_width = (n + 63u) / 64u; - - /* The builders return 0 on success (src/omega_blackwell_qmd.c); SUB@676f16f - * ignored their codes, ASTRA checked them. Checked here. */ - rc = omega_blackwell_build_cbank_driver(cbank_data, c->cbank.va); - if (rc == 0) rc = omega_blackwell_build_cbank_args(cbank_args, a->va, b->va, out->va, n); - if (rc == 0) rc = omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - if (rc == 0) rc = omega_blackwell_build_qmd1(qmd1_words, &cfg); - if (rc == 0) rc = omega_blackwell_verify_qmd_invariants(qmd1_words); /* SUB@676f16f line 118 */ - if (rc != 0) { - c->last_rc = rc; - note(c, "build: a descriptor builder or the QMD invariant check refused"); - return rc; - } - /* Extra QMD1 checks from ASTRA: release enable (word 9), the release - * semaphore address and the DONE value (words 15-17), and the memory - * barrier flags (word 19). The words come from src/omega_blackwell_qmd.c - * lines 81, 93-98. */ - if (qmd1_words[9] != 3u || qmd1_words[15] != (uint32_t)sem_va || - qmd1_words[16] != (uint32_t)(sem_va >> 32) || - qmd1_words[17] != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE || - qmd1_words[19] != 0x81810000u) { - note(c, "build: QMD1 release words do not match the expected layout"); - return -1; - } - - memcpy(c->cbank.cpu, cbank_data, sizeof cbank_data); /* SUB@676f16f line 112 */ - memcpy((uint8_t *)c->cbank.cpu + 0x380, cbank_args, sizeof cbank_args); /* line 113 */ - memcpy(c->qmd.cpu, qmd0_words, sizeof qmd0_words); /* line 120 */ - memcpy((uint8_t *)c->qmd.cpu + 0x1000, qmd1_words, sizeof qmd1_words); /* line 121 */ - - /* Initialise the synchronisation words in coherent memory (lines 124-128; - * divsqrt also zeroes the second marker, line 1113). Then dsb sy so the - * zeros are visible to the chip before the doorbell. */ - c->hsem = (volatile uint32_t *)((uint8_t *)c->qmd.cpu + BE_SEM_OFFSET); - c->hmarker = (volatile uint32_t *)c->marker.cpu; - c->hmarker2 = (volatile uint32_t *)((uint8_t *)c->marker.cpu + BE_MARKER2_OFFSET); - *c->hsem = 0; - *c->hmarker = 0; - *c->hmarker2 = 0; - if (!c->c3) c->hmarker2 = NULL; /* never waited for, never reported */ - __asm__ volatile("dsb sy" ::: "memory"); - - /* ---- unified pushbuffer, SUB@676f16f lines 130-195 ---- */ - c->pb_len = 0; - c->pb_overflow = 0; - - /* 1. setup words (18) */ - pb_copy(c, BE_SETUP_WORDS, 18u); - - /* 2. driver constant bank upload (224 words by DMA) */ - pb_put(c, nvrm_mthd(1, 0x0188, 2)); - pb_put(c, (uint32_t)(c->cbank.va >> 32)); - pb_put(c, (uint32_t)c->cbank.va); - pb_put(c, nvrm_mthd(1, 0x0180, 2)); - pb_put(c, 0x00000380); - pb_put(c, 0x00000001); - pb_put(c, nvrm_mthd(1, 0x01b0, 1)); - pb_put(c, 0x00000041); - pb_put(c, (uint32_t)((224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28))); - pb_copy(c, cbank_data, 224u); - - /* 3. kernel argument upload (7 words by DMA) */ - pb_put(c, nvrm_mthd(1, 0x0188, 2)); - pb_put(c, (uint32_t)((c->cbank.va + 0x380) >> 32)); - pb_put(c, (uint32_t)(c->cbank.va + 0x380)); - pb_put(c, nvrm_mthd(1, 0x0180, 2)); - pb_put(c, 0x0000001c); - pb_put(c, 0x00000001); - pb_put(c, nvrm_mthd(1, 0x01b0, 1)); - pb_put(c, 0x00000041); - pb_put(c, (uint32_t)((7 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28))); - pb_copy(c, cbank_args, 7u); - - /* 4. inline QMD 0 (2 address words + 96 QMD words) */ - pb_put(c, (uint32_t)((98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28))); - pb_put(c, (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff)); - pb_put(c, (uint32_t)(qmd0_va >> 8)); - pb_copy(c, qmd0_words, 96u); - - /* 5. intermediate semaphore initial value (one word by DMA) */ - pb_put(c, nvrm_mthd(1, 0x0188, 2)); - pb_put(c, (uint32_t)(sem_va >> 32)); - pb_put(c, (uint32_t)sem_va); - pb_put(c, nvrm_mthd(1, 0x0180, 2)); - pb_put(c, 0x00000004); - pb_put(c, 0x00000001); - pb_put(c, nvrm_mthd(1, 0x01b0, 1)); - pb_put(c, 0x00000041); - pb_put(c, (uint32_t)((1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28))); - pb_put(c, OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT); - - /* 6. inline QMD 1 */ - pb_put(c, (uint32_t)((98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28))); - pb_put(c, (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff)); - pb_put(c, (uint32_t)(qmd1_va >> 8)); - pb_copy(c, qmd1_words, 96u); - - /* 7. subchannel 0 completion release (RELEASE | WFI) */ - pb_put(c, nvrm_mthd(0, 0x005c, 5)); - pb_put(c, (uint32_t)marker_va); - pb_put(c, (uint32_t)(marker_va >> 32)); - pb_put(c, OMEGA_BW_MARKER_COMPLETION_PAYLOAD); - pb_put(c, 0); - pb_put(c, 0x1u | (1u << 20)); - - /* 8. C3, divsqrt lines 1145-1152 (NVC96F_MEM_OP_A..D = 0x28..0x34, operation - * L2_FLUSH_DIRTY 0x10 in bits 31:27; third_party/nvidia-open-580.173.02/src/ - * common/sdk/nvidia/inc/class/clc96f.h:36-73): flush the L2, then a second - * WFI release at marker page + 0x10 that the host waits for before readback. */ - if (c->c3) { - pb_put(c, nvrm_mthd(0, 0x0028, 4)); - pb_put(c, 0); - pb_put(c, 0); - pb_put(c, 0); - pb_put(c, 0x10u << 27); - pb_put(c, nvrm_mthd(0, 0x005c, 5)); - pb_put(c, (uint32_t)marker2_va); - pb_put(c, (uint32_t)(marker2_va >> 32)); - pb_put(c, BE_MARKER2_PAYLOAD); - pb_put(c, 0); - pb_put(c, 0x1u | (1u << 20)); - } - - if (c->pb_overflow) { - note(c, "build: pushbuffer exceeded its word capacity"); - return -1; - } - return 0; -} - -/* Submit methods to the GPFIFO ring and ring the doorbell, SUB@676f16f lines - * 198-200. m16_native_submit_methods rings only after the enqueue succeeded - * (physics/m16/m16_native.c:76-84), so a non-zero return means the doorbell - * was not rung: a known failure, not an uncertain completion. */ -static int be_submit(void *ctx) -{ - BeCtx *c = (BeCtx *)ctx; - int rc; - begin(c); - if (c->pb_len == 0) { - note(c, "submit: nothing was built"); - return -1; - } - c->info.launch_ns = now_ns(); /* SUB@676f16f line 199 */ - rc = m16_native_submit_methods(&c->m, c->pb_words, c->pb_len); - c->last_rc = rc; - return rc; -} - -/* Waits for one coherent word. m16_native_wait_marker is a ">=" serial compare - * (physics/m16/m16_native.c:93-108), so an overshoot also returns 0; ASTRA - * checked_alloc/checked_wait therefore re-checked equality, kept here and - * reported as UNKNOWN_STATE (the device wrote a value we cannot classify). - * Returns 0, OMEGA_GPU_BACKEND_TIMEOUT, OMEGA_GPU_BACKEND_UNKNOWN_STATE or a - * driver fault. *snap always receives the last value read. */ -static int wait_word(BeCtx *c, volatile uint32_t *w, uint32_t want, uint64_t ms, uint32_t *snap) -{ - int rc; - begin(c); - if (!w) { - note(c, "wait: the word is not mapped (wait before build or after free)"); - return -2; - } - rc = m16_native_wait_marker(w, want, ms); - *snap = *w; - if (rc != 0) { - c->last_rc = rc; - return rc == -1 ? OMEGA_GPU_BACKEND_TIMEOUT : -2; - } - if (*snap != want) { - (void)snprintf(c->text, sizeof c->text, "observed 0x%08x, wanted 0x%08x", *snap, want); - return OMEGA_GPU_BACKEND_UNKNOWN_STATE; - } - return 0; -} - -static int be_wait_marker(void *ctx, uint64_t timeout_ms) -{ - BeCtx *c = (BeCtx *)ctx; - int rc = wait_word(c, c->hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, timeout_ms, &c->info.marker); - if (rc == 0) c->info.marker_done_ns = now_ns(); /* SUB@676f16f line 204 */ - return rc; -} - -static int be_wait_marker2(void *ctx, uint64_t timeout_ms) -{ - BeCtx *c = (BeCtx *)ctx; - return wait_word(c, c->hmarker2, BE_MARKER2_PAYLOAD, timeout_ms, &c->info.marker2); -} - -/* The QMD's own release semaphore, written after the grid finishes (divsqrt - * lines 1163-1169). SUB@676f16f only compared it once (line 207); now it is waited for. */ -static int be_wait_release_semaphore(void *ctx, uint64_t timeout_ms) -{ - BeCtx *c = (BeCtx *)ctx; - return wait_word(c, c->hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, timeout_ms, - &c->info.semaphore); -} - -/* dsb sy before readback, divsqrt line 1171. Completion is already known here. */ -static int be_barrier(void *ctx, uint64_t timeout_ms) -{ - BeCtx *c = (BeCtx *)ctx; - (void)timeout_ms; - begin(c); - __asm__ volatile("dsb sy" ::: "memory"); - return 0; -} - -static int be_copy_out(void *ctx, void *dst, size_t bytes) -{ - BeCtx *c = (BeCtx *)ctx; - const NvrmMem *out = &c->buf[OMEGA_GPU_BUF_OUTPUT]; - begin(c); - if (!out->cpu || !dst || (uint64_t)bytes > out->size) { - note(c, "copy_out: no output buffer or length too large"); - return -1; - } - memcpy(dst, out->cpu, bytes); /* SUB@676f16f line 210 */ - return 0; -} - -/* Driver code, driver text and the sync words as they are right now. Words are - * read only while SCRATCH is still mapped (hmarker and friends are NULL before - * build and after SCRATCH is freed), so this is safe during cleanup. */ -static void be_diagnostics(void *ctx, OmegaGpuBackendDiag *d) -{ - BeCtx *c = (BeCtx *)ctx; - d->drv_rc = c->last_rc; - if (c->text[0] != '\0') copy_text(d->drv_text, sizeof d->drv_text, c->text); - else if (c->native_open) copy_text(d->drv_text, sizeof d->drv_text, c->m.rm.err); - if (c->hmarker) { - d->marker = *c->hmarker; - d->sync_valid |= OMEGA_GPU_SYNC_MARKER; - } - if (c->hmarker2) { - d->marker2 = *c->hmarker2; - d->sync_valid |= OMEGA_GPU_SYNC_MARKER2; - } - if (c->hsem) { - d->semaphore[0] = *c->hsem; - d->sync_valid |= OMEGA_GPU_SYNC_SEMAPHORE; - } -} - -/* Real nvrm_free per buffer. SUB@676f16f never freed (m16_native_close frees - * everything left, nvrm.c:757-766); nvrm_free before close is already used by - * src/omega_accelerator_world.c (A1b scout, section 4). DIVERGENCE, chip - * behaviour of free-then-close for this launcher is UNVERIFIED (confidence 70%). */ -static int be_free_buf(void *ctx, int role) -{ - BeCtx *c = (BeCtx *)ctx; - NvrmMem *m; - int rc; - begin(c); - if (role == (int)OMEGA_GPU_BUF_SCRATCH) { - rc = release_scratch(c); - c->last_rc = rc; - return rc; - } - m = role_mem(c, role); - if (!m) { - note(c, "free: unknown buffer role"); - return -1; - } - rc = nvrm_free(&c->m.rm, m); - c->last_rc = rc; - return rc; -} - -static int be_close(void *ctx) -{ - BeCtx *c = (BeCtx *)ctx; - int rc; - begin(c); - c->hmarker = NULL; - c->hmarker2 = NULL; - c->hsem = NULL; - rc = m16_native_close(&c->m); /* SUB@676f16f line 225 */ - c->last_rc = rc; - atomic_flag_clear(&g_busy); - return rc; -} - -static const OmegaGpuBackend g_backend = { - &g_be, - be_open_device, - be_create_channel, - be_alloc, - be_copy_in, - be_fill_poison, - be_build, - be_submit, - be_wait_marker, - be_wait_marker2, - be_wait_release_semaphore, - be_barrier, - be_copy_out, - be_diagnostics, - be_free_buf, - be_close, -}; - -const OmegaGpuBackend *omega_blackwell_engine_backend(void) -{ - return &g_backend; -} - -void omega_blackwell_engine_run_info(OmegaBlackwellEngineRunInfo *out) -{ - if (out) *out = g_be.info; -} diff --git a/src/omega_blackwell_engine.h b/src/omega_blackwell_engine.h deleted file mode 100644 index 4f94ca6c3..000000000 --- a/src/omega_blackwell_engine.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Omega GPU Engine, Blackwell GB10 backend (cut A3b1). - * - * This module is ONLY the device side of the engine. The public entry point is - * omega_gpu_execute in src/omega_gpu_engine.c (the A3a core); this file supplies - * the backend function table that the core drives (OmegaGpuBackend, declared in - * src/omega_gpu_engine.h). It does not define any job, result or execute type. - * - * Origin: the device sequence (open, channel, allocations, descriptor and QMD - * build, pushbuffer, submit, waits, copy-out, close) was seeded from the first - * cut by GPT-6 Astra (branch fix/omega-gpu-engine-first-cut, commit 21392ee, - * src/omega_blackwell_engine.c) and from omega_blackwell_execute_vector as it - * stood at 676f16f. See docs/numeric/OMEGA_GPU_ENGINE.md, section Origin. - * - * Usage: - * omega_gpu_engine_set_backend(omega_blackwell_engine_backend()); - * rc = omega_gpu_execute(&job, &result); - * Only the VECTOR_1D layout (two inputs, one output, 64 threads per block) is - * supported. One run at a time: the backend keeps one process-wide context and - * a second open while a run is active is refused as DEVICE_OPEN. - * - * Observed values on success: the core only copies driver diagnostics on a - * failure, and the core frees and closes the device (which unmaps the marker - * and semaphore memory) before it returns. So the backend snapshots what it saw - * inside its own wait callbacks, and omega_blackwell_engine_run_info returns - * that snapshot after a run. The vector wrapper in omega_blackwell_submit.c - * uses it to fill completion_marker, intermediate_semaphore and the timestamps. - * - * STATUS: DRAFT. Host NOT_RUN, chip NOT_RUN. Nothing here has been compiled or - * executed by its author. - */ -#ifndef OMEGA_BLACKWELL_ENGINE_H -#define OMEGA_BLACKWELL_ENGINE_H - -#include "omega_gpu_engine.h" - -#include - -/* What the backend observed during the most recent run (valid after the run). */ -typedef struct { - uint64_t launch_ns; /* CLOCK_MONOTONIC, just before the pushbuffer submit; 0 if never submitted */ - uint64_t marker_done_ns; /* CLOCK_MONOTONIC, just after the first marker wait succeeded; 0 if it did not */ - uint32_t marker; /* first marker word as observed by the wait (0x44444444 on success) */ - uint32_t marker2; /* second marker word as observed (0x46464646 on success, 0 with NO_C3) */ - uint32_t semaphore; /* QMD release semaphore word as observed (6 on success) */ -} OmegaBlackwellEngineRunInfo; - -/* The process-wide Blackwell backend table. Never NULL. The ctx inside it is - * the backend's static context; callers must not touch it. */ -const OmegaGpuBackend *omega_blackwell_engine_backend(void); - -/* Copies the snapshot of the most recent run into *out. Reset at every open. */ -void omega_blackwell_engine_run_info(OmegaBlackwellEngineRunInfo *out); - -#endif diff --git a/src/omega_blackwell_matmul.c b/src/omega_blackwell_matmul.c deleted file mode 100644 index be88ee15e..000000000 --- a/src/omega_blackwell_matmul.c +++ /dev/null @@ -1,189 +0,0 @@ -#include "omega_blackwell_matmul.h" -#include "sha256.h" -#ifndef OMEGA_GPU_NO_POSIX -#include -#endif -#include - -int omega_matmul_spec_init(OmegaMatMulSpec *spec, uint32_t m, uint32_t k, uint32_t n, OmegaMatMulPrecision precision) { - if (!spec || m == 0 || k == 0 || n == 0) return -1; - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return -1; - - spec->m = m; - spec->k = k; - spec->n = n; - spec->precision = precision; - - /* Canonical spec_id computed over (m, k, n, precision) */ - uint8_t spec_buf[16]; - spec_buf[0] = (uint8_t)(m & 0xff); - spec_buf[1] = (uint8_t)((m >> 8) & 0xff); - spec_buf[2] = (uint8_t)((m >> 16) & 0xff); - spec_buf[3] = (uint8_t)((m >> 24) & 0xff); - - spec_buf[4] = (uint8_t)(k & 0xff); - spec_buf[5] = (uint8_t)((k >> 8) & 0xff); - spec_buf[6] = (uint8_t)((k >> 16) & 0xff); - spec_buf[7] = (uint8_t)((k >> 24) & 0xff); - - spec_buf[8] = (uint8_t)(n & 0xff); - spec_buf[9] = (uint8_t)((n >> 8) & 0xff); - spec_buf[10] = (uint8_t)((n >> 16) & 0xff); - spec_buf[11] = (uint8_t)((n >> 24) & 0xff); - - spec_buf[12] = (uint8_t)(precision & 0xff); - spec_buf[13] = 0; - spec_buf[14] = 0; - spec_buf[15] = 0; - - sha256_hash(spec_buf, sizeof(spec_buf), spec->spec_id); - return 0; -} - -int omega_matmul_cpu_oracle_i32(const uint32_t *a, const uint32_t *b, uint32_t *c, uint32_t m, uint32_t k, uint32_t n) { - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return -1; - - for (uint32_t i = 0; i < m; i++) { - for (uint32_t j = 0; j < n; j++) { - uint32_t acc = 0; - for (uint32_t p = 0; p < k; p++) { - acc += a[i * k + p] * b[p * n + j]; - } - c[i * n + j] = acc; - } - } - return 0; -} - - -float omega_fp16_to_fp32(uint16_t h) { - uint32_t sign = (uint32_t)(h & 0x8000) << 16; - uint32_t exp = (uint32_t)(h & 0x7c00) >> 10; - uint32_t mant = (uint32_t)(h & 0x03ff); - uint32_t val; - if (exp == 0) { - if (mant == 0) { - val = sign; - } else { - exp = 1; - while ((mant & 0x0400) == 0) { - mant <<= 1; - exp--; - } - mant &= 0x03ff; - val = sign | ((exp + (127 - 15)) << 23) | (mant << 13); - } - } else if (exp == 31) { - val = sign | 0x7f800000 | (mant << 13); - } else { - val = sign | ((exp + (127 - 15)) << 23) | (mant << 13); - } - float f; - memcpy(&f, &val, 4); - return f; -} - -float omega_bf16_to_fp32(uint16_t b) { - uint32_t val = (uint32_t)b << 16; - float f; - memcpy(&f, &val, 4); - return f; -} - -uint16_t omega_fp32_to_fp16(float f) { - _Float16 h = (_Float16)f; - uint16_t u; - memcpy(&u, &h, 2); - return u; -} - -uint16_t omega_fp32_to_bf16(float f) { -#ifndef OMEGA_GPU_NO_POSIX - __bf16 b = (__bf16)f; - uint16_t u; - memcpy(&u, &b, 2); - return u; -#else - /* Freestanding (cut A.2): the __bf16 cast calls libgcc __truncsfbf2. Same rounding in integer form - * (omega_fp32_to_bf16_rne); the hosted cast and it agree on every one of the 2^32 inputs - * (make test-codegen-freestanding, bf16 sweep). */ - return omega_fp32_to_bf16_rne(f); -#endif -} - -int omega_matmul_cpu_oracle_f16(const uint16_t *a, const uint16_t *b, float *c, uint32_t m, uint32_t k, uint32_t n) { - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return -1; - for (uint32_t i = 0; i < m; i++) { - for (uint32_t j = 0; j < n; j++) { - float sum = 0.0f; - for (uint32_t p = 0; p < k; p++) { - sum += omega_fp16_to_fp32(a[i * k + p]) * omega_fp16_to_fp32(b[p * n + j]); - } - c[i * n + j] = sum; - } - } - return 0; -} - -int omega_matmul_cpu_oracle_bf16(const uint16_t *a, const uint16_t *b, float *c, uint32_t m, uint32_t k, uint32_t n) { - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return -1; - for (uint32_t i = 0; i < m; i++) { - for (uint32_t j = 0; j < n; j++) { - float sum = 0.0f; - for (uint32_t p = 0; p < k; p++) { - sum += omega_bf16_to_fp32(a[i * k + p]) * omega_bf16_to_fp32(b[p * n + j]); - } - c[i * n + j] = sum; - } - } - return 0; -} -#ifndef OMEGA_GPU_NO_POSIX /* frees what the hosted allocating generators malloc (omega_blackwell_codegen.h, cut A.2) */ -void omega_blackwell_kernel_free(OmegaBlackwellKernel *kernel) { - if (!kernel) return; - if (kernel->code) { - free(kernel->code); - kernel->code = NULL; - } - kernel->code_size = 0; - kernel->insn_count = 0; -} -#endif - -int omega_blackwell_bind_matmul_realization(const OmegaMatMulSpec *spec, const OmegaBlackwellKernel *kernel, OmegaBlackwellRealizationIdentity *id) { - if (!spec || !kernel || !id) return -1; - - memcpy(id->spec_id, spec->spec_id, 32); - /* NVIDIA_DGX_SPARK_GB10_SM121 canonical machine descriptor digest */ - const char *machine_str = "NVIDIA_DGX_SPARK_GB10_SM121"; - sha256_hash((const uint8_t *)machine_str, strlen(machine_str), id->machine_id); - memcpy(id->code_digest, kernel->code_digest, 32); - id->sm_arch = 121; - - /* Realization ID = SHA-256(spec_id || machine_id || code_digest || sm_arch) */ - uint8_t bound[100]; - memcpy(bound + 0, id->spec_id, 32); - memcpy(bound + 32, id->machine_id, 32); - memcpy(bound + 64, id->code_digest, 32); - bound[96] = (uint8_t)(id->sm_arch & 0xff); - bound[97] = (uint8_t)((id->sm_arch >> 8) & 0xff); - bound[98] = (uint8_t)((id->sm_arch >> 16) & 0xff); - bound[99] = (uint8_t)((id->sm_arch >> 24) & 0xff); - - sha256_hash(bound, sizeof(bound), id->realization_id); - return 0; -} - -#include "omega_blackwell_codegen.h" - -#ifndef OMEGA_GPU_NO_POSIX -int omega_blackwell_codegen_matmul(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel) { - if (!spec || !kernel) return -1; - if (spec->precision == OMEGA_MATMUL_PRECISION_INT32) { - return omega_blackwell_codegen_matmul_i32(spec, kernel); - } else if (spec->precision == OMEGA_MATMUL_PRECISION_FP16 || spec->precision == OMEGA_MATMUL_PRECISION_BF16) { - return omega_blackwell_codegen_matmul_tensor(spec, kernel); - } - return -1; -} -#endif diff --git a/src/omega_blackwell_matmul.h b/src/omega_blackwell_matmul.h deleted file mode 100644 index ba419fc8d..000000000 --- a/src/omega_blackwell_matmul.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef OMEGA_BLACKWELL_MATMUL_H -#define OMEGA_BLACKWELL_MATMUL_H - -#include -#include -#include - -#define OMEGA_BW_MATMUL_MAX_M 8192 -#define OMEGA_BW_MATMUL_MAX_K 16384 -#define OMEGA_BW_MATMUL_MAX_N 262144 - -/* Precision modes for Milestone 18 tensor matrix multiplication */ -typedef enum { - OMEGA_MATMUL_PRECISION_INT32 = 0, /* Exact integer arithmetic mod 2^32 */ - OMEGA_MATMUL_PRECISION_FP16 = 1, /* FP16 inputs with FP32 accumulator */ - OMEGA_MATMUL_PRECISION_BF16 = 2 /* BF16 inputs with FP32 accumulator */ -} OmegaMatMulPrecision; - -/* Semantic matrix multiplication operation descriptor in G_S */ -typedef struct { - uint32_t m; - uint32_t k; - uint32_t n; - OmegaMatMulPrecision precision; - uint8_t spec_id[32]; -} OmegaMatMulSpec; - -/* Dynamically synthesized sm_121 machine code artifact */ -typedef struct { - uint8_t *code; - size_t code_size; - size_t insn_count; - uint8_t code_digest[32]; - uint32_t gpr_count; - uint32_t uniform_gpr_count; -} OmegaBlackwellKernel; - -/* Four-component realization identity binding */ -typedef struct { - uint8_t spec_id[32]; - uint8_t machine_id[32]; - uint8_t code_digest[32]; - uint32_t sm_arch; - uint8_t realization_id[32]; -} OmegaBlackwellRealizationIdentity; - -/* Initializes semantic MatMul specification and computes canonical spec_id */ -int omega_matmul_spec_init(OmegaMatMulSpec *spec, uint32_t m, uint32_t k, uint32_t n, OmegaMatMulPrecision precision); - -/* Mathematical CPU reference oracle for verification (zero tolerance) */ -int omega_matmul_cpu_oracle_i32(const uint32_t *a, const uint32_t *b, uint32_t *c, uint32_t m, uint32_t k, uint32_t n); - -/* Mathematical CPU reference oracle for FP16 and BF16 tensor matrix multiplication */ -int omega_matmul_cpu_oracle_f16(const uint16_t *a, const uint16_t *b, float *c, uint32_t m, uint32_t k, uint32_t n); -int omega_matmul_cpu_oracle_bf16(const uint16_t *a, const uint16_t *b, float *c, uint32_t m, uint32_t k, uint32_t n); - -/* Format conversion functions */ -float omega_fp16_to_fp32(uint16_t h); -float omega_bf16_to_fp32(uint16_t b); -uint16_t omega_fp32_to_fp16(float f); -uint16_t omega_fp32_to_bf16(float f); -/* The integer form of omega_fp32_to_bf16, inline for bulk loops: round to nearest even, NaN kept quiet with its - * sign and top payload bits. It equals the hosted __bf16 cast on all 2^32 inputs (the freestanding - * omega_fp32_to_bf16 is this function; make test-codegen-freestanding sweeps it against the cast). The hosted - * cast is a libgcc call per element (about 5 ns on the Spark), so bulk converters use this form. */ -static inline uint16_t omega_fp32_to_bf16_rne(float f) { - union { float f; uint32_t u; } v = {f}; - const uint32_t u = v.u; - if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu)) return (uint16_t)((u >> 16) | 0x0040u); - return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); -} - -/* Dynamic sm_121 code generator: transforms G_S semantic spec into machine code */ -int omega_blackwell_codegen_matmul(const OmegaMatMulSpec *spec, OmegaBlackwellKernel *kernel); - -/* Frees resources allocated for dynamically synthesized kernel */ -void omega_blackwell_kernel_free(OmegaBlackwellKernel *kernel); - -/* Binds realization identity from spec, machine, and dynamically synthesized code */ -int omega_blackwell_bind_matmul_realization(const OmegaMatMulSpec *spec, const OmegaBlackwellKernel *kernel, OmegaBlackwellRealizationIdentity *id); - -#endif /* OMEGA_BLACKWELL_MATMUL_H */ diff --git a/src/omega_blackwell_qmd.c b/src/omega_blackwell_qmd.c deleted file mode 100644 index 417c51c6b..000000000 --- a/src/omega_blackwell_qmd.c +++ /dev/null @@ -1,237 +0,0 @@ -#include "omega_blackwell_qmd.h" -#include - -/* - * Driver constant buffer 0 base template (224 words, 896 bytes). - * Empirically captured from physical Blackwell GB10 compute channel bring-up. - */ -static const uint32_t CBANK0_DRIVER_TEMPLATE[OMEGA_BW_CBANK_DRIVER_WORDS] = { - 0x26420000, 0x00000003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x94fe5d00, 0xe811c39b, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000fffff, 0x00000000, - 0x20000000, 0x00000003, 0x22000000, 0x00000003, 0x24280000, 0x00000003, 0x24010000, 0x00000003, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000001, 0x00000000, 0x0400c000, 0x00000002, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04ba32c8, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000120, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x25b66900, 0x00000003, - 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x3f800000, 0x3f800000, 0x3f800000, 0x00000400, - 0x00000001, 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04ba32c8, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000120, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x25b66900, 0x00000003, - 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x3f800000, 0x3f800000, 0x3f800000, 0x00000400, - 0x00000001, 0x00000001, 0x00000001, 0x00000001, 0x00000030, 0x00000000, 0x00000000, 0x01000000, - 0x00000000, 0x0000e9c0, 0x00000000, 0x00000000, 0x00000000, 0x0000e9c0, 0x01000000, 0x0000e9bf, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x24280380, 0x00000003, 0x2428039c, 0x00000003, 0x00000000, 0x00000000, - 0x00000040, 0x00000001, 0x00000001, 0x00000000, 0x00000001, 0x00000001, 0x00000001, 0x00fffdc0, -}; - -int omega_blackwell_build_qmd0(uint32_t *qmd0_words, uint64_t qmd0_va, uint64_t qmd1_va) { - if (!qmd0_words) return -1; - (void)qmd0_va; - memset(qmd0_words, 0, OMEGA_BW_QMD_BYTES); - - /* Word 4: DEPENDENCE_COUNTER=2, QMD_TYPE=1 (GRID_NULL) */ - qmd0_words[4] = 0x00800002; - - /* Word 10: DEPENDENT_QMD0_ENABLE=1, ACTION=1 (SCHEDULE), SELF_COPY=1 */ - qmd0_words[10] = 0x00230000; - - /* Word 12: DEPENDENT_QMD0_POINTER = qmd1_va >> 8 */ - qmd0_words[12] = (uint32_t)(qmd1_va >> 8); - - /* Word 14: QMD_MAJOR_VERSION=5, SAMPLER_INDEX=1 */ - qmd0_words[14] = 0x00500200; - - /* Word 34: CTA_THREAD_DIMENSION0=1, CTA_THREAD_DIMENSION1=1 */ - qmd0_words[34] = 0x00010001; - - /* Word 35: CTA_THREAD_DIMENSION2=1, REGISTER_COUNT=8 */ - qmd0_words[35] = 0x00000801; - - return 0; -} - -int omega_blackwell_build_qmd1(uint32_t *qmd1_words, const OmegaBlackwellQmdConfig *cfg) { - if (!qmd1_words || !cfg) return -1; - memset(qmd1_words, 0, OMEGA_BW_QMD_BYTES); - - uint32_t tx = cfg->threads_x ? cfg->threads_x : (cfg->threads_per_block ? cfg->threads_per_block : 64); - uint32_t ty = cfg->threads_y ? cfg->threads_y : 1; - uint32_t tz = 1; - uint32_t gx = cfg->grid_x ? cfg->grid_x : (cfg->grid_width ? cfg->grid_width : (cfg->num_elements + tx - 1) / tx); - if (gx == 0) gx = 1; - uint32_t gy = cfg->grid_y ? cfg->grid_y : 1; - uint32_t gz = 1; - - /* Word 4: QMD_GROUP_ID=0x3f, QMD_TYPE=2 (GRID_CTA) */ - qmd1_words[4] = 0x013f0000; - - /* Word 9: RELEASE_ENABLE=1, RELEASE_STRUCTURE_SIZE=1 (ONE_WORD) */ - qmd1_words[9] = 0x00000003; - - /* Word 10: DEPENDENT_QMD0_ENABLE=1, ACTION=4 (DECREMENT_DEPENDENCE), PREFETCH=1 */ - qmd1_words[10] = 0x00190000; - - /* Word 12: DEPENDENT_QMD0_POINTER = qmd0_va >> 8 */ - qmd1_words[12] = (uint32_t)(cfg->qmd0_va >> 8); - - /* Word 14: QMD_VERSION=5, SASS_VERSION=0xa4, SAMPLER=1, cache invalidation flags */ - qmd1_words[14] = 0x2f5003a4; - - /* Words 15-17: RELEASE_SEMAPHORE0 (writes 6 to sem_va upon completion) */ - qmd1_words[15] = (uint32_t)cfg->sem_va; - qmd1_words[16] = (uint32_t)(cfg->sem_va >> 32); - qmd1_words[17] = 0x00000006; - - /* Word 19: CWD_MEMBAR_TYPE=1, FREE_CTA_SLOTS=24, PRE_EXIT=1 */ - qmd1_words[19] = 0x81810000; - - /* Words 20, 22: ARRIVE_AT_LATCH (ID 56, VALID=1) */ - qmd1_words[20] = 0x00000038; - qmd1_words[22] = 0x04000000; - - /* Words 32-33: PROGRAM_ADDRESS (code_va >> 4) and prefetch size 0xa (bits 29:21) */ - qmd1_words[32] = (uint32_t)(cfg->code_va >> 4); - qmd1_words[33] = (uint32_t)(((cfg->code_va >> 36) & 0x1fffff) | (0xa << 21)); - - /* Words 34-35: CTA thread dimensions, registers, 1 barrier */ - qmd1_words[34] = (tx & 0xffff) | ((ty & 0xffff) << 16); - uint32_t gpr = cfg->gpr_count ? cfg->gpr_count : 16; - if (gpr < 16) gpr = 16; - qmd1_words[35] = (tz & 0xff) | ((gpr & 0x1ff) << 8) | (1u << 17); - - /* Word 36: SHARED_MEMORY_SIZE_SHIFTED7 in bits 10:0 (default 8 = 1024 bytes), then the - * MIN/MAX/TARGET_SM_CONFIG_SHARED_MEM_SIZE fields (9, 26, 9) kept as they were. */ - if (cfg->shared_bytes > OMEGA_BW_QMD_MAX_SHARED_BYTES) return -1; - uint32_t smem7 = cfg->shared_bytes ? (cfg->shared_bytes + 127u) / 128u : 8u; - qmd1_words[36] = (0x04b44808u & ~0x7ffu) | smem7; - - /* Word 37: SHADER_LOCAL_MEMORY_HIGH_SIZE_SHIFTED4 = 0 (SKEDCHECK05 compliance) */ - qmd1_words[37] = 0x00000000; - - /* Words 39-41: Grid dimensions */ - qmd1_words[39] = gx; - qmd1_words[40] = gy; - qmd1_words[41] = gz; - - /* Words 42-43: Constant Buffer 0 (cbank_va, size 1024 bytes -> 0x40 shifted 19) */ - qmd1_words[42] = (uint32_t)(cfg->cbank_va >> 6); - qmd1_words[43] = (uint32_t)(((cfg->cbank_va >> 38) & 0x7ffff) | (0x40 << 19)); - - /* Words 44-45: Constant Buffer 1 (scratch_va, size 0x90 shifted 19) */ - qmd1_words[44] = (uint32_t)(cfg->scratch_va >> 6); - qmd1_words[45] = (uint32_t)(((cfg->scratch_va >> 38) & 0x7ffff) | (0x90 << 19)); - - /* Words 52-53: Constant Buffer 5 (cbank_va + 0x300, size 0x10 shifted 19) */ - qmd1_words[52] = (uint32_t)((cfg->cbank_va + 0x300) >> 6); - qmd1_words[53] = (uint32_t)((((cfg->cbank_va + 0x300) >> 38) & 0x7ffff) | (0x10 << 19)); - - /* Words 56-57: Constant Buffer 7 (scratch_va, size 0x1000 shifted 19) */ - qmd1_words[56] = (uint32_t)(cfg->scratch_va >> 6); - qmd1_words[57] = (uint32_t)(((cfg->scratch_va >> 38) & 0x7ffff) | (0x1000 << 19)); - - /* Word 58: Constant buffer valid mask (CB0, CB1, CB5, CB7) */ - qmd1_words[58] = 0x10300011; - - /* Word 59: PROGRAM_PREFETCH_ADDR_LOWER_SHIFTED8 = code_va >> 8 */ - qmd1_words[59] = (uint32_t)(cfg->code_va >> 8); - - return 0; -} - -int omega_blackwell_build_cbank_driver(uint32_t *cbank_words, uint64_t cbank_va) { - if (!cbank_words) return -1; - memcpy(cbank_words, CBANK0_DRIVER_TEMPLATE, sizeof(CBANK0_DRIVER_TEMPLATE)); - - /* Patch driver template addresses with actual cbank_va */ - cbank_words[68] = (uint32_t)(cbank_va >> 32); - cbank_words[69] = (uint32_t)cbank_va; - - cbank_words[210] = (uint32_t)((cbank_va + 0x380) >> 32); - cbank_words[211] = (uint32_t)(cbank_va + 0x380); - cbank_words[212] = (uint32_t)((cbank_va + 0x39c) >> 32); - cbank_words[213] = (uint32_t)(cbank_va + 0x39c); - - return 0; -} - -int omega_blackwell_build_cbank_args(uint32_t *args_words, uint64_t a_va, uint64_t b_va, - uint64_t c_va, uint32_t n) { - if (!args_words) return -1; - - args_words[0] = (uint32_t)a_va; - args_words[1] = (uint32_t)(a_va >> 32); - args_words[2] = (uint32_t)b_va; - args_words[3] = (uint32_t)(b_va >> 32); - args_words[4] = (uint32_t)c_va; - args_words[5] = (uint32_t)(c_va >> 32); - args_words[6] = n; - - return 0; -} - -int omega_blackwell_build_cbank_driver_2d(uint32_t *cbank_words, uint64_t cbank_va, - uint32_t threads_x, uint32_t threads_y, - uint32_t grid_x, uint32_t grid_y) { - if (!cbank_words) return -1; - if (omega_blackwell_build_cbank_driver(cbank_words, cbank_va) != 0) return -1; - if (threads_x > 0) cbank_words[216] = threads_x; - if (threads_y > 0) cbank_words[217] = threads_y; - if (grid_x > 0) cbank_words[220] = grid_x; - if (grid_y > 0) cbank_words[221] = grid_y; - return 0; -} - -int omega_blackwell_build_cbank_args_matmul(uint32_t *args_words, uint64_t a_va, uint64_t b_va, - uint64_t c_va, uint32_t m, uint32_t k, uint32_t n) { - if (!args_words) return -1; - args_words[0] = (uint32_t)a_va; - args_words[1] = (uint32_t)(a_va >> 32); - args_words[2] = (uint32_t)b_va; - args_words[3] = (uint32_t)(b_va >> 32); - args_words[4] = (uint32_t)c_va; - args_words[5] = (uint32_t)(c_va >> 32); - args_words[6] = m; - args_words[7] = k; - args_words[8] = n; - args_words[9] = 0; - return 0; -} - -int omega_blackwell_verify_qmd_invariants(const uint32_t *qmd1_words) { - if (!qmd1_words) return -1; - - /* 1. QMD Major Version must be 5 (bits 471:468 in Word 14) */ - uint32_t version = (qmd1_words[14] >> 20) & 0xf; - if (version != 5) return -1; - - /* 2. QMD Type must be GRID_CTA = 2 (bits 153:151 in Word 4) */ - uint32_t type = (qmd1_words[4] >> 23) & 0x7; - if (type != 2) return -1; - - /* 3. SKEDCHECK05 compliance: local memory high size shifted 4 must be 0 */ - if (qmd1_words[37] != 0) return -1; - - /* 4. Release semaphore payload must be non-zero */ - if (qmd1_words[17] == 0) return -1; - - /* 5. Program prefetch size must be 0xa (bits 29:21 in Word 33) */ - uint32_t prefetch = (qmd1_words[33] >> 21) & 0x1ff; - if (prefetch != 0xa) return -1; - - /* 6. Constant buffer valid mask must have CB0 enabled */ - if ((qmd1_words[58] & 0x1) == 0) return -1; - - return 0; -} diff --git a/src/omega_blackwell_qmd.h b/src/omega_blackwell_qmd.h deleted file mode 100644 index f1c7018f0..000000000 --- a/src/omega_blackwell_qmd.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef OMEGA_BLACKWELL_QMD_H -#define OMEGA_BLACKWELL_QMD_H - -#include -#include -#include - -#define OMEGA_BW_QMD_WORDS 96 -#define OMEGA_BW_QMD_BYTES (OMEGA_BW_QMD_WORDS * 4) /* 384 bytes */ -#define OMEGA_BW_CBANK_DRIVER_WORDS 224 -#define OMEGA_BW_CBANK_ARGS_WORDS 7 -#define OMEGA_BW_CBANK_MATMUL_ARGS_WORDS 10 - -/* Epistemic classifications for QMD fields */ -typedef enum { - EPISTEMIC_DOCUMENTED = 1, /* NVIDIA open-gpu-kernel-modules / clcdc0qmd.h */ - EPISTEMIC_OBSERVED = 2, /* Empirically verified on physical GB10 silicon */ - EPISTEMIC_REVERSE_ENGINEERED = 3 /* Derived from Blackwell instruction trace */ -} OmegaEpistemicTier; - -typedef struct { - uint64_t code_va; - uint64_t cbank_va; - uint64_t scratch_va; - uint64_t sem_va; - uint64_t qmd0_va; - uint64_t qmd1_va; - uint32_t num_elements; - uint32_t threads_per_block; - uint32_t grid_width; - uint32_t threads_x; - uint32_t threads_y; - uint32_t grid_x; - uint32_t grid_y; - uint32_t gpr_count; - /* Shared memory per CTA in bytes (clcec0qmd.h SHARED_MEMORY_SIZE_SHIFTED7, 128-byte units). - * 0 keeps the long-standing 1024. At most OMEGA_BW_QMD_MAX_SHARED_BYTES, well inside the - * TARGET_SM_CONFIG this QMD declares (word 36). */ - uint32_t shared_bytes; -} OmegaBlackwellQmdConfig; -#define OMEGA_BW_QMD_MAX_SHARED_BYTES 16384u - -/* Build QMD 0: GRID_NULL null-barrier grid with dependence counter 2 */ -int omega_blackwell_build_qmd0(uint32_t *qmd0_words, uint64_t qmd0_va, uint64_t qmd1_va); - -/* Build QMD 1: GRID_CTA compute grid for Blackwell sm_121 vector add and matmul */ -int omega_blackwell_build_qmd1(uint32_t *qmd1_words, const OmegaBlackwellQmdConfig *cfg); - -/* Build driver constant bank 0 (224 words) with hardware descriptor addresses */ -int omega_blackwell_build_cbank_driver(uint32_t *cbank_words, uint64_t cbank_va); - -/* Build driver constant bank 0 (224 words) with 2D tile geometry */ -int omega_blackwell_build_cbank_driver_2d(uint32_t *cbank_words, uint64_t cbank_va, - uint32_t threads_x, uint32_t threads_y, - uint32_t grid_x, uint32_t grid_y); - -/* Build kernel argument constant bank buffer (7 words: pointers A, B, C, length N) */ -int omega_blackwell_build_cbank_args(uint32_t *args_words, uint64_t a_va, uint64_t b_va, - uint64_t c_va, uint32_t n); - -/* Build matrix multiplication kernel argument constant bank buffer (10 words) */ -int omega_blackwell_build_cbank_args_matmul(uint32_t *args_words, uint64_t a_va, uint64_t b_va, - uint64_t c_va, uint32_t m, uint32_t k, uint32_t n); - -/* Verify QMD structural invariants (SKEDCHECK05, version, alignment, etc.) */ -int omega_blackwell_verify_qmd_invariants(const uint32_t *qmd1_words); - -#endif /* OMEGA_BLACKWELL_QMD_H */ diff --git a/src/omega_blackwell_realize.c b/src/omega_blackwell_realize.c deleted file mode 100644 index 9e2f14a61..000000000 --- a/src/omega_blackwell_realize.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "omega_blackwell_realize.h" -#include "sha256.h" -#include - -int omega_blackwell_get_machine_id(SemanticId *out_machine_id) { - if (!out_machine_id) return -1; - sha256_ctx ctx; - sha256_init(&ctx); - const char *machine_str = "NVIDIA_DGX_SPARK_GB10_SM121"; - sha256_update(&ctx, (const uint8_t *)machine_str, strlen(machine_str)); - sha256_final(&ctx, out_machine_id->bytes); - return 0; -} - -int omega_blackwell_realization_compute_id(OmegaBlackwellRealization *real) { - if (!real) return -1; - sha256_ctx ctx; - sha256_init(&ctx); - sha256_update(&ctx, real->spec_id.bytes, OMEGA_ID_BYTES); - sha256_update(&ctx, real->machine_id.bytes, OMEGA_ID_BYTES); - sha256_update(&ctx, real->code_digest, sizeof(real->code_digest)); - sha256_update(&ctx, (const uint8_t *)&real->sm_architecture, sizeof(real->sm_architecture)); - sha256_final(&ctx, real->realization_digest); - - memcpy(real->realization_id.bytes, real->realization_digest, OMEGA_ID_BYTES); - return 0; -} - -int omega_blackwell_realize_vector(const OmegaVectorSpec *spec, OmegaBlackwellRealization *out_real) { - if (!spec || !out_real) return -1; - memset(out_real, 0, sizeof(*out_real)); - - out_real->spec_id = spec->spec_id; - if (omega_blackwell_get_machine_id(&out_real->machine_id) != 0) return -1; - - out_real->sm_architecture = OMEGA_BW_SM_ARCH_121; - out_real->code_len = OMEGA_BW_VECADD_CODE_SIZE; - - /* Verify and digest generated Blackwell machine code */ - uint8_t code_buf[OMEGA_BW_VECADD_CODE_SIZE]; - size_t encoded_len = 0; - if (omega_blackwell_encode_vecadd(code_buf, sizeof(code_buf), &encoded_len) != 0) return -1; - if (omega_blackwell_compute_code_digest(code_buf, encoded_len, out_real->code_digest) != 0) return -1; - - /* Default launch geometry */ - out_real->qmd_cfg.num_elements = spec->element_count; - out_real->qmd_cfg.threads_per_block = 64; - out_real->qmd_cfg.grid_width = (spec->element_count + 63) / 64; - if (out_real->qmd_cfg.grid_width == 0) out_real->qmd_cfg.grid_width = 1; - - return omega_blackwell_realization_compute_id(out_real); -} diff --git a/src/omega_blackwell_realize.h b/src/omega_blackwell_realize.h deleted file mode 100644 index a3b3c5011..000000000 --- a/src/omega_blackwell_realize.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef OMEGA_BLACKWELL_REALIZE_H -#define OMEGA_BLACKWELL_REALIZE_H - -#include "omega_types.h" -#include "omega_vector.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_encoder.h" -#include -#include -#include - -#define OMEGA_BW_SM_ARCH_121 121 - -typedef struct { - SemanticId realization_id; - SemanticId spec_id; - SemanticId machine_id; - uint32_t sm_architecture; - size_t code_len; - uint8_t code_digest[32]; - uint8_t realization_digest[32]; - OmegaBlackwellQmdConfig qmd_cfg; -} OmegaBlackwellRealization; - -/* Machine PROFILE digest for the Blackwell GB10 SM target (same on every GB10). - * Not a machine identity: see AienMachineId (src/runtime/aien_machine_id.h). */ -int omega_blackwell_get_machine_id(SemanticId *out_machine_id); - -/* Bind an OmegaVectorSpec to Blackwell sm_121 hardware realization */ -int omega_blackwell_realize_vector(const OmegaVectorSpec *spec, OmegaBlackwellRealization *out_real); - -/* Compute triple hash realization ID: SHA-256(spec_id || machine_id || code_digest) */ -int omega_blackwell_realization_compute_id(OmegaBlackwellRealization *real); - -#endif /* OMEGA_BLACKWELL_REALIZE_H */ diff --git a/src/omega_blackwell_submit.c b/src/omega_blackwell_submit.c deleted file mode 100644 index 077f39b4e..000000000 --- a/src/omega_blackwell_submit.c +++ /dev/null @@ -1,724 +0,0 @@ -#include -#include "omega_blackwell_submit.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_encoder.h" -#include "omega_blackwell_engine.h" -#include "omega_gpu_engine.h" -#include "m16_native.h" -#include "omega_gpu_wait.h" -#include -#include -#include -#include -#include -#include "omega_gpu_code_alloc.h" - -/* Second completion marker payload for the C3 tail (marker page + 0x10), the same value as - * src/omega_blackwell_engine.c BE_MARKER2_PAYLOAD and src/omega_numeric_divsqrt_gb10.c:1152. */ - -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - -static uint64_t current_time_ns(void) { - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; -} - -int omega_blackwell_execute_vector(const OmegaVectorSpec *spec, - const OmegaBlackwellRealization *real, - const uint32_t *h_a, - const uint32_t *h_b, - uint32_t *h_c_out, - OmegaBlackwellVectorExecution *exec_info) { - if (!spec || !real || !h_a || !h_b || !h_c_out) return -1; - uint32_t n = spec->element_count; - if (n == 0) return -1; - - if (exec_info) { - memset(exec_info, 0, sizeof(*exec_info)); - strncpy(exec_info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof(exec_info->target_chip) - 1); - exec_info->sm_architecture = real->sm_architecture; - exec_info->element_count = n; - exec_info->zero_libcuda_linkage = (omega_blackwell_verify_zero_libcuda_linkage(NULL) == 0); - exec_info->zero_cuda_symbols = (omega_blackwell_verify_zero_cuda_symbols(NULL) == 0); - exec_info->zero_libcuda_runtime = (omega_blackwell_verify_zero_libcuda_runtime() == 0); - } - /* This executor no longer talks to the device itself. It builds the program - * and the poison words on the host, hands the job to omega_gpu_execute with - * the Blackwell backend (src/omega_blackwell_engine.c), and then does the - * arithmetic check here. The engine only checks that no output word is still - * equal to its poison word; it never judges the math. */ - - /* Program bytes. Capacity 0x1000 as before (the code page was 0x1000). */ - uint8_t code[0x1000]; - size_t encoded_len = 0; - if (omega_blackwell_encode_vecadd(code, sizeof(code), &encoded_len) != 0 || encoded_len == 0) return -1; - - /* Poison words. The expected output word is computed here, on the host, - * before launch: expected[i] = (a[i] + b[i]) mod 2^32 (the same sum - * omega_vector_verify_oracle uses). The poison word is the bit complement of - * it. A word and its bit complement always differ, so a poison word can - * never equal the expected output word at the same position. If the device - * leaves a word unwritten the engine sees poison and reports - * OUTPUT_UNCHANGED. (This replaces the old constant OMEGA_VECTOR_POISON_VALUE, - * which could in principle collide with a legitimate sum.) */ - uint32_t *poison = (uint32_t *)malloc((size_t)n * sizeof(uint32_t)); - if (!poison) return -1; - for (size_t i = 0; i < n; i++) { - poison[i] = ~(uint32_t)(h_a[i] + h_b[i]); - } - - OmegaGpuJob job; - OmegaGpuResult res; - memset(&job, 0, sizeof(job)); - job.program = code; - job.program_len = encoded_len; - job.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - job.element_count = n; - job.input_a = h_a; - job.input_a_len = (size_t)n * sizeof(uint32_t); - job.input_b = h_b; - job.input_b_len = (size_t)n * sizeof(uint32_t); - job.output = h_c_out; - job.output_len = (size_t)n * sizeof(uint32_t); - job.poison = poison; - job.poison_count = n; - /* 5000 ms is the marker wait this executor always used (the old - * m16_native_wait_marker(..., 5000) call). The same limit is used for the - * second marker and the semaphore, which the old code did not wait for, and - * for the barrier, which has no wait. flags 0 means every protection ON: - * the L2 flush and second marker are now part of this launch. */ - job.timeouts.marker_ms = 5000; - job.timeouts.release_semaphore_ms = 5000; - job.timeouts.marker2_ms = 5000; - job.timeouts.visibility_ms = 5000; - job.flags = 0; - - omega_gpu_engine_set_backend(omega_blackwell_engine_backend()); - int erc = omega_gpu_execute(&job, &res); - free(poison); - if (erc != OMEGA_GPU_ENGINE_OK) { - fprintf(stderr, "GB10_VECTOR_FAIL failure=%s step=%s state=%s drv_rc=%d errno=%d text=\"%s\"\n", - omega_gpu_engine_failure_name(res.failure), omega_gpu_engine_step_name(res.failed_step), - omega_gpu_engine_state_name(res.last_state), res.drv_rc, res.err_no, res.drv_text); - return -1; - } - - /* The engine returns only pass or fail. The marker, the semaphore and the - * timestamps come from what the backend observed in its own wait callbacks - * (the engine result carries them only on failure). Both values were - * already required by the backend; checked again here because the gates - * depend on them: marker payload 0x44444444, semaphore DONE (6). */ - OmegaBlackwellEngineRunInfo info; - omega_blackwell_engine_run_info(&info); - if (info.marker != OMEGA_BW_MARKER_COMPLETION_PAYLOAD) return -1; - if (info.semaphore != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) return -1; - - /* Verify against OMEGA semantic oracle */ - size_t mismatch_idx = 0; - int parity_res = omega_vector_verify_oracle(h_a, h_b, h_c_out, n, &mismatch_idx); - - if (exec_info) { - exec_info->launch_timestamp_ns = info.launch_ns; - exec_info->completion_timestamp_ns = info.marker_done_ns; - exec_info->elapsed_ns = (info.marker_done_ns > info.launch_ns) ? (info.marker_done_ns - info.launch_ns) : 0; - exec_info->completion_marker = info.marker; - exec_info->intermediate_semaphore = info.semaphore; - exec_info->parity_verified = (parity_res == 0); - } - - return parity_res; -} - -/* CHIPWAIT-2: the two direct launchers wait through the shared primitive - * (src/omega_gpu_wait.c): exact-value wait on the marker with marker2 required - * (marker2 lands only after the L2 flush, so the output is in memory), progress - * stall 5000 ms (the old budget), hard total 600000 ms. One tagged line on failure. - * The engine-routed launcher keeps the engine's own timed waits. */ -static int bw_wait_one(const char *site, const char *what, volatile uint32_t *w, uint32_t want, - volatile uint32_t *m2, uint32_t m2want) { - omega_gpu_wait_cfg_t cfg; - memset(&cfg, 0, sizeof(cfg)); - cfg.progress_timeout_ms = 5000; - cfg.total_timeout_ms = 600000; - cfg.marker2 = m2; - cfg.marker2_want = m2want; - omega_gpu_wait_report_t r; - if (omega_gpu_wait_fixed(w, want, &r, &cfg)) return 0; - fprintf(stderr, - "BW_WAIT_FAIL site=%s wait=%s kind=%s result=%s expected=0x%x observed=0x%x " - "marker2_observed=0x%x elapsed_ns=%llu progress_count=%llu polls=%llu\n", - site, what, omega_gpu_wait_kind_name(r.wait_kind), omega_gpu_wait_result_name(r.result), - r.expected, r.last_observed, r.last_marker2, (unsigned long long)r.elapsed_ns, - (unsigned long long)r.progress_count, (unsigned long long)r.polls); - return -1; -} - -int omega_blackwell_execute_matmul(const OmegaMatMulSpec *spec, - const OmegaBlackwellKernel *kernel, - const uint32_t *h_a, - const uint32_t *h_b, - uint32_t *h_c_out, - OmegaBlackwellMatMulExecution *exec_info) { - if (!spec || !kernel || !h_a || !h_b || !h_c_out) return -1; - if (!kernel->code || kernel->code_size == 0) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - - if (exec_info) { - memset(exec_info, 0, sizeof(*exec_info)); - strncpy(exec_info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof(exec_info->target_chip) - 1); - exec_info->sm_architecture = 121; - exec_info->m = spec->m; - exec_info->k = spec->k; - exec_info->n = spec->n; - exec_info->zero_libcuda_linkage = (omega_blackwell_verify_zero_libcuda_linkage(NULL) == 0); - exec_info->zero_cuda_symbols = (omega_blackwell_verify_zero_cuda_symbols(NULL) == 0); - exec_info->zero_libcuda_runtime = (omega_blackwell_verify_zero_libcuda_runtime() == 0); - } - - M16NativeContext ctx; - if (m16_native_open(&ctx) != 0) { return -1; } - if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return -1; } - - /* GB10: every buffer the CPU and GPU both touch is GPU-uncached. A plain nvrm_alloc forces - * GPU_CACHEABLE_YES, which nvos.h:1115-1118 says is not coherent with CPU mappings on - * system memory (R11 wrong results under load, hive-phases I37). */ - NvrmMem large_pb; - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return -1; } - ctx.pb_mem = large_pb; - - /* Sizing buffer allocations */ - size_t a_bytes = ((size_t)spec->m * spec->k * sizeof(uint32_t) + 0xFFFULL) & ~0xFFFULL; - if (a_bytes < 0x1000) a_bytes = 0x1000; - size_t b_bytes = ((size_t)spec->k * spec->n * sizeof(uint32_t) + 0xFFFULL) & ~0xFFFULL; - if (b_bytes < 0x1000) b_bytes = 0x1000; - size_t c_bytes = ((size_t)spec->m * spec->n * sizeof(uint32_t) + 0xFFFULL) & ~0xFFFULL; - if (c_bytes < 0x1000) c_bytes = 0x1000; - size_t code_bytes = omega_gpu_code_alloc_bytes(kernel->code_size); /* code + 2 KB prefetch tail, page rounded */ - if (code_bytes == 0) return -1; - - NvrmMem code_mem, cbank_mem, a_mem, b_mem, c_mem, marker_mem, qmd_mem; - if (nvrm_alloc_gpu_uncached(&ctx.rm, code_bytes, &code_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x1000, &cbank_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, a_bytes, &a_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, b_bytes, &b_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, c_bytes, &c_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x1000, &marker_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &qmd_mem) != 0) { m16_native_close(&ctx); return -1; } - - /* Copy dynamic machine code into code_mem */ - memcpy(code_mem.cpu, kernel->code, kernel->code_size); - memset((uint8_t *)code_mem.cpu + kernel->code_size, 0, code_bytes - kernel->code_size); - - /* Populate input buffers A, B and initialize C with poison */ - memcpy(a_mem.cpu, h_a, (size_t)spec->m * spec->k * sizeof(uint32_t)); - memcpy(b_mem.cpu, h_b, (size_t)spec->k * spec->n * sizeof(uint32_t)); - uint32_t *c_dev = (uint32_t *)c_mem.cpu; - for (size_t i = 0; i < (size_t)spec->m * spec->n; i++) { - c_dev[i] = OMEGA_VECTOR_POISON_VALUE; - } - - /* 2D Tile Configuration: 16x16 threads per block */ - uint32_t threads_x = 16; - uint32_t threads_y = 16; - uint32_t grid_x = (spec->n + 15) / 16; - uint32_t grid_y = (spec->m + 15) / 16; - - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, threads_y, grid_x, grid_y); - - uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - omega_blackwell_build_cbank_args_matmul(cbank_args, a_mem.va, b_mem.va, c_mem.va, spec->m, spec->k, spec->n); - - memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); - memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args)); - - uint64_t qmd0_va = qmd_mem.va; - uint64_t qmd1_va = qmd_mem.va + 0x1000; - uint64_t sem_va = qmd_mem.va + 0x2000; - uint64_t scratch_va = qmd_mem.va + 0x4000; - - OmegaBlackwellQmdConfig qmd_cfg = { - .code_va = code_mem.va, - .cbank_va = cbank_mem.va, - .scratch_va = scratch_va, - .sem_va = sem_va, - .qmd0_va = qmd0_va, - .qmd1_va = qmd1_va, - .num_elements = spec->m * spec->n, - .threads_per_block = 256, - .grid_width = grid_x * grid_y, - .threads_x = threads_x, - .threads_y = threads_y, - .grid_x = grid_x, - .grid_y = grid_y, - .gpr_count = (kernel->gpr_count > 16) ? ((kernel->gpr_count + 15) & ~15U) : 32 - }; - - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS]; - uint32_t qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg); - - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return -1; } - - memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words)); - memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words)); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); - *hsem = 0; - *hmarker = 0; - *hmarker2 = 0; - __asm__ volatile("dsb sy" ::: "memory"); - - /* Assemble unified pushbuffer */ - uint32_t pb[1024]; - size_t pb_len = 0; - - /* 1. Setup words (18 words) */ - memcpy(&pb[pb_len], SETUP_WORDS, sizeof(SETUP_WORDS)); - pb_len += sizeof(SETUP_WORDS) / 4; - - /* 2. Cbank driver data upload (224 words via DMA) */ - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)(cbank_mem.va >> 32); - pb[pb_len++] = (uint32_t)cbank_mem.va; - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000380; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[pb_len], cbank_data, 224 * 4); - pb_len += 224; - - /* 3. Kernel args upload (10 words via DMA = 40 = 0x28 bytes) */ - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); - pb[pb_len++] = (uint32_t)(cbank_mem.va + 0x380); - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000028; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (10 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[pb_len], cbank_args, 10 * 4); - pb_len += 10; - - /* 4. Inline QMD 0 (98 words: 2 addr + 96 QMD words) */ - pb[pb_len++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[pb_len++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); - pb[pb_len++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[pb_len], qmd0_words, 96 * 4); - pb_len += 96; - - /* 5. Intermediate semaphore upload (1 word = 5 via DMA) */ - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)(sem_va >> 32); - pb[pb_len++] = (uint32_t)sem_va; - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000004; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - pb[pb_len++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - - /* 6. Inline QMD 1 (98 words: 2 addr + 96 QMD words) */ - pb[pb_len++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[pb_len++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); - pb[pb_len++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[pb_len], qmd1_words, 96 * 4); - pb_len += 96; - - /* 7. Subchannel 0 completion release (WFI) */ - pb[pb_len++] = nvrm_mthd(0, 0x005c, 5); - pb[pb_len++] = (uint32_t)marker_mem.va; - pb[pb_len++] = (uint32_t)(marker_mem.va >> 32); - pb[pb_len++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; - pb[pb_len++] = 0; - pb[pb_len++] = 0x1 | (1u << 20); // RELEASE | WFI - - /* 8. C3 tail, the same words as src/omega_numeric_gb10.c and - * src/omega_blackwell_engine.c: flush GPU L2 dirty lines (NVC96F_MEM_OP_A..D = - * 0x28..0x34, D bits 31:27 OPERATION = L2_FLUSH_DIRTY 0x10), then a second WFI - * release at marker page + 0x10 that the host waits for before the readback. */ - pb[pb_len++] = nvrm_mthd(0, 0x0028, 4); - pb[pb_len++] = 0; - pb[pb_len++] = 0; - pb[pb_len++] = 0; - pb[pb_len++] = (0x10u << 27); - pb[pb_len++] = nvrm_mthd(0, 0x005c, 5); - pb[pb_len++] = (uint32_t)(marker_mem.va + 0x10); - pb[pb_len++] = (uint32_t)((marker_mem.va + 0x10) >> 32); - pb[pb_len++] = OMEGA_BW_MARKER2_PAYLOAD; - pb[pb_len++] = 0; - pb[pb_len++] = 0x1 | (1u << 20); // RELEASE | WFI - - /* Submit methods to hardware GPFIFO ring */ - uint64_t t_start = current_time_ns(); - if (m16_native_submit_methods(&ctx, pb, pb_len) != 0) { m16_native_close(&ctx); return -1; } - - /* Wait for hardware completion marker */ - /* CHIPWAIT-2: marker with marker2 required (C3: the second release lands only after the L2 flush). */ - if (bw_wait_one(__func__, "marker", hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, hmarker2, OMEGA_BW_MARKER2_PAYLOAD) != 0) { m16_native_close(&ctx); return -1; } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t_end = current_time_ns(); - - /* Validate intermediate semaphore updated to 6 */ - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return -1; } - - /* Copy device output back to host */ - memcpy(h_c_out, c_mem.cpu, (size_t)spec->m * spec->n * sizeof(uint32_t)); - - /* Verify against OMEGA MatMul mathematical reference oracle */ - uint32_t *h_expected = (uint32_t *)malloc((size_t)spec->m * spec->n * sizeof(uint32_t)); - if (!h_expected) { m16_native_close(&ctx); return -1; } - - omega_matmul_cpu_oracle_i32(h_a, h_b, h_expected, spec->m, spec->k, spec->n); - - size_t mismatches = 0; - for (size_t i = 0; i < (size_t)spec->m * spec->n; i++) { - if (h_c_out[i] != h_expected[i]) { - mismatches++; - } - } - free(h_expected); - - if (exec_info) { - exec_info->launch_timestamp_ns = t_start; - exec_info->completion_timestamp_ns = t_end; - exec_info->elapsed_ns = (t_end > t_start) ? (t_end - t_start) : 0; - exec_info->completion_marker = *hmarker; - exec_info->intermediate_semaphore = *hsem; - exec_info->mismatch_count = mismatches; - exec_info->parity_verified = (mismatches == 0); - } - - m16_native_close(&ctx); - return (mismatches == 0) ? 0 : -1; -} - - -int omega_blackwell_execute_matmul_tensor(const OmegaMatMulSpec *spec, - const OmegaBlackwellKernel *kernel, - const void *h_a, - const void *h_b, - float *h_c_out, - OmegaBlackwellMatMulExecution *exec_info, - float *out_max_abs_err, - float *out_max_rel_err) { - if (!spec || !kernel || !h_a || !h_b || !h_c_out) return -1; - if (!kernel->code || kernel->code_size == 0) return -1; - if (spec->m == 0 || spec->k == 0 || spec->n == 0) return -1; - if (spec->precision != OMEGA_MATMUL_PRECISION_FP16 && spec->precision != OMEGA_MATMUL_PRECISION_BF16) return -1; - - if (exec_info) { - memset(exec_info, 0, sizeof(*exec_info)); - strncpy(exec_info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof(exec_info->target_chip) - 1); - exec_info->sm_architecture = 121; - exec_info->m = spec->m; - exec_info->k = spec->k; - exec_info->n = spec->n; - exec_info->zero_libcuda_linkage = (omega_blackwell_verify_zero_libcuda_linkage(NULL) == 0); - exec_info->zero_cuda_symbols = (omega_blackwell_verify_zero_cuda_symbols(NULL) == 0); - exec_info->zero_libcuda_runtime = (omega_blackwell_verify_zero_libcuda_runtime() == 0); - } - - M16NativeContext ctx; - if (m16_native_open(&ctx) != 0) { return -1; } - if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return -1; } - - /* GB10: all buffers GPU-uncached, see omega_blackwell_execute_matmul. */ - NvrmMem large_pb; - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return -1; } - ctx.pb_mem = large_pb; - - size_t a_elems = (size_t)spec->m * spec->k; - size_t b_elems = (size_t)spec->k * spec->n; - size_t c_elems = (size_t)spec->m * spec->n; - - size_t a_bytes = ((a_elems * 2) + 0xFFFULL) & ~0xFFFULL; - if (a_bytes < 0x1000) a_bytes = 0x1000; - size_t b_bytes = ((b_elems * 2) + 0xFFFULL) & ~0xFFFULL; - if (b_bytes < 0x1000) b_bytes = 0x1000; - size_t c_bytes = ((c_elems * 4) + 0xFFFULL) & ~0xFFFULL; - if (c_bytes < 0x1000) c_bytes = 0x1000; - size_t code_bytes = omega_gpu_code_alloc_bytes(kernel->code_size); /* code + 2 KB prefetch tail, page rounded */ - if (code_bytes == 0) return -1; - - NvrmMem code_mem, cbank_mem, a_mem, b_mem, c_mem, marker_mem, qmd_mem; - if (nvrm_alloc_gpu_uncached(&ctx.rm, code_bytes, &code_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x1000, &cbank_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, a_bytes, &a_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, b_bytes, &b_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, c_bytes, &c_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x1000, &marker_mem) != 0) { m16_native_close(&ctx); return -1; } - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &qmd_mem) != 0) { m16_native_close(&ctx); return -1; } - - /* Copy dynamic machine code into code_mem */ - memcpy(code_mem.cpu, kernel->code, kernel->code_size); - memset((uint8_t *)code_mem.cpu + kernel->code_size, 0, code_bytes - kernel->code_size); - - /* Populate input buffers A, B and initialize C with poison */ - memcpy(a_mem.cpu, h_a, a_elems * 2); - memcpy(b_mem.cpu, h_b, b_elems * 2); - float *c_dev = (float *)c_mem.cpu; - for (size_t i = 0; i < c_elems; i++) { - c_dev[i] = -999.0f; - } - - uint32_t threads_x = 32; - uint32_t threads_y = 1; - uint32_t grid_x = spec->n / 8; - uint32_t grid_y = spec->m / 16; - if (grid_x == 0) grid_x = 1; - if (grid_y == 0) grid_y = 1; - - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, threads_y, grid_x, grid_y); - - uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - omega_blackwell_build_cbank_args_matmul(cbank_args, a_mem.va, b_mem.va, c_mem.va, spec->m, spec->k, spec->n); - - memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); - memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args)); - - uint64_t qmd0_va = qmd_mem.va; - uint64_t qmd1_va = qmd_mem.va + 0x1000; - uint64_t sem_va = qmd_mem.va + 0x2000; - uint64_t scratch_va = qmd_mem.va + 0x4000; - - OmegaBlackwellQmdConfig qmd_cfg = { - .code_va = code_mem.va, - .cbank_va = cbank_mem.va, - .scratch_va = scratch_va, - .sem_va = sem_va, - .qmd0_va = qmd0_va, - .qmd1_va = qmd1_va, - .num_elements = c_elems, - .threads_per_block = 32, - .grid_width = grid_x * grid_y, - .threads_x = threads_x, - .threads_y = threads_y, - .grid_x = grid_x, - .grid_y = grid_y, - .gpr_count = 64 - }; - - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS]; - uint32_t qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg); - - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return -1; } - - memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words)); - memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words)); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); - *hsem = 0; - *hmarker = 0; - *hmarker2 = 0; - __asm__ volatile("dsb sy" ::: "memory"); - - uint32_t pb[1024]; - size_t pb_len = 0; - - memcpy(&pb[pb_len], SETUP_WORDS, sizeof(SETUP_WORDS)); - pb_len += sizeof(SETUP_WORDS) / 4; - - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)(cbank_mem.va >> 32); - pb[pb_len++] = (uint32_t)cbank_mem.va; - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000380; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[pb_len], cbank_data, 224 * 4); - pb_len += 224; - - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); - pb[pb_len++] = (uint32_t)(cbank_mem.va + 0x380); - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000028; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (10 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[pb_len], cbank_args, 10 * 4); - pb_len += 10; - - pb[pb_len++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[pb_len++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); - pb[pb_len++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[pb_len], qmd0_words, 96 * 4); - pb_len += 96; - - pb[pb_len++] = nvrm_mthd(1, 0x0188, 2); - pb[pb_len++] = (uint32_t)(sem_va >> 32); - pb[pb_len++] = (uint32_t)sem_va; - pb[pb_len++] = nvrm_mthd(1, 0x0180, 2); - pb[pb_len++] = 0x00000004; - pb[pb_len++] = 0x00000001; - pb[pb_len++] = nvrm_mthd(1, 0x01b0, 1); - pb[pb_len++] = 0x00000041; - pb[pb_len++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - pb[pb_len++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - - pb[pb_len++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[pb_len++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); - pb[pb_len++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[pb_len], qmd1_words, 96 * 4); - pb_len += 96; - - pb[pb_len++] = nvrm_mthd(0, 0x005c, 5); - pb[pb_len++] = (uint32_t)marker_mem.va; - pb[pb_len++] = (uint32_t)(marker_mem.va >> 32); - pb[pb_len++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; - pb[pb_len++] = 0; - pb[pb_len++] = 0x1 | (1u << 20); - - /* C3 tail, same words as omega_blackwell_execute_matmul above: L2_FLUSH_DIRTY, then a - * second WFI release at marker page + 0x10 that the host waits for before the readback. */ - pb[pb_len++] = nvrm_mthd(0, 0x0028, 4); - pb[pb_len++] = 0; - pb[pb_len++] = 0; - pb[pb_len++] = 0; - pb[pb_len++] = (0x10u << 27); - pb[pb_len++] = nvrm_mthd(0, 0x005c, 5); - pb[pb_len++] = (uint32_t)(marker_mem.va + 0x10); - pb[pb_len++] = (uint32_t)((marker_mem.va + 0x10) >> 32); - pb[pb_len++] = OMEGA_BW_MARKER2_PAYLOAD; - pb[pb_len++] = 0; - pb[pb_len++] = 0x1 | (1u << 20); - - uint64_t t_start = current_time_ns(); - if (m16_native_submit_methods(&ctx, pb, pb_len) != 0) { m16_native_close(&ctx); return -1; } - - /* CHIPWAIT-2: marker with marker2 required (C3: the second release lands only after the L2 flush). */ - if (bw_wait_one(__func__, "marker", hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, hmarker2, OMEGA_BW_MARKER2_PAYLOAD) != 0) { m16_native_close(&ctx); return -1; } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t_end = current_time_ns(); - - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return -1; } - - memcpy(h_c_out, c_mem.cpu, c_elems * sizeof(float)); - - float *h_expected = (float *)malloc(c_elems * sizeof(float)); - if (!h_expected) { m16_native_close(&ctx); return -1; } - - if (spec->precision == OMEGA_MATMUL_PRECISION_FP16) { - omega_matmul_cpu_oracle_f16((const uint16_t *)h_a, (const uint16_t *)h_b, h_expected, spec->m, spec->k, spec->n); - } else { - omega_matmul_cpu_oracle_bf16((const uint16_t *)h_a, (const uint16_t *)h_b, h_expected, spec->m, spec->k, spec->n); - } - - float max_abs = 0.0f; - float max_rel = 0.0f; - size_t mismatches = 0; - for (size_t i = 0; i < c_elems; i++) { - float exp = h_expected[i]; - float act = h_c_out[i]; - float diff = fabsf(exp - act); - float rel = (fabsf(exp) > 1e-6f) ? (diff / fabsf(exp)) : diff; - if (diff > max_abs) max_abs = diff; - if (rel > max_rel) max_rel = rel; - if (diff > 1e-4f) { - mismatches++; - } - } - free(h_expected); - - if (out_max_abs_err) *out_max_abs_err = max_abs; - if (out_max_rel_err) *out_max_rel_err = max_rel; - - if (exec_info) { - exec_info->launch_timestamp_ns = t_start; - exec_info->completion_timestamp_ns = t_end; - exec_info->elapsed_ns = (t_end > t_start) ? (t_end - t_start) : 0; - exec_info->completion_marker = *hmarker; - exec_info->intermediate_semaphore = *hsem; - exec_info->mismatch_count = mismatches; - exec_info->parity_verified = (mismatches == 0); - } - - m16_native_close(&ctx); - return (mismatches == 0) ? 0 : -1; -} - -int omega_blackwell_verify_zero_libcuda_linkage(const char *binary_path) { - char cmd[512]; - if (binary_path) { - snprintf(cmd, sizeof(cmd), "ldd %s 2>/dev/null", binary_path); - } else { - snprintf(cmd, sizeof(cmd), "ldd /proc/self/exe 2>/dev/null"); - } - - FILE *f = popen(cmd, "r"); - if (!f) return -1; - - char line[512]; - bool found_cuda = false; - while (fgets(line, sizeof(line), f)) { - if (strstr(line, "libcuda.so") || strstr(line, "libcudart.so")) { - found_cuda = true; - break; - } - } - pclose(f); - return found_cuda ? -1 : 0; -} - -int omega_blackwell_verify_zero_cuda_symbols(const char *binary_path) { - char cmd[512]; - if (binary_path) { - snprintf(cmd, sizeof(cmd), "nm -u %s 2>/dev/null", binary_path); - } else { - snprintf(cmd, sizeof(cmd), "nm -u /proc/self/exe 2>/dev/null"); - } - - FILE *f = popen(cmd, "r"); - if (!f) return -1; - - char line[512]; - bool found_cuda_sym = false; - while (fgets(line, sizeof(line), f)) { - char sym[256]; - if (sscanf(line, " %*s %255s", sym) == 1 || sscanf(line, "%255s", sym) == 1) { - if (strncmp(sym, "cu", 2) == 0 || strncmp(sym, "cuda", 4) == 0) { - found_cuda_sym = true; - break; - } - } - } - pclose(f); - return found_cuda_sym ? -1 : 0; -} - -int omega_blackwell_verify_zero_libcuda_runtime(void) { - FILE *f = fopen("/proc/self/maps", "r"); - if (!f) return -1; - - char line[512]; - bool found_cuda = false; - while (fgets(line, sizeof(line), f)) { - if (strstr(line, "libcuda") || strstr(line, "libcudart")) { - found_cuda = true; - break; - } - } - fclose(f); - return found_cuda ? -1 : 0; -} diff --git a/src/omega_blackwell_submit.h b/src/omega_blackwell_submit.h deleted file mode 100644 index e9d330717..000000000 --- a/src/omega_blackwell_submit.h +++ /dev/null @@ -1,95 +0,0 @@ -#ifndef OMEGA_BLACKWELL_SUBMIT_H -#define OMEGA_BLACKWELL_SUBMIT_H - -#include "omega_types.h" -#include "omega_vector.h" -#include "omega_blackwell_realize.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include - -#define OMEGA_BW_MARKER_COMPLETION_PAYLOAD 0x44444444U -#define OMEGA_BW_MARKER2_PAYLOAD 0x46464646u /* C3 second release, after the L2 flush */ -/* Shader-cache invalidate, emitted as the first compute method of every launch that - * uploads kernel code (cut 1b finding: the SM instruction cache is not coherent with - * host writes; after a kernel-cache slot was evicted and its code address reused, the - * chip ran stale instructions). Method and bits from NVIDIA open-gpu-doc - * classes/compute/clcec0.h (BLACKWELL_COMPUTE_B): NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, - * _INSTRUCTION 0:0, _DATA 4:4, _CONSTANT 12:12. The shipped driver tree's clcec0.h is a - * 30-line class-id stub and does not list the method; chip-proven by receipt - * FB1-CUT1B-4345406 (18/18 parity after the fix). Emit: nvrm_mthd(1, MTHD, 1), ALL. */ -#define OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES 0x021cu -#define OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL ((1u << 0) | (1u << 4) | (1u << 12)) -#define OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT 5U -#define OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE 6U - -typedef struct { - char target_chip[64]; - uint32_t sm_architecture; - uint32_t element_count; - uint64_t launch_timestamp_ns; - uint64_t completion_timestamp_ns; - uint64_t elapsed_ns; - uint32_t completion_marker; - uint32_t intermediate_semaphore; - bool parity_verified; - bool zero_libcuda_linkage; - bool zero_cuda_symbols; - bool zero_libcuda_runtime; -} OmegaBlackwellVectorExecution; - -typedef struct { - char target_chip[64]; - uint32_t sm_architecture; - uint32_t m, k, n; - uint64_t launch_timestamp_ns; - uint64_t completion_timestamp_ns; - uint64_t elapsed_ns; - uint32_t completion_marker; - uint32_t intermediate_semaphore; - bool parity_verified; - size_t mismatch_count; - bool zero_libcuda_linkage; - bool zero_cuda_symbols; - bool zero_libcuda_runtime; -} OmegaBlackwellMatMulExecution; - -/* Execute vector addition on physical GB10 silicon. Since cut A3b1 (DRAFT, chip-unproven) the - * device sequence runs through omega_gpu_execute with the Blackwell backend in - * src/omega_blackwell_engine.c; this wrapper keeps the host oracle and the result fields. */ -int omega_blackwell_execute_vector(const OmegaVectorSpec *spec, - const OmegaBlackwellRealization *real, - const uint32_t *h_a, - const uint32_t *h_b, - uint32_t *h_c_out, - OmegaBlackwellVectorExecution *exec_info); - -/* Execute dynamic matrix multiplication on physical GB10 silicon through frozen M16 native submission */ -/* Execute dynamic tensor matrix multiplication on physical GB10 silicon through frozen M16 native submission */ -int omega_blackwell_execute_matmul_tensor(const OmegaMatMulSpec *spec, - const OmegaBlackwellKernel *kernel, - const void *h_a, - const void *h_b, - float *h_c_out, - OmegaBlackwellMatMulExecution *exec_info, - float *out_max_abs_err, - float *out_max_rel_err); - -int omega_blackwell_execute_matmul(const OmegaMatMulSpec *spec, - const OmegaBlackwellKernel *kernel, - const uint32_t *h_a, - const uint32_t *h_b, - uint32_t *h_c_out, - OmegaBlackwellMatMulExecution *exec_info); - -/* Validate that omegatool binary has zero dynamic linkage to libcuda.so or libcudart.so */ -int omega_blackwell_verify_zero_libcuda_linkage(const char *binary_path); - -/* Validate that omegatool binary has zero undefined symbols starting with cu or cuda */ -int omega_blackwell_verify_zero_cuda_symbols(const char *binary_path); - -/* Validate that current running process has zero mapped regions of libcuda */ -int omega_blackwell_verify_zero_libcuda_runtime(void); - -#endif /* OMEGA_BLACKWELL_SUBMIT_H */ diff --git a/src/omega_bw_em.h b/src/omega_bw_em.h deleted file mode 100644 index e72c743e0..000000000 --- a/src/omega_bw_em.h +++ /dev/null @@ -1,145 +0,0 @@ -/* omega_bw_em.h: the IR emitter helpers shared by the OWN-30B tensor-core generators (T3/T3b; private, static, header-only). - * Moved verbatim out of omega_blackwell_codegen_tc.c (T3 cut 1, chip-proven scheduling rules); see that file for the history. */ -#ifndef OMEGA_BW_EM_H -#define OMEGA_BW_EM_H -#include "omega_blackwell_codegen_tc.h" -#include -#pragma GCC diagnostic ignored "-Wunused-function" - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define NOREG (-1) -#define MAX_LOOPS 4 - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending, held; - int err; - int open_start[MAX_LOOPS]; - int depth; -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - /* Loads read their address operands late (the read barrier SB_RD): a later instruction must not overwrite an - * in-flight load's address register. Every load sets SB_RD and the next load of a batch waits on it (cheap: - * the operand read, not the data). Found on the chip: the deep k=2048 kernel hung when the allocator reused a - * dead scale address register as the next load's destination (evidence OWN30B-FP8-GEMV-c4006391). */ - case K_VAR: in.control = CW(4, SB_GPR, SB_RD, wait) | CW_YIELD; e->pending = (1u << SB_GPR) | (1u << SB_RD); break; - /* a further load of the same group: waits on nothing, joins the counting scoreboard */ - case K_VAR_MORE: in.control = CW(4, SB_GPR, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; e->pending |= (1u << SB_GPR) | (1u << SB_RD); break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; /* BAR.SYNC after the STS: the attention kernel's chip-proven pattern */ - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -static void ldcu64(Em *e, int ud, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = ud; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int d, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = d; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int d, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = d; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int d, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = d; i.imm = imm; emit(e, i, K_FIXED); } -static void movrz(Em *e, int d) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = d; emit(e, i, K_FIXED); } -/* d = a * imm + c (c NOREG = RZ); a may be a sub-register of a quad */ -static void imadi(Em *e, int d, int a, unsigned asub, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d = a * b + c (registers) */ -static void imadr(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* d64 = a * imm + c64 */ -static void imadw(Em *e, int d64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = d64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -static void shr(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void andi(Em *e, int d, int a, unsigned asub, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.imm = imm; emit(e, i, K_FIXED); } -static void ldg_wide(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, int first) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); -} -static void ldg32(Em *e, int d, int addr64, int udesc, int first) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = d; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void stg(Em *e, int addr64, uint32_t imm, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -static void lds128(Em *e, int d128, int addr, uint32_t imm, int first) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = d128; i.src1_vreg = addr; i.imm = imm; emit(e, i, first ? K_VAR : K_VAR_MORE); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void bar_sync(Em *e) { emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* d = a * b[bsub] + c */ -static void ffma(Em *e, int d, int a, int b, unsigned bsub, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void shfl_down(Em *e, int d, int a, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_if_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void bra(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -/* a forward branch whose target is patched when known: returns the instruction index */ -static int bra_if_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void patch_bra(Em *e, int at, int target) { if (!e->err) e->p->insns[at].imm = (uint32_t)(target - at); } -static int bssy_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = 0; i.imm = 2; emit(e, i, K_BSSY); return at; } -static void bsync(Em *e) { BlackwellIRInsn i = I0(BW_IR_BSYNC); i.bar_reg = 0; emit(e, i, K_BSYNC); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} - -/* Loops: a value defined before the loop and read inside it stays live until the back-branch - * (the linear-scan allocator knows no back edges; same rule as the elementwise emitter). */ -static void loop_begin(Em *e) { if (e->depth >= MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -static void loop_end(Em *e) { - if (e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - - -/* A weight/scale prefetch load: scoreboard `sb` (3 or 4) is held, not waited for, until consume() */ -static void ldw_pf(Em *e, BlackwellIROpcode op, int d, int addr64, uint32_t imm, int udesc, unsigned sb) { - BlackwellIRInsn in = I0(op); in.dst_vreg = d; in.src1_vreg = addr64; in.imm = imm; in.ureg = udesc; - in.control = CW(4, sb, SB_RD, (e->pending & (1u << SB_RD))) | CW_YIELD; - e->pending |= 1u << SB_RD; e->held |= 1u << sb; - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} -static void consume(Em *e, unsigned sb) { e->pending |= e->held & (1u << sb); e->held &= ~(1u << sb); } - -static int log2u(uint32_t v) { int l = 0; while ((1u << l) < v) l++; return (1u << l) == v ? l : -1; } - -/* HMMA d = a * b + c (a quad, b pair, c/d quad; c NOREG = RZ). stall 8: the next instruction must not read d (nvcc's - * spacing for independent HMMAs); hmma_wait15 + nop14 before any reader of d. */ -static void hmma(Em *e, int d, int a, int b, int c, uint32_t stall) { - BlackwellIRInsn i = I0(BW_IR_HMMA_BF16); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; - i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; - if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; -} -static void nop(Em *e, uint32_t stall) { - BlackwellIRInsn i = I0(BW_IR_NOP); i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; - if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; -} -static void lop3(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut; emit(e, i, K_FIXED); } -static void iadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void shfl_bfly(Em *e, int d, int a, uint32_t lane) { shfl_down(e, d, a, OMEGA_TC_MARK_BFLY | (lane & 31u)); } -static void f2fp_pack(Em *e, int d, int hi, int lo) { BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d; i.src1_vreg = hi; i.src2_vreg = lo; i.imm = OMEGA_TC_MARK_F2FP; emit(e, i, K_FIXED); } -#endif diff --git a/src/omega_bw_em_q.h b/src/omega_bw_em_q.h deleted file mode 100644 index 874a3de5c..000000000 --- a/src/omega_bw_em_q.h +++ /dev/null @@ -1,18 +0,0 @@ -/* omega_bw_em_q.h: private emitters for the native FP8 ops (W-L1G, 2026-10-14). Include after omega_bw_em.h. - * Both are placeholders patched by omega_qmma_patch_code (omega_blackwell_codegen_qmma.h). */ -#ifndef OMEGA_BW_EM_Q_H -#define OMEGA_BW_EM_Q_H -#include "omega_blackwell_codegen_qmma.h" -/* QMMA.16832.F32.E4M3.E4M3 d = a * b + c (c NOREG = RZ); operands may start at a subregister (b pair inside a quad) */ -static void qmma_s(Em *e, int d, int a, int b, unsigned bsub, int c, uint32_t stall) { - BlackwellIRInsn i = I0(BW_IR_HMMA_BF16); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.src3_vreg = c; i.imm = OMEGA_QMMA_MARK; - i.control = CW(stall, SB_NONE, SB_NONE, e->pending); e->pending = 0; - if (omega_bw_ir_append(e->p, &i) < 0) e->err = -1; -} -static void qmma(Em *e, int d, int a, int b, int c, uint32_t stall) { qmma_s(e, d, a, b, 0, c, stall); } -/* F2FP.SATFINITE.E4M3.F32.PACK_AB_MERGE_C Rd, Ra, Rb, RZ: Rd = e4m3(Ra) << 8 | e4m3(Rb) (byte order INFERRED, chip probe checks) */ -static void f2e4(Em *e, int d, int a, unsigned asub, int b, unsigned bsub) { - BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)asub; i.src2_vreg = b; i.src2_subreg = (uint8_t)bsub; i.imm = OMEGA_QMMA_MARK_F2E4; - emit(e, i, K_FIXED); -} -#endif diff --git a/src/omega_bw_reconv.h b/src/omega_bw_reconv.h deleted file mode 100644 index d432e5763..000000000 --- a/src/omega_bw_reconv.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef OMEGA_BW_RECONV_H -#define OMEGA_BW_RECONV_H -/* Structured warp reconvergence regions for the Blackwell IR emitters (omega #308). - * - * A region is the span between a BSSY (arm barrier Bn, name the join point) and the - * matching BSYNC (wait for every armed lane, continue as one warp). Inside a region the - * lanes of a warp may take different paths: a predicated forward branch, a loop whose - * trip count differs per lane, a break. Every path that leaves the region jumps to the - * BSYNC itself (that is where nvcc 13.0.88 sends loop exits on sm_121); the BSSY names the - * instruction after the BSYNC. Regions nest; the innermost open region owns Bn with - * n = depth, so nesting depth is bounded by the barrier register count and begin fails - * closed (returns -1) when that bound is reached. - * - * This header holds the bookkeeping only (indices, patching, bounds). Each emitter wraps - * it with its own control-word scheme: see region_begin / region_exit / region_join in - * src/omega_gpu_elementwise_api.c and src/omega_gpu_attention_api.c. - * - * Reference: Mesa NAK nak_nir_lower_cf.c (push_scope / pop_scope: bar_set_nv before a - * divergent if or loop, bar_sync_nv at its merge block, breaks jump to the sync) and the - * nvcc oracle listing in docs/gpu-reconvergence-308.md. */ - -#include "omega_blackwell_codegen.h" - -#define BW_RECONV_MAX_DEPTH BW_RECONV_MAX_BAR -#define BW_RECONV_MAX_EXITS 8 /* forward exits (breaks) recorded per region */ - -typedef struct { - int depth; /* open regions */ - int peak; /* deepest nesting seen (reported in receipts) */ - int opened; /* regions begun (for receipts) */ - int bssy_at[BW_RECONV_MAX_DEPTH]; - int exits[BW_RECONV_MAX_DEPTH][BW_RECONV_MAX_EXITS]; - int n_exits[BW_RECONV_MAX_DEPTH]; -} BwRegions; - -/* Called after the emitter appended the BSSY at index `bssy_index`. Returns the barrier - * register to use, or -1 when the nesting bound is reached (the caller must fail the - * build: no code with a missing barrier may be emitted). The caller allocates the - * barrier BEFORE emitting: use bw_regions_next_bar to pick it, then bw_regions_begin. */ -static inline int bw_regions_next_bar(const BwRegions *r) { - return r->depth < BW_RECONV_MAX_DEPTH ? r->depth : -1; -} -static inline int bw_regions_begin(BwRegions *r, int bssy_index) { - if (r->depth >= BW_RECONV_MAX_DEPTH || bssy_index < 0) return -1; - r->bssy_at[r->depth] = bssy_index; - r->n_exits[r->depth] = 0; - r->depth++; - r->opened++; - if (r->depth > r->peak) r->peak = r->depth; - return r->depth - 1; -} - -/* Records a forward branch (already appended at `bra_index`) that leaves the innermost - * open region; its target is patched to the BSYNC by bw_regions_join. -1 when no region - * is open or the per-region exit table is full. */ -static inline int bw_regions_exit(BwRegions *r, int bra_index) { - if (r->depth <= 0 || bra_index < 0) return -1; - int d = r->depth - 1; - if (r->n_exits[d] >= BW_RECONV_MAX_EXITS) return -1; - r->exits[d][r->n_exits[d]++] = bra_index; - return 0; -} - -/* Called after the emitter appended the BSYNC at index `bsync_index` for the innermost - * open region. Patches the BSSY to name the instruction after the BSYNC and every - * recorded exit to jump to the BSYNC. Returns the barrier register closed, or -1 when - * no region is open or an index is inconsistent (BSSY must precede the BSYNC). */ -static inline int bw_regions_join(BwRegions *r, BlackwellIRProgram *p, int bsync_index) { - if (r->depth <= 0 || !p || bsync_index < 0 || (size_t)bsync_index >= p->count) return -1; - int d = --r->depth; - int at = r->bssy_at[d]; - if (at < 0 || at >= bsync_index || p->insns[at].op != BW_IR_BSSY || p->insns[bsync_index].op != BW_IR_BSYNC) return -1; - if (p->insns[at].bar_reg != (uint8_t)d || p->insns[bsync_index].bar_reg != (uint8_t)d) return -1; - p->insns[at].imm = (uint32_t)(bsync_index + 1 - at); - for (int i = 0; i < r->n_exits[d]; i++) { - int b = r->exits[d][i]; - if (b <= at || b >= bsync_index || p->insns[b].op != BW_IR_BRA) return -1; - p->insns[b].imm = (uint32_t)(bsync_index - b); - } - return d; -} - -#endif /* OMEGA_BW_RECONV_H */ diff --git a/src/omega_gpu_attention_api.c b/src/omega_gpu_attention_api.c deleted file mode 100644 index d9d56b121..000000000 --- a/src/omega_gpu_attention_api.c +++ /dev/null @@ -1,1436 +0,0 @@ -/* omega_gpu_attention_api.c: FB-1 cut 5 (2026-10-04). See the header. - * - * Layout: (1) kernel codegen on the BlackwellIR with the serialising scheduler - * of cut 4 (every instruction waits on everything still pending; slow and safe), - * extended with forward branches and more loops; (2) the launcher, cloned from - * cut 4's run_abc with a fourth buffer (block tables and context lengths), 16 - * argument words, and cut 1b's shader-cache invalidate; (3) the public entry - * points, which stage the referenced KV blocks per launch and apply the oracle's - * argument rules (dropped tokens past the table, negative table entries, zero - * context) on the host. - * - * One CTA per (query head, sequence), head_dim threads (64 or 128; the text below says 64, the - * constants scale with KSpec.hd). The context is walked in chunks of head_dim tokens: - * phase A thread t owns token base+t: block lookup, K dot q (f32 FFMA), s = dot * scale - * (scale folds 1/sqrt(d) and log2 e), s and the token's byte offset go to shared; - * reduce chunk max (SHFL.DOWN tree per warp, lane partials to shared, BAR.SYNC, 2 LDS), - * m_new = max(m, chunk max), alpha = EX2(m - m_new), p = EX2(s - m_new) to shared, - * chunk sum the same way, l = l * alpha + chunk sum; - * phase B thread d owns dimension d: acc = acc * alpha + sum over the chunk of p_t * V[t][d]. - * Then out[d] = acc * RCP(l). The first chunk sees m = -inf, so alpha = EX2(-inf) = 0 and - * the initial l and acc drop out (PTX ISA ex2.approx: ex2(-Inf) = +0). - * - * Shared memory (16 * head_dim bytes; hd 64: 1024 bytes, the QMD default): [0,4hd) q, [4hd,8hd) s then p, - * [8hd,12hd) token byte offsets, [12hd,16hd) warp partials for the reductions (hd 64: 0, 256, 512, - * 768; hd 128: 0, 512, 1024, 1536; the partials of warp w are read at 12hd + 128w). - */ -#include "omega_gpu_attention_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_bw_reconv.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "sha256.h" -#ifdef OMEGA_ATTN_DEBUG -#include /* the debug trace only; never in the freestanding build */ -#endif -#include - -/* ------------------------------------------------------------------ codegen */ - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u -#define SB_RD 1u -#define SB_UGPR 2u -#define SB_LD2 4u /* second scoreboard for batched loads (the matmul kernel's B-load word, omega #328) */ -#define SB_LD3 3u /* third: phase B keeps shared loads and the two halves of the V loads on separate scoreboards */ -#define AT_BATCH_MAX 4 /* loads in flight per scoreboard: 4 complete on the chip, 8 never did (omega #328) */ - -enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -#define AT_MAX_LOOPS 8 -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; - uint32_t batch; /* scoreboards the open load batch is filling (no wait on them inside the batch) */ - int batch_n[8]; /* loads issued per scoreboard in the open batch */ - int err; - int loop_start[AT_MAX_LOOPS], loop_end[AT_MAX_LOOPS]; - int n_loops, depth, stack[AT_MAX_LOOPS]; - BwRegions rg; /* structured reconvergence regions (omega #308) */ - int rg_mutant; /* test only: 1 = drop the BSYNC at join (the 2026-10-04 bug shape; host sim must catch it) */ -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - e->batch = 0; memset(e->batch_n, 0, sizeof e->batch_n); /* an ordinary instruction waits on the whole batch */ - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(13, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - /* stall counts as nvcc 13.0.88 writes them for sm_121 (see src/omega_gpu_elementwise_api.c) */ - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} - -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int V128(Em *e) { int v = omega_bw_ir_alloc_vreg128(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -#define NOREG -1 -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static void ldcu64(Em *e, int udst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = udst; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int dst64, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = dst64; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int dst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = dst; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int dst, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = dst; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int dst, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = dst; i.imm = imm; emit(e, i, K_FIXED); } -static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); } -static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); } -/* dst = a * imm + c (c may be NOREG for RZ) */ -static void imadi(Em *e, int dst, int a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* dst = a * b + c (registers; c may be NOREG) */ -static void imadr(Em *e, int dst, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void iadd3(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void lop3xor(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void lop3andi(Em *e, int dst, int a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; emit(e, i, K_FIXED); } -static void shri(Em *e, int dst, int a, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; emit(e, i, K_FIXED); } -/* dst64 = idx * imm + base64 (byte address) */ -static void wide(Em *e, int dst64, int idx, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.imm = imm; i.src3_vreg = base64; emit(e, i, K_FIXED); } -static void ldg(Em *e, int dst, int addr64, int udesc) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, K_VAR); } -/* Batched loads (2026-10-12, long-context finding): every load above waits on the previous one, so - * phase A paid one global latency per dim pair and phase B one per token (~6 GB/s at 1268 ctx). A - * batched load sets `sb` and waits on every pending scoreboard except the ones the open batch is - * filling (and SB_RD, its read barrier), so up to AT_BATCH_MAX loads per scoreboard are in flight. - * The next ordinary instruction (emit) waits on all of them. SB_RD covers the address register: the - * allocator may hand that register to a later load's data before this load has read it. */ -static void emit_batched(Em *e, BlackwellIRInsn in, uint32_t sb) { - if (sb >= 8 || e->batch_n[sb] >= AT_BATCH_MAX) { e->err = -1; return; } - in.control = CW(4, sb, SB_RD, e->pending & ~e->batch) | CW_YIELD; - e->batch |= (1u << sb) | (1u << SB_RD); e->batch_n[sb]++; - e->pending |= (1u << sb) | (1u << SB_RD); - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} -/* A fixed-latency instruction inside an open load batch: it waits on the batch's read barrier (its - * destination may be a load's address register, which the load may read late) but not on the loads' - * data, so the address of the next load is computed while the earlier loads are in flight. Only for - * instructions that read no result of the open batch. */ -static void emit_fixed_in_batch(Em *e, BlackwellIRInsn in) { - uint32_t wait = (e->pending & ~e->batch) | (e->batch ? (1u << SB_RD) : 0u); - in.control = CW(6, SB_NONE, SB_NONE, wait); - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; -} -static void ldg128_b(Em *e, int dst128, int addr64, uint32_t imm, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E_128); i.dst_vreg = dst128; i.src1_vreg = addr64; i.imm = imm; i.ureg = udesc; emit_batched(e, i, sb); } -static void ldg_b(Em *e, int dst, int addr64, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit_batched(e, i, sb); } -static void ldg16_b(Em *e, int dst, int addr64, int udesc, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDG_E_U16); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit_batched(e, i, sb); } -static void lds128_b(Em *e, int dst128, int addr, uint32_t imm, uint32_t sb) { BlackwellIRInsn i = I0(BW_IR_LDS128); i.dst_vreg = dst128; i.src1_vreg = addr; i.imm = imm; emit_batched(e, i, sb); } -/* sub-register operands of a quad */ -static void e_ffma_s(Em *e, int d, int a, int as, int b, int bs, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.src2_vreg = b; i.src2_subreg = (uint8_t)bs; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void imadi_s(Em *e, int dst, int a, int as, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void lop3andi_s(Em *e, int dst, int a, int as, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_LOP3_AND); i.dst_vreg = dst; i.src1_vreg = a; i.src1_subreg = (uint8_t)as; i.imm = imm; emit(e, i, K_FIXED); } -static void wide_s(Em *e, int dst64, int idx, int is, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.src1_subreg = (uint8_t)is; i.imm = imm; i.src3_vreg = base64; emit(e, i, K_FIXED); } -static void wide_s_b(Em *e, int dst64, int idx, int is, uint32_t imm, int base64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.src1_subreg = (uint8_t)is; i.imm = imm; i.src3_vreg = base64; emit_fixed_in_batch(e, i); } -static void stg(Em *e, int addr64, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.ureg = udesc; emit(e, i, K_STORE); } -static void e_fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void e_fsub(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FSUB); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void e_fmul(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void e_ffma(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void e_fmax(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMNMX_MAX); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void mufu(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); } -/* SHFL and BAR.SYNC are refused inside an open reconvergence region (omega #308): on a split - * warp they read inactive lanes / count a partial warp, which is what produced wrong dims on - * the chip on 2026-10-04. The build fails closed instead. */ -static int in_region(Em *e) { if (e->rg.depth > 0) { e->err = -1; return 1; } return 0; } -static void shfl_down(Em *e, int d, int a, uint32_t off) { if (in_region(e)) return; BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void lds32(Em *e, int d, int addr) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d; i.src1_vreg = addr; emit(e, i, K_VAR); } -static void bar_sync(Em *e) { if (in_region(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -static void bra_back_if_not_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.predicate_not = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -/* @P0 BRA forward; the target is patched in when known */ -static int bra_fwd_if_p0(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 0; emit(e, i, K_BRA); return at; } -static void patch_fwd(Em *e, int at) { if (at >= 0 && (size_t)at < e->p->count) e->p->insns[at].imm = (uint32_t)(here(e) - at); else e->err = -1; } - -/* ---- structured reconvergence regions (omega #308); same API as the elementwise emitter ---- */ -enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 }; -static int region_begin(Em *e) { - int bar = bw_regions_next_bar(&e->rg); - if (bar < 0) { e->err = -1; return -1; } - int at = here(e); - BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY); - if (bw_regions_begin(&e->rg, at) < 0) e->err = -1; - return bar; -} -static void region_exit(Em *e, int cond) { - int at = here(e); - BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1; - if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); } - emit(e, i, K_BRA); - if (bw_regions_exit(&e->rg, at) < 0) e->err = -1; -} -static void region_join(Em *e) { - if (e->rg.depth <= 0) { e->err = -1; return; } - int d = e->rg.depth - 1, bsync = here(e); - BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC); - if (e->rg_mutant == 1) { - BwRegions *r = &e->rg; r->depth--; - e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]); - for (int k = 0; k < r->n_exits[d]; k++) e->p->insns[r->exits[d][k]].imm = (uint32_t)(bsync - r->exits[d][k]); - return; - } - if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1; -} -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -/* Loops nest; loop_end() extends every value defined before the loop and read inside - * it to the back-branch (the linear-scan allocator knows nothing about back-edges). */ -static void loop_begin(Em *e) { - if (e->depth >= AT_MAX_LOOPS || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; } - e->stack[e->depth++] = here(e); -} -static void loop_end(Em *e) { - if (e->depth == 0 || e->n_loops >= AT_MAX_LOOPS) { e->err = -1; return; } - int start = e->stack[--e->depth], end = here(e) - 1; - e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} -/* A value first defined inside a loop may not be read after it before being redefined. */ -static int check_loop_invariant(const Em *e) { - const OmegaRegAlloc *ra = &e->p->regalloc; - for (int L = 0; L < e->n_loops; L++) - for (int v = 0; v < ra->num_vregs; v++) { - int fd = ra->intervals[v].first_def; - if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue; - for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) { - const BlackwellIRInsn *in = &e->p->insns[i]; - if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1; - if (in->dst_vreg == v && !in->is_uniform) break; - } - } - return 0; -} - -/* Kernel argument words (constant bank 0 at 0x380; the bank is 1024 bytes, so 32 words fit). */ -#define ARG_Q 0x380u -#define ARG_POOL 0x388u -#define ARG_OUT 0x390u -#define ARG_TAB 0x398u -#define ARG_MAXB 0x3a0u /* words per block-table row */ -#define ARG_SCALE 0x3a4u /* bits of log2(e) / sqrt(head_dim) */ -#define ARG_BSTRIDE 0x3a8u /* bytes between staged blocks */ -#define ARG_TSTRIDE 0x3acu /* bytes between tokens */ -#define ARG_KVP 0x3b0u /* bytes from the K plane to the V plane */ -#define ARG_HSTRIDE 0x3b4u /* bytes between kv heads */ -#define ARG_NQH 0x3b8u /* query heads (q and out row count per sequence) */ -#define ARG_CTXOFF 0x3bcu /* byte offset of the context-length array inside the table buffer */ -#define ARG_WORDS 16u -#define DESC_OFF 0x358u - -/* Head dimension is a kernel parameter (64 or 128, see KSpec.hd). Shared memory is four arrays of hd words: - * q at SH_Q, s then p at hd*4, token byte offsets at hd*8, warp partials at hd*12 (hd 64: 0, 256, 512, 768, - * the layout of every cut before head_dim 128). */ -#define SH_Q 0u -#define F32_NEG_INF 0xff800000u - -/* divergent (omega #308 regression R2): 0 = production branch-free chunk loop; 1 = the - * lane-dependent "j >= ctx" branch restored inside a reconvergence region (BSSY/BSYNC) so - * the SHFL reductions run on a joined warp; 2 = the same with the BSYNC dropped (the - * 2026-10-04 bug shape, a negative control the host simulator must catch). */ -typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; int divergent; uint32_t hd; int split; } KSpec; -/* split (cut F, 2026-10-12): -1 = direct output (the gqa f32 and rows callers; byte for byte the kernel before). - * 0..MAX_LOG2SPLIT = the paged path: 2^split CTAs share one (sequence, head). Each sequence derives its own split - * count from its own context (so its result never depends on the other sequences in the launch), every CTA writes - * an unnormalised partial (acc[hd], running max, running sum; an empty slice writes acc 0, max -inf) and the host - * combines them, also when split == 0. */ - -/* cut K (2026-10-12, GQA group): at head_dim 128 one CTA serves the GC query heads of one kv head, GC = - * min(2^log2gqa, 4), so every K and V byte of a launch is read once instead of once per query head. The KV - * pool is GPU-uncached (host-written), so the four CTAs of a GQA group were four DRAM reads of the same - * bytes: 21 MB per call at 1268 tokens, the memory ceiling (sc leg smoke-ctx-chunk: 152 us per call). - * Grid x is the head group (num_q_heads / GC CTAs per sequence and split). Shared memory: q, scores and - * warp partials per head, token offsets once. GC = 1 (every hd 64 kernel, hd 128 with gqa 1) emits exactly - * the program before this cut (digest fixtures). */ -static uint32_t heads_per_cta(uint32_t hd, uint32_t log2gqa) { return hd == 128u ? (1u << (log2gqa < 2u ? log2gqa : 2u)) : 1u; } -static uint32_t shared_bytes_for(uint32_t hd, uint32_t log2gqa) { return (3u * heads_per_cta(hd, log2gqa) + 1u) * hd * 4u; } -uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa) { return heads_per_cta(head_dim, log2_gqa); } - -static void gen_attention(Em *e, const KSpec *k) { - const uint32_t elem = k->f32 ? 4u : 2u; - const uint32_t HD = k->hd, GC = heads_per_cta(HD, k->log2gqa), log2gc = GC == 4u ? 2u : GC == 2u ? 1u : 0u; - const uint32_t HB = HD * 4u; /* bytes of one per-head shared array */ - const uint32_t SH_S = GC * HB, SH_O = 2u * GC * HB, SH_R = SH_O + HB; /* warps per CTA: HD / 32 */ - int udesc = UV64(e), A = V64(e), B = V64(e), C = V64(e), D = V64(e); - int tid = V(e), h = V(e), seq = V(e); - int p_maxb = V(e), scale = V(e), p_bstride = V(e), p_tstride = V(e), p_kvp = V(e), p_hstride = V(e), p_nqh = V(e), p_ctxoff = V(e); - ldcu64(e, udesc, DESC_OFF); - ldc64(e, A, ARG_Q); ldc64(e, B, ARG_POOL); ldc64(e, C, ARG_OUT); ldc64(e, D, ARG_TAB); - ldc32(e, p_maxb, ARG_MAXB); ldc32(e, scale, ARG_SCALE); ldc32(e, p_bstride, ARG_BSTRIDE); ldc32(e, p_tstride, ARG_TSTRIDE); - ldc32(e, p_kvp, ARG_KVP); ldc32(e, p_hstride, ARG_HSTRIDE); ldc32(e, p_nqh, ARG_NQH); ldc32(e, p_ctxoff, ARG_CTXOFF); - s2r(e, tid, BW_SR_TID_X); s2r(e, h, BW_SR_CTAID_X); s2r(e, seq, BW_SR_CTAID_Y); - - /* cut F, partial mode: grid y = sequence * S + split; the split index picks this CTA's slice of the context (below) */ - const bool part = k->split >= 0; - const uint32_t LS = part ? (uint32_t)k->split : 0u, S = 1u << LS, log2hd = (HD == 128u) ? 7u : 6u; - int split = -1, kb = -1, kend = -1; - if (part) { split = V(e); if (LS) { lop3andi(e, split, seq, S - 1u); shri(e, seq, seq, LS); } else movrz(e, split); } - - int c1 = V(e), c4 = V(e), c32 = V(e), c64 = V(e), c256 = V(e), c512 = V(e), c768 = V(e), c896 = V(e), zero = V(e); - /* c32 / c64 keep their hd 64 names: the inner (dim pair) loop trip count HD / 2 and the chunk size HD */ - movi(e, c1, 1); movi(e, c4, 4); movi(e, c32, HD / 2); movi(e, c64, HD); - movi(e, c256, SH_S); movi(e, c512, SH_O); movi(e, c768, SH_R); movi(e, c896, SH_R + 128); movrz(e, zero); - /* warp partials 2 and 3 (lane 0 of warps 2 and 3): only a 128-thread CTA has them. Created and emitted only - * when HD == 128, so the hd 64 program (vreg numbering, instruction sequence) is exactly the one before. */ - int c1024 = -1, c1152 = -1, rc_ = -1, rd_ = -1; - if (HD == 128) { c1024 = V(e); c1152 = V(e); rc_ = V(e); rd_ = V(e); movi(e, c1024, SH_R + 256); movi(e, c1152, SH_R + 384); } - - /* q[tid] -> shared; out address kept for the end. Row = seq * num_q_heads + head for - * both q and out (flattened head-major, the oracle's layout). The head-wiring mutants - * swap the row of head h with h ^ 1 on one side only. GC > 1: head g of the group is - * h * GC + g; q goes to SH_Q + g * HB; the output rows are derived in the epilogue. */ - int tid4 = V(e), qrow = V(e), qoff = V(e), qaddr = V64(e), qv = V(e), oaddr = GC == 1 ? V64(e) : -1; - int hq = h, ho = h; - if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) { hq = V(e); lop3xor(e, hq, h, c1); } - if (GC == 1 && k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) { ho = V(e); lop3xor(e, ho, h, c1); } - imadi(e, tid4, tid, 4, NOREG); - if (GC == 1) { - imadr(e, qrow, seq, p_nqh, hq); - imadi(e, qoff, qrow, HD * 4, tid4); - wide(e, qaddr, qoff, 1, A); - ldg(e, qv, qaddr, udesc); - sts32(e, tid4, qv); /* SH_Q + tid*4 */ - if (!part) { /* direct output address; partial mode derives its row in the epilogue */ - if (ho == hq) wide(e, oaddr, qoff, 1, C); - else { - int orow = V(e), ooff = V(e); - imadr(e, orow, seq, p_nqh, ho); - imadi(e, ooff, orow, HD * 4, tid4); - wide(e, oaddr, ooff, 1, C); - } - } - } else { - int h0 = V(e), hg = V(e), qsh = V(e); - imadi(e, h0, h, GC, NOREG); - for (uint32_t g = 0; g < GC; g++) { - imadi(e, hg, c1, g, h0); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_Q_ROW) lop3xor(e, hg, hg, c1); - imadr(e, qrow, seq, p_nqh, hg); - imadi(e, qoff, qrow, HD * 4, tid4); - wide(e, qaddr, qoff, 1, A); - ldg(e, qv, qaddr, udesc); - imadi(e, qsh, c1, g * HB, tid4); - sts32(e, qsh, qv); - } - } - - /* kv head offset, this sequence's table row and context length */ - int kvh = V(e), kvoff = V(e), t1 = V(e), tab = V64(e), ca = V64(e), ctx = V(e), vb = V64(e); - shri(e, kvh, h, k->log2gqa - log2gc); /* GC heads per CTA: kv head = (h * GC) >> log2gqa */ - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_KV_HEAD) lop3xor(e, kvh, kvh, c1); - imadr(e, kvoff, kvh, p_hstride, NOREG); - imadr(e, t1, seq, p_maxb, NOREG); - imadi(e, t1, t1, 4, NOREG); - wide(e, tab, t1, 1, D); - imadi(e, t1, seq, 4, p_ctxoff); - wide(e, ca, t1, 1, D); - ldg(e, ctx, ca, udesc); - if (part) { - /* This sequence's own split count s_own = min(S, pow2floor(chunks)), chunks = ceil(ctx / HD), from its own - * context alone (the host picks the launch S the same way over the batch); per = roundup(ceil(ctx / s_own), HD) - * whole chunks per split; this CTA's slice is [kb, kend), kend = min(ctx, kb + per) through the sign bit of - * ctx - (kb + per). Splits past s_own get kb >= kend: an empty partial. Branch-free: candidate 2^c replaces - * per when chunks >= 2^c; the candidates nest, so the largest that fits wins. */ - int per = V(e), x = V(e), cand = V(e), dd = V(e), lt = V(e), cH1 = V(e), cK = V(e); - kb = V(e); kend = V(e); - movi(e, cH1, HD - 1u); - iadd3(e, per, ctx, cH1); lop3andi(e, per, per, ~(HD - 1u)); /* roundup(ctx, HD): one split takes it all */ - shri(e, x, per, log2hd); /* chunks (cut J: one whole chunk per split) */ - for (uint32_t c = 1; c <= LS; c++) { - movi(e, cK, (1u << c) - 1u); iadd3(e, cand, ctx, cK); shri(e, cand, cand, c); - iadd3(e, cand, cand, cH1); lop3andi(e, cand, cand, ~(HD - 1u)); /* roundup(ceil(ctx / 2^c), HD) */ - movi(e, cK, 0u - (1u << c)); iadd3(e, dd, x, cK); shri(e, lt, dd, 31); /* lt = (x < 2^c) */ - imadi(e, dd, cand, 0xFFFFFFFFu, per); /* per - cand */ - imadr(e, per, lt, dd, cand); /* lt ? per : cand */ - } - imadr(e, kb, split, per, NOREG); - iadd3(e, kend, kb, per); - imadi(e, dd, kend, 0xFFFFFFFFu, ctx); - shri(e, lt, dd, 31); - imadr(e, kend, lt, dd, kend); - } - const int lim = part ? kend : ctx; /* the end of this CTA's token range */ - /* V column base for dimension tid: pool + kv plane + tid * elem. The kv head offset is - * already inside the per-token offset phase A leaves in shared memory (found by the host - * simulator: adding it here too read V from the wrong head for every kv head but 0). */ - wide(e, vb, tid, elem, B); - wide(e, vb, p_kvp, 1, vb); - - /* running max, sum and accumulator per head of the group (GC = 1: one of each, as before) */ - int M[4], L[4], acc[4]; - for (uint32_t g = 0; g < GC; g++) M[g] = V(e); - for (uint32_t g = 0; g < GC; g++) L[g] = V(e); - for (uint32_t g = 0; g < GC; g++) acc[g] = V(e); - int base = V(e), sOff = V(e), oOff = V(e), rOff = V(e); - for (uint32_t g = 0; g < GC; g++) movi(e, M[g], F32_NEG_INF); - for (uint32_t g = 0; g < GC; g++) { if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) movrz(e, L[g]); else movf(e, L[g], 1.0f); } /* alpha = 0 on the first chunk clears it */ - for (uint32_t g = 0; g < GC; g++) movrz(e, acc[g]); - if (part) iadd3(e, base, kb, zero); else movrz(e, base); - iadd3(e, sOff, tid4, c256); iadd3(e, oOff, tid4, c512); iadd3(e, rOff, tid4, c768); - bar_sync(e); /* q visible to every thread */ - if (part) isetp_ge_u32(e, kb, kend); else isetp_ge_u32(e, zero, ctx); /* empty range: out = 0 (an empty partial) */ - int bZ = bra_fwd_if_p0(e); - - /* ---------------- chunk loop ---------------- */ - int j = V(e), s[4], koff; - for (uint32_t g = 0; g < GC; g++) s[g] = V(e); - koff = V(e); - int bi = V(e), sl = V(e), ta = V64(e), blk = V(e), ka = V64(e), dot[4], d; - for (uint32_t g = 0; g < GC; g++) dot[g] = V(e); - d = V(e); - int lo = V(e), hi = V(e), qa = V(e), j1 = V(e); - int dneg = V(e), over = V(e), ot = V(e), ctxm1 = V(e), cm1 = V(e), cninf = V(e), nb = V(e), ns = V(e); - int tsh = GC > 1 ? V(e) : -1; /* per-head shared address temporary (GC > 1 only) */ - movi(e, cm1, 0xFFFFFFFFu); iadd3(e, ctxm1, lim, cm1); movi(e, cninf, F32_NEG_INF); - loop_begin(e); - int Lout = here(e); - /* No branch here: a warp split by "j >= ctx" without a BSSY/BSYNC region stays split, and - * the SHFL reductions below then read inactive lanes, which is undefined (wrong dims - * tid >= tail on the chip, 2026-10-04). The IR has BSSY/BSYNC regions since omega #310 - * (omega_bw_reconv.h); this kernel stays branchless and does not use them. - * over = (j >= ctx) as 0/1 from the sign of ctx-1-j; out-of-range lanes read token `base` - * (always < ctx here) and their score is forced to -inf after the dot product with s = -max(-s, nb), nb = -inf or +inf. */ - iadd3(e, j, base, tid); - for (uint32_t g = 0; g < GC; g++) movi(e, s[g], F32_NEG_INF); - movrz(e, koff); - if (k->divergent) { - /* omega #308 R2: the lane-dependent branch, inside a reconvergence region. Lanes with - * j >= ctx skip phase A (s stays -inf, koff 0); the BSYNC at region_join rejoins them - * before the SHFL reductions below. divergent == 2 drops that BSYNC (negative control). */ - region_begin(e); - isetp_ge_u32(e, j, lim); - region_exit(e, RX_IF_P0); - } else { - imadi(e, dneg, j, 0xFFFFFFFFu, ctxm1); /* ctx - 1 - j */ - shri(e, over, dneg, 31); - imadr(e, ot, over, tid, NOREG); - imadi(e, j, ot, 0xFFFFFFFFu, j); /* j - over*tid */ - } - /* phase A: token j */ - shri(e, bi, j, k->log2bs); - lop3andi(e, sl, j, (1u << k->log2bs) - 1u); - wide(e, ta, bi, 4, tab); - ldg(e, blk, ta, udesc); - imadr(e, koff, blk, p_bstride, NOREG); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_SLOT) { - /* K read from slot (t + 1) % block_size, V from the right slot: a K/V mismatch. - * (Shifting both only permutes matched pairs inside a full block, which softmax cannot see.) */ - int sl1 = V(e); - iadd3(e, j1, j, c1); lop3andi(e, sl1, j1, (1u << k->log2bs) - 1u); - imadr(e, sl1, sl1, p_tstride, koff); - iadd3(e, sl1, sl1, kvoff); - wide(e, ka, sl1, 1, B); - imadr(e, koff, sl, p_tstride, koff); - iadd3(e, koff, koff, kvoff); - } else { - imadr(e, koff, sl, p_tstride, koff); - iadd3(e, koff, koff, kvoff); - wide(e, ka, koff, 1, B); - } - /* phase A inner loop (batched, 2026-10-12): two 128-bit global loads of K per pass on SB_GPR (16 dims - * bf16, 8 dims f32) with the first half of the matching q slice as 128-bit shared loads on SB_LD2, one - * wait; then the second half of q, one more (short) wait. The serial loop before paid one global - * latency per dim pair. Two halves keep the pass inside AT_GPR_BUDGET (the whole slice at once is - * 65 to 76 registers). qa = d * 4 is the shared byte offset of q[d]. GC > 1: the same K pass feeds - * every head of the group, each from its own q slice at SH_Q + g * HB (cut K). */ - const uint32_t dims = k->f32 ? 8u : 16u; /* dims per pass: 32 bytes of K either way */ - const uint32_t nq = dims / 4u; /* q quads per pass, loaded in two halves */ - int kx[2], qq[4]; - kx[0] = V128(e); kx[1] = V128(e); - for (uint32_t i = 0; i < nq; i++) qq[i] = V128(e); - for (uint32_t g = 0; g < GC; g++) movrz(e, dot[g]); - movrz(e, d); - loop_begin(e); - int Lin = here(e); - imadi(e, qa, d, 4, NOREG); - ldg128_b(e, kx[0], ka, 0u, udesc, SB_GPR); - ldg128_b(e, kx[1], ka, 16u, udesc, SB_GPR); - for (uint32_t g = 0; g < GC; g++) { - for (int hh = 0; hh < 2; hh++) { - for (uint32_t i = 0; i < nq / 2u; i++) { uint32_t qi = (uint32_t)hh * (nq / 2u) + i; lds128_b(e, qq[qi], qa, g * HB + qi * 16u, SB_LD2); } - if (k->f32) { - for (int s4 = 0; s4 < 4; s4++) e_ffma_s(e, dot[g], qq[hh], s4, kx[hh], s4, dot[g]); /* dim hh*4+s4 */ - } else { - for (int s4 = 0; s4 < 4; s4++) { - int pi = hh * 4 + s4; /* bf16 pair: dims 2*pi (low half) and 2*pi+1 (high half) */ - imadi_s(e, lo, kx[hh], s4, 0x10000u, NOREG); /* low bf16 -> f32: bits << 16 */ - lop3andi_s(e, hi, kx[hh], s4, 0xffff0000u); /* high bf16 -> f32: keep the top half */ - e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2, lo, 0, dot[g]); - e_ffma_s(e, dot[g], qq[pi / 2], (pi % 2) * 2 + 1, hi, 0, dot[g]); - } - } - } - } - wide(e, ka, c1, 32u, ka); - imadi(e, d, c1, dims, d); - isetp_ge_u32(e, d, c64); - bra_back_if_not_p0(e, Lin); - loop_end(e); - for (uint32_t g = 0; g < GC; g++) e_fmul(e, s[g], dot[g], scale); - if (k->divergent) { - region_join(e); /* every lane back before the cross-lane reductions */ - } else { - imadi(e, nb, over, 0x80000000u, cninf); /* over ? +inf : -inf (bits) */ - for (uint32_t g = 0; g < GC; g++) { e_fsub(e, ns, zero, s[g]); e_fmax(e, ns, ns, nb); e_fsub(e, s[g], zero, ns); } - } - for (uint32_t g = 0; g < GC; g++) { - if (g == 0) sts32(e, sOff, s[0]); - else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, s[g]); } - } - sts32(e, oOff, koff); - - /* chunk max, per head */ - int t = V(e), mw = V(e), ra = V(e), rb = V(e), mc = V(e), Mn = V(e), diff = V(e), alpha[4], parg, p, sw, lc; - alpha[0] = V(e); parg = V(e); p = V(e); sw = V(e); lc = V(e); - for (uint32_t g = 1; g < GC; g++) alpha[g] = V(e); - static const uint32_t steps[5] = { 16, 8, 4, 2, 1 }; - for (uint32_t g = 0; g < GC; g++) { - shfl_down(e, t, s[g], steps[0]); e_fmax(e, mw, s[g], t); - for (int i = 1; i < 5; i++) { shfl_down(e, t, mw, steps[i]); e_fmax(e, mw, mw, t); } - if (g == 0) sts32(e, rOff, mw); - else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, mw); } - } - bar_sync(e); - for (uint32_t g = 0; g < GC; g++) { - const int pg = GC == 1 ? p : s[g]; /* GC > 1: p overwrites the score register of its head */ - if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); } - else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); } - e_fmax(e, mc, ra, rb); - if (HD == 128) { - if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); } - else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); } - e_fmax(e, mc, mc, rc_); e_fmax(e, mc, mc, rd_); - } - e_fmax(e, Mn, M[g], mc); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_NO_MAX) { - movf(e, alpha[g], 1.0f); - mufu(e, BW_IR_MUFU_EX2, pg, s[g]); - e_fmax(e, M[g], Mn, mc); - } else { - e_fsub(e, diff, M[g], Mn); - mufu(e, BW_IR_MUFU_EX2, alpha[g], diff); - e_fmax(e, M[g], Mn, mc); /* M = Mn */ - e_fsub(e, parg, s[g], Mn); - mufu(e, BW_IR_MUFU_EX2, pg, parg); - } - } - bar_sync(e); /* everyone has read the max partials before they are overwritten */ - for (uint32_t g = 0; g < GC; g++) { - const int pg = GC == 1 ? p : s[g]; - if (g == 0) sts32(e, sOff, pg); - else { imadi(e, tsh, c1, g * HB, sOff); sts32(e, tsh, pg); } - shfl_down(e, t, pg, steps[0]); e_fadd(e, sw, pg, t); - for (int i = 1; i < 5; i++) { shfl_down(e, t, sw, steps[i]); e_fadd(e, sw, sw, t); } - if (g == 0) sts32(e, rOff, sw); - else { imadi(e, tsh, c1, g * HB, rOff); sts32(e, tsh, sw); } - } - bar_sync(e); - for (uint32_t g = 0; g < GC; g++) { - if (g == 0) { lds32(e, ra, c768); lds32(e, rb, c896); } - else { imadi(e, tsh, c1, g * HB, c768); lds32(e, ra, tsh); imadi(e, tsh, c1, g * HB, c896); lds32(e, rb, tsh); } - e_fadd(e, lc, ra, rb); - if (HD == 128) { - if (g == 0) { lds32(e, rc_, c1024); lds32(e, rd_, c1152); } - else { imadi(e, tsh, c1, g * HB, c1024); lds32(e, rc_, tsh); imadi(e, tsh, c1, g * HB, c1152); lds32(e, rd_, tsh); } - e_fadd(e, lc, lc, rc_); e_fadd(e, lc, lc, rd_); - } - e_ffma(e, L[g], L[g], alpha[g], lc); - if (k->mutant != OMEGA_GPU_ATTN_MUTANT_NO_RESCALE) e_fmul(e, acc[g], acc[g], alpha[g]); - } - - /* phase B (batched, 2026-10-12): dimension tid over the chunk's tokens, AT_TOK tokens per pass. The - * token offsets of a pass come in two 128-bit shared loads (SB_LD2, one wait), then each V address is - * computed into one register pair while the earlier V loads are in flight (emit_fixed_in_batch: the - * read barrier orders the overwrite after the load has read it) and its load issued on SB_GPR or - * SB_LD3; the p values follow as two more shared loads on SB_LD2; one wait for all of it. A token past - * ctx inside a pass has p = 0 and the offset of a real token (phase A), so it adds exactly 0. - * GC > 1: one V load per token feeds every head's accumulator from that head's p slice (cut K). */ - enum { AT_TOK = 8 }; - int kk = V(e), tt = V(e), oa = V(e), pa = V(e), ko4[2], pv4[2], va = V64(e), v[AT_TOK]; - for (int i = 0; i < 2; i++) { ko4[i] = V128(e); pv4[i] = V128(e); } - for (int i = 0; i < AT_TOK; i++) v[i] = V(e); - movrz(e, kk); - loop_begin(e); - int LB = here(e); - iadd3(e, tt, base, kk); - isetp_ge_u32(e, tt, lim); - int bB = bra_fwd_if_p0(e); - imadi(e, oa, kk, 4, c512); - imadi(e, pa, kk, 4, c256); - for (int i = 0; i < 2; i++) lds128_b(e, ko4[i], oa, (uint32_t)i * 16u, SB_LD2); - for (int i = 0; i < AT_TOK; i++) { - if (i == 0) wide_s(e, va, ko4[0], 0, 1, vb); /* ordinary: waits for the offsets */ - else wide_s_b(e, va, ko4[i / 4], i % 4, 1, vb); - uint32_t sb = (i < AT_TOK / 2) ? SB_GPR : SB_LD3; - if (k->f32) ldg_b(e, v[i], va, udesc, sb); else ldg16_b(e, v[i], va, udesc, sb); - } - if (GC == 1) { - for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, (uint32_t)i * 16u, SB_LD2); - for (int i = 0; i < AT_TOK; i++) { - if (!k->f32) imadi(e, v[i], v[i], 0x10000u, NOREG); - e_ffma_s(e, acc[0], pv4[i / 4], i % 4, v[i], 0, acc[0]); - } - } else { - if (!k->f32) for (int i = 0; i < AT_TOK; i++) imadi(e, v[i], v[i], 0x10000u, NOREG); - for (uint32_t g = 0; g < GC; g++) { - for (int i = 0; i < 2; i++) lds128_b(e, pv4[i], pa, g * HB + (uint32_t)i * 16u, SB_LD2); - for (int i = 0; i < AT_TOK; i++) e_ffma_s(e, acc[g], pv4[i / 4], i % 4, v[i], 0, acc[g]); - } - } - imadi(e, kk, c1, AT_TOK, kk); - isetp_ge_u32(e, kk, c64); - bra_back_if_not_p0(e, LB); - loop_end(e); - patch_fwd(e, bB); - bar_sync(e); /* phase B reads of s/p and offsets finish before the next chunk writes them */ - iadd3(e, base, base, c64); - isetp_ge_u32(e, base, lim); - bra_back_if_not_p0(e, Lout); - loop_end(e); - - patch_fwd(e, bZ); - if (part && GC == 1) { - /* partial row (seq * nqh + out head) * S + split: acc[HD] unnormalised, then M and L at words HD and HD + 1 - * (every lane stores the same CTA-wide M and L). Everything is re-derived here from the CTA ids and the - * constant bank so no extra value lives across the chunk loop (the hd 128 kernel sits at the register budget). */ - int cy = V(e), sq = V(e), sp = V(e), hh = V(e), nq_ = V(e), t4 = V(e), prow = V(e), poff = V(e); - int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e); - s2r(e, cy, BW_SR_CTAID_Y); s2r(e, hh, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hh, hh, c1); - if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); } - imadr(e, prow, sq, nq_, hh); - imadi(e, prow, prow, S, sp); - imadi(e, t4, tid, 4, NOREG); - imadi(e, poff, prow, (HD + 2u) * 4u, t4); - wide(e, paddr, poff, 1, Cp); - stg(e, paddr, acc[0], udesc); - imadi(e, poff, prow, (HD + 2u) * 4u, NOREG); - wide(e, maddr, poff, 1, Cp); - wide(e, maddr, c64, 4, maddr); - stg(e, maddr, M[0], udesc); - wide(e, laddr, c1, 4, maddr); - stg(e, laddr, L[0], udesc); - } else if (part) { - /* GC heads: row (seq * nqh + h * GC + g) * S + split for head g (OUT_ROW: g ^ 1 on the output side) */ - int cy = V(e), sq = V(e), sp = V(e), h0 = V(e), hg = V(e), nq_ = V(e), t4 = V(e), prow = V(e), poff = V(e); - int paddr = V64(e), maddr = V64(e), laddr = V64(e), Cp = V64(e); - s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT); - imadi(e, h0, h0, GC, NOREG); - if (LS) { lop3andi(e, sp, cy, S - 1u); shri(e, sq, cy, LS); } else { movrz(e, sp); iadd3(e, sq, cy, zero); } - imadi(e, t4, tid, 4, NOREG); - for (uint32_t g = 0; g < GC; g++) { - imadi(e, hg, c1, g, h0); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1); - imadr(e, prow, sq, nq_, hg); - imadi(e, prow, prow, S, sp); - imadi(e, poff, prow, (HD + 2u) * 4u, t4); - wide(e, paddr, poff, 1, Cp); - stg(e, paddr, acc[g], udesc); - imadi(e, poff, prow, (HD + 2u) * 4u, NOREG); - wide(e, maddr, poff, 1, Cp); - wide(e, maddr, c64, 4, maddr); - stg(e, maddr, M[g], udesc); - wide(e, laddr, c1, 4, maddr); - stg(e, laddr, L[g], udesc); - } - } else if (GC == 1) { - int inv = V(e), o = V(e); - mufu(e, BW_IR_MUFU_RCP, inv, L[0]); - e_fmul(e, o, acc[0], inv); - stg(e, oaddr, o, udesc); - } else { - /* direct output, GC heads: row seq * nqh + h * GC + g (OUT_ROW: g ^ 1), re-derived from the CTA ids */ - int inv = V(e), o = V(e), cy = V(e), h0 = V(e), hg = V(e), nq_ = V(e), t4 = V(e), orow = V(e), ooff = V(e); - int oa64 = V64(e), Cp = V64(e); - s2r(e, cy, BW_SR_CTAID_Y); s2r(e, h0, BW_SR_CTAID_X); ldc32(e, nq_, ARG_NQH); ldc64(e, Cp, ARG_OUT); - imadi(e, h0, h0, GC, NOREG); - imadi(e, t4, tid, 4, NOREG); - for (uint32_t g = 0; g < GC; g++) { - imadi(e, hg, c1, g, h0); - if (k->mutant == OMEGA_GPU_ATTN_MUTANT_OUT_ROW) lop3xor(e, hg, hg, c1); - imadr(e, orow, cy, nq_, hg); - imadi(e, ooff, orow, HD * 4, t4); - wide(e, oa64, ooff, 1, Cp); - mufu(e, BW_IR_MUFU_RCP, inv, L[g]); - e_fmul(e, o, acc[g], inv); - stg(e, oa64, o, udesc); - } - } - tail(e); -} - -#define AT_GPR_BUDGET 96u /* cut K: the GQA-group hd 128 kernel carries four heads of running state (the matmul blocked kernels launch at 108) */ - -static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) { - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL; - omega_bw_ir_init(prog); - Em e; memset(&e, 0, sizeof e); e.p = prog; - e.rg_mutant = (k->divergent == 2) ? 1 : 0; - gen_attention(&e, k); - if (e.depth != 0) e.err = -1; - if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */ - int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL; - int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1; - int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1; -#ifdef OMEGA_ATTN_DEBUG - fprintf(stderr, "attn codegen f32=%d log2bs=%u log2gqa=%u mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n", - (int)k->f32, k->log2bs, k->log2gqa, k->mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage); -#endif - if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) { - size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; - memset(kernel, 0, sizeof *kernel); - kernel->code = omega_gpu_host_alloc(max_bytes); - size_t emitted = 0; - if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { - kernel->code_size = emitted; - kernel->insn_count = emitted / 16; - kernel->gpr_count = prog->regalloc.peak_gpr_usage; - kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; - sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); - rc = OMEGA_GPU_ATTN_OK; - } else { - omega_gpu_host_free(kernel->code); kernel->code = NULL; - } - } - if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else omega_gpu_host_free(prog); - return rc; -} - -/* --------------------------------------------------------- kernel cache */ - -/* One kernel per KSpec; the device copy is uploaded once and stays resident for - * the process (cut 4b). The IR program is kept for the host simulator. */ -static int g_mutant; -static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */ -static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */ -typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; OmegaGpuMem code; } Slot; -static OmegaGpuAttnSim g_sim; -static Slot g_cache[16]; /* split variants (cut F) multiply the shapes in flight */ -static int g_split = -1; /* test hook: forced log2split (0..OMEGA_GPU_ATTN_MAX_LOG2SPLIT), -1 = chosen per launch from the context */ -static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */ -static OmegaGpuMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */ -static bool g_hooked; -#define LOCK() omega_gpu_session_lock() -#define UNLOCK() omega_gpu_session_unlock() - -void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); } -static uint32_t g_sim_shared_bytes; /* shared bytes the launcher would declare for the kernel the simulator is running */ -uint32_t omega_gpu_attention_test_shared_bytes(void) { return g_sim_shared_bytes; } -void omega_gpu_attention_test_set_dedupe(bool on) { LOCK(); g_dedupe = on; UNLOCK(); } -void omega_gpu_attention_test_set_split(int log2split) { LOCK(); g_split = (log2split >= 0 && log2split <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT) ? log2split : -1; UNLOCK(); } - -/* ---- resident KV pool (see the header) ---- */ - -static int dev_open_locked(void); - -/* The kernel computes block_id * block_stride + slot * token_stride + head offset in 32 bits before - * widening onto the 64-bit layer base: one layer slice (both planes, every token and head of the - * block) past the block's start must stay inside 32 bits. */ -static bool resident_fits(const OmegaGpuKvLayout *ly, uint32_t block_id) { - return ly->block_stride_bytes <= 0xffffffffull && - (uint64_t)block_id * ly->block_stride_bytes + ly->layer_stride_bytes <= 0xffffffffull; -} -bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id) { - return layout && resident_fits(layout, block_id); -} - -int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) { - if (!cpu || bytes == 0) return OMEGA_GPU_ATTN_BAD_ARGS; - *cpu = NULL; - LOCK(); - if (g_resident.cpu) { omega_gpu_session_set_error("attention pool: already allocated"); UNLOCK(); return OMEGA_GPU_ATTN_BAD_ARGS; } - if (g_sim) { - g_resident.cpu = omega_gpu_host_calloc(1, bytes); - if (!g_resident.cpu) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } - g_resident.va = (uintptr_t)g_resident.cpu; g_resident.size = bytes; - } else { - int rc = dev_open_locked(); - if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; } - if (omega_gpu_session_alloc(bytes, &g_resident) != 0) { memset(&g_resident, 0, sizeof g_resident); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } - } - *cpu = g_resident.cpu; - UNLOCK(); - return OMEGA_GPU_ATTN_OK; -} - -void omega_gpu_attention_pool_free(void) { - LOCK(); - if (g_resident.cpu) { if (g_sim) omega_gpu_host_free(g_resident.cpu); else omega_gpu_session_free(&g_resident); } - memset(&g_resident, 0, sizeof g_resident); - UNLOCK(); -} - -static void cache_clear_locked(void) { - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used) { omega_gpu_host_free(g_cache[i].kernel.code); omega_gpu_host_free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } -} - -void omega_gpu_attention_cache_clear(void) { - LOCK(); - cache_clear_locked(); - UNLOCK(); -} - -/* Called by the session (lock held, device still open) right before it closes. */ -static void on_session_close(void) { - cache_clear_locked(); - memset(&g_resident, 0, sizeof g_resident); /* the session's memory goes with it; the caller's mapping is dead */ - omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool); - omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out); -} - -void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) { - LOCK(); - g_mutant = (int)m; - cache_clear_locked(); - UNLOCK(); -} - -/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when - * `upload` (the chip path; the simulator never needs one). */ -static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, bool upload, Slot **out, bool *hit) { - KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = hd, .split = split }; - Slot *s = NULL; - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used && g_cache[i].k.f32 == k.f32 && g_cache[i].k.log2bs == k.log2bs && g_cache[i].k.log2gqa == k.log2gqa && g_cache[i].k.mutant == k.mutant && g_cache[i].k.divergent == k.divergent && g_cache[i].k.hd == k.hd && g_cache[i].k.split == k.split) { /* field compare: memcmp would read struct padding */ - s = &g_cache[i]; *hit = true; break; - } - if (!s) { - OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL; - int rc = build_kernel(&k, &kern, &kp); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - size_t slot = 0; - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } - s = &g_cache[slot]; - if (s->used) { omega_gpu_host_free(s->kernel.code); omega_gpu_host_free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ - memset(s, 0, sizeof *s); - s->used = 1; s->k = k; s->kernel = kern; s->prog = kp; - *hit = false; - } - if (upload && !s->code.cpu) { - if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; - memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); - if (omega_gpu_session_sync_to_gpu(&s->code) != 0) { omega_gpu_session_free(&s->code); return OMEGA_GPU_ATTN_CHIP_FAIL; } - } - *out = s; - return OMEGA_GPU_ATTN_OK; -} - -int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, OmegaBlackwellKernel *kernel) { - if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS; - if (head_dim != 64u && head_dim != 128u) return OMEGA_GPU_ATTN_TOO_LARGE; - LOCK(); - KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = head_dim, .split = -1 }; - UNLOCK(); - return build_kernel(&k, kernel, NULL); -} - -int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) { - return omega_gpu_attention_codegen_hd(kv_f32, log2_block_size, log2_gqa, OMEGA_GPU_ATTN_HEAD_DIM, kernel); -} - -const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); } - -/* ------------------------------------------------------------ launcher */ - -#define AT_POISON 0xffbadbadu -#define AT_WAIT_MS 600000ull - -static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */ - -typedef OmegaGpuAttnLaunch Launch; - -/* Caller holds the lock. Chip path: open the shared device on first use. */ -static int dev_open_locked(void) { - if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } - return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL; -} - -/* Where a call stages the KV slice it is about to hand the kernel: straight into the - * device staging buffer on the chip path (one copy), a host buffer under the simulator. - * Caller holds the lock; the result is valid until the next staging call. */ -static void *stage_target(size_t bytes, void **host_tmp, int *fail_rc) { - *host_tmp = NULL; - *fail_rc = OMEGA_GPU_ATTN_CHIP_FAIL; - if (g_sim) { *host_tmp = omega_gpu_host_alloc(bytes ? bytes : 1); return *host_tmp; } - int r = omega_gpu_session_scratch(&g_pool, bytes); - if (r != 0) { if (r == OMEGA_GPU_SESSION_SCRATCH_RESERVED) *fail_rc = OMEGA_GPU_ATTN_TOO_LARGE; return NULL; } /* reserved bound exceeded: loud, no allocation */ - return g_pool.mem.cpu; -} - -/* One launch through the shared session (omega_gpu_session_launch: shader-cache - * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), - * then readback and the poison scan. L->pool may already be the pool staging buffer. */ -static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { - int sr = omega_gpu_session_scratch(&g_q, L->q_bytes); - if (!sr) sr = omega_gpu_session_scratch(&g_tab, L->tab_bytes); - if (!sr) sr = omega_gpu_session_scratch(&g_out, L->out_bytes); - if (!sr && !L->pool_va && L->pool != g_pool.mem.cpu) sr = omega_gpu_session_scratch(&g_pool, L->pool_bytes); - if (sr) return sr == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_ATTN_TOO_LARGE : OMEGA_GPU_ATTN_CHIP_FAIL; - memcpy(g_q.mem.cpu, L->q, L->q_bytes); - if (!L->pool_va && L->pool != g_pool.mem.cpu) memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes); - const uint64_t pool_va = L->pool_va ? L->pool_va : g_pool.mem.va; /* resident: the caller's KV, read in place */ - memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes); - size_t out_words = L->out_bytes / 4; - uint32_t *out_dev = (uint32_t *)g_out.mem.cpu; - for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON; - /* the KV this launch reads: the staged pool, or the resident pool the caller wrote in place */ - if (omega_gpu_session_sync_to_gpu(&g_q.mem) != 0 || omega_gpu_session_sync_to_gpu(&g_tab.mem) != 0 || - omega_gpu_session_sync_to_gpu(&g_out.mem) != 0 || omega_gpu_session_sync_to_gpu(L->pool_va ? &g_resident : &g_pool.mem) != 0) - return OMEGA_GPU_ATTN_CHIP_FAIL; - - uint32_t args[ARG_WORDS]; - args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32); - args[2] = (uint32_t)pool_va; args[3] = (uint32_t)(pool_va >> 32); - args[4] = (uint32_t)g_out.mem.va; args[5] = (uint32_t)(g_out.mem.va >> 32); - args[6] = (uint32_t)g_tab.mem.va; args[7] = (uint32_t)(g_tab.mem.va >> 32); - memcpy(&args[8], L->params, sizeof L->params); - OmegaGpuLaunch GL = { - .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = ks->k.hd, .threads_y = 1, .shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa), /* (3 GC + 1) arrays of hd words: 1024 B for hd 64, 2048 B for hd 128 gqa 1, 6656 B for hd 128 gqa 4 */ - .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words, - .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS, - }; - uint64_t elapsed = 0; uint32_t marker = 0; - if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; - if (omega_gpu_session_sync_to_cpu(&g_out.mem) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; - - memcpy(L->out, g_out.mem.cpu, L->out_bytes); - uint32_t unwritten = 0; - for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++; - if (info) { - info->chip_calls++; - info->elapsed_ns += elapsed; - info->completion_marker = marker; - info->unwritten_words += unwritten; - info->threads_per_cta = ks->k.hd; - info->ctas_last_launch = L->grid_x * L->grid_y; - } - return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; -} - -/* Caller holds the lock. Accounts the launch's q / table / output traffic (the KV - * staging bytes are accounted where the slices are copied). */ -static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { - if (info) { - info->q_bytes += L->q_bytes; info->tab_bytes += L->tab_bytes; info->out_bytes += L->out_bytes; - info->kv_source = L->pool_va ? OMEGA_GPU_ATTN_KV_RESIDENT : OMEGA_GPU_ATTN_KV_STAGED; - } - if (g_sim) { g_sim_shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa); return g_sim(ks->prog, L, info); } - return run_launch(ks, L, info); -} - -/* ---- opt-in serving reservation (see the header) ---- */ - -static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa); -static int log2_exact(uint32_t v, uint32_t *out); - -int omega_gpu_attention_reserve(uint32_t max_context, uint32_t max_seqs, uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t kv_block_size) { - uint32_t log2gqa, log2bs; - if (max_context == 0 || max_seqs == 0) { omega_gpu_session_set_error("attention reserve: zero bound"); return OMEGA_GPU_ATTN_BAD_ARGS; } - if (kv_block_size && log2_exact(kv_block_size, &log2bs) != 0) { omega_gpu_session_set_error("attention reserve: block size not a power of two"); return OMEGA_GPU_ATTN_BAD_ARGS; } - int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); - if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_session_set_error("attention reserve: bad head shape"); return rc; } - /* KV staging, worst case over the two paths, per sequence: contiguous f32 holds both planes for max_context tokens - * (2 * ctx * kvh * hd * 4); paged bf16 stages whole blocks of both planes (round_up(ctx, block) * kvh * hd * 4), which - * is the larger one when max_context is under half a block. */ - size_t per_seq = 2u * max_context * (size_t)num_kv_heads * head_dim * 4u; - if (kv_block_size) { - size_t paged = ((size_t)max_context + kv_block_size - 1) / kv_block_size * kv_block_size * num_kv_heads * head_dim * 4u; - if (paged > per_seq) per_seq = paged; - } - const size_t pool = per_seq * max_seqs; - /* q rows for every sequence, and the output buffer sized for the paged path's partials of one launch - * (cut J: up to 2^MAX_LOG2SPLIT partials of head_dim + 2 words per (sequence, head), at most - * MAX_CTAS / num_q_heads sequences per launch; the rows reserve usually asks for more). */ - const size_t q_bytes = (size_t)max_seqs * num_q_heads * head_dim * 4u; - size_t launch_seqs = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; - if (launch_seqs == 0) launch_seqs = 1; - if (launch_seqs > max_seqs) launch_seqs = max_seqs; - const size_t partials = launch_seqs * num_q_heads * ((size_t)1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT) * ((size_t)head_dim + 2u) * 4u; - const size_t qo = q_bytes > partials ? q_bytes : partials; - const size_t tab = ((size_t)max_seqs * max_context + max_seqs) * 4u; - LOCK(); - rc = OMEGA_GPU_ATTN_OK; - if (g_sim) rc = OMEGA_GPU_ATTN_OK; /* the simulator stages in host memory: nothing to reserve */ - else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL; - else if (omega_gpu_session_scratch_reserve(&g_pool, pool) || omega_gpu_session_scratch_reserve(&g_q, q_bytes) || - omega_gpu_session_scratch_reserve(&g_out, qo) || omega_gpu_session_scratch_reserve(&g_tab, tab < 8 ? 8 : tab)) { - /* roll back this API's own buffers: a failed reserve leaves nothing flagged (growth allowed as before) */ - omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q); - omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab); - rc = OMEGA_GPU_ATTN_CHIP_FAIL; - } - UNLOCK(); - return rc; -} - -int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim) { - if (max_rows == 0 || num_q_heads == 0 || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS || (head_dim != 64u && head_dim != 128u)) { - omega_gpu_session_set_error("attention reserve rows: bad bound"); - return OMEGA_GPU_ATTN_BAD_ARGS; - } - uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads; - if (per == 0) per = 1; - if (per > max_rows) per = max_rows; - const size_t qo = (size_t)per * num_q_heads * head_dim * 4u, tab = (size_t)per * 8u; - LOCK(); - int rc = OMEGA_GPU_ATTN_OK; - if (g_sim) rc = OMEGA_GPU_ATTN_OK; - else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL; - else if ((qo > g_q.cap && omega_gpu_session_scratch_reserve(&g_q, qo)) || - (qo > g_out.cap && omega_gpu_session_scratch_reserve(&g_out, qo)) || - (tab > g_tab.cap && omega_gpu_session_scratch_reserve(&g_tab, tab))) - rc = OMEGA_GPU_ATTN_CHIP_FAIL; /* growth failed; whatever grew stays reserved at its larger size */ - UNLOCK(); - return rc; -} -void omega_gpu_attention_unreserve(void) { - LOCK(); - omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q); - omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab); - UNLOCK(); -} - -/* ------------------------------------------------------- public entries */ - -static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) { - if (!info) return; - memset(info, 0, sizeof *info); - info->kernel_cache_hit = hit; - info->gpr_count = k->gpr_count; - info->insn_count = (uint32_t)k->insn_count; - omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; -} -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static int log2_exact(uint32_t v, uint32_t *out) { - if (v == 0 || (v & (v - 1))) return -1; - uint32_t l = 0; while ((1u << l) != v) l++; - *out = l; return 0; -} -/* log2(e) / sqrt(head_dim) with the square roots as literals (8 and 11.313708498984761 = sqrt(128), both exactly what sqrt() returns): - * the library must not need libm (omegatool links without -lm; a constant head_dim folded sqrt away, a runtime one does not). */ -static float score_scale(uint32_t hd) { return (float)(1.4426950408889634 / (hd == 128u ? 11.313708498984761 : 8.0)); } - -/* Common head-shape checks; returns log2 of the gqa ratio. */ -static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) { - if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS; - if ((head_dim != 64u && head_dim != 128u) || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE; - if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS; - return OMEGA_GPU_ATTN_OK; -} - -/* Common prologue of every chip entry (lock held on success): device, kernel, info. */ -static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, Slot **ks, OmegaGpuAttnInfo *info) { - LOCK(); - int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked(); - bool hit = false; - if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, hd, split, !g_sim, ks, &hit); - if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; } - info_begin(info, &(*ks)->kernel, hit); - return OMEGA_GPU_ATTN_OK; -} - -int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, - uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, - uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { - uint64_t t0 = now_ns(); - if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS; - uint32_t log2gqa; - int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE; - const uint32_t HD = head_dim; - size_t n_out = (size_t)num_q_heads * HD; - if (seq_len == 0) { memset(out, 0, n_out * 4); if (info) { memset(info, 0, sizeof *info); info->call_ns = now_ns() - t0; } return OMEGA_GPU_ATTN_OK; } - Slot *ks = NULL; - const uint32_t log2bs = 12; /* one block of 4096 slots */ - rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - size_t plane = (size_t)seq_len * num_kv_heads * HD * 4; - void *host_tmp = NULL; - int stage_rc; - uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc); - if (!pool) { UNLOCK(); return stage_rc; } - memcpy(pool, k_cache, plane); - memcpy(pool + plane, v_cache, plane); - if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += 2 * plane; info->kv_blocks_logical += 1; info->kv_blocks_unique += 1; } /* one contiguous pseudo-block */ - uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */ - Launch L = { - .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab, - .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = 1, - .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 } - }; - rc = launch(ks, &L, info); - omega_gpu_host_free(host_tmp); - UNLOCK(); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -/* Rows per launch of the rows path: the CTA bound, then (under a reservation) what the q buffer holds. Caller holds the lock. */ -static uint32_t rows_per_launch(uint32_t num_rows, uint32_t num_q_heads, size_t row_bytes) { - uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads; - if (per == 0) per = 1; - if (per > num_rows) per = num_rows; - if (!g_sim && g_q.reserved && g_q.cap >= row_bytes) { - size_t fit = g_q.cap / row_bytes; - if (fit < per) per = (uint32_t)fit; - } - return per; -} - -int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache, - uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads, - uint32_t num_kv_heads, uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { - uint64_t t0 = now_ns(); - if (!q || !k_cache || !v_cache || !out || num_rows == 0) return OMEGA_GPU_ATTN_BAD_ARGS; - uint32_t log2gqa; - int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - if ((uint64_t)base_len + num_rows > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE; - const uint32_t HD = head_dim, total = base_len + num_rows; - const size_t row = (size_t)num_q_heads * HD; - Slot *ks = NULL; - const uint32_t log2bs = 12; /* one block of 4096 slots, as the single-row call */ - rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - /* the whole context (every row's keys are a prefix of it) staged once */ - size_t plane = (size_t)total * num_kv_heads * HD * 4; - void *host_tmp = NULL; - int stage_rc; - uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc); - if (!pool) { UNLOCK(); return stage_rc; } - memcpy(pool, k_cache, plane); - memcpy(pool + plane, v_cache, plane); - if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += (uint64_t)num_rows * 2 * plane; info->kv_blocks_logical += num_rows; info->kv_blocks_unique += 1; } - const uint32_t per = rows_per_launch(num_rows, num_q_heads, row * 4); - /* table of one launch: per block ids (all 0: the one staged block), then per context lengths */ - uint32_t *tab = omega_gpu_host_calloc(2 * (size_t)per, sizeof *tab); - if (!tab) { omega_gpu_host_free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } - for (uint32_t r0 = 0; r0 < num_rows && rc == OMEGA_GPU_ATTN_OK; r0 += per) { - const uint32_t nr = num_rows - r0 < per ? num_rows - r0 : per; - for (uint32_t i = 0; i < nr; i++) { tab[i] = 0; tab[nr + i] = base_len + r0 + i + 1; } - Launch L = { - .q = q + (size_t)r0 * row, .q_bytes = (size_t)nr * row * 4, .pool = pool, .pool_bytes = 2 * plane, - .tab = tab, .tab_bytes = (size_t)2 * nr * 4, .out = out + (size_t)r0 * row, .out_bytes = (size_t)nr * row * 4, - .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = nr, - .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, nr * 4 } - }; - rc = launch(ks, &L, info); - } - omega_gpu_host_free(tab); - omega_gpu_host_free(host_tmp); - UNLOCK(); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -/* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries - * (already filtered of negatives), ctx[s] the context length. */ -/* cut F: a sequence's own split count from its context alone (the kernel computes the same): log2 of the largest - * power of two <= min(2^MAX_LOG2SPLIT, chunks), chunks = ceil(ctx / HD) (cut J: one whole chunk per split; cut F took two). */ -static uint32_t own_log2split(uint32_t ctx, uint32_t HD) { - uint32_t x = (ctx + HD - 1) / HD, l = 0; - while (l < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << l) <= x) l++; - return l; -} - -/* 2^x in float without the math library (the engine archive also links where there is none): round x to the - * nearest integer n, 2^f on f in [-0.5, 0.5] by the Cephes exp2f polynomial, scale by 2^n through the exponent - * bits. x <= -127 (so also -inf, an empty split) is 0. The combine only passes x <= 0. */ -static float host_exp2(float x) { - if (x <= -127.0f) return 0.0f; - if (x > 127.0f) x = 127.0f; - int n = (int)(x + (x < 0.0f ? -0.5f : 0.5f)); - const float f = x - (float)n; - float px = 1.535336188319500e-4f; - px = px * f + 1.339887440266574e-3f; - px = px * f + 9.618437357674640e-3f; - px = px * f + 5.550332471162809e-2f; - px = px * f + 2.402264791363012e-1f; - px = px * f + 6.931472028550421e-1f; - px = 1.0f + f * px; - if (n < -126) { px *= 0.5f; n = -126; } - union { uint32_t u; float f; } sc; - sc.u = (uint32_t)(n + 127) << 23; - return px * sc.f; -} - -/* cut F: fold the per-split partials of each (sequence, head) row into out. w_s = 2^(M_s - max M): the kernel's - * running max and sum live in the log2 domain (scale carries log2 e, MUFU.EX2). A row whose every split is empty - * (context 0) is 0. */ -static void combine_splits(const float *part, float *out, size_t rows, uint32_t S, uint32_t HD) { - const size_t pw = (size_t)HD + 2; - for (size_t r = 0; r < rows; r++) { - const float *p = part + r * S * pw; - float *o = out + r * HD; - float mx = -__builtin_inff(); - for (uint32_t s = 0; s < S; s++) if (p[s * pw + HD] > mx) mx = p[s * pw + HD]; - if (!(mx > -__builtin_inff())) { memset(o, 0, (size_t)HD * 4); continue; } - float w[1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT], lsum = 0.0f; - for (uint32_t s = 0; s < S; s++) { w[s] = host_exp2(p[s * pw + HD] - mx); lsum += w[s] * p[s * pw + HD + 1]; } - const float inv = 1.0f / lsum; - for (uint32_t d = 0; d < HD; d++) { - float a = 0.0f; - for (uint32_t s = 0; s < S; s++) a += w[s] * p[s * pw + d]; - o[d] = a * inv; - } - } -} - -static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, - const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx, - uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads, - uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { - uint64_t t0 = now_ns(); - uint32_t log2gqa, log2bs; - int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); - if (rc != OMEGA_GPU_ATTN_OK) return rc; - const uint32_t HD = head_dim; - if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS; - /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */ - if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 || - ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes || - ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes) - return OMEGA_GPU_ATTN_BAD_ARGS; - size_t row = (size_t)num_q_heads * HD; - /* effective context per sequence and block id range check */ - uint32_t *eff = omega_gpu_host_calloc(num_seqs ? num_seqs : 1, sizeof *eff); - if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL; - for (uint32_t s = 0; s < num_seqs; s++) { - uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size; - eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap); - for (uint32_t b = 0; b < n_blocks[s]; b++) { - uint64_t id = tables[s][b]; - if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; } - } - } - uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; - if (seqs_per_launch == 0) seqs_per_launch = 1; - /* cut F: split each (sequence, head) over 2^log2split CTAs along the context: at least one whole chunk per - * split, from the longest context in the call, within the split launch bound (the test hook forces it). */ - uint32_t log2split = 0; - if (g_split >= 0) log2split = (uint32_t)g_split; - else for (uint32_t s = 0; s < num_seqs; s++) { uint32_t l = own_log2split(eff[s], HD); if (l > log2split) log2split = l; } - while (log2split && ((uint64_t)num_q_heads * seqs_per_launch << log2split) > OMEGA_GPU_ATTN_SPLIT_MAX_CTAS) log2split--; - const uint32_t S = 1u << log2split; - float *part = omega_gpu_host_alloc((size_t)seqs_per_launch * num_q_heads * S * (HD + 2) * 4); /* the partials of one launch */ - if (!part) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_CHIP_FAIL; } - Slot *ks = NULL; - rc = begin(false, log2bs, log2gqa, HD, (int)log2split, &ks, info); - if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(eff); omega_gpu_host_free(part); return rc; } - uint32_t maxb = 1; - for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s]; - /* Resident pool (2026-10-12): the caller's pool IS omega's allocation. Read it in place when the - * layout fits the allocation and every referenced block passes the 32-bit fit rule; else stage. */ - bool resident = g_resident.cpu && (const void *)pool == g_resident.cpu && ly->pool_bytes <= g_resident.size; - for (uint32_t s = 0; resident && s < num_seqs; s++) { - uint32_t need = eff[s] ? (eff[s] + ly->block_size - 1) / ly->block_size : 0; - for (uint32_t b = 0; b < need; b++) if (!resident_fits(ly, tables[s][b])) { resident = false; break; } - } - /* Dedupe map: physical block id -> staged slot of the current launch (-1 = not staged yet), - * plus the list of ids touched by the launch (in slot order) so the reset is O(unique). */ - int32_t *slot_of = NULL; uint32_t *touched = NULL; - if (g_dedupe && !resident) { - size_t nb = ly->num_blocks ? ly->num_blocks : 1; - slot_of = omega_gpu_host_alloc(nb * sizeof *slot_of); - touched = omega_gpu_host_alloc(nb * sizeof *touched); - if (!slot_of || !touched) { omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } - memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */ - } - for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) { - uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch; - /* logical references: every sequence's blocks up to its (truncated) context */ - uint32_t total = 0; - for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; - uint32_t *tab = omega_gpu_host_calloc((size_t)ns * maxb + ns, sizeof *tab); - if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } - if (resident) { - /* the table carries the physical ids; the kernel's block stride is the pool's; the layer - * base is the chip address of this layer's slice of block 0 */ - for (uint32_t s = 0; s < ns; s++) { - uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; - for (uint32_t b = 0; b < need; b++) tab[(size_t)s * maxb + b] = tables[s0 + s][b]; - tab[(size_t)ns * maxb + s] = eff[s0 + s]; - } - if (info) { info->kv_blocks_logical += total; info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; } - Launch L = { - .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, - .pool = (const uint8_t *)pool + (size_t)layer_idx * ly->layer_stride_bytes, .pool_bytes = 0, - .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, - .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4, - .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S, - .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->block_stride_bytes, (uint32_t)ly->token_stride_bytes, - (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }, - .pool_va = g_resident.va + (uint64_t)layer_idx * ly->layer_stride_bytes, - }; - rc = launch(ks, &L, info); - if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); - omega_gpu_host_free(tab); - continue; - } - /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table - * position): a CoW prefix block shared by several branches gets one slot. Each - * sequence's compact table keeps its own block order and truncated context. */ - uint32_t g = 0; - for (uint32_t s = 0; s < ns; s++) { - uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; - for (uint32_t b = 0; b < need; b++) { - uint32_t id = tables[s0 + s][b]; - if (g_dedupe) { - if (slot_of[id] < 0) { slot_of[id] = (int32_t)g; touched[g] = id; g++; } - tab[(size_t)s * maxb + b] = (uint32_t)slot_of[id]; - } else { - tab[(size_t)s * maxb + b] = g++; /* legacy: one slot per reference */ - } - } - tab[(size_t)ns * maxb + s] = eff[s0 + s]; - } - uint64_t staged_bytes = (uint64_t)(g ? g : 1) * ly->layer_stride_bytes; - if (staged_bytes > 0xffffffffull) { omega_gpu_host_free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; } - void *host_tmp = NULL; - int stage_rc; - uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp, &stage_rc); - if (!staged) { omega_gpu_host_free(tab); rc = stage_rc; break; } - /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */ - if (g_dedupe) { - for (uint32_t u = 0; u < g; u++) { - const uint8_t *src = pool + (size_t)touched[u] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes; - memcpy(staged + (size_t)u * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes); - slot_of[touched[u]] = -1; /* reset for the next launch */ - } - } else { - uint32_t w = 0; - for (uint32_t s = 0; s < ns; s++) { - uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; - for (uint32_t b = 0; b < need; b++, w++) { - const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes; - memcpy(staged + (size_t)w * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes); - } - } - } - if (info) { - info->kv_blocks_logical += total; info->kv_blocks_unique += g; - info->kv_bytes_staged += (uint64_t)g * ly->layer_stride_bytes; - info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; - } - Launch L = { - .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes, - .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, - .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4, - .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S, - .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes, - (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 } - }; - rc = launch(ks, &L, info); - if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); - omega_gpu_host_free(host_tmp); omega_gpu_host_free(tab); - } - UNLOCK(); - omega_gpu_host_free(eff); omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(part); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, - const uint32_t *block_ids, uint32_t num_block_ids, - uint32_t context_len, uint32_t layer_idx, - uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, - float *out, OmegaGpuAttnInfo *info) { - if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS; - const uint32_t *tables[1] = { block_ids }; - uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len }; - return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info); -} - -int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, - const int32_t *block_tables, const int32_t *context_lens, - uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx, - uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, - float *out, OmegaGpuAttnInfo *info) { - if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS; - /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */ - uint32_t **tables = omega_gpu_host_calloc(num_seqs, sizeof *tables); - uint32_t *nb = omega_gpu_host_calloc(num_seqs, sizeof *nb), *cx = omega_gpu_host_calloc(num_seqs, sizeof *cx); - if (!tables || !nb || !cx) { omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - int rc = OMEGA_GPU_ATTN_OK; - for (uint32_t s = 0; s < num_seqs; s++) { - cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0; - tables[s] = omega_gpu_host_calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables); - if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } - for (uint32_t b = 0; b < max_blocks_per_seq; b++) { - int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b]; - if (v >= 0) tables[s][nb[s]++] = (uint32_t)v; - } - } - if (rc == OMEGA_GPU_ATTN_OK) - rc = paged_core(q, pool, layout, (const uint32_t *const *)tables, nb, cx, num_seqs, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info); - for (uint32_t s = 0; s < num_seqs; s++) omega_gpu_host_free(tables[s]); - omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); - return rc; -} - -static const char *const k_mutant_names[OMEGA_GPU_ATTN_MUTANT_COUNT] = { - "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE", "Q_ROW", "OUT_ROW" -}; -_Static_assert(sizeof k_mutant_names / sizeof k_mutant_names[0] == OMEGA_GPU_ATTN_MUTANT_COUNT, "mutant name table"); - -const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m) { - return (m >= 0 && m < OMEGA_GPU_ATTN_MUTANT_COUNT && k_mutant_names[m]) ? k_mutant_names[m] : "?"; -} - -const char *omega_gpu_attention_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_ATTN_OK: return "OK"; - case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN"; - default: return "UNKNOWN"; - } -} - -/* omega #308 R2 test hook: 0 production, 1 lane-dependent branch inside a reconvergence - * region, 2 the same with the BSYNC dropped (negative control). Clears the kernel cache. */ -void omega_gpu_attention_test_set_divergent(int mode) { - LOCK(); - g_divergent = (mode < 0 || mode > 2) ? 0 : mode; - cache_clear_locked(); - UNLOCK(); -} diff --git a/src/omega_gpu_attention_api.h b/src/omega_gpu_attention_api.h deleted file mode 100644 index 3610af047..000000000 --- a/src/omega_gpu_attention_api.h +++ /dev/null @@ -1,290 +0,0 @@ -#ifndef OMEGA_GPU_ATTENTION_API_H -#define OMEGA_GPU_ATTENTION_API_H -/* - * omega_gpu_attention_api: native (no CUDA) decode attention for the AIEN - * inference stack (FB-1 cut 5, 2026-10-04). - * - * Two kernel families, one query per (sequence, query head), generated by our - * own codegen (src/omega_blackwell_codegen.c IR) and launched through the same - * chip-proven sequence as cuts 1b and 4: every buffer GPU-uncached (nvos.h - * NVOS32_ATTR2_GPU_CACHEABLE: system memory cached by the GPU is not coherent - * with CPU mappings), shader caches invalidated before the launch (clcec0.h - * NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), first marker, - * L2_FLUSH_DIRTY, second marker (C3 tail), poison-filled output scanned for - * unwritten words after readback. - * - * The math follows aien-sovereign-core crates/aien-inference-abi/src/backend.rs - * (ReferenceCpuBackend / TensorBackend defaults), read 2026-10-04 at main 8b5caed: - * gqa_attention(out, q, k_cache, v_cache, seq_len, num_q_heads, num_kv_heads, head_dim) - * k_cache / v_cache are f32 [seq_len][num_kv_heads][head_dim]; query head h reads - * kv head h / (num_q_heads / num_kv_heads); score = (q . k) / sqrt(head_dim); - * softmax over all seq_len tokens (no mask: one query attends to the whole history); - * out[h] = sum_t softmax_t v_t. seq_len == 0 writes zeros. - * paged_attention(out, q, pool, block_ids, context_len, layer_idx, ...) - * the KV pool is bf16 in aien-kv-cache's canonical layout (KvLayout strides in - * bytes: block, layer, kv plane (0 = K, 1 = V), token, head); token t lives in - * block_ids[t / block_size] at slot t % block_size; tokens whose block index is - * past the end of block_ids are dropped; context_len == 0 or no blocks writes zeros. - * paged_attention_batch: per sequence s, context_lens[s] <= 0 means 0, the block - * table row is block_tables[s*max_blocks .. (s+1)*max_blocks] (empty if that row - * runs past the array), negative entries are removed (the rest close up). - * - * Chip math: scores in f32 (FFMA over the head), online softmax per chunk of - * head_dim tokens: running max (FMNMX), p = EX2((s - m) * log2 e) folded into the - * score scale, rescale factor alpha = EX2(m_old - m_new), f32 sums, final MUFU.RCP. - * bf16 K is read as 32-bit pairs (LDG.E) and widened by a 16-bit shift (bf16 is - * the top half of an f32); bf16 V by LDG.E.U16 and the same shift. f32 K/V are - * read directly. Tolerances are stated and justified in tests/gpu_attention_test.c. - * - * Launch envelope: at most OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads sequences per launch (investigation - * I42, same as cuts 1b and 4): grid = (num_q_heads, sequences per launch * context splits); the paged - * path adds up to 2^OMEGA_GPU_ATTN_MAX_LOG2SPLIT context splits per (sequence, head) within - * OMEGA_GPU_ATTN_SPLIT_MAX_CTAS (cut F, the rows path proved 1024 CTAs on the chip). - * Shared memory: the QMD declares 16 * head_dim bytes (clcec0qmd.h SHARED_MEMORY_SIZE_SHIFTED7, - * src/omega_blackwell_qmd.c word 36); the kernel uses exactly 4 arrays of head_dim words: - * 1024 bytes for head_dim 64 (TinyLlama, Llama-3.2-1B; the QMD default) and 2048 bytes for - * head_dim 128 (Qwen3-4B; GB10 parity PASS 126/0 at 7dd92dc, evidence/FB1-CUT5-HD128-7dd92dc). - * head_dim is a kernel parameter (64 or 128): threads per CTA = head_dim = chunk size, one warp - * partial per 32 threads in the softmax reductions. - * - * Staging: the host copies q, the referenced KV blocks' layer slice, the (compacted, - * renumbered) block tables and the context lengths into GPU-uncached staging buffers - * for each launch and copies the result back. The kernel itself walks the block - * table. Resident pool (2026-10-12): a paged call whose pool pointer is the allocation - * omega_gpu_attention_pool_alloc returned reads the KV in place instead (no staging; see - * that declaration for the one rule). Since the attention hardening cut - * (2026-10-04) a launch stages each physical block's layer slice once however many - * sequences of the batch reference it (shared CoW prefixes), and OmegaGpuAttnInfo - * reports the bytes staged against the per-sequence (naive) figure. - * - * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide - * session shared with the matmul and elementwise APIs (omega_gpu_session.h): one - * open per process instead of one per call (~40 ms), kernels resident after first - * use, staging buffers reused at their high-water mark (the KV slice is written - * straight into the device staging buffer). Calls serialise on one lock. - */ -#include -#include -#include -#include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */ -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_ATTN_OK = 0, - OMEGA_GPU_ATTN_BAD_ARGS = -1, /* NULL pointer, zero dimension, head mapping or block id out of range */ - OMEGA_GPU_ATTN_TOO_LARGE = -2, /* head_dim not in {64, 128}, num_q_heads > 64, context past the envelope */ - OMEGA_GPU_ATTN_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */ - OMEGA_GPU_ATTN_CHIP_FAIL = -4, /* device open, alloc, submit, marker or release failed */ - OMEGA_GPU_ATTN_UNWRITTEN = -5 /* output words still equal to their poison after the run */ -}; - -#define OMEGA_GPU_ATTN_HEAD_DIM 64u /* the original head_dim; threads per CTA = head_dim (one thread per dimension / per token of a chunk) */ -#define OMEGA_GPU_ATTN_HEAD_DIM_128 128u /* the second supported head_dim (Qwen3-4B) */ -#define OMEGA_GPU_ATTN_MAX_CTAS 64u -/* Cut F (2026-10-12): a paged call splits each (sequence, head) over up to 2^MAX_LOG2SPLIT CTAs along the context - * (whole chunks each, at least one chunk per split since cut J, 2026-10-12, which also raised the cap from 8 to 16: at - * 1268 tokens the busiest CTA went from three chunks to two; the launch takes the largest count in the batch) within - * SPLIT_MAX_CTAS CTAs per launch (the rows path proved 1024 on the chip); the CTAs write unnormalised partials - * (acc[head_dim], running max, running sum) that the host combines, also when the split is 1 (the gqa f32 and rows - * kernels keep the direct output and are byte for byte the ones before). Each sequence picks its own split count - * from its own context, so a result never depends on the other sequences in a launch. */ -#define OMEGA_GPU_ATTN_MAX_LOG2SPLIT 4u -#define OMEGA_GPU_ATTN_SPLIT_MAX_CTAS 1024u -#define OMEGA_GPU_ATTN_MAX_Q_HEADS 64u -#define OMEGA_GPU_ATTN_MAX_GQA_CTX 4096u /* contiguous path: one block of 2^12 slots */ - -/* Mirror of aien-kv-cache KvLayoutDesc (crates/aien-kv-cache/src/lib.rs, main 8b5caed), - * field for field, strides in bytes. */ -typedef struct { - uint64_t block_stride_bytes; - uint64_t layer_stride_bytes; - uint64_t kv_plane_stride_bytes; - uint64_t token_stride_bytes; - uint64_t head_stride_bytes; - uint64_t pool_bytes; - uint32_t num_blocks; - uint32_t num_layers; - uint32_t block_size; /* must be a power of two (the kernel shifts and masks) */ -} OmegaGpuKvLayout; - -typedef struct { - uint32_t chip_calls; /* launches made */ - uint64_t elapsed_ns; /* sum of submit-to-second-marker over the launches */ - uint64_t call_ns; /* wall time of the whole API call (staging, launches, copy-out) */ - uint32_t completion_marker; /* first marker word of the last launch */ - uint32_t unwritten_words; /* poison words left in the outputs (0 on OK) */ - uint32_t gpr_count, insn_count; - bool kernel_cache_hit; /* the kernel was already generated */ - uint32_t ctas_last_launch, threads_per_cta; - char target_chip[64]; - uint32_t sm_architecture; - /* Appended (attention hardening cut, 2026-10-04): transfer accounting for the call. - * Existing field order above is ABI; sovereign-core mirrors this struct field for field. */ - uint64_t kv_bytes_staged; /* KV layer-slice bytes actually copied into staging (sum over launches) */ - uint64_t kv_bytes_naive; /* what per-sequence staging would have copied (every sequence its own blocks) */ - uint32_t kv_blocks_logical; /* block references summed over sequences, truncated to each context */ - uint32_t kv_blocks_unique; /* distinct (physical block, layer) slices staged, summed over launches */ - uint64_t q_bytes, tab_bytes, out_bytes; /* q, block-table/context and result traffic (sum over launches) */ - uint32_t kv_source; /* OMEGA_GPU_ATTN_KV_STAGED (slices copied per call) or OMEGA_GPU_ATTN_KV_RESIDENT (read in place) */ -} OmegaGpuAttnInfo; -#define OMEGA_GPU_ATTN_KV_STAGED 0u -#define OMEGA_GPU_ATTN_KV_RESIDENT 1u - -/* Contiguous f32 KV (TensorBackend::gqa_attention). q and out: [num_q_heads][head_dim]. */ -int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, - uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, - uint32_t head_dim, float *out, OmegaGpuAttnInfo *info); - -/* Contiguous f32 KV, many query rows in one call (the prompt read, 2026-10-12). q and out are - * [num_rows][num_q_heads][head_dim]; k_cache and v_cache hold base_len + num_rows tokens as - * [token][num_kv_heads][head_dim]. Row i attends over the first base_len + i + 1 tokens (causal: - * its own token and everything before it). The KV is staged once per call; the rows go to the - * chip in launches of up to OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads rows (grid y = row, the - * same kernel as omega_gpu_gqa_attention_f32, so one row per launch is bit-identical to that - * call). Under a serving reservation the rows per launch are also bounded by the q buffer - * omega_gpu_attention_reserve_rows sized. base_len + num_rows <= OMEGA_GPU_ATTN_MAX_GQA_CTX. */ -#define OMEGA_GPU_ATTN_ROWS_MAX_CTAS 1024u -int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache, - uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads, - uint32_t num_kv_heads, uint32_t head_dim, float *out, - OmegaGpuAttnInfo *info); - -/* Paged bf16 KV (TensorBackend::paged_attention). pool points at the pool base. */ -int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, - const uint32_t *block_ids, uint32_t num_block_ids, - uint32_t context_len, uint32_t layer_idx, - uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, - float *out, OmegaGpuAttnInfo *info); - -/* Batched (TensorBackend::paged_attention_batch). block_tables: [num_seqs][max_blocks_per_seq] i32 - * (negative = none), context_lens: [num_seqs] i32. q and out: [num_seqs][num_q_heads][head_dim]. */ -int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, - const int32_t *block_tables, const int32_t *context_lens, - uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx, - uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, - float *out, OmegaGpuAttnInfo *info); - -/* Resident KV pool (2026-10-12). One GPU-uncached, host-visible allocation of `bytes` that the caller - * writes its paged bf16 KV into directly (sovereign-core's pool buffer). A paged call whose `pool` - * pointer is this allocation reads the KV in place: nothing is staged, the block table carries the - * physical block ids and the kernel's block stride is the layout's block stride. The kernel forms - * block_id * block_stride + the in-block offsets in 32 bits, so a call takes the resident path only - * when block_stride_bytes and, for every block it references, block_id * block_stride_bytes + - * layer_stride_bytes fit in 32 bits, and the layout's pool_bytes fit the allocation; otherwise that - * call stages exactly as before. OmegaGpuAttnInfo.kv_source says which path ran. One pool per - * process: a second alloc is refused (BAD_ARGS) until omega_gpu_attention_pool_free. The alloc opens - * the session (CHIP_FAIL carries the driver text in omega_gpu_attention_last_error()); under the host - * simulator it is plain host memory. The caller must not free the pool while a call is in flight. */ -int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu); -void omega_gpu_attention_pool_free(void); - -const char *omega_gpu_attention_rc_name(int rc); -void omega_gpu_attention_cache_clear(void); - -/* OPT-IN serving reservation (omega_gpu_reserve_serving in omega_gpu_serving.h calls this). Allocates the KV staging - * pool (2 planes f32, 8 KiB per token at 8 kv heads x 128), q, output and table buffers once for contexts up to - * max_context and up to max_seqs sequences per call. A later call that fits never allocates; one that does not - * returns OMEGA_GPU_ATTN_TOO_LARGE ("serving reservation exceeded" in omega_gpu_attention_last_error()) and asks the - * driver for nothing. Never called = behaviour unchanged. The f32 contiguous path still refuses contexts past - * OMEGA_GPU_ATTN_MAX_GQA_CTX on its own. kv_block_size (power of two, 0 = no paged use) sizes the pool for the paged bf16 - * path too: it stages whole blocks, so under half a block of context it needs more than the f32 formula. The pool is - * sized in BYTES for the larger of the two paths: the paged path therefore admits up to about 2 x max_context tokens - * (whole blocks of the same bytes); what it refuses is a call whose staging exceeds the reserved bytes. max_seqs is - * checked per launch chunk (the batched call splits sequences into chunks of 64 / num_q_heads), so a call with more - * sequences than max_seqs succeeds when every chunk fits. A paged or batched call refused on a LATER chunk has already - * written the outputs of the earlier chunks: treat TOO_LARGE as "output incomplete". If the reserve fails part way it - * rolls back: none of this API's buffers stays flagged. 0 on success, else an OMEGA_GPU_ATTN_* code. */ -int omega_gpu_attention_reserve(uint32_t max_context, uint32_t max_seqs, uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t kv_block_size); -/* Grows the reservation's q, output and table buffers (never shrinks them) so that - * omega_gpu_gqa_attention_rows_f32 can send min(max_rows, OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads) - * rows per launch. The KV staging pool is untouched: the rows of one call share one staged context, - * which omega_gpu_attention_reserve already sized for max_context tokens. Call it after - * omega_gpu_attention_reserve (omega_gpu_reserve_serving does, with its max_rows). Without it the - * rows path still works under a reservation, in launches of as many rows as the q buffer holds. */ -int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim); -void omega_gpu_attention_unreserve(void); - -/* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs - * (omega_gpu_session_last_error); an open failure carries the driver text. */ -const char *omega_gpu_attention_last_error(void); - -/* Test hooks. Mutants are deliberately wrong kernels the parity test must catch; - * never set in production. */ -typedef enum { - OMEGA_GPU_ATTN_MUTANT_NONE = 0, - OMEGA_GPU_ATTN_MUTANT_NO_MAX, /* softmax without the running-max subtraction (overflows for large scores) */ - OMEGA_GPU_ATTN_MUTANT_KV_HEAD, /* reads kv head (h / ratio) ^ 1 */ - OMEGA_GPU_ATTN_MUTANT_SLOT, /* K read from slot (t + 1) % block_size while V keeps slot t (K/V mismatch) */ - OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, /* the accumulator is not rescaled when the max moves between chunks */ - /* Head-wiring mutants (attention hardening cut, 2026-10-04). Both swap the rows of - * query heads h and h ^ 1, so they need num_q_heads even (>= 2); never run them on a - * one-head shape (row h ^ 1 of the last sequence would be past the buffer). */ - OMEGA_GPU_ATTN_MUTANT_Q_ROW, /* q loaded from query-head row h ^ 1 (kv head and output row stay h) */ - OMEGA_GPU_ATTN_MUTANT_OUT_ROW, /* the correct result for head h stored in flattened output row h ^ 1 */ - OMEGA_GPU_ATTN_MUTANT_COUNT /* one past the last mutant: every battery enumerates 1 .. COUNT-1 */ -} OmegaGpuAttnMutant; -void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m); - -/* TEST ONLY (omega #308 regression R2). 0 = production branch-free chunk loop; 1 = the - * lane-dependent j >= ctx branch restored inside a BSSY/BSYNC reconvergence region; - * 2 = that kernel with the BSYNC dropped (negative control: the host simulator must refuse - * it). Clears the kernel cache. */ -void omega_gpu_attention_test_set_divergent(int mode); -/* "none", "NO_MAX", ... ; "?" past COUNT. The table is checked against COUNT at compile time. */ -const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m); - -/* Generate a kernel without launching (host tests, nvdisasm listings). - * log2_block_size: shift for token -> block; log2_gqa: shift for query head -> kv head. */ -int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, - OmegaBlackwellKernel *kernel); - -/* The same with an explicit head_dim (64 or 128; anything else is TOO_LARGE). The 4-argument - * omega_gpu_attention_codegen above is head_dim 64 and emits the same bytes as before head_dim 128 existed. */ -int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, - OmegaBlackwellKernel *kernel); - -/* One launch as the launcher sees it (test hook below). Pointers are host buffers; - * params are the eight argument words after the four buffer addresses: - * max_blocks, scale bits, block stride, token stride, kv plane stride, head stride, - * num_q_heads, context-array byte offset. */ -typedef struct { - const void *q; size_t q_bytes; - const void *pool; size_t pool_bytes; - const void *tab; size_t tab_bytes; - void *out; size_t out_bytes; - uint32_t grid_x, grid_y; - uint32_t params[8]; - uint64_t pool_va; /* resident pool: chip address of the layer base (`pool` is its host mapping, pool_bytes 0); 0 = stage `pool` */ -} OmegaGpuAttnLaunch; - -/* Host simulator hook (tests): when set, every launch runs the allocated IR program - * through `sim` instead of the chip. Lets the whole battery run on the host first - * (review before chip time). The program is post register allocation. */ -struct BlackwellIRProgramTag; -typedef int (*OmegaGpuAttnSim)(const void *prog /* const BlackwellIRProgram * */, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info); -void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim); -/* The shared memory the launcher declares for the kernel the simulator is running (set before each simulated launch). */ -uint32_t omega_gpu_attention_test_shared_bytes(void); -/* Query heads one CTA serves (cut K): hd 128 groups min(2^log2_gqa, 4) heads of one kv head; hd 64 keeps one head per CTA. */ -uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa); - -/* Shared-prefix staging dedupe (attention hardening cut, 2026-10-04): within one launch - * every (physical block, layer) slice referenced by the batch is staged once, keyed by the - * physical block id, and every sequence's compact table points at that one staged slot. - * On by default. `false` selects the legacy per-sequence staging (every sequence copies - * its own blocks), kept as the reference fallback and as the negative control of the - * staging-byte tests. Test hook; never cleared in production. */ -void omega_gpu_attention_test_set_dedupe(bool on); -/* Test hook: force the context split (log2, 0 = one CTA per head) on every paged call; -1 = automatic. */ -void omega_gpu_attention_test_set_split(int log2split); - -/* The resident pool's per-block fit rule (see omega_gpu_attention_pool_alloc), exposed so the - * 4 GiB edge can be checked without allocating a 4 GiB pool. Test hook. */ -bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id); - -#ifdef __cplusplus -} -#endif -#endif /* OMEGA_GPU_ATTENTION_API_H */ diff --git a/src/omega_gpu_bf16_gemv_api.c b/src/omega_gpu_bf16_gemv_api.c deleted file mode 100644 index a0d6b3d5e..000000000 --- a/src/omega_gpu_bf16_gemv_api.c +++ /dev/null @@ -1,275 +0,0 @@ -/* omega_gpu_bf16_gemv_api.c: bf16 streaming GEMV (lm_head) on the shared session, OWN-30B 2026-10-13. - * See the header. Submission path and buffer policy are the FP8 API's: every buffer both sides touch is - * GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will not be coherent with direct CPU - * mappings"); one launch = omega_gpu_session_launch. */ -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_cmdlist.h" -#include - -#define CACHE_SLOTS 8 -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) -#define DEFAULT_CTAS 96u - -struct OmegaGpuBf16Tensor { - uint32_t n, k; - OmegaGpuMem w; -}; - -typedef struct { - bool valid, pinned; - OmegaBf16GemvSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - OmegaGpuScratch x_buf, y_buf; - uint32_t rows, warps, depth, ctas; /* overrides, 0 = automatic */ - int mutant; - bool hooked; - Slot cache[CACHE_SLOTS]; - unsigned next; -} g; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -const char *omega_gpu_bf16_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_bf16_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_BF16_OK: return "OK"; - case OMEGA_GPU_BF16_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_BF16_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_BF16_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_BF16_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_BF16_NAN_WEIGHT: return "NAN_WEIGHT"; - default: return "UNKNOWN"; - } -} - -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - if (!g.cache[i].valid) continue; - omega_gpu_session_free(&g.cache[i].code); - memset(&g.cache[i], 0, sizeof g.cache[i]); - } - g.next = 0; -} -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g.x_buf); - omega_gpu_session_scratch_free(&g.y_buf); -} -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -void omega_gpu_bf16_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_bf16_set_shape(uint32_t rows, uint32_t warps, uint32_t depth) { - omega_gpu_session_lock(); g.rows = rows; g.warps = warps; g.depth = depth; cache_clear_locked(); omega_gpu_session_unlock(); -} -void omega_gpu_bf16_set_cta_budget(uint32_t ctas) { omega_gpu_session_lock(); g.ctas = ctas; omega_gpu_session_unlock(); } -void omega_gpu_bf16_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } - -/* Declared registers: peak + 1 rounded up to 8; a CTA must fit the 65536-register file (chip-found rules, see - * omega_gpu_fp8_api.c and ~/handoffs/own30b-K-report.md). */ -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } /* peak + 2 rounded up to 8: the chip hung at peak + 1 (omega_blackwell_codegen.h) */ -static bool register_file_fits(uint32_t warps, uint32_t peak) { - uint32_t decl = gpr_declared(peak); - if ((uint64_t)32u * warps * decl <= 65536u) return true; - char e[160]; omega_gpu_fmt(e, sizeof e, "bf16 kernel: %u warps x %u declared registers exceed the 65536-register file", warps, decl); - omega_gpu_session_set_error(e); - return false; -} -int omega_gpu_bf16_kernel_fits(const OmegaBf16GemvSpec *spec, uint32_t *declared) { - uint32_t peak = 0; - if (!spec || omega_bf16_gemv_prog_stats(spec, NULL, &peak) != 0) { omega_gpu_session_set_error("bf16 codegen refused the shape"); return OMEGA_GPU_BF16_CODEGEN_FAIL; } - if (declared) *declared = gpr_declared(peak); - return register_file_fits(spec->warps, peak) ? OMEGA_GPU_BF16_OK : OMEGA_GPU_BF16_TOO_LARGE; -} - -/* Automatic shape. DEFAULTS_BEGIN: set from the chip sweep (evidence OWN30B-BF16-*); see the report. */ -void omega_gpu_bf16_shape_for(uint32_t k, uint32_t *rows, uint32_t *warps, uint32_t *depth, uint32_t *ctas) { - uint32_t ks = k / 256u, w = 16u, r = 1u, d = ks; - while (d > 16u || ks % d || r * d > 16u) d--; - if (k % (32u * w) || k > 512u * w) w = 32u; - if (rows) *rows = g.rows ? g.rows : r; - if (warps) *warps = g.warps ? g.warps : w; - if (depth) *depth = g.depth ? g.depth : d; - if (ctas) *ctas = g.ctas ? g.ctas : DEFAULT_CTAS; -} -static void spec_for(uint32_t k, OmegaBf16GemvSpec *spec, uint32_t *ctas) { - memset(spec, 0, sizeof *spec); - spec->k = k; - omega_gpu_bf16_shape_for(k, &spec->rows, &spec->warps, &spec->depth, ctas); - spec->mutant = g.mutant; -} - -static int kernel_for(const OmegaBf16GemvSpec *spec, Slot **out, bool *hit) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - Slot *s = &g.cache[i]; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_BF16_OK; } - } - Slot *s = NULL; - for (unsigned i = 0; i < CACHE_SLOTS && !s; i++) { - Slot *c = &g.cache[(g.next + i) % CACHE_SLOTS]; - if (!c->valid || !c->pinned) { s = c; g.next = (unsigned)((c - g.cache) + 1) % CACHE_SLOTS; } - } - if (!s) { omega_gpu_session_set_error("bf16 kernel cache: every slot holds a prepared kernel"); return OMEGA_GPU_BF16_TOO_LARGE; } - if (g_rec && s->valid) { omega_gpu_session_set_error("bf16 record: kernel cache miss would evict a resident kernel (warm up before recording)"); return OMEGA_GPU_BF16_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("bf16 codegen: host memory"); return OMEGA_GPU_BF16_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_bf16_gemv_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("bf16 codegen refused the shape"); return OMEGA_GPU_BF16_CODEGEN_FAIL; } - if (!register_file_fits(spec->warps, prog->regalloc.peak_gpr_usage)) { omega_gpu_host_free(prog); return OMEGA_GPU_BF16_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_BF16_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_BF16_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_BF16_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_BF16_OK; -} - -int omega_gpu_bf16_prepare(uint32_t k) { - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_BF16_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_BF16_CHIP_FAIL; - else { Slot *s = NULL; bool hit = false; rc = kernel_for(&spec, &s, &hit); if (rc == OMEGA_GPU_BF16_OK) s->pinned = true; } - omega_gpu_session_unlock(); - return rc; -} - -void omega_gpu_bf16_tensor_shape(const OmegaGpuBf16Tensor *t, uint32_t *n, uint32_t *k) { - if (n) *n = t ? t->n : 0; - if (k) *k = t ? t->k : 0; -} - -int omega_gpu_bf16_tensor_upload(uint32_t n, uint32_t k, const uint16_t *w, OmegaGpuBf16Tensor **out) { - if (out) *out = NULL; - if (!w || !out || n == 0 || k == 0 || k % 256u) return OMEGA_GPU_BF16_BAD_ARGS; - if (k > OMEGA_BF16_MAX_K) return OMEGA_GPU_BF16_TOO_LARGE; - const size_t count = (size_t)n * k; - for (size_t i = 0; i < count; i++) if ((w[i] & 0x7f80u) == 0x7f80u) { - char e[120]; omega_gpu_fmt(e, sizeof e, "bf16 upload: NaN or infinity at element %zu", i); - omega_gpu_session_set_error(e); - return OMEGA_GPU_BF16_NAN_WEIGHT; - } - OmegaGpuBf16Tensor *t = omega_gpu_host_calloc(1, sizeof *t); - if (!t) return OMEGA_GPU_BF16_BAD_ARGS; - t->n = n; t->k = k; - int rc = OMEGA_GPU_BF16_OK; - omega_gpu_session_lock(); - if (!dev_open_locked() || omega_gpu_session_alloc(count * 2u, &t->w) != 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_BF16_OK) { - memcpy(t->w.cpu, w, count * 2u); - if (omega_gpu_session_sync_to_gpu(&t->w) != 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; - } - if (rc != OMEGA_GPU_BF16_OK) { omega_gpu_bf16_tensor_free(t); return rc; } - *out = t; - return OMEGA_GPU_BF16_OK; -} - -void omega_gpu_bf16_tensor_free(OmegaGpuBf16Tensor *t) { - if (!t) return; - omega_gpu_session_lock(); - if (t->w.cpu) omega_gpu_session_free(&t->w); - omega_gpu_session_unlock(); - omega_gpu_host_free(t); -} - -/* rec non-NULL (record path, caller holds the session lock): x and y are the device buffers dev_x / dev_y, the launch is - * appended to rec instead of submitted, nothing is staged, poisoned or read back. */ -static int gemv_core(const OmegaGpuBf16Tensor *t, const float *x32, const uint16_t *x16, float *y, OmegaGpuBf16Info *info, - OmegaGpuCmdList *rec, uint64_t dev_x, uint64_t dev_y) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (rec && (!dev_x || !dev_y)) return OMEGA_GPU_BF16_BAD_ARGS; - if (!t || !t->w.cpu || (!rec && ((!x32 && !x16) || !y))) return OMEGA_GPU_BF16_BAD_ARGS; - const uint32_t n = t->n, k = t->k; - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - if (n % spec.rows) return OMEGA_GPU_BF16_CODEGEN_FAIL; - const uint32_t RG = n / spec.rows; - uint32_t grid_x = (RG + spec.warps - 1) / spec.warps; - if (grid_x > ctas) grid_x = ctas; - if (grid_x == 0) grid_x = 1; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - int rc = OMEGA_GPU_BF16_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_BF16_CHIP_FAIL; } - if (!rec) { - int src = omega_gpu_session_scratch(&g.x_buf, (size_t)k * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)n * 4u); - if (src != 0) { UNLOCK(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_BF16_TOO_LARGE : OMEGA_GPU_BF16_CHIP_FAIL; } - } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_BF16_OK) { UNLOCK(); return rc; } - - float *xd = g.x_buf.mem.cpu, *yd = g.y_buf.mem.cpu; - if (!rec) { - if (x32) memcpy(xd, x32, (size_t)k * 4u); - else for (uint32_t i = 0; i < k; i++) { uint32_t b = (uint32_t)x16[i] << 16; memcpy(&xd[i], &b, 4); } - for (size_t i = 0; i < n; i++) yd[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; - } - - uint32_t args[OMEGA_BF16_ARGS_WORDS]; - const uint64_t x_va = rec ? dev_x : g.x_buf.mem.va, y_va = rec ? dev_y : g.y_buf.mem.va; - args[0] = (uint32_t)t->w.va; args[1] = (uint32_t)(t->w.va >> 32); - args[2] = (uint32_t)x_va; args[3] = (uint32_t)(x_va >> 32); - args[4] = (uint32_t)y_va; args[5] = (uint32_t)(y_va >> 32); - args[6] = RG; args[7] = grid_x * spec.warps; - if (info) { - info->n = n; info->k = k; info->rows_per_warp = spec.rows; info->warps_per_cta = spec.warps; info->depth = spec.depth; - info->grid_x = grid_x; info->steps = omega_bf16_gemv_steps(&spec); - info->weight_bytes = (uint64_t)n * k * 2u; - info->kernel_cache_hit = hit; - (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; - } - if (rc == OMEGA_GPU_BF16_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), - .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = grid_x, .grid_y = 1, - .num_elements = n, - .args = args, .n_args = OMEGA_BF16_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = omega_bf16_gemv_shared_bytes(&spec), - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_BF16_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; - } - if (rc == OMEGA_GPU_BF16_OK && !rec && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_BF16_CHIP_FAIL; - if (rc == OMEGA_GPU_BF16_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < n; i++) if (yd[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("output poison survived"); rc = OMEGA_GPU_BF16_CHIP_FAIL; } - else memcpy(y, yd, (size_t)n * sizeof *y); - } - UNLOCK(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} -#undef UNLOCK - -int omega_gpu_bf16_gemv_f32(const OmegaGpuBf16Tensor *t, const float *x, float *y, OmegaGpuBf16Info *info) { return gemv_core(t, x, NULL, y, info, NULL, 0, 0); } -int omega_gpu_bf16_gemv_bf16(const OmegaGpuBf16Tensor *t, const uint16_t *x, float *y, OmegaGpuBf16Info *info) { return gemv_core(t, NULL, x, y, info, NULL, 0, 0); } - -/* Record path (OWN-30B W-L2a decode graph): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_bf16_gemv_record(OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint64_t x_va, uint64_t y_va) { - if (!cl) return OMEGA_GPU_BF16_BAD_ARGS; - return gemv_core(t, NULL, NULL, NULL, NULL, cl, x_va, y_va); -} diff --git a/src/omega_gpu_bf16_gemv_api.h b/src/omega_gpu_bf16_gemv_api.h deleted file mode 100644 index 5f0a94f3b..000000000 --- a/src/omega_gpu_bf16_gemv_api.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef OMEGA_GPU_BF16_GEMV_API_H -#define OMEGA_GPU_BF16_GEMV_API_H -/* - * omega_gpu_bf16_gemv_api: native (no CUDA) bf16 streaming GEMV for the OWN-30B lane: the lm_head - * (vocab 151936 x hidden 2048, bf16 weights, f32 logits). New file on the shared session; no existing API changes. - * - * ============ C signatures and semantics (for the Rust binding) ============ - * typedef struct OmegaGpuBf16Tensor OmegaGpuBf16Tensor; // opaque, device resident - * - * int omega_gpu_bf16_tensor_upload(uint32_t n, uint32_t k, const uint16_t *w_bf16, OmegaGpuBf16Tensor **out); - * w: n * k bf16 bit patterns, row-major [n][k] (n output rows, k input columns): the checkpoint's lm_head.weight - * as is, copied byte for byte. Requires n >= 1, k % 256 == 0, 256 <= k <= 16384. Refuses a NaN or infinite bf16 - * (exponent all ones) with OMEGA_GPU_BF16_NAN_WEIGHT (nothing uploaded). Opens the device on first use. Resident - * until omega_gpu_bf16_tensor_free. - * - * int omega_gpu_bf16_gemv_f32 (const OmegaGpuBf16Tensor *t, const float *x, float *y, OmegaGpuBf16Info *info); - * int omega_gpu_bf16_gemv_bf16(const OmegaGpuBf16Tensor *t, const uint16_t *x, float *y, OmegaGpuBf16Info *info); - * y[r] = sum_c W[r][c] * x[c], r < n, c < k, f32 accumulate (summation order: omega_blackwell_codegen_bf16.h; the - * result is deterministic and the test's host emulation reproduces it bit for bit). x: k values, y: n f32. One - * launch. info may be NULL. - * - * int omega_gpu_bf16_prepare(uint32_t k); build and pin the kernel for width k now (serving). - * void omega_gpu_bf16_tensor_free(OmegaGpuBf16Tensor *t); - * void omega_gpu_bf16_tensor_shape(const OmegaGpuBf16Tensor *t, uint32_t *n, uint32_t *k); - * const char *omega_gpu_bf16_rc_name(int rc); const char *omega_gpu_bf16_last_error(void); - * - * Return codes: 0 OK; negative OMEGA_GPU_BF16_* below. An uncertain completion latches the process (every later call - * of every API returns CHIP_FAIL), as the other APIs do. Every output word is poisoned before the launch and the - * call refuses a result that still holds poison. No host oracle runs inside the call. - */ -#include -#include -#include -#include "omega_blackwell_codegen_bf16.h" - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_BF16_OK = 0, - OMEGA_GPU_BF16_BAD_ARGS = -1, - OMEGA_GPU_BF16_TOO_LARGE = -2, - OMEGA_GPU_BF16_CODEGEN_FAIL = -3, - OMEGA_GPU_BF16_CHIP_FAIL = -4, - OMEGA_GPU_BF16_NAN_WEIGHT = -5 -}; - -typedef struct { - uint32_t n, k, rows_per_warp, warps_per_cta, depth, grid_x, steps; - uint64_t weight_bytes; /* bf16 bytes the launch reads (n * k * 2) */ - uint64_t elapsed_ns; /* chip submit-to-second-marker */ - uint64_t call_ns; /* whole API call */ - uint32_t completion_marker; - bool kernel_cache_hit; - char target_chip[64]; - uint32_t sm_architecture; -} OmegaGpuBf16Info; - -typedef struct OmegaGpuBf16Tensor OmegaGpuBf16Tensor; - -int omega_gpu_bf16_tensor_upload(uint32_t n, uint32_t k, const uint16_t *w_bf16, OmegaGpuBf16Tensor **out); -void omega_gpu_bf16_tensor_free(OmegaGpuBf16Tensor *t); -void omega_gpu_bf16_tensor_shape(const OmegaGpuBf16Tensor *t, uint32_t *n, uint32_t *k); -int omega_gpu_bf16_gemv_f32(const OmegaGpuBf16Tensor *t, const float *x, float *y, OmegaGpuBf16Info *info); -int omega_gpu_bf16_gemv_bf16(const OmegaGpuBf16Tensor *t, const uint16_t *x, float *y, OmegaGpuBf16Info *info); -/* Record path (OWN-30B W-L2a, decode graph; omega_gpu_cmdlist.h): the same launch as gemv_f32 appended to cl instead - * of submitted. x_va: k f32 on the device (plain, not prescaled); y_va: n f32 written when the list runs. The caller - * holds omega_gpu_session_lock(). Nothing staged, poisoned or read back. A kernel cache miss that would evict a resident - * kernel is refused (TOO_LARGE): warm the shape up with one non-record call (or omega_gpu_bf16_prepare) first. */ -struct OmegaGpuCmdList; -int omega_gpu_bf16_gemv_record(struct OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint64_t x_va, uint64_t y_va); -int omega_gpu_bf16_prepare(uint32_t k); -const char *omega_gpu_bf16_rc_name(int rc); -const char *omega_gpu_bf16_last_error(void); -void omega_gpu_bf16_cache_clear(void); - -/* Register-file check (chip-found rule: 32 * warps * declared registers <= 65536, declared = peak + 1 rounded up to 8). */ -int omega_gpu_bf16_kernel_fits(const OmegaBf16GemvSpec *spec, uint32_t *declared); -/* The shape the API picks for width k (rows, warps, depth, CTAs): for tests and the bandwidth table. */ -void omega_gpu_bf16_shape_for(uint32_t k, uint32_t *rows, uint32_t *warps, uint32_t *depth, uint32_t *ctas); - -/* ---- measurement knobs (tests; each clears the kernel cache; 0 restores the automatic choice) ---- */ -void omega_gpu_bf16_set_shape(uint32_t rows, uint32_t warps, uint32_t depth); -void omega_gpu_bf16_set_cta_budget(uint32_t ctas); -/* TEST ONLY: deliberately wrong kernels 1, 2, 3 (see the codegen header). Production never calls this. */ -void omega_gpu_bf16_test_set_mutant(int mutant); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_cmdlist.c b/src/omega_gpu_cmdlist.c deleted file mode 100644 index a403e250f..000000000 --- a/src/omega_gpu_cmdlist.c +++ /dev/null @@ -1,369 +0,0 @@ -/* - * omega_gpu_cmdlist.c: many launches in one submission (see the header). - * - * The per-launch words reuse the session's chip-proven pieces (omega_gpu_session.c, read 2026-10-13): SETUP_WORDS, - * INVALIDATE_SHADER_CACHES_ALL, the QMD0/QMD1 builders, the C3 tail (first marker with RELEASE_WFI, L2_FLUSH_DIRTY - * mem-op, second marker on the uncached page) and the poll loop. What is new: banks and QMDs live in per-launch slots - * written by the CPU, WAIT_FOR_IDLE sits between launches, and the PCAS launch method. - */ -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include - -#define PAGE 0x1000ull -#define RING_WORDS (0x10000u / 4u) /* the session ring: 64 KB */ -#define DEFAULT_TIMEOUT_MS 20000ull -#define MTHD_WAIT_FOR_IDLE 0x0110u /* clcec0.h NVCEC0_WAIT_FOR_IDLE */ -/* Completion markers live on the SESSION marker page (OmegaGpuSession.marker, allocated by the session with - * OMEGA_GPU_RIGHT_HOST_POLLED, GPU-uncached): the platform refuses poll_word on any buffer without that right - * (omega_gpu_platform_linux.c ref_poll_word, chip run cmdlist-r1 2026-10-13: "marker poll refused"), and the session - * exposes no polled allocation. The session uses bytes 0..0x1f of the page; this module uses 0x100..0x11f. */ -#define MARKER_OFF 0x100ull -#define MTHD_SEND_PCAS_A 0x02b4u /* clcec0.h NVCEC0_SEND_PCAS_A, QMD_ADDRESS_SHIFTED8 */ -#define MTHD_SEND_SIGNALING_PCAS2_B 0x02c0u /* clcec0.h, PCAS_ACTION 3:0 */ -#define PCAS_ACTION_INVALIDATE_COPY_SCHEDULE 3u - -static inline uint32_t bw_mthd(uint32_t subc, uint32_t mthd, uint32_t count) { - return (2u << 28) | (count << 16) | (subc << 13) | (mthd >> 2); -} -/* Same words as omega_gpu_session.c / omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - -struct OmegaGpuCmdList { - uint32_t cap, n; - OmegaGpuMem banks, qmds, sems, scratch; - OmegaGpuMem stamps; /* (cap + 1) x 16 B: compute-class REPORT_SEMAPHORE four-word reports {u64 payload, u64 timestamp} - (mesa clcec0.h 0x0158..0x0168, nvk_query.h), slot 0 = submit start, slot i + 1 = launch i done */ - uint32_t *words; /* host method stream */ - uint32_t words_cap; - OmegaGpuMem nop_code; /* EXIT kernel used to force the session latch after a timeout */ - uint32_t nop_gpr; - uint8_t *indep; /* per launch: 1 = shares no data with the launch before it (mark_independent): no barrier before it */ - int stamped; /* the last submit had opts.stamps (the accessor refuses stale stamps from an earlier submit) */ -}; - -static uint32_t g_latched; - -int omega_gpu_cmdlist_is_latched(void) { return __atomic_load_n(&g_latched, __ATOMIC_ACQUIRE) ? 1 : 0; } -uint32_t omega_gpu_cmdlist_count(const OmegaGpuCmdList *cl) { return cl ? cl->n : 0; } -void omega_gpu_cmdlist_reset(OmegaGpuCmdList *cl) { if (cl) cl->n = 0; } -int omega_gpu_cmdlist_mark_independent(OmegaGpuCmdList *cl) { - if (!cl || cl->n == 0) { omega_gpu_session_set_error("cmdlist mark_independent: no launch recorded"); return -1; } - cl->indep[cl->n - 1] = 1; - return 0; -} - -static int build_nop(OmegaGpuCmdList *cl) { - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return -1; - omega_bw_ir_init(prog); - BlackwellIRInsn ex; memset(&ex, 0, sizeof ex); - ex.op = BW_IR_EXIT; ex.dst_vreg = ex.src1_vreg = ex.src2_vreg = ex.src3_vreg = ex.ureg = -1; - ex.control = (5u << 9) | (7u << 14) | (7u << 17); - BlackwellIRInsn self = ex; self.op = BW_IR_BRA; self.control = 0x000fc000u; - int rc = (omega_bw_ir_append(prog, &ex) < 0 || omega_bw_ir_append(prog, &self) < 0 || omega_bw_regalloc_solve(prog) != 0) ? -1 : 0; - size_t need = rc == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (need == 0 || omega_gpu_session_alloc_code(need, &cl->nop_code) != 0) { omega_gpu_host_free(prog); return -1; } - OmegaBlackwellKernel k; - rc = omega_blackwell_kernel_encode_into(prog, cl->nop_code.cpu, need, &k); - omega_gpu_host_free(prog); - if (rc != 0 || omega_gpu_session_sync_to_gpu(&cl->nop_code) != 0) return -1; - cl->nop_gpr = omega_bw_gpr_declared(k.gpr_count); - if (cl->nop_gpr < 64u) cl->nop_gpr = 64u; - return 0; -} - -int omega_gpu_cmdlist_create(uint32_t cap, OmegaGpuCmdList **out) { - if (!out || cap == 0 || cap > OMEGA_GPU_CMDLIST_MAX_LAUNCHES) { omega_gpu_session_set_error("cmdlist create: arguments"); return -1; } - *out = NULL; - OmegaGpuCmdList *cl = omega_gpu_host_calloc(1, sizeof *cl); - if (!cl) return -1; - cl->cap = cap; - cl->words_cap = RING_WORDS; - cl->words = omega_gpu_host_alloc((size_t)cl->words_cap * 4u); - cl->indep = omega_gpu_host_calloc(cap, 1); - int rc = cl->words && cl->indep ? 0 : -1; - omega_gpu_session_lock(); - if (rc == 0 && !omega_gpu_session_open()) rc = -1; - if (rc == 0 && (omega_gpu_session_alloc((size_t)cap * OMEGA_GPU_CMDLIST_BANK_BYTES, &cl->banks) != 0 || - omega_gpu_session_alloc((size_t)cap * OMEGA_GPU_CMDLIST_QMD_BYTES, &cl->qmds) != 0 || - omega_gpu_session_alloc((size_t)cap * 16u, &cl->sems) != 0 || - omega_gpu_session_alloc((size_t)(cap + 1u) * 16u, &cl->stamps) != 0 || - omega_gpu_session_alloc(0x4000, &cl->scratch) != 0)) - rc = -1; - if (rc == 0 && build_nop(cl) != 0) { omega_gpu_session_set_error("cmdlist create: nop kernel"); rc = -1; } - if (rc == 0) { - memset(cl->scratch.cpu, 0, 0x4000); - if (omega_gpu_session_sync_to_gpu(&cl->scratch) != 0) rc = -1; - } - omega_gpu_session_unlock(); - if (rc != 0) { omega_gpu_cmdlist_free(cl); return -1; } - *out = cl; - return 0; -} - -void omega_gpu_cmdlist_free(OmegaGpuCmdList *cl) { - if (!cl) return; - omega_gpu_session_lock(); - OmegaGpuMem *m[] = { &cl->banks, &cl->qmds, &cl->sems, &cl->stamps, &cl->scratch, &cl->nop_code }; - for (unsigned i = 0; i < sizeof m / sizeof m[0]; i++) if (m[i]->cpu) omega_gpu_session_free(m[i]); - omega_gpu_session_unlock(); - omega_gpu_host_free(cl->words); - omega_gpu_host_free(cl->indep); - omega_gpu_host_free(cl); -} - -static uint32_t round8(uint32_t v) { return (v + 7u) / 8u * 8u; } - -int omega_gpu_cmdlist_add(OmegaGpuCmdList *cl, const OmegaGpuLaunch *L) { - if (!cl || !L || !L->args || L->n_args == 0 || L->n_args > OMEGA_GPU_SESSION_MAX_ARGS || L->threads_x == 0 || L->grid_x == 0 || L->grid_y == 0 || - L->code_va == 0) { omega_gpu_session_set_error("cmdlist add: arguments"); return -1; } - if (cl->n >= cl->cap) { omega_gpu_session_set_error("cmdlist add: list full"); return -1; } - const uint32_t i = cl->n; - const uint32_t ty = L->threads_y ? L->threads_y : 1; - const uint64_t bank_va = cl->banks.va + (uint64_t)i * OMEGA_GPU_CMDLIST_BANK_BYTES; - uint8_t *bank = (uint8_t *)cl->banks.cpu + (size_t)i * OMEGA_GPU_CMDLIST_BANK_BYTES; - uint32_t drv[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(drv, bank_va, L->threads_x, ty, L->grid_x, L->grid_y); - memcpy(bank, drv, sizeof drv); - memset(bank + sizeof drv, 0, 0x380 - sizeof drv); - memcpy(bank + 0x380, L->args, (size_t)L->n_args * 4u); - - const uint64_t q1_va = cl->qmds.va + (uint64_t)i * OMEGA_GPU_CMDLIST_QMD_BYTES, q0_va = q1_va + 0x200; - const uint64_t sem_va = cl->sems.va + (uint64_t)i * 16u; - uint32_t gpr = L->gpr_count > 64u ? round8(L->gpr_count) : 64u; - OmegaBlackwellQmdConfig cfg = { - .code_va = L->code_va, .cbank_va = bank_va, .scratch_va = cl->scratch.va, .sem_va = sem_va, - .qmd0_va = q0_va, .qmd1_va = q1_va, .num_elements = (uint32_t)L->num_elements, - .threads_per_block = L->threads_x, .grid_width = L->grid_x * L->grid_y, .threads_x = L->threads_x, .threads_y = ty, - .grid_x = L->grid_x, .grid_y = L->grid_y, .gpr_count = gpr, .shared_bytes = L->shared_bytes, - }; - uint32_t q1[OMEGA_BW_QMD_WORDS], q0[OMEGA_BW_QMD_WORDS]; - if (omega_blackwell_build_qmd1(q1, &cfg) != 0 || omega_blackwell_verify_qmd_invariants(q1) != 0) { omega_gpu_session_set_error("cmdlist add: qmd"); return -1; } - omega_blackwell_build_qmd0(q0, q0_va, q1_va); - uint8_t *qs = (uint8_t *)cl->qmds.cpu + (size_t)i * OMEGA_GPU_CMDLIST_QMD_BYTES; - memcpy(qs, q1, sizeof q1); - memcpy(qs + 0x200, q0, sizeof q0); - cl->indep[cl->n] = 0; - cl->n++; - return (int)i; -} - -#define WAIT_OK 0 -#define WAIT_TIMED_OUT 2 -#define WAIT_REFUSED 3 - -static inline void cpu_relax(void) { -#if defined(__aarch64__) - __asm__ volatile("yield" ::: "memory"); -#else - __asm__ volatile("" ::: "memory"); -#endif -} - -static int wait_word(const OmegaGpuPlatform *p, const OmegaGpuMem *marker, uint64_t off, uint32_t want, uint64_t timeout_ms, uint32_t spin_us) { - off += MARKER_OFF; - volatile uint32_t *m = (volatile uint32_t *)((uint8_t *)marker->cpu + off); - if (spin_us) { - const uint64_t end = p->time_now_ns(p->ctx) + (uint64_t)spin_us * 1000u; - do { if ((int32_t)(*m - want) >= 0) return WAIT_OK; cpu_relax(); } while (p->time_now_ns(p->ctx) < end); - } - uint64_t waited = 0; - for (;;) { - uint32_t seen = 0; - int rc = p->poll_word(p->ctx, marker->handle, off, want, 1, &seen); - if (rc == OMEGA_GPU_PLAT_OK) return WAIT_OK; - if (rc != OMEGA_GPU_POLL_TIMED_OUT) return WAIT_REFUSED; - if (++waited >= timeout_ms) return WAIT_TIMED_OUT; - } -} - -/* Uncertain completion: latch this module, then queue a 1 ms session launch behind the stuck list. If the channel is - * still busy it times out and the session latches the whole process (parks every buffer, refuses every API). */ -static void force_latch(OmegaGpuCmdList *cl, const char *why) { - __atomic_store_n(&g_latched, 1u, __ATOMIC_RELEASE); - uint32_t arg = 0; - OmegaGpuLaunch L = { .code_va = cl->nop_code.va, .gpr_count = cl->nop_gpr, .threads_x = 32, .threads_y = 1, .grid_x = 1, .grid_y = 1, - .num_elements = 1, .args = &arg, .n_args = 1, .timeout_ms = 1 }; - (void)omega_gpu_session_launch(&L, NULL, NULL); - omega_gpu_session_set_error(why); -} - -static size_t emit_tail(uint32_t *pb, size_t n, uint64_t marker_va) { - pb[n++] = bw_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)marker_va; pb[n++] = (uint32_t)(marker_va >> 32); - pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - pb[n++] = bw_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = bw_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)(marker_va + 0x10); pb[n++] = (uint32_t)((marker_va + 0x10) >> 32); - pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - return n; -} -#define TAIL_WORDS 17u - -/* Compute-class four-word report {u64 payload = slot, u64 GPU timestamp} to stamps slot `slot` (mesa clcec0.h: PAYLOAD_LOWER 0x0158, - * PAYLOAD_UPPER 0x015c, ADDRESS_LOWER 0x0160, ADDRESS_UPPER 0x0164, EXECUTE 0x0168 = OPERATION_RELEASE 0 | STRUCTURE_SIZE_FOUR_WORDS 0). - * Ordered after the preceding WAIT_FOR_IDLE, like nvk_query_pool.c timestamp queries. */ -#define MTHD_REPORT_SEMAPHORE_PAYLOAD_LOWER 0x0158u -#define STAMP_WORDS 6u -/* INVALIDATE_SHADER_CACHES (NVCEC0 0x021c) fields, clc6c0.h:222-236 (same layout on Blackwell): INSTRUCTION 0:0, FLUSH_DATA 2:2, DATA 4:4, CONSTANT 12:12 */ -#define INVALIDATE_DATA (1u << 4) -#define INVALIDATE_FLUSH_DATA (1u << 2) -static size_t emit_stamp(uint32_t *pb, size_t n, uint64_t stamps_va, uint32_t slot) { - const uint64_t va = stamps_va + (uint64_t)slot * 16u; - pb[n++] = bw_mthd(1, MTHD_REPORT_SEMAPHORE_PAYLOAD_LOWER, 5); - pb[n++] = slot; pb[n++] = 0; pb[n++] = (uint32_t)va; pb[n++] = (uint32_t)(va >> 32); pb[n++] = 0; - return n; -} - -static size_t emit_inline_qmd(uint32_t *pb, size_t n, uint64_t va, const uint32_t *words) { - pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((va >> 40) & 0x1ff); pb[n++] = (uint32_t)(va >> 8); - memcpy(&pb[n], words, 96 * 4); return n + 96; -} - -int omega_gpu_cmdlist_submit(OmegaGpuCmdList *cl, const OmegaGpuCmdListOpts *opts, OmegaGpuCmdListStats *st) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - if (opts) o = *opts; - if (st) { memset(st, 0, sizeof *st); st->first_missing = -1; } - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - if (!cl || cl->n == 0 || !p) { omega_gpu_session_set_error("cmdlist submit: empty list or no platform"); return -1; } - if (omega_gpu_cmdlist_is_latched() || omega_gpu_session_is_blocked()) { omega_gpu_session_set_error("cmdlist submit: latched"); return -1; } - OmegaGpuSession *s = omega_gpu_session_open(); - if (!s) return -1; - if (!s->marker.cpu || s->marker.size < MARKER_OFF + 0x20) { omega_gpu_session_set_error("cmdlist submit: session marker page"); return -1; } - const OmegaGpuMem *marker = &s->marker; - const uint64_t marker_va = marker->va + MARKER_OFF; - const uint64_t timeout = o.timeout_ms ? o.timeout_ms : DEFAULT_TIMEOUT_MS; - const uint32_t spin = o.spin_us ? o.spin_us : omega_gpu_session_spin_us(); - const uint64_t th0 = p->time_now_ns(p->ctx); - - /* semaphores INIT, markers 0, everything the CPU wrote made visible */ - uint32_t *sem = cl->sems.cpu; - for (uint32_t i = 0; i < cl->n; i++) sem[4 * i] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - volatile uint32_t *mk = (volatile uint32_t *)((uint8_t *)marker->cpu + MARKER_OFF); - mk[0] = 0; mk[4] = 0; - if (p->sync_cpu_to_gpu(p->ctx, cl->banks.handle, 0, (uint64_t)cl->n * OMEGA_GPU_CMDLIST_BANK_BYTES) != OMEGA_GPU_PLAT_OK || - p->sync_cpu_to_gpu(p->ctx, cl->qmds.handle, 0, (uint64_t)cl->n * OMEGA_GPU_CMDLIST_QMD_BYTES) != OMEGA_GPU_PLAT_OK || - p->sync_cpu_to_gpu(p->ctx, cl->sems.handle, 0, (uint64_t)cl->n * 16u) != OMEGA_GPU_PLAT_OK || - p->sync_cpu_to_gpu(p->ctx, marker->handle, MARKER_OFF, 0x20) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist submit: sync_cpu_to_gpu"); return -1; - } - - const uint32_t per_launch = (o.mode == OMEGA_GPU_CMDLIST_INLINE ? 4u + 2u * 99u : 8u) + (o.stamps ? STAMP_WORDS : 0u); - /* The platform may put its own words ahead of ours in the ring (the Linux reference: the omega #457 L2 invalidate - * after a host write to a GPU-cached buffer). Budget what it publishes, or a near-full submission is refused. */ - const uint32_t prefix = omega_gpu_session_submit_prefix_words(); - const uint32_t avail = cl->words_cap - 18u - TAIL_WORDS - 2u - STAMP_WORDS; - if (prefix > avail || avail - prefix < per_launch) { omega_gpu_session_set_error("cmdlist submit: the platform submit prefix leaves no room for a launch"); return -1; } - uint64_t *stamp_cpu = cl->stamps.cpu; - cl->stamped = o.stamps ? 1 : 0; - if (o.stamps) { - memset(stamp_cpu, 0xff, (size_t)(cl->n + 1u) * 16u); /* poisoned: a slot the chip never wrote reads all-ones */ - if (p->sync_cpu_to_gpu(p->ctx, cl->stamps.handle, 0, (uint64_t)(cl->n + 1u) * 16u) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist submit: sync stamps"); return -1; - } - } - const uint32_t room = (avail - prefix) / per_launch; - uint64_t elapsed = 0, host = p->time_now_ns(p->ctx) - th0; - uint32_t done = 0, submits = 0, words = 0; - while (done < cl->n) { - const uint64_t tb = p->time_now_ns(p->ctx); - uint32_t *pb = cl->words; - size_t n = 0; - memcpy(pb, SETUP_WORDS, sizeof SETUP_WORDS); n += 18; - const uint32_t end = (cl->n - done > room) ? done + room : cl->n; - for (uint32_t i = done; i < end; i++) { - if (o.skip_launch && i == (uint32_t)(o.skip_launch - 1)) continue; - /* the first launch of a submission always gets the full barrier (CPU-written QMDs, code and banks before it) */ - const int indep = i != done && cl->indep[i]; /* marked independent: no barrier, overlaps the launch before it */ - const OmegaGpuCmdListBarrier b = i == done ? OMEGA_GPU_CMDLIST_BARRIER_WFI : indep ? OMEGA_GPU_CMDLIST_BARRIER_NONE : o.barrier; - if (indep && o.stamps) n = emit_stamp(pb, n, cl->stamps.va, i); /* no WFI: slot i is the front-end time, launch i - 1 may still run */ - if (b != OMEGA_GPU_CMDLIST_BARRIER_NONE) { - if (b != OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA) { pb[n++] = bw_mthd(1, MTHD_WAIT_FOR_IDLE, 1); pb[n++] = 0; } - else { pb[n++] = bw_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = INVALIDATE_DATA | INVALIDATE_FLUSH_DATA; } /* implicit WFI (NVK) */ - if (o.stamps) n = emit_stamp(pb, n, cl->stamps.va, i); /* slot i: launch i - 1 done (slot `done`: submit start) */ - if (b == OMEGA_GPU_CMDLIST_BARRIER_WFI) { pb[n++] = bw_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; } - else if (b == OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA) { pb[n++] = bw_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = INVALIDATE_DATA; } - } - const uint64_t q1_va = cl->qmds.va + (uint64_t)i * OMEGA_GPU_CMDLIST_QMD_BYTES; - if (o.mode == OMEGA_GPU_CMDLIST_INLINE) { - const uint8_t *qs = (const uint8_t *)cl->qmds.cpu + (size_t)i * OMEGA_GPU_CMDLIST_QMD_BYTES; - uint32_t q1[OMEGA_BW_QMD_WORDS]; - memcpy(q1, qs, sizeof q1); - q1[10] = 0x00190000u; q1[12] = (uint32_t)((q1_va + 0x200) >> 8); /* the session pair: QMD1 decrements QMD0 */ - n = emit_inline_qmd(pb, n, q1_va + 0x200, (const uint32_t *)(qs + 0x200)); - n = emit_inline_qmd(pb, n, q1_va, q1); - } else { - /* standalone grid: no dependent QMD (NVK builds Blackwell QMDs without one, nak/qmd.rs Qmd5_0) */ - uint32_t *q1 = (uint32_t *)((uint8_t *)cl->qmds.cpu + (size_t)i * OMEGA_GPU_CMDLIST_QMD_BYTES); - q1[10] = 0; q1[12] = 0; - pb[n++] = bw_mthd(1, MTHD_SEND_PCAS_A, 1); pb[n++] = (uint32_t)(q1_va >> 8); - pb[n++] = bw_mthd(1, MTHD_SEND_SIGNALING_PCAS2_B, 1); pb[n++] = PCAS_ACTION_INVALIDATE_COPY_SCHEDULE; - } - } - if (o.stamps) { - pb[n++] = bw_mthd(1, MTHD_WAIT_FOR_IDLE, 1); pb[n++] = 0; - n = emit_stamp(pb, n, cl->stamps.va, end); /* slot end: the last launch done */ - } - n = emit_tail(pb, n, marker_va); - if (o.mode != OMEGA_GPU_CMDLIST_INLINE && - p->sync_cpu_to_gpu(p->ctx, cl->qmds.handle, 0, (uint64_t)cl->n * OMEGA_GPU_CMDLIST_QMD_BYTES) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist submit: sync qmd"); return -1; - } - mk[0] = 0; mk[4] = 0; - (void)p->sync_cpu_to_gpu(p->ctx, marker->handle, MARKER_OFF, 0x20); - const uint64_t t0 = p->time_now_ns(p->ctx); - host += t0 - tb; - if (p->queue_submit(p->ctx, s->queue, pb, (uint32_t)n) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist submit: queue_submit refused"); return -1; /* refused: nothing in flight */ - } - int w = wait_word(p, marker, 0, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, timeout, spin); - if (w == WAIT_OK) w = wait_word(p, marker, 0x10, OMEGA_BW_MARKER2_PAYLOAD, timeout, spin); - if (w != WAIT_OK) { force_latch(cl, w == WAIT_TIMED_OUT ? "cmdlist: marker wait timed out (latched)" : "cmdlist: marker poll refused (latched)"); return -1; } - (void)p->sync_gpu_to_cpu(p->ctx, marker->handle, MARKER_OFF, 0x20); - elapsed += p->time_now_ns(p->ctx) - t0; - (void)p->queue_retire(p->ctx, s->queue); - submits++; words += (uint32_t)n; done = end; - } - (void)p->sync_gpu_to_cpu(p->ctx, cl->sems.handle, 0, (uint64_t)cl->n * 16u); - if (o.stamps) (void)p->sync_gpu_to_cpu(p->ctx, cl->stamps.handle, 0, (uint64_t)(cl->n + 1u) * 16u); - uint32_t ok = 0; int32_t missing = -1; - for (uint32_t i = 0; i < cl->n; i++) { - if (sem[4 * i] == OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) ok++; - else if (missing < 0) missing = (int32_t)i; - } - if (st) { st->launches = cl->n; st->submits = submits; st->words = words; st->elapsed_ns = elapsed; st->host_ns = host; st->sems_done = ok; st->first_missing = missing; } - if (missing >= 0) { omega_gpu_session_set_error("cmdlist: a launch semaphore is not DONE (launch did not run)"); return -1; } - return 0; -} - -int omega_gpu_cmdlist_stamps(const OmegaGpuCmdList *cl, uint64_t *out, uint32_t cap) { - if (!cl || !out || !cl->stamps.cpu) { omega_gpu_session_set_error("cmdlist stamps: arguments"); return -1; } - if (!cl->stamped) { omega_gpu_session_set_error("cmdlist stamps: the last submit had stamps off"); return -1; } - const uint32_t want = cl->n + 1u; - if (cap < want) { omega_gpu_session_set_error("cmdlist stamps: out too small"); return -1; } - const uint64_t *s = cl->stamps.cpu; - for (uint32_t i = 0; i < want; i++) { - if (s[2 * i] != (uint64_t)i || s[2 * i + 1] == UINT64_MAX) { omega_gpu_session_set_error("cmdlist stamps: a slot was not written (stamps off, or the launch did not run)"); return -1; } - out[i] = s[2 * i + 1]; - } - return (int)want; -} - -const char *omega_gpu_cmdlist_barrier_name(OmegaGpuCmdListBarrier b) { - switch (b) { - case OMEGA_GPU_CMDLIST_BARRIER_WFI: return "wfi+inval_all"; - case OMEGA_GPU_CMDLIST_BARRIER_NONE: return "none"; - case OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY: return "wfi_only"; - case OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA: return "wfi+inval_data"; - case OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA: return "flush_data"; - } - return "?"; -} diff --git a/src/omega_gpu_cmdlist.h b/src/omega_gpu_cmdlist.h deleted file mode 100644 index aaebf037e..000000000 --- a/src/omega_gpu_cmdlist.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef OMEGA_GPU_CMDLIST_H -#define OMEGA_GPU_CMDLIST_H -/* - * omega_gpu_cmdlist: many kernel launches in ONE submission (OWN-30B W-L2, decode launch collapse, 2026-10-13). - * - * Why: omega_gpu_session_launch submits one kernel per GPFIFO entry and polls two markers before it returns, so a - * Qwen3-30B decode token (289 launches) pays the submit + completion round trip 289 times. A command list records N - * launches, then submits them as one method stream with one completion (the C3 tail: marker, L2_FLUSH_DIRTY, second - * marker on the uncached page) at the end. - * - * What each launch gets (all buffers from omega_gpu_session_alloc, GPU-uncached; nvos.h:1117 read 2026-10-13): - * - its own constant bank 0 (1 KB: the 224 driver words patched for this bank, arguments at 0x380), CPU-written; - * - its own QMD slot (the session's QMD1 words with this launch's bank and semaphore), CPU-written; - * (completion markers: the session marker page at 0x100, the one page the platform lets the host poll) - * - its own release semaphore word, set to INTERMEDIATE_INIT (5) by the CPU and released to DONE (6) by the QMD when - * the grid completes. submit() checks every word: a launch that never ran is caught by name (index). - * - * Ordering between launches (the race this module must not create): Mesa NVK, the working open driver for this class, - * serialises dependent dispatches with WAIT_FOR_IDLE (NVCEC0 0x0110) or INVALIDATE_SHADER_CACHES ("This is also - * implicitly a WFI", nvk_cmd_buffer.c:633); without one, consecutive grids of one channel may overlap. Every launch - * here is preceded by WAIT_FOR_IDLE and the session's INVALIDATE_SHADER_CACHES_ALL (instruction, data, constant). - * OMEGA_GPU_CMDLIST_BARRIER_NONE exists only as the negative control of the chip test. - * - * Launch methods (opts.mode): - * PCAS QMD in memory, SEND_PCAS_A (qmd >> 8) + SEND_SIGNALING_PCAS2_B INVALIDATE_COPY_SCHEDULE (clcec0.h 0x02b4 / - * 0x02c0; the NVK dispatch sequence, nvk_cmd_dispatch.c), no dependent QMD: 8 words per launch, a whole - * decode token fits one 64 KB ring. - * INLINE the session's own chip-proven words per launch (QMD0 null grid + QMD1 inline), bank from memory: ~200 words - * per launch, so the list is cut into several submissions, each waited before the next (the ring is copied to - * offset 0 on every submit). - * - * Threading: the caller holds omega_gpu_session_lock() around add / submit (one channel, as for every API). - * Uncertain completion: a marker timeout latches this module and then forces the session latch (a 1 ms session - * launch queued behind the stuck list times out and latches the process), so no API keeps launching on a channel - * that may still be busy. - */ -#include "omega_gpu_session.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_CMDLIST_MAX_LAUNCHES 2048u -#define OMEGA_GPU_CMDLIST_BANK_BYTES 0x400u -#define OMEGA_GPU_CMDLIST_QMD_BYTES 0x400u /* QMD1 at +0, QMD0 (INLINE mode) at +0x200 */ - -typedef enum { OMEGA_GPU_CMDLIST_PCAS = 0, OMEGA_GPU_CMDLIST_INLINE = 1 } OmegaGpuCmdListMode; -/* Barrier before every launch after the first of a submission (the first always gets the full WFI + invalidate ALL): - * WFI WAIT_FOR_IDLE + INVALIDATE_SHADER_CACHES ALL (instruction, data, constant). The default since cut 1b. - * NONE nothing (TEST ONLY: negative control; consecutive grids may overlap). - * WFI_ONLY WAIT_FOR_IDLE, no cache invalidate (W-L2c launch-cost study: isolates the drain from the invalidate). - * WFI_DATA WAIT_FOR_IDLE + INVALIDATE_SHADER_CACHES {data} (keeps the instruction and constant caches warm). - * FLUSH_DATA INVALIDATE_SHADER_CACHES {data, flush_data} alone, which NVK uses for a storage-write to storage-read - * dependency between dispatches ("This is also implicitly a WFI", nvk_cmd_buffer.c:633). */ -typedef enum { OMEGA_GPU_CMDLIST_BARRIER_WFI = 0, OMEGA_GPU_CMDLIST_BARRIER_NONE = 1 /* TEST ONLY: negative control */, - OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY = 2, OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA = 3, OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA = 4 } OmegaGpuCmdListBarrier; -const char *omega_gpu_cmdlist_barrier_name(OmegaGpuCmdListBarrier b); - -typedef struct { - OmegaGpuCmdListMode mode; - OmegaGpuCmdListBarrier barrier; - uint64_t timeout_ms; /* per submission; 0 = 20000 */ - uint32_t spin_us; /* marker spin window before the platform poll; 0 = the session's process-wide setting */ - int stamps; /* 1: a GPU timestamp report before the first launch and after every launch (after its WAIT_FOR_IDLE), read - back by omega_gpu_cmdlist_stamps. Costs 6 words + the report per launch. 0 = off. */ - int skip_launch; /* TEST ONLY: >= 1 drops launch (skip_launch - 1) from the method stream (its slot stays - recorded), so the per-launch semaphore check must fail. 0 = off. */ -} OmegaGpuCmdListOpts; - -typedef struct { - uint32_t launches; /* recorded launches submitted */ - uint32_t submits; /* GPFIFO entries (1 in PCAS mode below the ring size) */ - uint32_t words; /* method words over all submissions */ - uint64_t elapsed_ns; /* first submit to last second marker */ - uint64_t host_ns; /* building the method stream (CPU) */ - uint32_t sems_done; /* launch semaphores found DONE */ - int32_t first_missing; /* index of the first launch whose semaphore was not DONE, -1 if none */ -} OmegaGpuCmdListStats; - -typedef struct OmegaGpuCmdList OmegaGpuCmdList; - -/* Takes the session lock itself. Allocates the slots for up to cap launches. 0 ok, -1 (session error names it). */ -int omega_gpu_cmdlist_create(uint32_t cap, OmegaGpuCmdList **out); -void omega_gpu_cmdlist_free(OmegaGpuCmdList *cl); -/* Caller holds the lock. Empties the list (slots are rewritten by the next adds). */ -void omega_gpu_cmdlist_reset(OmegaGpuCmdList *cl); -uint32_t omega_gpu_cmdlist_count(const OmegaGpuCmdList *cl); -/* Caller holds the lock. Marks the most recently added launch as sharing NO data with the launch before it (neither reads - * what the other writes): submit emits no barrier before it, so the two grids may overlap on the chip (W-L2d: a weight - * prefetch beside the latency-bound attention). The launch after it gets the normal barrier, which waits for both. - * Ignored for the first launch of a submission. 0 ok, -1 (no launch recorded). */ -int omega_gpu_cmdlist_mark_independent(OmegaGpuCmdList *cl); -/* Caller holds the lock. Writes the launch's bank and QMD into the next slot. The launch's code must stay resident - * until submit returns. Returns the launch index, or -1 (full, bad arguments, QMD refused). L->timeout_ms and - * L->spin_us are ignored (the list has one completion). */ -int omega_gpu_cmdlist_add(OmegaGpuCmdList *cl, const OmegaGpuLaunch *L); -/* Caller holds the lock, device open, not latched. Submits every recorded launch in order, waits for the completion, - * checks every launch semaphore. 0 ok; -1 with the stage named (omega_gpu_session_last_error). */ -int omega_gpu_cmdlist_submit(OmegaGpuCmdList *cl, const OmegaGpuCmdListOpts *opts, OmegaGpuCmdListStats *st); -/* 1 once a timeout latched this module. */ -int omega_gpu_cmdlist_is_latched(void); - -/* After a submit with opts.stamps = 1: out[0] = GPU timestamp (ns, PTIMER) before launch 0, out[i + 1] = after launch i completed - * (taken after its WAIT_FOR_IDLE). Returns the count written (launches + 1) or -1 (stamps off, slot unwritten, cap too small). */ -int omega_gpu_cmdlist_stamps(const OmegaGpuCmdList *cl, uint64_t *out, uint32_t cap); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_code_alloc.h b/src/omega_gpu_code_alloc.h deleted file mode 100644 index 60be2332e..000000000 --- a/src/omega_gpu_code_alloc.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Size of a GPU code buffer. Header only: no device, no physics headers. - * - * The SM instruction cache prefetches past the last instruction of a kernel, so the code buffer must - * stay mapped for 2 KB after the code. Source (NVIDIA guidance as recorded by Mesa NVK, - * src/nouveau/vulkan/nvk_device.c, shader heap set-up): "the I-cache pre-fetches and NVIDIA has - * informed us overallocating shaders BOs by 2K is sufficient". A page-rounded buffer alone leaves - * whatever happens to be left in the last page (2560 B of code: 1536 B; 2688 B: 1408 B). - * - * omega#323 (2026-10-07): GB10 Xid 31, GPCCLIENT_GCC FAULT_PTE read on a page boundary while the - * head_dim 128 attention kernel (2688 B) ran; that this tail is the cause is INFERRED until the - * padded build turns the fault off on the chip. Every code upload sizes its buffer here so no site - * can drop the tail (tests/test_omega_gpu_code_alloc.c also scans src/ for page-rounded code sizes). - */ -#ifndef OMEGA_GPU_CODE_ALLOC_H -#define OMEGA_GPU_CODE_ALLOC_H - -#include -#include - -#define OMEGA_GPU_CODE_PREFETCH_TAIL 2048u -#define OMEGA_GPU_CODE_PAGE 0x1000u - -/* Bytes to allocate for code_size bytes of code: code + 2 KB, rounded up to a page, at least one page. - * 0 when the sum would overflow (callers refuse the upload). */ -static inline size_t omega_gpu_code_alloc_bytes(size_t code_size) { -#ifdef OMEGA_GPU_CODE_ALLOC_MUTANT_NO_TAIL - const size_t tail = 0; /* mutant: the page-rounded size every site used before omega#323 */ -#else - const size_t tail = OMEGA_GPU_CODE_PREFETCH_TAIL; -#endif - if (code_size > SIZE_MAX - tail - (OMEGA_GPU_CODE_PAGE - 1u)) return 0; - size_t b = (code_size + tail + (OMEGA_GPU_CODE_PAGE - 1u)) & ~(size_t)(OMEGA_GPU_CODE_PAGE - 1u); - return b < OMEGA_GPU_CODE_PAGE ? OMEGA_GPU_CODE_PAGE : b; -} - -#endif diff --git a/src/omega_gpu_decode_attn_api.c b/src/omega_gpu_decode_attn_api.c deleted file mode 100644 index e69f65ad1..000000000 --- a/src/omega_gpu_decode_attn_api.c +++ /dev/null @@ -1,279 +0,0 @@ -/* - * omega_gpu_decode_attn_api.c: resident KV cache, RoPE table and launch for the one-launch decode attention (the - * double-precision host reference lives in tests/gpu_decode_attn_test.c so the library links without libm). See - * attention (see the header). Session use mirrors omega_gpu_fp8_api.c: every buffer from omega_gpu_session_alloc - * (GPU-uncached, host-visible), sync_to_gpu after host writes, sync_to_cpu before host reads, one - * omega_gpu_session_launch per call. - */ -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_hostmath.h" -#include -#include "omega_gpu_cmdlist.h" - -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -struct OmegaGpuDecodeAttnCache { - uint32_t layers, max_pos, max_splits; - double theta; - uint64_t plane_bytes; /* one K or V plane of a layer: 4 * max_pos * 256 + slack */ - OmegaGpuMem kv[OMEGA_GPU_DATTN_MAX_LAYERS]; /* [K plane | V plane] per layer */ - OmegaGpuMem rope, norms, part, cnt, qkv, out; -}; - -typedef struct { - bool valid; - OmegaDecodeAttnSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - bool hooked; - Slot slot; - uint32_t depth, per_split; - int mutant; -} g; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -static void slot_clear_locked(void) { if (g.slot.valid) omega_gpu_session_free(&g.slot.code); memset(&g.slot, 0, sizeof g.slot); } -static void on_session_close(void) { memset(&g.slot, 0, sizeof g.slot); } -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } /* peak + 2 rounded up to 8: the chip hung at peak + 1 (omega_blackwell_codegen.h) */ - -void omega_gpu_decode_attn_set_depth(uint32_t depth) { omega_gpu_session_lock(); g.depth = depth; slot_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_decode_attn_set_per_split(uint32_t per_split) { omega_gpu_session_lock(); g.per_split = per_split; omega_gpu_session_unlock(); } -void omega_gpu_decode_attn_test_set_mutant(int mutant) { omega_gpu_session_lock(); g.mutant = mutant; slot_clear_locked(); omega_gpu_session_unlock(); } -const char *omega_gpu_decode_attn_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_decode_attn_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_DATTN_OK: return "OK"; - case OMEGA_GPU_DATTN_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_DATTN_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_DATTN_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_DATTN_CHIP_FAIL: return "CHIP_FAIL"; - default: return "?"; - } -} - -/* ---- host math ---- */ -uint16_t omega_dattn_bf16_rne(float f) { - uint32_t x; memcpy(&x, &f, 4); - uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); - return (uint16_t)(r >> 16); -} -float omega_dattn_bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -void omega_dattn_rope_row(uint32_t pos, double theta, float *row128) { - for (unsigned i = 0; i < 64; i++) { - double inv = omega_hostmath_pow(theta, -(double)(2 * i) / 128.0), ang = (double)pos * inv, s, c; - omega_hostmath_sincos(ang, &s, &c); - row128[i] = (float)c; row128[64 + i] = (float)s; - } -} -/* ---- cache ---- */ -int omega_gpu_decode_attn_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, OmegaGpuDecodeAttnCache **out) { - if (!out) return OMEGA_GPU_DATTN_BAD_ARGS; - *out = NULL; - if (layers == 0 || layers > OMEGA_GPU_DATTN_MAX_LAYERS || max_pos == 0 || max_pos > OMEGA_GPU_DATTN_MAX_POS || max_pos % OMEGA_DATTN_CHUNK || !(rope_theta > 0)) return OMEGA_GPU_DATTN_BAD_ARGS; - OmegaGpuDecodeAttnCache *c = omega_gpu_host_calloc(1, sizeof *c); - if (!c) return OMEGA_GPU_DATTN_CHIP_FAIL; - c->layers = layers; c->max_pos = max_pos; c->theta = rope_theta; - c->max_splits = max_pos / OMEGA_DATTN_CHUNK; - c->plane_bytes = (uint64_t)OMEGA_GPU_DATTN_KV_HEADS * max_pos * OMEGA_DATTN_ROW_BYTES + OMEGA_DATTN_PLANE_SLACK; - int rc = OMEGA_GPU_DATTN_OK; - omega_gpu_session_lock(); - if (!dev_open_locked()) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - for (uint32_t L = 0; L < layers && rc == OMEGA_GPU_DATTN_OK; L++) if (omega_gpu_session_alloc((size_t)(2 * c->plane_bytes), &c->kv[L]) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - if (rc == OMEGA_GPU_DATTN_OK && (omega_gpu_session_alloc((size_t)max_pos * OMEGA_DATTN_ROPE_ROW_BYTES, &c->rope) != 0 || - omega_gpu_session_alloc((size_t)layers * 2 * 128 * 4, &c->norms) != 0 || - omega_gpu_session_alloc((size_t)OMEGA_GPU_DATTN_KV_HEADS * c->max_splits * OMEGA_DATTN_PARTIAL_WORDS * 4, &c->part) != 0 || - omega_gpu_session_alloc(64, &c->cnt) != 0 || - omega_gpu_session_alloc((size_t)OMEGA_GPU_DATTN_QKV_WORDS * 4, &c->qkv) != 0 || - omega_gpu_session_alloc((size_t)OMEGA_GPU_DATTN_Q_HEADS * 128 * 4, &c->out) != 0)) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - if (rc == OMEGA_GPU_DATTN_OK) { - float *r = c->rope.cpu; - for (uint32_t p = 0; p < max_pos; p++) omega_dattn_rope_row(p, rope_theta, r + (size_t)p * 128); - memset(c->cnt.cpu, 0, 64); - memset(c->norms.cpu, 0, (size_t)layers * 2 * 128 * 4); - for (uint32_t L = 0; L < layers; L++) memset(c->kv[L].cpu, 0, (size_t)(2 * c->plane_bytes)); - if (omega_gpu_session_sync_to_gpu(&c->rope) != 0 || omega_gpu_session_sync_to_gpu(&c->cnt) != 0 || omega_gpu_session_sync_to_gpu(&c->norms) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - for (uint32_t L = 0; L < layers && rc == OMEGA_GPU_DATTN_OK; L++) if (omega_gpu_session_sync_to_gpu(&c->kv[L]) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - } - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_DATTN_OK) { omega_gpu_decode_attn_cache_free(c); return rc; } - *out = c; - return OMEGA_GPU_DATTN_OK; -} -void omega_gpu_decode_attn_cache_free(OmegaGpuDecodeAttnCache *c) { - if (!c) return; - omega_gpu_session_lock(); - for (uint32_t L = 0; L < c->layers; L++) if (c->kv[L].cpu) omega_gpu_session_free(&c->kv[L]); - OmegaGpuMem *ms[] = { &c->rope, &c->norms, &c->part, &c->cnt, &c->qkv, &c->out }; - for (unsigned i = 0; i < 6; i++) if (ms[i]->cpu) omega_gpu_session_free(ms[i]); - omega_gpu_session_unlock(); - omega_gpu_host_free(c); -} -int omega_gpu_decode_attn_set_norms(OmegaGpuDecodeAttnCache *c, uint32_t layer, const float *q_norm, const float *k_norm) { - if (!c || layer >= c->layers || !q_norm || !k_norm) return OMEGA_GPU_DATTN_BAD_ARGS; - omega_gpu_session_lock(); - float *n = (float *)c->norms.cpu + (size_t)layer * 256; - memcpy(n, q_norm, 512); memcpy(n + 128, k_norm, 512); - int rc = omega_gpu_session_sync_to_gpu(&c->norms) == 0 ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} -static uint16_t *row_ptr(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, int plane) { - return (uint16_t *)((uint8_t *)c->kv[layer].cpu + (plane ? c->plane_bytes : 0) + ((size_t)kv_head * c->max_pos + pos) * OMEGA_DATTN_ROW_BYTES); -} -int omega_gpu_decode_attn_cache_write(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, uint32_t count, const uint16_t *k, const uint16_t *v) { - if (!c || layer >= c->layers || kv_head >= 4 || pos >= c->max_pos || count == 0 || count > c->max_pos - pos || !k || !v) return OMEGA_GPU_DATTN_BAD_ARGS; - omega_gpu_session_lock(); - memcpy(row_ptr(c, layer, kv_head, pos, 0), k, (size_t)count * 256); memcpy(row_ptr(c, layer, kv_head, pos, 1), v, (size_t)count * 256); - int rc = omega_gpu_session_sync_to_gpu(&c->kv[layer]) == 0 ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} -int omega_gpu_decode_attn_cache_read(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, uint16_t *k, uint16_t *v) { - if (!c || layer >= c->layers || kv_head >= 4 || pos >= c->max_pos || !k || !v) return OMEGA_GPU_DATTN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_session_sync_to_cpu(&c->kv[layer]) == 0 ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; - if (rc == OMEGA_GPU_DATTN_OK) { memcpy(k, row_ptr(c, layer, kv_head, pos, 0), 256); memcpy(v, row_ptr(c, layer, kv_head, pos, 1), 256); } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- kernel ---- */ -static int kernel_for(const OmegaDecodeAttnSpec *spec, Slot **out, bool *hit) { - Slot *s = &g.slot; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_DATTN_OK; } - if (g_rec && s->valid) { omega_gpu_session_set_error("decode attn record: kernel cache miss would evict the resident kernel (warm up before recording)"); return OMEGA_GPU_DATTN_TOO_LARGE; } - slot_clear_locked(); - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("decode attn codegen: host memory"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_decode_attn_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("decode attn codegen refused the spec"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if ((uint64_t)OMEGA_DATTN_CHUNK * gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("decode attn: register file"); return OMEGA_GPU_DATTN_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_DATTN_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); omega_gpu_session_set_error("decode attn encode"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_DATTN_CHIP_FAIL; } - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_DATTN_OK; -} - -/* rec non-NULL (record path, caller holds the session lock): qkv / out are the device buffers dev_qkv / dev_out, the - * launch is appended to rec instead of submitted, nothing is staged, poisoned or read back. The split counters are not - * zeroed by the host here: the kernel's last CTA of each KV head resets its own (header); omega_gpu_decode_attn_counters - * checks them after the list ran. */ -static int dattn_core(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, float out_scale, - float *out, OmegaGpuDecodeAttnInfo *info, OmegaGpuCmdList *rec, uint64_t dev_qkv, uint64_t dev_out) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!c || layer >= c->layers || pos >= c->max_pos || (rec ? (!dev_qkv || !dev_out) : (!qkv || !out))) return OMEGA_GPU_DATTN_BAD_ARGS; - const uint32_t per = g.per_split ? g.per_split : OMEGA_GPU_DATTN_PER_SPLIT; - if (per % OMEGA_DATTN_CHUNK) return OMEGA_GPU_DATTN_BAD_ARGS; - const uint32_t splits = (pos + per) / per; /* ceil((pos + 1) / per) */ - if (splits > c->max_splits) return OMEGA_GPU_DATTN_TOO_LARGE; - OmegaDecodeAttnSpec spec; memset(&spec, 0, sizeof spec); - spec.depth = g.depth ? g.depth : OMEGA_GPU_DATTN_DEPTH; spec.mutant = g.mutant; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - int rc = OMEGA_GPU_DATTN_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_DATTN_OK) { UNLOCK(); return rc; } - float *od = c->out.cpu; - if (!rec) { - memcpy(c->qkv.cpu, qkv, (size_t)OMEGA_GPU_DATTN_QKV_WORDS * 4); - for (size_t i = 0; i < 32 * 128; i++) od[i] = POISON_F32; - memset(c->cnt.cpu, 0, 64); - if (omega_gpu_session_sync_to_gpu(&c->qkv) != 0 || omega_gpu_session_sync_to_gpu(&c->out) != 0 || omega_gpu_session_sync_to_gpu(&c->cnt) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - } - - uint32_t args[OMEGA_DATTN_ARGS_WORDS]; - const uint64_t kc = c->kv[layer].va, vc = kc + c->plane_bytes, nm = c->norms.va + (uint64_t)layer * 1024; - const uint64_t qkv_va = rec ? dev_qkv : c->qkv.va, out_va = rec ? dev_out : c->out.va; - float fe = eps, fo = out_scale, fq = (float)(0.08838834764831845 * 1.4426950408889634); /* log2(e) / sqrt(128) */ - uint32_t ue, uo, uq; memcpy(&ue, &fe, 4); memcpy(&uo, &fo, 4); memcpy(&uq, &fq, 4); -#define A64(i, v) do { args[i] = (uint32_t)(v); args[(i) + 1] = (uint32_t)((v) >> 32); } while (0) - A64(0, qkv_va); A64(2, kc); A64(4, vc); A64(6, c->rope.va); A64(8, nm); A64(10, nm + 512); A64(12, out_va); A64(14, c->part.va); A64(16, c->cnt.va); -#undef A64 - args[18] = pos; args[19] = per; args[20] = splits; args[21] = (uint32_t)(c->max_pos * OMEGA_DATTN_ROW_BYTES); args[22] = ue; args[23] = uo; args[24] = uq; - if (info) { - info->layer = layer; info->pos = pos; info->splits = splits; info->per_split = per; info->depth = spec.depth; - info->grid_x = splits; info->grid_y = OMEGA_GPU_DATTN_KV_HEADS; info->threads = OMEGA_DATTN_CHUNK; - info->kv_bytes = 2ull * OMEGA_GPU_DATTN_KV_HEADS * (pos + 1ull) * OMEGA_DATTN_ROW_BYTES; - info->kernel_cache_hit = hit; - } - if (rc == OMEGA_GPU_DATTN_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), - .threads_x = OMEGA_DATTN_CHUNK, .threads_y = 1, .grid_x = splits, .grid_y = OMEGA_GPU_DATTN_KV_HEADS, - .num_elements = (size_t)32 * 128, - .args = args, .n_args = OMEGA_DATTN_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_DATTN_SHARED_BYTES, - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_DATTN_OK && !rec && (omega_gpu_session_sync_to_cpu(&c->out) != 0 || omega_gpu_session_sync_to_cpu(&c->cnt) != 0)) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - if (rc == OMEGA_GPU_DATTN_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < 32 * 128; i++) if (od[i] == POISON_F32) unchanged++; - const uint32_t *cn = c->cnt.cpu; - if (unchanged) { omega_gpu_session_set_error("decode attn: output poison survived"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else if (cn[0] | cn[1] | cn[2] | cn[3]) { omega_gpu_session_set_error("decode attn: a split counter did not return to zero"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else memcpy(out, od, (size_t)32 * 128 * 4); - } - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -/* ---- read-only view for the prefill attention (omega_gpu_prefill_attn_api.c) ---- */ -int omega_gpu_decode_attn_cache_view(const OmegaGpuDecodeAttnCache *c, uint32_t layer, OmegaGpuDecodeAttnCacheView *v) { - if (!c || !v || layer >= c->layers) return OMEGA_GPU_DATTN_BAD_ARGS; - v->layers = c->layers; v->max_pos = c->max_pos; - v->k_va = c->kv[layer].va; v->v_va = c->kv[layer].va + c->plane_bytes; - v->rope_va = c->rope.va; - v->q_norm_va = c->norms.va + (uint64_t)layer * 1024u; v->k_norm_va = v->q_norm_va + 512u; - return OMEGA_GPU_DATTN_OK; -} - -int omega_gpu_decode_attn(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, float out_scale, float *out, OmegaGpuDecodeAttnInfo *info) { - return dattn_core(c, layer, pos, qkv, eps, out_scale, out, info, NULL, 0, 0); -} - -/* Record path (OWN-30B W-L2a decode graph): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_decode_attn_record(OmegaGpuCmdList *cl, OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, uint64_t qkv_va, - float eps, float out_scale, uint64_t out_va) { - if (!cl) return OMEGA_GPU_DATTN_BAD_ARGS; - return dattn_core(c, layer, pos, NULL, eps, out_scale, NULL, NULL, cl, qkv_va, out_va); -} - -/* After a list ran (caller holds the lock): the four split counters must be back at zero (a non-zero word means a CTA - * never arrived). OK or CHIP_FAIL. */ -int omega_gpu_decode_attn_counters_check(OmegaGpuDecodeAttnCache *c) { - if (!c || !c->cnt.cpu) return OMEGA_GPU_DATTN_BAD_ARGS; - if (omega_gpu_session_sync_to_cpu(&c->cnt) != 0) return OMEGA_GPU_DATTN_CHIP_FAIL; - const uint32_t *cn = c->cnt.cpu; - if (cn[0] | cn[1] | cn[2] | cn[3]) { omega_gpu_session_set_error("decode attn: a split counter did not return to zero"); return OMEGA_GPU_DATTN_CHIP_FAIL; } - return OMEGA_GPU_DATTN_OK; -} diff --git a/src/omega_gpu_decode_attn_api.h b/src/omega_gpu_decode_attn_api.h deleted file mode 100644 index 0d1658ada..000000000 --- a/src/omega_gpu_decode_attn_api.h +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef OMEGA_GPU_DECODE_ATTN_API_H -#define OMEGA_GPU_DECODE_ATTN_API_H -/* - * omega_gpu_decode_attn_api: one-launch decode attention for Qwen3-30B-A3B (OWN-30B cut 8, 2026-10-13). - * C signatures for the Rust side first; the kernel is described in omega_blackwell_codegen_attn.h. - * - * int omega_gpu_decode_attn_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, OmegaGpuDecodeAttnCache **out); - * GPU-resident bf16 KV cache for `layers` layers of 4 KV heads x `max_pos` positions x 128 (one allocation per - * layer, 2 * 4 * max_pos * 256 bytes + slack), the RoPE table (f32 cos/sin per position, built in double from - * rope_theta), the per-layer q_norm/k_norm weights, the cross-split partials and counters. Opens the session. - * void omega_gpu_decode_attn_cache_free(OmegaGpuDecodeAttnCache *c); - * int omega_gpu_decode_attn_set_norms(OmegaGpuDecodeAttnCache *c, uint32_t layer, const float *q_norm, const float *k_norm); - * 128 f32 each (the checkpoint's bf16 q_norm.weight / k_norm.weight widened by the caller). - * int omega_gpu_decode_attn(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, - * float out_scale, float *out, OmegaGpuDecodeAttnInfo *info); - * qkv: f32 [5120] as the fused q/k/v GEMV writes it (q 32 heads x 128, then k 4 x 128, then v 4 x 128), pos: the - * new token's position (< max_pos; the context is positions 0..pos, 0..pos-1 must already be in the cache for - * that layer). The kernel appends K/V at pos and writes out[32][128] * out_scale (2^64 makes it the x' row of - * the FP8 o_proj GEMV, omega_gpu_fp8_gemv_* with x_prescaled; 1.0 gives plain attention output). - * Returns OMEGA_GPU_DATTN_OK or a code below; the chip failure text is in omega_gpu_decode_attn_last_error(). - * Test helpers: cache_write moves `count` consecutive bf16 K and V rows (128 each) of a layer and KV head into the - * cache in one sync; cache_read returns one row of each. - * The double-precision oracle the tests compare against (omega_decode_attn_reference) is defined in the test. - * - * Launch shape: grid (splits, 4), 256 threads, splits = ceil((pos + 1) / per_split), per_split a multiple of 256 - * (default OMEGA_GPU_DATTN_PER_SPLIT; omega_gpu_decode_attn_set_per_split overrides). Every buffer is GPU-uncached - * host-visible session memory (nvos.h:1117 rule), launched through omega_gpu_session_launch like the FP8 GEMV. - * The counters must be zero before a launch; the last CTA of each KV head resets its counter, and the API verifies - * the four words are zero after each call (a non-zero word means a CTA never arrived: CHIP_FAIL). - */ -#include "omega_blackwell_codegen_attn.h" -#include -#include - -enum { - OMEGA_GPU_DATTN_OK = 0, - OMEGA_GPU_DATTN_BAD_ARGS = -1, - OMEGA_GPU_DATTN_TOO_LARGE = -2, - OMEGA_GPU_DATTN_CODEGEN_FAIL = -3, - OMEGA_GPU_DATTN_CHIP_FAIL = -4 -}; - -#define OMEGA_GPU_DATTN_KV_HEADS 4u -#define OMEGA_GPU_DATTN_Q_HEADS 32u -#define OMEGA_GPU_DATTN_QKV_WORDS (32u * 128u + 2u * 4u * 128u) -#define OMEGA_GPU_DATTN_PER_SPLIT 256u -#define OMEGA_GPU_DATTN_MAX_LAYERS 64u -#define OMEGA_GPU_DATTN_MAX_POS 65536u - -typedef struct OmegaGpuDecodeAttnCache OmegaGpuDecodeAttnCache; - -typedef struct { - uint32_t layer, pos, splits, per_split, depth; - uint32_t grid_x, grid_y, threads; - uint64_t kv_bytes; /* K + V bytes the launch streams: 2 * 4 * (pos + 1) * 256 */ - uint64_t elapsed_ns; /* marker-to-marker chip time */ - uint64_t call_ns; /* whole call */ - uint32_t completion_marker; - int kernel_cache_hit; -} OmegaGpuDecodeAttnInfo; - -int omega_gpu_decode_attn_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, OmegaGpuDecodeAttnCache **out); -void omega_gpu_decode_attn_cache_free(OmegaGpuDecodeAttnCache *c); -int omega_gpu_decode_attn_set_norms(OmegaGpuDecodeAttnCache *c, uint32_t layer, const float *q_norm, const float *k_norm); -int omega_gpu_decode_attn(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, - float out_scale, float *out, OmegaGpuDecodeAttnInfo *info); -/* Record path (OWN-30B W-L2a, decode graph; omega_gpu_cmdlist.h): the launch of omega_gpu_decode_attn appended to cl - * instead of submitted. qkv_va: f32 [5120] on the device (the fused q|k|v GEMV output); out_va: f32 [32 * 128] written - * * out_scale when the list runs (2^64 = the o_proj FP8 x' row). pos and the split count are fixed at record time. - * The caller holds omega_gpu_session_lock(). Nothing staged, poisoned or read back; the split counters rely on the - * kernel's own reset (checked after the list by omega_gpu_decode_attn_counters_check). A kernel cache miss that would - * evict the resident kernel is refused (warm up with one non-record call first). */ -struct OmegaGpuCmdList; -int omega_gpu_decode_attn_record(struct OmegaGpuCmdList *cl, OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos, uint64_t qkv_va, - float eps, float out_scale, uint64_t out_va); -/* Caller holds the lock, after the list ran: OK when the four split counters are zero, else CHIP_FAIL. */ -int omega_gpu_decode_attn_counters_check(OmegaGpuDecodeAttnCache *c); -int omega_gpu_decode_attn_cache_write(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, uint32_t count, - const uint16_t *k_bf16, const uint16_t *v_bf16); /* count rows from pos, one sync */ -int omega_gpu_decode_attn_cache_read(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, - uint16_t *k_bf16, uint16_t *v_bf16); -/* Read-only view of a layer of the cache for the prefill attention (omega_gpu_prefill_attn_api.h): device addresses only. */ -typedef struct { - uint32_t layers, max_pos; - uint64_t k_va, v_va; /* K and V plane bases of `layer` (row (kv_head, pos) at + (kv_head * max_pos + pos) * 256) */ - uint64_t rope_va; /* f32 [max_pos][cos 64 | sin 64] */ - uint64_t q_norm_va, k_norm_va; /* f32 [128] each for `layer` */ -} OmegaGpuDecodeAttnCacheView; -int omega_gpu_decode_attn_cache_view(const OmegaGpuDecodeAttnCache *c, uint32_t layer, OmegaGpuDecodeAttnCacheView *out); -const char *omega_gpu_decode_attn_last_error(void); -const char *omega_gpu_decode_attn_rc_name(int rc); - -/* ---- measurement knobs (tests; each clears the kernel cache) ---- */ -void omega_gpu_decode_attn_set_depth(uint32_t depth); /* 0 = default (OMEGA_GPU_DATTN_DEPTH) */ -void omega_gpu_decode_attn_set_per_split(uint32_t per_split); /* 0 = default; multiple of 256 */ -void omega_gpu_decode_attn_test_set_mutant(int mutant); /* TEST ONLY: OmegaDecodeAttnSpec.mutant */ -#define OMEGA_GPU_DATTN_DEPTH 4u - -/* ---- host side ---- */ -/* bf16 round-to-nearest-even of an f32, the rounding the kernel applies to the appended K/V */ -uint16_t omega_dattn_bf16_rne(float f); -float omega_dattn_bf16_f32(uint16_t b); -/* RoPE table row for `pos`: cos[64] then sin[64], f32 from double, inv_freq[i] = theta^(-2i/128) */ -void omega_dattn_rope_row(uint32_t pos, double theta, float *row128); -/* The double-precision reference of the whole layer step (omega_decode_attn_reference) lives in - * tests/gpu_decode_attn_test.c: it needs libm and the library links without it. */ - -#endif diff --git a/src/omega_gpu_decode_graph.c b/src/omega_gpu_decode_graph.c deleted file mode 100644 index 5a07c7bb6..000000000 --- a/src/omega_gpu_decode_graph.c +++ /dev/null @@ -1,412 +0,0 @@ -/* - * omega_gpu_decode_graph.c: one decode token as one command list (see the header). Records the four decode APIs' - * *_record launches and the omega_blackwell_codegen_dec glue kernels into an omega_gpu_cmdlist. Buffers: - * omega_gpu_session_alloc only (GPU-uncached, nvos.h:1117); the host touches x (before), token and logits (after). - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include -#include - -#define TIMEOUT_MS 20000ull -#define SCALE_2P64 18446744073709551616.0f -#define NEG_PAD (-1e30f) -#define TOKEN_POISON 0xffffffffu - -/* glue kernels */ -enum { K_NORM, K_ADD, K_CN, K_SW, K_AM0, K_AM1, K_SW_M1, K_CN_M2, K_COUNT }; - -typedef struct { OmegaGpuMem code; uint32_t gpr; } Kern; - -/* the one buffer: byte offsets, every region 256-byte aligned (RES/SWIGLU load 16-byte vectors) */ -typedef struct { - size_t x, xq, qkv, attn, o, gu, act, dn, hidden, logits, am_v, am_i, token, norms, fnorm, tabs, pf_x, pf_y, bytes; -} Layout; - -struct OmegaGpuDecodeGraph { - OmegaGpuDecodeGraphConfig cfg; - uint32_t am_ctas; /* stage-1 ARGMAX CTAs = ceil(vocab / 2048) */ - Layout lo; - OmegaGpuMem buf; - Kern k[K_COUNT]; - OmegaGpuCmdList *cl; - struct { const OmegaGpuFp8Tensor *qkv, *o, *gu, *dn; int set; } layer[OMEGA_GPU_DGRAPH_MAX_LAYERS]; - int final_set; - /* token state */ - int in_token, failed; - int xq_layer; /* layer whose input-norm x' sits in xq, -1 none */ - int hidden_ready; - uint64_t t_begin; - OmegaGpuDecodeGraphStats acc; - int flush_each, mutant; - /* timeline (set_stamps): one kind per recorded launch and the GPU timestamps around every launch of the last token */ - int stamps; - uint32_t n_kind, tagged_in_list, n_stamp; - uint8_t kind[OMEGA_GPU_CMDLIST_MAX_LAUNCHES]; - uint64_t stamp[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; -}; - -static size_t al(size_t v) { return (v + 255u) & ~(size_t)255u; } -static uint64_t va_of(const OmegaGpuDecodeGraph *g, size_t off) { return g->buf.va + off; } -static void *cpu_of(const OmegaGpuDecodeGraph *g, size_t off) { return (uint8_t *)g->buf.cpu + off; } -static void put64(uint32_t *a, unsigned off, uint64_t v) { a[(off - 0x380) / 4] = (uint32_t)v; a[(off - 0x380) / 4 + 1] = (uint32_t)(v >> 32); } -static void putf(uint32_t *a, unsigned off, float f) { memcpy(&a[(off - 0x380) / 4], &f, 4); } -static int fail(OmegaGpuDecodeGraph *g, const char *what, int rc) { - if (g) g->failed = 1; - if (what) omega_gpu_session_set_error(what); - return rc; -} - -/* lock held */ -static int kern_build(Kern *k, OmegaDecKind kind, uint32_t mode, int mutant) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = kind; s.mode = mode; s.mutant = mutant; - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return OMEGA_GPU_DGRAPH_CODEGEN_FAIL; - int rc = OMEGA_GPU_DGRAPH_OK; - size_t need = 0; - if (omega_blackwell_codegen_dec_prog(&s, prog) != 0 || (need = omega_bw_program_code_bytes(prog)) == 0) rc = OMEGA_GPU_DGRAPH_CODEGEN_FAIL; - else if (omega_gpu_session_alloc_code(need, &k->code) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - else { - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(prog, k->code.cpu, need, &kk) != 0 || kk.code_size != need) rc = OMEGA_GPU_DGRAPH_CODEGEN_FAIL; - else if (omega_gpu_session_sync_to_gpu(&k->code) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - else { k->gpr = omega_bw_gpr_declared(kk.gpr_count); if (k->gpr < 64u) k->gpr = 64u; } /* as tests/gpu_cmdlist_test.c (chip PASS) */ - if (rc != OMEGA_GPU_DGRAPH_OK) { omega_gpu_session_free(&k->code); memset(k, 0, sizeof *k); } - } - omega_gpu_host_free(prog); - return rc; -} - -void omega_gpu_decode_graph_free(OmegaGpuDecodeGraph *g) { - if (!g) return; - if (g->cl) omega_gpu_cmdlist_free(g->cl); - omega_gpu_session_lock(); - for (unsigned i = 0; i < K_COUNT; i++) if (g->k[i].code.cpu) omega_gpu_session_free(&g->k[i].code); - if (g->buf.cpu) omega_gpu_session_free(&g->buf); - omega_gpu_session_unlock(); - omega_gpu_host_free(g); -} - -int omega_gpu_decode_graph_create(const OmegaGpuDecodeGraphConfig *cfg, OmegaGpuDecodeGraph **out) { - if (out) *out = NULL; - if (!cfg || !out || cfg->layers == 0 || cfg->layers > OMEGA_GPU_DGRAPH_MAX_LAYERS || !cfg->router || !cfg->attn || !cfg->lm_head || - cfg->vocab == 0 || cfg->vocab > OMEGA_DEC_ARGMAX_SPAN * OMEGA_DEC_ARGMAX_SPAN) return OMEGA_GPU_DGRAPH_BAD_ARGS; - uint32_t n = 0, k = 0; - omega_gpu_bf16_tensor_shape(cfg->lm_head, &n, &k); - if (n != cfg->vocab || k != OMEGA_GPU_DGRAPH_HIDDEN) return OMEGA_GPU_DGRAPH_BAD_ARGS; - OmegaGpuDecodeGraph *g = omega_gpu_host_calloc(1, sizeof *g); - if (!g) return OMEGA_GPU_DGRAPH_BAD_ARGS; - g->cfg = *cfg; - g->am_ctas = (cfg->vocab + OMEGA_DEC_ARGMAX_SPAN - 1) / OMEGA_DEC_ARGMAX_SPAN; - g->xq_layer = -1; - const size_t H = OMEGA_GPU_DGRAPH_HIDDEN, TK = OMEGA_GPU_DGRAPH_TOPK, I = OMEGA_GPU_DGRAPH_INTER; - Layout *L = &g->lo; size_t o = 0; -#define REG(f, bytes) do { L->f = o; o = al(o + (bytes)); } while (0) - REG(x, H * 4); REG(xq, H * 4); REG(qkv, OMEGA_GPU_DGRAPH_QKV * 4); REG(attn, OMEGA_GPU_DGRAPH_ATTN * 4); REG(o, H * 4); - REG(gu, TK * 2 * I * 4); REG(act, TK * I * 4); REG(dn, TK * H * 4); REG(hidden, H * 4); - REG(logits, (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN * 4); REG(am_v, OMEGA_DEC_ARGMAX_SPAN * 4); REG(am_i, OMEGA_DEC_ARGMAX_SPAN * 4); - REG(token, 16); REG(norms, (size_t)cfg->layers * H * 4); REG(fnorm, H * 4); REG(tabs, (size_t)cfg->layers * 2 * 16); - REG(pf_x, OMEGA_GPU_DGRAPH_ATTN * 4); REG(pf_y, H * 4); /* prefetch launch (W-L2d): x read by nothing else, y read by nothing */ -#undef REG - L->bytes = o; - int rc = OMEGA_GPU_DGRAPH_OK; - if (omega_gpu_cmdlist_create(OMEGA_GPU_CMDLIST_MAX_LAUNCHES, &g->cl) != 0) { omega_gpu_decode_graph_free(g); return OMEGA_GPU_DGRAPH_CHIP_FAIL; } - omega_gpu_session_lock(); - if (!omega_gpu_session_open() || omega_gpu_session_alloc(L->bytes, &g->buf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - static const struct { OmegaDecKind kind; uint32_t mode; int mutant; } spec[K_COUNT] = { - [K_NORM] = { OMEGA_DEC_RES, OMEGA_DEC_RES_NORM, 0 }, - [K_ADD] = { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD, 0 }, - [K_CN] = { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 0 }, - [K_SW] = { OMEGA_DEC_SWIGLU, 0, 0 }, - [K_AM0] = { OMEGA_DEC_ARGMAX, 0, 0 }, - [K_AM1] = { OMEGA_DEC_ARGMAX, 1, 0 }, - [K_SW_M1] = { OMEGA_DEC_SWIGLU, 0, 1 }, - [K_CN_M2] = { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 2 }, - }; - for (unsigned i = 0; i < K_COUNT && rc == OMEGA_GPU_DGRAPH_OK; i++) rc = kern_build(&g->k[i], spec[i].kind, spec[i].mode, spec[i].mutant); - if (rc == OMEGA_GPU_DGRAPH_OK) { - memset(g->buf.cpu, 0, L->bytes); - float *lg = cpu_of(g, L->logits), *amv = cpu_of(g, L->am_v); - for (size_t i = cfg->vocab; i < (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN; i++) lg[i] = NEG_PAD; /* lm_head writes [0, vocab) only */ - for (size_t i = 0; i < OMEGA_DEC_ARGMAX_SPAN; i++) amv[i] = NEG_PAD; /* stage 1 writes [0, ctas) only */ - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_DGRAPH_OK) { omega_gpu_decode_graph_free(g); return rc; } - *out = g; - return OMEGA_GPU_DGRAPH_OK; -} - -static int shape_is(const OmegaGpuFp8Tensor *t, uint32_t e, uint32_t n, uint32_t k) { - uint32_t te = 0, tn = 0, tk = 0; omega_gpu_fp8_tensor_shape(t, &te, &tn, &tk); - return t && te == e && tn == n && tk == k; -} - -int omega_gpu_decode_graph_set_layer(OmegaGpuDecodeGraph *g, uint32_t layer, const OmegaGpuFp8Tensor *qkv, const OmegaGpuFp8Tensor *o, - const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, const float *input_norm) { - if (!g || layer >= g->cfg.layers || !input_norm || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - const uint32_t H = OMEGA_GPU_DGRAPH_HIDDEN, I = OMEGA_GPU_DGRAPH_INTER; - if (!shape_is(qkv, 1, OMEGA_GPU_DGRAPH_QKV, H) || !shape_is(o, 1, H, OMEGA_GPU_DGRAPH_ATTN) || !shape_is(gate_up, 128, 2 * I, H) || !shape_is(down, 128, H, I)) - return OMEGA_GPU_DGRAPH_BAD_ARGS; - uint64_t t[4]; - if (omega_gpu_fp8_tensor_entry(qkv, 0, &t[0], &t[1]) != 0 || omega_gpu_fp8_tensor_entry(o, 0, &t[2], &t[3]) != 0) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - memcpy((uint8_t *)cpu_of(g, g->lo.tabs) + (size_t)layer * 32u, t, sizeof t); - memcpy((float *)cpu_of(g, g->lo.norms) + (size_t)layer * H, input_norm, H * 4u); - int rc = omega_gpu_session_sync_to_gpu(&g->buf) == 0 ? OMEGA_GPU_DGRAPH_OK : OMEGA_GPU_DGRAPH_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_DGRAPH_OK) { g->layer[layer].qkv = qkv; g->layer[layer].o = o; g->layer[layer].gu = gate_up; g->layer[layer].dn = down; g->layer[layer].set = 1; } - return rc; -} - -int omega_gpu_decode_graph_set_final_norm(OmegaGpuDecodeGraph *g, const float *final_norm) { - if (!g || !final_norm || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - memcpy(cpu_of(g, g->lo.fnorm), final_norm, OMEGA_GPU_DGRAPH_HIDDEN * 4u); - int rc = omega_gpu_session_sync_to_gpu(&g->buf) == 0 ? OMEGA_GPU_DGRAPH_OK : OMEGA_GPU_DGRAPH_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_DGRAPH_OK) g->final_set = 1; - return rc; -} - -OmegaGpuCmdList *omega_gpu_decode_graph_list(OmegaGpuDecodeGraph *g) { return g ? g->cl : NULL; } -void omega_gpu_decode_graph_set_flush_each(OmegaGpuDecodeGraph *g, int on) { if (g) g->flush_each = on ? 1 : 0; } -void omega_gpu_decode_graph_test_set_mutant(OmegaGpuDecodeGraph *g, int mutant) { if (g) g->mutant = mutant; } - -void omega_gpu_decode_graph_vas(const OmegaGpuDecodeGraph *g, OmegaGpuDecodeGraphVas *v) { - if (!v) return; - memset(v, 0, sizeof *v); - if (!g) return; - v->x = va_of(g, g->lo.x); v->xq = va_of(g, g->lo.xq); v->qkv = va_of(g, g->lo.qkv); v->attn = va_of(g, g->lo.attn); v->o = va_of(g, g->lo.o); - v->gu = va_of(g, g->lo.gu); v->act = va_of(g, g->lo.act); v->dn = va_of(g, g->lo.dn); v->hidden = va_of(g, g->lo.hidden); - v->logits = va_of(g, g->lo.logits); v->token = va_of(g, g->lo.token); -} - -/* ---- the list ---- */ - -/* barrier between the launches of a token (W-L2c launch-cost study): omega_gpu_decode_graph_set_barrier, else env - * AIEN_OMEGA_DGRAPH_BARRIER (0 wfi+inval_all = default, 2 wfi_only, 3 wfi+inval_data, 4 flush_data; 1 none is refused: the - * token is a dependency chain). Read once. */ -static int g_barrier = -1; -void omega_gpu_decode_graph_set_barrier(int b) { g_barrier = (b >= 0 && b <= 4 && b != 1) ? b : 0; } -int omega_gpu_decode_graph_barrier(void) { - if (g_barrier < 0) { const char *e = getenv("AIEN_OMEGA_DGRAPH_BARRIER"); omega_gpu_decode_graph_set_barrier(e ? atoi(e) : 0); } - return g_barrier; -} -void omega_gpu_decode_graph_test_set_barrier_none(void) { g_barrier = 1; } -/* weight prefetch (W-L2d): 1 = beside each layer's attention, an independent launch (no barrier before it) runs the o_proj GEMV - * on a scratch x into a scratch y, so the o_proj weights stream from DRAM while the latency-bound attention runs and the real - * o_proj then reads them from L2 (needs GPU-cached weights: an uncached mapping is never kept in L2, gpu_l2_reuse_test r2). - * omega_gpu_decode_graph_set_prefetch, else env AIEN_OMEGA_DGRAPH_PREFETCH ("1"). Read once. Default 0. */ -static int g_prefetch = -1, g_prefetch_red; -void omega_gpu_decode_graph_set_prefetch(int on) { g_prefetch = on ? 1 : 0; } -int omega_gpu_decode_graph_prefetch(void) { - if (g_prefetch < 0) { const char *e = getenv("AIEN_OMEGA_DGRAPH_PREFETCH"); g_prefetch = (e && e[0] == '1' && e[1] == 0) ? 1 : 0; } - return g_prefetch; -} -void omega_gpu_decode_graph_test_set_prefetch_red(int on) { g_prefetch_red = on ? 1 : 0; } -static OmegaGpuCmdListBarrier barrier_now(void) { return (OmegaGpuCmdListBarrier)omega_gpu_decode_graph_barrier(); } - -static OmegaGpuCmdListOpts list_opts(const OmegaGpuDecodeGraph *g) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = barrier_now(); o.timeout_ms = TIMEOUT_MS; o.stamps = g->stamps; - return o; -} - -static int submit_now(OmegaGpuDecodeGraph *g) { - if (omega_gpu_cmdlist_count(g->cl) == 0) return OMEGA_GPU_DGRAPH_OK; - OmegaGpuCmdListOpts o = list_opts(g); - OmegaGpuCmdListStats st; memset(&st, 0, sizeof st); - int rc = omega_gpu_cmdlist_submit(g->cl, &o, &st); - g->acc.launches += st.launches; g->acc.submits += st.submits; g->acc.chip_ns += st.elapsed_ns; g->acc.sems_done += st.sems_done; - if (rc == 0 && g->stamps) { /* before reset: the accessor sizes by the list; later submits (flush_each) drop their start slot */ - uint64_t tmp[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; - int cnt = omega_gpu_cmdlist_stamps(g->cl, tmp, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - if (cnt < 0) rc = -1; - else { const int from = g->n_stamp == 0 ? 0 : 1; for (int i = from; i < cnt; i++) g->stamp[g->n_stamp++] = tmp[i]; } - } - g->tagged_in_list = 0; - omega_gpu_cmdlist_reset(g->cl); - if (rc != 0) return fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - if (st.sems_done != st.launches) { - char e[128]; omega_gpu_fmt(e, sizeof e, "decode graph: %u of %u launch semaphores DONE (first missing %d)", st.sems_done, st.launches, st.first_missing); - return fail(g, e, OMEGA_GPU_DGRAPH_CHIP_FAIL); - } - return OMEGA_GPU_DGRAPH_OK; -} - -/* kinds for the launches added since the last tag (the timeline) */ -static void tag(OmegaGpuDecodeGraph *g, uint8_t kind) { - const uint32_t n = omega_gpu_cmdlist_count(g->cl); - for (; g->tagged_in_list < n && g->n_kind < OMEGA_GPU_CMDLIST_MAX_LAUNCHES; g->tagged_in_list++) g->kind[g->n_kind++] = kind; -} - -/* after every recorded launch: flush_each submits it on its own (the comparison path) */ -static int after_op(OmegaGpuDecodeGraph *g, uint8_t kind, int api_rc) { - if (api_rc != 0) return fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - tag(g, kind); - return g->flush_each ? submit_now(g) : OMEGA_GPU_DGRAPH_OK; -} - -static int add_glue(OmegaGpuDecodeGraph *g, uint8_t kind, const Kern *k, uint32_t gx, uint32_t gy, size_t elems, const uint32_t *args, uint32_t n_args) { - OmegaGpuLaunch L; memset(&L, 0, sizeof L); - L.code_va = k->code.va; L.gpr_count = k->gpr; L.threads_x = OMEGA_DEC_THREADS; L.threads_y = 1; L.grid_x = gx; L.grid_y = gy; - L.num_elements = elems; L.args = args; L.n_args = n_args; L.timeout_ms = TIMEOUT_MS; - return after_op(g, kind, omega_gpu_cmdlist_add(g->cl, &L) < 0 ? -1 : 0); -} - -static int res_kernel(const OmegaGpuDecodeGraph *g, uint32_t mode) { - if (mode == OMEGA_DEC_RES_NORM) return K_NORM; - if (mode == OMEGA_DEC_RES_ADD) return K_ADD; - if (mode == (OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM)) return g->mutant == 2 ? K_CN_M2 : K_CN; - return -1; -} - -int omega_gpu_decode_graph_record_res(OmegaGpuDecodeGraph *g, uint32_t mode, uint64_t x_va, uint64_t a_va, uint64_t w_va, - uint64_t nw_va, uint64_t y_va, float eps, float scale) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - int ki = res_kernel(g, mode); - if (ki < 0) return fail(g, "decode graph: RES mode not built (NORM, ADD, COMBINE|NORM)", OMEGA_GPU_DGRAPH_BAD_ARGS); - uint32_t a[OMEGA_DEC_RES_WORDS]; memset(a, 0, sizeof a); - put64(a, OMEGA_DEC_RES_X, x_va); put64(a, OMEGA_DEC_RES_A, a_va); put64(a, OMEGA_DEC_RES_W, w_va); put64(a, OMEGA_DEC_RES_NW, nw_va); - put64(a, OMEGA_DEC_RES_Y, y_va); putf(a, OMEGA_DEC_RES_EPS, eps); putf(a, OMEGA_DEC_RES_SCALE, scale); - const uint8_t kind = ki == K_ADD ? OMEGA_GPU_DGRAPH_K_ADD : ki == K_NORM ? OMEGA_GPU_DGRAPH_K_NORM : OMEGA_GPU_DGRAPH_K_COMBINE; - return add_glue(g, kind, &g->k[ki], 1, 1, OMEGA_GPU_DGRAPH_HIDDEN, a, OMEGA_DEC_RES_WORDS); -} - -int omega_gpu_decode_graph_record_swiglu(OmegaGpuDecodeGraph *g, uint64_t gu_va, uint64_t act_va, float scale) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - uint32_t a[OMEGA_DEC_SW_WORDS]; memset(a, 0, sizeof a); - put64(a, OMEGA_DEC_SW_GU, gu_va); put64(a, OMEGA_DEC_SW_ACT, act_va); putf(a, OMEGA_DEC_SW_SCALE, scale); - return add_glue(g, OMEGA_GPU_DGRAPH_K_SWIGLU, &g->k[g->mutant == 1 ? K_SW_M1 : K_SW], OMEGA_DEC_INTER / OMEGA_DEC_THREADS, OMEGA_DEC_TOPK, (size_t)OMEGA_DEC_TOPK * OMEGA_DEC_INTER, a, OMEGA_DEC_SW_WORDS); -} - -int omega_gpu_decode_graph_begin_token(OmegaGpuDecodeGraph *g, const float *x_embed) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - g->t_begin = omega_gpu_session_now_ns(); - g->in_token = 1; g->failed = 0; g->xq_layer = -1; g->hidden_ready = 0; - memset(&g->acc, 0, sizeof g->acc); - g->n_kind = 0; g->tagged_in_list = 0; g->n_stamp = 0; - omega_gpu_cmdlist_reset(g->cl); - if (!omega_gpu_session_open()) return fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - uint32_t *tok = cpu_of(g, g->lo.token); - tok[0] = TOKEN_POISON; tok[1] = TOKEN_POISON; - if (x_embed) memcpy(cpu_of(g, g->lo.x), x_embed, OMEGA_GPU_DGRAPH_HIDDEN * 4u); - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0) return fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - return OMEGA_GPU_DGRAPH_OK; -} - -int omega_gpu_decode_graph_record_layer(OmegaGpuDecodeGraph *g, uint32_t l, uint32_t pos) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->failed) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (l >= g->cfg.layers || !g->layer[l].set || g->hidden_ready || (l + 1 == g->cfg.layers && !g->final_set)) - return fail(g, "decode graph: layer not set, out of order, or final norm missing", OMEGA_GPU_DGRAPH_BAD_ARGS); - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(g, &v); - const float eps = g->cfg.eps; - const uint64_t norm_l = va_of(g, g->lo.norms) + (uint64_t)l * OMEGA_GPU_DGRAPH_HIDDEN * 4u, tab = va_of(g, g->lo.tabs) + (uint64_t)l * 32u; - int rc = OMEGA_GPU_DGRAPH_OK; - if (g->xq_layer != (int)l) rc = omega_gpu_decode_graph_record_res(g, OMEGA_DEC_RES_NORM, v.x, 0, 0, norm_l, v.xq, eps, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_QKV, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].qkv, 1, tab, v.xq, 1, v.qkv)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_ATTN, omega_gpu_decode_attn_record(g->cl, g->cfg.attn, l, pos, v.qkv, eps, g->mutant == 3 ? 1.0f : SCALE_2P64, v.attn)); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_decode_graph_prefetch()) { /* tagged attn: its time is the overlapped window */ - int prc = omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].o, 1, tab + 16u, va_of(g, g->lo.pf_x), 1, va_of(g, g->lo.pf_y)); - if (prc == 0 && omega_gpu_cmdlist_mark_independent(g->cl) != 0) prc = -1; - rc = after_op(g, OMEGA_GPU_DGRAPH_K_ATTN, prc); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_O, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].o, 1, tab + 16u, v.attn, 1, v.o)); - if (rc == OMEGA_GPU_DGRAPH_OK && g_prefetch_red && !g->flush_each && omega_gpu_cmdlist_mark_independent(g->cl) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; /* TEST ONLY red: o_proj itself unordered after the attention */ - if (rc == OMEGA_GPU_DGRAPH_OK) rc = omega_gpu_decode_graph_record_res(g, OMEGA_DEC_RES_ADD, v.x, v.o, 0, 0, 0, eps, 1.0f); - OmegaGpuRouterDevOut r; memset(&r, 0, sizeof r); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_ROUTER, omega_gpu_router_record(g->cl, g->cfg.router, l, v.x, eps, g->cfg.norm_topk, SCALE_2P64, &r)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_GATE_UP, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].gu, OMEGA_GPU_DGRAPH_TOPK, r.tab_gu_va, r.xout_va, 1, v.gu)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = omega_gpu_decode_graph_record_swiglu(g, v.gu, v.act, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_DOWN, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].dn, OMEGA_GPU_DGRAPH_TOPK, r.tab_dn_va, v.act, OMEGA_GPU_DGRAPH_TOPK, v.dn)); - if (rc == OMEGA_GPU_DGRAPH_OK) { - const int last = l + 1 == g->cfg.layers; - const uint64_t nw = last ? va_of(g, g->lo.fnorm) : norm_l + OMEGA_GPU_DGRAPH_HIDDEN * 4u; - rc = omega_gpu_decode_graph_record_res(g, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, v.x, v.dn, r.wts_va, nw, last ? v.hidden : v.xq, eps, last ? 1.0f : SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) { if (last) g->hidden_ready = 1; else g->xq_layer = (int)l + 1; } - } - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -int omega_gpu_decode_graph_record_final(OmegaGpuDecodeGraph *g) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->failed) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (!g->final_set) return fail(g, "decode graph: final norm not set", OMEGA_GPU_DGRAPH_BAD_ARGS); - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(g, &v); - int rc = OMEGA_GPU_DGRAPH_OK; - if (!g->hidden_ready) rc = omega_gpu_decode_graph_record_res(g, OMEGA_DEC_RES_NORM, v.x, 0, 0, va_of(g, g->lo.fnorm), v.hidden, g->cfg.eps, 1.0f); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_DGRAPH_K_LM_HEAD, omega_gpu_bf16_gemv_record(g->cl, g->cfg.lm_head, v.hidden, v.logits)); - uint32_t a0[OMEGA_DEC_AM_WORDS], a1[OMEGA_DEC_AM_WORDS]; memset(a0, 0, sizeof a0); memset(a1, 0, sizeof a1); - const uint64_t amv = va_of(g, g->lo.am_v), ami = va_of(g, g->lo.am_i); - put64(a0, OMEGA_DEC_AM_V, v.logits); put64(a0, OMEGA_DEC_AM_I, 0); put64(a0, OMEGA_DEC_AM_OV, amv); put64(a0, OMEGA_DEC_AM_OI, ami); - put64(a1, OMEGA_DEC_AM_V, amv); put64(a1, OMEGA_DEC_AM_I, ami); put64(a1, OMEGA_DEC_AM_OV, v.token + 4u); put64(a1, OMEGA_DEC_AM_OI, v.token); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_DGRAPH_K_ARGMAX, &g->k[K_AM0], g->am_ctas, 1, (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN, a0, OMEGA_DEC_AM_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_DGRAPH_K_ARGMAX, &g->k[K_AM1], 1, 1, OMEGA_DEC_ARGMAX_SPAN, a1, OMEGA_DEC_AM_WORDS); - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -int omega_gpu_decode_graph_end_token(OmegaGpuDecodeGraph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - int rc = g->failed ? OMEGA_GPU_DGRAPH_CHIP_FAIL : OMEGA_GPU_DGRAPH_OK; - const uint64_t t_rec = omega_gpu_session_now_ns(); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = submit_now(g); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_decode_attn_counters_check(g->cfg.attn) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_cpu(&g->buf) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - if (rc == OMEGA_GPU_DGRAPH_OK) { - const uint32_t t = ((const uint32_t *)cpu_of(g, g->lo.token))[0]; - if (t == TOKEN_POISON || t >= g->cfg.vocab) { - char e[96]; omega_gpu_fmt(e, sizeof e, "decode graph: token output %u not written or out of range", t); - rc = fail(g, e, OMEGA_GPU_DGRAPH_CHIP_FAIL); - } else if (token) *token = t; - } - omega_gpu_cmdlist_reset(g->cl); - g->in_token = 0; - const uint64_t t_end = omega_gpu_session_now_ns(); - if (st) { *st = g->acc; st->record_ns = (g->flush_each ? t_end : t_rec) - g->t_begin; st->total_ns = t_end - g->t_begin; } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_decode_graph_token(OmegaGpuDecodeGraph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st) { - if (!g) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (omega_gpu_decode_graph_begin_token(g, x_embed) == OMEGA_GPU_DGRAPH_BAD_ARGS) return OMEGA_GPU_DGRAPH_BAD_ARGS; - for (uint32_t l = 0; l < g->cfg.layers && !g->failed; l++) (void)omega_gpu_decode_graph_record_layer(g, l, pos); - if (!g->failed) (void)omega_gpu_decode_graph_record_final(g); - return omega_gpu_decode_graph_end_token(g, token, st); -} - -int omega_gpu_decode_graph_read(OmegaGpuDecodeGraph *g, float *x, float *hidden, float *logits) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_session_sync_to_cpu(&g->buf) == 0 ? OMEGA_GPU_DGRAPH_OK : OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (rc == OMEGA_GPU_DGRAPH_OK) { - if (x) memcpy(x, cpu_of(g, g->lo.x), OMEGA_GPU_DGRAPH_HIDDEN * 4u); - if (hidden) memcpy(hidden, cpu_of(g, g->lo.hidden), OMEGA_GPU_DGRAPH_HIDDEN * 4u); - if (logits) memcpy(logits, cpu_of(g, g->lo.logits), (size_t)g->cfg.vocab * 4u); - } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- timeline ---- */ -void omega_gpu_decode_graph_set_stamps(OmegaGpuDecodeGraph *g, int on) { if (g && !g->in_token) g->stamps = on ? 1 : 0; } - -int omega_gpu_decode_graph_stamps(const OmegaGpuDecodeGraph *g, uint64_t *stamps, uint8_t *kinds, uint32_t cap) { - if (!g || g->in_token || !stamps || !kinds) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!g->stamps || g->n_stamp != g->n_kind + 1u) { omega_gpu_session_set_error("decode graph: no timeline for the last token (stamps off or it failed)"); return OMEGA_GPU_DGRAPH_BAD_ARGS; } - if (cap < g->n_stamp) { omega_gpu_session_set_error("decode graph: timeline buffers too small"); return OMEGA_GPU_DGRAPH_BAD_ARGS; } - memcpy(stamps, g->stamp, (size_t)g->n_stamp * sizeof stamps[0]); - memcpy(kinds, g->kind, (size_t)g->n_kind); - return (int)g->n_kind; -} - -const char *omega_gpu_decode_graph_kind_name(uint8_t kind) { - static const char *const names[OMEGA_GPU_DGRAPH_K_COUNT] = { "norm", "qkv", "attn", "o_proj", "res_add", "router", "gate_up", "swiglu", "down", "combine_norm", "lm_head", "argmax" }; - return kind < OMEGA_GPU_DGRAPH_K_COUNT ? names[kind] : "?"; -} diff --git a/src/omega_gpu_decode_graph.h b/src/omega_gpu_decode_graph.h deleted file mode 100644 index c18dc7ab5..000000000 --- a/src/omega_gpu_decode_graph.h +++ /dev/null @@ -1,188 +0,0 @@ -#ifndef OMEGA_GPU_DECODE_GRAPH_H -#define OMEGA_GPU_DECODE_GRAPH_H -/* - * omega_gpu_decode_graph: one Qwen3-30B-A3B decode token as ONE command list (OWN-30B W-L2a, 2026-10-13). - * - * Today's token (sc qwen3_moe_omega.rs step()) is 6 synchronous launches per layer + lm_head with the residual x - * round-tripping through the host between them. Here x stays on the device and every step is recorded into one - * omega_gpu_cmdlist and submitted once: - * - * (layer 0 only) RES NORM xq = RMSNorm(x) * input_norm[0] * 2^64 (the FP8 x' row) - * per layer l: fp8 qkv qkv = W_qkv[l] . xq omega_gpu_fp8_gemv_grouped_record - * decode attn attn = attention(qkv, KV[l], pos) * 2^64 omega_gpu_decode_attn_record - * fp8 o o = W_o[l] . attn - * RES ADD x += o - * router xr = RMSNorm(x) * post_norm[l] * 2^64, ids, wts, tables omega_gpu_router_record - * fp8 gate_up gu[8][1536] = W_gu[ids] . xr (router's table) - * SWIGLU act[8][768] = silu(gate) * up * 2^64 - * fp8 down dn[8][2048] = W_dn[ids] . act[g] (router's table) - * RES COMBINE|NORM x += sum_g wts[g] * dn[g]; then - * xq = RMSNorm(x) * input_norm[l+1] * 2^64 (not the last layer), or - * hidden = RMSNorm(x) * final_norm (the last layer) - * final: bf16 lm_head logits = W_lm . hidden omega_gpu_bf16_gemv_record - * ARGMAX x2 token = lowest index of max(logits) (75 CTAs, then 1, for 151936) - * - * Launches: 9 per layer + 4 (48 layers: 436). The glue kernels are omega_blackwell_codegen_dec.h (chip parity PASS). - * Numerics vs the host-glue path: identical operations except the RMSNorm (f32 FFMA sum of squares + MUFU.RSQ vs the - * host's f64 sum and 1/sqrt) and SwiGLU (MUFU EX2/RCP vs expf): logits close, not bit-identical; the argmax is the - * host's rule (lowest index on ties). - * - * Memory: every buffer is omega_gpu_session_alloc (GPU-uncached; nvos.h:1117 "For system memory this will not be - * coherent with direct CPU mappings"): the host writes x before the submit and reads the token / logits after. - * - * Threading: begin_token takes omega_gpu_session_lock() and end_token releases it. Between them only record calls - * (this file's and the four APIs' *_record) may run on this thread; a non-record API call would self-deadlock. - * The four APIs refuse a record that would evict a cached kernel: run one plain call per shape (or one token with the - * host path) first, or simply record the first token (an empty cache slot is filled, never evicted). - * - * ============ C signatures (for the Rust binding) ============ - * int omega_gpu_decode_graph_create(const OmegaGpuDecodeGraphConfig *cfg, OmegaGpuDecodeGraph **out); - * void omega_gpu_decode_graph_free(OmegaGpuDecodeGraph *g); - * int omega_gpu_decode_graph_set_layer(OmegaGpuDecodeGraph *g, uint32_t layer, const OmegaGpuFp8Tensor *qkv, - * const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, const float *input_norm); - * int omega_gpu_decode_graph_set_final_norm(OmegaGpuDecodeGraph *g, const float *final_norm); - * int omega_gpu_decode_graph_token(OmegaGpuDecodeGraph *g, const float *x_embed, uint32_t pos, uint32_t *token, - * OmegaGpuDecodeGraphStats *st); begin + every layer + final + end - * int omega_gpu_decode_graph_begin_token(OmegaGpuDecodeGraph *g, const float *x_embed); - * int omega_gpu_decode_graph_record_layer(OmegaGpuDecodeGraph *g, uint32_t layer, uint32_t pos); - * int omega_gpu_decode_graph_record_final(OmegaGpuDecodeGraph *g); - * int omega_gpu_decode_graph_end_token(OmegaGpuDecodeGraph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st); - * int omega_gpu_decode_graph_record_res(OmegaGpuDecodeGraph *g, uint32_t mode, uint64_t x_va, uint64_t a_va, uint64_t w_va, - * uint64_t nw_va, uint64_t y_va, float eps, float scale); - * int omega_gpu_decode_graph_record_swiglu(OmegaGpuDecodeGraph *g, uint64_t gu_va, uint64_t act_va, float scale); - * struct OmegaGpuCmdList *omega_gpu_decode_graph_list(OmegaGpuDecodeGraph *g); - * void omega_gpu_decode_graph_vas(const OmegaGpuDecodeGraph *g, OmegaGpuDecodeGraphVas *v); - * int omega_gpu_decode_graph_read(OmegaGpuDecodeGraph *g, float *x, float *hidden, float *logits); - * Return codes: 0 OK, negative OMEGA_GPU_DGRAPH_* (the failing stage in omega_gpu_session_last_error()). - */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_router_api.h" -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_bf16_gemv_api.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_DGRAPH_OK = 0, - OMEGA_GPU_DGRAPH_BAD_ARGS = -1, /* NULL, bad layer, shape mismatch, layer not set, call out of order */ - OMEGA_GPU_DGRAPH_CODEGEN_FAIL = -3, - OMEGA_GPU_DGRAPH_CHIP_FAIL = -4, /* device, alloc, a record refused, submit, semaphore, counter or output check */ -}; - -#define OMEGA_GPU_DGRAPH_HIDDEN 2048u -#define OMEGA_GPU_DGRAPH_QKV 5120u /* 32 * 128 + 2 * 4 * 128 */ -#define OMEGA_GPU_DGRAPH_ATTN 4096u /* 32 * 128 */ -#define OMEGA_GPU_DGRAPH_TOPK 8u -#define OMEGA_GPU_DGRAPH_INTER 768u -#define OMEGA_GPU_DGRAPH_MAX_LAYERS 64u - -typedef struct { - uint32_t layers; /* 1..OMEGA_GPU_DGRAPH_MAX_LAYERS, <= the router's and the KV cache's */ - uint32_t vocab; /* lm_head rows (151936 for Qwen3-30B-A3B), <= 2048 * 2048 */ - float eps; /* rms_norm_eps */ - int norm_topk; /* config.json norm_topk_prob (1 for Qwen3-30B-A3B) */ - OmegaGpuRouter *router; /* per-layer router weights, post-attention norms and expert directories set */ - OmegaGpuDecodeAttnCache *attn; /* KV cache with the per-layer q/k norms set */ - const OmegaGpuBf16Tensor *lm_head; /* [vocab][2048] */ -} OmegaGpuDecodeGraphConfig; - -typedef struct { - uint32_t launches; /* launches recorded for the token */ - uint32_t submits; /* submissions (1 normally; = launches with flush_each) */ - uint64_t chip_ns; /* sum of the list submissions' first-submit-to-last-marker time */ - uint64_t record_ns; /* host: begin_token to the submit (recording) */ - uint64_t total_ns; /* host: begin_token to end_token return */ - uint32_t sems_done; /* launch semaphores found DONE */ -} OmegaGpuDecodeGraphStats; - -/* Device addresses of the graph's buffers (all f32 unless noted). */ -typedef struct { - uint64_t x; /* [2048] residual, device resident across the token */ - uint64_t xq; /* [2048] input-norm x' (* 2^64) */ - uint64_t qkv; /* [5120] */ - uint64_t attn; /* [4096] attention output * 2^64 */ - uint64_t o; /* [2048] */ - uint64_t gu; /* [8][1536] */ - uint64_t act; /* [8][768] * 2^64 */ - uint64_t dn; /* [8][2048] */ - uint64_t hidden; /* [2048] final norm output */ - uint64_t logits; /* [ctas * 2048], tail padded with -1e30 */ - uint64_t token; /* u32 greedy token, then f32 its logit */ -} OmegaGpuDecodeGraphVas; - -typedef struct OmegaGpuDecodeGraph OmegaGpuDecodeGraph; - -int omega_gpu_decode_graph_create(const OmegaGpuDecodeGraphConfig *cfg, OmegaGpuDecodeGraph **out); -void omega_gpu_decode_graph_free(OmegaGpuDecodeGraph *g); -/* Shapes are checked: qkv [1][5120][2048], o [1][2048][4096], gate_up [128][1536][2048], down [128][2048][768]. - * input_norm: the checkpoint's input_layernorm.weight widened to f32 [2048]. The tensors stay owned by the caller. */ -int omega_gpu_decode_graph_set_layer(OmegaGpuDecodeGraph *g, uint32_t layer, const OmegaGpuFp8Tensor *qkv, const OmegaGpuFp8Tensor *o, - const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, const float *input_norm); -int omega_gpu_decode_graph_set_final_norm(OmegaGpuDecodeGraph *g, const float *final_norm); - -/* One whole token: x_embed (f32 [2048], the token's embedding row) -> greedy token. pos: the token's position. */ -int omega_gpu_decode_graph_token(OmegaGpuDecodeGraph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st); - -/* The same in steps. begin_token takes the session lock, empties the list and (x_embed non-NULL) writes x. */ -int omega_gpu_decode_graph_begin_token(OmegaGpuDecodeGraph *g, const float *x_embed); -int omega_gpu_decode_graph_record_layer(OmegaGpuDecodeGraph *g, uint32_t layer, uint32_t pos); -int omega_gpu_decode_graph_record_final(OmegaGpuDecodeGraph *g); -/* Submits, checks every launch semaphore, the attention split counters and the token output (poisoned before the - * submit), reads the token (may be NULL), releases the lock. Always releases the lock, also after an earlier failed - * record (then returns that failure without submitting). */ -int omega_gpu_decode_graph_end_token(OmegaGpuDecodeGraph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st); - -/* Glue records (between begin and end): RES (omega_blackwell_codegen_dec.h modes ADD / COMBINE / NORM) and SWIGLU. */ -int omega_gpu_decode_graph_record_res(OmegaGpuDecodeGraph *g, uint32_t mode, uint64_t x_va, uint64_t a_va, uint64_t w_va, - uint64_t nw_va, uint64_t y_va, float eps, float scale); -int omega_gpu_decode_graph_record_swiglu(OmegaGpuDecodeGraph *g, uint64_t gu_va, uint64_t act_va, float scale); - -struct OmegaGpuCmdList *omega_gpu_decode_graph_list(OmegaGpuDecodeGraph *g); -void omega_gpu_decode_graph_vas(const OmegaGpuDecodeGraph *g, OmegaGpuDecodeGraphVas *v); -/* Takes the lock; copies the device x, hidden and logits (vocab values) of the last token; any pointer may be NULL. */ -int omega_gpu_decode_graph_read(OmegaGpuDecodeGraph *g, float *x, float *hidden, float *logits); - -/* ---- timeline (measurement) ---- */ -/* One kind per recorded launch, in list order. */ -enum { - OMEGA_GPU_DGRAPH_K_NORM = 0, OMEGA_GPU_DGRAPH_K_QKV, OMEGA_GPU_DGRAPH_K_ATTN, OMEGA_GPU_DGRAPH_K_O, OMEGA_GPU_DGRAPH_K_ADD, - OMEGA_GPU_DGRAPH_K_ROUTER, OMEGA_GPU_DGRAPH_K_GATE_UP, OMEGA_GPU_DGRAPH_K_SWIGLU, OMEGA_GPU_DGRAPH_K_DOWN, OMEGA_GPU_DGRAPH_K_COMBINE, - OMEGA_GPU_DGRAPH_K_LM_HEAD, OMEGA_GPU_DGRAPH_K_ARGMAX, OMEGA_GPU_DGRAPH_K_COUNT -}; -/* 1: every token also records a GPU timestamp (ns) before the first launch and after each launch (after its WAIT_FOR_IDLE). - * Call between tokens. Adds one report per launch to the list. 0 = off (default). */ -void omega_gpu_decode_graph_set_stamps(OmegaGpuDecodeGraph *g, int on); -/* Barrier between the launches of a token: 0 WFI + invalidate all (default), 2 WFI only, 3 WFI + invalidate data, 4 NVK-style - * flush_data (implicit WFI). Process-wide, read once (env AIEN_OMEGA_DGRAPH_BARRIER when never set). 1 (none) is refused. */ -void omega_gpu_decode_graph_set_barrier(int b); -int omega_gpu_decode_graph_barrier(void); -/* The last token with stamps on: stamps[0 .. n] (n + 1 values), kinds[0 .. n). Returns n (launches) or BAD_ARGS - * (stamps off, the token failed, buffers smaller than launches + 1). Launch i took stamps[i + 1] - stamps[i] ns. */ -int omega_gpu_decode_graph_stamps(const OmegaGpuDecodeGraph *g, uint64_t *stamps, uint8_t *kinds, uint32_t cap); -const char *omega_gpu_decode_graph_kind_name(uint8_t kind); - -/* ---- TEST ONLY ---- */ -/* 1: submit after every launch (same kernels and arguments, one submission each: the batching comparison). */ -void omega_gpu_decode_graph_set_flush_each(OmegaGpuDecodeGraph *g, int on); -/* 1 SWIGLU mutant (up half read at +767); 2 COMBINE skips expert 7; 3 wrong wiring: attention written at scale 1 - * instead of 2^64 (the o_proj then sees x' 2^64 too small). 0 none. */ -void omega_gpu_decode_graph_test_set_mutant(OmegaGpuDecodeGraph *g, int mutant); -/* TEST ONLY: negative control for the barrier study: lets barrier 1 (none) through, which set_barrier refuses. The token is a - * dependency chain, so the comparison against the per-launch path (B) must fail. */ -void omega_gpu_decode_graph_test_set_barrier_none(void); -/* Weight prefetch beside the attention (W-L2d): 1 = each layer records an independent o_proj GEMV on scratch buffers right after - * the attention launch (no barrier between them), pulling the o_proj weights into L2 while the attention runs; useful only - * with GPU-cached weights (AIEN_OMEGA_FP8_WEIGHT_CACHE=1). Process-wide; env AIEN_OMEGA_DGRAPH_PREFETCH ("1") when never set. - * Outputs unchanged by construction (the prefetch writes only its own scratch y). Default 0. */ -void omega_gpu_decode_graph_set_prefetch(int on); -int omega_gpu_decode_graph_prefetch(void); -/* TEST ONLY red for the prefetch run: the real o_proj is also marked independent (unordered after the attention): must FAIL. */ -void omega_gpu_decode_graph_test_set_prefetch_red(int on); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c deleted file mode 100644 index fb821e4f3..000000000 --- a/src/omega_gpu_elementwise_api.c +++ /dev/null @@ -1,1139 +0,0 @@ -/* omega_gpu_elementwise_api.c: FB-1 cut 4 (2026-10-04). See the header. - * - * Layout of this file: (1) kernel codegen on top of the BlackwellIR, with a - * small scheduler that writes every control word; (2) one launcher cloned from - * the chip-proven tensor matmul path (omega_blackwell_execute_matmul_tensor); - * (3) the public entry points, which split work into <= OMEGA_GPU_EW_MAX_CTAS - * launches and run the host-side bookkeeping. - * - * Scheduling rules (chip-learned, src/omega_numeric.c omega_numeric_check_patch): - * - a variable-latency result (LDG, LDS, LDC, LDCU, S2R, SHFL, MUFU) arrives through - * a scoreboard; the producer stalls >= 2 and the consumer waits on that SB; - * - a fixed-latency result (FADD FMUL FFMA IMAD IADD3 MOV LOP3 SHF) has no - * scoreboard: the producer stalls >= 5 before its consumer (we use 6); - * - a predicate producer (ISETP) stalls 14 before @P0 use (NAK SM120 padding); - * - stores (STG, STS) set a read barrier so the next instruction cannot overwrite - * the source register early. - * The emitter below serialises: every instruction waits on everything still - * pending. A final local pass tightens supported adjacent ALU pairs to 5 cycles. - */ -#include "omega_gpu_elementwise_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_bw_reconv.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include "omega_gpu_session.h" -#include "sha256.h" -#include -#include -#include -#include - -/* ------------------------------------------------------------------ codegen */ - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) -#define CW_YIELD 0x2000u -#define SB_NONE 7u -#define SB_GPR 0u /* variable-latency GPR results */ -#define SB_RD 1u /* store source-register read barrier */ -#define SB_UGPR 2u /* uniform-register results (LDCU) */ - -enum { K_FIXED, K_PRED, K_VAR, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -#define EW_MAX_LOOPS 4 -typedef struct { - BlackwellIRProgram *p; - uint32_t pending; /* scoreboards set and not yet waited on */ - int err; - int loop_start[EW_MAX_LOOPS], loop_end[EW_MAX_LOOPS]; - int n_loops; - int open_start[EW_MAX_LOOPS]; /* starts of loops begun and not yet ended (nesting stack) */ - int depth; - BwRegions rg; /* structured reconvergence regions (omega #308) */ - int rg_mutant; /* test only: 1 = drop the BSYNC at join, 2 = corrupt the BSSY target (host sim must catch both) */ - int exited; /* a predicated EXIT was emitted: some lanes of a warp may be gone */ - int exit_sync_ok; /* test only: lets a kernel put SHFL/BAR after a predicated EXIT (the negative control R6) */ - int test_path; /* building for omega_gpu_elementwise_codegen_ir (host tests), never for a launch */ -} Em; - -static void emit(Em *e, BlackwellIRInsn in, int kind) { - uint32_t wait = e->pending; - switch (kind) { - case K_FIXED: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_PRED: in.control = CW(14, SB_NONE, SB_NONE, wait); e->pending = 0; break; - case K_VAR: in.control = CW(4, SB_GPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_GPR; break; - case K_UVAR: in.control = CW(4, SB_UGPR, SB_NONE, wait) | CW_YIELD; e->pending = 1u << SB_UGPR; break; - case K_STORE: in.control = CW(4, SB_NONE, SB_RD, wait) | CW_YIELD; e->pending = 1u << SB_RD; break; - case K_SYNC: in.control = CW(6, SB_NONE, SB_NONE, wait); e->pending = 0; break; - /* a predicated EXIT or BRA that falls through must not be the only waiter */ - case K_EXIT: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - case K_BRA: in.control = CW(5, SB_NONE, SB_NONE, wait); e->pending = in.predicate_p0 ? wait : 0; break; - /* BSSY / BSYNC read no registers; the stall counts (1 and 5, both with yield) are the ones - * nvcc 13.0.88 writes for sm_121 (docs/gpu-reconvergence-308.md). They wait on everything - * pending so that, as for every branch here, nothing is in flight across a control edge - * and the straight-line scoreboard walk in the tests stays valid. */ - case K_BSSY: in.control = CW(1, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - case K_BSYNC: in.control = CW(5, SB_NONE, SB_NONE, wait) | CW_YIELD; e->pending = 0; break; - default: e->err = -1; return; - } - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; /* append returns the index */ -} - -static int V(Em *e) { int v = omega_bw_ir_alloc_vreg(e->p); if (v < 0) e->err = -1; return v; } -static int V64(Em *e) { int v = omega_bw_ir_alloc_vreg64(e->p); if (v < 0) e->err = -1; return v; } -static int UV64(Em *e) { int v = omega_bw_ir_alloc_uvreg64(e->p); if (v < 0) e->err = -1; return v; } -static int here(const Em *e) { return (int)e->p->count; } - -#define NOREG -1 -static BlackwellIRInsn I0(BlackwellIROpcode op) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = NOREG; in.src1_vreg = NOREG; in.src2_vreg = NOREG; in.src3_vreg = NOREG; in.ureg = NOREG; - return in; -} -static void ldcu64(Em *e, int udst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDCU64); i.dst_vreg = udst; i.imm = off; i.is_uniform = true; emit(e, i, K_UVAR); } -static void ldc64(Em *e, int dst64, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC64); i.dst_vreg = dst64; i.imm = off; emit(e, i, K_VAR); } -static void ldc32(Em *e, int dst, uint32_t off) { BlackwellIRInsn i = I0(BW_IR_LDC); i.dst_vreg = dst; i.imm = off; emit(e, i, K_VAR); } -static void s2r(Em *e, int dst, uint32_t sr) { BlackwellIRInsn i = I0(BW_IR_S2R); i.dst_vreg = dst; i.imm = sr; emit(e, i, K_VAR); } -static void movi(Em *e, int dst, uint32_t imm) { BlackwellIRInsn i = I0(BW_IR_MOV_IMM); i.dst_vreg = dst; i.imm = imm; emit(e, i, K_FIXED); } -static void movf(Em *e, int dst, float f) { uint32_t u; memcpy(&u, &f, 4); movi(e, dst, u); } -static void movrz(Em *e, int dst) { BlackwellIRInsn i = I0(BW_IR_MOV_RZ); i.dst_vreg = dst; emit(e, i, K_FIXED); } -/* dst = a * imm + c (c may be NOREG for RZ) */ -static void imadi(Em *e, int dst, int a, uint32_t imm, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c; emit(e, i, K_FIXED); } -/* dst = a * b + c (registers) */ -static void imadr(Em *e, int dst, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_IMAD); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void iadd3(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IADD3); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void lop3xor(Em *e, int dst, int a, int b) { BlackwellIRInsn i = I0(BW_IR_LOP3_XOR); i.dst_vreg = dst; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* dst64 = idx * 4 + ptr64 (byte address of element idx) */ -static void addr4(Em *e, int dst64, int idx, int ptr64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = idx; i.imm = 4; i.src3_vreg = ptr64; emit(e, i, K_FIXED); } -static void ldg(Em *e, int dst, int addr64, int udesc) { BlackwellIRInsn i = I0(BW_IR_LDG_E); i.dst_vreg = dst; i.src1_vreg = addr64; i.ureg = udesc; emit(e, i, K_VAR); } -/* Independent loads (LDG_E from global, or LDS32 from shared memory with ureg NOREG) issued - * back to back (campaign C2a, 2026-10-05). The first load - * waits on whatever is pending; the others wait on nothing, so all n are in flight together. - * Every load sets SB_GPR (a counting scoreboard), so the next instruction waits once for all - * of them instead of once per load. Fails the build if a load address is a destination of the - * group or a destination repeats (the later loads would read an operand still in flight). */ -static void ld_group(Em *e, BlackwellIROpcode op, int n, const int *dst, const int *addr, int ureg) { - for (int i = 0; i < n; i++) - for (int k = 0; k < n; k++) - if (addr[i] == dst[k] || (k != i && dst[i] == dst[k])) { e->err = -1; return; } - for (int i = 0; i < n; i++) { - if (op != BW_IR_LDG_E && op != BW_IR_LDS32) { e->err = -1; return; } - BlackwellIRInsn in = I0(op); in.dst_vreg = dst[i]; in.src1_vreg = addr[i]; in.ureg = ureg; - if (i == 0) { emit(e, in, K_VAR); continue; } - in.control = CW(4, SB_GPR, SB_NONE, 0) | CW_YIELD; /* nonzero, so the encoder keeps it */ - if (omega_bw_ir_append(e->p, &in) < 0) e->err = -1; - } -} -static void stg(Em *e, int addr64, int val, int udesc) { BlackwellIRInsn i = I0(BW_IR_STG_E); i.src1_vreg = addr64; i.src2_vreg = val; i.ureg = udesc; emit(e, i, K_STORE); } -static void fadd(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FADD); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void fsub(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FSUB); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void fmul(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_FMUL); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -static void ffma(Em *e, int d, int a, int b, int c) { BlackwellIRInsn i = I0(BW_IR_FFMA); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; emit(e, i, K_FIXED); } -static void mufu(Em *e, BlackwellIROpcode op, int d, int a) { BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; emit(e, i, K_VAR); } -/* Cross-lane and warp-ending ops are refused inside an open reconvergence region (omega #308): - * a SHFL or BAR.SYNC reached by a split warp reads inactive lanes / counts a partial warp - * (undefined; the 2026-10-04 attention bug), and a lane that EXITs inside a region can no - * longer be joined. The build fails closed instead of emitting such code. */ -/* Cross-lane instructions (SHFL, BAR.SYNC) need the whole warp present. The emitter refuses - * them (fails the build) inside an open reconvergence region, where lanes may be on different - * paths, and after a predicated EXIT, where lanes may be gone for good: a SHFL then reads - * inactive lanes (undefined on the chip, the attention failure of 2026-10-04). A kernel that - * must drop lanes before a cross-lane step clamps them instead and exits them afterwards. */ -static int warp_split(Em *e) { if (e->rg.depth > 0 || (e->exited && !e->exit_sync_ok)) { e->err = -1; return 1; } return 0; } -static void shfl_down(Em *e, int d, int a, uint32_t off) { if (warp_split(e)) return; BlackwellIRInsn i = I0(BW_IR_SHFL_DOWN); i.dst_vreg = d; i.src1_vreg = a; i.imm = off; emit(e, i, K_VAR); } -static void sts32(Em *e, int addr, int val) { BlackwellIRInsn i = I0(BW_IR_STS32); i.src1_vreg = addr; i.src2_vreg = val; emit(e, i, K_STORE); } -static void lds32(Em *e, int d, int addr) { BlackwellIRInsn i = I0(BW_IR_LDS32); i.dst_vreg = d; i.src1_vreg = addr; emit(e, i, K_VAR); } -static void bar_sync(Em *e) { if (warp_split(e)) return; emit(e, I0(BW_IR_BAR_SYNC), K_SYNC); } -static void isetp_ge_u32(Em *e, int a, int b) { BlackwellIRInsn i = I0(BW_IR_ISETP_GE_U32); i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_PRED); } -/* An EXIT inside a region would leave the barrier waiting for a lane that never comes: refused. */ -static void exit_if_p0(Em *e) { if (e->rg.depth > 0) { e->err = -1; return; } e->exited = 1; BlackwellIRInsn i = I0(BW_IR_EXIT); i.predicate_p0 = true; emit(e, i, K_EXIT); } -static void bra_back_if_not_p0(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.predicate_not = true; i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } -static void tail(Em *e) { - emit(e, I0(BW_IR_EXIT), K_EXIT); - BlackwellIRInsn self = I0(BW_IR_BRA); /* the self-branch every kernel here ends with */ - self.control = 0x000fc000u; - if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; -} -/* Loops may nest (prime race cut): begin pushes the start, end pops it, so the inner - * loop is closed (and its liveness fixed) first. For the single-level loops above this - * is exactly the old behaviour. */ -static void loop_begin(Em *e) { if (e->depth >= EW_MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } -/* Closing a loop: every value defined before the loop and read inside it stays - * live until the back-branch, otherwise the linear-scan allocator (which knows - * nothing about back-edges) would hand its register to a body temporary whose - * first definition comes after the value's last textual use (e.g. the scale y - * in rmsnorm pass 2), and the next iteration would read garbage. */ -static void loop_end(Em *e) { - if (e->n_loops >= EW_MAX_LOOPS || e->depth <= 0) { e->err = -1; return; } - int start = e->open_start[--e->depth], end = here(e) - 1; - e->loop_start[e->n_loops] = start; - e->loop_end[e->n_loops] = end; - e->n_loops++; - OmegaRegAlloc *ra = &e->p->regalloc; - for (int v = 0; v < ra->num_vregs; v++) { - OmegaLiveInterval *iv = &ra->intervals[v]; - if (iv->first_def >= 0 && iv->first_def < start && iv->last_use >= start && iv->last_use < end) iv->last_use = end; - } -} - -/* Kernel argument words (constant bank 0, same slots as the matmul path): - * 0x380 a, 0x388 b, 0x390 c (64-bit each), then four 32-bit parameters. */ -#define ARG_A 0x380u -#define ARG_B 0x388u -#define ARG_C 0x390u -#define ARG_P0 0x398u -#define ARG_P1 0x39cu -#define ARG_P2 0x3a0u -#define ARG_P3 0x3a4u -#define ARG_P4 0x3a8u -#define DESC_OFF 0x358u - -typedef struct { int udesc, pa, pb, pc, tid, cta; } Pro; -static Pro prologue(Em *e) { - Pro r; - r.udesc = UV64(e); r.pa = V64(e); r.pb = V64(e); r.pc = V64(e); r.tid = V(e); r.cta = V(e); - ldcu64(e, r.udesc, DESC_OFF); - ldc64(e, r.pa, ARG_A); ldc64(e, r.pb, ARG_B); ldc64(e, r.pc, ARG_C); - s2r(e, r.tid, BW_SR_TID_X); s2r(e, r.cta, BW_SR_CTAID_X); - return r; -} - -/* out[i] = 2^a[i] for i < n (n = P0). Threads 128, grid ceil(n/128). Mutant: 2^(a+1). */ -static void gen_ex2(Em *e, int mutant) { - Pro p = prologue(e); - int n = V(e), i = V(e), off = V64(e), x = V(e), y = V(e); - ldc32(e, n, ARG_P0); - imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); - isetp_ge_u32(e, i, n); - exit_if_p0(e); - addr4(e, off, i, p.pa); - ldg(e, x, off, p.udesc); - if (mutant) { int one = V(e); movf(e, one, 1.0f); fadd(e, x, x, one); } - mufu(e, BW_IR_MUFU_EX2, y, x); - addr4(e, off, i, p.pc); - stg(e, off, y, p.udesc); - tail(e); -} - -/* out[i] = a[i ^ 127] within each CTA of 128 (n % 128 == 0). STS own word, BAR.SYNC, - * LDS the partner word. Mutant: LDS own word (no exchange). */ -static void gen_xchg(Em *e, int mutant) { - Pro p = prologue(e); - int i = V(e), off = V64(e), x = V(e), saddr = V(e), paddr = V(e), mask = V(e), y = V(e); - imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); - addr4(e, off, i, p.pa); - ldg(e, x, off, p.udesc); - imadi(e, saddr, p.tid, 4, NOREG); - sts32(e, saddr, x); - bar_sync(e); - if (mutant) { - lds32(e, y, saddr); - } else { - movi(e, mask, OMEGA_GPU_EW_THREADS - 1); - lop3xor(e, paddr, p.tid, mask); - imadi(e, paddr, paddr, 4, NOREG); - lds32(e, y, paddr); - } - addr4(e, off, i, p.pc); - stg(e, off, y, p.udesc); - tail(e); -} - -/* One CTA of 128 threads per row. P0 = dim/128 (loop count), P1 = bits(1/dim), - * P2 = bits(eps), P3 = dim. Mutant: the warp tree drops the last SHFL step. */ -static void gen_rmsnorm(Em *e, int mutant) { - Pro p = prologue(e); - int nk = V(e), invd = V(e), eps = V(e), dim = V(e); - int rowbase = V(e), idx = V(e), col = V(e), k = V(e), acc = V(e), cT = V(e), c1 = V(e); - int off = V64(e), x = V(e), t = V(e); - ldc32(e, nk, ARG_P0); ldc32(e, invd, ARG_P1); ldc32(e, eps, ARG_P2); ldc32(e, dim, ARG_P3); - imadr(e, rowbase, p.cta, dim, NOREG); - iadd3(e, idx, rowbase, p.tid); - movrz(e, acc); movrz(e, k); - movi(e, cT, OMEGA_GPU_EW_THREADS); movi(e, c1, 1); - loop_begin(e); - int l1 = here(e); - addr4(e, off, idx, p.pa); - ldg(e, x, off, p.udesc); - ffma(e, acc, x, x, acc); - iadd3(e, idx, idx, cT); - iadd3(e, k, k, c1); - isetp_ge_u32(e, k, nk); - bra_back_if_not_p0(e, l1); - loop_end(e); - static const uint32_t steps[5] = { 16, 8, 4, 2, 1 }; - for (int s = 0; s < (mutant ? 4 : 5); s++) { shfl_down(e, t, acc, steps[s]); fadd(e, acc, acc, t); } - int saddr = V(e); - imadi(e, saddr, p.tid, 4, NOREG); - sts32(e, saddr, acc); - bar_sync(e); - int a0 = V(e), a1 = V(e), a2 = V(e), a3 = V(e), s0 = V(e), s1 = V(e), s2 = V(e), s3 = V(e), sum = V(e); - movrz(e, a0); movi(e, a1, 128); movi(e, a2, 256); movi(e, a3, 384); - lds32(e, s0, a0); lds32(e, s1, a1); lds32(e, s2, a2); lds32(e, s3, a3); - fadd(e, sum, s0, s1); fadd(e, sum, sum, s2); fadd(e, sum, sum, s3); - int v = V(e), y = V(e), u = V(e), cmh = V(e), c15 = V(e); - fmul(e, v, sum, invd); - fadd(e, v, v, eps); - mufu(e, BW_IR_MUFU_RSQ, y, v); - movf(e, cmh, -0.5f); movf(e, c15, 1.5f); - fmul(e, u, v, y); fmul(e, u, u, y); ffma(e, u, u, cmh, c15); fmul(e, y, y, u); - int offw = V64(e), offc = V64(e), w = V(e), o = V(e); - iadd3(e, idx, rowbase, p.tid); - imadi(e, col, p.tid, 1, NOREG); /* col = tid (the encoder maps a missing src2 to R0, not RZ, so no IADD3 here) */ - movrz(e, k); - loop_begin(e); - int l2 = here(e); - addr4(e, off, idx, p.pa); - ldg(e, x, off, p.udesc); - addr4(e, offw, col, p.pb); - ldg(e, w, offw, p.udesc); - fmul(e, o, x, y); - fmul(e, o, o, w); - addr4(e, offc, idx, p.pc); - stg(e, offc, o, p.udesc); - iadd3(e, idx, idx, cT); - iadd3(e, col, col, cT); - iadd3(e, k, k, c1); - isetp_ge_u32(e, k, nk); - bra_back_if_not_p0(e, l2); - loop_end(e); - tail(e); -} - -/* One CTA of head_dim/2 threads per head. P0 = head_dim, P1 = head_dim/2. - * a = vector, b = table (cos in the first half of each head, sin in the second). - * Mutant: out0 = q0*cos + q1*sin. */ -static void gen_rope(Em *e, int mutant) { - Pro p = prologue(e); - int hd = V(e), half = V(e), i0 = V(e), i1 = V(e), off0 = V64(e), off1 = V64(e); - int q0 = V(e), q1 = V(e), c = V(e), s = V(e), t0 = V(e), t1 = V(e), o0 = V(e), o1 = V(e); - ldc32(e, hd, ARG_P0); ldc32(e, half, ARG_P1); - imadr(e, i0, p.cta, hd, p.tid); - iadd3(e, i1, i0, half); - addr4(e, off0, i0, p.pa); ldg(e, q0, off0, p.udesc); - addr4(e, off1, i1, p.pa); ldg(e, q1, off1, p.udesc); - addr4(e, off0, i0, p.pb); ldg(e, c, off0, p.udesc); - addr4(e, off1, i1, p.pb); ldg(e, s, off1, p.udesc); - fmul(e, t0, q0, c); fmul(e, t1, q1, s); - if (mutant) fadd(e, o0, t0, t1); else fsub(e, o0, t0, t1); - fmul(e, t0, q0, s); fmul(e, t1, q1, c); - fadd(e, o1, t0, t1); - addr4(e, off0, i0, p.pc); stg(e, off0, o0, p.udesc); - addr4(e, off1, i1, p.pc); stg(e, off1, o1, p.udesc); - tail(e); -} - -/* out[i] = g/(1+2^(g*-log2e)) * up for i < n (P0). Mutant: 2^(g*+log2e). */ -static void gen_swiglu(Em *e, int mutant) { - Pro p = prologue(e); - int n = V(e), i = V(e), off = V64(e), g = V(e), u = V(e), k = V(e), t = V(e), ex = V(e), d = V(e), r = V(e), one = V(e), o = V(e); - ldc32(e, n, ARG_P0); - imadi(e, i, p.cta, OMEGA_GPU_EW_THREADS, p.tid); - isetp_ge_u32(e, i, n); - exit_if_p0(e); - addr4(e, off, i, p.pa); ldg(e, g, off, p.udesc); - addr4(e, off, i, p.pb); ldg(e, u, off, p.udesc); - movf(e, k, mutant ? 1.4426950408889634f : -1.4426950408889634f); - movf(e, one, 1.0f); - fmul(e, t, g, k); - mufu(e, BW_IR_MUFU_EX2, ex, t); - fadd(e, d, ex, one); - mufu(e, BW_IR_MUFU_RCP, r, d); - fmul(e, o, g, r); - fmul(e, o, o, u); - addr4(e, off, i, p.pc); - stg(e, off, o, p.udesc); - tail(e); -} - -/* ------------------------------------------- prime race sieve (2026-10-05) */ -static void lop3lut(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut & 0xffu; emit(e, i, K_FIXED); } -static void shl_r(Em *e, int d, int a, int n) { BlackwellIRInsn i = I0(BW_IR_SHF_L_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = n; emit(e, i, K_FIXED); } -static void shr_i(Em *e, int d, int a, uint32_t n) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.imm = n; emit(e, i, K_FIXED); } -static void imadhi(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IMAD_HI_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } -/* dst64 = a * imm + c64 (IMAD.WIDE.U32 immediate form) */ -static void widei(Em *e, int dst64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } -/* @P0 BRA forward; returns the instruction index for bra_patch_here */ -static int bra_fwd_if_p0(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static void bra_patch_here(Em *e, int at) { if (e->err == 0 && at >= 0 && at < here(e)) e->p->insns[at].imm = (uint32_t)(here(e) - at); else e->err = -1; } -static void bra_always(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } - -/* ---- structured reconvergence regions (omega #308; bookkeeping in omega_bw_reconv.h) ---- - * region_begin: BSSY Bd (d = nesting depth), fails closed when no barrier register is left. - * region_exit: a forward branch out of the innermost region, patched to its BSYNC at join - * (RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0). - * region_join: BSYNC Bd; patches the BSSY to the instruction after it and every exit to it. - * Usage: divergent loop = region_begin; L: isetp; region_exit(RX_IF_P0); body; bra_always(L); region_join. - * if/else diamond = region_begin; isetp; t = bra_fwd_if_p0; then; region_exit(RX_ALWAYS); - * bra_patch_here(t); else; region_join. */ -enum { RX_ALWAYS, RX_IF_P0, RX_IF_NOT_P0 }; -static int region_begin(Em *e) { - int bar = bw_regions_next_bar(&e->rg); - if (bar < 0) { e->err = -1; return -1; } - int at = here(e); - BlackwellIRInsn i = I0(BW_IR_BSSY); i.bar_reg = (uint8_t)bar; i.imm = 2; emit(e, i, K_BSSY); - if (bw_regions_begin(&e->rg, at) < 0) e->err = -1; - return bar; -} -static void region_exit(Em *e, int cond) { - int at = here(e); - BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1; - if (cond != RX_ALWAYS) { i.predicate_p0 = true; i.predicate_not = (cond == RX_IF_NOT_P0); } - emit(e, i, K_BRA); - if (bw_regions_exit(&e->rg, at) < 0) e->err = -1; -} -static void region_join(Em *e) { - if (e->rg.depth <= 0) { e->err = -1; return; } - int d = e->rg.depth - 1, bsync = here(e); - BlackwellIRInsn i = I0(e->rg_mutant == 1 ? BW_IR_NOP : BW_IR_BSYNC); i.bar_reg = (uint8_t)d; emit(e, i, K_BSYNC); - if (e->rg_mutant == 1) { - /* negative control (host sim only): the join is a NOP; patch as the real join would */ - BwRegions *r = &e->rg; r->depth--; - e->p->insns[r->bssy_at[d]].imm = (uint32_t)(bsync + 1 - r->bssy_at[d]); - for (int k = 0; k < r->n_exits[d]; k++) e->p->insns[r->exits[d][k]].imm = (uint32_t)(bsync - r->exits[d][k]); - return; - } - if (bw_regions_join(&e->rg, e->p, bsync) != d) e->err = -1; - if (e->rg_mutant == 2) e->p->insns[e->rg.bssy_at[d]].imm += 1; /* negative control: BSSY names the wrong join */ -} - -/* Word-parallel odd-only sieve (docs: handoff 2026-10-05 DESIGN "GPU kernel (native)"). - * Thread t owns 32-bit output words w = t, t + S, t + 2S, ... (S = P1 = threads launched; - * the I42 envelope caps a launch at OMEGA_GPU_EW_MAX_CTAS CTAs, so a grid-stride loop - * replaces one thread per word). Every word has exactly one writer; no atomics. - * Bit j of word w is the odd number 2(32w + j) + 1. - * Arguments: a (0x380) = prime table, entries {p, magic = ceil(2^32 / p), k0 = (p*p - 1)/2} - * (12 bytes, ascending p, odd primes <= isqrt(limit)) followed by ONE sentinel entry with - * k0 = 0xffffffff that ends every scan; c (0x390) = output words; - * P0 = nwords, P1 = S, P2 = last word index, P3 = ~tailmask (bits past the last odd). - * Range: limit < 2^32 (so base, k0 < 2^31 and the sign-bit tricks below hold). - * Per word: base = 32w; for each prime while k0 < base + 32: - * d = base - k0; neg = d >> 31 (k0 > base); dpos = neg ? 0 : d; jadd = neg ? k0 - base : 0 - * q = hi32(dpos * magic) (= floor(dpos/p) or one more: magic is rounded up) - * r = dpos - q*p (q one too big -> r = (dpos mod p) - p, wrapped) - * j = p - r; j -= p * ((r - 1) >> 31) (r == 0 -> 0; wrapped r -> p - (dpos mod p)) - * One fix covers both cases: with q one too big, dpos mod p >= p - dpos*e/2^32 > p/2 > 0 - * (e = magic*p - 2^32 < p, dpos < 2^31), so the true remainder is never 0 there and - * p - r - p = p - (dpos mod p) is the right offset. A separate "r += p if wrapped" step was - * removed after a negative control showed it changes no output (host sim, limit 1e7, where - * the overshoot occurs 268 times; bench/prime_race/tests magic_model). - * j += jadd; while j < 32 { acc |= 1 << j; j += p } - * then acc |= (w == 0) (the number 1), word = ~(acc | (w == last ? ~tailmask : 0)). - * Branch-free except the loop branches. Mutant: drops the j fix (j = p - r unreduced), so words where - * base - k0 is a multiple of p (or q overshot) mark the wrong bits. - * - * staged = 1 (OMEGA_GPU_EW_PRIME_SIEVE_SHARED, campaign C3): P4 = table words, sentinel included - * (3 per entry). The CTA first copies the table into shared memory at offset 0 (thread t copies - * words t, t + 128, ...), BAR_SYNC, then the prime loop reads shared memory (LDS) instead of - * uncached global memory. Every thread reaches the barrier: the w >= nwords exit comes after - * it. The launch must declare at least 4 * P4 bytes of shared memory. - * - * divergent (omega #308, regression R1): 0 = the warp-uniform mark loop above (campaign C5). - * 1 = the original lane-dependent mark loop (omega 888a011: `while j < 32 { acc |= 1 << j; j += p }`) - * wrapped in a reconvergence region. 2 = as 1, and the prime loop (whose break `k0 >= base + 32` - * is also lane-dependent: every lane sieves a different word) wrapped in an outer region, so the - * mark loop's region nests inside it (B0 outer, B1 inner). */ -static void gen_prime_sieve(Em *e, int mutant, int staged, int divergent) { - Pro pr = prologue(e); - int nwords = V(e), stride = V(e), lastw = V(e), tailinv = V(e); - int one = V(e), c32 = V(e), cm1 = V(e), w = V(e); - ldc32(e, nwords, ARG_P0); ldc32(e, stride, ARG_P1); ldc32(e, lastw, ARG_P2); ldc32(e, tailinv, ARG_P3); - movi(e, one, 1); movi(e, c32, 32); movi(e, cm1, 0xffffffffu); - int c4 = -1, c8 = -1, c12 = -1; - if (staged) { - int twords = V(e), i = V(e), ga = V64(e), val = V(e), sa = V(e); - c4 = V(e); c8 = V(e); c12 = V(e); - ldc32(e, twords, ARG_P4); - movi(e, c4, 4); movi(e, c8, 8); movi(e, c12, 12); - imadi(e, i, pr.tid, 1, NOREG); - /* The staging loop's trip count differs per thread (thread t copies words t, t+128, ...), - * so its exit splits the warp. The divergent variants rejoin the warp before BAR.SYNC - * (a barrier is not a reconvergence point: the fragments would stay split for the rest - * of the kernel). The production kernel keeps the 2026-10-05 C3 form unchanged. */ - if (divergent) region_begin(e); - loop_begin(e); /* staging loop */ - int ls = here(e); - isetp_ge_u32(e, i, twords); - int sdone = -1; - if (divergent) region_exit(e, RX_IF_P0); else sdone = bra_fwd_if_p0(e); - addr4(e, ga, i, pr.pa); - ldg(e, val, ga, pr.udesc); - imadi(e, sa, i, 4, NOREG); - sts32(e, sa, val); - imadi(e, i, one, OMEGA_GPU_EW_THREADS, i); - bra_always(e, ls); - loop_end(e); - if (divergent) region_join(e); else bra_patch_here(e, sdone); - bar_sync(e); - } - imadi(e, w, pr.cta, OMEGA_GPU_EW_THREADS, pr.tid); - isetp_ge_u32(e, w, nwords); - exit_if_p0(e); - - /* ptr, a64, a64m: global addresses, or (staged) 32-bit shared offsets */ - int base = V(e), basep32 = V(e), acc = V(e); - int ptr = staged ? V(e) : V64(e), a64 = staged ? V(e) : V64(e), a64m = staged ? V(e) : V64(e); - int p = V(e), magic = V(e), k0 = V(e), negp = V(e), d = V(e), neg = V(e), nd = V(e), dpos = V(e), jadd = V(e); - int q = V(e), r = V(e), j = V(e), t = V(e), z = V(e), bit = V(e); - int e1 = V(e), m = V(e), word = V(e), oaddr = V64(e); - int tt = V(e), jj = V(e), sh = V(e), c31 = V(e), cm32 = V(e); - movi(e, c31, 31); movi(e, cm32, 0xffffffe0u); - - loop_begin(e); /* word loop */ - int lw = here(e); - imadi(e, base, w, 32, NOREG); - iadd3(e, basep32, base, c32); - movrz(e, acc); - if (staged) movrz(e, ptr); else widei(e, ptr, one, 0, pr.pa); - - if (divergent >= 2) region_begin(e); /* outer region: the prime loop's break is lane-dependent */ - loop_begin(e); /* prime loop */ - int lp = here(e); - /* one memory round trip per prime: all three entry words load together (C2a). The - * sentinel entry is a whole entry, so loading p and magic before the k0 test is in bounds. */ - if (staged) { iadd3(e, a64, ptr, c8); iadd3(e, a64m, ptr, c4); } - else { widei(e, a64, one, 8, ptr); widei(e, a64m, one, 4, ptr); } - { - const int dsts[3] = { k0, p, magic }, adrs[3] = { a64, ptr, a64m }; - if (staged) ld_group(e, BW_IR_LDS32, 3, dsts, adrs, NOREG); - else ld_group(e, BW_IR_LDG_E, 3, dsts, adrs, pr.udesc); - } - isetp_ge_u32(e, k0, basep32); - int brk = -1; - if (divergent >= 2) region_exit(e, RX_IF_P0); else brk = bra_fwd_if_p0(e); - imadi(e, negp, p, 0xffffffffu, NOREG); /* -p */ - imadi(e, d, k0, 0xffffffffu, base); /* base - k0 */ - shr_i(e, neg, d, 31); - imadi(e, nd, d, 0xffffffffu, NOREG); /* -d */ - imadr(e, dpos, neg, nd, d); /* d - neg*d */ - imadr(e, jadd, neg, nd, NOREG); /* neg * (k0 - base) */ - imadhi(e, q, dpos, magic); - imadr(e, r, q, negp, dpos); /* dpos - q*p */ - imadi(e, j, r, 0xffffffffu, p); /* p - r */ - if (!mutant) { - iadd3(e, t, r, cm1); - shr_i(e, z, t, 31); /* r == 0, or r wrapped (q one too big) */ - imadr(e, j, z, negp, j); /* j - p */ - } - iadd3(e, j, j, jadd); - - /* mark loop (campaign C5): the trip count depends only on p, so every active lane runs the - * same ceil(32/p) steps and the warp never splits here (all active lanes are on the same - * prime). Bits past this word are masked out instead of branched around. The old loop ran - * "while j < 32", a lane-dependent branch with no reconvergence point. */ - if (divergent) { - /* R1: the 888a011 mark loop, lane-dependent trip count, inside a region. Each lane - * leaves at its own iteration (the exit jumps to the BSYNC) and the warp reunites there. */ - region_begin(e); - loop_begin(e); - int li = here(e); - isetp_ge_u32(e, j, c32); - region_exit(e, RX_IF_P0); - shl_r(e, bit, one, j); - lop3lut(e, acc, acc, bit, NOREG, 0xfc); /* acc | bit */ - iadd3(e, j, j, p); - bra_always(e, li); - loop_end(e); - region_join(e); - } else { - movrz(e, tt); - loop_begin(e); - int li = here(e); - isetp_ge_u32(e, tt, c32); - int done = bra_fwd_if_p0(e); - iadd3(e, jj, j, tt); - lop3lut(e, sh, jj, c31, NOREG, 0xc0); /* jj & 31 */ - shl_r(e, bit, one, sh); - iadd3(e, t, jj, cm32); - shr_i(e, z, t, 31); /* jj < 32 (j <= p + 31, far below 2^31) */ - imadi(e, m, z, 0xffffffffu, NOREG); /* all ones when jj < 32, else 0 */ - lop3lut(e, acc, acc, bit, m, 0xf8); /* acc | (bit & m) */ - iadd3(e, tt, tt, p); - bra_always(e, li); - loop_end(e); - bra_patch_here(e, done); - } - - if (staged) iadd3(e, ptr, ptr, c12); else widei(e, ptr, one, 12, ptr); - bra_always(e, lp); - loop_end(e); - if (divergent >= 2) region_join(e); else bra_patch_here(e, brk); - - iadd3(e, t, w, cm1); - shr_i(e, z, t, 31); /* w == 0: the number 1 is not prime */ - lop3lut(e, acc, acc, z, NOREG, 0xfc); - lop3xor(e, e1, w, lastw); - iadd3(e, t, e1, cm1); - shr_i(e, z, t, 31); /* w == last word */ - imadr(e, m, z, tailinv, NOREG); - lop3lut(e, word, acc, m, NOREG, 0x03); /* ~(acc | m) */ - addr4(e, oaddr, w, pr.pc); - stg(e, oaddr, word, pr.udesc); - /* IMAD, not IADD3: the IADD3 encoder ignores the scheduler control word (fixed - * 0x010fca00), so right after a store it would not wait on the read barrier */ - imadr(e, w, stride, one, w); - isetp_ge_u32(e, w, nwords); - bra_back_if_not_p0(e, lw); - loop_end(e); - tail(e); -} - -/* ---- reconvergence probes (omega #308, regressions R3..R6 and the resource bound) ---- - * All: a, b = u32 inputs, out = u32, P0 = n; 128 threads, grid ceil(n/128); launched by - * omega_gpu_reconv_probe_u32. A lane past n clamps its index to n-1 so that it loads valid - * data and takes part in the warp-wide SHFL; it exits only after the SHFL, before its store. - * Each probe computes a per-lane r on divergent paths, joins, then - * out[i] = r + 4099 * s, s = r of lane (lane+1) in the same warp (SHFL.DOWN 1; lane 31: own r) - * so a lane that joined late, never, or with the wrong value shows in the neighbour's word too. - * The host oracle is rc_oracle in tests/gpu_reconv_test.c. */ -typedef struct { Pro pr; int n, i, idx, x, y, r, s, one, cm1; } Rp; -static Rp rp_begin(Em *e) { - Rp k; memset(&k, 0, sizeof k); - k.pr = prologue(e); - k.n = V(e); k.i = V(e); k.idx = V(e); k.x = V(e); k.y = V(e); k.r = V(e); k.s = V(e); k.one = V(e); k.cm1 = V(e); - int nm1 = V(e), d = V(e), neg = V(e), off = V64(e); - ldc32(e, k.n, ARG_P0); - movi(e, k.one, 1); movi(e, k.cm1, 0xffffffffu); - imadi(e, k.i, k.pr.cta, OMEGA_GPU_EW_THREADS, k.pr.tid); - iadd3(e, nm1, k.n, k.cm1); /* n - 1 */ - imadi(e, d, k.i, 0xffffffffu, nm1); /* (n - 1) - i, top bit set when i > n - 1 */ - shr_i(e, neg, d, 31); - imadr(e, k.idx, neg, d, k.i); /* i, or n - 1 when past the end */ - addr4(e, off, k.idx, k.pr.pa); ldg(e, k.x, off, k.pr.udesc); - addr4(e, off, k.idx, k.pr.pb); ldg(e, k.y, off, k.pr.udesc); - return k; -} -static void rp_end(Em *e, const Rp *k) { - int out = V(e), off = V64(e); - shfl_down(e, k->s, k->r, 1); - imadi(e, out, k->s, 4099, k->r); - isetp_ge_u32(e, k->i, k->n); - exit_if_p0(e); - addr4(e, off, k->i, k->pr.pc); - stg(e, off, out, k->pr.udesc); - tail(e); -} -/* R3: if/else with sides of different length. x >= y: r = f(x, y) (5 steps); else r = x + 1. - * Math mutant: the long side is one too big. */ -static void gen_rc_diamond(Em *e, int mutant) { - Rp k = rp_begin(e); - int t = V(e), u = V(e); - region_begin(e); - isetp_ge_u32(e, k.x, k.y); - int els = bra_fwd_if_p0(e); - iadd3(e, k.r, k.x, k.one); /* short side */ - region_exit(e, RX_ALWAYS); - bra_patch_here(e, els); - imadi(e, t, k.x, 3, k.y); /* long side: t = 3x + y */ - lop3xor(e, u, t, k.x); /* u = t ^ x */ - imadi(e, k.r, u, 5, k.one); /* r = 5u + 1 */ - shr_i(e, t, k.r, 3); - iadd3(e, k.r, k.r, t); /* r += r >> 3 */ - if (mutant) iadd3(e, k.r, k.r, k.one); - region_join(e); - rp_end(e, &k); -} -/* The lane-dependent loop shared by R4 and R5: v = x & 255, step = (y & 15) + 1, - * while v < 256 { v += step; cnt += 1 }. Math mutant: the bound is 255. Emits the region. */ -static void rc_count_loop(Em *e, const Rp *k, int mutant, int v, int cnt) { - int st = V(e), bound = V(e), c255 = V(e), c15 = V(e); - movi(e, c255, 255); movi(e, c15, 15); movi(e, bound, mutant ? 255 : 256); - lop3lut(e, v, k->x, c255, NOREG, 0xc0); - lop3lut(e, st, k->y, c15, NOREG, 0xc0); - iadd3(e, st, st, k->one); - movrz(e, cnt); - region_begin(e); - loop_begin(e); - int L = here(e); - isetp_ge_u32(e, v, bound); - region_exit(e, RX_IF_P0); - iadd3(e, v, v, st); - iadd3(e, cnt, cnt, k->one); - bra_always(e, L); - loop_end(e); - region_join(e); -} -/* R4: lane-dependent loop exit (break). r = 256 * cnt + v. */ -static void gen_rc_loopbreak(Em *e, int mutant) { - Rp k = rp_begin(e); - int v = V(e), cnt = V(e); - rc_count_loop(e, &k, mutant, v, cnt); - imadi(e, k.r, cnt, 256, v); - rp_end(e, &k); -} -/* R5: nested divergence. Odd x: r = 7 (skips the inner region). Even x: the R4 loop inside the - * outer region, r = 256 * cnt + v + 100. */ -static void gen_rc_nested(Em *e, int mutant) { - Rp k = rp_begin(e); - int v = V(e), cnt = V(e), low = V(e), c100 = V(e); - movi(e, k.r, 7); movi(e, c100, 100); - lop3lut(e, low, k.x, k.one, NOREG, 0xc0); /* x & 1 */ - region_begin(e); - isetp_ge_u32(e, low, k.one); - region_exit(e, RX_IF_P0); - rc_count_loop(e, &k, mutant, v, cnt); - imadi(e, k.r, cnt, 256, v); - iadd3(e, k.r, k.r, c100); - region_join(e); - rp_end(e, &k); -} -/* R6: lanes past the end, a divergent region, then a CTA-wide exchange and the warp SHFL. - * xv = x | 1 computed on divergent paths (even lanes take the branch), every thread stores xv - * to its shared slot, BAR.SYNC, reads its partner's (tid ^ 1), r = 3x + partner_xv. - * Production form: lanes past n are clamped and exit after the SHFL (correct). early_exit - * (mutant 1): lanes past n EXIT first, as a naive kernel would; the emitter refuses that - * (BAR/SHFL after a predicated EXIT). Only the host-test build path (codegen_ir) may bypass the - * refusal, so the simulator can show what the kernel would do (SHFL_EXITED); a launch never can. */ -static void gen_rc_exit_bar(Em *e, int early_exit) { - Rp k = rp_begin(e); - int saddr = V(e), paddr = V(e), yv = V(e), xv = V(e), low = V(e); - if (early_exit) { - e->exit_sync_ok = early_exit == 1 && e->test_path; - isetp_ge_u32(e, k.i, k.n); - exit_if_p0(e); - } - imadi(e, xv, k.x, 1, NOREG); - lop3lut(e, low, k.x, k.one, NOREG, 0xc0); /* x & 1 */ - region_begin(e); - isetp_ge_u32(e, low, k.one); - region_exit(e, RX_IF_P0); /* odd lanes leave */ - iadd3(e, xv, xv, k.one); /* even lanes: xv = x + 1 */ - region_join(e); - imadi(e, saddr, k.pr.tid, 4, NOREG); - sts32(e, saddr, xv); - bar_sync(e); - lop3xor(e, paddr, k.pr.tid, k.one); - imadi(e, paddr, paddr, 4, NOREG); - lds32(e, yv, paddr); - imadi(e, k.r, k.x, 3, yv); - rp_end(e, &k); -} -/* Barrier-register bound: `levels` nested regions, each leaving lanes with x >= y out and adding 1 - * for the others: r = x + levels * (x < y). 16 levels must build (B0..B15); 17 must be refused. */ -static void gen_rc_depth(Em *e, int levels) { - Rp k = rp_begin(e); - imadi(e, k.r, k.x, 1, NOREG); - for (int d = 0; d < levels; d++) { - region_begin(e); - isetp_ge_u32(e, k.x, k.y); - region_exit(e, RX_IF_P0); - iadd3(e, k.r, k.r, k.one); - } - for (int d = 0; d < levels; d++) region_join(e); - rp_end(e, &k); -} -/* Codegen refusals (each must come back CODEGEN_FAIL; a kernel with a split warp at a - * cross-lane step must never reach the chip). */ -static void gen_rc_refuse(Em *e, OmegaGpuEwOp which) { - Rp k = rp_begin(e); - switch (which) { - case OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION: region_begin(e); isetp_ge_u32(e, k.i, k.n); exit_if_p0(e); region_join(e); break; - case OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION: region_begin(e); bar_sync(e); region_join(e); break; - case OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION: region_begin(e); shfl_down(e, k.s, k.x, 1); region_join(e); break; - case OMEGA_GPU_EW_RC_REFUSE_UNCLOSED: region_begin(e); isetp_ge_u32(e, k.x, k.y); region_exit(e, RX_IF_P0); break; /* no join */ - case OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY: region_join(e); break; /* BSYNC without BSSY */ - default: e->err = -1; break; - } - imadi(e, k.r, k.x, 1, NOREG); - rp_end(e, &k); -} - -/* A value first defined inside a loop body may not be read after the loop - * before it is written again: the allocator could have let a later body - * temporary share its register, and the last iteration's value would be lost. */ -static int check_loop_invariant(const Em *e) { - const OmegaRegAlloc *ra = &e->p->regalloc; - for (int L = 0; L < e->n_loops; L++) - for (int v = 0; v < ra->num_vregs; v++) { - int fd = ra->intervals[v].first_def; - if (fd < e->loop_start[L] || fd > e->loop_end[L]) continue; - for (size_t i = (size_t)e->loop_end[L] + 1; i < e->p->count; i++) { - const BlackwellIRInsn *in = &e->p->insns[i]; - if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1; - if (in->dst_vreg == v && !in->is_uniform) break; - } - } - return 0; -} - -#define EW_GPR_BUDGET 64u /* the QMD declares 64 registers, as the matmul launcher does */ - -/* Mesa NAK sm120_instr_latencies.rs + sm100/reg_raw.csv: ALU/dual-ALU pairs - * and FMA/FMA pairs need 4 + 1 cycles; mixed pairs need 5 + 1. CSV rows are - * READERS, columns WRITERS (see lat_rs_gen.py), not the reverse. IMAD.WIDE - * has operand-specific latencies and is deliberately excluded here. - * - * Retain at least 5 cycles after every fixed producer. Thus the next reader - * uses the pair-specific bound and later readers are >= 9 cycles away (the - * next instruction in a tightened pair is itself fixed). No instruction, - * branch target, wait, barrier assignment or register allocation is changed. - * IADD3's encoder still supplies its historical control word; do not pretend - * to schedule that producer here. Its existing 5-cycle delay is unchanged. - * - * Predicate-to-guard uses NAK paw_latency -> raw(write, None): reader - * RedirectedFp64, writer Dualalu = 13, plus SM120's 1 = 14, in emit above. - * NVIDIA's public ISA docs are silent about SASS control-word semantics. - */ -static int fixed_pair_class(BlackwellIROpcode op) { - switch (op) { - case BW_IR_MOV_RZ: case BW_IR_MOV_IMM: case BW_IR_IADD3: - case BW_IR_LOP3_XOR: case BW_IR_LOP3_LUT: - case BW_IR_SHF_R: case BW_IR_SHF_L_U32: return 1; - case BW_IR_IMAD: case BW_IR_IMAD_HI_U32: - case BW_IR_FADD: case BW_IR_FSUB: case BW_IR_FMUL: case BW_IR_FFMA: return 2; - default: return 0; - } -} - -static void schedule_fixed_pairs(BlackwellIRProgram *p) { - for (size_t i = 0; i + 1 < p->count; i++) { - BlackwellIRInsn *a = &p->insns[i]; - const BlackwellIRInsn *b = &p->insns[i + 1]; - int cls = fixed_pair_class(a->op); - if (!cls || cls != fixed_pair_class(b->op) || a->op == BW_IR_IADD3 || - a->predicate_p0 || b->predicate_p0 || ((a->control >> 9) & 15u) != 6) - continue; - a->control = (a->control & ~(15u << 9)) | (5u << 9); - } -} - -static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel, BlackwellIRProgram *prog_out, int test_path) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog) return OMEGA_GPU_EW_CODEGEN_FAIL; - omega_bw_ir_init(prog); - Em e; memset(&e, 0, sizeof e); e.p = prog; e.test_path = test_path; - /* mutant 1 = the op's math mutant (as before); 2 = the join (BSYNC) dropped; 3 = the BSSY - * names the wrong join. 2 and 3 only change kernels that open a region. */ - e.rg_mutant = mutant == 2 ? 1 : mutant == 3 ? 2 : 0; - int math = mutant == 1; - switch (op) { - case OMEGA_GPU_EW_EX2: gen_ex2(&e, math); break; - case OMEGA_GPU_EW_XCHG: gen_xchg(&e, math); break; - case OMEGA_GPU_EW_RMSNORM: gen_rmsnorm(&e, math); break; - case OMEGA_GPU_EW_ROPE: gen_rope(&e, math); break; - case OMEGA_GPU_EW_SWIGLU: gen_swiglu(&e, math); break; - case OMEGA_GPU_EW_PRIME_SIEVE: gen_prime_sieve(&e, math, 0, 0); break; - case OMEGA_GPU_EW_PRIME_SIEVE_SHARED: gen_prime_sieve(&e, math, 1, 0); break; - case OMEGA_GPU_EW_PRIME_SIEVE_DIV1: gen_prime_sieve(&e, math, 0, 1); break; - case OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV1: gen_prime_sieve(&e, math, 1, 1); break; - case OMEGA_GPU_EW_PRIME_SIEVE_DIV2: gen_prime_sieve(&e, math, 0, 2); break; - case OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2: gen_prime_sieve(&e, math, 1, 2); break; - case OMEGA_GPU_EW_RC_DIAMOND: gen_rc_diamond(&e, math); break; - case OMEGA_GPU_EW_RC_LOOPBREAK: gen_rc_loopbreak(&e, math); break; - case OMEGA_GPU_EW_RC_NESTED: gen_rc_nested(&e, math); break; - case OMEGA_GPU_EW_RC_EXIT_BAR: gen_rc_exit_bar(&e, math); break; - case OMEGA_GPU_EW_RC_REFUSE_EXIT_SHFL: gen_rc_exit_bar(&e, 2); break; - case OMEGA_GPU_EW_RC_DEPTH16: gen_rc_depth(&e, BW_RECONV_MAX_BAR); break; - case OMEGA_GPU_EW_RC_REFUSE_DEPTH17: gen_rc_depth(&e, BW_RECONV_MAX_BAR + 1); break; - case OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION: case OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION: - case OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION: case OMEGA_GPU_EW_RC_REFUSE_UNCLOSED: - case OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY: gen_rc_refuse(&e, op); break; - default: e.err = -1; break; - } - if (e.rg.depth != 0) e.err = -1; /* a region left open has no join: refuse the build */ - schedule_fixed_pairs(prog); - int rc = OMEGA_GPU_EW_CODEGEN_FAIL; - int ra_rc = (e.err == 0) ? omega_bw_regalloc_solve(prog) : -1; - int loop_rc = (ra_rc == 0) ? check_loop_invariant(&e) : -1; -#ifdef OMEGA_EW_DEBUG - fprintf(stderr, "ew codegen op=%d mutant=%d emit_err=%d insns=%zu vregs=%d regalloc=%d loops=%d peak_gpr=%u\n", - (int)op, mutant, e.err, prog->count, prog->regalloc.num_vregs, ra_rc, loop_rc, prog->regalloc.peak_gpr_usage); -#endif - if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= EW_GPR_BUDGET) { - size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; - memset(kernel, 0, sizeof *kernel); - kernel->code = malloc(max_bytes); - size_t emitted = 0; - if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { - kernel->code_size = emitted; - kernel->insn_count = emitted / 16; - kernel->gpr_count = prog->regalloc.peak_gpr_usage; - kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; - sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); - if (prog_out) *prog_out = *prog; - rc = OMEGA_GPU_EW_OK; - } else { -#ifdef OMEGA_EW_DEBUG - fprintf(stderr, "ew codegen op=%d: encode failed (an instruction form the encoder refuses)\n", (int)op); -#endif - free(kernel->code); kernel->code = NULL; - } - } - free(prog); - return rc; -} - -/* --------------------------------------------------------- kernel cache */ - -/* One kernel per (op, mutant); the device copy is uploaded once and stays - * resident for the process (cut 4b: no per-call code page). */ -typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; OmegaGpuMem code; } Slot; -static int g_mutant_op; /* 0 = none */ -static int g_mutant_level = 1; /* the mutant number built for g_mutant_op (1 math, 2 join dropped, 3 join corrupted) */ -static Slot g_cache[8]; -static OmegaGpuScratch g_a, g_b, g_c; /* staging, grown to the high-water mark, reused per call */ -static bool g_hooked; -#define LOCK() omega_gpu_session_lock() -#define UNLOCK() omega_gpu_session_unlock() - -static void cache_clear_locked(void) { - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used) { free(g_cache[i].kernel.code); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } -} - -void omega_gpu_elementwise_cache_clear(void) { - LOCK(); - cache_clear_locked(); - UNLOCK(); -} - -/* Called by the session (lock held, device still open) right before it closes. */ -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g_a); omega_gpu_session_scratch_free(&g_b); omega_gpu_session_scratch_free(&g_c); -} - -void omega_gpu_elementwise_test_set_mutant(int op) { - LOCK(); - g_mutant_op = op; g_mutant_level = 1; - cache_clear_locked(); - UNLOCK(); -} -void omega_gpu_elementwise_test_set_mutant_level(int op, int level) { - LOCK(); - g_mutant_op = op; g_mutant_level = level < 1 ? 1 : level > 3 ? 3 : level; - cache_clear_locked(); - UNLOCK(); -} - -/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when a - * device is open (upload = false lets the host-only codegen path run without a chip). */ -static int kernel_for(OmegaGpuEwOp op, bool upload, Slot **out, bool *hit) { - int mutant = (g_mutant_op == (int)op) ? g_mutant_level : 0; - Slot *s = NULL; - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { s = &g_cache[i]; *hit = true; break; } - if (!s) { - OmegaBlackwellKernel k; - int rc = build_kernel(op, mutant, &k, NULL, 0); - if (rc != OMEGA_GPU_EW_OK) return rc; - size_t slot = 0; - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } - s = &g_cache[slot]; - if (s->used) { free(s->kernel.code); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ - memset(s, 0, sizeof *s); - s->used = 1; s->op = (int)op; s->mutant = mutant; s->kernel = k; - *hit = false; - } - if (upload && !s->code.cpu) { - if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_EW_CHIP_FAIL; - memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); - __asm__ volatile("dsb sy" ::: "memory"); - } - *out = s; - return OMEGA_GPU_EW_OK; -} - -int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel) { - (void)dims; (void)eps; /* kernels read their shape from the argument words */ - if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; - LOCK(); - int mutant = (g_mutant_op == (int)op) ? g_mutant_level : 0; - UNLOCK(); - return build_kernel(op, mutant, kernel, NULL, 0); -} - -int omega_gpu_elementwise_codegen_ir(OmegaGpuEwOp op, int mutant, void *prog, OmegaBlackwellKernel *kernel) { - if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; - if (mutant < 0 || mutant > 3) return OMEGA_GPU_EW_BAD_ARGS; - return build_kernel(op, mutant, kernel, (BlackwellIRProgram *)prog, 1); -} - -const char *omega_gpu_elementwise_last_error(void) { return omega_gpu_session_last_error(); } - -/* ------------------------------------------------------------ launcher */ - -#define EW_POISON 0xffbadbadu /* a NaN pattern no kernel here produces on purpose */ -#define EW_WAIT_MS 600000ull /* like main's load/store launchers; a 5 s wait failed under contention (omega#198) */ - -static uint64_t now_ns(void) { - struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; -} - -/* Caller holds the lock. Opens the shared device on first use. */ -static int dev_open_locked(void) { - if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } - return omega_gpu_session_open() ? OMEGA_GPU_EW_OK : OMEGA_GPU_EW_CHIP_FAIL; -} - -/* One launch: a and b staged in, c out (c_bytes/4 words, poison-filled first), through - * the shared session (omega_gpu_session_launch: shader-cache invalidate, constant bank, - * QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), then readback and the - * poison scan. b may be NULL when b_fill wrote the staging buffer already. */ -static int run_abc(const Slot *ks, const void *a, size_t a_bytes, const void *b, size_t b_bytes, - void *c, size_t c_bytes, uint32_t threads_x, uint32_t grid_x, - const uint32_t params[4], OmegaGpuEwInfo *info) { - if (omega_gpu_session_scratch(&g_a, a_bytes) || omega_gpu_session_scratch(&g_b, b_bytes) || omega_gpu_session_scratch(&g_c, c_bytes)) - return OMEGA_GPU_EW_CHIP_FAIL; - memcpy(g_a.mem.cpu, a, a_bytes); - if (b) memcpy(g_b.mem.cpu, b, b_bytes); - size_t c_words = c_bytes / 4; - uint32_t *c_dev = (uint32_t *)g_c.mem.cpu; - for (size_t i = 0; i < c_words; i++) c_dev[i] = EW_POISON; - __asm__ volatile("dsb sy" ::: "memory"); - - uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - args[0] = (uint32_t)g_a.mem.va; args[1] = (uint32_t)(g_a.mem.va >> 32); - args[2] = (uint32_t)g_b.mem.va; args[3] = (uint32_t)(g_b.mem.va >> 32); - args[4] = (uint32_t)g_c.mem.va; args[5] = (uint32_t)(g_c.mem.va >> 32); - args[6] = params[0]; args[7] = params[1]; args[8] = params[2]; args[9] = params[3]; - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = EW_GPR_BUDGET, .threads_x = threads_x, .threads_y = 1, - .grid_x = grid_x, .grid_y = 1, .num_elements = c_words, - .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = EW_WAIT_MS, - }; - uint64_t elapsed = 0; uint32_t marker = 0; - if (omega_gpu_session_launch(&L, &elapsed, &marker) != 0) return OMEGA_GPU_EW_CHIP_FAIL; - - memcpy(c, g_c.mem.cpu, c_bytes); - uint32_t unwritten = 0; - for (size_t i = 0; i < c_words; i++) if (((uint32_t *)c)[i] == EW_POISON) unwritten++; - if (info) { - info->chip_calls++; - info->elapsed_ns += elapsed; - info->completion_marker = marker; - info->unwritten_words += unwritten; - info->threads_per_cta = threads_x; - info->ctas_last_launch = grid_x; - } - return unwritten ? OMEGA_GPU_EW_UNWRITTEN : OMEGA_GPU_EW_OK; -} - -/* ------------------------------------------------------- public entries */ - -static void info_begin(OmegaGpuEwInfo *info, const OmegaBlackwellKernel *k, bool hit) { - if (!info) return; - memset(info, 0, sizeof *info); - info->kernel_cache_hit = hit; - info->gpr_count = k->gpr_count; - info->insn_count = (uint32_t)k->insn_count; - snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; -} -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static void info_end(OmegaGpuEwInfo *info, uint64_t t0) { if (info) info->call_ns = now_ns() - t0; } - -/* Common prologue of every chip entry: lock, open, kernel (resident), info. */ -static int begin(OmegaGpuEwOp op, Slot **ks, OmegaGpuEwInfo *info) { - LOCK(); - int rc = dev_open_locked(); - bool hit = false; - if (rc == OMEGA_GPU_EW_OK) rc = kernel_for(op, true, ks, &hit); - if (rc != OMEGA_GPU_EW_OK) { UNLOCK(); return rc; } - info_begin(info, &(*ks)->kernel, hit); - return OMEGA_GPU_EW_OK; -} - -int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, - float eps, float *out, OmegaGpuEwInfo *info) { - uint64_t t0 = now_ns(); - if (!x || !weight || !out || rows == 0 || dim == 0 || dim % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; - if (dim > OMEGA_GPU_EW_MAX_DIM) return OMEGA_GPU_EW_TOO_LARGE; - Slot *k = NULL; - int rc = begin(OMEGA_GPU_EW_RMSNORM, &k, info); - if (rc != OMEGA_GPU_EW_OK) return rc; - uint32_t params[4] = { dim / OMEGA_GPU_EW_THREADS, f2u(1.0f / (float)dim), f2u(eps), dim }; - for (uint32_t r0 = 0; r0 < rows && rc == OMEGA_GPU_EW_OK; r0 += OMEGA_GPU_EW_MAX_CTAS) { - uint32_t nr = rows - r0 < OMEGA_GPU_EW_MAX_CTAS ? rows - r0 : OMEGA_GPU_EW_MAX_CTAS; - size_t bytes = (size_t)nr * dim * 4; - rc = run_abc(k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes, - OMEGA_GPU_EW_THREADS, nr, params, info); - } - UNLOCK(); - info_end(info, t0); - return rc; -} - -int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, - const float *cos_half, const float *sin_half, float *out, OmegaGpuEwInfo *info) { - uint64_t t0 = now_ns(); - if (!v || !cos_half || !sin_half || !out || heads == 0 || head_dim < 2 || (head_dim & 1)) return OMEGA_GPU_EW_BAD_ARGS; - if (head_dim > 2048) return OMEGA_GPU_EW_TOO_LARGE; - Slot *k = NULL; - int rc = begin(OMEGA_GPU_EW_ROPE, &k, info); - if (rc != OMEGA_GPU_EW_OK) return rc; - uint32_t half = head_dim / 2; - uint32_t params[4] = { head_dim, half, 0, 0 }; - for (uint32_t h0 = 0; h0 < heads && rc == OMEGA_GPU_EW_OK; h0 += OMEGA_GPU_EW_MAX_CTAS) { - uint32_t nh = heads - h0 < OMEGA_GPU_EW_MAX_CTAS ? heads - h0 : OMEGA_GPU_EW_MAX_CTAS; - size_t bytes = (size_t)nh * head_dim * 4; - /* table: cos in the first half of each head, sin in the second, written straight into - * the staging buffer (one copy per head of this launch) */ - if (omega_gpu_session_scratch(&g_b, bytes) != 0) { rc = OMEGA_GPU_EW_CHIP_FAIL; break; } - float *table = g_b.mem.cpu; - for (uint32_t h = 0; h < nh; h++) { - memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table); - memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table); - } - /* out may alias v: v is copied into the staging buffer before the result lands in out */ - rc = run_abc(k, v + (size_t)h0 * head_dim, bytes, NULL, bytes, out + (size_t)h0 * head_dim, bytes, half, nh, params, info); - } - UNLOCK(); - info_end(info, t0); - return rc; -} - -static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) { - uint64_t t0 = now_ns(); - Slot *k = NULL; - int rc = begin(op, &k, info); - if (rc != OMEGA_GPU_EW_OK) return rc; - const uint32_t chunk = OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS; - for (uint32_t i0 = 0; i0 < n && rc == OMEGA_GPU_EW_OK; i0 += chunk) { - uint32_t ni = n - i0 < chunk ? n - i0 : chunk; - uint32_t grid = (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS; - uint32_t params[4] = { ni, 0, 0, 0 }; - size_t bytes = (size_t)ni * 4; - rc = run_abc(k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes, - (uint8_t *)c + (size_t)i0 * 4, bytes, OMEGA_GPU_EW_THREADS, grid, params, info); - } - UNLOCK(); - info_end(info, t0); - return rc; -} - -int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) { - if (!gate || !up || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; - return run_1d(OMEGA_GPU_EW_SWIGLU, n, gate, up, out, info); -} -int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info) { - if (!x || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; - return run_1d(OMEGA_GPU_EW_EX2, n, x, NULL, out, info); -} -int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info) { - if (!x || !out || n == 0 || n % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; - return run_1d(OMEGA_GPU_EW_XCHG, n, x, NULL, out, info); -} -int omega_gpu_reconv_probe_u32(OmegaGpuEwOp op, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out, OmegaGpuEwInfo *info) { - if (!a || !b || !out || n == 0) return OMEGA_GPU_EW_BAD_ARGS; - switch (op) { - case OMEGA_GPU_EW_RC_DIAMOND: case OMEGA_GPU_EW_RC_LOOPBREAK: case OMEGA_GPU_EW_RC_NESTED: - case OMEGA_GPU_EW_RC_EXIT_BAR: case OMEGA_GPU_EW_RC_DEPTH16: break; - default: return OMEGA_GPU_EW_BAD_ARGS; - } - return run_1d(op, n, a, b, out, info); -} - -const char *omega_gpu_elementwise_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_EW_OK: return "OK"; - case OMEGA_GPU_EW_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_EW_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_EW_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_EW_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_EW_UNWRITTEN: return "UNWRITTEN"; - default: return "UNKNOWN"; - } -} diff --git a/src/omega_gpu_elementwise_api.h b/src/omega_gpu_elementwise_api.h deleted file mode 100644 index 243b1ed9c..000000000 --- a/src/omega_gpu_elementwise_api.h +++ /dev/null @@ -1,183 +0,0 @@ -#ifndef OMEGA_GPU_ELEMENTWISE_API_H -#define OMEGA_GPU_ELEMENTWISE_API_H -/* - * omega_gpu_elementwise_api: native (no CUDA) elementwise and row-reduction - * kernels for the AIEN inference stack (FB-1 cut 4, 2026-10-04). - * - * Three inference ops plus two probe ops, every kernel generated by our own - * codegen (src/omega_blackwell_codegen.c IR) and launched through the same - * chip-proven sequence as the tensor matmul path: all buffers GPU-uncached - * (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: system memory cached by the GPU is not - * coherent with CPU mappings), first marker, L2_FLUSH_DIRTY, second marker - * (C3 tail), poison-filled output scanned for unwritten words after readback. - * - * The math follows aien-sovereign-core crates/aien-inference-abi/src/tensor.rs - * (ReferenceCpuBackend), read 2026-10-04 at main 5fdab70: - * rmsnorm: scale = 1/sqrt(mean(x^2) + eps) (oracle sums in f64; the chip - * sums in f32 and uses MUFU.RSQ refined by one Newton step), - * out[i] = (x[i] * scale) * weight[i] in that order. - * rope: rotate_half pairs (i, i + head_dim/2) per head, cos/sin tables - * supplied by the host as f32 (the oracle casts f64 cos/sin to f32 - * before the f32 math): out0 = q0*cos - q1*sin, out1 = q0*sin + q1*cos, - * emitted as FMUL, FMUL, FADD (no fused multiply-add), so the chip - * result is bit-identical to the f32 oracle. - * swiglu: out = silu(gate) * up, silu(g) = g / (1 + exp(-g)); the chip uses - * MUFU.EX2(g * -log2(e)) and MUFU.RCP (approximate units), the - * oracle computes in f64. Tolerance is stated per op in the test. - * - * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide - * session shared with the matmul and attention APIs (omega_gpu_session.h): one open - * per process instead of one per call (~40 ms), kernels resident after first use, - * staging buffers reused at their high-water mark. Calls serialise on one lock. - * - * Launch envelope: at most OMEGA_GPU_EW_MAX_CTAS CTAs per launch; the API splits - * larger work on the host and makes several launches. The cap was 64 from the - * 2026-10-03 matmul sweep that lost whole tiles at 128 CTAs (investigation I42, - * root cause the GPU-cached completion marker, fixed by the uncached marker + - * L2_FLUSH_DIRTY release sequence every launch here goes through). Cut L - * (2026-10-12): 1024, the CTA budget the matmul path has run every serving leg - * at since; a prefill swiglu of 128 x 12288 was 192 launches of 64 CTAs (1.4 ms - * of chip time per call), now 12. The poison scan of every output word is the - * lost-tile detector and stays. - */ -#include -#include -#include -#include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */ - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_EW_OK = 0, - OMEGA_GPU_EW_BAD_ARGS = -1, /* NULL pointer, zero dimension, or a shape rule below broken */ - OMEGA_GPU_EW_TOO_LARGE = -2, /* dimension outside the codegen limits */ - OMEGA_GPU_EW_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */ - OMEGA_GPU_EW_CHIP_FAIL = -4, /* device open, submit, marker or release failed */ - OMEGA_GPU_EW_UNWRITTEN = -5 /* output words still equal to their poison after the run */ -}; - -/* Kernel families. The two probes exist to prove the new instructions on the - * chip with the smallest possible kernels (and are kept for regression). */ -typedef enum { - OMEGA_GPU_EW_EX2 = 1, /* out[i] = 2^a[i] (probe for MUFU.EX2) */ - OMEGA_GPU_EW_XCHG, /* out[i] = a[i ^ (T-1)] inside each CTA (probe for STS/BAR.SYNC/LDS) */ - OMEGA_GPU_EW_RMSNORM, - OMEGA_GPU_EW_ROPE, - OMEGA_GPU_EW_SWIGLU, - OMEGA_GPU_EW_PRIME_SIEVE, /* prime race (2026-10-05): word-parallel odd-only sieve, codegen only - * here; launched by bench/prime_race/gb10_native.c (argument words in - * gen_prime_sieve's comment) */ - OMEGA_GPU_EW_PRIME_SIEVE_SHARED, /* the same sieve with the table staged in shared memory (C3) */ - /* Structured warp reconvergence (omega #308). The four sieves below are the production sieve - * with its lane-dependent loops put back inside BSSY/BSYNC regions (regression R1): DIV1 wraps - * the original mark loop (omega 888a011), DIV2 also wraps the prime loop (nested regions). */ - OMEGA_GPU_EW_PRIME_SIEVE_DIV1, - OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV1, - OMEGA_GPU_EW_PRIME_SIEVE_DIV2, - OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2, - /* Probes for omega_gpu_reconv_probe_u32 (u32 in a, b; u32 out; oracle in tests/gpu_reconv_test.c) */ - OMEGA_GPU_EW_RC_DIAMOND, /* R3: if/else, sides of different length, SHFL after the join */ - OMEGA_GPU_EW_RC_LOOPBREAK, /* R4: loop with a lane-dependent break */ - OMEGA_GPU_EW_RC_NESTED, /* R5: a lane-dependent loop region inside an if region */ - OMEGA_GPU_EW_RC_EXIT_BAR, /* R6: lanes past the end + STS/BAR.SYNC/LDS exchange + SHFL, lanes exit last */ - OMEGA_GPU_EW_RC_DEPTH16, /* 16 nested regions: every barrier register B0..B15 in use */ - /* Codegen refusals: omega_gpu_elementwise_codegen_ir must return CODEGEN_FAIL for each */ - OMEGA_GPU_EW_RC_REFUSE_DEPTH17, /* a 17th nested region: no barrier register left */ - OMEGA_GPU_EW_RC_REFUSE_EXIT_SHFL, /* lanes EXIT, then BAR.SYNC/SHFL on the rest */ - OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION, /* EXIT inside an open region */ - OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION, /* BAR.SYNC inside an open region */ - OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION, /* SHFL inside an open region */ - OMEGA_GPU_EW_RC_REFUSE_UNCLOSED, /* region begun, never joined */ - OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY /* BSYNC with no BSSY */ -} OmegaGpuEwOp; - -/* Shape rules (checked, refused with BAD_ARGS / TOO_LARGE): - * rmsnorm: dim % OMEGA_GPU_EW_THREADS == 0, dim <= OMEGA_GPU_EW_MAX_DIM, rows >= 1 - * rope: head_dim even, 2 <= head_dim <= 2048 (head_dim/2 threads per CTA), heads >= 1 - * swiglu: n >= 1 (the kernel guards the tail with a predicated EXIT) - * ex2: n >= 1; xchg: n % OMEGA_GPU_EW_THREADS == 0 */ -#define OMEGA_GPU_EW_THREADS 128u -#define OMEGA_GPU_EW_MAX_DIM 16384u -#define OMEGA_GPU_EW_MAX_CTAS 1024u - -typedef struct { - uint32_t chip_calls; /* launches made */ - uint64_t elapsed_ns; /* sum of launch-to-second-marker over the launches */ - uint32_t completion_marker; /* observed first marker word of the last launch */ - uint32_t unwritten_words; /* output words still equal to poison (0 on success) */ - bool kernel_cache_hit; /* the shape's kernel was already generated in this process */ - uint32_t gpr_count; /* registers the generated kernel uses */ - uint32_t insn_count; - uint32_t threads_per_cta; - uint32_t ctas_last_launch; - char target_chip[64]; - uint32_t sm_architecture; - uint64_t call_ns; /* cut 4b: wall time of the whole API call (staging, launches, copy-out) */ -} OmegaGpuEwInfo; - -/* out[r*dim + i] = x[r*dim + i] * scale_r * weight[i]; scale_r = 1/sqrt(mean_i(x^2) + eps). */ -int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, - float eps, float *out, OmegaGpuEwInfo *info); - -/* v holds `heads` heads of head_dim values back to back; cos_half and sin_half - * hold head_dim/2 values each (cos(pos*freq_i), sin(pos*freq_i)); out gets the - * rotated heads (may alias v: the API copies through its own buffers). */ -int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, - const float *cos_half, const float *sin_half, float *out, - OmegaGpuEwInfo *info); - -/* out[i] = silu(gate[i]) * up[i] for i < n. */ -int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, - OmegaGpuEwInfo *info); - -/* Probes. ex2: out[i] = 2^x[i]. xchg: out[i] = x[i ^ (OMEGA_GPU_EW_THREADS-1)] within each CTA. */ -int omega_gpu_ex2_f32(uint32_t n, const float *x, float *out, OmegaGpuEwInfo *info); -int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, OmegaGpuEwInfo *info); -/* Reconvergence probes (op = one of OMEGA_GPU_EW_RC_DIAMOND .. OMEGA_GPU_EW_RC_DEPTH16, else - * BAD_ARGS). n >= 1, any n: lanes past the end take part in the warp step and exit before - * their store. out[i] = r_i + 4099 * r_(i+1 in warp); r per op in src/omega_gpu_elementwise_api.c. */ -int omega_gpu_reconv_probe_u32(OmegaGpuEwOp op, uint32_t n, const uint32_t *a, const uint32_t *b, - uint32_t *out, OmegaGpuEwInfo *info); - -/* Generate (without launching) the kernel for one op. Kernels read their shape - * from the argument words, so one kernel per op serves every shape; dims and eps - * are accepted for forward compatibility and ignored today (may be NULL / 0). - * Lets tests disassemble the bytes offline (nvdisasm) and check the register - * budget. Caller frees kernel->code. */ -int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, - OmegaBlackwellKernel *kernel); - -/* Same, with the mutant chosen by the caller (0 = production kernel, 1 = the op's math mutant, - * 2 = the reconvergence join (BSYNC) dropped, 3 = the BSSY names the wrong join; 2 and 3 change - * only kernels that open a region, the host simulator must catch both) and, when prog is - * not NULL, a copy of the allocated IR program (a BlackwellIRProgram, post register - * allocation) for a host IR simulator. Does not touch the device or the kernel cache. - * Caller frees kernel->code. */ -int omega_gpu_elementwise_codegen_ir(OmegaGpuEwOp op, int mutant, void *prog, - OmegaBlackwellKernel *kernel); - -/* TEST ONLY. Selects a deliberately wrong kernel for one op (0 clears). Each - * mutant changes the math by far more than the op's tolerance, so a parity - * check that still passes against it proves nothing. Clears the kernel cache. - * EX2: computes 2^(x+1). XCHG: reads its own shared word (no exchange). - * RMSNORM: the warp tree drops its last SHFL step (half the lanes go missing). - * ROPE: out0 = q0*cos + q1*sin. SWIGLU: exp(+g) instead of exp(-g). */ -void omega_gpu_elementwise_test_set_mutant(int op); -/* TEST ONLY. Like test_set_mutant, choosing the mutant number (1 math, 2 join dropped, 3 join - * corrupted) that the next launch of `op` builds; lets a chip test observe what a missing - * reconvergence does (the simulator must have flagged it first). */ -void omega_gpu_elementwise_test_set_mutant_level(int op, int level); - -const char *omega_gpu_elementwise_rc_name(int rc); -void omega_gpu_elementwise_cache_clear(void); - -/* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs - * (omega_gpu_session_last_error); an open failure carries the driver text. */ -const char *omega_gpu_elementwise_last_error(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_engine.c b/src/omega_gpu_engine.c deleted file mode 100644 index 021332753..000000000 --- a/src/omega_gpu_engine.c +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Omega GPU Engine core (A3a). See src/omega_gpu_engine.h and - * docs/numeric/OMEGA_GPU_ENGINE.md. - * - * omega_gpu_execute drives the backend function table in one fixed order: - * open, channel, alloc x5, copy-in x3, poison fill, build -> PREPARED - * submit -> SUBMITTED - * marker wait, marker2 wait (unless NO_C3), release wait -> GPU_COMPLETE - * barrier, copy-out -> OUTPUT_VISIBLE - * compare every output word with its poison word -> OUTPUT_PRODUCED - * free every buffer (reverse order), close -> SUCCESS - * Every exit runs cleanup EXCEPT an uncertain completion (any non-zero result - * from one of the three completion waits), which keeps the context and every - * allocation, sets the process-wide block and reports retained = 1. - * The engine never judges the math: it only checks that output words changed. - * - * Marker comments of the form MUT: label the lines that - * tools/gpu_engine_mutations.sh breaks one at a time. - */ -#include "omega_gpu_engine.h" - -#include -#include -#ifdef OMEGA_GPU_NO_POSIX -/* Freestanding link target (native v1 P07 cut A, aienos#286 cut A): no errno - * and no POSIX clock. err_no is always 0, and the millisecond clock must be - * installed with omega_gpu_engine_set_clock before any job runs; without one - * omega_gpu_execute refuses at STEP_CLOCK_CHECK instead of guessing. */ -#define ERRNO_CLEAR() ((void)0) -#define ERRNO_READ() 0 -#else -#include -#include -#define ERRNO_CLEAR() (errno = 0) -#define ERRNO_READ() (errno) -#endif - -static const char *const FAILURE_NAMES[OMEGA_GPU_ENGINE_FAILURE_COUNT] = { - "OK", - "DEVICE_OPEN", - "CHANNEL_CREATE", - "ALLOC", - "PREPARE", - "SUBMIT", - "COMPLETION_WAIT", - "RELEASE_WAIT", - "VISIBILITY_WAIT", - "OUTPUT_UNCHANGED", - "INVALID_ARGS", - "INTERNAL_INVARIANT", - "CLEANUP", - "UNCERTAIN_COMPLETION_BLOCKED", -}; - -static const char *const STATE_NAMES[OMEGA_GPU_ENGINE_STATE_COUNT] = { - "INITIAL", - "PREPARED", - "SUBMITTED", - "GPU_COMPLETE", - "OUTPUT_VISIBLE", - "OUTPUT_PRODUCED", - "SUCCESS", -}; - -static const char *const WAIT_NAMES[OMEGA_GPU_ENGINE_WAIT_COUNT] = { - "NONE", - "MARKER", - "RELEASE_SEMAPHORE", - "MARKER2", -}; - -static const char *const STEP_NAMES[OMEGA_GPU_ENGINE_STEP_COUNT] = { - "NONE", - "VALIDATE", - "BACKEND_CHECK", - "BLOCKED", - "NOT_IMPLEMENTED", - "OPEN_DEVICE", - "CREATE_CHANNEL", - "ALLOC", - "COPY_IN", - "FILL_POISON", - "BUILD", - "SUBMIT", - "WAIT_MARKER", - "WAIT_MARKER2", - "WAIT_RELEASE_SEMAPHORE", - "BARRIER", - "COPY_OUT", - "SCAN", - "FREE", - "CLOSE", - "CLOCK_CHECK", -}; - -static _Atomic(const OmegaGpuBackend *) g_backend; -static atomic_int g_blocked; -static uint64_t (*g_clock)(void); /* installed clock; NULL means CLOCK_MONOTONIC on the host, none when freestanding */ - -const char *omega_gpu_engine_failure_name(int failure) -{ - if (failure < 0 || failure >= (int)OMEGA_GPU_ENGINE_FAILURE_COUNT) return "UNKNOWN"; - return FAILURE_NAMES[failure]; -} - -const char *omega_gpu_engine_state_name(int state) -{ - if (state < 0 || state >= (int)OMEGA_GPU_ENGINE_STATE_COUNT) return "UNKNOWN"; - return STATE_NAMES[state]; -} - -const char *omega_gpu_engine_wait_name(int wait) -{ - if (wait < 0 || wait >= (int)OMEGA_GPU_ENGINE_WAIT_COUNT) return "UNKNOWN"; - return WAIT_NAMES[wait]; -} - -const char *omega_gpu_engine_step_name(int step) -{ - if (step < 0 || step >= (int)OMEGA_GPU_ENGINE_STEP_COUNT) return "UNKNOWN"; - return STEP_NAMES[step]; -} - -void omega_gpu_engine_set_backend(const OmegaGpuBackend *backend) -{ - atomic_store(&g_backend, backend); -} - -int omega_gpu_engine_is_blocked(void) -{ - return atomic_load(&g_blocked) ? 1 : 0; -} - -void omega_gpu_engine_test_reset_block(void) -{ - atomic_store(&g_blocked, 0); -} - -void omega_gpu_engine_test_force_block(void) -{ - atomic_store(&g_blocked, 1); -} - -void omega_gpu_engine_set_clock(uint64_t (*now_ms)(void)) -{ - g_clock = now_ms; -} - -void omega_gpu_engine_test_set_clock(uint64_t (*now_ms)(void)) -{ - g_clock = now_ms; -} - -#ifdef OMEGA_GPU_NO_POSIX -static uint64_t now_ms(void) -{ - return g_clock ? g_clock() : 0u; /* unreachable without a clock: omega_gpu_execute refuses first */ -} -#else -static uint64_t mono_ms(void) -{ - struct timespec ts; - if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0u; - return (uint64_t)ts.tv_sec * 1000u + (uint64_t)ts.tv_nsec / 1000000u; -} - -static uint64_t now_ms(void) -{ - return g_clock ? g_clock() : mono_ms(); -} -#endif - -static int backend_complete(const OmegaGpuBackend *b) -{ - return b->open_device && b->create_channel && b->alloc && b->copy_in && b->fill_poison && - b->build && b->submit && b->wait_marker && b->wait_marker2 && - b->wait_release_semaphore && b->barrier && b->copy_out && b->diagnostics && - b->free_buf && b->close; -} - -/* Returns 1 when the job is well formed for the VECTOR_1D layout. */ -static int job_valid(const OmegaGpuJob *job) -{ - uint64_t bytes; - if (!job->program || job->program_len == 0) return 0; /* MUT:VALID_PROGRAM */ - if (job->layout != OMEGA_GPU_LAYOUT_VECTOR_1D) return 0; /* MUT:VALID_LAYOUT */ - if (job->element_count == 0) return 0; /* MUT:VALID_COUNT_ZERO */ - bytes = (uint64_t)job->element_count * 4u; - if (!job->input_a || (uint64_t)job->input_a_len != bytes) return 0; - if (!job->input_b || (uint64_t)job->input_b_len != bytes) return 0; - if (!job->output || (uint64_t)job->output_len != bytes) return 0; - if (((uintptr_t)job->output & 3u) != 0) return 0; /* MUT:VALID_ALIGN */ - if (!job->poison || (uint64_t)job->poison_count != (uint64_t)job->element_count) return 0; /* MUT:VALID_POISON_COUNT */ - if ((job->flags & ~(uint32_t)OMEGA_GPU_ENGINE_FLAG_NO_C3) != 0) return 0; /* MUT:VALID_FLAGS */ - if (job->timeouts.marker_ms == 0) return 0; /* MUT:VALID_TIMEOUT_MARKER1 */ - if (job->timeouts.release_semaphore_ms == 0) return 0; - if (job->timeouts.visibility_ms == 0) return 0; - if ((job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0 && job->timeouts.marker2_ms == 0) return 0; /* MUT:VALID_TIMEOUT_MARKER2 */ - return 1; -} - -/* What the engine still owes the device: close if opened, free each allocated buffer. */ -typedef struct { - int opened; - int allocated[OMEGA_GPU_BUF_ROLE_COUNT]; -} Run; - -/* Failure before any backend call: nothing to capture, nothing to clean. */ -static int stop(OmegaGpuResult *result, int failure, int step) -{ - result->failure = failure; - result->failed_step = step; - return failure; -} - -/* Copies the backend diagnostics (driver code, text, observed words) into the result. */ -static void capture(const OmegaGpuBackend *b, OmegaGpuResult *result) -{ - OmegaGpuBackendDiag d; - memset(&d, 0, sizeof d); - b->diagnostics(b->ctx, &d); - result->drv_rc = d.drv_rc; - memcpy(result->drv_text, d.drv_text, sizeof result->drv_text); - result->drv_text[sizeof result->drv_text - 1u] = '\0'; - result->sync_valid = d.sync_valid; - result->marker = d.marker; - result->marker2 = d.marker2; - memcpy(result->semaphore, d.semaphore, sizeof result->semaphore); -} - -/* Records the failure of a backend call. err is errno captured right after that call. */ -static int fail(const OmegaGpuBackend *b, OmegaGpuResult *result, int failure, int step, int err) -{ - capture(b, result); - result->failure = failure; - result->failed_step = step; - result->err_no = err; - return failure; -} - -/* A cleanup call failed. The first failure of the run is never overwritten. */ -static void cleanup_fault(const OmegaGpuBackend *b, OmegaGpuResult *result, int step, int err) -{ - if (result->failure == OMEGA_GPU_ENGINE_OK) /* MUT:CLEANUP_OVERWRITES_FIRST */ - (void)fail(b, result, OMEGA_GPU_ENGINE_CLEANUP, step, err); - result->cleanup_failed = 1; /* MUT:CLEANUP_FLAG_NOT_SET */ -} - -/* Frees every allocated buffer (reverse of allocation order), then closes the - * device. A failing call does not stop the rest. Returns result->failure. */ -static int leave(const OmegaGpuBackend *b, const Run *run, OmegaGpuResult *result) -{ - int role; - int rc; - int e; - for (role = (int)OMEGA_GPU_BUF_ROLE_COUNT - 1; role >= 0; role--) { - if (!run->allocated[role]) continue; /* MUT:FREE_UNALLOCATED */ - ERRNO_CLEAR(); - rc = b->free_buf(b->ctx, role); /* MUT:FREE_SKIPPED */ - e = ERRNO_READ(); - if (rc != 0) cleanup_fault(b, result, OMEGA_GPU_ENGINE_STEP_FREE, e); - } - if (run->opened) { - ERRNO_CLEAR(); - rc = b->close(b->ctx); /* MUT:CLOSE_SKIPPED */ - e = ERRNO_READ(); - if (rc != 0) cleanup_fault(b, result, OMEGA_GPU_ENGINE_STEP_CLOSE, e); - } - return result->failure; -} - -/* A completion wait gave a non-zero result: completion is uncertain. Keep the - * context and every allocation (no free, no close), say so, and block the process. */ -static int uncertain(const OmegaGpuBackend *b, OmegaGpuResult *result, int failure, int step, - int wait, uint64_t limit_ms, uint64_t waited_ms, int err) -{ - (void)fail(b, result, failure, step, err); - result->wait = wait; - result->wait_timeout_ms = limit_ms; - result->waited_ms = waited_ms; - result->retained = 1; /* MUT:RETAINED_FLAG_NOT_SET */ - atomic_store(&g_blocked, 1); /* MUT:NO_BLOCK */ - return failure; -} - -/* Calls a timed backend callback; captures errno right after it and measures the wait. */ -static int timed_call(int (*fn)(void *, uint64_t), void *ctx, uint64_t ms, uint64_t *waited_ms, - int *err) -{ - uint64_t t0 = now_ms(); - uint64_t t1; - int rc; - ERRNO_CLEAR(); - rc = fn(ctx, ms); - *err = ERRNO_READ(); - t1 = now_ms(); - *waited_ms = t1 >= t0 ? t1 - t0 : 0u; /* MUT:WAITED_NOT_A_DIFFERENCE */ - return rc; -} - -static int copy_in_role(const OmegaGpuBackend *b, int role, const void *src, size_t bytes, int *err) -{ - int rc; - ERRNO_CLEAR(); - rc = b->copy_in(b->ctx, role, src, bytes); - *err = ERRNO_READ(); - return rc; -} - -/* Device bytes for a buffer role. SCRATCH (pushbuffer, marker page, QMD) is the - * backend's own business, so the engine passes 0 and the backend sizes it. */ -static size_t buf_bytes(const OmegaGpuJob *job, int role) -{ - switch (role) { - case OMEGA_GPU_BUF_PROGRAM: return job->program_len; - case OMEGA_GPU_BUF_INPUT_A: return job->input_a_len; - case OMEGA_GPU_BUF_INPUT_B: return job->input_b_len; - case OMEGA_GPU_BUF_OUTPUT: return job->output_len; - default: return 0u; - } -} - -int omega_gpu_execute(const OmegaGpuJob *job, OmegaGpuResult *result) -{ - const OmegaGpuBackend *b; - Run run; - uint64_t waited = 0u; - uint64_t unchanged = 0u; - size_t i; - int role; - int rc; - int e = 0; - - if (!result) return OMEGA_GPU_ENGINE_INVALID_ARGS; - memset(result, 0, sizeof *result); - result->failure = OMEGA_GPU_ENGINE_OK; - result->last_state = OMEGA_GPU_ENGINE_STATE_INITIAL; - result->failed_step = OMEGA_GPU_ENGINE_STEP_NONE; - result->wait = OMEGA_GPU_ENGINE_WAIT_NONE; - if (omega_gpu_engine_is_blocked()) /* MUT:BLOCK_CHECK_SKIPPED */ - return stop(result, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, - OMEGA_GPU_ENGINE_STEP_BLOCKED); - if (!job || !job_valid(job)) /* MUT:VALIDATE_SKIPPED */ - return stop(result, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STEP_VALIDATE); - b = atomic_load(&g_backend); - if (!b) - return stop(result, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - if (!backend_complete(b)) /* MUT:BACKEND_CHECK_SKIPPED */ - return stop(result, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, - OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK); -#ifdef OMEGA_GPU_NO_POSIX - if (!g_clock) /* no platform clock: waited_ms could not be measured; refuse before touching the device */ - return stop(result, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_CLOCK_CHECK); -#endif - memset(&run, 0, sizeof run); - - /* INITIAL -> PREPARED */ - ERRNO_CLEAR(); - rc = b->open_device(b->ctx); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_DEVICE_OPEN, OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, e); - return leave(b, &run, result); - } - run.opened = 1; /* MUT:OPEN_NOT_TRACKED */ - - ERRNO_CLEAR(); - rc = b->create_channel(b->ctx); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_CHANNEL_CREATE, OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, e); - return leave(b, &run, result); /* MUT:CLEANUP_SKIPPED_CHANNEL */ - } - - for (role = 0; role < (int)OMEGA_GPU_BUF_ROLE_COUNT; role++) { - ERRNO_CLEAR(); - rc = b->alloc(b->ctx, role, buf_bytes(job, role)); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STEP_ALLOC, e); - return leave(b, &run, result); /* MUT:CLEANUP_SKIPPED_ALLOC */ - } - run.allocated[role] = 1; /* MUT:ALLOC_NOT_TRACKED */ - } - - rc = copy_in_role(b, OMEGA_GPU_BUF_PROGRAM, job->program, job->program_len, &e); - if (rc == 0) rc = copy_in_role(b, OMEGA_GPU_BUF_INPUT_A, job->input_a, job->input_a_len, &e); - if (rc == 0) rc = copy_in_role(b, OMEGA_GPU_BUF_INPUT_B, job->input_b, job->input_b_len, &e); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STEP_COPY_IN, e); - return leave(b, &run, result); /* MUT:CLEANUP_SKIPPED_COPY_IN */ - } - - ERRNO_CLEAR(); rc = b->fill_poison(b->ctx, job->poison, job->poison_count); e = ERRNO_READ(); /* MUT:POISON_FILL_SKIPPED */ - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STEP_FILL_POISON, e); - return leave(b, &run, result); - } - - ERRNO_CLEAR(); - rc = b->build(b->ctx, job); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STEP_BUILD, e); - return leave(b, &run, result); - } - result->last_state = OMEGA_GPU_ENGINE_STATE_PREPARED; /* MUT:STATE_PREPARED_SKIPPED */ - - /* PREPARED -> SUBMITTED. A failed submit is a known failure, not an uncertain completion. */ - ERRNO_CLEAR(); - rc = b->submit(b->ctx); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STEP_SUBMIT, e); - return leave(b, &run, result); /* MUT:CLEANUP_SKIPPED_SUBMIT */ - } - result->last_state = OMEGA_GPU_ENGINE_STATE_SUBMITTED; /* MUT:STATE_SUBMITTED_SKIPPED */ - - /* SUBMITTED -> GPU_COMPLETE: marker, marker2 (unless NO_C3), release semaphore. - * Any non-zero result is an uncertain completion. */ - rc = timed_call(b->wait_marker, b->ctx, job->timeouts.marker_ms, &waited, &e); /* MUT:MARKER1_WAIT_SKIPPED MUT:MARKER1_TIMEOUT_WRONG */ - if (rc != 0) return uncertain(b, result, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, OMEGA_GPU_ENGINE_WAIT_MARKER, job->timeouts.marker_ms, waited, e); /* MUT:MARKER1_RESULT_IGNORED MUT:UNCERTAIN_FREES_MARKER1 */ - if (!(job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3)) { /* MUT:MARKER2_WAIT_SKIPPED MUT:C3_FLAG_IGNORED */ - rc = timed_call(b->wait_marker2, b->ctx, job->timeouts.marker2_ms, &waited, &e); - if (rc != 0) return uncertain(b, result, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, OMEGA_GPU_ENGINE_WAIT_MARKER2, job->timeouts.marker2_ms, waited, e); /* MUT:MARKER2_RESULT_IGNORED MUT:UNCERTAIN_FREES_MARKER2 */ - } - rc = timed_call(b->wait_release_semaphore, b->ctx, job->timeouts.release_semaphore_ms, &waited, &e); /* MUT:RELEASE_WAIT_SKIPPED */ - if (rc != 0) return uncertain(b, result, OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, job->timeouts.release_semaphore_ms, waited, e); /* MUT:RELEASE_RESULT_IGNORED MUT:UNCERTAIN_FREES_RELEASE */ - result->last_state = OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE; /* MUT:STATE_GPU_COMPLETE_SKIPPED */ - - /* GPU_COMPLETE -> OUTPUT_VISIBLE: completion is known here, so a failure cleans up. */ - rc = timed_call(b->barrier, b->ctx, job->timeouts.visibility_ms, &waited, &e); /* MUT:BARRIER_SKIPPED */ - if (rc != 0) { /* MUT:BARRIER_RESULT_IGNORED */ - (void)fail(b, result, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STEP_BARRIER, e); - return leave(b, &run, result); - } - ERRNO_CLEAR(); - rc = b->copy_out(b->ctx, job->output, job->output_len); - e = ERRNO_READ(); - if (rc != 0) { - (void)fail(b, result, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STEP_COPY_OUT, e); - return leave(b, &run, result); - } - result->last_state = OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE; /* MUT:STATE_OUTPUT_VISIBLE_SKIPPED */ - - /* OUTPUT_VISIBLE -> OUTPUT_PRODUCED: no output word may still equal its poison word. */ - for (i = 0; i < (size_t)job->element_count; i++) { - uint32_t w; - memcpy(&w, (const unsigned char *)job->output + i * 4u, sizeof w); - if (w == job->poison[i]) unchanged++; /* MUT:POISON_INDEX_FIXED MUT:UNCHANGED_COUNT_SATURATES */ - } - result->n_outputs = 1u; - result->output_unchanged_words[0] = unchanged; - if (unchanged != 0u) { /* MUT:UNCHANGED_CHECK_SKIPPED */ - (void)fail(b, result, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STEP_SCAN, 0); - return leave(b, &run, result); - } - result->last_state = OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED; /* MUT:STATE_OUTPUT_PRODUCED_SKIPPED */ - - /* OUTPUT_PRODUCED -> SUCCESS, only when cleanup also went well. */ - rc = leave(b, &run, result); - if (rc == OMEGA_GPU_ENGINE_OK) result->last_state = OMEGA_GPU_ENGINE_STATE_SUCCESS; /* MUT:STATE_SUCCESS_SKIPPED MUT:SUCCESS_AFTER_CLEANUP_FAIL */ - return rc; -} diff --git a/src/omega_gpu_engine.h b/src/omega_gpu_engine.h deleted file mode 100644 index 00e81f22e..000000000 --- a/src/omega_gpu_engine.h +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Omega GPU Engine: run one already-built GPU kernel job and return SUCCESS or - * exactly one named failure. - * - * Purpose: today several launcher files repeat the same open / alloc / copy-in / - * pushbuffer / submit / completion-wait / readback / close sequence with three - * different error styles. This module owns that sequence once. Design: - * docs/numeric/OMEGA_GPU_ENGINE.md (the first-cut plan is Drake's, 2026-10-02). - * - * Public entry point: - * int omega_gpu_execute(const OmegaGpuJob *job, OmegaGpuResult *result); - * It returns OMEGA_GPU_ENGINE_OK (0) on success, otherwise the failure code, - * which is also stored in result->failure. - * - * States: INITIAL -> PREPARED -> SUBMITTED -> GPU_COMPLETE -> OUTPUT_VISIBLE -> - * OUTPUT_PRODUCED -> SUCCESS. The result records the last completed state and - * the precise failed step. (The earlier draft of this header called the final - * state COMMITTED and the first one NONE.) - * - * Poison: the wrapper supplies one poison word per output word. The engine - * writes those words to the device output before submit and, after readback, - * checks only whether any word is still equal to its poison word. The engine - * never chooses poison and never judges whether the math is right. - * - * Uncertain completion: if the engine cannot tell whether the GPU finished (a - * completion wait timed out, or the device returned an unknown state), it keeps - * the device context and every allocation (no free, no close), records that in - * the result, and blocks every later omega_gpu_execute call in this process, - * which then returns UNCERTAIN_COMPLETION_BLOCKED. - * - * STATUS: A3a engine core. omega_gpu_execute drives the backend table below - * through the whole state machine; only a fake backend exists (host tests). - * With no backend set it still returns INTERNAL_INVARIANT at step - * NOT_IMPLEMENTED. The real Blackwell backend is a later cut (A3b). This cut is - * not chip-qualified (host NOT_RUN, chip NOT_RUN). - */ -#ifndef OMEGA_GPU_ENGINE_H -#define OMEGA_GPU_ENGINE_H - -#include -#include - -/* One failure name per run. OK is 0, so the return value reads as a boolean. */ -typedef enum { - OMEGA_GPU_ENGINE_OK = 0, - OMEGA_GPU_ENGINE_DEVICE_OPEN, /* device could not be opened */ - OMEGA_GPU_ENGINE_CHANNEL_CREATE, /* channel could not be created */ - OMEGA_GPU_ENGINE_ALLOC, /* a device buffer could not be allocated */ - OMEGA_GPU_ENGINE_PREPARE, /* copy-in, poison fill or descriptor build failed */ - OMEGA_GPU_ENGINE_SUBMIT, /* submitting the work failed */ - OMEGA_GPU_ENGINE_COMPLETION_WAIT, /* marker or marker2 wait failed or timed out */ - OMEGA_GPU_ENGINE_RELEASE_WAIT, /* release semaphore wait failed or timed out */ - OMEGA_GPU_ENGINE_VISIBILITY_WAIT, /* barrier or readback failed or timed out */ - OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, /* after readback, output words still equal their poison */ - OMEGA_GPU_ENGINE_INVALID_ARGS, /* the job or the result pointer is malformed */ - OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, /* the engine or its backend broke its own contract */ - OMEGA_GPU_ENGINE_CLEANUP, /* free or close failed after an otherwise good run */ - OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, /* an earlier job left completion uncertain */ - OMEGA_GPU_ENGINE_FAILURE_COUNT /* not a failure: number of names above */ -} OmegaGpuEngineFailure; - -/* How far a run got. Success is only SUCCESS. */ -typedef enum { - OMEGA_GPU_ENGINE_STATE_INITIAL = 0, /* nothing completed yet (device may be unopened) */ - OMEGA_GPU_ENGINE_STATE_PREPARED, - OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STATE_SUCCESS, - OMEGA_GPU_ENGINE_STATE_COUNT /* not a state: number of names above */ -} OmegaGpuEngineState; - -/* Which completion wait failed (meaningful for COMPLETION_WAIT and RELEASE_WAIT). */ -typedef enum { - OMEGA_GPU_ENGINE_WAIT_NONE = 0, - OMEGA_GPU_ENGINE_WAIT_MARKER, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_MARKER2, - OMEGA_GPU_ENGINE_WAIT_COUNT /* not a wait: number of names above */ -} OmegaGpuEngineWait; - -/* The precise step that failed (the step the run was in when it stopped). */ -typedef enum { - OMEGA_GPU_ENGINE_STEP_NONE = 0, /* no step failed (success) */ - OMEGA_GPU_ENGINE_STEP_VALIDATE, - OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK, - OMEGA_GPU_ENGINE_STEP_BLOCKED, - OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED, - OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, - OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, - OMEGA_GPU_ENGINE_STEP_ALLOC, - OMEGA_GPU_ENGINE_STEP_COPY_IN, - OMEGA_GPU_ENGINE_STEP_FILL_POISON, - OMEGA_GPU_ENGINE_STEP_BUILD, - OMEGA_GPU_ENGINE_STEP_SUBMIT, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, - OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_STEP_BARRIER, - OMEGA_GPU_ENGINE_STEP_COPY_OUT, - OMEGA_GPU_ENGINE_STEP_SCAN, - OMEGA_GPU_ENGINE_STEP_FREE, - OMEGA_GPU_ENGINE_STEP_CLOSE, - OMEGA_GPU_ENGINE_STEP_CLOCK_CHECK, /* freestanding build only: no platform clock installed */ - OMEGA_GPU_ENGINE_STEP_COUNT /* not a step: number of names above */ -} OmegaGpuEngineStep; - -/* Argument layouts the engine accepts. Later layouts are separate qualified cuts. */ -typedef enum { - OMEGA_GPU_LAYOUT_VECTOR_1D = 0, /* two inputs, one output, element_count 32-bit words each */ - OMEGA_GPU_LAYOUT_COUNT /* not a layout: number of layouts above */ -} OmegaGpuLayout; - -/* Job flags. A zero flags word means every protection ON. */ -#define OMEGA_GPU_ENGINE_FLAG_NO_C3 0x1u /* A/B control arm only: skip L2 flush and marker2 */ - -#define OMEGA_GPU_ENGINE_JOB_OUTPUTS 1u /* VECTOR_1D has exactly one output buffer */ -#define OMEGA_GPU_ENGINE_SEMAPHORE_WORDS 1u /* the vector path uses one semaphore word */ -#define OMEGA_GPU_ENGINE_DRV_TEXT_BYTES 128u - -/* Per-step timeouts in milliseconds. Never hard-coded by the engine. Each wait - * that is enabled needs a value greater than 0 (marker2_ms is ignored with NO_C3). */ -typedef struct { - uint64_t marker_ms; - uint64_t release_semaphore_ms; - uint64_t marker2_ms; - uint64_t visibility_ms; -} OmegaGpuTimeouts; - -typedef struct { - const void *program; /* encoded program bytes, already built by the caller */ - size_t program_len; /* bytes, > 0 */ - int layout; /* OmegaGpuLayout; only VECTOR_1D today */ - uint32_t element_count; /* > 0; each buffer below holds element_count 32-bit words */ - const void *input_a; /* element_count * 4 bytes */ - size_t input_a_len; - const void *input_b; /* element_count * 4 bytes */ - size_t input_b_len; - void *output; /* host destination, 4-byte aligned, element_count * 4 bytes */ - size_t output_len; - const uint32_t *poison; /* wrapper-supplied, one word per output word */ - size_t poison_count; /* must equal element_count */ - OmegaGpuTimeouts timeouts; - uint32_t flags; /* OMEGA_GPU_ENGINE_FLAG_* */ -} OmegaGpuJob; - -typedef struct { - int failure; /* OmegaGpuEngineFailure, OK on success */ - int last_state; /* last COMPLETED OmegaGpuEngineState */ - int failed_step; /* OmegaGpuEngineStep, NONE on success */ - int wait; /* OmegaGpuEngineWait, NONE unless a completion or release wait failed */ - uint64_t wait_timeout_ms; /* the configured limit of that wait */ - uint64_t waited_ms; /* how long the engine actually waited before giving up */ - int drv_rc; /* driver return code of the failing call, 0 if none */ - int err_no; /* errno captured right after the failing call, 0 if none */ - char drv_text[OMEGA_GPU_ENGINE_DRV_TEXT_BYTES]; /* driver message, NUL terminated, "" if none */ - uint32_t sync_valid; /* OMEGA_GPU_SYNC_* mask: which observed values below are meaningful */ - uint32_t marker; /* observed first marker word */ - uint32_t marker2; /* observed second marker word */ - uint32_t semaphore[OMEGA_GPU_ENGINE_SEMAPHORE_WORDS]; /* observed semaphore words */ - int retained; /* 1 when context and allocations were kept (uncertain completion) */ - int cleanup_failed; /* 1 when free or close failed (first failure is never overwritten) */ - size_t n_outputs; /* number of valid entries in output_unchanged_words */ - uint64_t output_unchanged_words[OMEGA_GPU_ENGINE_JOB_OUTPUTS]; /* words still equal to poison, per output */ -} OmegaGpuResult; - -#define OMEGA_GPU_SYNC_MARKER 0x1u -#define OMEGA_GPU_SYNC_MARKER2 0x2u -#define OMEGA_GPU_SYNC_SEMAPHORE 0x4u - -/* - * Backend seam. A fake backend implements these to drive every transition in - * host tests; the Blackwell GB10 backend (src/omega_blackwell_engine.c, later - * cut) wraps the m16_native_* calls the launchers use today. All callbacks - * must be non-NULL. Every callback returns 0 on success. The three wait - * callbacks and the barrier may also return: - */ -#define OMEGA_GPU_BACKEND_TIMEOUT 1 /* the wait ran out of time */ -#define OMEGA_GPU_BACKEND_UNKNOWN_STATE 2 /* the device reported a state the backend cannot classify */ -/* Any other nonzero value is a driver fault; the backend reports its raw driver code via diagnostics. */ - -typedef enum { - OMEGA_GPU_BUF_SCRATCH = 0, /* backend-internal: pushbuffer, marker page, QMD */ - OMEGA_GPU_BUF_PROGRAM, - OMEGA_GPU_BUF_INPUT_A, - OMEGA_GPU_BUF_INPUT_B, - OMEGA_GPU_BUF_OUTPUT, - OMEGA_GPU_BUF_ROLE_COUNT /* not a role: number of roles above */ -} OmegaGpuBufRole; - -typedef struct { - int drv_rc; - char drv_text[OMEGA_GPU_ENGINE_DRV_TEXT_BYTES]; - uint32_t sync_valid; /* OMEGA_GPU_SYNC_* */ - uint32_t marker; - uint32_t marker2; - uint32_t semaphore[OMEGA_GPU_ENGINE_SEMAPHORE_WORDS]; -} OmegaGpuBackendDiag; - -typedef struct { - void *ctx; /* passed to every callback; owned by the backend */ - int (*open_device)(void *ctx); - int (*create_channel)(void *ctx); - int (*alloc)(void *ctx, int role, size_t bytes); /* SCRATCH gets bytes == 0: the backend sizes it */ - int (*copy_in)(void *ctx, int role, const void *src, size_t bytes); - int (*fill_poison)(void *ctx, const uint32_t *words, size_t count); /* device-side output pre-fill */ - int (*build)(void *ctx, const OmegaGpuJob *job); /* descriptors, QMD, pushbuffer */ - int (*submit)(void *ctx); - int (*wait_marker)(void *ctx, uint64_t timeout_ms); - int (*wait_marker2)(void *ctx, uint64_t timeout_ms); - int (*wait_release_semaphore)(void *ctx, uint64_t timeout_ms); - int (*barrier)(void *ctx, uint64_t timeout_ms); /* visibility before readback */ - int (*copy_out)(void *ctx, void *dst, size_t bytes); - void (*diagnostics)(void *ctx, OmegaGpuBackendDiag *diag); /* driver rc, text, observed words */ - int (*free_buf)(void *ctx, int role); - int (*close)(void *ctx); -} OmegaGpuBackend; - -/* Runs one job on the process-wide default backend. See the header comment. */ -int omega_gpu_execute(const OmegaGpuJob *job, OmegaGpuResult *result); - -/* Sets the process-wide default backend (NULL clears it). The pointer must stay - * valid while it is set. With none set, omega_gpu_execute returns the defined - * stub result: INTERNAL_INVARIANT at step NOT_IMPLEMENTED. Real code sets it; - * host tests set a fake. */ -void omega_gpu_engine_set_backend(const OmegaGpuBackend *backend); - -/* 1 once an uncertain completion has blocked this process, else 0. */ -int omega_gpu_engine_is_blocked(void); - -/* TEST ONLY. Clears the block. Production code must never call this: a blocked - * process stays blocked because the GPU may still be running. */ -void omega_gpu_engine_test_reset_block(void); - -/* TEST ONLY. Forces the blocked state so tests can exercise the blocked - * result without a real uncertain completion. */ -void omega_gpu_engine_test_force_block(void); - -/* Platform time service. Installs the monotonic millisecond clock the engine - * uses to measure waited_ms. Host build: NULL restores CLOCK_MONOTONIC. - * Freestanding build (OMEGA_GPU_NO_POSIX, see src/omega_gpu_platform.h): - * there is no default; omega_gpu_execute refuses with INTERNAL_INVARIANT at - * STEP_CLOCK_CHECK until a clock is installed. Not thread safe: set it before - * any job runs. */ -void omega_gpu_engine_set_clock(uint64_t (*now_ms)(void)); - -/* TEST ONLY. Same as omega_gpu_engine_set_clock; lets host tests assert exact - * waited_ms with a fake clock. Kept so existing tests and mutants read as before. */ -void omega_gpu_engine_test_set_clock(uint64_t (*now_ms)(void)); - -/* Static name strings, never NULL. Out-of-range values give "UNKNOWN". */ -const char *omega_gpu_engine_failure_name(int failure); -const char *omega_gpu_engine_state_name(int state); -const char *omega_gpu_engine_wait_name(int wait); -const char *omega_gpu_engine_step_name(int step); - -#endif diff --git a/src/omega_gpu_fmt.c b/src/omega_gpu_fmt.c deleted file mode 100644 index 2652cc1a2..000000000 --- a/src/omega_gpu_fmt.c +++ /dev/null @@ -1,65 +0,0 @@ -/* omega_gpu_fmt.c -- see omega_gpu_fmt.h. Freestanding: stdarg only. */ -#include "omega_gpu_fmt.h" -#include -#include - -typedef struct { char *out; size_t cap, n; } Sink; - -static void put(Sink *s, char c) { - if (s->n + 1 < s->cap) s->out[s->n++] = c; -} -static void put_str(Sink *s, const char *p) { - if (!p) p = "(null)"; - while (*p) put(s, *p++); -} -static void put_u(Sink *s, unsigned long long v, unsigned base) { - char tmp[24]; - int i = 0; - do { unsigned d = (unsigned)(v % base); tmp[i++] = (char)(d < 10 ? '0' + d : 'a' + d - 10); v /= base; } while (v); - while (i) put(s, tmp[--i]); -} -static void put_d(Sink *s, long long v) { - if (v < 0) { put(s, '-'); put_u(s, (unsigned long long)(-(v + 1)) + 1ull, 10); } - else put_u(s, (unsigned long long)v, 10); -} - -int omega_gpu_fmt(char *out, size_t cap, const char *fmt, ...) { - Sink s = { out, cap, 0 }; - va_list ap; - if (!out || cap == 0) return 0; - if (!fmt) fmt = ""; - va_start(ap, fmt); - for (const char *p = fmt; *p; p++) { - if (*p != '%') { put(&s, *p); continue; } - const char *start = p++; - int l = 0, z = 0; - if (*p == 'z') { z = 1; p++; } - else while (*p == 'l' && l < 2) { l++; p++; } - switch (*p) { - case 's': put_str(&s, va_arg(ap, const char *)); break; - case 'c': put(&s, (char)va_arg(ap, int)); break; - case 'd': - if (z) put_d(&s, (long long)va_arg(ap, ptrdiff_t)); - else if (l == 2) put_d(&s, va_arg(ap, long long)); - else if (l == 1) put_d(&s, va_arg(ap, long)); - else put_d(&s, va_arg(ap, int)); - break; - case 'u': case 'x': { - unsigned base = *p == 'x' ? 16u : 10u; - if (z) put_u(&s, va_arg(ap, size_t), base); - else if (l == 2) put_u(&s, va_arg(ap, unsigned long long), base); - else if (l == 1) put_u(&s, va_arg(ap, unsigned long), base); - else put_u(&s, va_arg(ap, unsigned int), base); - break; - } - case '%': put(&s, '%'); break; - default: /* unsupported conversion: copy it literally, consume nothing */ - for (const char *q = start; q <= p && *q; q++) put(&s, *q); - if (!*p) p--; - break; - } - } - va_end(ap); - s.out[s.n] = '\0'; - return (int)s.n; -} diff --git a/src/omega_gpu_fmt.h b/src/omega_gpu_fmt.h deleted file mode 100644 index 99c903d49..000000000 --- a/src/omega_gpu_fmt.h +++ /dev/null @@ -1,10 +0,0 @@ -/* omega_gpu_fmt.h -- bounded message formatting for the freestanding GPU code (native v1 P07 cut C session - * part, aienos#286). The session and the tensor APIs format their error stages with it in both builds, so a - * stage reads the same with or without libc. Conversions: %s %c %d %u %x %ld %lu %lld %llu %zu %%; anything - * else is copied literally. Always NUL-terminates inside cap (cap > 0); truncates, never overflows. Returns - * the number of characters written (without the NUL). */ -#ifndef OMEGA_GPU_FMT_H -#define OMEGA_GPU_FMT_H -#include -int omega_gpu_fmt(char *out, size_t cap, const char *fmt, ...) __attribute__((format(printf, 3, 4))); -#endif diff --git a/src/omega_gpu_fp8_api.c b/src/omega_gpu_fp8_api.c deleted file mode 100644 index 199dab47a..000000000 --- a/src/omega_gpu_fp8_api.c +++ /dev/null @@ -1,416 +0,0 @@ -/* omega_gpu_fp8_api.c: FP8 e4m3 GEMV entry points on the shared session (OWN-30B Cut 6 / Cut 5). - * See the header. Submission path and buffer policy are the matmul API's: every buffer both sides - * touch is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will not be - * coherent with direct CPU mappings"), one launch = omega_gpu_session_launch (shader-cache - * invalidate, constant bank, QMD0/QMD1, marker, L2_FLUSH_DIRTY, second marker on uncached memory). */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_mem_cached.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_codegen_moe2.h" /* variant 2 (W-L2c) */ -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_cmdlist.h" -#include -#include - -#define CACHE_SLOTS 16 -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -struct OmegaGpuFp8Tensor { - uint32_t experts, n, k; - OmegaGpuMem w; /* experts * n * k e4m3 bytes, row-major */ - OmegaGpuMem s; /* experts * (n/128) * (k/128) f32 (scale * 2^56) */ -}; - -typedef struct { - bool valid, pinned; - uint32_t variant; /* 1 or 2: which generator built the kernel (part of the cache key) */ - OmegaFp8GemvSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - OmegaGpuScratch x_buf, y_buf; - OmegaGpuMem tab; /* group table, OMEGA_GPU_FP8_MAX_GROUPS * 16 bytes */ - uint32_t cta_budget; int cta_budget_set; - uint32_t lane_bytes, rows, warps; /* overrides, 0 = automatic */ - int depth_set; uint32_t depth; /* depth override (depth_set: 0 = automatic) */ - uint32_t gpr_pad; /* registers declared beyond the kernel's peak (diagnosis knob) */ - int mutant, no_fold, sealed; - int variant, variant_set; /* GEMV variant 1 or 2 (omega_gpu_fp8_set_variant / AIEN_OMEGA_FP8_GEMV), read once */ - int weights_cached; /* omega_gpu_fp8_set_weight_cache: uploads after it allocate GPU-cached (read-only weights) */ - int weights_cached_set; /* 0: never set, the first upload reads env AIEN_OMEGA_FP8_WEIGHT_CACHE (W-L2d: "1" = cached) */ - bool hooked; - Slot cache[CACHE_SLOTS]; - unsigned next; -} g = { .cta_budget = OMEGA_GPU_FP8_MAX_CTAS }; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -const char *omega_gpu_fp8_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_fp8_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_FP8_OK: return "OK"; - case OMEGA_GPU_FP8_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_FP8_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_FP8_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_FP8_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_FP8_NAN_WEIGHT: return "NAN_WEIGHT"; - default: return "UNKNOWN"; - } -} - -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - if (!g.cache[i].valid) continue; - omega_gpu_session_free(&g.cache[i].code); - memset(&g.cache[i], 0, sizeof g.cache[i]); - } - g.next = 0; -} -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g.x_buf); - omega_gpu_session_scratch_free(&g.y_buf); - omega_gpu_session_free(&g.tab); - g.sealed = 0; -} -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -void omega_gpu_fp8_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8_set_shape(uint32_t lb, uint32_t rows, uint32_t warps) { - omega_gpu_session_lock(); g.lane_bytes = lb; g.rows = rows; g.warps = warps; cache_clear_locked(); omega_gpu_session_unlock(); -} -void omega_gpu_fp8_set_depth(int set, uint32_t depth) { omega_gpu_session_lock(); g.depth_set = set; g.depth = depth; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8_set_gpr_pad(uint32_t pad) { omega_gpu_session_lock(); g.gpr_pad = pad; omega_gpu_session_unlock(); } -void omega_gpu_fp8_set_cta_budget(uint32_t ctas) { omega_gpu_session_lock(); g.cta_budget_set = ctas != 0; g.cta_budget = ctas ? ctas : OMEGA_GPU_FP8_MAX_CTAS; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8_test_set_no_fold(int on) { g.no_fold = on ? 1 : 0; } -void omega_gpu_fp8_seal(int on) { omega_gpu_session_lock(); g.sealed = on ? 1 : 0; omega_gpu_session_unlock(); } - -/* ---- GEMV variant (W-L2c): 1 = omega_blackwell_codegen_moe.c (default), 2 = omega_blackwell_codegen_moe2.c (row-pipelined) ---- */ -static int variant_now(void) { - if (!g.variant_set) { - const char *v = getenv("AIEN_OMEGA_FP8_GEMV"); - g.variant = (v && v[0] == '2' && v[1] == 0) ? 2 : 1; - g.variant_set = 1; - } - return g.variant; -} -void omega_gpu_fp8_set_variant(int variant) { - omega_gpu_session_lock(); - g.variant = variant == 2 ? 2 : 1; g.variant_set = 1; - cache_clear_locked(); - omega_gpu_session_unlock(); -} -int omega_gpu_fp8_variant(void) { return variant_now(); } -/* codegen by variant */ -static int prog_for(int variant, const OmegaFp8GemvSpec *spec, BlackwellIRProgram *prog) { - return variant == 2 ? omega_blackwell_codegen_fp8_gemv2_prog(spec, prog) : omega_blackwell_codegen_fp8_gemv_prog(spec, prog); -} -static int stats_for(int variant, const OmegaFp8GemvSpec *spec, uint32_t *insns, uint32_t *gprs) { - return variant == 2 ? omega_fp8_gemv2_prog_stats(spec, insns, gprs) : omega_fp8_gemv_prog_stats(spec, insns, gprs); -} -static uint32_t shared_for(int variant, const OmegaFp8GemvSpec *spec) { - return variant == 2 ? omega_fp8_gemv2_shared_bytes(spec) : omega_fp8_gemv_shared_bytes(spec); -} - -/* ---- shape choice ---- */ - -/* Largest lane width dividing k (16 for k % 512 == 0: one LDG.E.128 per row per step); one row per warp: - * the chip sweep (evidence/OWN30B-FP8-GEMV-7ce5dd4b-*, rows 1/2/4/8 one variable at a time) measured rows = 1 - * fastest at every shape (more warps and CTAs in flight on the same bytes beats fewer, wider warps). */ -void omega_gpu_fp8_shape_for(uint32_t k, uint32_t n, uint32_t *lane_bytes, uint32_t *rows, uint32_t *warps) { - uint32_t lb = k % 512u == 0 ? 16u : 8u; /* k % 256 == 0 is required (codegen refuses otherwise) */ - uint32_t r = 1; (void)n; - if (lane_bytes) *lane_bytes = g.lane_bytes ? g.lane_bytes : lb; - if (rows) *rows = g.rows ? g.rows : r; - if (warps) *warps = g.warps ? g.warps : 8u; -} - -/* ---- kernel cache (lock held, device open) ---- */ - -/* Registers declared in the QMD: the peak plus one, rounded up to a multiple of 8. Measured on the chip - * (evidence OWN30B-FP8-GEMV-c4006391, kernel log Xid 13 "Out Of Range Register"): a kernel whose peak is - * exactly 64 (top register R63) and declares 64 faults; declaring 65 runs. Every earlier kernel had a peak - * that was not a multiple of 8, so the hardware's rounding hid the rule. */ -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } /* peak + 2 rounded up to 8: the chip hung at peak + 1 (omega_blackwell_codegen.h) */ - -/* Register file: a CTA of 32 * warps threads must fit the SM's 65536 registers at the declared count. Measured - * (chip, 2026-10-13, kernel log Xid 13): the deep k=2048 kernel (72 declared) at 32 warps faults, 73728 > 65536. */ -static bool register_file_fits(uint32_t warps, uint32_t peak) { - uint32_t decl = gpr_declared(peak); - if ((uint64_t)32u * warps * decl <= 65536u) return true; - char e[160]; omega_gpu_fmt(e, sizeof e, "fp8 kernel: %u warps x %u declared registers exceed the 65536-register file", warps, decl); - omega_gpu_session_set_error(e); - return false; -} - -int omega_gpu_fp8_kernel_fits(const OmegaFp8GemvSpec *spec, uint32_t *declared) { - uint32_t peak = 0; - if (!spec || stats_for(variant_now(), spec, NULL, &peak) != 0) { omega_gpu_session_set_error("fp8 codegen refused the shape"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } - if (declared) *declared = gpr_declared(peak); - return register_file_fits(spec->warps, peak) ? OMEGA_GPU_FP8_OK : OMEGA_GPU_FP8_TOO_LARGE; -} - -static int kernel_for(const OmegaFp8GemvSpec *spec, Slot **out, bool *hit) { - const uint32_t variant = (uint32_t)variant_now(); - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - Slot *s = &g.cache[i]; - if (s->valid && s->variant == variant && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_FP8_OK; } - } - if (g.sealed) { - char e[160]; - omega_gpu_fmt(e, sizeof e, "serving reservation exceeded: fp8 kernel k=%u lb=%u rows=%u warps=%u was not prepared", - spec->k, spec->lane_bytes, spec->rows, spec->warps); - omega_gpu_session_set_error(e); - return OMEGA_GPU_FP8_TOO_LARGE; - } - Slot *s = NULL; - for (unsigned i = 0; i < CACHE_SLOTS && !s; i++) { - Slot *c = &g.cache[(g.next + i) % CACHE_SLOTS]; - if (!c->valid || !c->pinned) { s = c; g.next = (unsigned)((c - g.cache) + 1) % CACHE_SLOTS; } - } - if (!s) { omega_gpu_session_set_error("fp8 kernel cache: every slot holds a prepared kernel"); return OMEGA_GPU_FP8_TOO_LARGE; } - /* record path: a recorded launch may still point at the slot's code until the list is submitted */ - if (g_rec && s->valid) { omega_gpu_session_set_error("fp8 record: kernel cache miss would evict a resident kernel (warm up before recording)"); return OMEGA_GPU_FP8_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("fp8 codegen: host memory"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } - int cg = prog_for((int)variant, spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("fp8 codegen refused the shape"); return OMEGA_GPU_FP8_CODEGEN_FAIL; } - if (!register_file_fits(spec->warps, prog->regalloc.peak_gpr_usage)) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - s->valid = true; s->variant = variant; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_FP8_OK; -} - -/* Deep kernel (x' staged in shared memory, every load of the row issued at once) whenever the whole row fits - * the budgets (rows * KS * lane_bytes <= 128, i.e. rows * k <= 4096) and the staging rounds are exact; else the step-by-step kernel. */ -uint32_t omega_gpu_fp8_depth_for(const OmegaFp8GemvSpec *spec, uint32_t n, uint32_t groups) { - if (g.depth_set) return g.depth; - uint32_t ks = spec->k / (32u * spec->lane_bytes); - if (ks * spec->rows * spec->lane_bytes > 128u || spec->k % (32u * spec->warps) || spec->k > 512u * spec->warps) return 0; - /* Measured (evidence OWN30B-FP8-GEMV-fc05176a-*, main vs depth0 in one run): the deep kernel wins on single - * projections up to a few MB (gate+up 1536x2048: 30 us vs 51; k_proj: 30 vs 44) and loses on the grouped - * 8-expert launches (its per-CTA x staging re-reads 8 KB per CTA: 188 us vs 150) and on o_proj (79 vs 64). */ - if (groups != 1u || (uint64_t)n * spec->k > (4u << 20)) return 0; - OmegaFp8GemvSpec deep = *spec; deep.depth = ks; deep.mutant = 0; - uint32_t peak = 0; - if (omega_fp8_gemv_prog_stats(&deep, NULL, &peak) != 0 || (uint64_t)32u * spec->warps * gpr_declared(peak) > 65536u) return 0; - return ks; -} - -static void spec_for(uint32_t k, uint32_t n, uint32_t groups, OmegaFp8GemvSpec *spec) { - memset(spec, 0, sizeof *spec); - spec->k = k; - omega_gpu_fp8_shape_for(k, n, &spec->lane_bytes, &spec->rows, &spec->warps); - /* Grouped launches (8 experts): 32 warps per CTA and few CTAs per group (OMEGA_GPU_FP8_GROUPED_CTAS, one per SM - * for 8 groups) measured fastest: down 2048x768 x 8 went from 181 us (256 x 8 CTAs of 8 warps) to 90 us - * (4..6 x 8 CTAs of 32 warps); gate+up 146 -> 140 us (probe logs listed in ~/handoffs/own30b-K-report.md). */ - if (groups > 1u && !g.warps) spec->warps = 32u; - if (variant_now() == 2) { - /* variant 2 (W-L2c): 16 warps per CTA (two CTAs per SM at its register count) for every launch unless overridden; - * the whole row group is always in flight (depth = KS, informational: the generator ignores the field). */ - if (!g.warps) spec->warps = OMEGA_GPU_FP8_V2_WARPS; - spec->depth = spec->k / (32u * spec->lane_bytes); - } else spec->depth = omega_gpu_fp8_depth_for(spec, n, groups); - spec->mutant = g.mutant; -} - -int omega_gpu_fp8_prepare(uint32_t k) { - OmegaFp8GemvSpec spec; spec_for(k, 1u << 20, 1, &spec); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_FP8_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_FP8_CHIP_FAIL; - else { Slot *s = NULL; bool hit = false; rc = kernel_for(&spec, &s, &hit); if (rc == OMEGA_GPU_FP8_OK) s->pinned = true; } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- tensors ---- */ - -void omega_gpu_fp8_tensor_shape(const OmegaGpuFp8Tensor *t, uint32_t *experts, uint32_t *n, uint32_t *k) { - if (experts) *experts = t ? t->experts : 0; - if (n) *n = t ? t->n : 0; - if (k) *k = t ? t->k : 0; -} - -int omega_gpu_fp8_tensor_upload(uint32_t experts, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *scale, OmegaGpuFp8Tensor **out) { - if (out) *out = NULL; - if (!w || !scale || !out || experts == 0 || n == 0 || k == 0 || n % OMEGA_FP8_BLOCK || k % OMEGA_FP8_BLOCK) return OMEGA_GPU_FP8_BAD_ARGS; - if (k > OMEGA_FP8_MAX_K) return OMEGA_GPU_FP8_TOO_LARGE; - const size_t wbytes = (size_t)experts * n * k, scount = (size_t)experts * (n / OMEGA_FP8_BLOCK) * (k / OMEGA_FP8_BLOCK); - size_t first = 0; - if (omega_fp8_pack_scan_nan(w, wbytes, &first)) { - char e[120]; omega_gpu_fmt(e, sizeof e, "fp8 upload: e4m3 NaN code at byte %zu", first); - omega_gpu_session_set_error(e); - return OMEGA_GPU_FP8_NAN_WEIGHT; - } - OmegaGpuFp8Tensor *t = omega_gpu_host_calloc(1, sizeof *t); - if (!t) return OMEGA_GPU_FP8_BAD_ARGS; - t->experts = experts; t->n = n; t->k = k; - int rc = OMEGA_GPU_FP8_OK; - omega_gpu_session_lock(); - if (!g.weights_cached_set) { const char *v = getenv("AIEN_OMEGA_FP8_WEIGHT_CACHE"); g.weights_cached = (v && v[0] == '1' && v[1] == 0) ? 1 : 0; g.weights_cached_set = 1; } - int (*const alloc)(size_t, OmegaGpuMem *) = g.weights_cached ? omega_gpu_session_alloc_cached : omega_gpu_session_alloc; - if (!dev_open_locked() || alloc(wbytes, &t->w) != 0 || alloc(scount * 4u, &t->s) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_FP8_OK) { - memcpy(t->w.cpu, w, wbytes); - if (omega_fp8_pack_scales(scale, scount, t->s.cpu, g.no_fold) != 0) { omega_gpu_session_set_error("fp8 upload: NaN, inf or overflowing scale"); rc = OMEGA_GPU_FP8_BAD_ARGS; } - else if (omega_gpu_session_sync_to_gpu(&t->w) != 0 || omega_gpu_session_sync_to_gpu(&t->s) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - } - if (rc != OMEGA_GPU_FP8_OK) { omega_gpu_fp8_tensor_free(t); return rc; } - *out = t; - return OMEGA_GPU_FP8_OK; -} - -void omega_gpu_fp8_tensor_free(OmegaGpuFp8Tensor *t) { - if (!t) return; - omega_gpu_session_lock(); - if (t->w.cpu) omega_gpu_session_free(&t->w); - if (t->s.cpu) omega_gpu_session_free(&t->s); - omega_gpu_session_unlock(); - omega_gpu_host_free(t); -} - -/* ---- the GEMV (lock held inside) ---- */ - -/* dev_tab / dev_x non-zero: the group table / the x' row already sit on the device (written by the router launch). - * rec non-NULL (record path, caller holds the session lock): dev_tab, dev_x and dev_y are required, the launch is - * appended to rec instead of submitted, and nothing is staged, poisoned or read back (the list's per-launch semaphore - * and the caller's end-of-token checks replace the poison check). */ -static int gemv_core(const OmegaGpuFp8Tensor *t, uint32_t groups, const uint32_t *ids, const float *x32, const uint16_t *x16, - uint32_t x_rows, float *y, OmegaGpuFp8Info *info, uint64_t dev_tab, uint64_t dev_x, - OmegaGpuCmdList *rec, uint64_t dev_y) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (rec && (!dev_tab || !dev_x || !dev_y)) return OMEGA_GPU_FP8_BAD_ARGS; - if (!t || !t->w.cpu || (!ids && !dev_tab) || (!x32 && !x16 && !dev_x) || (!y && !rec) || groups == 0 || (x_rows != 1 && x_rows != groups)) return OMEGA_GPU_FP8_BAD_ARGS; - if (groups > OMEGA_GPU_FP8_MAX_GROUPS) return OMEGA_GPU_FP8_TOO_LARGE; - if (!dev_tab) for (uint32_t gi = 0; gi < groups; gi++) if (ids[gi] >= t->experts) return OMEGA_GPU_FP8_BAD_ARGS; - const uint32_t n = t->n, k = t->k; - OmegaFp8GemvSpec spec; spec_for(k, n, groups, &spec); - if (n % spec.rows) return OMEGA_GPU_FP8_CODEGEN_FAIL; - const uint32_t RG = n / spec.rows; - uint32_t grid_x = (RG + spec.warps - 1) / spec.warps; - const int variant = variant_now(); - uint32_t budget = g.cta_budget_set ? g.cta_budget : (groups > 1u ? (variant == 2 ? OMEGA_GPU_FP8_V2_GROUPED_CTAS : OMEGA_GPU_FP8_GROUPED_CTAS) : OMEGA_GPU_FP8_MAX_CTAS); - if (grid_x > budget) grid_x = budget; - if (grid_x == 0) grid_x = 1; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - int rc = OMEGA_GPU_FP8_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_FP8_CHIP_FAIL; } - if (!rec) { /* staging buffers: the record path reads and writes only the caller's device buffers */ - if (!g.tab.cpu && omega_gpu_session_alloc((size_t)OMEGA_GPU_FP8_MAX_GROUPS * 16u, &g.tab) != 0) { UNLOCK(); return OMEGA_GPU_FP8_CHIP_FAIL; } - int src = omega_gpu_session_scratch(&g.x_buf, (size_t)x_rows * k * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)groups * n * 4u); - if (src != 0) { UNLOCK(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_FP8_TOO_LARGE : OMEGA_GPU_FP8_CHIP_FAIL; } - } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_FP8_OK) { UNLOCK(); return rc; } - - /* group table: {w_va, s_va} per group */ - uint64_t *tab = g.tab.cpu; - const uint64_t wstride = (uint64_t)n * k, sstride = (uint64_t)(n / OMEGA_FP8_BLOCK) * (k / OMEGA_FP8_BLOCK) * 4u; - if (!dev_tab) for (uint32_t gi = 0; gi < groups; gi++) { tab[2 * gi] = t->w.va + ids[gi] * wstride; tab[2 * gi + 1] = t->s.va + ids[gi] * sstride; } - /* x' rows, y poisoned */ - float *xd = g.x_buf.mem.cpu, *yd = g.y_buf.mem.cpu; - for (uint32_t r = 0; r < x_rows && !dev_x; r++) { - if (x32) omega_fp8_pack_x_f32(x32 + (size_t)r * k, k, xd + (size_t)r * k); - else omega_fp8_pack_x_bf16(x16 + (size_t)r * k, k, xd + (size_t)r * k); - } - if (!rec) { - for (size_t i = 0; i < (size_t)groups * n; i++) yd[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g.tab) != 0 || omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - } - - uint32_t args[OMEGA_FP8_ARGS_WORDS]; - const uint64_t tab_va = dev_tab ? dev_tab : g.tab.va, x_va = dev_x ? dev_x : g.x_buf.mem.va, y_va = rec ? dev_y : g.y_buf.mem.va; - args[0] = (uint32_t)tab_va; args[1] = (uint32_t)(tab_va >> 32); - args[2] = (uint32_t)x_va; args[3] = (uint32_t)(x_va >> 32); - args[4] = (uint32_t)y_va; args[5] = (uint32_t)(y_va >> 32); - args[6] = RG; args[7] = x_rows == 1 ? 0u : k * 4u; args[8] = n * 4u; args[9] = grid_x * spec.warps; - if (info) { - info->experts = t->experts; info->n = n; info->k = k; info->groups = groups; - info->lane_bytes = spec.lane_bytes; info->rows_per_warp = spec.rows; info->warps_per_cta = spec.warps; info->depth = spec.depth; - info->grid_x = grid_x; info->grid_y = groups; info->steps = omega_fp8_gemv_steps(&spec); - info->weight_bytes = (uint64_t)groups * wstride; info->scale_bytes = (uint64_t)groups * sstride; - info->kernel_cache_hit = hit; - (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; - } - if (rc == OMEGA_GPU_FP8_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count) + g.gpr_pad, - .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = grid_x, .grid_y = groups, - .num_elements = (size_t)groups * n, - .args = args, .n_args = OMEGA_FP8_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = shared_for(variant, &spec), - }; - if (L.gpr_count < ks->kernel.gpr_count + 2u) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_FP8_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - } - if (rc == OMEGA_GPU_FP8_OK && !rec && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - if (rc == OMEGA_GPU_FP8_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < (size_t)groups * n; i++) if (yd[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("output poison survived"); rc = OMEGA_GPU_FP8_CHIP_FAIL; } - else memcpy(y, yd, (size_t)groups * n * sizeof *y); - } - UNLOCK(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} -#undef UNLOCK - -int omega_gpu_fp8_gemv_f32(const OmegaGpuFp8Tensor *t, uint32_t expert, const float *x, float *y, OmegaGpuFp8Info *info) { - return gemv_core(t, 1, &expert, x, NULL, 1, y, info, 0, 0, NULL, 0); -} -int omega_gpu_fp8_gemv_bf16(const OmegaGpuFp8Tensor *t, uint32_t expert, const uint16_t *x, float *y, OmegaGpuFp8Info *info) { - return gemv_core(t, 1, &expert, NULL, x, 1, y, info, 0, 0, NULL, 0); -} -int omega_gpu_fp8_gemv_grouped_f32(const OmegaGpuFp8Tensor *t, uint32_t groups, const uint32_t *ids, const float *x, uint32_t x_rows, float *y, OmegaGpuFp8Info *info) { - return gemv_core(t, groups, ids, x, NULL, x_rows, y, info, 0, 0, NULL, 0); -} -int omega_gpu_fp8_gemv_grouped_dev(const OmegaGpuFp8Tensor *t, uint32_t groups, uint64_t tab_va, uint64_t x_va, float *y, OmegaGpuFp8Info *info) { - if (!tab_va || !x_va) return OMEGA_GPU_FP8_BAD_ARGS; - return gemv_core(t, groups, NULL, NULL, NULL, 1, y, info, tab_va, x_va, NULL, 0); -} -int omega_gpu_fp8_tensor_entry(const OmegaGpuFp8Tensor *t, uint32_t expert, uint64_t *w_va, uint64_t *s_va) { - if (!t || !t->w.cpu || expert >= t->experts || !w_va || !s_va) return OMEGA_GPU_FP8_BAD_ARGS; - *w_va = t->w.va + (uint64_t)expert * t->n * t->k; - *s_va = t->s.va + (uint64_t)expert * (t->n / OMEGA_FP8_BLOCK) * (t->k / OMEGA_FP8_BLOCK) * 4u; - return OMEGA_GPU_FP8_OK; -} - -/* Record path (OWN-30B W-L2a decode graph): the launch of omega_gpu_fp8_gemv_grouped_dev appended to cl, every input - * and the output in device memory. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_fp8_gemv_grouped_record(OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t groups, uint64_t tab_va, - uint64_t x_va, uint32_t x_rows, uint64_t y_va) { - if (!cl) return OMEGA_GPU_FP8_BAD_ARGS; - return gemv_core(t, groups, NULL, NULL, NULL, x_rows, NULL, NULL, tab_va, x_va, cl, y_va); -} - -/* ---- weight cache policy (OWN-30B L2 kernel-time cut) ---- */ -void omega_gpu_fp8_set_weight_cache(int on) { omega_gpu_session_lock(); g.weights_cached = on ? 1 : 0; g.weights_cached_set = 1; omega_gpu_session_unlock(); } -int omega_gpu_fp8_weight_cache(void) { return g.weights_cached; } diff --git a/src/omega_gpu_fp8_api.h b/src/omega_gpu_fp8_api.h deleted file mode 100644 index 1e848d8f1..000000000 --- a/src/omega_gpu_fp8_api.h +++ /dev/null @@ -1,182 +0,0 @@ -#ifndef OMEGA_GPU_FP8_API_H -#define OMEGA_GPU_FP8_API_H -/* - * omega_gpu_fp8_api: native (no CUDA) FP8 e4m3 block-scaled GEMV for the OWN-30B lane - * (Cut 6: m = 1 decode GEMV; Cut 5: grouped experts, one launch for the selected experts). - * New file on the shared session (omega_gpu_session.h); no existing API file changes. - * - * ============ C signatures and semantics (for the Rust binding) ============ - * - * typedef struct OmegaGpuFp8Tensor OmegaGpuFp8Tensor; // opaque, device resident - * - * int omega_gpu_fp8_tensor_upload(uint32_t experts, uint32_t n, uint32_t k, - * const uint8_t *w, const uint16_t *scale_inv_bf16, - * OmegaGpuFp8Tensor **out); - * w: experts * n * k bytes, e4m3, row-major [expert][n][k] (n output rows, k input columns): - * exactly the checkpoint's `weight` for one projection, experts concatenated (the sc - * capsule GATE_UP [128][1536][2048] and DOWN [128][2048][768] layouts; attention - * projections have experts = 1, e.g. q_proj [4096][2048]). - * scale_inv_bf16: experts * (n/128) * (k/128) bf16, [expert][n/128][k/128] (`weight_scale_inv`). - * Requires n % 128 == 0, k % 128 == 0, 128 <= k <= 16384, experts >= 1. Refuses any e4m3 NaN - * code (0x7F, 0xFF) in w with OMEGA_GPU_FP8_NAN_WEIGHT (nothing uploaded), a NaN/inf scale with - * BAD_ARGS. Weights are copied byte for byte (no reorder); scales are stored as f32 * 2^56. - * Opens the device on first use. Resident until omega_gpu_fp8_tensor_free. - * - * int omega_gpu_fp8_gemv_f32 (const OmegaGpuFp8Tensor *t, uint32_t expert, const float *x, float *y, OmegaGpuFp8Info *info); - * int omega_gpu_fp8_gemv_bf16(const OmegaGpuFp8Tensor *t, uint32_t expert, const uint16_t *x, float *y, OmegaGpuFp8Info *info); - * y[r] = sum_c W[expert][r][c] * x[c] * scale[expert][r/128][c/128], r < n, c < k. f32 accumulate. - * x: k values (f32, or bf16 bits), y: n f32. One launch. info may be NULL. - * - * int omega_gpu_fp8_gemv_grouped_f32(const OmegaGpuFp8Tensor *t, uint32_t groups, const uint32_t *expert_ids, - * const float *x, uint32_t x_rows, float *y, OmegaGpuFp8Info *info); - * One launch for `groups` experts (1..OMEGA_GPU_FP8_MAX_GROUPS, each id < experts, repeats allowed): - * y[g][r] = sum_c W[expert_ids[g]][r][c] * x[g'][c] * scale[...], with g' = 0 when x_rows == 1 - * (one activation row shared by every group: the gate+up projections of 8 experts) or g' = g when - * x_rows == groups (one row per group: the down projections). x: x_rows * k f32, y: groups * n f32. - * The m = 1 call above is this call with groups = 1. - * - * int omega_gpu_fp8_prepare(uint32_t k); build and pin the kernel for width k now (serving). - * void omega_gpu_fp8_tensor_free(OmegaGpuFp8Tensor *t); - * void omega_gpu_fp8_tensor_shape(const OmegaGpuFp8Tensor *t, uint32_t *experts, uint32_t *n, uint32_t *k); - * const char *omega_gpu_fp8_rc_name(int rc); const char *omega_gpu_fp8_last_error(void); - * - * Return codes: 0 OK; negative OMEGA_GPU_FP8_* below. An uncertain completion latches the process - * (every later call of every API returns CHIP_FAIL), as the other APIs do. - * - * Every output word is poisoned before the launch and the call refuses a result that still holds - * poison (CHIP_FAIL "output poison survived"). No host oracle runs inside the call (speed); the test - * holds the reference (omega_fp8_gemv_oracle below). - */ -#include -#include -#include -#include "omega_blackwell_codegen_moe.h" /* OmegaFp8GemvSpec (depth query) */ - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_FP8_OK = 0, - OMEGA_GPU_FP8_BAD_ARGS = -1, /* NULL, zero or misaligned dimension, bad expert id, out of host memory */ - OMEGA_GPU_FP8_TOO_LARGE = -2, /* k past OMEGA_FP8_MAX_K, groups past the table, sealed cache miss */ - OMEGA_GPU_FP8_CODEGEN_FAIL = -3, /* our codegen refused the shape */ - OMEGA_GPU_FP8_CHIP_FAIL = -4, /* device open, alloc, submit, marker or output-written check failed */ - OMEGA_GPU_FP8_NAN_WEIGHT = -5 /* an e4m3 NaN code in the weights (refused at upload) */ -}; - -#define OMEGA_GPU_FP8_MAX_GROUPS 64u -#define OMEGA_GPU_FP8_MAX_CTAS 256u /* default CTA budget per group for a single projection; the elementwise and attention rows paths proved 1024 */ -#define OMEGA_GPU_FP8_GROUPED_CTAS 6u /* CTAs per group for a grouped launch (32 warps each): measured best for 8 experts */ - -typedef struct { - uint32_t experts, n, k, groups; - uint32_t lane_bytes, rows_per_warp, warps_per_cta; /* kernel shape chosen for the call */ - uint32_t depth; /* 0: step-by-step kernel; D: deep kernel, D K steps of loads in flight, x' in shared memory */ - uint32_t grid_x, grid_y, steps; - uint64_t weight_bytes; /* e4m3 bytes the launch reads (groups * n * k) */ - uint64_t scale_bytes; /* f32 scale words it reads */ - uint64_t elapsed_ns; /* chip submit-to-second-marker */ - uint64_t call_ns; /* whole API call */ - uint32_t completion_marker; - bool kernel_cache_hit; - char target_chip[64]; - uint32_t sm_architecture; -} OmegaGpuFp8Info; - -typedef struct OmegaGpuFp8Tensor OmegaGpuFp8Tensor; - -int omega_gpu_fp8_tensor_upload(uint32_t experts, uint32_t n, uint32_t k, const uint8_t *w, - const uint16_t *scale_inv_bf16, OmegaGpuFp8Tensor **out); -void omega_gpu_fp8_tensor_free(OmegaGpuFp8Tensor *t); -void omega_gpu_fp8_tensor_shape(const OmegaGpuFp8Tensor *t, uint32_t *experts, uint32_t *n, uint32_t *k); - -int omega_gpu_fp8_gemv_f32(const OmegaGpuFp8Tensor *t, uint32_t expert, const float *x, float *y, OmegaGpuFp8Info *info); -int omega_gpu_fp8_gemv_bf16(const OmegaGpuFp8Tensor *t, uint32_t expert, const uint16_t *x, float *y, OmegaGpuFp8Info *info); -int omega_gpu_fp8_gemv_grouped_f32(const OmegaGpuFp8Tensor *t, uint32_t groups, const uint32_t *expert_ids, - const float *x, uint32_t x_rows, float *y, OmegaGpuFp8Info *info); -/* Device-resident inputs (OWN-30B router, 2026-10-13): the group table ({w_va, s_va} per group, `groups` entries) and - * the single x' row (f32, k values, already * 2^64) are read from tab_va / x_va, which another launch (the router) - * wrote; no host copy of either. y and the poison check as above. */ -int omega_gpu_fp8_gemv_grouped_dev(const OmegaGpuFp8Tensor *t, uint32_t groups, uint64_t tab_va, uint64_t x_va, float *y, OmegaGpuFp8Info *info); -/* Record path (OWN-30B W-L2a, decode graph; omega_gpu_cmdlist.h): the same launch as grouped_dev, appended to cl instead - * of submitted. tab_va: `groups` {w_va, s_va} entries (omega_gpu_fp8_tensor_entry, or the router's table); x_va: x_rows - * rows of k f32 already * 2^64 (1 row shared, or one per group); y_va: groups * n f32, written when the list runs. - * The caller holds omega_gpu_session_lock() (do not call another API's non-record entry point while holding it). - * Nothing is staged, poisoned or read back: the list's per-launch semaphore check and the caller's end-of-token checks - * replace the poison check. A kernel cache miss that would evict a resident kernel is refused (TOO_LARGE): warm the - * shape up with one non-record call before recording. */ -struct OmegaGpuCmdList; -int omega_gpu_fp8_gemv_grouped_record(struct OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t groups, uint64_t tab_va, - uint64_t x_va, uint32_t x_rows, uint64_t y_va); -/* Device addresses of one expert's weights and scales (for a directory the router copies from). */ -int omega_gpu_fp8_tensor_entry(const OmegaGpuFp8Tensor *t, uint32_t expert, uint64_t *w_va, uint64_t *s_va); - -/* Serving: build and pin the kernel for width k (the one the automatic shape choice uses for that k). */ -int omega_gpu_fp8_prepare(uint32_t k); -/* on = 1: a call whose kernel is not cached is refused with TOO_LARGE instead of built. */ -void omega_gpu_fp8_seal(int on); - -const char *omega_gpu_fp8_rc_name(int rc); -const char *omega_gpu_fp8_last_error(void); -void omega_gpu_fp8_cache_clear(void); - -/* ---- measurement knobs (tests; each clears the kernel cache) ---- */ -/* Kernel shape override: lane_bytes 8/16, rows 1/2/4/8, warps 1..32; 0 = automatic. */ -void omega_gpu_fp8_set_shape(uint32_t lane_bytes, uint32_t rows_per_warp, uint32_t warps_per_cta); -/* Kernel depth override: set = 0 automatic (deep for a single projection of at most 4 MiB whose row fits: rows * k <= 4096), set = 1 forces `depth` - * (0 = step-by-step kernel). Each call clears the kernel cache. */ -void omega_gpu_fp8_set_depth(int set, uint32_t depth); -/* The depth the automatic choice makes for a spec (k, lane_bytes, rows, warps filled in), n rows, `groups` experts: - * deep only for a single projection of at most 4 MiB of weights (measured, see omega_gpu_fp8_api.c). */ -uint32_t omega_gpu_fp8_depth_for(const OmegaFp8GemvSpec *spec, uint32_t n, uint32_t groups); -/* Register-file check for a spec (chip-found rule: 32 * warps * declared registers <= 65536, declared = peak + 1 rounded - * up to 8). OK, TOO_LARGE (last_error names the counts) or CODEGEN_FAIL. The automatic depth choice and every build apply it. */ -int omega_gpu_fp8_kernel_fits(const OmegaFp8GemvSpec *spec, uint32_t *declared); -/* CTAs per group per launch (0 restores the automatic choice: MAX_CTAS single, GROUPED_CTAS grouped). */ -void omega_gpu_fp8_set_cta_budget(uint32_t ctas); -/* 1: tensors uploaded from now on live in GPU-cached memory (read-only weights; omega_gpu_mem_cached.h). Default 0: - * GPU-uncached like every session buffer. Tensors already uploaded keep their policy. Never set: the first upload reads env - * AIEN_OMEGA_FP8_WEIGHT_CACHE ("1" = cached; W-L2d, so sc can switch it without a code change). */ -void omega_gpu_fp8_set_weight_cache(int on); -/* GEMV variant (W-L2c, 2026-10-14): 1 = omega_blackwell_codegen_moe.c (the default, unchanged), 2 = omega_blackwell_codegen_moe2.c - * (row-pipelined: the whole row group in flight per warp and the next row group's loads in flight while this one is multiplied; - * same arithmetic order, y bit-identical). Read once from AIEN_OMEGA_FP8_GEMV ("2") at the first call unless set here first. - * Each call clears the kernel cache. Variant 2 defaults: OMEGA_GPU_FP8_V2_WARPS warps per CTA, OMEGA_GPU_FP8_V2_GROUPED_CTAS CTAs - * per group for grouped launches (the shape and budget knobs above still override). */ -void omega_gpu_fp8_set_variant(int variant); -int omega_gpu_fp8_variant(void); -#define OMEGA_GPU_FP8_V2_WARPS 16u -#define OMEGA_GPU_FP8_V2_GROUPED_CTAS 12u -int omega_gpu_fp8_weight_cache(void); -/* Diagnosis: declare `pad` registers beyond the kernel's peak in the QMD (0 = exact peak). */ -void omega_gpu_fp8_set_gpr_pad(uint32_t pad); -/* TEST ONLY: deliberately wrong kernels (1 scale dropped, 2 scale block never advances, 3 group table entry - * of cy ^ 1). The parity test must catch each. Production never calls this. */ -void omega_gpu_fp8_test_set_mutant(int mutant); -/* TEST ONLY: upload scales without the 2^56 fold (host-side mutant; the parity test must catch it). */ -void omega_gpu_fp8_test_set_no_fold(int on); -/* The spec the API would pick for (k, n): for tests and the bandwidth table. */ -void omega_gpu_fp8_shape_for(uint32_t k, uint32_t n, uint32_t *lane_bytes, uint32_t *rows_per_warp, uint32_t *warps_per_cta); - -/* ---- host helpers (omega_gpu_fp8_pack.c), no device ---- */ -/* Reference e4m3 decode (port of sc fp8_e4m3fn_to_f32: bias 7, subnormal m * 2^-9, NaN for 0x7f / 0xff). */ -float omega_fp8_e4m3_ref(uint8_t b); -/* The kernel's conversion: f32 bits equal to e4m3(b) * 2^-120 (wrong for the NaN codes, which are refused). */ -uint32_t omega_fp8_e4m3_kernel_bits(uint8_t b); -int omega_fp8_e4m3_is_nan(uint8_t b); -/* NaN codes in w; first = index of the first one. */ -size_t omega_fp8_pack_scan_nan(const uint8_t *w, size_t count, size_t *first); -/* bf16 scales -> f32 * 2^56 (mutant_no_fold: * 1). -1 on a NaN/inf scale or fold overflow. */ -int omega_fp8_pack_scales(const uint16_t *bf16, size_t count, float *out, int mutant_no_fold); -void omega_fp8_pack_x_f32(const float *x, uint32_t k, float *out); -void omega_fp8_pack_x_bf16(const uint16_t *x, uint32_t k, float *out); -/* Host oracle in double: y[r] = sum_c ref(w[r][c]) * x[c] * bf16(scale[r/128][c/128]); yscale[r] = sum |terms| - * (the accumulation scale a relative tolerance is measured against). w: n x k, scales (n/128) x (k/128). */ -void omega_fp8_gemv_oracle(const uint8_t *w, const uint16_t *scale_bf16, uint32_t n, uint32_t k, - const float *x, double *y, double *yscale); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_fp8_pack.c b/src/omega_gpu_fp8_pack.c deleted file mode 100644 index 2b67ea271..000000000 --- a/src/omega_gpu_fp8_pack.c +++ /dev/null @@ -1,74 +0,0 @@ -/* omega_gpu_fp8_pack.c: host side of the FP8 e4m3 GEMV (OWN-30B Cut 6). See omega_gpu_fp8_api.h. - * - * The weight bytes keep the checkpoint's row-major [n][k] order on the device (a warp reads - * 32 * lane_bytes contiguous bytes of a row per step), so "packing" is: refuse the two e4m3 NaN - * codes, convert the bf16 scale grid to f32 times 2^OMEGA_FP8_SCALE_EXP, and stage x as f32 times - * 2^OMEGA_FP8_X_EXP. All three are exact (powers of two; refused on overflow). */ -#include "omega_gpu_fp8_api.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_matmul.h" -#include -#include - -float omega_fp8_e4m3_ref(uint8_t b) { - int exponent = (b >> 3) & 0x0f; - float mantissa = (float)(b & 0x07); - float sign = (b & 0x80) ? -1.0f : 1.0f; - if (exponent == 0x0f && (b & 0x07) == 0x07) return NAN; /* 0x7f / 0xff */ - if (exponent == 0) return sign * mantissa * ldexpf(1.0f, -9); - return sign * (1.0f + mantissa / 8.0f) * ldexpf(1.0f, exponent - 7); -} - -uint32_t omega_fp8_e4m3_kernel_bits(uint8_t b) { - return ((uint32_t)(b & 0x7fu) << 20) | ((uint32_t)(b & 0x80u) << 24); -} - -int omega_fp8_e4m3_is_nan(uint8_t b) { return (b & 0x7fu) == 0x7fu; } - -size_t omega_fp8_pack_scan_nan(const uint8_t *w, size_t count, size_t *first) { - size_t n = 0; - for (size_t i = 0; i < count; i++) - if (omega_fp8_e4m3_is_nan(w[i])) { if (n == 0 && first) *first = i; n++; } - return n; -} - -int omega_fp8_pack_scales(const uint16_t *bf16, size_t count, float *out, int mutant_no_fold) { - const float fold = mutant_no_fold ? 1.0f : ldexpf(1.0f, OMEGA_FP8_SCALE_EXP); - for (size_t i = 0; i < count; i++) { - float s = omega_bf16_to_fp32(bf16[i]); - if (!(fabsf(s) <= 3.0e38f)) return -1; /* NaN or inf scale */ - float f = s * fold; - if (!(fabsf(f) <= 3.0e38f)) return -1; /* fold overflow */ - out[i] = f; - } - return 0; -} - -void omega_fp8_pack_x_f32(const float *x, uint32_t k, float *out) { - const float fold = ldexpf(1.0f, OMEGA_FP8_X_EXP); - for (uint32_t i = 0; i < k; i++) out[i] = x[i] * fold; -} - -void omega_fp8_pack_x_bf16(const uint16_t *x, uint32_t k, float *out) { - const float fold = ldexpf(1.0f, OMEGA_FP8_X_EXP); - for (uint32_t i = 0; i < k; i++) out[i] = omega_bf16_to_fp32(x[i]) * fold; -} - -void omega_fp8_gemv_oracle(const uint8_t *w, const uint16_t *scale_bf16, uint32_t n, uint32_t k, - const float *x, double *y, double *yscale) { - const uint32_t kb = k / OMEGA_FP8_BLOCK; - for (uint32_t r = 0; r < n; r++) { - double acc = 0.0, mag = 0.0; - const uint8_t *row = w + (size_t)r * k; - const uint16_t *srow = scale_bf16 + (size_t)(r / OMEGA_FP8_BLOCK) * kb; - for (uint32_t b = 0; b < kb; b++) { - double s = (double)omega_bf16_to_fp32(srow[b]); - for (uint32_t c = b * OMEGA_FP8_BLOCK; c < (b + 1) * OMEGA_FP8_BLOCK; c++) { - double p = (double)omega_fp8_e4m3_ref(row[c]) * (double)x[c] * s; - acc += p; mag += fabs(p); - } - } - y[r] = acc; - if (yscale) yscale[r] = mag; - } -} diff --git a/src/omega_gpu_fp8gemm_api.c b/src/omega_gpu_fp8gemm_api.c deleted file mode 100644 index a2c436667..000000000 --- a/src/omega_gpu_fp8gemm_api.c +++ /dev/null @@ -1,256 +0,0 @@ -/* omega_gpu_fp8gemm_api.c: FP8 grouped GEMM for prefill on the shared session (OWN-30B builder F item 26). - * See the header. Submission path and buffer policy are the FP8 GEMV API's: every buffer both sides touch is - * GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE), one launch = omega_gpu_session_launch. */ -#include "omega_gpu_fp8gemm_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include -#include - -#define CACHE_SLOTS 8 -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -typedef struct { - bool valid, pinned; - OmegaFp8GemmSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - OmegaGpuScratch x_buf, y_buf, seg_buf; - uint32_t mt, warps, ctas; - int mutant; - bool hooked; - Slot cache[CACHE_SLOTS]; - unsigned next; -} g; - -const char *omega_gpu_fp8gemm_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_fp8gemm_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_FP8GEMM_OK: return "OK"; - case OMEGA_GPU_FP8GEMM_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_FP8GEMM_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_FP8GEMM_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_FP8GEMM_CHIP_FAIL: return "CHIP_FAIL"; - default: return "UNKNOWN"; - } -} -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - if (!g.cache[i].valid) continue; - omega_gpu_session_free(&g.cache[i].code); - memset(&g.cache[i], 0, sizeof g.cache[i]); - } - g.next = 0; -} -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g.x_buf); - omega_gpu_session_scratch_free(&g.y_buf); - omega_gpu_session_scratch_free(&g.seg_buf); -} -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -void omega_gpu_fp8gemm_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8gemm_set_shape(uint32_t mt, uint32_t warps) { omega_gpu_session_lock(); g.mt = mt; g.warps = warps; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8gemm_set_cta_budget(uint32_t c) { omega_gpu_session_lock(); g.ctas = c; omega_gpu_session_unlock(); } -void omega_gpu_fp8gemm_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } - -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } /* peak + 2 rounded up to 8: the chip hung at peak + 1 (omega_blackwell_codegen.h) */ -static bool register_file_fits(uint32_t warps, uint32_t peak) { - uint32_t decl = gpr_declared(peak); - if ((uint64_t)32u * warps * decl <= 65536u) return true; - char e[160]; omega_gpu_fmt(e, sizeof e, "fp8 gemm kernel: %u warps x %u declared registers exceed the 65536-register file", warps, decl); - omega_gpu_session_set_error(e); - return false; -} -int omega_gpu_fp8gemm_kernel_fits(const OmegaFp8GemmSpec *spec, uint32_t *declared) { - uint32_t peak = 0; - if (!spec || omega_fp8gemm_prog_stats(spec, NULL, &peak) != 0) { omega_gpu_session_set_error("fp8 gemm codegen refused the shape"); return OMEGA_GPU_FP8GEMM_CODEGEN_FAIL; } - if (declared) *declared = gpr_declared(peak); - return register_file_fits(spec->warps, peak) ? OMEGA_GPU_FP8GEMM_OK : OMEGA_GPU_FP8GEMM_TOO_LARGE; -} - -void omega_gpu_fp8gemm_shape_for(uint32_t k, uint32_t *mt, uint32_t *warps, uint32_t *lane_bytes) { - uint32_t lb = k % 512u == 0 ? 16u : 8u; - if (lane_bytes) *lane_bytes = lb; - /* default 4 rows per pass: chip sweep 2026-10-13, gate|up 3.5 ms at 4 vs 6.0 ms at 8 (8 rows fill the 16 KB of shared memory and run at half the rate) */ - if (mt) *mt = g.mt ? g.mt : 4u; - if (warps) *warps = g.warps ? g.warps : 16u; -} -/* dense = a few distinct experts with many rows each (qkv, o): 8 rows per pass measured best there */ -static void spec_for(uint32_t k, uint32_t segs, OmegaFp8GemmSpec *spec) { - memset(spec, 0, sizeof *spec); - spec->k = k; - omega_gpu_fp8gemm_shape_for(k, &spec->mt, &spec->warps, &spec->lane_bytes); - if (!g.mt && segs < 8u) spec->mt = 8u; - spec->mutant = g.mutant; -} - -static int kernel_for(const OmegaFp8GemmSpec *spec, Slot **out, bool *hit) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - Slot *s = &g.cache[i]; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_FP8GEMM_OK; } - } - Slot *s = NULL; - for (unsigned i = 0; i < CACHE_SLOTS && !s; i++) { - Slot *c = &g.cache[(g.next + i) % CACHE_SLOTS]; - if (!c->valid || !c->pinned) { s = c; g.next = (unsigned)((c - g.cache) + 1) % CACHE_SLOTS; } - } - if (!s) { omega_gpu_session_set_error("fp8 gemm kernel cache: every slot holds a prepared kernel"); return OMEGA_GPU_FP8GEMM_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("fp8 gemm codegen: host memory"); return OMEGA_GPU_FP8GEMM_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_fp8gemm_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("fp8 gemm codegen refused the shape"); return OMEGA_GPU_FP8GEMM_CODEGEN_FAIL; } - if (!register_file_fits(spec->warps, prog->regalloc.peak_gpr_usage)) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8GEMM_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8GEMM_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_FP8GEMM_OK; -} - -int omega_gpu_fp8gemm_prepare(uint32_t k) { - /* both variants: many experts (4 rows per pass) and dense (8 rows per pass) */ - OmegaFp8GemmSpec sp[2]; spec_for(k, 64u, &sp[0]); spec_for(k, 1u, &sp[1]); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_FP8GEMM_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; - else for (int v = 0; v < 2 && rc == OMEGA_GPU_FP8GEMM_OK; v++) { Slot *s = NULL; bool hit = false; rc = kernel_for(&sp[v], &s, &hit); if (rc == OMEGA_GPU_FP8GEMM_OK) s->pinned = true; } - omega_gpu_session_unlock(); - return rc; -} - -/* x' = x * 2^64 in the kernel's lane layout: column c = s*32*LB + L*LB + w*4 + e -> index s*32*LB + (w*32 + L)*4 + e */ -void omega_fp8gemm_permute_x(const float *x, uint32_t k, uint32_t lb, float *out) { - const uint32_t row = 32u * lb, nw = lb / 4u; - for (uint32_t s0 = 0; s0 + row <= k; s0 += row) - for (uint32_t L = 0; L < 32u; L++) - for (uint32_t w = 0; w < nw; w++) { - const float *src = x + s0 + L * lb + w * 4u; float *dst = out + s0 + (w * 32u + L) * 4u; - dst[0] = src[0] * 18446744073709551616.0f; dst[1] = src[1] * 18446744073709551616.0f; - dst[2] = src[2] * 18446744073709551616.0f; dst[3] = src[3] * 18446744073709551616.0f; - } -} - -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt; uint32_t pad[2]; } SegEntry; -_Static_assert(sizeof(SegEntry) == OMEGA_GEMM_SEG_BYTES, "segment entry layout"); - -static int gemm_core(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *ids, const uint32_t *trow, const float *x32, - const uint16_t *x16, uint32_t x_rows, float *y, OmegaGpuFp8GemmInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - uint32_t experts = 0, n = 0, k = 0; - omega_gpu_fp8_tensor_shape(t, &experts, &n, &k); - if (!t || !experts || !ids || !trow || (!x32 && !x16) || !y || M == 0 || x_rows == 0) return OMEGA_GPU_FP8GEMM_BAD_ARGS; - if (M > OMEGA_GPU_FP8GEMM_MAX_ROWS) return OMEGA_GPU_FP8GEMM_TOO_LARGE; - uint32_t segs = 0; - for (uint32_t i = 0; i < M; i++) { - if (ids[i] >= experts || trow[i] >= x_rows || (i && ids[i] < ids[i - 1])) return OMEGA_GPU_FP8GEMM_BAD_ARGS; - if (i == 0 || ids[i] != ids[i - 1]) segs++; - } - if (segs > OMEGA_GPU_FP8GEMM_MAX_SEGMENTS) return OMEGA_GPU_FP8GEMM_TOO_LARGE; - OmegaFp8GemmSpec spec; spec_for(k, segs, &spec); - const uint32_t MT = spec.mt, W = spec.warps; - uint32_t grid_x = (n + W - 1) / W; - uint32_t budget = g.ctas ? g.ctas : (segs >= 64u ? 2u : segs >= 8u ? 12u : 96u); - if (grid_x > budget) grid_x = budget; - if (grid_x == 0) grid_x = 1; - - omega_gpu_session_lock(); - int rc = OMEGA_GPU_FP8GEMM_OK; - if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - int src = omega_gpu_session_scratch(&g.x_buf, ((size_t)M + MT) * k * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)M * n * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.seg_buf, (size_t)OMEGA_GPU_FP8GEMM_MAX_SEGMENTS * OMEGA_GEMM_SEG_BYTES); - if (src != 0) { omega_gpu_session_unlock(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_FP8GEMM_TOO_LARGE : OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - Slot *ks = NULL; bool hit = false; - rc = kernel_for(&spec, &ks, &hit); - if (rc != OMEGA_GPU_FP8GEMM_OK) { omega_gpu_session_unlock(); return rc; } - - /* segment table, permuted x' rows, poisoned y */ - SegEntry *tab = g.seg_buf.mem.cpu; - uint64_t streamed = 0, distinct = 0; uint32_t sg = 0, passes_max = 0; - for (uint32_t i = 0; i < M;) { - uint32_t j = i; while (j < M && ids[j] == ids[i]) j++; - memset(&tab[sg], 0, sizeof tab[sg]); - (void)omega_gpu_fp8_tensor_entry(t, ids[i], &tab[sg].w_va, &tab[sg].s_va); - tab[sg].row0 = i; tab[sg].cnt = j - i; - uint32_t passes = (j - i + MT - 1) / MT; if (passes > passes_max) passes_max = passes; - streamed += (uint64_t)passes * n * k; distinct += (uint64_t)n * k; - sg++; i = j; - } - float *xd = g.x_buf.mem.cpu, *yd = g.y_buf.mem.cpu; - { - float tmp[OMEGA_FP8_MAX_K], tp[OMEGA_FP8_MAX_K]; /* permute in cached memory, then one sequential copy: element-wise writes into the uncached buffer cost 2.8 ms per 4 MB */ - /* a source row routed to several experts (top-k) is permuted once and copied after: the permuted rows are kept in cached memory */ - float *pc = ((size_t)x_rows * k * 4u <= (16u << 20)) ? malloc((size_t)x_rows * k * 4u) : NULL; - unsigned char *have = pc ? calloc(x_rows, 1) : NULL; - for (uint32_t i = 0; i < M; i++) { - const uint32_t r = trow[i]; - if (have && have[r]) { memcpy(xd + (size_t)i * k, pc + (size_t)r * k, (size_t)k * 4u); continue; } - if (x32) memcpy(tmp, x32 + (size_t)r * k, (size_t)k * 4u); - else for (uint32_t c = 0; c < k; c++) { uint32_t b = (uint32_t)x16[(size_t)r * k + c] << 16; memcpy(&tmp[c], &b, 4); } - float *dst = have ? pc + (size_t)r * k : tp; - omega_fp8gemm_permute_x(tmp, k, spec.lane_bytes, dst); - if (have) have[r] = 1; - memcpy(xd + (size_t)i * k, dst, (size_t)k * 4u); - } - free(pc); free(have); - memset(xd + (size_t)M * k, 0, (size_t)MT * k * 4u); - } - for (size_t i = 0; i < (size_t)M * n; i++) yd[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g.seg_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; - - uint32_t args[OMEGA_GEMM_ARGS_WORDS]; - args[0] = (uint32_t)g.seg_buf.mem.va; args[1] = (uint32_t)(g.seg_buf.mem.va >> 32); - args[2] = (uint32_t)g.x_buf.mem.va; args[3] = (uint32_t)(g.x_buf.mem.va >> 32); - args[4] = (uint32_t)g.y_buf.mem.va; args[5] = (uint32_t)(g.y_buf.mem.va >> 32); - args[6] = n; args[7] = grid_x * W; - if (info) { - info->rows = M; info->segments = sg; info->n = n; info->k = k; info->mt = MT; info->warps_per_cta = W; info->lane_bytes = spec.lane_bytes; - info->grid_x = grid_x; info->grid_y = sg; info->passes_max = passes_max; - info->weight_bytes = distinct; info->streamed_bytes = streamed; info->kernel_cache_hit = hit; - } - if (rc == OMEGA_GPU_FP8GEMM_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), - .threads_x = 32u * W, .threads_y = 1, .grid_x = grid_x, .grid_y = sg, - .num_elements = (size_t)M * n, - .args = args, .n_args = OMEGA_GEMM_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = omega_fp8gemm_shared_bytes(&spec), - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; - } - if (rc == OMEGA_GPU_FP8GEMM_OK && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; - if (rc == OMEGA_GPU_FP8GEMM_OK) { - size_t unchanged = 0; - for (size_t i = 0; i < (size_t)M * n; i++) if (yd[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("output poison survived"); rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - else memcpy(y, yd, (size_t)M * n * sizeof *y); - } - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_fp8gemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *ids, const uint32_t *trow, const float *x, uint32_t x_rows, float *y, OmegaGpuFp8GemmInfo *info) { - return gemm_core(t, M, ids, trow, x, NULL, x_rows, y, info); -} -int omega_gpu_fp8gemm_bf16(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *ids, const uint32_t *trow, const uint16_t *x, uint32_t x_rows, float *y, OmegaGpuFp8GemmInfo *info) { - return gemm_core(t, M, ids, trow, NULL, x, x_rows, y, info); -} diff --git a/src/omega_gpu_fp8gemm_api.h b/src/omega_gpu_fp8gemm_api.h deleted file mode 100644 index 4f9c2e089..000000000 --- a/src/omega_gpu_fp8gemm_api.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef OMEGA_GPU_FP8GEMM_API_H -#define OMEGA_GPU_FP8GEMM_API_H -/* - * omega_gpu_fp8gemm_api: native (no CUDA) FP8 e4m3 block-128-scaled GROUPED GEMM for prefill (OWN-30B, builder F - * item 26). It streams each distinct expert's weights once per pass of up to MT rows for all the rows routed to it, - * instead of once per row (omega_gpu_fp8_api's grouped GEMV). New file on the shared session; no existing API changes. - * - * ============ C signatures and semantics (for the Rust binding) ============ - * Weights are the existing OmegaGpuFp8Tensor (omega_gpu_fp8_api.h): experts x n x k e4m3 + 128x128 bf16-derived - * scales, uploaded once and shared with the GEMV path. Dense projections (qkv n=5120 k=2048, o n=2048 k=4096) are - * tensors with experts = 1. - * - * int omega_gpu_fp8gemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *expert_ids, - * const uint32_t *token_rows, const float *x, uint32_t x_rows, float *y, - * OmegaGpuFp8GemmInfo *info); - * int omega_gpu_fp8gemm_bf16(... const uint16_t *x ...); same with bf16 activations - * The row table: row i (0 <= i < M) computes expert expert_ids[i] on activation row x[token_rows[i]] (x: x_rows * k - * values). expert_ids must be non-decreasing (sorted by expert; equal ids form one segment, the weights of a segment - * are streamed once per pass of MT rows). Output y: M * n f32 in ROW-TABLE order: y[i][r] = sum_c W[expert_ids[i]][r][c] - * * x[token_rows[i]][c] * scale, f32 accumulate, the same summation order as omega_gpu_fp8_gemv_f32 (the result is - * bit-identical to calling the GEMV once per row). M <= 1024, at most 256 segments, k and n as the tensor. - * One launch. info may be NULL. - * - * int omega_gpu_fp8gemm_prepare(uint32_t k); build and pin the kernel for width k now (serving). - * const char *omega_gpu_fp8gemm_rc_name(int rc); const char *omega_gpu_fp8gemm_last_error(void); - * - * Return codes: 0 OK; negative OMEGA_GPU_FP8GEMM_*. An uncertain completion latches the process (every later call of - * every API returns CHIP_FAIL). Every output word is poisoned before the launch and the call refuses a result that still - * holds poison. No host oracle runs inside the call. - */ -#include -#include -#include -#include "omega_gpu_fp8_api.h" -#include "omega_blackwell_codegen_gemm.h" - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_FP8GEMM_OK = 0, - OMEGA_GPU_FP8GEMM_BAD_ARGS = -1, - OMEGA_GPU_FP8GEMM_TOO_LARGE = -2, - OMEGA_GPU_FP8GEMM_CODEGEN_FAIL = -3, - OMEGA_GPU_FP8GEMM_CHIP_FAIL = -4 -}; -#define OMEGA_GPU_FP8GEMM_MAX_ROWS 1024u -#define OMEGA_GPU_FP8GEMM_MAX_SEGMENTS 256u - -typedef struct { - uint32_t rows, segments, n, k, mt, warps_per_cta, lane_bytes, grid_x, grid_y, passes_max; - uint64_t weight_bytes; /* e4m3 bytes of the distinct experts, one pass each */ - uint64_t streamed_bytes; /* bytes the launch reads from the weights (sum over segments of passes * n * k) */ - uint64_t elapsed_ns; /* chip submit-to-second-marker */ - uint64_t call_ns; /* whole API call (host permute, launch, copy back) */ - uint32_t completion_marker; - bool kernel_cache_hit; -} OmegaGpuFp8GemmInfo; - -int omega_gpu_fp8gemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *expert_ids, const uint32_t *token_rows, - const float *x, uint32_t x_rows, float *y, OmegaGpuFp8GemmInfo *info); -int omega_gpu_fp8gemm_bf16(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *expert_ids, const uint32_t *token_rows, - const uint16_t *x, uint32_t x_rows, float *y, OmegaGpuFp8GemmInfo *info); -int omega_gpu_fp8gemm_prepare(uint32_t k); -const char *omega_gpu_fp8gemm_rc_name(int rc); -const char *omega_gpu_fp8gemm_last_error(void); -void omega_gpu_fp8gemm_cache_clear(void); - -/* Register-file check (declared = peak + 1 rounded up to 8; 32 * warps * declared <= 65536). */ -int omega_gpu_fp8gemm_kernel_fits(const OmegaFp8GemmSpec *spec, uint32_t *declared); -/* The shape the API picks for width k: rows per pass, warps per CTA, lane bytes. */ -void omega_gpu_fp8gemm_shape_for(uint32_t k, uint32_t *mt, uint32_t *warps, uint32_t *lane_bytes); - -/* ---- measurement knobs (each clears the kernel cache; 0 restores the automatic choice) ---- */ -void omega_gpu_fp8gemm_set_shape(uint32_t mt, uint32_t warps); -void omega_gpu_fp8gemm_set_cta_budget(uint32_t ctas_per_segment); -/* TEST ONLY: deliberately wrong kernels 1 (scale dropped), 2 (scale pointer never advances), 3 (neighbour row's x). */ -void omega_gpu_fp8gemm_test_set_mutant(int mutant); - -/* host helper: the permuted, 2^64-scaled x' row the kernel reads (k values in, k out) */ -void omega_fp8gemm_permute_x(const float *x, uint32_t k, uint32_t lane_bytes, float *out); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_hostmath.c b/src/omega_gpu_hostmath.c deleted file mode 100644 index e042023c9..000000000 --- a/src/omega_gpu_hostmath.c +++ /dev/null @@ -1,82 +0,0 @@ -/* omega_gpu_hostmath: libm-free double-precision log / exp / pow / sincos (see the header). */ -#include "omega_gpu_hostmath.h" -#include -#include - -static double bits_d(uint64_t u) { double d; memcpy(&d, &u, 8); return d; } -static uint64_t d_bits(double d) { uint64_t u; memcpy(&u, &d, 8); return u; } - -#define HM_LN2_HI 6.93147180369123816490e-01 /* fdlibm: ln2 split so that k * LN2_HI is exact for |k| < 2^20 */ -#define HM_LN2_LO 1.90821492927058770002e-10 -#define HM_INV_LN2 1.44269504088896338700e+00 -#define HM_SQRT2 1.41421356237309504880e+00 - -/* 2^k as a double for -1074 <= k <= 1023 (two steps below the normal range) */ -static double pow2i(int k) { - if (k > 1023) return bits_d(0x7ff0000000000000ull); - if (k < -1074) return 0.0; - if (k >= -1022) return bits_d((uint64_t)(k + 1023) << 52); - return bits_d((uint64_t)1 << 52) * bits_d((uint64_t)(k + 1022 + 1023) << 52); /* 2^-1022 * 2^(k+1022) */ -} - -double omega_hostmath_log(double x) { - if (!(x > 0.0) || x > 1.7976931348623157e308) return bits_d(0x7ff8000000000000ull); - int e = 0; - if (x < 2.2250738585072014e-308) { x *= 18014398509481984.0; e = -54; } /* subnormal: scale by 2^54 */ - uint64_t u = d_bits(x); - e += (int)((u >> 52) & 0x7ff) - 1023; - double m = bits_d((u & 0x000fffffffffffffull) | 0x3ff0000000000000ull); /* [1, 2) */ - if (m > HM_SQRT2) { m *= 0.5; e += 1; } /* [sqrt(1/2), sqrt(2)) */ - double t = (m - 1.0) / (m + 1.0), t2 = t * t; /* |t| < 0.1716 */ - double s = 0.0; - for (int k = 25; k >= 1; k -= 2) s = s * t2 + 1.0 / (double)k; /* sum t2^j / (2j+1), j = 0..12 */ - return (double)e * HM_LN2_HI + (2.0 * t * s + (double)e * HM_LN2_LO); -} - -double omega_hostmath_exp(double y) { - if (y != y) return y; - if (y > 709.78) return bits_d(0x7ff0000000000000ull); - if (y < -745.2) return 0.0; - double fk = y * HM_INV_LN2; - long long k = (long long)(fk + (fk >= 0.0 ? 0.5 : -0.5)); - double kd = (double)k; - double r = (y - kd * HM_LN2_HI) - kd * HM_LN2_LO; /* |r| <= 0.3466 */ - double p = 1.0; - for (int n = 17; n >= 1; n--) p = 1.0 + r * p / (double)n; /* 1 + r(1 + r/2(1 + r/3(...))) */ - if (k < -1020) return p * pow2i(-1020) * pow2i((int)k + 1020); - return p * pow2i((int)k); -} - -double omega_hostmath_pow(double base, double e) { - if (base == 1.0 || e == 0.0) return 1.0; - return omega_hostmath_exp(e * omega_hostmath_log(base)); -} - -/* fdlibm e_rem_pio2 pieces of pi/2: the first three have 33 significant bits, so n * piece is exact for n < 2^20 */ -#define HM_PIO2_1 1.57079632673412561417e+00 -#define HM_PIO2_2 6.07710050630396597660e-11 -#define HM_PIO2_3 2.02226624871116645580e-21 -#define HM_PIO2_3T 8.47842766036889956997e-32 -#define HM_2_OVER_PI 6.36619772367581382433e-01 - -void omega_hostmath_sincos(double a, double *s, double *c) { - double fn = a * HM_2_OVER_PI; - long long n = (long long)(fn + (fn >= 0.0 ? 0.5 : -0.5)); - double nd = (double)n; - double r = a - nd * HM_PIO2_1; - r -= nd * HM_PIO2_2; - r -= nd * HM_PIO2_3; - r -= nd * HM_PIO2_3T; /* |r| <= pi/4 + tiny */ - double w = r * r; - double ps = 1.0; - for (int k = 15; k >= 3; k -= 2) ps = 1.0 - w * ps / (double)(k * (k - 1)); /* sin r = r * ps, terms to r^15 */ - double pc = 1.0; - for (int k = 16; k >= 2; k -= 2) pc = 1.0 - w * pc / (double)(k * (k - 1)); /* cos r = pc, terms to r^16 */ - double sr = r * ps, cr = pc; - switch ((int)(n & 3)) { - case 0: *s = sr; *c = cr; break; - case 1: *s = cr; *c = -sr; break; - case 2: *s = -sr; *c = -cr; break; - default: *s = -cr; *c = sr; break; - } -} diff --git a/src/omega_gpu_hostmath.h b/src/omega_gpu_hostmath.h deleted file mode 100644 index 50f0ecef5..000000000 --- a/src/omega_gpu_hostmath.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef OMEGA_GPU_HOSTMATH_H -#define OMEGA_GPU_HOSTMATH_H -/* - * omega_gpu_hostmath: libm-free double-precision host math for the production side of libomega_gpu.a - * (OWN-30B, 2026-10-13). The library must link without -lm (omegatool and the Rust FFI crate link it bare), - * so the few transcendental values the APIs build on the host (the RoPE cos/sin table, the inverse frequency - * powers, the router oracle's exp) come from here. Everything is plain double arithmetic: range reduction plus - * short Taylor/atanh series, checked against libm by tests/gpu_decode_attn_test.c --host-only (the test links -lm). - * - * log(x): x > 0 finite; NaN otherwise. Error a few ulp. - * exp(y): 0 below -745, +inf above 709.8. Error a few ulp. - * pow(b, e): b > 0 finite; exp(e * log(b)). Relative error about |e * log b| * 2^-52. - * sincos(a): valid for |a| < 2^20 * pi/2 (about 1.6e6; the RoPE table needs pos < 65536). Three-part - * Cody-Waite reduction with the fdlibm pi/2 pieces, series to r^16. Absolute error about 1e-16. - */ -double omega_hostmath_log(double x); -double omega_hostmath_exp(double y); -double omega_hostmath_pow(double base, double e); -void omega_hostmath_sincos(double a, double *s, double *c); -#endif diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c deleted file mode 100644 index a0c5975e1..000000000 --- a/src/omega_gpu_matmul_api.c +++ /dev/null @@ -1,640 +0,0 @@ -/* - * omega_gpu_matmul_api.c: FB-1 cut 1b, on the shared session since cut 4b. - * See the header for the contract. - * - * Submission path: omega_gpu_session_launch (src/omega_gpu_session.c), the same - * words this file emitted in cut 1b (chip PASS FB1-CUT1B-4345406): SETUP_WORDS, - * shader-cache invalidate, constant bank upload, QMD0/QMD1 launch, first marker - * release, then the C3 tail (L2_FLUSH_DIRTY and a second release on uncached - * memory the host waits for before reading). Every buffer both sides touch is - * GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will - * not be coherent with direct CPU mappings"). The device, channel, pushbuffer, - * constant bank, marker page and QMD page now belong to the session and are - * shared with the elementwise and attention APIs; this file keeps the resident - * tensors, the kernel cache (host and device copies) and its staging buffers. - */ -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include - -#define CACHE_SLOTS 8 /* default kernel cache slots; raised only by omega_gpu_matmul_reserve */ -#define CACHE_SLOTS_MAX 128 /* storage for the opt-in larger cache (a code buffer is a few KB); Qwen3-4B serving needs 95 */ -#define FRAG_PACK_TILES 64u /* column tiles per host packing chunk at upload */ -#define MARKER_TIMEOUT_MS 20000ull /* a 1x2048x128256 call is ~0.1 s; 20 s is a stall, not a slow run */ -#define POISON_F32 (-999.0f) -#define ORACLE_TOL 1e-5 - -struct OmegaGpuTensor { - uint32_t k, n, kp, np; - OmegaGpuMem mem; /* kp x np bf16 in fragment order (omega_matmul_frag_pack_b) */ -}; - -typedef struct { - bool valid; - bool pinned; /* built by omega_gpu_matmul_prepare: never evicted */ - uint32_t kp, np, grid_x; - uint32_t rt, ct; /* tiles per warp (omega_matmul_frag_block_shape); 1, 1 = the single-tile kernel */ - int mutant; - OmegaMatMulSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; /* resident copy of kernel.code */ -} CacheSlot; - -static struct { - OmegaGpuScratch a_buf, c_buf; /* activation and result staging, grown to the high-water mark */ - /* a_buf holds a full one-row pack (rows 1..15 of every block zero) at width a_row0_kp in the - * allocation a_row0_cpu: the next one-row call of that width writes row 0 only. Cleared by any - * other pack and whenever the buffer is freed. */ - bool a_row0_ready; uint32_t a_row0_kp; const void *a_row0_cpu; - uint64_t a_row0_hits; /* one-row calls that wrote row 0 only (test hook) */ - uint32_t cta_budget; - int oracle, mutant; - uint32_t unroll; /* test override of the fragment kernel unroll; 0 = omega_matmul_frag_unroll */ - bool hooked; - CacheSlot cache[CACHE_SLOTS_MAX]; - unsigned cache_next; - unsigned slots; /* active kernel cache slots, <= CACHE_SLOTS_MAX */ - int sealed; /* omega_gpu_matmul_seal: a kernel cache miss is refused, never built */ - OmegaGpuMatmulStages stages; /* the most recent matmul_core call (omega #473), written under the session lock */ -} g = { .cta_budget = OMEGA_GPU_MATMUL_MAX_CTAS, .oracle = 1, .slots = CACHE_SLOTS }; - -#define FAILAT(s) (omega_gpu_session_set_error(s), 1) -const char *omega_gpu_matmul_last_error(void) { return omega_gpu_session_last_error(); } - -static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */ -static inline double abs_d(double x) { return x < 0.0 ? -x : x; } - -static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } - -const char *omega_gpu_matmul_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_MATMUL_OK: return "OK"; - case OMEGA_GPU_MATMUL_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_MATMUL_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_MATMUL_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_MATMUL_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_MATMUL_PARITY_FAIL: return "PARITY_FAIL"; - default: return "UNKNOWN"; - } -} - -int omega_gpu_matmul_is_blocked(void) { return omega_gpu_session_is_blocked(); } - -void omega_gpu_matmul_last_stages(OmegaGpuMatmulStages *out) { - if (!out) return; - omega_gpu_session_lock(); - *out = g.stages; - omega_gpu_session_unlock(); -} - -/* ---- device-side state (caller holds the session lock) ---- */ - -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS_MAX; i++) { - CacheSlot *s = &g.cache[i]; - if (!s->valid) continue; - omega_gpu_session_free(&s->code); /* kernel.code points into it */ - memset(s, 0, sizeof *s); - } - g.cache_next = 0; -} - -/* Called by the session (lock held, device still open) right before it closes. */ -static void on_session_close(void) { - cache_clear_locked(); - g.a_row0_ready = false; - omega_gpu_session_scratch_free(&g.a_buf); - omega_gpu_session_scratch_free(&g.c_buf); - g.slots = CACHE_SLOTS; /* a serving reservation ends with the device */ - g.sealed = 0; -} - -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} - -void omega_gpu_device_close(void) { omega_gpu_session_close(); } - -void omega_gpu_matmul_cache_clear(void) { - omega_gpu_session_lock(); - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -void omega_gpu_matmul_set_cta_budget(uint32_t ctas) { - omega_gpu_session_lock(); - g.cta_budget = ctas ? ctas : OMEGA_GPU_MATMUL_MAX_CTAS; - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -uint32_t omega_gpu_matmul_cta_budget(void) { return g.cta_budget; } - -/* ---- opt-in serving reservation (see the header) ---- */ - -int omega_gpu_matmul_reserve(uint32_t max_rows, uint32_t max_k, uint32_t max_n, uint32_t max_n_one_row, uint32_t kernel_slots) { - if (max_rows == 0 || max_k == 0 || max_n == 0) { omega_gpu_session_set_error("matmul reserve: zero bound"); return OMEGA_GPU_MATMUL_BAD_ARGS; } - if (max_rows > OMEGA_BW_MATMUL_MAX_M || max_k > OMEGA_BW_MATMUL_MAX_K || max_n > OMEGA_BW_MATMUL_MAX_N || max_n_one_row > OMEGA_BW_MATMUL_MAX_N || - kernel_slots > CACHE_SLOTS_MAX) { - omega_gpu_session_set_error("matmul reserve: bound past the matmul envelope"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - const size_t mp = round_up(max_rows, OMEGA_GPU_MATMUL_TILE_M), kp = round_up(max_k, OMEGA_GPU_MATMUL_TILE_K); - size_t c_bytes = mp * round_up(max_n, OMEGA_GPU_MATMUL_TILE_N) * 4u; - if (max_n_one_row) { /* a call of up to 16 rows (one row tile) may be wider than the batch width: lm_head */ - size_t one = (size_t)OMEGA_GPU_MATMUL_TILE_M * round_up(max_n_one_row, OMEGA_GPU_MATMUL_TILE_N) * 4u; - if (one > c_bytes) c_bytes = one; - } - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - else if (omega_gpu_session_scratch_reserve(&g.a_buf, mp * kp * 2u) != 0 || omega_gpu_session_scratch_reserve(&g.c_buf, c_bytes) != 0) { - /* roll back this API's own buffers: a failed reserve leaves nothing flagged */ - omega_gpu_session_scratch_unreserve(&g.a_buf); omega_gpu_session_scratch_unreserve(&g.c_buf); - rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - } - else if (kernel_slots > g.slots) { /* grow only; the cache restarts empty */ - cache_clear_locked(); - g.slots = kernel_slots; - } - omega_gpu_session_unlock(); - return rc; -} - -void omega_gpu_matmul_unreserve(void) { - omega_gpu_session_lock(); - omega_gpu_session_scratch_unreserve(&g.a_buf); - omega_gpu_session_scratch_unreserve(&g.c_buf); - omega_gpu_session_unlock(); -} - -static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, uint32_t rt, uint32_t ct, CacheSlot **out, bool *hit); -static void launch_shape(uint32_t mp, uint32_t np, uint32_t *rows_per_launch, uint32_t *grid_x, uint32_t *rt, uint32_t *ct); - -int omega_gpu_matmul_prepare(uint32_t m, uint32_t k, uint32_t n) { - if (m == 0 || k == 0 || n == 0) { omega_gpu_session_set_error("matmul prepare: zero dimension"); return OMEGA_GPU_MATMUL_BAD_ARGS; } - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) { - omega_gpu_session_set_error("matmul prepare: shape past the matmul envelope"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M), kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K), np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); - uint32_t rows_per_launch, grid_x, rt, ct; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - else { - launch_shape(mp, np, &rows_per_launch, &grid_x, &rt, &ct); - CacheSlot *s = NULL; bool hit = false; - rc = kernel_for(kp, np, grid_x, rt, ct, &s, &hit); - if (rc == OMEGA_GPU_MATMUL_OK) s->pinned = true; /* a prepared kernel is never evicted */ - } - omega_gpu_session_unlock(); - return rc; -} - -/* Anything that clears the kernel cache while sealed (cache_clear, set_cta_budget, the test knobs, a - * reserve that grows the slot count) also drops the pinned kernels; the seal stays, so every later - * call is refused by name ("was not prepared") until the server prepares again or releases. */ -void omega_gpu_matmul_seal(int on) { - omega_gpu_session_lock(); - g.sealed = on ? 1 : 0; - omega_gpu_session_unlock(); -} - -void omega_gpu_matmul_set_oracle(int on) { g.oracle = on ? 1 : 0; } - -void omega_gpu_matmul_test_set_mutant(int on) { - omega_gpu_session_lock(); - g.mutant = on ? 1 : 0; - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -uint64_t omega_gpu_matmul_test_a_row0_hits(void) { return g.a_row0_hits; } - -void omega_gpu_matmul_test_set_unroll(uint32_t unroll) { - omega_gpu_session_lock(); - g.unroll = unroll; - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -/* ---- one launch shape (the kernel cache key bakes in grid_x) ---- */ - -/* rows per launch: all of them unless the row blocks alone exceed the CTA budget; grid_x fills the rest of - * the budget. A CTA (one warp) owns rt row tiles x ct column tiles (omega_matmul_frag_block_shape, 2026-10-12): - * rt = ct = 1 for decode rows (the single-tile kernel), 4 x 4 at m = 128. Every launch of a call has a row - * count divisible by 16*rt (rows_per_launch is, and so is the remainder, since rt divides mp/16). */ -static void launch_shape(uint32_t mp, uint32_t np, uint32_t *rows_per_launch, uint32_t *grid_x, uint32_t *rt, uint32_t *ct) { - const uint32_t budget = g.cta_budget ? g.cta_budget : OMEGA_GPU_MATMUL_MAX_CTAS, mt = mp / 16u, nt = np / 8u; - omega_matmul_frag_block_shape(mt, nt, rt, ct); - const uint32_t rb = mt / *rt, nb = nt / *ct; - *rows_per_launch = rb <= budget ? mp : budget * 16u * *rt; - uint32_t gx = budget / (*rows_per_launch / 16u / *rt); - if (gx == 0) gx = 1; - if (gx > nb) gx = nb; - *grid_x = gx; -} - -/* ---- kernel cache (caller holds the lock, device open) ---- */ - -static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, uint32_t rt, uint32_t ct, CacheSlot **out, bool *hit) { - for (unsigned i = 0; i < g.slots; i++) { - CacheSlot *s = &g.cache[i]; - if (s->valid && s->kp == kp && s->np == np && s->grid_x == grid_x && s->rt == rt && s->ct == ct && s->mutant == g.mutant) { - *out = s; *hit = true; - return OMEGA_GPU_MATMUL_OK; - } - } - if (g.sealed) { - char e[160]; - omega_gpu_fmt(e, sizeof e, "serving reservation exceeded: matmul kernel kp=%u np=%u grid_x=%u rt=%u ct=%u was not prepared", kp, np, grid_x, rt, ct); - omega_gpu_session_set_error(e); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - /* choose the slot before any build or driver call: round-robin, skipping prepared (pinned) kernels; all pinned = refused, nothing evicted */ - CacheSlot *s = NULL; - for (unsigned i = 0; i < g.slots && !s; i++) { - CacheSlot *c = &g.cache[(g.cache_next + i) % g.slots]; - if (!c->valid || !c->pinned) { s = c; g.cache_next = (unsigned)((c - g.cache) + 1) % g.slots; } - } - if (!s) { - omega_gpu_session_set_error("matmul kernel cache: every slot holds a prepared kernel (raise kernel_slots)"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - OmegaMatMulSpec spec; - /* the kernel ignores M; 16 keeps the spec inside the tile rule */ - if (omega_matmul_spec_init(&spec, 16, kp, np, OMEGA_MATMUL_PRECISION_BF16) != 0) return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaBlackwellKernel kernel; - memset(&kernel, 0, sizeof kernel); - const bool blocked = rt > 1 || ct > 1; - /* the test unroll knob applies to the single-tile kernel; the blocked kernel keeps its own rule */ - uint32_t unroll = blocked ? omega_matmul_frag_block_unroll(kp, rt, ct) : g.unroll ? g.unroll : omega_matmul_frag_unroll(kp); - /* the mutant drops the last pass, so it needs two: halve the unroll of a one-pass shape */ - if (g.mutant && (blocked || !g.unroll)) while (unroll > 1 && kp / 16u / unroll < 2) unroll /= 2; - /* P07 cut C: the program is built in host memory and encoded straight into the device code buffer, sized - * exactly (omega_bw_program_code_bytes: the bytes the allocating generators produce, cut A.2 proves them - * identical). kernel.code then points into that buffer and owns nothing. */ - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("matmul codegen: host memory"); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - int cg = blocked ? omega_blackwell_codegen_matmul_frag_block_prog(&spec, grid_x, unroll, rt, ct, g.mutant, prog) - : omega_blackwell_codegen_matmul_frag_prog(&spec, grid_x, unroll, g.mutant, prog); - const size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - s->valid = true; s->pinned = false; s->kp = kp; s->np = np; s->grid_x = grid_x; s->rt = rt; s->ct = ct; s->mutant = g.mutant; - s->spec = spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_MATMUL_OK; -} - -/* ---- one launch (caller holds the lock, device open, not blocked) ---- */ - -static int launch(const CacheSlot *ks, uint64_t a_va, uint64_t b_va, uint64_t c_va, - uint32_t grid_x, uint32_t grid_y, uint64_t *elapsed_ns, uint32_t *marker_out) { - uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - omega_blackwell_build_cbank_args_matmul(cbank_args, a_va, b_va, c_va, grid_y * 16u * ks->rt, ks->kp, ks->np); - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = ks->kernel.gpr_count, - .threads_x = 32, .threads_y = 1, .grid_x = grid_x, .grid_y = grid_y, - .num_elements = (size_t)grid_x * grid_y * 128u, - .args = cbank_args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - }; - return omega_gpu_session_launch(&L, elapsed_ns, marker_out) == 0 ? OMEGA_GPU_MATMUL_OK : OMEGA_GPU_MATMUL_CHIP_FAIL; -} - -/* ---- tensors ---- */ - -void omega_gpu_tensor_shape(const OmegaGpuTensor *t, uint32_t *k, uint32_t *n) { - if (k) *k = t ? t->k : 0; - if (n) *n = t ? t->n : 0; -} - -int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuTensor **out) { - if (out) *out = NULL; - if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaGpuTensor *t = omega_gpu_host_calloc(1, sizeof *t); - if (!t) return OMEGA_GPU_MATMUL_BAD_ARGS; - t->k = k; t->n = n; t->kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K); t->np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); - /* fragment order (omega_matmul_frag_pack_b), packed on the host FRAG_PACK_TILES column - * tiles at a time and copied in order into the uncached device buffer */ - const uint32_t nt = t->np / 8u; - uint16_t *h = omega_gpu_host_alloc((size_t)FRAG_PACK_TILES * t->kp * 8u * sizeof *h); - if (!h) { omega_gpu_host_free(t); return OMEGA_GPU_MATMUL_BAD_ARGS; } - int rc = OMEGA_GPU_MATMUL_OK; - omega_gpu_session_lock(); - if (!dev_open_locked() || omega_gpu_session_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_MATMUL_OK) { omega_gpu_host_free(h); omega_gpu_host_free(t); return rc; } - uint16_t *d = t->mem.cpu; - for (uint32_t nt0 = 0; nt0 < nt; nt0 += FRAG_PACK_TILES) { - const uint32_t nt1 = nt - nt0 < FRAG_PACK_TILES ? nt : nt0 + FRAG_PACK_TILES; - omega_matmul_frag_pack_b(b, k, n, t->kp, nt0, nt1, h); - memcpy(&d[(size_t)nt0 * t->kp * 8u], h, (size_t)(nt1 - nt0) * t->kp * 8u * sizeof *h); - } - omega_gpu_host_free(h); - if (omega_gpu_session_sync_to_gpu(&t->mem) != 0) { omega_gpu_tensor_free(t); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - *out = t; - return OMEGA_GPU_MATMUL_OK; -} - -int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuTensor **out) { - if (out) *out = NULL; - if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; - size_t cnt = (size_t)k * n; - uint16_t *h = omega_gpu_host_alloc(cnt * sizeof *h); - if (!h) return OMEGA_GPU_MATMUL_BAD_ARGS; - for (size_t i = 0; i < cnt; i++) h[i] = omega_fp32_to_bf16(b[i]); - int rc = omega_gpu_tensor_upload_bf16(k, n, h, out); - omega_gpu_host_free(h); - return rc; -} - -/* ---- in-place update ---- */ - -/* f32 rounding staging for tensor_update: static, used only under the session lock, so an update never asks - * for memory (no out-of-memory path, no per-call allocation). 256 Ki elements (512 KiB): one chunk is - * UPDATE_STAGE_ELEMS / (k * 8) column tiles, capped at FRAG_PACK_TILES (42 tiles at k = 768, 2 at the - * largest k). */ -#define UPDATE_STAGE_ELEMS (256u * 1024u) -_Static_assert(UPDATE_STAGE_ELEMS / (OMEGA_BW_MATMUL_MAX_K * 8u) >= 1u, "staging holds one column tile at the largest k"); -static uint16_t g_update_stage[UPDATE_STAGE_ELEMS]; - -/* Packs b (k x n bf16, or f32 rounded as at upload) straight into the tensor's packed buffer dst, a chunk of - * column tiles at a time: each chunk is one contiguous run of dst, written while it is hot in cache. An f32 - * chunk is first rounded into the staging block (omega_fp32_to_bf16_rne, the shared integer form of - * omega_fp32_to_bf16), then packed as a k x w matrix whose tiles 0 .. nt1 - nt0 are the tensor's tiles - * nt0 .. nt1 (columns past n stay zero either way). */ -static void pack_b_into(const OmegaGpuTensor *t, const uint16_t *b16, const float *b32, uint16_t *dst) { - const uint32_t k = t->k, n = t->n, kp = t->kp, nt = t->np / 8u; - uint32_t chunk = FRAG_PACK_TILES; - if (b32 && UPDATE_STAGE_ELEMS / (k * 8u) < chunk) chunk = UPDATE_STAGE_ELEMS / (k * 8u); - for (uint32_t nt0 = 0; nt0 < nt; nt0 += chunk) { - const uint32_t nt1 = nt - nt0 < chunk ? nt : nt0 + chunk; - uint16_t *out = &dst[(size_t)nt0 * kp * 8u]; - if (b16) { omega_matmul_frag_pack_b(b16, k, n, kp, nt0, nt1, out); continue; } - const uint32_t c0 = nt0 * 8u, w = (nt1 * 8u < n ? nt1 * 8u : n) - c0; - for (uint32_t r = 0; r < k; r++) { - const float *src = &b32[(size_t)r * n + c0]; - uint16_t *row = &g_update_stage[(size_t)r * w]; - for (uint32_t j = 0; j < w; j++) row[j] = omega_fp32_to_bf16_rne(src[j]); - } - omega_matmul_frag_pack_b(g_update_stage, k, w, kp, 0, nt1 - nt0, out); - } -} - -/* b16 or b32 (exactly one non-NULL). Holds the session lock for the whole update (see the header's thread - * safety note). The tensor must be a session DATA buffer: the session allocates every buffer GPU-uncached - * (mem_alloc, omega_gpu_session.h), so the chip reads what the CPU wrote once the sync below has ordered it; - * anything else is refused rather than risk the chip reading stale cached weights. The first sync validates - * the handle before anything is written: a handle from a closed or reopened device is refused by the - * platform, and its CPU view may be unmapped. */ -static int tensor_update(OmegaGpuTensor *t, uint32_t k, uint32_t n, const uint16_t *b16, const float *b32) { - if (!t || !t->mem.cpu || (!b16 && !b32)) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (k != t->k || n != t->n) { - omega_gpu_session_lock(); - omega_gpu_session_set_error("tensor update refused: shape differs from the tensor's"); - omega_gpu_session_unlock(); - return OMEGA_GPU_MATMUL_BAD_ARGS; - } - if (t->mem.kind != OMEGA_GPU_HANDLE_BUF_DATA) return OMEGA_GPU_MATMUL_BAD_ARGS; - int rc = OMEGA_GPU_MATMUL_OK; - omega_gpu_session_lock(); - if (omega_gpu_session_is_blocked()) { - omega_gpu_session_set_error("tensor update refused: the session is latched (the device may still read the buffer)"); - rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - } else if (omega_gpu_session_sync_to_gpu(&t->mem) != 0) { - rc = OMEGA_GPU_MATMUL_CHIP_FAIL; /* stale handle or closed device: nothing written */ - } else { - pack_b_into(t, b16, b32, t->mem.cpu); - if (omega_gpu_session_sync_to_gpu(&t->mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_tensor_update_bf16(OmegaGpuTensor *t, uint32_t k, uint32_t n, const uint16_t *b) { - return b ? tensor_update(t, k, n, b, NULL) : OMEGA_GPU_MATMUL_BAD_ARGS; -} -int omega_gpu_tensor_update_f32(OmegaGpuTensor *t, uint32_t k, uint32_t n, const float *b) { - return b ? tensor_update(t, k, n, NULL, b) : OMEGA_GPU_MATMUL_BAD_ARGS; -} - -void omega_gpu_tensor_free(OmegaGpuTensor *t) { - if (!t) return; - omega_gpu_session_lock(); - omega_gpu_session_free(&t->mem); - omega_gpu_session_unlock(); - omega_gpu_host_free(t); -} - -/* ---- the matmul ---- */ - -/* stage timer (omega #473): each mark closes one stage at the time it is called; put stores the record - * (caller holds the session lock) */ -#define STAGE_MARK(field) do { const uint64_t now_ = now_ns(); st.field = now_ - mark; mark = now_; } while (0) -static void stages_put(OmegaGpuMatmulStages *st, uint64_t chip_ns, uint64_t t0) { - st->chip_ns = chip_ns; - st->core_ns = now_ns() - t0; - g.stages = *st; -} - -/* a16 or a32 (exactly one non-NULL): the activation rows as bf16 or as f32, packed into fragment - * order in one pass either way (f32 rows are converted while packing, no staging copy) */ -static int matmul_core(uint32_t m, const uint16_t *a16, const float *a32, const OmegaGpuTensor *b, float *c, OmegaGpuMatmulInfo *info) { - const uint64_t t0 = now_ns(); - uint64_t mark = t0, chip_ns = 0; - OmegaGpuMatmulStages st; - memset(&st, 0, sizeof st); - const uint32_t k = b->k, n = b->n, kp = b->kp, np = b->np; - const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) { STAGE_MARK(setup_ns); stages_put(&st, 0, t0); omega_gpu_session_unlock(); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - uint32_t rows_per_launch, grid_x, rt, ct; - launch_shape(mp, np, &rows_per_launch, &grid_x, &rt, &ct); - uint32_t grid_y_full = rows_per_launch / 16u / rt; - if (info) { - info->m = m; info->k = k; info->n = n; info->padded_m = mp; info->padded_n = np; info->padded_k = kp; - info->k_slices = 1; info->rows_per_call = rows_per_launch; info->grid_x = grid_x; info->grid_y = grid_y_full; - info->resident = true; info->kernel_cache_hit = true; - (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; - } - if (g.sealed && !(g.a_buf.reserved && g.c_buf.reserved)) { - /* sealed means no driver allocation on the call path; without a scratch reservation the - * buffers below could still grow, so refuse before touching them */ - omega_gpu_session_set_error("serving reservation exceeded: matmul sealed without a scratch reservation (call omega_gpu_reserve_serving first)"); - STAGE_MARK(setup_ns); stages_put(&st, 0, t0); - omega_gpu_session_unlock(); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - int src = omega_gpu_session_scratch(&g.a_buf, (size_t)mp * kp * 2u); - if (src == 0) src = omega_gpu_session_scratch(&g.c_buf, (size_t)mp * np * 4u); - if (src != 0) { - STAGE_MARK(setup_ns); stages_put(&st, 0, t0); - omega_gpu_session_unlock(); - /* a serving reservation refuses growth loudly (TOO_LARGE, error text names the sizes); anything else is a driver failure */ - return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_MATMUL_TOO_LARGE : OMEGA_GPU_MATMUL_CHIP_FAIL; - } - /* activation rows in, fragment order (omega_matmul_frag_pack_a / _f32: f32 rows are converted - * while packing, one pass), zero padded, packed on the host straight into the uncached buffer - * (the CPU side of that memory is ordinary cached memory; dsb below orders it before the launch); - * result rows poisoned. A one-row call (decode) writes row 0 only when the buffer already holds - * a full one-row pack of this width (rows 1..15 of every block zero): the 15 zero rows are not - * rewritten per token. */ - STAGE_MARK(setup_ns); - uint16_t *ad = g.a_buf.mem.cpu; - const bool one_row = m == 1 && mp == 16u; - if (one_row && g.a_row0_ready && g.a_row0_kp == kp && g.a_row0_cpu == ad) { - if (a32) omega_matmul_frag_pack_a_row0_f32(a32, k, kp, ad); - else omega_matmul_frag_pack_a_row0(a16, k, kp, ad); - g.a_row0_hits++; - } else { - if (a32) omega_matmul_frag_pack_a_f32(a32, m, k, mp, kp, ad); - else omega_matmul_frag_pack_a(a16, m, k, mp, kp, ad); - g.a_row0_ready = one_row; g.a_row0_kp = kp; g.a_row0_cpu = ad; - } - /* result sentinels: one poison word per 16 x 8 fragment tile holding a real output word, at the tile's - * last real row and column (omega_matmul_result_sentinels). The kernel stores a tile as one straight-line - * run of STG.E words, so a tile whose sentinel survives was never stored. Poisoning and scanning every - * word was three passes over m x np (12.6 MB at m = 128, n = 24576: about 2 ms per prefill call, 2026-10-12). */ - float *cd = g.c_buf.mem.cpu; - omega_matmul_result_sentinels(cd, m, n, np, POISON_F32, 1); - STAGE_MARK(pack_ns); - if (omega_gpu_session_sync_to_gpu(&g.a_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.c_buf.mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - STAGE_MARK(upload_ns); - - for (uint32_t r0 = 0; r0 < mp && rc == OMEGA_GPU_MATMUL_OK; r0 += rows_per_launch) { - uint32_t rows = mp - r0 < rows_per_launch ? mp - r0 : rows_per_launch; - uint32_t grid_y = rows / 16u / rt; - CacheSlot *ks = NULL; bool hit = false; - rc = kernel_for(kp, np, grid_x, rt, ct, &ks, &hit); - if (rc != OMEGA_GPU_MATMUL_OK) break; - if (info && !hit) info->kernel_cache_hit = false; - rc = launch(ks, g.a_buf.mem.va + (uint64_t)r0 * kp * 2u, b->mem.va, g.c_buf.mem.va + (uint64_t)r0 * np * 4u, - grid_x, grid_y, &chip_ns, info ? &info->completion_marker : NULL); - if (info) info->chip_calls++; - } - if (info) info->elapsed_ns = chip_ns; - STAGE_MARK(launch_ns); - if (rc == OMEGA_GPU_MATMUL_OK && omega_gpu_session_sync_to_cpu(&g.c_buf.mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - STAGE_MARK(sync_ns); - if (rc == OMEGA_GPU_MATMUL_OK) { - /* the chip must have stored every fragment tile with a real output word (sentinel check) */ - size_t unchanged = omega_matmul_result_sentinels(cd, m, n, np, POISON_F32, 0); - if (unchanged && FAILAT("output poison survived")) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - else for (uint32_t r = 0; r < m; r++) memcpy(&c[(size_t)r * n], &cd[(size_t)r * np], (size_t)n * sizeof *c); - } - STAGE_MARK(copy_out_ns); - stages_put(&st, chip_ns, t0); - omega_gpu_session_unlock(); - return rc; -} -#undef STAGE_MARK - -static int resident_entry(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, OmegaGpuMatmulInfo *info) { - uint64_t t0 = now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!a || !b || !c || m == 0 || !b->mem.cpu) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (m > OMEGA_BW_MATMUL_MAX_M) return OMEGA_GPU_MATMUL_TOO_LARGE; - int rc = matmul_core(m, a, NULL, b, c, info); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -int omega_gpu_matmul_resident_bf16(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, - OmegaGpuMatmulInfo *info) { - return resident_entry(m, a, b, c, info); -} - -int omega_gpu_matmul_resident_f32(uint32_t m, const float *a, const OmegaGpuTensor *b, float *c, - OmegaGpuMatmulInfo *info) { - uint64_t t0 = now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!a || !b || !c || m == 0 || !b->mem.cpu) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (m > OMEGA_BW_MATMUL_MAX_M) return OMEGA_GPU_MATMUL_TOO_LARGE; - int rc = matmul_core(m, NULL, a, b, c, info); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -/* Host oracle: double accumulation of the bf16 inputs; an element mismatches when - * its error exceeds ORACLE_TOL of the accumulation scale (sum of |terms|). */ -static void oracle(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, const float *c, OmegaGpuMatmulInfo *info) { - float max_abs = 0.0f, max_rel = 0.0f; - size_t mism = 0; - for (uint32_t i = 0; i < m; i++) { - for (uint32_t j = 0; j < n; j++) { - double acc = 0.0, scale = 0.0; - for (uint32_t t = 0; t < k; t++) { - double p = (double)omega_bf16_to_fp32(a[(size_t)i * k + t]) * (double)omega_bf16_to_fp32(b[(size_t)t * n + j]); - acc += p; scale += abs_d(p); - } - double d = abs_d(acc - (double)c[(size_t)i * n + j]); - double rel = d / (scale > 1e-6 ? scale : 1e-6); - if ((float)d > max_abs) max_abs = (float)d; - if ((float)rel > max_rel) max_rel = (float)rel; - if (rel > ORACLE_TOL) mism++; - } - } - info->max_abs_err = max_abs; info->max_rel_err = max_rel; info->mismatch_count = mism; - info->oracle_ran = true; info->parity_verified = (mism == 0); -} - -int omega_gpu_matmul_bf16(uint32_t m, uint32_t k, uint32_t n, - const uint16_t *a, const uint16_t *b, float *c, - OmegaGpuMatmulInfo *info) { - uint64_t t0 = now_ns(); - OmegaGpuMatmulInfo local; - if (!info) info = &local; - memset(info, 0, sizeof *info); - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) - return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaGpuTensor *t = NULL; - int rc = omega_gpu_tensor_upload_bf16(k, n, b, &t); - if (rc != OMEGA_GPU_MATMUL_OK) return rc; - rc = matmul_core(m, a, NULL, t, c, info); - omega_gpu_tensor_free(t); - info->resident = false; - if (rc == OMEGA_GPU_MATMUL_OK && g.oracle) { - oracle(m, k, n, a, b, c, info); - if (!info->parity_verified) rc = OMEGA_GPU_MATMUL_PARITY_FAIL; - } - info->call_ns = now_ns() - t0; - return rc; -} - -int omega_gpu_matmul_f32(uint32_t m, uint32_t k, uint32_t n, - const float *a, const float *b, float *c, - OmegaGpuMatmulInfo *info) { - if (info) memset(info, 0, sizeof *info); - if (!a || !b || !c || m == 0 || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) - return OMEGA_GPU_MATMUL_TOO_LARGE; - size_t na = (size_t)m * k, nb = (size_t)k * n; - uint16_t *ab = omega_gpu_host_alloc(na * sizeof *ab); - uint16_t *bb = omega_gpu_host_alloc(nb * sizeof *bb); - if (!ab || !bb) { omega_gpu_host_free(ab); omega_gpu_host_free(bb); return OMEGA_GPU_MATMUL_BAD_ARGS; } - for (size_t i = 0; i < na; i++) ab[i] = omega_fp32_to_bf16(a[i]); - for (size_t i = 0; i < nb; i++) bb[i] = omega_fp32_to_bf16(b[i]); - int rc = omega_gpu_matmul_bf16(m, k, n, ab, bb, c, info); - omega_gpu_host_free(ab); - omega_gpu_host_free(bb); - return rc; -} diff --git a/src/omega_gpu_matmul_api.h b/src/omega_gpu_matmul_api.h deleted file mode 100644 index d75b09962..000000000 --- a/src/omega_gpu_matmul_api.h +++ /dev/null @@ -1,222 +0,0 @@ -#ifndef OMEGA_GPU_MATMUL_API_H -#define OMEGA_GPU_MATMUL_API_H -/* - * omega_gpu_matmul_api: the native (no CUDA) matrix-multiply entry point for - * the AIEN inference stack (FB-1 cut 1, 2026-10-03; cut 1b speed, 2026-10-04). - * - * Inputs are row-major bf16 (A: m x k, B: k x n), output is row-major f32 - * (C: m x n). Kernels are generated by our own codegen and cached in-process. - * - * Cut 1b: - * - the whole K dimension is accumulated on the chip (looped HMMA kernel, - * omega_blackwell_codegen_matmul_tensor_loop); no host K slicing; - * - the device and its channel are opened once per process and reused; - * - weights are uploaded once (omega_gpu_tensor_upload_*) and stay resident; - * omega_gpu_matmul_resident_* then moves only the activation rows and the - * result per call. The original omega_gpu_matmul_* calls keep working (they - * upload B, run, free) and keep running the host oracle per call as cut 1 - * promised; the resident calls never run an oracle (speed), the caller or - * the test holds the reference. - * - every call poisons the output rows on the device before the launch and - * refuses a result that still holds poison (OUTPUT_UNCHANGED -> CHIP_FAIL). - * - an uncertain completion (marker wait timed out) latches the process: - * nothing is freed or closed (the GPU may still be running) and every later - * call returns CHIP_FAIL, as the engine does (omega_gpu_engine.h). - */ -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_MATMUL_OK = 0, - OMEGA_GPU_MATMUL_BAD_ARGS = -1, /* NULL pointer, zero dimension, shape mismatch, out of memory */ - OMEGA_GPU_MATMUL_TOO_LARGE = -2, /* a dimension exceeds OMEGA_BW_MATMUL_MAX_* */ - OMEGA_GPU_MATMUL_CODEGEN_FAIL = -3, /* our codegen refused the shape */ - OMEGA_GPU_MATMUL_CHIP_FAIL = -4, /* device open, alloc, submit, marker, release or output-written check failed */ - OMEGA_GPU_MATMUL_PARITY_FAIL = -5 /* chip result disagrees with the host oracle (non-resident calls only) */ -}; - -/* Kernel tile rule (omega_blackwell_codegen_matmul_tensor_loop): M multiple of - * 16, N multiple of 8, K multiple of 16. The API zero-pads: A rows/columns on - * the way in per call, B at upload, and reads back only the real m x n block. */ -#define OMEGA_GPU_MATMUL_TILE_M 16 -#define OMEGA_GPU_MATMUL_TILE_N 8 -#define OMEGA_GPU_MATMUL_TILE_K 16 -/* Launch envelope. Cut 1 (2026-10-03 sweep, evidence GPU-MATMUL-API-2ea8e67, - * investigation I42) saw grids of 128 CTAs and above lose output with the - * single-tile kernel. The looped kernel does not need big grids: each CTA walks - * column tiles x, x + grid_x, ... so any shape is one launch inside the budget - * (rows are split across launches only when m / 16 alone exceeds it). The - * budget is a tunable (omega_gpu_matmul_set_cta_budget) so the chip test can - * measure larger grids. - * Default 1024 since omega #473 R4 (sealed receipt evidence/R4-MATMUL-CTA-ffc3176a, - * tests/gpu_matmul_r4_receipt.c): every output element of every call compared - * with a double reference at 8192x768x{2304,768,3072}, 8192x3072x768, - * 1024x768x50304 and two single-tile-kernel shapes (1x2048x8192, 112x768x3072), - * budgets 64..1024, 3 repeats per sign, bit-identical repeats and runs, no - * stale (I42) element at any grid of 128 CTAs and up, mutant caught. 1024 has - * the least chip time summed over all seven shapes; it was 64 before. The - * speedup is for the five training shapes only (1.3x-1.7x less chip time than - * at 64). The small shape 112x768x3072 is 1.1x-2x SLOWER at 1024 than at 64 - * (0.32 ms at 64, 0.62 ms at 1024 in run 2); callers dominated by small - * shapes can lower the budget with omega_gpu_matmul_set_cta_budget. */ -#define OMEGA_GPU_MATMUL_MAX_CTAS 1024 - -typedef struct { - uint32_t m, k, n; - uint32_t padded_m, padded_n;/* shape handed to the kernel */ - uint32_t k_slices; /* always 1 since cut 1b (whole K on the chip) */ - uint32_t chip_calls; /* launches made (row blocks) */ - uint32_t rows_per_call; /* row block height chosen for the CTA envelope */ - uint64_t elapsed_ns; /* sum of chip launch-to-completion over the launches */ - float max_abs_err; /* vs host oracle (non-resident calls only, else 0) */ - float max_rel_err; /* vs host oracle, relative to the accumulation scale */ - size_t mismatch_count; /* host oracle elements beyond tolerance (non-resident calls only) */ - bool parity_verified; /* oracle ran and every element agreed (always false for resident calls) */ - uint32_t completion_marker; /* observed first marker word of the last launch */ - bool kernel_cache_hit; /* every launch found its kernel already generated */ - char target_chip[64]; - uint32_t sm_architecture; - /* cut 1b additions (appended; earlier fields keep their offsets) */ - uint32_t grid_x, grid_y; /* grid of the last launch */ - uint32_t padded_k; - bool resident; /* B came from a resident tensor handle */ - bool oracle_ran; /* the host oracle was computed for this call */ - uint64_t call_ns; /* wall time of the whole API call (copy-in, launch, wait, copy-out) */ -} OmegaGpuMatmulInfo; - -/* Resident weight tensor: k x n bf16, zero-padded to the tile rule, kept in - * GPU-uncached unified memory until freed. Opaque. */ -typedef struct OmegaGpuTensor OmegaGpuTensor; - -/* Upload a k x n row-major matrix once. f32 input is rounded to bf16 on the - * host (round-to-nearest-even). Opens the device on first use. */ -int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuTensor **out); -int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuTensor **out); -void omega_gpu_tensor_free(OmegaGpuTensor *t); -void omega_gpu_tensor_shape(const OmegaGpuTensor *t, uint32_t *k, uint32_t *n); - -/* Replace a resident tensor's values in place (a training step's new weights): b is k x n row-major and - * k, n must equal the tensor's shape (BAD_ARGS otherwise, nothing written); f32 is rounded to bf16 as at - * upload. The new values are packed straight into the tensor's existing GPU-uncached device buffer: no - * driver allocation or free and no host allocation, so it is allowed while the API is sealed and has no - * out-of-memory path. Refused (CHIP_FAIL, nothing written) when the session is latched or the handle's - * device was closed; BAD_ARGS for NULL arguments. - * - * Thread safety of the resident calls: omega_gpu_matmul_resident_* and omega_gpu_tensor_update_* - * each hold the session lock for the whole call, and a launch has completed before its call - * returns, so a resident matmul reads B entirely from before or entirely from after an update, - * never a mix, and an update never writes while the chip reads. upload builds a new buffer and - * needs no ordering. The caller must not free a tensor while another thread uses it. */ -int omega_gpu_tensor_update_bf16(OmegaGpuTensor *t, uint32_t k, uint32_t n, const uint16_t *b); -int omega_gpu_tensor_update_f32(OmegaGpuTensor *t, uint32_t k, uint32_t n, const float *b); - -/* C[m x n] = A[m x k] * B, B resident (k and n come from the handle). No host - * oracle: info->parity_verified is false, mismatch_count 0. */ -int omega_gpu_matmul_resident_bf16(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, - OmegaGpuMatmulInfo *info); -int omega_gpu_matmul_resident_f32(uint32_t m, const float *a, const OmegaGpuTensor *b, float *c, - OmegaGpuMatmulInfo *info); - -/* C[m x n] = A[m x k] * B[k x n], bf16 inputs, f32 output. info may be NULL. - * Uploads B for the call, runs, frees it, and checks the result against the - * host oracle (double accumulation, tolerance 1e-5 of the accumulation scale). */ -int omega_gpu_matmul_bf16(uint32_t m, uint32_t k, uint32_t n, - const uint16_t *a, const uint16_t *b, float *c, - OmegaGpuMatmulInfo *info); - -/* Same, taking f32 inputs: they are rounded to bf16 on the host first - * (round-to-nearest-even), so the result carries bf16 input precision. */ -int omega_gpu_matmul_f32(uint32_t m, uint32_t k, uint32_t n, - const float *a, const float *b, float *c, - OmegaGpuMatmulInfo *info); - -/* Name of a return code, for logs and receipts. */ -const char *omega_gpu_matmul_rc_name(int rc); - -/* Drop every cached kernel (host and device copies). */ -void omega_gpu_matmul_cache_clear(void); - -/* Close the device and free every API-owned buffer (not resident tensors the - * caller still holds; free those first). Refused (no-op) after an uncertain - * completion. The next call reopens. */ -void omega_gpu_device_close(void); - -/* 1 once an uncertain completion has latched this process. */ -int omega_gpu_matmul_is_blocked(void); - -/* Stage name of the most recent CHIP_FAIL ("" if none), for logs and receipts. */ -const char *omega_gpu_matmul_last_error(void); - -/* Where the time of one matmul goes (omega #473). A separate struct, not new OmegaGpuMatmulInfo fields: - * Rust callers mirror OmegaGpuMatmulInfo by size (no size assert), and the API memsets the caller's - * struct, so growing it would overrun every mirror that has not been updated. The stages tile the - * call's work in order; core_ns is their span, so core_ns - (the six stages) is clock overhead only. - * setup_ns lock wait, device open, launch shape, staging buffer growth - * pack_ns activation rows packed into the GPU-visible staging buffer (f32 -> bf16 on the way), - * plus the result sentinels - * upload_ns CPU-to-GPU visibility of both staging buffers (platform sync) - * launch_ns kernel cache lookup (or build), submit and completion wait, every launch; contains chip_ns - * chip_ns = OmegaGpuMatmulInfo.elapsed_ns (launch to completion marker, summed over launches) - * sync_ns GPU-to-CPU visibility of the result buffer - * copy_out_ns sentinel scan and copy of the real m x n block into the caller's array - * The non-resident calls add the B upload before and the host oracle after (in OmegaGpuMatmulInfo.call_ns, - * not here). */ -typedef struct { - uint64_t setup_ns, pack_ns, upload_ns, launch_ns, chip_ns, sync_ns, copy_out_ns; - uint64_t core_ns; /* entry to exit of the matmul body; a resident call's call_ns adds argument checks only */ -} OmegaGpuMatmulStages; -/* Stages of the most recent matmul in this process. The record is ONE per process, shared by every thread: - * another thread's matmul can overwrite it between your call and this read, so read it from the thread that - * made the call, with no other matmul in between. Calls are serialized by the session lock, so a read never sees - * a half-written record. All zero before the first call; a call that fails records the stages it reached. */ -void omega_gpu_matmul_last_stages(OmegaGpuMatmulStages *out); - -/* CTA budget per launch (default OMEGA_GPU_MATMUL_MAX_CTAS; 0 restores it). - * Clears the kernel cache (kernels bake in grid_x). Test and measurement knob. */ -void omega_gpu_matmul_set_cta_budget(uint32_t ctas); -uint32_t omega_gpu_matmul_cta_budget(void); - -/* OPT-IN serving reservation (omega_gpu_reserve_serving in omega_gpu_serving.h calls this). Allocates the - * activation and result staging buffers once for calls of up to max_rows rows over weights up to max_k x max_n - * (max_n_one_row, 0 = none: a wider n allowed for calls of at most 16 rows, e.g. lm_head), and makes the kernel - * cache kernel_slots deep (0 or <= 8 = unchanged; at most 128). From then on a call that fits never allocates - * staging; a call that does not fit returns OMEGA_GPU_MATMUL_TOO_LARGE with omega_gpu_matmul_last_error() saying - * "serving reservation exceeded", and asks the driver for nothing. Never called = behaviour unchanged. The kernel - * cache still builds each NEW shape once (one small code buffer); a slot count at least the number of distinct - * shapes keeps them for good. 0 on success, else an OMEGA_GPU_MATMUL_* code. */ -int omega_gpu_matmul_reserve(uint32_t max_rows, uint32_t max_k, uint32_t max_n, uint32_t max_n_one_row, uint32_t kernel_slots); - -/* OPT-IN, after omega_gpu_matmul_reserve: build now the kernel a call of m rows over a k x n weight will use, and - * pin it (a prepared kernel is never evicted). The kernel cache key bakes in grid_x, which depends on the row - * count, so a server prepares every (row count, weight shape) it will run; repeated keys are cache hits. Refused - * with TOO_LARGE, before any build or driver call, when every slot already holds a prepared kernel. */ -int omega_gpu_matmul_prepare(uint32_t m, uint32_t k, uint32_t n); -/* on = 1: from now on a call whose kernel is not cached is refused with OMEGA_GPU_MATMUL_TOO_LARGE ("serving - * reservation exceeded: matmul kernel ... was not prepared") and asks the driver for nothing. 0 lifts it; closing - * the device also ends it. */ -void omega_gpu_matmul_seal(int on); -/* Drop the reservation flag (buffers stay allocated, growth is allowed again). */ -void omega_gpu_matmul_unreserve(void); - -/* Host oracle on the non-resident calls (default on). */ -void omega_gpu_matmul_set_oracle(int on); - -/* TEST ONLY. Non-zero generates deliberately wrong kernels (last K step - * dropped) so the parity test can prove it catches a wrong kernel. Clears the - * kernel cache. Production code must never call this. */ -void omega_gpu_matmul_test_set_mutant(int on); -/* Test only: force the fragment kernel unroll (1, 2, 4 or 8; it must divide kp / 16 or the call - * fails CODEGEN_FAIL); 0 restores the automatic choice. Clears the kernel cache. */ -void omega_gpu_matmul_test_set_unroll(uint32_t unroll); -/* Test hook: one-row calls so far that wrote only row 0 into a buffer already zero in rows 1..15. */ -uint64_t omega_gpu_matmul_test_a_row0_hits(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_mem_cached.c b/src/omega_gpu_mem_cached.c deleted file mode 100644 index 79a6c48d8..000000000 --- a/src/omega_gpu_mem_cached.c +++ /dev/null @@ -1,24 +0,0 @@ -#include "omega_gpu_mem_cached.h" -#include -#include "omega_gpu_platform.h" -#include "omega_gpu_fmt.h" - -int omega_gpu_session_alloc_cached(size_t bytes, OmegaGpuMem *out) { - if (!out || bytes == 0) { omega_gpu_session_set_error("cached alloc: arguments"); return -1; } - memset(out, 0, sizeof *out); - OmegaGpuSession *s = omega_gpu_session_open(); - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - if (!s || !p) return -1; - const size_t want = (bytes + 0xfffu) & ~(size_t)0xfffu; - OmegaGpuBufferDesc d = { .kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ, /* no CPU_READ: the platform refuses a CPU-readable GPU-cached buffer */ - .gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED, .align = 0x1000u, .bytes = want }; - OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; - int prc = p->dma_alloc(p->ctx, s->dev, &d, &out->handle, &cpu, &va, &bus); - if (prc != OMEGA_GPU_PLAT_OK || !cpu.ptr || cpu.len < want) { - if (prc == OMEGA_GPU_PLAT_OK) (void)p->dma_free(p->ctx, out->handle); - char e[96]; omega_gpu_fmt(e, sizeof e, "cached alloc of %zu bytes refused (%d)", want, prc); - omega_gpu_session_set_error(e); memset(out, 0, sizeof *out); return -1; - } - out->kind = OMEGA_GPU_HANDLE_BUF_DATA; out->cpu = cpu.ptr; out->va = va.va; out->size = cpu.len; - return 0; -} diff --git a/src/omega_gpu_mem_cached.h b/src/omega_gpu_mem_cached.h deleted file mode 100644 index 7c257fab4..000000000 --- a/src/omega_gpu_mem_cached.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef OMEGA_GPU_MEM_CACHED_H -#define OMEGA_GPU_MEM_CACHED_H -/* GPU-cached device-visible memory for read-only weights (OWN-30B L2 kernel-time cut). - * - * The session's own allocations are GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will not - * be coherent with direct CPU mappings"). Weights are written once by the CPU before their first GPU use - * (omega_gpu_session_sync_to_gpu), are never host-polled and never rewritten, so the GPU may cache them. Same descriptor - * as omega_gpu_prefill.c in omega-own30b-tc (W-L1G, T3b 4a84906b) minus CPU_READ: the platform allows GPU-cached data buffers - * only without CPU_READ / HOST_POLLED. Invariant here: the CPU writes the buffer once (fresh allocation, never read by the GPU - * yet, so no stale L2 line exists), omega_gpu_session_sync_to_gpu flushes the CPU side, then only the GPU reads it, ever. - * The caller holds the session lock with the device - * open (as for omega_gpu_session_alloc); the buffer is freed and synced through the session like any other. */ -#include -#include "omega_gpu_session.h" -#ifdef __cplusplus -extern "C" { -#endif -int omega_gpu_session_alloc_cached(size_t bytes, OmegaGpuMem *out); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_moe_api.c b/src/omega_gpu_moe_api.c deleted file mode 100644 index 8f18e3bec..000000000 --- a/src/omega_gpu_moe_api.c +++ /dev/null @@ -1,424 +0,0 @@ -/* - * omega_gpu_moe_api.c: column windows over a resident bf16 tensor (OWN-30B cut 2). See the header. - * - * Same submission path, buffers, poison check and latch rules as omega_gpu_matmul_api.c (FB-1 cut 1b - * on the shared session), restated here rather than shared because that file is owned by the 8B - * decode-speed lane and its tensor type is opaque; this file only ADDS exports. Every buffer both - * sides touch is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will not - * be coherent with direct CPU mappings"). - * - * The window rule: B is in fragment order (omega_matmul_frag_pack_b), column tile nt = kp x 8 - * elements contiguous at element nt * kp * 8. A window starting at column tile t0 of width wnp - * (padded to 8) is therefore the chip-proven kernel for (kp, wnp) with b_va advanced by - * t0 * kp * 8 * 2 bytes. Nothing else about the launch changes. - */ -#include "omega_gpu_moe_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include "omega_blackwell_qmd.h" -#include - -#define MOE_CACHE_SLOTS 16 /* default kernel cache slots; raised only by omega_gpu_moe_reserve */ -#define MOE_CACHE_SLOTS_MAX 128 -#define FRAG_PACK_TILES 64u /* column tiles per host packing chunk at upload */ -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -struct OmegaGpuMoeTensor { - uint32_t k, n, kp, np; - OmegaGpuMem mem; /* kp x np bf16 in fragment order */ -}; - -typedef struct { - bool valid, pinned; - uint32_t kp, np, grid_x, rt, ct; - int mutant; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} MoeCacheSlot; - -static struct { - OmegaGpuScratch a_buf, c_buf; - bool a_row0_ready; uint32_t a_row0_kp; const void *a_row0_cpu; - uint64_t a_row0_hits; - uint32_t cta_budget; - int mutant; - int32_t skew; /* test only: column tiles added to every window's B base */ - bool hooked; - MoeCacheSlot cache[MOE_CACHE_SLOTS_MAX]; - unsigned cache_next, slots; - int sealed; -} g = { .cta_budget = OMEGA_GPU_MATMUL_MAX_CTAS, .slots = MOE_CACHE_SLOTS }; - -#define FAILAT(s) (omega_gpu_session_set_error(s), 1) -static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } -static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } - -uint64_t omega_gpu_moe_window_byte_offset(uint32_t kp, uint32_t col0) { - return (uint64_t)(col0 / OMEGA_GPU_MATMUL_TILE_N) * kp * OMEGA_GPU_MATMUL_TILE_N * 2u; -} - -/* ---- device-side state (caller holds the session lock) ---- */ - -static void cache_clear_locked(void) { - for (unsigned i = 0; i < MOE_CACHE_SLOTS_MAX; i++) { - MoeCacheSlot *s = &g.cache[i]; - if (!s->valid) continue; - omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - } - g.cache_next = 0; -} - -static void on_session_close(void) { - cache_clear_locked(); - g.a_row0_ready = false; - omega_gpu_session_scratch_free(&g.a_buf); - omega_gpu_session_scratch_free(&g.c_buf); - g.slots = MOE_CACHE_SLOTS; - g.sealed = 0; -} - -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} - -void omega_gpu_moe_cache_clear(void) { - omega_gpu_session_lock(); - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -void omega_gpu_moe_set_cta_budget(uint32_t ctas) { - omega_gpu_session_lock(); - g.cta_budget = ctas ? ctas : OMEGA_GPU_MATMUL_MAX_CTAS; - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -uint32_t omega_gpu_moe_cta_budget(void) { return g.cta_budget; } - -void omega_gpu_moe_test_set_mutant(int on) { - omega_gpu_session_lock(); - g.mutant = on ? 1 : 0; - cache_clear_locked(); - omega_gpu_session_unlock(); -} - -void omega_gpu_moe_test_set_window_skew(int32_t tiles) { - omega_gpu_session_lock(); - g.skew = tiles; - omega_gpu_session_unlock(); -} - -uint64_t omega_gpu_moe_test_a_row0_hits(void) { return g.a_row0_hits; } - -/* ---- launch shape and kernel cache (the matmul API's rules, restated) ---- */ - -static void launch_shape(uint32_t mp, uint32_t np, uint32_t *rows_per_launch, uint32_t *grid_x, uint32_t *rt, uint32_t *ct) { - const uint32_t budget = g.cta_budget ? g.cta_budget : OMEGA_GPU_MATMUL_MAX_CTAS, mt = mp / 16u, nt = np / 8u; - omega_matmul_frag_block_shape(mt, nt, rt, ct); - const uint32_t rb = mt / *rt, nb = nt / *ct; - *rows_per_launch = rb <= budget ? mp : budget * 16u * *rt; - uint32_t gx = budget / (*rows_per_launch / 16u / *rt); - if (gx == 0) gx = 1; - if (gx > nb) gx = nb; - *grid_x = gx; -} - -static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, uint32_t rt, uint32_t ct, MoeCacheSlot **out, bool *hit) { - for (unsigned i = 0; i < g.slots; i++) { - MoeCacheSlot *s = &g.cache[i]; - if (s->valid && s->kp == kp && s->np == np && s->grid_x == grid_x && s->rt == rt && s->ct == ct && s->mutant == g.mutant) { - *out = s; *hit = true; - return OMEGA_GPU_MATMUL_OK; - } - } - if (g.sealed) { - char e[160]; - omega_gpu_fmt(e, sizeof e, "serving reservation exceeded: moe window kernel kp=%u np=%u grid_x=%u rt=%u ct=%u was not prepared", kp, np, grid_x, rt, ct); - omega_gpu_session_set_error(e); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - MoeCacheSlot *s = NULL; - for (unsigned i = 0; i < g.slots && !s; i++) { - MoeCacheSlot *c = &g.cache[(g.cache_next + i) % g.slots]; - if (!c->valid || !c->pinned) { s = c; g.cache_next = (unsigned)((c - g.cache) + 1) % g.slots; } - } - if (!s) { - omega_gpu_session_set_error("moe window kernel cache: every slot holds a prepared kernel (raise kernel_slots)"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - OmegaMatMulSpec spec; - if (omega_matmul_spec_init(&spec, 16, kp, np, OMEGA_MATMUL_PRECISION_BF16) != 0) return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaBlackwellKernel kernel; - memset(&kernel, 0, sizeof kernel); - const bool blocked = rt > 1 || ct > 1; - uint32_t unroll = blocked ? omega_matmul_frag_block_unroll(kp, rt, ct) : omega_matmul_frag_unroll(kp); - if (g.mutant) while (unroll > 1 && kp / 16u / unroll < 2) unroll /= 2; - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("moe window codegen: host memory"); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - int cg = blocked ? omega_blackwell_codegen_matmul_frag_block_prog(&spec, grid_x, unroll, rt, ct, g.mutant, prog) - : omega_blackwell_codegen_matmul_frag_prog(&spec, grid_x, unroll, g.mutant, prog); - const size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - s->valid = true; s->pinned = false; s->kp = kp; s->np = np; s->grid_x = grid_x; s->rt = rt; s->ct = ct; s->mutant = g.mutant; - s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_MATMUL_OK; -} - -static int launch(const MoeCacheSlot *ks, uint64_t a_va, uint64_t b_va, uint64_t c_va, - uint32_t grid_x, uint32_t grid_y, uint64_t *elapsed_ns, uint32_t *marker_out) { - uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - omega_blackwell_build_cbank_args_matmul(cbank_args, a_va, b_va, c_va, grid_y * 16u * ks->rt, ks->kp, ks->np); - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = omega_bw_gpr_declared(ks->kernel.gpr_count), /* peak + 2 rounded up to 8 (the session passed the raw peak before) */ - .threads_x = 32, .threads_y = 1, .grid_x = grid_x, .grid_y = grid_y, - .num_elements = (size_t)grid_x * grid_y * 128u, - .args = cbank_args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - return omega_gpu_session_launch(&L, elapsed_ns, marker_out) == 0 ? OMEGA_GPU_MATMUL_OK : OMEGA_GPU_MATMUL_CHIP_FAIL; -} - -/* ---- serving reservation ---- */ - -int omega_gpu_moe_reserve(uint32_t max_rows, uint32_t max_k, uint32_t max_cols, uint32_t kernel_slots) { - if (max_rows == 0 || max_k == 0 || max_cols == 0) { omega_gpu_session_set_error("moe reserve: zero bound"); return OMEGA_GPU_MATMUL_BAD_ARGS; } - if (max_rows > OMEGA_BW_MATMUL_MAX_M || max_k > OMEGA_BW_MATMUL_MAX_K || max_cols > OMEGA_BW_MATMUL_MAX_N || kernel_slots > MOE_CACHE_SLOTS_MAX) { - omega_gpu_session_set_error("moe reserve: bound past the matmul envelope"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - const size_t mp = round_up(max_rows, OMEGA_GPU_MATMUL_TILE_M), kp = round_up(max_k, OMEGA_GPU_MATMUL_TILE_K); - const size_t c_bytes = mp * round_up(max_cols, OMEGA_GPU_MATMUL_TILE_N) * 4u; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - else if (omega_gpu_session_scratch_reserve(&g.a_buf, mp * kp * 2u) != 0 || omega_gpu_session_scratch_reserve(&g.c_buf, c_bytes) != 0) { - omega_gpu_session_scratch_unreserve(&g.a_buf); omega_gpu_session_scratch_unreserve(&g.c_buf); - rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - } else if (kernel_slots > g.slots) { - cache_clear_locked(); - g.slots = kernel_slots; - } - g.a_row0_ready = false; - omega_gpu_session_unlock(); - return rc; -} - -void omega_gpu_moe_unreserve(void) { - omega_gpu_session_lock(); - omega_gpu_session_scratch_unreserve(&g.a_buf); - omega_gpu_session_scratch_unreserve(&g.c_buf); - omega_gpu_session_unlock(); -} - -int omega_gpu_moe_prepare(uint32_t m, uint32_t k, uint32_t cols) { - if (m == 0 || k == 0 || cols == 0) { omega_gpu_session_set_error("moe prepare: zero dimension"); return OMEGA_GPU_MATMUL_BAD_ARGS; } - if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || cols > OMEGA_BW_MATMUL_MAX_N) { - omega_gpu_session_set_error("moe prepare: shape past the matmul envelope"); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M), kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K), np = round_up(cols, OMEGA_GPU_MATMUL_TILE_N); - uint32_t rows_per_launch, grid_x, rt, ct; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - else { - launch_shape(mp, np, &rows_per_launch, &grid_x, &rt, &ct); - MoeCacheSlot *s = NULL; bool hit = false; - rc = kernel_for(kp, np, grid_x, rt, ct, &s, &hit); - if (rc == OMEGA_GPU_MATMUL_OK) s->pinned = true; - } - omega_gpu_session_unlock(); - return rc; -} - -void omega_gpu_moe_seal(int on) { - omega_gpu_session_lock(); - g.sealed = on ? 1 : 0; - omega_gpu_session_unlock(); -} - -/* ---- tensors ---- */ - -void omega_gpu_moe_tensor_shape(const OmegaGpuMoeTensor *t, uint32_t *k, uint32_t *n) { - if (k) *k = t ? t->k : 0; - if (n) *n = t ? t->n : 0; -} - -int omega_gpu_moe_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuMoeTensor **out) { - if (out) *out = NULL; - if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaGpuMoeTensor *t = omega_gpu_host_calloc(1, sizeof *t); - if (!t) return OMEGA_GPU_MATMUL_BAD_ARGS; - t->k = k; t->n = n; t->kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K); t->np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); - const uint32_t nt = t->np / 8u; - uint16_t *h = omega_gpu_host_alloc((size_t)FRAG_PACK_TILES * t->kp * 8u * sizeof *h); - if (!h) { omega_gpu_host_free(t); return OMEGA_GPU_MATMUL_BAD_ARGS; } - int rc = OMEGA_GPU_MATMUL_OK; - omega_gpu_session_lock(); - if (!dev_open_locked() || omega_gpu_session_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_MATMUL_OK) { omega_gpu_host_free(h); omega_gpu_host_free(t); return rc; } - uint16_t *d = t->mem.cpu; - for (uint32_t nt0 = 0; nt0 < nt; nt0 += FRAG_PACK_TILES) { - const uint32_t nt1 = nt - nt0 < FRAG_PACK_TILES ? nt : nt0 + FRAG_PACK_TILES; - omega_matmul_frag_pack_b(b, k, n, t->kp, nt0, nt1, h); - memcpy(&d[(size_t)nt0 * t->kp * 8u], h, (size_t)(nt1 - nt0) * t->kp * 8u * sizeof *h); - } - omega_gpu_host_free(h); - if (omega_gpu_session_sync_to_gpu(&t->mem) != 0) { omega_gpu_moe_tensor_free(t); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - *out = t; - return OMEGA_GPU_MATMUL_OK; -} - -int omega_gpu_moe_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuMoeTensor **out) { - if (out) *out = NULL; - if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; - size_t cnt = (size_t)k * n; - uint16_t *h = omega_gpu_host_alloc(cnt * sizeof *h); - if (!h) return OMEGA_GPU_MATMUL_BAD_ARGS; - for (size_t i = 0; i < cnt; i++) h[i] = omega_fp32_to_bf16(b[i]); - int rc = omega_gpu_moe_tensor_upload_bf16(k, n, h, out); - omega_gpu_host_free(h); - return rc; -} - -void omega_gpu_moe_tensor_free(OmegaGpuMoeTensor *t) { - if (!t) return; - omega_gpu_session_lock(); - omega_gpu_session_free(&t->mem); - omega_gpu_session_unlock(); - omega_gpu_host_free(t); -} - -/* ---- the window matmul ---- */ - -/* The alignment rule, fail-closed, with the stage named. */ -static int window_args_ok(const OmegaGpuMoeTensor *t, uint32_t col0, uint32_t cols) { - char e[160]; - if (col0 % OMEGA_GPU_MATMUL_TILE_N != 0) { - omega_gpu_fmt(e, sizeof e, "moe window: col0=%u is not a multiple of %u (a window starts on a column tile)", col0, OMEGA_GPU_MATMUL_TILE_N); - omega_gpu_session_set_error(e); - return 0; - } - if (cols == 0 || col0 > t->n || cols > t->n - col0) { - omega_gpu_fmt(e, sizeof e, "moe window: [%u, %u + %u) is not inside the tensor's %u columns", col0, col0, cols, t->n); - omega_gpu_session_set_error(e); - return 0; - } - return 1; -} - -/* a16 or a32 (exactly one non-NULL). nwin windows of `cols` columns at col0[w]; c receives nwin - * blocks of m x cols. The activation pack and the kernel are shared by every window of the call. */ -static int windows_core(uint32_t m, const uint16_t *a16, const float *a32, const OmegaGpuMoeTensor *t, - uint32_t nwin, const uint32_t *col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info) { - const uint32_t k = t->k, kp = t->kp; - const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M), np = round_up(cols, OMEGA_GPU_MATMUL_TILE_N); - for (uint32_t w = 0; w < nwin; w++) if (!window_args_ok(t, col0[w], cols)) return OMEGA_GPU_MATMUL_BAD_ARGS; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_MATMUL_OK; - if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - uint32_t rows_per_launch, grid_x, rt, ct; - launch_shape(mp, np, &rows_per_launch, &grid_x, &rt, &ct); - if (info) { - info->m = m; info->k = k; info->n = cols; info->padded_m = mp; info->padded_n = np; info->padded_k = kp; - info->k_slices = 1; info->rows_per_call = rows_per_launch; info->grid_x = grid_x; info->grid_y = rows_per_launch / 16u / rt; - info->resident = true; info->kernel_cache_hit = true; - (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; - } - if (g.sealed && !(g.a_buf.reserved && g.c_buf.reserved)) { - omega_gpu_session_set_error("serving reservation exceeded: moe window sealed without a scratch reservation (call omega_gpu_moe_reserve first)"); - omega_gpu_session_unlock(); - return OMEGA_GPU_MATMUL_TOO_LARGE; - } - int src = omega_gpu_session_scratch(&g.a_buf, (size_t)mp * kp * 2u); - if (src == 0) src = omega_gpu_session_scratch(&g.c_buf, (size_t)mp * np * 4u); - if (src != 0) { - omega_gpu_session_unlock(); - return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_MATMUL_TOO_LARGE : OMEGA_GPU_MATMUL_CHIP_FAIL; - } - uint16_t *ad = g.a_buf.mem.cpu; - const bool one_row = m == 1 && mp == 16u; - if (one_row && g.a_row0_ready && g.a_row0_kp == kp && g.a_row0_cpu == ad) { - if (a32) omega_matmul_frag_pack_a_row0_f32(a32, k, kp, ad); - else omega_matmul_frag_pack_a_row0(a16, k, kp, ad); - g.a_row0_hits++; - } else { - if (a32) omega_matmul_frag_pack_a_f32(a32, m, k, mp, kp, ad); - else omega_matmul_frag_pack_a(a16, m, k, mp, kp, ad); - g.a_row0_ready = one_row; g.a_row0_kp = kp; g.a_row0_cpu = ad; - } - if (omega_gpu_session_sync_to_gpu(&g.a_buf.mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - float *cd = g.c_buf.mem.cpu; - for (uint32_t w = 0; w < nwin && rc == OMEGA_GPU_MATMUL_OK; w++) { - /* the window's B base: column tile col0 / 8 (plus the test skew, which must be caught) */ - const int64_t tile0 = (int64_t)(col0[w] / OMEGA_GPU_MATMUL_TILE_N) + g.skew; - const uint64_t b_va = t->mem.va + (uint64_t)tile0 * kp * OMEGA_GPU_MATMUL_TILE_N * 2u; - omega_matmul_result_sentinels(cd, m, cols, np, POISON_F32, 1); - if (omega_gpu_session_sync_to_gpu(&g.c_buf.mem) != 0) { rc = OMEGA_GPU_MATMUL_CHIP_FAIL; break; } - for (uint32_t r0 = 0; r0 < mp && rc == OMEGA_GPU_MATMUL_OK; r0 += rows_per_launch) { - uint32_t rows = mp - r0 < rows_per_launch ? mp - r0 : rows_per_launch; - uint32_t grid_y = rows / 16u / rt; - MoeCacheSlot *ks = NULL; bool hit = false; - rc = kernel_for(kp, np, grid_x, rt, ct, &ks, &hit); - if (rc != OMEGA_GPU_MATMUL_OK) break; - if (info && !hit) info->kernel_cache_hit = false; - rc = launch(ks, g.a_buf.mem.va + (uint64_t)r0 * kp * 2u, b_va, g.c_buf.mem.va + (uint64_t)r0 * np * 4u, - grid_x, grid_y, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL); - if (info) info->chip_calls++; - } - if (rc != OMEGA_GPU_MATMUL_OK) break; - if (omega_gpu_session_sync_to_cpu(&g.c_buf.mem) != 0) { rc = OMEGA_GPU_MATMUL_CHIP_FAIL; break; } - size_t unchanged = omega_matmul_result_sentinels(cd, m, cols, np, POISON_F32, 0); - if (unchanged && FAILAT("output poison survived")) { rc = OMEGA_GPU_MATMUL_CHIP_FAIL; break; } - float *cw = c + (size_t)w * m * cols; - for (uint32_t r = 0; r < m; r++) memcpy(&cw[(size_t)r * cols], &cd[(size_t)r * np], (size_t)cols * sizeof *c); - } - omega_gpu_session_unlock(); - return rc; -} - -static int entry(uint32_t m, const uint16_t *a16, const float *a32, const OmegaGpuMoeTensor *t, - uint32_t nwin, const uint32_t *col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info) { - uint64_t t0 = now_ns(); - if (info) memset(info, 0, sizeof *info); - if ((!a16 && !a32) || !t || !c || !col0 || m == 0 || nwin == 0 || !t->mem.cpu) return OMEGA_GPU_MATMUL_BAD_ARGS; - if (nwin > OMEGA_GPU_MOE_MAX_WINDOWS) { omega_gpu_session_set_error("moe window: too many windows in one call"); return OMEGA_GPU_MATMUL_BAD_ARGS; } - if (m > OMEGA_BW_MATMUL_MAX_M) return OMEGA_GPU_MATMUL_TOO_LARGE; - int rc = windows_core(m, a16, a32, t, nwin, col0, cols, c, info); - if (info) info->call_ns = now_ns() - t0; - return rc; -} - -int omega_gpu_matmul_resident_window_f32(uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info) { - return entry(m, NULL, a, t, 1, &col0, cols, c, info); -} - -int omega_gpu_matmul_resident_window_bf16(uint32_t m, const uint16_t *a, const OmegaGpuMoeTensor *t, - uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info) { - return entry(m, a, NULL, t, 1, &col0, cols, c, info); -} - -int omega_gpu_matmul_resident_windows_f32(uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - uint32_t nwin, const uint32_t *col0, uint32_t cols, float *c, - OmegaGpuMatmulInfo *info) { - return entry(m, NULL, a, t, nwin, col0, cols, c, info); -} diff --git a/src/omega_gpu_moe_api.h b/src/omega_gpu_moe_api.h deleted file mode 100644 index 5838114b8..000000000 --- a/src/omega_gpu_moe_api.h +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef OMEGA_GPU_MOE_API_H -#define OMEGA_GPU_MOE_API_H -/* - * omega_gpu_moe_api: column windows over a resident bf16 weight tensor (OWN-30B cut 2, 2026-10-13). - * - * Why: a mixture-of-experts layer keeps the 128 experts' gate+up (k 2048, n 128 x 1536) and down - * (k 768, n 128 x 2048) projections as ONE resident tensor each and, per token, multiplies the - * activation row by the 8 selected experts' column windows. The whole-tensor entry - * (omega_gpu_matmul_resident_*) computes every column; this file computes only [col0, col0 + cols) - * of a resident tensor with the SAME chip-proven kernel: B is tile-major (column tile nt = kp x 8 - * elements contiguous at element nt * kp * 8, omega_blackwell_codegen.h, omega_matmul_frag_pack_b), - * so a window that starts on a column tile is the same kernel with the B base advanced to that - * tile and np = the window's padded width. No kernel change, new file only (8B-lane collision rule). - * - * ---- FFI contract (for the Rust wrapper; C ABI, every function is thread-safe through the - * process-wide session lock, every pointer is a host pointer) ---- - * - * typedef struct OmegaGpuMoeTensor OmegaGpuMoeTensor; // opaque, device resident - * - * int omega_gpu_moe_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuMoeTensor **out); - * int omega_gpu_moe_tensor_upload_f32 (uint32_t k, uint32_t n, const float *b, OmegaGpuMoeTensor **out); - * b: k x n row-major (f32 is rounded to bf16, round-to-nearest-even); packed tile-major on the - * host and kept in GPU-uncached memory until omega_gpu_moe_tensor_free. Limits: k <= 16384, - * n <= 262144 (OMEGA_BW_MATMUL_MAX_*). Returns OMEGA_GPU_MATMUL_OK (0) or an OMEGA_GPU_MATMUL_* - * code (omega_gpu_matmul_api.h); *out is NULL on failure. - * void omega_gpu_moe_tensor_free (OmegaGpuMoeTensor *t); // NULL is a no-op - * void omega_gpu_moe_tensor_shape(const OmegaGpuMoeTensor *t, uint32_t *k, uint32_t *n); - * - * int omega_gpu_matmul_resident_window_f32 (uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - * uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info); - * int omega_gpu_matmul_resident_window_bf16(uint32_t m, const uint16_t *a, const OmegaGpuMoeTensor *t, - * uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info); - * C[m x cols] = A[m x k] * B[:, col0 .. col0 + cols), f32 output row-major with row stride cols, - * i.e. element (r, j) of C equals element (r, col0 + j) of the whole-tensor product. - * a: m x k row-major (f32 rounded to bf16 on the way in, as the whole-tensor calls do). - * info may be NULL; when given it is filled like the whole-tensor call (n = cols, padded_n = the - * window's padded width, resident = true, elapsed_ns = chip time, call_ns = whole call). - * ALIGNMENT RULE (fail-closed, OMEGA_GPU_MATMUL_BAD_ARGS, omega_gpu_matmul_last_error() names it): - * col0 % 8 == 0 (OMEGA_GPU_MATMUL_TILE_N: a window starts on a column tile), - * cols >= 1 and col0 + cols <= n (never past the real columns), - * m >= 1 and m <= 8192. - * cols itself need not be a multiple of 8: the kernel computes whole tiles and only the real - * cols columns are copied out (the rest of the last tile is the tensor's next columns or its - * zero padding, computed and discarded). - * int omega_gpu_matmul_resident_windows_f32(uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - * uint32_t nwin, const uint32_t *col0, uint32_t cols, float *c, - * OmegaGpuMatmulInfo *info); - * nwin windows of the same width (the 8 experts of a token): A is packed and staged once, then one - * launch per window. c holds nwin consecutive row-major blocks of m x cols: window w's result is at - * c + w * m * cols. Every col0[w] obeys the alignment rule; nwin >= 1 and <= 64. info (if given) - * sums elapsed_ns over the windows and counts chip_calls. - * - * int omega_gpu_moe_reserve(uint32_t max_rows, uint32_t max_k, uint32_t max_cols, uint32_t kernel_slots); - * int omega_gpu_moe_prepare(uint32_t m, uint32_t k, uint32_t cols); - * void omega_gpu_moe_seal(int on); - * void omega_gpu_moe_unreserve(void); - * Serving reservation, the same contract as omega_gpu_matmul_reserve / _prepare / _seal (no - * driver allocation on the call path once reserved, sealed = an unprepared kernel is refused - * with OMEGA_GPU_MATMUL_TOO_LARGE). This API has its own staging buffers and kernel cache, so a - * server reserves both APIs. - * void omega_gpu_moe_cache_clear(void); - * void omega_gpu_moe_set_cta_budget(uint32_t ctas); // 0 restores the default; clears the kernel cache - * uint32_t omega_gpu_moe_cta_budget(void); - * - * Return codes and OmegaGpuMatmulInfo are those of omega_gpu_matmul_api.h; the failure stage is in - * omega_gpu_matmul_last_error(). An uncertain completion latches the process exactly as the - * whole-tensor API does (omega_gpu_matmul_is_blocked()). - */ -#include "omega_gpu_matmul_api.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct OmegaGpuMoeTensor OmegaGpuMoeTensor; - -#define OMEGA_GPU_MOE_MAX_WINDOWS 64u - -int omega_gpu_moe_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, OmegaGpuMoeTensor **out); -int omega_gpu_moe_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpuMoeTensor **out); -void omega_gpu_moe_tensor_free(OmegaGpuMoeTensor *t); -void omega_gpu_moe_tensor_shape(const OmegaGpuMoeTensor *t, uint32_t *k, uint32_t *n); - -int omega_gpu_matmul_resident_window_f32(uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info); -int omega_gpu_matmul_resident_window_bf16(uint32_t m, const uint16_t *a, const OmegaGpuMoeTensor *t, - uint32_t col0, uint32_t cols, float *c, OmegaGpuMatmulInfo *info); -int omega_gpu_matmul_resident_windows_f32(uint32_t m, const float *a, const OmegaGpuMoeTensor *t, - uint32_t nwin, const uint32_t *col0, uint32_t cols, float *c, - OmegaGpuMatmulInfo *info); - -int omega_gpu_moe_reserve(uint32_t max_rows, uint32_t max_k, uint32_t max_cols, uint32_t kernel_slots); -int omega_gpu_moe_prepare(uint32_t m, uint32_t k, uint32_t cols); -void omega_gpu_moe_seal(int on); -void omega_gpu_moe_unreserve(void); -void omega_gpu_moe_cache_clear(void); -void omega_gpu_moe_set_cta_budget(uint32_t ctas); -uint32_t omega_gpu_moe_cta_budget(void); - -/* Pure host arithmetic, exported for tests and the Rust side: the byte offset of column tile - * (col0 / 8) inside a packed tensor of padded depth kp, i.e. where a window's B starts. */ -uint64_t omega_gpu_moe_window_byte_offset(uint32_t kp, uint32_t col0); - -/* TEST ONLY. mutant: deliberately wrong kernels (last K pass dropped), the parity oracle must catch - * them. skew: every window's B base is moved by this many column tiles (the "wrong window" control: - * the window must then disagree with the whole-tensor columns). Both clear the kernel cache / take - * effect on the next call; production code never calls them. */ -void omega_gpu_moe_test_set_mutant(int on); -void omega_gpu_moe_test_set_window_skew(int32_t tiles); -/* Test hook: one-row calls so far that rewrote row 0 only of an already zero-padded activation pack. */ -uint64_t omega_gpu_moe_test_a_row0_hits(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_pfgemm.c b/src/omega_gpu_pfgemm.c deleted file mode 100644 index abc46f3ce..000000000 --- a/src/omega_gpu_pfgemm.c +++ /dev/null @@ -1,200 +0,0 @@ -/* omega_gpu_pfgemm.c: device-resident tensor-core FP8 grouped GEMM v2 (OWN-30B T3b). See omega_gpu_prefill.h. */ -#include "omega_gpu_prefill.h" -#include "omega_blackwell_codegen_tc2.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_fmt.h" -#include -#include - -#define KIND_TC2 2u -static struct { uint32_t rt, warps, aqn; int mutant; } g; -void omega_gpu_pf_gemm_set_shape(uint32_t rt, uint32_t warps, uint32_t aqn) { g.rt = rt; g.warps = warps; g.aqn = aqn; } -void omega_gpu_pf_gemm_test_set_mutant(int m) { g.mutant = m; } -static uint32_t RT(void) { return g.rt ? g.rt : 8u; } -uint32_t omega_gpu_pf_gemm_bm(void) { return 16u * RT(); } - -static uint32_t perm4(uint32_t q) { static const uint32_t o[4] = { 0, 2, 1, 3 }; return (q & ~3u) | o[q & 3u]; } - -int omega_gpu_pf_weights_host_form(uint32_t E, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *sinv, uint32_t layout, uint8_t *pw, float *ratio) { - if (!E || !n || !k || n % 128u || k % 128u || !w || !sinv || !pw || !ratio || layout > OMEGA_GPU_PF_SWIGLU) return OMEGA_GPU_PF_BAD_ARGS; - if (layout == OMEGA_GPU_PF_SWIGLU && n % 256u) return OMEGA_GPU_PF_BAD_ARGS; - const uint32_t KB = k / 128u, NB = n / 128u, I = n / 2u; - float *sf = malloc((size_t)NB * KB * 4u); - if (!sf) return OMEGA_GPU_PF_TOO_LARGE; - int rc = OMEGA_GPU_PF_OK; - for (uint32_t e = 0; e < E && rc == OMEGA_GPU_PF_OK; e++) { - if (omega_fp8_pack_scales(sinv + (size_t)e * NB * KB, (size_t)NB * KB, sf, 0) != 0) { rc = OMEGA_GPU_PF_BAD_ARGS; break; } - for (uint32_t p = 0; p < n; p++) { - uint32_t src = p; - if (layout == OMEGA_GPU_PF_SWIGLU) { uint32_t G = p / 16u, h = p % 16u, i = perm4(8u * G + h % 8u); src = h < 8u ? i : I + i; } - memcpy(pw + ((size_t)e * n + p) * k, w + ((size_t)e * n + src) * k, k); - if (p % 8u == 0) { - /* pair layout: [e][p / 16][kb 0..KB][p / 8 % 2] (the kernel loads both column tiles of a warp with one LDG.64) */ - float *rt = ratio + ((size_t)e * (n / 16u) + p / 16u) * (KB + 1u) * 2u + (p / 8u) % 2u; - const float *s = sf + (size_t)(src / 128u) * KB; - rt[0] = 1.0f; - for (uint32_t kb = 1; kb < KB; kb++) rt[2u * kb] = s[kb - 1] / s[kb]; - rt[2u * KB] = s[KB - 1]; - } - } - } - free(sf); - return rc; -} - -int omega_gpu_pf_weights_upload(uint32_t E, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *sinv, uint32_t layout, OmegaPfWeights *out) { - if (!out) return OMEGA_GPU_PF_BAD_ARGS; - memset(out, 0, sizeof *out); - const size_t wb = (size_t)E * n * k, rb = (size_t)E * (n / 8u) * (k / 128u + 1u) * 4u; - uint8_t *pw = malloc(wb); float *ratio = malloc(rb + 16u); - int rc = (!pw || !ratio) ? OMEGA_GPU_PF_TOO_LARGE : omega_gpu_pf_weights_host_form(E, n, k, w, sinv, layout, pw, ratio); - const size_t rb16 = (rb + 15u) & ~(size_t)15u; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_alloc_dev(wb, &out->w); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_alloc_dev(rb16, &out->r); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_upload(&out->w, 0, pw, wb & ~(size_t)15u); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_upload(&out->r, 0, ratio, rb16); - free(pw); free(ratio); - if (rc != OMEGA_GPU_PF_OK) { omega_gpu_pf_free(&out->w); omega_gpu_pf_free(&out->r); memset(out, 0, sizeof *out); return rc; } - out->experts = E; out->n = n; out->k = k; out->layout = layout; - return OMEGA_GPU_PF_OK; -} -void omega_gpu_pf_weights_free(OmegaPfWeights *w) { if (!w) return; omega_gpu_pf_free(&w->w); omega_gpu_pf_free(&w->r); memset(w, 0, sizeof *w); } - -typedef struct { uint64_t w_va, r_va; uint32_t row0, cnt; uint64_t pad; } Tile; -_Static_assert(sizeof(Tile) == OMEGA_TC2_TILE_BYTES, "tile entry"); -uint32_t omega_gpu_pf_gemm_tiles(const OmegaPfWeights *w, const uint32_t *counts, void *tab, uint32_t max) { - if (!w || !counts || !tab) return 0; - const uint32_t bm = omega_gpu_pf_gemm_bm(), KB = w->k / 128u; - Tile *t = tab; uint32_t nt = 0, row = 0; - for (uint32_t e = 0; e < w->experts; e++) { - for (uint32_t r = 0; r < counts[e]; r += bm) { - if (nt >= max) return 0; - t[nt].w_va = w->w.va + (uint64_t)e * w->n * w->k; - t[nt].r_va = w->r.va + (uint64_t)e * (w->n / 8u) * (KB + 1u) * 4u; - t[nt].row0 = row + r; t[nt].cnt = counts[e] - r < bm ? counts[e] - r : bm; t[nt].pad = 0; nt++; - } - row += counts[e]; - } - return nt; -} - -static int gen_tc2(const OmegaPfKey *key, void *prog) { OmegaTc2Spec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_tc2_prog(&s, prog); } - -int omega_gpu_pf_gemm(const OmegaPfWeights *w, uint64_t tiles_va, uint32_t ntiles, uint64_t rowidx_va, uint64_t x_va, uint64_t y_va, uint64_t *ns) { - if (!w || !w->w.va || !tiles_va || !x_va || !y_va) return OMEGA_GPU_PF_BAD_ARGS; - if (ntiles == 0) return OMEGA_GPU_PF_OK; - if (ntiles > 65535u) return OMEGA_GPU_PF_TOO_LARGE; - OmegaTc2Spec s; memset(&s, 0, sizeof s); - s.k = w->k; s.rt = RT(); s.ct = 2; s.warps = g.warps ? g.warps : 16u; s.aqn = g.aqn ? g.aqn : 1u; - s.epi = w->layout == OMEGA_GPU_PF_SWIGLU ? OMEGA_TC2_EPI_SWIGLU : OMEGA_TC2_EPI_F32; s.direct = rowidx_va == 0; s.n = w->n; s.mutant = g.mutant; - if (!omega_tc2_spec_ok(&s)) return OMEGA_GPU_PF_BAD_ARGS; - const uint32_t span = omega_tc2_span(&s); - if (w->n % span) return OMEGA_GPU_PF_BAD_ARGS; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_TC2; memcpy(key.words, &s, sizeof s); - _Static_assert(sizeof(OmegaTc2Spec) <= sizeof key.words, "spec fits the key"); - uint32_t args[OMEGA_TC2_ARGS_WORDS]; - const uint64_t va[4] = { tiles_va, rowidx_va, x_va, y_va }; - for (int i = 0; i < 4; i++) { args[2 * i] = (uint32_t)va[i]; args[2 * i + 1] = (uint32_t)(va[i] >> 32); } - args[8] = w->n; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - OmegaPfKernel k; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_tc2, &k); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_launch_locked(&k, 32u * s.warps, w->n / span, ntiles, omega_tc2_shared_bytes(&s), args, OMEGA_TC2_ARGS_WORDS, ns); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- native FP8 path (W-L1G): activation quantiser (omega_blackwell_codegen_qg.h) ---- */ -#include "omega_blackwell_codegen_qg.h" -#define KIND_PQ 3u -static int pq_mutant; -void omega_gpu_pf_quant_test_set_mutant(int m) { pq_mutant = m; } -static int gen_pq(const OmegaPfKey *key, void *prog) { OmegaPqSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_pq_prog(&s, prog); } -int omega_gpu_pf_quant(uint32_t k, uint32_t in_type, uint32_t rows, uint64_t x_va, uint64_t q_va, uint64_t s_va, uint64_t *ns) { - OmegaPqSpec s; memset(&s, 0, sizeof s); s.k = k; s.in_type = in_type; s.mutant = pq_mutant; - if (!omega_pq_spec_ok(&s) || !x_va || !q_va || !s_va) return OMEGA_GPU_PF_BAD_ARGS; - if (rows == 0) return OMEGA_GPU_PF_OK; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_PQ; memcpy(key.words, &s, sizeof s); - const uint32_t args[OMEGA_PQ_ARGS_WORDS] = { (uint32_t)x_va, (uint32_t)(x_va >> 32), (uint32_t)q_va, (uint32_t)(q_va >> 32), (uint32_t)s_va, (uint32_t)(s_va >> 32) }; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - OmegaPfKernel kern; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_pq, &kern); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_launch_locked(&kern, 32u * (k / 128u), rows, 1, 0, args, OMEGA_PQ_ARGS_WORDS, ns); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- native FP8 path (W-L1G): grouped GEMM on QMMA (omega_blackwell_codegen_qg.h) ---- */ -#define KIND_QG 4u -static struct { uint32_t rt, warps, wait, set; int mutant; } q; -void omega_gpu_pf_qgemm_set_shape(uint32_t rt, uint32_t warps, uint32_t wait) { q.rt = rt; q.warps = warps; q.wait = wait; q.set = rt || warps || wait; } -void omega_gpu_pf_qgemm_test_set_mutant(int m) { q.mutant = m; } -static uint32_t QRT(void) { return q.rt ? q.rt : 4u; } -static uint32_t QWARPS(void) { return q.warps ? q.warps : 8u; } -static uint32_t QWAIT(void) { return q.set ? q.wait : 45u; } /* 45 cycles: chip-safe QMMA read distance (evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13) */ -uint32_t omega_gpu_pf_qgemm_bm(void) { return 16u * QRT(); } - -/* tile table from per-expert base addresses (w_va[e], s_va[e]: GEMV-tensor layout, wherever it lives) */ -uint32_t omega_gpu_pf_qgemm_tiles_va(uint32_t E, const uint64_t *w_va, const uint64_t *s_va, const uint32_t *counts, void *tab, uint32_t max) { - if (!E || !w_va || !s_va || !counts || !tab) return 0; - const uint32_t bm = omega_gpu_pf_qgemm_bm(); - Tile *tl = tab; uint32_t nt = 0, row = 0; - for (uint32_t e = 0; e < E; e++) { - for (uint32_t r = 0; r < counts[e]; r += bm) { - if (nt >= max) return 0; - tl[nt].w_va = w_va[e]; tl[nt].r_va = s_va[e]; - tl[nt].row0 = row + r; tl[nt].cnt = counts[e] - r < bm ? counts[e] - r : bm; tl[nt].pad = 0; nt++; - } - row += counts[e]; - } - return nt; -} -/* the same straight from an FP8 GEMV tensor (omega_gpu_fp8_tensor_entry, read in place, no copy) */ -uint32_t omega_gpu_pf_qgemm_tiles(const OmegaGpuFp8Tensor *t, const uint32_t *counts, void *tab, uint32_t max) { - if (!t || !counts || !tab) return 0; - uint32_t E = 0, n = 0, k = 0; omega_gpu_fp8_tensor_shape(t, &E, &n, &k); - const uint32_t bm = omega_gpu_pf_qgemm_bm(); - Tile *tl = tab; uint32_t nt = 0, row = 0; - for (uint32_t e = 0; e < E; e++) { - if (!counts[e]) continue; - uint64_t w_va = 0, s_va = 0; - if (omega_gpu_fp8_tensor_entry(t, e, &w_va, &s_va) != 0) return 0; - for (uint32_t r = 0; r < counts[e]; r += bm) { - if (nt >= max) return 0; - tl[nt].w_va = w_va; tl[nt].r_va = s_va; - tl[nt].row0 = row + r; tl[nt].cnt = counts[e] - r < bm ? counts[e] - r : bm; tl[nt].pad = 0; nt++; - } - row += counts[e]; - } - return nt; -} - -static int gen_qg(const OmegaPfKey *key, void *prog) { OmegaQgSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_qgemm_prog(&s, prog); } - -int omega_gpu_pf_qgemm(uint32_t n, uint32_t k, uint32_t layout, uint64_t tiles_va, uint32_t ntiles, uint64_t rowidx_va, uint64_t xq_va, uint64_t xs_va, uint64_t y_va, uint64_t *ns) { - if (!tiles_va || !xq_va || !xs_va || !y_va) return OMEGA_GPU_PF_BAD_ARGS; - if (layout != OMEGA_GPU_PF_PLAIN && layout != OMEGA_GPU_PF_SWIGLU_NAT) return OMEGA_GPU_PF_BAD_ARGS; - if (ntiles == 0) return OMEGA_GPU_PF_OK; - if (ntiles > 65535u) return OMEGA_GPU_PF_TOO_LARGE; - OmegaQgSpec s; memset(&s, 0, sizeof s); - s.k = k; s.rt = QRT(); s.warps = QWARPS(); s.wait = QWAIT(); s.n = n; s.mutant = q.mutant; - s.epi = layout == OMEGA_GPU_PF_SWIGLU_NAT ? OMEGA_QG_EPI_SWIGLU : OMEGA_QG_EPI_F32; s.direct = rowidx_va == 0; - if (!omega_qg_spec_ok(&s)) return OMEGA_GPU_PF_BAD_ARGS; - const uint32_t span = omega_qg_span(&s); - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_QG; memcpy(key.words, &s, sizeof s); - _Static_assert(sizeof(OmegaQgSpec) <= sizeof key.words, "spec fits the key"); - _Static_assert(sizeof(Tile) == OMEGA_QG_TILE_BYTES, "tile entry"); - uint32_t args[OMEGA_QG_ARGS_WORDS]; - const uint64_t va[5] = { tiles_va, rowidx_va, xq_va, y_va, xs_va }; - for (int i = 0; i < 5; i++) { args[2 * i] = (uint32_t)va[i]; args[2 * i + 1] = (uint32_t)(va[i] >> 32); } - args[10] = n; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - OmegaPfKernel kern; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_qg, &kern); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_launch_locked(&kern, 32u * s.warps, n / span, ntiles, omega_qg_shared_bytes(&s), args, OMEGA_QG_ARGS_WORDS, ns); - omega_gpu_session_unlock(); - return rc; -} diff --git a/src/omega_gpu_pfhost.c b/src/omega_gpu_pfhost.c deleted file mode 100644 index 02b8c0d17..000000000 --- a/src/omega_gpu_pfhost.c +++ /dev/null @@ -1,59 +0,0 @@ -/* omega_gpu_pfhost.c: launchers for the whole-prompt router logits and MoE combine (W-L1G-D). See omega_gpu_pfhost.h. */ -#include "omega_gpu_pfhost.h" -#include "omega_blackwell_codegen_pfhost.h" -#include - -#define KIND_RL 0x50u -#define KIND_MC 0x51u -static int rl_mutant, mc_mutant; -static uint32_t rl_rows; -void omega_gpu_pf_router_test_set_mutant(int m) { rl_mutant = m; } -void omega_gpu_pf_combine_test_set_mutant(int m) { mc_mutant = m; } -void omega_gpu_pf_router_set_rows(uint32_t t) { rl_rows = t; } -uint32_t omega_gpu_pf_router_rows(void) { return rl_rows ? rl_rows : 16u; } - -size_t omega_gpu_pf_router_packed_bytes(uint32_t e, uint32_t k) { return (size_t)(k / 4u + 1u) * e * 16u; } -void omega_gpu_pf_router_pack(uint32_t e, uint32_t k, const float *w, float *wq) { - if (!w || !wq) return; - for (uint32_t g = 0; g < k / 4u; g++) - for (uint32_t ex = 0; ex < e; ex++) - for (uint32_t q = 0; q < 4u; q++) wq[((size_t)g * e + ex) * 4u + q] = w[(size_t)ex * k + 4u * g + q]; - memset(wq + (size_t)(k / 4u) * e * 4u, 0, (size_t)e * 16u); -} - -static int gen_rl(const OmegaPfKey *key, void *prog) { OmegaRlSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_rl_prog(&s, prog); } -static int gen_mc(const OmegaPfKey *key, void *prog) { OmegaMcSpec s; memcpy(&s, key->words, sizeof s); return omega_blackwell_codegen_mc_prog(&s, prog); } - -int omega_gpu_pf_router_logits(uint32_t k, uint32_t e, uint32_t rows, uint64_t x_va, uint64_t wq_va, uint64_t logits_va, uint64_t *ns) { - OmegaRlSpec s; memset(&s, 0, sizeof s); s.k = k; s.e = e; s.t = omega_gpu_pf_router_rows(); s.mutant = rl_mutant; - if (!omega_rl_spec_ok(&s) || !x_va || !wq_va || !logits_va || (x_va & 15u) || (wq_va & 15u) || (logits_va & 3u)) return OMEGA_GPU_PF_BAD_ARGS; - if (rows == 0) return OMEGA_GPU_PF_OK; - _Static_assert(sizeof(OmegaRlSpec) <= sizeof(((OmegaPfKey *)0)->words), "spec fits the key"); - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_RL; memcpy(key.words, &s, sizeof s); - const uint32_t args[OMEGA_RL_ARGS_WORDS] = { (uint32_t)x_va, (uint32_t)(x_va >> 32), (uint32_t)wq_va, (uint32_t)(wq_va >> 32), (uint32_t)logits_va, (uint32_t)(logits_va >> 32) }; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - OmegaPfKernel kern; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_rl, &kern); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_launch_locked(&kern, e, (rows + s.t - 1u) / s.t, 1, omega_rl_shared_bytes(&s), args, OMEGA_RL_ARGS_WORDS, ns); - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_pf_moe_combine(uint32_t h, uint32_t top_k, uint32_t rows, uint64_t down_va, uint64_t inv_va, uint64_t wt_va, uint64_t out_va, uint64_t *ns) { - OmegaMcSpec s; memset(&s, 0, sizeof s); s.h = h; s.top_k = top_k; s.mutant = mc_mutant; - if (!omega_mc_spec_ok(&s) || !down_va || !inv_va || !wt_va || !out_va) return OMEGA_GPU_PF_BAD_ARGS; - if ((down_va | inv_va | wt_va | out_va) & 15u) return OMEGA_GPU_PF_BAD_ARGS; - if (rows == 0) return OMEGA_GPU_PF_OK; - _Static_assert(sizeof(OmegaMcSpec) <= sizeof(((OmegaPfKey *)0)->words), "spec fits the key"); - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_MC; memcpy(key.words, &s, sizeof s); - const uint32_t args[OMEGA_MC_ARGS_WORDS] = { (uint32_t)down_va, (uint32_t)(down_va >> 32), (uint32_t)inv_va, (uint32_t)(inv_va >> 32), - (uint32_t)wt_va, (uint32_t)(wt_va >> 32), (uint32_t)out_va, (uint32_t)(out_va >> 32) }; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - OmegaPfKernel kern; - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_mc, &kern); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_launch_locked(&kern, h / 4u, rows, 1, 0, args, OMEGA_MC_ARGS_WORDS, ns); - omega_gpu_session_unlock(); - return rc; -} diff --git a/src/omega_gpu_pfhost.h b/src/omega_gpu_pfhost.h deleted file mode 100644 index 383983fe5..000000000 --- a/src/omega_gpu_pfhost.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef OMEGA_GPU_PFHOST_H -#define OMEGA_GPU_PFHOST_H -/* - * omega_gpu_pfhost (OWN-30B W-L1G-D, 2026-10-14): the whole-prompt prefill's router logits and MoE combine on the chip. New file. - * Kernels and their exact semantics: omega_blackwell_codegen_pfhost.h (bit-identical to the Rust driver's host loops). - * Buffers are omega_gpu_prefill.h buffers (DEVICE or HOST, by VA); every call takes the session lock and is synchronous. - * - * uint32_t omega_gpu_pf_router_rows(void); - * Rows per CTA of the router-logits launch (t). x must have ceil(rows / t) * t readable rows; logits gets that many rows. - * size_t omega_gpu_pf_router_packed_bytes(uint32_t e, uint32_t k); - * void omega_gpu_pf_router_pack(uint32_t e, uint32_t k, const float *w, float *wq); - * w: f32 [e][k] (row ex = expert ex); wq: the packed layout R4 plus the pad group (zeros), packed_bytes bytes. - * int omega_gpu_pf_router_logits(uint32_t k, uint32_t e, uint32_t rows, uint64_t x_va, uint64_t wq_va, uint64_t logits_va, uint64_t *ns); - * int omega_gpu_pf_moe_combine(uint32_t h, uint32_t top_k, uint32_t rows, uint64_t down_va, uint64_t inv_va, uint64_t wt_va, - * uint64_t out_va, uint64_t *ns); - * Return codes OMEGA_GPU_PF_*; *ns (when given) gains the chip nanoseconds. - */ -#include -#include -#include "omega_gpu_prefill.h" - -#ifdef __cplusplus -extern "C" { -#endif -uint32_t omega_gpu_pf_router_rows(void); -size_t omega_gpu_pf_router_packed_bytes(uint32_t e, uint32_t k); -void omega_gpu_pf_router_pack(uint32_t e, uint32_t k, const float *w, float *wq); -int omega_gpu_pf_router_logits(uint32_t k, uint32_t e, uint32_t rows, uint64_t x_va, uint64_t wq_va, uint64_t logits_va, uint64_t *ns); -int omega_gpu_pf_moe_combine(uint32_t h, uint32_t top_k, uint32_t rows, uint64_t down_va, uint64_t inv_va, uint64_t wt_va, uint64_t out_va, uint64_t *ns); -/* tests only: kernel mutants (0 restores) and the router's rows per CTA (0 = default 16) */ -void omega_gpu_pf_router_test_set_mutant(int m); -void omega_gpu_pf_combine_test_set_mutant(int m); -void omega_gpu_pf_router_set_rows(uint32_t t); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_platform.c b/src/omega_gpu_platform.c deleted file mode 100644 index 79f43c94a..000000000 --- a/src/omega_gpu_platform.c +++ /dev/null @@ -1,192 +0,0 @@ -/* omega_gpu_platform.c -- contract checks and the handle table of - * src/omega_gpu_platform.h. Freestanding: no libc beyond memset. */ -#include "omega_gpu_platform.h" - -#include - -static const char *const REFUSAL_NAMES[OMEGA_GPU_PLAT_REFUSAL_COUNT] = { - "OK", - "REFUSED_ARGS", - "REFUSED_ABI", - "REFUSED_MISSING_SERVICE", - "REFUSED_NULL_SERVICE", - "REFUSED_BAD_HANDLE", - "REFUSED_STALE_HANDLE", - "REFUSED_BAD_LENGTH", - "REFUSED_BAD_RIGHTS", - "REFUSED_BAD_KIND", - "REFUSED_CACHE_POLICY", - "REFUSED_LIMIT", - "REFUSED_BUSY", - "REFUSED_DEVICE", -}; - -const char *omega_gpu_platform_refusal_name(int refusal) -{ - if (refusal < 0 || refusal >= (int)OMEGA_GPU_PLAT_REFUSAL_COUNT) return "UNKNOWN"; - return REFUSAL_NAMES[refusal]; -} - -int omega_gpu_platform_negotiate(const OmegaGpuPlatformCaps *provided, const OmegaGpuPlatformCaps *required) -{ - if (!provided || !required) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (provided->abi_major != required->abi_major) return OMEGA_GPU_PLAT_REFUSED_ABI; - if (provided->abi_minor < required->abi_minor) return OMEGA_GPU_PLAT_REFUSED_ABI; - if ((provided->services | required->services) & ~OMEGA_GPU_SVC_ALL) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (required->services & ~provided->services) return OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE; - if (required->max_devices > provided->max_devices) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (required->max_buffers > provided->max_buffers) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (required->max_queues > provided->max_queues) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (required->max_inflight > provided->max_inflight) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (required->max_buffer_bytes > provided->max_buffer_bytes) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (required->max_total_bytes > provided->max_total_bytes) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - return OMEGA_GPU_PLAT_OK; -} - -/* A claimed service must have its functions; an unclaimed one must have none - * (a function the table never negotiated would be a silent fallback path). */ -static int svc(uint32_t services, uint32_t bit, int present_all, int present_any) -{ - if (services & bit) return present_all ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE; - return present_any ? OMEGA_GPU_PLAT_REFUSED_ARGS : OMEGA_GPU_PLAT_OK; -} - -int omega_gpu_platform_check(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) -{ - return omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_V1); -} - -int omega_gpu_platform_check_for(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps, uint32_t required) -{ - int rc; - uint32_t s; - if (!p || !caps) return OMEGA_GPU_PLAT_REFUSED_ARGS; - s = caps->services; - if (s & ~OMEGA_GPU_SVC_ALL) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (required & ~OMEGA_GPU_SVC_ALL) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if ((s & required) != required) return OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE; - if ((rc = svc(s, OMEGA_GPU_SVC_TIME, p->time_now_ms != 0, p->time_now_ms != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_WAIT, p->wait_ms != 0, p->wait_ms != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_LOCK, p->lock != 0 && p->unlock != 0, p->lock != 0 || p->unlock != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_MMIO, p->mmio_read32 != 0 && p->mmio_write32 != 0, - p->mmio_read32 != 0 || p->mmio_write32 != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_DMA, p->dma_alloc != 0 && p->dma_free != 0, - p->dma_alloc != 0 || p->dma_free != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_SYNC, p->sync_cpu_to_gpu != 0 && p->sync_gpu_to_cpu != 0, - p->sync_cpu_to_gpu != 0 || p->sync_gpu_to_cpu != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_COMPLETION, p->poll_word != 0, p->poll_word != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_IRQ, p->irq_wait != 0, p->irq_wait != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_DEVICE, p->device_open != 0 && p->device_close != 0 && p->diag_text != 0, - p->device_open != 0 || p->device_close != 0 || p->diag_text != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_QUEUE, - p->queue_open != 0 && p->queue_close != 0 && p->queue_submit != 0 && p->queue_retire != 0, - p->queue_open != 0 || p->queue_close != 0 || p->queue_submit != 0 || p->queue_retire != 0)) != 0) - return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_CLOCK_NS, p->time_now_ns != 0, p->time_now_ns != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_HOST_MEM, p->host_alloc != 0 && p->host_free != 0, - p->host_alloc != 0 || p->host_free != 0)) != 0) - return rc; - return OMEGA_GPU_PLAT_OK; -} - -static int is_pow2(uint32_t v) -{ - return v != 0u && (v & (v - 1u)) == 0u; -} - -int omega_gpu_platform_check_buffer(const OmegaGpuBufferDesc *d, const OmegaGpuPlatformCaps *caps) -{ - uint32_t r; - if (!d || !caps) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (d->kind != OMEGA_GPU_HANDLE_BUF_DATA && d->kind != OMEGA_GPU_HANDLE_BUF_CODE && - d->kind != OMEGA_GPU_HANDLE_BUF_QUEUE) - return OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (d->bytes == 0u) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - if (d->bytes > caps->max_buffer_bytes) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (d->align != 0u && !is_pow2(d->align)) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (d->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED && d->gpu_cache != OMEGA_GPU_CACHE_GPU_CACHED) - return OMEGA_GPU_PLAT_REFUSED_ARGS; - r = d->rights; - if (r == 0u || (r & ~OMEGA_GPU_RIGHT_ALL)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - if ((r & OMEGA_GPU_RIGHT_GPU_EXEC) && d->kind != OMEGA_GPU_HANDLE_BUF_CODE) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - if (d->kind == OMEGA_GPU_HANDLE_BUF_CODE) { - /* code: CPU writes it, GPU executes it, GPU never writes it, nobody polls it */ - if (r & (OMEGA_GPU_RIGHT_GPU_WRITE | OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - if (!(r & OMEGA_GPU_RIGHT_GPU_EXEC) || !(r & OMEGA_GPU_RIGHT_CPU_WRITE)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - } - if (d->kind == OMEGA_GPU_HANDLE_BUF_QUEUE) { - /* a submission ring: the CPU writes methods, the device reads them */ - if (!(r & OMEGA_GPU_RIGHT_CPU_WRITE) || !(r & OMEGA_GPU_RIGHT_GPU_READ)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - } - if (r & OMEGA_GPU_RIGHT_HOST_POLLED) { - if (!(r & OMEGA_GPU_RIGHT_CPU_READ) || !(r & OMEGA_GPU_RIGHT_GPU_WRITE)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - if (d->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED) return OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY; - } - return OMEGA_GPU_PLAT_OK; -} - -void omega_gpu_handles_init(OmegaGpuHandleTable *t) -{ - uint32_t i; - if (!t) return; - memset(t, 0, sizeof *t); - for (i = 0; i < OMEGA_GPU_HANDLE_SLOTS; i++) t->generation[i] = 1u; -} - -static int kind_known(uint32_t kind) -{ - return kind >= OMEGA_GPU_HANDLE_DEVICE && kind < OMEGA_GPU_HANDLE_KIND_COUNT; -} - -int omega_gpu_handles_open(OmegaGpuHandleTable *t, uint32_t kind, uint64_t bytes, uint32_t limit_slots, - uint64_t limit_bytes, uint32_t *index, uint32_t *generation) -{ - uint32_t i; - uint32_t same_kind = 0; - if (!t || !index || !generation) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (!kind_known(kind)) return OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - for (i = 0; i < OMEGA_GPU_HANDLE_SLOTS; i++) - if (t->live[i] && t->kind[i] == kind) same_kind++; - if (same_kind >= limit_slots) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (bytes != 0u && (bytes > limit_bytes || t->total_bytes > limit_bytes - bytes)) /* byte accounting: buffers only */ - return OMEGA_GPU_PLAT_REFUSED_LIMIT; - for (i = 0; i < OMEGA_GPU_HANDLE_SLOTS; i++) { - if (t->live[i]) continue; - if (t->generation[i] == 0u) continue; /* generation wrapped: the slot is retired, never reissued */ - t->live[i] = 1; - t->kind[i] = kind; - t->bytes[i] = bytes; - t->nlive++; - t->total_bytes += bytes; - *index = i; - *generation = t->generation[i]; - return OMEGA_GPU_PLAT_OK; - } - return OMEGA_GPU_PLAT_REFUSED_LIMIT; -} - -int omega_gpu_handles_check(const OmegaGpuHandleTable *t, uint32_t index, uint32_t generation, uint32_t kind) -{ - if (!t) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (index >= OMEGA_GPU_HANDLE_SLOTS || generation == 0u) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - if (!t->live[index] || t->generation[index] != generation) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (t->kind[index] != kind) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - return OMEGA_GPU_PLAT_OK; -} - -int omega_gpu_handles_close(OmegaGpuHandleTable *t, uint32_t index, uint32_t generation, uint32_t kind) -{ - int rc = omega_gpu_handles_check(t, index, generation, kind); - if (rc != OMEGA_GPU_PLAT_OK) return rc; - t->live[index] = 0; - t->total_bytes -= t->bytes[index]; - t->bytes[index] = 0u; - t->nlive--; - t->generation[index]++; /* the closed handle is now stale; 0 after wrap retires the slot */ - return OMEGA_GPU_PLAT_OK; -} diff --git a/src/omega_gpu_platform.h b/src/omega_gpu_platform.h deleted file mode 100644 index 34c91cb9c..000000000 --- a/src/omega_gpu_platform.h +++ /dev/null @@ -1,249 +0,0 @@ -/* omega_gpu_platform.h -- native platform contract for the Omega GPU engine. - * - * Native v1 P07 cut A (aienos#286 cut A, aien-architecture#190). This header - * names what a GPU backend may ask of the platform it runs on, in a form that - * works the same under Linux (today's nvrm/m16 backend) and under AIENOS - * (the native backend of later cuts). It is pure C with no Linux header and - * no libc call; it builds in the freestanding link target - * (`make gpu-engine-freestanding`). - * - * Rules (from aienos#286 cut A): - * - Resources are typed handles (index + generation), never a Linux fd, a - * raw pointer or an unchecked physical address. A handle is valid only - * while its slot generation matches, so a closed handle is refused. - * - Every byte range carries an explicit length and explicit rights. - * - CPU views, GPU virtual addresses and bus (SMMU input) addresses are - * three distinct types. There is no type for a raw physical address on - * purpose: the native backend resolves DMA through the SMMU (cut B). - * - Buffers, code and queues have separate kinds and lifetimes. - * - A backend negotiates an ABI version and a service set up front; what - * the platform does not provide is refused, never emulated. There is no - * silent fallback to Linux, to the CPU, or to a remote device. - * - Polling a word is not interrupt support: OMEGA_GPU_SVC_IRQ is claimed - * only by a platform whose irq_wait blocks on a real device interrupt. - * - Anything the CPU polls for a device write (completion markers, - * semaphores) is OMEGA_GPU_RIGHT_HOST_POLLED and must be GPU-uncached - * (nvidia-open 580.173.02 nvos.h: GPU-cacheable system memory "will not - * be coherent with direct CPU mappings"; the 2026-10-02 E1 stall). - * - * What this header does NOT claim: no device has been opened through it, no - * GB10 register has been touched, and the Linux backend still owns every - * driver responsibility (docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md). Hardware - * evidence for device ownership is NOT_RUN until cut B runs in an attended - * window. - */ -#ifndef OMEGA_GPU_PLATFORM_H -#define OMEGA_GPU_PLATFORM_H - -#include -#include - -#define OMEGA_GPU_PLATFORM_ABI_MAJOR 1u -/* minor: additive change (a service bit or a caps field appended); negotiate refuses a provided minor older than the - * required one. 1.1 (P07 cut C session part): DEVICE, QUEUE, CLOCK_NS, HOST_MEM; COMPLETION is poll_word. - * 1.2 (omega #457/#459): caps.submit_prefix_words. */ -#define OMEGA_GPU_PLATFORM_ABI_MINOR 2u - -/* ---- typed handles ------------------------------------------------------ */ - -/* Generation 0 is never issued, so a zeroed handle is "none". */ -typedef struct { uint32_t index; uint32_t generation; } OmegaGpuDeviceHandle; -typedef struct { uint32_t index; uint32_t generation; } OmegaGpuBufferHandle; -typedef struct { uint32_t index; uint32_t generation; } OmegaGpuQueueHandle; - -/* Handle kinds (also the buffer kinds below share the BUF_* space). */ -typedef enum { - OMEGA_GPU_HANDLE_DEVICE = 1, - OMEGA_GPU_HANDLE_BUF_DATA = 2, /* inputs, outputs, scratch */ - OMEGA_GPU_HANDLE_BUF_CODE = 3, /* kernel code: CPU writes once, GPU executes, GPU never writes */ - OMEGA_GPU_HANDLE_BUF_QUEUE = 4, /* pushbuffer / submission ring */ - OMEGA_GPU_HANDLE_QUEUE = 5, /* a channel or submission queue */ - OMEGA_GPU_HANDLE_KIND_COUNT -} OmegaGpuHandleKind; - -/* ---- address kinds ------------------------------------------------------ */ - -typedef struct { void *ptr; size_t len; } OmegaCpuView; /* CPU mapping with its length */ -typedef struct { uint64_t va; } OmegaGpuVa; /* GPU virtual address (device page tables) */ -typedef struct { uint64_t iova; } OmegaGpuBusAddr; /* what the device emits on the fabric (SMMU input) */ - -/* ---- rights and buffer descriptors -------------------------------------- */ - -enum { - OMEGA_GPU_RIGHT_CPU_READ = 1u << 0, - OMEGA_GPU_RIGHT_CPU_WRITE = 1u << 1, - OMEGA_GPU_RIGHT_GPU_READ = 1u << 2, - OMEGA_GPU_RIGHT_GPU_WRITE = 1u << 3, - OMEGA_GPU_RIGHT_GPU_EXEC = 1u << 4, /* code buffers only */ - OMEGA_GPU_RIGHT_HOST_POLLED = 1u << 5, /* CPU polls a device write here: must be GPU-uncached */ - OMEGA_GPU_RIGHT_ALL = (1u << 6) - 1u -}; - -typedef enum { OMEGA_GPU_CACHE_GPU_UNCACHED = 0, OMEGA_GPU_CACHE_GPU_CACHED = 1 } OmegaGpuCachePolicy; - -typedef struct { - uint32_t kind; /* OMEGA_GPU_HANDLE_BUF_DATA, _BUF_CODE or _BUF_QUEUE */ - uint32_t rights; /* OMEGA_GPU_RIGHT_* mask, never 0 */ - uint32_t gpu_cache; /* OmegaGpuCachePolicy */ - uint32_t align; /* bytes, a power of two, 0 means the platform minimum */ - uint64_t bytes; /* explicit length, never 0 */ -} OmegaGpuBufferDesc; - -/* ---- services and capabilities ------------------------------------------ */ - -enum { - OMEGA_GPU_SVC_TIME = 1u << 0, /* monotonic millisecond clock */ - OMEGA_GPU_SVC_WAIT = 1u << 1, /* bounded sleep or yield */ - OMEGA_GPU_SVC_LOCK = 1u << 2, /* mutual exclusion for queues and tables */ - OMEGA_GPU_SVC_MMIO = 1u << 3, /* bounded register access by device handle and region */ - OMEGA_GPU_SVC_DMA = 1u << 4, /* device-visible memory with CPU view, GPU VA and bus address */ - OMEGA_GPU_SVC_SYNC = 1u << 5, /* explicit CPU<->GPU visibility (cache maintenance, flush) */ - OMEGA_GPU_SVC_COMPLETION = 1u << 6, /* POLL an uncached word (poll_word); polling is never an interrupt */ - OMEGA_GPU_SVC_IRQ = 1u << 7, /* real device interrupt wait; polling never counts */ - OMEGA_GPU_SVC_REQUIRED_V1 = OMEGA_GPU_SVC_TIME | OMEGA_GPU_SVC_WAIT | OMEGA_GPU_SVC_LOCK | - OMEGA_GPU_SVC_MMIO | OMEGA_GPU_SVC_DMA | OMEGA_GPU_SVC_SYNC | - OMEGA_GPU_SVC_COMPLETION, - /* ABI 1.1: what the persistent GPU session (src/omega_gpu_session.c) needs on top of v1 */ - OMEGA_GPU_SVC_DEVICE = 1u << 8, /* open / close one device context, driver text of the last failure */ - OMEGA_GPU_SVC_QUEUE = 1u << 9, /* submission queue over a BUF_QUEUE ring: open, submit, retire, close */ - OMEGA_GPU_SVC_CLOCK_NS = 1u << 10, /* monotonic nanosecond clock (launch timing) */ - OMEGA_GPU_SVC_HOST_MEM = 1u << 11, /* CPU-only memory for tables and staging (never device-visible) */ - OMEGA_GPU_SVC_REQUIRED_SESSION = OMEGA_GPU_SVC_TIME | OMEGA_GPU_SVC_WAIT | OMEGA_GPU_SVC_LOCK | - OMEGA_GPU_SVC_DMA | OMEGA_GPU_SVC_SYNC | OMEGA_GPU_SVC_COMPLETION | - OMEGA_GPU_SVC_DEVICE | OMEGA_GPU_SVC_QUEUE | OMEGA_GPU_SVC_CLOCK_NS | - OMEGA_GPU_SVC_HOST_MEM, - OMEGA_GPU_SVC_ALL = (1u << 12) - 1u -}; - -typedef struct { - uint32_t abi_major; - uint32_t abi_minor; - uint32_t services; /* OMEGA_GPU_SVC_* provided (or required) */ - uint32_t max_devices; - uint32_t max_buffers; /* live buffer handles */ - uint32_t max_queues; - uint32_t max_inflight; /* jobs in flight per queue (concurrency limit) */ - uint64_t max_buffer_bytes; /* one buffer */ - uint64_t max_total_bytes; /* all live buffers */ - uint32_t submit_prefix_words; /* ABI 1.2: most words queue_submit may put ahead of the caller's words in the ring (the Linux - * reference: the omega #457 L2 invalidate); a caller filling the ring budgets - * ring words minus this. 0 = never. Not negotiated. */ -} OmegaGpuPlatformCaps; - -/* ---- refusals ----------------------------------------------------------- */ - -typedef enum { - OMEGA_GPU_PLAT_OK = 0, - OMEGA_GPU_PLAT_REFUSED_ARGS, /* NULL or malformed argument */ - OMEGA_GPU_PLAT_REFUSED_ABI, /* major differs, or provided minor older than required */ - OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE, /* a required service is not provided */ - OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE, /* a claimed service has no function */ - OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE, /* index out of range or kind mismatch */ - OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE, /* generation mismatch: closed or never opened */ - OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH, /* zero length */ - OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS, /* empty, unknown or contradictory rights */ - OMEGA_GPU_PLAT_REFUSED_BAD_KIND, /* unknown kind */ - OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY, /* host-polled buffer asked to be GPU-cached */ - OMEGA_GPU_PLAT_REFUSED_LIMIT, /* a capability limit would be exceeded */ - OMEGA_GPU_PLAT_REFUSED_BUSY, /* concurrency limit reached */ - OMEGA_GPU_PLAT_REFUSED_DEVICE, /* 1.1: the device or its driver refused (diag_text says why) */ - OMEGA_GPU_PLAT_REFUSAL_COUNT -} OmegaGpuPlatformRefusal; - -const char *omega_gpu_platform_refusal_name(int refusal); /* static strings, never NULL */ - -/* poll_word result when the word did not reach the value in time (not a refusal: nothing was wrong with the call). */ -#define OMEGA_GPU_POLL_TIMED_OUT 100 - -/* ---- the platform service table ----------------------------------------- */ - -typedef struct { - void *ctx; - /* TIME, WAIT, LOCK */ - uint64_t (*time_now_ms)(void *ctx); - int (*wait_ms)(void *ctx, uint64_t ms); - int (*lock)(void *ctx, uint32_t lock_id); - int (*unlock)(void *ctx, uint32_t lock_id); - /* MMIO: bounded by (device, region); the platform refuses an offset past the region. */ - int (*mmio_read32)(void *ctx, OmegaGpuDeviceHandle dev, uint32_t region, uint64_t offset, uint32_t *out); - int (*mmio_write32)(void *ctx, OmegaGpuDeviceHandle dev, uint32_t region, uint64_t offset, uint32_t value); - /* DMA: one allocation yields a handle plus the three views; free by handle only. */ - int (*dma_alloc)(void *ctx, OmegaGpuDeviceHandle dev, const OmegaGpuBufferDesc *desc, - OmegaGpuBufferHandle *out, OmegaCpuView *cpu, OmegaGpuVa *gpu, OmegaGpuBusAddr *bus); - int (*dma_free)(void *ctx, OmegaGpuBufferHandle buf); - /* SYNC: explicit visibility over a byte range of one buffer. */ - int (*sync_cpu_to_gpu)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint64_t len); - int (*sync_gpu_to_cpu)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint64_t len); - /* COMPLETION, by POLLING (never an interrupt): read one GPU-uncached 32-bit word of a HOST_POLLED buffer until - * it has reached expected in serial-number order, (int32_t)(word - expected) >= 0 (the m16_native_wait_marker - * rule), or timeout_ms passes. 0 reached, OMEGA_GPU_POLL_TIMED_OUT not reached, else a refusal. *observed is - * the last value read. A timeout says nothing about the device: the work may still be running. */ - int (*poll_word)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint32_t expected, - uint64_t timeout_ms, uint32_t *observed); - /* IRQ: NULL unless OMEGA_GPU_SVC_IRQ is claimed. */ - int (*irq_wait)(void *ctx, OmegaGpuDeviceHandle dev, uint64_t timeout_ms); - /* ---- ABI 1.1 ---- */ - /* DEVICE: open the device context with this ordinal (0 = the one GB10), close it. Closing makes every buffer and - * queue handle of the device stale. diag_text: driver text of the most recent failure, "" if none, never NULL. */ - int (*device_open)(void *ctx, uint32_t ordinal, OmegaGpuDeviceHandle *out); - int (*device_close)(void *ctx, OmegaGpuDeviceHandle dev); - const char *(*diag_text)(void *ctx); - /* QUEUE: a submission queue whose ring is a BUF_QUEUE buffer of the same device. queue_submit copies nwords method - * words into the ring and rings the doorbell (one GPFIFO entry); queue_retire marks every submitted entry consumed - * and is called only after the caller saw that work complete. A refused queue_submit rang no doorbell: nothing of it is in - * flight (m16_native_submit_methods fails before nvrm_ring). */ - int (*queue_open)(void *ctx, OmegaGpuDeviceHandle dev, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *out); - int (*queue_close)(void *ctx, OmegaGpuQueueHandle q); - int (*queue_submit)(void *ctx, OmegaGpuQueueHandle q, const uint32_t *words, uint32_t nwords); - int (*queue_retire)(void *ctx, OmegaGpuQueueHandle q); - /* CLOCK_NS */ - uint64_t (*time_now_ns)(void *ctx); - /* HOST_MEM: NULL on refusal; host_free(NULL) is a no-op. */ - void *(*host_alloc)(void *ctx, size_t bytes); - void (*host_free)(void *ctx, void *p); -} OmegaGpuPlatform; - -/* ---- contract checks (pure, freestanding) -------------------------------- */ - -/* Version and service negotiation. required.services must be a subset of - * provided.services, required limits must not exceed provided limits. */ -int omega_gpu_platform_negotiate(const OmegaGpuPlatformCaps *provided, const OmegaGpuPlatformCaps *required); - -/* Every service in caps->services has a function in p; every function - * outside caps->services is NULL (no undeclared service, no fallback); the - * v1 required set is present. */ -int omega_gpu_platform_check(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps); -/* The same, requiring the service set `required` (for example OMEGA_GPU_SVC_REQUIRED_SESSION) instead of the v1 set. - * omega_gpu_platform_check(p, caps) is omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_V1). */ -int omega_gpu_platform_check_for(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps, uint32_t required); - -/* Buffer descriptor rules: kind known, length non-zero and within caps, - * rights non-empty and consistent with the kind, host-polled means - * GPU-uncached, align a power of two. */ -int omega_gpu_platform_check_buffer(const OmegaGpuBufferDesc *d, const OmegaGpuPlatformCaps *caps); - -/* ---- handle table (index + generation) ----------------------------------- */ - -#define OMEGA_GPU_HANDLE_SLOTS 1024u /* 1.1: a serving session holds one buffer per weight tensor (Qwen3-8B: ~260) */ - -typedef struct { - uint32_t generation[OMEGA_GPU_HANDLE_SLOTS]; /* next generation to issue for the slot; starts at 1 */ - uint32_t kind[OMEGA_GPU_HANDLE_SLOTS]; - uint64_t bytes[OMEGA_GPU_HANDLE_SLOTS]; - uint8_t live[OMEGA_GPU_HANDLE_SLOTS]; - uint32_t nlive; - uint64_t total_bytes; -} OmegaGpuHandleTable; - -void omega_gpu_handles_init(OmegaGpuHandleTable *t); -/* Opens a slot of the given kind. limit_slots caps live handles of that kind. - * bytes is accounted against limit_bytes across all slots; devices and queues - * pass bytes 0 and are not byte-accounted. */ -int omega_gpu_handles_open(OmegaGpuHandleTable *t, uint32_t kind, uint64_t bytes, uint32_t limit_slots, - uint64_t limit_bytes, uint32_t *index, uint32_t *generation); -/* OK only for a live slot whose generation and kind match. */ -int omega_gpu_handles_check(const OmegaGpuHandleTable *t, uint32_t index, uint32_t generation, uint32_t kind); -/* Closes a live, matching slot and bumps its generation so the old handle is stale. */ -int omega_gpu_handles_close(OmegaGpuHandleTable *t, uint32_t index, uint32_t generation, uint32_t kind); - -#endif /* OMEGA_GPU_PLATFORM_H */ diff --git a/src/omega_gpu_platform_linux.c b/src/omega_gpu_platform_linux.c deleted file mode 100644 index d76543f4b..000000000 --- a/src/omega_gpu_platform_linux.c +++ /dev/null @@ -1,383 +0,0 @@ -/* omega_gpu_platform_linux.c -- Linux REFERENCE implementation of OmegaGpuPlatform 1.1. REFERENCE ONLY: see the - * header. Every driver call here is the one src/omega_gpu_session.c made directly before P07 cut C, in the same - * order, so the launch path on GB10 under Linux is unchanged: - * device_open = nvrm_open + m16_native_create_channel (session open, before the four session buffers) - * dma_alloc = nvrm_alloc_gpu_uncached (every session / API buffer) - * dma_free = nvrm_free - * queue_open = ctx.pb_mem = the ring buffer (m16_native_enqueue_methods copies methods there) - * queue_submit = m16_native_submit_methods - * queue_retire = nvrm_retire(&rm, rm.put) (after both markers landed) - * poll_word = m16_native_wait_marker (>= serial compare, 50 us sleep-poll) - * sync_* = dsb sy (the barrier the session issued itself) - * device_close = m16_native_close (nvrm_close) - */ -#include "omega_gpu_platform_linux.h" - -#include "m16_native.h" -#include "nvrm.h" - -#include -#include -#include -#include -#include - -#define LINUX_REF_BUFFERS (OMEGA_GPU_HANDLE_SLOTS - 2u) /* one slot each for the device and the queue */ - -typedef struct { - pthread_mutex_t mu; /* table, device and diagnostics */ - pthread_mutex_t locks[OMEGA_GPU_PLATFORM_LINUX_LOCKS]; - int ready; - OmegaGpuHandleTable t; - NvrmMem mem[OMEGA_GPU_HANDLE_SLOTS]; - uint32_t rights[OMEGA_GPU_HANDLE_SLOTS]; - uint8_t gpu_cached[OMEGA_GPU_HANDLE_SLOTS]; /* allocated GPU-cached (nvrm_alloc), omega #457 */ - int l2_inval_pending; /* a host sync into a GPU-cached buffer since the last submission, omega #457 */ - M16NativeContext m16; - OmegaGpuDeviceHandle dev; /* generation 0 = closed */ - OmegaGpuQueueHandle queue; - char diag[320]; -} LinuxRef; - -static LinuxRef g_ref = { - .mu = PTHREAD_MUTEX_INITIALIZER, - .locks = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}, -}; - -/* omega #457: MEM_OP_A..D = 0, 0, 0, OPERATION L2_SYSMEM_NCOH_INVALIDATE 0x11 in D bits 31:27 (clc96f.h:30-73), the - * same method form as the C3 tail's L2_FLUSH_DIRTY. ref_queue_submit puts it ahead of the next submission after a host - * sync into a GPU-cached buffer; g_caps.submit_prefix_words is its size, so callers budget exactly what is written. */ -static const uint32_t L2_INVAL_PREFIX[] = { (2u << 28) | (4u << 16) | (0x0028u >> 2), 0, 0, 0, 0x11u << 27 }; -#define L2_INVAL_PREFIX_WORDS ((uint32_t)(sizeof L2_INVAL_PREFIX / sizeof L2_INVAL_PREFIX[0])) - -static const OmegaGpuPlatformCaps g_caps = { - .submit_prefix_words = L2_INVAL_PREFIX_WORDS, - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, - .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, /* no MMIO (RM owns the registers), no IRQ (polling only) */ - .max_devices = 1, - .max_buffers = LINUX_REF_BUFFERS, - .max_queues = 1, - .max_inflight = 1, - .max_buffer_bytes = 1ull << 37, /* 128 GiB: the whole unified pool */ - .max_total_bytes = 1ull << 37, -}; - -static void ref_lock(LinuxRef *r) { - pthread_mutex_lock(&r->mu); - if (!r->ready) { omega_gpu_handles_init(&r->t); r->ready = 1; } -} -static void ref_unlock(LinuxRef *r) { pthread_mutex_unlock(&r->mu); } - -/* Records why the call failed; REFUSED_DEVICE carries the driver text (Nvrm.err). Called with r->mu held. */ -static int refuse(LinuxRef *r, int rc, const char *stage) { - if (rc == OMEGA_GPU_PLAT_REFUSED_DEVICE) - snprintf(r->diag, sizeof r->diag, "%s: %s", stage, r->m16.rm.err[0] ? r->m16.rm.err : "(no driver text)"); - else - snprintf(r->diag, sizeof r->diag, "%s: %s", stage, omega_gpu_platform_refusal_name(rc)); - return rc; -} - -static int dev_ok(LinuxRef *r, OmegaGpuDeviceHandle d) { - return omega_gpu_handles_check(&r->t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); -} - -/* A live buffer handle of any buffer kind; *kind gets it. */ -static int buf_ok(LinuxRef *r, OmegaGpuBufferHandle b, uint32_t *kind) { - if (b.index >= OMEGA_GPU_HANDLE_SLOTS || b.generation == 0u) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - if (!r->t.live[b.index] || r->t.generation[b.index] != b.generation) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - const uint32_t k = r->t.kind[b.index]; - if (k != OMEGA_GPU_HANDLE_BUF_DATA && k != OMEGA_GPU_HANDLE_BUF_CODE && k != OMEGA_GPU_HANDLE_BUF_QUEUE) - return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - if (kind) *kind = k; - return OMEGA_GPU_PLAT_OK; -} - -static int range_ok(LinuxRef *r, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { - const uint64_t size = r->mem[b.index].size; - return (len == 0u || off > size || len > size - off) ? OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH : OMEGA_GPU_PLAT_OK; -} - -static uint64_t ref_now_ns(void *ctx) { - (void)ctx; - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; -} -static uint64_t ref_now_ms(void *ctx) { return ref_now_ns(ctx) / 1000000ull; } - -static int ref_wait_ms(void *ctx, uint64_t ms) { - (void)ctx; - struct timespec t = {.tv_sec = (time_t)(ms / 1000u), .tv_nsec = (long)(ms % 1000u) * 1000000L}; - while (nanosleep(&t, &t) != 0) {} - return OMEGA_GPU_PLAT_OK; -} - -static int ref_lock_id(void *ctx, uint32_t id) { - LinuxRef *r = ctx; - if (id >= OMEGA_GPU_PLATFORM_LINUX_LOCKS) return OMEGA_GPU_PLAT_REFUSED_ARGS; - return pthread_mutex_lock(&r->locks[id]) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_PLAT_REFUSED_BUSY; -} -static int ref_unlock_id(void *ctx, uint32_t id) { - LinuxRef *r = ctx; - if (id >= OMEGA_GPU_PLATFORM_LINUX_LOCKS) return OMEGA_GPU_PLAT_REFUSED_ARGS; - return pthread_mutex_unlock(&r->locks[id]) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_PLAT_REFUSED_ARGS; -} - -static int ref_device_open(void *ctx, uint32_t ordinal, OmegaGpuDeviceHandle *out) { - LinuxRef *r = ctx; - int rc; - if (!out) return OMEGA_GPU_PLAT_REFUSED_ARGS; - memset(out, 0, sizeof *out); - ref_lock(r); - if (ordinal != 0u) { rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_ARGS, "device_open"); goto out; } - if (r->dev.generation != 0u) { rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_LIMIT, "device_open (already open)"); goto out; } - memset(&r->m16, 0, sizeof r->m16); - /* nvrm_open directly (m16_native_open is memset + nvrm_open + nvrm_close on failure) so the driver's own - * failure text survives into the stage name, as the session did before cut C. */ - if (nvrm_open(&r->m16.rm) != 0) { - rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "nvrm_open"); - (void)nvrm_close(&r->m16.rm); - goto out; - } - if (m16_native_create_channel(&r->m16) != 0) { - rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "m16_native_create_channel"); - (void)m16_native_close(&r->m16); - goto out; - } - rc = omega_gpu_handles_open(&r->t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc != OMEGA_GPU_PLAT_OK) { (void)m16_native_close(&r->m16); rc = refuse(r, rc, "device_open"); goto out; } - r->dev = *out; - r->diag[0] = '\0'; -out: - ref_unlock(r); - return rc; -} - -static int ref_device_close(void *ctx, OmegaGpuDeviceHandle dev) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = dev_ok(r, dev); - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "device_close"); ref_unlock(r); return rc; } - /* Every handle of the device goes stale. The RM client close below releases the driver objects; buffers the - * caller did not free are not unmapped here, exactly as before cut C. */ - for (uint32_t i = 0; i < OMEGA_GPU_HANDLE_SLOTS; i++) { - if (!r->t.live[i] || i == dev.index) continue; - (void)omega_gpu_handles_close(&r->t, i, r->t.generation[i], r->t.kind[i]); - memset(&r->mem[i], 0, sizeof r->mem[i]); - r->rights[i] = 0; - r->gpu_cached[i] = 0; - } - (void)omega_gpu_handles_close(&r->t, dev.index, dev.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&r->dev, 0, sizeof r->dev); - r->l2_inval_pending = 0; /* omega #457: nothing pending survives the device */ - memset(&r->queue, 0, sizeof r->queue); - (void)m16_native_close(&r->m16); - ref_unlock(r); - return OMEGA_GPU_PLAT_OK; -} - -static const char *ref_diag_text(void *ctx) { return ((LinuxRef *)ctx)->diag; } - -static int ref_dma_alloc(void *ctx, OmegaGpuDeviceHandle dev, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *out, - OmegaCpuView *cpu, OmegaGpuVa *gpu, OmegaGpuBusAddr *bus) { - LinuxRef *r = ctx; - if (!desc || !out || !cpu || !gpu) return OMEGA_GPU_PLAT_REFUSED_ARGS; - memset(out, 0, sizeof *out); memset(cpu, 0, sizeof *cpu); memset(gpu, 0, sizeof *gpu); - if (bus) memset(bus, 0, sizeof *bus); - ref_lock(r); - int rc = dev_ok(r, dev); - if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - /* GPU-uncached by default. GPU-cached only for DEVICE-PRIVATE data buffers (OWN-30B T3b, 2026-10-13): no CPU_READ, no - * HOST_POLLED, so the CPU never reads a line the GPU may still hold in L2 (nvos.h:1116 "For system memory this will not be - * coherent with direct CPU mappings"). omega_gpu_mem_cached.c (OWN-30B L2) writes such a buffer from the CPU exactly once, - * before any GPU read, then syncs; omega_gpu_devmem.h (T3b) fills them with GPU writes only. Either way no stale L2 line exists. */ - const int cached = desc->gpu_cache == OMEGA_GPU_CACHE_GPU_CACHED; - if (rc == OMEGA_GPU_PLAT_OK && cached && - (desc->kind != OMEGA_GPU_HANDLE_BUF_DATA || (desc->rights & (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_HOST_POLLED)))) - rc = OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY; - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_alloc"); ref_unlock(r); return rc; } - uint32_t idx = 0, gen = 0; - rc = omega_gpu_handles_open(&r->t, desc->kind, desc->bytes, LINUX_REF_BUFFERS, g_caps.max_total_bytes, &idx, &gen); - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_alloc"); ref_unlock(r); return rc; } - NvrmMem m; - if ((cached ? nvrm_alloc(&r->m16.rm, desc->bytes, &m) : nvrm_alloc_gpu_uncached(&r->m16.rm, desc->bytes, &m)) != 0) { - (void)omega_gpu_handles_close(&r->t, idx, gen, desc->kind); /* this slot never got memory: its generation moves on */ - rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, cached ? "nvrm_alloc" : "nvrm_alloc_gpu_uncached"); - ref_unlock(r); - return rc; - } - r->mem[idx] = m; - r->rights[idx] = desc->rights; - r->gpu_cached[idx] = (uint8_t)cached; - out->index = idx; out->generation = gen; - cpu->ptr = m.cpu; cpu->len = (size_t)m.size; - gpu->va = m.va; - ref_unlock(r); - return OMEGA_GPU_PLAT_OK; -} - -static int ref_dma_free(void *ctx, OmegaGpuBufferHandle b) { - LinuxRef *r = ctx; - uint32_t kind = 0; - ref_lock(r); - int rc = buf_ok(r, b, &kind); - if (rc == OMEGA_GPU_PLAT_OK && r->queue.generation != 0u && r->m16.pb_mem.handle == r->mem[b.index].handle && - r->m16.pb_mem.cpu == r->mem[b.index].cpu) - rc = OMEGA_GPU_PLAT_REFUSED_BUSY; /* the open queue still uses it as its ring */ - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_free"); ref_unlock(r); return rc; } - (void)nvrm_free(&r->m16.rm, &r->mem[b.index]); - (void)omega_gpu_handles_close(&r->t, b.index, b.generation, kind); - memset(&r->mem[b.index], 0, sizeof r->mem[b.index]); - r->rights[b.index] = 0; - r->gpu_cached[b.index] = 0; - ref_unlock(r); - return OMEGA_GPU_PLAT_OK; -} - -static void barrier(void) { -#if defined(__aarch64__) - __asm__ volatile("dsb sy" ::: "memory"); -#else - __sync_synchronize(); -#endif -} - -static int ref_sync(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len, const char *stage, int to_gpu) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = buf_ok(r, b, NULL); - if (rc == OMEGA_GPU_PLAT_OK) rc = range_ok(r, b, off, len); - if (rc != OMEGA_GPU_PLAT_OK) rc = refuse(r, rc, stage); - /* omega #457 (chip, 2026-10-15): after the host rewrites a GPU-cached buffer the GPU already read, every later launch - * read the old bytes from L2 (nvos.h:1117 "For system memory this will not be coherent with direct CPU mappings"). - * The next submission therefore starts with L2_SYSMEM_NCOH_INVALIDATE (ref_queue_submit). */ - else if (to_gpu && r->gpu_cached[b.index]) r->l2_inval_pending = 1; - ref_unlock(r); - if (rc == OMEGA_GPU_PLAT_OK) barrier(); /* uncached system memory: a full barrier is the whole sync */ - return rc; -} -static int ref_sync_to_gpu(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { return ref_sync(ctx, b, off, len, "sync_cpu_to_gpu", 1); } -static int ref_sync_to_cpu(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { return ref_sync(ctx, b, off, len, "sync_gpu_to_cpu", 0); } - -static int ref_poll_word(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint32_t expected, uint64_t timeout_ms, uint32_t *observed) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = buf_ok(r, b, NULL); - if (rc == OMEGA_GPU_PLAT_OK && !(r->rights[b.index] & OMEGA_GPU_RIGHT_HOST_POLLED)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - if (rc == OMEGA_GPU_PLAT_OK && (off & 3u)) rc = OMEGA_GPU_PLAT_REFUSED_ARGS; - if (rc == OMEGA_GPU_PLAT_OK) rc = range_ok(r, b, off, 4u); - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "poll_word"); ref_unlock(r); return rc; } - volatile uint32_t *w = (volatile uint32_t *)((uint8_t *)r->mem[b.index].cpu + off); - ref_unlock(r); /* never hold the table lock while polling */ - rc = m16_native_wait_marker(w, expected, timeout_ms) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_POLL_TIMED_OUT; - if (observed) *observed = *w; - return rc; -} - -static int queue_ok(LinuxRef *r, OmegaGpuQueueHandle q) { - return omega_gpu_handles_check(&r->t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); -} - -static int ref_queue_open(void *ctx, OmegaGpuDeviceHandle dev, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *out) { - LinuxRef *r = ctx; - uint32_t kind = 0; - if (!out) return OMEGA_GPU_PLAT_REFUSED_ARGS; - memset(out, 0, sizeof *out); - ref_lock(r); - int rc = dev_ok(r, dev); - if (rc == OMEGA_GPU_PLAT_OK) rc = buf_ok(r, ring, &kind); - if (rc == OMEGA_GPU_PLAT_OK && kind != OMEGA_GPU_HANDLE_BUF_QUEUE) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (rc == OMEGA_GPU_PLAT_OK && r->queue.generation != 0u) rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; - if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_handles_open(&r->t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &out->index, &out->generation); - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "queue_open"); ref_unlock(r); return rc; } - r->m16.pb_mem = r->mem[ring.index]; /* m16_native_enqueue_methods copies the method stream here */ - r->queue = *out; - ref_unlock(r); - return OMEGA_GPU_PLAT_OK; -} - -static int ref_queue_close(void *ctx, OmegaGpuQueueHandle q) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = queue_ok(r, q); - if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_handles_close(&r->t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "queue_close"); ref_unlock(r); return rc; } - memset(&r->queue, 0, sizeof r->queue); - memset(&r->m16.pb_mem, 0, sizeof r->m16.pb_mem); - ref_unlock(r); - return OMEGA_GPU_PLAT_OK; -} - -static int ref_queue_submit(void *ctx, OmegaGpuQueueHandle q, const uint32_t *words, uint32_t nwords) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = queue_ok(r, q); - if (rc == OMEGA_GPU_PLAT_OK && (!words || nwords == 0u)) rc = OMEGA_GPU_PLAT_REFUSED_ARGS; - /* omega #457: a host sync into a GPU-cached buffer is pending, so this submission starts with L2_INVAL_PREFIX. - * No dirty line is dropped: every earlier submission ended with L2_FLUSH_DIRTY and the host waited for it. - * DOCS SILENT on ordering between this MEM_OP and the launch that follows (no WFI is inserted); the chip gate - * tools/run_gpu_l2_stale_chip.sh (20/20 FRESH) is the only proof. The prefix counts against the ring like any - * word; callers budget it from g_caps.submit_prefix_words (omega_gpu_cmdlist.c). */ - const uint32_t pre = r->l2_inval_pending ? L2_INVAL_PREFIX_WORDS : 0u; - if (rc == OMEGA_GPU_PLAT_OK && ((uint64_t)nwords + pre) * 4u > r->m16.pb_mem.size) rc = OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - uint32_t *buf = NULL; const char *stage = "submit_methods"; - if (rc == OMEGA_GPU_PLAT_OK && pre) { - buf = malloc(((size_t)nwords + pre) * 4u); - if (!buf) { rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; stage = "submit_methods (host copy for the #457 L2 invalidate prefix)"; } - else { - memcpy(buf, L2_INVAL_PREFIX, sizeof L2_INVAL_PREFIX); - memcpy(buf + pre, words, (size_t)nwords * 4u); - } - } - if (rc == OMEGA_GPU_PLAT_OK && m16_native_submit_methods(&r->m16, buf ? buf : words, nwords + pre) != 0) rc = OMEGA_GPU_PLAT_REFUSED_DEVICE; - if (rc == OMEGA_GPU_PLAT_OK && pre) r->l2_inval_pending = 0; - free(buf); - if (rc != OMEGA_GPU_PLAT_OK) rc = refuse(r, rc, stage); - ref_unlock(r); - return rc; -} - -static int ref_queue_retire(void *ctx, OmegaGpuQueueHandle q) { - LinuxRef *r = ctx; - ref_lock(r); - int rc = queue_ok(r, q); - if (rc == OMEGA_GPU_PLAT_OK) nvrm_retire(&r->m16.rm, r->m16.rm.put); /* both releases landed: the entry is consumed */ - else rc = refuse(r, rc, "queue_retire"); - ref_unlock(r); - return rc; -} - -static void *ref_host_alloc(void *ctx, size_t bytes) { (void)ctx; return bytes ? malloc(bytes) : NULL; } -static void ref_host_free(void *ctx, void *p) { (void)ctx; free(p); } - -static const OmegaGpuPlatform g_platform = { - .ctx = &g_ref, - .time_now_ms = ref_now_ms, - .wait_ms = ref_wait_ms, - .lock = ref_lock_id, - .unlock = ref_unlock_id, - .mmio_read32 = NULL, /* not provided: the RM driver owns the registers */ - .mmio_write32 = NULL, - .dma_alloc = ref_dma_alloc, - .dma_free = ref_dma_free, - .sync_cpu_to_gpu = ref_sync_to_gpu, - .sync_gpu_to_cpu = ref_sync_to_cpu, - .poll_word = ref_poll_word, - .irq_wait = NULL, /* polling is not interrupt support */ - .device_open = ref_device_open, - .device_close = ref_device_close, - .diag_text = ref_diag_text, - .queue_open = ref_queue_open, - .queue_close = ref_queue_close, - .queue_submit = ref_queue_submit, - .queue_retire = ref_queue_retire, - .time_now_ns = ref_now_ns, - .host_alloc = ref_host_alloc, - .host_free = ref_host_free, -}; - -const OmegaGpuPlatform *omega_gpu_platform_linux(OmegaGpuPlatformCaps *caps) { - if (caps) *caps = g_caps; - return &g_platform; -} diff --git a/src/omega_gpu_platform_linux.h b/src/omega_gpu_platform_linux.h deleted file mode 100644 index 076922b31..000000000 --- a/src/omega_gpu_platform_linux.h +++ /dev/null @@ -1,40 +0,0 @@ -/* omega_gpu_platform_linux.h -- the Linux REFERENCE implementation of OmegaGpuPlatform (ABI 1.1). - * - * REFERENCE ONLY (native v1 P07 cut C, session part; aienos#286). This is today's GB10 path under Linux - * (physics nvrm + m16_native, the open NVIDIA kernel driver), wrapped in the platform contract so the - * portable session (src/omega_gpu_session.c) runs the same launch words it always ran. It is NOT the - * native platform and is not part of the freestanding closure: it includes Linux headers, takes pthread - * mutexes, reads CLOCK_MONOTONIC and calls malloc. The AIENOS platform implements the same table over its - * own device ownership (cut B); nothing in the session may depend on anything this file does beyond the - * contract in src/omega_gpu_platform.h. - * - * What it provides: TIME, WAIT, LOCK, DMA, SYNC, COMPLETION (polling: m16_native_wait_marker, a 50 us - * sleep-poll), DEVICE, QUEUE, CLOCK_NS, HOST_MEM. Not MMIO (the RM driver owns the registers) and not IRQ - * (polling is never claimed as interrupt support). One device (ordinal 0), one queue (the m16 channel, - * GPFIFO entries carrying the method words copied into the BUF_QUEUE ring), every buffer GPU-uncached - * (nvrm_alloc_gpu_uncached; a GPU_CACHED request is refused with REFUSED_CACHE_POLICY because nothing here - * would flush it). The bus address is reported as 0: the RM driver owns the IOMMU mapping and does not - * expose it. Closing the device makes every buffer and queue handle of it stale (generation bump); the RM - * client close releases the driver objects, as the session always did. - * - * Tested by tests/test_omega_gpu_platform_linux.c on the simulated driver (tests/fake_m16_native.c); - * GB10 execution through it is the same driver calls as before this cut and is NOT re-run here. - */ -#ifndef OMEGA_GPU_PLATFORM_LINUX_H -#define OMEGA_GPU_PLATFORM_LINUX_H - -#include "omega_gpu_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_PLATFORM_LINUX_LOCKS 4u /* lock ids 0..3 */ - -/* The process-wide Linux reference platform and its caps (written to *caps when caps is not NULL). */ -const OmegaGpuPlatform *omega_gpu_platform_linux(OmegaGpuPlatformCaps *caps); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_prefill.c b/src/omega_gpu_prefill.c deleted file mode 100644 index 9cea0025b..000000000 --- a/src/omega_gpu_prefill.c +++ /dev/null @@ -1,168 +0,0 @@ -/* omega_gpu_prefill.c: device-resident prefill buffers, kernel cache and launch helper (OWN-30B T3b). See the header. */ -#include "omega_gpu_prefill.h" -#include "omega_blackwell_codegen_pf.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_blackwell_codegen_qmma.h" -#include "omega_gpu_platform.h" -#include "omega_gpu_fmt.h" -#include - -#define PF_SLOTS 64 -#define PF_STAGE_BYTES (64ull << 20) -#define PF_TIMEOUT_MS 20000ull -#define PF_SPIN_US 200000u /* spin on the marker: prefill launches are back to back, a sleep-poll costs ~100 us each */ - -typedef struct { bool valid; OmegaPfKey key; OmegaPfKernel k; OmegaGpuMem code; } Slot; -static struct { - bool hooked; - Slot slot[PF_SLOTS]; - OmegaGpuScratch stage; - uint64_t chip_ns, launches; -} g; - -const char *omega_gpu_pf_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_PF_OK: return "OK"; - case OMEGA_GPU_PF_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_PF_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_PF_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_PF_CHIP_FAIL: return "CHIP_FAIL"; - default: return "UNKNOWN"; - } -} - -static void on_close(void) { - for (unsigned i = 0; i < PF_SLOTS; i++) if (g.slot[i].valid) { omega_gpu_session_free(&g.slot[i].code); memset(&g.slot[i], 0, sizeof g.slot[i]); } - omega_gpu_session_scratch_free(&g.stage); -} -int omega_gpu_pf_open_locked(void) { - if (!g.hooked) { if (omega_gpu_session_on_close(on_close) != 0) { omega_gpu_session_set_error("prefill: no session hook slot left"); return OMEGA_GPU_PF_CHIP_FAIL; } g.hooked = true; } - return omega_gpu_session_open() ? OMEGA_GPU_PF_OK : OMEGA_GPU_PF_CHIP_FAIL; -} - -void omega_gpu_pf_stats(uint64_t *chip_ns, uint64_t *launches) { if (chip_ns) *chip_ns = g.chip_ns; if (launches) *launches = g.launches; } -void omega_gpu_pf_stats_reset(void) { g.chip_ns = 0; g.launches = 0; } - -int omega_gpu_pf_alloc_dev(size_t bytes, OmegaGpuMem *out) { - if (!out || bytes == 0) return OMEGA_GPU_PF_BAD_ARGS; - memset(out, 0, sizeof *out); - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - if (rc == OMEGA_GPU_PF_OK) { - OmegaGpuSession *s = omega_gpu_session_open(); - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - const size_t want = (bytes + 0xfffu) & ~(size_t)0xfffu; - OmegaGpuBufferDesc d = { .kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_GPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, - .gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED, .align = 0x1000u, .bytes = want }; - OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; - int prc = (s && p) ? p->dma_alloc(p->ctx, s->dev, &d, &out->handle, &cpu, &va, &bus) : OMEGA_GPU_PLAT_REFUSED_ARGS; - if (prc != OMEGA_GPU_PLAT_OK || !cpu.ptr || cpu.len < want) { - if (prc == OMEGA_GPU_PLAT_OK) (void)p->dma_free(p->ctx, out->handle); - char e[96]; omega_gpu_fmt(e, sizeof e, "prefill: cached alloc of %zu bytes refused (%d)", want, prc); - omega_gpu_session_set_error(e); memset(out, 0, sizeof *out); rc = OMEGA_GPU_PF_CHIP_FAIL; - } else { out->kind = OMEGA_GPU_HANDLE_BUF_DATA; out->cpu = cpu.ptr; out->va = va.va; out->size = cpu.len; } - } - omega_gpu_session_unlock(); - return rc; -} -int omega_gpu_pf_alloc_host(size_t bytes, OmegaGpuMem *out) { - if (!out || bytes == 0) return OMEGA_GPU_PF_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - if (rc == OMEGA_GPU_PF_OK && omega_gpu_session_alloc(bytes, out) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} -void omega_gpu_pf_free(OmegaGpuMem *m) { omega_gpu_session_lock(); omega_gpu_session_free(m); omega_gpu_session_unlock(); } - -int omega_gpu_pf_kernel_locked(const OmegaPfKey *key, OmegaPfGen gen, OmegaPfKernel *out) { - for (unsigned i = 0; i < PF_SLOTS; i++) if (g.slot[i].valid && !memcmp(&g.slot[i].key, key, sizeof *key)) { *out = g.slot[i].k; return OMEGA_GPU_PF_OK; } - Slot *s = NULL; - for (unsigned i = 0; i < PF_SLOTS && !s; i++) if (!g.slot[i].valid) s = &g.slot[i]; - if (!s) { omega_gpu_session_set_error("prefill kernel cache full"); return OMEGA_GPU_PF_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("prefill codegen: host memory"); return OMEGA_GPU_PF_CODEGEN_FAIL; } - int cg = gen(key, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill codegen refused the shape"); return OMEGA_GPU_PF_CODEGEN_FAIL; } - const uint32_t peak = prog->regalloc.peak_gpr_usage, decl = omega_bw_gpr_declared(peak); - if (decl > 128u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill kernel: more than 128 registers"); return OMEGA_GPU_PF_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_PF_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - if (cg == 0 && omega_tc_patch_code(prog, code.cpu, need) < 0) cg = -1; - if (cg == 0 && omega_qmma_patch_code(prog, code.cpu, need) < 0) cg = -1; - omega_gpu_host_free(prog); - if (cg != 0 || kernel.code_size != need) { omega_gpu_session_free(&code); omega_gpu_session_set_error("prefill encode failed"); return OMEGA_GPU_PF_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_PF_CHIP_FAIL; } - memset(s, 0, sizeof *s); - s->valid = true; s->key = *key; s->code = code; - s->k.code_va = code.va; s->k.gpr_peak = kernel.gpr_count; s->k.gpr_declared = omega_bw_gpr_declared(kernel.gpr_count); - *out = s->k; - return OMEGA_GPU_PF_OK; -} - -int omega_gpu_pf_launch_locked(const OmegaPfKernel *k, uint32_t threads, uint32_t grid_x, uint32_t grid_y, uint32_t shared_bytes, - const uint32_t *args, uint32_t n_args, uint64_t *ns) { - if (!k || !threads || !grid_x || !grid_y) return OMEGA_GPU_PF_BAD_ARGS; - if ((uint64_t)threads * k->gpr_declared > 65536u) { omega_gpu_session_set_error("prefill launch: registers x threads exceed the file"); return OMEGA_GPU_PF_TOO_LARGE; } - if (!omega_bw_gpr_declared_ok(k->gpr_declared, k->gpr_peak)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); return OMEGA_GPU_PF_CHIP_FAIL; } - OmegaGpuLaunch L = { .code_va = k->code_va, .gpr_count = k->gpr_declared, .threads_x = threads, .threads_y = 1, .grid_x = grid_x, .grid_y = grid_y, - .num_elements = (size_t)threads * grid_x * grid_y, .args = args, .n_args = n_args, .timeout_ms = PF_TIMEOUT_MS, - .shared_bytes = shared_bytes, .spin_us = PF_SPIN_US }; - uint64_t t = 0; - if (omega_gpu_session_launch(&L, &t, NULL) != 0) return OMEGA_GPU_PF_CHIP_FAIL; - g.chip_ns += t; g.launches++; - if (ns) *ns += t; - return OMEGA_GPU_PF_OK; -} - -static int gen_copy(const OmegaPfKey *key, void *prog) { (void)key; return omega_blackwell_codegen_pf_copy_prog(prog); } -#define KIND_COPY 1u -static int copy_locked(uint64_t dst, uint64_t src, size_t bytes) { - if ((bytes & 15u) || (dst & 15u) || (src & 15u)) return OMEGA_GPU_PF_BAD_ARGS; - if (bytes == 0) return OMEGA_GPU_PF_OK; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = KIND_COPY; - OmegaPfKernel k; int rc = omega_gpu_pf_kernel_locked(&key, gen_copy, &k); - for (size_t done = 0; rc == OMEGA_GPU_PF_OK && done < bytes;) { - size_t part = bytes - done; if (part > (1ull << 30)) part = 1ull << 30; - const uint32_t units = (uint32_t)(part / 16u), grid = (units + OMEGA_PF_COPY_THREADS - 1u) / OMEGA_PF_COPY_THREADS; - const uint64_t d = dst + done, s = src + done; - uint32_t args[5] = { (uint32_t)d, (uint32_t)(d >> 32), (uint32_t)s, (uint32_t)(s >> 32), units }; - rc = omega_gpu_pf_launch_locked(&k, OMEGA_PF_COPY_THREADS, grid, 1, 0, args, 5, NULL); - done += part; - } - return rc; -} -int omega_gpu_pf_copy_va(uint64_t dst_va, uint64_t src_va, size_t bytes) { - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - if (rc == OMEGA_GPU_PF_OK) rc = copy_locked(dst_va, src_va, bytes); - omega_gpu_session_unlock(); - return rc; -} - -static int xfer(const OmegaGpuMem *dev, size_t off, void *host, size_t bytes, int up) { - if (!dev || !host || (off & 15u) || (bytes & 15u) || off + bytes > dev->size) return OMEGA_GPU_PF_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_pf_open_locked(); - if (rc == OMEGA_GPU_PF_OK && omega_gpu_session_scratch(&g.stage, PF_STAGE_BYTES) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - for (size_t done = 0; rc == OMEGA_GPU_PF_OK && done < bytes;) { - size_t part = bytes - done; if (part > PF_STAGE_BYTES) part = PF_STAGE_BYTES; - if (up) { - memcpy(g.stage.mem.cpu, (const uint8_t *)host + done, part); - if (omega_gpu_session_sync_to_gpu(&g.stage.mem) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - else rc = copy_locked(dev->va + off + done, g.stage.mem.va, part); - } else { - rc = copy_locked(g.stage.mem.va, dev->va + off + done, part); - if (rc == OMEGA_GPU_PF_OK && omega_gpu_session_sync_to_cpu(&g.stage.mem) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - if (rc == OMEGA_GPU_PF_OK) memcpy((uint8_t *)host + done, g.stage.mem.cpu, part); - } - done += part; - } - omega_gpu_session_unlock(); - return rc; -} -int omega_gpu_pf_upload(const OmegaGpuMem *dst, size_t off, const void *src, size_t bytes) { return xfer(dst, off, (void *)src, bytes, 1); } -int omega_gpu_pf_download(const OmegaGpuMem *src, size_t off, void *dst, size_t bytes) { return xfer(src, off, dst, bytes, 0); } diff --git a/src/omega_gpu_prefill.h b/src/omega_gpu_prefill.h deleted file mode 100644 index 0bda73b6e..000000000 --- a/src/omega_gpu_prefill.h +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef OMEGA_GPU_PREFILL_H -#define OMEGA_GPU_PREFILL_H -/* - * omega_gpu_prefill (OWN-30B T3b, 2026-10-13): the device-resident one-pass prefill API on the shared session. New file. - * Every buffer the prefill pipeline passes between its kernels stays on the device; the host builds small tables only. - * - * Memory policy (nvos.h:1116-1118, read 2026-10-13: GPU caching "For system memory ... will not be coherent with direct CPU - * mappings"; clc96f.h:72 L2_FLUSH_DIRTY): - * - DEVICE buffers (omega_gpu_pf_alloc_dev) are GPU-cached and device-private: the CPU never reads them and never writes - * them; they are filled only by GPU writes (omega_gpu_pf_upload copies through an uncached staging buffer with the copy - * kernel), so the GPU L2 never holds a stale line, and GPU producers / consumers share the L2 (the whole point: the - * uncached buffers get no cache reuse, evidence OWN30B-T3-TC-PEAK-BW). - * - HOST buffers (omega_gpu_pf_alloc_host) are the session's GPU-uncached buffers: tables and inputs the host writes, - * results the host reads. - * - Reading a device buffer back (tests, logits) goes through omega_gpu_pf_download: a GPU copy into uncached staging. - * One session hook (on_close) frees every kernel and staging buffer of this module. - * - * All functions take the session lock themselves unless named _locked. Return codes OMEGA_GPU_PF_*. - */ -#include -#include -#include -#include "omega_gpu_session.h" - -#ifdef __cplusplus -extern "C" { -#endif -enum { OMEGA_GPU_PF_OK = 0, OMEGA_GPU_PF_BAD_ARGS = -1, OMEGA_GPU_PF_TOO_LARGE = -2, OMEGA_GPU_PF_CODEGEN_FAIL = -3, OMEGA_GPU_PF_CHIP_FAIL = -4 }; -const char *omega_gpu_pf_rc_name(int rc); - -/* buffers */ -int omega_gpu_pf_alloc_dev(size_t bytes, OmegaGpuMem *out); /* GPU-cached, device-private */ -int omega_gpu_pf_alloc_host(size_t bytes, OmegaGpuMem *out); /* GPU-uncached, host reads and writes */ -void omega_gpu_pf_free(OmegaGpuMem *m); -/* host bytes -> device buffer at byte offset off (16-byte multiples), through the staging buffer and the copy kernel */ -int omega_gpu_pf_upload(const OmegaGpuMem *dst, size_t off, const void *src, size_t bytes); -/* device buffer bytes at off -> host (16-byte multiples) */ -int omega_gpu_pf_download(const OmegaGpuMem *src, size_t off, void *dst, size_t bytes); -/* device-to-device copy by VA (16-byte multiples) */ -int omega_gpu_pf_copy_va(uint64_t dst_va, uint64_t src_va, size_t bytes); - -/* accumulated chip time and launch count of this module since the last reset (prefill timing) */ -void omega_gpu_pf_stats(uint64_t *chip_ns, uint64_t *launches); -void omega_gpu_pf_stats_reset(void); - -/* ---- internal to the prefill module family (omega_gpu_prefill*.c) ---- */ -typedef struct { uint32_t kind; uint32_t words[15]; } OmegaPfKey; /* kernel identity: kind + the generator's spec words */ -typedef int (*OmegaPfGen)(const OmegaPfKey *key, void *prog); /* builds the BlackwellIRProgram for key */ -typedef struct { uint64_t code_va; uint32_t gpr_declared, gpr_peak; } OmegaPfKernel; -/* lock held, device open: the resident kernel for key (generated, encoded, patched and uploaded on first use) */ -int omega_gpu_pf_kernel_locked(const OmegaPfKey *key, OmegaPfGen gen, OmegaPfKernel *out); -/* lock held: one launch, chip time added to the module stats (and to *ns when given) */ -int omega_gpu_pf_launch_locked(const OmegaPfKernel *k, uint32_t threads, uint32_t grid_x, uint32_t grid_y, uint32_t shared_bytes, - const uint32_t *args, uint32_t n_args, uint64_t *ns); -int omega_gpu_pf_open_locked(void); /* opens the device, registers the hook: OMEGA_GPU_PF_OK or CHIP_FAIL */ - -/* ---- GEMM v2 (omega_gpu_pfgemm.c, kernels omega_blackwell_codegen_tc2.h) ---- - * Weights live in device buffers in the kernel's PHYSICAL row order with the per-8-row ratio table (tc2 header). - * Layout PLAIN: rows unchanged. Layout SWIGLU: w is [E][2I][k] with the I gate rows first then the I up rows (scales - * [E][2I/128][k/128]); physical row p = 16G + h holds gate (h < 8) or up (h >= 8) of intermediate index - * i = perm(8G + h % 8), perm = the (0,2,1,3) group permutation, so the SwiGLU epilogue writes act rows in stored order. */ -#ifndef OMEGA_GPU_PF_LAYOUTS -#define OMEGA_GPU_PF_LAYOUTS -enum { OMEGA_GPU_PF_PLAIN = 0, OMEGA_GPU_PF_SWIGLU = 1, OMEGA_GPU_PF_SWIGLU_NAT = 2 }; -#endif -typedef struct { OmegaGpuMem w, r; uint32_t experts, n, k, layout; } OmegaPfWeights; -/* w: experts * n * k e4m3 bytes; scale_inv: experts * (n/128) * (k/128) bf16 (checkpoint weight_scale_inv) */ -int omega_gpu_pf_weights_upload(uint32_t experts, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *scale_inv, uint32_t layout, OmegaPfWeights *out); -void omega_gpu_pf_weights_free(OmegaPfWeights *w); -/* the host-side physical form (tests and emulation): pw experts * n * k, ratio experts * (n/8) * (k/128 + 1) f32 */ -int omega_gpu_pf_weights_host_form(uint32_t experts, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *scale_inv, uint32_t layout, uint8_t *pw, float *ratio); -uint32_t omega_gpu_pf_gemm_bm(void); /* rows per tile */ -/* tile table (32-byte entries) for rows sorted by expert: counts[e] rows of expert e; returns the tile count (<= max) or 0 */ -uint32_t omega_gpu_pf_gemm_tiles(const OmegaPfWeights *w, const uint32_t *counts, void *tab, uint32_t max); -/* one launch. rowidx_va 0 = direct rows (row r reads x row r). x: bf16 stored rows of k (rows to row0+bm-1 readable); - * y: f32 rows of n (PLAIN) or bf16 act rows of n/2 (SWIGLU). */ -int omega_gpu_pf_gemm(const OmegaPfWeights *w, uint64_t tiles_va, uint32_t ntiles, uint64_t rowidx_va, uint64_t x_va, uint64_t y_va, uint64_t *ns); -/* measurement knobs (0 restores): rt, warps, aqn; test-only mutant */ -void omega_gpu_pf_gemm_set_shape(uint32_t rt, uint32_t warps, uint32_t aqn); -void omega_gpu_pf_gemm_test_set_mutant(int m); -/* ---- native FP8 path (W-L1G) ---- - * activation quantiser: x (f32 or bf16 rows of k, in_type OMEGA_QG_IN_*) -> q (e4m3 rows of k) + s (f32 [rows][k/128] power-of-two - * scales); semantics in omega_blackwell_codegen_qg.h */ -int omega_gpu_pf_quant(uint32_t k, uint32_t in_type, uint32_t rows, uint64_t x_va, uint64_t q_va, uint64_t s_va, uint64_t *ns); -void omega_gpu_pf_quant_test_set_mutant(int m); -/* grouped GEMM on QMMA, weights read in place from an FP8 GEMV tensor (omega_gpu_fp8_api.h, checkpoint row order, no copy). - * layout PLAIN: y f32 rows of n. layout SWIGLU_NAT: the tensor is [E][2I][k] gate rows then up rows; y = bf16 act rows of I = n/2, - * act[i] = silu(gate_i) * up_i (capped exponent, omega_blackwell_codegen_qg.h). xq: e4m3 rows of k, xs: f32 [rows][k/128] - * power-of-two scales (omega_gpu_pf_quant). Rows grouped by expert: counts[e] rows of expert e, tile table from qgemm_tiles. */ -typedef struct OmegaGpuFp8Tensor OmegaGpuFp8Tensor; -uint32_t omega_gpu_pf_qgemm_bm(void); -uint32_t omega_gpu_pf_qgemm_tiles(const OmegaGpuFp8Tensor *t, const uint32_t *counts, void *tab, uint32_t max); -/* the same from per-expert base addresses of a GEMV-layout copy (e.g. a GPU-cached device buffer) */ -uint32_t omega_gpu_pf_qgemm_tiles_va(uint32_t experts, const uint64_t *w_va, const uint64_t *s_va, const uint32_t *counts, void *tab, uint32_t max); -int omega_gpu_pf_qgemm(uint32_t n, uint32_t k, uint32_t layout, uint64_t tiles_va, uint32_t ntiles, uint64_t rowidx_va, uint64_t xq_va, uint64_t xs_va, uint64_t y_va, uint64_t *ns); -void omega_gpu_pf_qgemm_set_shape(uint32_t rt, uint32_t warps, uint32_t wait); /* knobs (all 0 restores rt 4, warps 8, wait 45) */ -void omega_gpu_pf_qgemm_test_set_mutant(int m); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_prefill_attn_api.c b/src/omega_gpu_prefill_attn_api.c deleted file mode 100644 index 9bef1d426..000000000 --- a/src/omega_gpu_prefill_attn_api.c +++ /dev/null @@ -1,395 +0,0 @@ -/* - * omega_gpu_prefill_attn_api.c: chunked launches of the tensor-core causal prefill attention (see the header). - * Session use mirrors omega_gpu_decode_attn_api.c: buffers from omega_gpu_session_alloc (GPU-uncached, host-visible), - * sync_to_gpu after host writes, sync_to_cpu before host reads, one omega_gpu_session_launch per chunk. - * The kernel uses the SHFL.BFLY / F2FP placeholders of omega_blackwell_codegen_tc.h: the code is patched after encoding - * and the patch count must equal the program's placeholder count. - */ -#include "omega_gpu_prefill_attn_api.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include -#if defined(__has_include) -#if __has_include("omega_gpu_prefill.h") -#include "omega_gpu_prefill.h" /* GPU-cached device buffers + copy kernel (integration builds) */ -#include "omega_blackwell_codegen_pf.h" -#define PATTN_HAVE_PF 1 -#endif -#endif -#ifndef PATTN_HAVE_PF -#define PATTN_HAVE_PF 0 -#endif - -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -typedef struct { - bool valid; - OmegaPrefillAttnSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -#define MAX_LAUNCH_LOG 256u - -static struct { - bool hooked; - Slot slot[3]; /* one per OMEGA_PATTN_MODE_* */ - uint32_t warps; - int mutant; - int fused; /* 1: 64-token fused chunks (cut 1 path); 0 (default): APPEND + ATTEND launch pairs */ - bool have_bufs; - uint32_t buf_rows; /* host-entry staging capacity in tokens */ - OmegaGpuMem qkv, out; - uint64_t launch_ns[MAX_LAUNCH_LOG]; - uint32_t n_launch; /* launches of the last call (log keeps the first MAX_LAUNCH_LOG) */ - int mirror_off; /* 1: ATTEND reads the uncached cache (cut 3); 0 (default with PATTN_HAVE_PF): GPU-cached K/V mirror */ - int mirror_per_call; /* TEST: 1 forgets the mirrored rows before every call (cut 4 behaviour: history copied every time) */ - struct Mir { uint64_t key; uint32_t max_pos, valid; uint64_t plane; OmegaGpuMem mem; } mir[OMEGA_GPU_PATTN_MAX_MIRRORS]; - uint32_t n_mir; /* persistent mirrors, one per (cache, layer), keyed by the layer's K plane VA */ -} g; - -static void slot_clear_locked(void) { - for (unsigned i = 0; i < 3; i++) { if (g.slot[i].valid) omega_gpu_session_free(&g.slot[i].code); memset(&g.slot[i], 0, sizeof g.slot[i]); } -} -static void on_session_close(void) { memset(g.mir, 0, sizeof g.mir); g.n_mir = 0; memset(g.slot, 0, sizeof g.slot); g.have_bufs = false; g.buf_rows = 0; memset(&g.qkv, 0, sizeof g.qkv); memset(&g.out, 0, sizeof g.out); } -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} - -void omega_gpu_prefill_attn_set_warps(uint32_t warps) { omega_gpu_session_lock(); g.warps = warps; slot_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_prefill_attn_test_set_mutant(int mutant) { omega_gpu_session_lock(); g.mutant = mutant; slot_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_prefill_attn_set_fused(int fused) { omega_gpu_session_lock(); g.fused = fused ? 1 : 0; omega_gpu_session_unlock(); } -void omega_gpu_prefill_attn_set_kv_mirror(int on) { omega_gpu_session_lock(); g.mirror_off = on ? 0 : 1; omega_gpu_session_unlock(); } -int omega_gpu_prefill_attn_kv_mirror_available(void) { return PATTN_HAVE_PF; } -uint32_t omega_gpu_prefill_attn_test_launch_ns(uint64_t *ns, uint32_t cap) { - omega_gpu_session_lock(); - uint32_t n = g.n_launch < MAX_LAUNCH_LOG ? g.n_launch : MAX_LAUNCH_LOG; - for (uint32_t i = 0; i < n && i < cap; i++) ns[i] = g.launch_ns[i]; - uint32_t total = g.n_launch; - omega_gpu_session_unlock(); - return total; -} -void omega_gpu_prefill_attn_release(void) { - omega_gpu_session_lock(); - slot_clear_locked(); - if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); g.have_bufs = false; g.buf_rows = 0; } - omega_gpu_session_unlock(); -#if PATTN_HAVE_PF - for (uint32_t i = 0; i < g.n_mir; i++) omega_gpu_pf_free(&g.mir[i].mem); - memset(g.mir, 0, sizeof g.mir); g.n_mir = 0; -#endif -} - -#if PATTN_HAVE_PF -/* Persistent mirror of one (cache, layer): the decode cache's exact layout ([K plane | V plane], plane = v_va - k_va, - * row (kv_head, pos) at plane + (kv_head * max_pos + pos) * 256) in GPU-cached device memory. Rows 0 .. valid-1 equal - * the cache. Zero-filled when allocated, so rows past the last key of a 32-key block are finite (their P is exactly 0, - * and 0 * NaN would poison O). Lock NOT held (the pf calls take it). */ -static struct Mir *mirror_get(const OmegaGpuDecodeAttnCacheView *v) { - for (uint32_t i = 0; i < g.n_mir; i++) - if (g.mir[i].key == v->k_va && g.mir[i].max_pos == v->max_pos) return &g.mir[i]; - if (g.n_mir >= OMEGA_GPU_PATTN_MAX_MIRRORS) { omega_gpu_session_set_error("prefill attn: too many KV mirrors"); return NULL; } - struct Mir *m = &g.mir[g.n_mir]; - memset(m, 0, sizeof *m); - const uint64_t plane = v->v_va - v->k_va, bytes = 2u * plane; - if (v->v_va <= v->k_va || (plane & 15u)) { omega_gpu_session_set_error("prefill attn: cache planes"); return NULL; } - if (omega_gpu_pf_alloc_dev(bytes, &m->mem) != OMEGA_GPU_PF_OK) { memset(m, 0, sizeof *m); return NULL; } - const size_t step = (size_t)16u << 20; /* zero-fill in 16 MB uploads */ - void *z = omega_gpu_host_calloc(1, step); - int ok = z != NULL; - for (uint64_t off = 0; ok && off < bytes; off += step) { - const size_t part = bytes - off < step ? (size_t)(bytes - off) : step; - ok = omega_gpu_pf_upload(&m->mem, off, z, part) == OMEGA_GPU_PF_OK; - } - omega_gpu_host_free(z); - if (!ok) { omega_gpu_pf_free(&m->mem); memset(m, 0, sizeof *m); omega_gpu_session_set_error("prefill attn: KV mirror zero-fill"); return NULL; } - m->key = v->k_va; m->max_pos = v->max_pos; m->plane = plane; m->valid = 0; - g.n_mir++; - return m; -} -static struct Mir *mirror_find(const OmegaGpuDecodeAttnCacheView *v) { - for (uint32_t i = 0; i < g.n_mir; i++) if (g.mir[i].key == v->k_va && g.mir[i].max_pos == v->max_pos) return &g.mir[i]; - return NULL; -} -/* lock held: the copy kernel of the prefill module (same key and generator as omega_gpu_pf_copy_va) */ -static int gen_copy(const OmegaPfKey *key, void *prog) { (void)key; return omega_blackwell_codegen_pf_copy_prog(prog); } -static int copy_locked(uint64_t dst, uint64_t src, size_t bytes, uint64_t *ns) { - if ((bytes & 15u) || (dst & 15u) || (src & 15u)) return OMEGA_GPU_PF_BAD_ARGS; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = 1u; /* KIND_COPY of omega_gpu_prefill.c */ - OmegaPfKernel k; int rc = omega_gpu_pf_open_locked(); - if (rc == OMEGA_GPU_PF_OK) rc = omega_gpu_pf_kernel_locked(&key, gen_copy, &k); - if (rc != OMEGA_GPU_PF_OK || bytes == 0) return rc; - const uint32_t units = (uint32_t)(bytes / 16u), grid = (units + OMEGA_PF_COPY_THREADS - 1u) / OMEGA_PF_COPY_THREADS; - uint32_t args[5] = { (uint32_t)dst, (uint32_t)(dst >> 32), (uint32_t)src, (uint32_t)(src >> 32), units }; - return omega_gpu_pf_launch_locked(&k, OMEGA_PF_COPY_THREADS, grid, 1, 0, args, 5, ns); -} -#endif - -size_t omega_gpu_prefill_attn_encode(const OmegaPrefillAttnSpec *spec, uint8_t *code, size_t cap, uint32_t *gprs, int *patched) { - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return 0; - size_t need = 0; - if (omega_blackwell_codegen_prefill_attn_prog(spec, prog) == 0) need = omega_bw_program_code_bytes(prog); - OmegaBlackwellKernel k; - if (need == 0 || need > cap || omega_blackwell_kernel_encode_into(prog, code, cap, &k) != 0) { omega_gpu_host_free(prog); return 0; } - int np = omega_tc_patch_code(prog, code, need); - if (gprs) *gprs = k.gpr_count; - if (patched) *patched = np; - omega_gpu_host_free(prog); - return np < 0 ? 0 : need; -} - -static int kernel_for(const OmegaPrefillAttnSpec *spec, Slot **out, bool *hit) { - Slot *s = &g.slot[spec->mode]; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_DATTN_OK; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("prefill attn codegen: host memory"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_prefill_attn_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill attn codegen refused the spec"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if ((uint64_t)32u * spec->warps * omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill attn: register file"); return OMEGA_GPU_DATTN_TOO_LARGE; } - uint32_t expect = 0; - for (size_t i = 0; i < prog->count; i++) { - const BlackwellIRInsn *in = &prog->insns[i]; - if ((in->op == BW_IR_SHFL_DOWN && (in->imm & OMEGA_TC_MARK_BFLY)) || (in->op == BW_IR_FMNMX_MAX && in->imm == OMEGA_TC_MARK_F2FP)) expect++; - } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_DATTN_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - int np = cg == 0 ? omega_tc_patch_code(prog, code.cpu, need) : -1; - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); omega_gpu_session_set_error("prefill attn encode"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if (np < 0 || (uint32_t)np != expect) { omega_gpu_session_free(&code); omega_gpu_session_set_error("prefill attn: placeholder patch count mismatch"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_DATTN_CHIP_FAIL; } - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_DATTN_OK; -} - -/* host-entry staging for `rows` tokens (grown on demand, contents not kept) */ -static int bufs_locked(uint32_t rows) { - if (g.have_bufs && g.buf_rows >= rows) return 0; - if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); g.have_bufs = false; g.buf_rows = 0; } - if (omega_gpu_session_alloc((size_t)rows * OMEGA_PATTN_QKV_WORDS * 4u, &g.qkv) != 0) return -1; - if (omega_gpu_session_alloc((size_t)rows * OMEGA_PATTN_OUT_WORDS * 4u, &g.out) != 0) { omega_gpu_session_free(&g.qkv); return -1; } - g.have_bufs = true; g.buf_rows = rows; - return 0; -} - -typedef struct { OmegaGpuDecodeAttnCacheView v; uint32_t ue, uo, uq; OmegaPrefillAttnSpec base; struct Mir *mir; } Run; - -static int prepare(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos0, uint32_t m, float eps, float out_scale, Run *r) { - memset(r, 0, sizeof *r); - if (!c || m == 0 || omega_gpu_decode_attn_cache_view(c, layer, &r->v) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DATTN_BAD_ARGS; - if (pos0 > r->v.max_pos || m > r->v.max_pos - pos0) return OMEGA_GPU_DATTN_BAD_ARGS; - r->base.warps = g.warps ? g.warps : OMEGA_GPU_PATTN_WARPS; r->base.mutant = g.mutant; - if (!omega_pattn_spec_ok(&r->base)) return OMEGA_GPU_DATTN_BAD_ARGS; - float qk_f = (float)(0.08838834764831845 * 1.4426950408889634); /* log2(e) / sqrt(128) */ - memcpy(&r->ue, &eps, 4); memcpy(&r->uo, &out_scale, 4); memcpy(&r->uq, &qk_f, 4); - return OMEGA_GPU_DATTN_OK; -} - -/* lock held, device open: one launch of `mode` over tokens pos0 .. pos0+mc-1 whose qkv / out rows start at the VAs */ -/* K/V planes a launch reads (kc, vc, kvs) and, for APPEND with a mirror, also writes (kc2, vc2, kvs2) */ -typedef struct { uint64_t kc, vc, kc2, vc2; uint32_t kvs, kvs2; } KvPlanes; -static int launch_locked(const Run *r, uint32_t mode, const KvPlanes *kv, uint64_t qkv_va, uint64_t out_va, uint32_t p0, uint32_t mc, - OmegaGpuPrefillAttnInfo *info) { - OmegaPrefillAttnSpec spec = r->base; spec.mode = mode; spec.mirror = kv->kc2 ? 1u : 0u; - Slot *ks = NULL; bool hit = false; - int rc = kernel_for(&spec, &ks, &hit); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - const uint32_t W = spec.warps; - uint32_t args[OMEGA_PATTN_ARGS_WORDS]; - memset(args, 0, sizeof args); -#define A64(i, val) do { uint64_t _x = (val); args[i] = (uint32_t)_x; args[(i) + 1] = (uint32_t)(_x >> 32); } while (0) - A64(0, qkv_va); A64(2, kv->kc); A64(4, kv->vc); A64(6, r->v.rope_va); A64(8, r->v.q_norm_va); A64(10, r->v.k_norm_va); A64(12, out_va); A64(20, kv->kc2); A64(22, kv->vc2); -#undef A64 - args[14] = p0; args[15] = mc; args[16] = kv->kvs; args[24] = kv->kvs2; args[17] = r->ue; args[18] = r->uo; args[19] = r->uq; - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = omega_bw_gpr_declared(ks->kernel.gpr_count), - .threads_x = 32u * W, .threads_y = 1, .grid_x = (mc + W - 1u) / W, .grid_y = OMEGA_GPU_DATTN_KV_HEADS, - .num_elements = (size_t)mc * OMEGA_PATTN_OUT_WORDS, - .args = args, .n_args = OMEGA_PATTN_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_PATTN_SHARED_BYTES, - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); return OMEGA_GPU_DATTN_CHIP_FAIL; } - uint64_t el = 0; uint32_t marker = 0; - if (omega_gpu_session_launch(&L, &el, &marker) != 0) return OMEGA_GPU_DATTN_CHIP_FAIL; - if (g.n_launch < MAX_LAUNCH_LOG) g.launch_ns[g.n_launch] = el; - g.n_launch++; - if (info) { - if (info->chunks == 0) { info->grid_x = L.grid_x; info->grid_y = L.grid_y; info->threads = L.threads_x; info->splits = 1; info->per_split = p0 + mc; info->kernel_cache_hit = hit; } - else info->kernel_cache_hit &= hit; - info->chunks++; info->elapsed_ns += el; - } - return OMEGA_GPU_DATTN_OK; -} - -/* lock held, device open: all the launches for tokens pos0 .. pos0+m-1, rows at the VAs (device memory, row strides - * 5120 / 4096 f32). Split (default): one APPEND then one ATTEND launch over all m tokens. Fused: 64-token chunks. */ -static int run_locked(const Run *r, uint32_t pos0, uint32_t m, uint64_t qkv_va, uint64_t out_va, OmegaGpuPrefillAttnInfo *info) { - int rc = OMEGA_GPU_DATTN_OK; - const KvPlanes cache = { .kc = r->v.k_va, .vc = r->v.v_va, .kvs = r->v.max_pos * OMEGA_DATTN_ROW_BYTES }; - if (!g.fused) { -#if PATTN_HAVE_PF - if (!g.mirror_off) { - /* persistent GPU-cached mirror (same layout as the cache): rows valid .. pos0-1 that the cache gained since the - * last call (decode steps) are copied in, rows >= pos0 are (re)written by APPEND to both places, ATTEND reads - * only the mirror (L2 reuse across CTAs). Rows 0 .. min(valid, pos0)-1 are trusted: see the header contract. */ - struct Mir *mm = r->mir ? mirror_find(&r->v) : NULL; /* re-found under the lock (forget may have moved it) */ - if (!mm) { omega_gpu_session_set_error("prefill attn: KV mirror not allocated"); return OMEGA_GPU_DATTN_CHIP_FAIL; } - if (g.mirror_per_call) mm->valid = 0; - const uint32_t t = mm->valid < pos0 ? mm->valid : pos0; - mm->valid = 0; /* until this call succeeds */ - const KvPlanes mir = { .kc = mm->mem.va, .vc = mm->mem.va + mm->plane, .kvs = cache.kvs }; - for (uint32_t h = 0; h < OMEGA_GPU_DATTN_KV_HEADS && t < pos0 && rc == OMEGA_GPU_DATTN_OK; h++) { - uint64_t ns = 0; - const uint64_t off = (uint64_t)h * cache.kvs + (uint64_t)t * OMEGA_DATTN_ROW_BYTES; - const size_t bytes = (size_t)(pos0 - t) * OMEGA_DATTN_ROW_BYTES; - int prc = copy_locked(mir.kc + off, cache.kc + off, bytes, &ns); - if (prc == OMEGA_GPU_PF_OK) prc = copy_locked(mir.vc + off, cache.vc + off, bytes, &ns); - if (prc != OMEGA_GPU_PF_OK) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - if (g.n_launch < MAX_LAUNCH_LOG) g.launch_ns[g.n_launch] = ns; - g.n_launch++; - if (info) info->elapsed_ns += ns; - } - KvPlanes app = cache; app.kc2 = mir.kc; app.vc2 = mir.vc; app.kvs2 = mir.kvs; - if (rc == OMEGA_GPU_DATTN_OK) rc = launch_locked(r, OMEGA_PATTN_MODE_APPEND, &app, qkv_va, out_va, pos0, m, info); - if (rc == OMEGA_GPU_DATTN_OK) rc = launch_locked(r, OMEGA_PATTN_MODE_ATTEND, &mir, qkv_va, out_va, pos0, m, info); - if (rc == OMEGA_GPU_DATTN_OK) mm->valid = pos0 + m; - return rc; - } -#endif - rc = launch_locked(r, OMEGA_PATTN_MODE_APPEND, &cache, qkv_va, out_va, pos0, m, info); - if (rc == OMEGA_GPU_DATTN_OK) rc = launch_locked(r, OMEGA_PATTN_MODE_ATTEND, &cache, qkv_va, out_va, pos0, m, info); - return rc; - } - for (uint32_t done = 0; done < m && rc == OMEGA_GPU_DATTN_OK; done += OMEGA_PATTN_CHUNK) { - const uint32_t mc = m - done < OMEGA_PATTN_CHUNK ? m - done : OMEGA_PATTN_CHUNK; - rc = launch_locked(r, OMEGA_PATTN_MODE_FUSED, &cache, qkv_va + (uint64_t)done * OMEGA_PATTN_QKV_WORDS * 4u, - out_va + (uint64_t)done * OMEGA_PATTN_OUT_WORDS * 4u, pos0 + done, mc, info); - } - return rc; -} - -static void info_head(OmegaGpuPrefillAttnInfo *info, uint32_t layer, uint32_t pos0, uint32_t m) { - if (!info) return; - memset(info, 0, sizeof *info); - info->layer = layer; info->pos0 = pos0; info->m = m; -} - -int omega_gpu_prefill_attn(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos0, uint32_t m, const float *qkv, float eps, - float out_scale, float *out, OmegaGpuPrefillAttnInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - info_head(info, layer, pos0, m); - Run r; - if (!qkv || !out) return OMEGA_GPU_DATTN_BAD_ARGS; - int rc = prepare(c, layer, pos0, m, eps, out_scale, &r); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - const uint32_t pass = g.fused ? OMEGA_PATTN_CHUNK : OMEGA_GPU_PATTN_HOST_PASS; -#if PATTN_HAVE_PF - if (!g.fused && !g.mirror_off && !(r.mir = mirror_get(&r.v))) return OMEGA_GPU_DATTN_CHIP_FAIL; -#endif - - omega_gpu_session_lock(); - if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - g.n_launch = 0; - if (bufs_locked(m < pass ? m : pass) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - for (uint32_t done = 0; done < m && rc == OMEGA_GPU_DATTN_OK; done += pass) { - const uint32_t mp = m - done < pass ? m - done : pass; - memcpy(g.qkv.cpu, qkv + (size_t)done * OMEGA_PATTN_QKV_WORDS, (size_t)mp * OMEGA_PATTN_QKV_WORDS * 4u); - float *od = g.out.cpu; - for (size_t i = 0; i < (size_t)mp * OMEGA_PATTN_OUT_WORDS; i++) od[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g.qkv) != 0 || omega_gpu_session_sync_to_gpu(&g.out) != 0) { rc = OMEGA_GPU_DATTN_CHIP_FAIL; break; } - rc = run_locked(&r, pos0 + done, mp, g.qkv.va, g.out.va, info); - if (rc != OMEGA_GPU_DATTN_OK) break; - if (omega_gpu_session_sync_to_cpu(&g.out) != 0) { rc = OMEGA_GPU_DATTN_CHIP_FAIL; break; } - size_t unchanged = 0; - for (size_t i = 0; i < (size_t)mp * OMEGA_PATTN_OUT_WORDS; i++) if (od[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("prefill attn: output poison survived"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; break; } - memcpy(out + (size_t)done * OMEGA_PATTN_OUT_WORDS, od, (size_t)mp * OMEGA_PATTN_OUT_WORDS * 4u); - } - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_prefill_attn_dev(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos0, uint32_t m, uint64_t qkv_va, float eps, - float out_scale, uint64_t out_va, OmegaGpuPrefillAttnInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - info_head(info, layer, pos0, m); - Run r; - if (!qkv_va || !out_va || (qkv_va & 15u) || (out_va & 15u)) return OMEGA_GPU_DATTN_BAD_ARGS; - int rc = prepare(c, layer, pos0, m, eps, out_scale, &r); - if (rc != OMEGA_GPU_DATTN_OK) return rc; -#if PATTN_HAVE_PF - if (!g.fused && !g.mirror_off && !(r.mir = mirror_get(&r.v))) return OMEGA_GPU_DATTN_CHIP_FAIL; -#endif - omega_gpu_session_lock(); - if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - g.n_launch = 0; - rc = run_locked(&r, pos0, m, qkv_va, out_va, info); - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -/* ---- persistent K/V mirror: view and contract (see the header) ---- */ -int omega_gpu_prefill_attn_kv_mirror_view(const OmegaGpuDecodeAttnCache *c, uint32_t layer, OmegaGpuPrefillAttnMirrorView *out) { - OmegaGpuDecodeAttnCacheView v; - if (!out) return OMEGA_GPU_DATTN_BAD_ARGS; - memset(out, 0, sizeof *out); - if (!c || omega_gpu_decode_attn_cache_view(c, layer, &v) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DATTN_BAD_ARGS; - omega_gpu_session_lock(); -#if PATTN_HAVE_PF - struct Mir *m = mirror_find(&v); - if (m) { out->k_va = m->mem.va; out->v_va = m->mem.va + m->plane; out->kv_stride = v.max_pos * OMEGA_DATTN_ROW_BYTES; out->max_pos = v.max_pos; out->valid = m->valid; } -#endif - omega_gpu_session_unlock(); - return out->k_va ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_BAD_ARGS; -} -static uint32_t layers_of(const OmegaGpuDecodeAttnCache *c) { - OmegaGpuDecodeAttnCacheView v; - return c && omega_gpu_decode_attn_cache_view(c, 0, &v) == OMEGA_GPU_DATTN_OK ? v.layers : 0; -} -void omega_gpu_prefill_attn_kv_mirror_invalidate(const OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t from_pos) { - const uint32_t nl = layers_of(c); - omega_gpu_session_lock(); -#if PATTN_HAVE_PF - for (uint32_t l = 0; l < nl; l++) { - if (layer != UINT32_MAX && l != layer) continue; - OmegaGpuDecodeAttnCacheView v; - if (omega_gpu_decode_attn_cache_view(c, l, &v) != OMEGA_GPU_DATTN_OK) continue; - struct Mir *m = mirror_find(&v); - if (m && m->valid > from_pos) m->valid = from_pos; - } -#else - (void)layer; (void)from_pos; (void)nl; -#endif - omega_gpu_session_unlock(); -} -void omega_gpu_prefill_attn_kv_mirror_forget(const OmegaGpuDecodeAttnCache *c) { -#if PATTN_HAVE_PF - const uint32_t nl = layers_of(c); - for (uint32_t l = 0; l < nl; l++) { - OmegaGpuDecodeAttnCacheView v; - if (omega_gpu_decode_attn_cache_view(c, l, &v) != OMEGA_GPU_DATTN_OK) continue; - omega_gpu_session_lock(); - struct Mir *m = mirror_find(&v); - OmegaGpuMem mem; memset(&mem, 0, sizeof mem); - if (m) { mem = m->mem; *m = g.mir[g.n_mir - 1]; memset(&g.mir[g.n_mir - 1], 0, sizeof g.mir[0]); g.n_mir--; } - omega_gpu_session_unlock(); - if (mem.va) omega_gpu_pf_free(&mem); - } -#else - (void)c; -#endif -} -void omega_gpu_prefill_attn_test_set_mirror_per_call(int on) { omega_gpu_session_lock(); g.mirror_per_call = on ? 1 : 0; omega_gpu_session_unlock(); } diff --git a/src/omega_gpu_prefill_attn_api.h b/src/omega_gpu_prefill_attn_api.h deleted file mode 100644 index f241a7f4d..000000000 --- a/src/omega_gpu_prefill_attn_api.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef OMEGA_GPU_PREFILL_ATTN_API_H -#define OMEGA_GPU_PREFILL_ATTN_API_H -/* - * omega_gpu_prefill_attn_api: causal prefill attention on tensor cores for Qwen3-30B-A3B (OWN-30B L1 attention, - * 2026-10-13). The API of ~/handoffs/own30b-attn-api.md; the kernel is described in omega_blackwell_codegen_pattn.h. - * - * int omega_gpu_prefill_attn(c, layer, pos0, m, qkv, eps, out_scale, out, info) - * c: the decode attention's cache (shared KV cache; positions 0 .. pos0-1 of `layer` already in it). - * qkv: host f32 [m][5120] (q 32 x 128 | k 4 x 128 | v 4 x 128, raw), tokens at positions pos0 .. pos0+m-1. - * Appends K = bf16(RoPE(RMSNorm(k) * k_norm)) and V = bf16(v) for those positions (the decode kernel's operation - * order, so the rows equal m decode steps' rows on the same chip), and writes out: host f32 [m][32 * 128] (token- - * major, head h at h * 128) multiplied by out_scale. Staged in passes of up to 1024 tokens, each one APPEND + one ATTEND launch (cut 3; set_fused(1): 64-token fused chunks). pos0 + m <= max_pos. - * Returns OMEGA_GPU_DATTN_OK or an OMEGA_GPU_DATTN_* code; the text is in omega_gpu_decode_attn_last_error(). - * - * Every buffer is GPU-uncached host-visible session memory (nvos.h:1117 rule), launched through - * omega_gpu_session_launch. The chunk staging buffers (qkv 64 x 5120 f32, out 64 x 4096 f32) belong to this module - * and are released with omega_gpu_prefill_attn_release() or when the session closes. - */ -#include "omega_gpu_decode_attn_api.h" -#include "omega_blackwell_codegen_pattn.h" -#include - -typedef struct { - uint32_t layer, pos0, m, chunks; /* chunks = launches made (2 per pass, or ceil(m / 64) fused) */ - uint32_t grid_x, grid_y, threads, splits, per_split; /* of the first launch; splits = 1 (no key split), per_split = keys seen by that launch's last CTA */ - uint64_t elapsed_ns; /* chip time, summed over the launches */ - uint64_t call_ns; - int kernel_cache_hit; -} OmegaGpuPrefillAttnInfo; - -int omega_gpu_prefill_attn(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos0, uint32_t m, - const float *qkv, float eps, float out_scale, float *out, - OmegaGpuPrefillAttnInfo *info); -void omega_gpu_prefill_attn_release(void); - -/* Device-resident entry (cut 3), for the one-pass prefill pipeline: the same work with no host copies. - * qkv_va: f32 [m][5120] rows (20480-byte stride), out_va: f32 [m][4096] rows (16384-byte stride), both 16-byte aligned - * GPU VAs in the shared session (GPU-cached device buffers from omega_gpu_pf_alloc_dev, or session buffers). - * The kernels only read qkv and only write out; no poison check is possible here (the host never reads device - * buffers), the caller's download path is the check. Two launches (APPEND then ATTEND over all m tokens), or - * 64-token fused chunks after omega_gpu_prefill_attn_set_fused(1). Same return codes as omega_gpu_prefill_attn. */ -int omega_gpu_prefill_attn_dev(OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t pos0, uint32_t m, - uint64_t qkv_va, float eps, float out_scale, uint64_t out_va, - OmegaGpuPrefillAttnInfo *info); - -/* ---- measurement knobs (tests; each clears the kernel cache) ---- */ -void omega_gpu_prefill_attn_set_warps(uint32_t warps); /* 0 = default (OMEGA_GPU_PATTN_WARPS); 4 or 8 */ -void omega_gpu_prefill_attn_test_set_mutant(int mutant); /* TEST ONLY: OmegaPrefillAttnSpec.mutant */ -#define OMEGA_GPU_PATTN_WARPS 8u -void omega_gpu_prefill_attn_set_fused(int fused); /* 1: cut-1 path (64-token fused chunks); 0 (default): APPEND + ATTEND */ -/* ATTEND reads a GPU-cached mirror of the layer's K/V (history copied in, new rows written by APPEND to both places). - * Default on when built with omega_gpu_prefill.h (kv_mirror_available() == 1); a no-op otherwise. */ -void omega_gpu_prefill_attn_set_kv_mirror(int on); -/* Persistent mirror (cut 5): one per (cache, layer), kept between calls, in the decode cache's EXACT layout - * ([K plane | V plane], plane = view.v_va - view.k_va, row (kv_head, pos) at plane + (kv_head * max_pos + pos) * 256, bf16) - * but in GPU-cached device memory (omega_gpu_pf_alloc_dev), so the decode kernel can later be pointed at it unchanged. - * Rows 0 .. valid-1 equal the cache. A call copies only cache rows valid .. pos0-1 (rows decode appended since) and - * writes rows pos0 .. pos0+m-1 to both. CONTRACT for token identity (the mirror cannot see other writers): - * - anyone who rewrites cache rows below a mirror's `valid` other than through this API (a new sequence decoded into a - * used cache, omega_gpu_decode_attn_cache_write, ...) calls omega_gpu_prefill_attn_kv_mirror_invalidate(c, layer - * or UINT32_MAX for all, from_pos) first; appending at positions >= valid (normal decode) needs nothing; - * - before omega_gpu_decode_attn_cache_free(c), call omega_gpu_prefill_attn_kv_mirror_forget(c) (mirrors are keyed by - * the layer's K plane VA; a later cache at the same VA would otherwise inherit stale rows). */ -#define OMEGA_GPU_PATTN_MAX_MIRRORS 128u -typedef struct { uint64_t k_va, v_va; uint32_t kv_stride, max_pos, valid; } OmegaGpuPrefillAttnMirrorView; -int omega_gpu_prefill_attn_kv_mirror_view(const OmegaGpuDecodeAttnCache *c, uint32_t layer, OmegaGpuPrefillAttnMirrorView *out); -void omega_gpu_prefill_attn_kv_mirror_invalidate(const OmegaGpuDecodeAttnCache *c, uint32_t layer, uint32_t from_pos); -void omega_gpu_prefill_attn_kv_mirror_forget(const OmegaGpuDecodeAttnCache *c); -void omega_gpu_prefill_attn_test_set_mirror_per_call(int on); /* TEST: forget mirrored rows before every call (cut 4 cost) */ -int omega_gpu_prefill_attn_kv_mirror_available(void); -/* launches of the last call (return value) and the chip time of each (first `cap` of at most 256 logged) */ -uint32_t omega_gpu_prefill_attn_test_launch_ns(uint64_t *ns, uint32_t cap); -#define OMEGA_GPU_PATTN_HOST_PASS 1024u /* host entry: tokens per staged pass in split mode */ - -/* host: build + encode + patch the kernel for a spec into code (cap bytes); returns the code size or 0 (tests) */ -size_t omega_gpu_prefill_attn_encode(const OmegaPrefillAttnSpec *spec, uint8_t *code, size_t cap, uint32_t *gprs, int *patched); - -#endif diff --git a/src/omega_gpu_router_api.c b/src/omega_gpu_router_api.c deleted file mode 100644 index b786e10d4..000000000 --- a/src/omega_gpu_router_api.c +++ /dev/null @@ -1,276 +0,0 @@ -/* - * omega_gpu_router_api.c: resident router weights, directories, launch buffers and the one-launch router call - * (see the header). Session use mirrors omega_gpu_decode_attn_api.c: every buffer from omega_gpu_session_alloc - * (GPU-uncached, host-visible), sync_to_gpu after host writes, sync_to_cpu before host reads, one - * omega_gpu_session_launch per call. - */ -#include "omega_gpu_router_api.h" -#include "omega_gpu_session.h" -#include -#include -#include "omega_gpu_cmdlist.h" - -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) -#define POISON_ID 0xffffffffu - -/* the launch buffer: one allocation, fixed offsets (bytes) */ -#define LB_X 0u -#define LB_XOUT 8192u -#define LB_IDS 16384u -#define LB_WTS 16448u -#define LB_TAB_GU 16512u -#define LB_TAB_DN 16640u -#define LB_BYTES 16768u - -struct OmegaGpuRouter { - uint32_t layers; - OmegaGpuMem gate; /* [layers][128][2048] bf16 */ - OmegaGpuMem norm; /* [layers][2048] f32 */ - OmegaGpuMem dir; /* [layers][2][128][2] u64 */ - OmegaGpuMem lb; /* launch buffer */ -}; - -typedef struct { - bool valid; - OmegaRouterSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - bool hooked; - Slot slot; - uint32_t warps, depth; - int mutant; -} g; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -static void slot_clear_locked(void) { if (g.slot.valid) omega_gpu_session_free(&g.slot.code); memset(&g.slot, 0, sizeof g.slot); } -static void on_session_close(void) { memset(&g.slot, 0, sizeof g.slot); } -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } /* peak + 2 rounded up to 8: the chip hung at peak + 1 (omega_blackwell_codegen.h) */ - -void omega_gpu_router_set_shape(uint32_t warps, uint32_t depth) { omega_gpu_session_lock(); g.warps = warps; g.depth = depth; slot_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_router_test_set_mutant(int mutant) { omega_gpu_session_lock(); g.mutant = mutant; slot_clear_locked(); omega_gpu_session_unlock(); } -const char *omega_gpu_router_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_router_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_ROUTER_OK: return "OK"; - case OMEGA_GPU_ROUTER_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_ROUTER_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_ROUTER_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_ROUTER_CHIP_FAIL: return "CHIP_FAIL"; - default: return "?"; - } -} - -/* ---- buffers ---- */ -int omega_gpu_router_alloc(uint32_t layers, OmegaGpuRouter **out) { - if (!out || layers == 0 || layers > OMEGA_GPU_ROUTER_MAX_LAYERS) return OMEGA_GPU_ROUTER_BAD_ARGS; - *out = NULL; - OmegaGpuRouter *r = omega_gpu_host_calloc(1, sizeof *r); - if (!r) return OMEGA_GPU_ROUTER_BAD_ARGS; - r->layers = layers; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_ROUTER_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && omega_gpu_session_alloc((size_t)layers * OMEGA_ROUTER_EXPERTS * OMEGA_ROUTER_ROW_BYTES, &r->gate) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && omega_gpu_session_alloc((size_t)layers * OMEGA_ROUTER_HIDDEN * 4u, &r->norm) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && omega_gpu_session_alloc((size_t)layers * 2u * OMEGA_ROUTER_DIR_BYTES, &r->dir) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && omega_gpu_session_alloc(LB_BYTES, &r->lb) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK) { - memset(r->dir.cpu, 0, (size_t)layers * 2u * OMEGA_ROUTER_DIR_BYTES); - memset(r->lb.cpu, 0, LB_BYTES); - if (omega_gpu_session_sync_to_gpu(&r->dir) != 0 || omega_gpu_session_sync_to_gpu(&r->lb) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - } - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_ROUTER_OK) { omega_gpu_router_free(r); return rc; } - *out = r; - return OMEGA_GPU_ROUTER_OK; -} - -void omega_gpu_router_free(OmegaGpuRouter *r) { - if (!r) return; - omega_gpu_session_lock(); - if (r->gate.cpu) omega_gpu_session_free(&r->gate); - if (r->norm.cpu) omega_gpu_session_free(&r->norm); - if (r->dir.cpu) omega_gpu_session_free(&r->dir); - if (r->lb.cpu) omega_gpu_session_free(&r->lb); - omega_gpu_session_unlock(); - omega_gpu_host_free(r); -} - -int omega_gpu_router_set_layer(OmegaGpuRouter *r, uint32_t layer, const uint16_t *gate_bf16, const float *norm_w) { - if (!r || layer >= r->layers || !gate_bf16 || !norm_w) return OMEGA_GPU_ROUTER_BAD_ARGS; - omega_gpu_session_lock(); - memcpy((uint8_t *)r->gate.cpu + (size_t)layer * OMEGA_ROUTER_EXPERTS * OMEGA_ROUTER_ROW_BYTES, gate_bf16, (size_t)OMEGA_ROUTER_EXPERTS * OMEGA_ROUTER_ROW_BYTES); - memcpy((uint8_t *)r->norm.cpu + (size_t)layer * OMEGA_ROUTER_HIDDEN * 4u, norm_w, (size_t)OMEGA_ROUTER_HIDDEN * 4u); - int rc = (omega_gpu_session_sync_to_gpu(&r->gate) == 0 && omega_gpu_session_sync_to_gpu(&r->norm) == 0) ? OMEGA_GPU_ROUTER_OK : OMEGA_GPU_ROUTER_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_router_set_directory(OmegaGpuRouter *r, uint32_t layer, const uint64_t *gu, const uint64_t *dn) { - if (!r || layer >= r->layers || !gu || !dn) return OMEGA_GPU_ROUTER_BAD_ARGS; - omega_gpu_session_lock(); - uint8_t *d = (uint8_t *)r->dir.cpu + (size_t)layer * 2u * OMEGA_ROUTER_DIR_BYTES; - memcpy(d, gu, OMEGA_ROUTER_DIR_BYTES); - memcpy(d + OMEGA_ROUTER_DIR_BYTES, dn, OMEGA_ROUTER_DIR_BYTES); - int rc = omega_gpu_session_sync_to_gpu(&r->dir) == 0 ? OMEGA_GPU_ROUTER_OK : OMEGA_GPU_ROUTER_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_router_set_directory_fp8(OmegaGpuRouter *r, uint32_t layer, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down) { - if (!r || !gate_up || !down) return OMEGA_GPU_ROUTER_BAD_ARGS; - uint64_t gu[OMEGA_ROUTER_EXPERTS * 2], dn[OMEGA_ROUTER_EXPERTS * 2]; - for (uint32_t x = 0; x < OMEGA_ROUTER_EXPERTS; x++) { - if (omega_gpu_fp8_tensor_entry(gate_up, x, &gu[2 * x], &gu[2 * x + 1]) != 0) return OMEGA_GPU_ROUTER_BAD_ARGS; - if (omega_gpu_fp8_tensor_entry(down, x, &dn[2 * x], &dn[2 * x + 1]) != 0) return OMEGA_GPU_ROUTER_BAD_ARGS; - } - return omega_gpu_router_set_directory(r, layer, gu, dn); -} - -void omega_gpu_router_device_outputs(const OmegaGpuRouter *r, uint64_t *xout_va, uint64_t *tab_gu_va, uint64_t *tab_dn_va) { - if (xout_va) *xout_va = r ? r->lb.va + LB_XOUT : 0; - if (tab_gu_va) *tab_gu_va = r ? r->lb.va + LB_TAB_GU : 0; - if (tab_dn_va) *tab_dn_va = r ? r->lb.va + LB_TAB_DN : 0; -} - -int omega_gpu_router_read_back(OmegaGpuRouter *r, float *xout, uint64_t *tab_gu, uint64_t *tab_dn) { - if (!r) return OMEGA_GPU_ROUTER_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_session_sync_to_cpu(&r->lb) == 0 ? OMEGA_GPU_ROUTER_OK : OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK) { - const uint8_t *b = r->lb.cpu; - if (xout) memcpy(xout, b + LB_XOUT, OMEGA_ROUTER_HIDDEN * 4u); - if (tab_gu) memcpy(tab_gu, b + LB_TAB_GU, OMEGA_ROUTER_TAB_BYTES); - if (tab_dn) memcpy(tab_dn, b + LB_TAB_DN, OMEGA_ROUTER_TAB_BYTES); - } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- kernel ---- */ -static int kernel_for(const OmegaRouterSpec *spec, Slot **out, bool *hit) { - Slot *s = &g.slot; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_ROUTER_OK; } - if (g_rec && s->valid) { omega_gpu_session_set_error("router record: kernel cache miss would evict the resident kernel (warm up before recording)"); return OMEGA_GPU_ROUTER_TOO_LARGE; } - slot_clear_locked(); - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("router codegen: host memory"); return OMEGA_GPU_ROUTER_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_router_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("router codegen refused the spec"); return OMEGA_GPU_ROUTER_CODEGEN_FAIL; } - if ((uint64_t)32u * spec->warps * gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("router: register file"); return OMEGA_GPU_ROUTER_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_ROUTER_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); omega_gpu_session_set_error("router encode"); return OMEGA_GPU_ROUTER_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_ROUTER_CHIP_FAIL; } - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_ROUTER_OK; -} - -/* rec non-NULL (record path, caller holds the session lock): x is the device row dev_x, the launch is appended to rec - * instead of submitted, nothing is staged, poisoned or read back (outputs stay at the launch-buffer addresses). */ -static int router_core(OmegaGpuRouter *r, uint32_t layer, const float *x, float eps, int norm_topk, float out_scale, - uint32_t *ids, float *weights, OmegaGpuRouterInfo *info, OmegaGpuCmdList *rec, uint64_t dev_x) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!r || layer >= r->layers || (rec ? !dev_x : (!x || !ids || !weights))) return OMEGA_GPU_ROUTER_BAD_ARGS; - OmegaRouterSpec spec; memset(&spec, 0, sizeof spec); - spec.warps = g.warps ? g.warps : OMEGA_GPU_ROUTER_WARPS; spec.depth = g.depth ? g.depth : OMEGA_GPU_ROUTER_DEPTH; spec.mutant = g.mutant; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - int rc = OMEGA_GPU_ROUTER_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_ROUTER_CHIP_FAIL; } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_ROUTER_OK) { UNLOCK(); return rc; } - uint8_t *b = r->lb.cpu; - float *xo = (float *)(b + LB_XOUT), *wd = (float *)(b + LB_WTS); - uint32_t *idd = (uint32_t *)(b + LB_IDS); - if (!rec) { - memcpy(b + LB_X, x, OMEGA_ROUTER_HIDDEN * 4u); - for (size_t i = 0; i < OMEGA_ROUTER_HIDDEN; i++) xo[i] = POISON_F32; - for (size_t i = 0; i < OMEGA_ROUTER_TOPK; i++) { wd[i] = POISON_F32; idd[i] = POISON_ID; } - memset(b + LB_TAB_GU, 0, OMEGA_ROUTER_TAB_BYTES); memset(b + LB_TAB_DN, 0, OMEGA_ROUTER_TAB_BYTES); - if (omega_gpu_session_sync_to_gpu(&r->lb) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - } - - uint32_t args[OMEGA_ROUTER_ARGS_WORDS]; - const uint64_t gate = r->gate.va + (uint64_t)layer * OMEGA_ROUTER_EXPERTS * OMEGA_ROUTER_ROW_BYTES; - const uint64_t norm = r->norm.va + (uint64_t)layer * OMEGA_ROUTER_HIDDEN * 4u; - const uint64_t dgu = r->dir.va + (uint64_t)layer * 2u * OMEGA_ROUTER_DIR_BYTES, ddn = dgu + OMEGA_ROUTER_DIR_BYTES; - float fe = eps, fo = out_scale; uint32_t ue, uo; memcpy(&ue, &fe, 4); memcpy(&uo, &fo, 4); -#define A64(i, v) do { args[i] = (uint32_t)(v); args[(i) + 1] = (uint32_t)((v) >> 32); } while (0) - A64(0, rec ? dev_x : r->lb.va + LB_X); A64(2, gate); A64(4, norm); A64(6, r->lb.va + LB_XOUT); A64(8, r->lb.va + LB_IDS); A64(10, r->lb.va + LB_WTS); - A64(12, dgu); A64(14, ddn); A64(16, r->lb.va + LB_TAB_GU); A64(18, r->lb.va + LB_TAB_DN); -#undef A64 - args[20] = ue; args[21] = uo; args[22] = norm_topk ? 1u : 0u; - if (info) { - info->layer = layer; info->warps = spec.warps; info->depth = spec.depth; info->threads = 32u * spec.warps; - info->weight_bytes = (uint64_t)OMEGA_ROUTER_EXPERTS * OMEGA_ROUTER_ROW_BYTES; - info->kernel_cache_hit = hit; - } - if (rc == OMEGA_GPU_ROUTER_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), - .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = 1, .grid_y = 1, - .num_elements = (size_t)OMEGA_ROUTER_HIDDEN, - .args = args, .n_args = OMEGA_ROUTER_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_ROUTER_SHARED_BYTES, - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_ROUTER_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - } - if (rc == OMEGA_GPU_ROUTER_OK && !rec && omega_gpu_session_sync_to_cpu(&r->lb) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < OMEGA_ROUTER_HIDDEN; i++) if (xo[i] == POISON_F32) unchanged++; - for (size_t i = 0; i < OMEGA_ROUTER_TOPK; i++) if (wd[i] == POISON_F32 || idd[i] == POISON_ID) unchanged++; - const uint64_t *tg = (const uint64_t *)(b + LB_TAB_GU), *td = (const uint64_t *)(b + LB_TAB_DN); - size_t tab_zero = 0; - for (size_t i = 0; i < 2 * OMEGA_ROUTER_TOPK; i++) { if (tg[i] == 0) tab_zero++; if (td[i] == 0) tab_zero++; } - size_t bad_id = 0; - for (size_t i = 0; i < OMEGA_ROUTER_TOPK; i++) if (idd[i] >= OMEGA_ROUTER_EXPERTS) bad_id++; - if (unchanged) { omega_gpu_session_set_error("router: output poison survived"); rc = OMEGA_GPU_ROUTER_CHIP_FAIL; } - else if (bad_id) { omega_gpu_session_set_error("router: an expert id is out of range"); rc = OMEGA_GPU_ROUTER_CHIP_FAIL; } - else if (tab_zero) { omega_gpu_session_set_error("router: a group table word stayed zero (directory not set?)"); rc = OMEGA_GPU_ROUTER_CHIP_FAIL; } - else { memcpy(ids, idd, OMEGA_ROUTER_TOPK * 4u); memcpy(weights, wd, OMEGA_ROUTER_TOPK * 4u); } - } - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_router(OmegaGpuRouter *r, uint32_t layer, const float *x, float eps, int norm_topk, float out_scale, - uint32_t *ids, float *weights, OmegaGpuRouterInfo *info) { - return router_core(r, layer, x, eps, norm_topk, out_scale, ids, weights, info, NULL, 0); -} - -/* Record path (OWN-30B W-L2a decode graph): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_router_record(OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, float eps, int norm_topk, - float out_scale, OmegaGpuRouterDevOut *out) { - if (!cl) return OMEGA_GPU_ROUTER_BAD_ARGS; - int rc = router_core(r, layer, NULL, eps, norm_topk, out_scale, NULL, NULL, NULL, cl, x_va); - if (rc == OMEGA_GPU_ROUTER_OK && out) { - out->xout_va = r->lb.va + LB_XOUT; out->ids_va = r->lb.va + LB_IDS; out->wts_va = r->lb.va + LB_WTS; - out->tab_gu_va = r->lb.va + LB_TAB_GU; out->tab_dn_va = r->lb.va + LB_TAB_DN; - } - return rc; -} diff --git a/src/omega_gpu_router_api.h b/src/omega_gpu_router_api.h deleted file mode 100644 index 566c57ad4..000000000 --- a/src/omega_gpu_router_api.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef OMEGA_GPU_ROUTER_API_H -#define OMEGA_GPU_ROUTER_API_H -/* - * omega_gpu_router_api: one-launch MoE router for Qwen3-30B-A3B (OWN-30B cut 8 item 2, 2026-10-13). - * C signatures for the Rust side first; the kernel is described in omega_blackwell_codegen_router.h. - * - * int omega_gpu_router_alloc(uint32_t layers, OmegaGpuRouter **out); - * Device-resident per-layer router weights (bf16 [128][2048]), post-attention norm weights (f32 [2048]) and - * the two expert directories (u64 [128][2] {w_va, s_va} for the gate+up and the down FP8 tensors), plus the - * launch buffers: x in, x' out, ids, weights and the two group tables the grouped FP8 GEMV reads. - * int omega_gpu_router_set_layer(OmegaGpuRouter *r, uint32_t layer, const uint16_t *gate_bf16, const float *norm_w); - * gate_bf16: the checkpoint's mlp.gate.weight [128][2048] as bf16 bits; norm_w: post_attention_layernorm.weight - * widened to f32 by the caller. - * int omega_gpu_router_set_directory_fp8(OmegaGpuRouter *r, uint32_t layer, const OmegaGpuFp8Tensor *gate_up, - * const OmegaGpuFp8Tensor *down); - * Builds the layer's directories from two resident FP8 tensors with 128 experts (omega_gpu_fp8_tensor_entry). - * int omega_gpu_router_set_directory(OmegaGpuRouter *r, uint32_t layer, const uint64_t *gu, const uint64_t *dn); - * Raw form of the above (tests): gu / dn are [128][2] {w_va, s_va}. - * int omega_gpu_router(OmegaGpuRouter *r, uint32_t layer, const float *x, float eps, int norm_topk, float out_scale, - * uint32_t *ids, float *weights, OmegaGpuRouterInfo *info); - * x: f32 [2048] residual row (host). One launch: RMSNorm(x) with the layer's norm weight and eps, logits, - * softmax, top-8, weights renormalised when norm_topk != 0 (config.json norm_topk_prob). Outputs: ids[8] - * (descending by logit) and weights[8] to the host; on the device x' = RMSNorm(x) * out_scale (2^64 gives the - * x' row of omega_gpu_fp8_gemv_grouped_dev) and the two group tables, entry g = directory[ids[g]], at the - * addresses omega_gpu_router_device_outputs returns. The grouped GEMV consumes them with no host round trip: - * omega_gpu_fp8_gemv_grouped_dev(gate_up, 8, tab_gu_va, xout_va, y, info). - * void omega_gpu_router_device_outputs(const OmegaGpuRouter *r, uint64_t *xout_va, uint64_t *tab_gu_va, uint64_t *tab_dn_va); - * int omega_gpu_router_read_back(OmegaGpuRouter *r, float *xout, uint64_t *tab_gu, uint64_t *tab_dn); - * Test helper: syncs the device outputs of the last call to the host (any pointer may be NULL). - * - * Every buffer is GPU-uncached host-visible session memory (nvos.h:1117 rule), launched through - * omega_gpu_session_launch like the FP8 GEMV and the decode attention. Output words are poisoned before the launch - * and a surviving poison word is CHIP_FAIL. - */ -#include "omega_blackwell_codegen_router.h" -#include "omega_gpu_fp8_api.h" -#include -#include - -enum { - OMEGA_GPU_ROUTER_OK = 0, - OMEGA_GPU_ROUTER_BAD_ARGS = -1, - OMEGA_GPU_ROUTER_TOO_LARGE = -2, - OMEGA_GPU_ROUTER_CODEGEN_FAIL = -3, - OMEGA_GPU_ROUTER_CHIP_FAIL = -4 -}; - -#define OMEGA_GPU_ROUTER_MAX_LAYERS 64u -#define OMEGA_GPU_ROUTER_WARPS 32u /* default kernel shape (omega_gpu_router_set_shape overrides) */ -#define OMEGA_GPU_ROUTER_DEPTH 4u - -typedef struct OmegaGpuRouter OmegaGpuRouter; - -typedef struct { - uint32_t layer, warps, depth, threads; - uint64_t weight_bytes; /* bf16 router bytes the launch streams: 128 * 2048 * 2 */ - uint64_t elapsed_ns; /* marker-to-marker chip time */ - uint64_t call_ns; /* whole call */ - uint32_t completion_marker; - int kernel_cache_hit; -} OmegaGpuRouterInfo; - -int omega_gpu_router_alloc(uint32_t layers, OmegaGpuRouter **out); -void omega_gpu_router_free(OmegaGpuRouter *r); -int omega_gpu_router_set_layer(OmegaGpuRouter *r, uint32_t layer, const uint16_t *gate_bf16, const float *norm_w); -int omega_gpu_router_set_directory(OmegaGpuRouter *r, uint32_t layer, const uint64_t *gu, const uint64_t *dn); -int omega_gpu_router_set_directory_fp8(OmegaGpuRouter *r, uint32_t layer, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down); -int omega_gpu_router(OmegaGpuRouter *r, uint32_t layer, const float *x, float eps, int norm_topk, float out_scale, - uint32_t *ids, float *weights, OmegaGpuRouterInfo *info); -void omega_gpu_router_device_outputs(const OmegaGpuRouter *r, uint64_t *xout_va, uint64_t *tab_gu_va, uint64_t *tab_dn_va); -/* Record path (OWN-30B W-L2a, decode graph; omega_gpu_cmdlist.h): the launch of omega_gpu_router with the residual row - * read from x_va (f32 [2048] on the device) appended to cl instead of submitted. The caller holds - * omega_gpu_session_lock(). Nothing is staged, poisoned or read back. The outputs land, when the list runs, at the - * router's launch buffer (one per router: a later record of another layer overwrites them, in list order): - * xout = RMSNorm(x) * out_scale [2048] f32, ids [8] u32, wts [8] f32 (the COMBINE weights), and the two group tables - * (8 x {w_va, s_va}) for gate+up and down. A kernel cache miss that would evict the resident kernel is refused. */ -typedef struct { uint64_t xout_va, ids_va, wts_va, tab_gu_va, tab_dn_va; } OmegaGpuRouterDevOut; -struct OmegaGpuCmdList; -int omega_gpu_router_record(struct OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, float eps, int norm_topk, - float out_scale, OmegaGpuRouterDevOut *out); -int omega_gpu_router_read_back(OmegaGpuRouter *r, float *xout, uint64_t *tab_gu, uint64_t *tab_dn); -const char *omega_gpu_router_last_error(void); -const char *omega_gpu_router_rc_name(int rc); - -/* ---- measurement knobs (tests) ---- */ -void omega_gpu_router_set_shape(uint32_t warps, uint32_t depth); /* 0 = default; clears the kernel cache */ -void omega_gpu_router_test_set_mutant(int mutant); /* TEST ONLY: OmegaRouterSpec.mutant */ - -#endif diff --git a/src/omega_gpu_serving.c b/src/omega_gpu_serving.c deleted file mode 100644 index 1fee9cd80..000000000 --- a/src/omega_gpu_serving.c +++ /dev/null @@ -1,25 +0,0 @@ -/* omega_gpu_serving.c: see omega_gpu_serving.h. Thin wrapper over the per-API reserve calls. */ -#include "omega_gpu_serving.h" -#include "omega_gpu_attention_api.h" -#include "omega_gpu_matmul_api.h" - -int omega_gpu_reserve_serving(const OmegaGpuServingBounds *b) { - if (!b) return OMEGA_GPU_MATMUL_BAD_ARGS; - int rc = omega_gpu_attention_reserve(b->max_context, b->max_seqs ? b->max_seqs : 1, b->num_q_heads, b->num_kv_heads, b->head_dim, b->kv_block_size); - if (rc != 0) return rc; - if (b->max_rows > 1) { /* the prompt read's rows path (omega_gpu_gqa_attention_rows_f32): q/out/table for a chunk of rows */ - rc = omega_gpu_attention_reserve_rows(b->max_rows, b->num_q_heads, b->head_dim); - if (rc != 0) { omega_gpu_attention_unreserve(); return rc; } - } - rc = omega_gpu_matmul_reserve(b->max_rows, b->max_k, b->max_n, b->max_n_one_row ? b->max_n_one_row : b->max_n, b->kernel_slots); - if (rc != 0) omega_gpu_attention_unreserve(); /* the matmul half failed: do not leave half a reservation active */ - return rc; -} - -void omega_gpu_serving_seal(void) { omega_gpu_matmul_seal(1); } - -void omega_gpu_serving_release(void) { - omega_gpu_matmul_seal(0); - omega_gpu_attention_unreserve(); - omega_gpu_matmul_unreserve(); -} diff --git a/src/omega_gpu_serving.h b/src/omega_gpu_serving.h deleted file mode 100644 index bbf9979f0..000000000 --- a/src/omega_gpu_serving.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * omega_gpu_serving.h: OPT-IN up-front reservation of the GB10 serving buffers (sovereign-core design - * note docs/design/gb10-weight-ownership.md, sc#277). - * - * Without this call nothing changes: the attention staging pool, the matmul activation and result - * buffers and the matmul kernel cache grow on demand, which on the GB10 means one driver allocation - * per new context length and per row-count growth (omega PR #332 measured 458 after warm-up over 428 - * tokens). With it, a daemon calls omega_gpu_reserve_serving once after loading weights, and every - * later call inside the declared bounds reuses the same buffers. A call outside the bounds is refused - * with TOO_LARGE and a clear omega_gpu_*_last_error() text ("serving reservation exceeded: need N - * bytes, reserved M"); it never asks the driver for more memory, so it cannot fault the session. - * - * Not covered (documented follow-ups): the elementwise API's scratch (it stops growing after the - * first full-size call), the attention kernel cache (8 slots, one kernel per model shape and context split count), and the - * first build of each distinct matmul shape unless the server prepares every shape it will run - * (omega_gpu_matmul_prepare: one small code buffer per shape, pinned) and then seals - * (omega_gpu_serving_seal): after that an unprepared shape is refused, never built. - */ -#ifndef OMEGA_GPU_SERVING_H -#define OMEGA_GPU_SERVING_H - -#include - -typedef struct { - uint32_t max_context; /* longest sequence (tokens) one attention call may cover */ - uint32_t max_seqs; /* sequences per attention call; 0 = 1 */ - uint32_t num_q_heads, num_kv_heads, head_dim; /* the model's attention shape */ - uint32_t kv_block_size; /* paged KV block size in tokens (power of two); 0 = the paged bf16 path is not used */ - uint32_t max_rows; /* most rows one matmul call may carry (prefill chunk) */ - uint32_t max_k; /* widest weight input dimension */ - uint32_t max_n; /* widest weight output dimension for calls of up to max_rows rows */ - uint32_t max_n_one_row; /* widest output dimension for calls of at most 16 rows (lm_head); 0 = max_n */ - uint32_t kernel_slots; /* matmul kernel cache slots; 0 = leave at 8; at most 128. Qwen3-4B, rows 1..256: 83 distinct kernels (grid_x and the row/column block vary with rows) */ -} OmegaGpuServingBounds; - -/* Opens the device if needed. 0 on success, else the first failing OMEGA_GPU_MATMUL_* / ATTN_* code - * (omega_gpu_matmul_last_error() has the text). All-or-nothing: each API rolls back its own buffers when one of its - * allocations fails, and this call rolls back the attention half when the matmul half fails, so a failed reserve - * leaves nothing flagged. Notes: a refused paged/batched attention call may follow earlier launch chunks that already - * wrote their outputs (TOO_LARGE = output incomplete); max_seqs is checked per launch chunk, not per call. */ -int omega_gpu_reserve_serving(const OmegaGpuServingBounds *b); - -/* After the server prepared its matmul shapes: refuse any unprepared one from now on (omega_gpu_matmul_seal). */ -void omega_gpu_serving_seal(void); -/* Lift the reservation and the seal: buffers stay, growth is allowed again. (Closing the device also ends both.) */ -void omega_gpu_serving_release(void); - -#endif diff --git a/src/omega_gpu_session.c b/src/omega_gpu_session.c deleted file mode 100644 index 5dcaaadc2..000000000 --- a/src/omega_gpu_session.c +++ /dev/null @@ -1,543 +0,0 @@ -/* - * omega_gpu_session.c: FB-1 cut 4b, made portable in native v1 P07 cut C (session part). See the header. - * - * The launch words are the ones omega_gpu_matmul_api.c (cut 1b, chip PASS FB1-CUT1B-4345406) and - * omega_gpu_elementwise_api.c (cut 4, FB1-CUT4-0d0241a) both emitted; cut C did not change one of them. What - * changed is where the machine comes from: every device, buffer, queue, clock, lock and host-memory call goes - * through the installed OmegaGpuPlatform (ABI 1.1), so this file builds freestanding (OMEGA_GPU_NO_POSIX) with no - * Linux header and no libc call. The hosted build installs the Linux reference (src/omega_gpu_platform_linux.c) - * on first use; it makes the same driver calls in the same order as this file did before. - * - * No read-modify-write atomics: the freestanding target must not pull libgcc outline atomics, so shared words are - * plain atomic loads and stores, and counters are only written with the session lock held. - */ -#include "omega_gpu_session.h" -#include "omega_gpu_code_alloc.h" -#include "omega_gpu_fmt.h" -#include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" /* launch constants only (macros); the vector executor itself stays Linux-private */ -#include - -#ifndef OMEGA_GPU_NO_POSIX -#include "omega_gpu_platform_linux.h" -#include -#endif - -#define PAGE 0x1000ull - -/* Push-buffer method header (the nvrm_mthd encoding, physics nvrm.h): increasing, count words, subchannel. */ -static inline uint32_t bw_mthd(uint32_t subc, uint32_t mthd, uint32_t count) { - return (2u << 28) | (count << 16) | (subc << 13) | (mthd >> 2); -} - -/* Same words as src/omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - -static const OmegaGpuPlatform *g_p; /* installed platform (atomic load / store) */ -static OmegaGpuPlatformCaps g_caps; -static OmegaGpuSession g_s; -static bool g_open; -static uint32_t g_blocked; /* latched (atomic) */ -static uint32_t g_locked; /* session lock held (atomic) */ -static uint32_t g_cancel; /* cancel requested (atomic) */ -static uint32_t g_spin_us; /* omega_gpu_session_set_spin_us; 0 = poll_word only */ -static char g_err[320] = ""; -static void (*g_hooks[8])(void); -static unsigned g_nhooks; -static OmegaGpuAllocStats g_stats; /* written with the lock held, read with atomic loads */ -static OmegaGpuBufferHandle g_parked[OMEGA_GPU_SESSION_PARK_MAX]; -static OmegaGpuParkStats g_park; - -#define LOAD(x) __atomic_load_n(&(x), __ATOMIC_ACQUIRE) -#define STORE(x, v) __atomic_store_n(&(x), (v), __ATOMIC_RELEASE) -#define BUMP(x, by) STORE((x), LOAD(x) + (by)) /* lock held: one writer */ - -/* ---- platform ---- */ - -static int install(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) { - if (!p || !caps) return OMEGA_GPU_PLAT_REFUSED_ARGS; - OmegaGpuPlatformCaps req = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, - .max_devices = 1, .max_buffers = 8, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 0x10000, .max_total_bytes = 0x10000 + 3 * 0x10000, - }; - int rc = omega_gpu_platform_negotiate(caps, &req); - if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_SESSION); - if (rc != OMEGA_GPU_PLAT_OK) return rc; - g_caps = *caps; - STORE(g_p, p); - return OMEGA_GPU_PLAT_OK; -} - -int omega_gpu_session_set_platform(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) { - if (g_open || LOAD(g_locked) || LOAD(g_blocked)) return OMEGA_GPU_PLAT_REFUSED_BUSY; - if (!p) { STORE(g_p, (const OmegaGpuPlatform *)0); return OMEGA_GPU_PLAT_OK; } - return install(p, caps); -} - -#ifndef OMEGA_GPU_NO_POSIX -static pthread_once_t g_default_once = PTHREAD_ONCE_INIT; -static void install_default(void) { - if (LOAD(g_p)) return; /* one was installed explicitly */ - OmegaGpuPlatformCaps c; - const OmegaGpuPlatform *p = omega_gpu_platform_linux(&c); - (void)install(p, &c); -} -#endif - -static const OmegaGpuPlatform *platform(void) { - const OmegaGpuPlatform *p = LOAD(g_p); -#ifndef OMEGA_GPU_NO_POSIX - if (!p) { pthread_once(&g_default_once, install_default); p = LOAD(g_p); } -#endif - return p; -} - -const OmegaGpuPlatform *omega_gpu_session_platform(void) { return platform(); } -uint32_t omega_gpu_session_submit_prefix_words(void) { return platform() ? g_caps.submit_prefix_words : 0u; } /* g_caps is written before g_p is published */ -OmegaGpuCompletionMode omega_gpu_session_completion_mode(void) { return OMEGA_GPU_COMPLETION_POLLING; } - -uint64_t omega_gpu_session_now_ns(void) { - const OmegaGpuPlatform *p = platform(); - return p ? p->time_now_ns(p->ctx) : 0u; -} - -void *omega_gpu_host_alloc(size_t bytes) { - const OmegaGpuPlatform *p = platform(); - return p ? p->host_alloc(p->ctx, bytes ? bytes : 1) : (void *)0; /* 0 bytes: a unique 1-byte block, as malloc(0) gives */ -} -void *omega_gpu_host_calloc(size_t n, size_t size) { - size_t bytes; - if (__builtin_mul_overflow(n, size, &bytes)) return (void *)0; - void *q = omega_gpu_host_alloc(bytes); - if (q) memset(q, 0, bytes); - return q; -} -void omega_gpu_host_free(void *q) { - const OmegaGpuPlatform *p = platform(); - if (p && q) p->host_free(p->ctx, q); -} - -/* ---- errors ---- */ - -const char *omega_gpu_session_last_error(void) { return g_err; } -void omega_gpu_session_set_error(const char *stage) { omega_gpu_fmt(g_err, sizeof g_err, "%s", stage ? stage : ""); } - -/* A platform refusal: the driver text when the device refused (the Linux reference writes ": ", - * the stage names the session ever reported), else the stage and the refusal name. */ -static void fail_plat(const char *stage, int rc) { - const OmegaGpuPlatform *p = LOAD(g_p); - const char *diag = p ? p->diag_text(p->ctx) : ""; - if (rc == OMEGA_GPU_PLAT_REFUSED_DEVICE && diag && diag[0]) - omega_gpu_fmt(g_err, sizeof g_err, "%s", diag); - else - omega_gpu_fmt(g_err, sizeof g_err, "%s: %s", stage, omega_gpu_platform_refusal_name(rc)); -} - -/* ---- lock, state ---- */ - -void omega_gpu_session_lock(void) { - const OmegaGpuPlatform *p = platform(); - if (!p) return; - (void)p->lock(p->ctx, OMEGA_GPU_SESSION_LOCK_ID); - STORE(g_locked, 1u); -} -void omega_gpu_session_unlock(void) { - const OmegaGpuPlatform *p = LOAD(g_p); - if (!p) return; - STORE(g_locked, 0u); - (void)p->unlock(p->ctx, OMEGA_GPU_SESSION_LOCK_ID); -} -bool omega_gpu_session_is_open(void) { return g_open; } -int omega_gpu_session_is_blocked(void) { return LOAD(g_blocked) ? 1 : 0; } -int omega_gpu_session_set_spin_us(uint32_t us) { - if (us > OMEGA_GPU_SESSION_MAX_SPIN_US) return -1; - STORE(g_spin_us, us); - return 0; -} -uint32_t omega_gpu_session_spin_us(void) { return LOAD(g_spin_us); } -void omega_gpu_session_cancel(void) { STORE(g_cancel, 1u); } - -/* Consumes a pending cancel request. */ -static bool take_cancel(void) { - if (!LOAD(g_cancel)) return false; - STORE(g_cancel, 0u); - return true; -} - -void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out) { - if (!out) return; - out->allocs = LOAD(g_stats.allocs); - out->alloc_bytes = LOAD(g_stats.alloc_bytes); - out->alloc_failures = LOAD(g_stats.alloc_failures); - out->frees = LOAD(g_stats.frees); - out->stale_refusals = LOAD(g_stats.stale_refusals); -} - -/* ---- parking ---- */ - -static void park(const OmegaGpuMem *m) { - uint32_t n = LOAD(g_park.buffers) - LOAD(g_park.untracked); - for (uint32_t i = 0; i < n; i++) - if (g_parked[i].index == m->handle.index && g_parked[i].generation == m->handle.generation) return; - if (n < OMEGA_GPU_SESSION_PARK_MAX) g_parked[n] = m->handle; - else BUMP(g_park.untracked, 1u); - BUMP(g_park.bytes, m->size); - BUMP(g_park.buffers, 1u); -} - -void omega_gpu_session_parked(OmegaGpuParkStats *out) { - if (!out) return; - out->buffers = LOAD(g_park.buffers); - out->untracked = LOAD(g_park.untracked); - out->bytes = LOAD(g_park.bytes); -} - -int omega_gpu_session_is_parked(OmegaGpuBufferHandle h) { - uint32_t n = LOAD(g_park.buffers) - LOAD(g_park.untracked); - if (h.generation == 0u) return 0; - for (uint32_t i = 0; i < n && i < OMEGA_GPU_SESSION_PARK_MAX; i++) - if (g_parked[i].index == h.index && g_parked[i].generation == h.generation) return 1; - return 0; -} - -/* Uncertain completion: the device may still touch any session buffer. Keep everything, refuse everything. */ -static void latch(const char *why) { - STORE(g_blocked, 1u); - if (g_s.pb.cpu) park(&g_s.pb); - if (g_s.cbank.cpu) park(&g_s.cbank); - if (g_s.marker.cpu) park(&g_s.marker); - if (g_s.qmd.cpu) park(&g_s.qmd); - omega_gpu_session_set_error(why); -} - -/* ---- buffers ---- */ - -static size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } - -static int mem_alloc(uint32_t kind, uint32_t rights, size_t bytes, OmegaGpuMem *out) { - const OmegaGpuPlatform *p = LOAD(g_p); - memset(out, 0, sizeof *out); - if (!g_open || LOAD(g_blocked) || !p) { omega_gpu_session_set_error("alloc without open device"); return -1; } - const size_t want = page_up(bytes); - OmegaGpuBufferDesc d = {.kind = kind, .rights = rights, .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .align = (uint32_t)PAGE, .bytes = want}; - OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; /* the bus address never leaves this function */ - int rc = p->dma_alloc(p->ctx, g_s.dev, &d, &out->handle, &cpu, &va, &bus); - if (rc != OMEGA_GPU_PLAT_OK || !cpu.ptr || cpu.len < want) { - if (rc == OMEGA_GPU_PLAT_OK) { (void)p->dma_free(p->ctx, out->handle); rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; } - BUMP(g_stats.alloc_failures, 1u); - fail_plat("dma_alloc", rc); - memset(out, 0, sizeof *out); - return -1; - } - out->kind = kind; out->cpu = cpu.ptr; out->va = va.va; out->size = cpu.len; - BUMP(g_stats.allocs, 1u); - BUMP(g_stats.alloc_bytes, (uint64_t)want); - return 0; -} - -#define RIGHTS_DATA (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE) -#define RIGHTS_CODE (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ | OMEGA_GPU_RIGHT_GPU_EXEC) -#define RIGHTS_RING (OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ) -#define RIGHTS_MARKER (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_WRITE | OMEGA_GPU_RIGHT_HOST_POLLED) -#define RIGHTS_CBANK (OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ) - -int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out) { - return mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_DATA, bytes, out); -} - -int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out) { - size_t bytes = omega_gpu_code_alloc_bytes(code_size); - if (bytes == 0) { omega_gpu_session_set_error("code size overflow"); memset(out, 0, sizeof *out); return -1; } - if (mem_alloc(OMEGA_GPU_HANDLE_BUF_CODE, RIGHTS_CODE, bytes, out) != 0) return -1; - memset((uint8_t *)out->cpu + code_size, 0, bytes - code_size); - return 0; -} - -void omega_gpu_session_free(OmegaGpuMem *m) { - if (!m) return; - if (m->cpu) { - const OmegaGpuPlatform *p = LOAD(g_p); - if (LOAD(g_blocked)) { - park(m); /* the device may still use it */ - } else if (!g_open || !p) { - BUMP(g_stats.stale_refusals, 1u); /* its device is closed: the handle is stale, nothing to release */ - } else { - int rc = p->dma_free(p->ctx, m->handle); - if (rc == OMEGA_GPU_PLAT_OK) BUMP(g_stats.frees, 1u); - else { BUMP(g_stats.stale_refusals, 1u); fail_plat("dma_free", rc); } - } - } - memset(m, 0, sizeof *m); -} - -static int sync_mem(const OmegaGpuMem *m, int to_gpu) { - const OmegaGpuPlatform *p = LOAD(g_p); - if (!m || !m->cpu) return 0; - if (!p || !g_open) { omega_gpu_session_set_error("sync without open device"); return -1; } - int rc = to_gpu ? p->sync_cpu_to_gpu(p->ctx, m->handle, 0, m->size) : p->sync_gpu_to_cpu(p->ctx, m->handle, 0, m->size); - if (rc != OMEGA_GPU_PLAT_OK) { fail_plat(to_gpu ? "sync_cpu_to_gpu" : "sync_gpu_to_cpu", rc); return -1; } - return 0; -} -int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m) { return sync_mem(m, 1); } -int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m) { return sync_mem(m, 0); } - -int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes) { - if (s->reserved && (bytes > s->cap || !s->mem.cpu)) { - omega_gpu_fmt(g_err, sizeof g_err, "serving reservation exceeded: need %zu bytes, reserved %zu", bytes, s->cap); - return OMEGA_GPU_SESSION_SCRATCH_RESERVED; - } - if (bytes > s->high_water) s->high_water = bytes; - if (s->cap >= bytes && s->mem.cpu) return 0; - omega_gpu_session_free(&s->mem); - s->cap = 0; - if (omega_gpu_session_alloc(s->high_water, &s->mem) != 0) return -1; - s->cap = (size_t)s->mem.size; - return 0; -} - -void omega_gpu_session_scratch_free(OmegaGpuScratch *s) { - omega_gpu_session_free(&s->mem); - s->cap = 0; - s->reserved = false; -} - -int omega_gpu_session_scratch_reserve(OmegaGpuScratch *s, size_t bytes) { - s->reserved = false; /* grow normally first */ - if (omega_gpu_session_scratch(s, bytes) != 0) return -1; - s->reserved = true; - return 0; -} - -void omega_gpu_session_scratch_unreserve(OmegaGpuScratch *s) { s->reserved = false; } - -static void free_session_buffers(void) { - omega_gpu_session_free(&g_s.qmd); omega_gpu_session_free(&g_s.marker); - omega_gpu_session_free(&g_s.cbank); omega_gpu_session_free(&g_s.pb); -} - -/* ---- open, close ---- */ - -OmegaGpuSession *omega_gpu_session_open(void) { - if (LOAD(g_blocked)) { omega_gpu_session_set_error("process latched"); return NULL; } - if (g_open) return &g_s; - const OmegaGpuPlatform *p = platform(); - if (!p) { omega_gpu_session_set_error("no GPU platform installed (omega_gpu_session_set_platform)"); return NULL; } - uint64_t t0 = p->time_now_ns(p->ctx); - const uint32_t opens = g_s.opens; - memset(&g_s, 0, sizeof g_s); - g_s.opens = opens; - int rc = p->device_open(p->ctx, 0, &g_s.dev); - if (rc != OMEGA_GPU_PLAT_OK) { fail_plat("device_open", rc); memset(&g_s.dev, 0, sizeof g_s.dev); return NULL; } - g_open = true; /* so alloc / free work during the rest of the open */ - /* same four buffers, same sizes, same order as before cut C; every one GPU-uncached */ - if (mem_alloc(OMEGA_GPU_HANDLE_BUF_QUEUE, RIGHTS_RING, 0x10000, &g_s.pb) || - mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_CBANK, PAGE, &g_s.cbank) || - mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_MARKER, PAGE, &g_s.marker) || - mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_DATA, 0x10000, &g_s.qmd) || - (rc = p->queue_open(p->ctx, g_s.dev, g_s.pb.handle, &g_s.queue)) != OMEGA_GPU_PLAT_OK) { - char keep[sizeof g_err]; - if (rc != OMEGA_GPU_PLAT_OK) fail_plat("queue_open", rc); - memcpy(keep, g_err, sizeof keep); - free_session_buffers(); - g_open = false; - (void)p->device_close(p->ctx, g_s.dev); - memset(&g_s.dev, 0, sizeof g_s.dev); - omega_gpu_fmt(g_err, sizeof g_err, "session scratch alloc (%s)", keep); - return NULL; - } - g_s.opens++; - g_s.last_open_ns = p->time_now_ns(p->ctx) - t0; - return &g_s; -} - -int omega_gpu_session_on_close(void (*hook)(void)) { /* caller holds the lock (the APIs register from their open path) */ - if (!hook) return -1; - int rc = 0; - bool seen = false; - for (unsigned i = 0; i < g_nhooks; i++) if (g_hooks[i] == hook) seen = true; - if (!seen) { if (g_nhooks < sizeof g_hooks / sizeof g_hooks[0]) g_hooks[g_nhooks++] = hook; else rc = -1; } - return rc; -} - -void omega_gpu_session_close(void) { - omega_gpu_session_lock(); - const OmegaGpuPlatform *p = LOAD(g_p); - if (g_open && !LOAD(g_blocked) && p) { - for (unsigned i = 0; i < g_nhooks; i++) g_hooks[i](); - if (!LOAD(g_blocked)) { /* a hook's launch may have latched: then nothing below runs */ - (void)p->queue_close(p->ctx, g_s.queue); - memset(&g_s.queue, 0, sizeof g_s.queue); - free_session_buffers(); - (void)p->device_close(p->ctx, g_s.dev); /* every handle of this device is stale from here */ - memset(&g_s.dev, 0, sizeof g_s.dev); - g_open = false; - } - } - omega_gpu_session_unlock(); -} - -/* ---- launch ---- */ - -static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } - -static inline void cpu_relax(void) { -#if defined(__aarch64__) - __asm__ volatile("yield" ::: "memory"); -#else - __asm__ volatile("" ::: "memory"); -#endif -} - -#define WAIT_CANCELLED 1 -#define WAIT_TIMED_OUT 2 -#define WAIT_REFUSED 3 - -/* Marker wait by POLLING. With spin_us, the host first re-reads the uncached marker word back to back (with the - * ARM yield hint) so a launch that finishes inside the window is seen within about one read. Then the platform's - * poll_word in slices of OMEGA_GPU_SESSION_POLL_SLICE_MS (Linux reference: the m16 50 us sleep-poll) until - * timeout_ms, checking for a cancel request between slices. */ -static int session_wait(const OmegaGpuPlatform *p, uint64_t off, uint32_t want, uint64_t timeout_ms, uint32_t spin_us) { - volatile uint32_t *m = (volatile uint32_t *)((uint8_t *)g_s.marker.cpu + off); - if (spin_us) { - const uint64_t end = p->time_now_ns(p->ctx) + (uint64_t)spin_us * 1000u; - do { - if ((int32_t)(*m - want) >= 0) return 0; - if (LOAD(g_cancel)) return WAIT_CANCELLED; - cpu_relax(); - } while (p->time_now_ns(p->ctx) < end); - } - uint64_t waited = 0; - for (;;) { - if (LOAD(g_cancel)) return WAIT_CANCELLED; - const uint64_t left = timeout_ms - waited; - const uint64_t slice = left < OMEGA_GPU_SESSION_POLL_SLICE_MS ? left : OMEGA_GPU_SESSION_POLL_SLICE_MS; - uint32_t seen = 0; - int rc = p->poll_word(p->ctx, g_s.marker.handle, off, want, slice, &seen); - if (rc == OMEGA_GPU_PLAT_OK) return 0; - if (rc != OMEGA_GPU_POLL_TIMED_OUT) return WAIT_REFUSED; - waited += slice; - if (waited >= timeout_ms) return WAIT_TIMED_OUT; - } -} - -int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out) { - const OmegaGpuPlatform *p = LOAD(g_p); - if (!g_open || LOAD(g_blocked) || !p) { - omega_gpu_session_set_error(LOAD(g_blocked) ? "process latched" : "launch without open device"); return -1; - } - if (!L || !L->args || L->n_args == 0 || L->n_args > OMEGA_GPU_SESSION_MAX_ARGS || L->threads_x == 0 || L->grid_x == 0 || L->grid_y == 0 || - L->spin_us > OMEGA_GPU_SESSION_MAX_SPIN_US) { - omega_gpu_session_set_error("launch arguments"); return -1; - } - if (take_cancel()) { omega_gpu_session_set_error("launch cancelled before submit"); return OMEGA_GPU_SESSION_CANCELLED; } - const uint32_t threads_y = L->threads_y ? L->threads_y : 1; - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, g_s.cbank.va, L->threads_x, threads_y, L->grid_x, L->grid_y); - memcpy(g_s.cbank.cpu, cbank_data, sizeof cbank_data); - memcpy((uint8_t *)g_s.cbank.cpu + 0x380, L->args, (size_t)L->n_args * 4u); - - const uint64_t qmd0_va = g_s.qmd.va, qmd1_va = g_s.qmd.va + 0x1000, sem_va = g_s.qmd.va + 0x2000, scratch_va = g_s.qmd.va + 0x4000; - uint32_t gpr = L->gpr_count > 64u ? round_up(L->gpr_count, 8u) : 64u; - OmegaBlackwellQmdConfig cfg = { - .code_va = L->code_va, .cbank_va = g_s.cbank.va, .scratch_va = scratch_va, .sem_va = sem_va, - .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = L->num_elements, - .threads_per_block = L->threads_x, .grid_width = L->grid_x * L->grid_y, .threads_x = L->threads_x, .threads_y = threads_y, - .grid_x = L->grid_x, .grid_y = L->grid_y, .gpr_count = gpr, - .shared_bytes = L->shared_bytes, - }; - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - if (omega_blackwell_build_qmd1(qmd1_words, &cfg) != 0) { omega_gpu_session_set_error("qmd build (shared_bytes)"); return -1; } - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { omega_gpu_session_set_error("qmd invariants"); return -1; } - memcpy(g_s.qmd.cpu, qmd0_words, sizeof qmd0_words); - memcpy((uint8_t *)g_s.qmd.cpu + 0x1000, qmd1_words, sizeof qmd1_words); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)g_s.qmd.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)g_s.marker.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)g_s.marker.cpu + 0x10); - *hsem = 0; *hmarker = 0; *hmarker2 = 0; - /* explicit visibility of everything the CPU just wrote (Linux reference: dsb sy, the barrier issued here before) */ - int rc = p->sync_cpu_to_gpu(p->ctx, g_s.cbank.handle, 0, PAGE); - if (rc == OMEGA_GPU_PLAT_OK) rc = p->sync_cpu_to_gpu(p->ctx, g_s.qmd.handle, 0, 0x3000); - if (rc == OMEGA_GPU_PLAT_OK) rc = p->sync_cpu_to_gpu(p->ctx, g_s.marker.handle, 0, 0x20); - if (rc != OMEGA_GPU_PLAT_OK) { fail_plat("sync_cpu_to_gpu", rc); return -1; } - - uint32_t pb[1024]; - size_t n = 0; - memcpy(&pb[n], SETUP_WORDS, sizeof SETUP_WORDS); n += sizeof SETUP_WORDS / 4; - /* Invalidate the SM instruction, constant and data caches before this launch - * (cut 1b finding: a reused code address served stale instructions; clcec0.h - * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, bits INSTRUCTION 0, DATA 4, CONSTANT 12). */ - pb[n++] = bw_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; - /* constant bank 0: driver words, then our arguments at 0x380 (inline upload) */ - pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g_s.cbank.va >> 32); pb[n++] = (uint32_t)g_s.cbank.va; - pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; - pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (224u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_data, 224 * 4); n += 224; - pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g_s.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g_s.cbank.va + 0x380); - pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = L->n_args * 4u; pb[n++] = 0x00000001; - pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (L->n_args << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], L->args, (size_t)L->n_args * 4u); n += L->n_args; - /* QMD0 (null grid, dependence 2) */ - pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; - /* intermediate semaphore init */ - pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; - pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; - pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (1u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - /* QMD1 (the kernel) */ - pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; - /* first marker */ - pb[n++] = bw_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)g_s.marker.va; pb[n++] = (uint32_t)(g_s.marker.va >> 32); - pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - /* C3 tail: L2_FLUSH_DIRTY, then the second release on the uncached marker page */ - pb[n++] = bw_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = bw_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)(g_s.marker.va + 0x10); pb[n++] = (uint32_t)((g_s.marker.va + 0x10) >> 32); - pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - - const uint32_t spin_us = L->spin_us ? L->spin_us : omega_gpu_session_spin_us(); - uint64_t t0 = p->time_now_ns(p->ctx); - rc = p->queue_submit(p->ctx, g_s.queue, pb, (uint32_t)n); - if (rc != OMEGA_GPU_PLAT_OK) { - fail_plat("submit_methods", rc); /* contract: a refused submit rang no doorbell, nothing is in flight */ - return -1; - } - int w = session_wait(p, 0, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, L->timeout_ms, spin_us); - if (w == 0) w = session_wait(p, 0x10, OMEGA_BW_MARKER2_PAYLOAD, L->timeout_ms, spin_us); - if (w != 0) { - /* uncertain completion: keep everything (parked), refuse every later call */ - if (w == WAIT_CANCELLED) { - (void)take_cancel(); - latch("launch cancelled after submit (completion uncertain, latched)"); - return OMEGA_GPU_SESSION_CANCELLED; - } - latch(w == WAIT_TIMED_OUT ? "marker wait timed out (latched)" : "marker poll refused (latched)"); - return -1; - } - (void)p->sync_gpu_to_cpu(p->ctx, g_s.marker.handle, 0, 0x20); - (void)p->sync_gpu_to_cpu(p->ctx, g_s.qmd.handle, 0x2000, 4); - uint64_t t1 = p->time_now_ns(p->ctx); - (void)p->queue_retire(p->ctx, g_s.queue); /* both releases landed: the GPFIFO entry is consumed */ - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { omega_gpu_session_set_error("intermediate semaphore not DONE"); return -1; } - if (elapsed_ns) *elapsed_ns += t1 - t0; - if (marker_out) *marker_out = *hmarker; - (void)hmarker2; - return 0; -} - -uint32_t omega_gpu_session_open_count(void) { return g_s.opens; } diff --git a/src/omega_gpu_session.h b/src/omega_gpu_session.h deleted file mode 100644 index 82c5e5d22..000000000 --- a/src/omega_gpu_session.h +++ /dev/null @@ -1,256 +0,0 @@ -#ifndef OMEGA_GPU_SESSION_H -#define OMEGA_GPU_SESSION_H -/* - * omega_gpu_session: the ONE persistent device for the native GPU APIs - * (FB-1 cut 4b, 2026-10-04). Shared by omega_gpu_matmul_api, - * omega_gpu_elementwise_api and omega_gpu_attention_api. - * - * Before this cut the matmul API kept its own device open for the process while - * the elementwise and attention APIs opened a client, device, VA space and - * channel for EVERY call and closed them again (~40 ms per call against ~0.1 ms - * of chip time; TinyLlama decode makes ~3500 elementwise calls per 32 tokens, - * sovereign-core cut 3c: 0.207 tok/s). Now: - * - one RM client / device / channel per process, opened on the first launch of - * any API and kept until omega_gpu_session_close(); - * - one pushbuffer, constant bank, marker page and QMD page, reused per launch; - * - staging buffers owned by the callers grow to a high-water mark and are reused - * (omega_gpu_session_scratch); - * - every buffer is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE, read - * 2026-10-04: "For system memory this will not be coherent with direct CPU - * mappings"; the default for system memory is uncached), because the host - * writes inputs the chip then reads, and polls the markers the chip writes; - * - every launch keeps the chip-proven sequence: shader-cache invalidate - * (clcec0.h NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), constant bank - * upload, QMD0 / QMD1, first marker, L2_FLUSH_DIRTY, second marker on the - * uncached page (C3 tail, omega#225/#230), GPFIFO retire after completion. - * - an uncertain completion (marker wait timed out) latches the process: nothing - * is freed or closed (the chip may still be running) and every later launch - * of every API is refused, as the engine does (omega_gpu_engine.h). - * - * Threading: one process-wide mutex. A caller takes omega_gpu_session_lock(), - * does its whole call (kernel lookup, staging, launches, readback) and unlocks. - * Calls from several threads therefore serialise on the device; that is the - * documented model (one channel, one GPFIFO). - * - * Diagnostics (cut 4b flake investigation): every failure names its stage - * (omega_gpu_session_last_error) and an open failure carries the driver text - * (Nvrm.err: RM class, ioctl errno, RM status) so a first-call failure is never - * reported as a bare CHIP_FAIL again. - * - * Portability (native v1 P07 cut C, session part; aienos#286, docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md): - * this file and omega_gpu_session.c no longer name a Linux driver type or call one. Everything the session - * needs from the machine goes through the installed OmegaGpuPlatform (src/omega_gpu_platform.h, ABI 1.1, - * service set OMEGA_GPU_SVC_REQUIRED_SESSION): device open/close, typed DMA buffers with explicit rights, - * kind and GPU-uncached policy, the submission queue, POLLING completion (poll_word; the session never - * claims or waits on an interrupt), explicit CPU<->GPU sync, the nanosecond clock, the session lock and - * CPU-only host memory. omega_gpu_session_set_platform installs one; the hosted build installs the Linux - * reference (src/omega_gpu_platform_linux.c, reference only) on first use when none was installed; the - * freestanding build (OMEGA_GPU_NO_POSIX) has no default and refuses until a platform is installed. - * Buffers are OmegaGpuMem: a typed handle (index + generation) plus the CPU view and the GPU VA as two - * distinct fields; no bus or physical address reaches the APIs. A handle from a closed device is stale and - * every use of it is refused. - * - * Uncertain completion parks, it never releases: after a marker poll timed out or a launch was cancelled - * after submit, the device may still be reading or writing any session buffer, so every buffer the session - * or an API frees from then on is PARKED (kept allocated, counted in omega_gpu_session_parked) and never - * returned to the platform; close and reopen are refused; the latch holds for the life of the process. - */ -#include -#include -#include -#include "omega_gpu_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* A device buffer: typed handle, kind, CPU view (cpu, size bytes) and GPU VA (va). cpu NULL = none. */ -typedef struct { - OmegaGpuBufferHandle handle; - uint32_t kind; /* OMEGA_GPU_HANDLE_BUF_DATA, _BUF_CODE or _BUF_QUEUE */ - void *cpu; /* CPU view (OmegaCpuView.ptr) */ - uint64_t va; /* GPU virtual address (OmegaGpuVa.va) */ - uint64_t size; /* bytes of both views */ -} OmegaGpuMem; - -typedef struct { - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle queue; - OmegaGpuMem pb, cbank, marker, qmd; /* per-launch scratch, owned by the session (pb is the queue ring) */ - uint32_t opens; /* device opens in this process */ - uint64_t last_open_ns; /* wall time of the last successful open */ -} OmegaGpuSession; - -/* A caller-owned staging buffer that grows to its high-water mark. */ -typedef struct { - OmegaGpuMem mem; - size_t cap; /* usable bytes */ - size_t high_water; /* largest request so far */ - bool reserved; /* serving reservation active: a request past cap is refused, never allocated (omega_gpu_session_scratch_reserve) */ -} OmegaGpuScratch; - -/* One launch: a kernel already resident at code_va, the argument words for - * constant bank 0 at 0x380 (buffer addresses then parameters), the grid. */ -typedef struct { - uint64_t code_va; - uint32_t gpr_count; /* registers the QMD declares (multiple of 8, >= 64 in practice) */ - uint32_t threads_x, threads_y; - uint32_t grid_x, grid_y; - size_t num_elements; /* QMD config num_elements (kept per API for identical words) */ - const uint32_t *args; /* n_args words written at cbank + 0x380 */ - uint32_t n_args; /* <= OMEGA_GPU_SESSION_MAX_ARGS */ - uint64_t timeout_ms; /* marker poll; past it the completion is uncertain and the process latches */ - uint32_t shared_bytes; /* shared memory per CTA; 0 = the QMD default (1024) */ - uint32_t spin_us; /* poll the marker without sleeping for up to this long, then the platform's - poll_word (Linux reference: 50 us sleep-poll) until timeout_ms; 0 = poll_word only */ -} OmegaGpuLaunch; -#define OMEGA_GPU_SESSION_MAX_SPIN_US 1000000u -#define OMEGA_GPU_SESSION_MAX_ARGS 32u -/* poll_word is called in slices of at most this many ms so a cancel request is seen within one slice */ -#define OMEGA_GPU_SESSION_POLL_SLICE_MS 1u - -/* ---- platform (ABI 1.1) ---- */ - -/* Installs the platform the session runs on. Negotiates caps against OMEGA_GPU_SVC_REQUIRED_SESSION and checks the - * table (omega_gpu_platform_check_for). OMEGA_GPU_PLAT_OK, or the refusal; REFUSED_BUSY while the device is open, - * the lock is held or the process is latched. NULL p uninstalls (refused the same way). Install once, at start. */ -int omega_gpu_session_set_platform(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps); -/* The installed platform (the hosted build installs the Linux reference here when none was installed); NULL in the - * freestanding build until omega_gpu_session_set_platform. */ -const OmegaGpuPlatform *omega_gpu_session_platform(void); -/* The installed platform's caps.submit_prefix_words: words queue_submit may put ahead of the caller's in the ring, so a - * caller that fills the ring budgets ring words minus this (omega #457 L2 invalidate prefix). 0 with no platform. */ -uint32_t omega_gpu_session_submit_prefix_words(void); - -/* Completion is observed by polling a GPU-uncached word; the session never claims interrupt support. */ -typedef enum { OMEGA_GPU_COMPLETION_POLLING = 1 } OmegaGpuCompletionMode; -OmegaGpuCompletionMode omega_gpu_session_completion_mode(void); - -/* Platform clock in ns (CLOCK_NS); 0 without a platform. */ -uint64_t omega_gpu_session_now_ns(void); - -/* CPU-only memory for API tables and staging, from the platform HOST_MEM service (Linux reference: malloc/free). - * NULL without a platform or on refusal; 0 bytes gives a unique 1-byte block (malloc(0) behaviour); calloc also - * refuses n * size overflow. free(NULL) is a no-op. */ -void *omega_gpu_host_alloc(size_t bytes); -void *omega_gpu_host_calloc(size_t n, size_t size); -void omega_gpu_host_free(void *p); - -/* ---- lock, open, state ---- */ - -/* Take the session lock (platform LOCK service, lock id OMEGA_GPU_SESSION_LOCK_ID). Does not touch the device. - * Without a platform it is a no-op and the open that follows refuses. */ -#define OMEGA_GPU_SESSION_LOCK_ID 0u -void omega_gpu_session_lock(void); -void omega_gpu_session_unlock(void); - -/* Caller holds the lock. Opens the device on first use. NULL when the process is - * latched, no platform is installed or the open failed (stage in omega_gpu_session_last_error). */ -OmegaGpuSession *omega_gpu_session_open(void); -bool omega_gpu_session_is_open(void); - -/* 1 once an uncertain completion has latched this process. */ -int omega_gpu_session_is_blocked(void); - -/* Process-wide marker-poll spin window, used by every launch whose own spin_us is 0 - * (the matmul, elementwise and attention APIs leave it 0). 0 (the default) keeps the - * poll_word sleep-poll (Linux reference: 50 us, which Linux timer slack rounds to about 102 us - * per launch on GB10, omega#328). 0 on success, -1 above OMEGA_GPU_SESSION_MAX_SPIN_US (setting unchanged). */ -int omega_gpu_session_set_spin_us(uint32_t us); -uint32_t omega_gpu_session_spin_us(void); - -/* ---- buffers ---- */ - -/* Caller holds the lock, device open. GPU-uncached DATA buffer (CPU and GPU read/write), page rounded. */ -int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out); -/* Caller holds the lock, device open. A CODE buffer (CPU writes, GPU executes, GPU never writes) for code_size - * bytes with the 2 KB instruction prefetch tail (omega_gpu_code_alloc.h), the tail zero-filled; the caller writes - * the code to out->cpu. */ -int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out); -/* Releases m to the platform and zeroes *m. Latched: m is PARKED instead (never released). A handle from a closed - * device (stale) or a closed session is refused: nothing is released, the refusal is counted - * (OmegaGpuAllocStats.stale_refusals) and *m is zeroed. */ -void omega_gpu_session_free(OmegaGpuMem *m); - -/* Explicit visibility of a whole buffer (platform SYNC): CPU writes before the device reads them, device writes - * before the CPU reads them (Linux reference: dsb sy, the barrier the APIs issued themselves before cut C). - * 0 also for a buffer with no CPU view (nothing to sync); -1 with the stage named when refused or no device. */ -int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m); -int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m); - -/* Caller holds the lock, device open. Makes s->mem at least `bytes` long - * (reallocated when it grows; contents are not kept). */ -int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes); -/* Caller holds the lock, device open. Allocates s->mem for `bytes` now and marks it reserved: from then on - * omega_gpu_session_scratch(s, n) with n <= the reserved capacity never touches the driver, and with n past it - * returns OMEGA_GPU_SESSION_SCRATCH_RESERVED (-2) with a clear error and no allocation. 0 on success, -1 on - * allocation failure (not reserved then). Cleared by omega_gpu_session_scratch_free (device close) or _unreserve. */ -#define OMEGA_GPU_SESSION_SCRATCH_RESERVED (-2) -int omega_gpu_session_scratch_reserve(OmegaGpuScratch *s, size_t bytes); -void omega_gpu_session_scratch_unreserve(OmegaGpuScratch *s); -void omega_gpu_session_scratch_free(OmegaGpuScratch *s); - -/* ---- launch, cancel ---- */ - -/* Caller holds the lock, device open, not latched. Submits one launch and polls - * for both markers. 0 on success; -1 with the stage named on failure. A marker - * timeout latches the process (uncertain completion). elapsed_ns (submit to second - * marker) and the observed first marker word are added / stored when the pointers are given. - * OMEGA_GPU_SESSION_CANCELLED: a cancel request was seen. Before submit nothing was submitted and the - * session stays usable; after submit the completion is uncertain and the process latches. */ -#define OMEGA_GPU_SESSION_CANCELLED (-3) -int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out); - -/* Asks the launch in progress (or the next one) to stop. Any thread, no lock. Polling cannot stop the device: a - * launch already submitted is not cancelled on the chip, its completion becomes uncertain (latch + park). The - * request is consumed by the launch that sees it. */ -void omega_gpu_session_cancel(void); - -/* Stage of the most recent failure ("" if none). Shared by every API. */ -const char *omega_gpu_session_last_error(void); -void omega_gpu_session_set_error(const char *stage); - -/* Caller holds the lock. Register a function the session calls (lock held, device - * still open) right before it closes, so an API can drop its resident kernels and - * scratch. Up to 8; the same function is registered once. (Taking the lock inside - * deadlocked the first call of every API on 2026-10-04: the APIs register from - * their open path, which already holds it.) */ -int omega_gpu_session_on_close(void (*hook)(void)); - -/* Close the device and free every session buffer. Takes the lock itself. - * Refused (no-op) after an uncertain completion. The next open reopens; every handle of the - * closed device is stale from then on. */ -void omega_gpu_session_close(void); - -/* Device opens so far in this process (diagnostics; a persistent session shows 1). */ -uint32_t omega_gpu_session_open_count(void); - -/* Driver allocations made through omega_gpu_session_alloc (every GPU API buffer, tensor, scratch growth and kernel - * code buffer) since the process started, for measurement: a serving daemon reads it after warm-up and per request - * to show that serving asks the driver for nothing. Covers this session layer only, not other engines. */ -typedef struct { - uint64_t allocs; /* successful driver allocations */ - uint64_t alloc_bytes; /* their page-rounded bytes */ - uint64_t alloc_failures; /* driver refusals (e.g. NV_ERR_NO_MEMORY) */ - uint64_t frees; /* driver frees */ - uint64_t stale_refusals; /* frees refused because the handle was stale (closed device or double free) */ -} OmegaGpuAllocStats; -void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out); - -/* Buffers parked after an uncertain completion: kept allocated, never returned to the platform. The session's own - * launch buffers (ring, constant bank, marker, QMD page) are parked at the latch; every later free parks too. - * The first OMEGA_GPU_SESSION_PARK_MAX are listed by handle; past that they are still kept, counted in untracked. */ -#define OMEGA_GPU_SESSION_PARK_MAX 512u -typedef struct { - uint32_t buffers; /* parked buffers (listed + untracked) */ - uint32_t untracked; /* parked past the list (still never released) */ - uint64_t bytes; /* their bytes */ -} OmegaGpuParkStats; -void omega_gpu_session_parked(OmegaGpuParkStats *out); -/* 1 if this handle is parked (listed). */ -int omega_gpu_session_is_parked(OmegaGpuBufferHandle h); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_tcgemm_api.c b/src/omega_gpu_tcgemm_api.c deleted file mode 100644 index 29adb491e..000000000 --- a/src/omega_gpu_tcgemm_api.c +++ /dev/null @@ -1,188 +0,0 @@ -/* omega_gpu_tcgemm_api.c: tensor-core FP8 grouped GEMM on the shared session (OWN-30B T3 cut 1). See the header. - * Submission path and buffer policy follow omega_gpu_fp8gemm_api.c (GPU-uncached buffers, one omega_gpu_session_launch). */ -#include "omega_gpu_tcgemm_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include -#include - -#define CACHE_SLOTS 8 -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -typedef struct { bool valid, pinned; OmegaTcGemmSpec spec; OmegaBlackwellKernel kernel; OmegaGpuMem code; } Slot; -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt, pad[2]; } TileEntry; -_Static_assert(sizeof(TileEntry) == OMEGA_TCGEMM_TILE_BYTES, "tile entry layout"); - -static struct { - OmegaGpuScratch x_buf, y_buf, tile_buf, ridx_buf; - uint32_t rt, ct, warps; - int mutant; - bool hooked; - Slot cache[CACHE_SLOTS]; - unsigned next; -} g; - -const char *omega_gpu_tcgemm_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_tcgemm_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_TCGEMM_OK: return "OK"; - case OMEGA_GPU_TCGEMM_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_TCGEMM_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_TCGEMM_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_TCGEMM_CHIP_FAIL: return "CHIP_FAIL"; - default: return "UNKNOWN"; - } -} -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { if (!g.cache[i].valid) continue; omega_gpu_session_free(&g.cache[i].code); memset(&g.cache[i], 0, sizeof g.cache[i]); } - g.next = 0; -} -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g.x_buf); omega_gpu_session_scratch_free(&g.y_buf); - omega_gpu_session_scratch_free(&g.tile_buf); omega_gpu_session_scratch_free(&g.ridx_buf); -} -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -void omega_gpu_tcgemm_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_tcgemm_set_shape(uint32_t rt, uint32_t ct, uint32_t w) { omega_gpu_session_lock(); g.rt = rt; g.ct = ct; g.warps = w; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_tcgemm_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } - -void omega_gpu_tcgemm_spec_for(uint32_t k, uint32_t n, OmegaTcGemmSpec *spec) { - memset(spec, 0, sizeof *spec); - spec->k = k; - /* 64 rows x 128 columns per CTA, 8 warps (peak 124 registers, declared 128); 64 columns when n is not a multiple of 128 */ - spec->rt = g.rt ? g.rt : 4u; spec->ct = g.ct ? g.ct : (n % 128u == 0 ? 2u : 1u); spec->warps = g.warps ? g.warps : 8u; - spec->mutant = g.mutant; -} - -static int kernel_for(const OmegaTcGemmSpec *spec, Slot **out, bool *hit) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { Slot *s = &g.cache[i]; if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_TCGEMM_OK; } } - Slot *s = NULL; - for (unsigned i = 0; i < CACHE_SLOTS && !s; i++) { Slot *c = &g.cache[(g.next + i) % CACHE_SLOTS]; if (!c->valid || !c->pinned) { s = c; g.next = (unsigned)((c - g.cache) + 1) % CACHE_SLOTS; } } - if (!s) { omega_gpu_session_set_error("tc gemm kernel cache: every slot holds a prepared kernel"); return OMEGA_GPU_TCGEMM_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("tc gemm codegen: host memory"); return OMEGA_GPU_TCGEMM_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_tcgemm_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("tc gemm codegen refused the shape"); return OMEGA_GPU_TCGEMM_CODEGEN_FAIL; } - const uint32_t decl = omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage); - if (decl > 128u || (uint64_t)32u * spec->warps * decl > 65536u) { - char e[160]; omega_gpu_fmt(e, sizeof e, "tc gemm kernel: %u warps x %u declared registers do not fit", spec->warps, decl); - omega_gpu_session_set_error(e); omega_gpu_host_free(prog); return OMEGA_GPU_TCGEMM_TOO_LARGE; - } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_TCGEMM_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_TCGEMM_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_TCGEMM_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - *out = s; *hit = false; - return OMEGA_GPU_TCGEMM_OK; -} - -int omega_gpu_tcgemm_prepare(uint32_t k) { - OmegaTcGemmSpec sp; omega_gpu_tcgemm_spec_for(k, 128u, &sp); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_TCGEMM_OK; Slot *s = NULL; bool hit = false; - if (!dev_open_locked()) rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; - else if ((rc = kernel_for(&sp, &s, &hit)) == OMEGA_GPU_TCGEMM_OK) s->pinned = true; - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_tcgemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *ids, const uint32_t *trow, const float *x, uint32_t x_rows, float *y, OmegaGpuTcGemmInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - uint32_t experts = 0, n = 0, k = 0; - if (!t) return OMEGA_GPU_TCGEMM_BAD_ARGS; - omega_gpu_fp8_tensor_shape(t, &experts, &n, &k); - if (!experts || !ids || !trow || !x || !y || M == 0 || x_rows == 0) return OMEGA_GPU_TCGEMM_BAD_ARGS; - OmegaTcGemmSpec spec; omega_gpu_tcgemm_spec_for(k, n, &spec); - if (!omega_tcgemm_spec_ok(&spec)) return OMEGA_GPU_TCGEMM_BAD_ARGS; - const uint32_t BM = 16u * spec.rt, span = omega_tcgemm_span(&spec); - if (n % span || n % 128u) return OMEGA_GPU_TCGEMM_BAD_ARGS; - uint32_t segs = 0, ntiles = 0; - for (uint32_t i = 0; i < M;) { - if (ids[i] >= experts) return OMEGA_GPU_TCGEMM_BAD_ARGS; - uint32_t j = i; while (j < M && ids[j] == ids[i]) { if (trow[j] >= x_rows) return OMEGA_GPU_TCGEMM_BAD_ARGS; j++; } - if (j < M && ids[j] < ids[i]) return OMEGA_GPU_TCGEMM_BAD_ARGS; - segs++; ntiles += (j - i + BM - 1) / BM; i = j; - } - if (ntiles > 65535u) return OMEGA_GPU_TCGEMM_TOO_LARGE; - const uint32_t grid_x = n / span; - - omega_gpu_session_lock(); - int rc = OMEGA_GPU_TCGEMM_OK; - if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_TCGEMM_CHIP_FAIL; } - int src = omega_gpu_session_scratch(&g.x_buf, (size_t)x_rows * k * 2u); - if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)M * n * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.tile_buf, (size_t)ntiles * OMEGA_TCGEMM_TILE_BYTES); - if (src == 0) src = omega_gpu_session_scratch(&g.ridx_buf, ((size_t)M + BM) * 4u); - if (src != 0) { omega_gpu_session_unlock(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_TCGEMM_TOO_LARGE : OMEGA_GPU_TCGEMM_CHIP_FAIL; } - Slot *ks = NULL; bool hit = false; - rc = kernel_for(&spec, &ks, &hit); - if (rc != OMEGA_GPU_TCGEMM_OK) { omega_gpu_session_unlock(); return rc; } - - TileEntry *tab = g.tile_buf.mem.cpu; uint32_t *ridx = g.ridx_buf.mem.cpu; uint32_t nt = 0; - uint64_t distinct = 0; - for (uint32_t i = 0; i < M;) { - uint32_t j = i; while (j < M && ids[j] == ids[i]) j++; - uint64_t w_va = 0, s_va = 0; (void)omega_gpu_fp8_tensor_entry(t, ids[i], &w_va, &s_va); - for (uint32_t r = i; r < j; r += BM) { memset(&tab[nt], 0, sizeof tab[nt]); tab[nt].w_va = w_va; tab[nt].s_va = s_va; tab[nt].row0 = r; tab[nt].cnt = j - r < BM ? j - r : BM; nt++; } - distinct += (uint64_t)n * k; i = j; - } - { uint32_t *tmp = malloc(((size_t)M + BM) * 4u); if (!tmp) { omega_gpu_session_unlock(); return OMEGA_GPU_TCGEMM_CHIP_FAIL; } - for (uint32_t i = 0; i < M + BM; i++) tmp[i] = i < M ? trow[i] : 0u; - memcpy(ridx, tmp, ((size_t)M + BM) * 4u); free(tmp); } - { /* permute in cached memory, one sequential copy per row into the uncached buffer */ - uint16_t *row = malloc((size_t)k * 2u); uint16_t *xd = g.x_buf.mem.cpu; - if (!row) { omega_gpu_session_unlock(); return OMEGA_GPU_TCGEMM_CHIP_FAIL; } - for (uint32_t r = 0; r < x_rows; r++) { omega_tcgemm_permute_x(x + (size_t)r * k, k, row); memcpy(xd + (size_t)r * k, row, (size_t)k * 2u); } - free(row); - } - float *yd = g.y_buf.mem.cpu; - for (size_t i = 0; i < (size_t)M * n; i++) yd[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g.tile_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.ridx_buf.mem) != 0 || - omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; - - uint32_t args[OMEGA_TCGEMM_ARGS_WORDS]; - const uint64_t va[4] = { g.tile_buf.mem.va, g.ridx_buf.mem.va, g.x_buf.mem.va, g.y_buf.mem.va }; - for (int i = 0; i < 4; i++) { args[2 * i] = (uint32_t)va[i]; args[2 * i + 1] = (uint32_t)(va[i] >> 32); } - args[8] = n; - const uint32_t decl = omega_bw_gpr_declared(ks->kernel.gpr_count); - if (info) { - info->rows = M; info->segments = segs; info->tiles = nt; info->n = n; info->k = k; info->rt = spec.rt; info->ct = spec.ct; info->warps = spec.warps; - info->grid_x = grid_x; info->grid_y = nt; info->gpr_declared = decl; - info->weight_bytes = distinct; info->streamed_bytes = (uint64_t)nt * n * k; - info->act_bytes = (uint64_t)nt * grid_x * BM * k * 2u; info->kernel_cache_hit = hit; - } - if (rc == OMEGA_GPU_TCGEMM_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = decl, - .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = grid_x, .grid_y = nt, - .num_elements = (size_t)M * n, - .args = args, .n_args = OMEGA_TCGEMM_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = omega_tcgemm_shared_bytes(&spec), - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; - } - if (rc == OMEGA_GPU_TCGEMM_OK && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; - if (rc == OMEGA_GPU_TCGEMM_OK) { - size_t unchanged = 0; - for (size_t i = 0; i < (size_t)M * n; i++) if (yd[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("output poison survived"); rc = OMEGA_GPU_TCGEMM_CHIP_FAIL; } - else memcpy(y, yd, (size_t)M * n * sizeof *y); - } - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} diff --git a/src/omega_gpu_tcgemm_api.h b/src/omega_gpu_tcgemm_api.h deleted file mode 100644 index 10eecbaa7..000000000 --- a/src/omega_gpu_tcgemm_api.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef OMEGA_GPU_TCGEMM_API_H -#define OMEGA_GPU_TCGEMM_API_H -/* - * omega_gpu_tcgemm_api (OWN-30B T3 cut 1): FP8 e4m3 block-128-scaled GROUPED GEMM on the tensor cores - * (HMMA.16816.F32.BF16; e4m3 -> bf16 dequantised in registers, exact). New file on the shared session. - * - * int omega_gpu_tcgemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *expert_ids, - * const uint32_t *token_rows, const float *x, uint32_t x_rows, float *y, OmegaGpuTcGemmInfo *info); - * Row i computes expert expert_ids[i] (non-decreasing) on x[token_rows[i]]; y is M x n f32 in row-table order. - * Arithmetic (bit-exact contract, tests/gpu_tcgemm_test.c emulate()): x rounded RNE to bf16 after * 2^64; per 128-wide - * k block, eight HMMA steps of 16 terms each (GB10 fused-sum model, tests/bw_hmma_model.h) from zero, then - * acc = fmaf(block, scale', acc). This differs from the FFMA path's order (not bit-identical to omega_gpu_fp8gemm). - * No row cap beyond device memory; every output word is poisoned and checked. - * int omega_gpu_tcgemm_prepare(uint32_t k); - * Return codes: the OMEGA_GPU_TCGEMM_* values below; an uncertain completion latches the session (CHIP_FAIL). - */ -#include -#include -#include "omega_gpu_fp8_api.h" -#include "omega_blackwell_codegen_tc.h" - -#ifdef __cplusplus -extern "C" { -#endif -enum { OMEGA_GPU_TCGEMM_OK = 0, OMEGA_GPU_TCGEMM_BAD_ARGS = -1, OMEGA_GPU_TCGEMM_TOO_LARGE = -2, OMEGA_GPU_TCGEMM_CODEGEN_FAIL = -3, OMEGA_GPU_TCGEMM_CHIP_FAIL = -4 }; - -typedef struct { - uint32_t rows, segments, tiles, n, k, rt, ct, warps, grid_x, grid_y, gpr_declared; - uint64_t weight_bytes; /* e4m3 bytes of the distinct experts */ - uint64_t streamed_bytes; /* weight bytes the launch reads (tiles * n * k) */ - uint64_t act_bytes; /* activation bytes gathered (tiles * grid_x * 16 rt * k * 2) */ - uint64_t elapsed_ns; /* chip submit-to-second-marker */ - uint64_t call_ns; - uint32_t completion_marker; - bool kernel_cache_hit; -} OmegaGpuTcGemmInfo; - -int omega_gpu_tcgemm_f32(const OmegaGpuFp8Tensor *t, uint32_t M, const uint32_t *expert_ids, const uint32_t *token_rows, - const float *x, uint32_t x_rows, float *y, OmegaGpuTcGemmInfo *info); -int omega_gpu_tcgemm_prepare(uint32_t k); -const char *omega_gpu_tcgemm_rc_name(int rc); -const char *omega_gpu_tcgemm_last_error(void); -void omega_gpu_tcgemm_cache_clear(void); -/* the shape the API uses for width k and output width n */ -void omega_gpu_tcgemm_spec_for(uint32_t k, uint32_t n, OmegaTcGemmSpec *spec); -/* measurement knob: force rt, ct, warps (0 restores); TEST ONLY mutants 1-4 (omega_blackwell_codegen_tc.h) */ -void omega_gpu_tcgemm_set_shape(uint32_t rt, uint32_t ct, uint32_t warps); -void omega_gpu_tcgemm_test_set_mutant(int mutant); -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_tern_api.c b/src/omega_gpu_tern_api.c deleted file mode 100644 index 051865a51..000000000 --- a/src/omega_gpu_tern_api.c +++ /dev/null @@ -1,348 +0,0 @@ -/* omega_gpu_tern_api.c: KT1 W2A8 ternary GEMV on the shared session, ternary engine stage T0 (2026-10-15). See the header. - * Buffer policy: weights GPU-cached by default (written once by the CPU before any GPU read, then only read by the GPU; - * omega_gpu_mem_cached.h). Everything else both sides touch (x, a_scale, scales, y) is GPU-uncached (nvos.h - * NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will not be coherent with direct CPU mappings"). Submission path - * and kernel cache are the bf16 API's. */ -#include "omega_gpu_tern_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_mem_cached.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_cmdlist.h" -#include -#include - -#define CACHE_SLOTS 8 -#define MARKER_TIMEOUT_MS 20000ull -#define DEFAULT_CTAS 160u /* T0 sweep: 160 beat 96 and 256 on the four BitNet shapes (row-major, rows 1) */ -#define DEFAULT_WARPS 8u - -struct OmegaGpuTernTensor { - uint32_t n, k, n_padded, layout, R; - bool cached; - OmegaGpuTernSegments seg; - OmegaGpuMem w, ws; -}; - -typedef struct { - bool valid; - OmegaTernGemvSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - OmegaGpuScratch x_buf, y_buf, as_buf; - uint32_t rows, warps, depth, ctas; /* overrides, 0 = automatic */ - uint32_t layout, block_rows; /* upload layout; block_rows 0 = 4 */ - int uncached; /* 1 = uploads use uncached weights */ - int mutant; - bool hooked; - Slot cache[CACHE_SLOTS]; - unsigned next; -} g = { .layout = OMEGA_TERN_LAYOUT_ROWMAJOR }; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -const char *omega_gpu_tern_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_tern_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_TERN_OK: return "OK"; - case OMEGA_GPU_TERN_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_TERN_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_TERN_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_TERN_CHIP_FAIL: return "CHIP_FAIL"; - case OMEGA_GPU_TERN_BAD_TRIT: return "BAD_TRIT"; - default: return "UNKNOWN"; - } -} - -static void cache_clear_locked(void) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - if (!g.cache[i].valid) continue; - omega_gpu_session_free(&g.cache[i].code); - memset(&g.cache[i], 0, sizeof g.cache[i]); - } - g.next = 0; -} -static void on_session_close(void) { - cache_clear_locked(); - omega_gpu_session_scratch_free(&g.x_buf); - omega_gpu_session_scratch_free(&g.y_buf); - omega_gpu_session_scratch_free(&g.as_buf); -} -static OmegaGpuSession *dev_open_locked(void) { - if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } - return omega_gpu_session_open(); -} -void omega_gpu_tern_cache_clear(void) { omega_gpu_session_lock(); cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_tern_set_layout(uint32_t layout, uint32_t block_rows) { omega_gpu_session_lock(); g.layout = layout; g.block_rows = block_rows; omega_gpu_session_unlock(); } -void omega_gpu_tern_set_shape(uint32_t rows, uint32_t warps, uint32_t depth) { - omega_gpu_session_lock(); g.rows = rows; g.warps = warps; g.depth = depth; cache_clear_locked(); omega_gpu_session_unlock(); -} -void omega_gpu_tern_set_cta_budget(uint32_t ctas) { omega_gpu_session_lock(); g.ctas = ctas; omega_gpu_session_unlock(); } -void omega_gpu_tern_set_weight_cache(int cached) { omega_gpu_session_lock(); g.uncached = !cached; omega_gpu_session_unlock(); } -void omega_gpu_tern_test_set_mutant(int m) { omega_gpu_session_lock(); g.mutant = m; cache_clear_locked(); omega_gpu_session_unlock(); } - -static uint32_t gpr_declared(uint32_t peak) { return omega_bw_gpr_declared(peak); } -static bool register_file_fits(uint32_t warps, uint32_t peak) { - uint32_t decl = gpr_declared(peak); - if ((uint64_t)32u * warps * decl <= 65536u) return true; - char e[160]; omega_gpu_fmt(e, sizeof e, "tern kernel: %u warps x %u declared registers exceed the 65536-register file", warps, decl); - omega_gpu_session_set_error(e); - return false; -} -int omega_gpu_tern_kernel_fits(const OmegaTernGemvSpec *spec, uint32_t *declared) { - uint32_t peak = 0; - if (!spec || omega_tern_gemv_prog_stats(spec, NULL, &peak) != 0) { omega_gpu_session_set_error("tern codegen refused the shape"); return OMEGA_GPU_TERN_CODEGEN_FAIL; } - if (declared) *declared = gpr_declared(peak); - return register_file_fits(spec->warps, peak) ? OMEGA_GPU_TERN_OK : OMEGA_GPU_TERN_TOO_LARGE; -} - -/* Automatic shape. Defaults from the T0 chip sweep (evidence TERN-T0-*). */ -void omega_gpu_tern_shape_for(uint32_t k, uint32_t layout, uint32_t R, uint32_t *rows, uint32_t *warps, uint32_t *depth, uint32_t *ctas) { - uint32_t nch = (k + OMEGA_TERN_CHUNK_MAX - 1u) / OMEGA_TERN_CHUNK_MAX; - uint32_t ksc = nch ? k / nch / 256u : 0; - uint32_t r = layout == OMEGA_TERN_LAYOUT_BLOCK ? R : (g.rows ? g.rows : 1u); - uint32_t d = g.depth ? g.depth : 16u / r; - while (d > 1u && (ksc % d || r * d > 16u)) d--; - if (rows) *rows = r; - if (warps) *warps = g.warps ? g.warps : DEFAULT_WARPS; - if (depth) *depth = d; - if (ctas) *ctas = g.ctas ? g.ctas : DEFAULT_CTAS; -} - -static int kernel_for(const OmegaTernGemvSpec *spec, Slot **out, bool *hit) { - for (unsigned i = 0; i < CACHE_SLOTS; i++) { - Slot *s = &g.cache[i]; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_TERN_OK; } - } - Slot *s = &g.cache[g.next]; - if (g_rec && s->valid) { omega_gpu_session_set_error("tern record: kernel cache miss would evict a resident kernel (warm up before recording)"); return OMEGA_GPU_TERN_TOO_LARGE; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("tern codegen: host memory"); return OMEGA_GPU_TERN_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_tern_gemv_prog(spec, prog); - size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; - if (cg != 0 || need == 0) { omega_gpu_host_free(prog); omega_gpu_session_set_error("tern codegen refused the shape"); return OMEGA_GPU_TERN_CODEGEN_FAIL; } - if (!register_file_fits(spec->warps, prog->regalloc.peak_gpr_usage)) { omega_gpu_host_free(prog); return OMEGA_GPU_TERN_TOO_LARGE; } - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_TERN_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - omega_gpu_host_free(prog); - if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_TERN_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_TERN_CHIP_FAIL; } - if (s->valid) omega_gpu_session_free(&s->code); - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; - g.next = (g.next + 1u) % CACHE_SLOTS; - *out = s; *hit = false; - return OMEGA_GPU_TERN_OK; -} - -uint32_t omega_gpu_tern_padded_rows(uint32_t n) { return (n + OMEGA_TERN_ROW_PAD - 1u) / OMEGA_TERN_ROW_PAD * OMEGA_TERN_ROW_PAD; } - -int omega_gpu_tern_pack(uint32_t n, uint32_t k, const int8_t *w, uint32_t layout, uint32_t R, uint32_t *out, uint32_t n_padded) { - if (!w || !out || n == 0 || k % 16u || n_padded < n || n_padded % (2u * (layout == OMEGA_TERN_LAYOUT_BLOCK ? R : 1u))) return OMEGA_GPU_TERN_BAD_ARGS; - const uint32_t kw = k / 16u; - memset(out, 0, (size_t)n_padded * kw * 4u); - for (uint32_t r = 0; r < n; r++) { - const int8_t *row = w + (size_t)r * k; - for (uint32_t c = 0; c < kw; c++) { - uint32_t word = 0; - for (uint32_t i = 0; i < 16u; i++) { - const int8_t v = row[16u * c + i]; - const uint32_t code = v == 1 ? 1u : v == -1 ? 2u : v == 0 ? 0u : 3u; - if (code == 3u) return OMEGA_GPU_TERN_BAD_TRIT; - word |= code << (2u * i); - } - out[omega_tern_word_offset(layout, R, k, r, c) / 4u] = word; - } - } - return OMEGA_GPU_TERN_OK; -} - -int omega_gpu_tern_segment_bounds(uint32_t n, const OmegaGpuTernSegments *seg, int mutant, uint32_t b[3]) { - const uint32_t cnt = seg ? seg->count : 1u; - if (cnt < 1u || cnt > 4u) return OMEGA_GPU_TERN_BAD_ARGS; - for (uint32_t i = 0; i < 3; i++) { - if (i + 1u >= cnt) b[i] = n; - else if (mutant == 2) b[i] = (i + 1u) * (n / cnt); /* TEST ONLY: ws_idx = r / (n / count) */ - else b[i] = seg->end[i]; - } - return OMEGA_GPU_TERN_OK; -} - -static int seg_ok(uint32_t n, const OmegaGpuTernSegments *seg) { - if (!seg) return 1; - if (seg->count < 1u || seg->count > 4u || seg->end[seg->count - 1u] != n) return 0; - for (uint32_t i = 0; i < seg->count; i++) { - if (!isfinite(seg->scale[i])) return 0; - if (seg->end[i] == 0 || (i && seg->end[i] <= seg->end[i - 1u])) return 0; - } - return 1; -} - -void omega_gpu_tern_tensor_shape(const OmegaGpuTernTensor *t, uint32_t *n, uint32_t *k) { - if (n) *n = t ? t->n : 0; - if (k) *k = t ? t->k : 0; -} -uint64_t omega_gpu_tern_tensor_bytes(const OmegaGpuTernTensor *t) { return t ? (uint64_t)t->n_padded * t->k / 4u : 0; } - -int omega_gpu_tern_tensor_upload(uint32_t n, uint32_t k, const int8_t *w, const OmegaGpuTernSegments *seg, OmegaGpuTernTensor **out) { - if (out) *out = NULL; - if (!w || !out || n == 0 || n > 0x40000000u || k == 0 || k % 256u || !seg_ok(n, seg)) return OMEGA_GPU_TERN_BAD_ARGS; - if (k > OMEGA_TERN_MAX_K || (k > OMEGA_TERN_CHUNK_MAX && k % 512u)) return OMEGA_GPU_TERN_TOO_LARGE; - omega_gpu_session_lock(); - const uint32_t layout = g.layout, R = g.block_rows ? g.block_rows : 4u; const int uncached = g.uncached; - omega_gpu_session_unlock(); - if (layout > OMEGA_TERN_LAYOUT_BLOCK || (layout == OMEGA_TERN_LAYOUT_BLOCK && R != 2u && R != 4u)) return OMEGA_GPU_TERN_BAD_ARGS; - const size_t count = (size_t)n * k; - for (size_t i = 0; i < count; i++) if (w[i] < -1 || w[i] > 1) { - char e[120]; omega_gpu_fmt(e, sizeof e, "tern upload: value %d at element %zu is not a trit", (int)w[i], i); - omega_gpu_session_set_error(e); - return OMEGA_GPU_TERN_BAD_TRIT; - } - OmegaGpuTernTensor *t = omega_gpu_host_calloc(1, sizeof *t); - if (!t) return OMEGA_GPU_TERN_BAD_ARGS; - t->n = n; t->k = k; t->n_padded = omega_gpu_tern_padded_rows(n); t->layout = layout; t->R = R; t->cached = !uncached; - if (seg) t->seg = *seg; else { t->seg.count = 1; t->seg.end[0] = n; t->seg.scale[0] = 1.0f; } - const size_t bytes = (size_t)t->n_padded * k / 4u; - int rc = OMEGA_GPU_TERN_OK; - omega_gpu_session_lock(); - if (!dev_open_locked() || (uncached ? omega_gpu_session_alloc(bytes, &t->w) : omega_gpu_session_alloc_cached(bytes, &t->w)) != 0 - || omega_gpu_session_alloc(16u, &t->ws) != 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_TERN_OK) rc = omega_gpu_tern_pack(n, k, w, layout, R, t->w.cpu, t->n_padded); - if (rc == OMEGA_GPU_TERN_OK) { - float rev[4] = { 0, 0, 0, 0 }; - for (uint32_t i = 0; i < t->seg.count; i++) rev[3u - i] = t->seg.scale[i]; - memcpy(t->ws.cpu, rev, sizeof rev); - if (omega_gpu_session_sync_to_gpu(&t->w) != 0 || omega_gpu_session_sync_to_gpu(&t->ws) != 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; - } - if (rc != OMEGA_GPU_TERN_OK) { omega_gpu_tern_tensor_free(t); return rc; } - *out = t; - return OMEGA_GPU_TERN_OK; -} - -void omega_gpu_tern_tensor_free(OmegaGpuTernTensor *t) { - if (!t) return; - omega_gpu_session_lock(); - if (t->w.cpu) omega_gpu_session_free(&t->w); - if (t->ws.cpu) omega_gpu_session_free(&t->ws); - omega_gpu_session_unlock(); - omega_gpu_host_free(t); -} - -/* rec non-NULL (record path, caller holds the session lock): device buffers dev_x / dev_y / dev_as, the launch is appended - * to rec, nothing staged, poisoned or read back. */ -static int gemv_core(const OmegaGpuTernTensor *t, const int8_t *x, int f32, float a_scale, void *y, OmegaGpuTernInfo *info, - OmegaGpuCmdList *rec, uint64_t dev_x, uint64_t dev_y, uint64_t dev_as) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (rec && (!dev_x || !dev_y || (dev_x & 15u))) return OMEGA_GPU_TERN_BAD_ARGS; - if (!t || !t->w.cpu || (!rec && (!x || !y))) return OMEGA_GPU_TERN_BAD_ARGS; - if (f32 && !rec && !isfinite(a_scale)) return OMEGA_GPU_TERN_BAD_ARGS; - const uint32_t n = t->n, k = t->k; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - OmegaTernGemvSpec spec; uint32_t ctas; - memset(&spec, 0, sizeof spec); - spec.k = k; spec.layout = t->layout; spec.epi = f32 ? OMEGA_TERN_EPI_F32 : OMEGA_TERN_EPI_I32; - omega_gpu_tern_shape_for(k, t->layout, t->R, &spec.rows, &spec.warps, &spec.depth, &ctas); - spec.mutant = g.mutant == 2 ? 0 : g.mutant; - uint32_t bounds[3]; - if (!omega_tern_gemv_spec_ok(&spec) || omega_gpu_tern_segment_bounds(n, &t->seg, g.mutant, bounds) != 0) { - omega_gpu_session_set_error("tern: kernel shape refused for this tensor"); - UNLOCK(); return OMEGA_GPU_TERN_CODEGEN_FAIL; - } - const uint32_t U = t->n_padded / (2u * spec.rows); - if (t->n_padded % (2u * spec.rows)) { UNLOCK(); return OMEGA_GPU_TERN_CODEGEN_FAIL; } - uint32_t grid_x = (U + spec.warps - 1u) / spec.warps; - if (grid_x > ctas) grid_x = ctas; - if (grid_x == 0) grid_x = 1; - - int rc = OMEGA_GPU_TERN_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_TERN_CHIP_FAIL; } - if (!rec) { - int src = omega_gpu_session_scratch(&g.x_buf, (size_t)k); - if (src == 0) src = omega_gpu_session_scratch(&g.y_buf, (size_t)n * 4u); - if (src == 0) src = omega_gpu_session_scratch(&g.as_buf, 16u); - if (src != 0) { UNLOCK(); return src == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_TERN_TOO_LARGE : OMEGA_GPU_TERN_CHIP_FAIL; } - if (g.x_buf.mem.va & 15u) { omega_gpu_session_set_error("tern: x scratch not 16-byte aligned"); UNLOCK(); return OMEGA_GPU_TERN_CHIP_FAIL; } - } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_TERN_OK) { UNLOCK(); return rc; } - - uint32_t *yd = g.y_buf.mem.cpu; - if (!rec) { - memcpy(g.x_buf.mem.cpu, x, k); - memcpy(g.as_buf.mem.cpu, &a_scale, 4); - const uint32_t poison = f32 ? OMEGA_GPU_TERN_POISON_F32_BITS : (uint32_t)OMEGA_GPU_TERN_POISON_I32; - for (size_t i = 0; i < n; i++) yd[i] = poison; - if (omega_gpu_session_sync_to_gpu(&g.x_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.y_buf.mem) != 0 - || omega_gpu_session_sync_to_gpu(&g.as_buf.mem) != 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; - } - - uint32_t args[OMEGA_TERN_ARGS_WORDS]; - memset(args, 0, sizeof args); - const uint64_t x_va = rec ? dev_x : g.x_buf.mem.va, y_va = rec ? dev_y : g.y_buf.mem.va; - const uint64_t as_va = rec ? dev_as : g.as_buf.mem.va, ws_va = t->ws.va; - args[0] = (uint32_t)t->w.va; args[1] = (uint32_t)(t->w.va >> 32); - args[2] = (uint32_t)x_va; args[3] = (uint32_t)(x_va >> 32); - args[4] = (uint32_t)y_va; args[5] = (uint32_t)(y_va >> 32); - args[6] = (uint32_t)ws_va; args[7] = (uint32_t)(ws_va >> 32); - args[8] = (uint32_t)as_va; args[9] = (uint32_t)(as_va >> 32); - args[10] = U; args[11] = grid_x * spec.warps; - args[12] = 0u - n; - for (int i = 0; i < 3; i++) args[13 + i] = 0u - bounds[i]; - if (info) { - info->n = n; info->k = k; info->n_padded = t->n_padded; info->layout = t->layout; info->rows_per_half = spec.rows; - info->warps_per_cta = spec.warps; info->depth = spec.depth; info->grid_x = grid_x; - info->chunks = omega_tern_gemv_chunks(&spec); info->epi = spec.epi; - info->weight_bytes = omega_gpu_tern_tensor_bytes(t); - info->kernel_cache_hit = hit; info->weights_cached = t->cached; - memcpy(info->seg_bounds, bounds, sizeof bounds); - (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); - info->sm_architecture = 121; - } - if (rc == OMEGA_GPU_TERN_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = gpr_declared(ks->kernel.gpr_count), - .threads_x = 32u * spec.warps, .threads_y = 1, .grid_x = grid_x, .grid_y = 1, - .num_elements = n, - .args = args, .n_args = OMEGA_TERN_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = omega_tern_gemv_shared_bytes(&spec), - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_TERN_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_TERN_OK && !rec && omega_gpu_session_sync_to_cpu(&g.y_buf.mem) != 0) rc = OMEGA_GPU_TERN_CHIP_FAIL; - if (rc == OMEGA_GPU_TERN_OK && !rec) { - const uint32_t poison = f32 ? OMEGA_GPU_TERN_POISON_F32_BITS : (uint32_t)OMEGA_GPU_TERN_POISON_I32; - size_t unchanged = 0; - for (size_t i = 0; i < n; i++) if (yd[i] == poison) unchanged++; - if (unchanged) { - char e[120]; omega_gpu_fmt(e, sizeof e, "tern: output poison survived in %zu of %u rows", unchanged, n); - omega_gpu_session_set_error(e); rc = OMEGA_GPU_TERN_CHIP_FAIL; - } else memcpy(y, yd, (size_t)n * 4u); - } - UNLOCK(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} -#undef UNLOCK - -int omega_gpu_tern_gemv_i32(const OmegaGpuTernTensor *t, const int8_t *x, int32_t *y, OmegaGpuTernInfo *info) { - return gemv_core(t, x, 0, 1.0f, y, info, NULL, 0, 0, 0); -} -int omega_gpu_tern_gemv_f32(const OmegaGpuTernTensor *t, const int8_t *x, float a_scale, float *y, OmegaGpuTernInfo *info) { - return gemv_core(t, x, 1, a_scale, y, info, NULL, 0, 0, 0); -} -int omega_gpu_tern_gemv_record(OmegaGpuCmdList *cl, const OmegaGpuTernTensor *t, uint64_t x_va, uint64_t y_va, uint64_t as_va) { - if (!cl) return OMEGA_GPU_TERN_BAD_ARGS; - return gemv_core(t, NULL, as_va != 0, 1.0f, NULL, NULL, cl, x_va, y_va, as_va); -} diff --git a/src/omega_gpu_tern_api.h b/src/omega_gpu_tern_api.h deleted file mode 100644 index 7b845f980..000000000 --- a/src/omega_gpu_tern_api.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef OMEGA_GPU_TERN_API_H -#define OMEGA_GPU_TERN_API_H -/* - * omega_gpu_tern_api: KT1, the native (no CUDA) W2A8 ternary GEMV on the shared session, ternary engine stage T0 - * (2026-10-15). New file; no existing API changes. Kernel: omega_blackwell_codegen_tern.h. - * - * typedef struct OmegaGpuTernTensor OmegaGpuTernTensor; // opaque, device resident - * int omega_gpu_tern_tensor_upload(uint32_t n, uint32_t k, const int8_t *w, const OmegaGpuTernSegments *seg, - * OmegaGpuTernTensor **out); - * w: n * k values in {-1, 0, +1}, row-major [n][k]. Any other value is refused (BAD_TRIT, nothing uploaded). - * Requires n >= 1, k % 256 == 0 (k % 512 above 8192), k <= 16384. Packed to omega's 2-bit trit code - * (src/algebra/oma_trit.h) in the layout set by omega_gpu_tern_set_layout (read at upload), zero rows padding n to a - * multiple of 8. Weights are GPU-cached by default (written once by the CPU, then only read by the GPU; - * omega_gpu_mem_cached.h). seg may be NULL (one segment, scale 1). - * seg: the per-matrix weight scales of a fused projection, one per OUTPUT SEGMENT with explicit row boundaries: - * count 1..4, end[i] the first row after segment i (strictly increasing, end[count - 1] == n), scale[i] finite. - * Example q|k|v: count 3, end {2560, 3200, 3840}. Row r uses scale[i] for the segment i that contains r. - * int omega_gpu_tern_gemv_i32(const OmegaGpuTernTensor *t, const int8_t *x, int32_t *y, OmegaGpuTernInfo *info); - * y[r] = sum_c W[r][c] * x[c], exact int32 (the contract of oma_rz_oracle). x: k int8, y: n int32. One launch. - * int omega_gpu_tern_gemv_f32(const OmegaGpuTernTensor *t, const int8_t *x, float a_scale, float *y, OmegaGpuTernInfo *info); - * y[r] = ((float)y_int[r] * a_scale) * scale[seg(r)], two round-to-nearest f32 multiplies in that order. a_scale finite. - * k <= 8192 only (one x chunk). Not the same rounding as the divide form (float)acc / s_a * w_scale; the T2 host - * reference defines which one the engine uses. - * Return codes: 0 OK; negative OMEGA_GPU_TERN_* below. Every output word is poisoned before the launch and a result that - * still holds poison is refused. An uncertain completion latches the process (the session's rule). - */ -#include -#include -#include -#include "omega_blackwell_codegen_tern.h" - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_GPU_TERN_OK = 0, - OMEGA_GPU_TERN_BAD_ARGS = -1, - OMEGA_GPU_TERN_TOO_LARGE = -2, - OMEGA_GPU_TERN_CODEGEN_FAIL = -3, - OMEGA_GPU_TERN_CHIP_FAIL = -4, - OMEGA_GPU_TERN_BAD_TRIT = -5 -}; - -#define OMEGA_GPU_TERN_POISON_I32 0x7f7f7f7f /* |y| <= 128 * 16384 < 2^22: never a result */ -#define OMEGA_GPU_TERN_POISON_F32_BITS 0x7fc0deadu - -typedef struct { - uint32_t count; - uint32_t end[4]; - float scale[4]; -} OmegaGpuTernSegments; - -typedef struct { - uint32_t n, k, n_padded, layout, rows_per_half, warps_per_cta, depth, grid_x, chunks, epi; - uint64_t weight_bytes; /* packed trit bytes the launch reads (n_padded * k / 4) */ - uint64_t elapsed_ns; /* chip submit-to-second-marker */ - uint64_t call_ns; /* whole API call */ - uint32_t completion_marker; - bool kernel_cache_hit, weights_cached; - uint32_t seg_bounds[3]; /* the row boundaries the launch used */ - char target_chip[64]; - uint32_t sm_architecture; -} OmegaGpuTernInfo; - -typedef struct OmegaGpuTernTensor OmegaGpuTernTensor; - -int omega_gpu_tern_tensor_upload(uint32_t n, uint32_t k, const int8_t *w, const OmegaGpuTernSegments *seg, OmegaGpuTernTensor **out); -void omega_gpu_tern_tensor_free(OmegaGpuTernTensor *t); -void omega_gpu_tern_tensor_shape(const OmegaGpuTernTensor *t, uint32_t *n, uint32_t *k); -uint64_t omega_gpu_tern_tensor_bytes(const OmegaGpuTernTensor *t); /* packed bytes on the device */ -int omega_gpu_tern_gemv_i32(const OmegaGpuTernTensor *t, const int8_t *x, int32_t *y, OmegaGpuTernInfo *info); -int omega_gpu_tern_gemv_f32(const OmegaGpuTernTensor *t, const int8_t *x, float a_scale, float *y, OmegaGpuTernInfo *info); -/* Record path (omega_gpu_cmdlist.h): the same launch appended to cl. x_va: k int8 on the device (16-byte aligned); - * y_va: n words; as_va: the f32 a_scale word for the f32 epilogue, 0 for int32 output. The caller holds - * omega_gpu_session_lock(). Nothing staged, poisoned or read back. A kernel cache miss that would evict is refused - * (TOO_LARGE): warm the shape up with one non-record call first. */ -struct OmegaGpuCmdList; -int omega_gpu_tern_gemv_record(struct OmegaGpuCmdList *cl, const OmegaGpuTernTensor *t, uint64_t x_va, uint64_t y_va, uint64_t as_va); -const char *omega_gpu_tern_rc_name(int rc); -const char *omega_gpu_tern_last_error(void); -void omega_gpu_tern_cache_clear(void); - -/* Trit packing and segment boundaries as the device sees them (tests and the host emulation use the same code). */ -int omega_gpu_tern_pack(uint32_t n, uint32_t k, const int8_t *w, uint32_t layout, uint32_t R, uint32_t *out_words, uint32_t n_padded); -uint32_t omega_gpu_tern_padded_rows(uint32_t n); -int omega_gpu_tern_segment_bounds(uint32_t n, const OmegaGpuTernSegments *seg, int mutant, uint32_t bounds[3]); - -/* Register-file check (32 * warps * declared registers <= 65536). */ -int omega_gpu_tern_kernel_fits(const OmegaTernGemvSpec *spec, uint32_t *declared); -/* The kernel shape the API picks for (k, layout, R): rows, warps, depth, CTAs. */ -void omega_gpu_tern_shape_for(uint32_t k, uint32_t layout, uint32_t R, uint32_t *rows, uint32_t *warps, uint32_t *depth, uint32_t *ctas); - -/* ---- measurement knobs (tests; 0 restores the automatic choice) ---- */ -void omega_gpu_tern_set_layout(uint32_t layout, uint32_t block_rows); /* read by later uploads; default row-major (rows 1, 160 CTAs: T0 sweep) */ -void omega_gpu_tern_set_shape(uint32_t rows, uint32_t warps, uint32_t depth); /* clears the kernel cache */ -void omega_gpu_tern_set_cta_budget(uint32_t ctas); -void omega_gpu_tern_set_weight_cache(int cached); /* 1 GPU-cached (default), 0 uncached; read by later uploads */ -/* TEST ONLY: 1 flipped planes, 3 dropped pair (kernel mutants); 2 maps segments as r / (n / count) (the API). */ -void omega_gpu_tern_test_set_mutant(int mutant); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_wait.c b/src/omega_gpu_wait.c deleted file mode 100644 index 8a4342586..000000000 --- a/src/omega_gpu_wait.c +++ /dev/null @@ -1,155 +0,0 @@ -#include "omega_gpu_wait.h" - -#include - -#ifndef OMEGA_GPU_NO_POSIX -#include -static uint64_t real_now_ns(void *ctx) { - (void)ctx; - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; -} -#define DEFAULT_NOW_NS real_now_ns -#else -/* P07 cut C: the freestanding build has no clock of its own; the caller passes the platform clock - * (cfg->now_ns, e.g. OmegaGpuPlatform.time_now_ns) and a wait without one is refused (INVALID_STATE). */ -#define DEFAULT_NOW_NS NULL -#endif - -static void real_barrier(void *ctx) { - (void)ctx; -#if defined(__aarch64__) - __asm__ volatile("dsb sy" ::: "memory"); -#else - __atomic_thread_fence(__ATOMIC_SEQ_CST); -#endif -} - -static void real_relax(void *ctx) { - (void)ctx; -#if defined(__aarch64__) - __asm__ volatile("yield"); -#else - __asm__ volatile("" ::: "memory"); -#endif -} - -const char *omega_gpu_wait_result_name(omega_gpu_wait_result_t r) { - switch (r) { - case OMEGA_GPU_WAIT_PASS: return "PASS"; - case OMEGA_GPU_WAIT_TIMEOUT: return "TIMEOUT"; - case OMEGA_GPU_WAIT_STALLED: return "STALLED"; - case OMEGA_GPU_WAIT_INVALID_STATE: return "INVALID_STATE"; - case OMEGA_GPU_WAIT_ABORTED: return "ABORTED"; - default: return "UNKNOWN"; - } -} - -const char *omega_gpu_wait_kind_name(omega_gpu_wait_kind_t k) { - return k == OMEGA_GPU_WAIT_FIXED ? "fixed" : k == OMEGA_GPU_WAIT_SEQUENCE ? "sequence" : "unknown"; -} - -static bool wait_core(omega_gpu_wait_kind_t kind, volatile uint32_t *word, uint32_t expected, - omega_gpu_wait_report_t *rpt, const omega_gpu_wait_cfg_t *cfg) { - omega_gpu_wait_report_t local; - omega_gpu_wait_cfg_t zero; - if (!rpt) rpt = &local; - memset(rpt, 0, sizeof(*rpt)); - rpt->wait_kind = kind; - rpt->expected = expected; - if (!cfg) { - memset(&zero, 0, sizeof(zero)); - cfg = &zero; - } - - uint64_t (*now_ns)(void *) = cfg->now_ns ? cfg->now_ns : DEFAULT_NOW_NS; - if (!now_ns) { - rpt->result = OMEGA_GPU_WAIT_INVALID_STATE; /* no clock: a bounded wait cannot be bounded */ - return false; - } - void (*barrier)(void *) = cfg->barrier ? cfg->barrier : real_barrier; - void (*relax)(void *) = cfg->relax ? cfg->relax : real_relax; - uint64_t total_ns = 1000000ull * (cfg->total_timeout_ms ? cfg->total_timeout_ms : OMEGA_GPU_WAIT_DEFAULT_TOTAL_MS); - uint64_t stall_ns = 1000000ull * (cfg->progress_timeout_ms ? cfg->progress_timeout_ms : OMEGA_GPU_WAIT_DEFAULT_PROGRESS_MS); - - uint64_t start = now_ns(cfg->hook_ctx); - uint64_t hard_deadline = start + total_ns; - uint64_t stall_deadline = start + stall_ns; - rpt->start_ns = start; - rpt->last_progress_ns = start; - uint64_t now = start; - bool first = true; - - /* A null word is a caller bug; report it as an invalid state, not a hang. */ - if (!word) { - rpt->result = OMEGA_GPU_WAIT_INVALID_STATE; - return false; - } - - while (now < hard_deadline) { - uint32_t m, m2 = 0, snap[2] = {0, 0}; - if (cfg->abort && cfg->abort(cfg->hook_ctx)) { - rpt->result = OMEGA_GPU_WAIT_ABORTED; - rpt->elapsed_ns = now - start; - return false; - } -#ifndef OMEGA_GPU_WAIT_MUTANT_NO_READ_BARRIER - barrier(cfg->hook_ctx); -#endif - m = *word; - if (cfg->marker2) m2 = *cfg->marker2; - if (cfg->snapshot) cfg->snapshot(cfg->snapshot_ctx, snap); - rpt->polls++; - now = now_ns(cfg->hook_ctx); - - bool changed = m != rpt->last_observed || m2 != rpt->last_marker2 || - snap[0] != rpt->snap[0] || snap[1] != rpt->snap[1]; - rpt->last_observed = m; - rpt->last_marker2 = m2; - rpt->snap[0] = snap[0]; - rpt->snap[1] = snap[1]; - rpt->elapsed_ns = now - start; - - if (changed && !first) { - rpt->progress_count++; - rpt->last_progress_ns = now; -#ifndef OMEGA_GPU_WAIT_MUTANT_STALL_NO_RESET - stall_deadline = now + stall_ns; -#endif -#ifdef OMEGA_GPU_WAIT_MUTANT_PROGRESS_EXTENDS_HARD - hard_deadline = now + total_ns; -#endif - } - bool ok = kind == OMEGA_GPU_WAIT_FIXED ? (m == expected) : ((int32_t)(m - expected) >= 0); - if (ok && (!cfg->marker2 || m2 == cfg->marker2_want)) { - barrier(cfg->hook_ctx); /* acquire: later CPU loads are ordered after the marker load */ - rpt->result = OMEGA_GPU_WAIT_PASS; - return true; - } - if (cfg->valid && !cfg->valid(cfg->hook_ctx, m)) { - rpt->result = OMEGA_GPU_WAIT_INVALID_STATE; - return false; - } - first = false; - if (now >= stall_deadline) { - rpt->result = OMEGA_GPU_WAIT_STALLED; - return false; - } - relax(cfg->hook_ctx); - now = now_ns(cfg->hook_ctx); - } - rpt->elapsed_ns = now - start; - rpt->result = OMEGA_GPU_WAIT_TIMEOUT; - return false; -} - -bool omega_gpu_wait_fixed(volatile uint32_t *word, uint32_t expected, - omega_gpu_wait_report_t *rpt, const omega_gpu_wait_cfg_t *cfg) { - return wait_core(OMEGA_GPU_WAIT_FIXED, word, expected, rpt, cfg); -} - -bool omega_gpu_wait_sequence(volatile uint32_t *word, uint32_t target, - omega_gpu_wait_report_t *rpt, const omega_gpu_wait_cfg_t *cfg) { - return wait_core(OMEGA_GPU_WAIT_SEQUENCE, word, target, rpt, cfg); -} diff --git a/src/omega_gpu_wait.h b/src/omega_gpu_wait.h deleted file mode 100644 index 27e2c3613..000000000 --- a/src/omega_gpu_wait.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef OMEGA_GPU_WAIT_H -#define OMEGA_GPU_WAIT_H - -/* Shared completion wait for words the GPU writes to host-visible memory. - * - * Pure C, no NVRM dependency, so the host unit test can drive it with fake - * memory and a fake clock. - * - * Two wait kinds, never one ambiguous wait: - * omega_gpu_wait_fixed the word must equal `expected` exactly. A value - * that overshoots is NOT success. - * omega_gpu_wait_sequence the word is a free-running u32 counter (for - * example dispatch ids). Success when it has reached - * or passed `target` in serial-number order, i.e. - * (int32_t)(observed - target) >= 0, so it is - * correct across the 0xffffffff -> 0 wrap. Valid - * while the counter is less than 2^31 ahead. - * - * Two bounds, both on CLOCK_MONOTONIC in nanoseconds: - * total_timeout_ms hard deadline from the start; never extended. A device - * that advances occasionally still hits it (TIMEOUT). - * progress_timeout_ms stall deadline; restarts only when a watched word - * (word, marker2, snapshot words) changes (STALLED). - * - * Memory visibility: a barrier (dsb sy on AArch64, a full fence elsewhere) runs - * before every read of the watched words and once more, after the success - * observation, before returning PASS. After PASS, the CPU loads issued by the - * caller are ordered after the marker load. That is ordering only. It does not - * make a cached CPU mapping coherent with GPU writes and it does not flush the - * GPU L2: the marker page must still be GPU-uncached and the producing work must - * flush (the omega_numeric_*_gb10.c pattern). The timer does not fix visibility. - * - * If cfg->marker2 is set, PASS also requires *marker2 == marker2_want (read - * output only after both). */ - -#include -#include - -typedef enum { - OMEGA_GPU_WAIT_FIXED = 1, - OMEGA_GPU_WAIT_SEQUENCE = 2 -} omega_gpu_wait_kind_t; - -typedef enum { - OMEGA_GPU_WAIT_PASS = 0, - OMEGA_GPU_WAIT_TIMEOUT = 1, /* hard total deadline */ - OMEGA_GPU_WAIT_STALLED = 2, /* no progress for progress_timeout_ms */ - OMEGA_GPU_WAIT_INVALID_STATE = 3, /* cfg->valid rejected an observed value */ - OMEGA_GPU_WAIT_ABORTED = 4 /* cfg->abort asked to stop */ -} omega_gpu_wait_result_t; - -typedef struct { - omega_gpu_wait_kind_t wait_kind; - omega_gpu_wait_result_t result; - uint32_t expected; /* fixed value or sequence target */ - uint32_t last_observed; /* last value read from the watched word */ - uint32_t last_marker2; /* last value read from marker2 (0 when unused) */ - uint32_t snap[2]; /* last values from the snapshot callback */ - uint64_t start_ns; - uint64_t elapsed_ns; - uint64_t last_progress_ns; /* time of the last observed change (start if none) */ - uint64_t progress_count; /* observed changes after the first read */ - uint64_t polls; -} omega_gpu_wait_report_t; - -typedef struct { - uint32_t total_timeout_ms; /* 0 means the default, 600000 */ - uint32_t progress_timeout_ms; /* 0 means the default, 5000 */ - volatile uint32_t *marker2; - uint32_t marker2_want; - /* Optional: fill two extra words that count as progress when they change - * (for example GP_PUT and a semaphore). Called once per poll. */ - void (*snapshot)(void *ctx, uint32_t out[2]); - void *snapshot_ctx; - /* Optional: return false to declare the observed word out of order. */ - bool (*valid)(void *ctx, uint32_t observed); - /* Optional: return true to stop the wait (ABORTED). */ - bool (*abort)(void *ctx); - /* Test hooks. NULL means the real ones (CLOCK_MONOTONIC, dsb, yield). - * hook_ctx is passed to now_ns, barrier, relax, valid and abort. The freestanding build (OMEGA_GPU_NO_POSIX) - * has no default clock: now_ns is required there (the platform clock) and a wait without it is INVALID_STATE. */ - uint64_t (*now_ns)(void *ctx); - void (*barrier)(void *ctx); - void (*relax)(void *ctx); - void *hook_ctx; -} omega_gpu_wait_cfg_t; - -#define OMEGA_GPU_WAIT_DEFAULT_TOTAL_MS 600000u -#define OMEGA_GPU_WAIT_DEFAULT_PROGRESS_MS 5000u - -/* Both return true on PASS. rpt and cfg may be NULL (cfg NULL means defaults). */ -bool omega_gpu_wait_fixed(volatile uint32_t *word, uint32_t expected, - omega_gpu_wait_report_t *rpt, const omega_gpu_wait_cfg_t *cfg); -bool omega_gpu_wait_sequence(volatile uint32_t *word, uint32_t target, - omega_gpu_wait_report_t *rpt, const omega_gpu_wait_cfg_t *cfg); - -const char *omega_gpu_wait_result_name(omega_gpu_wait_result_t r); -const char *omega_gpu_wait_kind_name(omega_gpu_wait_kind_t k); - -#endif diff --git a/tests/bw_hmma_model.h b/tests/bw_hmma_model.h deleted file mode 100644 index 198c2ba90..000000000 --- a/tests/bw_hmma_model.h +++ /dev/null @@ -1,57 +0,0 @@ -/* bw_hmma_model.h (OWN-30B T3, 2026-10-13): parametrised C model of one HMMA.16816.F32.BF16 dot product - * d = c + sum_{k<16} a_k * b_k (a_k, b_k bf16 values given as f32; products are exact in double) - * The vendor documents no rounding behaviour for mma (DOCS SILENT, Context7 PTX ISA). Published measurements of earlier - * tensor cores (Fasi, Higham, Mikaitis, Pranesh 2021) describe: exact products, alignment of a group of terms to the - * largest exponent with the shifted-out bits truncated, exact addition, and a truncating normalisation. This header - * implements that family so the chip probe (tests/gpu_tc_probe_test.c) can find the member the GB10 matches bit for bit: - * group G in {1, 2, 4, 8, 16}: the 16 products are consumed in 16/G groups, k order; each group is added to the - * running accumulator in one fused step - * extra alignment keeps 24 + extra significant bits below the group's largest exponent (terms truncated toward 0) - * rn 0: the fused sum is converted to f32 by truncation (RZ), 1: round to nearest even - * Zero, subnormal and huge inputs: products and sums in double; the probe keeps exponents in a range where double is exact. - * HM_FMA (group 0) is the plain sequential fmaf chain, for comparison. */ -#ifndef BW_HMMA_MODEL_H -#define BW_HMMA_MODEL_H -#include -#include -#include - -typedef struct { int group, extra, rn, nominal, csep; } HmmaModel; -/* nominal 1: a product's alignment exponent is exp(a) + exp(b) + 1 (its significand taken as [1, 4)), not its true exponent. - * csep 1: the group's products are aligned and summed among themselves first; the accumulator is then added exactly and the - * total converted once (rn). */ - -static float hm_to_f32(double v, int rn) { - if (rn) return (float)v; /* the C conversion is round to nearest even */ - float f = (float)v; - if ((double)f != v && fabs((double)f) > fabs(v)) f = nextafterf(f, 0.0f); /* round toward zero */ - return f; -} -/* truncate v toward zero to a multiple of 2^qexp */ -static double hm_trunc_to(double v, int qexp) { - double q = ldexp(1.0, qexp); - return trunc(v / q) * q; -} -static float hm_dot16(const HmmaModel *m, const float *a, const float *b, float c) { - if (m->group == 0) { float acc = c; for (int k = 0; k < 16; k++) acc = fmaf(a[k], b[k], acc); return acc; } - float acc = c; - for (int k0 = 0; k0 < 16; k0 += m->group) { - double t[17]; int ne[17]; int n = 0; - if (!m->csep) { t[n] = (double)acc; { int e; frexp(t[n], &e); ne[n] = e; } n++; } - for (int k = k0; k < k0 + m->group; k++) { - t[n] = (double)a[k] * (double)b[k]; - int e; frexp(t[n], &e); - if (m->nominal && t[n] != 0.0) { int ea, eb; frexp(a[k], &ea); frexp(b[k], &eb); e = ea + eb - (m->nominal == 2); } /* |a| < 2^ea, |b| < 2^eb; mode 2: exponent of the product of the leading bits, frexp convention */ - ne[n] = e; n++; - } - int emax = -100000; - for (int i = 0; i < n; i++) if (t[i] != 0.0 && ne[i] > emax) emax = ne[i]; - if (emax == -100000) { if (!m->csep) acc = 0.0f * acc; continue; } - double s = 0.0; - for (int i = 0; i < n; i++) s += hm_trunc_to(t[i], emax - 24 - m->extra); - if (m->csep) s += (double)acc; - acc = hm_to_f32(s, m->rn); - } - return acc; -} -#endif diff --git a/tests/bw_qmma_model.h b/tests/bw_qmma_model.h deleted file mode 100644 index 7ae6479d9..000000000 --- a/tests/bw_qmma_model.h +++ /dev/null @@ -1,66 +0,0 @@ -/* bw_qmma_model.h (OWN-30B L1 GEMM, W-L1G, 2026-10-14): parametrised C model of one QMMA.16832.F32.E4M3.E4M3 dot product - * d = c + sum_{k<32} a_k * b_k (a_k, b_k e4m3 values given as f32; products exact in double) - * Same family as tests/bw_hmma_model.h (chip-exact for HMMA: evidence bf9b0378) widened for FP8: the vendor documents no - * rounding behaviour (DOCS SILENT), and FP8 tensor cores of earlier chips are reported to keep fewer accumulator bits than - * f32 (UNVERIFIED for GB10), so `keep` spans 10 .. 32 significant bits below the group's largest exponent. - * group G in {1, 2, 4, 8, 16, 32}: products consumed in 32/G groups, k order, each added to the accumulator in one step - * keep bits kept below the group's largest exponent (terms truncated toward 0) - * rn 0: the fused sum converts to f32 by truncation, 1: round to nearest even - * nominal 1: a product's alignment exponent is exp(a) + exp(b) (frexp), 2: that minus 1 - * csep 1: products aligned among themselves, the accumulator added exactly, one conversion */ -#ifndef BW_QMMA_MODEL_H -#define BW_QMMA_MODEL_H -#include -#include -#include - -typedef struct { int group, keep, rn, nominal, csep; } QmmaModel; - -static float qm_to_f32(double v, int rn) { - if (rn) return (float)v; - float f = (float)v; - if ((double)f != v && fabs((double)f) > fabs(v)) f = nextafterf(f, 0.0f); - return f; -} -static double qm_trunc_to(double v, int qexp) { double q = ldexp(1.0, qexp); return trunc(v / q) * q; } -static float qm_dot32(const QmmaModel *m, const float *a, const float *b, float c) { - if (m->group == 0) { float acc = c; for (int k = 0; k < 32; k++) acc = fmaf(a[k], b[k], acc); return acc; } - float acc = c; - for (int k0 = 0; k0 < 32; k0 += m->group) { - double t[33]; int ne[33]; int n = 0; - if (!m->csep) { t[n] = (double)acc; { int e; frexp(t[n], &e); ne[n] = e; } n++; } - for (int k = k0; k < k0 + m->group; k++) { - t[n] = (double)a[k] * (double)b[k]; - int e; frexp(t[n], &e); - if (m->nominal && t[n] != 0.0) { int ea, eb; frexp(a[k], &ea); frexp(b[k], &eb); e = ea + eb - (m->nominal == 2); } - ne[n] = e; n++; - } - int emax = -100000; - for (int i = 0; i < n; i++) if (t[i] != 0.0 && ne[i] > emax) emax = ne[i]; - if (emax == -100000) { if (!m->csep) acc = 0.0f * acc; continue; } - double s = 0.0; - for (int i = 0; i < n; i++) s += qm_trunc_to(t[i], emax - m->keep); - if (m->csep) s += (double)acc; - acc = qm_to_f32(s, m->rn); - } - return acc; -} - -/* e4m3 (OCP FP8, bias 7, no infinities, 0x7f / 0xff NaN) */ -static float qm_e4m3(uint8_t c) { - int s = c >> 7, e = (c >> 3) & 15, mm = c & 7; - float v = e ? ldexpf(1.0f + (float)mm / 8.0f, e - 7) : ldexpf((float)mm / 8.0f, -6); - return s ? -v : v; -} -/* f32 -> e4m3, round to nearest even, saturate to +-448 (PTX cvt.rn.satfinite; NaN handled by the caller) */ -static uint8_t qm_e4m3_rne_sat(float f) { - uint8_t s = signbit(f) ? 0x80 : 0; double a = fabs((double)f); - if (isinf(f) || a > 448.0) return s | 0x7e; - if (a < ldexp(1.0, -6)) return s | (uint8_t)rint(a * 512.0); - int e; double m = frexp(a, &e); m *= 2.0; e -= 1; /* a = m * 2^e, m in [1, 2) */ - double mm = rint((m - 1.0) * 8.0); - if (mm >= 8.0) { mm = 0.0; e++; } - if (e + 7 > 15 || (((e + 7) << 3) | (int)mm) > 0x7e) return s | 0x7e; - return s | (uint8_t)(((e + 7) << 3) | (int)mm); -} -#endif diff --git a/tests/bw_warp_sim.h b/tests/bw_warp_sim.h deleted file mode 100644 index 3e98e8545..000000000 --- a/tests/bw_warp_sim.h +++ /dev/null @@ -1,318 +0,0 @@ -/* bw_warp_sim.h: host SIMT simulator for the Blackwell IR (omega #308). - * - * Models what the earlier per-thread simulators could not: a warp of 32 lanes with an - * active mask, divergence at predicated branches, structured reconvergence through the - * barrier registers (BSSY arms Bn for the lanes executing it and names the join; BSYNC - * parks arriving lanes until every armed lane that has not exited is there, then the - * warp continues as one), nested regions, and lane participation in SHFL and BAR.SYNC. - * - * A warp is a set of fragments (pc, lane mask). A predicated branch whose lanes disagree - * splits the fragment; the scheduler then runs one fragment at a time in a chosen order - * (lowest pc first or highest pc first; tests run both), which is the freedom the chip's - * scheduler also has. Fragments only merge at a BSYNC. Errors (all fatal, first one wins): - * WS_E_SHFL_SPLIT a SHFL reached by a fragment that is not the whole live warp - * (the chip reads inactive lanes: undefined; attention 2026-10-04) - * WS_E_SHFL_EXITED a SHFL on a warp some of whose lanes already exited (undefined too) - * WS_E_BAR_SPLIT (defined, never raised) a BAR.SYNC reached by a split warp is allowed: - * since Volta the CTA barrier counts arriving threads, not warps (CUDA - * programming guide, independent thread scheduling; INFERRED for sm_121, - * not chip-verified by us). The simulator parks each fragment, releases - * them together, counts the event in bar_split_arrivals, and leaves the - * fragments split: a barrier is not a reconvergence point, so a SHFL after - * it still fails with SHFL_SPLIT unless a BSYNC rejoined the warp. - * WS_E_BSYNC_UNARMED BSYNC on a barrier no BSSY armed - * WS_E_BSSY_REARM BSSY on a barrier still armed (lanes may still be heading to its join) - * WS_E_JOIN_MISMATCH BSYNC at an address other than the one the BSSY named minus one - * WS_E_NONMEMBER a lane reached BSYNC Bn without having executed its BSSY - * WS_E_STUCK lanes parked at a BSYNC that can never complete (a join was dropped, - * an exit jumped past it, or a target was corrupted) - * WS_E_NEVER_JOINED the warp finished with a barrier still armed - * WS_E_SELF_BRANCH, WS_E_PC, WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS - * Every error names the pc. Memory: global addresses are host pointers (optionally range - * checked); shared memory is a per-CTA buffer poisoned at CTA start so a read of a word - * nobody wrote shows up in the oracle comparison. - * - * Per-lane ALU semantics are those of the two earlier simulators (tests/gpu_attention_test.c, - * bench/prime_race/tests/gb10_sieve_host_test.c). EX2 and RCP are exact here; the chip's - * are approximate. LDCU64 (memory descriptor) is not modelled. */ -#ifndef BW_WARP_SIM_H -#define BW_WARP_SIM_H - -#include "omega_blackwell_codegen.h" -#include -#include -#include -#include -#include - -#define WS_WARP 32 -#define WS_MAX_THREADS 256 -#define WS_MAX_WARPS (WS_MAX_THREADS / WS_WARP) -#define WS_MAX_FRAGS 64 -#define WS_NBAR BW_RECONV_MAX_BAR -#define WS_MAX_RANGES 8 - -enum { - WS_OK = 0, WS_E_SHFL_SPLIT, WS_E_SHFL_EXITED, WS_E_BAR_SPLIT, WS_E_BSYNC_UNARMED, WS_E_BSSY_REARM, - WS_E_JOIN_MISMATCH, WS_E_NONMEMBER, WS_E_STUCK, WS_E_NEVER_JOINED, WS_E_SELF_BRANCH, WS_E_PC, - WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS, WS_E_BAR_TIMEOUT, WS_E_STEPS -}; -static const char *ws_err_name(int e) { - static const char *const n[] = { "OK", "SHFL_SPLIT", "SHFL_EXITED", "BAR_SPLIT", "BSYNC_UNARMED", "BSSY_REARM", - "JOIN_MISMATCH", "NONMEMBER", "STUCK", "NEVER_JOINED", "SELF_BRANCH", "PC", "OP", "SHIFT", "MEM", "SMEM", - "FRAGS", "BAR_TIMEOUT", "STEPS" }; - return (e >= 0 && e < (int)(sizeof n / sizeof n[0])) ? n[e] : "?"; -} - -typedef struct { uint32_t r[256]; uint8_t p0; } WsLane; -typedef struct { int pc; uint32_t mask; int parked; /* waiting at a BAR.SYNC */ } WsFrag; -typedef struct { int valid; int target; uint32_t members, arrived; } WsBar; -typedef struct { - WsLane lane[WS_WARP]; - WsFrag frag[WS_MAX_FRAGS]; - int nfrag; - WsBar bar[WS_NBAR]; - uint32_t exited; -} WsWarp; -typedef struct { uintptr_t lo, hi; } WsRange; - -typedef struct { - const BlackwellIRProgram *p; - uint32_t cbank[256]; /* constant bank 0 words (byte offset / 4) */ - uint32_t threads; /* per CTA, a multiple of 32, <= WS_MAX_THREADS */ - uint8_t *smem; /* per-CTA shared memory buffer (poisoned at CTA start) */ - uint32_t smem_bytes; - WsRange ranges[WS_MAX_RANGES]; int nranges; /* when > 0, every global access must fall in one */ - int order; /* 0 = lowest pc first, 1 = highest pc first */ - int trace; /* print every issue of warp 0 of CTA (0,0) */ - /* results */ - int err; int err_pc; char msg[200]; - uint64_t warp_issues; /* fragment-instruction issues (the chip's cost unit for divergence) */ - uint64_t lane_issues; /* lanes active over those issues */ - uint64_t splits; /* branches that split a fragment */ - uint64_t bar_split_arrivals; /* BAR.SYNC reached by a fragment that is not the whole live warp */ - int max_frags, peak_bars; -} WsSim; - -static void ws_fail(WsSim *s, int err, int pc, const char *what) { - if (s->err) return; - s->err = err; s->err_pc = pc; - snprintf(s->msg, sizeof s->msg, "%s at pc %d: %s", ws_err_name(err), pc, what ? what : ""); -} - -static uint32_t ws_rd(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[ph & 0xff]; } -static uint64_t ws_rd64(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)l->r[ph] | ((uint64_t)l->r[(ph + 1) & 0xff] << 32); } -static void ws_wr(WsLane *l, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[ph & 0xff] = x; } -static void ws_wr64(WsLane *l, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; l->r[ph] = (uint32_t)x; l->r[(ph + 1) & 0xff] = (uint32_t)(x >> 32); } -/* sub-register operands (quad/pair lanes, BlackwellIRInsn.*_subreg) */ -static uint32_t ws_rds(const WsLane *l, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[(ph + sub) & 0xff]; } -static void ws_wrs(WsLane *l, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[(ph + sub) & 0xff] = x; } -static float ws_u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t ws_f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint32_t ws_lut3(uint32_t lut, uint32_t a, uint32_t b, uint32_t c) { - uint32_t r = 0; - for (int i = 0; i < 8; i++) if (lut >> i & 1) r |= ((i & 4) ? a : ~a) & ((i & 2) ? b : ~b) & ((i & 1) ? c : ~c); - return r; -} -static int ws_mem_ok(WsSim *s, uint64_t a, unsigned bytes, int pc) { - if (s->nranges == 0) return 1; - for (int i = 0; i < s->nranges; i++) if (a >= s->ranges[i].lo && a + bytes <= s->ranges[i].hi) return 1; - ws_fail(s, WS_E_MEM, pc, "global access outside the declared buffers"); return 0; -} -static uint32_t *ws_smem(WsSim *s, uint32_t a, int pc) { - if ((a & 3) || a + 4 > s->smem_bytes) { ws_fail(s, WS_E_SMEM, pc, "shared access past the declared size"); return NULL; } - return (uint32_t *)(s->smem + a); -} -static int ws_popc(uint32_t m) { return __builtin_popcount(m); } - -/* One lane, one non-control instruction. */ -static void ws_lane_exec(WsSim *s, WsLane *l, const BlackwellIRInsn *in, int pc, uint32_t tid, uint32_t cx, uint32_t cy) { - const BlackwellIRProgram *p = s->p; - uint32_t a = ws_rds(l, in->src1_vreg, in->src1_subreg, p), b = ws_rds(l, in->src2_vreg, in->src2_subreg, p), c = ws_rds(l, in->src3_vreg, in->src3_subreg, p); - switch (in->op) { - case BW_IR_NOP: break; - case BW_IR_S2R: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; - case BW_IR_LDC: ws_wrs(l, in->dst_vreg, in->dst_subreg, s->cbank[(in->imm / 4) & 0xff], p); break; - case BW_IR_LDC64: ws_wr64(l, in->dst_vreg, (uint64_t)s->cbank[(in->imm / 4) & 0xff] | ((uint64_t)s->cbank[(in->imm / 4 + 1) & 0xff] << 32), p); break; - case BW_IR_LDCU64: case BW_IR_LDCU: break; /* memory descriptor: not modelled */ - case BW_IR_MOV_IMM: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm, p); break; - case BW_IR_MOV_RZ: ws_wrs(l, in->dst_vreg, in->dst_subreg, 0, p); break; - case BW_IR_IMAD: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; - case BW_IR_IMAD_WIDE: ws_wr64(l, in->dst_vreg, (uint64_t)a * in->imm + ws_rd64(l, in->src3_vreg, p), p); break; - case BW_IR_IMAD_HI_U32: ws_wrs(l, in->dst_vreg, in->dst_subreg, (uint32_t)(((uint64_t)a * b) >> 32) + c, p); break; - case BW_IR_IADD3: ws_wrs(l, in->dst_vreg, in->dst_subreg, a + b, p); break; /* the encoder's IADD3 has Rc = RZ */ - case BW_IR_SHF_R: ws_wrs(l, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; - case BW_IR_SHF_L_U32: if (b >= 32) { ws_fail(s, WS_E_SHIFT, pc, "SHF.L.U32 amount >= 32 (not chip-verified)"); return; } ws_wrs(l, in->dst_vreg, in->dst_subreg, a << b, p); break; - case BW_IR_LOP3_AND: ws_wrs(l, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; - case BW_IR_LOP3_XOR: ws_wrs(l, in->dst_vreg, in->dst_subreg, a ^ b, p); break; - case BW_IR_LOP3_LUT: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_lut3(in->imm & 0xff, a, b, c), p); break; - case BW_IR_ISETP_GE_U32: l->p0 = a >= b; break; - case BW_IR_LDG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_LDG_E_U16: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 2, pc)) return; uint16_t x; memcpy(&x, (const void *)(uintptr_t)ad, 2); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, n, pc)) return; if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, i, x[i], p); break; } - case BW_IR_LDS128: { uint32_t ad = a + in->imm; if (ad & 15u) { ws_fail(s, WS_E_SMEM, pc, "LDS.128 address not 16-byte aligned"); return; } for (unsigned i = 0; i < 4; i++) { uint32_t *m = ws_smem(s, ad + 4u * i, pc); if (!m) return; ws_wrs(l, in->dst_vreg, i, *m, p); } break; } - case BW_IR_LDS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; ws_wrs(l, in->dst_vreg, in->dst_subreg, *m, p); break; } - case BW_IR_STS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; *m = b; break; } - case BW_IR_FADD: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) + ws_u2f(b)), p); break; - case BW_IR_FSUB: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) - ws_u2f(b)), p); break; - case BW_IR_FMUL: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) * ws_u2f(b)), p); break; - case BW_IR_FFMA: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaf(ws_u2f(a), ws_u2f(b), ws_u2f(c))), p); break; - case BW_IR_FMNMX_MAX: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaxf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_FMNMX_MIN: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fminf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_MUFU_EX2: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(exp2f(ws_u2f(a))), p); break; - case BW_IR_MUFU_RCP: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / ws_u2f(a)), p); break; - case BW_IR_MUFU_RSQ: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / sqrtf(ws_u2f(a))), p); break; - default: ws_fail(s, WS_E_OP, pc, "opcode not modelled"); return; - } -} - -static int ws_pick(const WsSim *s, const WsWarp *w) { - int best = -1; - for (int i = 0; i < w->nfrag; i++) { - if (w->frag[i].mask == 0 || w->frag[i].parked) continue; - if (best < 0) { best = i; continue; } - if (s->order == 0 ? w->frag[i].pc < w->frag[best].pc : w->frag[i].pc > w->frag[best].pc) best = i; - } - return best; -} -static void ws_drop_frag(WsWarp *w, int i) { w->frag[i] = w->frag[--w->nfrag]; } -static int ws_add_frag(WsSim *s, WsWarp *w, int pc, uint32_t mask) { - if (mask == 0) return 0; - if (w->nfrag >= WS_MAX_FRAGS) { ws_fail(s, WS_E_FRAGS, pc, "too many fragments"); return -1; } - w->frag[w->nfrag].pc = pc; w->frag[w->nfrag].mask = mask; w->frag[w->nfrag].parked = 0; w->nfrag++; - if (w->nfrag > s->max_frags) s->max_frags = w->nfrag; - return 0; -} - -/* Runs one warp until it has no runnable fragment (finished, parked at BAR.SYNC, or stuck). - * Returns 1 when parked at BAR.SYNC, 0 when finished, -1 on error. */ -static int ws_run_warp(WsSim *s, WsWarp *w, uint32_t warp, uint32_t cx, uint32_t cy, int trace) { - const BlackwellIRProgram *p = s->p; - const uint32_t live_all = 0xffffffffu; - for (uint64_t guard = 0;; guard++) { - if (s->err) return -1; - if (guard > 2000000000ull) { ws_fail(s, WS_E_STEPS, -1, "step budget"); return -1; } - int fi = ws_pick(s, w); - if (fi < 0) { - /* nothing runnable: parked at the CTA barrier, finished, or lanes waiting at a BSYNC - * that can never complete */ - for (int i = 0; i < w->nfrag; i++) if (w->frag[i].parked) return 1; - for (int b = 0; b < WS_NBAR; b++) if (w->bar[b].valid) { - if (w->bar[b].arrived) { ws_fail(s, WS_E_STUCK, w->bar[b].target - 1, "lanes parked at BSYNC, the rest never arrive"); return -1; } - ws_fail(s, WS_E_NEVER_JOINED, w->bar[b].target - 1, "warp finished with a barrier still armed"); return -1; - } - return 0; - } - WsFrag *f = &w->frag[fi]; - int pc = f->pc; - if (pc < 0 || (size_t)pc >= p->count) { ws_fail(s, WS_E_PC, pc, "pc outside the program"); return -1; } - const BlackwellIRInsn *in = &p->insns[pc]; - uint32_t mask = f->mask; - s->warp_issues++; s->lane_issues += (uint64_t)ws_popc(mask); - if (trace) printf("W%u pc=%d op=%d mask=%08x frags=%d\n", warp, pc, (int)in->op, mask, w->nfrag); - uint32_t live = live_all & ~w->exited; - uint32_t pmask = 0; - for (int L = 0; L < WS_WARP; L++) if ((mask >> L & 1) && w->lane[L].p0) pmask |= 1u << L; - uint32_t cond = in->predicate_p0 ? (in->predicate_not ? (mask & ~pmask) : (mask & pmask)) : mask; - switch (in->op) { - case BW_IR_EXIT: { - w->exited |= cond; - f->mask = mask & ~cond; - if (f->mask == 0) ws_drop_frag(w, fi); else f->pc = pc + 1; - break; - } - case BW_IR_BRA: { - int32_t delta = (int32_t)in->imm; - uint32_t taken = cond, fall = mask & ~cond; - if (taken && delta == 0) { ws_fail(s, WS_E_SELF_BRANCH, pc, "branch to itself"); return -1; } - if (taken && fall) s->splits++; - if (taken == 0) { f->pc = pc + 1; break; } - if (fall == 0) { f->pc = pc + delta; break; } - f->mask = fall; f->pc = pc + 1; - if (ws_add_frag(s, w, pc + delta, taken) < 0) return -1; - break; - } - case BW_IR_BSSY: { - WsBar *b = &w->bar[in->bar_reg & (WS_NBAR - 1)]; - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - if (b->valid) { ws_fail(s, WS_E_BSSY_REARM, pc, "BSSY on an armed barrier"); return -1; } - b->valid = 1; b->target = pc + (int32_t)in->imm; b->members = cond; b->arrived = 0; - int armed = 0; for (int k = 0; k < WS_NBAR; k++) armed += w->bar[k].valid; - if (armed > s->peak_bars) s->peak_bars = armed; - f->pc = pc + 1; - break; - } - case BW_IR_BSYNC: { - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - WsBar *b = &w->bar[in->bar_reg]; - if (!b->valid) { ws_fail(s, WS_E_BSYNC_UNARMED, pc, "BSYNC without a BSSY"); return -1; } - if (cond & ~b->members) { ws_fail(s, WS_E_NONMEMBER, pc, "a lane at BSYNC did not execute the BSSY"); return -1; } - b->arrived |= cond; - uint32_t rest = mask & ~cond; /* a predicated-off lane walks on */ - if (rest) { f->mask = rest; f->pc = pc + 1; } else ws_drop_frag(w, fi); - if (b->arrived == (b->members & ~w->exited)) { - if (b->target != pc + 1) { ws_fail(s, WS_E_JOIN_MISMATCH, pc, "BSSY named a different join point"); return -1; } - uint32_t joined = b->arrived; b->valid = 0; b->arrived = 0; b->members = 0; - if (ws_add_frag(s, w, pc + 1, joined) < 0) return -1; - } - break; - } - case BW_IR_SHFL_DOWN: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "SHFL on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "SHFL on a split warp"); return -1; } - uint32_t src[WS_WARP]; - for (int L = 0; L < WS_WARP; L++) src[L] = ws_rd(&w->lane[L], in->src1_vreg, p); - for (int L = 0; L < WS_WARP; L++) { int from = L + (int)(in->imm & 31); ws_wr(&w->lane[L], in->dst_vreg, from < WS_WARP ? src[from] : src[L], p); } - f->pc = pc + 1; - break; - } - case BW_IR_BAR_SYNC: { - if (mask != live) s->bar_split_arrivals++; - f->parked = 1; /* released by ws_run when every live lane of the CTA has arrived */ - break; - } - default: { - for (int L = 0; L < WS_WARP; L++) if (mask >> L & 1) { - ws_lane_exec(s, &w->lane[L], in, pc, warp * WS_WARP + (uint32_t)L, cx, cy); - if (s->err) return -1; - } - f->pc = pc + 1; - break; - } - } - } -} - -/* Runs every CTA of the grid. Returns s->err (0 = clean). */ -static int ws_run(WsSim *s, uint32_t grid_x, uint32_t grid_y) { - s->err = 0; s->msg[0] = 0; s->warp_issues = s->lane_issues = s->splits = s->bar_split_arrivals = 0; s->max_frags = 0; s->peak_bars = 0; - if (!s->p || s->threads == 0 || s->threads % WS_WARP || s->threads > WS_MAX_THREADS) { ws_fail(s, WS_E_OP, -1, "bad simulator configuration"); return s->err; } - static WsWarp warps[WS_MAX_WARPS]; - uint32_t nw = s->threads / WS_WARP; - for (uint32_t cy = 0; cy < grid_y && !s->err; cy++) for (uint32_t cx = 0; cx < grid_x && !s->err; cx++) { - memset(warps, 0, sizeof(WsWarp) * nw); - if (s->smem && s->smem_bytes) for (uint32_t i = 0; i + 4 <= s->smem_bytes; i += 4) { uint32_t poison = 0xfeedfaceu; memcpy(s->smem + i, &poison, 4); } - for (uint32_t w = 0; w < nw; w++) { warps[w].nfrag = 1; warps[w].frag[0].pc = 0; warps[w].frag[0].mask = 0xffffffffu; warps[w].frag[0].parked = 0; } - int trace = s->trace && cx == 0 && cy == 0; - /* Barrier phases: every warp runs until all of its fragments are parked at BAR.SYNC or it - * has finished (exited lanes do not hold the barrier up: INFERRED, see WS_E_BAR_SPLIT). - * Then every parked fragment is released and the next phase starts. */ - for (int phase = 0; ; phase++) { - int parked = 0; - for (uint32_t w = 0; w < nw && !s->err; w++) { - if (warps[w].nfrag == 0) continue; - int r = ws_run_warp(s, &warps[w], w, cx, cy, trace && w == 0); - if (r < 0) break; - if (r == 1) parked++; - } - if (s->err || parked == 0) break; /* error, or every warp finished */ - for (uint32_t w = 0; w < nw; w++) for (int i = 0; i < warps[w].nfrag; i++) - if (warps[w].frag[i].parked) { warps[w].frag[i].parked = 0; warps[w].frag[i].pc++; } - if (phase > 100000) { ws_fail(s, WS_E_BAR_TIMEOUT, -1, "barrier phases"); break; } - } - } - return s->err; -} - -#endif /* BW_WARP_SIM_H */ diff --git a/tests/bw_warp_sim_k.h b/tests/bw_warp_sim_k.h deleted file mode 100644 index 676b29344..000000000 --- a/tests/bw_warp_sim_k.h +++ /dev/null @@ -1,329 +0,0 @@ -/* bw_warp_sim.h: host SIMT simulator for the Blackwell IR (omega #308). - * - * Models what the earlier per-thread simulators could not: a warp of 32 lanes with an - * active mask, divergence at predicated branches, structured reconvergence through the - * barrier registers (BSSY arms Bn for the lanes executing it and names the join; BSYNC - * parks arriving lanes until every armed lane that has not exited is there, then the - * warp continues as one), nested regions, and lane participation in SHFL and BAR.SYNC. - * - * A warp is a set of fragments (pc, lane mask). A predicated branch whose lanes disagree - * splits the fragment; the scheduler then runs one fragment at a time in a chosen order - * (lowest pc first or highest pc first; tests run both), which is the freedom the chip's - * scheduler also has. Fragments only merge at a BSYNC. Errors (all fatal, first one wins): - * WS_E_SHFL_SPLIT a SHFL reached by a fragment that is not the whole live warp - * (the chip reads inactive lanes: undefined; attention 2026-10-04) - * WS_E_SHFL_EXITED a SHFL on a warp some of whose lanes already exited (undefined too) - * WS_E_BAR_SPLIT (defined, never raised) a BAR.SYNC reached by a split warp is allowed: - * since Volta the CTA barrier counts arriving threads, not warps (CUDA - * programming guide, independent thread scheduling; INFERRED for sm_121, - * not chip-verified by us). The simulator parks each fragment, releases - * them together, counts the event in bar_split_arrivals, and leaves the - * fragments split: a barrier is not a reconvergence point, so a SHFL after - * it still fails with SHFL_SPLIT unless a BSYNC rejoined the warp. - * WS_E_BSYNC_UNARMED BSYNC on a barrier no BSSY armed - * WS_E_BSSY_REARM BSSY on a barrier still armed (lanes may still be heading to its join) - * WS_E_JOIN_MISMATCH BSYNC at an address other than the one the BSSY named minus one - * WS_E_NONMEMBER a lane reached BSYNC Bn without having executed its BSSY - * WS_E_STUCK lanes parked at a BSYNC that can never complete (a join was dropped, - * an exit jumped past it, or a target was corrupted) - * WS_E_NEVER_JOINED the warp finished with a barrier still armed - * WS_E_SELF_BRANCH, WS_E_PC, WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS - * Every error names the pc. Memory: global addresses are host pointers (optionally range - * checked); shared memory is a per-CTA buffer poisoned at CTA start so a read of a word - * nobody wrote shows up in the oracle comparison. - * - * Per-lane ALU semantics are those of the two earlier simulators (tests/gpu_attention_test.c, - * bench/prime_race/tests/gb10_sieve_host_test.c). EX2 and RCP are exact here; the chip's - * are approximate. LDCU64 (memory descriptor) is not modelled. */ -#ifndef BW_WARP_SIM_K_H -#define BW_WARP_SIM_K_H -/* bw_warp_sim_k.h (OWN-30B cut 8, 2026-10-13): tests/bw_warp_sim.h plus the system-scope opcodes the decode attention - * kernel uses (ATOMG.ADD, LDG/STG.STRONG.SYS, MEMBAR): a derived copy so the 8B lane's file stays untouched. - * The simulator runs CTAs one after another, so an atomic counter sees every earlier CTA's add. */ - -#include "omega_blackwell_codegen.h" -#include -#include -#include -#include -#include - -#define WS_WARP 32 -#ifndef WS_MAX_THREADS -#define WS_MAX_THREADS 256 -#endif -#define WS_MAX_WARPS (WS_MAX_THREADS / WS_WARP) -#define WS_MAX_FRAGS 64 -#define WS_NBAR BW_RECONV_MAX_BAR -#define WS_MAX_RANGES 8 - -enum { - WS_OK = 0, WS_E_SHFL_SPLIT, WS_E_SHFL_EXITED, WS_E_BAR_SPLIT, WS_E_BSYNC_UNARMED, WS_E_BSSY_REARM, - WS_E_JOIN_MISMATCH, WS_E_NONMEMBER, WS_E_STUCK, WS_E_NEVER_JOINED, WS_E_SELF_BRANCH, WS_E_PC, - WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS, WS_E_BAR_TIMEOUT, WS_E_STEPS -}; -static const char *ws_err_name(int e) { - static const char *const n[] = { "OK", "SHFL_SPLIT", "SHFL_EXITED", "BAR_SPLIT", "BSYNC_UNARMED", "BSSY_REARM", - "JOIN_MISMATCH", "NONMEMBER", "STUCK", "NEVER_JOINED", "SELF_BRANCH", "PC", "OP", "SHIFT", "MEM", "SMEM", - "FRAGS", "BAR_TIMEOUT", "STEPS" }; - return (e >= 0 && e < (int)(sizeof n / sizeof n[0])) ? n[e] : "?"; -} - -typedef struct { uint32_t r[256]; uint8_t p0; } WsLane; -typedef struct { int pc; uint32_t mask; int parked; /* waiting at a BAR.SYNC */ } WsFrag; -typedef struct { int valid; int target; uint32_t members, arrived; } WsBar; -typedef struct { - WsLane lane[WS_WARP]; - WsFrag frag[WS_MAX_FRAGS]; - int nfrag; - WsBar bar[WS_NBAR]; - uint32_t exited; -} WsWarp; -typedef struct { uintptr_t lo, hi; } WsRange; - -typedef struct { - const BlackwellIRProgram *p; - uint32_t cbank[256]; /* constant bank 0 words (byte offset / 4) */ - uint32_t threads; /* per CTA, a multiple of 32, <= WS_MAX_THREADS */ - uint8_t *smem; /* per-CTA shared memory buffer (poisoned at CTA start) */ - uint32_t smem_bytes; - WsRange ranges[WS_MAX_RANGES]; int nranges; /* when > 0, every global access must fall in one */ - int order; /* 0 = lowest pc first, 1 = highest pc first */ - int trace; /* print every issue of warp 0 of CTA (0,0) */ - /* results */ - int err; int err_pc; char msg[200]; - uint64_t warp_issues; /* fragment-instruction issues (the chip's cost unit for divergence) */ - uint64_t lane_issues; /* lanes active over those issues */ - uint64_t splits; /* branches that split a fragment */ - uint64_t bar_split_arrivals; /* BAR.SYNC reached by a fragment that is not the whole live warp */ - int max_frags, peak_bars; -} WsSim; - -static void ws_fail(WsSim *s, int err, int pc, const char *what) { - if (s->err) return; - s->err = err; s->err_pc = pc; - snprintf(s->msg, sizeof s->msg, "%s at pc %d: %s", ws_err_name(err), pc, what ? what : ""); -} - -static uint32_t ws_rd(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[ph & 0xff]; } -static uint64_t ws_rd64(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)l->r[ph] | ((uint64_t)l->r[(ph + 1) & 0xff] << 32); } -static void ws_wr(WsLane *l, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[ph & 0xff] = x; } -static void ws_wr64(WsLane *l, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; l->r[ph] = (uint32_t)x; l->r[(ph + 1) & 0xff] = (uint32_t)(x >> 32); } -/* sub-register operands (quad/pair lanes, BlackwellIRInsn.*_subreg) */ -static uint32_t ws_rds(const WsLane *l, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[(ph + sub) & 0xff]; } -static void ws_wrs(WsLane *l, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[(ph + sub) & 0xff] = x; } -static float ws_u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t ws_f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint32_t ws_lut3(uint32_t lut, uint32_t a, uint32_t b, uint32_t c) { - uint32_t r = 0; - for (int i = 0; i < 8; i++) if (lut >> i & 1) r |= ((i & 4) ? a : ~a) & ((i & 2) ? b : ~b) & ((i & 1) ? c : ~c); - return r; -} -static int ws_mem_ok(WsSim *s, uint64_t a, unsigned bytes, int pc) { - if (s->nranges == 0) return 1; - for (int i = 0; i < s->nranges; i++) if (a >= s->ranges[i].lo && a + bytes <= s->ranges[i].hi) return 1; - if (getenv("WS_DBG")) { fprintf(stderr, "bad addr %llx +%u pc %d\n", (unsigned long long)a, bytes, pc); for (int i = 0; i < s->nranges; i++) fprintf(stderr, " range %d %llx..%llx\n", i, (unsigned long long)s->ranges[i].lo, (unsigned long long)s->ranges[i].hi); } - ws_fail(s, WS_E_MEM, pc, "global access outside the declared buffers"); return 0; -} -static uint32_t *ws_smem(WsSim *s, uint32_t a, int pc) { - if ((a & 3) || a + 4 > s->smem_bytes) { ws_fail(s, WS_E_SMEM, pc, "shared access past the declared size"); return NULL; } - return (uint32_t *)(s->smem + a); -} -static int ws_popc(uint32_t m) { return __builtin_popcount(m); } - -/* One lane, one non-control instruction. */ -static void ws_lane_exec(WsSim *s, WsLane *l, const BlackwellIRInsn *in, int pc, uint32_t tid, uint32_t cx, uint32_t cy) { - const BlackwellIRProgram *p = s->p; - uint32_t a = ws_rds(l, in->src1_vreg, in->src1_subreg, p), b = ws_rds(l, in->src2_vreg, in->src2_subreg, p), c = ws_rds(l, in->src3_vreg, in->src3_subreg, p); - switch (in->op) { - case BW_IR_NOP: break; - case BW_IR_S2R: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; - case BW_IR_LDC: ws_wrs(l, in->dst_vreg, in->dst_subreg, s->cbank[(in->imm / 4) & 0xff], p); break; - case BW_IR_LDC64: ws_wr64(l, in->dst_vreg, (uint64_t)s->cbank[(in->imm / 4) & 0xff] | ((uint64_t)s->cbank[(in->imm / 4 + 1) & 0xff] << 32), p); break; - case BW_IR_LDCU64: case BW_IR_LDCU: break; /* memory descriptor: not modelled */ - case BW_IR_MOV_IMM: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm, p); break; - case BW_IR_MOV_RZ: ws_wrs(l, in->dst_vreg, in->dst_subreg, 0, p); break; - case BW_IR_IMAD: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; - case BW_IR_IMAD_WIDE: ws_wr64(l, in->dst_vreg, (uint64_t)a * in->imm + ws_rd64(l, in->src3_vreg, p), p); break; - case BW_IR_IMAD_HI_U32: ws_wrs(l, in->dst_vreg, in->dst_subreg, (uint32_t)(((uint64_t)a * b) >> 32) + c, p); break; - case BW_IR_IADD3: ws_wrs(l, in->dst_vreg, in->dst_subreg, a + b, p); break; /* the encoder's IADD3 has Rc = RZ */ - case BW_IR_SHF_R: ws_wrs(l, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; - case BW_IR_SHF_L_U32: if (b >= 32) { ws_fail(s, WS_E_SHIFT, pc, "SHF.L.U32 amount >= 32 (not chip-verified)"); return; } ws_wrs(l, in->dst_vreg, in->dst_subreg, a << b, p); break; - case BW_IR_LOP3_AND: ws_wrs(l, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; - case BW_IR_LOP3_XOR: ws_wrs(l, in->dst_vreg, in->dst_subreg, a ^ b, p); break; - case BW_IR_LOP3_LUT: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_lut3(in->imm & 0xff, a, b, c), p); break; - case BW_IR_ISETP_GE_U32: l->p0 = a >= b; break; - case BW_IR_LDG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_LDG_E_U16: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 2, pc)) return; uint16_t x; memcpy(&x, (const void *)(uintptr_t)ad, 2); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, n, pc)) { if (getenv("WS_DBG")) fprintf(stderr, " tid %u cx %u cy %u\n", tid, cx, cy); return; } if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, i, x[i], p); break; } - case BW_IR_LDS128: { uint32_t ad = a + in->imm; if (ad & 15u) { ws_fail(s, WS_E_SMEM, pc, "LDS.128 address not 16-byte aligned"); return; } for (unsigned i = 0; i < 4; i++) { uint32_t *m = ws_smem(s, ad + 4u * i, pc); if (!m) return; ws_wrs(l, in->dst_vreg, i, *m, p); } break; } - case BW_IR_LDS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; ws_wrs(l, in->dst_vreg, in->dst_subreg, *m, p); break; } - case BW_IR_STS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; *m = b; break; } - case BW_IR_FADD: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) + ws_u2f(b)), p); break; - case BW_IR_FSUB: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) - ws_u2f(b)), p); break; - case BW_IR_FMUL: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) * ws_u2f(b)), p); break; - case BW_IR_I2FP: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u((float)(int32_t)a), p); break; /* I2FP.F32.S32, round to nearest */ - case BW_IR_FFMA: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaf(ws_u2f(a), ws_u2f(b), ws_u2f(c))), p); break; - case BW_IR_FMNMX_MAX: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaxf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_FMNMX_MIN: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fminf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_MUFU_EX2: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(exp2f(ws_u2f(a))), p); break; - case BW_IR_MUFU_RCP: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / ws_u2f(a)), p); break; - case BW_IR_MUFU_RSQ: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / sqrtf(ws_u2f(a))), p); break; - case BW_IR_LDG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_ATOMG_ADD_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t old; memcpy(&old, (const void *)(uintptr_t)ad, 4); uint32_t nw = old + b; memcpy((void *)(uintptr_t)ad, &nw, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, old, p); break; } - case BW_IR_MEMBAR_ALL_SYS: break; - default: ws_fail(s, WS_E_OP, pc, "opcode not modelled"); return; - } -} - -static int ws_pick(const WsSim *s, const WsWarp *w) { - int best = -1; - for (int i = 0; i < w->nfrag; i++) { - if (w->frag[i].mask == 0 || w->frag[i].parked) continue; - if (best < 0) { best = i; continue; } - if (s->order == 0 ? w->frag[i].pc < w->frag[best].pc : w->frag[i].pc > w->frag[best].pc) best = i; - } - return best; -} -static void ws_drop_frag(WsWarp *w, int i) { w->frag[i] = w->frag[--w->nfrag]; } -static int ws_add_frag(WsSim *s, WsWarp *w, int pc, uint32_t mask) { - if (mask == 0) return 0; - if (w->nfrag >= WS_MAX_FRAGS) { ws_fail(s, WS_E_FRAGS, pc, "too many fragments"); return -1; } - w->frag[w->nfrag].pc = pc; w->frag[w->nfrag].mask = mask; w->frag[w->nfrag].parked = 0; w->nfrag++; - if (w->nfrag > s->max_frags) s->max_frags = w->nfrag; - return 0; -} - -/* Runs one warp until it has no runnable fragment (finished, parked at BAR.SYNC, or stuck). - * Returns 1 when parked at BAR.SYNC, 0 when finished, -1 on error. */ -static int ws_run_warp(WsSim *s, WsWarp *w, uint32_t warp, uint32_t cx, uint32_t cy, int trace) { - const BlackwellIRProgram *p = s->p; - const uint32_t live_all = 0xffffffffu; - for (uint64_t guard = 0;; guard++) { - if (s->err) return -1; - if (guard > 2000000000ull) { ws_fail(s, WS_E_STEPS, -1, "step budget"); return -1; } - int fi = ws_pick(s, w); - if (fi < 0) { - /* nothing runnable: parked at the CTA barrier, finished, or lanes waiting at a BSYNC - * that can never complete */ - for (int i = 0; i < w->nfrag; i++) if (w->frag[i].parked) return 1; - for (int b = 0; b < WS_NBAR; b++) if (w->bar[b].valid) { - if (w->bar[b].arrived) { ws_fail(s, WS_E_STUCK, w->bar[b].target - 1, "lanes parked at BSYNC, the rest never arrive"); return -1; } - ws_fail(s, WS_E_NEVER_JOINED, w->bar[b].target - 1, "warp finished with a barrier still armed"); return -1; - } - return 0; - } - WsFrag *f = &w->frag[fi]; - int pc = f->pc; - if (pc < 0 || (size_t)pc >= p->count) { ws_fail(s, WS_E_PC, pc, "pc outside the program"); return -1; } - const BlackwellIRInsn *in = &p->insns[pc]; - uint32_t mask = f->mask; - s->warp_issues++; s->lane_issues += (uint64_t)ws_popc(mask); - if (trace) printf("W%u pc=%d op=%d mask=%08x frags=%d\n", warp, pc, (int)in->op, mask, w->nfrag); - uint32_t live = live_all & ~w->exited; - uint32_t pmask = 0; - for (int L = 0; L < WS_WARP; L++) if ((mask >> L & 1) && w->lane[L].p0) pmask |= 1u << L; - uint32_t cond = in->predicate_p0 ? (in->predicate_not ? (mask & ~pmask) : (mask & pmask)) : mask; - switch (in->op) { - case BW_IR_EXIT: { - w->exited |= cond; - f->mask = mask & ~cond; - if (f->mask == 0) ws_drop_frag(w, fi); else f->pc = pc + 1; - break; - } - case BW_IR_BRA: { - int32_t delta = (int32_t)in->imm; - uint32_t taken = cond, fall = mask & ~cond; - if (taken && delta == 0) { ws_fail(s, WS_E_SELF_BRANCH, pc, "branch to itself"); return -1; } - if (taken && fall) s->splits++; - if (taken == 0) { f->pc = pc + 1; break; } - if (fall == 0) { f->pc = pc + delta; break; } - f->mask = fall; f->pc = pc + 1; - if (ws_add_frag(s, w, pc + delta, taken) < 0) return -1; - break; - } - case BW_IR_BSSY: { - WsBar *b = &w->bar[in->bar_reg & (WS_NBAR - 1)]; - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - if (b->valid) { ws_fail(s, WS_E_BSSY_REARM, pc, "BSSY on an armed barrier"); return -1; } - b->valid = 1; b->target = pc + (int32_t)in->imm; b->members = cond; b->arrived = 0; - int armed = 0; for (int k = 0; k < WS_NBAR; k++) armed += w->bar[k].valid; - if (armed > s->peak_bars) s->peak_bars = armed; - f->pc = pc + 1; - break; - } - case BW_IR_BSYNC: { - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - WsBar *b = &w->bar[in->bar_reg]; - if (!b->valid) { ws_fail(s, WS_E_BSYNC_UNARMED, pc, "BSYNC without a BSSY"); return -1; } - if (cond & ~b->members) { ws_fail(s, WS_E_NONMEMBER, pc, "a lane at BSYNC did not execute the BSSY"); return -1; } - b->arrived |= cond; - uint32_t rest = mask & ~cond; /* a predicated-off lane walks on */ - if (rest) { f->mask = rest; f->pc = pc + 1; } else ws_drop_frag(w, fi); - if (b->arrived == (b->members & ~w->exited)) { - if (b->target != pc + 1) { ws_fail(s, WS_E_JOIN_MISMATCH, pc, "BSSY named a different join point"); return -1; } - uint32_t joined = b->arrived; b->valid = 0; b->arrived = 0; b->members = 0; - if (ws_add_frag(s, w, pc + 1, joined) < 0) return -1; - } - break; - } - case BW_IR_SHFL_DOWN: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "SHFL on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "SHFL on a split warp"); return -1; } - uint32_t src[WS_WARP]; - for (int L = 0; L < WS_WARP; L++) src[L] = ws_rd(&w->lane[L], in->src1_vreg, p); - for (int L = 0; L < WS_WARP; L++) { int from = L + (int)(in->imm & 31); ws_wr(&w->lane[L], in->dst_vreg, from < WS_WARP ? src[from] : src[L], p); } - f->pc = pc + 1; - break; - } - case BW_IR_BAR_SYNC: { - if (mask != live) s->bar_split_arrivals++; - f->parked = 1; /* released by ws_run when every live lane of the CTA has arrived */ - break; - } - default: { - for (int L = 0; L < WS_WARP; L++) if (mask >> L & 1) { - ws_lane_exec(s, &w->lane[L], in, pc, warp * WS_WARP + (uint32_t)L, cx, cy); - if (s->err) return -1; - } - f->pc = pc + 1; - break; - } - } - } -} - -/* Runs every CTA of the grid. Returns s->err (0 = clean). */ -static int ws_run(WsSim *s, uint32_t grid_x, uint32_t grid_y) { - s->err = 0; s->msg[0] = 0; s->warp_issues = s->lane_issues = s->splits = s->bar_split_arrivals = 0; s->max_frags = 0; s->peak_bars = 0; - if (!s->p || s->threads == 0 || s->threads % WS_WARP || s->threads > WS_MAX_THREADS) { ws_fail(s, WS_E_OP, -1, "bad simulator configuration"); return s->err; } - static WsWarp warps[WS_MAX_WARPS]; - uint32_t nw = s->threads / WS_WARP; - for (uint32_t cy = 0; cy < grid_y && !s->err; cy++) for (uint32_t cx = 0; cx < grid_x && !s->err; cx++) { - memset(warps, 0, sizeof(WsWarp) * nw); - if (s->smem && s->smem_bytes) for (uint32_t i = 0; i + 4 <= s->smem_bytes; i += 4) { uint32_t poison = 0xfeedfaceu; memcpy(s->smem + i, &poison, 4); } - for (uint32_t w = 0; w < nw; w++) { warps[w].nfrag = 1; warps[w].frag[0].pc = 0; warps[w].frag[0].mask = 0xffffffffu; warps[w].frag[0].parked = 0; } - int trace = s->trace && cx == 0 && cy == 0; - /* Barrier phases: every warp runs until all of its fragments are parked at BAR.SYNC or it - * has finished (exited lanes do not hold the barrier up: INFERRED, see WS_E_BAR_SPLIT). - * Then every parked fragment is released and the next phase starts. */ - for (int phase = 0; ; phase++) { - int parked = 0; - for (uint32_t w = 0; w < nw && !s->err; w++) { - if (warps[w].nfrag == 0) continue; - int r = ws_run_warp(s, &warps[w], w, cx, cy, trace && w == 0); - if (r < 0) break; - if (r == 1) parked++; - } - if (s->err || parked == 0) break; /* error, or every warp finished */ - for (uint32_t w = 0; w < nw; w++) for (int i = 0; i < warps[w].nfrag; i++) - if (warps[w].frag[i].parked) { warps[w].frag[i].parked = 0; warps[w].frag[i].pc++; } - if (phase > 100000) { ws_fail(s, WS_E_BAR_TIMEOUT, -1, "barrier phases"); break; } - } - } - return s->err; -} - -#endif /* BW_WARP_SIM_K_H */ diff --git a/tests/bw_warp_sim_pa.h b/tests/bw_warp_sim_pa.h deleted file mode 100644 index 7657df020..000000000 --- a/tests/bw_warp_sim_pa.h +++ /dev/null @@ -1,370 +0,0 @@ -/* bw_warp_sim.h: host SIMT simulator for the Blackwell IR (omega #308). - * - * Models what the earlier per-thread simulators could not: a warp of 32 lanes with an - * active mask, divergence at predicated branches, structured reconvergence through the - * barrier registers (BSSY arms Bn for the lanes executing it and names the join; BSYNC - * parks arriving lanes until every armed lane that has not exited is there, then the - * warp continues as one), nested regions, and lane participation in SHFL and BAR.SYNC. - * - * A warp is a set of fragments (pc, lane mask). A predicated branch whose lanes disagree - * splits the fragment; the scheduler then runs one fragment at a time in a chosen order - * (lowest pc first or highest pc first; tests run both), which is the freedom the chip's - * scheduler also has. Fragments only merge at a BSYNC. Errors (all fatal, first one wins): - * WS_E_SHFL_SPLIT a SHFL reached by a fragment that is not the whole live warp - * (the chip reads inactive lanes: undefined; attention 2026-10-04) - * WS_E_SHFL_EXITED a SHFL on a warp some of whose lanes already exited (undefined too) - * WS_E_BAR_SPLIT (defined, never raised) a BAR.SYNC reached by a split warp is allowed: - * since Volta the CTA barrier counts arriving threads, not warps (CUDA - * programming guide, independent thread scheduling; INFERRED for sm_121, - * not chip-verified by us). The simulator parks each fragment, releases - * them together, counts the event in bar_split_arrivals, and leaves the - * fragments split: a barrier is not a reconvergence point, so a SHFL after - * it still fails with SHFL_SPLIT unless a BSYNC rejoined the warp. - * WS_E_BSYNC_UNARMED BSYNC on a barrier no BSSY armed - * WS_E_BSSY_REARM BSSY on a barrier still armed (lanes may still be heading to its join) - * WS_E_JOIN_MISMATCH BSYNC at an address other than the one the BSSY named minus one - * WS_E_NONMEMBER a lane reached BSYNC Bn without having executed its BSSY - * WS_E_STUCK lanes parked at a BSYNC that can never complete (a join was dropped, - * an exit jumped past it, or a target was corrupted) - * WS_E_NEVER_JOINED the warp finished with a barrier still armed - * WS_E_SELF_BRANCH, WS_E_PC, WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS - * Every error names the pc. Memory: global addresses are host pointers (optionally range - * checked); shared memory is a per-CTA buffer poisoned at CTA start so a read of a word - * nobody wrote shows up in the oracle comparison. - * - * Per-lane ALU semantics are those of the two earlier simulators (tests/gpu_attention_test.c, - * bench/prime_race/tests/gb10_sieve_host_test.c). EX2 and RCP are exact here; the chip's - * are approximate. LDCU64 (memory descriptor) is not modelled. */ -#ifndef BW_WARP_SIM_PA_H -/* bw_warp_sim_pa.h (OWN-30B L1 attention, 2026-10-13): bw_warp_sim_tc.h with the HMMA operands read at their sub-register - * offsets (src1/src2/src3_subreg; the encoder adds them to the physical register, bw_warp_sim_tc.h ignored them). The - * prefill attention takes its B pairs from the upper half of LDS.128 quads. A derived copy: the T3 file stays untouched. */ -#define BW_WARP_SIM_PA_H -/* bw_warp_sim_k.h (OWN-30B cut 8, 2026-10-13): tests/bw_warp_sim.h plus the system-scope opcodes the decode attention - * kernel uses (ATOMG.ADD, LDG/STG.STRONG.SYS, MEMBAR): a derived copy so the 8B lane's file stays untouched. - * The simulator runs CTAs one after another, so an atomic counter sees every earlier CTA's add. */ -/* bw_warp_sim_tc.h (OWN-30B T3, 2026-10-13): bw_warp_sim_k.h plus (a) HMMA.16816.F32.BF16 as a warp-collective operation - * computed with the GB10 arithmetic model that matched 3 x 262144 chip outputs bit for bit (tests/bw_hmma_model.h, evidence - * OWN30B-T3-HMMA-MODEL), requiring the whole live warp (like SHFL), and (b) the STG.E immediate byte offset, which the - * encoder emits and bw_warp_sim_k.h ignored. Timing (stall counts, scoreboards) is not modelled. */ - -#include "omega_blackwell_codegen.h" -#include "bw_hmma_model.h" -#include "omega_blackwell_codegen_tc.h" -#include -#include -#include -#include -#include - -#define WS_WARP 32 -#ifndef WS_MAX_THREADS -#define WS_MAX_THREADS 256 -#endif -#define WS_MAX_WARPS (WS_MAX_THREADS / WS_WARP) -#define WS_MAX_FRAGS 64 -#define WS_NBAR BW_RECONV_MAX_BAR -#define WS_MAX_RANGES 8 - -enum { - WS_OK = 0, WS_E_SHFL_SPLIT, WS_E_SHFL_EXITED, WS_E_BAR_SPLIT, WS_E_BSYNC_UNARMED, WS_E_BSSY_REARM, - WS_E_JOIN_MISMATCH, WS_E_NONMEMBER, WS_E_STUCK, WS_E_NEVER_JOINED, WS_E_SELF_BRANCH, WS_E_PC, - WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS, WS_E_BAR_TIMEOUT, WS_E_STEPS -}; -static const char *ws_err_name(int e) { - static const char *const n[] = { "OK", "SHFL_SPLIT", "SHFL_EXITED", "BAR_SPLIT", "BSYNC_UNARMED", "BSSY_REARM", - "JOIN_MISMATCH", "NONMEMBER", "STUCK", "NEVER_JOINED", "SELF_BRANCH", "PC", "OP", "SHIFT", "MEM", "SMEM", - "FRAGS", "BAR_TIMEOUT", "STEPS" }; - return (e >= 0 && e < (int)(sizeof n / sizeof n[0])) ? n[e] : "?"; -} - -typedef struct { uint32_t r[256]; uint8_t p0; } WsLane; -typedef struct { int pc; uint32_t mask; int parked; /* waiting at a BAR.SYNC */ } WsFrag; -typedef struct { int valid; int target; uint32_t members, arrived; } WsBar; -typedef struct { - WsLane lane[WS_WARP]; - WsFrag frag[WS_MAX_FRAGS]; - int nfrag; - WsBar bar[WS_NBAR]; - uint32_t exited; -} WsWarp; -typedef struct { uintptr_t lo, hi; } WsRange; - -typedef struct { - const BlackwellIRProgram *p; - uint32_t cbank[256]; /* constant bank 0 words (byte offset / 4) */ - uint32_t threads; /* per CTA, a multiple of 32, <= WS_MAX_THREADS */ - uint8_t *smem; /* per-CTA shared memory buffer (poisoned at CTA start) */ - uint32_t smem_bytes; - WsRange ranges[WS_MAX_RANGES]; int nranges; /* when > 0, every global access must fall in one */ - int order; /* 0 = lowest pc first, 1 = highest pc first */ - int trace; /* print every issue of warp 0 of CTA (0,0) */ - /* results */ - int err; int err_pc; char msg[200]; - uint64_t warp_issues; /* fragment-instruction issues (the chip's cost unit for divergence) */ - uint64_t lane_issues; /* lanes active over those issues */ - uint64_t splits; /* branches that split a fragment */ - uint64_t bar_split_arrivals; /* BAR.SYNC reached by a fragment that is not the whole live warp */ - int max_frags, peak_bars; -} WsSim; - -static void ws_fail(WsSim *s, int err, int pc, const char *what) { - if (s->err) return; - s->err = err; s->err_pc = pc; - snprintf(s->msg, sizeof s->msg, "%s at pc %d: %s", ws_err_name(err), pc, what ? what : ""); -} - -static uint32_t ws_rd(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[ph & 0xff]; } -static uint64_t ws_rd64(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)l->r[ph] | ((uint64_t)l->r[(ph + 1) & 0xff] << 32); } -static void ws_wr(WsLane *l, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[ph & 0xff] = x; } -static void ws_wr64(WsLane *l, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; l->r[ph] = (uint32_t)x; l->r[(ph + 1) & 0xff] = (uint32_t)(x >> 32); } -/* sub-register operands (quad/pair lanes, BlackwellIRInsn.*_subreg) */ -static uint32_t ws_rds(const WsLane *l, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[(ph + sub) & 0xff]; } -static void ws_wrs(WsLane *l, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[(ph + sub) & 0xff] = x; } -static float ws_u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t ws_f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint32_t ws_bf16_rn(uint32_t u) { if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u; return (u + 0x7fffu + ((u >> 16) & 1u)) >> 16; } /* f32 bits -> bf16 bits, round to nearest even */ -static uint32_t ws_lut3(uint32_t lut, uint32_t a, uint32_t b, uint32_t c) { - uint32_t r = 0; - for (int i = 0; i < 8; i++) if (lut >> i & 1) r |= ((i & 4) ? a : ~a) & ((i & 2) ? b : ~b) & ((i & 1) ? c : ~c); - return r; -} -static int ws_mem_ok(WsSim *s, uint64_t a, unsigned bytes, int pc) { - if (s->nranges == 0) return 1; - for (int i = 0; i < s->nranges; i++) if (a >= s->ranges[i].lo && a + bytes <= s->ranges[i].hi) return 1; - if (getenv("WS_DBG")) { fprintf(stderr, "bad addr %llx +%u pc %d\n", (unsigned long long)a, bytes, pc); for (int i = 0; i < s->nranges; i++) fprintf(stderr, " range %d %llx..%llx\n", i, (unsigned long long)s->ranges[i].lo, (unsigned long long)s->ranges[i].hi); } - ws_fail(s, WS_E_MEM, pc, "global access outside the declared buffers"); return 0; -} -static uint32_t *ws_smem(WsSim *s, uint32_t a, int pc) { - if ((a & 3) || a + 4 > s->smem_bytes) { ws_fail(s, WS_E_SMEM, pc, "shared access past the declared size"); return NULL; } - return (uint32_t *)(s->smem + a); -} -static int ws_popc(uint32_t m) { return __builtin_popcount(m); } - -/* One lane, one non-control instruction. */ -static void ws_lane_exec(WsSim *s, WsLane *l, const BlackwellIRInsn *in, int pc, uint32_t tid, uint32_t cx, uint32_t cy) { - const BlackwellIRProgram *p = s->p; - uint32_t a = ws_rds(l, in->src1_vreg, in->src1_subreg, p), b = ws_rds(l, in->src2_vreg, in->src2_subreg, p), c = ws_rds(l, in->src3_vreg, in->src3_subreg, p); - switch (in->op) { - case BW_IR_NOP: break; - case BW_IR_S2R: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; - case BW_IR_LDC: ws_wrs(l, in->dst_vreg, in->dst_subreg, s->cbank[(in->imm / 4) & 0xff], p); break; - case BW_IR_LDC64: ws_wr64(l, in->dst_vreg, (uint64_t)s->cbank[(in->imm / 4) & 0xff] | ((uint64_t)s->cbank[(in->imm / 4 + 1) & 0xff] << 32), p); break; - case BW_IR_LDCU64: case BW_IR_LDCU: break; /* memory descriptor: not modelled */ - case BW_IR_MOV_IMM: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm, p); break; - case BW_IR_MOV_RZ: ws_wrs(l, in->dst_vreg, in->dst_subreg, 0, p); break; - case BW_IR_IMAD: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; - case BW_IR_IMAD_WIDE: ws_wr64(l, in->dst_vreg, (uint64_t)a * in->imm + ws_rd64(l, in->src3_vreg, p), p); break; - case BW_IR_IMAD_HI_U32: ws_wrs(l, in->dst_vreg, in->dst_subreg, (uint32_t)(((uint64_t)a * b) >> 32) + c, p); break; - case BW_IR_IADD3: ws_wrs(l, in->dst_vreg, in->dst_subreg, a + b, p); break; /* the encoder's IADD3 has Rc = RZ */ - case BW_IR_SHF_R: ws_wrs(l, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; - case BW_IR_SHF_L_U32: if (b >= 32) { ws_fail(s, WS_E_SHIFT, pc, "SHF.L.U32 amount >= 32 (not chip-verified)"); return; } ws_wrs(l, in->dst_vreg, in->dst_subreg, a << b, p); break; - case BW_IR_LOP3_AND: ws_wrs(l, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; - case BW_IR_LOP3_XOR: ws_wrs(l, in->dst_vreg, in->dst_subreg, a ^ b, p); break; - case BW_IR_LOP3_LUT: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_lut3(in->imm & 0xff, a, b, c), p); break; - case BW_IR_ISETP_GE_U32: l->p0 = a >= b; break; - case BW_IR_LDG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_LDG_E_U16: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 2, pc)) return; uint16_t x; memcpy(&x, (const void *)(uintptr_t)ad, 2); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, n, pc)) { if (getenv("WS_DBG")) fprintf(stderr, " tid %u cx %u cy %u\n", tid, cx, cy); return; } if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, i, x[i], p); break; } - case BW_IR_LDS128: { uint32_t ad = a + in->imm; if (ad & 15u) { ws_fail(s, WS_E_SMEM, pc, "LDS.128 address not 16-byte aligned"); return; } for (unsigned i = 0; i < 4; i++) { uint32_t *m = ws_smem(s, ad + 4u * i, pc); if (!m) return; ws_wrs(l, in->dst_vreg, i, *m, p); } break; } - case BW_IR_LDS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; ws_wrs(l, in->dst_vreg, in->dst_subreg, *m, p); break; } - case BW_IR_STS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; *m = b; break; } - case BW_IR_FADD: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) + ws_u2f(b)), p); break; - case BW_IR_FSUB: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) - ws_u2f(b)), p); break; - case BW_IR_FMUL: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) * ws_u2f(b)), p); break; - case BW_IR_FFMA: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaf(ws_u2f(a), ws_u2f(b), ws_u2f(c))), p); break; - case BW_IR_FMNMX_MAX: - if (in->imm == OMEGA_TC_MARK_F2FP) { ws_wrs(l, in->dst_vreg, in->dst_subreg, (ws_bf16_rn(a) << 16) | ws_bf16_rn(b), p); break; } /* F2FP.BF16.F32.PACK_AB placeholder */ - ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaxf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_FMNMX_MIN: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fminf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_MUFU_EX2: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(exp2f(ws_u2f(a))), p); break; - case BW_IR_MUFU_RCP: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / ws_u2f(a)), p); break; - case BW_IR_MUFU_RSQ: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(1.0f / sqrtf(ws_u2f(a))), p); break; - case BW_IR_LDG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_ATOMG_ADD_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t old; memcpy(&old, (const void *)(uintptr_t)ad, 4); uint32_t nw = old + b; memcpy((void *)(uintptr_t)ad, &nw, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, old, p); break; } - case BW_IR_MEMBAR_ALL_SYS: break; - default: ws_fail(s, WS_E_OP, pc, "opcode not modelled"); return; - } -} - -static int ws_pick(const WsSim *s, const WsWarp *w) { - int best = -1; - for (int i = 0; i < w->nfrag; i++) { - if (w->frag[i].mask == 0 || w->frag[i].parked) continue; - if (best < 0) { best = i; continue; } - if (s->order == 0 ? w->frag[i].pc < w->frag[best].pc : w->frag[i].pc > w->frag[best].pc) best = i; - } - return best; -} -static void ws_drop_frag(WsWarp *w, int i) { w->frag[i] = w->frag[--w->nfrag]; } -static int ws_add_frag(WsSim *s, WsWarp *w, int pc, uint32_t mask) { - if (mask == 0) return 0; - if (w->nfrag >= WS_MAX_FRAGS) { ws_fail(s, WS_E_FRAGS, pc, "too many fragments"); return -1; } - w->frag[w->nfrag].pc = pc; w->frag[w->nfrag].mask = mask; w->frag[w->nfrag].parked = 0; w->nfrag++; - if (w->nfrag > s->max_frags) s->max_frags = w->nfrag; - return 0; -} - -/* Runs one warp until it has no runnable fragment (finished, parked at BAR.SYNC, or stuck). - * Returns 1 when parked at BAR.SYNC, 0 when finished, -1 on error. */ -static int ws_run_warp(WsSim *s, WsWarp *w, uint32_t warp, uint32_t cx, uint32_t cy, int trace) { - const BlackwellIRProgram *p = s->p; - const uint32_t live_all = 0xffffffffu; - for (uint64_t guard = 0;; guard++) { - if (s->err) return -1; - if (guard > 2000000000ull) { ws_fail(s, WS_E_STEPS, -1, "step budget"); return -1; } - int fi = ws_pick(s, w); - if (fi < 0) { - /* nothing runnable: parked at the CTA barrier, finished, or lanes waiting at a BSYNC - * that can never complete */ - for (int i = 0; i < w->nfrag; i++) if (w->frag[i].parked) return 1; - for (int b = 0; b < WS_NBAR; b++) if (w->bar[b].valid) { - if (w->bar[b].arrived) { ws_fail(s, WS_E_STUCK, w->bar[b].target - 1, "lanes parked at BSYNC, the rest never arrive"); return -1; } - ws_fail(s, WS_E_NEVER_JOINED, w->bar[b].target - 1, "warp finished with a barrier still armed"); return -1; - } - return 0; - } - WsFrag *f = &w->frag[fi]; - int pc = f->pc; - if (pc < 0 || (size_t)pc >= p->count) { ws_fail(s, WS_E_PC, pc, "pc outside the program"); return -1; } - const BlackwellIRInsn *in = &p->insns[pc]; - uint32_t mask = f->mask; - s->warp_issues++; s->lane_issues += (uint64_t)ws_popc(mask); - if (trace) printf("W%u pc=%d op=%d mask=%08x frags=%d\n", warp, pc, (int)in->op, mask, w->nfrag); - uint32_t live = live_all & ~w->exited; - uint32_t pmask = 0; - for (int L = 0; L < WS_WARP; L++) if ((mask >> L & 1) && w->lane[L].p0) pmask |= 1u << L; - uint32_t cond = in->predicate_p0 ? (in->predicate_not ? (mask & ~pmask) : (mask & pmask)) : mask; - switch (in->op) { - case BW_IR_EXIT: { - w->exited |= cond; - f->mask = mask & ~cond; - if (f->mask == 0) ws_drop_frag(w, fi); else f->pc = pc + 1; - break; - } - case BW_IR_BRA: { - int32_t delta = (int32_t)in->imm; - uint32_t taken = cond, fall = mask & ~cond; - if (taken && delta == 0) { ws_fail(s, WS_E_SELF_BRANCH, pc, "branch to itself"); return -1; } - if (taken && fall) s->splits++; - if (taken == 0) { f->pc = pc + 1; break; } - if (fall == 0) { f->pc = pc + delta; break; } - f->mask = fall; f->pc = pc + 1; - if (ws_add_frag(s, w, pc + delta, taken) < 0) return -1; - break; - } - case BW_IR_BSSY: { - WsBar *b = &w->bar[in->bar_reg & (WS_NBAR - 1)]; - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - if (b->valid) { ws_fail(s, WS_E_BSSY_REARM, pc, "BSSY on an armed barrier"); return -1; } - b->valid = 1; b->target = pc + (int32_t)in->imm; b->members = cond; b->arrived = 0; - int armed = 0; for (int k = 0; k < WS_NBAR; k++) armed += w->bar[k].valid; - if (armed > s->peak_bars) s->peak_bars = armed; - f->pc = pc + 1; - break; - } - case BW_IR_BSYNC: { - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - WsBar *b = &w->bar[in->bar_reg]; - if (!b->valid) { ws_fail(s, WS_E_BSYNC_UNARMED, pc, "BSYNC without a BSSY"); return -1; } - if (cond & ~b->members) { ws_fail(s, WS_E_NONMEMBER, pc, "a lane at BSYNC did not execute the BSSY"); return -1; } - b->arrived |= cond; - uint32_t rest = mask & ~cond; /* a predicated-off lane walks on */ - if (rest) { f->mask = rest; f->pc = pc + 1; } else ws_drop_frag(w, fi); - if (b->arrived == (b->members & ~w->exited)) { - if (b->target != pc + 1) { ws_fail(s, WS_E_JOIN_MISMATCH, pc, "BSSY named a different join point"); return -1; } - uint32_t joined = b->arrived; b->valid = 0; b->arrived = 0; b->members = 0; - if (ws_add_frag(s, w, pc + 1, joined) < 0) return -1; - } - break; - } - case BW_IR_SHFL_DOWN: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "SHFL on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "SHFL on a split warp"); return -1; } - uint32_t src[WS_WARP]; - for (int L = 0; L < WS_WARP; L++) src[L] = ws_rd(&w->lane[L], in->src1_vreg, p); - for (int L = 0; L < WS_WARP; L++) { - int from = (in->imm & OMEGA_TC_MARK_BFLY) ? (L ^ (int)(in->imm & 31)) : L + (int)(in->imm & 31); /* BFLY placeholder (omega_blackwell_codegen_tc.h) */ - ws_wr(&w->lane[L], in->dst_vreg, from < WS_WARP ? src[from] : src[L], p); - } - f->pc = pc + 1; - break; - } - case BW_IR_HMMA_BF16: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "HMMA on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "HMMA on a split warp"); return -1; } - static const HmmaModel gb10 = { 16, 2, 0, 2, 0 }; - float A[16][16], B[16][8], C[16][8]; - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; - const WsLane *ln = &w->lane[L]; - uint32_t a4[4], b2[2], c4[4]; - for (unsigned q = 0; q < 4; q++) { a4[q] = ws_rds(ln, in->src1_vreg, in->src1_subreg + q, p); c4[q] = in->src3_vreg >= 0 ? ws_rds(ln, in->src3_vreg, in->src3_subreg + q, p) : 0u; } - for (unsigned q = 0; q < 2; q++) b2[q] = ws_rds(ln, in->src2_vreg, in->src2_subreg + q, p); - const int ar[4] = { gg, gg + 8, gg, gg + 8 }, ac[4] = { 2 * tt, 2 * tt, 2 * tt + 8, 2 * tt + 8 }; - for (unsigned q = 0; q < 4; q++) { A[ar[q]][ac[q]] = ws_u2f(a4[q] << 16); A[ar[q]][ac[q] + 1] = ws_u2f(a4[q] & 0xffff0000u); } - for (unsigned q = 0; q < 2; q++) { B[2 * tt + 8 * q][gg] = ws_u2f(b2[q] << 16); B[2 * tt + 8 * q + 1][gg] = ws_u2f(b2[q] & 0xffff0000u); } - C[gg][2 * tt] = ws_u2f(c4[0]); C[gg][2 * tt + 1] = ws_u2f(c4[1]); C[gg + 8][2 * tt] = ws_u2f(c4[2]); C[gg + 8][2 * tt + 1] = ws_u2f(c4[3]); - } - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; - for (unsigned q = 0; q < 4; q++) { - int rr = gg + (q >= 2 ? 8 : 0), nn = 2 * tt + (int)(q & 1u); - float av[16], bv[16]; for (int k = 0; k < 16; k++) { av[k] = A[rr][k]; bv[k] = B[k][nn]; } - ws_wrs(&w->lane[L], in->dst_vreg, in->dst_subreg + q, ws_f2u(hm_dot16(&gb10, av, bv, C[rr][nn])), p); - } - } - f->pc = pc + 1; - break; - } - case BW_IR_BAR_SYNC: { - if (mask != live) s->bar_split_arrivals++; - f->parked = 1; /* released by ws_run when every live lane of the CTA has arrived */ - break; - } - default: { - for (int L = 0; L < WS_WARP; L++) if (mask >> L & 1) { - ws_lane_exec(s, &w->lane[L], in, pc, warp * WS_WARP + (uint32_t)L, cx, cy); - if (s->err) return -1; - } - f->pc = pc + 1; - break; - } - } - } -} - -/* Runs every CTA of the grid. Returns s->err (0 = clean). */ -static int ws_run(WsSim *s, uint32_t grid_x, uint32_t grid_y) { - s->err = 0; s->msg[0] = 0; s->warp_issues = s->lane_issues = s->splits = s->bar_split_arrivals = 0; s->max_frags = 0; s->peak_bars = 0; - if (!s->p || s->threads == 0 || s->threads % WS_WARP || s->threads > WS_MAX_THREADS) { ws_fail(s, WS_E_OP, -1, "bad simulator configuration"); return s->err; } - static WsWarp warps[WS_MAX_WARPS]; - uint32_t nw = s->threads / WS_WARP; - for (uint32_t cy = 0; cy < grid_y && !s->err; cy++) for (uint32_t cx = 0; cx < grid_x && !s->err; cx++) { - memset(warps, 0, sizeof(WsWarp) * nw); - if (s->smem && s->smem_bytes) for (uint32_t i = 0; i + 4 <= s->smem_bytes; i += 4) { uint32_t poison = 0xfeedfaceu; memcpy(s->smem + i, &poison, 4); } - for (uint32_t w = 0; w < nw; w++) { warps[w].nfrag = 1; warps[w].frag[0].pc = 0; warps[w].frag[0].mask = 0xffffffffu; warps[w].frag[0].parked = 0; } - int trace = s->trace && cx == 0 && cy == 0; - /* Barrier phases: every warp runs until all of its fragments are parked at BAR.SYNC or it - * has finished (exited lanes do not hold the barrier up: INFERRED, see WS_E_BAR_SPLIT). - * Then every parked fragment is released and the next phase starts. */ - for (int phase = 0; ; phase++) { - int parked = 0; - for (uint32_t w = 0; w < nw && !s->err; w++) { - if (warps[w].nfrag == 0) continue; - int r = ws_run_warp(s, &warps[w], w, cx, cy, trace && w == 0); - if (r < 0) break; - if (r == 1) parked++; - } - if (s->err || parked == 0) break; /* error, or every warp finished */ - for (uint32_t w = 0; w < nw; w++) for (int i = 0; i < warps[w].nfrag; i++) - if (warps[w].frag[i].parked) { warps[w].frag[i].parked = 0; warps[w].frag[i].pc++; } - if (phase > 100000) { ws_fail(s, WS_E_BAR_TIMEOUT, -1, "barrier phases"); break; } - } - } - return s->err; -} - -#endif /* BW_WARP_SIM_PA_H */ diff --git a/tests/bw_warp_sim_tc.h b/tests/bw_warp_sim_tc.h deleted file mode 100644 index 703a8b6b0..000000000 --- a/tests/bw_warp_sim_tc.h +++ /dev/null @@ -1,401 +0,0 @@ -/* bw_warp_sim.h: host SIMT simulator for the Blackwell IR (omega #308). - * - * Models what the earlier per-thread simulators could not: a warp of 32 lanes with an - * active mask, divergence at predicated branches, structured reconvergence through the - * barrier registers (BSSY arms Bn for the lanes executing it and names the join; BSYNC - * parks arriving lanes until every armed lane that has not exited is there, then the - * warp continues as one), nested regions, and lane participation in SHFL and BAR.SYNC. - * - * A warp is a set of fragments (pc, lane mask). A predicated branch whose lanes disagree - * splits the fragment; the scheduler then runs one fragment at a time in a chosen order - * (lowest pc first or highest pc first; tests run both), which is the freedom the chip's - * scheduler also has. Fragments only merge at a BSYNC. Errors (all fatal, first one wins): - * WS_E_SHFL_SPLIT a SHFL reached by a fragment that is not the whole live warp - * (the chip reads inactive lanes: undefined; attention 2026-10-04) - * WS_E_SHFL_EXITED a SHFL on a warp some of whose lanes already exited (undefined too) - * WS_E_BAR_SPLIT (defined, never raised) a BAR.SYNC reached by a split warp is allowed: - * since Volta the CTA barrier counts arriving threads, not warps (CUDA - * programming guide, independent thread scheduling; INFERRED for sm_121, - * not chip-verified by us). The simulator parks each fragment, releases - * them together, counts the event in bar_split_arrivals, and leaves the - * fragments split: a barrier is not a reconvergence point, so a SHFL after - * it still fails with SHFL_SPLIT unless a BSYNC rejoined the warp. - * WS_E_BSYNC_UNARMED BSYNC on a barrier no BSSY armed - * WS_E_BSSY_REARM BSSY on a barrier still armed (lanes may still be heading to its join) - * WS_E_JOIN_MISMATCH BSYNC at an address other than the one the BSSY named minus one - * WS_E_NONMEMBER a lane reached BSYNC Bn without having executed its BSSY - * WS_E_STUCK lanes parked at a BSYNC that can never complete (a join was dropped, - * an exit jumped past it, or a target was corrupted) - * WS_E_NEVER_JOINED the warp finished with a barrier still armed - * WS_E_SELF_BRANCH, WS_E_PC, WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS - * Every error names the pc. Memory: global addresses are host pointers (optionally range - * checked); shared memory is a per-CTA buffer poisoned at CTA start so a read of a word - * nobody wrote shows up in the oracle comparison. - * - * Per-lane ALU semantics are those of the two earlier simulators (tests/gpu_attention_test.c, - * bench/prime_race/tests/gb10_sieve_host_test.c). EX2 and RCP are exact here; the chip's - * are approximate. LDCU64 (memory descriptor) is not modelled. */ -#ifndef BW_WARP_SIM_TC_H -#define BW_WARP_SIM_TC_H -/* bw_warp_sim_k.h (OWN-30B cut 8, 2026-10-13): tests/bw_warp_sim.h plus the system-scope opcodes the decode attention - * kernel uses (ATOMG.ADD, LDG/STG.STRONG.SYS, MEMBAR): a derived copy so the 8B lane's file stays untouched. - * The simulator runs CTAs one after another, so an atomic counter sees every earlier CTA's add. */ -/* bw_warp_sim_tc.h (OWN-30B T3, 2026-10-13): bw_warp_sim_k.h plus (a) HMMA.16816.F32.BF16 as a warp-collective operation - * computed with the GB10 arithmetic model that matched 3 x 262144 chip outputs bit for bit (tests/bw_hmma_model.h, evidence - * OWN30B-T3-HMMA-MODEL), requiring the whole live warp (like SHFL), and (b) the STG.E immediate byte offset, which the - * encoder emits and bw_warp_sim_k.h ignored. Timing (stall counts, scoreboards) is not modelled. */ - -#include "omega_blackwell_codegen.h" -#include "bw_hmma_model.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_blackwell_codegen_qmma.h" -#include "bw_qmma_model.h" -/* QMMA arithmetic used by the simulator (W-L1G): set by the test to the chip-measured model (gpu_qmma_probe_test) */ -static QmmaModel ws_qmma_model = { 32, 26, 0, 2, 0 }; /* chip-exact 262144/262144, evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13 */ -#include -#include -#include -#include -#include - -#define WS_WARP 32 -#ifndef WS_MAX_THREADS -#define WS_MAX_THREADS 256 -#endif -#define WS_MAX_WARPS (WS_MAX_THREADS / WS_WARP) -#define WS_MAX_FRAGS 64 -#define WS_NBAR BW_RECONV_MAX_BAR -#define WS_MAX_RANGES 8 - -enum { - WS_OK = 0, WS_E_SHFL_SPLIT, WS_E_SHFL_EXITED, WS_E_BAR_SPLIT, WS_E_BSYNC_UNARMED, WS_E_BSSY_REARM, - WS_E_JOIN_MISMATCH, WS_E_NONMEMBER, WS_E_STUCK, WS_E_NEVER_JOINED, WS_E_SELF_BRANCH, WS_E_PC, - WS_E_OP, WS_E_SHIFT, WS_E_MEM, WS_E_SMEM, WS_E_FRAGS, WS_E_BAR_TIMEOUT, WS_E_STEPS -}; -static const char *ws_err_name(int e) { - static const char *const n[] = { "OK", "SHFL_SPLIT", "SHFL_EXITED", "BAR_SPLIT", "BSYNC_UNARMED", "BSSY_REARM", - "JOIN_MISMATCH", "NONMEMBER", "STUCK", "NEVER_JOINED", "SELF_BRANCH", "PC", "OP", "SHIFT", "MEM", "SMEM", - "FRAGS", "BAR_TIMEOUT", "STEPS" }; - return (e >= 0 && e < (int)(sizeof n / sizeof n[0])) ? n[e] : "?"; -} - -typedef struct { uint32_t r[256]; uint8_t p0; } WsLane; -typedef struct { int pc; uint32_t mask; int parked; /* waiting at a BAR.SYNC */ } WsFrag; -typedef struct { int valid; int target; uint32_t members, arrived; } WsBar; -typedef struct { - WsLane lane[WS_WARP]; - WsFrag frag[WS_MAX_FRAGS]; - int nfrag; - WsBar bar[WS_NBAR]; - uint32_t exited; -} WsWarp; -typedef struct { uintptr_t lo, hi; } WsRange; - -typedef struct { - const BlackwellIRProgram *p; - uint32_t cbank[256]; /* constant bank 0 words (byte offset / 4) */ - uint32_t threads; /* per CTA, a multiple of 32, <= WS_MAX_THREADS */ - uint8_t *smem; /* per-CTA shared memory buffer (poisoned at CTA start) */ - uint32_t smem_bytes; - WsRange ranges[WS_MAX_RANGES]; int nranges; /* when > 0, every global access must fall in one */ - int order; /* 0 = lowest pc first, 1 = highest pc first */ - int trace; /* print every issue of warp 0 of CTA (0,0) */ - /* results */ - int err; int err_pc; char msg[200]; - uint64_t warp_issues; /* fragment-instruction issues (the chip's cost unit for divergence) */ - uint64_t lane_issues; /* lanes active over those issues */ - uint64_t splits; /* branches that split a fragment */ - uint64_t bar_split_arrivals; /* BAR.SYNC reached by a fragment that is not the whole live warp */ - int max_frags, peak_bars; -} WsSim; - -static void ws_fail(WsSim *s, int err, int pc, const char *what) { - if (s->err) return; - s->err = err; s->err_pc = pc; - snprintf(s->msg, sizeof s->msg, "%s at pc %d: %s", ws_err_name(err), pc, what ? what : ""); -} - -static uint32_t ws_rd(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[ph & 0xff]; } -static uint64_t ws_rd64(const WsLane *l, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)l->r[ph] | ((uint64_t)l->r[(ph + 1) & 0xff] << 32); } -static void ws_wr(WsLane *l, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[ph & 0xff] = x; } -static void ws_wr64(WsLane *l, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; l->r[ph] = (uint32_t)x; l->r[(ph + 1) & 0xff] = (uint32_t)(x >> 32); } -/* sub-register operands (quad/pair lanes, BlackwellIRInsn.*_subreg) */ -static uint32_t ws_rds(const WsLane *l, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : l->r[(ph + sub) & 0xff]; } -static void ws_wrs(WsLane *l, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) l->r[(ph + sub) & 0xff] = x; } -static float ws_u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t ws_f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint32_t ws_bf16_rn(uint32_t u) { if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u; return (u + 0x7fffu + ((u >> 16) & 1u)) >> 16; } /* f32 bits -> bf16 bits, round to nearest even */ -/* MUFU (the SASS EX2 / RCP / RSQ unit) flushes a subnormal result to a sign-preserving zero. Chip-observed on GB10: the SwiGLU - * reciprocal 1 / (2^t + 1) for t in (126, 128) came back as +-0 on all 101 of 101 differing elements (evidence - * OWN30B-L1G-PFGEMM-SWIGLU-FTZ-df9bd9c4, gpu_pfgemm_test host red test). Doc-inferred, not separately chip-observed: the input flush - * and the EX2 / RSQ cases follow the same rule, PTX ISA 9.7.3.13 (rcp) and 9.7.3.21 (ex2) "flushes subnormal inputs and results to - * sign-preserving zero" for the .ftz form, which is what the bare MUFU we emit is (the non-ftz PTX variants are ptxas sequences around - * MUFU; NVIDIA publishes no SASS semantics). Limit: the chip's MUFU is approximate (RCP 1 ulp, EX2 2 ulp), the model flushes a correctly - * rounded IEEE result, so right at the subnormal boundary the two can disagree 0 versus nonzero. This simulator and the pfgemm reference - * go through this helper; bw_warp_sim.h, bw_warp_sim_k.h, bw_warp_sim_pa.h and gpu_attention_test.c still model MUFU as IEEE (issue filed - * with PR #461). omega_numeric.c has its own ftz() on the library side. */ -static float ws_mufu_ftz(float f) { uint32_t u = ws_f2u(f); if ((u & 0x7f800000u) == 0u) u &= 0x80000000u; return ws_u2f(u); } -static uint32_t ws_lut3(uint32_t lut, uint32_t a, uint32_t b, uint32_t c) { - uint32_t r = 0; - for (int i = 0; i < 8; i++) if (lut >> i & 1) r |= ((i & 4) ? a : ~a) & ((i & 2) ? b : ~b) & ((i & 1) ? c : ~c); - return r; -} -static int ws_mem_ok(WsSim *s, uint64_t a, unsigned bytes, int pc) { - if (s->nranges == 0) return 1; - for (int i = 0; i < s->nranges; i++) if (a >= s->ranges[i].lo && a + bytes <= s->ranges[i].hi) return 1; - if (getenv("WS_DBG")) { fprintf(stderr, "bad addr %llx +%u pc %d\n", (unsigned long long)a, bytes, pc); for (int i = 0; i < s->nranges; i++) fprintf(stderr, " range %d %llx..%llx\n", i, (unsigned long long)s->ranges[i].lo, (unsigned long long)s->ranges[i].hi); } - ws_fail(s, WS_E_MEM, pc, "global access outside the declared buffers"); return 0; -} -static uint32_t *ws_smem(WsSim *s, uint32_t a, int pc) { - if ((a & 3) || a + 4 > s->smem_bytes) { ws_fail(s, WS_E_SMEM, pc, "shared access past the declared size"); return NULL; } - return (uint32_t *)(s->smem + a); -} -static int ws_popc(uint32_t m) { return __builtin_popcount(m); } - -/* One lane, one non-control instruction. */ -static void ws_lane_exec(WsSim *s, WsLane *l, const BlackwellIRInsn *in, int pc, uint32_t tid, uint32_t cx, uint32_t cy) { - const BlackwellIRProgram *p = s->p; - uint32_t a = ws_rds(l, in->src1_vreg, in->src1_subreg, p), b = ws_rds(l, in->src2_vreg, in->src2_subreg, p), c = ws_rds(l, in->src3_vreg, in->src3_subreg, p); - switch (in->op) { - case BW_IR_NOP: break; - case BW_IR_S2R: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; - case BW_IR_LDC: ws_wrs(l, in->dst_vreg, in->dst_subreg, s->cbank[(in->imm / 4) & 0xff], p); break; - case BW_IR_LDC64: ws_wr64(l, in->dst_vreg, (uint64_t)s->cbank[(in->imm / 4) & 0xff] | ((uint64_t)s->cbank[(in->imm / 4 + 1) & 0xff] << 32), p); break; - case BW_IR_LDCU64: case BW_IR_LDCU: break; /* memory descriptor: not modelled */ - case BW_IR_MOV_IMM: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->imm, p); break; - case BW_IR_MOV_RZ: ws_wrs(l, in->dst_vreg, in->dst_subreg, 0, p); break; - case BW_IR_IMAD: ws_wrs(l, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; - case BW_IR_IMAD_WIDE: ws_wr64(l, in->dst_vreg, (uint64_t)a * in->imm + ws_rd64(l, in->src3_vreg, p), p); break; - case BW_IR_IMAD_HI_U32: ws_wrs(l, in->dst_vreg, in->dst_subreg, (uint32_t)(((uint64_t)a * b) >> 32) + c, p); break; - case BW_IR_IADD3: ws_wrs(l, in->dst_vreg, in->dst_subreg, a + b, p); break; /* the encoder's IADD3 has Rc = RZ */ - case BW_IR_SHF_R: ws_wrs(l, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; - case BW_IR_SHF_L_U32: if (b >= 32) { ws_fail(s, WS_E_SHIFT, pc, "SHF.L.U32 amount >= 32 (not chip-verified)"); return; } ws_wrs(l, in->dst_vreg, in->dst_subreg, a << b, p); break; - case BW_IR_LOP3_AND: ws_wrs(l, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; - case BW_IR_LOP3_XOR: ws_wrs(l, in->dst_vreg, in->dst_subreg, a ^ b, p); break; - case BW_IR_LOP3_LUT: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_lut3(in->imm & 0xff, a, b, c), p); break; - case BW_IR_ISETP_GE_U32: l->p0 = a >= b; break; - case BW_IR_LDG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_LDG_E_U16: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 2, pc)) return; uint16_t x; memcpy(&x, (const void *)(uintptr_t)ad, 2); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_E: { uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = ws_rd64(l, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (!ws_mem_ok(s, ad, n, pc)) { if (getenv("WS_DBG")) fprintf(stderr, " tid %u cx %u cy %u\n", tid, cx, cy); return; } if (ad & (n - 1)) { ws_fail(s, WS_E_MEM, pc, "wide global load not naturally aligned"); return; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) ws_wrs(l, in->dst_vreg, i, x[i], p); break; } - case BW_IR_LDS128: { uint32_t ad = a + in->imm; if (ad & 15u) { ws_fail(s, WS_E_SMEM, pc, "LDS.128 address not 16-byte aligned"); return; } for (unsigned i = 0; i < 4; i++) { uint32_t *m = ws_smem(s, ad + 4u * i, pc); if (!m) return; ws_wrs(l, in->dst_vreg, i, *m, p); } break; } - case BW_IR_LDS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; ws_wrs(l, in->dst_vreg, in->dst_subreg, *m, p); break; } - case BW_IR_STS32: { uint32_t *m = ws_smem(s, a, pc); if (!m) return; *m = b; break; } - case BW_IR_FADD: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) + ws_u2f(b)), p); break; - case BW_IR_FSUB: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) - ws_u2f(b)), p); break; - case BW_IR_FMUL: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_u2f(a) * ws_u2f(b)), p); break; - case BW_IR_FFMA: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaf(ws_u2f(a), ws_u2f(b), ws_u2f(c))), p); break; - case BW_IR_FMNMX_MAX: - if (in->imm == OMEGA_TC_MARK_F2FP) { ws_wrs(l, in->dst_vreg, in->dst_subreg, (ws_bf16_rn(a) << 16) | ws_bf16_rn(b), p); break; } /* F2FP.BF16.F32.PACK_AB placeholder */ - if (in->imm == OMEGA_QMMA_MARK_F2E4) { ws_wrs(l, in->dst_vreg, in->dst_subreg, (uint32_t)qm_e4m3_rne_sat(ws_u2f(a)) << 8 | qm_e4m3_rne_sat(ws_u2f(b)), p); break; } /* F2FP.SATFINITE.E4M3 placeholder (NaN not modelled) */ - ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fmaxf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_FMNMX_MIN: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(fminf(ws_u2f(a), ws_u2f(b))), p); break; - case BW_IR_MUFU_EX2: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_mufu_ftz(exp2f(ws_mufu_ftz(ws_u2f(a))))), p); break; - case BW_IR_MUFU_RCP: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_mufu_ftz(1.0f / ws_mufu_ftz(ws_u2f(a)))), p); break; - case BW_IR_MUFU_RSQ: ws_wrs(l, in->dst_vreg, in->dst_subreg, ws_f2u(ws_mufu_ftz(1.0f / sqrtf(ws_mufu_ftz(ws_u2f(a))))), p); break; - case BW_IR_LDG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t x; memcpy(&x, (const void *)(uintptr_t)ad, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; memcpy((void *)(uintptr_t)ad, &b, 4); break; } - case BW_IR_ATOMG_ADD_STRONG_SYS: { uint64_t ad = ws_rd64(l, in->src1_vreg, p); if (!ws_mem_ok(s, ad, 4, pc)) return; uint32_t old; memcpy(&old, (const void *)(uintptr_t)ad, 4); uint32_t nw = old + b; memcpy((void *)(uintptr_t)ad, &nw, 4); ws_wrs(l, in->dst_vreg, in->dst_subreg, old, p); break; } - case BW_IR_MEMBAR_ALL_SYS: break; - default: ws_fail(s, WS_E_OP, pc, "opcode not modelled"); return; - } -} - -static int ws_pick(const WsSim *s, const WsWarp *w) { - int best = -1; - for (int i = 0; i < w->nfrag; i++) { - if (w->frag[i].mask == 0 || w->frag[i].parked) continue; - if (best < 0) { best = i; continue; } - if (s->order == 0 ? w->frag[i].pc < w->frag[best].pc : w->frag[i].pc > w->frag[best].pc) best = i; - } - return best; -} -static void ws_drop_frag(WsWarp *w, int i) { w->frag[i] = w->frag[--w->nfrag]; } -static int ws_add_frag(WsSim *s, WsWarp *w, int pc, uint32_t mask) { - if (mask == 0) return 0; - if (w->nfrag >= WS_MAX_FRAGS) { ws_fail(s, WS_E_FRAGS, pc, "too many fragments"); return -1; } - w->frag[w->nfrag].pc = pc; w->frag[w->nfrag].mask = mask; w->frag[w->nfrag].parked = 0; w->nfrag++; - if (w->nfrag > s->max_frags) s->max_frags = w->nfrag; - return 0; -} - -/* Runs one warp until it has no runnable fragment (finished, parked at BAR.SYNC, or stuck). - * Returns 1 when parked at BAR.SYNC, 0 when finished, -1 on error. */ -static int ws_run_warp(WsSim *s, WsWarp *w, uint32_t warp, uint32_t cx, uint32_t cy, int trace) { - const BlackwellIRProgram *p = s->p; - const uint32_t live_all = 0xffffffffu; - for (uint64_t guard = 0;; guard++) { - if (s->err) return -1; - if (guard > 2000000000ull) { ws_fail(s, WS_E_STEPS, -1, "step budget"); return -1; } - int fi = ws_pick(s, w); - if (fi < 0) { - /* nothing runnable: parked at the CTA barrier, finished, or lanes waiting at a BSYNC - * that can never complete */ - for (int i = 0; i < w->nfrag; i++) if (w->frag[i].parked) return 1; - for (int b = 0; b < WS_NBAR; b++) if (w->bar[b].valid) { - if (w->bar[b].arrived) { ws_fail(s, WS_E_STUCK, w->bar[b].target - 1, "lanes parked at BSYNC, the rest never arrive"); return -1; } - ws_fail(s, WS_E_NEVER_JOINED, w->bar[b].target - 1, "warp finished with a barrier still armed"); return -1; - } - return 0; - } - WsFrag *f = &w->frag[fi]; - int pc = f->pc; - if (pc < 0 || (size_t)pc >= p->count) { ws_fail(s, WS_E_PC, pc, "pc outside the program"); return -1; } - const BlackwellIRInsn *in = &p->insns[pc]; - uint32_t mask = f->mask; - s->warp_issues++; s->lane_issues += (uint64_t)ws_popc(mask); - if (trace) printf("W%u pc=%d op=%d mask=%08x frags=%d\n", warp, pc, (int)in->op, mask, w->nfrag); - uint32_t live = live_all & ~w->exited; - uint32_t pmask = 0; - for (int L = 0; L < WS_WARP; L++) if ((mask >> L & 1) && w->lane[L].p0) pmask |= 1u << L; - uint32_t cond = in->predicate_p0 ? (in->predicate_not ? (mask & ~pmask) : (mask & pmask)) : mask; - switch (in->op) { - case BW_IR_EXIT: { - w->exited |= cond; - f->mask = mask & ~cond; - if (f->mask == 0) ws_drop_frag(w, fi); else f->pc = pc + 1; - break; - } - case BW_IR_BRA: { - int32_t delta = (int32_t)in->imm; - uint32_t taken = cond, fall = mask & ~cond; - if (taken && delta == 0) { ws_fail(s, WS_E_SELF_BRANCH, pc, "branch to itself"); return -1; } - if (taken && fall) s->splits++; - if (taken == 0) { f->pc = pc + 1; break; } - if (fall == 0) { f->pc = pc + delta; break; } - f->mask = fall; f->pc = pc + 1; - if (ws_add_frag(s, w, pc + delta, taken) < 0) return -1; - break; - } - case BW_IR_BSSY: { - WsBar *b = &w->bar[in->bar_reg & (WS_NBAR - 1)]; - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - if (b->valid) { ws_fail(s, WS_E_BSSY_REARM, pc, "BSSY on an armed barrier"); return -1; } - b->valid = 1; b->target = pc + (int32_t)in->imm; b->members = cond; b->arrived = 0; - int armed = 0; for (int k = 0; k < WS_NBAR; k++) armed += w->bar[k].valid; - if (armed > s->peak_bars) s->peak_bars = armed; - f->pc = pc + 1; - break; - } - case BW_IR_BSYNC: { - if (in->bar_reg >= WS_NBAR) { ws_fail(s, WS_E_OP, pc, "barrier id"); return -1; } - WsBar *b = &w->bar[in->bar_reg]; - if (!b->valid) { ws_fail(s, WS_E_BSYNC_UNARMED, pc, "BSYNC without a BSSY"); return -1; } - if (cond & ~b->members) { ws_fail(s, WS_E_NONMEMBER, pc, "a lane at BSYNC did not execute the BSSY"); return -1; } - b->arrived |= cond; - uint32_t rest = mask & ~cond; /* a predicated-off lane walks on */ - if (rest) { f->mask = rest; f->pc = pc + 1; } else ws_drop_frag(w, fi); - if (b->arrived == (b->members & ~w->exited)) { - if (b->target != pc + 1) { ws_fail(s, WS_E_JOIN_MISMATCH, pc, "BSSY named a different join point"); return -1; } - uint32_t joined = b->arrived; b->valid = 0; b->arrived = 0; b->members = 0; - if (ws_add_frag(s, w, pc + 1, joined) < 0) return -1; - } - break; - } - case BW_IR_SHFL_DOWN: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "SHFL on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "SHFL on a split warp"); return -1; } - uint32_t src[WS_WARP]; - for (int L = 0; L < WS_WARP; L++) src[L] = ws_rd(&w->lane[L], in->src1_vreg, p); - for (int L = 0; L < WS_WARP; L++) { - int from = (in->imm & OMEGA_TC_MARK_BFLY) ? (L ^ (int)(in->imm & 31)) : L + (int)(in->imm & 31); /* BFLY placeholder (omega_blackwell_codegen_tc.h) */ - ws_wr(&w->lane[L], in->dst_vreg, from < WS_WARP ? src[from] : src[L], p); - } - f->pc = pc + 1; - break; - } - case BW_IR_HMMA_BF16: { - if (w->exited) { ws_fail(s, WS_E_SHFL_EXITED, pc, "HMMA on a warp with exited lanes"); return -1; } - if (mask != live) { ws_fail(s, WS_E_SHFL_SPLIT, pc, "HMMA on a split warp"); return -1; } - if (in->imm == OMEGA_QMMA_MARK) { /* QMMA.16832.F32.E4M3.E4M3 (fragment layout: omega_blackwell_codegen_qmma.h) */ - static float QA[16][32], QB[32][8], QC[16][8]; - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; const WsLane *ln = &w->lane[L]; - for (unsigned q = 0; q < 4; q++) { uint32_t av = ws_rds(ln, in->src1_vreg, in->src1_subreg + q, p); int r = gg + (q & 1u ? 8 : 0), k0 = 4 * tt + (q & 2u ? 16 : 0); - for (int j = 0; j < 4; j++) QA[r][k0 + j] = qm_e4m3((uint8_t)(av >> (8 * j))); } - for (unsigned q = 0; q < 2; q++) { uint32_t bv = ws_rds(ln, in->src2_vreg, in->src2_subreg + q, p); int k0 = 4 * tt + 16 * (int)q; - for (int j = 0; j < 4; j++) QB[k0 + j][gg] = qm_e4m3((uint8_t)(bv >> (8 * j))); } - for (unsigned q = 0; q < 4; q++) QC[gg + (q >= 2 ? 8 : 0)][2 * tt + (int)(q & 1u)] = in->src3_vreg >= 0 ? ws_u2f(ws_rds(ln, in->src3_vreg, in->src3_subreg + q, p)) : 0.0f; - } - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; - for (unsigned q = 0; q < 4; q++) { int rr = gg + (q >= 2 ? 8 : 0), nn = 2 * tt + (int)(q & 1u); float av[32], bv[32]; - for (int k = 0; k < 32; k++) { av[k] = QA[rr][k]; bv[k] = QB[k][nn]; } - ws_wrs(&w->lane[L], in->dst_vreg, q, ws_f2u(qm_dot32(&ws_qmma_model, av, bv, QC[rr][nn])), p); } - } - f->pc = pc + 1; - break; - } - static const HmmaModel gb10 = { 16, 2, 0, 2, 0 }; - float A[16][16], B[16][8], C[16][8]; - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; - const WsLane *ln = &w->lane[L]; - uint32_t a4[4], b2[2], c4[4]; - for (unsigned q = 0; q < 4; q++) { a4[q] = ws_rds(ln, in->src1_vreg, q, p); c4[q] = in->src3_vreg >= 0 ? ws_rds(ln, in->src3_vreg, q, p) : 0u; } - for (unsigned q = 0; q < 2; q++) b2[q] = ws_rds(ln, in->src2_vreg, q, p); - const int ar[4] = { gg, gg + 8, gg, gg + 8 }, ac[4] = { 2 * tt, 2 * tt, 2 * tt + 8, 2 * tt + 8 }; - for (unsigned q = 0; q < 4; q++) { A[ar[q]][ac[q]] = ws_u2f(a4[q] << 16); A[ar[q]][ac[q] + 1] = ws_u2f(a4[q] & 0xffff0000u); } - for (unsigned q = 0; q < 2; q++) { B[2 * tt + 8 * q][gg] = ws_u2f(b2[q] << 16); B[2 * tt + 8 * q + 1][gg] = ws_u2f(b2[q] & 0xffff0000u); } - C[gg][2 * tt] = ws_u2f(c4[0]); C[gg][2 * tt + 1] = ws_u2f(c4[1]); C[gg + 8][2 * tt] = ws_u2f(c4[2]); C[gg + 8][2 * tt + 1] = ws_u2f(c4[3]); - } - for (int L = 0; L < WS_WARP; L++) { - int gg = L / 4, tt = L % 4; - for (unsigned q = 0; q < 4; q++) { - int rr = gg + (q >= 2 ? 8 : 0), nn = 2 * tt + (int)(q & 1u); - float av[16], bv[16]; for (int k = 0; k < 16; k++) { av[k] = A[rr][k]; bv[k] = B[k][nn]; } - ws_wrs(&w->lane[L], in->dst_vreg, q, ws_f2u(hm_dot16(&gb10, av, bv, C[rr][nn])), p); - } - } - f->pc = pc + 1; - break; - } - case BW_IR_BAR_SYNC: { - if (mask != live) s->bar_split_arrivals++; - f->parked = 1; /* released by ws_run when every live lane of the CTA has arrived */ - break; - } - default: { - for (int L = 0; L < WS_WARP; L++) if (mask >> L & 1) { - ws_lane_exec(s, &w->lane[L], in, pc, warp * WS_WARP + (uint32_t)L, cx, cy); - if (s->err) return -1; - } - f->pc = pc + 1; - break; - } - } - } -} - -/* Runs every CTA of the grid. Returns s->err (0 = clean). */ -static int ws_run(WsSim *s, uint32_t grid_x, uint32_t grid_y) { - s->err = 0; s->msg[0] = 0; s->warp_issues = s->lane_issues = s->splits = s->bar_split_arrivals = 0; s->max_frags = 0; s->peak_bars = 0; - if (!s->p || s->threads == 0 || s->threads % WS_WARP || s->threads > WS_MAX_THREADS) { ws_fail(s, WS_E_OP, -1, "bad simulator configuration"); return s->err; } - static WsWarp warps[WS_MAX_WARPS]; - uint32_t nw = s->threads / WS_WARP; - for (uint32_t cy = 0; cy < grid_y && !s->err; cy++) for (uint32_t cx = 0; cx < grid_x && !s->err; cx++) { - memset(warps, 0, sizeof(WsWarp) * nw); - if (s->smem && s->smem_bytes) for (uint32_t i = 0; i + 4 <= s->smem_bytes; i += 4) { uint32_t poison = 0xfeedfaceu; memcpy(s->smem + i, &poison, 4); } - for (uint32_t w = 0; w < nw; w++) { warps[w].nfrag = 1; warps[w].frag[0].pc = 0; warps[w].frag[0].mask = 0xffffffffu; warps[w].frag[0].parked = 0; } - int trace = s->trace && cx == 0 && cy == 0; - /* Barrier phases: every warp runs until all of its fragments are parked at BAR.SYNC or it - * has finished (exited lanes do not hold the barrier up: INFERRED, see WS_E_BAR_SPLIT). - * Then every parked fragment is released and the next phase starts. */ - for (int phase = 0; ; phase++) { - int parked = 0; - for (uint32_t w = 0; w < nw && !s->err; w++) { - if (warps[w].nfrag == 0) continue; - int r = ws_run_warp(s, &warps[w], w, cx, cy, trace && w == 0); - if (r < 0) break; - if (r == 1) parked++; - } - if (s->err || parked == 0) break; /* error, or every warp finished */ - for (uint32_t w = 0; w < nw; w++) for (int i = 0; i < warps[w].nfrag; i++) - if (warps[w].frag[i].parked) { warps[w].frag[i].parked = 0; warps[w].frag[i].pc++; } - if (phase > 100000) { ws_fail(s, WS_E_BAR_TIMEOUT, -1, "barrier phases"); break; } - } - } - return s->err; -} - -#endif /* BW_WARP_SIM_TC_H */ diff --git a/tests/fake_m16_native.c b/tests/fake_m16_native.c deleted file mode 100644 index 5adc437c6..000000000 --- a/tests/fake_m16_native.c +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Simulated GB10 driver. See tests/fake_m16_native.h for what it models. - * NOT_RUN: written in cut A3b2, never compiled or executed by its author. - * - * Linked INSTEAD of physics/m16/m16_native.c and physics/nvrm/nvrm.c. The - * physics headers are still included, so the types (Nvrm, NvrmMem, - * M16NativeContext) and the prototypes are the real ones. - */ -#include "fake_m16_native.h" -#include "m16_native.h" - -#include -#include -#include -#include - - -FakeDriver fk; - -typedef struct { - uint32_t handle; - void *ptr; - uint64_t size; -} LiveAlloc; - -static LiveAlloc g_live[FK_LIVE_MAX]; -static uint32_t g_next_handle; -static void *g_chan_pb; /* the channel's own 4 KiB pushbuffer, not counted in fk.live */ - -/* ---- test-side helpers ---------------------------------------------------- */ - -void fake_release_all(void) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle != 0) { - free(g_live[i].ptr); - g_live[i].handle = 0; - g_live[i].ptr = NULL; - } - } - fk.live = 0; - free(g_chan_pb); - g_chan_pb = NULL; -} - -void fake_reset(void) -{ - fake_release_all(); - memset(&fk, 0, sizeof fk); - g_next_handle = 0; -} - -uint64_t fake_now_ms(void) -{ - return fk.clock_ms; -} - -int fake_count(int kind) -{ - int i; - int n = 0; - for (i = 0; i < fk.nev; i++) - if (fk.ev[i].kind == kind) n++; - return n; -} - -int fake_nth(int kind, int nth) -{ - int i; - int n = 0; - for (i = 0; i < fk.nev; i++) { - if (fk.ev[i].kind != kind) continue; - n++; - if (n == nth) return i; - } - return -1; -} - -/* ---- internal ------------------------------------------------------------- */ - -static void logev(int kind, uint64_t a, uint64_t b, uint64_t c) -{ - if (fk.nev >= FK_EV_MAX) { - fk.ev_overflow = 1; - return; - } - fk.ev[fk.nev].kind = kind; - fk.ev[fk.nev].a = a; - fk.ev[fk.nev].b = b; - fk.ev[fk.nev].c = c; - fk.nev++; -} - -/* A failed driver call: errno and the driver's own text, like the real nvrm does. */ -static int inject(Nvrm *rm, int rc) -{ - errno = EIO; - if (rm) (void)snprintf(rm->err, sizeof rm->err, "%s", FK_TEXT); - return rc; -} - -static void live_add(uint32_t handle, void *ptr, uint64_t size) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle == 0) { - g_live[i].handle = handle; - g_live[i].ptr = ptr; - g_live[i].size = size; - fk.live++; - return; - } - } - free(ptr); /* the table is full: more live buffers than any test needs */ -} - -/* Returns 1 if the handle was live and is now released, else 0. */ -static int live_release(uint32_t handle) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle == handle) { - free(g_live[i].ptr); - g_live[i].handle = 0; - g_live[i].ptr = NULL; - fk.live--; - return 1; - } - } - return 0; -} - -static volatile uint32_t *word_at(uint64_t va) -{ - return (volatile uint32_t *)(uintptr_t)va; -} - -/* ---- the simulated GPU: pushbuffer parser and kernel ---------------------- */ - -/* The vector kernel: QMD1 words give the program address (32, 33), the thread - * count (34 and 39), the constant bank (42, 43) and the completion semaphore - * (15, 16, 17), as written by src/omega_blackwell_qmd.c. The arguments are read - * from constant bank + 0x380: a, b, c addresses (lo, hi) and the element count. */ -static void run_kernel(const uint32_t *q) -{ - uint64_t prog = ((uint64_t)(q[33] & 0x1fffffu) << 36) | ((uint64_t)q[32] << 4); - uint64_t cb = ((uint64_t)(q[43] & 0x7ffffu) << 38) | ((uint64_t)q[42] << 6); - uint64_t threads = (uint64_t)(q[34] & 0xffffu) * (uint64_t)q[39]; - const uint32_t *args = (const uint32_t *)(uintptr_t)(cb + 0x380u); - uint32_t *a = (uint32_t *)(uintptr_t)(((uint64_t)args[1] << 32) | args[0]); - uint32_t *b = (uint32_t *)(uintptr_t)(((uint64_t)args[3] << 32) | args[2]); - uint32_t *c = (uint32_t *)(uintptr_t)(((uint64_t)args[5] << 32) | args[4]); - uint32_t n = args[6]; - uint64_t sem = ((uint64_t)q[16] << 32) | q[15]; - - if (fk.kernel_mode == FK_KERNEL_SKIP) { /* the kernel is not modelled: count the launch, release the semaphore */ - fk.kernel_ran++; - if (fk.sem_mode != FK_SYNC_NEVER) *word_at(sem) = q[17] + (fk.sem_mode == FK_SYNC_OVERSHOOT ? 1u : 0u); - return; - } - uint64_t count = n < threads ? n : threads; - uint32_t i; - int ok = 1; - - fk.kernel_ran++; - fk.kernel_threads = threads; - fk.arg_a = (uint64_t)(uintptr_t)a; - fk.arg_b = (uint64_t)(uintptr_t)b; - fk.arg_c = (uint64_t)(uintptr_t)c; - fk.prog_va_seen = prog; - fk.cbank_va_seen = cb; - fk.kernel_n = n; - if (fk.prog_expect != NULL && fk.prog_len != 0) - ok = memcmp((const void *)(uintptr_t)prog, fk.prog_expect, fk.prog_len) == 0; - fk.prog_matched = ok; - logev(FK_EV_KERNEL, threads, n, 0); - - /* What the device output holds just before the kernel runs, and whether the - * poison words collide with the correct sums. */ - fk.snap_n = n < FK_SNAP_WORDS ? n : FK_SNAP_WORDS; - for (i = 0; i < fk.snap_n; i++) { - fk.out_before[i] = c[i]; - if (c[i] == (uint32_t)(a[i] + b[i])) fk.poison_collisions++; - } - - if (ok && fk.kernel_mode != FK_KERNEL_NO_WRITE) { - if (fk.kernel_mode == FK_KERNEL_HALF) count /= 2u; - for (i = 0; i < count; i++) { - c[i] = (uint32_t)(a[i] + b[i]); - if (fk.kernel_mode == FK_KERNEL_WRONG) c[i] += 1u; - } - } - - /* Completion semaphore (RELEASE_SEMAPHORE0 of the QMD): value q[17]. */ - if (fk.sem_mode != FK_SYNC_NEVER) - *word_at(sem) = q[17] + (fk.sem_mode == FK_SYNC_OVERSHOOT ? 1u : 0u); -} - -/* SEND_PCAS_A carries the QMD address >> 8 in 32 bits (a 40-bit GPU address). The fake's GPU address is the host - * pointer, which can be wider: find the live allocation whose low 40 bits match. NULL if none does. */ -static const uint32_t *qmd_from_shifted8(uint32_t s8) -{ - const uint64_t low = (uint64_t)s8 << 8, mask40 = (1ull << 40) - 1u; - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - uint64_t base = (uint64_t)(uintptr_t)g_live[i].ptr, a = (base & ~mask40) | low; - if (g_live[i].handle == 0) continue; - if (a < base) a += 1ull << 40; - if (a >= base && a + 96u * 4u <= base + g_live[i].size) return (const uint32_t *)(uintptr_t)a; - } - return NULL; -} - -/* Walks the submitted pushbuffer. exec == 0 only collects addresses (so the - * state at the doorbell can be captured first); exec == 1 runs it. Every packet - * is a header (type 2 or 6 in bits 31:28, count in 28:16, subchannel in 15:13, - * method in 11:0 times 4) followed by count data words. */ -static void walk(const uint32_t *w, size_t n, int exec) -{ - size_t i = 0; - uint64_t dst = 0; - uint32_t line_bytes = 0; - uint32_t lines = 0; - int nrel = 0; - int flushed = 0; - - while (i < n) { - uint32_t h = w[i++]; - uint32_t type = h >> 28; - uint32_t cnt = (h >> 16) & 0x1fffu; - uint32_t subc = (h >> 13) & 7u; - uint32_t mthd = (h & 0xfffu) << 2; - const uint32_t *d; - - if ((type != 2u && type != 6u) || i + cnt > n) { - fk.pb_parse_error = 1; - return; - } - d = &w[i]; - i += cnt; - - if (subc == 1u && mthd == 0x0188u && cnt == 2u) { - dst = ((uint64_t)d[0] << 32) | d[1]; - } else if (subc == 1u && mthd == 0x0180u && cnt == 2u) { - line_bytes = d[0]; - lines = d[1]; - } else if (subc == 1u && mthd == 0x01b4u) { - if (dst == 0 || (uint64_t)cnt * 4u != (uint64_t)line_bytes * lines) { - fk.pb_parse_error = 1; - continue; - } - if (!exec) { - if (cnt == 1u) { - fk.sem_va = dst; - fk.sem_init_value = d[0]; - } - } else { - memcpy((void *)(uintptr_t)dst, d, (size_t)cnt * 4u); - if (cnt == 224u) logev(FK_EV_PB_CBANK, dst, cnt, 0); - else if (cnt == 7u) logev(FK_EV_PB_ARGS, dst, cnt, 0); - else if (cnt == 1u) logev(FK_EV_PB_SEM_INIT, dst, d[0], 0); - } - } else if (subc == 1u && mthd == 0x0318u && cnt == 98u) { - uint64_t qaddr = ((uint64_t)(d[0] & 0x1ffu) << 40) | ((uint64_t)d[1] << 8); - const uint32_t *q = d + 2; - int launch = ((d[0] >> 30) & 1u) != 0; - if (exec) { - if (qaddr == 0) { - fk.pb_parse_error = 1; - continue; - } - memcpy((void *)(uintptr_t)qaddr, q, 96u * 4u); - logev(FK_EV_PB_QMD, qaddr, (launch && (q[9] & 1u) != 0) ? 1u : 0u, 0); - if (launch && (q[9] & 1u) != 0) run_kernel(q); - } - } else if (subc == 1u && mthd == 0x02b4u && cnt == 1u) { - /* SEND_PCAS_A (clcec0.h, QMD address >> 8): a standalone QMD the command list (src/omega_gpu_cmdlist.c) - * wrote to memory. Modelled only with FK_KERNEL_SKIP: the launch releases its completion semaphore. */ - const uint32_t *q = exec && fk.kernel_mode == FK_KERNEL_SKIP ? qmd_from_shifted8(d[0]) : NULL; - if (q && (q[9] & 1u) != 0) run_kernel(q); - } else if (subc == 0u && mthd == 0x005cu && cnt == 5u) { - uint64_t addr = ((uint64_t)d[1] << 32) | d[0]; - uint32_t payload = d[2]; - uint32_t flags = d[4]; - nrel++; - if (!exec) { - if (nrel == 1) fk.marker1_va = addr; - else if (nrel == 2) fk.marker2_va = addr; - } else { - int mode = nrel == 1 ? fk.marker_mode : fk.marker2_mode; - int writes = (flags & 1u) != 0; - logev(FK_EV_PB_RELEASE, addr, payload, flags); - if (nrel <= 2) fk.release_flags[nrel - 1] = flags; - /* Modelling choice: the second release only lands if an L2 flush - * memory operation came between the two releases. */ - if (nrel == 2 && !flushed) writes = 0; - if (mode == FK_SYNC_NEVER) writes = 0; - if (writes && addr != 0) - *word_at(addr) = payload + (mode == FK_SYNC_OVERSHOOT ? 1u : 0u); - flushed = 0; - } - } else if (subc == 0u && mthd == 0x0028u && cnt == 4u) { - if (exec) { - logev(FK_EV_PB_FLUSH, d[3], 0, 0); - if (d[3] == (0x10u << 27)) flushed = 1; - } - } - /* every other packet is a setup method: ignored */ - } -} - -/* ---- the seven faked symbols ---------------------------------------------- */ - -int m16_native_open(M16NativeContext *ctx) -{ - if (!ctx) return -1; - memset(ctx, 0, sizeof *ctx); - fk.open_calls++; - logev(FK_EV_OPEN, 0, 0, 0); - if (fk.open_fail) return inject(&ctx->rm, -1); - fk.device_open = 1; - return 0; -} - -int m16_native_create_channel(M16NativeContext *ctx) -{ - void *p = NULL; - if (!ctx) return -1; - fk.channel_calls++; - logev(FK_EV_CHANNEL, 0, 0, 0); - if (fk.channel_fail) return inject(&ctx->rm, -1); - if (posix_memalign(&p, 4096, 0x1000) != 0) return -1; - memset(p, 0, 0x1000); - ctx->pb_mem.handle = ++g_next_handle; - ctx->pb_mem.size = 0x1000; - ctx->pb_mem.cpu = p; - ctx->pb_mem.va = (uint64_t)(uintptr_t)p; - g_chan_pb = p; - fk.channel_up = 1; - return 0; -} - -int nvrm_alloc(Nvrm *rm, uint64_t size, NvrmMem *out) -{ - void *p = NULL; - int mode = -1; - fk.alloc_calls++; - logev(FK_EV_ALLOC, size, 0, 0); - if (!out || size == 0 || size > (fk.alloc_max ? fk.alloc_max : 0x100000u)) return -1; - if (fk.alloc_fail_nth != 0 && fk.alloc_fail_nth == fk.alloc_calls) { - mode = fk.alloc_mode; - if (mode == FK_ALLOC_FAIL) return inject(rm, -1); - } - if (posix_memalign(&p, 4096, (size_t)size) != 0) return -1; - memset(p, 0x5a, (size_t)size); /* dirty memory */ - out->handle = ++g_next_handle; - out->size = size; - out->cpu = p; - out->va = (uint64_t)(uintptr_t)p; - live_add(out->handle, p, size); - if (fk.alloc_size_n < FK_SIZE_LOG) fk.alloc_size_log[fk.alloc_size_n] = size; - fk.alloc_size_n++; - if (fk.alloc_calls >= 1 && fk.alloc_calls <= 16) fk.alloc_va[fk.alloc_calls - 1] = out->va; - if (mode == FK_ALLOC_NO_CPU) out->cpu = NULL; - else if (mode == FK_ALLOC_SHORT) out->size = size / 2u; - else if (mode == FK_ALLOC_MISALIGNED) out->va += 0x10u; - return 0; -} - -/* Same as nvrm_alloc (the fake has no GPU cache); only counts the uncached request. */ -int nvrm_alloc_gpu_uncached(Nvrm *rm, uint64_t size, NvrmMem *out) -{ - fk.uncached_calls++; - return nvrm_alloc(rm, size, out); -} - -int nvrm_free(Nvrm *rm, NvrmMem *m) -{ - if (!m || m->handle == 0) return 0; /* a zeroed NvrmMem is a no-op (nvrm.h) */ - fk.free_calls++; - logev(FK_EV_FREE, m->handle, 0, 0); - if (fk.free_fail_nth != 0 && fk.free_fail_nth == fk.free_calls) return inject(rm, -1); - if (fk.free_size_n < FK_SIZE_LOG) fk.free_size_log[fk.free_size_n] = m->size; - fk.free_size_n++; - if (!live_release(m->handle)) { - fk.double_free++; - errno = EINVAL; - return -1; - } - memset(m, 0, sizeof *m); - errno = EBADF; /* a real free runs munmap and ioctl calls, which may change errno */ - return 0; -} - -int m16_native_submit_methods(M16NativeContext *ctx, const uint32_t *methods, size_t count) -{ - if (!ctx || !methods || count == 0) return -1; - fk.submit_calls++; - logev(FK_EV_SUBMIT, count, 0, 0); - if (!fk.channel_up || fk.submit_fail) return inject(&ctx->rm, -1); - /* Like m16_native_enqueue_methods: the words must fit the ring buffer. */ - if (count > ctx->pb_mem.size / sizeof(uint32_t) || count > FK_PB_MAX) return inject(&ctx->rm, -1); - fk.pb_mem_size = ctx->pb_mem.size; - memcpy(fk.pb, methods, count * sizeof(uint32_t)); - fk.pb_len = count; - - walk(fk.pb, count, 0); - if (fk.marker1_va != 0 && fk.sem_va != 0) { - fk.pre_marker1 = *word_at(fk.marker1_va); - fk.pre_marker2 = fk.marker2_va != 0 ? *word_at(fk.marker2_va) : 0u; - fk.pre_sem = *word_at(fk.sem_va); - fk.pre_valid = 1; - } - walk(fk.pb, count, 1); - return 0; -} - -static int which_word(volatile uint32_t *p) -{ - uint64_t a = (uint64_t)(uintptr_t)p; - if (p == NULL) return FK_W_UNKNOWN; - if (fk.marker1_va != 0 && a == fk.marker1_va) return FK_W_MARKER1; - if (fk.marker2_va != 0 && a == fk.marker2_va) return FK_W_MARKER2; - if (fk.sem_va != 0 && a == fk.sem_va) return FK_W_SEM; - return FK_W_UNKNOWN; -} - -/* The real wait is a ">=" serial compare in a loop with a deadline. The fake - * checks once and, if it is not satisfied, "waits" the whole timeout by - * advancing the fake clock. */ -int m16_native_wait_marker(volatile uint32_t *marker, uint32_t expected, uint64_t timeout_ms) -{ - int w = which_word(marker); - fk.wait_calls++; - fk.wait_n[w]++; - fk.wait_ms[w] = timeout_ms; - fk.wait_expected[w] = expected; - logev(FK_EV_WAIT, (uint64_t)w, expected, timeout_ms); - if (!marker) return -1; - if ((int32_t)(*marker - expected) >= 0) return 0; - fk.clock_ms += timeout_ms; - return -1; -} - -int m16_native_close(M16NativeContext *ctx) -{ - int rc = 0; - if (!ctx) return -1; - fk.close_calls++; - fk.live_at_close = fk.live; - logev(FK_EV_CLOSE, (uint64_t)fk.live, 0, 0); - /* Like nvrm_close: whatever is still allocated is released here. */ - fake_release_all(); - fk.device_open = 0; - if (fk.close_fail) rc = inject(&ctx->rm, -1); - return rc; -} diff --git a/tests/fake_m16_native.h b/tests/fake_m16_native.h deleted file mode 100644 index 079da0b1b..000000000 --- a/tests/fake_m16_native.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Simulated GB10 driver for the host test of the Blackwell GPU engine backend - * (tests/test_omega_blackwell_engine.c). NOT_RUN: written in cut A3b2 and never - * compiled or executed by its author. - * - * It replaces seven symbols of the real driver stack, so the REAL backend - * (src/omega_blackwell_engine.c) and the REAL vector wrapper - * (src/omega_blackwell_submit.c) run unchanged on a machine with no GPU: - * m16_native_open, m16_native_create_channel, m16_native_submit_methods, - * m16_native_wait_marker, m16_native_close, nvrm_alloc, nvrm_free. - * The signatures come from physics/m16/m16_native.h and physics/nvrm/nvrm.h at - * the physics pin; the fake file includes those headers, so a mismatch is a - * compile error. - * - * What it models (every point is a MODEL, UNVERIFIED on the chip, confidence - * about 70 percent that it matches the real driver): - * - "device" memory is host memory, GPU address equals CPU address, dirty - * (0x5a fill) so a missing zeroing step shows up; - * - the submitted pushbuffer is parsed and executed in order: DMA uploads, - * the two inline QMDs, the semaphore initial value, the release packets and - * the L2 flush memory operation (method 0x28, operation 0x10 << 27); - * - the vector kernel is a simple loop (c[i] = a[i] + b[i] for the threads the - * QMD asks for) and only runs if the program bytes in device memory are the - * bytes the test expects; - * - the second marker release is only written if an L2 flush operation - * appears between the two releases (modelling choice, see the doc); - * - m16_native_wait_marker is the real ">=" serial compare with no loop; a - * timeout advances the fake clock by the timeout so waited_ms is exact; - * - nvrm_free of a zeroed NvrmMem is a no-op that counts nothing, a real free - * zeroes the NvrmMem and clobbers errno (like a munmap or ioctl might). - */ -#ifndef FAKE_M16_NATIVE_H -#define FAKE_M16_NATIVE_H - -#include -#include - -#define FK_TEXT "fake driver says no" -#define FK_EV_MAX 512 -#define FK_SNAP_WORDS 256 -#define FK_PB_MAX 16384 /* the whole 64 KiB session ring (omega_gpu_cmdlist.c RING_WORDS), so a near-full command list fits */ - -/* Event kinds in the log (fk.ev). */ -enum { - FK_EV_OPEN = 1, - FK_EV_CHANNEL, - FK_EV_ALLOC, /* a = bytes asked */ - FK_EV_FREE, /* a = handle */ - FK_EV_SUBMIT, /* a = word count */ - FK_EV_WAIT, /* a = FK_W_*, b = expected value, c = timeout ms */ - FK_EV_CLOSE, /* a = live allocations at the moment of close */ - FK_EV_PB_CBANK, /* a = destination, b = words (224) */ - FK_EV_PB_ARGS, /* a = destination, b = words (7) */ - FK_EV_PB_SEM_INIT, /* a = destination, b = value */ - FK_EV_PB_QMD, /* a = QMD address, b = 1 if it is the kernel QMD */ - FK_EV_PB_RELEASE, /* a = address, b = payload, c = flags word */ - FK_EV_PB_FLUSH, /* a = operation word (last word of the packet) */ - FK_EV_KERNEL /* a = threads, b = element count */ -}; - -/* Which coherent word a wait looked at. */ -enum { FK_W_UNKNOWN = 0, FK_W_MARKER1, FK_W_MARKER2, FK_W_SEM, FK_W_COUNT }; - -enum { FK_ALLOC_FAIL = 0, FK_ALLOC_NO_CPU, FK_ALLOC_SHORT, FK_ALLOC_MISALIGNED }; -enum { FK_SYNC_NORMAL = 0, FK_SYNC_NEVER, FK_SYNC_OVERSHOOT }; -/* FK_KERNEL_SKIP: run no kernel at all and only release the completion semaphore (for tests that count - * driver calls with kernels the fake does not model, such as the matmul and attention launches). */ -enum { FK_KERNEL_OK = 0, FK_KERNEL_NO_WRITE, FK_KERNEL_HALF, FK_KERNEL_WRONG, FK_KERNEL_SKIP }; - -#define FK_SIZE_LOG 8192 -#define FK_LIVE_MAX 128 /* live driver buffers the fake can track at once */ - -typedef struct { - int kind; - uint64_t a; - uint64_t b; - uint64_t c; -} FakeEvent; - -typedef struct { - /* ---- faults and behaviour, set by the test after fake_reset ---- */ - int open_fail; - int channel_fail; - int submit_fail; - int close_fail; - uint64_t alloc_max; /* largest nvrm_alloc the fake grants, 0 = the default 1 MiB */ - int alloc_fail_nth; /* 1-based nvrm_alloc call that misbehaves, 0 = none */ - int alloc_mode; /* FK_ALLOC_* for that call */ - int free_fail_nth; /* 1-based real nvrm_free call that fails, 0 = none */ - int marker_mode; /* FK_SYNC_*: first marker release */ - int marker2_mode; /* FK_SYNC_*: second marker release */ - int sem_mode; /* FK_SYNC_*: kernel completion semaphore */ - int kernel_mode; /* FK_KERNEL_* */ - const void *prog_expect; /* program bytes the device memory must hold, NULL = do not check */ - size_t prog_len; - - /* ---- observations ---- */ - uint64_t clock_ms; /* the fake millisecond clock (fake_now_ms) */ - int open_calls; - int channel_calls; - int alloc_calls; - int uncached_calls; /* allocations made through nvrm_alloc_gpu_uncached (also counted in alloc_calls) */ - int free_calls; /* real frees only (a zeroed NvrmMem is not counted) */ - int close_calls; - int submit_calls; - int wait_calls; - int double_free; /* frees of a handle that was not live */ - int live; /* live backend allocations right now (not the channel's own 4 KiB buffer) */ - int live_at_close; /* live allocations when m16_native_close was called */ - int device_open; - int channel_up; - uint64_t pb_mem_size; /* ctx->pb_mem.size when the pushbuffer was submitted */ - int pb_parse_error; /* the pushbuffer had a packet the fake could not parse */ - uint32_t pb[FK_PB_MAX]; - size_t pb_len; - - uint64_t marker1_va; /* first release address, from the pushbuffer */ - uint64_t marker2_va; /* second release address, 0 with NO_C3 */ - uint64_t sem_va; /* destination of the semaphore initial value DMA */ - uint32_t sem_init_value; - uint32_t pre_marker1; /* values the GPU would see at the doorbell */ - uint32_t pre_marker2; - uint32_t pre_sem; - int pre_valid; /* the three pre_* values were captured */ - int kernel_ran; - int prog_matched; - uint64_t kernel_threads; - uint64_t kernel_n; - uint32_t out_before[FK_SNAP_WORDS]; /* device output words just before the kernel ran */ - size_t snap_n; - int poison_collisions; /* snapshot words equal to the correct sum (a bad poison word) */ - uint32_t release_flags[2]; - uint64_t alloc_va[16]; /* GPU address of the nth nvrm_alloc (1-based nth stored at [nth - 1]) */ - uint64_t arg_a; /* kernel argument addresses the device saw in the constant bank */ - uint64_t arg_b; - uint64_t arg_c; - uint64_t prog_va_seen; /* program address from QMD1 */ - uint64_t cbank_va_seen;/* constant bank address from QMD1 */ - - int wait_n[FK_W_COUNT]; - uint64_t wait_ms[FK_W_COUNT]; - uint32_t wait_expected[FK_W_COUNT]; - - uint64_t alloc_size_log[FK_SIZE_LOG]; /* size asked by the nth granted nvrm_alloc (0-based), first FK_SIZE_LOG only */ - int alloc_size_n; - uint64_t free_size_log[FK_SIZE_LOG]; /* size of the nth real nvrm_free */ - int free_size_n; - - FakeEvent ev[FK_EV_MAX]; - int nev; - int ev_overflow; -} FakeDriver; - -extern FakeDriver fk; - -/* Frees every host allocation the fake still holds (the test's own teardown, not a driver call). */ -void fake_release_all(void); -/* fake_release_all, then zero the whole state. Call at the start of every case. */ -void fake_reset(void); -/* Millisecond clock for omega_gpu_engine_test_set_clock. */ -uint64_t fake_now_ms(void); -/* Number of events of this kind in the log. */ -int fake_count(int kind); -/* Index of the nth (1-based) event of this kind, or -1. */ -int fake_nth(int kind, int nth); - -#endif diff --git a/tests/gpu_attention_test.c b/tests/gpu_attention_test.c deleted file mode 100644 index 45790315a..000000000 --- a/tests/gpu_attention_test.c +++ /dev/null @@ -1,1182 +0,0 @@ -/* gpu_attention_test: FB-1 cut 5 gate for omega_gpu_attention_api. - * - * ./gpu_attention_test --host-only refusals, codegen (both kernel families and every - * mutant), register budget, nvdisasm listing check - * ./gpu_attention_test --split-timing [--hd 128] [--spin-us N] [--out r.json] paged bf16 32q/8kv at ATTN_SPLIT_CTX - * (default 1268): 100 calls per forced split 1,2,4,8 + auto, parity - * ./gpu_attention_test --timing [--out r.json] cut 4b gate: 1 query x 32 heads x 2048 ctx, 100 calls - * through the persistent session, median under 3 ms - * ./gpu_attention_test --sweep [--out s.json] head-scaling sweep: paged bf16 at head_dim 64 over q heads - * 1..64 x every kv-head divisor x ctx 256/2048, parity + timings - * (receipt OMEGA_GPU_ATTENTION_SWEEP_V1; --sim marks host timings) - * ./gpu_attention_test --out receipt.json chip gate: every shape against the host oracle, the - * mutants (deliberately wrong kernels, all of - * 1 .. OMEGA_GPU_ATTN_MUTANT_COUNT-1) which the same - * check must catch, a negative control, timings - * - * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/backend.rs (main 8b5caed) in C: - * ReferenceCpuBackend::gqa_attention (f64 scores, max, exp, sum, 1/max(sum,1e-12), f64 weighted sum), - * TensorBackend::paged_attention (f64 online softmax token by token over the paged bf16 pool, tokens - * past the block table dropped, zeros for empty context) and paged_attention_batch (ctx <= 0 -> 0, - * table rows past the array -> empty, negative entries removed). Compiled with -ffp-contract=off. - * - * Tolerance (why): the chip accumulates the 64-term dot products, the per-chunk sums and the - * rescaled running sums in f32 (worst case about n * 2^-24 relative over n = 2048 terms, 1.2e-4), - * uses MUFU.EX2 (PTX ex2.approx: 2^-22.5 relative) for every weight and for the 32 chunk rescale - * factors, and MUFU.RCP for the final normalisation. Every output is a convex combination of V - * values of unit scale, so |error| <= 2e-4 * |want| + 2e-5 covers these with margin; the mutants - * move results by 1e-2 or more (wrong head, wrong token) or produce NaN (overflow without the max). - * The large-score case (scores up to ~300) carries the f32 rounding of the score itself into the - * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute. - */ -#include "omega_gpu_attention_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen.h" -#include "bw_warp_sim.h" /* omega #308: SIMT warp simulator for --divergent */ -#include -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -static int g_sim_mode; /* --sim: the host simulator never opens the device */ -static int g_divergent; /* --divergent (omega #308 R2): the j >= ctx branch inside a BSSY/BSYNC region */ -static uint32_t g_hd = 64; /* --hd 128: the whole battery at head_dim 128 (Qwen3-4B shapes); both simulators size the CTA from it */ -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint16_t f2bf(float f) { uint32_t u; memcpy(&u, &f, 4); uint32_t r = ((u >> 16) & 1u) + 0x7fffu; return (uint16_t)((u + r) >> 16); } -static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } - -/* ----------------------------------------------------------------- oracles */ -static void oracle_gqa(const float *q, const float *kc, const float *vc, size_t seq_len, size_t nqh, size_t nkv, size_t hd, float *out) { - if (seq_len == 0) { memset(out, 0, nqh * hd * 4); return; } - size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); - double *scores = malloc(seq_len * sizeof *scores); - for (size_t h = 0; h < nqh; h++) { - size_t kvh = h / ratio; const float *qh = q + h * hd; - for (size_t t = 0; t < seq_len; t++) { - const float *kt = kc + (t * nkv + kvh) * hd; double dot = 0.0; - for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)kt[d]; - scores[t] = dot * inv_sqrt_d; - } - double mx = -INFINITY; for (size_t t = 0; t < seq_len; t++) if (scores[t] > mx) mx = scores[t]; - double sum = 0.0; for (size_t t = 0; t < seq_len; t++) { scores[t] = exp(scores[t] - mx); sum += scores[t]; } - double inv = 1.0 / (sum > 1e-12 ? sum : 1e-12); - for (size_t t = 0; t < seq_len; t++) scores[t] *= inv; - for (size_t d = 0; d < hd; d++) { - double s = 0.0; - for (size_t t = 0; t < seq_len; t++) s += scores[t] * (double)vc[(t * nkv + kvh) * hd + d]; - out[h * hd + d] = (float)s; - } - } - free(scores); -} -/* bf16 pool in the canonical layout; the oracle's read_kv_head: element_offset(block, layer, is_value, token) + kv_head*head_dim*2 */ -static const uint16_t *kv_head(const uint8_t *pool, const OmegaGpuKvLayout *ly, size_t blk, size_t layer, int is_v, size_t tok, size_t kvh, size_t hd) { - size_t off = blk * ly->block_stride_bytes + layer * ly->layer_stride_bytes + (is_v ? ly->kv_plane_stride_bytes : 0) + tok * ly->token_stride_bytes + kvh * hd * 2; - return (const uint16_t *)(pool + off); -} -static void oracle_paged(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const uint32_t *ids, size_t nids, size_t ctx, size_t layer, - size_t nqh, size_t nkv, size_t hd, float *out) { - if (ctx == 0 || nids == 0) { memset(out, 0, nqh * hd * 4); return; } - size_t ratio = nqh / nkv; double inv_sqrt_d = 1.0 / sqrt((double)hd); size_t bs = ly->block_size; - double *acc = malloc(hd * sizeof *acc); - for (size_t h = 0; h < nqh; h++) { - size_t kvh = h / ratio; const float *qh = q + h * hd; - double m = -INFINITY, l = 0.0; for (size_t d = 0; d < hd; d++) acc[d] = 0.0; - for (size_t t = 0; t < ctx; t++) { - size_t bi = t / bs; if (bi >= nids) break; - const uint16_t *kh = kv_head(pool, ly, ids[bi], layer, 0, t % bs, kvh, hd); - const uint16_t *vh = kv_head(pool, ly, ids[bi], layer, 1, t % bs, kvh, hd); - double dot = 0.0; for (size_t d = 0; d < hd; d++) dot += (double)qh[d] * (double)bf2f(kh[d]); - double score = dot * inv_sqrt_d, mn = m > score ? m : score, alpha = exp(m - mn), beta = exp(score - mn); - l = l * alpha + beta; - for (size_t d = 0; d < hd; d++) acc[d] = acc[d] * alpha + beta * (double)bf2f(vh[d]); - m = mn; - } - double inv = l > 0.0 ? 1.0 / l : 0.0; - for (size_t d = 0; d < hd; d++) out[h * hd + d] = (float)(acc[d] * inv); - } - free(acc); -} -static void oracle_batch(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, const int32_t *tables, const int32_t *ctxs, size_t maxb, size_t nseq, - size_t layer, size_t nqh, size_t nkv, size_t hd, float *out) { - size_t stride = nqh * hd; - uint32_t *ids = malloc((maxb ? maxb : 1) * sizeof *ids); - for (size_t s = 0; s < nseq; s++) { - size_t ctx = ctxs[s] > 0 ? (size_t)ctxs[s] : 0, n = 0; - size_t total = nseq * maxb; /* the table array length as the trait sees it */ - if ((s + 1) * maxb <= total) for (size_t b = 0; b < maxb; b++) if (tables[s * maxb + b] >= 0) ids[n++] = (uint32_t)tables[s * maxb + b]; - oracle_paged(q + s * stride, pool, ly, ids, n, ctx, layer, nqh, nkv, hd, out + s * stride); - } - free(ids); -} - -static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { - size_t bad = 0; *worst = 0.0; - for (size_t i = 0; i < n; i++) { - double d = fabs((double)got[i] - (double)want[i]); - double lim = rel * fabs((double)want[i]) + abs_tol; - double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); - if (scaled > *worst) *worst = scaled; - if (!(d <= lim)) bad++; /* NaN counts as bad */ - } - return bad; -} - -/* ------------------------------------------------------------- host only */ -static int nvdisasm_check(bool f32, const char *name, const char *const *must, int n_must) { - const char *nv = "/usr/local/cuda/bin/nvdisasm"; - if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if (omega_gpu_attention_codegen_hd(f32, f32 ? 12 : 4, 3, g_hd, &k) != OMEGA_GPU_ATTN_OK) return -1; - char bin[64], lst[64], cmd[256]; - snprintf(bin, sizeof bin, "/tmp/omega_attn_%s_%d.bin", name, (int)getpid()); - snprintf(lst, sizeof lst, "/tmp/omega_attn_%s_%d.sass", name, (int)getpid()); - FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; } - fwrite(k.code, 1, k.code_size, f); fclose(f); - snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); - int rc = system(cmd); - free(k.code); - FILE *l = fopen(lst, "r"); if (!l) return -1; - char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*0")) continue; - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; - } - fclose(l); - int miss = 0; - for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } - printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - unlink(bin); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} - -static OmegaGpuKvLayout layout_for(uint32_t num_blocks, uint32_t bs, uint32_t layers, uint32_t nkv, uint32_t hd) { - OmegaGpuKvLayout ly; - ly.head_stride_bytes = (uint64_t)hd * 2; ly.token_stride_bytes = ly.head_stride_bytes * nkv; - ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes; - ly.block_stride_bytes = ly.layer_stride_bytes * layers; ly.pool_bytes = ly.block_stride_bytes * num_blocks; - ly.num_blocks = num_blocks; ly.num_layers = layers; ly.block_size = bs; - return ly; -} - -static void host_only(void) { - float q[64 * 64], kv[64 * 64], out[64 * 64]; memset(q, 0, sizeof q); memset(kv, 0, sizeof kv); - CHECK(omega_gpu_gqa_attention_f32(NULL, kv, kv, 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "NULL q refused"); - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 4, 96, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "head_dim 96 refused (TOO_LARGE)"); - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 4, 256, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "head_dim 256 refused (TOO_LARGE)"); - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 6, 2, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "gqa ratio 3 refused"); - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 1, 32, 5, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "32 q heads / 5 kv heads refused"); - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, OMEGA_GPU_ATTN_MAX_GQA_CTX + 1, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_TOO_LARGE, "context past the envelope refused"); - for (int i = 0; i < 64; i++) out[i] = 1.0f; - OmegaGpuAttnInfo info; - CHECK(omega_gpu_gqa_attention_f32(q, kv, kv, 0, 1, 1, 64, out, &info) == OMEGA_GPU_ATTN_OK && out[0] == 0.0f && out[63] == 0.0f && info.chip_calls == 0, "seq_len 0 writes zeros without a launch"); - OmegaGpuKvLayout ly = layout_for(8, 16, 2, 4, 64); - uint8_t *pool = calloc(ly.pool_bytes, 1); - uint32_t ids[2] = { 1, 9 }; - CHECK(omega_gpu_paged_attention_bf16(q, pool, &ly, ids, 2, 20, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "block id past the pool refused"); - CHECK(omega_gpu_paged_attention_bf16(q, pool, &ly, ids, 1, 20, 2, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "layer past the pool refused"); - OmegaGpuKvLayout bad = ly; bad.block_size = 12; - CHECK(omega_gpu_paged_attention_bf16(q, pool, &bad, ids, 1, 10, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "block size 12 (not a power of two) refused"); - bad = ly; bad.head_stride_bytes = 256; - CHECK(omega_gpu_paged_attention_bf16(q, pool, &bad, ids, 1, 10, 0, 32, 4, 64, out, NULL) == OMEGA_GPU_ATTN_BAD_ARGS, "layout whose head stride is not head_dim*2 refused"); - free(pool); - CHECK(strcmp(omega_gpu_attention_rc_name(OMEGA_GPU_ATTN_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); - - /* with --divergent the listing must also show the region ops (last two entries) */ - static const char *const must_bf16[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E.U16", "LDG.E ", "LDG.E.128", "LDS.128", "LDS R", "STS [R", "STG.E", "LOP3.LUT", "SHF.R.U32.HI", "BSSY", "BSYNC" }; - static const char *const must_f32[] = { "MUFU.EX2", "MUFU.RCP", "FMNMX", "BAR.SYNC", "SHFL.DOWN", "@P0 BRA", "@!P0 BRA", "LDG.E ", "LDG.E.128", "LDS.128", "LDS R", "STS [R", "STG.E", "BSSY", "BSYNC" }; - for (int f32 = 0; f32 < 2; f32++) { - const char *name = f32 ? "gqa_f32" : "paged_bf16"; - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - int rc = omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 3, g_hd, &k); - CHECK(rc == OMEGA_GPU_ATTN_OK && k.code_size > 0 && k.gpr_count <= 64, "%s kernel generated (rc %s, %zu insns, %u gprs)", name, omega_gpu_attention_rc_name(rc), k.insn_count, k.gpr_count); - printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", name, k.insn_count, k.gpr_count, k.uniform_gpr_count); - /* every mutant (1 .. COUNT-1) is a distinct kernel: different from the baseline and from - * every other mutant, named, and inside the register budget */ - uint8_t digests[OMEGA_GPU_ATTN_MUTANT_COUNT][32]; memcpy(digests[0], k.code_digest, 32); - free(k.code); - for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) { - omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)m); - memset(&k, 0, sizeof k); - int mrc = omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 3, g_hd, &k); - CHECK(mrc == OMEGA_GPU_ATTN_OK && k.gpr_count <= 64, "%s mutant %s generated (rc %s, %u gprs)", name, omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), omega_gpu_attention_rc_name(mrc), k.gpr_count); - CHECK(strcmp(omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), "?") != 0, "mutant %d has a name", m); - memcpy(digests[m], k.code_digest, 32); - free(k.code); - omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); - for (int o = 0; o < m; o++) - CHECK(memcmp(digests[o], digests[m], 32) != 0, "%s mutant %s kernel differs from %s", name, omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m), omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)o)); - } - CHECK(strcmp(omega_gpu_attention_mutant_name(OMEGA_GPU_ATTN_MUTANT_COUNT), "?") == 0, "COUNT has no name"); - /* a different shape key is a different kernel */ - memset(&k, 0, sizeof k); - CHECK(omega_gpu_attention_codegen_hd(f32 != 0, f32 ? 12 : 4, 2, g_hd, &k) == OMEGA_GPU_ATTN_OK && memcmp(digests[0], k.code_digest, 32) != 0, "%s log2gqa 2 kernel differs from log2gqa 3", name); - free(k.code); - CHECK(nvdisasm_check(f32 != 0, name, f32 ? must_f32 : must_bf16, (f32 ? 11 : 14) + (g_divergent ? 2 : 0)) == 0, "%s nvdisasm listing decodes and shows the expected instructions", name); - } -} - -/* ------------------------------------------------------------- chip gate */ -typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; uint64_t chip_ns, call_ns; uint32_t calls, unwritten; - int mutants_run, mutants_caught; char mutant_note[400]; - uint64_t kv_staged, kv_naive; uint32_t blk_logical, blk_unique; } Case; -static void case_info(Case *c, const OmegaGpuAttnInfo *i) { - c->chip_ns = i->elapsed_ns; c->call_ns = i->call_ns; c->calls = i->chip_calls; c->unwritten = i->unwritten_words; - c->kv_staged = i->kv_bytes_staged; c->kv_naive = i->kv_bytes_naive; c->blk_logical = i->kv_blocks_logical; c->blk_unique = i->kv_blocks_unique; -} -static Case g_cases[64]; static int g_ncases; -static int g_mutant_caught[OMEGA_GPU_ATTN_MUTANT_COUNT], g_mutant_run[OMEGA_GPU_ATTN_MUTANT_COUNT]; - -static void record(Case c, FILE *out) { - g_cases[g_ncases++] = c; - CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst); - CHECK(c.mutants_caught == c.mutants_run, "%s mutants caught %d of %d (%s)", c.name, c.mutants_caught, c.mutants_run, c.mutant_note); - printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " call_ns=%" PRIu64 " calls=%u unwritten=%u kv_staged=%" PRIu64 "/%" PRIu64 " blocks=%u/%u | mutants %d/%d %s\n", - c.pass && c.mutants_caught == c.mutants_run ? "PASS" : "FAIL", c.name, c.n, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.call_ns, c.calls, c.unwritten, - c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_caught, c.mutants_run, c.mutant_note); - if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"call_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u," - "\"kv_bytes_staged\":%" PRIu64 ",\"kv_bytes_naive\":%" PRIu64 ",\"kv_blocks_unique\":%u,\"kv_blocks_logical\":%u,\"mutants_run\":%d,\"mutants_caught\":%d,\"mutant_note\":\"%s\"}", - g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_attention_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.call_ns, c.calls, c.unwritten, - c.kv_staged, c.kv_naive, c.blk_unique, c.blk_logical, c.mutants_run, c.mutants_caught, c.mutant_note); -} - -static const char *mutant_name(int m) { return omega_gpu_attention_mutant_name((OmegaGpuAttnMutant)m); } - -/* Runs the mutants listed in `ms` (terminated by 0) through `run` and counts the catches. */ -typedef int (*RunFn)(void *ctx, float *got, OmegaGpuAttnInfo *info); -/* The forced launch split the battery currently holds (the engine hook has no getter); -1 = automatic. */ -static int g_forced_split = -1; -static void set_split(int log2split) { g_forced_split = log2split; omega_gpu_attention_test_set_split(log2split); } - -static void run_mutants(Case *c, const int *ms, RunFn run, void *ctx, float *got, const float *want, size_t n, double rel, double abs_tol) { - size_t pos = strlen(c->mutant_note); /* appends: a case may call this more than once */ - for (int i = 0; ms[i]; i++) { - OmegaGpuAttnInfo info; double w; - omega_gpu_attention_test_set_mutant((OmegaGpuAttnMutant)ms[i]); - /* cut J (one chunk per split): a paged call at up to 16 chunks gives every CTA one chunk, so the in-kernel - * rescale between chunks never runs and the NO_RESCALE mutant would be invisible. That mutant runs with the - * whole context in one CTA per head (forced split 1), where the rescale happens on every chunk after the first. */ - const int one_cta = ms[i] == OMEGA_GPU_ATTN_MUTANT_NO_RESCALE; - if (one_cta) omega_gpu_attention_test_set_split(0); - int rc = run(ctx, got, &info); - if (one_cta) omega_gpu_attention_test_set_split(g_forced_split); - size_t bad = compare(got, want, n, rel, abs_tol, &w); - int caught = rc != OMEGA_GPU_ATTN_OK || bad > 0; - omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); - c->mutants_run++; c->mutants_caught += caught; g_mutant_run[ms[i]]++; g_mutant_caught[ms[i]] += caught; - pos += (size_t)snprintf(c->mutant_note + pos, sizeof c->mutant_note - pos, "%s%s:%s(rc=%s,bad=%zu)", pos ? " " : "", mutant_name(ms[i]), caught ? "CAUGHT" : "MISSED", omega_gpu_attention_rc_name(rc), bad); - if (pos >= sizeof c->mutant_note) break; - } -} - -typedef struct { const float *q, *kc, *vc; uint32_t seq, nqh, nkv; } GqaCtx; -static int run_gqa(void *p, float *got, OmegaGpuAttnInfo *info) { GqaCtx *c = p; return omega_gpu_gqa_attention_f32(c->q, c->kc, c->vc, c->seq, c->nqh, c->nkv, g_hd, got, info); } -typedef struct { const float *q, *kc, *vc; uint32_t base, nr, nqh, nkv; } RowsCtx; -static int run_rows(void *p, float *got, OmegaGpuAttnInfo *info) { RowsCtx *c = p; return omega_gpu_gqa_attention_rows_f32(c->q, c->kc, c->vc, c->base, c->nr, c->nqh, c->nkv, g_hd, got, info); } -typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const uint32_t *ids; uint32_t nids, ctx, layer, nqh, nkv; } PagedCtx; -static int run_paged(void *p, float *got, OmegaGpuAttnInfo *info) { PagedCtx *c = p; return omega_gpu_paged_attention_bf16(c->q, c->pool, c->ly, c->ids, c->nids, c->ctx, c->layer, c->nqh, c->nkv, g_hd, got, info); } -typedef struct { const float *q; const uint8_t *pool; const OmegaGpuKvLayout *ly; const int32_t *tables, *ctxs; uint32_t maxb, nseq, layer, nqh, nkv; } BatchCtx; -static int run_batch(void *p, float *got, OmegaGpuAttnInfo *info) { BatchCtx *c = p; return omega_gpu_paged_attention_batch_bf16(c->q, c->pool, c->ly, c->tables, c->ctxs, c->maxb, c->nseq, c->layer, c->nqh, c->nkv, g_hd, got, info); } -/* single vs batched parity and repeat (L6-KV, CAND-0 coverage): each sequence of a batch, run - * alone through the single-sequence entry point with the batch's own rules applied by hand - * (negative table entries removed, ctx <= 0 -> 0), must equal its row of the batched output bit - * for bit (same kernel, same per-CTA inputs; the batch only shares staging). Then the batch is - * called again with the same inputs: kernel cache hit, bit-identical output, identical staging - * counters. `got` must hold the batched output of `bc`. */ -static void batch_single_repeat_checks(const char *name, const BatchCtx *bc, const float *got, const Case *c) { - size_t row = (size_t)bc->nqh * g_hd, n = (size_t)bc->nseq * row; - float *one = malloc(row * 4), *again = malloc(n * 4); - uint32_t *ids = malloc((bc->maxb ? bc->maxb : 1) * 4); - for (uint32_t s = 0; s < bc->nseq; s++) { - uint32_t nb = 0; - for (uint32_t b = 0; b < bc->maxb; b++) { int32_t v = bc->tables[(size_t)s * bc->maxb + b]; if (v >= 0) ids[nb++] = (uint32_t)v; } - uint32_t ctx = bc->ctxs[s] > 0 ? (uint32_t)bc->ctxs[s] : 0; - for (size_t i = 0; i < row; i++) one[i] = -7.0f; /* poison: an unwritten row cannot match */ - OmegaGpuAttnInfo si; - int src = omega_gpu_paged_attention_bf16(bc->q + (size_t)s * row, bc->pool, bc->ly, ids, nb, ctx, bc->layer, bc->nqh, bc->nkv, g_hd, one, &si); - CHECK(src == OMEGA_GPU_ATTN_OK && memcmp(one, got + (size_t)s * row, row * 4) == 0, - "%s: sequence %u alone (single entry point, %u blocks, ctx %u) is bit-identical to its batched row (rc=%s)", name, s, nb, ctx, omega_gpu_attention_rc_name(src)); - } - OmegaGpuAttnInfo ri; - int rrc = omega_gpu_paged_attention_batch_bf16(bc->q, bc->pool, bc->ly, bc->tables, bc->ctxs, bc->maxb, bc->nseq, bc->layer, bc->nqh, bc->nkv, g_hd, again, &ri); - CHECK(rrc == OMEGA_GPU_ATTN_OK && ri.kernel_cache_hit && memcmp(again, got, n * 4) == 0 && ri.kv_bytes_staged == c->kv_staged && ri.kv_bytes_naive == c->kv_naive - && ri.kv_blocks_unique == c->blk_unique && ri.kv_blocks_logical == c->blk_logical, - "%s: repeated batch call is a cache hit, bit-identical, same staging counters (rc=%s hit=%d staged %" PRIu64 "/%" PRIu64 ")", - name, omega_gpu_attention_rc_name(rrc), (int)ri.kernel_cache_hit, ri.kv_bytes_staged, c->kv_staged); - free(one); free(again); free(ids); -} - - -static int chip(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_V1\",\"tolerances\":{\"rel\":2e-4,\"abs\":2e-5,\"large_scores_rel\":1e-3,\"large_scores_abs\":1e-4},\"cases\":["); - uint32_t seed = 0xfb1c0005u; - const uint32_t hd = g_hd; - typedef struct { uint32_t nqh, nkv; const char *model; } Shape; - const Shape shapes64[2] = { { 32, 4, "tinyllama" }, { 32, 8, "llama32_1b" } }; - /* head_dim 128: Qwen3-4B (32 q heads, 8 kv heads, GQA 4:1) and a ratio-8 shape */ - const Shape shapes128[2] = { { 32, 8, "qwen3_4b" }, { 32, 4, "gqa8" } }; - const Shape *shapes = hd == 128 ? shapes128 : shapes64; - /* 65, 129, 300 and 1000 end in a partial 64-token chunk after whole ones: the case that - * caught the diverged-warp shuffle on the chip (2026-10-04); 1, 17, 128, 256, 2048 did not. */ - /* head_dim 128 chunks are 128 tokens: 127, 128, 129 straddle a chunk, 300 and 1000 end in a partial one */ - const uint32_t ctxs64[9] = { 1, 17, 256, 2048, 65, 128, 129, 300, 1000 }, ctxs128[9] = { 1, 17, 256, 2048, 127, 128, 129, 300, 1000 }; - const uint32_t *ctxs = hd == 128 ? ctxs128 : ctxs64; - const int no_mutants[1] = { 0 }; - - /* 1. contiguous f32 KV (gqa_attention) */ - for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) { - uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, seq = ctxs[ci]; - size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - char name[96]; snprintf(name, sizeof name, "gqa_f32_%s_%uq%ukv_ctx%u", shapes[sh].model, nqh, nkv, seq); - Case c = { .name = strdup(name), .n = n }; - OmegaGpuAttnInfo info; - GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; - c.rc = run_gqa(&gc, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - if (ci == 3) { - OmegaGpuAttnInfo i2; int rc2 = run_gqa(&gc, again, &i2); - CHECK(rc2 == OMEGA_GPU_ATTN_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name); - /* negative control: the comparison must reject a wrong expectation (kv heads swapped) */ - float *wrong = malloc(n * 4); double w2; - for (uint32_t h = 0; h < nqh; h++) memcpy(wrong + (size_t)h * hd, want + (size_t)((h + nqh / nkv) % nqh) * hd, hd * 4); - size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2); - CHECK(neg > n / 2, "%s negative control: wrong expectation flagged (%zu of %zu)", name, neg, n); - free(wrong); - static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; - run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); - } else if (ci == 1 && sh == 1) { - static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; - run_mutants(&c, ms, run_gqa, &gc, got, want, n, 2e-4, 2e-5); - } else run_mutants(&c, no_mutants, run_gqa, &gc, got, want, n, 2e-4, 2e-5); - record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(again); - } - /* 1b. rows path (prompt read, 2026-10-12): base_len tokens already in the KV, then num_rows - * query rows in one call; row i attends over base_len + i + 1 tokens. Expected per row from - * oracle_gqa on that prefix. 40 rows at 32 q heads exceed the 1024-CTA launch bound: 2 launches. */ - for (int sh = 0; sh < 2; sh++) for (int ri = 0; ri < 3; ri++) { - static const uint32_t bases[3] = { 0, 17, 300 }, nrows[3] = { 1, 5, 40 }; - uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, base = bases[ri], nr = nrows[ri], total = base + nr; - size_t row = (size_t)nqh * hd, n = row * nr, nkvs = (size_t)total * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } - for (uint32_t i = 0; i < nr; i++) oracle_gqa(q + i * row, kc, vc, base + i + 1, nqh, nkv, hd, want + i * row); - char name[96]; snprintf(name, sizeof name, "gqa_rows_f32_%s_%uq%ukv_base%u_rows%u", shapes[sh].model, nqh, nkv, base, nr); - Case c = { .name = strdup(name), .n = n }; - OmegaGpuAttnInfo info; - RowsCtx rx = { q, kc, vc, base, nr, nqh, nkv }; - c.rc = run_rows(&rx, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - if (nr == 1) { - /* one row is the single-row call, bit for bit */ - float *one = malloc(row * 4); OmegaGpuAttnInfo i1; - int rc1 = omega_gpu_gqa_attention_f32(q, kc, vc, total, nqh, nkv, hd, one, &i1); - CHECK(rc1 == OMEGA_GPU_ATTN_OK && memcmp(got, one, row * 4) == 0, "%s equals omega_gpu_gqa_attention_f32 bit for bit", name); - free(one); - } - if (nr == 40) { - CHECK(info.chip_calls == 2, "%s 40 rows x %u heads go in 2 launches (got %u)", name, nqh, info.chip_calls); - CHECK(info.kv_bytes_staged == 2 * nkvs * 4, "%s KV staged once (%" PRIu64 " bytes, expected %zu)", name, info.kv_bytes_staged, 2 * nkvs * 4); - /* negative control: every row scored over the whole context (no causal cut) must be flagged */ - float *wrong = malloc(n * 4); double w2; - for (uint32_t i = 0; i < nr; i++) oracle_gqa(q + i * row, kc, vc, total, nqh, nkv, hd, wrong + i * row); - size_t neg = compare(got, wrong, n, 2e-4, 2e-5, &w2); - CHECK(neg > n / 4, "%s negative control: non-causal expectation flagged (%zu of %zu)", name, neg, n); - free(wrong); - static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; - run_mutants(&c, ms, run_rows, &rx, got, want, n, 2e-4, 2e-5); - } else run_mutants(&c, no_mutants, run_rows, &rx, got, want, n, 2e-4, 2e-5); - record(c, out); free(q); free(kc); free(vc); free(got); free(want); - } - { /* rows path refusals */ - float d[1]; OmegaGpuAttnInfo i0; - CHECK(omega_gpu_gqa_attention_rows_f32(d, d, d, 0, 0, 32, 4, hd, d, &i0) == OMEGA_GPU_ATTN_BAD_ARGS, "rows: zero rows refused"); - CHECK(omega_gpu_gqa_attention_rows_f32(d, d, d, OMEGA_GPU_ATTN_MAX_GQA_CTX, 1, 32, 4, hd, d, &i0) == OMEGA_GPU_ATTN_TOO_LARGE, "rows: base + rows past the context bound refused"); - } - /* 2. large scores (q scaled by 200): the softmax without the running max overflows */ - { - uint32_t nqh = 32, nkv = 4, seq = 256; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -200.0f, 200.0f); /* scores ~ +-200 natural: EX2 without the max subtraction overflows f32 (2^128) */ - for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - Case c = { .name = "gqa_f32_large_scores_32q4kv_ctx256", .n = n }; - OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; - c.rc = run_gqa(&gc, got, &info); - c.bad = compare(got, want, n, 1e-3, 1e-4, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_NO_MAX, 0 }; - run_mutants(&c, ms, run_gqa, &gc, got, want, n, 1e-3, 1e-4); - record(c, out); free(q); free(kc); free(vc); free(got); free(want); - } - /* 2b. MHA (16q/16kv, ratio 1, ctx 300 = 4 full chunks + a partial one): the head-wiring - * mutants Q_ROW and OUT_ROW are observably different here (Q_ROW keeps kv head h, OUT_ROW - * lands on kv head h^1), unlike GQA where both swap the same pair of outputs. */ - { - uint32_t nqh = 16, nkv = 16, seq = 300; size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4), *got_q = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - Case c = { .name = "gqa_f32_mha_16q16kv_ctx300", .n = n }; - OmegaGpuAttnInfo info; GqaCtx gc = { q, kc, vc, seq, nqh, nkv }; - c.rc = run_gqa(&gc, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - static const int ms_q[2] = { OMEGA_GPU_ATTN_MUTANT_Q_ROW, 0 }; - static const int ms_o[3] = { OMEGA_GPU_ATTN_MUTANT_OUT_ROW, OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; - run_mutants(&c, ms_q, run_gqa, &gc, got, want, n, 2e-4, 2e-5); - memcpy(got_q, got, n * 4); /* Q_ROW output */ - run_mutants(&c, ms_o, run_gqa, &gc, got, want, n, 2e-4, 2e-5); - /* `got` now holds the KV_HEAD output; rerun OUT_ROW alone to compare it with Q_ROW */ - omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_OUT_ROW); - OmegaGpuAttnInfo i3; int rc3 = run_gqa(&gc, got, &i3); - omega_gpu_attention_test_set_mutant(OMEGA_GPU_ATTN_MUTANT_NONE); - double wq; size_t differ = compare(got, got_q, n, 2e-4, 2e-5, &wq); - CHECK(rc3 == OMEGA_GPU_ATTN_OK && differ > n / 2, "mha: Q_ROW and OUT_ROW outputs are distinct wrong answers (%zu of %zu differ)", differ, n); - record(c, out); free(q); free(kc); free(vc); free(got); free(want); free(got_q); - } - /* resident fit rule at the 32-bit edge (Qwen3-8B geometry: 36 layers, 8 kv heads x 128, block 16), no allocation */ - { - OmegaGpuKvLayout big = layout_for(4096, 16, 36, 8, 128); - uint32_t id_ok = (uint32_t)((0xffffffffull - big.layer_stride_bytes) / big.block_stride_bytes); - CHECK(omega_gpu_attention_test_resident_fits(&big, id_ok) && !omega_gpu_attention_test_resident_fits(&big, id_ok + 1), - "resident fit rule at the 4 GiB edge: block %u fits, %u does not (block stride %llu)", id_ok, id_ok + 1, - (unsigned long long)big.block_stride_bytes); - } - /* 3. paged bf16 KV, block size 16, 2 layers (layer 1 under test), scattered block ids */ - for (int sh = 0; sh < 2; sh++) for (int ci = 0; ci < 9; ci++) { - uint32_t nqh = shapes[sh].nqh, nkv = shapes[sh].nkv, ctx = ctxs[ci], bs = 16, layers = 2, layer = 1; - uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 7; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - uint32_t *ids = malloc(nblk * 4); /* a scattered permutation of the pool blocks */ - for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks; - size_t n = (size_t)nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); - char name[96]; snprintf(name, sizeof name, "paged_bf16_%s_%uq%ukv_bs%u_ctx%u", shapes[sh].model, nqh, nkv, bs, ctx); - Case c = { .name = strdup(name), .n = n }; - OmegaGpuAttnInfo info; PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; - c.rc = run_paged(&pc, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - /* Resident pool (2026-10-12): the same bytes in omega's own allocation, read in place. Same kernel, - * same data, only the addressing differs: bit-identical to the staged result just computed (which is - * the negative control: a plain host pool reports STAGED), nothing staged, info says RESIDENT. */ - if (c.rc == OMEGA_GPU_ATTN_OK) { - void *rp = NULL; - int arc = omega_gpu_attention_pool_alloc(ly.pool_bytes, &rp); - CHECK(arc == OMEGA_GPU_ATTN_OK && rp, "%s: resident pool alloc rc=%d (%s)", name, arc, omega_gpu_attention_last_error()); - if (arc == OMEGA_GPU_ATTN_OK) { - memcpy(rp, pool, ly.pool_bytes); - float *got_r = malloc(n * 4); OmegaGpuAttnInfo ri; - PagedCtx rpc = { q, rp, &ly, ids, nblk, ctx, layer, nqh, nkv }; - int rrc = run_paged(&rpc, got_r, &ri); - int same = memcmp(got_r, got, n * 4) == 0; - CHECK(rrc == OMEGA_GPU_ATTN_OK && ri.kv_source == OMEGA_GPU_ATTN_KV_RESIDENT && ri.kv_bytes_staged == 0 && - info.kv_source == OMEGA_GPU_ATTN_KV_STAGED && same, - "%s: resident pool rc=%d source=%u staged=%llu (control source=%u) bit-identical=%d", name, rrc, ri.kv_source, - (unsigned long long)ri.kv_bytes_staged, info.kv_source, same); - free(got_r); - } - omega_gpu_attention_pool_free(); - } - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - if (ci == 3) { - /* NO_MAX cannot overflow on unit-scale scores (softmax is shift invariant); it is caught by the large-score gqa case */ - static const int ms3[6] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; - run_mutants(&c, ms3, run_paged, &pc, got, want, n, 2e-4, 2e-5); - } else if (ci == 1) { - static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; - run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); - } else if (ci == 0) { - /* one token: its softmax weight is 1 whatever K says, so a K-only slot shift is invisible; KV_HEAD still shows */ - static const int ms[2] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, 0 }; - run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); - } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5); - record(c, out); free(pool); free(ids); free(q); free(got); free(want); - } - /* 3b. context split (cut F): the 32q/8kv shape at ctx 1000 under every forced split against the oracle, the - * CTA count per launch grows with the split, the automatic choice at this context is 8 (hd 128: 8 chunks) or - * 16 (hd 64: 16 chunks; cut J, one chunk per split), and a short context (ctx 100, one chunk) stays unsplit. A forced launch split at or above - * the sequence's own count gives the same bits (the extra CTAs write empty partials that add exact zeros). */ - { - uint32_t nqh = 32, nkv = 8, bs = 16, layers = 2, layer = 1; - const uint32_t cx[2] = { 1000, 100 }; - for (int ci = 0; ci < 2; ci++) { - uint32_t ctx = cx[ci], nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 3; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - uint32_t *ids = malloc(nblk * 4); - for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 5 + 1) % pool_blocks; - size_t n = (size_t)nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *auto_got = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); - PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; - OmegaGpuAttnInfo ai; - int arc = run_paged(&pc, auto_got, &ai); - uint32_t chunks = (ctx + hd - 1) / hd, want_log2 = 0; - const uint32_t gcta = nqh / omega_gpu_attention_heads_per_cta(hd, 2); /* CTAs per split: cut K groups 4 heads per CTA at hd 128 */ - while (want_log2 < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << want_log2) <= chunks) want_log2++; - CHECK(arc == OMEGA_GPU_ATTN_OK && ai.ctas_last_launch == (gcta << want_log2), - "split auto ctx %u: rc=%s ctas=%u (expected %u)", ctx, omega_gpu_attention_rc_name(arc), ai.ctas_last_launch, gcta << want_log2); - for (int ls = 0; ls <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT; ls++) { - set_split(ls); - OmegaGpuAttnInfo fi; - char name[96]; snprintf(name, sizeof name, "paged_bf16_split%d_32q8kv_ctx%u", 1 << ls, ctx); - Case c = { .name = strdup(name), .n = n }; - c.rc = run_paged(&pc, got, &fi); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &fi); - CHECK(fi.ctas_last_launch == (gcta << ls) && fi.out_bytes == (uint64_t)nqh * (1u << ls) * (hd + 2) * 4, - "%s: ctas=%u out_bytes=%llu", name, fi.ctas_last_launch, (unsigned long long)fi.out_bytes); - if ((uint32_t)ls >= want_log2) CHECK(memcmp(got, auto_got, n * 4) == 0, "%s equals the automatic choice bit for bit (a larger launch split only adds empty partials)", name); - if (ls == 1 && ci == 0) { - static const int ms[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; - run_mutants(&c, ms, run_paged, &pc, got, want, n, 2e-4, 2e-5); - } else run_mutants(&c, no_mutants, run_paged, &pc, got, want, n, 2e-4, 2e-5); - record(c, out); - } - set_split(-1); - if (ci == 1 && chunks == 1) CHECK(ai.ctas_last_launch == gcta, "ctx %u: one chunk stays unsplit (%u CTAs)", ctx, ai.ctas_last_launch); - else if (ci == 1) CHECK(ai.ctas_last_launch == (gcta << want_log2), "ctx %u: %u chunks -> %u splits (%u CTAs)", ctx, chunks, 1u << want_log2, ai.ctas_last_launch); - free(pool); free(ids); free(q); free(got); free(want); free(auto_got); - } - } - /* 4. batch: three sequences (short, empty, truncated by its table), a negative table entry, table rows of 16 */ - { - uint32_t nqh = 32, nkv = 8, bs = 16, layers = 3, layer = 2, maxb = 16, nseq = 3, pool_blocks = 40; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - int32_t *tables = malloc((size_t)nseq * maxb * 4); - for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1; - /* seq 0: ctx 40 over blocks 5, 17 (-1 in the middle closes up), 29 */ - tables[0] = 5; tables[1] = -1; tables[2] = 17; tables[3] = 29; - /* seq 1: ctx 0 with a table */ - tables[maxb + 0] = 1; - /* seq 2: ctx 100 but only 4 blocks (64 tokens used) */ - tables[2 * maxb + 0] = 30; tables[2 * maxb + 1] = 2; tables[2 * maxb + 2] = 33; tables[2 * maxb + 3] = 11; - int32_t ctxs2[3] = { 40, 0, 100 }; - size_t n = (size_t)nseq * nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - oracle_batch(q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv, hd, want); - Case c = { .name = "paged_bf16_batch_3seq_32q8kv_ctx40_0_100", .n = n }; - OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs2, maxb, nseq, layer, nqh, nkv }; - c.rc = run_batch(&bc, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - int zeros = 1; for (size_t i = 0; i < (size_t)nqh * hd; i++) if (got[(size_t)nqh * hd + i] != 0.0f) zeros = 0; - CHECK(zeros, "batch: the empty sequence is all zeros"); - batch_single_repeat_checks(c.name, &bc, got, &c); - static const int ms[5] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, OMEGA_GPU_ATTN_MUTANT_Q_ROW, OMEGA_GPU_ATTN_MUTANT_OUT_ROW, 0 }; - run_mutants(&c, ms, run_batch, &bc, got, want, n, 2e-4, 2e-5); - /* all 7 referenced blocks are distinct here, so dedupe stages exactly the naive figure */ - CHECK(c.blk_logical == 7 && c.blk_unique == 7 && c.kv_staged == c.kv_naive && c.kv_staged == 7ull * ly.layer_stride_bytes, "batch: 7 distinct blocks staged once each (%u/%u, %" PRIu64 " bytes)", c.blk_unique, c.blk_logical, c.kv_staged); - record(c, out); free(pool); free(tables); free(q); free(got); free(want); - } - /* 5. branch-heavy batch (attention hardening cut): four sequences share the same 10 physical - * prefix blocks (160 tokens, scattered ids) and own private tails of 1..3 blocks ending in a - * partial 64-token chunk. The shared prefix must be staged once per launch, keyed by the - * physical block id. Two head shapes: 8q/2kv puts all four sequences in one launch - * (unique = 10 + 9 tails), 32q/8kv splits them two per launch (unique = 2*10 + 9). - * Negative control: the legacy per-sequence staging (test hook) copies the prefix four - * times and the byte-reduction check must flag it. */ - for (int sh = 0; sh < 2; sh++) { - uint32_t nqh = sh ? 32 : 8, nkv = sh ? 8 : 2, bs = 16, layers = 2, layer = 1, nseq = 4, prefix_blocks = 10, pool_blocks = 64; - uint32_t expect_unique = sh ? 2 * prefix_blocks + 9 : prefix_blocks + 9; - uint32_t maxb = prefix_blocks + 3; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - int32_t *tables = malloc((size_t)nseq * maxb * 4); - for (size_t i = 0; i < (size_t)nseq * maxb; i++) tables[i] = -1; - const uint32_t tails[4] = { 1, 2, 3, 3 }; /* private blocks per sequence: 9 in all */ - const int32_t ctxs5[4] = { 165, 180, 193, 207 }; /* 160 + 5, 20, 33, 47: every last chunk partial */ - for (uint32_t s = 0; s < nseq; s++) { - for (uint32_t b = 0; b < prefix_blocks; b++) tables[s * maxb + b] = (int32_t)((b * 5 + 7) % pool_blocks); /* same scattered physical prefix */ - for (uint32_t b = 0; b < tails[s]; b++) tables[s * maxb + prefix_blocks + b] = (int32_t)(50 + s * 3 + b); /* private, distinct */ - } - size_t n = (size_t)nseq * nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *legacy = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - oracle_batch(q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv, hd, want); - char name[96]; snprintf(name, sizeof name, "paged_bf16_shared_prefix_4seq_%uq%ukv_10pre", nqh, nkv); - Case c = { .name = strdup(name), .n = n }; - OmegaGpuAttnInfo info; BatchCtx bc = { q, pool, &ly, tables, ctxs5, maxb, nseq, layer, nqh, nkv }; - c.rc = run_batch(&bc, got, &info); - c.bad = compare(got, want, n, 2e-4, 2e-5, &c.worst); - c.pass = c.rc == OMEGA_GPU_ATTN_OK && c.bad == 0; case_info(&c, &info); - uint32_t logical = 4 * prefix_blocks + 9; - CHECK(c.blk_logical == logical && c.blk_unique == expect_unique, "%s: %u logical references, %u unique staged (expected %u/%u)", name, c.blk_logical, c.blk_unique, logical, expect_unique); - CHECK(c.kv_naive == (uint64_t)logical * ly.layer_stride_bytes && c.kv_staged == (uint64_t)expect_unique * ly.layer_stride_bytes && c.kv_staged < c.kv_naive, - "%s: staged %" PRIu64 " < naive %" PRIu64 " bytes (saved %" PRIu64 ")", name, c.kv_staged, c.kv_naive, c.kv_naive - c.kv_staged); - /* cut F: the output traffic is the partials, launch split = the largest own split in the call (cut J: hd 64: ctx 193 and 207 are 4 chunks, 4 splits; hd 128: 2 chunks, 2 splits) */ - uint32_t ls_max = 0; - for (uint32_t s = 0; s < nseq; s++) { uint32_t x = ((uint32_t)ctxs5[s] + hd - 1) / hd, l = 0; while (l < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << l) <= x) l++; if (l > ls_max) ls_max = l; } - const uint64_t out_expect = (uint64_t)nseq * nqh * (1u << ls_max) * (hd + 2) * 4; - CHECK(info.kv_source == OMEGA_GPU_ATTN_KV_STAGED && info.q_bytes == n * 4 && info.out_bytes == out_expect && info.tab_bytes > 0, "%s: q/out/table traffic accounted (q=%" PRIu64 " out=%" PRIu64 " tab=%" PRIu64 ")", name, info.q_bytes, info.out_bytes, info.tab_bytes); - /* negative control: legacy per-sequence staging duplicates the shared prefix; same answer, more bytes */ - omega_gpu_attention_test_set_dedupe(false); - OmegaGpuAttnInfo li; int lrc = run_batch(&bc, legacy, &li); - omega_gpu_attention_test_set_dedupe(true); - double lw; size_t lbad = compare(legacy, want, n, 2e-4, 2e-5, &lw); - CHECK(lrc == OMEGA_GPU_ATTN_OK && lbad == 0, "%s legacy staging: parity (rc=%s bad=%zu)", name, omega_gpu_attention_rc_name(lrc), lbad); - CHECK(li.kv_blocks_unique == logical && li.kv_bytes_staged == li.kv_bytes_naive && li.kv_bytes_staged > c.kv_staged, - "%s negative control: duplicated prefix staging is flagged (legacy staged %" PRIu64 " == naive %" PRIu64 ", dedupe %" PRIu64 ")", name, li.kv_bytes_staged, li.kv_bytes_naive, c.kv_staged); - CHECK(memcmp(got, legacy, n * 4) == 0, "%s: dedupe and legacy staging are bit-identical", name); - batch_single_repeat_checks(name, &bc, got, &c); - static const int ms5[3] = { OMEGA_GPU_ATTN_MUTANT_KV_HEAD, OMEGA_GPU_ATTN_MUTANT_SLOT, 0 }; - run_mutants(&c, ms5, run_batch, &bc, got, want, n, 2e-4, 2e-5); - record(c, out); free(pool); free(tables); free(q); free(got); free(want); free(legacy); - } - /* every mutant the API knows (1 .. COUNT-1) ran at least once and was caught every time; - * a mutant added to the enum without a battery entry fails here */ - for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) { - CHECK(g_mutant_run[m] > 0 && g_mutant_caught[m] == g_mutant_run[m], "mutant %s caught %d of %d runs", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); - printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); - } - CHECK(omega_gpu_session_open_count() == (g_sim_mode ? 0u : 1u), "device opened %s for the battery (opens=%u)", g_sim_mode ? "never (simulator)" : "once", omega_gpu_session_open_count()); - printf("device_opens=%u\n", omega_gpu_session_open_count()); - if (out) { - fprintf(out, "],\"mutant_count\":%d,\"mutants\":{", OMEGA_GPU_ATTN_MUTANT_COUNT - 1); - for (int m = 1; m < OMEGA_GPU_ATTN_MUTANT_COUNT; m++) fprintf(out, "%s\"%s\":{\"run\":%d,\"caught\":%d}", m > 1 ? "," : "", mutant_name(m), g_mutant_run[m], g_mutant_caught[m]); - fprintf(out, "},\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL"); - fclose(out); - } - return 0; -} - -/* ------------------------------------------------------------ host simulator - * Executes the allocated IR program (physical registers, so the register allocator's - * loop handling is under test too) for every CTA of a launch: 64 threads, 1 KB shared, - * host pointers as addresses, SHFL and BAR as lockstep points (all threads of the CTA - * must sit at the same instruction). EX2 and RCP are exact here; the chip's are approximate. */ -/* path: hash of every branch decision so far. The attention kernels use no reconvergence - * region (the IR has BSSY/BSYNC since omega #310, omega_bw_reconv.h; the --divergent mode - * below covers them), so once a warp splits it may stay split on the chip, and a - * SHFL reading an inactive lane is undefined (CUDA guide, warp shuffle functions). Every - * SHFL therefore requires one path across the warp, or the simulator stops with error 7. */ -typedef struct { uint32_t r[256]; int pc; int p0; int done; uint64_t path; } SimThr; -static uint32_t sim_cbank[256]; -static uint8_t sim_shared[8192]; -#define SIM_TMAX 128 -#define SIM_T ((int)g_hd) /* threads per CTA = head_dim */ -static uint32_t g_smem_cap; /* negative control: pretend the QMD declared this many bytes (0 = the real 16 * head_dim) */ -#define SIM_SMEM (g_smem_cap ? g_smem_cap : omega_gpu_attention_test_shared_bytes()) /* the shared memory the QMD declares for this kernel (launcher: shared_bytes_for) */ -static int g_sim_err; -static int g_trace, g_trace_launch; static uint32_t g_trace_cx; -static uint32_t rd(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : t->r[ph & 0xff]; } -static uint64_t rd64(const SimThr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)t->r[ph] | ((uint64_t)t->r[ph + 1] << 32); } -static void wr(SimThr *t, int v, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) t->r[ph & 0xff] = x; } -static void wr64(SimThr *t, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; t->r[ph] = (uint32_t)x; t->r[ph + 1] = (uint32_t)(x >> 32); } -static uint32_t rds(const SimThr *t, int v, unsigned sub, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v]; return ph < 0 ? 0 : t->r[(ph + sub) & 0xff]; } -static void wrs(SimThr *t, int v, unsigned sub, uint32_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v]; if (ph >= 0) t->r[(ph + sub) & 0xff] = x; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u_(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -/* run one thread until it reaches a SHFL or BAR (not executed) or EXIT; returns 1 if parked at a sync op */ -static int sim_step(SimThr *t, const BlackwellIRProgram *p, uint32_t tid, uint32_t cx, uint32_t cy) { - for (int guard = 0; guard < 50000000; guard++) { - if (t->done) return 0; - if (t->pc < 0 || (size_t)t->pc >= p->count) { g_sim_err = 1; t->done = 1; return 0; } - const BlackwellIRInsn *in = &p->insns[t->pc]; - uint32_t a = rds(t, in->src1_vreg, in->src1_subreg, p), b = rds(t, in->src2_vreg, in->src2_subreg, p), c = rds(t, in->src3_vreg, in->src3_subreg, p); - switch (in->op) { - case BW_IR_SHFL_DOWN: case BW_IR_BAR_SYNC: return 1; - case BW_IR_EXIT: if (!in->predicate_p0 || t->p0) { t->done = 1; return 0; } break; - case BW_IR_BRA: { - int take = !in->predicate_p0 || (in->predicate_not ? !t->p0 : t->p0); - t->path = t->path * 1000003u + (((uint64_t)t->pc << 1) | (uint64_t)take); - if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; t->done = 1; return 0; } t->pc += (int32_t)in->imm; continue; } - break; } - case BW_IR_MOV_IMM: wrs(t, in->dst_vreg, in->dst_subreg, in->imm, p); break; - case BW_IR_MOV_RZ: wrs(t, in->dst_vreg, in->dst_subreg, 0, p); break; - case BW_IR_S2R: wrs(t, in->dst_vreg, in->dst_subreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cx : in->imm == BW_SR_CTAID_Y ? cy : 0, p); break; - case BW_IR_LDC: wrs(t, in->dst_vreg, in->dst_subreg, sim_cbank[in->imm / 4], p); break; - case BW_IR_LDC64: wr64(t, in->dst_vreg, (uint64_t)sim_cbank[in->imm / 4] | ((uint64_t)sim_cbank[in->imm / 4 + 1] << 32), p); break; - case BW_IR_LDCU64: break; /* memory descriptor: not modelled */ - case BW_IR_IMAD: wrs(t, in->dst_vreg, in->dst_subreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; - case BW_IR_IMAD_WIDE: wr64(t, in->dst_vreg, (uint64_t)a * in->imm + rd64(t, in->src3_vreg, p), p); break; - case BW_IR_IADD3: wrs(t, in->dst_vreg, in->dst_subreg, a + b, p); break; - case BW_IR_SHF_R: wrs(t, in->dst_vreg, in->dst_subreg, a >> (in->imm & 31), p); break; - case BW_IR_LOP3_AND: wrs(t, in->dst_vreg, in->dst_subreg, a & in->imm, p); break; - case BW_IR_LOP3_XOR: wrs(t, in->dst_vreg, in->dst_subreg, a ^ b, p); break; - case BW_IR_ISETP_GE_U32: t->p0 = a >= b; break; - case BW_IR_LDG_E: { uint32_t x; memcpy(&x, (const void *)(uintptr_t)rd64(t, in->src1_vreg, p), 4); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_LDG_E_U16: { uint16_t x; memcpy(&x, (const void *)(uintptr_t)rd64(t, in->src1_vreg, p), 2); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STG_E: memcpy((void *)(uintptr_t)rd64(t, in->src1_vreg, p), &b, 4); break; - case BW_IR_LDG_E_64: case BW_IR_LDG_E_128: { unsigned n = in->op == BW_IR_LDG_E_64 ? 8u : 16u; uint64_t ad = rd64(t, in->src1_vreg, p) + (uint64_t)(int64_t)(int32_t)in->imm; if (ad & (n - 1)) { g_sim_err = 5; t->done = 1; return 0; } uint32_t x[4]; memcpy(x, (const void *)(uintptr_t)ad, n); for (unsigned i = 0; i < n / 4; i++) wrs(t, in->dst_vreg, i, x[i], p); break; } - case BW_IR_LDS128: { uint32_t ad = a + in->imm; if ((ad & 15u) || ad + 16 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } for (unsigned i = 0; i < 4; i++) { uint32_t x; memcpy(&x, sim_shared + ad + 4u * i, 4); wrs(t, in->dst_vreg, i, x, p); } break; } - case BW_IR_LDS32: { uint32_t x; if (a + 4 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } memcpy(&x, sim_shared + a, 4); wrs(t, in->dst_vreg, in->dst_subreg, x, p); break; } - case BW_IR_STS32: if (a + 4 > SIM_SMEM) { g_sim_err = 3; t->done = 1; return 0; } memcpy(sim_shared + a, &b, 4); break; - case BW_IR_FADD: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) + u2f(b)), p); break; - case BW_IR_FSUB: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) - u2f(b)), p); break; - case BW_IR_FMUL: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(u2f(a) * u2f(b)), p); break; - case BW_IR_FFMA: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(fmaf(u2f(a), u2f(b), u2f(c))), p); break; - case BW_IR_FMNMX_MAX: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(fmaxf(u2f(a), u2f(b))), p); break; - case BW_IR_MUFU_EX2: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(exp2f(u2f(a))), p); break; - case BW_IR_MUFU_RCP: wrs(t, in->dst_vreg, in->dst_subreg, f2u_(1.0f / u2f(a)), p); break; - default: g_sim_err = 100 + (int)in->op; t->done = 1; return 0; - } - if (g_trace && tid == 0 && cx == g_trace_cx && cy == 0 && g_trace_launch == 1) { uint32_t dv = rd(t, in->dst_vreg, p); printf("T pc=%d op=%d dst=v%d(r%d)=%08x f=%g p0=%d a=%08x b=%08x c=%08x\n", t->pc, (int)in->op, in->dst_vreg, in->dst_vreg >= 0 ? p->regalloc.vreg_to_phys[in->dst_vreg] : -1, dv, u2f(dv), t->p0, a, b, c); } - t->pc++; - } - g_sim_err = 4; t->done = 1; return 0; -} -static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) { - const BlackwellIRProgram *p = progv; - memset(sim_cbank, 0, sizeof sim_cbank); - uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab; - sim_cbank[0x380 / 4] = (uint32_t)qa; sim_cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32); - sim_cbank[0x388 / 4] = (uint32_t)pa; sim_cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32); - sim_cbank[0x390 / 4] = (uint32_t)oa; sim_cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32); - sim_cbank[0x398 / 4] = (uint32_t)ta; sim_cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32); - memcpy(&sim_cbank[0x3a0 / 4], L->params, sizeof L->params); - uint32_t *outw = L->out; for (size_t i = 0; i < L->out_bytes / 4; i++) outw[i] = 0xffbadbadu; - g_sim_err = 0; - static SimThr th[SIM_TMAX]; - g_trace_launch++; if (getenv("ATTN_SIM_TRACE")) { g_trace = 1; g_trace_cx = (uint32_t)atoi(getenv("ATTN_SIM_TRACE")); } - for (uint32_t cy = 0; cy < L->grid_y && !g_sim_err; cy++) for (uint32_t cx = 0; cx < L->grid_x && !g_sim_err; cx++) { - memset(th, 0, sizeof th); memset(sim_shared, 0, sizeof sim_shared); - for (;;) { - int parked = 0, alive = 0; - for (int i = 0; i < SIM_T; i++) { if (th[i].done) continue; alive++; parked += sim_step(&th[i], p, (uint32_t)i, cx, cy); } - if (g_sim_err) break; - if (alive == 0) break; - if (parked == 0) continue; /* every live thread exited this round */ - if (parked != alive) { g_sim_err = 5; break; } /* a thread exited while others wait at a barrier */ - int pc = -1; - for (int i = 0; i < SIM_T; i++) if (!th[i].done) { if (pc < 0) pc = th[i].pc; else if (th[i].pc != pc) g_sim_err = 6; } - if (g_sim_err) break; - const BlackwellIRInsn *in = &p->insns[pc]; - if (in->op == BW_IR_SHFL_DOWN) { - for (int i = 0; i < SIM_T; i++) if (!th[i].done && !th[i & ~31].done && th[i].path != th[i & ~31].path) g_sim_err = 7; - if (g_sim_err) break; - uint32_t src[SIM_TMAX]; - for (int i = 0; i < SIM_T; i++) src[i] = rd(&th[i], in->src1_vreg, p); - for (int i = 0; i < SIM_T; i++) { int lane = i & 31, from = lane + (int)(in->imm & 31); wr(&th[i], in->dst_vreg, from < 32 ? src[(i & ~31) + from] : src[i], p); } - } - for (int i = 0; i < SIM_T; i++) th[i].pc++; - } - } - uint32_t unwritten = 0; for (size_t i = 0; i < L->out_bytes / 4; i++) if (outw[i] == 0xffbadbadu) unwritten++; - if (info) { info->chip_calls++; info->unwritten_words += unwritten; info->ctas_last_launch = L->grid_x * L->grid_y; info->threads_per_cta = SIM_T; } - if (g_sim_err) { printf("simulator error %d\n", g_sim_err); return OMEGA_GPU_ATTN_CHIP_FAIL; } - return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; -} - - -/* ---------------------------------------------------- timing (cut 4b) */ -/* One query step of TinyLlama attention at context 2048 (32 q heads, 4 kv heads, - * f32 KV) 100 times through the persistent session, every call checked against the - * oracle; gate: median wall time per call under 3 ms, one device open per process. */ -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } -/* --split-timing: the paged bf16 decode shape (32 q / 8 kv heads at the current head_dim, one sequence, context - * ATTN_SPLIT_CTX, default 1268: the campaign's document tasks) through the persistent session, 100 calls per - * forced launch split 1, 2, 4, 8 and the automatic choice; median wall and mean chip time per call, every call - * against the oracle. A measurement for the decode-speed work (2026-10-12): whether the kernel's time at this - * context falls with more CTAs per (sequence, head) or stays flat (bandwidth bound: the four query heads of a - * kv head each read its slice). */ -static int split_timing(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - enum { N = 100 }; - const uint32_t hd = g_hd, nqh = 32, nkv = 8, bs = 16, layers = 2, layer = 1; - const char *ce = getenv("ATTN_SPLIT_CTX"); - const uint32_t ctx = ce && atoi(ce) > 0 ? (uint32_t)atoi(ce) : 1268u; - const uint32_t nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 3; - uint32_t seed = 0x5b17c0deu; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - uint32_t *ids = malloc(nblk * 4); - for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 5 + 1) % pool_blocks; - const size_t n = (size_t)nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); - PagedCtx pc = { q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv }; - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_SPLIT_TIMING_V1\",\"hd\":%u,\"ctx\":%u,\"calls\":%d,\"spin_us\":%u,\"cases\":[", - hd, ctx, N, omega_gpu_session_spin_us()); - int first = 1; - for (int ls = -1; ls <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT; ls++) { - set_split(ls); - OmegaGpuAttnInfo info; - int rc0 = run_paged(&pc, got, &info); /* warm-up: opens the device, generates this split's kernel */ - CHECK(rc0 == OMEGA_GPU_ATTN_OK, "split-timing split=%d first call rc=%s err=\"%s\"", ls, omega_gpu_attention_rc_name(rc0), omega_gpu_attention_last_error()); - double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; - for (int i = 0; i < N; i++) { - double t0 = now_ms(); - int rc = run_paged(&pc, got, &info); - samples[i] = now_ms() - t0; - double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); - if (w > worst) worst = w; - bad_total += bad; chip_sum += info.elapsed_ns; - if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++; - } - qsort(samples, N, sizeof samples[0], cmp_d); - const double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; - const int pass = ok_calls == N && bad_total == 0; - CHECK(pass, "split-timing split=%d ctx=%u ok_calls=%d/%d violations=%zu", ls, ctx, ok_calls, N, bad_total); - printf("%s split-timing split=%s ctas=%u ctx=%u ok_calls=%d/%d worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f\n", - pass ? "PASS" : "FAIL", ls < 0 ? "auto" : (const char *[]){ "1", "2", "4", "8", "16" }[ls], info.ctas_last_launch, ctx, ok_calls, N, worst, - median, p90, mn, mx, chip_sum / 1e3 / N); - if (out) fprintf(out, "%s{\"split\":%d,\"ctas\":%u,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"pass\":%s}", - first ? "" : ",", ls, info.ctas_last_launch, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, pass ? "true" : "false"); - first = 0; - } - set_split(-1); - free(pool); free(ids); free(q); free(got); free(want); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_SPLIT_TIMING_PASS" : "OMEGA_GPU_ATTENTION_SPLIT_TIMING_FAIL"); fclose(out); } - return 0; -} - -static int timing(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - enum { N = 100 }; - const uint32_t hd = 64, nqh = 32, nkv = 4, seq = 2048; - const char *name = "gqa_f32_tinyllama_32q4kv_ctx2048"; - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_TIMING_V1\",\"gate_median_ms\":3.0,\"calls\":%d,\"cases\":[", N); - uint32_t seed = 0xfb1c004bu; - size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; - OmegaGpuAttnInfo info; - /* warm-up: the first call opens the device and generates the kernel (not timed) */ - int rc0 = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); - double first_ms = info.call_ns / 1e6; - CHECK(rc0 == OMEGA_GPU_ATTN_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_attention_rc_name(rc0), omega_gpu_attention_last_error()); - for (int i = 0; i < N; i++) { - double t0 = now_ms(); - int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); - samples[i] = now_ms() - t0; - double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); - if (w > worst) worst = w; - bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; - if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++; - } - qsort(samples, N, sizeof samples[0], cmp_d); - double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; - uint32_t opens = omega_gpu_session_open_count(); - int pass = ok_calls == N && bad_total == 0 && median < 3.0 && opens == 1; - CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_attention_rc_name(rc_last), omega_gpu_attention_last_error()); - printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", - pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); - if (out) fprintf(out, "{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", - name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); - free(q); free(kc); free(vc); free(got); free(want); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_TIMING_PASS" : "OMEGA_GPU_ATTENTION_TIMING_FAIL"); fclose(out); } - return 0; -} - -/* ------------------------------------------------ head-scaling sweep (attention hardening cut) - * `--sweep [--out sweep.json]`: the production paged bf16 path at head_dim 64 over query-head - * counts 1, 2, 4, 8, 16, 24, 32, 64 and every divisor as the kv-head count, at context 256 - * (latency) and 2048 (bandwidth), block size 16, scattered block ids. Points whose GQA ratio - * is not a power of two are mathematically legal (the generic contract allows them) but - * outside the current kernel envelope (codegen selects the kv head with a shift): they are - * called anyway, must be refused with BAD_ARGS, and are recorded as - * "unsupported_by_kernel_envelope" (no chip time). Every supported point is checked against - * the host oracle on its first call, then warmed and timed over N calls (median / p90 of the - * whole call and of the chip kernel time). Gates: parity, no unwritten word, one device open, - * every call OK; the timings are evidence, not a threshold. Only quantities the stack measures - * are recorded; SM occupancy, bandwidth utilisation and cache hit rates are not observable - * through this path and are reported as unavailable. Under --sim the timings are host-simulator - * timings and the receipt says so. */ -static int sweep(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - const int N = g_sim_mode ? 1 : 20; - const uint32_t hd = 64, bs = 16, layers = 1, layer = 0; - static const uint32_t qheads[8] = { 1, 2, 4, 8, 16, 24, 32, 64 }; - static const uint32_t ctxs[2] = { 256, 2048 }; - uint32_t seed = 0xfb1c05eeu; - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_SWEEP_V1\",\"path\":\"paged_bf16\",\"head_dim\":%u,\"block_size\":%u,\"timed_calls\":%d,\"host_simulator\":%s," - "\"tolerances\":{\"rel\":2e-4,\"abs\":2e-5},\"hardware_counters\":\"unavailable (SM occupancy, bandwidth utilisation, cache hit rates are not observable through this path)\",\"points\":[", - hd, bs, N, g_sim_mode ? "true" : "false"); - int npoints = 0, supported = 0, unsupported = 0; - double *samples = malloc((size_t)N * sizeof *samples), *ksamples = malloc((size_t)N * sizeof *ksamples); - for (int qi = 0; qi < 8; qi++) for (uint32_t nkv = 1; nkv <= qheads[qi]; nkv++) { - uint32_t nqh = qheads[qi]; - if (nqh % nkv) continue; - uint32_t ratio = nqh / nkv; int pow2 = (ratio & (ratio - 1)) == 0; - for (int ci = 0; ci < 2; ci++) { - uint32_t ctx = ctxs[ci], nblk = (ctx + bs - 1) / bs, pool_blocks = nblk + 5; - OmegaGpuKvLayout ly = layout_for(pool_blocks, bs, layers, nkv, hd); - uint8_t *pool = malloc(ly.pool_bytes); uint16_t *pw = (uint16_t *)pool; - for (size_t i = 0; i < ly.pool_bytes / 2; i++) pw[i] = f2bf(frand(&seed, -1.0f, 1.0f)); - uint32_t *ids = malloc(nblk * 4); - for (uint32_t b = 0; b < nblk; b++) ids[b] = (b * 7 + 3) % pool_blocks; - size_t n = (size_t)nqh * hd; - float *q = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); - OmegaGpuAttnInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &info); - const char *klass; int pass; size_t bad = 0; double worst = 0; int ok_calls = 0; uint32_t unwritten = 0, cache_hits = 0; double med = 0, p90 = 0, kmed = 0, kp90 = 0; - if (!pow2) { - klass = "unsupported_by_kernel_envelope"; - pass = rc == OMEGA_GPU_ATTN_BAD_ARGS; unsupported++; - CHECK(pass, "sweep %uq/%ukv ctx %u: ratio %u (not a power of two) refused with BAD_ARGS (got %s)", nqh, nkv, ctx, ratio, omega_gpu_attention_rc_name(rc)); - } else { - klass = "supported"; supported++; - oracle_paged(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, want); - bad = compare(got, want, n, 2e-4, 2e-5, &worst); - unwritten = info.unwritten_words; - uint64_t kv_staged = info.kv_bytes_staged, kv_naive = info.kv_bytes_naive, qb = info.q_bytes, tb = info.tab_bytes, ob = info.out_bytes; - uint32_t launches = info.chip_calls, ctas = info.ctas_last_launch, blk_l = info.kv_blocks_logical, blk_u = info.kv_blocks_unique, kv_src = info.kv_source; - for (int i = 0; i < N; i++) { - OmegaGpuAttnInfo ti; - int trc = omega_gpu_paged_attention_bf16(q, pool, &ly, ids, nblk, ctx, layer, nqh, nkv, hd, got, &ti); - samples[i] = ti.call_ns / 1e6; ksamples[i] = ti.elapsed_ns / 1e6; - double w; size_t b2 = compare(got, want, n, 2e-4, 2e-5, &w); - if (w > worst) worst = w; - bad += b2; unwritten += ti.unwritten_words; cache_hits += ti.kernel_cache_hit; - if (trc == OMEGA_GPU_ATTN_OK && b2 == 0) ok_calls++; - } - qsort(samples, (size_t)N, sizeof samples[0], cmp_d); qsort(ksamples, (size_t)N, sizeof ksamples[0], cmp_d); - med = samples[N / 2]; p90 = samples[N * 9 / 10]; kmed = ksamples[N / 2]; kp90 = ksamples[N * 9 / 10]; - pass = rc == OMEGA_GPU_ATTN_OK && bad == 0 && ok_calls == N && unwritten == 0 && cache_hits == (uint32_t)N; - CHECK(pass, "sweep %uq/%ukv ctx %u: rc=%s violations=%zu ok_calls=%d/%d unwritten=%u cache_hits=%u", nqh, nkv, ctx, omega_gpu_attention_rc_name(rc), bad, ok_calls, N, unwritten, cache_hits); - printf("%s sweep %2uq/%2ukv ratio %2u ctx %4u: launches=%u ctas=%u call_ms med=%.3f p90=%.3f kernel_ms med=%.3f p90=%.3f kv_staged=%" PRIu64 " (naive %" PRIu64 ") blocks=%u/%u q=%" PRIu64 " tab=%" PRIu64 " out=%" PRIu64 " worst=%g\n", - pass ? "PASS" : "FAIL", nqh, nkv, ratio, ctx, launches, ctas, med, p90, kmed, kp90, kv_staged, kv_naive, blk_u, blk_l, qb, tb, ob, worst); - if (out) fprintf(out, "%s{\"q_heads\":%u,\"kv_heads\":%u,\"gqa_ratio\":%u,\"head_dim\":%u,\"context\":%u,\"q_width\":%zu,\"out_width\":%zu,\"class\":\"%s\",\"rc\":\"%s\",\"pass\":%s," - "\"violations\":%zu,\"worst_scaled_err\":%g,\"unwritten_words\":%u,\"launches_per_call\":%u,\"ctas_last_launch\":%u,\"threads_per_cta\":%u," - "\"call_ms_median\":%.4f,\"call_ms_p90\":%.4f,\"kernel_ms_median\":%.4f,\"kernel_ms_p90\":%.4f,\"kernel_cache_hits\":%u,\"first_call_cache_hit\":%s," - "\"kv_bytes_staged\":%" PRIu64 ",\"kv_bytes_naive\":%" PRIu64 ",\"kv_blocks_logical\":%u,\"kv_blocks_unique\":%u,\"q_bytes\":%" PRIu64 ",\"tab_bytes\":%" PRIu64 ",\"out_bytes\":%" PRIu64 ",\"kv_source\":\"%s\"}", - npoints ? "," : "", nqh, nkv, ratio, hd, ctx, n, n, klass, omega_gpu_attention_rc_name(rc), pass ? "true" : "false", bad, worst, unwritten, launches, ctas, info.threads_per_cta, - med, p90, kmed, kp90, cache_hits, info.kernel_cache_hit ? "true" : "false", kv_staged, kv_naive, blk_l, blk_u, qb, tb, ob, kv_src == OMEGA_GPU_ATTN_KV_STAGED ? "staged" : "resident"); - npoints++; - } - if (!pow2) { - printf("%s sweep %2uq/%2ukv ratio %2u ctx %4u: %s (rc=%s)\n", pass ? "PASS" : "FAIL", nqh, nkv, ratio, ctx, klass, omega_gpu_attention_rc_name(rc)); - if (out) fprintf(out, "%s{\"q_heads\":%u,\"kv_heads\":%u,\"gqa_ratio\":%u,\"head_dim\":%u,\"context\":%u,\"q_width\":%zu,\"out_width\":%zu,\"class\":\"%s\",\"rc\":\"%s\",\"pass\":%s}", - npoints ? "," : "", nqh, nkv, ratio, hd, ctx, n, n, klass, omega_gpu_attention_rc_name(rc), pass ? "true" : "false"); - npoints++; - } - free(pool); free(ids); free(q); free(got); free(want); - } - } - free(samples); free(ksamples); - uint32_t opens = omega_gpu_session_open_count(); - CHECK(opens == (g_sim_mode ? 0u : 1u), "sweep: device opened %s (opens=%u)", g_sim_mode ? "never (simulator)" : "once", opens); - printf("sweep: %d points (%d supported, %d unsupported by the kernel envelope), device_opens=%u\n", npoints, supported, unsupported, opens); - if (out) { fprintf(out, "],\"points_total\":%d,\"points_supported\":%d,\"points_unsupported\":%d,\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", npoints, supported, unsupported, opens, g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_SWEEP_PASS" : "OMEGA_GPU_ATTENTION_SWEEP_FAIL"); fclose(out); } - return 0; -} - -/* ------------------------------------------------------------ warp simulator (omega #308) - * The per-thread simulator above has no model of a warp (its SHFL rule is "one path across the - * warp or error 7"). With --divergent the kernel carries a real lane-dependent branch inside a - * BSSY/BSYNC region, and every launch runs through tests/bw_warp_sim.h instead: 32-lane - * fragments, barrier registers, SHFL/BAR participation. Each launch runs in both fragment - * orders and the two outputs must be bit-identical. */ -static uint64_t g_ws_issues, g_ws_launches; -static int ws_attn_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info) { - const BlackwellIRProgram *p = progv; - uint32_t *outw = L->out; size_t nw = L->out_bytes / 4; - uint32_t *copy = malloc(L->out_bytes); - int err = 0; char msg[240] = ""; - for (int order = 0; order < 2 && !err && copy; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = p; s.threads = SIM_T; s.smem = sim_shared; s.smem_bytes = SIM_SMEM; s.order = order; - uint64_t qa = (uintptr_t)L->q, pa = (uintptr_t)L->pool, oa = (uintptr_t)L->out, ta = (uintptr_t)L->tab; - s.cbank[0x380 / 4] = (uint32_t)qa; s.cbank[0x380 / 4 + 1] = (uint32_t)(qa >> 32); - s.cbank[0x388 / 4] = (uint32_t)pa; s.cbank[0x388 / 4 + 1] = (uint32_t)(pa >> 32); - s.cbank[0x390 / 4] = (uint32_t)oa; s.cbank[0x390 / 4 + 1] = (uint32_t)(oa >> 32); - s.cbank[0x398 / 4] = (uint32_t)ta; s.cbank[0x398 / 4 + 1] = (uint32_t)(ta >> 32); - memcpy(&s.cbank[0x3a0 / 4], L->params, sizeof L->params); - for (size_t i = 0; i < nw; i++) outw[i] = 0xffbadbadu; - err = ws_run(&s, L->grid_x, L->grid_y); - if (err) { snprintf(msg, sizeof msg, "order %d: %s", order, s.msg); break; } - g_ws_issues += s.warp_issues; - if (order == 0) memcpy(copy, outw, L->out_bytes); - else if (memcmp(copy, outw, L->out_bytes) != 0) { err = -1; snprintf(msg, sizeof msg, "the fragment order changed the result"); } - } - free(copy); - g_ws_launches++; - uint32_t unwritten = 0; for (size_t i = 0; i < nw; i++) if (outw[i] == 0xffbadbadu) unwritten++; - if (info) { info->chip_calls++; info->unwritten_words += unwritten; info->ctas_last_launch = L->grid_x * L->grid_y; info->threads_per_cta = SIM_T; } - if (err) { printf("warp simulator error: %s\n", msg); return OMEGA_GPU_ATTN_CHIP_FAIL; } - return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; -} -/* Negative control for --divergent --sim: mode 2 builds the same kernel with the BSYNC dropped; - * the warp simulator must reject it (the whole point of the simulator: the old one could not). */ -static void divergent_negative_control(void) { - enum { SEQ = 65, NQH = 8, NKV = 2 }; - const uint32_t HD = g_hd; - float *q = malloc(NQH * HD * 4), *kv = malloc((size_t)SEQ * NKV * HD * 4), *out = malloc(NQH * HD * 4); - uint32_t seed = 0x308u; - for (uint32_t i = 0; i < NQH * HD; i++) q[i] = frand(&seed, -1.0f, 1.0f); - for (size_t i = 0; i < (size_t)SEQ * NKV * HD; i++) kv[i] = frand(&seed, -1.0f, 1.0f); - omega_gpu_attention_test_set_divergent(2); - int rc = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL); - omega_gpu_attention_test_set_divergent(1); - CHECK(rc == OMEGA_GPU_ATTN_CHIP_FAIL, "divergent mode 2 (BSYNC dropped) rejected by the warp simulator (rc %s)", omega_gpu_attention_rc_name(rc)); - int rc1 = omega_gpu_gqa_attention_f32(q, kv, kv, SEQ, NQH, NKV, HD, out, NULL); - CHECK(rc1 == OMEGA_GPU_ATTN_OK, "divergent mode 1 (regioned branch) runs clean on the same input (rc %s)", omega_gpu_attention_rc_name(rc1)); - free(q); free(kv); free(out); -} - -/* ------------------------------------------------------------ head_dim 128 (CPU phase) - * Checks that need the public API only, so the same code runs on the host simulators now and on - * the chip in the coordinated window. Run with --hd 128 (--sim for the host simulators). - * They target what head_dim 128 changed: four warps per CTA, so the chunk max and the chunk sum - * each combine FOUR warp partials (lane 0 of warps 0..3), and 128-token chunks. - * (a) uniform scores (K = 0): every weight is 1, the output is the mean of V over the context; - * a sum that drops the partial of warp 2 or 3 gives about twice the mean; - * (b) one dominant token with a score above the f32 exponent range (EX2 overflows without the - * right running max): the token sits in each of the four warps of chunk 0 and in the later, - * partial chunks; a max that ignores warp 2 or 3 overflows to inf / NaN. - * Negative controls: the comparison rejects the answer of a different token, and a shared-memory - * declaration of 1024 bytes (the head_dim 64 size) is refused by the simulators. */ -static void hd128_checks(void) { - const uint32_t hd = 128, nqh = 8, nkv = 2, seq = 300; - uint32_t seed = 0x128u; - size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; - float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) q[i] = 1.0f; - for (size_t i = 0; i < nkvs; i++) vc[i] = frand(&seed, -1.0f, 1.0f); - OmegaGpuAttnInfo info; - /* (a) uniform */ - memset(kc, 0, nkvs * 4); - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); - double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); - CHECK(rc == OMEGA_GPU_ATTN_OK && bad == 0 && info.threads_per_cta == 128, "hd128 uniform scores: mean of V over 300 tokens (rc %s, %zu bad, worst %g, %u threads)", omega_gpu_attention_rc_name(rc), bad, w, info.threads_per_cta); - float *half = malloc(n * 4); for (size_t i = 0; i < n; i++) half[i] = want[i] * 0.5f; - size_t neg = compare(got, half, n, 2e-4, 2e-5, &w); - CHECK(neg > n / 2, "hd128 uniform negative control: a result with the sum of two warps dropped (half the mean) is flagged (%zu of %zu)", neg, n); - free(half); - /* (b) one dominant token */ - static const uint32_t pos[] = { 5, 40, 70, 100, 127, 128 + 3, 256 + 43 }; - int all_ok = 1; size_t worst_bad = 0; - for (size_t pi = 0; pi < sizeof pos / sizeof pos[0]; pi++) { - memset(kc, 0, nkvs * 4); - for (uint32_t kvh = 0; kvh < nkv; kvh++) for (uint32_t d = 0; d < hd; d++) kc[((size_t)pos[pi] * nkv + kvh) * hd + d] = 12.0f; /* dot 1536, scaled by log2e / sqrt(128): about 2^196 */ - oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); - rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); - bad = compare(got, want, n, 2e-4, 2e-5, &w); - if (rc != OMEGA_GPU_ATTN_OK || bad) { all_ok = 0; if (bad > worst_bad) worst_bad = bad; } - printf(" hd128 dominant token %u (warp %u of chunk %u): rc %s, %zu bad, worst %g\n", pos[pi], (pos[pi] % 128) / 32, pos[pi] / 128, omega_gpu_attention_rc_name(rc), bad, w); - if (pi == 0) { - /* negative control: the answer of token 6 instead of token 5 must be flagged */ - float *other = malloc(n * 4); - for (uint32_t h = 0; h < nqh; h++) for (uint32_t d = 0; d < hd; d++) other[h * hd + d] = vc[((size_t)6 * nkv + h / (nqh / nkv)) * hd + d]; - size_t negb = compare(got, other, n, 2e-4, 2e-5, &w); - CHECK(negb > n / 2, "hd128 dominant-token negative control: the neighbouring token's V is flagged (%zu of %zu)", negb, n); - free(other); - } - } - CHECK(all_ok, "hd128 dominant token in every warp and chunk: exact max/sum over four warp partials (worst bad %zu)", worst_bad); - /* a kernel that needs 2048 bytes of shared memory must not run in a 1024-byte declaration (simulators only: they bound shared accesses) */ - if (g_sim_mode) { - g_smem_cap = 1024; - rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, NULL); - g_smem_cap = 0; - CHECK(rc == OMEGA_GPU_ATTN_CHIP_FAIL, "hd128 kernel refused under a 1024-byte shared-memory declaration (rc %s)", omega_gpu_attention_rc_name(rc)); - rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, NULL); - CHECK(rc == OMEGA_GPU_ATTN_OK, "hd128 kernel runs under the 2048-byte declaration (rc %s)", omega_gpu_attention_rc_name(rc)); - } - free(q); free(kc); free(vc); free(got); free(want); -} - -/* head_dim 64 byte-identity pin and head_dim 128 codegen facts (CPU only, no device, no simulator). - * The digests are SHA-256 of the encoded kernel bytes as emitted by the batched-load program of 2026-10-12 - * (speed/attention-batched-loads; before it, main c0369e6 was pinned at 160 instructions); any change to the head_dim 64 program changes a digest and fails here. */ -typedef struct { bool f32; uint32_t log2bs, log2gqa; size_t insns; const char *sha256; } Pin; -static const Pin k_pins64[] = { - { false, 4, 3, 216, "44d27fae78ea21ee77fd7a0ebd2ebfcac52e9e45a81de84b035868092e13e424" }, - { false, 4, 2, 216, "3bc79d4a54fd0d82024b376dfdb718e8326431917251f13f5c44be6ba8eb6f0c" }, - { false, 4, 0, 216, "83eca9872e32c17321d2f8ec6a6ec92638ed72b136d8958cda5cdfc451c01ef8" }, - { true, 12, 3, 184, "b6a25d8739185bbd944bfcc1ec174abb24ce46529f06c56f8d5ac77bf6883ddd" }, - { true, 12, 2, 184, "46a2b82ebcb55237f4a7585679b42ac9558c7a434e8e80ccef6cc0bfaed8fcb9" }, - { true, 12, 0, 184, "970db9533c836eca7c86783875a2ad898cd69bc3070cae418cc92b3ce2dbbd9c" }, -}; -static void hex_digest(const uint8_t d[32], char out[65]) { for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", d[i]); } -static void hd_codegen_checks(void) { - char hex[65]; - for (size_t i = 0; i < sizeof k_pins64 / sizeof k_pins64[0]; i++) { - const Pin *p = &k_pins64[i]; - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - int rc = omega_gpu_attention_codegen_hd(p->f32, p->log2bs, p->log2gqa, 64, &k); - hex_digest(k.code_digest, hex); - CHECK(rc == OMEGA_GPU_ATTN_OK && k.insn_count == p->insns && strcmp(hex, p->sha256) == 0, "hd64 %s log2bs %u log2gqa %u: encoded kernel is byte-identical to the pinned program (%zu insns, sha256 %s)", p->f32 ? "f32 " : "bf16", p->log2bs, p->log2gqa, k.insn_count, hex); - free(k.code); - /* the 4-argument entry point is the same kernel */ - OmegaBlackwellKernel k4; memset(&k4, 0, sizeof k4); - CHECK(omega_gpu_attention_codegen(p->f32, p->log2bs, p->log2gqa, &k4) == OMEGA_GPU_ATTN_OK && memcmp(k4.code_digest, k.code_digest, 32) == 0, "hd64 4-argument codegen entry is the same kernel"); - free(k4.code); - /* head_dim 128: encodes, inside the register budget, a different (longer) program */ - OmegaBlackwellKernel k2; memset(&k2, 0, sizeof k2); - int rc2 = omega_gpu_attention_codegen_hd(p->f32, p->log2bs, p->log2gqa, 128, &k2); - CHECK(rc2 == OMEGA_GPU_ATTN_OK && k2.code_size > 0 && k2.gpr_count <= 96 /* AT_GPR_BUDGET; cut K: the four-head kernel peaks at 84 */ && k2.insn_count > p->insns && memcmp(k2.code_digest, k.code_digest, 32) != 0, - "hd128 %s log2bs %u log2gqa %u: kernel encodes (%zu insns vs %zu, %u gprs)", p->f32 ? "f32 " : "bf16", p->log2bs, p->log2gqa, k2.insn_count, p->insns, k2.gpr_count); - free(k2.code); - } - OmegaBlackwellKernel kx; memset(&kx, 0, sizeof kx); - CHECK(omega_gpu_attention_codegen_hd(false, 4, 3, 96, &kx) == OMEGA_GPU_ATTN_TOO_LARGE, "codegen refuses head_dim 96"); - CHECK(omega_gpu_attention_codegen_hd(false, 4, 3, 256, &kx) == OMEGA_GPU_ATTN_TOO_LARGE, "codegen refuses head_dim 256"); - /* negative control for the pin itself: a one-bit change to a pinned digest must not match */ - OmegaBlackwellKernel kn; memset(&kn, 0, sizeof kn); - (void)omega_gpu_attention_codegen_hd(k_pins64[0].f32, k_pins64[0].log2bs, k_pins64[0].log2gqa, 64, &kn); - kn.code_digest[0] ^= 1u; hex_digest(kn.code_digest, hex); - CHECK(strcmp(hex, k_pins64[0].sha256) != 0, "pin negative control: a flipped digest bit does not match the pin"); - free(kn.code); -} - - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, sim = 0, timing_mode = 0, sweep_mode = 0, split_timing_mode = 0; - uint32_t spin_us = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--divergent") == 0) g_divergent = 1; - else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; - else if (strcmp(argv[i], "--split-timing") == 0) split_timing_mode = 1; - else if (strcmp(argv[i], "--sweep") == 0) sweep_mode = 1; - else if (strcmp(argv[i], "--hd") == 0 && i + 1 < argc) g_hd = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin_us = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - if (g_hd != 64 && g_hd != 128) { printf("--hd must be 64 or 128\n"); return 2; } - if (g_hd == 128 && (timing_mode || sweep_mode)) { printf("--hd 128 supports the battery, --split-timing and --host-only (timing and sweep are head_dim 64 only)\n"); return 2; } - if (spin_us && omega_gpu_session_set_spin_us(spin_us) != 0) { printf("--spin-us %u refused\n", spin_us); return 2; } - if (g_divergent) omega_gpu_attention_test_set_divergent(1); - if (sim) { g_sim_mode = 1; omega_gpu_attention_test_set_simulator(g_divergent ? ws_attn_launch : sim_launch); } - if (sim && g_divergent && !host) divergent_negative_control(); - if (host) { host_only(); hd_codegen_checks(); } - else if (split_timing_mode) { if (split_timing(out_path) != 0) return 2; } - else if (timing_mode) { if (timing(out_path) != 0) return 2; } - else if (sweep_mode) { if (sweep(out_path) != 0) return 2; } - else { if (chip(out_path) != 0) return 2; if (g_hd == 128) hd128_checks(); } - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_bf16_gemv_test.c b/tests/gpu_bf16_gemv_test.c deleted file mode 100644 index 7b8e231c4..000000000 --- a/tests/gpu_bf16_gemv_test.c +++ /dev/null @@ -1,279 +0,0 @@ -/* - * gpu_bf16_gemv_test: the bf16 streaming GEMV (omega_gpu_bf16_gemv_api.h), OWN-30B lm_head. - * --host-only emulation vs double oracle, codegen budgets and refusals (no device) - * --sim warp-simulator parity at 8 warps (both fragment orders, rows 1/2/4, depths, k 512/2048, multi-CTA - * with the row-group loop): bit-identical to the host f32 emulation; mutants 1-3 caught - * (default) the chip: all 151936 logits bit-identical to the host emulation and within tolerance of the double - * oracle, second call bit-identical, bf16-x entry, mutants 1-3 caught on a small tensor, timing - * (--reps N, --n N, --rows R, --warps W, --depth D, --ctas C, --no-evict, --spin-us, --out receipt.json) - * Verdict line last: "gpu_bf16_gemv_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } - -/* The kernel's exact f32 result for one row: per lane one FFMA chain (step, word, low half, high half), then the - * SHFL.DOWN tree 16, 8, 4, 2, 1 (lane L adds lane L + o's value; lane 0 is the result). */ -static float emu_row(const uint16_t *w, const float *x, uint32_t k) { - float a[32]; - for (unsigned lane = 0; lane < 32; lane++) { - float acc = 0.0f; - for (uint32_t s = 0; s < k / 256u; s++) { - const uint16_t *wl = w + s * 256u + lane * 8u; const float *xl = x + s * 256u + lane * 8u; - for (unsigned i = 0; i < 8; i++) acc = fmaf(bf16_f32(wl[i]), xl[i], acc); - } - a[lane] = acc; - } - for (unsigned o = 16; o >= 1; o /= 2) { float b[32]; for (unsigned l = 0; l < 32; l++) b[l] = a[l + o < 32 ? l + o : l]; for (unsigned l = 0; l < 32; l++) a[l] += b[l]; } - return a[0]; -} -static void oracle_row(const uint16_t *w, const float *x, uint32_t k, double *y, double *ys) { - double s = 0, m = 0; - for (uint32_t c = 0; c < k; c++) { double t = (double)bf16_f32(w[c]) * x[c]; s += t; m += fabs(t); } - *y = s; *ys = m; -} -static uint16_t *make_w(size_t count, uint32_t seed) { - uint16_t *w = malloc(count * 2); uint32_t s = seed; - for (size_t i = 0; i < count; i++) w[i] = bf16_rne(frand(&s, -0.06f, 0.06f)); - return w; -} -static float *make_x(uint32_t k, uint32_t seed) { - float *x = malloc((size_t)k * 4); uint32_t s = seed; - for (uint32_t i = 0; i < k; i++) x[i] = frand(&s, -2.0f, 2.0f); - return x; -} -/* bit-identical compare of n outputs against the emulation; returns the number of differing rows */ -static size_t compare_emu(const uint16_t *w, const float *x, uint32_t n, uint32_t k, const float *y, size_t *first) { - size_t bad = 0; *first = (size_t)-1; - for (uint32_t r = 0; r < n; r++) { - float e = emu_row(w + (size_t)r * k, x, k); - if (memcmp(&e, &y[r], 4) != 0) { if (!bad) *first = r; bad++; } - } - return bad; -} - -static void host_only(void) { - printf("host-only: emulation, oracle, budgets\n"); - { uint16_t *w = make_w(2048, 5); float *x = make_x(2048, 6); - double yo, ys; oracle_row(w, x, 2048, &yo, &ys); - float e = emu_row(w, x, 2048); - CHECK(fabs((double)e - yo) <= 1e-6 * ys, "emulation within 1e-6 of the double oracle (%.9g vs %.9g, scale %.3g)", (double)e, yo, ys); - printf("emulation vs oracle: abs %.3e, scale %.3f\n", fabs((double)e - yo), ys); - /* a known hand case: w = 1 on the first 256 columns, x = c: sum 0..255 = 32640 */ - uint16_t hw[256]; float hx[256]; for (unsigned i = 0; i < 256; i++) { hw[i] = 0x3f80; hx[i] = (float)i; } - CHECK(emu_row(hw, hx, 256) == 32640.0f, "hand case sum 0..255 = 32640"); - free(w); free(x); } - uint32_t ws[] = { 4, 8, 16, 32 }, rs[] = { 1, 2, 4 }; - for (unsigned i = 0; i < 4; i++) for (unsigned j = 0; j < 3; j++) for (uint32_t d = 1; d <= 8; d *= 2) for (int m = 0; m <= 3; m++) { - OmegaBf16GemvSpec s = { 2048, rs[j], ws[i], d, m }; - if (rs[j] * d > 16u) continue; - uint32_t n = 0, g = 0; int rc = omega_bf16_gemv_prog_stats(&s, &n, &g); - uint32_t decl = ((g + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024, "codegen k2048 rows %u warps %u depth %u mutant %d: rc %d insns %u gprs %u", rs[j], ws[i], d, m, rc, n, g); - if (m == 0 && rc == 0 && rs[j] == 1 && d == 8) printf("codegen rows %u warps %2u depth %u: %u instructions, %u registers (declared %u, register file %u of 65536)%s\n", rs[j], ws[i], d, n, g, decl, 32u * ws[i] * decl, 32u * ws[i] * decl <= 65536u ? "" : " DOES NOT FIT"); - } - { OmegaBf16GemvSpec s = { 2048, 3, 8, 8, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "rows 3 refused"); } - { OmegaBf16GemvSpec s = { 2000, 1, 8, 8, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "k 2000 refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 8, 3, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "depth 3 refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 8, 8, 4 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "mutant 4 refused"); } - CHECK(OMEGA_BF16_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); - uint16_t bad[256]; memset(bad, 0, sizeof bad); bad[7] = 0x7f80; - OmegaGpuBf16Tensor *t = NULL; - CHECK(omega_gpu_bf16_tensor_upload(1, 256, bad, &t) == OMEGA_GPU_BF16_NAN_WEIGHT && !t, "an infinite bf16 weight is refused before any device use"); - CHECK(omega_gpu_bf16_tensor_upload(1, 200, bad, &t) == OMEGA_GPU_BF16_BAD_ARGS, "k 200 refused at upload"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int sim_point(uint32_t k, uint32_t n, uint32_t rows, uint32_t warps, uint32_t depth, uint32_t grid_x, int mutant, uint32_t seed, char *msg, size_t msgn, size_t *bad) { - static BlackwellIRProgram prog; - OmegaBf16GemvSpec spec = { k, rows, warps, depth, mutant }; - if (omega_blackwell_codegen_bf16_gemv_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint16_t *w = aligned_alloc(16, (size_t)n * k * 2); { uint16_t *t = make_w((size_t)n * k, seed); memcpy(w, t, (size_t)n * k * 2); free(t); } - float *x = aligned_alloc(16, (size_t)k * 4); { float *t = make_x(k, seed + 1); memcpy(x, t, (size_t)k * 4); free(t); } - float *y = aligned_alloc(16, ((size_t)n * 4 + 15) & ~15ull); - uint8_t *smem = aligned_alloc(16, omega_bf16_gemv_shared_bytes(&spec)); - float first[1] = { 0 }; float *ycopy = NULL; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * warps; s.order = order; s.smem = smem; s.smem_bytes = omega_bf16_gemv_shared_bytes(&spec); - for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - uint64_t A[3] = { (uintptr_t)w, (uintptr_t)x, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_BF16_ARG_RG / 4] = n / rows; s.cbank[OMEGA_BF16_ARG_STRIDE / 4] = grid_x * warps; - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)w; s.ranges[0].hi = (uintptr_t)w + (size_t)n * k * 2; - s.ranges[1].lo = (uintptr_t)x; s.ranges[1].hi = (uintptr_t)x + (size_t)k * 4; - s.ranges[2].lo = (uintptr_t)y; s.ranges[2].hi = (uintptr_t)y + (size_t)n * 4; - err = ws_run(&s, grid_x, 1); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (uint32_t i = 0; i < n; i++) if (y[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msgn, "%zu output words never written", unwritten); break; } - if (order == 0) { ycopy = malloc((size_t)n * 4); memcpy(ycopy, y, (size_t)n * 4); } - else if (memcmp(ycopy, y, (size_t)n * 4) != 0) { err = -1; snprintf(msg, msgn, "the fragment order changed the result"); } - } - (void)first; - if (!err) { size_t f; *bad = compare_emu(w, x, n, k, y, &f); snprintf(msg, msgn, "%zu of %u rows differ from the emulation%s", *bad, n, *bad ? "" : " (bit-identical)"); } - free(ycopy); free(w); free(x); free(y); free(smem); - return err; -} -static void sim_battery(void) { - struct { uint32_t k, n, rows, warps, depth, grid; } pts[] = { - { 2048, 100, 1, 8, 8, 2 }, { 2048, 100, 1, 8, 4, 3 }, { 2048, 64, 1, 8, 1, 2 }, { 2048, 96, 2, 8, 4, 2 }, { 2048, 96, 4, 8, 4, 1 }, - { 512, 70, 1, 8, 2, 2 }, { 512, 70, 2, 4, 1, 3 }, { 4096, 40, 1, 8, 16, 2 }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_point(pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, 0, 31 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim k %u n %u rows %u warps %u depth %u grid %u: %s", pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, msg); - printf("sim k %u n %u rows %u warps %u depth %u grid %u: %s %s\n", pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 3; m++) { - char msg[300]; size_t bad = 0; - int err = sim_point(2048, 64, 1, 8, 4, 2, m, 77, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static double med(uint64_t *v, uint32_t n) { qsort(v, n, 8, cmp_u64); return (double)v[n / 2]; } - -static int chip_run(const char *out_path, uint32_t reps, uint32_t N, uint32_t K) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_BF16_GEMV_V1\",\"n\":%u,\"k\":%u,\"reps\":%u,\"evict\":%d,\"spin_us\":%u,\"points\":[", N, K, reps, g_evict, omega_gpu_session_spin_us()); - uint16_t *w = make_w((size_t)N * K, 90001); float *x = make_x(K, 90002); - OmegaGpuBf16Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_bf16_tensor_upload(N, K, w, &t); - printf("upload %u x %u bf16 (%.0f MB): rc=%s %.0f ms (%s)\n", N, K, (double)N * K * 2 / 1e6, omega_gpu_bf16_rc_name(rc), now_ms() - t0, rc ? omega_gpu_bf16_last_error() : ""); - CHECK(rc == 0, "upload"); - if (rc) { if (out) { fprintf(out, "],\"verdict\":\"FAIL\"}\n"); fclose(out); } return 1; } - float *y = malloc((size_t)N * 4), *y2 = malloc((size_t)N * 4); OmegaGpuBf16Info info; - rc = omega_gpu_bf16_gemv_f32(t, x, y, &info); - CHECK(rc == 0, "gemv: %s %s", omega_gpu_bf16_rc_name(rc), rc ? omega_gpu_bf16_last_error() : ""); - if (rc == 0) { - size_t first; size_t bad = compare_emu(w, x, N, K, y, &first); - CHECK(bad == 0, "chip vs host emulation: %zu of %u rows differ (first %zd)", bad, N, (ssize_t)first); - double worst = 0, wy = 0; size_t arg_o = 0, arg_c = 0; double bo = -1e300; float bc = -1e30f; - for (uint32_t r = 0; r < N; r++) { - double yo, ys; oracle_row(w + (size_t)r * K, x, K, &yo, &ys); - double d = fabs((double)y[r] - yo) / (ys + 1e-30); if (d > worst) { worst = d; wy = yo; } - if (yo > bo) { bo = yo; arg_o = r; } - if (y[r] > bc) { bc = y[r]; arg_c = r; } - } - CHECK(worst < 1e-5, "chip vs double oracle: worst rel-to-scale %.2e", worst); - printf("parity: %zu of %u rows differ from the f32 emulation (bit compare); worst error vs double oracle %.2e of the term scale (y %.4g); argmax chip %zu oracle %zu\n", bad, N, worst, wy, arg_c, arg_o); - if (out) fprintf(out, "{\"point\":\"parity\",\"rows_bad\":%zu,\"worst_rel\":%.3e,\"argmax_chip\":%zu,\"argmax_oracle\":%zu}", bad, worst, arg_c, arg_o); - rc = omega_gpu_bf16_gemv_f32(t, x, y2, NULL); - CHECK(rc == 0 && memcmp(y, y2, (size_t)N * 4) == 0, "second call bit-identical"); - printf("second call: %s\n", rc == 0 && memcmp(y, y2, (size_t)N * 4) == 0 ? "bit-identical" : "DIFFERS"); - uint16_t *xb = malloc(K * 2); float *xf = malloc(K * 4); - for (uint32_t i = 0; i < K; i++) { xb[i] = bf16_rne(x[i]); xf[i] = bf16_f32(xb[i]); } - rc = omega_gpu_bf16_gemv_bf16(t, xb, y2, NULL); - size_t b2 = 0, f2; if (rc == 0) b2 = compare_emu(w, xf, N, K, y2, &f2); - CHECK(rc == 0 && b2 == 0, "bf16-x entry equals the emulation on the rounded x (%zu rows differ)", b2); - printf("bf16-x entry: %s\n", rc == 0 && b2 == 0 ? "bit-identical to the emulation" : "MISMATCH"); - free(xb); free(xf); - } - /* timing */ - { - uint64_t *ce = malloc(reps * 8), *cc = malloc(reps * 8); uint32_t done = 0; int ok = 1; - for (uint32_t i = 0; i < reps && ok; i++) { - if (g_evict) evict_host_caches(); - if (omega_gpu_bf16_gemv_f32(t, x, y2, &info) != 0) { ok = 0; break; } - ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; - } - CHECK(done == reps, "timing loop completed %u of %u", done, reps); - if (done) { - double mc = med(ce, done), ma = med(cc, done); - printf("timing (medians of %u, evict %d): rows %u warps %u depth %u ctas %u: chip %.1f us = %.1f GB/s on %.0f MB; call %.1f us = %.1f GB/s\n", - done, g_evict, info.rows_per_warp, info.warps_per_cta, info.depth, info.grid_x, mc / 1e3, (double)info.weight_bytes / mc, (double)info.weight_bytes / 1e6, ma / 1e3, (double)info.weight_bytes / ma); - if (out) fprintf(out, ",{\"point\":\"timing\",\"rows\":%u,\"warps\":%u,\"depth\":%u,\"ctas\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%.0f,\"weight_bytes\":%" PRIu64 ",\"chip_gbps\":%.2f,\"call_gbps\":%.2f,\"marker\":%u}", - info.rows_per_warp, info.warps_per_cta, info.depth, info.grid_x, done, mc, ma, info.weight_bytes, (double)info.weight_bytes / mc, (double)info.weight_bytes / ma, info.completion_marker); - } - free(ce); free(cc); - } - omega_gpu_bf16_tensor_free(t); - /* mutants on a small tensor */ - { - const uint32_t MN = 4096; OmegaGpuBf16Tensor *ts = NULL; - rc = omega_gpu_bf16_tensor_upload(MN, K, w, &ts); - CHECK(rc == 0, "small tensor upload"); - if (rc == 0) { - float *ys = malloc(MN * 4); - rc = omega_gpu_bf16_gemv_f32(ts, x, ys, NULL); size_t f; size_t b0 = rc == 0 ? compare_emu(w, x, MN, K, ys, &f) : (size_t)-1; - CHECK(b0 == 0, "small tensor unmutated parity (%zu rows differ)", b0); - for (int m = 1; m <= 3; m++) { - omega_gpu_bf16_test_set_mutant(m); - rc = omega_gpu_bf16_gemv_f32(ts, x, ys, NULL); - size_t b = rc == 0 ? compare_emu(w, x, MN, K, ys, &f) : (size_t)-1; - CHECK(b != 0, "chip mutant %d must be caught (rc %s)", m, omega_gpu_bf16_rc_name(rc)); - printf("chip mutant %d: %s (%zu of %u rows differ)\n", m, b ? "caught" : "NOT CAUGHT", b == (size_t)-1 ? (size_t)MN : b, MN); - if (out) fprintf(out, ",{\"point\":\"mutant %d\",\"caught\":%d}", m, b != 0); - } - omega_gpu_bf16_test_set_mutant(0); - free(ys); - } - omega_gpu_bf16_tensor_free(ts); - } - free(w); free(x); free(y); free(y2); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 0, rows = 0, warps = 0, depth = 0, ctas = 0, spin = 2000, N = 151936, K = 2048; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--rows") == 0 && i + 1 < argc) rows = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--ctas") == 0 && i + 1 < argc) ctas = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) N = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) K = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (rows || warps || depth) omega_gpu_bf16_set_shape(rows, warps, depth); - if (ctas) omega_gpu_bf16_set_cta_budget(ctas); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1, N, K); - omega_gpu_session_close(); - } - printf("gpu_bf16_gemv_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_cmdlist_test.c b/tests/gpu_cmdlist_test.c deleted file mode 100644 index f0647d615..000000000 --- a/tests/gpu_cmdlist_test.c +++ /dev/null @@ -1,464 +0,0 @@ -/* - * gpu_cmdlist_test: OWN-30B W-L2 decode launch collapse (omega_gpu_cmdlist.h + omega_blackwell_codegen_dec.h). - * --host-only codegen budgets and refusals of the four glue kernels (no device) - * --sim warp-simulator parity of AXPY chain, RES (ADD / COMBINE / NORM, scale 1 and 2^64), SWIGLU, ARGMAX - * (two stages, tie case) against the host reference; mutants caught - * (default) chip, caller holds the GB10 lock: - * baseline: L dependent AXPY launches one omega_gpu_session_launch at a time - * main: the same L launches recorded once and submitted once (PCAS) and in INLINE mode; x bit-identical - * to the baseline, every launch semaphore DONE; negative control skip_launch (must fail, first_missing - * named, x short by one a); BARRIER_NONE recorded (informational); per-launch medians (--reps N); - * glue kernels in one list: RES ADD|NORM, SWIGLU, RES COMBINE|NORM, ARGMAX x2 against the host - * reference; mutants caught on chip. --out receipt.json - * Verdict: exit 0 when every CHECK passed. - */ -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -#define H OMEGA_DEC_HIDDEN -#define TK OMEGA_DEC_TOPK -#define INTER OMEGA_DEC_INTER -#define VOCAB 151936u -#define AM_CTAS ((VOCAB + OMEGA_DEC_ARGMAX_SPAN - 1) / OMEGA_DEC_ARGMAX_SPAN) /* 75 */ -#define AM_PAD (AM_CTAS * OMEGA_DEC_ARGMAX_SPAN) /* 153600 */ -#define EPS 1e-6f -#define SCALE_2P64 18446744073709551616.0f - -/* ---- host references (float, the kernel's operation order where it matters; -ffp-contract=off) ---- */ -static void ref_res(uint32_t mode, float *x, const float *a, const float *w, const float *nw, float *y, float eps, float scale) { - if (mode & OMEGA_DEC_RES_ADD) for (unsigned i = 0; i < H; i++) x[i] = x[i] + a[i]; - if (mode & OMEGA_DEC_RES_COMBINE) for (unsigned i = 0; i < H; i++) { - float m = w[0] * a[i]; - for (unsigned g = 1; g < TK; g++) { float t = w[g] * a[g * H + i]; m = m + t; } - x[i] = x[i] + m; - } - if (mode & OMEGA_DEC_RES_NORM) { - double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i]; - float rs = (float)(1.0 / sqrt(sq / H + (double)eps)); - for (unsigned i = 0; i < H; i++) { float v = x[i] * rs; v = v * nw[i]; y[i] = v * scale; } - } -} -static void ref_swiglu(const float *gu, float *act, float scale) { - for (unsigned g = 0; g < TK; g++) for (unsigned c = 0; c < INTER; c++) { - float v = gu[g * 2 * INTER + c], u = gu[g * 2 * INTER + INTER + c]; - float s = v / (1.0f + expf(-v)); - act[g * INTER + c] = s * u * scale; - } -} -static uint32_t ref_argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; } -static int close_rel(float a, float b, float rel, float abs_) { float d = fabsf(a - b); return d <= abs_ || d <= rel * fabsf(b); } - -/* ---- one glue-kernel case: buffers in plain host memory (sim) or in device buffers (chip) ---- */ -typedef struct { - float *x, *a8, *w, *nw, *y, *gu, *act, *logits, *ov; uint32_t *oi; - float x_ref[H], y_ref[H], act_ref[TK * INTER]; uint32_t am_ref; -} Glue; -static void glue_fill(Glue *g, uint32_t seed, int tie) { - uint32_t s = seed; - for (unsigned i = 0; i < H; i++) { g->x[i] = frand(&s, -2, 2); g->nw[i] = frand(&s, 0.5f, 1.5f); } - for (unsigned i = 0; i < TK * H; i++) g->a8[i] = frand(&s, -1, 1); - for (unsigned i = 0; i < TK; i++) g->w[i] = frand(&s, 0, 0.3f); - for (unsigned i = 0; i < TK * 2 * INTER; i++) g->gu[i] = frand(&s, -4, 4); - for (unsigned i = 0; i < AM_PAD; i++) g->logits[i] = i < VOCAB ? frand(&s, -50, 50) : -1e30f; - if (tie) { g->logits[1007] = 60.0f; g->logits[90007] = 60.0f; } /* lowest index wins: 1007 (a j == 7 slot) */ - for (unsigned i = 0; i < OMEGA_DEC_ARGMAX_SPAN; i++) { g->ov[i] = -1e30f; g->oi[i] = 0; } - g->am_ref = ref_argmax(g->logits, VOCAB); -} - -/* ---- kernels ---- */ -typedef struct { BlackwellIRProgram prog; OmegaGpuMem code; uint32_t gpr; int built; } Kern; -static Kern K_axpy, K_res_an, K_res_cn, K_sw, K_am0, K_am1, K_res_m1, K_res_m2, K_res_cn_m1, K_sw_m1, K_am_m1, K_axpy_big; - -static int kern_prog(Kern *k, const OmegaDecSpec *sp) { k->built = 0; return omega_blackwell_codegen_dec_prog(sp, &k->prog); } -static int kern_upload(Kern *k) { - size_t need = omega_bw_program_code_bytes(&k->prog); - if (need == 0 || omega_gpu_session_alloc_code(need, &k->code) != 0) return -1; - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(&k->prog, k->code.cpu, need, &kk) != 0 || omega_gpu_session_sync_to_gpu(&k->code) != 0) return -1; - k->gpr = omega_bw_gpr_declared(kk.gpr_count); - if (k->gpr < 64u) k->gpr = 64u; - k->built = 1; - return 0; -} -static void put64(uint32_t *a, unsigned off, uint64_t v) { a[(off - 0x380) / 4] = (uint32_t)v; a[(off - 0x380) / 4 + 1] = (uint32_t)(v >> 32); } -static void putf(uint32_t *a, unsigned off, float f) { memcpy(&a[(off - 0x380) / 4], &f, 4); } - -#define AXPY_STRIDE 2048u /* small launch: 8 CTAs x 256 threads, one element each */ -#define AXPY_BIG_STRIDE 65536u /* heavy launch for the no-barrier control: 256 CTAs x 16 iterations */ -#define AXPY_BIG_ITERS 16u - -static int specs_build(void) { - OmegaDecSpec s; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_AXPY; s.stride = AXPY_STRIDE; if (kern_prog(&K_axpy, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_AXPY; s.stride = AXPY_BIG_STRIDE; if (kern_prog(&K_axpy_big, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM; if (kern_prog(&K_res_an, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; if (kern_prog(&K_res_cn, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM; s.mutant = 1; if (kern_prog(&K_res_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; s.mutant = 2; if (kern_prog(&K_res_m2, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; s.mutant = 1; if (kern_prog(&K_res_cn_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; if (kern_prog(&K_sw, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; s.mutant = 1; if (kern_prog(&K_sw_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 0; if (kern_prog(&K_am0, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 1; if (kern_prog(&K_am1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 0; s.mutant = 1; if (kern_prog(&K_am_m1, &s)) return -1; - return 0; -} - -/* ---- host-only ---- */ -static int host_only(void) { - const struct { const char *name; OmegaDecSpec s; } cases[] = { - { "axpy", { OMEGA_DEC_AXPY, 0, AXPY_STRIDE, 0 } }, - { "res add|norm", { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, 0, 0 } }, - { "res combine|norm", { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 0, 0 } }, - { "res add", { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD, 0, 0 } }, - { "swiglu", { OMEGA_DEC_SWIGLU, 0, 0, 0 } }, - { "argmax", { OMEGA_DEC_ARGMAX, 0, 0, 0 } }, - { "argmax indexed", { OMEGA_DEC_ARGMAX, 1, 0, 0 } }, - }; - for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) { - uint32_t insns = 0, gprs = 0; - int rc = omega_dec_prog_stats(&cases[i].s, &insns, &gprs); - CHECK(rc == 0, "codegen %s", cases[i].name); - CHECK(gprs <= 200, "%s gprs %u within budget", cases[i].name, gprs); - printf("codegen %s: %u insns, peak %u gprs, declared %u\n", cases[i].name, insns, gprs, omega_bw_gpr_declared(gprs)); - } - OmegaDecSpec bad[] = { { OMEGA_DEC_AXPY, 0, 0, 0 }, { OMEGA_DEC_AXPY, 0, 100, 0 }, { OMEGA_DEC_RES, 0, 0, 0 }, - { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_COMBINE, 0, 0 }, { (OmegaDecKind)0, 0, 0, 0 }, { OMEGA_DEC_RES, 8, 0, 0 } }; - for (unsigned i = 0; i < sizeof bad / sizeof bad[0]; i++) CHECK(omega_dec_prog_stats(&bad[i], NULL, NULL) != 0, "refusal %u", i); - return g_failed ? 1 : 0; -} - -/* ---- simulator ---- */ -static int sim_one(Kern *k, const uint32_t *args, unsigned n_args, uint32_t gx, uint32_t gy, WsRange *ranges, int nr, const char *what) { - static uint8_t smem[OMEGA_DEC_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = &k->prog; s.threads = OMEGA_DEC_THREADS; s.smem = smem; s.smem_bytes = sizeof smem; - memcpy(&s.cbank[0x380 / 4], args, n_args * 4u); - s.nranges = nr; for (int i = 0; i < nr; i++) s.ranges[i] = ranges[i]; - int err = ws_run(&s, gx, gy); - CHECK(err == 0, "sim %s: %s (pc %d)", what, s.msg, s.err_pc); - return err; -} -static int sim_mode(void) { - if (specs_build()) { printf("FAIL: codegen\n"); return 1; } - /* AXPY chain: 3 launches x += a over 2048 */ - { - static float x[AXPY_STRIDE], a[AXPY_STRIDE], xr[AXPY_STRIDE]; - uint32_t s = 7; for (unsigned i = 0; i < AXPY_STRIDE; i++) { x[i] = frand(&s, -1, 1); a[i] = frand(&s, -1, 1); xr[i] = x[i]; } - uint32_t args[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(args, OMEGA_DEC_AXPY_X, (uintptr_t)x); put64(args, OMEGA_DEC_AXPY_A, (uintptr_t)a); args[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = 1; - WsRange r[2] = { { (uintptr_t)x, (uintptr_t)x + sizeof x }, { (uintptr_t)a, (uintptr_t)a + sizeof a } }; - for (int l = 0; l < 3; l++) { if (sim_one(&K_axpy, args, OMEGA_DEC_AXPY_WORDS, AXPY_STRIDE / OMEGA_DEC_THREADS, 1, r, 2, "axpy")) return 1; for (unsigned i = 0; i < AXPY_STRIDE; i++) xr[i] = xr[i] + a[i]; } - CHECK(memcmp(x, xr, sizeof x) == 0, "sim axpy chain bit-identical"); - } - /* glue kernels */ - static float x[H], a8[TK * H], w[TK], nw[H], y[H], gu[TK * 2 * INTER], act[TK * INTER], logits[AM_PAD], ov[OMEGA_DEC_ARGMAX_SPAN]; - static uint32_t oi[OMEGA_DEC_ARGMAX_SPAN]; - Glue g = { x, a8, w, nw, y, gu, act, logits, ov, oi, { 0 }, { 0 }, { 0 }, 0 }; - WsRange rr[6] = { { (uintptr_t)x, (uintptr_t)x + sizeof x }, { (uintptr_t)a8, (uintptr_t)a8 + sizeof a8 }, { (uintptr_t)w, (uintptr_t)w + sizeof w }, - { (uintptr_t)nw, (uintptr_t)nw + sizeof nw }, { (uintptr_t)y, (uintptr_t)y + sizeof y }, { (uintptr_t)gu, (uintptr_t)gu + sizeof gu } }; - const float scales[2] = { 1.0f, SCALE_2P64 }; - for (int sc = 0; sc < 2; sc++) for (int mode = 0; mode < 2; mode++) for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 100 + sc, 0); - memcpy(g.x_ref, x, sizeof x); - const uint32_t M = mode == 0 ? (OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM) : (OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM); - ref_res(M, g.x_ref, a8, w, nw, g.y_ref, EPS, scales[sc]); - uint32_t args[OMEGA_DEC_RES_WORDS] = { 0 }; - put64(args, OMEGA_DEC_RES_X, (uintptr_t)x); put64(args, OMEGA_DEC_RES_A, (uintptr_t)a8); put64(args, OMEGA_DEC_RES_W, (uintptr_t)w); - put64(args, OMEGA_DEC_RES_NW, (uintptr_t)nw); put64(args, OMEGA_DEC_RES_Y, (uintptr_t)y); putf(args, OMEGA_DEC_RES_EPS, EPS); putf(args, OMEGA_DEC_RES_SCALE, scales[sc]); - Kern *k = mut ? (mode == 0 ? &K_res_m1 : &K_res_m2) : (mode == 0 ? &K_res_an : &K_res_cn); - if (sim_one(k, args, OMEGA_DEC_RES_WORDS, 1, 1, rr, 5, "res")) return 1; - int xbad = memcmp(x, g.x_ref, sizeof x) != 0, ybad = 0; - for (unsigned i = 0; i < H; i++) if (!close_rel(y[i], g.y_ref[i], 2e-5f, 1e-6f)) ybad++; - if (!mut) { CHECK(!xbad, "sim res mode %u scale %d: x bit-identical", M, sc); CHECK(ybad == 0, "sim res mode %u scale %d: y within 2e-5 (%d bad)", M, sc, ybad); } - else CHECK(xbad || ybad, "sim res mutant (mode %u) caught", M); - printf("sim res mode %u scale %s mutant %d: x %s, y %d/%u outside tolerance\n", M, sc ? "2^64" : "1", mut, xbad ? "DIFFERS" : "identical", ybad, H); - } - for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 200, 0); - ref_swiglu(gu, g.act_ref, 1.0f); - uint32_t args[OMEGA_DEC_SW_WORDS] = { 0 }; put64(args, OMEGA_DEC_SW_GU, (uintptr_t)gu); put64(args, OMEGA_DEC_SW_ACT, (uintptr_t)act); putf(args, OMEGA_DEC_SW_SCALE, 1.0f); - WsRange r2[2] = { rr[5], { (uintptr_t)act, (uintptr_t)act + sizeof act } }; - if (sim_one(mut ? &K_sw_m1 : &K_sw, args, OMEGA_DEC_SW_WORDS, INTER / OMEGA_DEC_THREADS, TK, r2, 2, "swiglu")) return 1; - int bad = 0; for (unsigned i = 0; i < TK * INTER; i++) if (!close_rel(act[i], g.act_ref[i], 5e-5f, 1e-6f)) bad++; - if (!mut) CHECK(bad == 0, "sim swiglu within 5e-5 (%d bad)", bad); else CHECK(bad > 0, "sim swiglu mutant caught"); - printf("sim swiglu mutant %d: %d/%u outside tolerance\n", mut, bad, TK * INTER); - } - for (int tie = 0; tie < 2; tie++) for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 300 + tie, tie); - uint32_t a0[OMEGA_DEC_AM_WORDS] = { 0 }, a1[OMEGA_DEC_AM_WORDS] = { 0 }; - static float ov2[1]; static uint32_t oi2[1]; - put64(a0, OMEGA_DEC_AM_V, (uintptr_t)logits); put64(a0, OMEGA_DEC_AM_I, 0); put64(a0, OMEGA_DEC_AM_OV, (uintptr_t)ov); put64(a0, OMEGA_DEC_AM_OI, (uintptr_t)oi); - put64(a1, OMEGA_DEC_AM_V, (uintptr_t)ov); put64(a1, OMEGA_DEC_AM_I, (uintptr_t)oi); put64(a1, OMEGA_DEC_AM_OV, (uintptr_t)ov2); put64(a1, OMEGA_DEC_AM_OI, (uintptr_t)oi2); - WsRange r3[4] = { { (uintptr_t)logits, (uintptr_t)logits + sizeof logits }, { (uintptr_t)ov, (uintptr_t)ov + sizeof ov }, { (uintptr_t)oi, (uintptr_t)oi + sizeof oi }, - { (uintptr_t)ov2, (uintptr_t)ov2 + 4 } }; - WsRange r4[5] = { r3[0], r3[1], r3[2], r3[3], { (uintptr_t)oi2, (uintptr_t)oi2 + 4 } }; - if (sim_one(mut ? &K_am_m1 : &K_am0, a0, OMEGA_DEC_AM_WORDS, AM_CTAS, 1, r4, 5, "argmax stage 1")) return 1; - if (sim_one(&K_am1, a1, OMEGA_DEC_AM_WORDS, 1, 1, r4, 5, "argmax stage 2")) return 1; - if (!mut) CHECK(oi2[0] == g.am_ref && ov2[0] == logits[g.am_ref], "sim argmax tie %d: %u (ref %u)", tie, oi2[0], g.am_ref); - else if (tie) CHECK(oi2[0] != g.am_ref, "sim argmax mutant caught (max at a j == 7 slot)"); - printf("sim argmax tie %d mutant %d: index %u value %g (ref %u)\n", tie, mut, oi2[0], ov2[0], g.am_ref); - } - return g_failed ? 1 : 0; -} - -/* ---- chip ---- */ -static OmegaGpuLaunch axpy_launch(const Kern *k, uint32_t *args, uint32_t stride, uint32_t iters) { - OmegaGpuLaunch L; memset(&L, 0, sizeof L); - L.code_va = k->code.va; L.gpr_count = k->gpr; L.threads_x = OMEGA_DEC_THREADS; L.threads_y = 1; L.grid_x = stride / OMEGA_DEC_THREADS; L.grid_y = 1; - L.num_elements = (size_t)stride * iters; L.args = args; L.n_args = OMEGA_DEC_AXPY_WORDS; L.timeout_ms = 20000; - return L; -} -static int chip_fail(const char *what) { printf("FAIL: %s: %s\n", what, omega_gpu_session_last_error()); g_checks++; g_failed++; return 1; } - -typedef struct { uint32_t L; uint64_t base_ns, pcas_ns, inline_ns, base_wall_ns, pcas_wall_ns, pcas_submits, inline_submits; int pcas_ok, inline_ok; uint64_t stamps_span_ns, stamps_min_ns, stamps_max_ns, stamps_chip_ns; } Row; - -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (specs_build()) { printf("FAIL: codegen\n"); return 1; } - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(OMEGA_GPU_CMDLIST_MAX_LAUNCHES, &cl) != 0) return chip_fail("cmdlist create"); - omega_gpu_session_lock(); - Kern *ks[] = { &K_axpy, &K_axpy_big, &K_res_an, &K_res_cn, &K_res_m1, &K_res_m2, &K_res_cn_m1, &K_sw, &K_sw_m1, &K_am0, &K_am1, &K_am_m1 }; - for (unsigned i = 0; i < sizeof ks / sizeof ks[0]; i++) if (kern_upload(ks[i])) { omega_gpu_session_unlock(); return chip_fail("kernel upload"); } - OmegaGpuMem bx, ba, bx0; - const size_t big = (size_t)AXPY_BIG_STRIDE * AXPY_BIG_ITERS * 4u; - if (omega_gpu_session_alloc(big, &bx) || omega_gpu_session_alloc(big, &ba) || omega_gpu_session_alloc(big, &bx0)) { omega_gpu_session_unlock(); return chip_fail("alloc"); } - uint32_t s = 11; float *x0 = bx0.cpu, *a = ba.cpu, *x = bx.cpu; - for (size_t i = 0; i < big / 4; i++) { x0[i] = frand(&s, -1, 1); a[i] = frand(&s, -1, 1); } - omega_gpu_session_sync_to_gpu(&ba); - uint32_t args[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(args, OMEGA_DEC_AXPY_X, bx.va); put64(args, OMEGA_DEC_AXPY_A, ba.va); args[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = 1; - OmegaGpuLaunch L = axpy_launch(&K_axpy, args, AXPY_STRIDE, 1); - static float base[AXPY_STRIDE], xref[AXPY_STRIDE]; - const uint32_t Ls[] = { 64, 289, 1024 }; - Row rows[3]; memset(rows, 0, sizeof rows); - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_CMDLIST_V1\",\"reps\":%u,\"spin_us\":%u,\"rows\":[", reps, omega_gpu_session_spin_us()); - for (unsigned li = 0; li < 3; li++) { - const uint32_t N = Ls[li]; - Row *r = &rows[li]; r->L = N; - memcpy(xref, x0, sizeof xref); for (uint32_t l = 0; l < N; l++) for (unsigned i = 0; i < AXPY_STRIDE; i++) xref[i] = xref[i] + a[i]; - /* baseline: one session launch at a time */ - uint64_t *tb = calloc(reps, 8), *tw = calloc(reps, 8), *tp = calloc(reps, 8), *tpw = calloc(reps, 8), *ti = calloc(reps, 8); - int base_ok = 1; - for (uint32_t rep = 0; rep < reps && base_ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - uint64_t ns = 0; struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { base_ok = 0; chip_fail("baseline launch"); break; } - clock_gettime(CLOCK_MONOTONIC, &t1); - omega_gpu_session_sync_to_cpu(&bx); - if (rep == 0) memcpy(base, x, sizeof base); - tb[rep] = ns; tw[rep] = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000000ull + (uint64_t)(t1.tv_nsec - t0.tv_nsec); - } - if (!base_ok) break; - CHECK(memcmp(base, xref, sizeof base) == 0, "L=%u baseline x == host reference (bit-identical)", N); - r->base_ns = median_u64(tb, reps); r->base_wall_ns = median_u64(tw, reps); - /* main: one list, PCAS */ - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - OmegaGpuCmdListStats st; int ok = 1; - for (uint32_t rep = 0; rep < reps && ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_cmdlist_add(cl, &L) < 0) { ok = 0; chip_fail("cmdlist add"); break; } - if (!ok) break; - struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); - int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - clock_gettime(CLOCK_MONOTONIC, &t1); - omega_gpu_session_sync_to_cpu(&bx); - if (rc != 0) { ok = 0; printf("PCAS L=%u rep %u: submit rc %d (%s) sems_done %u first_missing %d\n", N, rep, rc, omega_gpu_session_last_error(), st.sems_done, st.first_missing); break; } - if (memcmp(x, base, sizeof base) != 0) { ok = 0; printf("PCAS L=%u rep %u: x differs from the baseline\n", N, rep); break; } - tp[rep] = st.elapsed_ns; tpw[rep] = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000000ull + (uint64_t)(t1.tv_nsec - t0.tv_nsec); - r->pcas_submits = st.submits; - } - r->pcas_ok = ok; - CHECK(ok, "L=%u PCAS list: every rep bit-identical to the baseline, all semaphores DONE", N); - if (ok) { r->pcas_ns = median_u64(tp, reps); r->pcas_wall_ns = median_u64(tpw, reps); } - if (omega_gpu_cmdlist_is_latched()) { printf("cmdlist latched; stopping\n"); break; } - /* instrument: GPU timestamps around every launch (stamps on), x still identical; stamps off -> accessor refuses */ - if (ok) { - static uint64_t stamps[1025]; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) (void)omega_gpu_cmdlist_add(cl, &L); - OmegaGpuCmdListOpts os = o; os.stamps = 1; - int rc = omega_gpu_cmdlist_submit(cl, &os, &st); - omega_gpu_session_sync_to_cpu(&bx); - int cnt = omega_gpu_cmdlist_stamps(cl, stamps, 1025); - int mono = 1; uint64_t mn = UINT64_MAX, mx = 0; - for (int i = 1; i < cnt; i++) { if (stamps[i] < stamps[i - 1]) mono = 0; uint64_t d = stamps[i] - stamps[i - 1]; if (d < mn) mn = d; if (d > mx) mx = d; } - const uint64_t span = cnt > 1 ? stamps[cnt - 1] - stamps[0] : 0; - CHECK(rc == 0 && memcmp(x, base, sizeof base) == 0 && cnt == (int)N + 1 && mono && span > 0 && span <= st.elapsed_ns, - "L=%u stamps on: rc %d, x identical, %d stamps (want %u), monotonic %d, span %.1f us <= chip %.1f us, per launch min %.2f max %.2f us", - N, rc, cnt, N + 1, mono, span / 1e3, st.elapsed_ns / 1e3, mn / 1e3, mx / 1e3); - r->stamps_span_ns = span; r->stamps_min_ns = mn; r->stamps_max_ns = mx; r->stamps_chip_ns = st.elapsed_ns; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) (void)omega_gpu_cmdlist_add(cl, &L); - rc = omega_gpu_cmdlist_submit(cl, &o, &st); - cnt = omega_gpu_cmdlist_stamps(cl, stamps, 1025); - CHECK(rc == 0 && cnt < 0, "L=%u stamps off: submit rc %d, stamps accessor refuses (%d)", N, rc, cnt); - } - /* INLINE mode (the session's own words per launch, several submissions) */ - o.mode = OMEGA_GPU_CMDLIST_INLINE; ok = 1; - for (uint32_t rep = 0; rep < reps && ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_cmdlist_add(cl, &L) < 0) { ok = 0; chip_fail("cmdlist add"); break; } - if (!ok) break; - int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - if (rc != 0) { ok = 0; printf("INLINE L=%u rep %u: submit rc %d (%s) sems_done %u first_missing %d\n", N, rep, rc, omega_gpu_session_last_error(), st.sems_done, st.first_missing); break; } - if (memcmp(x, base, sizeof base) != 0) { ok = 0; printf("INLINE L=%u rep %u: x differs from the baseline\n", N, rep); break; } - ti[rep] = st.elapsed_ns; r->inline_submits = st.submits; - } - r->inline_ok = ok; - CHECK(ok, "L=%u INLINE list: every rep bit-identical to the baseline, all semaphores DONE", N); - if (ok) r->inline_ns = median_u64(ti, reps); - if (omega_gpu_cmdlist_is_latched()) { printf("cmdlist latched; stopping\n"); break; } - printf("L=%u: baseline %.1f us/launch (chip %.1f us, wall %.1f us per launch); PCAS %s %.2f us/launch (wall %.2f, %" PRIu64 " submits); INLINE %s %.2f us/launch (%" PRIu64 " submits)\n", - N, r->base_ns / 1e3 / N, r->base_ns / 1e3 / N, r->base_wall_ns / 1e3 / N, r->pcas_ok ? "ok" : "FAIL", r->pcas_ns / 1e3 / N, r->pcas_wall_ns / 1e3 / N, r->pcas_submits, - r->inline_ok ? "ok" : "FAIL", r->inline_ns / 1e3 / N, r->inline_submits); - if (out) fprintf(out, "%s{\"L\":%u,\"baseline_ns\":%" PRIu64 ",\"baseline_wall_ns\":%" PRIu64 ",\"pcas_ok\":%d,\"pcas_ns\":%" PRIu64 ",\"pcas_wall_ns\":%" PRIu64 ",\"pcas_submits\":%" PRIu64 ",\"inline_ok\":%d,\"inline_ns\":%" PRIu64 ",\"inline_submits\":%" PRIu64 ",\"stamps_span_ns\":%" PRIu64 ",\"stamps_min_ns\":%" PRIu64 ",\"stamps_max_ns\":%" PRIu64 ",\"stamps_chip_ns\":%" PRIu64 "}", - li ? "," : "", N, r->base_ns, r->base_wall_ns, r->pcas_ok, r->pcas_ns, r->pcas_wall_ns, r->pcas_submits, r->inline_ok, r->inline_ns, r->inline_submits, r->stamps_span_ns, r->stamps_min_ns, r->stamps_max_ns, r->stamps_chip_ns); - free(tb); free(tw); free(tp); free(tpw); free(ti); - } - if (out) fprintf(out, "],"); - /* negative control: drop launch 32 of 64 from the stream; the semaphore check must name it */ - if (!omega_gpu_cmdlist_is_latched()) { - const uint32_t N = 64; - memcpy(xref, x0, sizeof xref); for (uint32_t l = 0; l + 1 < N; l++) for (unsigned i = 0; i < AXPY_STRIDE; i++) xref[i] = xref[i] + a[i]; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) omega_gpu_cmdlist_add(cl, &L); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; o.skip_launch = 33; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - CHECK(rc != 0 && st.first_missing == 32 && st.sems_done == N - 1, "negative control: skipped launch 32 caught (rc %d, first_missing %d, sems_done %u)", rc, st.first_missing, st.sems_done); - CHECK(memcmp(x, xref, sizeof base) == 0, "negative control: x == x0 + 63 a (the other 63 launches ran)"); - printf("negative control skip_launch=33: rc %d first_missing %d sems_done %u/%u x %s\n", rc, st.first_missing, st.sems_done, N, memcmp(x, xref, sizeof base) == 0 ? "x0+63a" : "UNEXPECTED"); - if (out) fprintf(out, "\"skip_control\":{\"rc\":%d,\"first_missing\":%d,\"sems_done\":%u},", rc, st.first_missing, st.sems_done); - } - /* informational: no WFI between heavy dependent launches (256 CTAs x 16 iterations each, 32 launches) */ - if (!omega_gpu_cmdlist_is_latched()) { - const uint32_t N = 32; const size_t n = (size_t)AXPY_BIG_STRIDE * AXPY_BIG_ITERS; - float *xr = malloc(n * 4); memcpy(xr, x0, n * 4); - for (uint32_t l = 0; l < N; l++) for (size_t i = 0; i < n; i++) xr[i] = xr[i] + a[i]; - uint32_t ab[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(ab, OMEGA_DEC_AXPY_X, bx.va); put64(ab, OMEGA_DEC_AXPY_A, ba.va); ab[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = AXPY_BIG_ITERS; - OmegaGpuLaunch LB = axpy_launch(&K_axpy_big, ab, AXPY_BIG_STRIDE, AXPY_BIG_ITERS); - size_t diff_wfi = 0, diff_none = 0; uint64_t ns_wfi = 0, ns_none = 0; int rc_wfi = -1, rc_none = -1; - for (int variant = 0; variant < 2; variant++) { - memcpy(x, x0, n * 4); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) omega_gpu_cmdlist_add(cl, &LB); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - o.barrier = variant ? OMEGA_GPU_CMDLIST_BARRIER_NONE : OMEGA_GPU_CMDLIST_BARRIER_WFI; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - size_t d = 0; for (size_t i = 0; i < n; i++) if (x[i] != xr[i]) d++; - if (variant) { diff_none = d; ns_none = st.elapsed_ns; rc_none = rc; } else { diff_wfi = d; ns_wfi = st.elapsed_ns; rc_wfi = rc; } - if (omega_gpu_cmdlist_is_latched()) break; - } - CHECK(rc_wfi == 0 && diff_wfi == 0, "heavy chain with WFI: rc %d, %zu of %zu elements differ", rc_wfi, diff_wfi, n); - printf("heavy chain (32 x 1M elements): WFI rc %d %zu differ %.1f us; BARRIER_NONE rc %d %zu differ %.1f us (informational: %s)\n", - rc_wfi, diff_wfi, ns_wfi / 1e3, rc_none, diff_none, ns_none / 1e3, - diff_none ? "grids overlapped without the barrier: the WFI is load-bearing" : "no difference seen; this does not prove ordering without a barrier"); - if (out) fprintf(out, "\"no_barrier_control\":{\"wfi_rc\":%d,\"wfi_diff\":%zu,\"wfi_ns\":%" PRIu64 ",\"none_rc\":%d,\"none_diff\":%zu,\"none_ns\":%" PRIu64 "},", rc_wfi, diff_wfi, ns_wfi, rc_none, diff_none, ns_none); - free(xr); - } - /* glue kernels in one list: RES ADD|NORM, SWIGLU, RES COMBINE|NORM, ARGMAX x2; then mutants */ - if (!omega_gpu_cmdlist_is_latched()) { - OmegaGpuMem m; if (omega_gpu_session_alloc(4u * (H + TK * H + TK + H + H + TK * 2 * INTER + TK * INTER + AM_PAD + 2 * OMEGA_DEC_ARGMAX_SPAN + 2 * OMEGA_DEC_ARGMAX_SPAN), &m)) { omega_gpu_session_unlock(); return chip_fail("alloc glue"); } - float *p = m.cpu; uint64_t va = m.va; - Glue g; g.x = p; g.a8 = p + H; g.w = g.a8 + TK * H; g.nw = g.w + TK; g.y = g.nw + H; g.gu = g.y + H; g.act = g.gu + TK * 2 * INTER; g.logits = g.act + TK * INTER; - g.ov = g.logits + AM_PAD; g.oi = (uint32_t *)(g.ov + OMEGA_DEC_ARGMAX_SPAN); float *ov2 = (float *)(g.oi + OMEGA_DEC_ARGMAX_SPAN); uint32_t *oi2 = (uint32_t *)(ov2 + OMEGA_DEC_ARGMAX_SPAN); -#define VA(ptr) (va + (uint64_t)((const uint8_t *)(ptr) - (const uint8_t *)p)) - static float x_after_an[H], y_an[H], y_cn[H], act_ref[TK * INTER], x_after_cn[H]; - /* 0 real; 1 norm-without-weight in slot 2 (the norm whose output is compared: slot 0 norm output is overwritten by - * slot 2, chip run r2 showed a slot-0 mutant cannot show); 2 combine skips expert 7 in slot 2; 3 argmax mutant */ - for (int mut = 0; mut < 4; mut++) { - for (int tie = mut == 0 ? 0 : 1; tie < 2; tie++) { /* mutants run on the tie case: the max sits in a j == 7 slot */ - glue_fill(&g, 400 + tie, tie); - memcpy(x_after_an, g.x, sizeof x_after_an); ref_res(OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, x_after_an, g.a8, g.w, g.nw, y_an, EPS, 1.0f); - ref_swiglu(g.gu, act_ref, 1.0f); - memcpy(x_after_cn, x_after_an, sizeof x_after_cn); ref_res(OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, x_after_cn, g.a8, g.w, g.nw, y_cn, EPS, SCALE_2P64); - omega_gpu_session_sync_to_gpu(&m); - uint32_t ra[OMEGA_DEC_RES_WORDS] = { 0 }, rb[OMEGA_DEC_RES_WORDS] = { 0 }, sa[OMEGA_DEC_SW_WORDS] = { 0 }, a0[OMEGA_DEC_AM_WORDS] = { 0 }, a1[OMEGA_DEC_AM_WORDS] = { 0 }; - put64(ra, OMEGA_DEC_RES_X, VA(g.x)); put64(ra, OMEGA_DEC_RES_A, VA(g.a8)); put64(ra, OMEGA_DEC_RES_W, VA(g.w)); put64(ra, OMEGA_DEC_RES_NW, VA(g.nw)); put64(ra, OMEGA_DEC_RES_Y, VA(g.y)); putf(ra, OMEGA_DEC_RES_EPS, EPS); putf(ra, OMEGA_DEC_RES_SCALE, 1.0f); - memcpy(rb, ra, sizeof rb); putf(rb, OMEGA_DEC_RES_SCALE, SCALE_2P64); - put64(sa, OMEGA_DEC_SW_GU, VA(g.gu)); put64(sa, OMEGA_DEC_SW_ACT, VA(g.act)); putf(sa, OMEGA_DEC_SW_SCALE, 1.0f); - put64(a0, OMEGA_DEC_AM_V, VA(g.logits)); put64(a0, OMEGA_DEC_AM_I, 0); put64(a0, OMEGA_DEC_AM_OV, VA(g.ov)); put64(a0, OMEGA_DEC_AM_OI, VA(g.oi)); - put64(a1, OMEGA_DEC_AM_V, VA(g.ov)); put64(a1, OMEGA_DEC_AM_I, VA(g.oi)); put64(a1, OMEGA_DEC_AM_OV, VA(ov2)); put64(a1, OMEGA_DEC_AM_OI, VA(oi2)); - OmegaGpuLaunch l[5]; memset(l, 0, sizeof l); - for (int i = 0; i < 5; i++) { l[i].threads_x = OMEGA_DEC_THREADS; l[i].threads_y = 1; l[i].grid_y = 1; l[i].timeout_ms = 20000; } - Kern *k0 = &K_res_an, *k2 = mut == 1 ? &K_res_cn_m1 : mut == 2 ? &K_res_m2 : &K_res_cn, *k3 = mut == 3 ? &K_am_m1 : &K_am0; - l[0].code_va = k0->code.va; l[0].gpr_count = k0->gpr; l[0].grid_x = 1; l[0].num_elements = H; l[0].args = ra; l[0].n_args = OMEGA_DEC_RES_WORDS; - l[1].code_va = K_sw.code.va; l[1].gpr_count = K_sw.gpr; l[1].grid_x = INTER / OMEGA_DEC_THREADS; l[1].grid_y = TK; l[1].num_elements = TK * INTER; l[1].args = sa; l[1].n_args = OMEGA_DEC_SW_WORDS; - l[2].code_va = k2->code.va; l[2].gpr_count = k2->gpr; l[2].grid_x = 1; l[2].num_elements = H; l[2].args = rb; l[2].n_args = OMEGA_DEC_RES_WORDS; - l[3].code_va = k3->code.va; l[3].gpr_count = k3->gpr; l[3].grid_x = AM_CTAS; l[3].num_elements = AM_PAD; l[3].args = a0; l[3].n_args = OMEGA_DEC_AM_WORDS; - l[4].code_va = K_am1.code.va; l[4].gpr_count = K_am1.gpr; l[4].grid_x = 1; l[4].num_elements = OMEGA_DEC_ARGMAX_SPAN; l[4].args = a1; l[4].n_args = OMEGA_DEC_AM_WORDS; - omega_gpu_cmdlist_reset(cl); - int ok = 1; for (int i = 0; i < 5; i++) if (omega_gpu_cmdlist_add(cl, &l[i]) < 0) { ok = 0; chip_fail("glue add"); } - if (!ok) break; - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&m); - int xbad = memcmp(g.x, x_after_cn, sizeof x_after_cn) != 0, ybad = 0, abad = 0; - for (unsigned i = 0; i < H; i++) if (!close_rel(g.y[i], y_cn[i], 2e-5f, 1e-6f)) ybad++; - for (unsigned i = 0; i < TK * INTER; i++) if (!close_rel(g.act[i], act_ref[i], 5e-5f, 1e-6f)) abad++; - int ambad = oi2[0] != g.am_ref; - if (mut == 0) { - CHECK(rc == 0, "glue list rc %d (%s)", rc, rc ? omega_gpu_session_last_error() : ""); - CHECK(!xbad, "glue tie %d: residual x after ADD then COMBINE bit-identical to the host reference", tie); - CHECK(ybad == 0, "glue tie %d: final RMSNorm (scale 2^64) within 2e-5 (%d bad)", tie, ybad); - CHECK(abad == 0, "glue tie %d: SwiGLU within 5e-5 (%d bad)", tie, abad); - CHECK(!ambad, "glue tie %d: argmax %u == host %u (value %g)", tie, oi2[0], g.am_ref, ov2[0]); - printf("glue list tie %d: rc %d, 5 launches in %u submit(s) %.1f us chip; x %s, y %d bad, act %d bad, argmax %u (ref %u)\n", tie, rc, st.submits, st.elapsed_ns / 1e3, xbad ? "DIFFERS" : "identical", ybad, abad, oi2[0], g.am_ref); - if (out) fprintf(out, "\"glue_tie%d\":{\"rc\":%d,\"chip_ns\":%" PRIu64 ",\"x_identical\":%d,\"y_bad\":%d,\"act_bad\":%d,\"argmax\":%u,\"argmax_ref\":%u},", tie, rc, st.elapsed_ns, !xbad, ybad, abad, oi2[0], g.am_ref); - } else { - int caught = mut == 3 ? ambad : (xbad || ybad); - CHECK(rc == 0 && caught, "chip mutant %d caught (rc %d, x %s, y %d bad, argmax %u ref %u)", mut, rc, xbad ? "differs" : "same", ybad, oi2[0], g.am_ref); - printf("chip mutant %d: rc %d, x %s, y %d bad, argmax %u (ref %u): %s\n", mut, rc, xbad ? "differs" : "same", ybad, oi2[0], g.am_ref, caught ? "caught" : "NOT CAUGHT"); - } - if (omega_gpu_cmdlist_is_latched()) break; - } - if (omega_gpu_cmdlist_is_latched()) break; - } -#undef VA - omega_gpu_session_free(&m); - } - omega_gpu_session_free(&bx); omega_gpu_session_free(&ba); omega_gpu_session_free(&bx0); - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - if (out) { fprintf(out, "\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; uint32_t reps = 20; const char *out = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) omega_gpu_session_set_spin_us((uint32_t)atoi(argv[++i])); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out = argv[++i]; - else { printf("usage: %s [--host-only|--sim] [--reps N] [--spin-us U] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0) reps = 1; - int rc = host ? host_only() : sim ? sim_mode() : chip_run(out, reps); - printf("%s: %d checks, %d failed: %s\n", host ? "host-only" : sim ? "sim" : "chip", g_checks, g_failed, rc ? "FAIL" : "PASS"); - return rc; -} diff --git a/tests/gpu_decode_attn_test.c b/tests/gpu_decode_attn_test.c deleted file mode 100644 index 6a30d1835..000000000 --- a/tests/gpu_decode_attn_test.c +++ /dev/null @@ -1,456 +0,0 @@ -/* - * gpu_decode_attn_test: the one-launch decode attention (OWN-30B cut 8, omega_gpu_decode_attn_api.h). - * --host-only host pieces: bf16 rounding, RoPE row, reference sanity (context 1 returns v_new, a one-hot - * key wins), codegen budget per depth and mutant, refusals. No device. - * --sim the kernel through tests/bw_warp_sim_k.h (no chip): contexts 1, 7, 256, 257, 301, 701 (1..3 - * splits, the cross-split combine), both fragment orders, every mutant caught at context 301. - * (default) the chip: parity against the double reference at contexts 1, 7, 256, 1024, 4096, 8192, 32768 - * (the appended K/V row read back and compared), second call identical, timing medians with - * the host caches evicted, every mutant caught at context 301, JSON receipt with --out. - * Tolerance: |out - ref| <= 3e-3 * max|v| + 1e-6 per element (MUFU.EX2 / RSQ are 2^-22-ish, bf16 rounding of the - * appended K/V can flip one ulp against the f32 chip path). The mutants miss by 0.1 .. 1.0 of that scale. - * --q-heads Q --kv-heads K --head-dim D: any geometry other than 32 / 4 / 128 is REFUSED with reasons (exit 3, receipt - * verdict "REFUSED"); e.g. the BitNet b1.58 layout 20 / 5 / 128 (ternary engine T0). - * Host and simulator passes are never chip results. - */ -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_hostmath.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; /* config.json rope_theta */ -static const float EPS = 1e-6f; - -/* one layer's random state: qkv, history rows (bf16) for 4 KV heads, norms */ -typedef struct { - uint32_t max_pos, pos; - float qkv[OMEGA_GPU_DATTN_QKV_WORDS], qn[128], kn[128]; - uint16_t *kc, *vc; /* [4][max_pos][128] (history 0..pos-1 filled; the rest zero) */ - float vmax; -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos = pos; - for (size_t i = 0; i < OMEGA_GPU_DATTN_QKV_WORDS; i++) c->qkv[i] = frand(&s, -1.0f, 1.0f) * (i < 4096 ? qscale : 1.0f); - for (unsigned i = 0; i < 128; i++) { c->qn[i] = frand(&s, 0.8f, 1.2f); c->kn[i] = frand(&s, 0.8f, 1.2f); } - size_t words = (size_t)4 * max_pos * 128; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - c->vmax = 1.0f; - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < pos; t++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + t) * 128 + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->kc); free(c->vc); } - -/* ---- double-precision oracle (test-owned: it uses libm, which the library does not link) ---- - * RMSNorm + RoPE of one head (double), in place; cs: cos[64], sn: sin[64] */ -static void norm_rope(double *x, const float *w, float eps, const double *cs, const double *sn, int rope) { - double ss = 0; for (unsigned i = 0; i < 128; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / 128.0 + (double)eps); - for (unsigned i = 0; i < 128; i++) x[i] = x[i] * r * (double)w[i]; - if (!rope) return; - double y[128]; - for (unsigned i = 0; i < 64; i++) { y[i] = x[i] * cs[i] - x[i + 64] * sn[i]; y[i + 64] = x[i + 64] * cs[i] + x[i] * sn[i]; } - memcpy(x, y, sizeof y); -} -/* Reference of the whole layer step. kc/vc: this layer's bf16 planes [4][max_pos][128] holding positions 0..pos-1; - * out: [32*128] doubles (already * out_scale); k_new/v_new: the bf16 rows the kernel must have appended at pos - * ([4][128] each). The reference rounds its k_new/v_new to bf16 and attends over the rounded values. */ -static void omega_decode_attn_reference(const float *qkv, const uint16_t *kc, const uint16_t *vc, uint32_t max_pos, uint32_t pos, - const float *q_norm, const float *k_norm, float eps, double rope_theta, float out_scale, - double *out, uint16_t *k_new, uint16_t *v_new) { - double cs[64], sn[64]; - for (unsigned i = 0; i < 64; i++) { double ang = (double)pos * pow(rope_theta, -(double)(2 * i) / 128.0); cs[i] = cos(ang); sn[i] = sin(ang); } - const double qscale = 1.0 / sqrt(128.0); - for (unsigned gk = 0; gk < 4; gk++) { - double k[128]; - for (unsigned i = 0; i < 128; i++) k[i] = qkv[4096 + gk * 128 + i]; - norm_rope(k, k_norm, eps, cs, sn, 1); - for (unsigned i = 0; i < 128; i++) { k_new[gk * 128 + i] = omega_dattn_bf16_rne((float)k[i]); v_new[gk * 128 + i] = omega_dattn_bf16_rne(qkv[4096 + 512 + gk * 128 + i]); } - } - double *p = calloc((size_t)pos + 1, sizeof(double)); - for (unsigned h = 0; h < 32; h++) { - unsigned gk = h / 8; - double q[128]; - for (unsigned i = 0; i < 128; i++) q[i] = qkv[h * 128 + i]; - norm_rope(q, q_norm, eps, cs, sn, 1); - double mx = -1e300; - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *kr = t == pos ? k_new + gk * 128 : kc + ((size_t)gk * max_pos + t) * 128; - double s = 0; for (unsigned i = 0; i < 128; i++) s += q[i] * (double)omega_dattn_bf16_f32(kr[i]); - s *= qscale; p[t] = s; if (s > mx) mx = s; - } - double l = 0; for (uint32_t t = 0; t <= pos; t++) { p[t] = exp(p[t] - mx); l += p[t]; } - double o[128]; memset(o, 0, sizeof o); - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *vr = t == pos ? v_new + gk * 128 : vc + ((size_t)gk * max_pos + t) * 128; - for (unsigned i = 0; i < 128; i++) o[i] += p[t] * (double)omega_dattn_bf16_f32(vr[i]); - } - for (unsigned i = 0; i < 128; i++) out[h * 128 + i] = o[i] / l * (double)out_scale; - } - free(p); -} - -/* the library's libm-free host math against libm: RoPE rows bit-equal or within one f32 ulp, double values close */ -static void host_math_vs_libm(void) { - uint32_t s = 77; unsigned flips = 0, worse = 0; double maxd = 0; - static const uint32_t fixed[] = { 0, 1, 2, 3, 100, 255, 256, 4095, 4096, 8191, 32767, 32768, 65535 }; - for (unsigned n = 0; n < 1000 + sizeof fixed / sizeof fixed[0]; n++) { - uint32_t pos = n < sizeof fixed / sizeof fixed[0] ? fixed[n] : lcg(&s) % 65536u; - float row[128]; omega_dattn_rope_row(pos, THETA, row); - for (unsigned i = 0; i < 64; i++) { - double ang = (double)pos * pow(THETA, -(double)(2 * i) / 128.0); - float c = (float)cos(ang), sn = (float)sin(ang); - uint32_t a, b; memcpy(&a, &row[i], 4); memcpy(&b, &c, 4); - int dc = (int)a - (int)b; memcpy(&a, &row[64 + i], 4); memcpy(&b, &sn, 4); int ds = (int)a - (int)b; - if (dc < -1 || dc > 1 || ds < -1 || ds > 1) worse++; else if (dc || ds) flips++; - } - } - CHECK(worse == 0, "rope rows vs libm: %u entries differ by more than one f32 ulp", worse); - printf("rope rows vs libm: 1013 positions x 64 dims, %u one-ulp differences, %u worse\n", flips, worse); - for (unsigned n = 0; n < 200000; n++) { - double a = ((double)(lcg(&s) % 2000001u) - 1000000.0) * (n & 1 ? 1.0 : 1e-6), hs, hc; - omega_hostmath_sincos(a, &hs, &hc); - double d = fabs(hs - sin(a)); if (d > maxd) maxd = d; d = fabs(hc - cos(a)); if (d > maxd) maxd = d; - } - CHECK(maxd < 1e-14, "hostmath sincos vs libm over |a| <= 1e6: max abs diff %.3g", maxd); - double maxr = 0; - for (unsigned n = 0; n < 200000; n++) { - double b = 1e-6 + (double)(lcg(&s) % 100000000u) * 1e-1, e = ((double)(lcg(&s) % 20001u) - 10000.0) / 10000.0 * 4.0; - double h = omega_hostmath_pow(b, e), l = pow(b, e), r = fabs(h - l) / l; if (r > maxr) maxr = r; - h = omega_hostmath_exp(e * 20.0); l = exp(e * 20.0); r = fabs(h - l) / l; if (r > maxr) maxr = r; - h = omega_hostmath_log(b); l = log(b); r = fabs(h - l) / (1.0 + fabs(l)); if (r > maxr) maxr = r; - } - CHECK(maxr < 1e-13, "hostmath pow/exp/log vs libm: max rel diff %.3g", maxr); - printf("hostmath vs libm: sincos max abs %.3g, pow/exp/log max rel %.3g\n", maxd, maxr); - CHECK(omega_hostmath_exp(0.0) == 1.0 && omega_hostmath_log(1.0) == 0.0 && omega_hostmath_pow(THETA, 0.0) == 1.0, "hostmath identities"); - CHECK(omega_hostmath_log(-1.0) != omega_hostmath_log(-1.0) && omega_hostmath_exp(-800.0) == 0.0, "hostmath log(-1) is NaN, exp(-800) is 0"); -} - -/* compares out (f32 [4096]) against the reference; returns the number of elements outside the tolerance and the worst ratio */ -static size_t parity(const Case *c, const float *out, float out_scale, double *worst, uint16_t *k_new, uint16_t *v_new) { - double *ref = malloc(4096 * sizeof(double)); - omega_decode_attn_reference(c->qkv, c->kc, c->vc, c->max_pos, c->pos, c->qn, c->kn, EPS, THETA, out_scale, ref, k_new, v_new); - double tol = 3e-3 * c->vmax * out_scale + 1e-6 * out_scale; size_t bad = 0; *worst = 0; - for (size_t i = 0; i < 4096; i++) { double d = fabs((double)out[i] - ref[i]); if (d / tol > *worst) *worst = d / tol; if (d > tol) bad++; } - free(ref); - return bad; -} -/* appended rows: v exact, k within one bf16 ulp on at most 4 elements per head */ -static int rows_ok(const uint16_t *k_chip, const uint16_t *v_chip, const uint16_t *k_ref, const uint16_t *v_ref, char *why, size_t n) { - unsigned kflips = 0; - for (unsigned i = 0; i < 512; i++) { - if (v_chip[i] != v_ref[i]) { snprintf(why, n, "v[%u] chip %04x ref %04x", i, v_chip[i], v_ref[i]); return 0; } - if (k_chip[i] != k_ref[i]) { int d = (int)k_chip[i] - (int)k_ref[i]; if (d < -1 || d > 1) { snprintf(why, n, "k[%u] chip %04x ref %04x", i, k_chip[i], k_ref[i]); return 0; } kflips++; } - } - if (kflips > 16) { snprintf(why, n, "%u one-ulp k flips", kflips); return 0; } - snprintf(why, n, "ok (%u one-ulp k flips)", kflips); - return 1; -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - CHECK(omega_dattn_bf16_rne(1.0f) == 0x3f80, "bf16 of 1.0"); - CHECK(omega_dattn_bf16_rne(1.00390625f) == 0x3f80, "bf16 rounds 1 + 2^-8 to even (down)"); - CHECK(omega_dattn_bf16_rne(1.01171875f) == 0x3f82, "bf16 rounds 1 + 3 * 2^-8 to even (up)"); - CHECK(omega_dattn_bf16_rne(-2.5f) == 0xc020, "bf16 of -2.5"); - float row[128]; omega_dattn_rope_row(0, THETA, row); - int ok = 1; for (unsigned i = 0; i < 64; i++) ok &= row[i] == 1.0f && row[64 + i] == 0.0f; - CHECK(ok, "rope row 0 is cos 1 sin 0"); - omega_dattn_rope_row(100, THETA, row); - CHECK(fabs((double)row[0] - cos(100.0)) < 1e-6 && fabs((double)row[64] - sin(100.0)) < 1e-6, "rope row 100 dim 0 is cos/sin(100)"); - CHECK(fabs((double)row[63] - cos(100.0 * pow(THETA, -126.0 / 128.0))) < 1e-6, "rope row 100 dim 63 uses theta^(-126/128)"); - host_math_vs_libm(); - /* reference sanity: context 1 returns v_new (rounded), whatever q and k */ - { Case c; case_make(&c, 256, 0, 11, 1.0f); double *ref = malloc(4096 * sizeof(double)); uint16_t kn[512], vn[512]; - omega_decode_attn_reference(c.qkv, c.kc, c.vc, 256, 0, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - int good = 1; for (unsigned h = 0; h < 32 && good; h++) for (unsigned i = 0; i < 128; i++) if (ref[h * 128 + i] != (double)omega_dattn_bf16_f32(vn[(h / 8) * 128 + i])) { good = 0; break; } - CHECK(good, "reference: context 1 returns the rounded v_new of the head's KV group"); - /* a dominant key: history row 3 equal to the roped-normed q direction of head 0 scaled up -> output ~ v row 3 */ - free(ref); case_free(&c); } - { Case c; case_make(&c, 256, 8, 12, 1.0f); - double *ref = malloc(4096 * sizeof(double)); uint16_t kn[512], vn[512]; - omega_decode_attn_reference(c.qkv, c.kc, c.vc, 256, 8, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - /* k_new is unit-rms-ish: rms of the k_norm-weighted row around 1 */ - double ss = 0; for (unsigned i = 0; i < 128; i++) { double v = omega_dattn_bf16_f32(kn[i]); ss += v * v; } - CHECK(ss / 128.0 > 0.6 && ss / 128.0 < 1.5, "reference: k_new has rms about 1 after RMSNorm (%.3f)", ss / 128.0); - double os = 0; for (unsigned i = 0; i < 4096; i++) os += fabs(ref[i]); - CHECK(os / 4096.0 < 0.6, "reference: a 9-token softmax average of U(-1,1) rows is small (%.3f)", os / 4096.0); - free(ref); case_free(&c); } - /* codegen budget */ - for (uint32_t d = 1; d <= 4; d++) for (int m = 0; m <= 4; m++) { - OmegaDecodeAttnSpec s = { d, m }; uint32_t n = 0, gp = 0; - int rc = omega_decode_attn_prog_stats(&s, &n, &gp); - CHECK(rc == 0 && n <= 1024 && gp <= 128, "codegen depth %u mutant %d: rc %d insns %u gprs %u", d, m, rc, n, gp); - if (rc == 0 && m == 0) printf("codegen depth %u: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536)\n", d, n, gp, ((gp + 8) / 8) * 8, 256 * ((gp + 8) / 8) * 8); - } - { OmegaDecodeAttnSpec s = { 0, 0 }; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "depth 0 refused"); - s.depth = 5; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "depth 5 refused"); - s.depth = 1; s.mutant = 5; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "mutant 5 refused"); } - CHECK(omega_gpu_decode_attn_cache_alloc(0, 256, THETA, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL out refused"); - { OmegaGpuDecodeAttnCache *c = (OmegaGpuDecodeAttnCache *)1; - CHECK(omega_gpu_decode_attn_cache_alloc(1, 100, THETA, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "max_pos not a multiple of 256 refused before any device work"); } - CHECK(OMEGA_DATTN_SHARED_BYTES <= 16384u, "shared memory within the QMD cap (%u)", OMEGA_DATTN_SHARED_BYTES); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int sim_point(uint32_t max_pos, uint32_t pos, uint32_t depth, int mutant, uint32_t per_split, float qscale, uint32_t seed, char *msg, size_t n, double *worst, size_t *bad, char *rows, size_t rn) { - static BlackwellIRProgram prog; - OmegaDecodeAttnSpec spec = { depth, mutant }; - if (omega_blackwell_codegen_decode_attn_prog(&spec, &prog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make(&c, max_pos, pos, seed, qscale); - const uint32_t splits = (pos + per_split) / per_split; - size_t plane = (size_t)4 * max_pos * 256 + OMEGA_DATTN_PLANE_SLACK; - uint8_t *kv = aligned_alloc(16, 2 * plane); memset(kv, 0, 2 * plane); - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); - float *rope = aligned_alloc(16, (size_t)max_pos * 512); for (uint32_t p = 0; p < max_pos; p++) omega_dattn_rope_row(p, THETA, rope + (size_t)p * 128); - float *norms = aligned_alloc(16, 1024); memcpy(norms, c.qn, 512); memcpy(norms + 128, c.kn, 512); - float *qkv = aligned_alloc(16, sizeof c.qkv); memcpy(qkv, c.qkv, sizeof c.qkv); - float *out = aligned_alloc(16, 4096 * 4), *copy = malloc(4096 * 4); - float *part = aligned_alloc(16, (size_t)4 * splits * OMEGA_DATTN_PARTIAL_WORDS * 4); - uint32_t *cnt = aligned_alloc(16, 16); - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 256; s.order = order; - static uint8_t smem[OMEGA_DATTN_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_DATTN_SHARED_BYTES; - memset(cnt, 0, 16); for (unsigned i = 0; i < 4096; i++) out[i] = -999.0f; - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); /* fresh history (the kernel appends) */ - uint64_t A[9] = { (uintptr_t)qkv, (uintptr_t)kv, (uintptr_t)(kv + plane), (uintptr_t)rope, (uintptr_t)norms, (uintptr_t)(norms + 128), (uintptr_t)out, (uintptr_t)part, (uintptr_t)cnt }; - for (unsigned i = 0; i < 9; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = 1.0f, fq = (float)((1.0 / sqrt(128.0)) * 1.4426950408889634); - memcpy(&s.cbank[OMEGA_DATTN_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_DATTN_ARG_OUT_SCALE / 4], &fo, 4); memcpy(&s.cbank[OMEGA_DATTN_ARG_QK_SCALE / 4], &fq, 4); - s.cbank[OMEGA_DATTN_ARG_POS / 4] = pos; s.cbank[OMEGA_DATTN_ARG_PER_SPLIT / 4] = per_split; s.cbank[OMEGA_DATTN_ARG_SPLITS / 4] = splits; s.cbank[OMEGA_DATTN_ARG_KV_STRIDE / 4] = max_pos * 256; - s.nranges = 7; - s.ranges[0].lo = (uintptr_t)qkv; s.ranges[0].hi = (uintptr_t)qkv + sizeof c.qkv; - s.ranges[1].lo = (uintptr_t)kv; s.ranges[1].hi = (uintptr_t)kv + 2 * plane; - s.ranges[2].lo = (uintptr_t)rope; s.ranges[2].hi = (uintptr_t)rope + (size_t)max_pos * 512; - s.ranges[3].lo = (uintptr_t)norms; s.ranges[3].hi = (uintptr_t)norms + 1024; - s.ranges[4].lo = (uintptr_t)out; s.ranges[4].hi = (uintptr_t)out + 4096 * 4; - s.ranges[5].lo = (uintptr_t)part; s.ranges[5].hi = (uintptr_t)part + (size_t)4 * splits * OMEGA_DATTN_PARTIAL_WORDS * 4; - s.ranges[6].lo = (uintptr_t)cnt; s.ranges[6].hi = (uintptr_t)cnt + 16; - err = ws_run(&s, splits, 4); - if (err) { snprintf(msg, n, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < 4096; i++) if (out[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - if (cnt[0] | cnt[1] | cnt[2] | cnt[3]) { err = -1; snprintf(msg, n, "counters not reset: %u %u %u %u", cnt[0], cnt[1], cnt[2], cnt[3]); break; } - if (order == 0) memcpy(copy, out, 4096 * 4); - else if (memcmp(copy, out, 4096 * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - uint16_t kn[512], vn[512]; - *bad = parity(&c, out, 1.0f, worst, kn, vn); - uint16_t kchip[512], vchip[512]; - for (unsigned g = 0; g < 4; g++) { memcpy(kchip + g * 128, kv + ((size_t)g * max_pos + pos) * 256, 256); memcpy(vchip + g * 128, kv + plane + ((size_t)g * max_pos + pos) * 256, 256); } - if (!rows_ok(kchip, vchip, kn, vn, rows, rn)) *bad += 1000; - if (getenv("DATTN_DUMP")) { for (int dr = -1; dr <= 1; dr++) { if ((int)pos + dr < 0) continue; const uint16_t *r = (const uint16_t *)(kv + plane + ((size_t)0 * max_pos + pos + dr) * 256); printf(" v row %d:", (int)pos + dr); for (unsigned i = 0; i < 12; i++) printf(" %04x", r[i]); printf(" ... ref:"); for (unsigned i = 0; i < 12; i++) printf(" %04x", vn[i]); printf("\n"); } - const uint16_t *r = (const uint16_t *)(kv + ((size_t)0 * max_pos + pos) * 256); printf(" k row %u:", pos); for (unsigned i = 0; i < 12; i++) printf(" %04x", r[i]); printf(" ... ref:"); for (unsigned i = 0; i < 12; i++) printf(" %04x", kn[i]); printf("\n"); } - snprintf(msg, n, "bad=%zu worst=%.3f rows: %s", *bad, *worst, rows); - } - free(kv); free(rope); free(norms); free(qkv); free(out); free(copy); free(part); free(cnt); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[300], rows[120]; double worst; size_t bad; - struct { uint32_t max_pos, pos, depth, per; float qscale; const char *name; } pts[] = { - { 256, 0, 1, 256, 1.0f, "context 1" }, - { 256, 6, 2, 256, 1.0f, "context 7" }, - { 256, 6, 4, 256, 4.0f, "context 7, sharp q (x4)" }, - { 256, 255, 4, 256, 1.0f, "context 256 (full chunk, 1 split)" }, - { 512, 256, 4, 256, 1.0f, "context 257 (2 splits, last holds one position)" }, - { 512, 300, 3, 256, 1.0f, "context 301 (2 splits)" }, - { 1024, 700, 4, 256, 1.0f, "context 701 (3 splits)" }, - { 1024, 700, 2, 512, 1.0f, "context 701 (per_split 512: 2 chunks per CTA)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - int err = sim_point(pts[i].max_pos, pts[i].pos, pts[i].depth, 0, pts[i].per, pts[i].qscale, 100 + (uint32_t)i, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - CHECK(err == 0 && bad == 0, "sim %s depth %u: %s", pts[i].name, pts[i].depth, msg); - printf("sim %-50s depth %u: %s %s\n", pts[i].name, pts[i].depth, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 4; m++) { - int err = sim_point(512, 300, 2, m, 256, 1.0f, 200, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim mutant %d NOT caught (%s)", m, msg); - printf("sim mutant %d at context 301: %s (%s)\n", m, caught ? "caught" : "MISSED", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; static const char *g_only; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static int fill_history(OmegaGpuDecodeAttnCache *cache, const Case *c) { - if (c->pos == 0) return OMEGA_GPU_DATTN_OK; - for (unsigned g = 0; g < 4; g++) { - int rc = omega_gpu_decode_attn_cache_write(cache, 0, g, 0, c->pos, c->kc + (size_t)g * c->max_pos * 128, c->vc + (size_t)g * c->max_pos * 128); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - } - return OMEGA_GPU_DATTN_OK; -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_DECODE_ATTN_V1\",\"reps\":%u,\"evict\":%d,\"points\":[", reps, g_evict); - const uint32_t MAXP = 32768; - OmegaGpuDecodeAttnCache *cache = NULL; - double t0 = now_ms(); - int rc = omega_gpu_decode_attn_cache_alloc(1, MAXP, THETA, &cache); - printf("cache alloc (1 layer, %u positions): rc=%s %.1f ms (%s)\n", MAXP, omega_gpu_decode_attn_rc_name(rc), now_ms() - t0, rc ? omega_gpu_decode_attn_last_error() : ""); - CHECK(rc == OMEGA_GPU_DATTN_OK, "cache alloc"); - if (rc != OMEGA_GPU_DATTN_OK) { if (out) fprintf(out, "],\"verdict\":\"FAIL\"}\n"); return 1; } - struct { uint32_t pos; float qscale; const char *name; } pts[] = { - { 0, 1.0f, "context 1" }, { 6, 1.0f, "context 7" }, { 255, 1.0f, "context 256" }, { 300, 4.0f, "context 301 sharp q" }, - { 1023, 1.0f, "context 1024" }, { 4095, 1.0f, "context 4096" }, { 8191, 1.0f, "context 8192" }, { 32767, 1.0f, "context 32768" }, - }; - int first = 1; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - if (g_only && !strstr(pts[i].name, g_only)) continue; - Case c; case_make(&c, MAXP, pts[i].pos, 500 + (uint32_t)i, pts[i].qscale); - CHECK(omega_gpu_decode_attn_set_norms(cache, 0, c.qn, c.kn) == OMEGA_GPU_DATTN_OK, "set norms"); - t0 = now_ms(); - rc = fill_history(cache, &c); - double fill_ms = now_ms() - t0; - float *y = malloc(4096 * 4), *y2 = malloc(4096 * 4); - OmegaGpuDecodeAttnInfo info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y, &info); - size_t bad = 0; double worst = 1e9; uint16_t kn[512], vn[512], kchip[512], vchip[512]; char rows[120] = "n/a"; - if (rc == OMEGA_GPU_DATTN_OK) { - bad = parity(&c, y, 1.0f, &worst, kn, vn); - for (unsigned g = 0; g < 4; g++) if (omega_gpu_decode_attn_cache_read(cache, 0, g, c.pos, kchip + g * 128, vchip + g * 128) != OMEGA_GPU_DATTN_OK) bad += 1000; - if (!rows_ok(kchip, vchip, kn, vn, rows, sizeof rows)) bad += 1000; - } - int ok = rc == OMEGA_GPU_DATTN_OK && bad == 0; - int same = 0; OmegaGpuDecodeAttnInfo i2; memset(&i2, 0, sizeof i2); - if (ok) { int r2 = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, &i2); same = r2 == OMEGA_GPU_DATTN_OK && memcmp(y, y2, 4096 * 4) == 0 && i2.kernel_cache_hit; } - CHECK(ok && same, "chip %s: rc=%s bad=%zu worst=%.3f rows=%s second-call-identical=%d (%s)", pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, omega_gpu_decode_attn_last_error()); - /* the out_scale path (2^64 for the FP8 x' row): bit-exact scaling is not required, a relative check is */ - if (ok) { - float *ys = malloc(4096 * 4); int r3 = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 18446744073709551616.0f, ys, NULL); - int good = r3 == OMEGA_GPU_DATTN_OK; double wr = 0; - for (unsigned k = 0; k < 4096 && good; k++) { double e = fabs((double)ys[k] / 18446744073709551616.0 - (double)y[k]); double r = e / (fabs((double)y[k]) + 1e-6); if (r > wr) wr = r; } - CHECK(good && wr < 1e-5, "chip %s: out_scale 2^64 matches the unscaled output (worst rel %.2e)", pts[i].name, wr); - free(ys); - } - uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl); uint32_t done = 0; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && ok; r++) { OmegaGpuDecodeAttnInfo ti; if (omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, &ti) != OMEGA_GPU_DATTN_OK) break; el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++; } - uint64_t med_el = 0, med_cl = 0; double gbs = 0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2]; gbs = med_el ? (double)info.kv_bytes / (double)med_el : 0; } - printf("chip %-24s rc=%-9s bad=%zu worst=%.3f rows=%s grid=%ux%u per_split=%u depth=%u kv_bytes=%" PRIu64 " fill=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus reps=%u\n", - pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el / 1e3, gbs, med_cl / 1e3, done); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"pos\":%u,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f,\"rows\":\"%s\",\"second_call_identical\":%d,\"grid_x\":%u,\"grid_y\":%u,\"per_split\":%u,\"depth\":%u," - "\"kv_bytes\":%" PRIu64 ",\"fill_ms\":%.1f,\"chip_median_ns\":%" PRIu64 ",\"gb_per_s\":%.1f,\"call_median_ns\":%" PRIu64 ",\"reps\":%u}", - first ? "" : ",", pts[i].name, c.pos, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el, gbs, med_cl, done); - first = 0; - free(el); free(cl); - if (ok && c.pos == 300) { - for (int m = 1; m <= 4; m++) { - omega_gpu_decode_attn_test_set_mutant(m); - (void)fill_history(cache, &c); /* mutant 3 must not inherit the row the honest kernel wrote */ - uint16_t zk[128] = { 0 }, zv[128] = { 0 }; (void)omega_gpu_decode_attn_cache_write(cache, 0, 0, c.pos, 1, zk, zv); - for (unsigned g = 1; g < 4; g++) (void)omega_gpu_decode_attn_cache_write(cache, 0, g, c.pos, 1, zk, zv); - int r = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, NULL); - size_t mb = 0; double mw = 0; uint16_t k2[512], v2[512]; - if (r == OMEGA_GPU_DATTN_OK) { mb = parity(&c, y2, 1.0f, &mw, k2, v2); } - int caught = r != OMEGA_GPU_DATTN_OK || mb > 0; - if (m == 4 && info.grid_x == 1) { printf("chip %-24s mutant 4: inert (1 split, the combine is not exercised)\n", pts[i].name); omega_gpu_decode_attn_test_set_mutant(0); continue; } - CHECK(caught, "chip mutant %d NOT caught", m); - printf("chip %-24s mutant %d: %s (rc=%s bad=%zu worst=%.3f)\n", pts[i].name, m, caught ? "caught" : "MISSED", omega_gpu_decode_attn_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f}", pts[i].name, m, caught, omega_gpu_decode_attn_rc_name(r), mb, mw); - omega_gpu_decode_attn_test_set_mutant(0); - } - } - free(y); free(y2); case_free(&c); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - omega_gpu_decode_attn_cache_free(cache); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_DECODE_ATTN_PASS" : "OMEGA_GPU_DECODE_ATTN_FAIL"); fclose(out); } - return 0; -} - -/* --q-heads Q --kv-heads K --head-dim D (ternary engine T0, 2026-10-15): asks for an attention geometry. The kernel is - * built for one geometry only (OMEGA_GPU_DATTN_Q_HEADS 32, OMEGA_GPU_DATTN_KV_HEADS 4, head dim 128, per-head q_norm / - * k_norm before RoPE). Any other geometry is REFUSED here, with the reasons recorded (receipt verdict "REFUSED", exit 3), - * instead of running a kernel that would read the wrong q / k / v slices. */ -static int geometry_refusal(uint32_t qh, uint32_t kvh, uint32_t hd, const char *out_path) { - if (qh == OMEGA_GPU_DATTN_Q_HEADS && kvh == OMEGA_GPU_DATTN_KV_HEADS && hd == 128u) return 0; - char why[4][200]; int nw = 0; - if (qh != OMEGA_GPU_DATTN_Q_HEADS || kvh != OMEGA_GPU_DATTN_KV_HEADS) - snprintf(why[nw++], sizeof why[0], "head layout fixed at %u query / %u KV heads (%u per KV head); asked %u / %u (%u per KV head)", - OMEGA_GPU_DATTN_Q_HEADS, OMEGA_GPU_DATTN_KV_HEADS, OMEGA_GPU_DATTN_Q_HEADS / OMEGA_GPU_DATTN_KV_HEADS, qh, kvh, kvh ? qh / kvh : 0); - snprintf(why[nw++], sizeof why[0], "fused q|k|v input fixed at %u words; the asked layout needs %u", OMEGA_GPU_DATTN_QKV_WORDS, (qh + 2u * kvh) * hd); - snprintf(why[nw++], sizeof why[0], "per-head q_norm / k_norm is built in (Qwen3); a model without QK norm needs a kernel without it"); - if (hd != 128u) snprintf(why[nw++], sizeof why[0], "head dim fixed at 128; asked %u", hd); - printf("REFUSED: decode attention at %u query / %u KV heads, head dim %u\n", qh, kvh, hd); - for (int i = 0; i < nw; i++) printf(" reason %d: %s\n", i + 1, why[i]); - printf(" needed: a decode attention kernel for this geometry (ternary engine design KT3)\n"); - if (out_path) { - FILE *f = fopen(out_path, "w"); - if (f) { - fprintf(f, "{\"test\":\"gpu_decode_attn_test\",\"q_heads\":%u,\"kv_heads\":%u,\"head_dim\":%u,\"kernel_q_heads\":%u,\"kernel_kv_heads\":%u,\"reasons\":[", - qh, kvh, hd, OMEGA_GPU_DATTN_Q_HEADS, OMEGA_GPU_DATTN_KV_HEADS); - for (int i = 0; i < nw; i++) fprintf(f, "%s\"%s\"", i ? "," : "", why[i]); - fprintf(f, "],\"needed\":\"KT3 decode attention for this geometry\",\"verdict\":\"REFUSED\"}\n"); - fclose(f); - } - } - printf("gpu_decode_attn_test: REFUSED (geometry %u/%u/%u not built)\n", qh, kvh, hd); - return 3; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 20, depth = 0, per = 0, spin = 2000; int sim_pos = -1; uint32_t sim_max = 256; - uint32_t q_heads = OMEGA_GPU_DATTN_Q_HEADS, kv_heads = OMEGA_GPU_DATTN_KV_HEADS, head_dim = 128; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--per-split") == 0 && i + 1 < argc) per = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else if (strcmp(argv[i], "--sim-pos") == 0 && i + 1 < argc) sim_pos = atoi(argv[++i]); - else if (strcmp(argv[i], "--sim-max") == 0 && i + 1 < argc) sim_max = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i]; - else if (strcmp(argv[i], "--q-heads") == 0 && i + 1 < argc) q_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--kv-heads") == 0 && i + 1 < argc) kv_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--head-dim") == 0 && i + 1 < argc) head_dim = (uint32_t)atoi(argv[++i]); - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - { int g = geometry_refusal(q_heads, kv_heads, head_dim, out_path); if (g) return g; } - if (host) host_only(); - if (sim && sim_pos >= 0 && sim_max <= (uint32_t)sim_pos) sim_max = (uint32_t)sim_pos + 1u; - if (sim && sim_pos >= 0) { char msg[300], rows[120]; double worst; size_t bad; int err = sim_point(sim_max, (uint32_t)sim_pos, depth ? depth : 2, 0, per ? per : 256, 1.0f, 777, msg, sizeof msg, &worst, &bad, rows, sizeof rows); printf("sim pos %d: %s %s\n", sim_pos, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); return err || bad; } - if (sim) sim_battery(); - if (!host && !sim) { - if (depth) omega_gpu_decode_attn_set_depth(depth); - if (per) omega_gpu_decode_attn_set_per_split(per); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_decode_attn_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_decode_graph_test.c b/tests/gpu_decode_graph_test.c deleted file mode 100644 index 7fc413fad..000000000 --- a/tests/gpu_decode_graph_test.c +++ /dev/null @@ -1,355 +0,0 @@ -/* - * gpu_decode_graph_test: OWN-30B W-L2a, one Qwen3-30B-A3B decode token as ONE command list (omega_gpu_decode_graph.h). - * --host-only glue-kernel specs the graph builds (codegen, no device) and the record entry points' argument refusals - * (default) chip, caller holds the GB10 lock. A synthetic Qwen3-30B-A3B-shaped step on random weights (hidden 2048, - * 128 experts top-8, intermediate 768, head_dim 128, 32/4 heads; --layers N (2), --vocab V (151936), - * pos 300 over a random KV prefix: 2 attention splits): - * A baseline = today's path: the four APIs one call at a time, host glue in C mirroring sc - * qwen3_moe_omega.rs step() (rmsnorm f64, x += o, device router, gate_up from the router's table, - * SwiGLU expf, down, combine, final rmsnorm, lm_head, argmax strict >) - * C main = the same step recorded as one list (omega_gpu_decode_graph_token) - * B the same list submitted one launch per submission (flush_each): batching comparison - * Checks: C deterministic over the reps; B == C bit for bit (x, hidden, logits, token); A vs C token - * identical and logits within tolerance; negative controls (SWIGLU mutant, COMBINE mutant) must fail - * the A-vs-C comparison. Per-token medians over --reps (20). --out receipt.json - * --red the C path with the wrong-wiring mutant 3 (attention at scale 1, not 2^64): this run MUST FAIL - * (red-before-green receipt). - * Verdict: exit 0 when every CHECK passed. - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include - -#define H 2048u -#define QKV 5120u -#define ATT 4096u -#define NE 128u -#define TK 8u -#define I 768u -#define EPS 1e-6f -#define POS 300u -#define MAX_POS 512u -#define SCALE_2P64 18446744073709551616.0f -/* A vs C logits: |dl| <= TOL_REL * max|l_A|. Sources of difference (header): RMSNorm f32 FFMA + MUFU.RSQ vs f64 host, - * SwiGLU MUFU EX2/RCP vs expf (~1e-7 relative each), carried through 2 layers of random weights and 2048-term sums; - * 1e-4 is ~100x that. Mutants move logits by O(1e-1..1) of max|l|. */ -#define TOL_REL 1e-4 - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -/* ---- host glue: the Rust step()'s operations ---- */ -static void rmsnorm(const float *x, const float *w, float *out) { /* tensor.rs rmsnorm */ - double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i]; - float s = (float)(1.0 / sqrt(sq / H + (double)EPS)); - for (unsigned i = 0; i < H; i++) out[i] = x[i] * s * w[i]; -} -static void swiglu(const float *gu, float *act) { /* qwen3_moe_omega.rs swiglu: g / (1 + exp(-g)) * up */ - for (unsigned g = 0; g < TK; g++) for (unsigned j = 0; j < I; j++) { - float v = gu[g * 2 * I + j]; - act[g * I + j] = v / (1.0f + expf(-v)) * gu[g * 2 * I + I + j]; - } -} -static uint32_t argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; } - -/* ---- the synthetic model ---- */ -typedef struct { - uint32_t layers, vocab; - OmegaGpuFp8Tensor *qkv, *o, *gu, *dn; /* shared by every layer (memory); norms, router and KV differ per layer */ - OmegaGpuRouter *router; - OmegaGpuDecodeAttnCache *attn; - OmegaGpuBf16Tensor *lm; - float *in_norm, *fnorm, *x0; -} Model; - -static int fp8_random(uint32_t seed, uint32_t e, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out) { - size_t wb = (size_t)e * n * k, sb = (size_t)e * (n / 128) * (k / 128); - uint8_t *w = malloc(wb); uint16_t *s = malloc(sb * 2); - if (!w || !s) { free(w); free(s); return -1; } - uint32_t st = seed; - for (size_t i = 0; i < wb; i += 4) { uint32_t r = lcg(&st); for (unsigned j = 0; j < 4 && i + j < wb; j++) w[i + j] = (uint8_t)((r >> (8 * j)) & 0xbfu); } /* |v| <= 1.875: never a NaN code */ - for (size_t i = 0; i < sb; i++) s[i] = bf16_rne(frand(&st, 0.02f, 0.04f)); - int rc = omega_gpu_fp8_tensor_upload(e, n, k, w, s, out); - free(w); free(s); - return rc; -} - -static int model_build(Model *m, uint32_t layers, uint32_t vocab) { - memset(m, 0, sizeof *m); m->layers = layers; m->vocab = vocab; - uint32_t s = 1234; - if (fp8_random(11, 1, QKV, H, &m->qkv) || fp8_random(12, 1, H, ATT, &m->o) || fp8_random(13, NE, 2 * I, H, &m->gu) || fp8_random(14, NE, H, I, &m->dn)) { printf("fp8 upload: %s\n", omega_gpu_fp8_last_error()); return -1; } - if (omega_gpu_router_alloc(layers, &m->router) != 0) { printf("router alloc: %s\n", omega_gpu_router_last_error()); return -1; } - uint16_t *gate = malloc((size_t)NE * H * 2); float *nw = malloc(H * 4); - m->in_norm = malloc((size_t)layers * H * 4); m->fnorm = malloc(H * 4); m->x0 = malloc(H * 4); - if (!gate || !nw || !m->in_norm || !m->fnorm || !m->x0) return -1; - for (uint32_t l = 0; l < layers; l++) { - for (size_t i = 0; i < (size_t)NE * H; i++) gate[i] = bf16_rne(frand(&s, -0.05f, 0.05f)); - for (unsigned i = 0; i < H; i++) nw[i] = frand(&s, 0.8f, 1.2f); - if (omega_gpu_router_set_layer(m->router, l, gate, nw) != 0 || omega_gpu_router_set_directory_fp8(m->router, l, m->gu, m->dn) != 0) { printf("router layer: %s\n", omega_gpu_router_last_error()); return -1; } - for (unsigned i = 0; i < H; i++) m->in_norm[(size_t)l * H + i] = frand(&s, 0.8f, 1.2f); - } - free(gate); free(nw); - for (unsigned i = 0; i < H; i++) { m->fnorm[i] = frand(&s, 0.8f, 1.2f); m->x0[i] = frand(&s, -1.0f, 1.0f); } - if (omega_gpu_decode_attn_cache_alloc(layers, MAX_POS, 1000000.0, &m->attn) != 0) { printf("attn alloc: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - float qn[128], kn[128]; uint16_t *kr = malloc((size_t)POS * 128 * 2), *vr = malloc((size_t)POS * 128 * 2); - if (!kr || !vr) return -1; - for (uint32_t l = 0; l < layers; l++) { - for (unsigned i = 0; i < 128; i++) { qn[i] = frand(&s, 0.8f, 1.2f); kn[i] = frand(&s, 0.8f, 1.2f); } - if (omega_gpu_decode_attn_set_norms(m->attn, l, qn, kn) != 0) return -1; - for (uint32_t h = 0; h < 4; h++) { - for (size_t i = 0; i < (size_t)POS * 128; i++) { kr[i] = bf16_rne(frand(&s, -1, 1)); vr[i] = bf16_rne(frand(&s, -1, 1)); } - if (omega_gpu_decode_attn_cache_write(m->attn, l, h, 0, POS, kr, vr) != 0) { printf("kv write: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - } - } - free(kr); free(vr); - uint16_t *lw = malloc((size_t)vocab * H * 2); - if (!lw) return -1; - for (size_t i = 0; i < (size_t)vocab * H; i++) lw[i] = bf16_rne(frand(&s, -0.05f, 0.05f)); - int rc = omega_gpu_bf16_tensor_upload(vocab, H, lw, &m->lm); - free(lw); - if (rc != 0) { printf("lm_head upload: %s\n", omega_gpu_bf16_last_error()); return -1; } - return 0; -} - -/* A: today's path, one API call at a time, host glue */ -static int step_host(const Model *m, float *x, float *hidden, float *logits, uint32_t *tok, uint32_t *launches) { - static float xn[H], qkv[QKV], att[ATT], op[H], gu[TK * 2 * I], act[TK * I], dn[TK * H], mo[H]; - uint32_t ids[TK], zero = 0; float wts[TK]; uint64_t xout = 0, tgu = 0, tdn = 0; - memcpy(x, m->x0, H * 4); *launches = 0; - for (uint32_t l = 0; l < m->layers; l++) { - rmsnorm(x, m->in_norm + (size_t)l * H, xn); - if (omega_gpu_fp8_gemv_grouped_f32(m->qkv, 1, &zero, xn, 1, qkv, NULL)) return printf("A qkv: %s\n", omega_gpu_fp8_last_error()), -1; - if (omega_gpu_decode_attn(m->attn, l, POS, qkv, EPS, 1.0f, att, NULL)) return printf("A attn: %s\n", omega_gpu_decode_attn_last_error()), -1; - if (omega_gpu_fp8_gemv_grouped_f32(m->o, 1, &zero, att, 1, op, NULL)) return printf("A o: %s\n", omega_gpu_fp8_last_error()), -1; - for (unsigned i = 0; i < H; i++) x[i] += op[i]; - if (omega_gpu_router(m->router, l, x, EPS, 1, SCALE_2P64, ids, wts, NULL)) return printf("A router: %s\n", omega_gpu_router_last_error()), -1; - omega_gpu_router_device_outputs(m->router, &xout, &tgu, &tdn); - if (omega_gpu_fp8_gemv_grouped_dev(m->gu, TK, tgu, xout, gu, NULL)) return printf("A gate_up: %s\n", omega_gpu_fp8_last_error()), -1; - swiglu(gu, act); - if (omega_gpu_fp8_gemv_grouped_f32(m->dn, TK, ids, act, TK, dn, NULL)) return printf("A down: %s\n", omega_gpu_fp8_last_error()), -1; - for (unsigned i = 0; i < H; i++) mo[i] = 0.0f; - for (unsigned g = 0; g < TK; g++) for (unsigned i = 0; i < H; i++) mo[i] += wts[g] * dn[g * H + i]; - for (unsigned i = 0; i < H; i++) x[i] += mo[i]; - *launches += 6; - } - rmsnorm(x, m->fnorm, hidden); - if (omega_gpu_bf16_gemv_f32(m->lm, hidden, logits, NULL)) return printf("A lm_head: %s\n", omega_gpu_bf16_last_error()), -1; - *launches += 1; - *tok = argmax(logits, m->vocab); - return 0; -} - -typedef struct { float x[H], hidden[H]; float *logits; uint32_t tok; } Out; -static int out_alloc(Out *o, uint32_t vocab) { memset(o, 0, sizeof *o); o->logits = malloc((size_t)vocab * 4); return o->logits ? 0 : -1; } - -static int run_graph(OmegaGpuDecodeGraph *gr, const Model *m, Out *o, OmegaGpuDecodeGraphStats *st) { - int rc = omega_gpu_decode_graph_token(gr, m->x0, POS, &o->tok, st); - if (rc != 0) { printf("graph token rc %d: %s\n", rc, omega_gpu_session_last_error()); return rc; } - return omega_gpu_decode_graph_read(gr, o->x, o->hidden, o->logits); -} - -typedef struct { double max_abs, scale; int tok_same; } Cmp; -static Cmp compare(const Out *a, const Out *c, uint32_t vocab) { - Cmp r = { 0, 0, a->tok == c->tok }; - for (uint32_t i = 0; i < vocab; i++) { double d = fabs((double)a->logits[i] - c->logits[i]); if (d > r.max_abs) r.max_abs = d; if (fabs(a->logits[i]) > r.scale) r.scale = fabs(a->logits[i]); } - return r; -} -static int cmp_pass(Cmp c) { return c.tok_same && c.max_abs <= TOL_REL * c.scale; } -static double max_rel(const float *a, const float *b, unsigned n) { double mx = 0, sc = 0; for (unsigned i = 0; i < n; i++) { double d = fabs((double)a[i] - b[i]); if (d > mx) mx = d; if (fabs(a[i]) > sc) sc = fabs(a[i]); } return sc > 0 ? mx / sc : mx; } - -static int host_only(void) { - static const struct { OmegaDecKind kind; uint32_t mode; int mutant; const char *name; } sp[] = { - { OMEGA_DEC_RES, OMEGA_DEC_RES_NORM, 0, "RES NORM" }, { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD, 0, "RES ADD" }, - { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 0, "RES COMBINE|NORM" }, { OMEGA_DEC_SWIGLU, 0, 0, "SWIGLU" }, - { OMEGA_DEC_ARGMAX, 0, 0, "ARGMAX identity" }, { OMEGA_DEC_ARGMAX, 1, 0, "ARGMAX indexed" }, - { OMEGA_DEC_SWIGLU, 0, 1, "SWIGLU mutant 1" }, { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 2, "RES COMBINE|NORM mutant 2" }, - }; - for (unsigned i = 0; i < sizeof sp / sizeof sp[0]; i++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = sp[i].kind; s.mode = sp[i].mode; s.mutant = sp[i].mutant; - uint32_t ins = 0, gpr = 0; int rc = omega_dec_prog_stats(&s, &ins, &gpr); - CHECK(rc == 0 && ins > 0, "%s builds (%u instructions, peak %u registers)", sp[i].name, ins, gpr); - } - OmegaDecSpec bad; memset(&bad, 0, sizeof bad); bad.kind = OMEGA_DEC_RES; bad.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_COMBINE; - CHECK(omega_dec_prog_stats(&bad, NULL, NULL) != 0, "RES ADD|COMBINE refused by codegen"); - /* record entry points refuse a missing list or missing device addresses before touching the device */ - CHECK(omega_gpu_fp8_gemv_grouped_record(NULL, NULL, 1, 1, 1, 1, 1) == OMEGA_GPU_FP8_BAD_ARGS, "fp8 record without a list: BAD_ARGS"); - CHECK(omega_gpu_bf16_gemv_record(NULL, NULL, 1, 1) == OMEGA_GPU_BF16_BAD_ARGS, "bf16 record without a list: BAD_ARGS"); - CHECK(omega_gpu_router_record(NULL, NULL, 0, 1, EPS, 1, 1.0f, NULL) == OMEGA_GPU_ROUTER_BAD_ARGS, "router record without a list: BAD_ARGS"); - CHECK(omega_gpu_decode_attn_record(NULL, NULL, 0, 0, 1, EPS, 1.0f, 1) == OMEGA_GPU_DATTN_BAD_ARGS, "decode attn record without a list: BAD_ARGS"); - OmegaGpuCmdList *fake = (OmegaGpuCmdList *)(uintptr_t)16; /* never dereferenced: the argument checks come first */ - CHECK(omega_gpu_fp8_gemv_grouped_record(fake, NULL, 1, 0, 1, 1, 1) == OMEGA_GPU_FP8_BAD_ARGS, "fp8 record with tab_va 0: BAD_ARGS"); - CHECK(omega_gpu_bf16_gemv_record(fake, NULL, 0, 1) == OMEGA_GPU_BF16_BAD_ARGS, "bf16 record with x_va 0: BAD_ARGS"); - CHECK(omega_gpu_router_record(fake, NULL, 0, 0, EPS, 1, 1.0f, NULL) == OMEGA_GPU_ROUTER_BAD_ARGS, "router record with a NULL router: BAD_ARGS"); - CHECK(omega_gpu_decode_attn_record(fake, NULL, 0, 0, 0, EPS, 1.0f, 1) == OMEGA_GPU_DATTN_BAD_ARGS, "decode attn record with a NULL cache: BAD_ARGS"); - OmegaGpuDecodeGraphConfig cfg; memset(&cfg, 0, sizeof cfg); - OmegaGpuDecodeGraph *gr = NULL; - CHECK(omega_gpu_decode_graph_create(&cfg, &gr) == OMEGA_GPU_DGRAPH_BAD_ARGS && !gr, "graph create with an empty config: BAD_ARGS"); - return g_failed ? 1 : 0; -} - -static int chip_run(uint32_t layers, uint32_t vocab, uint32_t reps, int red, int cached, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"layers\":%u,\"vocab\":%u,\"pos\":%u,\"reps\":%u,\"red\":%d,\"cached_weights\":%d,", layers, vocab, POS, reps, red, cached); - omega_gpu_fp8_set_weight_cache(cached); /* one variable: the FP8 tensors uploaded below live GPU-cached or not */ - Model m; - uint64_t t0 = omega_gpu_session_now_ns(); - if (model_build(&m, layers, vocab) != 0) { CHECK(0, "synthetic model build"); return 1; } - printf("model built in %.1f s (layers %u, vocab %u, pos %u)\n", (omega_gpu_session_now_ns() - t0) / 1e9, layers, vocab, POS); - OmegaGpuDecodeGraphConfig cfg = { .layers = layers, .vocab = vocab, .eps = EPS, .norm_topk = 1, .router = m.router, .attn = m.attn, .lm_head = m.lm }; - OmegaGpuDecodeGraph *gr = NULL; - int rc = omega_gpu_decode_graph_create(&cfg, &gr); - if (rc != 0) { CHECK(0, "graph create rc %d: %s", rc, omega_gpu_session_last_error()); return 1; } - for (uint32_t l = 0; l < layers; l++) - if (omega_gpu_decode_graph_set_layer(gr, l, m.qkv, m.o, m.gu, m.dn, m.in_norm + (size_t)l * H) != 0) { CHECK(0, "set_layer %u", l); return 1; } - if (omega_gpu_decode_graph_set_final_norm(gr, m.fnorm) != 0) { CHECK(0, "set_final_norm"); return 1; } - - Out A, A0, C, C0, B; uint64_t *ta = calloc(reps, 8), *tc = calloc(reps, 8), *tb = calloc(reps, 8), *cc = calloc(reps, 8), *cb = calloc(reps, 8), *rcn = calloc(reps, 8); - if (out_alloc(&A, vocab) || out_alloc(&A0, vocab) || out_alloc(&C, vocab) || out_alloc(&C0, vocab) || out_alloc(&B, vocab) || !ta || !tc || !tb || !cc || !cb || !rcn) return 1; - - /* A: baseline first (also fills every API's kernel cache, so no record has to build) */ - uint32_t la = 0; int a_ok = 1, a_det = 1; - for (uint32_t r = 0; r < reps && a_ok; r++) { - uint64_t s = omega_gpu_session_now_ns(); - if (step_host(&m, A.x, A.hidden, A.logits, &A.tok, &la) != 0) { a_ok = 0; break; } - ta[r] = omega_gpu_session_now_ns() - s; - if (r == 0) { memcpy(A0.x, A.x, sizeof A.x); memcpy(A0.hidden, A.hidden, sizeof A.hidden); memcpy(A0.logits, A.logits, (size_t)vocab * 4); A0.tok = A.tok; } - else if (A.tok != A0.tok || memcmp(A.logits, A0.logits, (size_t)vocab * 4)) a_det = 0; - } - CHECK(a_ok, "A (baseline, host glue) %u reps ran", reps); - if (!a_ok) return 1; - CHECK(a_det, "A deterministic over %u reps (token %u)", reps, A0.tok); - /* top-2 gap of the baseline: how much margin the argmax identity has */ - uint32_t t1 = A0.tok, t2 = t1 == 0 ? 1 : 0; for (uint32_t i = 0; i < vocab; i++) if (i != t1 && A0.logits[i] > A0.logits[t2]) t2 = i; - printf("A: token %u logit %.6f, runner-up %u logit %.6f (gap %.3g)\n", t1, A0.logits[t1], t2, A0.logits[t2], (double)A0.logits[t1] - A0.logits[t2]); - - if (red) omega_gpu_decode_graph_test_set_mutant(gr, 3); - /* C: one list per token */ - OmegaGpuDecodeGraphStats st; memset(&st, 0, sizeof st); uint32_t lc = 0, sc = 0; int c_ok = 1, c_det = 1; - for (uint32_t r = 0; r < reps && c_ok; r++) { - if (run_graph(gr, &m, &C, &st) != 0) { c_ok = 0; break; } - tc[r] = st.total_ns; cc[r] = st.chip_ns; rcn[r] = st.record_ns; lc = st.launches; sc = st.submits; - if (r == 0) { C0 = C; C0.logits = malloc((size_t)vocab * 4); memcpy(C0.logits, C.logits, (size_t)vocab * 4); } - else if (C.tok != C0.tok || memcmp(C.logits, C0.logits, (size_t)vocab * 4) || memcmp(C.x, C0.x, sizeof C.x)) c_det = 0; - } - CHECK(c_ok, "C (one list per token) %u reps ran: %u launches in %u submission(s)", reps, lc, sc); - if (!c_ok) return 1; - CHECK(c_det, "C deterministic over %u reps (token %u)", reps, C0.tok); - Cmp ac = compare(&A0, &C0, vocab); - double xr = max_rel(A0.x, C0.x, H), hr = max_rel(A0.hidden, C0.hidden, H); - printf("A vs C: token %u vs %u, logits max |d| %.3g (scale %.3g, rel %.3g, tol %.0e), x max rel %.3g, hidden max rel %.3g\n", - A0.tok, C0.tok, ac.max_abs, ac.scale, ac.max_abs / ac.scale, TOL_REL, xr, hr); - CHECK(ac.tok_same, "argmax token identical: A %u, C %u", A0.tok, C0.tok); - CHECK(ac.max_abs <= TOL_REL * ac.scale, "logits A vs C within %.0e of max|logit| (max |d| %.3g, scale %.3g)", TOL_REL, ac.max_abs, ac.scale); - if (out) fprintf(out, "\"A\":{\"token\":%u,\"runner_up\":%u,\"gap\":%.6g,\"launches\":%u},\"C\":{\"token\":%u,\"launches\":%u,\"submits\":%u},\"A_vs_C\":{\"tok_same\":%d,\"logit_max_abs\":%.6g,\"logit_scale\":%.6g,\"x_max_rel\":%.6g,\"hidden_max_rel\":%.6g,\"tol_rel\":%g},", - t1, t2, (double)A0.logits[t1] - A0.logits[t2], la, C0.tok, lc, sc, ac.tok_same, ac.max_abs, ac.scale, xr, hr, TOL_REL); - - if (!red) { - /* B: same list, one launch per submission: bit-identical to C */ - omega_gpu_decode_graph_set_flush_each(gr, 1); - uint32_t lb = 0, sb = 0; int b_ok = 1, b_same = 1; - for (uint32_t r = 0; r < reps && b_ok; r++) { - if (run_graph(gr, &m, &B, &st) != 0) { b_ok = 0; break; } - tb[r] = st.total_ns; cb[r] = st.chip_ns; lb = st.launches; sb = st.submits; - if (B.tok != C0.tok || memcmp(B.logits, C0.logits, (size_t)vocab * 4) || memcmp(B.x, C0.x, sizeof B.x) || memcmp(B.hidden, C0.hidden, sizeof B.hidden)) b_same = 0; - } - omega_gpu_decode_graph_set_flush_each(gr, 0); - CHECK(b_ok, "B (one launch per submission) %u reps ran: %u launches in %u submissions", reps, lb, sb); - CHECK(b_ok && b_same, "B bit-identical to C (x, hidden, logits, token) in every rep"); - - /* negative controls: a mutant glue kernel in C must fail the A-vs-C comparison */ - for (int mut = 1; mut <= 2; mut++) { - omega_gpu_decode_graph_test_set_mutant(gr, mut); - Out M; out_alloc(&M, vocab); - int mrc = run_graph(gr, &m, &M, &st); - Cmp mc = compare(&A0, &M, vocab); - CHECK(mrc == 0 && !cmp_pass(mc), "negative control: %s mutant fails the comparison (token %u vs %u, max |d| %.3g = %.3g of scale)", - mut == 1 ? "SWIGLU" : "COMBINE", M.tok, A0.tok, mc.max_abs, mc.max_abs / mc.scale); - if (out) fprintf(out, "\"mutant%d\":{\"rc\":%d,\"token\":%u,\"logit_max_abs\":%.6g,\"caught\":%d},", mut, mrc, M.tok, mc.max_abs, mrc == 0 && !cmp_pass(mc)); - free(M.logits); - } - omega_gpu_decode_graph_test_set_mutant(gr, 0); - /* after the mutants the real list must still agree (state not poisoned) */ - int prc = run_graph(gr, &m, &C, &st); - CHECK(prc == 0 && C.tok == C0.tok && !memcmp(C.logits, C0.logits, (size_t)vocab * 4), "C after the mutants bit-identical to the first C"); - - if (out) { uint64_t h = 1469598103934665603ull; const unsigned char *b = (const unsigned char *)C0.logits; for (size_t i = 0; i < (size_t)vocab * 4; i++) { h ^= b[i]; h *= 1099511628211ull; } - fprintf(out, "\"C0_token\":%u,\"C0_logits_fnv\":\"%016" PRIx64 "\",", C0.tok, h); } - /* timeline instrument: stamps on -> one timestamp per launch, monotonic, span within the chip time; token unchanged; off -> refuses */ - { - static uint64_t sts[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; static uint8_t kinds[OMEGA_GPU_CMDLIST_MAX_LAUNCHES]; - omega_gpu_decode_graph_set_stamps(gr, 1); - Out S; out_alloc(&S, vocab); - int src_ = run_graph(gr, &m, &S, &st); - int n = omega_gpu_decode_graph_stamps(gr, sts, kinds, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - int mono = 1; uint64_t per_kind[OMEGA_GPU_DGRAPH_K_COUNT] = { 0 }; uint32_t cnt_kind[OMEGA_GPU_DGRAPH_K_COUNT] = { 0 }; - for (int i = 0; i < n; i++) { if (sts[i + 1] < sts[i]) mono = 0; if (kinds[i] < OMEGA_GPU_DGRAPH_K_COUNT) { per_kind[kinds[i]] += sts[i + 1] - sts[i]; cnt_kind[kinds[i]]++; } } - const uint64_t span = n > 0 ? sts[n] - sts[0] : 0; - CHECK(src_ == 0 && n == (int)st.launches && mono && span > 0 && span <= st.chip_ns && S.tok == C0.tok && !memcmp(S.logits, C0.logits, (size_t)vocab * 4), - "timeline: rc %d, %d stamps for %u launches, monotonic %d, span %.1f us <= chip %.1f us, token and logits unchanged", src_, n, st.launches, mono, span / 1e3, st.chip_ns / 1e3); - printf("TIMELINE (%u layers, pos %u):", layers, POS); - for (unsigned k = 0; k < OMEGA_GPU_DGRAPH_K_COUNT; k++) if (cnt_kind[k]) printf(" %s x%u %.1f us", omega_gpu_decode_graph_kind_name((uint8_t)k), cnt_kind[k], per_kind[k] / 1e3); - printf("\n"); - if (out) { fprintf(out, "\"timeline\":{\"launches\":%d,\"span_ns\":%" PRIu64 ",\"chip_ns\":%" PRIu64 ",\"per_kind_ns\":{", n, span, st.chip_ns); - int first = 1; for (unsigned k = 0; k < OMEGA_GPU_DGRAPH_K_COUNT; k++) if (cnt_kind[k]) { fprintf(out, "%s\"%s\":[%u,%" PRIu64 "]", first ? "" : ",", omega_gpu_decode_graph_kind_name((uint8_t)k), cnt_kind[k], per_kind[k]); first = 0; } - fprintf(out, "}},"); } - omega_gpu_decode_graph_set_stamps(gr, 0); - int orc = run_graph(gr, &m, &S, &st); - int n2 = omega_gpu_decode_graph_stamps(gr, sts, kinds, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - CHECK(orc == 0 && n2 < 0, "timeline off: token rc %d, stamps accessor refuses (%d)", orc, n2); - free(S.logits); - } - uint64_t ma = median_u64(ta, reps), mc_ = median_u64(tc, reps), mb = median_u64(tb, reps), mcc = median_u64(cc, reps), mcb = median_u64(cb, reps), mr = median_u64(rcn, reps); - printf("PER TOKEN (median of %u, %u layers): A host-glue %u launches %.1f us | C one list %u launches %.1f us (chip %.1f us, record %.1f us) | B per-launch submits %u launches %.1f us (chip sum %.1f us)\n", - reps, layers, la, ma / 1e3, lc, mc_ / 1e3, mcc / 1e3, mr / 1e3, lb, mb / 1e3, mcb / 1e3); - if (out) fprintf(out, "\"median_ns\":{\"A_total\":%" PRIu64 ",\"C_total\":%" PRIu64 ",\"C_chip\":%" PRIu64 ",\"C_record\":%" PRIu64 ",\"B_total\":%" PRIu64 ",\"B_chip\":%" PRIu64 "},\"B\":{\"launches\":%u,\"submits\":%u,\"identical\":%d},", - ma, mc_, mcc, mr, mb, mcb, lb, sb, b_ok && b_same); - } - omega_gpu_decode_graph_free(gr); - if (out) { fprintf(out, "\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, red = 0, cached = 0, variant = 0, barrier = -1, prefetch = 0, prefetch_red = 0; uint32_t cta_budget = 0, sh_lane = 0, sh_rows = 0, sh_warps = 0; uint32_t reps = 20, layers = 2, vocab = 151936; const char *out = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--red") == 0) red = 1; - else if (strcmp(argv[i], "--cached-weights") == 0) cached = 1; - else if (strcmp(argv[i], "--prefetch") == 0) prefetch = 1; /* W-L2d: o_proj weight prefetch beside the attention */ - else if (strcmp(argv[i], "--prefetch-red") == 0) prefetch = prefetch_red = 1; /* its red: o_proj unordered, MUST FAIL */ - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) cta_budget = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--variant") == 0 && i + 1 < argc) variant = atoi(argv[++i]); /* FP8 GEMV generator: 1 (default) or 2 (W-L2c) */ - else if (strcmp(argv[i], "--barrier") == 0 && i + 1 < argc) barrier = atoi(argv[++i]); /* per-launch barrier mode (W-L2c): 0 wfi+inval_all, 2 wfi_only, 3 wfi+inval_data, 4 flush_data */ - else if (strcmp(argv[i], "--shape") == 0 && i + 3 < argc) { sh_lane = (uint32_t)atoi(argv[++i]); sh_rows = (uint32_t)atoi(argv[++i]); sh_warps = (uint32_t)atoi(argv[++i]); } - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--layers") == 0 && i + 1 < argc) layers = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--vocab") == 0 && i + 1 < argc) vocab = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out = argv[++i]; - else { printf("usage: %s [--host-only] [--red] [--reps N] [--layers N] [--vocab V] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0) reps = 1; - if (layers == 0 || layers > 8) layers = 2; - if (variant) omega_gpu_fp8_set_variant(variant); - omega_gpu_decode_graph_set_prefetch(prefetch); omega_gpu_decode_graph_test_set_prefetch_red(prefetch_red); - if (barrier == 1) omega_gpu_decode_graph_test_set_barrier_none(); /* negative control: this run MUST FAIL */ - else if (barrier >= 0) omega_gpu_decode_graph_set_barrier(barrier); - if (cta_budget) omega_gpu_fp8_set_cta_budget(cta_budget); /* one variable per run (timeline sweeps) */ - if (sh_lane) omega_gpu_fp8_set_shape(sh_lane, sh_rows, sh_warps); - printf("dgraph prefetch %d (red %d)\n", omega_gpu_decode_graph_prefetch(), prefetch_red); - printf("fp8 knobs: variant %d barrier %d (%s) cta_budget %u shape %u/%u/%u cached %d\n", omega_gpu_fp8_variant(), omega_gpu_decode_graph_barrier(), omega_gpu_cmdlist_barrier_name((OmegaGpuCmdListBarrier)omega_gpu_decode_graph_barrier()), cta_budget, sh_lane, sh_rows, sh_warps, cached); - int rc = host ? host_only() : chip_run(layers, vocab, reps, red, cached, out); - printf("%s: %d checks, %d failed: %s\n", host ? "host-only" : red ? "chip-red" : "chip", g_checks, g_failed, rc ? "FAIL" : "PASS"); - return rc; -} diff --git a/tests/gpu_elementwise_test.c b/tests/gpu_elementwise_test.c deleted file mode 100644 index e485d0680..000000000 --- a/tests/gpu_elementwise_test.c +++ /dev/null @@ -1,387 +0,0 @@ -/* gpu_elementwise_test: FB-1 cut 4 gate for omega_gpu_elementwise_api. - * - * ./gpu_elementwise_test --host-only refusals, codegen, word fixtures, register budget, - * nvdisasm listing check when /usr/local/cuda/bin/nvdisasm exists - * ./gpu_elementwise_test --out receipt.json chip gate: every op against the host oracle, then its mutant - * (a deliberately wrong kernel) which the same check must catch - * ./gpu_elementwise_test --timing --out t.json cut 4b gate: persistent device, 100 calls each of rmsnorm 1x2048 - * and swiglu 5632 under 0.5 ms median, one device open per process - * - * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/tensor.rs (main 5fdab70) in C: - * rmsnorm sums in f64, rope computes cos/sin in f64 and casts to f32 before f32 math, swiglu is f64. - * This file is compiled with -ffp-contract=off so the f32 oracle math has no hidden fused multiply-add. - * - * Tolerances (why): EX2 1e-6 rel (PTX ex2.approx.f32: 2^-22.5 rel, we allow 2x). XCHG exact. - * RMSNORM 1e-5 rel + 1e-6 abs (f32 sum of up to 16384 squares against an f64 sum, plus RSQ seed with one - * Newton step; the mutant moves the scale by about 40 percent). ROPE exact (same f32 ops, same order). - * SWIGLU 1e-5 rel + 1e-6 abs (EX2 and RCP approximations, each about 2^-22 rel; the mutant flips the sign - * of the exponent, which is wrong by a factor of e^(2g)). - */ -#include "omega_gpu_elementwise_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } - -/* ----------------------------------------------------------------- oracles */ -static void oracle_rmsnorm(const float *x, const float *w, float eps, float *out, size_t dim) { - double ss = 0.0; - for (size_t i = 0; i < dim; i++) ss += (double)x[i] * (double)x[i]; - double mean = ss / (double)dim; - float scale = (float)(1.0 / sqrt(mean + (double)eps)); - for (size_t i = 0; i < dim; i++) { float t = x[i] * scale; out[i] = t * w[i]; } -} -static void oracle_rope_tables(size_t head_dim, size_t pos, float theta, float *cos_half, float *sin_half) { - size_t half = head_dim / 2; - for (size_t i = 0; i < half; i++) { - double exponent = (double)(2 * i) / (double)head_dim; - double freq = 1.0 / pow((double)theta, exponent); - double rot = (double)pos * freq; - sin_half[i] = (float)sin(rot); - cos_half[i] = (float)cos(rot); - } -} -static void oracle_rope(const float *v, size_t heads, size_t head_dim, const float *cos_half, const float *sin_half, float *out) { - size_t half = head_dim / 2; - for (size_t h = 0; h < heads; h++) - for (size_t i = 0; i < half; i++) { - size_t i0 = h * head_dim + i, i1 = i0 + half; - float q0 = v[i0], q1 = v[i1], c = cos_half[i], s = sin_half[i]; - float a = q0 * c, b = q1 * s; out[i0] = a - b; - float d = q0 * s, e = q1 * c; out[i1] = d + e; - } -} -static void oracle_swiglu(const float *g, const float *u, float *out, size_t n) { - for (size_t i = 0; i < n; i++) { double gg = g[i]; double silu = gg / (1.0 + exp(-gg)); out[i] = (float)(silu * (double)u[i]); } -} - -/* |got - want| <= rel*|want| + abs; returns the number of violations and the worst scaled error */ -static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { - size_t bad = 0; *worst = 0.0; - for (size_t i = 0; i < n; i++) { - double d = fabs((double)got[i] - (double)want[i]); - double lim = rel * fabs((double)want[i]) + abs_tol; - double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); - if (scaled > *worst) *worst = scaled; - if (!(d <= lim)) bad++; /* NaN counts as bad */ - } - return bad; -} - -/* ------------------------------------------------------------- host only */ -static int nvdisasm_check(OmegaGpuEwOp op, const char *name, const char *const *must, int n_must) { - const char *nv = "/usr/local/cuda/bin/nvdisasm"; - if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if (omega_gpu_elementwise_codegen(op, NULL, 0.0f, &k) != OMEGA_GPU_EW_OK) return -1; - char bin[64], lst[64], cmd[256]; - snprintf(bin, sizeof bin, "/tmp/omega_ew_%s_%d.bin", name, (int)getpid()); - snprintf(lst, sizeof lst, "/tmp/omega_ew_%s_%d.sass", name, (int)getpid()); - FILE *f = fopen(bin, "wb"); if (!f) { free(k.code); return -1; } - fwrite(k.code, 1, k.code_size, f); fclose(f); - snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); - int rc = system(cmd); - free(k.code); - FILE *l = fopen(lst, "r"); if (!l) return -1; - char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*0")) continue; - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; - } - fclose(l); - int miss = 0; - for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } - printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - unlink(bin); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} - -static void host_only(void) { - CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "word fixtures MUFU_EX2 / BAR_SYNC / LDS32 / STS32 (rc %d)", omega_blackwell_verify_codegen_fixtures_fb1cut4()); - float a[256] = {0}, b[256] = {0}, c[256] = {0}; - CHECK(omega_gpu_rmsnorm_f32(0, 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rows=0 refused"); - CHECK(omega_gpu_rmsnorm_f32(1, 100, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "dim not a multiple of 128 refused"); - CHECK(omega_gpu_rmsnorm_f32(1, OMEGA_GPU_EW_MAX_DIM + 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_TOO_LARGE, "dim over limit refused"); - CHECK(omega_gpu_rope_f32(1, 63, a, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "odd head_dim refused"); - CHECK(omega_gpu_rope_f32(1, 64, NULL, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "NULL vector refused"); - CHECK(omega_gpu_swiglu_f32(0, a, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "n=0 refused"); - CHECK(omega_gpu_shared_xchg_u32(100, (uint32_t *)a, (uint32_t *)c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "xchg n not a multiple of 128 refused"); - CHECK(strcmp(omega_gpu_elementwise_rc_name(OMEGA_GPU_EW_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); - - struct { OmegaGpuEwOp op; const char *name; const char *must[6]; int n; } ops[] = { - { OMEGA_GPU_EW_EX2, "ex2", { "MUFU.EX2", "@P0 EXIT", "STG.E" }, 3 }, - { OMEGA_GPU_EW_XCHG, "xchg", { "STS [R", "BAR.SYNC", "LDS R" }, 3 }, - { OMEGA_GPU_EW_RMSNORM, "rmsnorm", { "SHFL.DOWN", "BAR.SYNC", "MUFU.RSQ", "@!P0 BRA", "STS [R", "LDS R" }, 6 }, - { OMEGA_GPU_EW_ROPE, "rope", { "FADD", "FMUL", "STG.E" }, 3 }, - { OMEGA_GPU_EW_SWIGLU, "swiglu", { "MUFU.EX2", "MUFU.RCP", "@P0 EXIT" }, 3 }, - }; - for (size_t i = 0; i < sizeof ops / sizeof ops[0]; i++) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - int rc = omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k); - CHECK(rc == OMEGA_GPU_EW_OK && k.code_size > 0 && k.gpr_count <= 64, "%s kernel generated (rc %s, %zu insns, %u gprs)", ops[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count); - printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", ops[i].name, k.insn_count, k.gpr_count, k.uniform_gpr_count); - uint8_t digest[32]; memcpy(digest, k.code_digest, 32); - free(k.code); - /* the mutant must be a different kernel */ - omega_gpu_elementwise_test_set_mutant((int)ops[i].op); - memset(&k, 0, sizeof k); - CHECK(omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k) == OMEGA_GPU_EW_OK && memcmp(digest, k.code_digest, 32) != 0, "%s mutant kernel differs", ops[i].name); - free(k.code); - omega_gpu_elementwise_test_set_mutant(0); - CHECK(nvdisasm_check(ops[i].op, ops[i].name, ops[i].must, ops[i].n) == 0, "%s nvdisasm listing decodes and shows the expected instructions", ops[i].name); - } -} - -/* ------------------------------------------------------------- chip gate */ -typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; int mutant_rc; size_t mutant_bad; int mutant_caught; uint64_t chip_ns; uint32_t calls; uint32_t unwritten; } Case; -static Case g_cases[16]; static int g_ncases; - -static void record(Case c, FILE *out) { - g_cases[g_ncases++] = c; - CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst); - CHECK(c.mutant_caught, "%s mutant caught (rc=%s violations=%zu)", c.name, omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad); - printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " calls=%u unwritten=%u | mutant rc=%s violations=%zu %s\n", - c.pass && c.mutant_caught ? "PASS" : "FAIL", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.calls, c.unwritten, - omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "CAUGHT" : "NOT CAUGHT"); - if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"mutant_rc\":\"%s\",\"mutant_violations\":%zu,\"mutant_caught\":%s}", - g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.calls, c.unwritten, - omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "true" : "false"); -} - -static int chip(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_V1\",\"tolerances\":{\"ex2_rel\":1e-6,\"xchg\":\"exact\",\"rmsnorm_rel\":1e-5,\"rmsnorm_abs\":1e-6,\"rope\":\"exact\",\"swiglu_rel\":1e-5,\"swiglu_abs\":1e-6},\"cases\":["); - uint32_t seed = 0xfb1c0004u; - OmegaGpuEwInfo info; - - /* 1. EX2 probe, with a negative control on the comparison itself */ - { - size_t n = 4096; float *x = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *wrong = malloc(n * 4); - for (size_t i = 0; i < n; i++) { x[i] = frand(&seed, -20.0f, 20.0f); want[i] = (float)exp2((double)x[i]); wrong[i] = (float)exp2((double)x[i] + 1.0); } - Case c = { .name = "ex2_probe", .n = n }; - c.rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); - c.bad = compare(got, want, n, 1e-6, 0.0, &c.worst); - double w2; size_t neg = compare(got, wrong, n, 1e-6, 0.0, &w2); - CHECK(neg > n / 2, "ex2 negative control: the check rejects a wrong expectation (%zu of %zu flagged)", neg, n); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_EX2); - c.mutant_rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); - c.mutant_bad = compare(got, want, n, 1e-6, 0.0, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(got); free(want); free(wrong); - } - /* 2. shared-memory exchange probe (STS, BAR.SYNC, LDS) */ - { - size_t n = 4096; uint32_t *x = malloc(n * 4), *got = malloc(n * 4); - for (size_t i = 0; i < n; i++) x[i] = lcg(&seed); - Case c = { .name = "shared_xchg_probe", .n = n }; - c.rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); - for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.bad++; - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_XCHG); - c.mutant_rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); - for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.mutant_bad++; - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(got); - } - /* 3. rmsnorm at the model hidden sizes (TinyLlama and Llama-3.2-1B: 2048), plus small and large */ - { size_t dims[3] = { 2048, 256, 8192 }; size_t rowss[3] = { 4, 1, 2 }; - for (int t = 0; t < 3; t++) { - size_t dim = dims[t], rows = rowss[t], n = rows * dim; float eps = 1e-5f; - float *x = malloc(n * 4), *w = malloc(dim * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4); - for (size_t i = 0; i < n; i++) x[i] = frand(&seed, -3.0f, 3.0f); - for (size_t i = 0; i < dim; i++) w[i] = frand(&seed, 0.5f, 1.5f); - for (size_t r = 0; r < rows; r++) oracle_rmsnorm(x + r * dim, w, eps, want + r * dim, dim); - char name[64]; snprintf(name, sizeof name, "rmsnorm_%zux%zu", rows, dim); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); - c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - OmegaGpuEwInfo i2; int rc2 = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, again, &i2); - CHECK(rc2 == OMEGA_GPU_EW_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name); - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_RMSNORM); - double w2; c.mutant_rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); - c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(w); free(got); free(want); free(again); - } } - /* 4. rope: TinyLlama (32 q heads, 4 kv heads, head_dim 64, theta 10000) and Llama-3.2-1B (32/8, 64, 500000) */ - { struct { size_t heads, hd, pos; float theta; } rs[4] = { { 32, 64, 17, 10000.0f }, { 4, 64, 17, 10000.0f }, { 32, 64, 1023, 500000.0f }, { 8, 64, 1023, 500000.0f } }; - for (int t = 0; t < 4; t++) { - size_t heads = rs[t].heads, hd = rs[t].hd, n = heads * hd, half = hd / 2; - float *v = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *ch = malloc(half * 4), *sh = malloc(half * 4); - for (size_t i = 0; i < n; i++) v[i] = frand(&seed, -4.0f, 4.0f); - oracle_rope_tables(hd, rs[t].pos, rs[t].theta, ch, sh); - oracle_rope(v, heads, hd, ch, sh, want); - char name[64]; snprintf(name, sizeof name, "rope_%zuh_%zud_pos%zu_theta%g", heads, hd, rs[t].pos, rs[t].theta); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); - c.bad = compare(got, want, n, 0.0, 0.0, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_ROPE); - double w2; c.mutant_rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); - c.mutant_bad = compare(got, want, n, 0.0, 0.0, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(v); free(got); free(want); free(ch); free(sh); - } } - /* 5. swiglu at the model ffn sizes (TinyLlama 5632, Llama-3.2-1B 8192), an odd tail, one past the - * 1024-CTA chunk (two launches) and the Qwen3-8B prefill call 128 x 12288 (twelve launches; cut L) */ - { size_t ns[5] = { 5632, 8192, 1000, 131073, 1572864 }; - for (int t = 0; t < 5; t++) { - size_t n = ns[t]; - float *g = malloc(n * 4), *u = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) { g[i] = frand(&seed, -12.0f, 12.0f); u[i] = frand(&seed, -2.0f, 2.0f); } - oracle_swiglu(g, u, want, n); - char name[64]; snprintf(name, sizeof name, "swiglu_%zu", n); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); - c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_SWIGLU); - double w2; c.mutant_rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); - c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(g); free(u); free(got); free(want); - } } - /* 6. stale-SM-instruction-cache guard (cut 1b finding, omega #256): 10 distinct kernels - * (5 ops + 5 mutants) in rotation, two rounds. Every launch uploads code into a freshly - * allocated page, so a kernel routinely lands on the code address its predecessor used, - * and 10 keys evict the 8-slot kernel cache. Each clean launch must match the oracle and - * each mutant must still be caught; a stale icache would make a mutant pass or a clean - * kernel fail. Red was observed by cut 1b on matmul before its invalidate (receipt - * FB1-CUT1B-f629798); this build carries the invalidate, so the case is a guard. */ - { - enum { RN = 256, RH = 4, RD = 64 }; - float *x = malloc(RN * 4), *w = malloc(RN * 4), *u = malloc(RN * 4), *got = malloc(RN * 4), *want = malloc(RN * 4); - float *ch = malloc(RD / 2 * 4), *sh = malloc(RD / 2 * 4); - uint32_t *xu = malloc(RN * 4), *gu = malloc(RN * 4); - for (size_t i = 0; i < RN; i++) { x[i] = frand(&seed, -3.0f, 3.0f); w[i] = frand(&seed, 0.5f, 1.5f); u[i] = frand(&seed, -2.0f, 2.0f); xu[i] = lcg(&seed); } - oracle_rope_tables(RD, 17, 10000.0f, ch, sh); - Case c = { .name = "icache_reuse_rotation", .n = 20 }; - c.rc = OMEGA_GPU_EW_OK; c.mutant_rc = OMEGA_GPU_EW_OK; c.mutant_caught = 1; - const int order[10] = { OMEGA_GPU_EW_EX2, -OMEGA_GPU_EW_SWIGLU, OMEGA_GPU_EW_XCHG, -OMEGA_GPU_EW_EX2, OMEGA_GPU_EW_RMSNORM, - -OMEGA_GPU_EW_XCHG, OMEGA_GPU_EW_SWIGLU, -OMEGA_GPU_EW_ROPE, OMEGA_GPU_EW_ROPE, -OMEGA_GPU_EW_RMSNORM }; - for (int step = 0; step < 20; step++) { - int round = step / 10, k = step % 10; - int mut = order[k] < 0, op = mut ? -order[k] : order[k]; - omega_gpu_elementwise_test_set_mutant(mut ? op : 0); - int rc; size_t bad = 0; double wst; - switch (op) { - case OMEGA_GPU_EW_EX2: - for (size_t i = 0; i < RN; i++) want[i] = (float)exp2((double)x[i]); - rc = omega_gpu_ex2_f32(RN, x, got, &info); bad = compare(got, want, RN, 1e-6, 0.0, &wst); break; - case OMEGA_GPU_EW_XCHG: - rc = omega_gpu_shared_xchg_u32(RN, xu, gu, &info); - for (size_t i = 0; i < RN; i++) { if (gu[i] != xu[i ^ (OMEGA_GPU_EW_THREADS - 1)]) bad++; } - break; - case OMEGA_GPU_EW_RMSNORM: - oracle_rmsnorm(x, w, 1e-5f, want, RN); - rc = omega_gpu_rmsnorm_f32(1, RN, x, w, 1e-5f, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; - case OMEGA_GPU_EW_ROPE: - oracle_rope(x, RH, RD, ch, sh, want); - rc = omega_gpu_rope_f32(RH, RD, x, ch, sh, got, &info); bad = compare(got, want, RH * RD, 0.0, 0.0, &wst); break; - default: - oracle_swiglu(x, u, want, RN); - rc = omega_gpu_swiglu_f32(RN, x, u, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; - } - omega_gpu_elementwise_test_set_mutant(0); - int ok = rc == OMEGA_GPU_EW_OK && bad == 0; - if (!mut && !ok) { c.bad++; if (rc != OMEGA_GPU_EW_OK) c.rc = rc; printf(" rotation %d/%d: clean op %d FAILED rc=%s violations=%zu\n", round, k, op, omega_gpu_elementwise_rc_name(rc), bad); } - if (mut && ok) { c.mutant_bad++; c.mutant_caught = 0; printf(" rotation %d/%d: mutant op %d NOT caught\n", round, k, op); } - c.chip_ns += info.elapsed_ns; c.calls += info.chip_calls; c.unwritten += info.unwritten_words; - } - c.pass = c.bad == 0 && c.rc == OMEGA_GPU_EW_OK; - record(c, out); - free(x); free(w); free(u); free(got); free(want); free(ch); free(sh); free(xu); free(gu); - } - /* cut 4b: the whole battery (clean and mutant kernels, cache clears) ran on ONE device open */ - CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count()); - printf("device_opens=%u\n", omega_gpu_session_open_count()); - if (out) { - fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL"); - fclose(out); - } - return 0; -} - -/* ------------------------------------------------------------ timing gate (cut 4b) */ -/* The persistent device: 100 calls each of rmsnorm 1x2048 and swiglu 5632 (the TinyLlama - * decode shapes), every call checked against the oracle, median wall time per call under - * 0.5 ms (cut 4 opened and closed the device per call: ~40 ms). The device must have been - * opened exactly once in this process. */ -static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int timing(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_TIMING_V1\",\"gate_median_ms\":0.5,\"calls\":100,\"cases\":["); - uint32_t seed = 0xfb1c004bu; - enum { N = 100 }; - for (int t = 0; t < 2; t++) { - const char *name = t == 0 ? "rmsnorm_1x2048" : "swiglu_5632"; - size_t n = t == 0 ? 2048 : 5632; - float *a = malloc(n * 4), *b = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) { a[i] = frand(&seed, -3.0f, 3.0f); b[i] = t == 0 ? frand(&seed, 0.5f, 1.5f) : frand(&seed, -2.0f, 2.0f); } - if (t == 0) oracle_rmsnorm(a, b, 1e-5f, want, n); else oracle_swiglu(a, b, want, n); - double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; - OmegaGpuEwInfo info; - /* warm-up: first call opens the device and generates the kernel (not timed) */ - int rc0 = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); - double first_ms = info.call_ns / 1e6; - CHECK(rc0 == OMEGA_GPU_EW_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_elementwise_rc_name(rc0), omega_gpu_elementwise_last_error()); - for (int i = 0; i < N; i++) { - double t0 = now_ms(); - int rc = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); - samples[i] = now_ms() - t0; - double w; size_t bad = compare(got, want, n, 1e-5, 1e-6, &w); - if (w > worst) worst = w; - bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; - if (rc == OMEGA_GPU_EW_OK && bad == 0) ok_calls++; - } - qsort(samples, N, sizeof samples[0], cmp_d); - double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; - uint32_t opens = omega_gpu_session_open_count(); - int pass = ok_calls == N && bad_total == 0 && median < 0.5 && opens == 1; - CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_elementwise_rc_name(rc_last), omega_gpu_elementwise_last_error()); - printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", - pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); - if (out) fprintf(out, "%s{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", - t ? "," : "", name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); - free(a); free(b); free(got); free(want); - } - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_TIMING_PASS" : "OMEGA_GPU_ELEMENTWISE_TIMING_FAIL"); fclose(out); } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, timing_mode = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - if (host) host_only(); - else if (timing_mode) { if (timing(out_path) != 0) return 2; } - else if (chip(out_path) != 0) return 2; - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_fp8_api_test.c b/tests/gpu_fp8_api_test.c deleted file mode 100644 index bec0db1b9..000000000 --- a/tests/gpu_fp8_api_test.c +++ /dev/null @@ -1,598 +0,0 @@ -/* gpu_fp8_api_test: OWN-30B Cut 6 / Cut 5 gate for omega_gpu_fp8_api (FP8 e4m3 block-scaled GEMV). - * - * ./gpu_fp8_api_test --host-only exhaustive 256-code e4m3 conversion vs the reference decode - * (subnormals, both zeros, NaN codes refused), pack refusals, - * codegen for every kernel shape (instruction and register budget), - * API argument refusals, nvdisasm listing when /usr/local/cuda/bin/nvdisasm exists - * ./gpu_fp8_api_test --sim the kernel through tests/bw_warp_sim.h (no chip): one-hot conversion - * of every code through the kernel, parity battery vs the double oracle - * (both fragment orders bit-identical), grouped experts, and the four - * mutants (1 scale dropped, 2 scale block frozen, 3 group table swapped, - * host no-fold) which the same check must catch - * ./gpu_fp8_api_test --out receipt.json chip gate: parity battery, mutants, grouped experts, then the - * bandwidth table (median of --reps calls) at the expert and attention shapes - * knobs: --lane-bytes N --rows N --warps N --cta-budget N --reps N --spin-us N - * --n N --k K: one custom point n x k instead of the battery (with mutants 1, 2, 4), e.g. 128256 x 2560 - * - * Pass rule per point: rc OK, every output within TOL of the double oracle relative to the accumulation - * scale (sum of |terms|). Host and simulator passes are never chip results. - */ -#include "omega_gpu_fp8_api.h" -#include "omega_blackwell_codegen_moe2.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_matmul.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim.h" -#include -#include -#include -#include -#include -#include -#include - -#define TOL 1e-5 -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; } -static uint16_t bf16_of(float f) { return omega_fp32_to_bf16(f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* ------------------------------------------------------------------ data */ -typedef struct { - uint32_t experts, n, k; - uint8_t *w; uint16_t *s; /* checkpoint layout */ -} Weights; -static void weights_make(Weights *W, uint32_t experts, uint32_t n, uint32_t k, uint32_t seed) { - W->experts = experts; W->n = n; W->k = k; - size_t wb = (size_t)experts * n * k, sc = (size_t)experts * (n / 128) * (k / 128); - W->w = aligned_alloc(64, (wb + 63) & ~(size_t)63); W->s = malloc(sc * 2); - uint32_t st = seed; - for (size_t i = 0; i < wb; i++) W->w[i] = rand_e4m3(&st); - for (size_t i = 0; i < sc; i++) W->s[i] = bf16_of(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f)); -} -static void weights_free(Weights *W) { free(W->w); free(W->s); } - -/* max relative error of y (groups x n) against the oracle over the selected experts */ -static double parity(const Weights *W, uint32_t groups, const uint32_t *ids, const float *x, uint32_t x_rows, const float *y, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - double *ref = malloc(W->n * sizeof *ref), *mag = malloc(W->n * sizeof *mag); - for (uint32_t g = 0; g < groups; g++) { - const uint8_t *w = W->w + (size_t)ids[g] * W->n * W->k; - const uint16_t *s = W->s + (size_t)ids[g] * (W->n / 128) * (W->k / 128); - omega_fp8_gemv_oracle(w, s, W->n, W->k, x + (size_t)(x_rows == 1 ? 0 : g) * W->k, ref, mag); - for (uint32_t r = 0; r < W->n; r++) { - double d = fabs(ref[r] - (double)y[(size_t)g * W->n + r]); - double rel = d / (mag[r] > 1e-30 ? mag[r] : 1e-30); - if (rel > worst) worst = rel; - if (rel >= TOL || isnan(y[(size_t)g * W->n + r])) nbad++; - } - } - free(ref); free(mag); - if (bad) *bad = nbad; - return worst; -} - -/* ------------------------------------------------------------- host-only */ -static int nvdisasm_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name); -static int nvdisasm_check(const OmegaFp8GemvSpec *spec, const char *name) { return nvdisasm_check_v(1, spec, name); } -static int nvdisasm_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name) { - const char *nv = "/usr/local/cuda/bin/nvdisasm"; - if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if ((variant == 2 ? omega_blackwell_codegen_fp8_gemv2(spec, &k) : omega_blackwell_codegen_fp8_gemv(spec, &k)) != 0) return -1; - char bin[96], lst[96], cmd[320]; - snprintf(bin, sizeof bin, "/tmp/omega_fp8_%s_%d.bin", name, (int)getpid()); - snprintf(lst, sizeof lst, "/tmp/omega_fp8_%s_%d.sass", name, (int)getpid()); - FILE *f = fopen(bin, "wb"); if (!f) { omega_blackwell_kernel_free(&k); return -1; } - fwrite(k.code, 1, k.code_size, f); fclose(f); - snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); - int rc = system(cmd); - omega_blackwell_kernel_free(&k); - static const char *const must[] = { "LDG.E.128", "FFMA", "SHFL.DOWN", "BSSY", "BSYNC", "STG.E", "LOP3.LUT", "IMAD" }; - FILE *l = fopen(lst, "r"); if (!l) return -1; - char line[512]; int seen[8] = {0}; int bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*") || !strstr(line, "*/")) continue; /* every address line */ - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - if (strstr(line, ".FTZ")) { printf(" %s: flush-to-zero instruction: %s", name, line); bad++; } /* e4m3 subnormals travel as f32 subnormals */ - for (int i = 0; i < 8; i++) if (strstr(line, must[i])) seen[i] = 1; - } - fclose(l); - int miss = 0; - for (int i = 0; i < 8; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } - printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - unlink(bin); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} - -static void host_only(void) { - /* 1. exhaustive conversion: kernel bits * 2^120 == reference, bit for bit, for every non-NaN code; - * sign of zero preserved; NaN codes are exactly 0x7f and 0xff and are refused by the scan */ - int exact = 0, nan_codes = 0, zero_sign_ok = 0, f32_subnormal = 0; - for (int b = 0; b < 256; b++) { - float ref = omega_fp8_e4m3_ref((uint8_t)b); - uint32_t kb = omega_fp8_e4m3_kernel_bits((uint8_t)b); - float kf; memcpy(&kf, &kb, 4); - /* the kernel-side f32 is subnormal exactly for the e4m3 subnormal codes (exponent field 0, mantissa != 0): - * the chip must not flush them (no .FTZ instruction in the listing, chip one-hot test) */ - if ((kb & 0x7f800000u) == 0 && (kb & 0x007fffffu) != 0) { f32_subnormal++; CHECK((b & 0x78) == 0 && (b & 7) != 0, "code 0x%02x maps to an f32 subnormal but is not an e4m3 subnormal", b); } - else CHECK((b & 0x78) != 0 || (b & 7) == 0, "e4m3 subnormal code 0x%02x maps to a normal f32", b); - float kv = ldexpf(kf, 120); /* exact: a power-of-two scaling (host, no flush to zero) */ - if (isnan(ref)) { nan_codes++; CHECK(omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is NaN in the reference and must be flagged", b); continue; } - CHECK(!omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is finite in the reference and must not be flagged", b); - uint32_t rb, vb; memcpy(&rb, &ref, 4); memcpy(&vb, &kv, 4); - if (rb == vb) exact++; - CHECK(rb == vb, "code 0x%02x: kernel conversion %a (bits %08x) != reference %a (bits %08x)", b, kv, vb, ref, rb); - if (ref == 0.0f) { if (signbit(ref) == signbit(kv)) zero_sign_ok++; } - /* the fold is exact as two steps too (x * 2^64 then * 2^56) */ - CHECK(ldexpf(ldexpf(kf, OMEGA_FP8_X_EXP), OMEGA_FP8_SCALE_EXP) == ref, "code 0x%02x: split fold not exact", b); - } - CHECK(exact == 254 && nan_codes == 2 && zero_sign_ok == 2, "conversion: %d exact, %d NaN codes, %d zero signs (want 254, 2, 2)", exact, nan_codes, zero_sign_ok); - CHECK(f32_subnormal == 14, "f32-subnormal kernel values: %d (want 14: +-0x01..0x07)", f32_subnormal); - printf("conversion: %d/256 exact, %d NaN codes refused, %d codes travel as f32 subnormals (2^-129 .. 7 * 2^-129): the chip must not flush them\n", exact, nan_codes, f32_subnormal); - /* subnormal spot values from the e4m3 definition */ - CHECK(omega_fp8_e4m3_ref(0x01) == ldexpf(1.0f, -9) && omega_fp8_e4m3_ref(0x07) == 7.0f * ldexpf(1.0f, -9), "subnormal spot values"); - CHECK(omega_fp8_e4m3_ref(0x7e) == 448.0f && omega_fp8_e4m3_ref(0xfe) == -448.0f && omega_fp8_e4m3_ref(0x38) == 1.0f, "normal spot values"); - /* conversion mutant: skipping the fold is caught by the same comparison */ - { float kf; uint32_t kb = omega_fp8_e4m3_kernel_bits(0x38); memcpy(&kf, &kb, 4); CHECK(kf != 1.0f, "fold mutant: unfolded bits must not equal the value"); } - - /* 2. pack refusals */ - { uint8_t w[8] = { 0x38, 0x7f, 0x00, 0xff, 1, 2, 3, 4 }; size_t first = 99; - CHECK(omega_fp8_pack_scan_nan(w, 8, &first) == 2 && first == 1, "NaN scan finds both codes, first at 1"); - CHECK(omega_fp8_pack_scan_nan(w, 1, &first) == 0, "NaN scan clean prefix"); } - { uint16_t s[3] = { bf16_of(0.5f), 0x7fc0 /* NaN */, bf16_of(1.0f) }; float o[3]; - CHECK(omega_fp8_pack_scales(s, 1, o, 0) == 0 && o[0] == ldexpf(0.5f, OMEGA_FP8_SCALE_EXP), "scale fold exact"); - CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "NaN scale refused"); - s[1] = 0x7f80; CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "inf scale refused"); - s[1] = bf16_of(3.0e38f); CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "fold overflow refused"); - CHECK(omega_fp8_pack_scales(s, 1, o, 1) == 0 && o[0] == 0.5f, "no-fold mutant pack"); } - { float x[4] = { 1.0f, -2.0f, 0.5f, 0.0f }, o[4]; omega_fp8_pack_x_f32(x, 4, o); - CHECK(o[0] == ldexpf(1.0f, 64) && o[1] == ldexpf(-2.0f, 64) && o[3] == 0.0f, "x fold exact"); } - - /* 3. codegen: every shape builds inside the budgets; refusals */ - static const uint32_t ks[] = { 128, 256, 768, 2048, 4096, 16384 }; - static const uint32_t lbs[] = { 8, 16 }, rows[] = { 1, 2, 4, 8 }; - uint32_t worst_insns = 0, worst_gprs = 0; int built = 0; - for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) for (int m = 0; m <= 3; m++) for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 8, .mutant = m }; - uint32_t ni, ng; - if (ks[a] % (32 * lbs[b])) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "k=%u lb=%u must be refused", ks[a], lbs[b]); continue; } - if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 4096) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "deep k=%u lb=%u rows=%u must be refused", ks[a], lbs[b], rows[c]); continue; } } - int rc = omega_fp8_gemv_prog_stats(&sp, &ni, &ng); - CHECK(rc == 0, "codegen k=%u lb=%u rows=%u mutant=%d deep=%d", ks[a], lbs[b], rows[c], m, deep); - if (rc == 0) { built++; if (ni > worst_insns) worst_insns = ni; if (ng > worst_gprs) worst_gprs = ng; } - } - printf("codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built, worst_insns, worst_gprs); - CHECK(worst_insns <= BW_MAX_IR_INSNS && worst_gprs <= 128, "budgets"); - { OmegaFp8GemvSpec bad = { .k = 192, .lane_bytes = 8, .rows = 1, .warps = 1 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k not a multiple of 128 refused"); - bad.k = 256; bad.lane_bytes = 4; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 4 refused (LDG.E has no immediate offset)"); bad.lane_bytes = 8; - bad.k = 2048; bad.rows = 3; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "rows 3 refused"); - bad.rows = 8; bad.warps = 33; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "warps 33 refused"); - bad.warps = 8; bad.lane_bytes = 32; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 32 refused"); - bad.lane_bytes = 16; bad.k = 32768; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k past the limit refused"); } - /* Register file (chip-found 2026-10-13): 32 * warps * declared registers must be <= 65536; the API refuses the launch. - * The deep k=2048 kernel at 32 warps (72 declared x 1024 threads = 73728) faulted on the chip with Xid 13. */ - { OmegaFp8GemvSpec deep = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 32, .depth = 4 }; uint32_t gp = 0; - CHECK(omega_fp8_gemv_prog_stats(&deep, NULL, &gp) == 0, "deep4 k2048 encodes"); - uint32_t decl = ((gp + 1u + 7u) / 8u) * 8u; - CHECK(32u * 32u * decl > 65536u, "deep4 k2048 at 32 warps needs %u declared registers x 1024 threads: over the 65536 file", decl); - uint32_t de = 0; int rf = omega_gpu_fp8_kernel_fits(&deep, &de); - CHECK(rf == OMEGA_GPU_FP8_TOO_LARGE && de == decl, "API refuses the register-file overflow (rc %d, declared %u): %s", rf, de, omega_gpu_fp8_last_error()); - deep.warps = 16; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the same kernel at 16 warps fits"); - deep.depth = 0; deep.warps = 32; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the classic kernel at 32 warps fits"); - deep.depth = 4; CHECK(omega_gpu_fp8_depth_for(&deep, 2048, 1) == 0, "automatic depth falls back to classic when deep would overflow the register file"); } - - /* 4. API refusals that need no device */ - { OmegaGpuFp8Tensor *t = NULL; uint8_t w[128 * 128]; uint16_t s[1] = { bf16_of(1.0f) }; memset(w, 0x38, sizeof w); - CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, NULL, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "NULL w refused"); - CHECK(omega_gpu_fp8_tensor_upload(1, 100, 128, w, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "n not a multiple of 128 refused"); - CHECK(omega_gpu_fp8_tensor_upload(1, 128, 32768, w, s, &t) == OMEGA_GPU_FP8_TOO_LARGE, "k past the limit refused"); - w[77] = 0xff; CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, w, s, &t) == OMEGA_GPU_FP8_NAN_WEIGHT && t == NULL, "NaN weight refused before any device work"); - CHECK(strstr(omega_gpu_fp8_last_error(), "byte 77") != NULL, "error names the byte (%s)", omega_gpu_fp8_last_error()); - float y[8]; CHECK(omega_gpu_fp8_gemv_f32(NULL, 0, y, y, NULL) == OMEGA_GPU_FP8_BAD_ARGS, "NULL tensor refused"); } - - /* 5. nvdisasm listing of the production shapes */ - { OmegaFp8GemvSpec a = { .k = 2048, .lane_bytes = 16, .rows = 8, .warps = 8 }, b = { .k = 768, .lane_bytes = 8, .rows = 2, .warps = 8 }; - CHECK(nvdisasm_check(&a, "k2048_lb16_r8") == 0, "nvdisasm listing k=2048"); - OmegaFp8GemvSpec d = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 8, .depth = 4 }; - CHECK(nvdisasm_check(&d, "k2048_lb16_r1_deep4") == 0, "nvdisasm listing deep k=2048"); - CHECK(nvdisasm_check(&b, "k768_lb8_r2") == 0, "nvdisasm listing k=768"); } - - /* 6. variant 2 (W-L2c, omega_blackwell_codegen_moe2.c): every OWN-30B width builds inside the budgets at 16 warps, - * the production shapes fit the register file, the whole-row-group rule refuses what it must */ - { - static const uint32_t k2[] = { 768, 2048, 4096 }, r2[] = { 1, 2, 4 }; - uint32_t worst_i = 0, worst_g = 0; int built2 = 0; - for (size_t a = 0; a < 3; a++) for (size_t c = 0; c < 3; c++) for (int m = 0; m <= 3; m++) { - OmegaFp8GemvSpec sp = { .k = k2[a], .lane_bytes = k2[a] % 512u == 0 ? 16u : 8u, .rows = r2[c], .warps = 16, .mutant = m }; - uint32_t ks = sp.k / (32u * sp.lane_bytes), ni = 0, ng = 0; - int rc = omega_fp8_gemv2_prog_stats(&sp, &ni, &ng); - if (sp.rows * ks * sp.lane_bytes > 128u) { CHECK(rc != 0, "v2 k=%u rows=%u must be refused (row group past 128 bytes per lane)", sp.k, sp.rows); continue; } - CHECK(rc == 0 && ni <= BW_MAX_IR_INSNS, "v2 codegen k=%u lb=%u rows=%u mutant=%d: rc %d, %u insns", sp.k, sp.lane_bytes, sp.rows, m, rc, ni); - if (rc == 0) { built2++; if (ni > worst_i) worst_i = ni; if (ng > worst_g) worst_g = ng; if (m == 0) printf("v2 codegen k=%u lb=%u rows=%u: %u insns, peak %u GPRs, declared %u\n", sp.k, sp.lane_bytes, sp.rows, ni, ng, omega_bw_gpr_declared(ng)); } - } - printf("v2 codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built2, worst_i, worst_g); - /* the production shapes at the variant's default (16 warps, 1 row) must fit the 65536-register file */ - omega_gpu_fp8_set_variant(2); - static const uint32_t kp[] = { 768, 2048, 4096 }; - for (size_t a = 0; a < 3; a++) { - OmegaFp8GemvSpec sp = { .k = kp[a], .lane_bytes = kp[a] % 512u == 0 ? 16u : 8u, .rows = 1, .warps = OMEGA_GPU_FP8_V2_WARPS }; - uint32_t decl = 0; int rf = omega_gpu_fp8_kernel_fits(&sp, &decl); - CHECK(rf == OMEGA_GPU_FP8_OK && 32u * sp.warps * decl <= 65536u, "v2 k=%u at %u warps fits the register file (rc %d, declared %u)", sp.k, sp.warps, rf, decl); - printf("v2 k=%u rows=1 warps=%u: declared %u registers, %u per SM at one CTA\n", sp.k, sp.warps, decl, 32u * sp.warps * decl); - } - omega_gpu_fp8_set_variant(1); - { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 2 }; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=2048 at 2 warps refused (staging rounds)"); - bad.warps = 16; bad.k = 16384; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=16384 refused (row past 128 bytes per lane)"); - bad.k = 2048; bad.lane_bytes = 8; bad.rows = 2; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) == 0, "v2 k=2048 lb8 rows=2 (128 bytes per lane) builds"); } - OmegaFp8GemvSpec v = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 16 }; - CHECK(nvdisasm_check_v(2, &v, "v2_k2048_lb16_r1_w16") == 0, "nvdisasm listing v2 k=2048"); - } -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int g_sim_variant = 1; /* which generator sim_gemv runs: 1 (omega_blackwell_codegen_moe.c) or 2 (moe2.c, W-L2c) */ -/* Runs the kernel for (W, groups, ids, x, x_rows) on the warp simulator in both fragment orders. Returns 0 and y - * on success, -1 on a simulator error or an order-dependent result. */ -static int sim_gemv(const OmegaFp8GemvSpec *spec, const Weights *W, uint32_t groups, const uint32_t *ids, const float *x, - uint32_t x_rows, float *y, uint32_t cta_budget, int no_fold, char *msg, size_t msglen) { - static BlackwellIRProgram prog; - if ((g_sim_variant == 2 ? omega_blackwell_codegen_fp8_gemv2_prog(spec, &prog) : omega_blackwell_codegen_fp8_gemv_prog(spec, &prog)) != 0) { snprintf(msg, msglen, "codegen refused"); return -1; } - const uint32_t n = W->n, k = W->k, RG = n / spec->rows; - size_t sc = (size_t)W->experts * (n / 128) * (k / 128); - float *sf = aligned_alloc(16, ((sc * 4) + 15) & ~(size_t)15); - if (omega_fp8_pack_scales(W->s, sc, sf, no_fold) != 0) { free(sf); snprintf(msg, msglen, "scale pack refused"); return -1; } - float *xf = aligned_alloc(16, ((size_t)x_rows * k * 4 + 15) & ~(size_t)15); - for (uint32_t r = 0; r < x_rows; r++) omega_fp8_pack_x_f32(x + (size_t)r * k, k, xf + (size_t)r * k); - uint64_t *tab = aligned_alloc(16, 16 * (size_t)groups); - for (uint32_t g = 0; g < groups; g++) { - tab[2 * g] = (uintptr_t)(W->w + (size_t)ids[g] * n * k); - tab[2 * g + 1] = (uintptr_t)(sf + (size_t)ids[g] * (n / 128) * (k / 128)); - } - float *yd = aligned_alloc(16, ((size_t)groups * n * 4 + 15) & ~(size_t)15); - float *copy = malloc((size_t)groups * n * 4); - uint32_t grid_x = (RG + spec->warps - 1) / spec->warps; if (grid_x > cta_budget) grid_x = cta_budget; if (!grid_x) grid_x = 1; - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32 * spec->warps; s.order = order; - static uint8_t smem[OMEGA_FP8_MAX_K * 4]; s.smem = smem; s.smem_bytes = g_sim_variant == 2 ? omega_fp8_gemv2_shared_bytes(spec) : omega_fp8_gemv_shared_bytes(spec); /* the bytes the launch declares (0: any shared access fails) */ - uint64_t ta = (uintptr_t)tab, xa = (uintptr_t)xf, ya = (uintptr_t)yd; - s.cbank[OMEGA_FP8_ARG_TAB / 4] = (uint32_t)ta; s.cbank[OMEGA_FP8_ARG_TAB / 4 + 1] = (uint32_t)(ta >> 32); - s.cbank[OMEGA_FP8_ARG_X / 4] = (uint32_t)xa; s.cbank[OMEGA_FP8_ARG_X / 4 + 1] = (uint32_t)(xa >> 32); - s.cbank[OMEGA_FP8_ARG_Y / 4] = (uint32_t)ya; s.cbank[OMEGA_FP8_ARG_Y / 4 + 1] = (uint32_t)(ya >> 32); - s.cbank[OMEGA_FP8_ARG_RG / 4] = RG; s.cbank[OMEGA_FP8_ARG_XSTRIDE / 4] = x_rows == 1 ? 0 : k * 4; - s.cbank[OMEGA_FP8_ARG_YSTRIDE / 4] = n * 4; s.cbank[OMEGA_FP8_ARG_STRIDE / 4] = grid_x * spec->warps; - /* every global access must land in a declared buffer */ - s.nranges = 4; - s.ranges[0].lo = (uintptr_t)W->w; s.ranges[0].hi = (uintptr_t)W->w + (size_t)W->experts * n * k; - s.ranges[1].lo = (uintptr_t)sf; s.ranges[1].hi = (uintptr_t)sf + sc * 4; - s.ranges[2].lo = (uintptr_t)xf; s.ranges[2].hi = (uintptr_t)xf + (size_t)x_rows * k * 4; - s.ranges[3].lo = (uintptr_t)yd; s.ranges[3].hi = (uintptr_t)yd + (size_t)groups * n * 4; - /* the table is read too */ - s.nranges = 5; s.ranges[4].lo = (uintptr_t)tab; s.ranges[4].hi = (uintptr_t)tab + 16 * (size_t)groups; - for (size_t i = 0; i < (size_t)groups * n; i++) yd[i] = -999.0f; - err = ws_run(&s, grid_x, groups); - if (err) { snprintf(msg, msglen, "order %d: %s", order, s.msg); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)groups * n; i++) if (yd[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msglen, "%zu output words never written", unwritten); break; } - if (order == 0) memcpy(copy, yd, (size_t)groups * n * 4); - else if (memcmp(copy, yd, (size_t)groups * n * 4) != 0) { err = -1; snprintf(msg, msglen, "the fragment order changed the result"); } - } - if (!err) memcpy(y, yd, (size_t)groups * n * 4); - free(sf); free(xf); free(tab); free(yd); free(copy); - return err ? -1 : 0; -} - -typedef struct { uint32_t experts, n, k, groups, x_rows, lb, rows, warps; const char *name; } SimPoint; - -static void sim_battery(uint32_t cta_budget) { - char msg[240]; - /* 1. one-hot conversion through the kernel: 254 rows, row r holds code r at column 0 (NaN codes replaced by - * 0x00), x = e_0, scale 1: y[r] must equal the reference exactly (zero rows compare as 0) */ - { - Weights W; W.experts = 1; W.n = 256; W.k = 256; - W.w = aligned_alloc(64, 256 * 256); memset(W.w, 0, 256 * 256); - W.s = malloc(4 * 2); for (int b = 0; b < 4; b++) W.s[b] = bf16_of(1.0f); - for (int r = 0; r < 256; r++) W.w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r; - float x[256] = { 0 }; x[0] = 1.0f; float y[256]; uint32_t id = 0; - OmegaFp8GemvSpec sp = { .k = 256, .lane_bytes = 8, .rows = 8, .warps = 4 }; - int rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg); - CHECK(rc == 0, "one-hot sim run: %s", msg); - int exact = 0; - if (rc == 0) for (int r = 0; r < 256; r++) { - float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r); - if (y[r] == ref) exact++; else { CHECK(0, "one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref); } - } - printf("sim one-hot conversion: %d/256 rows exact\n", exact); - /* x on the other lanes/words: code at column c, x = e_c for c in {1, 17, 127} on one row each */ - for (int t = 0; t < 3; t++) { - const int cols[3] = { 1, 17, 255 }; const uint8_t codes[3] = { 0xc0, 0x05, 0x7e }; - memset(W.w, 0, 256 * 256); W.w[3 * 256 + cols[t]] = codes[t]; - memset(x, 0, sizeof x); x[cols[t]] = -2.5f; for (int b = 0; b < 4; b++) W.s[b] = bf16_of(0.75f); - rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg); - CHECK(rc == 0 && y[3] == omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, "one-hot column %d code 0x%02x: %a vs %a (%s)", cols[t], codes[t], rc == 0 ? y[3] : 0.0f, omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, msg); - } - weights_free(&W); - } - /* 2. parity battery */ - static const SimPoint pts[] = { - { 1, 128, 256, 1, 1, 8, 1, 1, "k256 lb8 r1 w1" }, - { 1, 256, 256, 1, 1, 8, 2, 2, "k256 lb8 r2 w2" }, - { 1, 256, 768, 1, 1, 8, 4, 8, "k768 lb8 r4 w8 (down shape width)" }, - { 1, 256, 768, 1, 1, 8, 8, 8, "k768 lb8 r8" }, - { 1, 384, 2048, 1, 1, 16, 8, 8, "k2048 lb16 r8 w8 (gate shape width)" }, - { 1, 128, 2048, 1, 1, 16, 1, 8, "k2048 lb16 r1" }, - { 1, 256, 512, 1, 1, 16, 2, 3, "k512 lb16 r2 w3 (odd warps, tail row groups)" }, - { 4, 256, 2048, 4, 1, 16, 8, 8, "4 experts shared x (gate+up)" }, - { 6, 256, 768, 8, 8, 8, 4, 8, "8 groups per-group x, repeated ids (down)" }, - { 3, 128, 256, 2, 2, 8, 8, 4, "2 groups per-group x" }, - { 2, 256, 768, 2, 2, 8, 1, 7, "k768 w7: partial staging round (deep)" }, - }; - const size_t npts = sizeof pts / sizeof pts[0]; - double worst_all = 0.0; - for (size_t i = 0; i < npts; i++) { - const SimPoint *p = &pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - float *y = malloc((size_t)p->groups * p->n * 4); - /* every point runs the step-by-step kernel (depth 0) and, when the row fits, the deep kernel (depth = KS) */ - for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; } - char nm[96]; snprintf(nm, sizeof nm, "%s%s", p->name, deep ? " deep" : ""); - double t0 = now_ms(); - int rc = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - if (worst > worst_all) worst_all = worst; - CHECK(rc == 0 && bad == 0, "sim %s: rc=%d bad=%zu worst_rel=%.3e %s", nm, rc, bad, worst, msg); - printf("sim %-45s rc=%d worst_rel=%.3e bad=%zu (%.0f ms)\n", nm, rc, worst, bad, now_ms() - t0); - /* mutants on the two grouped points and the first two single points: each must be caught */ - if (i == 1 || i == 4 || i == 7 || i == 8) { - for (int m = 1; m <= 4; m++) { - if (m == 3 && p->groups == 1) continue; /* group swap needs two groups */ - if (m == 2 && omega_fp8_gemv_steps(&sp) < 2) { printf("sim %s mutant 2: one K step, control not applicable\n", p->name); continue; } - OmegaFp8GemvSpec ms = sp; ms.mutant = m == 4 ? 0 : m; - rc = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y, cta_budget, m == 4, msg, sizeof msg); - bad = 0; worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - int caught = rc != 0 || bad > 0; - if (m == 3 && rc == 0) { /* the ids must differ for the swap to show; make sure the control is meaningful */ - int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1; - if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; } - } - CHECK(caught, "sim %s mutant %d NOT caught (worst_rel=%.3e)", nm, m, worst); - printf("sim %-45s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e)\n", nm, m, caught ? "caught" : "MISSED", rc, bad, worst); - } - } - } - free(x); free(y); weights_free(&W); - } - printf("sim battery: worst relative error %.3e over %zu points, %" PRIu64 " warp issues\n", worst_all, npts, g_sim_issues); - - /* 3. variant 2 (W-L2c): y bit-identical to variant 1 on every point (same arithmetic order), parity against the oracle, - * mutants caught; the identity check is shown to say "no" on a mutant */ - { - static const SimPoint v2pts[] = { - { 1, 256, 2048, 1, 1, 16, 1, 8, "v2 k2048 lb16 r1 w8 (gate_up/qkv width)" }, - { 1, 256, 2048, 1, 1, 16, 2, 8, "v2 k2048 lb16 r2 w8 (128 B per lane)" }, - { 1, 256, 4096, 1, 1, 16, 1, 8, "v2 k4096 lb16 r1 w8 (o_proj width)" }, - { 1, 256, 768, 1, 1, 8, 1, 8, "v2 k768 lb8 r1 w8 (down width)" }, - { 1, 256, 768, 1, 1, 8, 4, 8, "v2 k768 lb8 r4 w8" }, - { 2, 256, 768, 2, 2, 8, 1, 7, "v2 k768 w7: partial staging round" }, - { 4, 256, 2048, 4, 1, 16, 1, 8, "v2 4 experts shared x (gate_up)" }, - { 6, 256, 768, 8, 8, 8, 2, 8, "v2 8 groups per-group x, repeated ids (down)" }, - { 3, 128, 256, 2, 2, 8, 8, 4, "v2 2 groups per-group x, r8 k256" }, - { 1, 256, 512, 1, 1, 16, 2, 3, "v2 k512 w3 (odd warps, tail row groups)" }, - }; - const size_t n2 = sizeof v2pts / sizeof v2pts[0]; - int identical = 0; - for (size_t i = 0; i < n2; i++) { - const SimPoint *p = &v2pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 177 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - const size_t ny = (size_t)p->groups * p->n; - float *y1 = malloc(ny * 4), *y2 = malloc(ny * 4); - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - g_sim_variant = 1; int rc1 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - CHECK(rc1 == 0, "v1 reference for %s: %s", p->name, msg); - double t0 = now_ms(); - g_sim_variant = 2; int rc2 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc2 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0; - int same = rc1 == 0 && rc2 == 0 && memcmp(y1, y2, ny * 4) == 0; - CHECK(rc2 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_v1=%d %s", p->name, rc2, bad, worst, same, msg); - if (same) identical++; - printf("sim %-48s rc=%d worst_rel=%.3e bad=%zu identical_to_v1=%d (%.0f ms)\n", p->name, rc2, worst, bad, same, now_ms() - t0); - if (i == 0 || i == 6 || i == 7) { - for (int m = 1; m <= 3; m++) { - if (m == 3 && p->groups == 1) continue; - OmegaFp8GemvSpec ms = sp; ms.mutant = m; - int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg); - bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0; - int caught = rcm != 0 || bad > 0, differs = rcm != 0 || memcmp(y1, y2, ny * 4) != 0; - if (m == 3 && rcm == 0) { int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1; if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; } } - CHECK(caught && differs, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e identity says %s)", p->name, m, bad, worst, differs ? "different" : "SAME"); - printf("sim %-48s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e, identity check differs=%d)\n", p->name, m, caught ? "caught" : "MISSED", rcm, bad, worst, differs); - } - } - g_sim_variant = 1; - free(x); free(y1); free(y2); weights_free(&W); - } - printf("sim v2 battery: %d/%zu points bit-identical to variant 1\n", identical, n2); - } -} - -/* ------------------------------------------------------------------- chip */ -typedef struct { uint32_t experts, n, k, groups, x_rows; const char *name; int parity_check; } ChipPoint; - -static int g_evict = 1; /* stream 512 MB through the host caches between upload and timing (nvrm.c:433: freshly written - host memory is served from the CPU caches by snooping and reads faster) */ -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} - -static const char *g_only; static int g_depth_forced; /* run only the battery points whose name contains this (diagnosis) */ -/* --n N --k K (ternary engine T0, 2026-10-15): run ONE custom point n x k (one expert, one group) instead of the battery, - * with the parity check, timing and mutants 1, 2 and 4 (3 needs groups > 1); e.g. the BitNet word table 128256 x 2560. */ -static uint32_t g_custom_n, g_custom_k; static char g_custom_name[48]; -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_FP8_GEMV\",\"points\":["); - static const ChipPoint pts[] = { - { 1, 128, 256, 1, 1, "k256 n128", 1 }, - { 1, 256, 768, 1, 1, "k768 n256", 1 }, - { 1, 384, 2048, 1, 1, "k2048 n384", 1 }, - { 1, 768, 2048, 1, 1, "gate 768x2048", 1 }, - { 1, 1536, 2048, 1, 1, "gate+up 1536x2048", 1 }, - { 1, 2048, 768, 1, 1, "down 2048x768", 1 }, - { 1, 4096, 2048, 1, 1, "q_proj 4096x2048", 1 }, - { 1, 512, 2048, 1, 1, "k_proj 512x2048", 1 }, - { 1, 2048, 4096, 1, 1, "o_proj 2048x4096", 1 }, - { 1, 5120, 2048, 1, 1, "qkv fused 5120x2048", 1 }, - { 8, 1536, 2048, 8, 1, "8 experts gate+up shared x", 1 }, - { 8, 2048, 768, 8, 8, "8 experts down per-group x", 1 }, - { 16, 1536, 2048, 8, 1, "8 of 16 experts gate+up", 1 }, - { 1, 16384, 2048, 1, 1, "large 16384x2048", 1 }, - }; - /* 0. one-hot conversion on the chip: row r holds code r at column 0 (NaN codes as 0x00), x = e_0, scale 1. - * y[r] must equal the reference bit for bit. The e4m3 subnormal codes 0x01..0x07 (and negatives) travel - * through the FFMA chain as f32 subnormals (e4m3 * 2^-120); a flush-to-zero FFMA would return 0 here. */ - int one_hot_exact = -1; - { - uint8_t *w = calloc(256, 256); uint16_t s[4]; float x[256] = { 0 }, y[256]; OmegaGpuFp8Tensor *t = NULL; - for (int b = 0; b < 4; b++) s[b] = bf16_of(1.0f); - for (int r = 0; r < 256; r++) w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r; - x[0] = 1.0f; - int rc = omega_gpu_fp8_tensor_upload(1, 256, 256, w, s, &t); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL); - one_hot_exact = 0; - if (rc == OMEGA_GPU_FP8_OK) for (int r = 0; r < 256; r++) { - float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r); - if (y[r] == ref) one_hot_exact++; else CHECK(0, "chip one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref); - } - if (g_depth_forced && rc == OMEGA_GPU_FP8_CODEGEN_FAIL) printf("chip one-hot conversion: skipped (forced depth does not fit k=256)\n"); - else CHECK(rc == OMEGA_GPU_FP8_OK && one_hot_exact == 256, "chip one-hot conversion: rc=%s exact=%d/256", omega_gpu_fp8_rc_name(rc), one_hot_exact); - printf("chip one-hot conversion: rc=%s %d/256 rows exact (subnormal codes 0x01..0x07 included: no flush to zero)\n", omega_gpu_fp8_rc_name(rc), one_hot_exact); - if (out) fprintf(out, "{\"name\":\"one-hot conversion\",\"rc\":\"%s\",\"exact_rows\":%d,\"of\":256}", omega_gpu_fp8_rc_name(rc), one_hot_exact); - if (t) omega_gpu_fp8_tensor_free(t); - free(w); - } - static ChipPoint custom; const ChipPoint *P = pts; size_t npts = sizeof pts / sizeof pts[0]; - if (g_custom_n && !g_custom_k) { CHECK(0, "--n needs --k"); if (out) fclose(out); return 1; } - if (g_custom_n) { snprintf(g_custom_name, sizeof g_custom_name, "custom %ux%u", g_custom_n, g_custom_k); custom = (ChipPoint){ 1, g_custom_n, g_custom_k, 1, 1, g_custom_name, 1 }; P = &custom; npts = 1; } - int first = 1; - first = out ? 0 : 1; - for (size_t i = 0; i < npts; i++) { - const ChipPoint *p = &P[i]; - if (g_only && !strstr(p->name, g_only)) continue; - Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 99 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = (p->experts > p->groups ? lcg(&st) % p->experts : (p->groups - 1 - g) % p->experts); - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - float *y = malloc((size_t)p->groups * p->n * 4), *y2 = malloc((size_t)p->groups * p->n * 4); - OmegaGpuFp8Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &t); - double up_ms = now_ms() - t0; - OmegaGpuFp8Info info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y, &info); - size_t bad = 0; double worst = rc == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - int ok = rc == OMEGA_GPU_FP8_OK && bad == 0; - /* second call: cache hit, bit-identical */ - int same = 0; OmegaGpuFp8Info i2; memset(&i2, 0, sizeof i2); - if (ok) { int r2 = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &i2); same = r2 == OMEGA_GPU_FP8_OK && memcmp(y, y2, (size_t)p->groups * p->n * 4) == 0 && i2.kernel_cache_hit; } - CHECK(ok && same, "chip %s: rc=%s bad=%zu worst_rel=%.3e second-call-identical=%d (%s)", p->name, omega_gpu_fp8_rc_name(rc), bad, worst, same, omega_gpu_fp8_last_error()); - /* timing: median of reps */ - uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl); - uint32_t done = 0; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && ok; r++) { - OmegaGpuFp8Info ti; if (omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &ti) != OMEGA_GPU_FP8_OK) break; - el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++; - } - uint64_t med_el = 0, med_cl = 0; double gbs = 0.0, gbs_call = 0.0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2]; - gbs = med_el ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_el : 0.0; gbs_call = med_cl ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_cl : 0.0; } - printf("chip %-32s variant=%d rc=%-9s bad=%zu worst_rel=%.3e grid=%ux%u lb=%u rows=%u warps=%u depth=%u bytes=%" PRIu64 " upload=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus (%.1f GB/s) reps=%u\n", - p->name, omega_gpu_fp8_variant(), omega_gpu_fp8_rc_name(rc), bad, worst, info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, - info.weight_bytes + info.scale_bytes, up_ms, med_el / 1e3, gbs, med_cl / 1e3, gbs_call, done); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"experts\":%u,\"n\":%u,\"k\":%u,\"groups\":%u,\"x_rows\":%u,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e,\"second_call_identical\":%d," - "\"variant\":%d,\"grid_x\":%u,\"grid_y\":%u,\"lane_bytes\":%u,\"rows_per_warp\":%u,\"warps_per_cta\":%u,\"depth\":%u,\"bytes\":%" PRIu64 ",\"upload_ms\":%.2f,\"chip_median_ns\":%" PRIu64 ",\"gbps_chip\":%.2f,\"call_median_ns\":%" PRIu64 ",\"gbps_call\":%.2f,\"reps\":%u,\"marker\":%u,\"evict\":%d}", - first ? "" : ",", p->name, p->experts, p->n, p->k, p->groups, p->x_rows, omega_gpu_fp8_rc_name(rc), bad, worst, same, - omega_gpu_fp8_variant(), info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, up_ms, med_el, gbs, med_cl, gbs_call, done, info.completion_marker, g_evict); - first = 0; - free(el); free(cl); - /* mutants on the first grouped point and the gate shape: each must be caught on the chip */ - if (ok && (g_custom_n || i == 4 || i == 10)) { - for (int m = 1; m <= 4; m++) { - if (m == 3 && p->groups == 1) continue; - if (m == 4) omega_gpu_fp8_test_set_no_fold(1); else omega_gpu_fp8_test_set_mutant(m); - OmegaGpuFp8Tensor *tm = t; - if (m == 4) { tm = NULL; if (omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &tm) != OMEGA_GPU_FP8_OK) tm = NULL; } - int r = tm ? omega_gpu_fp8_gemv_grouped_f32(tm, p->groups, ids, x, p->x_rows, y2, NULL) : OMEGA_GPU_FP8_CHIP_FAIL; - size_t mb = 0; double mw = r == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y2, &mb) : 1.0; - int caught = r != OMEGA_GPU_FP8_OK || mb > 0; - CHECK(caught, "chip %s mutant %d NOT caught", p->name, m); - printf("chip %-32s mutant %d: %s (rc=%s bad=%zu worst_rel=%.3e)\n", p->name, m, caught ? "caught" : "MISSED", omega_gpu_fp8_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e}", p->name, m, caught, omega_gpu_fp8_rc_name(r), mb, mw); - if (m == 4) { omega_gpu_fp8_test_set_no_fold(0); if (tm) omega_gpu_fp8_tensor_free(tm); } else omega_gpu_fp8_test_set_mutant(0); - } - } - omega_gpu_fp8_tensor_free(t); - free(x); free(y); free(y2); weights_free(&W); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_FP8_GEMV_PASS" : "OMEGA_GPU_FP8_GEMV_FAIL"); fclose(out); } - return 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 20, lb = 0, rows = 0, warps = 0, budget = 0, spin = 2000, depth = 0; int depth_set = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--lane-bytes") == 0 && i + 1 < argc) lb = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--rows") == 0 && i + 1 < argc) rows = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) budget = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) { depth_set = 1; depth = (uint32_t)atoi(argv[++i]); } - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i]; - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) g_custom_n = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) g_custom_k = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--gpr-pad") == 0 && i + 1 < argc) omega_gpu_fp8_set_gpr_pad((uint32_t)atoi(argv[++i])); - else if (strcmp(argv[i], "--variant") == 0 && i + 1 < argc) omega_gpu_fp8_set_variant(atoi(argv[++i])); /* 1 (default) or 2 (W-L2c row-pipelined) */ - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(budget ? budget : 4); - if (!host && !sim) { - if (lb || rows || warps) omega_gpu_fp8_set_shape(lb, rows, warps); - if (budget) omega_gpu_fp8_set_cta_budget(budget); - if (depth_set) { omega_gpu_fp8_set_depth(1, depth); g_depth_forced = 1; } - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_fp8gemm_test.c b/tests/gpu_fp8gemm_test.c deleted file mode 100644 index 691d3df40..000000000 --- a/tests/gpu_fp8gemm_test.c +++ /dev/null @@ -1,345 +0,0 @@ -/* - * gpu_fp8gemm_test: the prefill FP8 grouped GEMM (omega_gpu_fp8gemm_api.h), OWN-30B builder F item 26. - * --host-only emulation vs the FP8 double oracle, permutation, codegen budgets and refusals (no device) - * --sim warp-simulator parity (build with -DWS_MAX_THREADS=512): bit-identical to the host emulation of the - * GEMV's summation order in both fragment orders, multi-segment, multi-pass, row clamping, mutants 1-3 caught - * (default) the chip. Gate|up 128 x 1536 x 2048 and down 128 x 2048 x 768 over 64 tokens x top-8 routed rows, dense - * qkv 5120 x 2048 and o 2048 x 4096 over 64 rows: every output row bit-identical to omega_gpu_fp8_gemv_f32 - * on the same row, a few rows against the host emulation and the double oracle, mutants caught, - * timing medians (host caches evicted) vs the per-token grouped-GEMV path. - * knobs: --reps N --mt N --warps N --ctas N --no-evict --tokens N --spin-us N --shape gateup|down|qkv|o|all --out receipt.json - * Verdict line last: "gpu_fp8gemm_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_fp8gemm_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; } -static float f32_of_bits(uint32_t b) { float f; memcpy(&f, &b, 4); return f; } - -typedef struct { uint32_t experts, n, k; uint8_t *w; uint16_t *s; } Weights; -static void weights_make(Weights *W, uint32_t experts, uint32_t n, uint32_t k, uint32_t seed) { - W->experts = experts; W->n = n; W->k = k; - size_t wb = (size_t)experts * n * k, sc = (size_t)experts * ((n + 127) / 128) * (k / 128); - W->w = malloc(wb); W->s = malloc(sc * 2); - uint32_t st = seed; - for (size_t i = 0; i < wb; i++) W->w[i] = rand_e4m3(&st); - for (size_t i = 0; i < sc; i++) W->s[i] = bf16_rne(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f)); -} -static void weights_free(Weights *W) { free(W->w); free(W->s); } - -/* The kernel's exact f32 result for one (expert row, activation row): per lane, per K step a dot chain over the lane's LB - * bytes (word, byte), acc = fma(dot, S', acc), then the SHFL.DOWN tree 16..1. w: the row's k bytes, s: its k/128 scale words - * (bf16 bits of one 128-row block), x: natural-order activation row. */ -static float emu_row(const uint8_t *w, const uint16_t *s, const float *x, uint32_t k, uint32_t lb) { - float xp[16384]; omega_fp8_pack_x_f32(x, k, xp); - float a[32]; const uint32_t steps = k / (32u * lb); - for (unsigned lane = 0; lane < 32; lane++) { - float acc = 0.0f; - for (uint32_t st = 0; st < steps; st++) { - float dot = 0.0f; const uint32_t c0 = st * 32u * lb + lane * lb; - for (uint32_t b = 0; b < lb; b++) dot = fmaf(f32_of_bits(omega_fp8_e4m3_kernel_bits(w[c0 + b])), xp[c0 + b], dot); - float sp = bf16_f32(s[c0 / 128u]) * 72057594037927936.0f; /* * 2^56 */ - acc = fmaf(dot, sp, acc); - } - a[lane] = acc; - } - for (unsigned o = 16; o >= 1; o /= 2) { float b[32]; for (unsigned l = 0; l < 32; l++) b[l] = a[l + o < 32 ? l + o : l]; for (unsigned l = 0; l < 32; l++) a[l] += b[l]; } - return a[0]; -} -/* full expected output of a row table against Weights W (emulation) */ -static void expect_rows(const Weights *W, uint32_t M, const uint32_t *ids, const uint32_t *trow, const float *x, float *y, uint32_t lb) { - const uint32_t n = W->n, k = W->k; - for (uint32_t i = 0; i < M; i++) for (uint32_t r = 0; r < n; r++) - y[(size_t)i * n + r] = emu_row(W->w + ((size_t)ids[i] * n + r) * k, W->s + ((size_t)ids[i] * ((n + 127) / 128) + r / 128) * (k / 128), x + (size_t)trow[i] * k, k, lb); -} -static float *make_x(uint32_t rows, uint32_t k, uint32_t seed) { - float *x = malloc((size_t)rows * k * 4); uint32_t s = seed; - for (size_t i = 0; i < (size_t)rows * k; i++) x[i] = frand(&s, -2.0f, 2.0f); - return x; -} -/* a routed row table: `tokens` tokens x top-k distinct experts, sorted by expert (ties by token) */ -static uint32_t make_table(uint32_t tokens, uint32_t topk, uint32_t experts, uint32_t seed, uint32_t *ids, uint32_t *trow, uint32_t *picks) { - uint32_t M = tokens * topk, st = seed; - uint32_t *cnt = calloc(experts, 4), (*pick)[16] = malloc((size_t)tokens * sizeof *pick); - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) { - uint32_t e; int dup; - do { e = (lcg(&st) >> 8) % experts; dup = 0; for (uint32_t q = 0; q < j; q++) if (pick[t][q] == e) dup = 1; } while (dup); - pick[t][j] = e; cnt[e]++; - } - uint32_t *pos = malloc(experts * 4), c = 0; - for (uint32_t e = 0; e < experts; e++) { pos[e] = c; c += cnt[e]; } - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) { uint32_t e = pick[t][j], p = pos[e]++; ids[p] = e; trow[p] = t; } - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) picks[t * topk + j] = pick[t][j]; - free(cnt); free(pick); free(pos); - return M; -} - -static void host_only(void) { - printf("host-only: emulation, permutation, budgets\n"); - { Weights W; weights_make(&W, 1, 128, 2048, 5); float *x = make_x(1, 2048, 6); - double yo[128], ys[128]; omega_fp8_gemv_oracle(W.w, W.s, 128, 2048, x, yo, ys); - double worst = 0; for (uint32_t r = 0; r < 128; r++) { float e = emu_row(W.w + (size_t)r * 2048, W.s, x, 2048, 16); (void)e; } - for (uint32_t r = 0; r < 128; r++) { float e = emu_row(W.w + (size_t)r * 2048, W.s + (r / 128) * 16, x, 2048, 16); double d = fabs((double)e - yo[r]) / (ys[r] + 1e-30); if (d > worst) worst = d; } - CHECK(worst < 1e-5, "emulation vs the FP8 double oracle: worst rel %.2e", worst); - printf("emulation vs oracle: worst relative error %.2e of the term scale\n", worst); - weights_free(&W); free(x); } - { /* permutation is a bijection of each row, scaled by 2^64 */ - float x[2048], p[2048]; for (unsigned i = 0; i < 2048; i++) x[i] = (float)(i + 1); - omega_fp8gemm_permute_x(x, 2048, 16, p); - char *seen = calloc(2048, 1); int ok = 1; - for (unsigned i = 0; i < 2048; i++) { double v = (double)p[i] / 18446744073709551616.0; if (v < 1 || v > 2048 || seen[(int)v - 1]++) ok = 0; } - CHECK(ok, "permutation of a 2048-row is a bijection"); free(seen); - float p8[768]; float x8[768]; for (unsigned i = 0; i < 768; i++) x8[i] = (float)(i + 1); - omega_fp8gemm_permute_x(x8, 768, 8, p8); ok = 1; seen = calloc(768, 1); - for (unsigned i = 0; i < 768; i++) { double v = (double)p8[i] / 18446744073709551616.0; if (v < 1 || v > 768 || seen[(int)v - 1]++) ok = 0; } - CHECK(ok, "permutation of a 768-row (lane 8) is a bijection"); free(seen); - /* column c = lane L, word w, byte e of step 0 lands at (w*32 + L)*4 + e: c = 5 * 16 + 6 = 86 -> L 5, j 6 -> w 1, e 2 */ - CHECK(p[(1 * 32 + 5) * 4 + 2] / 18446744073709551616.0f == x[86], "column 86 sits at lane 5 word 1 element 2"); } - struct { uint32_t k, lb, mt, w; } shp[] = { { 2048, 16, 8, 16 }, { 4096, 16, 8, 16 }, { 1024, 16, 8, 16 }, { 768, 8, 8, 16 }, { 768, 8, 8, 8 }, { 2048, 8, 8, 16 }, { 2048, 16, 4, 16 }, { 2048, 16, 8, 32 }, { 2048, 16, 8, 8 }, { 2048, 16, 4, 8 }, { 4096, 16, 4, 8 } }; - for (unsigned i = 0; i < sizeof shp / sizeof shp[0]; i++) for (int m = 0; m <= 3; m++) { - OmegaFp8GemmSpec s = { shp[i].k, shp[i].lb, shp[i].mt, shp[i].w, m }; uint32_t n = 0, gp = 0; - int rc = omega_fp8gemm_prog_stats(&s, &n, &gp); - uint32_t decl = ((gp + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024, "codegen k %u lb %u mt %u warps %u mutant %d: rc %d insns %u gprs %u", s.k, s.lane_bytes, s.mt, s.warps, m, rc, n, gp); - if (m == 0 && rc == 0) printf("codegen k %4u lane %2u mt %2u warps %2u: %u instructions, %u registers (declared %u, register file %u of 65536)%s, shared %u B\n", s.k, s.lane_bytes, s.mt, s.warps, n, gp, decl, 32u * s.warps * decl, 32u * s.warps * decl <= 65536u ? "" : " DOES NOT FIT", omega_fp8gemm_shared_bytes(&s)); - } - { OmegaFp8GemmSpec s = { 2048, 16, 16, 16, 0 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mt 16 at lane 16 refused (32 KB of shared memory)"); } - { OmegaFp8GemmSpec s = { 2048, 16, 6, 16, 0 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mt 6 refused"); } - { OmegaFp8GemmSpec s = { 2048, 16, 8, 16, 4 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mutant 4 refused"); } - CHECK(OMEGA_GEMM_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); - uint32_t ids[3] = { 2, 1, 1 }, tr[3] = { 0, 0, 0 }; float xr[2048] = { 0 }, yo[4]; - CHECK(omega_gpu_fp8gemm_f32(NULL, 3, ids, tr, xr, 1, yo, NULL) == OMEGA_GPU_FP8GEMM_BAD_ARGS, "a NULL tensor is refused"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -typedef struct { uint32_t k, n, lb, mt, w, grid; uint32_t counts[4]; uint32_t nseg; } SimPt; -static int sim_point(const SimPt *p, int mutant, uint32_t seed, char *msg, size_t msgn, size_t *bad) { - static BlackwellIRProgram prog; - OmegaFp8GemmSpec spec = { p->k, p->lb, p->mt, p->w, mutant }; - if (omega_blackwell_codegen_fp8gemm_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint32_t M = 0; for (uint32_t g = 0; g < p->nseg; g++) M += p->counts[g]; - Weights W; weights_make(&W, p->nseg, p->n, p->k, seed); - uint32_t ids[64], trow[64]; { uint32_t i = 0; for (uint32_t g = 0; g < p->nseg; g++) for (uint32_t c = 0; c < p->counts[g]; c++, i++) { ids[i] = g; trow[i] = (i * 5 + 1) % 16; } } - float *x = make_x(16, p->k, seed + 1); - float *yexp = malloc((size_t)M * p->n * 4); - expect_rows(&W, M, ids, trow, x, yexp, p->lb); - size_t wbytes = (size_t)p->nseg * p->n * p->k, sc = (size_t)p->nseg * ((p->n + 127) / 128) * (p->k / 128); - uint8_t *wd = aligned_alloc(16, (wbytes + 15) & ~15ull); memcpy(wd, W.w, wbytes); - float *sd = aligned_alloc(16, ((sc * 4) + 15) & ~15ull); omega_fp8_pack_scales(W.s, sc, sd, 0); - float *xp = aligned_alloc(16, ((size_t)(M + p->mt) * p->k * 4 + 15) & ~15ull); memset(xp, 0, (size_t)(M + p->mt) * p->k * 4); - float *tmp = malloc((size_t)p->k * 4); - for (uint32_t i = 0; i < M; i++) { memcpy(tmp, x + (size_t)trow[i] * p->k, (size_t)p->k * 4); omega_fp8gemm_permute_x(tmp, p->k, p->lb, xp + (size_t)i * p->k); } - typedef struct { uint64_t w, s; uint32_t row0, cnt, pad[2]; } Seg; - Seg *seg = aligned_alloc(16, 64 * sizeof(Seg)); memset(seg, 0, 64 * sizeof(Seg)); - { uint32_t r0 = 0; for (uint32_t g = 0; g < p->nseg; g++) { seg[g].w = (uintptr_t)(wd + (size_t)g * p->n * p->k); seg[g].s = (uintptr_t)(sd + (size_t)g * ((p->n + 127) / 128) * (p->k / 128)); seg[g].row0 = r0; seg[g].cnt = p->counts[g]; r0 += p->counts[g]; } } - float *y = aligned_alloc(16, ((size_t)M * p->n * 4 + 15) & ~15ull); - uint32_t shared = omega_fp8gemm_shared_bytes(&spec); - uint8_t *smem = aligned_alloc(16, shared); - float *ycopy = NULL; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * p->w; s.order = order; s.smem = smem; s.smem_bytes = shared; - for (size_t i = 0; i < (size_t)M * p->n; i++) y[i] = -999.0f; - uint64_t A[3] = { (uintptr_t)seg, (uintptr_t)xp, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_GEMM_ARG_N / 4] = p->n; s.cbank[OMEGA_GEMM_ARG_STRIDE / 4] = p->grid * p->w; - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)seg; s.ranges[0].hi = (uintptr_t)seg + 64 * sizeof(Seg); - s.ranges[1].lo = (uintptr_t)wd; s.ranges[1].hi = (uintptr_t)wd + wbytes; - s.ranges[2].lo = (uintptr_t)sd; s.ranges[2].hi = (uintptr_t)sd + sc * 4; - s.ranges[3].lo = (uintptr_t)xp; s.ranges[3].hi = (uintptr_t)xp + (size_t)(M + p->mt) * p->k * 4; - s.ranges[4].lo = (uintptr_t)y; s.ranges[4].hi = (uintptr_t)y + (size_t)M * p->n * 4; - err = ws_run(&s, p->grid, p->nseg); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (y[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msgn, "%zu output words never written", unwritten); break; } - if (order == 0) { ycopy = malloc((size_t)M * p->n * 4); memcpy(ycopy, y, (size_t)M * p->n * 4); } - else if (memcmp(ycopy, y, (size_t)M * p->n * 4) != 0) { err = -1; snprintf(msg, msgn, "the fragment order changed the result"); } - } - if (!err) { size_t b = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (memcmp(&yexp[i], &y[i], 4) != 0) b++; *bad = b; snprintf(msg, msgn, "%zu of %zu outputs differ from the emulation%s", b, (size_t)M * p->n, b ? "" : " (bit-identical)"); } - free(ycopy); free(wd); free(sd); free(xp); free(tmp); free(seg); free(y); free(smem); free(yexp); free(x); weights_free(&W); - return err; -} -static void sim_battery(void) { - SimPt pts[] = { - { 2048, 40, 16, 8, 16, 2, { 1, 5, 9 }, 3 }, /* lane 16, KS 4 (2 iterations), 2 passes in segment 3, row clamping (n 40 < 2 x 32 x 1) */ - { 4096, 20, 16, 8, 16, 1, { 3, 8 }, 2 }, /* KS 8: 4 iterations */ - { 1024, 33, 16, 8, 16, 2, { 2, 1 }, 2 }, /* KS 2: one iteration, no tail prefetch */ - { 768, 130, 8, 8, 16, 2, { 4, 17 }, 2 }, /* lane 8, KS 3 (odd, unrolled), 2 row blocks of scales, 2 passes */ - { 768, 24, 8, 8, 8, 1, { 1, 8, 2 }, 3 }, /* lane 8 at 8 warps */ - { 2048, 16, 16, 4, 16, 1, { 6, 4 }, 2 }, /* mt 4 */ - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_point(&pts[i], 0, 31 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim k %u n %u lane %u mt %u warps %u grid %u: %s", pts[i].k, pts[i].n, pts[i].lb, pts[i].mt, pts[i].w, pts[i].grid, msg); - printf("sim k %u n %u lane %u mt %u warps %u grid %u: %s %s\n", pts[i].k, pts[i].n, pts[i].lb, pts[i].mt, pts[i].w, pts[i].grid, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 3; m++) { - char msg[300]; size_t bad = 0; - int err = sim_point(&pts[0], m, 77, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static double med(uint64_t *v, uint32_t n) { qsort(v, n, 8, cmp_u64); return (double)v[n / 2]; } - -typedef struct { const char *name; uint32_t experts, n, k, tokens, topk; } Shape; -static FILE *g_out; static int g_first = 1; - -static void run_shape(const Shape *S, uint32_t reps, uint32_t seed) { - printf("== %s: %u experts, n %u, k %u, %u tokens x top-%u\n", S->name, S->experts, S->n, S->k, S->tokens, S->topk); - Weights W; weights_make(&W, S->experts, S->n, S->k, seed); - OmegaGpuFp8Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_fp8_tensor_upload(S->experts, S->n, S->k, W.w, W.s, &t); - printf("upload %.0f MB: rc=%s %.0f ms\n", (double)S->experts * S->n * S->k / 1e6, omega_gpu_fp8_rc_name(rc), now_ms() - t0); - CHECK(rc == 0, "%s upload", S->name); - if (rc) { weights_free(&W); return; } - const uint32_t M = S->tokens * S->topk; - uint32_t *ids = malloc(M * 4), *trow = malloc(M * 4); - uint32_t *picks = malloc((size_t)M * 4); - make_table(S->tokens, S->topk, S->experts, seed + 7, ids, trow, picks); - uint32_t xrows = S->experts > 1 ? (S->k == 768 ? M : S->tokens) : S->tokens; - if (S->experts > 1 && S->k == 768) for (uint32_t i = 0; i < M; i++) trow[i] = i; /* down: one activation row per routed row */ - float *x = make_x(xrows, S->k, seed + 3); - float *y = malloc((size_t)M * S->n * 4), *yref = malloc((size_t)M * S->n * 4), *y2 = malloc((size_t)M * S->n * 4); - OmegaGpuFp8GemmInfo info; - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y, &info); - CHECK(rc == 0, "%s gemm: %s %s", S->name, omega_gpu_fp8gemm_rc_name(rc), rc ? omega_gpu_fp8gemm_last_error() : ""); - if (rc == 0) { - /* reference: the existing GEMV, one call per row */ - double tr = now_ms(); size_t bad = 0, first = (size_t)-1; - for (uint32_t i = 0; i < M; i++) { - int r2 = omega_gpu_fp8_gemv_f32(t, ids[i], x + (size_t)trow[i] * S->k, yref + (size_t)i * S->n, NULL); - if (r2) { printf("gemv reference failed at row %u: %s\n", i, omega_gpu_fp8_last_error()); bad = (size_t)-1; break; } - } - if (bad == 0) for (size_t i = 0; i < (size_t)M * S->n; i++) if (memcmp(&y[i], &yref[i], 4) != 0) { if (!bad) first = i; bad++; } - CHECK(bad == 0, "%s: %zu of %zu outputs differ from the per-row GEMV (first %zd)", S->name, bad, (size_t)M * S->n, (ssize_t)first); - printf("parity vs per-row GEMV (%u calls, %.0f ms): %zu of %zu outputs differ%s\n", M, now_ms() - tr, bad, (size_t)M * S->n, bad ? "" : " (bit-identical)"); - /* host emulation + oracle on a few rows */ - size_t eb = 0; double worst = 0; uint32_t lb = info.lane_bytes; - for (uint32_t q = 0; q < 4; q++) { - uint32_t i = (q * 977u + 3u) % M, r = (q * 331u + 17u) % S->n; - float e = emu_row(W.w + ((size_t)ids[i] * S->n + r) * S->k, W.s + ((size_t)ids[i] * ((S->n + 127) / 128) + r / 128) * (S->k / 128), x + (size_t)trow[i] * S->k, S->k, lb); - if (memcmp(&e, &y[(size_t)i * S->n + r], 4) != 0) eb++; - double yo[128], ys[128]; /* oracle over the 128-row block holding r */ - uint32_t b0 = (r / 128) * 128; - omega_fp8_gemv_oracle(W.w + ((size_t)ids[i] * S->n + b0) * S->k, W.s + ((size_t)ids[i] * ((S->n + 127) / 128) + r / 128) * (S->k / 128), 128, S->k, x + (size_t)trow[i] * S->k, yo, ys); - double d = fabs((double)y[(size_t)i * S->n + r] - yo[r - b0]) / (ys[r - b0] + 1e-30); if (d > worst) worst = d; - } - CHECK(eb == 0 && worst < 1e-5, "%s: host emulation mismatches %zu, oracle worst %.2e", S->name, eb, worst); - printf("4 sampled outputs: %zu differ from the host emulation, worst relative error vs the double oracle %.2e\n", eb, worst); - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, NULL); - CHECK(rc == 0 && memcmp(y, y2, (size_t)M * S->n * 4) == 0, "%s: second call bit-identical", S->name); - printf("second call: %s\n", rc == 0 && memcmp(y, y2, (size_t)M * S->n * 4) == 0 ? "bit-identical" : "DIFFERS"); - /* mutants */ - for (int m = 1; m <= 3; m++) { - omega_gpu_fp8gemm_test_set_mutant(m); - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, NULL); - size_t b = 0; if (rc == 0) for (size_t i = 0; i < (size_t)M * S->n; i++) if (memcmp(&y[i], &y2[i], 4) != 0) b++; - if (rc != 0) printf("chip mutant %d: call returned %s: %s\n", m, omega_gpu_fp8gemm_rc_name(rc), omega_gpu_fp8gemm_last_error()); - int caught = rc == 0 && b != 0; - if (m == 2 && info.k / (32u * info.lane_bytes) < 2) caught = 1; /* single-step k: mutant 2 has no effect by construction */ - CHECK(caught, "%s: chip mutant %d must be caught", S->name, m); - printf("chip mutant %d: %s (%zu of %zu outputs differ)\n", m, caught ? "caught" : "NOT CAUGHT", b, (size_t)M * S->n); - if (g_out) fprintf(g_out, "%s{\"point\":\"%s mutant %d\",\"caught\":%d}", g_first ? "" : ",", S->name, m, caught), g_first = 0; - } - omega_gpu_fp8gemm_test_set_mutant(0); - /* timing: the new path vs the per-token path (grouped GEMV, 8 experts per token for the MoE shapes; one GEMV per row for dense) */ - uint64_t *ce = malloc(reps * 8), *cc = malloc(reps * 8); uint32_t done = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - { int r3 = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, &info); if (r3 != 0) { printf("timing call %u: %s: %s\n", i, omega_gpu_fp8gemm_rc_name(r3), omega_gpu_fp8gemm_last_error()); break; } } - ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; - } - CHECK(done == reps, "%s timing loop completed %u of %u", S->name, done, reps); - double mc = done ? med(ce, done) : 0, ma = done ? med(cc, done) : 0; - printf("GEMM (medians of %u, evict %d): mt %u warps %u ctas %u x %u segments, %u rows, up to %u passes: chip %.1f us, call %.1f us; streams %.0f MB (distinct experts %.0f MB) = %.1f GB/s on streamed, %.1f GB/s on distinct\n", - done, g_evict, info.mt, info.warps_per_cta, info.grid_x, info.segments, M, info.passes_max, mc / 1e3, ma / 1e3, info.streamed_bytes / 1e6, info.weight_bytes / 1e6, info.streamed_bytes / mc, info.weight_bytes / mc); - /* per-token baseline: for the MoE shapes one grouped GEMV (topk experts) per token; the sorted table is rebuilt per token */ - uint64_t *bc = malloc(reps * 8), *bw = malloc(reps * 8); uint32_t bd = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - uint64_t sum_e = 0, sum_c = 0; int ok = 1; - for (uint32_t tk = 0; tk < S->tokens && ok; tk++) { - OmegaGpuFp8Info fi; int r2; - if (S->experts == 1) r2 = omega_gpu_fp8_gemv_f32(t, 0, x + (size_t)tk * S->k, yref, &fi); - else if (S->k == 768) r2 = omega_gpu_fp8_gemv_grouped_f32(t, S->topk, picks + (size_t)tk * S->topk, x + (size_t)tk * S->topk * S->k, S->topk, yref, &fi); - else r2 = omega_gpu_fp8_gemv_grouped_f32(t, S->topk, picks + (size_t)tk * S->topk, x + (size_t)tk * S->k, 1, yref, &fi); - if (r2) ok = 0; else { sum_e += fi.elapsed_ns; sum_c += fi.call_ns; } - } - if (!ok) break; - bc[bd] = sum_e; bw[bd] = sum_c; bd++; - } - double mb = bd ? med(bc, bd) : 0, mbw = bd ? med(bw, bd) : 0; - if (bd) printf("per-token grouped GEMV baseline (%u tokens, medians of %u): chip %.1f us, call %.1f us => GEMM is %.2fx faster (chip), %.2fx (call)\n", S->tokens, bd, mb / 1e3, mbw / 1e3, mb / mc, mbw / ma); - printf("per token: GEMM chip %.1f us/token, call %.1f us/token\n", mc / 1e3 / S->tokens, ma / 1e3 / S->tokens); - if (g_out) fprintf(g_out, "%s{\"point\":\"%s timing\",\"rows\":%u,\"segments\":%u,\"mt\":%u,\"warps\":%u,\"ctas\":%u,\"passes_max\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%.0f,\"streamed_bytes\":%" PRIu64 ",\"distinct_bytes\":%" PRIu64 ",\"gbps_streamed\":%.2f,\"baseline_chip_median_ns\":%.0f,\"baseline_call_median_ns\":%.0f,\"parity_bad\":%zu}", - g_first ? "" : ",", S->name, M, info.segments, info.mt, info.warps_per_cta, info.grid_x, info.passes_max, done, mc, ma, info.streamed_bytes, info.weight_bytes, info.streamed_bytes / mc, mb, mbw, bad), g_first = 0; - free(ce); free(cc); free(bc); free(bw); - } - omega_gpu_fp8_tensor_free(t); - free(ids); free(trow); free(picks); free(x); free(y); free(yref); free(y2); weights_free(&W); -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL, *shape = "all"; uint32_t reps = 0, mt = 0, warps = 0, ctas = 0, spin = 2000, tokens = 64; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--shape") == 0 && i + 1 < argc) shape = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--mt") == 0 && i + 1 < argc) mt = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--ctas") == 0 && i + 1 < argc) ctas = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--tokens") == 0 && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (mt || warps) omega_gpu_fp8gemm_set_shape(mt, warps); - if (ctas) omega_gpu_fp8gemm_set_cta_budget(ctas); - (void)omega_gpu_session_set_spin_us(spin); - if (out_path) { g_out = fopen(out_path, "w"); if (g_out) fprintf(g_out, "{\"receipt\":\"OMEGA_GPU_FP8GEMM_V1\",\"reps\":%u,\"evict\":%d,\"tokens\":%u,\"spin_us\":%u,\"points\":[", reps ? reps : 1, g_evict, tokens, omega_gpu_session_spin_us()); } - Shape shapes[] = { { "gateup", 128, 1536, 2048, tokens, 8 }, { "down", 128, 2048, 768, tokens, 8 }, { "qkv", 1, 5120, 2048, tokens, 1 }, { "o", 1, 2048, 4096, tokens, 1 }, { "d768", 1, 2048, 768, tokens, 1 } }; - for (unsigned i = 0; i < 5; i++) if ((!strcmp(shape, "all") && i < 4) || !strcmp(shape, shapes[i].name)) run_shape(&shapes[i], reps ? reps : 1, 1000 + i); - if (g_out) { fprintf(g_out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(g_out); } - omega_gpu_session_close(); - } - printf("gpu_fp8gemm_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_gpr_boundary_test.c b/tests/gpu_gpr_boundary_test.c deleted file mode 100644 index 448606952..000000000 --- a/tests/gpu_gpr_boundary_test.c +++ /dev/null @@ -1,85 +0,0 @@ -/* gpu_gpr_boundary_test: host-only audit of the declared-register rule (OWN-30B, 2026-10-13). - * Rule (omega_blackwell_codegen.h): declared = peak + 2 rounded up to a multiple of 8. A fp8 grouped GEMM kernel with - * peak 103 declared 104 (the old peak + 1 rule) hung the chip; the same program declared 112 ran. - * Checks: the helper for every peak; every launcher's own `declared` for every live kernel spec; the matmul family - * (declared by the session from the raw peak) is listed and must not be reachable at a boundary from a Qwen3-30B-A3B shape. */ -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_codegen_bf16.h" -#include "omega_blackwell_codegen_router.h" -#include "omega_blackwell_codegen_attn.h" -#include "omega_blackwell_codegen_gemm.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_router_api.h" -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_fp8gemm_api.h" -#include -#include - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static BlackwellIRProgram g_prog; - -int main(void) { - for (uint32_t peak = 0; peak <= 126; peak++) { - uint32_t d = omega_bw_gpr_declared(peak); - CHECK(d >= peak + 2 && d % 8 == 0 && d - (peak + 2) < 8 && omega_bw_gpr_declared_ok(d, peak), "helper at peak %u gives %u", peak, d); - CHECK(!omega_bw_gpr_declared_ok(((peak + 1u + 7u) / 8u) * 8u, peak) || peak % 8 != 7, "old rule at peak %u must be refused", peak); - } - CHECK(!omega_bw_gpr_declared_ok(104, 103) && omega_bw_gpr_declared_ok(112, 103), "the 103 / 104 hang case is refused, 112 accepted"); - CHECK(!omega_bw_gpr_declared_ok(64, 64) && !omega_bw_gpr_declared_ok(72, 72) && omega_bw_gpr_declared_ok(72, 64), "peak 64 and 72 need 72 and 80 / 72"); - - /* fp8 GEMV: live shapes through the API's own shape / depth rules */ - struct { unsigned n, k, groups; } fs[] = { {4096,2048,1},{512,2048,1},{5120,2048,1},{2048,4096,1},{1536,2048,8},{2048,768,8},{1536,2048,1},{2048,768,1},{1u<<20,2048,1},{1u<<20,4096,1},{1u<<20,768,1} }; - for (unsigned i = 0; i < sizeof fs / sizeof *fs; i++) { - OmegaFp8GemvSpec s; memset(&s, 0, sizeof s); s.k = fs[i].k; - omega_gpu_fp8_shape_for(s.k, fs[i].n, &s.lane_bytes, &s.rows, &s.warps); - if (fs[i].groups > 1) s.warps = 32; - s.depth = omega_gpu_fp8_depth_for(&s, fs[i].n, fs[i].groups); - uint32_t peak = 0, decl = 0; - CHECK(omega_fp8_gemv_prog_stats(&s, NULL, &peak) == 0, "fp8 gemv %ux%u x%u builds", fs[i].n, fs[i].k, fs[i].groups); - (void)omega_gpu_fp8_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "fp8 gemv %ux%u x%u: peak %u declared %u", fs[i].n, fs[i].k, fs[i].groups, peak, decl); - } - /* every buildable fp8 GEMV variant */ - { unsigned bad = 0, n = 0; - for (unsigned k = 256; k <= 8192; k += 256) for (unsigned lb = 8; lb <= 16; lb += 8) for (unsigned rows = 1; rows <= 8; rows *= 2) for (unsigned w = 1; w <= 32; w *= 2) for (unsigned dp = 0; dp <= 8; dp += dp ? dp : 1) { - OmegaFp8GemvSpec s = { k, lb, rows, w, dp, 0 }; uint32_t peak = 0, decl = 0; - if (omega_fp8_gemv_prog_stats(&s, NULL, &peak) != 0) continue; - n++; (void)omega_gpu_fp8_kernel_fits(&s, &decl); - if (!omega_bw_gpr_declared_ok(decl, peak) && decl != 0) bad++; - } - CHECK(bad == 0, "fp8 gemv sweep: %u of %u variants declared below peak + 2", bad, n); printf("fp8 gemv sweep: %u variants, %u below peak + 2\n", n, bad); } - /* bf16 GEMV */ - { unsigned ks[] = { 2048, 4096 }; for (unsigned i = 0; i < 2; i++) { OmegaBf16GemvSpec s; memset(&s, 0, sizeof s); s.k = ks[i]; uint32_t c; omega_gpu_bf16_shape_for(s.k, &s.rows, &s.warps, &s.depth, &c); - uint32_t peak = 0, decl = 0; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, &peak) == 0, "bf16 k%u builds", ks[i]); (void)omega_gpu_bf16_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "bf16 gemv k%u: peak %u declared %u", ks[i], peak, decl); } } - /* fp8 grouped GEMM (all shapes we launch) */ - { unsigned ks[] = { 2048, 768, 4096 }, mts[] = { 4, 8 }; for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 2; j++) { - OmegaFp8GemmSpec s = { ks[i], ks[i] % 512 ? 8u : 16u, mts[j], 16, 0 }; uint32_t peak = 0, decl = 0; - CHECK(omega_fp8gemm_prog_stats(&s, NULL, &peak) == 0, "gemm k%u mt%u builds", ks[i], mts[j]); (void)omega_gpu_fp8gemm_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "gemm k%u mt%u: peak %u declared %u", ks[i], mts[j], peak, decl); } } - /* router and decode attention: the launcher uses omega_bw_gpr_declared(peak) (static), so check the helper on the real peak */ - { OmegaRouterSpec s = { OMEGA_GPU_ROUTER_WARPS, OMEGA_GPU_ROUTER_DEPTH, 0 }; uint32_t peak = 0; - CHECK(omega_router_prog_stats(&s, NULL, &peak) == 0 && omega_bw_gpr_declared_ok(omega_bw_gpr_declared(peak), peak), "router peak %u", peak); printf("router peak %u -> declared %u\n", peak, omega_bw_gpr_declared(peak)); } - { OmegaDecodeAttnSpec s = { OMEGA_GPU_DATTN_DEPTH, 0 }; uint32_t peak = 0; - CHECK(omega_decode_attn_prog_stats(&s, NULL, &peak) == 0 && omega_bw_gpr_declared_ok(omega_bw_gpr_declared(peak), peak), "decode attn peak %u", peak); printf("decode attn peak %u -> declared %u\n", peak, omega_bw_gpr_declared(peak)); } - /* matmul / moe-window fragment kernels: declared by the session from the raw peak (max(64, peak rounded up to 8)). - * Boundary combinations are reported; the shapes of Qwen3-30B-A3B (n a multiple of 32) never select them. */ - { unsigned kps[] = { 768, 2048, 4096 }, nps[] = { 8, 128, 1536, 2048, 4096, 5120, 151936 }; unsigned built = 0, boundary = 0, model_boundary = 0; - for (unsigned a = 0; a < 3; a++) for (unsigned b = 0; b < 7; b++) for (unsigned rt = 1; rt <= 4; rt *= 2) for (unsigned ct = 1; ct <= 4; ct *= 2) { - OmegaMatMulSpec s; if (omega_matmul_spec_init(&s, 16, kps[a], nps[b], OMEGA_MATMUL_PRECISION_BF16) != 0) continue; - unsigned un = (rt > 1 || ct > 1) ? omega_matmul_frag_block_unroll(kps[a], rt, ct) : omega_matmul_frag_unroll(kps[a]); - memset(&g_prog, 0, sizeof g_prog); - int rc = (rt > 1 || ct > 1) ? omega_blackwell_codegen_matmul_frag_block_prog(&s, 48, un, rt, ct, 0, &g_prog) : omega_blackwell_codegen_matmul_frag_prog(&s, 48, un, 0, &g_prog); - if (rc) continue; - built++; - uint32_t pk = g_prog.regalloc.peak_gpr_usage, decl = pk > 64 ? ((pk + 7) / 8) * 8 : 64; - if (decl < pk + 2) { boundary++; unsigned mt = 4, nt = nps[b] / 8; uint32_t r, c; omega_matmul_frag_block_shape(mt, nt, &r, &c); if (r == rt && c == ct) model_boundary++; } - } - printf("matmul fragment kernels: %u built, %u at a boundary (session declares the raw peak), %u of those selected for a model shape\n", built, boundary, model_boundary); - CHECK(model_boundary == 0, "a Qwen3-30B shape reaches a matmul kernel declared below peak + 2"); } - printf("gpu_gpr_boundary_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_l2_reuse_test.c b/tests/gpu_l2_reuse_test.c deleted file mode 100644 index 556cb872c..000000000 --- a/tests/gpu_l2_reuse_test.c +++ /dev/null @@ -1,120 +0,0 @@ -/* gpu_l2_reuse_test: does an FP8 GEMV that re-reads weights another launch just read run faster? (OWN-30B W-L2d, 2026-10-14) - * - * Question behind it: a decode token has ~120 us per layer where DRAM is idle (attention at pos 300 ~73 us latency-bound, - * router ~25 us, glue ~18 us; W-L2 timeline). If the GB10 L2 keeps a GEMV's weights between two launches, an independent - * prefetch launch overlapped with those latency-bound launches (no barrier between them: no data dependency) could pull the - * NEXT GEMV's weights into L2, and that GEMV would then run from L2. This test measures only the precondition: the same - * tensor read twice in one list, [GEMV(T) -> y][WAIT_FOR_IDLE][GEMV(T) -> y], GPU timestamps around each launch. - * One variable per pass: the weight memory policy (GPU-uncached = every session buffer today, vs GPU-cached, - * omega_gpu_fp8_set_weight_cache). Sizes n x 2048 for n = 1024 .. 16384 (2 .. 33.5 MB) bracket the unknown L2 size. - * Barrier WFI_ONLY (no shader-cache invalidate; the chip study r1 showed the form does not change the time). - * Every rep: y poisoned first, y bit-identical to the one-launch-at-a-time reference. - * Negative control: the uncached pass (no reuse is possible through an uncached mapping, nvos.h:1117) must show warm ~= cold. - * Chip only: caller holds the GB10 lock. Output "L2 cached=.. n=.. MB=.. cold_us=.. warm_us=.. ratio=..", --out receipt JSON. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -static int g_checks, g_failed; -#define EV_N 32768u -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median(uint64_t *v, uint32_t n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -int main(int argc, char **argv) { - uint32_t reps = 10, k = 2048; const char *out_path = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else { printf("usage: %s [--reps R] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0 || reps > 64) reps = 10; - static const uint32_t ns[] = { 1024, 2048, 4096, 8192, 12288, 16384 }; - const uint32_t nmax = 16384; - omega_gpu_fp8_set_depth(1, 0); - (void)omega_gpu_session_set_spin_us(2000); - uint8_t *w = malloc((size_t)nmax * k); uint16_t *sc = malloc((size_t)(nmax / 128) * (k / 128) * 2); float *x = malloc((size_t)k * 4), *ref = malloc((size_t)nmax * 4); - uint32_t st = 2026; - for (size_t i = 0; i < (size_t)nmax * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); w[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(nmax / 128) * (k / 128); i++) sc[i] = 0x3F80; - for (uint32_t i = 0; i < k; i++) x[i] = (float)(lcg(&st) >> 8) / 16777216.0f * 2.0f - 1.0f; - - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(8, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; } - OmegaGpuMem tab, xd, yd, ye; - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc(32u, &tab) | omega_gpu_session_alloc((size_t)k * 4u, &xd) | omega_gpu_session_alloc((size_t)nmax * 4u, &yd) | omega_gpu_session_alloc((size_t)EV_N * 4u, &ye); - omega_gpu_session_unlock(); - if (arc != 0) { printf("alloc: %s\n", omega_gpu_session_last_error()); return 1; } - omega_fp8_pack_x_f32(x, k, xd.cpu); - if (omega_gpu_session_sync_to_gpu(&xd) != 0) return 1; - - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_L2_REUSE\",\"k\":%u,\"reps\":%u,\"points\":[", k, reps); - int first_pt = 1; double ratio_unc_max = 0, ratio_cached_min = 1e9; - /* evictor: a GPU-cached EV_N x k tensor (67 MB) read first in every list, so "cold" is cold even if L2 keeps lines across submits */ - OmegaGpuFp8Tensor *ev = NULL; - { uint8_t *we = malloc((size_t)EV_N * k); uint16_t *se = malloc((size_t)(EV_N / 128) * (k / 128) * 2); - for (size_t i = 0; i < (size_t)EV_N * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); we[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(EV_N / 128) * (k / 128); i++) se[i] = 0x3F80; - omega_gpu_fp8_set_weight_cache(1); - int erc = omega_gpu_fp8_tensor_upload(1, EV_N, k, we, se, &ev); - free(we); free(se); - float *yev = malloc((size_t)EV_N * 4); if (erc == OMEGA_GPU_FP8_OK) erc = omega_gpu_fp8_gemv_f32(ev, 0, x, yev, NULL); free(yev); /* kernel built + warm */ - uint64_t *tw = tab.cpu; - if (erc != OMEGA_GPU_FP8_OK || omega_gpu_fp8_tensor_entry(ev, 0, &tw[2], &tw[3]) != 0) { printf("evictor upload: %s\n", omega_gpu_fp8_last_error()); return 1; } } - for (int pass = 0; pass < 3; pass++) { const int cached = pass > 0, evict = pass != 1; /* (uncached, evict) (cached, no evict) (cached, evict) */ - omega_gpu_fp8_set_weight_cache(cached); - for (size_t ni = 0; ni < sizeof ns / sizeof ns[0]; ni++) { - const uint32_t n = ns[ni]; const uint64_t bytes = (uint64_t)n * k + (uint64_t)(n / 128) * (k / 128) * 4u; - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(1, n, k, w, sc, &t); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_f32(t, 0, x, ref, NULL); - if (rc != OMEGA_GPU_FP8_OK) { printf("upload/reference n=%u cached=%d: %s (%s)\n", n, cached, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); g_failed++; omega_gpu_fp8_tensor_free(t); break; } - uint64_t *tabw = tab.cpu; - if (omega_gpu_fp8_tensor_entry(t, 0, &tabw[0], &tabw[1]) != 0 || omega_gpu_session_sync_to_gpu(&tab) != 0) { g_failed++; omega_gpu_fp8_tensor_free(t); break; } - uint64_t colds[64], warms[64]; int identical = 1, ok = 1; - for (uint32_t r = 0; r < reps && ok; r++) { - float *y = yd.cpu; for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - if (omega_gpu_session_sync_to_gpu(&yd) != 0) { ok = 0; break; } - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - if (evict && omega_gpu_fp8_gemv_grouped_record(cl, ev, 1, tab.va + 16u, xd.va, 1, ye.va) != 0) { printf("record evictor: %s\n", omega_gpu_fp8_last_error()); ok = 0; } - for (int j = 0; j < 2 && ok; j++) - if (omega_gpu_fp8_gemv_grouped_record(cl, t, 1, tab.va, xd.va, 1, yd.va) != 0) { printf("record: %s\n", omega_gpu_fp8_last_error()); ok = 0; } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY; o.stamps = 1; - OmegaGpuCmdListStats s; memset(&s, 0, sizeof s); - uint64_t sts[4]; int cnt = -1; const int want = evict ? 4 : 3; - if (ok && omega_gpu_cmdlist_submit(cl, &o, &s) != 0) { printf("submit: %s\n", omega_gpu_session_last_error()); ok = 0; } - if (ok) cnt = omega_gpu_cmdlist_stamps(cl, sts, 4); - omega_gpu_session_unlock(); - if (!ok || cnt != want) { ok = 0; break; } - colds[r] = sts[want - 2] - sts[want - 3]; warms[r] = sts[want - 1] - sts[want - 2]; - if (omega_gpu_session_sync_to_cpu(&yd) != 0) { ok = 0; break; } - if (memcmp(y, ref, (size_t)n * 4) != 0) identical = 0; - } - CHECK(ok && identical, "cached=%d evict=%d n=%u: %u reps ran, y bit-identical to the reference on every rep", cached, evict, n, reps); - if (ok) { - const double c = median(colds, reps) / 1e3, wm = median(warms, reps) / 1e3, ratio = wm / c; - printf("L2 cached=%d evict=%d n=%-5u MB=%.1f cold_us=%.1f warm_us=%.1f ratio=%.3f cold_GB/s=%.1f warm_GB/s=%.1f\n", cached, evict, n, bytes / 1e6, c, wm, ratio, bytes / (c * 1e3), bytes / (wm * 1e3)); - if (cached && evict) { if (ratio < ratio_cached_min) ratio_cached_min = ratio; } else if (!cached && ratio > ratio_unc_max) ratio_unc_max = ratio; - if (out) { fprintf(out, "%s{\"cached\":%d,\"evict\":%d,\"n\":%u,\"bytes\":%" PRIu64 ",\"cold_ns\":%" PRIu64 ",\"warm_ns\":%" PRIu64 ",\"identical\":%d}", first_pt ? "" : ",", cached, evict, n, bytes, median(colds, reps), median(warms, reps), identical); first_pt = 0; } - } - omega_gpu_fp8_tensor_free(t); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); g_failed++; break; } - } - } - omega_gpu_fp8_set_weight_cache(0); - printf("SUMMARY uncached max warm/cold %.3f, cached min warm/cold %.3f\n", ratio_unc_max, ratio_cached_min); - if (out) { fprintf(out, "],\"uncached_ratio_max\":%.4f,\"cached_ratio_min\":%.4f,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", ratio_unc_max, ratio_cached_min, g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - printf("gpu_l2_reuse_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - omega_gpu_fp8_tensor_free(ev); - omega_gpu_cmdlist_free(cl); - free(w); free(sc); free(x); free(ref); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_l2_stale_test.c b/tests/gpu_l2_stale_test.c deleted file mode 100644 index f11c84ae7..000000000 --- a/tests/gpu_l2_stale_test.c +++ /dev/null @@ -1,106 +0,0 @@ -/* gpu_l2_stale_test: omega #457 regression test (chip). After the host rewrites a GPU-cached (CPU_WRITE | GPU_READ) buffer that the GPU has - * already read, does the next launch read the old bytes from GPU L2? - * - * Real path only: omega_gpu_fp8_tensor_upload (memcpy into the CPU mapping + omega_gpu_session_sync_to_gpu, which is - * a dsb sy and nothing else) and omega_gpu_fp8_gemv_f32 (one launch, C3 tail, output read back from uncached memory). - * One variable per process: --cached 0|1 (omega_gpu_fp8_set_weight_cache). --cached 0 is the negative control - * (uncached mapping: nvos.h:1117-1118 says only the cached case is not coherent with CPU mappings). - * - * Tensor: 1 expert x N=256 x K=2048 e4m3 (512 KB), scales bf16 1.0, x = 1.0. - * A = every weight +1.0 (0x38) -> every y = +2048. B = every weight -1.0 (0xB8) -> every y = -2048. - * Camera: a row's 2048 bytes are 16 lines of 128 B; a stale line adds +128 instead of -128, so - * stale_lines(row) = (y + 2048) / 256, exact in f32. Any other y is printed as UNDECODED. - * Modes: - * rewrite upload A, GEMV (GPU reads A), host memcpy B into the SAME buffer + sync_to_gpu, then GEMV x reps. - * realloc upload A, GEMV, free A, upload B (fresh buffer: VA printed, same-VA noted), then GEMV x reps. - * The first GEMV on A must read +2048 on every row: that shows the decode can see A's bytes at all. - * Exit 0 = FRESH, 1 = STALE_READ or API failure, 2 = usage. Red receipt (unfixed platform, omega 710d438c): rewrite - * --cached 1 read 4096 of 4096 lines stale on every launch, 5/5; --cached 0 FRESH 5/5. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -/* Copied verbatim from omega src/omega_gpu_fp8_api.c:20-24 (frozen candidate, not modified). Checked at run time - * against the public omega_gpu_fp8_tensor_entry() VAs; a mismatch aborts. */ -struct OmegaGpuFp8Tensor { - uint32_t experts, n, k; - OmegaGpuMem w; /* experts * n * k e4m3 bytes, row-major */ - OmegaGpuMem s; /* experts * (n/128) * (k/128) f32 (scale * 2^56) */ -}; - -#define N 256u -#define K 2048u - -static int snap(const char *site, const float *y, float expect) { - uint32_t stale_rows = 0, stale_lines = 0, undecoded = 0; float lo = y[0], hi = y[0]; - for (uint32_t r = 0; r < N; r++) { - if (y[r] < lo) lo = y[r]; - if (y[r] > hi) hi = y[r]; - if (expect > 0) { if (y[r] != 2048.0f) undecoded++; continue; } - float s = (y[r] + 2048.0f) / 256.0f; - if (s != (float)(int)s || s < 0 || s > 16) { undecoded++; continue; } - if (s > 0) { stale_rows++; stale_lines += (uint32_t)s; } - } - printf("SNAP site=%s expected=%.0f rows=%u stale_rows=%u stale_lines=%u of %u undecoded=%u y_min=%.1f y_max=%.1f\n", - site, expect, N, stale_rows, stale_lines, N * 16u, undecoded, lo, hi); - if (undecoded) printf("SNAP site=%s y_row0=%.3f interpretation=UNDECODED\n", site, y[0]); - return expect > 0 ? (undecoded ? -1 : 0) : (int)(stale_lines + undecoded); -} - -int main(int argc, char **argv) { - const char *mode = NULL; int cached = -1; uint32_t reps = 3; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--mode") == 0 && i + 1 < argc) mode = argv[++i]; - else if (strcmp(argv[i], "--cached") == 0 && i + 1 < argc) cached = atoi(argv[++i]); - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else { printf("usage: %s --mode rewrite|realloc --cached 0|1 [--reps R]\n", argv[0]); return 2; } - } - if (!mode || (strcmp(mode, "rewrite") && strcmp(mode, "realloc")) || (cached != 0 && cached != 1) || reps == 0 || reps > 64) { - printf("usage: %s --mode rewrite|realloc --cached 0|1 [--reps R]\n", argv[0]); return 2; - } - (void)omega_gpu_session_set_spin_us(2000); - omega_gpu_fp8_set_weight_cache(cached); - printf("RUN mode=%s cached=%d weight_cache_now=%d n=%u k=%u reps=%u\n", mode, cached, omega_gpu_fp8_weight_cache(), N, K, reps); - - uint8_t *wa = malloc((size_t)N * K), *wb = malloc((size_t)N * K); - uint16_t sc[(N / 128) * (K / 128)]; float x[K], y[N]; - memset(wa, 0x38, (size_t)N * K); memset(wb, 0xB8, (size_t)N * K); - for (size_t i = 0; i < sizeof sc / sizeof sc[0]; i++) sc[i] = 0x3F80; - for (uint32_t i = 0; i < K; i++) x[i] = 1.0f; - - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(1, N, K, wa, sc, &t); - if (rc != OMEGA_GPU_FP8_OK) { printf("FAIL upload A: %s\n", omega_gpu_fp8_last_error()); return 1; } - uint64_t wva = 0, sva = 0; - if (omega_gpu_fp8_tensor_entry(t, 0, &wva, &sva) != 0 || wva != t->w.va || sva != t->s.va || !t->w.cpu) { - printf("FAIL mirror struct does not match omega (entry w_va 0x%" PRIx64 " vs mirror 0x%" PRIx64 ")\n", wva, t->w.va); return 1; - } - const uint64_t va_a = t->w.va; - memset(y, 0, sizeof y); - if ((rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL)) != OMEGA_GPU_FP8_OK) { printf("FAIL gemv A: %s\n", omega_gpu_fp8_last_error()); return 1; } - if (snap("gemv-A", y, 2048.0f) != 0) { printf("STALE verdict=INVALID reason=first read of A is not +2048 (decode cannot see A)\n"); return 1; } - - if (strcmp(mode, "rewrite") == 0) { - memcpy(t->w.cpu, wb, (size_t)N * K); /* what omega_gpu_fp8_tensor_upload does, on the same buffer */ - if (omega_gpu_session_sync_to_gpu(&t->w) != 0) { printf("FAIL sync: %s\n", omega_gpu_session_last_error()); return 1; } - printf("HOST rewrote w (va 0x%" PRIx64 ") with B and synced\n", va_a); - } else { - omega_gpu_fp8_tensor_free(t); t = NULL; - if ((rc = omega_gpu_fp8_tensor_upload(1, N, K, wb, sc, &t)) != OMEGA_GPU_FP8_OK) { printf("FAIL upload B: %s\n", omega_gpu_fp8_last_error()); return 1; } - printf("HOST freed A (va 0x%" PRIx64 "), uploaded B at va 0x%" PRIx64 " same_va=%s phys=UNKNOWN reason=no physical address in the API\n", - va_a, t->w.va, t->w.va == va_a ? "yes" : "no"); - } - uint32_t total = 0; - for (uint32_t r = 0; r < reps; r++) { - char site[32]; snprintf(site, sizeof site, "gemv-B-%u", r + 1); - for (uint32_t i = 0; i < N; i++) y[i] = 12345.0f; - if ((rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL)) != OMEGA_GPU_FP8_OK) { printf("FAIL gemv B: %s\n", omega_gpu_fp8_last_error()); return 1; } - total += (uint32_t)snap(site, y, -2048.0f); - } - printf("STALE mode=%s cached=%d stale_or_undecoded_lines_total=%u verdict=%s\n", mode, cached, total, total ? "STALE_READ" : "FRESH"); - omega_gpu_fp8_tensor_free(t); free(wa); free(wb); - return total ? 1 : 0; -} diff --git a/tests/gpu_launch_cost_test.c b/tests/gpu_launch_cost_test.c deleted file mode 100644 index b256b16b2..000000000 --- a/tests/gpu_launch_cost_test.c +++ /dev/null @@ -1,154 +0,0 @@ -/* gpu_launch_cost_test: what does one FP8 GEMV launch cost inside a command list beyond its bytes? (OWN-30B W-L2c, 2026-10-14) - * - * The same weight bytes (n x k e4m3, default 16384 x 2048 = 33.5 MB) are split into m = 1, 2, 4, 8, 16 launches (m tensors of - * n/m rows, independent: distinct rows, distinct y), recorded into ONE command list and timed with the GPU timestamps - * (omega_gpu_cmdlist stamps). T(m) - T(1) over (m - 1) is the per-launch fixed cost with the WAIT_FOR_IDLE barrier between - * launches. Variant (one variable): the same lists with OMEGA_GPU_CMDLIST_BARRIER_NONE (legal here: the launches share no - * data), which tells whether the barrier or the kernel's own ramp/tail is the cost. Every rep checks y bit-identical to the - * session's one-launch-at-a-time result for every tensor (poisoned first). Negative control: a dropped launch (skip_launch) - * must be named by submit. - * Chip only (no host mode): caller holds the GB10 lock. Output: lines "COST m=.. barrier=.. span_us=.. per_launch_us=.. GB/s=.." - * and the fixed-cost lines; --out writes the receipt JSON. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median(uint64_t *v, uint32_t n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -#define MAX_M 16 -typedef struct { OmegaGpuFp8Tensor *t[MAX_M]; float *ref; uint32_t m, rows; } Split; - -static int make_split(Split *s, uint32_t m, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *sc, const float *x) { - memset(s, 0, sizeof *s); - s->m = m; s->rows = n / m; s->ref = malloc((size_t)n * 4); - for (uint32_t i = 0; i < m; i++) { - int rc = omega_gpu_fp8_tensor_upload(1, s->rows, k, w + (size_t)i * s->rows * k, sc + (size_t)i * (s->rows / 128) * (k / 128), &s->t[i]); - if (rc != OMEGA_GPU_FP8_OK) { printf("upload m=%u i=%u: %s (%s)\n", m, i, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return -1; } - rc = omega_gpu_fp8_gemv_f32(s->t[i], 0, x, s->ref + (size_t)i * s->rows, NULL); /* warm-up (kernel cached) + the reference */ - if (rc != OMEGA_GPU_FP8_OK) { printf("reference m=%u i=%u: %s (%s)\n", m, i, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return -1; } - } - return 0; -} -static void free_split(Split *s) { for (uint32_t i = 0; i < s->m; i++) omega_gpu_fp8_tensor_free(s->t[i]); free(s->ref); } - -/* one list of m launches, submitted reps times; medians of the stamp span and of the host-seen elapsed; y checked every rep */ -static int time_split(Split *s, OmegaGpuCmdList *cl, OmegaGpuMem *tab, OmegaGpuMem *xd, OmegaGpuMem *yd, OmegaGpuCmdListBarrier bar, - uint32_t reps, uint64_t *span_med, uint64_t *elapsed_med, uint64_t *first_med, int *identical) { - const uint32_t m = s->m, n = s->rows * m; - uint64_t *spans = malloc(reps * 8), *els = malloc(reps * 8), *firsts = malloc(reps * 8); - uint64_t *tabw = tab->cpu; - for (uint32_t i = 0; i < m; i++) if (omega_gpu_fp8_tensor_entry(s->t[i], 0, &tabw[2 * i], &tabw[2 * i + 1]) != 0) return -1; - if (omega_gpu_session_sync_to_gpu(tab) != 0) return -1; - *identical = 1; - int rc = 0; - for (uint32_t r = 0; r < reps && rc == 0; r++) { - float *y = yd->cpu; for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - if (omega_gpu_session_sync_to_gpu(yd) != 0) { rc = -1; break; } - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - for (uint32_t i = 0; i < m && rc == 0; i++) - if (omega_gpu_fp8_gemv_grouped_record(cl, s->t[i], 1, tab->va + 16u * i, xd->va, 1, yd->va + (uint64_t)i * s->rows * 4u) != 0) { printf("record m=%u i=%u: %s\n", m, i, omega_gpu_fp8_last_error()); rc = -1; } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = bar; o.stamps = 1; - OmegaGpuCmdListStats st; memset(&st, 0, sizeof st); - if (rc == 0 && omega_gpu_cmdlist_submit(cl, &o, &st) != 0) { printf("submit m=%u barrier=%s: %s\n", m, omega_gpu_cmdlist_barrier_name(bar), omega_gpu_session_last_error()); rc = -1; } - uint64_t stamps[MAX_M + 1]; const int none = bar == OMEGA_GPU_CMDLIST_BARRIER_NONE; int cnt = rc == 0 && !none ? omega_gpu_cmdlist_stamps(cl, stamps, MAX_M + 1) : -1; /* barrier none: only the first and last stamp exist, so the GPU span is not readable; elapsed (host wall, ~5 us above span) is the comparable figure */ - omega_gpu_session_unlock(); - if (rc == 0 && !none && cnt != (int)m + 1) { printf("stamps m=%u: %d\n", m, cnt); rc = -1; } - if (rc != 0) break; - els[r] = st.elapsed_ns; spans[r] = none ? 0 : stamps[m] - stamps[0]; firsts[r] = none ? 0 : stamps[1] - stamps[0]; - if (omega_gpu_session_sync_to_cpu(yd) != 0) { rc = -1; break; } - if (memcmp(y, s->ref, (size_t)n * 4) != 0) *identical = 0; - } - if (rc == 0) { *span_med = median(spans, reps); *elapsed_med = median(els, reps); *first_med = median(firsts, reps); } - free(spans); free(els); free(firsts); - return rc; -} - -int main(int argc, char **argv) { - uint32_t reps = 20, n = 16384, k = 2048; const char *out_path = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) n = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) k = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else { printf("usage: %s [--reps N] [--n ROWS] [--k K] [--out receipt.json]\n", argv[0]); return 2; } - } - if (n % (128u * MAX_M) || k % 512u) { printf("n must be a multiple of %u and k of 512\n", 128u * MAX_M); return 2; } - omega_gpu_fp8_set_depth(1, 0); /* one kernel (the step-by-step production kernel) for every split: the row count must not change the kernel */ - (void)omega_gpu_session_set_spin_us(2000); - /* data: random e4m3 bytes without the NaN codes, scales 1.0, x in [-1, 1) */ - uint8_t *w = malloc((size_t)n * k); uint16_t *sc = malloc((size_t)(n / 128) * (k / 128) * 2); float *x = malloc((size_t)k * 4); - uint32_t st = 2026; - for (size_t i = 0; i < (size_t)n * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); w[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(n / 128) * (k / 128); i++) sc[i] = 0x3F80; /* bf16 1.0 */ - for (uint32_t i = 0; i < k; i++) x[i] = (float)(lcg(&st) >> 8) / 16777216.0f * 2.0f - 1.0f; - const uint64_t bytes = (uint64_t)n * k + (uint64_t)(n / 128) * (k / 128) * 4u; - - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(64, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; } - OmegaGpuMem tab, xd, yd; - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc(16u * MAX_M, &tab) | omega_gpu_session_alloc((size_t)k * 4u, &xd) | omega_gpu_session_alloc((size_t)n * 4u, &yd); - omega_gpu_session_unlock(); - if (arc != 0) { printf("alloc: %s\n", omega_gpu_session_last_error()); return 1; } - omega_fp8_pack_x_f32(x, k, xd.cpu); - if (omega_gpu_session_sync_to_gpu(&xd) != 0) return 1; - - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_LAUNCH_COST\",\"n\":%u,\"k\":%u,\"bytes\":%" PRIu64 ",\"reps\":%u,\"points\":[", n, k, bytes, reps); - static const uint32_t ms[] = { 1, 2, 4, 8, 16 }; - double t1[8] = { 0 }; int first_pt = 1; - static const OmegaGpuCmdListBarrier bars[] = { OMEGA_GPU_CMDLIST_BARRIER_WFI, OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY, OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA, OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA, OMEGA_GPU_CMDLIST_BARRIER_NONE, OMEGA_GPU_CMDLIST_BARRIER_WFI }; - for (unsigned bi = 0; bi < sizeof bars / sizeof bars[0]; bi++) { const OmegaGpuCmdListBarrier bar = bars[bi]; const char *bn = omega_gpu_cmdlist_barrier_name(bar); /* WFI first and last: drift control */ - for (size_t mi = 0; mi < sizeof ms / sizeof ms[0]; mi++) { - Split s; - if (make_split(&s, ms[mi], n, k, w, sc, x) != 0) { printf("split m=%u failed\n", ms[mi]); g_failed++; free_split(&s); break; } - uint64_t span = 0, el = 0, first = 0; int identical = 0; - int rc = time_split(&s, cl, &tab, &xd, &yd, bar, reps, &span, &el, &first, &identical); - CHECK(rc == 0 && identical, "m=%u barrier=%s: %u reps ran, y bit-identical to the one-launch-at-a-time reference on every rep", ms[mi], bn, reps); - if (rc == 0) { - double span_us = span / 1e3, el_us = el / 1e3, per = el_us / ms[mi], gbs = (double)bytes / (double)el; /* elapsed-based: comparable across barrier modes */ - if (ms[mi] == 1) t1[bi] = el_us; - double fixed = ms[mi] > 1 ? (el_us - t1[bi]) / (ms[mi] - 1) : 0.0; - printf("COST m=%-2u barrier=%-14s span_us=%.1f per_launch_us=%.1f first_launch_us=%.1f elapsed_us=%.1f GB/s=%.1f fixed_per_extra_launch_us=%.2f\n", - ms[mi], bn, span_us, per, first / 1e3, el / 1e3, gbs, fixed); - if (out) { fprintf(out, "%s{\"m\":%u,\"barrier\":\"%s\",\"span_ns\":%" PRIu64 ",\"first_launch_ns\":%" PRIu64 ",\"elapsed_ns\":%" PRIu64 ",\"gbps\":%.2f,\"fixed_per_extra_launch_us\":%.2f,\"identical\":%d}", - first_pt ? "" : ",", ms[mi], bn, span, first, el, gbs, fixed, identical); first_pt = 0; } - } - free_split(&s); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - } - /* negative control: a dropped launch is named */ - { - Split s; int rc = make_split(&s, 2, n, k, w, sc, x); - if (rc == 0) { - uint64_t *tabw = tab.cpu; for (uint32_t i = 0; i < 2; i++) omega_gpu_fp8_tensor_entry(s.t[i], 0, &tabw[2 * i], &tabw[2 * i + 1]); - omega_gpu_session_sync_to_gpu(&tab); - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - for (uint32_t i = 0; i < 2; i++) omega_gpu_fp8_gemv_grouped_record(cl, s.t[i], 1, tab.va + 16u * i, xd.va, 1, yd.va + (uint64_t)i * s.rows * 4u); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI; o.skip_launch = 2; - OmegaGpuCmdListStats st2; memset(&st2, 0, sizeof st2); - int src = omega_gpu_cmdlist_submit(cl, &o, &st2); - omega_gpu_session_unlock(); - CHECK(src != 0 && st2.first_missing == 1, "negative control: dropped launch 1 named by submit (rc %d, first_missing %d)", src, st2.first_missing); - } else g_failed++; - free_split(&s); - } - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - omega_gpu_session_lock(); omega_gpu_session_free(&tab); omega_gpu_session_free(&xd); omega_gpu_session_free(&yd); omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - omega_gpu_session_close(); - printf("gpu_launch_cost_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_lmhead_fp8_study.c b/tests/gpu_lmhead_fp8_study.c deleted file mode 100644 index 6dd0aa8de..000000000 --- a/tests/gpu_lmhead_fp8_study.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - * gpu_lmhead_fp8_study: report-only study (OWN-30B, 2026-10-13). Does an FP8-quantised lm_head pick the same next token - * as the bf16 lm_head? Loads the real lm_head.weight (bf16 [151936][2048]) and model.norm.weight from the checkpoint - * dir, quantises the weight to e4m3 in 128x128 blocks (scale = amax / 448, rounded to bf16, the checkpoint's - * weight_scale_inv convention; round-to-nearest-even into e4m3, saturating), then runs both GEMVs on the chip - * (bf16 streaming kernel and the FP8 kernel) on N random hidden states and compares the argmax. Nothing is switched. - * usage: gpu_lmhead_fp8_study MODEL_DIR [--states N] [--seed S] [--out report.txt] - */ -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include -#include - -#define V 151936u -#define H 2048u -#define DATA0 89616ull /* 8 + header length of shard 4 */ -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float urand(uint32_t *s) { return (float)(lcg(s) >> 8) / 16777216.0f; } -static float gauss(uint32_t *s) { float a = 0; for (int i = 0; i < 12; i++) a += urand(s); return a - 6.0f; } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* positive e4m3 values by code 0..126 (127 is NaN): increasing */ -static float pos[127]; -static uint8_t enc_e4m3(float v) { /* nearest, ties to the even code, saturating at 448 */ - uint8_t sign = v < 0 ? 0x80 : 0; float a = fabsf(v); - int lo = 0, hi = 126; - if (a >= pos[126]) return sign | 126; - while (hi - lo > 1) { int m = (lo + hi) / 2; if (pos[m] <= a) lo = m; else hi = m; } - float dl = a - pos[lo], dh = pos[hi] - a; - int c = dl < dh ? lo : dh < dl ? hi : ((lo & 1) ? hi : lo); - return sign | (uint8_t)c; -} - -int main(int argc, char **argv) { - if (argc < 2) { printf("usage: %s MODEL_DIR [--states N] [--seed S] [--out file]\n", argv[0]); return 2; } - uint32_t states = 1000, seed = 20261013; const char *out_path = NULL; - for (int i = 2; i < argc; i++) { - if (!strcmp(argv[i], "--states") && i + 1 < argc) states = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--seed") && i + 1 < argc) seed = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i]; - } - for (int c = 0; c < 127; c++) { int e = c >> 3, m = c & 7; pos[c] = e == 0 ? (float)m * (1.0f / 512.0f) : ldexpf(1.0f + m / 8.0f, e - 7); } - char path[600]; snprintf(path, sizeof path, "%s/model-00004-of-00004.safetensors", argv[1]); - FILE *f = fopen(path, "rb"); if (!f) { printf("cannot open %s\n", path); return 1; } - uint16_t *w = malloc((size_t)V * H * 2), nw[H]; - fseeko(f, (off_t)DATA0, SEEK_SET); - if (fread(w, 2, (size_t)V * H, f) != (size_t)V * H) { printf("short read lm_head\n"); return 1; } - fseeko(f, (off_t)(DATA0 + 622405248ull), SEEK_SET); - if (fread(nw, 2, H, f) != H) { printf("short read norm\n"); return 1; } - fclose(f); - /* quantise */ - uint8_t *q = malloc((size_t)V * H); uint16_t *sc = malloc((size_t)(V / 128) * (H / 128) * 2); - double sq_err = 0, sq_w = 0; - for (uint32_t bi = 0; bi < V / 128; bi++) for (uint32_t bj = 0; bj < H / 128; bj++) { - float amax = 0; - for (uint32_t r = 0; r < 128; r++) for (uint32_t c = 0; c < 128; c++) { float a = fabsf(bf16_f32(w[(size_t)(bi * 128 + r) * H + bj * 128 + c])); if (a > amax) amax = a; } - uint16_t sb = bf16_rne(amax > 0 ? amax / 448.0f : 1.0f); float s = bf16_f32(sb); - sc[bi * (H / 128) + bj] = sb; - for (uint32_t r = 0; r < 128; r++) for (uint32_t c = 0; c < 128; c++) { - size_t idx = (size_t)(bi * 128 + r) * H + bj * 128 + c; float wv = bf16_f32(w[idx]); - uint8_t e = enc_e4m3(wv / s); q[idx] = e; - float d = (e & 0x80 ? -1.0f : 1.0f) * pos[e & 0x7f] * s; sq_err += (double)(d - wv) * (d - wv); sq_w += (double)wv * wv; - } - } - printf("quantised lm_head: weight rms error %.4f of weight rms (block-scaled e4m3)\n", sqrt(sq_err / sq_w)); - OmegaGpuBf16Tensor *tb = NULL; OmegaGpuFp8Tensor *tf = NULL; - int r1 = omega_gpu_bf16_tensor_upload(V, H, w, &tb), r2 = omega_gpu_fp8_tensor_upload(1, V, H, q, sc, &tf); - printf("uploads: bf16 %s, fp8 %s\n", omega_gpu_bf16_rc_name(r1), omega_gpu_fp8_rc_name(r2)); - if (r1 || r2) return 1; - (void)omega_gpu_session_set_spin_us(2000); - float *x = malloc(H * 4), *yb = malloc(V * 4), *yf = malloc(V * 4); - uint32_t s = seed, agree = 0, top5_in = 0, fails = 0; - uint64_t *tb_ns = malloc(states * 8), *tf_ns = malloc(states * 8); - double maxrel = 0; - uint32_t bucket[4] = { 0, 0, 0, 0 }, bucket_dis[4] = { 0, 0, 0, 0 }; /* margin <0.05, <0.2, <1, >=1 (bf16 logit gap top1-top2) */ - for (uint32_t it = 0; it < states; it++) { - for (uint32_t i = 0; i < H; i++) x[i] = gauss(&s) * bf16_f32(nw[i]); - OmegaGpuBf16Info ib; OmegaGpuFp8Info jf; - if (omega_gpu_bf16_gemv_f32(tb, x, yb, &ib) || omega_gpu_fp8_gemv_f32(tf, 0, x, yf, &jf)) { fails++; printf("state %u: chip call failed (%s)\n", it, omega_gpu_bf16_last_error()); break; } - tb_ns[it] = ib.elapsed_ns; tf_ns[it] = jf.elapsed_ns; - uint32_t ab = 0, af = 0; float m2 = -1e30f; - for (uint32_t v = 1; v < V; v++) { if (yb[v] > yb[ab]) ab = v; if (yf[v] > yf[af]) af = v; } - for (uint32_t v = 0; v < V; v++) if (v != ab && yb[v] > m2) m2 = yb[v]; - double margin = yb[ab] - m2; - int ok = ab == af; agree += ok; - /* is the bf16 argmax inside the fp8 top 5? */ - uint32_t better = 0; for (uint32_t v = 0; v < V; v++) if (yf[v] > yf[ab]) better++; - top5_in += better < 5; - int b = margin < 0.05 ? 0 : margin < 0.2 ? 1 : margin < 1.0 ? 2 : 3; bucket[b]++; if (!ok) { bucket_dis[b]++; } - double num = 0, den = 0; for (uint32_t v = 0; v < V; v++) { double d = (double)yf[v] - yb[v]; num += d * d; den += (double)yb[v] * yb[v]; } - double rel = sqrt(num / den); if (rel > maxrel) maxrel = rel; - if (it == 0) printf("state 0: bf16 argmax %u (%.3f), fp8 argmax %u (%.3f), margin %.4f, logit rms rel diff %.4f\n", ab, yb[ab], af, yf[af], margin, rel); - } - uint32_t n = states - fails; - qsort(tb_ns, n, 8, cmp_u64); qsort(tf_ns, n, 8, cmp_u64); - char rep[2000]; - snprintf(rep, sizeof rep, - "lm_head fp8 vs bf16 argmax study (real lm_head.weight, %u random hidden states = gaussian x model.norm.weight, seed %u)\n" - "argmax agreement: %u of %u (%.2f%%); bf16 argmax within fp8 top-5: %u of %u\n" - "logit rms relative difference, worst over states: %.4f\n" - "agreement by bf16 top1-top2 logit gap: <0.05: %u/%u disagree, <0.2: %u/%u, <1: %u/%u, >=1: %u/%u\n" - "chip medians: bf16 kernel %.1f us, fp8 kernel %.1f us\n", - n, seed, agree, n, 100.0 * agree / (n ? n : 1), top5_in, n, maxrel, - bucket_dis[0], bucket[0], bucket_dis[1], bucket[1], bucket_dis[2], bucket[2], bucket_dis[3], bucket[3], - n ? tb_ns[n / 2] / 1e3 : 0.0, n ? tf_ns[n / 2] / 1e3 : 0.0); - printf("%s", rep); - if (out_path) { FILE *o = fopen(out_path, "w"); if (o) { fputs(rep, o); fclose(o); } } - omega_gpu_bf16_tensor_free(tb); omega_gpu_fp8_tensor_free(tf); - omega_gpu_session_close(); - return fails ? 1 : 0; -} diff --git a/tests/gpu_matmul_api_test.c b/tests/gpu_matmul_api_test.c deleted file mode 100644 index 2f89808a5..000000000 --- a/tests/gpu_matmul_api_test.c +++ /dev/null @@ -1,692 +0,0 @@ -/* gpu_matmul_api_test: FB-1 cut 1 / 1b gate for omega_gpu_matmul_api. - * - * ./gpu_matmul_api_test --host-only argument and limit refusals, codegen only, no chip - * ./gpu_matmul_api_test --out receipt.json chip sweep over shapes, JSON receipt - * ./gpu_matmul_api_test --timing --out r.json resident GEMV timing (median of 100 calls) + parity - * ./gpu_matmul_api_test --update --out r.json tensor_update_* in place vs a fresh upload, and its timing (R3) - * ./gpu_matmul_api_test --mutant --out r.json wrong kernel (last K step dropped) must FAIL parity; - * exit 0 when every shape caught it ("mutant killed") - * ./gpu_matmul_api_test --cta-budget N ... run with a different CTA budget (I42 experiment) - * ./gpu_matmul_api_test --spin-us N ... marker-wait spin window for every launch (omega#328) - * ./gpu_matmul_api_test --unroll N ... force the fragment kernel unroll (omega #328 experiment) - * ./gpu_matmul_api_test --stages --out r.json omega #473 stage profile (resident, bf16 and f32 rows, median of 7) - * - * Shapes come from OMEGA_GPU_MATMUL_SHAPES ("m,k,n;m,k,n;..."), default below. - * Pass rule per shape: rc OK, parity verified by the API oracle, end-to-end error < 1e-5 relative to - * the accumulation scale (bf16 inputs against a double reference; only accumulation order and the - * chip's f32 accumulator differ), second call hits the kernel cache and agrees bit for bit. - */ -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include -#include -#include -#include - -/* round a float to bf16 and back, as the API does on the way in */ -static float bf16r(float f) { uint16_t h = omega_fp32_to_bf16(f); uint32_t u = (uint32_t)h << 16; float o; memcpy(&o, &u, 4); return o; } - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -/* cut-1 list unchanged, then the cut-1b Llama shapes (hidden 2048, ffn 8192, vocab 128256) */ -static const char *DEFAULT_SHAPES = - "16,16,16;32,32,32;64,64,64;128,128,128;256,256,256;512,512,512;" - "1,1024,1024;1,256,1024;16,1024,256;8,1024,8;" - "1024,16,128;192,16,192;512,16,64;256,16,256;128,16,512;" - "1,2048,8192;1,8192,2048;1,2048,128256"; -static const char *MUTANT_SHAPES = "16,32,16;1,2048,8192;64,64,64;1,1024,1024"; -static const char *TIMING_SHAPES = "1,2048,8192;1,8192,2048"; -/* omega #473 training shapes */ -static const char *STAGE_SHAPES = "8192,768,2304;8192,768,768;8192,768,3072;8192,3072,768;1024,768,50304"; - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } - -static void fill(float *a, size_t n, uint32_t *seed) { for (size_t i = 0; i < n; i++) a[i] = ((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f; } - -/* end-to-end: full-K product on the host from the same bf16-rounded inputs, in double; error relative - * to the accumulation scale (sum of |terms|), not to a result that may cancel to near zero */ -static double e2e_max_rel(uint32_t m, uint32_t k, uint32_t n, const float *a, const float *b, const float *c, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - for (size_t i = 0; i < m; i++) for (size_t j = 0; j < n; j++) { - double acc = 0.0, scale = 0.0; - for (size_t t = 0; t < k; t++) { double p = (double)bf16r(a[i * k + t]) * (double)bf16r(b[t * n + j]); acc += p; scale += fabs(p); } - double rel = fabs(acc - (double)c[i * n + j]) / (scale > 1e-6 ? scale : 1e-6); - if (rel > worst) worst = rel; - if (rel >= 1e-5) nbad++; - } - if (bad) *bad = nbad; - return worst; -} - -/* omega #328 fragment-major kernel, host only. The unpack below is written from the PTX ISA - * table for mma.m16n8k16 (.bf16 A: a0,a1 row g cols 2t,2t+1; a2,a3 row g+8; a4,a5 row g cols - * 2t+8,2t+9; a6,a7 row g+8. B: b0,b1 rows 2t,2t+1 col g; b2,b3 rows 2t+8,2t+9; g = lane>>2, - * t = lane&3), independently of the packers: pack then unpack must give the matrix back. */ -/* Result sentinels: one poison word per 16 x 8 fragment tile that holds a real output word, inside the - * tile's real rows and columns; the scan counts exactly the survivors. */ -static void sentinel_host_checks(void) { - static const uint32_t shapes[][2] = { { 1u, 24576u }, { 1u, 4096u }, { 16u, 151936u }, { 128u, 24576u }, { 116u, 4096u }, { 3u, 20u }, { 17u, 9u } }; - const float poison = -999.0f; - for (size_t s = 0; s < sizeof shapes / sizeof shapes[0]; s++) { - const uint32_t m = shapes[s][0], n = shapes[s][1], mp = (m + 15u) / 16u * 16u, np = (n + 7u) / 8u * 8u; - const uint32_t mt = (m + 15u) / 16u, nt = (n + 7u) / 8u; - float *cd = calloc((size_t)mp * np, sizeof *cd); - const size_t set = omega_matmul_result_sentinels(cd, m, n, np, poison, 1); - CHECK(set == (size_t)mt * nt, "sentinel count m=%u n=%u: %zu != %u", m, n, set, mt * nt); - /* every fragment tile with a real word holds exactly one sentinel, inside its real rows and columns */ - size_t tiles_ok = 0, outside = 0; - for (uint32_t ti = 0; ti < mt; ti++) - for (uint32_t tj = 0; tj < nt; tj++) { - size_t in_tile = 0; - for (uint32_t r = ti * 16u; r < ti * 16u + 16u; r++) - for (uint32_t c = tj * 8u; c < tj * 8u + 8u; c++) - if (cd[(size_t)r * np + c] == poison) { if (r < m && c < n) in_tile++; else outside++; } - if (in_tile == 1) tiles_ok++; - } - CHECK(tiles_ok == (size_t)mt * nt && outside == 0, "sentinel placement m=%u n=%u: %zu tiles ok, %zu outside", m, n, tiles_ok, outside); - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == set, "sentinel scan m=%u n=%u: all survive", m, n); - /* clearing one tile's sentinel removes exactly one survivor; a fully written result has none */ - cd[(size_t)(m - 1u) * np + (n - 1u)] = 0.0f; - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == set - 1u, "sentinel scan m=%u n=%u: one cleared", m, n); - for (size_t i = 0; i < (size_t)mp * np; i++) cd[i] = 1.5f; - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == 0, "sentinel scan m=%u n=%u: none survive", m, n); - free(cd); - } -} - -static void frag_host_checks(void) { - sentinel_host_checks(); - /* row-0 pack (one-row decode call): a full one-row pack of A2 equals a full pack of A1 followed by the - * row-0 pack of A2, bf16 and f32 inputs, including a width with padding columns */ - { - const uint32_t ks[] = { 4096u, 40u }; - for (size_t i = 0; i < 2; i++) { - const uint32_t k = ks[i], kp = (k + 15u) / 16u * 16u; - float *a1 = malloc(k * sizeof *a1), *a2 = malloc(k * sizeof *a2); - uint16_t *b1 = malloc(k * 2), *b2 = malloc(k * 2), *full = malloc((size_t)16 * kp * 2), *inc = malloc((size_t)16 * kp * 2); - uint32_t seed = 77u + k; - fill(a1, k, &seed); fill(a2, k, &seed); - for (uint32_t j = 0; j < k; j++) { b1[j] = omega_fp32_to_bf16(a1[j]); b2[j] = omega_fp32_to_bf16(a2[j]); } - omega_matmul_frag_pack_a(b2, 1, k, 16, kp, full); - omega_matmul_frag_pack_a(b1, 1, k, 16, kp, inc); - omega_matmul_frag_pack_a_row0(b2, k, kp, inc); - CHECK(memcmp(full, inc, (size_t)16 * kp * 2) == 0, "row-0 pack bf16 k=%u equals the full one-row pack", k); - omega_matmul_frag_pack_a_f32(a1, 1, k, 16, kp, inc); - omega_matmul_frag_pack_a_row0_f32(a2, k, kp, inc); - CHECK(memcmp(full, inc, (size_t)16 * kp * 2) == 0, "row-0 pack f32 k=%u equals the full one-row pack", k); - free(a1); free(a2); free(b1); free(b2); free(full); free(inc); - } - } - CHECK(omega_blackwell_verify_codegen_fixtures_fragmm() == 0, "fragment matmul golden words (rc %d)", omega_blackwell_verify_codegen_fixtures_fragmm()); - struct { uint32_t m, k, n; } sh[] = { {1, 16, 8}, {1, 40, 13}, {17, 48, 24}, {33, 2560, 72}, {5, 160, 1000} }; - for (size_t s = 0; s < sizeof sh / sizeof sh[0]; s++) { - const uint32_t m = sh[s].m, k = sh[s].k, n = sh[s].n; - const uint32_t mp = (m + 15) / 16 * 16, kp = (k + 15) / 16 * 16, np = (n + 7) / 8 * 8, KS = kp / 16, NT = np / 8; - uint16_t *a = malloc((size_t)m * k * 2), *b = malloc((size_t)k * n * 2); - uint16_t *pa = malloc((size_t)mp * kp * 2), *pb = malloc((size_t)kp * np * 2); - uint32_t seed = 7 + (uint32_t)s; - for (size_t i = 0; i < (size_t)m * k; i++) a[i] = (uint16_t)(1 + lcg(&seed) % 60000); - for (size_t i = 0; i < (size_t)k * n; i++) b[i] = (uint16_t)(1 + lcg(&seed) % 60000); - omega_matmul_frag_pack_a(a, m, k, mp, kp, pa); - /* B in two uneven chunks, as the upload does in FRAG_PACK_TILES steps */ - uint32_t split = NT / 2; - omega_matmul_frag_pack_b(b, k, n, kp, 0, split, pb); - omega_matmul_frag_pack_b(b, k, n, kp, split, NT, pb + (size_t)split * kp * 8); - size_t bad_a = 0, bad_b = 0; - for (uint32_t mt = 0; mt < mp / 16; mt++) - for (uint32_t ks = 0; ks < KS; ks++) - for (uint32_t lane = 0; lane < 32; lane++) { - const uint32_t gg = lane >> 2, t = lane & 3; - const uint32_t rows[8] = { gg, gg, gg + 8, gg + 8, gg, gg, gg + 8, gg + 8 }; - const uint32_t cols[8] = { 2 * t, 2 * t + 1, 2 * t, 2 * t + 1, 2 * t + 8, 2 * t + 9, 2 * t + 8, 2 * t + 9 }; - for (int e = 0; e < 8; e++) { - uint32_t r = mt * 16 + rows[e], c = ks * 16 + cols[e]; - uint16_t want = (r < m && c < k) ? a[(size_t)r * k + c] : 0; - if (pa[(((size_t)mt * KS + ks) * 32 + lane) * 8 + e] != want) bad_a++; - } - } - for (uint32_t nt = 0; nt < NT; nt++) - for (uint32_t ks = 0; ks < KS; ks++) - for (uint32_t lane = 0; lane < 32; lane++) { - const uint32_t gg = lane >> 2, t = lane & 3; - const uint32_t rows[4] = { 2 * t, 2 * t + 1, 2 * t + 8, 2 * t + 9 }; - for (int e = 0; e < 4; e++) { - uint32_t r = ks * 16 + rows[e], c = nt * 8 + gg; - uint16_t want = (r < k && c < n) ? b[(size_t)r * n + c] : 0; - if (pb[(((size_t)nt * KS + ks) * 32 + lane) * 4 + e] != want) bad_b++; - } - } - CHECK(bad_a == 0 && bad_b == 0, "fragment pack round trip %ux%ux%u (A bad %zu, B bad %zu)", m, k, n, bad_a, bad_b); - /* the fused f32 packer equals convert-then-pack bit for bit (ties, denormals, inf, NaN included) */ - float *af = malloc((size_t)m * k * sizeof *af); - uint16_t *pf = malloc((size_t)mp * kp * 2); - for (size_t i = 0; i < (size_t)m * k; i++) { - uint32_t bits = lcg(&seed) * 2654435761u; - switch (i % 7) { - case 0: bits = (bits & 0x807fffffu) | 0x3f800000u; break; /* in [1,2) with every mantissa bit live (rounding ties) */ - case 1: bits = 0x7f800000u | ((bits >> 9) & 0x7fffffu); break; /* inf (0 payload) or NaN payloads */ - case 2: bits &= 0x807fffffu; break; /* zero and denormals */ - default: break; - } - memcpy(&af[i], &bits, 4); - a[i] = omega_fp32_to_bf16(af[i]); - } - omega_matmul_frag_pack_a(a, m, k, mp, kp, pa); - omega_matmul_frag_pack_a_f32(af, m, k, mp, kp, pf); - CHECK(memcmp(pa, pf, (size_t)mp * kp * 2) == 0, "fused f32 pack equals convert-then-pack %ux%u", m, k); - free(af); free(pf); - free(a); free(b); free(pa); free(pb); - } - /* the kernel generates for every padded Qwen3-4B and Llama-3.2-1B decode shape at the API's unroll */ - struct { uint32_t k, n, gx; } ok[] = { {16, 8, 1}, {2560, 4096, 256}, {2560, 1024, 128}, {4096, 2560, 256}, {2560, 9728, 256}, - {9728, 2560, 256}, {2560, 151936, 256}, {2048, 8192, 64}, {8192, 2048, 64}, - {2048, 128256, 64}, {16384, 262144, 64}, {48, 16, 2} }; - for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - const uint32_t u = omega_matmul_frag_unroll(ok[i].k); - int rc = omega_matmul_spec_init(&spec, 16, ok[i].k, ok[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&spec, ok[i].gx, u, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "fragment kernel K=%u N=%u gx=%u unroll=%u generated", ok[i].k, ok[i].n, ok[i].gx, u); - CHECK(kernel.gpr_count <= 64, "fragment kernel K=%u N=%u unroll=%u fits 64 registers (got %u)", ok[i].k, ok[i].n, u, kernel.gpr_count); - if (i == 1) printf("fragment kernel K=2560 N=4096 unroll %u: %zu instructions, %u registers\n", u, kernel.insn_count, kernel.gpr_count); - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_frag(&spec, ok[i].gx, u, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "fragment mutant differs K=%u N=%u", ok[i].k, ok[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(ok[i].k / 16 / u < 2, "fragment mutant refused only with one pass (K=%u)", ok[i].k); - omega_blackwell_kernel_free(&kernel); - } - CHECK(omega_matmul_frag_unroll(2560) == 4 && omega_matmul_frag_unroll(48) == 1 && omega_matmul_frag_unroll(64) == 4 && - omega_matmul_frag_unroll(32) == 2 && omega_matmul_frag_unroll(128) == 4, "unroll choice (capped at 4)"); - { /* unroll 8 still generates (experiments) */ - OmegaMatMulSpec s8; OmegaBlackwellKernel k8; memset(&k8, 0, sizeof k8); - CHECK(omega_matmul_spec_init(&s8, 16, 2560, 4096, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&s8, 256, 8, 0, &k8) == 0 && k8.code_size > 0, "unroll 8 generates"); - omega_blackwell_kernel_free(&k8); - } - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 48, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&spec, 1, 2, 0, &kernel) != 0, "unroll not dividing K/16 refused"); - CHECK(omega_blackwell_codegen_matmul_frag(&spec, 1, 3, 0, &kernel) != 0, "unroll 3 refused"); - CHECK(omega_blackwell_codegen_matmul_frag(&spec, 3, 1, 0, &kernel) != 0, "fragment grid_x beyond the column tiles refused"); - /* 2026-10-12: the blocked kernel (rt row tiles x ct column tiles per warp) generates for the Qwen3-8B - * prefill shapes at m = 128 (rt 4, ct 4, grid_x 512 at the daemon's 1024-CTA budget) and the small - * parity shapes; it fits the allocator's 128 registers; its mutant differs; the envelope is enforced */ - struct { uint32_t k, n, gx, rt, ct; } bk[] = { {4096, 24576, 512, 4, 4}, {12288, 4096, 128, 4, 4}, {4096, 6144, 192, 4, 4}, - {128, 128, 4, 4, 4}, {32, 32, 1, 2, 4}, {16, 8, 1, 2, 1}, {1024, 8, 1, 4, 1}, - {64, 64, 2, 4, 2}, {48, 16, 1, 2, 2} }; - for (size_t i = 0; i < sizeof bk / sizeof bk[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - const uint32_t u = omega_matmul_frag_block_unroll(bk[i].k, bk[i].rt, bk[i].ct); - int rc = omega_matmul_spec_init(&spec, 16, bk[i].k, bk[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag_block(&spec, bk[i].gx, u, bk[i].rt, bk[i].ct, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "blocked kernel K=%u N=%u gx=%u rt=%u ct=%u unroll=%u generated", bk[i].k, bk[i].n, bk[i].gx, bk[i].rt, bk[i].ct, u); - CHECK(u * (bk[i].rt + bk[i].ct) <= 8, "blocked kernel K=%u rt=%u ct=%u issues at most 8 loads per pass (unroll %u)", bk[i].k, bk[i].rt, bk[i].ct, u); - if (i < 3) printf("blocked kernel K=%u N=%u rt=%u ct=%u unroll %u: %zu instructions, %u registers\n", bk[i].k, bk[i].n, bk[i].rt, bk[i].ct, u, kernel.insn_count, kernel.gpr_count); - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_frag_block(&spec, bk[i].gx, u, bk[i].rt, bk[i].ct, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "blocked mutant differs K=%u N=%u", bk[i].k, bk[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(bk[i].k / 16 / u < 2, "blocked mutant refused only with one pass (K=%u)", bk[i].k); - omega_blackwell_kernel_free(&kernel); - } - { - uint32_t rt, ct; - omega_matmul_frag_block_shape(8, 3072, &rt, &ct); CHECK(rt == 4 && ct == 4, "block shape m=128 n=24576 is 4x4"); - omega_matmul_frag_block_shape(1, 3072, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape m=1 is the single-tile kernel"); - omega_matmul_frag_block_shape(7, 3072, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape m=112 (7 row tiles) is the single-tile kernel"); - omega_matmul_frag_block_shape(6, 6, &rt, &ct); CHECK(rt == 2 && ct == 2, "block shape 6 row tiles, 6 column tiles is 2x2"); - omega_matmul_frag_block_shape(4, 1, &rt, &ct); CHECK(rt == 4 && ct == 1, "block shape 4 row tiles, 1 column tile is 4x1"); - /* the C store offset of the last row tile is a signed 24-bit immediate: wide N steps rt down (lm_head: to 1) */ - omega_matmul_frag_block_shape(2, 18992, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape lm_head (N 151936) at 2 row tiles is the single-tile kernel: %ux%u", rt, ct); - omega_matmul_frag_block_shape(8, 18992, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape lm_head (N 151936) at 8 row tiles is the single-tile kernel: %ux%u", rt, ct); - omega_matmul_frag_block_shape(8, 8192, &rt, &ct); CHECK(rt == 2 && ct == 4, "block shape N 65536 at 8 row tiles steps rt 4 -> 2: %ux%u", rt, ct); - CHECK(omega_matmul_frag_block_unroll(4096, 4, 4) == 1 && omega_matmul_frag_block_unroll(4096, 2, 2) == 2 && - omega_matmul_frag_block_unroll(48, 2, 2) == 1 && omega_matmul_frag_block_unroll(4096, 4, 2) == 1, "blocked unroll rule (loads per pass <= 8)"); - OmegaMatMulSpec s; OmegaBlackwellKernel kk; memset(&kk, 0, sizeof kk); - CHECK(omega_matmul_spec_init(&s, 16, 4096, 6144, OMEGA_MATMUL_PRECISION_BF16) == 0, "spec for refusals"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 1, 1, 0, &kk) != 0, "blocked 1x1 refused (single-tile kernel)"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 3, 2, 0, &kk) != 0, "blocked rt 3 refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 8, 4, 0, &kk) != 0, "blocked 8x4 (32 accumulators) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 8, 1, 0, &kk) != 0, "blocked 8x1 (9 loads per pass) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 2, 4, 4, 0, &kk) != 0, "blocked unroll 2 at 4x4 (16 loads per pass) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 4, 2, 2, 0, &kk) != 0, "blocked unroll 4 refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 193, 1, 4, 4, 0, &kk) != 0, "blocked grid_x beyond the column blocks refused"); - OmegaMatMulSpec s3; CHECK(omega_matmul_spec_init(&s3, 16, 64, 24, OMEGA_MATMUL_PRECISION_BF16) == 0, "spec n=24"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s3, 1, 1, 2, 4, 0, &kk) != 0, "blocked ct not dividing the column tiles refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s3, 1, 1, 2, 2, 0, &kk) != 0, "blocked ct 2 on 3 column tiles refused"); - } -} - -static void host_only(void) { - float a[16 * 16] = {0}, b[16 * 16] = {0}, c[16 * 16] = {0}; - OmegaGpuMatmulInfo info; - CHECK(omega_gpu_matmul_f32(0, 16, 16, a, b, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "m=0 refused"); - CHECK(omega_gpu_matmul_f32(16, 16, 16, NULL, b, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "NULL a refused"); - CHECK(omega_gpu_matmul_f32(OMEGA_BW_MATMUL_MAX_M + 1, 16, 16, a, b, c, &info) == OMEGA_GPU_MATMUL_TOO_LARGE, "m over limit refused"); - CHECK(omega_gpu_matmul_bf16(16, OMEGA_BW_MATMUL_MAX_K + 1, 16, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "k over limit refused (NULL info ok)"); - /* session spin window (omega#328): in-range value kept, out-of-range refused unchanged, 0 restores */ - const uint32_t spin0 = omega_gpu_session_spin_us(); - CHECK(omega_gpu_session_set_spin_us(2000) == 0 && omega_gpu_session_spin_us() == 2000, "spin window 2000 us set"); - CHECK(omega_gpu_session_set_spin_us(OMEGA_GPU_SESSION_MAX_SPIN_US + 1) == -1 && omega_gpu_session_spin_us() == 2000, - "spin window over the maximum refused, setting unchanged"); - CHECK(omega_gpu_session_set_spin_us(0) == 0 && omega_gpu_session_spin_us() == 0, "spin window 0 restores the sleep-poll"); - omega_gpu_session_set_spin_us(spin0); - CHECK(omega_gpu_matmul_bf16(16, 16, OMEGA_BW_MATMUL_MAX_N + 1, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "n over limit refused"); - CHECK(OMEGA_BW_MATMUL_MAX_N >= 128256 && OMEGA_BW_MATMUL_MAX_K >= 8192 && OMEGA_BW_MATMUL_MAX_M >= 2048, "limits cover Llama shapes (vocab 128256, ffn 8192)"); - OmegaGpuTensor *t = NULL; - CHECK(omega_gpu_tensor_upload_f32(0, 16, a, &t) == OMEGA_GPU_MATMUL_BAD_ARGS && t == NULL, "tensor k=0 refused"); - CHECK(omega_gpu_tensor_upload_f32(16, 16, NULL, &t) == OMEGA_GPU_MATMUL_BAD_ARGS, "tensor NULL refused"); - CHECK(omega_gpu_matmul_resident_f32(16, a, NULL, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "resident NULL tensor refused"); - CHECK(omega_gpu_tensor_update_f32(NULL, 16, 16, a) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL tensor refused"); - CHECK(omega_gpu_tensor_update_bf16(NULL, 16, 16, (const uint16_t *)a) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL tensor refused"); - CHECK(strcmp(omega_gpu_matmul_rc_name(OMEGA_GPU_MATMUL_PARITY_FAIL), "PARITY_FAIL") == 0, "rc name"); - CHECK(omega_gpu_matmul_cta_budget() == OMEGA_GPU_MATMUL_MAX_CTAS, "default CTA budget"); - { - OmegaGpuMatmulStages s0; - memset(&s0, 0xff, sizeof s0); - omega_gpu_matmul_last_stages(&s0); - omega_gpu_matmul_last_stages(NULL); - CHECK(s0.core_ns == 0 && s0.launch_ns == 0 && s0.pack_ns == 0, "stages all zero before the first matmul"); - } - /* omega #473 R4: the default is the best budget of the sealed receipt evidence/R4-MATMUL-CTA-ffc3176a (every element of - * every call at the five training shapes and two single-tile shapes, budgets 64..1024, all sealed; 1024 fastest) */ - CHECK(OMEGA_GPU_MATMUL_MAX_CTAS == 1024u, "default CTA budget is the R4 sealed budget 1024 (got %u)", (unsigned)OMEGA_GPU_MATMUL_MAX_CTAS); - CHECK(omega_gpu_matmul_is_blocked() == 0, "not blocked at start"); - - /* codegen only: the looped kernel must accept every padded Llama shape without touching the chip */ - struct { uint32_t k, n, gx; } ok[] = { {16, 8, 1}, {2048, 8192, 64}, {8192, 2048, 64}, {2048, 128256, 64}, {1024, 1024, 1}, {16384, 262144, 64} }; - for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - int rc = omega_matmul_spec_init(&spec, 16, ok[i].k, ok[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "loop kernel K=%u N=%u gx=%u generated", ok[i].k, ok[i].n, ok[i].gx); - CHECK(kernel.gpr_count <= 64, "loop kernel K=%u N=%u fits 64 registers (got %u)", ok[i].k, ok[i].n, kernel.gpr_count); - /* the mutant kernel is a different program */ - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "mutant kernel differs K=%u N=%u", ok[i].k, ok[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(ok[i].k == 16, "mutant refused only for K=16 (K=%u)", ok[i].k); - omega_blackwell_kernel_free(&kernel); - } - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 24, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 1, 0, &kernel) != 0, "K not multiple of 16 refused by codegen (the API pads)"); - CHECK(omega_matmul_spec_init(&spec, 16, 16, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 3, 0, &kernel) != 0, "grid_x beyond the column tiles refused"); - /* the single-tile kernel of cut 1 still generates (other gates use it) */ - memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 16, 8, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul(&spec, &kernel) == 0 && kernel.code_size > 0, "16x16x8 single-tile kernel generated"); - omega_blackwell_kernel_free(&kernel); - frag_host_checks(); - omega_gpu_matmul_cache_clear(); -} - -/* One-row calls reuse the zero padding rows of the activation buffer: a second one-row call of the same - * width writes row 0 only (hook counts it) and still matches the oracle with a different A; a wider - * call in between, or another width, forces a full pack again. */ -static void one_row_repack_checks(void) { - const uint32_t k = 4096, n = 256; - float *a = malloc((size_t)32 * k * sizeof *a), *b = malloc((size_t)k * n * sizeof *b), *c = malloc((size_t)32 * n * sizeof *c); - uint32_t seed = 0x10c0u; - fill(a, (size_t)32 * k, &seed); fill(b, (size_t)k * n, &seed); - OmegaGpuMatmulInfo info; - const uint64_t h0 = omega_gpu_matmul_test_a_row0_hits(); - int rc1 = omega_gpu_matmul_f32(1, k, n, a, b, c, &info); - CHECK(rc1 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "one-row call 1 (full pack) rc=%s parity=%d", omega_gpu_matmul_rc_name(rc1), info.parity_verified); - const uint64_t h1 = omega_gpu_matmul_test_a_row0_hits(); - int rc2 = omega_gpu_matmul_f32(1, k, n, a + k, b, c, &info); - const uint64_t h2 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc2 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "one-row call 2 (row 0 only, new A) rc=%s parity=%d", omega_gpu_matmul_rc_name(rc2), info.parity_verified); - CHECK(h1 == h0 && h2 == h1 + 1, "row-0 path taken on the second one-row call only (hits %" PRIu64 " %" PRIu64 " %" PRIu64 ")", h0, h1, h2); - int rc3 = omega_gpu_matmul_f32(32, k, n, a, b, c, &info); - CHECK(rc3 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "32-row call between rc=%s parity=%d", omega_gpu_matmul_rc_name(rc3), info.parity_verified); - int rc4 = omega_gpu_matmul_f32(1, k, n, a + 2 * (size_t)k, b, c, &info); - const uint64_t h4 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc4 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h4 == h2, "one-row call after a wider call packs in full (hits %" PRIu64 ")", h4); - int rc5 = omega_gpu_matmul_f32(1, k, n, a + 3 * (size_t)k, b, c, &info); - const uint64_t h5 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc5 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h5 == h4 + 1, "one-row call after a one-row call writes row 0 only (hits %" PRIu64 ")", h5); - int rc6 = omega_gpu_matmul_f32(1, 64, n, a, b, c, &info); - const uint64_t h6 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc6 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h6 == h5, "one-row call of another width packs in full (hits %" PRIu64 ")", h6); - free(a); free(b); free(c); -} - -/* omega #473: the stage timer must explain the call. The six stages tile matmul_core in order, the chip - * time sits inside the launch stage, and the core span sits inside the whole call. */ -static uint64_t stage_sum(const OmegaGpuMatmulStages *s) { - return s->setup_ns + s->pack_ns + s->upload_ns + s->launch_ns + s->sync_ns + s->copy_out_ns; -} -static void stage_checks(const char *tag, const OmegaGpuMatmulInfo *info) { - OmegaGpuMatmulStages s; - omega_gpu_matmul_last_stages(&s); - CHECK(s.chip_ns == info->elapsed_ns && s.chip_ns > 0, "%s stages: chip_ns %" PRIu64 " equals elapsed_ns %" PRIu64, tag, s.chip_ns, info->elapsed_ns); - CHECK(s.launch_ns >= s.chip_ns, "%s stages: launch_ns %" PRIu64 " holds chip_ns %" PRIu64, tag, s.launch_ns, s.chip_ns); - CHECK(s.pack_ns > 0 && s.copy_out_ns > 0, "%s stages: pack %" PRIu64 " and copy-out %" PRIu64 " measured", tag, s.pack_ns, s.copy_out_ns); - CHECK(stage_sum(&s) <= s.core_ns && s.core_ns <= info->call_ns && s.core_ns > 0, - "%s stages: sum %" PRIu64 " <= core %" PRIu64 " <= call %" PRIu64, tag, stage_sum(&s), s.core_ns, info->call_ns); -} - -/* omega #473 profile: resident calls at the given shapes, 3 warmups then 7 timed calls per input type - * (bf16 rows, f32 rows); median of each stage. Correctness is the R4 receipt's job; here the two input - * types must agree bit for bit and every call must pass stage_checks. */ -static uint64_t med_u64(uint64_t *v, int n) { - for (int i = 1; i < n; i++) for (int j = i; j > 0 && v[j - 1] > v[j]; j--) { uint64_t t = v[j]; v[j] = v[j - 1]; v[j - 1] = t; } - return v[n / 2]; -} -static int stages_profile(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_STAGES_V1\",\"cta_budget\":%u,\"warmups\":3,\"timed\":7,\"rows\":[", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes), *save = NULL; - int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - const size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * 4), *b = malloc(nb * 4), *c16 = malloc(nc * 4), *c32 = malloc(nc * 4); - uint16_t *ah = malloc(na * 2); - if (!a || !b || !c16 || !c32 || !ah) { CHECK(0, "host memory for %s", tok); break; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - OmegaGpuTensor *t = NULL; - int urc = omega_gpu_tensor_upload_f32(k, n, b, &t); - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %s rc=%s", tok, omega_gpu_matmul_rc_name(urc)); - if (urc != OMEGA_GPU_MATMUL_OK) break; - for (int in32 = 0; in32 < 2; in32++) { - uint64_t v[9][7]; /* setup pack upload launch chip sync copy_out core call */ - int ok = 1; - for (int it = 0; it < 10 && ok; it++) { - OmegaGpuMatmulInfo info; - int rc = in32 ? omega_gpu_matmul_resident_f32(m, a, t, c32, &info) : omega_gpu_matmul_resident_bf16(m, ah, t, c16, &info); - if (rc != OMEGA_GPU_MATMUL_OK) { CHECK(0, "%s %s rc=%s (%s)", tok, in32 ? "f32" : "bf16", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); ok = 0; break; } - stage_checks(tok, &info); - if (it < 3) continue; - OmegaGpuMatmulStages s; omega_gpu_matmul_last_stages(&s); - const uint64_t row[9] = { s.setup_ns, s.pack_ns, s.upload_ns, s.launch_ns, s.chip_ns, s.sync_ns, s.copy_out_ns, s.core_ns, info.call_ns }; - for (int q = 0; q < 9; q++) v[q][it - 3] = row[q]; - } - if (!ok) continue; - uint64_t md[9]; - for (int q = 0; q < 9; q++) md[q] = med_u64(v[q], 7); - const double flop = 2.0 * m * k * n; - printf("STAGES %s in=%s budget=%u call_ms=%.3f core_ms=%.3f setup=%.3f pack=%.3f upload=%.3f launch=%.3f chip=%.3f launch_minus_chip=%.3f sync=%.3f copy_out=%.3f " - "tflops_chip=%.3f tflops_call=%.3f chip_share=%.1f%%\n", tok, in32 ? "f32" : "bf16", omega_gpu_matmul_cta_budget(), md[8] / 1e6, md[7] / 1e6, - md[0] / 1e6, md[1] / 1e6, md[2] / 1e6, md[3] / 1e6, md[4] / 1e6, (md[3] > md[4] ? md[3] - md[4] : 0) / 1e6, md[5] / 1e6, md[6] / 1e6, - flop / (double)md[4] / 1e3, flop / (double)md[8] / 1e3, 100.0 * (double)md[4] / (double)md[8]); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"input\":\"%s\",\"median_ns\":{\"setup\":%" PRIu64 ",\"pack\":%" PRIu64 ",\"upload\":%" PRIu64 ",\"launch\":%" PRIu64 - ",\"chip\":%" PRIu64 ",\"sync\":%" PRIu64 ",\"copy_out\":%" PRIu64 ",\"core\":%" PRIu64 ",\"call\":%" PRIu64 "},\"tflops_chip\":%.4f,\"tflops_call\":%.4f}", - first ? "" : ",", m, k, n, in32 ? "f32" : "bf16", md[0], md[1], md[2], md[3], md[4], md[5], md[6], md[7], md[8], flop / (double)md[4] / 1e3, flop / (double)md[8] / 1e3); - first = 0; - } - } - size_t diff = 0; - for (size_t i = 0; i < nc; i++) diff += memcmp(&c16[i], &c32[i], 4) != 0; - CHECK(diff == 0, "%s bf16-in and f32-in outputs agree bit for bit (%zu differ)", tok, diff); - omega_gpu_tensor_free(t); - free(a); free(b); free(c16); free(c32); free(ah); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return 0; -} - -static int chip_sweep(const char *shapes, const char *out_path, int mutant) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_SWEEP_V2\",\"mutant\":%s,\"cta_budget\":%u,\"shapes\":[", mutant ? "true" : "false", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes); - char *save = NULL; - int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c2 = malloc(nc * sizeof *c2); - if (!a || !b || !c || !c2) { printf("out of host memory for %s\n", tok); free(a); free(b); free(c); free(c2); continue; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < nc; i++) c[i] = -12345.0f; - OmegaGpuMatmulInfo info, info2; - double t0 = now_ms(); - int rc = omega_gpu_matmul_f32(m, k, n, a, b, c, &info); - double wall_ms = now_ms() - t0; - if (!mutant && rc == OMEGA_GPU_MATMUL_OK) stage_checks(tok, &info); - /* second call on the same shape must hit the kernel cache and agree */ - int rc2 = omega_gpu_matmul_f32(m, k, n, a, b, c2, &info2); - size_t repeat_mismatch = 0; - for (size_t i = 0; i < nc; i++) if (c[i] != c2[i]) repeat_mismatch++; - size_t e2e_bad = 0; - double e2e = (rc == OMEGA_GPU_MATMUL_OK || rc == OMEGA_GPU_MATMUL_PARITY_FAIL) ? e2e_max_rel(m, k, n, a, b, c, &e2e_bad) : 0.0; - int pass = rc == OMEGA_GPU_MATMUL_OK && info.parity_verified && e2e < 1e-5 - && rc2 == OMEGA_GPU_MATMUL_OK && info2.kernel_cache_hit && repeat_mismatch == 0; - if (mutant) { - /* the wrong kernel must be caught: PARITY_FAIL from the API oracle and a visible e2e error */ - int caught = rc == OMEGA_GPU_MATMUL_PARITY_FAIL && !info.parity_verified && e2e >= 1e-5; - CHECK(caught, "mutant shape %ux%ux%u NOT caught: rc=%s parity=%d e2e_rel=%g", m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, e2e); - pass = caught; - } else { - CHECK(pass, "shape %ux%ux%u rc=%s parity=%d max_rel=%g e2e_rel=%g rc2=%s hit=%d repeat_mismatch=%zu", - m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, info.max_rel_err, e2e, - omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit, repeat_mismatch); - } - printf("%s %ux%ux%u rc=%s chip_ns=%" PRIu64 " call_ms=%.3f wall_ms=%.1f max_abs=%g max_rel=%g mismatches=%zu e2e_rel=%g e2e_bad=%zu grid=%ux%u calls=%u rows_per_call=%u cache_hit2=%d err=\"%s\"\n", - pass ? (mutant ? "KILLED" : "PASS") : (mutant ? "SURVIVED" : "FAIL"), m, k, n, omega_gpu_matmul_rc_name(rc), info.elapsed_ns, info.call_ns / 1e6, wall_ms, - info.max_abs_err, info.max_rel_err, info.mismatch_count, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info2.kernel_cache_hit, rc == OMEGA_GPU_MATMUL_CHIP_FAIL ? omega_gpu_matmul_last_error() : ""); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"rc\":\"%s\",\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 - ",\"call_ms\":%.3f,\"wall_ms\":%.3f,\"max_abs_err\":%g,\"max_rel_err\":%g,\"mismatch_count\":%zu," - "\"parity_verified\":%s,\"completion_marker\":%u,\"repeat_rc\":\"%s\",\"repeat_cache_hit\":%s," - "\"repeat_mismatch\":%zu,\"e2e_max_rel\":%g,\"e2e_bad\":%zu,\"grid_x\":%u,\"grid_y\":%u,\"chip_calls\":%u,\"rows_per_call\":%u,\"padded_m\":%u,\"padded_k\":%u,\"padded_n\":%u,\"target_chip\":\"%s\",\"sm_architecture\":%u}", - first ? "" : ",", m, k, n, omega_gpu_matmul_rc_name(rc), pass ? "true" : "false", - info.elapsed_ns, info.call_ns / 1e6, wall_ms, info.max_abs_err, info.max_rel_err, info.mismatch_count, - info.parity_verified ? "true" : "false", info.completion_marker, - omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit ? "true" : "false", - repeat_mismatch, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info.padded_m, info.padded_k, info.padded_n, info.target_chip, info.sm_architecture); - first = 0; - } - free(a); free(b); free(c); free(c2); - if (omega_gpu_matmul_is_blocked()) { printf("device latched after an uncertain completion; stopping the sweep\n"); break; } - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? (mutant ? "OMEGA_GPU_MATMUL_MUTANT_KILLED" : "OMEGA_GPU_MATMUL_API_PASS") : (mutant ? "OMEGA_GPU_MATMUL_MUTANT_SURVIVED" : "OMEGA_GPU_MATMUL_API_FAIL")); - fclose(out); - } - return 0; -} - -static int cmp_double(const void *x, const void *y) { double a = *(const double *)x, b = *(const double *)y; return a < b ? -1 : a > b; } - -/* Resident path: upload B once, then 100 calls; median wall time per call must be under 5 ms. - * Parity: first and last result against the double reference (0 elements at or beyond 1e-5). */ -static int timing(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_TIMING_V1\",\"cta_budget\":%u,\"spin_us\":%u,\"calls\":100,\"shapes\":[", omega_gpu_matmul_cta_budget(), omega_gpu_session_spin_us()); - char *copy = strdup(shapes); char *save = NULL; int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c_first = malloc(nc * sizeof *c_first); - uint16_t *ah = malloc(na * sizeof *ah); - if (!a || !b || !c || !c_first || !ah) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x7111e000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - OmegaGpuTensor *t = NULL; - double tu0 = now_ms(); - int urc = omega_gpu_tensor_upload_f32(k, n, b, &t); - double upload_ms = now_ms() - tu0; - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %ux%u rc=%s", k, n, omega_gpu_matmul_rc_name(urc)); - double samples[100]; int ok_calls = 0; OmegaGpuMatmulInfo info; memset(&info, 0, sizeof info); - uint64_t chip_ns_sum = 0; size_t repeat_mismatch = 0; - if (urc == OMEGA_GPU_MATMUL_OK) { - for (int i = 0; i < 100; i++) { - for (size_t j = 0; j < nc; j++) c[j] = -12345.0f; - double t0 = now_ms(); - int rc = omega_gpu_matmul_resident_bf16(m, ah, t, c, &info); - samples[i] = now_ms() - t0; - /* OMEGA_GPU_MATMUL_TIMING_NO_ORACLE=1: the per-call host oracle (m x n x k double MACs) only on the first - * call; at m = 128 it is minutes per shape and the timing is the point (2026-10-12). */ - if (i == 0 && getenv("OMEGA_GPU_MATMUL_TIMING_NO_ORACLE")) omega_gpu_matmul_set_oracle(0); - if (rc == OMEGA_GPU_MATMUL_OK) ok_calls++; - chip_ns_sum += info.elapsed_ns; - if (i == 0) memcpy(c_first, c, nc * sizeof *c); - else for (size_t j = 0; j < nc; j++) if (c[j] != c_first[j]) repeat_mismatch++; - if (omega_gpu_matmul_is_blocked()) break; - } - } - qsort(samples, 100, sizeof samples[0], cmp_double); - double median = samples[50], p90 = samples[90], mn = samples[0], mx = samples[99]; - size_t bad_first = 0, bad_last = 0; - double e2e_first = e2e_max_rel(m, k, n, a, b, c_first, &bad_first); - double e2e_last = e2e_max_rel(m, k, n, a, b, c, &bad_last); - int pass = ok_calls == 100 && bad_first == 0 && bad_last == 0 && repeat_mismatch == 0 && (m > 1 || median < 5.0); /* the 5 ms gate is the GEMV (m = 1) gate */ - CHECK(pass, "timing %ux%ux%u ok_calls=%d median_ms=%.3f e2e_first=%g e2e_last=%g bad=%zu/%zu repeat_mismatch=%zu", - m, k, n, ok_calls, median, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); - printf("%s timing %ux%ux%u upload_ms=%.1f ok_calls=%d median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_ns_mean=%" PRIu64 " grid=%ux%u e2e_first=%g e2e_last=%g repeat_mismatch=%zu\n", - pass ? "PASS" : "FAIL", m, k, n, upload_ms, ok_calls, median, p90, mn, mx, ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, repeat_mismatch); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"pass\":%s,\"upload_ms\":%.3f,\"ok_calls\":%d,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f," - "\"chip_ns_mean\":%" PRIu64 ",\"grid_x\":%u,\"grid_y\":%u,\"e2e_first\":%g,\"e2e_last\":%g,\"e2e_bad_first\":%zu,\"e2e_bad_last\":%zu,\"repeat_mismatch\":%zu}", - first ? "" : ",", m, k, n, pass ? "true" : "false", upload_ms, ok_calls, median, p90, mn, mx, - ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); - first = 0; - } - omega_gpu_matmul_set_oracle(1); - omega_gpu_tensor_free(t); - free(a); free(b); free(c); free(c_first); free(ah); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_MATMUL_TIMING_PASS" : "OMEGA_GPU_MATMUL_TIMING_FAIL"); - fclose(out); - } - return 0; -} - -/* --update (R3, omega #473): omega_gpu_tensor_update_* on the chip. Per shape (m rows of A, k x n weights): - * upload B1, matmul -> c1; update_f32(B2), matmul -> c2; fresh upload of B2, matmul -> c2f. c2 must equal c2f - * bit for bit and the double reference of A x B2 (0 elements at or beyond 1e-5); update_bf16(bf16(B1)) then - * matmul must give c1 back bit for bit. Timing, median of 5 each: update_f32, update_bf16, and the - * upload_f32 + free that an update replaces. */ -static const char *UPDATE_SHAPES = "16,768,2304;16,768,50304"; -static double median5(double *s) { qsort(s, 5, sizeof *s, cmp_double); return s[2]; } -static int update_mode(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_TENSOR_UPDATE_V1\",\"cta_budget\":%u,\"timed_calls\":5,\"shapes\":[", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes); char *save = NULL; int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b1 = malloc(nb * sizeof *b1), *b2 = malloc(nb * sizeof *b2); - float *c1 = malloc(nc * sizeof *c1), *c2 = malloc(nc * sizeof *c2), *c2f = malloc(nc * sizeof *c2f), *c3 = malloc(nc * sizeof *c3); - uint16_t *b1h = malloc(nb * sizeof *b1h); - if (!a || !b1 || !b2 || !c1 || !c2 || !c2f || !c3 || !b1h) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x0bda7e00u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b1, nb, &seed); fill(b2, nb, &seed); - for (size_t i = 0; i < nb; i++) b1h[i] = omega_fp32_to_bf16(b1[i]); - OmegaGpuTensor *t = NULL, *tf = NULL; - int rc = omega_gpu_tensor_upload_f32(k, n, b1, &t); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update %ux%ux%u: upload B1 rc=%s", m, k, n, omega_gpu_matmul_rc_name(rc)); - if (rc != OMEGA_GPU_MATMUL_OK) return 2; - rc = omega_gpu_matmul_resident_f32(m, a, t, c1, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul B1 rc=%s", omega_gpu_matmul_rc_name(rc)); - rc = omega_gpu_tensor_update_f32(t, k, n, b2); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_f32 rc=%s %s", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - rc = omega_gpu_matmul_resident_f32(m, a, t, c2, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul after update rc=%s", omega_gpu_matmul_rc_name(rc)); - rc = omega_gpu_tensor_upload_f32(k, n, b2, &tf); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "fresh upload B2 rc=%s", omega_gpu_matmul_rc_name(rc)); - if (rc == OMEGA_GPU_MATMUL_OK) rc = omega_gpu_matmul_resident_f32(m, a, tf, c2f, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul fresh B2 rc=%s", omega_gpu_matmul_rc_name(rc)); - omega_gpu_tensor_free(tf); - size_t vs_fresh = 0, back = 0, bad = 0; - for (size_t j = 0; j < nc; j++) vs_fresh += memcmp(&c2[j], &c2f[j], 4) != 0; - double e2e = e2e_max_rel(m, k, n, a, b2, c2, &bad); - rc = omega_gpu_tensor_update_bf16(t, k, n, b1h); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_bf16 rc=%s %s", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - rc = omega_gpu_matmul_resident_f32(m, a, t, c3, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul after update back rc=%s", omega_gpu_matmul_rc_name(rc)); - for (size_t j = 0; j < nc; j++) back += memcmp(&c3[j], &c1[j], 4) != 0; - CHECK(vs_fresh == 0, "update %ux%ux%u: %zu of %zu outputs differ from a fresh upload of the same values", m, k, n, vs_fresh, nc); - CHECK(bad == 0, "update %ux%ux%u: %zu outputs off the double reference (worst %g)", m, k, n, bad, e2e); - CHECK(back == 0, "update %ux%ux%u: %zu of %zu outputs differ after updating back to B1", m, k, n, back, nc); - double s_f32[5], s_bf16[5], s_up[5]; - int timed_ok = 1; - for (int i = 0; i < 5; i++) { - double t0 = now_ms(); timed_ok &= omega_gpu_tensor_update_f32(t, k, n, b2) == OMEGA_GPU_MATMUL_OK; s_f32[i] = now_ms() - t0; - t0 = now_ms(); timed_ok &= omega_gpu_tensor_update_bf16(t, k, n, b1h) == OMEGA_GPU_MATMUL_OK; s_bf16[i] = now_ms() - t0; - t0 = now_ms(); timed_ok &= omega_gpu_tensor_upload_f32(k, n, b2, &tf) == OMEGA_GPU_MATMUL_OK; omega_gpu_tensor_free(tf); s_up[i] = now_ms() - t0; - } - CHECK(timed_ok, "update %ux%ux%u: a timed call failed", m, k, n); - double mf = median5(s_f32), mb = median5(s_bf16), mu = median5(s_up); - int pass = vs_fresh == 0 && bad == 0 && back == 0 && timed_ok; - printf("%s update %ux%ux%u vs_fresh=%zu e2e=%g bad=%zu back=%zu update_f32_ms=%.2f update_bf16_ms=%.2f upload_f32_free_ms=%.2f\n", - pass ? "PASS" : "FAIL", m, k, n, vs_fresh, e2e, bad, back, mf, mb, mu); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"pass\":%s,\"vs_fresh_diff\":%zu,\"e2e_max_rel\":%g,\"e2e_bad\":%zu,\"back_diff\":%zu," - "\"update_f32_ms\":%.3f,\"update_bf16_ms\":%.3f,\"upload_f32_free_ms\":%.3f}", - first ? "" : ",", m, k, n, pass ? "true" : "false", vs_fresh, e2e, bad, back, mf, mb, mu); - first = 0; - } - omega_gpu_tensor_free(t); - free(a); free(b1); free(b2); free(c1); free(c2); free(c2f); free(c3); free(b1h); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_TENSOR_UPDATE_PASS" : "OMEGA_GPU_TENSOR_UPDATE_FAIL"); - fclose(out); - } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; - int host = 0, mutant = 0, do_timing = 0, do_update = 0, do_stages = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--mutant") == 0) mutant = 1; - else if (strcmp(argv[i], "--timing") == 0) do_timing = 1; - else if (strcmp(argv[i], "--update") == 0) do_update = 1; - else if (strcmp(argv[i], "--stages") == 0) do_stages = 1; - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) omega_gpu_matmul_set_cta_budget((uint32_t)strtoul(argv[++i], NULL, 10)); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) { - if (omega_gpu_session_set_spin_us((uint32_t)strtoul(argv[++i], NULL, 10)) != 0) { fprintf(stderr, "--spin-us out of range\n"); return 2; } - } - else if (strcmp(argv[i], "--unroll") == 0 && i + 1 < argc) omega_gpu_matmul_test_set_unroll((uint32_t)strtoul(argv[++i], NULL, 10)); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - const char *shapes = getenv("OMEGA_GPU_MATMUL_SHAPES"); - if (shapes && !*shapes) shapes = NULL; - int rc = 0; - if (host) host_only(); - else if (do_timing) rc = timing(shapes ? shapes : TIMING_SHAPES, out_path); - else if (do_update) rc = update_mode(shapes ? shapes : UPDATE_SHAPES, out_path); - else if (do_stages) rc = stages_profile(shapes ? shapes : STAGE_SHAPES, out_path); - else if (mutant) { omega_gpu_matmul_test_set_mutant(1); rc = chip_sweep(shapes ? shapes : MUTANT_SHAPES, out_path, 1); omega_gpu_matmul_test_set_mutant(0); } - else rc = chip_sweep(shapes ? shapes : DEFAULT_SHAPES, out_path, 0); - if (!host && !do_timing && !do_update && !do_stages && !mutant && !omega_gpu_matmul_is_blocked()) one_row_repack_checks(); - if (!omega_gpu_matmul_is_blocked()) omega_gpu_device_close(); - if (rc) return 2; - printf("%s: %d checks, %d failed%s\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed, mutant ? (g_failed ? " (mutant SURVIVED)" : " (mutant killed)") : ""); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_matmul_r4_receipt.c b/tests/gpu_matmul_r4_receipt.c deleted file mode 100644 index 75db507fd..000000000 --- a/tests/gpu_matmul_r4_receipt.c +++ /dev/null @@ -1,377 +0,0 @@ -/* gpu_matmul_r4_receipt: the sealed CTA-budget receipt omega_gpu_matmul_api.h asks for before - * OMEGA_GPU_MATMUL_MAX_CTAS moves (omega #473, R4). - * - * ./gpu_matmul_r4_receipt --host-only reference and comparator self-tests, no chip - * ./gpu_matmul_r4_receipt --out receipt.json chip receipt (run under the quiet flag) - * [--budgets 64,128,256,512,1024] [--repeats 3] [--threads 12] [--shapes "m,k,n;..."] - * - * Per shape: B is uploaded once (resident, bf16). The reference is the full m x n product of the same - * bf16 inputs in double on the host (threaded), with the accumulation scale (sum of |terms|) per element. - * Per budget: the CTA budget is set (kernel cache cleared), then 2 x repeats resident calls alternate - * -A, +A, -A, +A, ... (A negated by its sign bit, so the exact answer of each call is the negation of the - * previous one). Every element of every call is checked: - * - rep 0 of each sign: every element within 1e-5 of the accumulation scale of the reference - * (the rule of gpu_matmul_api_test.c e2e_max_rel), and finite; - * - later repeats: bit-identical to rep 0 of the same sign; - * - I42 (cut 1: grids of 128 CTAs and above lost output with the single-tile kernel): an element still - * holding the previous call's bits (nonzero) is stale, i.e. not written by this call. Alternating the - * sign makes stale output visible; the budget sequence starts with -A because the previous budget - * ended with +A. The device-side sentinel check (OUTPUT_UNCHANGED) runs inside the API as well. - * Negative controls: the comparator flags a one-element perturbation and a planted stale element; the - * chip mutant kernel (last K step dropped) at the largest budget must be flagged by the full comparison. - * Timing: chip = OmegaGpuMatmulInfo.elapsed_ns, call = call_ns; median over all 2 x repeats calls. - * The best sealed budget is the one with every shape PASS and the least summed median chip time. - */ -#include "omega_gpu_matmul_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include "sha256.h" -#include -#include -#include -#include -#include - -#define TOL 1e-5 -#define MAX_BUDGETS 16 -#define NAN_FILL 0x7fc0deadu - -static const char *DEFAULT_SHAPES = - /* the five training shapes (omega #473), then two I42 shapes on the single-tile kernel (rt = ct = 1): - * decode 1 x 2048 x 8192 (grid_x up to the budget) and 7 row tiles (112 rows) */ - "8192,768,2304;8192,768,768;8192,768,3072;8192,3072,768;1024,768,50304;1,2048,8192;112,768,3072"; -static const uint32_t DEFAULT_BUDGETS[] = { 64, 128, 256, 512, 1024 }; - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static inline double absd(double x) { return x < 0.0 ? -x : x; } -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static uint32_t fbits(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static float bitsf(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static int is_finite(float f) { return (fbits(f) & 0x7f800000u) != 0x7f800000u; } - -/* inputs as gpu_matmul_api_test.c fill(): values in [-1, 1] at 1/1000 steps, rounded to bf16 */ -static void fill_bf16(uint16_t *x, size_t n, uint32_t *seed) { - for (size_t i = 0; i < n; i++) x[i] = omega_fp32_to_bf16(((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f); -} - -/* ---- reference: acc[i*n+j] = sum_t a[i,t] b[t,j] in double, sc = max(sum |terms|, 1e-6) ---- */ -typedef struct { - uint32_t m, k, n, r0, r1; - const double *ad, *btd; /* A m x k, B transposed n x k, both exact bf16 values in double */ - double *acc, *sc; -} RefJob; - -static void *ref_rows(void *p) { - RefJob *J = p; - const uint32_t k = J->k, n = J->n; - for (uint32_t i = J->r0; i < J->r1; i++) { - const double *ar = J->ad + (size_t)i * k; - for (uint32_t j = 0; j < n; j++) { - const double *br = J->btd + (size_t)j * k; - double s0 = 0, s1 = 0, s2 = 0, s3 = 0, q0 = 0, q1 = 0, q2 = 0, q3 = 0; - uint32_t t = 0; - for (; t + 4 <= k; t += 4) { - double p0 = ar[t] * br[t], p1 = ar[t + 1] * br[t + 1], p2 = ar[t + 2] * br[t + 2], p3 = ar[t + 3] * br[t + 3]; - s0 += p0; s1 += p1; s2 += p2; s3 += p3; - q0 += absd(p0); q1 += absd(p1); q2 += absd(p2); q3 += absd(p3); - } - for (; t < k; t++) { double p0 = ar[t] * br[t]; s0 += p0; q0 += absd(p0); } - const double q = (q0 + q1) + (q2 + q3); - J->acc[(size_t)i * n + j] = (s0 + s1) + (s2 + s3); - J->sc[(size_t)i * n + j] = q > 1e-6 ? q : 1e-6; - } - } - return NULL; -} - -static int reference(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, unsigned threads, double *acc, double *sc) { - double *ad = malloc((size_t)m * k * sizeof *ad), *btd = malloc((size_t)n * k * sizeof *btd); - if (!ad || !btd) { free(ad); free(btd); return -1; } - for (size_t i = 0; i < (size_t)m * k; i++) ad[i] = omega_bf16_to_fp32(a[i]); - for (uint32_t t = 0; t < k; t++) - for (uint32_t j = 0; j < n; j++) btd[(size_t)j * k + t] = omega_bf16_to_fp32(b[(size_t)t * n + j]); - if (threads < 1) threads = 1; - if (threads > 64) threads = 64; - if (threads > m) threads = m; - pthread_t th[64]; RefJob J[64]; - int rc = 0; - for (unsigned w = 0; w < threads; w++) { - J[w] = (RefJob){ m, k, n, (uint32_t)((uint64_t)m * w / threads), (uint32_t)((uint64_t)m * (w + 1) / threads), ad, btd, acc, sc }; - if (pthread_create(&th[w], NULL, ref_rows, &J[w]) != 0) { ref_rows(&J[w]); th[w] = 0; } - } - for (unsigned w = 0; w < threads; w++) if (th[w]) pthread_join(th[w], NULL); - free(ad); free(btd); - return rc; -} - -/* ---- full comparison of one output against sign * reference ---- */ -typedef struct { size_t mismatches, nonfinite; double max_rel; } Cmp; - -static Cmp compare_full(size_t cnt, const float *c, const double *acc, const double *sc, double sign) { - Cmp r = { 0, 0, 0.0 }; - for (size_t i = 0; i < cnt; i++) { - if (!is_finite(c[i])) { r.nonfinite++; r.mismatches++; continue; } - const double rel = absd((double)c[i] - sign * acc[i]) / sc[i]; - if (rel > r.max_rel) r.max_rel = rel; - if (rel > TOL) r.mismatches++; - } - return r; -} - -static size_t count_bit_diff(size_t cnt, const float *x, const float *y) { - size_t d = 0; - for (size_t i = 0; i < cnt; i++) d += fbits(x[i]) != fbits(y[i]); - return d; -} - -/* elements still holding the previous call's bits (the exact answer flipped sign, so only an element - * whose answer is exactly zero may legitimately repeat; those are excluded) */ -static size_t count_stale(size_t cnt, const float *cur, const float *prev) { - size_t s = 0; - for (size_t i = 0; i < cnt; i++) s += fbits(cur[i]) == fbits(prev[i]) && (fbits(cur[i]) & 0x7fffffffu) != 0; - return s; -} - -static size_t count_not_negation(size_t cnt, const float *pos, const float *neg) { - size_t d = 0; - for (size_t i = 0; i < cnt; i++) d += fbits(pos[i]) != (fbits(neg[i]) ^ 0x80000000u); - return d; -} - -/* sha256 of the output bytes (first 16 hex digits), so separate runs can be compared bit for bit */ -static void digest16(const float *c, size_t cnt, char hex[17]) { - uint8_t d[SHA256_DIGEST_SIZE]; - sha256_hash((const uint8_t *)c, cnt * sizeof *c, d); - for (int i = 0; i < 8; i++) snprintf(hex + 2 * i, 3, "%02x", d[i]); -} - -static int cmp_u64(const void *x, const void *y) { uint64_t a = *(const uint64_t *)x, b = *(const uint64_t *)y; return a < b ? -1 : a > b; } -static uint64_t median_u64(uint64_t *v, size_t n) { qsort(v, n, sizeof *v, cmp_u64); return n ? v[n / 2] : 0; } - -/* comparator self-test on data the caller has (exact reference rounded to f32 is the "chip" output) */ -static void comparator_controls(uint32_t m, uint32_t n, const double *acc, const double *sc, const char *tag, FILE *out) { - const size_t cnt = (size_t)m * n; - float *c = malloc(cnt * sizeof *c), *prev = malloc(cnt * sizeof *prev); - if (!c || !prev) { CHECK(0, "%s comparator controls: host memory", tag); free(c); free(prev); return; } - for (size_t i = 0; i < cnt; i++) { c[i] = (float)acc[i]; prev[i] = -(float)acc[i]; } - Cmp clean = compare_full(cnt, c, acc, sc, 1.0); - const size_t at = cnt / 2 + 3; - c[at] = (float)(acc[at] + 4.0 * TOL * sc[at]); - Cmp pert = compare_full(cnt, c, acc, sc, 1.0); - c[at] = (float)acc[at]; - const size_t at2 = cnt - 1; - float keep = c[at2]; - if (acc[at2] == 0.0) { c[at2] = 1.0f; prev[at2] = 1.0f; } else c[at2] = prev[at2]; - const size_t stale = count_stale(cnt, c, prev); - c[at2] = keep; - c[0] = bitsf(NAN_FILL); - Cmp nan = compare_full(cnt, c, acc, sc, 1.0); - CHECK(clean.mismatches == 0, "%s control: exact reference must compare clean (%zu)", tag, clean.mismatches); - CHECK(pert.mismatches == 1, "%s control: one perturbed element must be flagged (%zu)", tag, pert.mismatches); - CHECK(stale == 1, "%s control: one planted stale element must be flagged (%zu)", tag, stale); - CHECK(nan.mismatches == 1 && nan.nonfinite == 1, "%s control: one unwritten (NaN) element must be flagged (%zu)", tag, nan.mismatches); - printf("%s comparator controls: clean=%zu perturbed=%zu stale=%zu unwritten=%zu\n", tag, clean.mismatches, pert.mismatches, stale, nan.mismatches); - if (out) fprintf(out, "\"comparator_control\":{\"shape\":\"%s\",\"clean_mismatches\":%zu,\"perturbed_flagged\":%zu,\"stale_flagged\":%zu,\"unwritten_flagged\":%zu},", - tag, clean.mismatches, pert.mismatches, stale, nan.mismatches); - free(c); free(prev); -} - -static int host_only(unsigned threads) { - /* threaded reference against a naive single-thread double loop, and the comparator controls */ - const uint32_t m = 37, k = 80, n = 52; - uint16_t *a = malloc((size_t)m * k * 2), *b = malloc((size_t)k * n * 2); - double *acc = malloc((size_t)m * n * 8), *sc = malloc((size_t)m * n * 8); - uint32_t seed = 4730u; - fill_bf16(a, (size_t)m * k, &seed); fill_bf16(b, (size_t)k * n, &seed); - CHECK(reference(m, k, n, a, b, threads, acc, sc) == 0, "reference ran"); - double worst = 0.0; - for (uint32_t i = 0; i < m; i++) - for (uint32_t j = 0; j < n; j++) { - double s = 0, q = 0; - for (uint32_t t = 0; t < k; t++) { double p = (double)omega_bf16_to_fp32(a[i * k + t]) * omega_bf16_to_fp32(b[t * n + j]); s += p; q += absd(p); } - double d = absd(s - acc[i * n + j]) / (q > 1e-6 ? q : 1e-6); - if (d > worst) worst = d; - if (absd(q - sc[i * n + j]) > 1e-12 * (q > 1.0 ? q : 1.0)) worst = 1.0; - } - CHECK(worst < 1e-12, "threaded reference equals the naive loop (worst rel %g)", worst); - comparator_controls(m, n, acc, sc, "host 37x80x52", NULL); - /* sign-bit negation of bf16 A negates the reference exactly */ - for (size_t i = 0; i < (size_t)m * k; i++) a[i] ^= 0x8000u; - double *acc2 = malloc((size_t)m * n * 8), *sc2 = malloc((size_t)m * n * 8); - reference(m, k, n, a, b, threads, acc2, sc2); - size_t notneg = 0; - for (size_t i = 0; i < (size_t)m * n; i++) notneg += acc2[i] != -acc[i] || sc2[i] != sc[i]; - CHECK(notneg == 0, "negated A gives the exact negated reference (%zu differ)", notneg); - free(a); free(b); free(acc); free(sc); free(acc2); free(sc2); - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} - -typedef struct { uint64_t chip_med_ns; int pass; } Cell; - -int main(int argc, char **argv) { - const char *out_path = NULL, *shapes = DEFAULT_SHAPES; - uint32_t budgets[MAX_BUDGETS]; unsigned nb = 0; - unsigned repeats = 3, threads = 12; - int host = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--shapes") == 0 && i + 1 < argc) shapes = argv[++i]; - else if (strcmp(argv[i], "--repeats") == 0 && i + 1 < argc) repeats = (unsigned)strtoul(argv[++i], NULL, 10); - else if (strcmp(argv[i], "--threads") == 0 && i + 1 < argc) threads = (unsigned)strtoul(argv[++i], NULL, 10); - else if (strcmp(argv[i], "--budgets") == 0 && i + 1 < argc) { - char *s = argv[++i]; - while (*s && nb < MAX_BUDGETS) { budgets[nb++] = (uint32_t)strtoul(s, &s, 10); if (*s == ',') s++; else break; } - } else { fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } - } - if (host) return host_only(threads); - if (!nb) { nb = sizeof DEFAULT_BUDGETS / sizeof DEFAULT_BUDGETS[0]; memcpy(budgets, DEFAULT_BUDGETS, sizeof DEFAULT_BUDGETS); } - if (repeats < 1) repeats = 1; - if (repeats > 32) repeats = 32; /* 2 x repeats calls fit the per-budget timing arrays */ - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) { - fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_R4_RECEIPT_V1\",\"default_budget\":%u,\"repeats\":%u,\"tol_rel_scale\":%g,\"budgets\":[", OMEGA_GPU_MATMUL_MAX_CTAS, repeats, TOL); - for (unsigned b = 0; b < nb; b++) fprintf(out, "%s%u", b ? "," : "", budgets[b]); - fprintf(out, "],"); - } - Cell cells[32][MAX_BUDGETS]; memset(cells, 0, sizeof cells); - char shape_names[32][40]; unsigned ns = 0; - int controls_done = 0, mutant_done = 0; - if (out) fprintf(out, "\"runs\":["); - int first_run = 1; - char *copy = strdup(shapes), *save = NULL; - for (char *tok = strtok_r(copy, ";", &save); tok && ns < 32 && !omega_gpu_matmul_is_blocked(); tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { CHECK(0, "bad shape %s", tok); continue; } - snprintf(shape_names[ns], sizeof shape_names[ns], "%ux%ux%u", m, k, n); - const size_t na = (size_t)m * k, nbb = (size_t)k * n, cnt = (size_t)m * n; - uint16_t *a = malloc(na * 2), *an = malloc(na * 2), *b = malloc(nbb * 2); - double *acc = malloc(cnt * 8), *sc = malloc(cnt * 8); - float *pos0 = malloc(cnt * 4), *neg0 = malloc(cnt * 4), *tmp[2] = { malloc(cnt * 4), malloc(cnt * 4) }, *base_pos = malloc(cnt * 4); - if (!a || !an || !b || !acc || !sc || !pos0 || !neg0 || !tmp[0] || !tmp[1] || !base_pos) { CHECK(0, "host memory for %s", tok); break; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill_bf16(a, na, &seed); fill_bf16(b, nbb, &seed); - for (size_t i = 0; i < na; i++) an[i] = a[i] ^ 0x8000u; - uint32_t rt, ct; omega_matmul_frag_block_shape((m + 15u) / 16u, (n + 7u) / 8u, &rt, &ct); - const double flop = 2.0 * m * k * n; - if (reference(m, k, n, a, b, threads, acc, sc) != 0) { CHECK(0, "reference %s: host memory", tok); break; } - if (!controls_done && m == 8192 && n == 768 && k == 768) { - if (out) { fprintf(out, "%s{\"control\":true,", first_run ? "" : ","); first_run = 0; } - comparator_controls(m, n, acc, sc, shape_names[ns], out); - if (out) fprintf(out, "\"pass\":%s}", g_failed ? "false" : "true"); - controls_done = 1; - } - OmegaGpuTensor *t = NULL; - int urc = omega_gpu_tensor_upload_bf16(k, n, b, &t); - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %s rc=%s (%s)", tok, omega_gpu_matmul_rc_name(urc), omega_gpu_matmul_last_error()); - if (urc != OMEGA_GPU_MATMUL_OK) break; - float *prev = NULL; - for (unsigned bi = 0; bi < nb; bi++) { - omega_gpu_matmul_set_cta_budget(budgets[bi]); - const unsigned calls = 2u * repeats; - uint64_t chip[64], call[64]; int rcs_ok = 1, hit_after_first = 1; - size_t rep_diff = 0, stale_total = 0, stale_max = 0; - Cmp cp = { 0, 0, 0 }, cn = { 0, 0, 0 }; - OmegaGpuMatmulInfo info; memset(&info, 0, sizeof info); - for (unsigned ci = 0; ci < calls && ci < 64; ci++) { - const int neg = (ci % 2u) == 0, rep = (int)(ci / 2u); - float *dst = rep == 0 ? (neg ? neg0 : pos0) : tmp[ci % 2u]; - for (size_t i = 0; i < cnt; i++) dst[i] = bitsf(NAN_FILL); - int rc = omega_gpu_matmul_resident_bf16(m, neg ? an : a, t, dst, &info); - chip[ci] = info.elapsed_ns; call[ci] = info.call_ns; - if (rc != OMEGA_GPU_MATMUL_OK) { - rcs_ok = 0; - CHECK(0, "%s budget %u call %u rc=%s (%s)", tok, budgets[bi], ci, omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - break; - } - if (ci > 0 && !info.kernel_cache_hit) hit_after_first = 0; - if (prev) { size_t s = count_stale(cnt, dst, prev); stale_total += s; if (s > stale_max) stale_max = s; } - if (rep == 0) { - if (neg) cn = compare_full(cnt, dst, acc, sc, -1.0); else cp = compare_full(cnt, dst, acc, sc, 1.0); - } else rep_diff += count_bit_diff(cnt, dst, neg ? neg0 : pos0); - prev = dst; - } - const unsigned done = rcs_ok ? calls : 0; - uint64_t chip_s[64], call_s[64]; - memcpy(chip_s, chip, sizeof chip); memcpy(call_s, call, sizeof call); - const uint64_t chip_med = done ? median_u64(chip_s, done) : 0, call_med = done ? median_u64(call_s, done) : 0; - const size_t neg_exact = rcs_ok ? count_not_negation(cnt, pos0, neg0) : cnt; - size_t cross = 0; - if (rcs_ok) { if (bi == 0) memcpy(base_pos, pos0, cnt * 4); else cross = count_bit_diff(cnt, pos0, base_pos); } - char dig[17] = "-"; - if (rcs_ok) digest16(pos0, cnt, dig); - const uint32_t ctas = info.grid_x * info.grid_y; - const int pass = rcs_ok && cp.mismatches == 0 && cn.mismatches == 0 && rep_diff == 0 && stale_total == 0; - CHECK(pass, "%s budget %u: rc_ok=%d pos_mism=%zu neg_mism=%zu repeat_diff=%zu stale=%zu", tok, budgets[bi], rcs_ok, cp.mismatches, cn.mismatches, rep_diff, stale_total); - cells[ns][bi].pass = pass; cells[ns][bi].chip_med_ns = chip_med; - const double tflops = chip_med ? flop / (double)chip_med / 1e3 : 0.0; - printf("%s %s budget=%u grid=%ux%u ctas=%u launches=%u rt=%u ct=%u i42_regime=%d chip_med_ms=%.3f call_med_ms=%.3f tflops_chip=%.3f " - "elements=%zu pos_mism=%zu neg_mism=%zu max_rel=%.3g repeat_bitdiff=%zu stale=%zu neg_exact_diff=%zu vs_first_budget_bitdiff=%zu sha=%s cache_hit=%d\n", - pass ? "PASS" : "FAIL", tok, budgets[bi], info.grid_x, info.grid_y, ctas, info.chip_calls, rt, ct, ctas >= 128, - chip_med / 1e6, call_med / 1e6, tflops, cnt, cp.mismatches, cn.mismatches, cp.max_rel > cn.max_rel ? cp.max_rel : cn.max_rel, - rep_diff, stale_total, neg_exact, cross, dig, hit_after_first); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"budget\":%u,\"pass\":%s,\"grid_x\":%u,\"grid_y\":%u,\"ctas_per_launch\":%u,\"launches\":%u," - "\"rt\":%u,\"ct\":%u,\"single_tile_kernel\":%s,\"i42_regime\":%s,\"calls\":%u,\"elements_per_call\":%zu," - "\"pos_mismatches\":%zu,\"neg_mismatches\":%zu,\"nonfinite\":%zu,\"max_rel\":%.4g,\"repeat_bitdiff\":%zu," - "\"stale_elements\":%zu,\"stale_max_per_call\":%zu,\"neg_exact_negation_diff\":%zu,\"vs_first_budget_bitdiff\":%zu," - "\"pos_output_sha256_16\":\"%s\",\"cache_hit_after_first\":%s,\"chip_median_ns\":%" PRIu64 ",\"call_median_ns\":%" PRIu64 ",\"tflops_chip\":%.4f,\"chip_ns\":[", - first_run ? "" : ",", m, k, n, budgets[bi], pass ? "true" : "false", info.grid_x, info.grid_y, ctas, info.chip_calls, - rt, ct, rt == 1 && ct == 1 ? "true" : "false", ctas >= 128 ? "true" : "false", done, cnt, - cp.mismatches, cn.mismatches, cp.nonfinite + cn.nonfinite, cp.max_rel > cn.max_rel ? cp.max_rel : cn.max_rel, rep_diff, - stale_total, stale_max, neg_exact, cross, dig, hit_after_first ? "true" : "false", chip_med, call_med, tflops); - for (unsigned ci = 0; ci < done; ci++) fprintf(out, "%s%" PRIu64, ci ? "," : "", chip[ci]); - fprintf(out, "],\"call_ns\":["); - for (unsigned ci = 0; ci < done; ci++) fprintf(out, "%s%" PRIu64, ci ? "," : "", call[ci]); - fprintf(out, "]}"); - first_run = 0; - } - fflush(stdout); - if (omega_gpu_matmul_is_blocked()) break; - } - /* negative control on the chip: the mutant kernel at the largest budget must be flagged */ - if (!mutant_done && m == 8192 && k == 768 && n == 768 && !omega_gpu_matmul_is_blocked()) { - omega_gpu_matmul_set_cta_budget(budgets[nb - 1]); - omega_gpu_matmul_test_set_mutant(1); - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_bf16(m, a, t, pos0, &info); - Cmp mc = rc == OMEGA_GPU_MATMUL_OK ? compare_full(cnt, pos0, acc, sc, 1.0) : (Cmp){ 0, 0, 0 }; - omega_gpu_matmul_test_set_mutant(0); - const int caught = rc != OMEGA_GPU_MATMUL_OK || mc.mismatches > 0; - CHECK(caught, "mutant at budget %u NOT caught by the full comparison", budgets[nb - 1]); - printf("%s mutant control %s budget=%u rc=%s flagged=%zu of %zu\n", caught ? "KILLED" : "SURVIVED", tok, budgets[nb - 1], omega_gpu_matmul_rc_name(rc), mc.mismatches, cnt); - if (out) { fprintf(out, ",{\"mutant_control\":true,\"m\":%u,\"k\":%u,\"n\":%u,\"budget\":%u,\"rc\":\"%s\",\"flagged\":%zu,\"elements\":%zu,\"killed\":%s}", - m, k, n, budgets[nb - 1], omega_gpu_matmul_rc_name(rc), mc.mismatches, cnt, caught ? "true" : "false"); } - mutant_done = 1; - } - omega_gpu_tensor_free(t); - free(a); free(an); free(b); free(acc); free(sc); free(pos0); free(neg0); free(tmp[0]); free(tmp[1]); free(base_pos); - ns++; - } - free(copy); - omega_gpu_matmul_set_cta_budget(0); - CHECK(controls_done && mutant_done, "negative controls ran (comparator %d, mutant %d)", controls_done, mutant_done); - /* best sealed budget: every shape PASS, least summed median chip time over every shape in the run (the default - * list is the five training shapes plus 1x2048x8192 and 112x768x3072) */ - int best = -1; uint64_t best_sum = 0; - if (out) fprintf(out, "],\"budget_summary\":["); - for (unsigned bi = 0; bi < nb; bi++) { - int all = ns > 0; uint64_t sum = 0; - for (unsigned s = 0; s < ns; s++) { all &= cells[s][bi].pass; sum += cells[s][bi].chip_med_ns; } - printf("budget %u: %s, summed median chip %.3f ms over %u shapes\n", budgets[bi], all ? "SEALED" : "NOT SEALED", sum / 1e6, ns); - if (out) fprintf(out, "%s{\"budget\":%u,\"sealed\":%s,\"sum_chip_median_ns\":%" PRIu64 "}", bi ? "," : "", budgets[bi], all ? "true" : "false", sum); - if (all && (best < 0 || sum < best_sum)) { best = (int)bi; best_sum = sum; } - } - const int ok = g_failed == 0 && best >= 0 && !omega_gpu_matmul_is_blocked(); - printf("best sealed budget: %d\n%s: %d checks, %d failed\n", best >= 0 ? (int)budgets[best] : -1, ok ? "PASS" : "FAIL", g_checks, g_failed); - if (out) { - fprintf(out, "],\"best_sealed_budget\":%d,\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", best >= 0 ? (int)budgets[best] : -1, - omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, ok ? "OMEGA_GPU_MATMUL_R4_SEALED" : "OMEGA_GPU_MATMUL_R4_FAIL"); - fclose(out); - } - return ok ? 0 : 1; -} diff --git a/tests/gpu_moe_window_test.c b/tests/gpu_moe_window_test.c deleted file mode 100644 index 27c9d50da..000000000 --- a/tests/gpu_moe_window_test.c +++ /dev/null @@ -1,283 +0,0 @@ -/* gpu_moe_window_test: OWN-30B cut 2 gate for omega_gpu_moe_api (column windows over a resident tensor). - * - * ./gpu_moe_window_test --host-only argument refusals (alignment rule fail-closed) and the packed - * window byte rule (a window's bytes in the packed tensor equal - * the pack of the sub-matrix; one tile of skew differs); no chip - * ./gpu_moe_window_test --out receipt.json chip gate: for every case the window result equals the - * whole-tensor (omega_gpu_matmul_resident_*) columns bit for bit - * and the double oracle; repeat call is a cache hit and identical; - * the multi-window call equals the single windows; negative - * controls (wrong window by one tile, wrong kernel) are caught; - * timing of 8 expert windows per call (the Stage A decode shape) - * ./gpu_moe_window_test --cta-budget N --spin-us N --calls N --small (knobs; --small skips the 128-expert tensors) - */ -#include "omega_gpu_moe_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static void fill(float *a, size_t n, uint32_t *seed) { for (size_t i = 0; i < n; i++) a[i] = ((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f; } -static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } -static int cmp_double(const void *x, const void *y) { double a = *(const double *)x, b = *(const double *)y; return a < b ? -1 : a > b; } - -/* double oracle of the window: error relative to the accumulation scale, count at or beyond 1e-5 */ -static double window_oracle(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, uint32_t col0, uint32_t cols, const float *c, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - for (size_t i = 0; i < m; i++) for (size_t j = 0; j < cols; j++) { - double acc = 0.0, scale = 0.0; - for (size_t t = 0; t < k; t++) { double p = (double)bf2f(a[i * k + t]) * (double)bf2f(b[t * n + col0 + j]); acc += p; scale += fabs(p); } - double rel = fabs(acc - (double)c[i * cols + j]) / (scale > 1e-6 ? scale : 1e-6); - if (rel > worst) worst = rel; - if (rel >= 1e-5) nbad++; - } - if (bad) *bad = nbad; - return worst; -} - -/* ------------------------------------------------------------------ host only */ -static void host_only(void) { - /* the packed window byte rule: for a tile-aligned col0, the bytes of the packed tensor from - * omega_gpu_moe_window_byte_offset(kp, col0) are the pack of B[:, col0 .. col0 + wnp); moving one - * tile (the wrong-window control) changes them */ - struct { uint32_t k, n, col0, cols; } sh[] = { { 48, 1000, 8, 13 }, { 48, 1000, 792, 200 }, { 2048, 6144, 1536, 1536 }, { 768, 8192, 6144, 2048 }, { 40, 24, 16, 8 } }; - for (size_t s = 0; s < sizeof sh / sizeof sh[0]; s++) { - const uint32_t k = sh[s].k, n = sh[s].n, col0 = sh[s].col0, cols = sh[s].cols; - const uint32_t kp = (k + 15) / 16 * 16, np = (n + 7) / 8 * 8, NT = np / 8, wnp = (cols + 7) / 8 * 8, WT = wnp / 8; - uint16_t *b = malloc((size_t)k * n * 2), *full = malloc((size_t)kp * np * 2), *win = malloc((size_t)kp * wnp * 2), *sub = malloc((size_t)k * wnp * 2); - uint32_t seed = 11 + (uint32_t)s; - for (size_t i = 0; i < (size_t)k * n; i++) b[i] = (uint16_t)(1 + lcg(&seed) % 60000); - omega_matmul_frag_pack_b(b, k, n, kp, 0, NT, full); - /* the sub-matrix B[:, col0 .. col0 + real) where real = min(wnp, n - col0): past the real columns the - * tensor's padding is zero, which the sub-matrix pack reproduces by having only `real` columns */ - const uint32_t real = n - col0 < wnp ? n - col0 : wnp; - for (uint32_t r = 0; r < k; r++) for (uint32_t j = 0; j < real; j++) sub[(size_t)r * real + j] = b[(size_t)r * n + col0 + j]; - omega_matmul_frag_pack_b(sub, k, real, kp, 0, WT, win); - const uint64_t off = omega_gpu_moe_window_byte_offset(kp, col0); - CHECK(off == (uint64_t)(col0 / 8) * kp * 8 * 2, "offset arithmetic k=%u col0=%u", k, col0); - CHECK(memcmp((const uint8_t *)full + off, win, (size_t)kp * wnp * 2) == 0, "window bytes k=%u n=%u col0=%u cols=%u equal the sub-matrix pack", k, n, col0, cols); - /* wrong window: one tile of skew (either way) must differ */ - int differs = 1; - if (col0 / 8 + 1 + WT <= NT) differs = memcmp((const uint8_t *)full + off + (size_t)kp * 8 * 2, win, (size_t)kp * wnp * 2) != 0; - else differs = memcmp((const uint8_t *)full + off - (size_t)kp * 8 * 2, win, (size_t)kp * wnp * 2) != 0; - CHECK(differs, "window bytes k=%u col0=%u: one tile of skew differs (wrong-window control)", k, col0); - free(b); free(full); free(win); free(sub); - } - /* refusals: nothing below opens the device (the alignment rule is checked before the lock) */ - float a[64] = { 0 }, c[64]; - uint32_t col0s[2] = { 0, 8 }; - CHECK(omega_gpu_matmul_resident_window_f32(1, NULL, NULL, 0, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "NULL a / tensor refused"); - CHECK(omega_gpu_matmul_resident_window_f32(0, a, NULL, 0, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "m = 0 refused"); - CHECK(omega_gpu_matmul_resident_windows_f32(1, a, NULL, 0, col0s, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "nwin = 0 refused"); - CHECK(omega_gpu_moe_tensor_upload_bf16(0, 8, (const uint16_t *)a, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "upload k = 0 / NULL out refused"); - OmegaGpuMoeTensor *t = NULL; - CHECK(omega_gpu_moe_tensor_upload_bf16(16, OMEGA_BW_MATMUL_MAX_N + 8, (const uint16_t *)a, &t) == OMEGA_GPU_MATMUL_TOO_LARGE && t == NULL, "upload n past the envelope refused"); - CHECK(omega_gpu_moe_reserve(0, 16, 16, 0) == OMEGA_GPU_MATMUL_BAD_ARGS, "reserve zero bound refused"); - CHECK(omega_gpu_moe_prepare(1, 16, OMEGA_BW_MATMUL_MAX_N + 8) == OMEGA_GPU_MATMUL_TOO_LARGE, "prepare past the envelope refused"); - uint32_t kk, nn; omega_gpu_moe_tensor_shape(NULL, &kk, &nn); - CHECK(kk == 0 && nn == 0, "shape of NULL is 0 x 0"); - omega_gpu_moe_tensor_free(NULL); - printf("host-only: alignment refusals that need a tensor (col0 %% 8, window past n) run in the chip gate\n"); -} - -/* ------------------------------------------------------------------ chip */ -typedef struct { uint32_t k, n, m, cols, nwin; const char *name; int big; } Case; - -static int chip(const char *out_path, int calls, int small) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MOE_WINDOW_V1\",\"cta_budget\":%u,\"spin_us\":%u,\"calls\":%d,\"cases\":[", - omega_gpu_moe_cta_budget(), omega_gpu_session_spin_us(), calls); - const Case cases[] = { - { 48, 1000, 1, 13, 3, "small_m1_unaligned_cols", 0 }, - { 48, 1000, 5, 200, 2, "small_m5", 0 }, - { 2048, 1536 * 16, 1, 1536, 8, "gate_up_16_experts", 0 }, - { 2048, 1536 * 128, 1, 1536, 8, "gate_up_128_experts", 1 }, - { 768, 2048 * 128, 1, 2048, 8, "down_128_experts", 1 }, - { 2048, 1536 * 16, 16, 1536, 8, "gate_up_16_experts_m16", 0 }, - /* one variable: the same 1536-wide window on a standalone one-expert tensor (one spare tile so the - * skew control stays inside the allocation); compares against the window inside the 16/128-expert tensors */ - { 2048, 1536 + 8, 1, 1536, 1, "gate_up_1_expert_standalone", 0 }, - { 768, 2048 + 8, 1, 2048, 1, "down_1_expert_standalone", 0 }, - }; - int first = 1; - for (size_t ci = 0; ci < sizeof cases / sizeof cases[0]; ci++) { - const Case *cs = &cases[ci]; - if (small && cs->big) continue; - const uint32_t k = cs->k, n = cs->n, m = cs->m, cols = cs->cols, nwin = cs->nwin; - const uint32_t kp = (k + 15) / 16 * 16, wnp = (cols + 7) / 8 * 8; - printf("== %s: k=%u n=%u m=%u cols=%u windows=%u\n", cs->name, k, n, m, cols, nwin); - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n, nw = (size_t)m * cols; - float *a = malloc(na * 4), *whole = malloc(nc * 4), *cw = malloc(nw * 4), *cw2 = malloc(nw * 4), *multi = malloc(nw * 4 * nwin); - uint16_t *ah = malloc(na * 2), *bh = malloc(nb * 2); - if (!a || !whole || !cw || !cw2 || !multi || !ah || !bh) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x30b0000u ^ (k << 8) ^ n ^ m; - fill(a, na, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - { float *bt = malloc((size_t)1 << 20); size_t done = 0; /* bf16 B in 256K-element chunks, no k x n f32 copy */ - while (done < nb) { size_t c = nb - done < (1u << 18) ? nb - done : (1u << 18); fill(bt, c, &seed); for (size_t i = 0; i < c; i++) bh[done + i] = omega_fp32_to_bf16(bt[i]); done += c; } - free(bt); } - /* the 8 windows: distinct tile-aligned expert slots, never the last tile (the skew control moves one tile up) */ - uint32_t col0[8]; const uint32_t slots = n / cols; - for (uint32_t w = 0; w < nwin; w++) { uint32_t s; int dup; do { s = lcg(&seed) % (slots > 1 ? slots - 1 : 1); dup = 0; for (uint32_t v = 0; v < w; v++) if (col0[v] == s * cols) dup = 1; } while (dup); col0[w] = s * cols; } - if (cs->cols == 13) { col0[0] = 8; col0[1] = 16; col0[2] = 976; } /* 976 + 13 = 989 < 1000, inside the real columns */ - if (cs->cols == 200) { col0[0] = 792; col0[1] = 0; } /* 792 + 200 = 992 */ - - OmegaGpuTensor *tc = NULL; OmegaGpuMoeTensor *tm = NULL; - double t0 = now_ms(); - int rc1 = omega_gpu_tensor_upload_bf16(k, n, bh, &tc); - double up_classic = now_ms() - t0; t0 = now_ms(); - int rc2 = omega_gpu_moe_tensor_upload_bf16(k, n, bh, &tm); - double up_moe = now_ms() - t0; - CHECK(rc1 == OMEGA_GPU_MATMUL_OK && rc2 == OMEGA_GPU_MATMUL_OK, "%s: uploads (classic %s, moe %s)", cs->name, omega_gpu_matmul_rc_name(rc1), omega_gpu_matmul_rc_name(rc2)); - printf(" upload classic %.0f ms, moe %.0f ms (%zu MB bf16)\n", up_classic, up_moe, nb * 2 / (1u << 20)); - if (rc1 != OMEGA_GPU_MATMUL_OK || rc2 != OMEGA_GPU_MATMUL_OK) break; - - /* alignment rule, fail-closed, with the tensor present */ - OmegaGpuMatmulInfo info; - int rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, 4, 8, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS && strstr(omega_gpu_matmul_last_error(), "not a multiple of 8"), "%s: col0 = 4 refused (%s: %s)", cs->name, omega_gpu_matmul_rc_name(rr), omega_gpu_matmul_last_error()); - rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, (n - 8) / 8 * 8, 16, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS && strstr(omega_gpu_matmul_last_error(), "not inside"), "%s: window past n refused (%s: %s)", cs->name, omega_gpu_matmul_rc_name(rr), omega_gpu_matmul_last_error()); - rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, 0, 0, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS, "%s: cols = 0 refused (%s)", cs->name, omega_gpu_matmul_rc_name(rr)); - - /* whole-tensor product through the existing API (the reference the window must match column for column) */ - OmegaGpuMatmulInfo wi; - int wrc = omega_gpu_matmul_resident_bf16(m, ah, tc, whole, &wi); - CHECK(wrc == OMEGA_GPU_MATMUL_OK, "%s: whole-tensor call rc=%s (%s)", cs->name, omega_gpu_matmul_rc_name(wrc), omega_gpu_matmul_last_error()); - if (wrc != OMEGA_GPU_MATMUL_OK) break; - printf(" whole: %.3f ms call, chip %.3f ms, grid %ux%u\n", wi.call_ns / 1e6, wi.elapsed_ns / 1e6, wi.grid_x, wi.grid_y); - - size_t mism_total = 0, oracle_bad_total = 0; double oracle_worst = 0.0; int all_hit = 1, f32_same = 1; double win_chip_ms = 0.0; - for (uint32_t w = 0; w < nwin; w++) { - OmegaGpuMatmulInfo i1, i2, i3; - int r1 = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[w], cols, cw, &i1); - CHECK(r1 == OMEGA_GPU_MATMUL_OK && i1.n == cols && i1.padded_n == wnp && i1.resident, "%s: window %u (col0 %u) rc=%s (%s)", cs->name, w, col0[w], omega_gpu_matmul_rc_name(r1), omega_gpu_matmul_last_error()); - if (r1 != OMEGA_GPU_MATMUL_OK) break; - size_t mism = 0; - for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) if (cw[(size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) mism++; - mism_total += mism; - size_t bad = 0; double worst = window_oracle(m, k, n, ah, bh, col0[w], cols, cw, &bad); - oracle_bad_total += bad; if (worst > oracle_worst) oracle_worst = worst; - /* repeat: cache hit, bit-identical; f32 activation path: identical too (same bf16 rounding) */ - int r2 = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[w], cols, cw2, &i2); - int r3 = omega_gpu_matmul_resident_window_f32(m, a, tm, col0[w], cols, multi, &i3); - if (!(r2 == OMEGA_GPU_MATMUL_OK && i2.kernel_cache_hit && memcmp(cw, cw2, nw * 4) == 0)) all_hit = 0; - if (!(r3 == OMEGA_GPU_MATMUL_OK && memcmp(cw, multi, nw * 4) == 0)) f32_same = 0; - win_chip_ms += i1.elapsed_ns / 1e6; - printf(" window %u col0=%u: mismatches vs whole %zu/%zu, oracle worst %.2e bad %zu, chip %.3f ms, grid %ux%u, hit=%d\n", - w, col0[w], mism, nw, worst, bad, i1.elapsed_ns / 1e6, i1.grid_x, i1.grid_y, (int)i2.kernel_cache_hit); - if (omega_gpu_matmul_is_blocked()) break; - } - CHECK(mism_total == 0, "%s: every window equals the whole-tensor columns bit for bit (%zu mismatches)", cs->name, mism_total); - CHECK(oracle_bad_total == 0, "%s: every window within 1e-5 of the double oracle (worst %g, %zu bad)", cs->name, oracle_worst, oracle_bad_total); - CHECK(all_hit, "%s: repeated window calls hit the kernel cache and are bit-identical", cs->name); - CHECK(f32_same, "%s: f32 activation path is bit-identical to the bf16 one", cs->name); - if (omega_gpu_matmul_is_blocked()) break; - - /* the multi-window call (one activation pack, nwin launches) equals the single windows */ - OmegaGpuMatmulInfo mi; - int mrc = omega_gpu_matmul_resident_windows_f32(m, a, tm, nwin, col0, cols, multi, &mi); - size_t mm = 0; - if (mrc == OMEGA_GPU_MATMUL_OK) for (uint32_t w = 0; w < nwin; w++) for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) - if (multi[(size_t)w * nw + (size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) mm++; - CHECK(mrc == OMEGA_GPU_MATMUL_OK && mi.chip_calls == nwin && mm == 0, "%s: multi-window call rc=%s launches=%u mismatches=%zu", cs->name, omega_gpu_matmul_rc_name(mrc), mi.chip_calls, mm); - - /* negative control 1: the wrong window (one tile up) must disagree with the whole-tensor columns */ - omega_gpu_moe_test_set_window_skew(1); - int src = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[0], cols, cw, &info); - size_t skew_mism = 0; - for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) if (cw[(size_t)r * cols + j] != whole[(size_t)r * n + col0[0] + j]) skew_mism++; - omega_gpu_moe_test_set_window_skew(0); - CHECK(src == OMEGA_GPU_MATMUL_OK && skew_mism > nw / 2, "%s: wrong-window control caught (rc=%s, %zu/%zu differ)", cs->name, omega_gpu_matmul_rc_name(src), skew_mism, nw); - /* negative control 2: the wrong kernel (last K pass dropped) must fail the oracle */ - omega_gpu_moe_test_set_mutant(1); - int mut = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[0], cols, cw, &info); - size_t mut_bad = 0; double mut_worst = mut == OMEGA_GPU_MATMUL_OK ? window_oracle(m, k, n, ah, bh, col0[0], cols, cw, &mut_bad) : 0.0; - omega_gpu_moe_test_set_mutant(0); - CHECK(mut == OMEGA_GPU_MATMUL_OK && mut_bad > 0, "%s: wrong-kernel control caught (rc=%s, worst %g, %zu bad)", cs->name, omega_gpu_matmul_rc_name(mut), mut_worst, mut_bad); - if (omega_gpu_matmul_is_blocked()) break; - - /* timing: `calls` multi-window calls (the per-token expert pattern) and `calls` single-window calls */ - double *sm = malloc((size_t)calls * sizeof *sm), *ss = malloc((size_t)calls * sizeof *ss); - uint64_t chip_multi = 0, chip_single = 0; int ok_m = 0, ok_s = 0; size_t rep_mism = 0; - for (int i = 0; i < calls; i++) { - double q0 = now_ms(); - int r = omega_gpu_matmul_resident_windows_f32(m, a, tm, nwin, col0, cols, multi, &mi); - sm[i] = now_ms() - q0; - if (r == OMEGA_GPU_MATMUL_OK) { ok_m++; chip_multi += mi.elapsed_ns; } - if (omega_gpu_matmul_is_blocked()) break; - } - for (uint32_t w = 0; w < nwin; w++) for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) - if (multi[(size_t)w * nw + (size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) rep_mism++; - for (int i = 0; i < calls && !omega_gpu_matmul_is_blocked(); i++) { - double q0 = now_ms(); - int r = omega_gpu_matmul_resident_window_f32(m, a, tm, col0[i % nwin], cols, cw, &info); - ss[i] = now_ms() - q0; - if (r == OMEGA_GPU_MATMUL_OK) { ok_s++; chip_single += info.elapsed_ns; } - } - qsort(sm, (size_t)calls, sizeof *sm, cmp_double); qsort(ss, (size_t)calls, sizeof *ss, cmp_double); - const double med_m = sm[calls / 2], med_s = ss[calls / 2]; - const double bytes_win = (double)kp * wnp * 2.0; - const double gbs_multi = bytes_win * nwin / (med_m * 1e-3) / 1e9, gbs_single = bytes_win / (med_s * 1e-3) / 1e9; - CHECK(ok_m == calls && ok_s == calls && rep_mism == 0, "%s: timing calls ok %d/%d multi, %d/%d single, last multi result mismatches %zu", cs->name, ok_m, calls, ok_s, calls, rep_mism); - printf(" timing: %u windows/call median %.3f ms (%.1f us/window, chip mean %.1f us/window, %.1f GB/s); single window median %.3f ms (%.1f GB/s, chip mean %.1f us); %.2f MB per window\n", - nwin, med_m, med_m * 1e3 / nwin, ok_m ? chip_multi / 1e3 / ok_m / nwin : 0.0, gbs_multi, med_s, gbs_single, ok_s ? chip_single / 1e3 / ok_s : 0.0, bytes_win / 1e6); - if (out) { - fprintf(out, "%s{\"case\":\"%s\",\"k\":%u,\"n\":%u,\"m\":%u,\"cols\":%u,\"padded_cols\":%u,\"windows\":%u,\"col0\":[", first ? "" : ",", cs->name, k, n, m, cols, wnp, nwin); - for (uint32_t w = 0; w < nwin; w++) fprintf(out, "%s%u", w ? "," : "", col0[w]); - fprintf(out, "],\"upload_classic_ms\":%.1f,\"upload_moe_ms\":%.1f,\"whole_call_ms\":%.4f,\"whole_chip_ms\":%.4f," - "\"window_mismatches_vs_whole\":%zu,\"oracle_worst_rel\":%g,\"oracle_bad\":%zu,\"repeat_cache_hit_identical\":%s,\"f32_path_identical\":%s," - "\"multi_rc\":\"%s\",\"multi_mismatches\":%zu,\"skew_control_differ\":%zu,\"skew_control_elems\":%zu,\"mutant_control_bad\":%zu,\"mutant_control_worst\":%g," - "\"calls\":%d,\"multi_median_ms\":%.4f,\"multi_p90_ms\":%.4f,\"multi_min_ms\":%.4f,\"multi_chip_us_per_window\":%.2f,\"multi_gbs\":%.1f," - "\"single_median_ms\":%.4f,\"single_p90_ms\":%.4f,\"single_min_ms\":%.4f,\"single_chip_us\":%.2f,\"single_gbs\":%.1f,\"bytes_per_window\":%.0f,\"grid_x\":%u,\"grid_y\":%u}", - up_classic, up_moe, wi.call_ns / 1e6, wi.elapsed_ns / 1e6, - mism_total, oracle_worst, oracle_bad_total, all_hit ? "true" : "false", f32_same ? "true" : "false", - omega_gpu_matmul_rc_name(mrc), mm, skew_mism, nw, mut_bad, mut_worst, - calls, med_m, sm[calls * 9 / 10], sm[0], ok_m ? chip_multi / 1e3 / ok_m / nwin : 0.0, gbs_multi, - med_s, ss[calls * 9 / 10], ss[0], ok_s ? chip_single / 1e3 / ok_s : 0.0, gbs_single, bytes_win, info.grid_x, info.grid_y); - first = 0; - } - free(sm); free(ss); - omega_gpu_tensor_free(tc); omega_gpu_moe_tensor_free(tm); - free(a); free(whole); free(cw); free(cw2); free(multi); free(ah); free(bh); - if (omega_gpu_matmul_is_blocked()) break; - } - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_MOE_WINDOW_PASS" : "OMEGA_GPU_MOE_WINDOW_FAIL"); - fclose(out); - } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, calls = 100, small = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--small") == 0) small = 1; - else if (strcmp(argv[i], "--calls") == 0 && i + 1 < argc) calls = atoi(argv[++i]); - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) { uint32_t b = (uint32_t)strtoul(argv[++i], NULL, 10); omega_gpu_moe_set_cta_budget(b); omega_gpu_matmul_set_cta_budget(b); } - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) { if (omega_gpu_session_set_spin_us((uint32_t)strtoul(argv[++i], NULL, 10)) != 0) { fprintf(stderr, "--spin-us out of range\n"); return 2; } } - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - if (calls < 2) calls = 2; - int rc = 0; - if (host) host_only(); - else rc = chip(out_path, calls, small); - if (!omega_gpu_matmul_is_blocked()) omega_gpu_device_close(); - if (rc) return 2; - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_pf_mem_test.c b/tests/gpu_pf_mem_test.c deleted file mode 100644 index dd8fe1206..000000000 --- a/tests/gpu_pf_mem_test.c +++ /dev/null @@ -1,106 +0,0 @@ -/* gpu_pf_mem_test.c (OWN-30B T3b, 2026-10-13): device-resident prefill memory. - * --host-only the copy kernel in the warp simulator (exact copy, nothing past `units` written) - * (default) the chip (caller holds flock /tmp/aien-gb10.lock): - * 1. upload/download round trip of 96 MB through a GPU-cached device buffer (bit-exact; the host buffer is poisoned - * first, so a download that did not run is caught), and a second upload over the same buffer read back exactly - * (a stale L2 line would show here: the GPU rewrote lines it had cached); - * 2. read bandwidth, uncached (session buffer) vs cached (device buffer): every CTA distinct (DRAM) and every CTA the - * same bytes (cache reuse), 5 runs each, median; every XOR result checked. - * Verdict line last: "GPU_PF_MEM: PASS|FAIL". */ -#include "omega_gpu_prefill.h" -#include "omega_blackwell_codegen_pf.h" -#include "omega_blackwell_codegen_tc.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int host_only(void) { - static BlackwellIRProgram p; - if (omega_blackwell_codegen_pf_copy_prog(&p) != 0) { printf("copy codegen refused\n"); return 1; } - enum { U = 1000, CAP = 1100 }; - static uint32_t src[CAP * 4], dst[CAP * 4]; - for (int i = 0; i < CAP * 4; i++) { src[i] = 0x9e3779b9u * (uint32_t)i; dst[i] = 0xdeadbeefu; } - static WsSim s; memset(&s, 0, sizeof s); s.p = &p; s.threads = OMEGA_PF_COPY_THREADS; - uint64_t d = (uintptr_t)dst, sv = (uintptr_t)src; - s.cbank[0x380 / 4] = (uint32_t)d; s.cbank[0x384 / 4] = (uint32_t)(d >> 32); s.cbank[0x388 / 4] = (uint32_t)sv; s.cbank[0x38c / 4] = (uint32_t)(sv >> 32); s.cbank[0x390 / 4] = U; - s.ranges[0].lo = d; s.ranges[0].hi = d + sizeof dst; s.ranges[1].lo = sv; s.ranges[1].hi = sv + sizeof src; s.nranges = 2; - int err = ws_run(&s, (U + OMEGA_PF_COPY_THREADS - 1) / OMEGA_PF_COPY_THREADS, 1); - size_t bad = 0, past = 0; - for (int i = 0; i < CAP * 4; i++) { if (i < U * 4 && dst[i] != src[i]) bad++; if (i >= U * 4 && dst[i] != 0xdeadbeefu) past++; } - printf("sim copy: %s, peak %u registers, %zu wrong, %zu written past the end\n", err ? s.msg : "ran", p.regalloc.peak_gpr_usage, bad, past); - return (err || bad || past) ? 1 : 0; -} - -typedef struct { uint32_t iters, groups, threads; } BwSpec; -static int gen_bw(const OmegaPfKey *k, void *prog) { return omega_blackwell_codegen_tc_bw_prog(k->words[0], k->words[1], k->words[2], prog); } - -int main(int argc, char **argv) { - int fail = host_only(); - if (argc > 1 && !strcmp(argv[1], "--host-only")) { printf("GPU_PF_MEM: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - if (fail) { printf("GPU_PF_MEM: FAIL\n"); return 1; } - - /* 1. round trip */ - const size_t RB = 96ull << 20; - uint32_t *a = malloc(RB), *b = malloc(RB); - if (!a || !b) return 1; - for (size_t i = 0; i < RB / 4; i++) a[i] = (uint32_t)(i * 2654435761u) ^ 0x5bd1e995u; - OmegaGpuMem dev; - int rc = omega_gpu_pf_alloc_dev(RB, &dev); - if (rc) { printf("alloc_dev: %s (%s)\n", omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); printf("GPU_PF_MEM: FAIL\n"); return 1; } - memset(b, 0xa5, RB); - rc = omega_gpu_pf_upload(&dev, 0, a, RB); - if (!rc) rc = omega_gpu_pf_download(&dev, 0, b, RB); - size_t bad = 0; for (size_t i = 0; i < RB / 4; i++) if (a[i] != b[i]) bad++; - printf("round trip 1 (%zu MB, cached device buffer): rc %s, %zu wrong words\n", RB >> 20, omega_gpu_pf_rc_name(rc), bad); - if (rc || bad) fail++; - for (size_t i = 0; i < RB / 4; i++) a[i] = ~a[i] + (uint32_t)i; - memset(b, 0x5a, RB); - rc = omega_gpu_pf_upload(&dev, 0, a, RB); - if (!rc) rc = omega_gpu_pf_download(&dev, 0, b, RB); - bad = 0; for (size_t i = 0; i < RB / 4; i++) if (a[i] != b[i]) bad++; - printf("round trip 2 (rewritten by the GPU over cached lines): rc %s, %zu wrong words\n", omega_gpu_pf_rc_name(rc), bad); - if (rc || bad) fail++; - omega_gpu_pf_free(&dev); - - /* 2. bandwidth: uncached vs cached, distinct vs same */ - const uint32_t T = 256, grid = 384; - for (int cached = 0; cached < 2 && !fail; cached++) for (int same = 0; same < 2 && !fail; same++) { - const uint32_t iters = same ? 8u : 32u, groups = same ? 1u : grid; - const size_t region = (size_t)iters * T * 128u, sb = region * groups, ob = (size_t)grid * T * 4u; - OmegaGpuMem src = { 0 }, out = { 0 }; - uint32_t *pat = malloc(sb); - for (size_t q = 0; q < sb / 4; q++) pat[q] = (uint32_t)(q * 2654435761u); - rc = cached ? omega_gpu_pf_alloc_dev(sb, &src) : omega_gpu_pf_alloc_host(sb, &src); - if (!rc) rc = omega_gpu_pf_alloc_host(ob, &out); - if (!rc) { if (cached) rc = omega_gpu_pf_upload(&src, 0, pat, sb); else { memcpy(src.cpu, pat, sb); } } - uint32_t *want = calloc((size_t)grid * T, 4); - for (uint32_t c = 0; c < grid; c++) for (uint32_t t = 0; t < T; t++) { uint32_t x = 0; const uint32_t *r = pat + (size_t)(groups == 1 ? 0 : c) * region / 4; - for (uint32_t it = 0; it < iters; it++) for (uint32_t q = 0; q < 8; q++) for (uint32_t s = 0; s < 4; s++) x ^= r[((size_t)it * T * 128u + (size_t)q * T * 16u + t * 16u) / 4 + s]; - want[(size_t)c * T + t] = x; } - uint64_t ns[5] = { 0 }; size_t wrong = 0; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = 0x100u; key.words[0] = iters; key.words[1] = groups; key.words[2] = T; - for (int r = 0; r < 5 && !rc; r++) { - uint32_t *o = out.cpu; memset(o, 0, ob); - uint32_t args[4] = { (uint32_t)src.va, (uint32_t)(src.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - omega_gpu_session_lock(); - OmegaPfKernel k; rc = omega_gpu_pf_open_locked(); - if (!rc) rc = omega_gpu_pf_kernel_locked(&key, gen_bw, &k); - if (!rc && omega_gpu_session_sync_to_gpu(&out) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - if (!rc) rc = omega_gpu_pf_launch_locked(&k, T, grid, 1, 0, args, 4, &ns[r]); - if (!rc && omega_gpu_session_sync_to_cpu(&out) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - omega_gpu_session_unlock(); - if (!rc) for (size_t q = 0; q < (size_t)grid * T; q++) if (o[q] != want[q]) wrong++; - } - qsort(ns, 5, 8, cmp_u64); - const double bytes = (double)grid * iters * T * 128.0; - printf("bw %s %s: rc %s, median %.1f us, %.1f GB/s, %zu wrong\n", cached ? "cached " : "uncached", same ? "same-1MB" : "distinct", omega_gpu_pf_rc_name(rc), ns[2] / 1e3, bytes / ns[2], wrong); - if (rc || wrong) { fail++; printf(" error: %s\n", omega_gpu_session_last_error()); } - free(pat); free(want); omega_gpu_pf_free(&src); omega_gpu_pf_free(&out); - } - free(a); free(b); - printf("GPU_PF_MEM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_pfgemm_test.c b/tests/gpu_pfgemm_test.c deleted file mode 100644 index c2a4fc096..000000000 --- a/tests/gpu_pfgemm_test.c +++ /dev/null @@ -1,327 +0,0 @@ -/* gpu_pfgemm_test.c (OWN-30B T3b, 2026-10-13): tensor-core grouped FP8 GEMM v2, device resident (omega_blackwell_codegen_tc2.h, - * omega_gpu_pfgemm.c). - * --host-only register budgets of the production specs; the SWIGLU layout transform against a double oracle on the - * original (unpermuted) weights; the C emulation of the folded scale against a double oracle - * --sim the kernel in the warp simulator (both fragment orders) bit-identical to the C emulation (F32 and SWIGLU, - * indexed and direct rows); mutants 1-4 caught (a simulator error is a FAIL, never "caught") - * --chip (under flock /tmp/aien-gb10.lock) through the device API with GPU-cached buffers: sampled rows vs the - * emulation (F32 bit-identical; SWIGLU within 1 bf16 ulp: MUFU.EX2/RCP are approximate on the chip), second - * launch identical, mutants caught, medians of --reps at --tokens for every production shape - * Verdict line last: "GPU_PFGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc2.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_prefill.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static const HmmaModel GB10 = { 16, 2, 0, 2, 0 }; -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float frnd(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint16_t bf16_rn(float f) { uint32_t u = f2u(f); if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u; return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -static uint32_t stored_ix(uint32_t p) { static const uint32_t inv[4] = { 0, 2, 1, 3 }; return (p & ~3u) | inv[p & 3u]; } - -typedef struct { - uint32_t E, n, k, M, xr, layout, direct; - uint8_t *w, *pw; /* original and physical weights */ - uint16_t *sbf; /* scale_inv bf16 */ - float *ratio; /* physical ratio table */ - float *x; /* xr * k true values */ - uint16_t *xp; /* (xr + pad) * k stored bf16 */ - uint32_t *eid, *src, *counts; -} Prob; - -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static void prob_make(Prob *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, uint32_t layout, uint32_t direct, uint32_t pad) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = direct ? M : xr; p->layout = layout; p->direct = direct; - const size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * (k / 128), rn = (size_t)E * (n / 8) * (k / 128 + 1); - p->w = malloc(wn); p->pw = malloc(wn); p->sbf = malloc(sn * 2); p->ratio = malloc(rn * 4); - p->x = malloc((size_t)p->xr * k * 4); p->xp = calloc((size_t)(p->xr + pad) * k, 2); - p->eid = malloc(M * 4); p->src = malloc(M * 4); p->counts = calloc(E, 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) { float s = ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4); p->sbf[i] = (uint16_t)(f2u(s) >> 16); } - if (omega_gpu_pf_weights_host_form(E, n, k, p->w, p->sbf, layout, p->pw, p->ratio) != 0) { printf("host form refused\n"); exit(2); } - for (size_t i = 0; i < (size_t)p->xr * k; i++) p->x[i] = frnd() * (rnd() % 16 == 0 ? 8.0f : 1.0f); - for (uint32_t r = 0; r < p->xr; r++) omega_tcgemm_permute_x(p->x + (size_t)r * k, k, p->xp + (size_t)r * k); - /* sorted expert ids with random segment lengths (some experts empty, some multi-tile) */ - uint32_t i = 0; - for (uint32_t e = 0; e < E && i < M; e++) { uint32_t c = e + 1 == E ? M - i : (uint32_t)((uint64_t)(rnd() % 2000) * 2 * M / (2000ull * E)); if (c > M - i) c = M - i; for (uint32_t q = 0; q < c; q++) { p->eid[i + q] = e; } p->counts[e] = c; i += c; } - for (uint32_t q = 0; q < M; q++) p->src[q] = direct ? q : rnd() % p->xr; -} -static void prob_free(Prob *p) { free(p->w); free(p->pw); free(p->sbf); free(p->ratio); free(p->x); free(p->xp); free(p->eid); free(p->src); free(p->counts); } - -/* emulation of one physical output (row i, physical col c): the kernel's arithmetic */ -static float emu_phys(const Prob *p, uint32_t i, uint32_t c) { - const uint32_t n = p->n, k = p->k, KB = k / 128; - const uint16_t *xs = p->xp + (size_t)p->src[i] * k; - const uint8_t *wr = p->pw + ((size_t)p->eid[i] * n + c) * k; - const float *R0 = p->ratio + ((size_t)p->eid[i] * (n / 16) + c / 16) * (KB + 1) * 2 + (c / 8) % 2; -#define R(q) R0[2 * (q)] - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - acc = acc * R(kb); - for (uint32_t ch = 0; ch < 2; ch++) for (uint32_t s = 0; s < 4; s++) { - float a[16], b[16]; int m = 0; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - uint32_t e = kb * 128 + ch * 64 + 16 * t + 4 * s + j; - a[m] = u2f((uint32_t)xs[stored_ix(e)] << 16); b[m] = u2f((uint32_t)omega_tcgemm_w_bf16(wr[e]) << 16); m++; - } - acc = hm_dot16(&GB10, a, b, acc); - } - } - return acc * R(KB); -#undef R -} -/* the kernel's epilogue arithmetic: MUFU.EX2, FADD, MUFU.RCP, FMUL x 3, F2FP. The two MUFU results pass through ws_mufu_ftz - * (bw_warp_sim_tc.h): the chip's MUFU flushes a subnormal result to a sign-preserving zero, so for t = -g log2 e in (126, 128) - * (g in (-88.72, -87.34)) the reciprocal is +-0 and the activation is +-0, not the 2^-56-ish product an IEEE 1/d would give. */ -static uint16_t swiglu_bits(float g, float u) { - float t = g * u2f(0xbfb8aa3bu), ex = ws_mufu_ftz(exp2f(ws_mufu_ftz(t))), d = ex + 1.0f, r = ws_mufu_ftz(1.0f / ws_mufu_ftz(d)), o = g * r; - o = o * u; o = o * u2f(0x5f800000u); - return bf16_rn(o); -} -/* emulated output row i: F32 -> n floats; SWIGLU -> n/2 bf16 (as u16 in the low half of each u32 slot of out) */ -static void emu_row(const Prob *p, uint32_t i, float *yf, uint16_t *ya) { - if (p->layout == OMEGA_GPU_PF_PLAIN) { for (uint32_t c = 0; c < p->n; c++) yf[c] = emu_phys(p, i, c); return; } - for (uint32_t a = 0; a < p->n / 2; a++) { uint32_t G = a / 8, m = a % 8; ya[a] = swiglu_bits(emu_phys(p, i, 16 * G + m), emu_phys(p, i, 16 * G + 8 + m)); } -} - -typedef struct { uint64_t w_va, r_va; uint32_t row0, cnt; uint64_t pad; } Tile; -static uint32_t make_tiles(const Prob *p, uint32_t bm, Tile *t) { - uint32_t nt = 0, row = 0; const uint32_t KB = p->k / 128; - for (uint32_t e = 0; e < p->E; e++) { for (uint32_t r = 0; r < p->counts[e]; r += bm) { - t[nt].w_va = (uintptr_t)(p->pw + (size_t)e * p->n * p->k); t[nt].r_va = (uintptr_t)(p->ratio + (size_t)e * (p->n / 8) * (KB + 1)); - t[nt].row0 = row + r; t[nt].cnt = p->counts[e] - r < bm ? p->counts[e] - r : bm; t[nt].pad = 0; nt++; } row += p->counts[e]; } - return nt; -} - -static int host_only(void) { - int fail = 0; - static const OmegaTc2Spec specs[] = { - { 2048, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 0, 5120, 0 }, { 2048, 8, 2, 16, 1, OMEGA_TC2_EPI_SWIGLU, 0, 1536, 0 }, { 768, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 1, 2048, 0 }, - { 4096, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 0, 2048, 0 }, { 2048, 8, 2, 16, 2, OMEGA_TC2_EPI_F32, 0, 5120, 0 }, { 2048, 8, 2, 16, 2, OMEGA_TC2_EPI_SWIGLU, 0, 1536, 0 }, - { 768, 8, 2, 16, 2, OMEGA_TC2_EPI_F32, 1, 2048, 0 }, { 2048, 4, 2, 8, 2, OMEGA_TC2_EPI_F32, 0, 2048, 0 }, - }; - static BlackwellIRProgram prog; - for (size_t i = 0; i < sizeof specs / sizeof specs[0]; i++) { - int rc = omega_blackwell_codegen_tc2_prog(&specs[i], &prog); - uint32_t peak = rc == 0 ? prog.regalloc.peak_gpr_usage : 0, decl = omega_bw_gpr_declared(peak); - int ok = rc == 0 && decl <= 128u && 32u * specs[i].warps * decl <= 65536u; - printf("spec k %u rt %u ct %u warps %u aqn %u epi %u direct %u: %s, %zu instructions, peak %u, declared %u -> %s\n", specs[i].k, specs[i].rt, specs[i].ct, specs[i].warps, specs[i].aqn, - specs[i].epi, specs[i].direct, rc ? "REFUSED" : "built", rc ? 0 : prog.count, peak, decl, ok ? "fits" : "DOES NOT FIT"); - if (!ok && specs[i].aqn == 1) fail++; /* aqn 2 is optional */ - } - /* layout + emulation vs double oracle on the ORIGINAL weights: SWIGLU act[a] ~ silu(x.Wg[i]) * x.Wu[i] * 2^64, i = perm(a) */ - Prob p; prob_make(&p, 2, 256, 256, 24, 8, OMEGA_GPU_PF_SWIGLU, 0, 32); - double worst = 0; const uint32_t KB = p.k / 128, NB = p.n / 128, I = p.n / 2; - for (uint32_t i = 0; i < p.M; i++) { - uint16_t act[128]; emu_row(&p, i, NULL, act); - for (uint32_t a = 0; a < I; a++) { - uint32_t li = stored_ix(a); double d[2]; - for (int h = 0; h < 2; h++) { uint32_t row = h ? I + li : li; double s = 0; - for (uint32_t kk = 0; kk < p.k; kk++) { - double sc = (double)u2f((uint32_t)p.sbf[((size_t)p.eid[i] * NB + row / 128) * KB + kk / 128] << 16); - double wv = ldexp((double)u2f((uint32_t)omega_tcgemm_w_bf16(p.w[((size_t)p.eid[i] * p.n + row) * p.k + kk]) << 16), 120); - double xv = (double)u2f((uint32_t)p.xp[(size_t)p.src[i] * p.k + stored_ix(kk)] << 16) / 18446744073709551616.0; - s += sc * wv * xv; } - d[h] = s; } - double want = d[0] / (1.0 + exp(-d[0])) * d[1], got = (double)u2f((uint32_t)act[a] << 16) / 18446744073709551616.0; - double err = fabs(got - want) / (fabs(want) + 1e-3 * 1e-0); - if (err > worst) worst = err; - } - } - printf("SWIGLU layout + emulation vs double oracle on the original weights: worst relative error %.3g (bf16 output: < 1e-2 expected)\n", worst); - if (!(worst < 1e-2)) fail++; - prob_free(&p); - /* the reference against the chip's MUFU.RCP flush (GB10, evidence OWN30B-L1G-PFGEMM-SWIGLU-FTZ-df9bd9c4, 2026-10-15): at 3600 - * tokens, 48 sampled rows, all 101 of 101 elements that differed from the IEEE reference had t = -g log2 e in (126.03, 127.99) - * and came back +-0 from the chip. g and u are the emulated f32 gate / up values (9 significant digits round-trip exactly), - * act the chip's bf16; the first and last entries are the smallest and largest t observed. */ - static const struct { float g, u; uint16_t act; } chip[] = { - { -87.3551483f, 274.485016f, 0x8000 }, { -87.4824142f, 122.849442f, 0x8000 }, { -87.8418655f, 45.4098854f, 0x8000 }, - { -88.1839066f, -28.427494f, 0x0000 }, { -88.3344727f, -3.59300494f, 0x0000 }, { -88.7186356f, 180.687149f, 0x8000 }, - }; - size_t ok = 0; - for (size_t i = 0; i < sizeof chip / sizeof chip[0]; i++) ok += swiglu_bits(chip[i].g, chip[i].u) == chip[i].act; - /* negative control: g -87 (t 125.5) has a normal reciprocal and must stay a nonzero finite negative activation (the flush must not - * reach outside the window); g -89 (t 128.4) overflows ex2 to +inf and is -0 in both arithmetics (not a flush) */ - const uint16_t nc_lo = swiglu_bits(-87.0f, 100.0f), nc_hi = swiglu_bits(-89.0f, 100.0f); - const int nc_ok = (nc_lo & 0x7fffu) != 0 && (nc_lo & 0x7f80u) != 0x7f80u && (nc_lo & 0x8000u) && nc_hi == 0x8000u; - printf("SWIGLU reference vs chip-observed MUFU.RCP flush window: %zu/%zu match; control g -87 -> %04x (nonzero), g -89 -> %04x (-0): %s\n", - ok, sizeof chip / sizeof chip[0], nc_lo, nc_hi, ok == sizeof chip / sizeof chip[0] && nc_ok ? "ok" : "FAIL"); - if (ok != sizeof chip / sizeof chip[0] || !nc_ok) fail++; - return fail; -} - -static int sim_run(const Prob *p, const OmegaTc2Spec *sp, int order, void *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_tc2_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused (spec_ok %d)", omega_tc2_spec_ok(sp)); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_tc2_span(sp); - Tile *tiles = calloc(p->M + 1, sizeof *tiles); - uint32_t nt = make_tiles(p, bm, tiles); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - const size_t yb = (size_t)(p->M + bm) * p->n * (p->layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - memset(y, 0xee, yb); - uint8_t *smem = malloc(omega_tc2_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_tc2_shared_bytes(sp); s.order = order; - uint64_t a[4] = { (uintptr_t)tiles, sp->direct ? 0 : (uintptr_t)ridx, (uintptr_t)p->xp, (uintptr_t)y }; - for (int i = 0; i < 4; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a0 / 4] = p->n; - const uint32_t KB = p->k / 128; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xp; s.ranges[2].hi = (uintptr_t)(p->xp + (size_t)(p->xr + (p->direct ? bm : 0)) * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)y + (size_t)p->M * p->n * (p->layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - s.ranges[4].lo = (uintptr_t)p->pw; s.ranges[4].hi = (uintptr_t)(p->pw + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->ratio; s.ranges[5].hi = (uintptr_t)(p->ratio + (size_t)p->E * (p->n / 8) * (KB + 1)); - s.nranges = 6; - int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} -static size_t compare(const Prob *p, const void *y, const uint32_t *rows, uint32_t nrows, int tol_ulp, size_t *ulp1) { - size_t bad = 0; if (ulp1) *ulp1 = 0; - float *yf = malloc(p->n * 4); uint16_t *ya = malloc(p->n); - for (uint32_t q = 0; q < nrows; q++) { - uint32_t i = rows[q]; emu_row(p, i, yf, ya); - if (p->layout == OMEGA_GPU_PF_PLAIN) { const uint32_t *g = (const uint32_t *)y + (size_t)i * p->n; for (uint32_t c = 0; c < p->n; c++) if (g[c] != f2u(yf[c])) { if (getenv("PFDBG") && bad < 6) printf(" row %u col %u got %.9g want %.9g\n", i, c, u2f(g[c]), yf[c]); bad++; } } - else { const uint16_t *g = (const uint16_t *)y + (size_t)i * (p->n / 2); - for (uint32_t c = 0; c < p->n / 2; c++) if (g[c] != ya[c]) { int d = abs((int)g[c] - (int)ya[c]); if (d <= tol_ulp && ((g[c] ^ ya[c]) & 0x8000) == 0) { if (ulp1) (*ulp1)++; } - else { if (getenv("PFDBG") && bad < 128) { const uint32_t G = c / 8, mm = c % 8; const float gg = emu_phys(p, i, 16 * G + mm), uu = emu_phys(p, i, 16 * G + 8 + mm); - printf(" row %u act %u got %04x want %04x g %.9g u %.9g t %.6f\n", i, c, g[c], ya[c], gg, uu, gg * u2f(0xbfb8aa3bu)); } bad++; } } } - } - free(yf); free(ya); - return bad; -} - -static int sim_tests(void) { - int fail = 0; char msg[256]; - static const struct { uint32_t E, n, k, M, xr, layout, direct, rt, warps, aqn; } cs[] = { - { 3, 256, 256, 70, 20, OMEGA_GPU_PF_PLAIN, 0, 8, 16, 1 }, { 3, 256, 384, 70, 20, OMEGA_GPU_PF_SWIGLU, 0, 8, 16, 1 }, - { 3, 256, 256, 150, 0, OMEGA_GPU_PF_PLAIN, 1, 8, 16, 1 }, { 2, 256, 256, 40, 9, OMEGA_GPU_PF_PLAIN, 0, 4, 8, 2 }, - { 2, 512, 128, 300, 30, OMEGA_GPU_PF_SWIGLU, 0, 8, 16, 2 }, - { 3, 512, 256, 150, 40, OMEGA_GPU_PF_SWIGLU, 0, 4, 16, 1 }, { 3, 256, 384, 130, 0, OMEGA_GPU_PF_PLAIN, 1, 4, 16, 1 }, /* the chip shape (QMD shared cap) */ - }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - Prob p; prob_make(&p, cs[c].E, cs[c].n, cs[c].k, cs[c].M, cs[c].xr, cs[c].layout, cs[c].direct, 16 * cs[c].rt); - OmegaTc2Spec sp = { cs[c].k, cs[c].rt, 2, cs[c].warps, cs[c].aqn, cs[c].layout == OMEGA_GPU_PF_SWIGLU ? OMEGA_TC2_EPI_SWIGLU : OMEGA_TC2_EPI_F32, cs[c].direct, cs[c].n, 0 }; - void *y = malloc((size_t)(p.M + 128) * p.n * 4); - uint32_t *rows = malloc(p.M * 4); for (uint32_t i = 0; i < p.M; i++) rows[i] = i; - for (int order = 0; order < 2; order++) { - int rc = sim_run(&p, &sp, order, y, msg, sizeof msg); - size_t bad = rc ? (size_t)-1 : compare(&p, y, rows, p.M, 0, NULL); - printf("sim case %zu (E %u n %u k %u M %u %s%s rt %u warps %u aqn %u) order %d: %s, %zu differ\n", c, p.E, p.n, p.k, p.M, p.layout ? "SWIGLU" : "F32", p.direct ? " direct" : "", sp.rt, sp.warps, sp.aqn, order, rc ? msg : "ran", rc ? 0 : bad); - if (rc || bad) fail++; - } - if (c == 0 || c == 1) for (int m = 1; m <= 4; m++) { - OmegaTc2Spec mm = sp; mm.mutant = m; - int rc = sim_run(&p, &mm, 0, y, msg, sizeof msg); - size_t bad = rc ? 0 : compare(&p, y, rows, p.M, 0, NULL); - printf("sim case %zu mutant %d: %s\n", c, m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - free(y); free(rows); prob_free(&p); - } - return fail; -} - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int chip_shape(const char *name, uint32_t tokens, int reps, int check_rows, int mutants) { - uint32_t E, n, k, M, xr, layout, direct; - if (!strcmp(name, "gateup")) { E = 128; n = 1536; k = 2048; M = tokens * 8; xr = tokens; layout = OMEGA_GPU_PF_SWIGLU; direct = 0; } - else if (!strcmp(name, "down")) { E = 128; n = 2048; k = 768; M = tokens * 8; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "qkv")) { E = 1; n = 5120; k = 2048; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else if (!strcmp(name, "o")) { E = 1; n = 2048; k = 4096; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else { printf("unknown shape %s\n", name); return 1; } - const uint32_t bm = omega_gpu_pf_gemm_bm(); - Prob p; prob_make(&p, E, n, k, M, xr, layout, direct, bm); - int fail = 0, rc; - OmegaPfWeights wt; OmegaGpuMem xd = { 0 }, yd = { 0 }, tab = { 0 }, ridx = { 0 }; - rc = omega_gpu_pf_weights_upload(E, n, k, p.w, p.sbf, layout, &wt); - const size_t xb = ((size_t)(p.xr + bm) * k * 2 + 15) & ~(size_t)15, yb = (size_t)(M + bm) * n * (layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - if (!rc) rc = omega_gpu_pf_alloc_dev(xb, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(yb, &yd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, p.xp, xb); - const uint32_t maxt = M / bm + E + 1; - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)maxt * 32, &tab); - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(M + bm) * 4, &ridx); - if (rc) { printf("%s setup: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); return 1; } - uint32_t nt = omega_gpu_pf_gemm_tiles(&wt, p.counts, tab.cpu, maxt); - { uint32_t *ri = ridx.cpu; for (uint32_t i = 0; i < M + bm; i++) ri[i] = i < M ? p.src[i] : 0; } - omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&tab); (void)omega_gpu_session_sync_to_gpu(&ridx); omega_gpu_session_unlock(); - const uint64_t rva = direct ? 0 : ridx.va; - uint8_t *y1 = malloc(yb), *y2 = malloc(yb); - uint64_t ns[32] = { 0 }; - if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y1, yb & ~(size_t)15); - memset(y2, 0, yb); - { uint8_t z[4096]; memset(z, 0, sizeof z); /* zero the output on the device, run once more: the second result must be identical */ - uint8_t *zb = calloc(1, yb); if (!rc) rc = omega_gpu_pf_upload(&yd, 0, zb, yb & ~(size_t)15); free(zb); (void)z; } - uint64_t ns2 = 0; - if (!rc) rc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, &ns2); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - if (rc) { printf("%s run: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - const size_t outb = (size_t)M * n * (layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - printf("%s second launch identical: %s\n", name, memcmp(y1, y2, outb) ? "NO" : "yes"); - if (memcmp(y1, y2, outb)) fail++; - uint32_t *rows = malloc(check_rows * 4); for (int q = 0; q < check_rows; q++) rows[q] = q == 0 ? 0 : q == 1 ? M - 1 : rnd() % M; - size_t ulp1 = 0, bad = compare(&p, y1, rows, check_rows, layout == OMEGA_GPU_PF_SWIGLU ? 1 : 0, &ulp1); - printf("%s bit-identity on %d sampled rows: %zu differ%s", name, check_rows, bad, layout == OMEGA_GPU_PF_SWIGLU ? "" : "\n"); - if (layout == OMEGA_GPU_PF_SWIGLU) printf(" (beyond 1 bf16 ulp; %zu within 1 ulp of %zu)\n", ulp1, (size_t)check_rows * n / 2); - if (bad) fail++; - qsort(ns, reps, 8, cmp_u64); - const double fl = 2.0 * M * n * k, med = (double)ns[reps / 2]; - printf("TCGEMM2 %s tokens %u M %u n %u k %u tiles %u: median %.3f ms (min %.3f), %.1f TFLOPS, weights %.0f MB -> %.0f GB/s of distinct weights\n", name, tokens, M, n, k, nt, - med / 1e6, ns[0] / 1e6, fl / med / 1e3, (double)E * n * k / 1e6, (double)E * n * k / med); - if (mutants) for (int m = 1; m <= 4; m++) { - omega_gpu_pf_gemm_test_set_mutant(m); - int mrc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, NULL); - if (!mrc) mrc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - omega_gpu_pf_gemm_test_set_mutant(0); - size_t mb = mrc ? 0 : compare(&p, y2, rows, check_rows > 8 ? 8 : check_rows, layout == OMEGA_GPU_PF_SWIGLU ? 1 : 0, NULL); - printf("%s mutant %d: %s\n", name, m, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - free(rows); - } - free(y1); free(y2); - omega_gpu_pf_weights_free(&wt); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&yd); omega_gpu_pf_free(&tab); omega_gpu_pf_free(&ridx); - prob_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7, check = 48, mutants = 1; uint32_t tokens = 3600; const char *shape = NULL; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--shape") && i + 1 < argc) shape = argv[++i]; - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--check-rows") && i + 1 < argc) check = atoi(argv[++i]); - else if (!strcmp(argv[i], "--no-mutants")) mutants = 0; - else if (!strcmp(argv[i], "--shape-knob") && i + 3 < argc) { uint32_t a = (uint32_t)atoi(argv[i + 1]), b = (uint32_t)atoi(argv[i + 2]), c = (uint32_t)atoi(argv[i + 3]); omega_gpu_pf_gemm_set_shape(a, b, c); i += 3; } - } - int fail = 0; - if (host) fail += host_only(); - if (sim) fail += sim_tests(); - if (chip) { - static const char *all[] = { "gateup", "down", "qkv", "o" }; - for (int s = 0; s < 4; s++) if (!shape || !strcmp(shape, all[s])) fail += chip_shape(all[s], tokens, reps, check, mutants); - } - printf("GPU_PFGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_pfhost_test.c b/tests/gpu_pfhost_test.c deleted file mode 100644 index fef63ebf8..000000000 --- a/tests/gpu_pfhost_test.c +++ /dev/null @@ -1,278 +0,0 @@ -/* gpu_pfhost_test.c (OWN-30B W-L1G-D, 2026-10-14): router logits and MoE combine for the whole-prompt prefill - * (omega_blackwell_codegen_pfhost.h). Both kernels must equal the host loops of the Rust driver BIT FOR BIT. - * --host-only reference self-checks (packing, the -0.0 start, mutant references differ) - * --sim kernels in the warp simulator bit-identical to the reference, both scheduling orders; mutants caught - * --chip (under flock /tmp/aien-gb10.lock) through the device API at --tokens rows: bit-identical, mutants caught, medians - * Verdict line last: "GPU_PFHOST: PASS|FAIL". */ -#include "omega_blackwell_codegen_pfhost.h" -#include "omega_gpu_pfhost.h" -#include "omega_gpu_prefill.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static float rand_unit(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -/* router weights as the checkpoint has them: bf16 values widened to f32 */ -static float rand_bf16w(void) { return u2f(f2u(rand_unit() * 0.08f) & 0xffff0000u); } -/* activations: RMSNorm-like magnitudes with some outliers and exact zeros */ -static float rand_act(void) { float v = rand_unit() * 2.0f; int r = rnd() % 64; if (r == 0) v *= 40.0f; else if (r == 1) v = 0.0f; return v; } - -/* ---------------- references (compiled with -ffp-contract=off: a * b then +, as Rust) ---------------- */ -static void rl_ref(const float *x, const float *w, uint32_t rows, uint32_t k, uint32_t e, float *lg, int mutant) { - const uint32_t kk = mutant == 2 ? k - 128u : k; - for (uint32_t r = 0; r < rows; r++) - for (uint32_t ex = 0; ex < e; ex++) { - float acc = -0.0f; - for (uint32_t j = 0; j < kk; j++) acc = mutant == 1 ? fmaf(w[(size_t)ex * k + j], x[(size_t)r * k + j], acc) : acc + w[(size_t)ex * k + j] * x[(size_t)r * k + j]; - lg[(size_t)r * e + ex] = acc; - } -} -static void mc_ref(const float *down, const uint32_t *inv, const float *wt, uint32_t rows, uint32_t h, uint32_t K, float *out, int mutant) { - const uint32_t used = mutant == 2 ? K - 1u : K; - for (uint32_t r = 0; r < rows; r++) - for (uint32_t c = 0; c < h; c++) { - float acc = 0.0f; - for (uint32_t s = 0; s < used; s++) { - const float d = down[(size_t)inv[(size_t)r * K + s] * h + c], ww = wt[(size_t)r * K + s]; - acc = mutant == 1 ? fmaf(ww, d, acc) : acc + ww * d; - } - out[(size_t)r * h + c] = acc; - } -} -static size_t diff_bits(const float *a, const float *b, size_t n) { size_t bad = 0; for (size_t i = 0; i < n; i++) if (f2u(a[i]) != f2u(b[i])) bad++; return bad; } - -typedef struct { uint32_t rows, k, e, t, rp; float *x, *w, *wq, *ref; } RlProb; -static void rl_make(RlProb *p, uint32_t rows, uint32_t k, uint32_t e, uint32_t t) { - p->rows = rows; p->k = k; p->e = e; p->t = t; p->rp = (rows + t - 1u) / t * t; - p->x = malloc((size_t)p->rp * k * 4); p->w = malloc((size_t)e * k * 4); - p->wq = malloc(omega_gpu_pf_router_packed_bytes(e, k)); p->ref = malloc((size_t)rows * e * 4); - for (size_t i = 0; i < (size_t)p->rp * k; i++) p->x[i] = i < (size_t)rows * k ? rand_act() : u2f(0x7fc00000u); /* pad rows NaN: must not leak */ - for (size_t i = 0; i < (size_t)e * k; i++) p->w[i] = rand_bf16w(); - if (rows > 2) memset(p->x + 2 * (size_t)k, 0, k * 4); /* an all-zero row: every logit -0.0 + 0 products */ - omega_gpu_pf_router_pack(e, k, p->w, p->wq); - rl_ref(p->x, p->w, rows, k, e, p->ref, 0); -} -static void rl_free(RlProb *p) { free(p->x); free(p->w); free(p->wq); free(p->ref); } - -typedef struct { uint32_t rows, h, K; float *down, *wt, *ref; uint32_t *inv; } McProb; -static void mc_make(McProb *p, uint32_t rows, uint32_t h, uint32_t K) { - p->rows = rows; p->h = h; p->K = K; - const size_t g = (size_t)rows * K; - p->down = malloc(g * h * 4); p->wt = malloc(g * 4); p->inv = malloc(g * 4); p->ref = malloc((size_t)rows * h * 4); - for (size_t i = 0; i < g * h; i++) p->down[i] = rand_act() * 0.5f; - for (size_t i = 0; i < g; i++) { p->wt[i] = (float)(rnd() & 0xffff) / 65536.0f * 0.4f; p->inv[i] = (uint32_t)i; } - for (size_t i = g; i > 1; i--) { size_t j = rnd() % i; uint32_t t = p->inv[i - 1]; p->inv[i - 1] = p->inv[j]; p->inv[j] = t; } /* a permutation, like the expert sort */ - mc_ref(p->down, p->inv, p->wt, rows, h, K, p->ref, 0); -} -static void mc_free(McProb *p) { free(p->down); free(p->wt); free(p->inv); free(p->ref); } - -/* ---------------- host-only ---------------- */ -static int host_checks(void) { - int fail = 0; - /* packing: wq[g][ex][q] = w[ex][4g + q], pad group zero */ - { const uint32_t e = 32, k = 256; float *w = malloc(e * k * 4), *wq = malloc(omega_gpu_pf_router_packed_bytes(e, k)); - for (uint32_t i = 0; i < e * k; i++) w[i] = (float)i; - omega_gpu_pf_router_pack(e, k, w, wq); - size_t bad = 0; - for (uint32_t g = 0; g < k / 4; g++) for (uint32_t ex = 0; ex < e; ex++) for (uint32_t q = 0; q < 4; q++) if (wq[(g * e + ex) * 4 + q] != w[ex * k + 4 * g + q]) bad++; - for (uint32_t i = 0; i < e * 4; i++) if (f2u(wq[(k / 4) * e * 4 + i]) != 0) bad++; - printf("host pack R4: %zu wrong\n", bad); if (bad) fail++; - free(w); free(wq); } - /* the sum starts at -0.0 (Rust f32 Sum): an all-zero row gives -0.0 + (+0.0 products) = +0.0, a row of -0.0 products stays -0.0 */ - { float z = -0.0f; z = z + 0.0f * -1.0f; printf("host -0.0 start: -0 + (-0) = %s\n", signbit(z) ? "-0 (ok)" : "+0 (WRONG)"); if (!signbit(z)) fail++; } - /* the mutant references really differ */ - { RlProb p; rl_make(&p, 5, 256, 32, 4); float *m = malloc(5 * 32 * 4); - for (int mu = 1; mu <= 2; mu++) { rl_ref(p.x, p.w, 5, 256, 32, m, mu); size_t d = diff_bits(m, p.ref, 5 * 32); printf("host router mutant %d reference differs in %zu of 160\n", mu, d); if (!d) fail++; } - free(m); rl_free(&p); } - { McProb p; mc_make(&p, 3, 128, 8); float *m = malloc(3 * 128 * 4); - for (int mu = 1; mu <= 2; mu++) { mc_ref(p.down, p.inv, p.wt, 3, 128, 8, m, mu); size_t d = diff_bits(m, p.ref, 3 * 128); printf("host combine mutant %d reference differs in %zu of 384\n", mu, d); if (!d) fail++; } - free(m); mc_free(&p); } - return fail; -} - -/* ---------------- simulator ---------------- */ -static int rl_sim_one(const RlProb *p, int mutant, int order, float *lg, char *msg, size_t msgn) { - OmegaRlSpec sp = { p->k, p->e, p->t, mutant }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_rl_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const size_t lgb = (size_t)p->rp * p->e * 4, wqb = omega_gpu_pf_router_packed_bytes(p->e, p->k); - uint8_t *smem = malloc(omega_rl_shared_bytes(&sp)); - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = p->e; ws.smem = smem; ws.smem_bytes = omega_rl_shared_bytes(&sp); ws.order = order; - uint64_t a[3] = { (uintptr_t)p->x, (uintptr_t)p->wq, (uintptr_t)lg }; - for (int i = 0; i < 3; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)p->x; ws.ranges[0].hi = (uintptr_t)p->x + (size_t)p->rp * p->k * 4; - ws.ranges[1].lo = (uintptr_t)p->wq; ws.ranges[1].hi = (uintptr_t)p->wq + wqb; - ws.ranges[2].lo = (uintptr_t)lg; ws.ranges[2].hi = (uintptr_t)lg + lgb; - ws.nranges = 3; - memset(lg, 0xee, lgb); - int err = ws_run(&ws, p->rp / p->t, 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - free(smem); - return err ? -1 : 0; -} -static int mc_sim_one(const McProb *p, int mutant, int order, float *out, char *msg, size_t msgn) { - OmegaMcSpec sp = { p->h, p->K, mutant }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_mc_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const size_t g = (size_t)p->rows * p->K; - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = p->h / 4; ws.order = order; - uint64_t a[4] = { (uintptr_t)p->down, (uintptr_t)p->inv, (uintptr_t)p->wt, (uintptr_t)out }; - for (int i = 0; i < 4; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)p->down; ws.ranges[0].hi = (uintptr_t)p->down + g * p->h * 4; - ws.ranges[1].lo = (uintptr_t)p->inv; ws.ranges[1].hi = (uintptr_t)p->inv + g * 4; - ws.ranges[2].lo = (uintptr_t)p->wt; ws.ranges[2].hi = (uintptr_t)p->wt + g * 4; - ws.ranges[3].lo = (uintptr_t)out; ws.ranges[3].hi = (uintptr_t)out + (size_t)p->rows * p->h * 4; - ws.nranges = 4; - memset(out, 0xee, (size_t)p->rows * p->h * 4); - int err = ws_run(&ws, p->rows, 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - return err ? -1 : 0; -} -static int sim_checks(void) { - int fail = 0; char msg[200]; - static const struct { uint32_t rows, k, e, t; } rc[] = { { 37, 2048, 128, 16 }, { 9, 256, 32, 4 }, { 21, 384, 64, 8 }, { 16, 2048, 128, 4 } }; - for (size_t c = 0; c < sizeof rc / sizeof rc[0]; c++) { - RlProb p; rl_make(&p, rc[c].rows, rc[c].k, rc[c].e, rc[c].t); - float *lg = malloc((size_t)p.rp * p.e * 4); - for (int order = 0; order < 2; order++) { - int r = rl_sim_one(&p, 0, order, lg, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(lg, p.ref, (size_t)p.rows * p.e); - printf("sim router k %u e %u t %u rows %u order %d: %s, %zu of %zu differ\n", p.k, p.e, p.t, p.rows, order, r ? msg : "ran", bad, (size_t)p.rows * p.e); - if (r || bad) fail++; - } - if (c == 0) for (int mu = 1; mu <= 2; mu++) { - int r = rl_sim_one(&p, mu, 0, lg, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(lg, p.ref, (size_t)p.rows * p.e); - printf("sim router mutant %d: %s\n", mu, r ? msg : bad ? "caught" : "NOT CAUGHT"); - if (r || !bad) fail++; - } - free(lg); rl_free(&p); - } - static const struct { uint32_t rows, h, K; } mc[] = { { 7, 2048, 8 }, { 5, 128, 4 }, { 3, 384, 16 } }; - for (size_t c = 0; c < sizeof mc / sizeof mc[0]; c++) { - McProb p; mc_make(&p, mc[c].rows, mc[c].h, mc[c].K); - float *out = malloc((size_t)p.rows * p.h * 4); - for (int order = 0; order < 2; order++) { - int r = mc_sim_one(&p, 0, order, out, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(out, p.ref, (size_t)p.rows * p.h); - printf("sim combine h %u top_k %u rows %u order %d: %s, %zu of %zu differ\n", p.h, p.K, p.rows, order, r ? msg : "ran", bad, (size_t)p.rows * p.h); - if (r || bad) fail++; - } - if (c == 0) for (int mu = 1; mu <= 2; mu++) { - int r = mc_sim_one(&p, mu, 0, out, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(out, p.ref, (size_t)p.rows * p.h); - printf("sim combine mutant %d: %s\n", mu, r ? msg : bad ? "caught" : "NOT CAUGHT"); - if (r || !bad) fail++; - } - free(out); mc_free(&p); - } - return fail; -} - -/* ---------------- chip ---------------- */ -static int alloc_fill(int host, size_t bytes, const void *src, OmegaGpuMem *m) { - bytes = (bytes + 15u) & ~(size_t)15u; - int rc = host ? omega_gpu_pf_alloc_host(bytes, m) : omega_gpu_pf_alloc_dev(bytes, m); - if (rc) return rc; - if (!src) return 0; - if (host) { memcpy(m->cpu, src, bytes); return 0; } - return omega_gpu_pf_upload(m, 0, src, bytes); -} -static int rl_chip(uint32_t rows, int reps) { - int fail = 0; - const uint32_t k = 2048, e = 128, t = omega_gpu_pf_router_rows(); - RlProb p; rl_make(&p, rows, k, e, t); - const size_t lgb = (size_t)p.rp * e * 4; - OmegaGpuMem xd = { 0 }, wd = { 0 }, ld = { 0 }; - /* as the driver: x and logits in HOST (GPU-uncached) buffers, the packed weights GPU-cached */ - int rc = alloc_fill(1, (size_t)p.rp * k * 4, p.x, &xd); - if (!rc) rc = alloc_fill(0, omega_gpu_pf_router_packed_bytes(e, k), p.wq, &wd); - if (!rc) rc = alloc_fill(1, lgb, NULL, &ld); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; if (reps < 1) reps = 1; - float *lg = malloc(lgb); - for (int r = 0; r < reps && !rc; r++) { memset(ld.cpu, 0xee, lgb); rc = omega_gpu_pf_router_logits(k, e, rows, xd.va, wd.va, ld.va, &ns[r]); } - if (rc) { printf("ROUTER chip rows %u: %s (%s)\n", rows, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - memcpy(lg, ld.cpu, lgb); - size_t bad = diff_bits(lg, p.ref, (size_t)rows * e); - qsort(ns, (size_t)reps, 8, cmp_u64); - printf("ROUTER chip k %u e %u t %u rows %u: %zu of %zu differ from the host loop; median %.3f ms\n", k, e, t, rows, bad, (size_t)rows * e, ns[reps / 2] / 1e6); - if (bad) fail++; - for (int mu = 1; mu <= 2; mu++) { - omega_gpu_pf_router_test_set_mutant(mu); - memset(ld.cpu, 0xee, lgb); - int mrc = omega_gpu_pf_router_logits(k, e, rows, xd.va, wd.va, ld.va, NULL); - omega_gpu_pf_router_test_set_mutant(0); - memcpy(lg, ld.cpu, lgb); - size_t mb = mrc ? 0 : diff_bits(lg, p.ref, (size_t)rows * e); - printf("ROUTER chip mutant %d: %s\n", mu, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - } - free(lg); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&wd); omega_gpu_pf_free(&ld); rl_free(&p); - return fail; -} -static int mc_chip(uint32_t rows, int reps) { - int fail = 0; - const uint32_t h = 2048, K = 8; - McProb p; mc_make(&p, rows, h, K); - const size_t g = (size_t)rows * K, ob = (size_t)rows * h * 4; - OmegaGpuMem dd = { 0 }, id = { 0 }, wd = { 0 }, od = { 0 }; - /* as the driver: down rows GPU-cached (the down GEMM writes them), inv / weights / out in HOST buffers */ - int rc = alloc_fill(0, g * h * 4, p.down, &dd); - if (!rc) rc = alloc_fill(1, g * 4, p.inv, &id); - if (!rc) rc = alloc_fill(1, g * 4, p.wt, &wd); - if (!rc) rc = alloc_fill(1, ob, NULL, &od); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; if (reps < 1) reps = 1; - float *out = malloc(ob); - for (int r = 0; r < reps && !rc; r++) { memset(od.cpu, 0xee, ob); rc = omega_gpu_pf_moe_combine(h, K, rows, dd.va, id.va, wd.va, od.va, &ns[r]); } - if (rc) { printf("COMBINE chip rows %u: %s (%s)\n", rows, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - memcpy(out, od.cpu, ob); - size_t bad = diff_bits(out, p.ref, (size_t)rows * h); - qsort(ns, (size_t)reps, 8, cmp_u64); - printf("COMBINE chip h %u top_k %u rows %u: %zu of %zu differ from the host loop; median %.3f ms\n", h, K, rows, bad, (size_t)rows * h, ns[reps / 2] / 1e6); - if (bad) fail++; - for (int mu = 1; mu <= 2; mu++) { - omega_gpu_pf_combine_test_set_mutant(mu); - memset(od.cpu, 0xee, ob); - int mrc = omega_gpu_pf_moe_combine(h, K, rows, dd.va, id.va, wd.va, od.va, NULL); - omega_gpu_pf_combine_test_set_mutant(0); - memcpy(out, od.cpu, ob); - size_t mb = mrc ? 0 : diff_bits(out, p.ref, (size_t)rows * h); - printf("COMBINE chip mutant %d: %s\n", mu, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - } - free(out); omega_gpu_pf_free(&dd); omega_gpu_pf_free(&id); omega_gpu_pf_free(&wd); omega_gpu_pf_free(&od); mc_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7; uint32_t tokens = 2048; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - } - int fail = 0; - if (host) fail += host_checks(); - if (sim) fail += sim_checks(); - if (chip) { - fail += rl_chip(tokens, reps); fail += rl_chip(37, 3); - fail += mc_chip(tokens, reps); fail += mc_chip(7, 3); - } - printf("GPU_PFHOST: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_prefill_attn_test.c b/tests/gpu_prefill_attn_test.c deleted file mode 100644 index 6daaa012c..000000000 --- a/tests/gpu_prefill_attn_test.c +++ /dev/null @@ -1,654 +0,0 @@ -/* - * gpu_prefill_attn_test: the tensor-core causal prefill attention (omega_gpu_prefill_attn_api.h, OWN-30B L1 attention). - * --host-only codegen budgets (instructions <= 1024, declared registers <= 128, placeholders patched against the - * oracle words), refusals, reference sanity. No device. - * --sim the kernel through tests/bw_warp_sim_pa.h (chip-exact HMMA model; EX2/RSQ/RCP exact): several - * (pos0, m) points incl. two chunks, warps 4 and 8, both fragment orders. Gates: appended K/V rows - * bit-equal to a host emulation of the decode kernel's operation order; outputs within the tolerance - * of a double reference over the cache contents; mutants 1-4 caught. - * (default) the chip: parity against the double reference; appended K/V rows bit-identical to m calls of the - * decode kernel on a twin cache (gate 2) and its outputs within the tolerance; second call identical; - * out_scale 2^64; mutants 1-4 caught; timing medians (prefill vs the per-token decode loop). - * Tolerance: |out - ref| <= 1e-2 * max|v| * out_scale per element. Derivation: q' and P are rounded to bf16 (relative - * 2^-9 each). P rounding moves each weight by <= 2^-9 relative while l sums the f32 p: <= 2^-9 * max|v| = 0.0020. - * q' rounding moves a score (log2 units) by <= 2^-9 * sum|q'_i k_i|; for the normed rows here (|q'|, |k| ~ sqrt(128) - * with random signs) that is ~2^-9 * sqrt(128) * log2(e)/sqrt(128) * ... ~ 3e-3 relative on the weights in the worst - * measured case; EX2/RSQ on the chip add ~2^-22. 1e-2 covers the sum with margin; the measured worst ratio is printed - * and the mutants miss by far more than the tolerance. - * Host and simulator passes are never chip results. - */ -#include "omega_gpu_prefill_attn_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen_tc.h" -#include "bw_warp_sim_pa.h" -#if defined(__has_include) -#if __has_include("omega_gpu_prefill.h") -#include "omega_gpu_prefill.h" /* W-L1G device-resident module (integration builds): GPU-cached buffers for the dev check */ -#define PATTN_HAVE_PF 1 -#endif -#endif -#ifndef PATTN_HAVE_PF -#define PATTN_HAVE_PF 0 -#endif -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; -static const float EPS = 1e-6f; -#define QKVW OMEGA_PATTN_QKV_WORDS -#define OUTW OMEGA_PATTN_OUT_WORDS - -/* one layer's random state */ -typedef struct { - uint32_t max_pos, pos0, m; - float *qkv; /* [m][5120] */ - float qn[128], kn[128]; - uint16_t *kc, *vc; /* [4][max_pos][128]: history 0..pos0-1 */ -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos0 = pos0; c->m = m; - c->qkv = malloc((size_t)m * QKVW * 4); - for (size_t t = 0; t < m; t++) for (size_t i = 0; i < QKVW; i++) c->qkv[t * QKVW + i] = frand(&s, -1.0f, 1.0f) * (i < 4096 ? qscale : 1.0f); - for (unsigned i = 0; i < 128; i++) { c->qn[i] = frand(&s, 0.8f, 1.2f); c->kn[i] = frand(&s, 0.8f, 1.2f); } - size_t words = (size_t)4 * max_pos * 128; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < pos0; t++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + t) * 128 + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->qkv); free(c->kc); free(c->vc); } - -/* ---- host emulation of the decode kernel's K/V row (float, the kernel's operation order; RSQ exact as in the simulator) */ -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static void emu_rows(const float *qkv_row, const float *kn, float eps, uint32_t pos, double theta, uint16_t *krow /*[4][128]*/, uint16_t *vrow) { - float rope[128]; omega_dattn_rope_row(pos, theta, rope); - for (unsigned gk = 0; gk < 4; gk++) { - float x[128], sq[32]; - for (unsigned i = 0; i < 128; i++) x[i] = qkv_row[4096 + gk * 128 + i]; - for (unsigned L = 0; L < 32; L++) { float a = x[4 * L] * x[4 * L]; for (unsigned i = 1; i < 4; i++) a = fmaf(x[4 * L + i], x[4 * L + i], a); sq[L] = a; } - for (unsigned o = 16; o >= 1; o /= 2) { float nx[32]; for (unsigned L = 0; L < 32; L++) nx[L] = sq[L] + (L + o < 32 ? sq[L + o] : sq[L]); memcpy(sq, nx, sizeof sq); } - float rs = 1.0f / sqrtf(fmaf(sq[0], u2f(0x3c000000u), eps)); - for (unsigned i = 0; i < 128; i++) { x[i] = x[i] * rs; x[i] = x[i] * kn[i]; } - float y[128]; - for (unsigned i = 0; i < 128; i++) { - unsigned j = i % 64; float cs = rope[j], sn = rope[64 + j]; float part = x[i < 64 ? i + 64 : i - 64]; - float ts = x[i] * cs; y[i] = fmaf(part, i < 64 ? -sn : sn, ts); - } - for (unsigned i = 0; i < 128; i++) { krow[gk * 128 + i] = omega_dattn_bf16_rne(y[i]); vrow[gk * 128 + i] = omega_dattn_bf16_rne(qkv_row[4096 + 512 + gk * 128 + i]); } - } -} - -/* ---- double reference over the cache contents (kc/vc hold positions 0 .. pos0+m-1 after the call) */ -static void norm_rope_d(double *x, const float *w, float eps, uint32_t pos) { - double ss = 0; for (unsigned i = 0; i < 128; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / 128.0 + (double)eps); - for (unsigned i = 0; i < 128; i++) x[i] = x[i] * r * (double)w[i]; - double y[128]; - for (unsigned i = 0; i < 64; i++) { - double ang = (double)pos * pow(THETA, -(double)(2 * i) / 128.0), cs = cos(ang), sn = sin(ang); - y[i] = x[i] * cs - x[i + 64] * sn; y[i + 64] = x[i + 64] * cs + x[i] * sn; - } - memcpy(x, y, sizeof y); -} -static void reference(const Case *c, const uint16_t *kc, const uint16_t *vc, float out_scale, double *out /*[m][4096]*/) { - double *p = malloc(((size_t)c->pos0 + c->m) * sizeof(double)); - for (uint32_t t = 0; t < c->m; t++) { - const uint32_t pos = c->pos0 + t; - for (unsigned h = 0; h < 32; h++) { - unsigned gk = h / 8; double q[128]; - for (unsigned i = 0; i < 128; i++) q[i] = c->qkv[(size_t)t * QKVW + h * 128 + i]; - norm_rope_d(q, c->qn, EPS, pos); - double mx = -1e300; - for (uint32_t k = 0; k <= pos; k++) { - const uint16_t *kr = kc + ((size_t)gk * c->max_pos + k) * 128; - double s = 0; for (unsigned i = 0; i < 128; i++) s += q[i] * (double)omega_dattn_bf16_f32(kr[i]); - s /= sqrt(128.0); p[k] = s; if (s > mx) mx = s; - } - double l = 0, o[128]; memset(o, 0, sizeof o); - for (uint32_t k = 0; k <= pos; k++) { p[k] = exp(p[k] - mx); l += p[k]; } - for (uint32_t k = 0; k <= pos; k++) { const uint16_t *vr = vc + ((size_t)gk * c->max_pos + k) * 128; for (unsigned i = 0; i < 128; i++) o[i] += p[k] * (double)omega_dattn_bf16_f32(vr[i]); } - for (unsigned i = 0; i < 128; i++) out[(size_t)t * OUTW + h * 128 + i] = o[i] / l * (double)out_scale; - } - } - free(p); -} -static size_t parity(const Case *c, const uint16_t *kc, const uint16_t *vc, const float *out, float out_scale, double *worst) { - double *ref = malloc((size_t)c->m * OUTW * sizeof(double)); - reference(c, kc, vc, out_scale, ref); - double tol = 1e-2 * out_scale; size_t bad = 0; *worst = 0; - for (size_t i = 0; i < (size_t)c->m * OUTW; i++) { double d = fabs((double)out[i] - ref[i]); if (!(d <= tol)) bad++; if (d / tol > *worst || d != d) *worst = d != d ? 1e9 : d / tol; } - free(ref); - return bad; -} -/* appended rows (cache contents at pos0 .. pos0+m-1) against the host emulation: count of differing bf16 words and the - * largest difference in ulps */ -static void rows_vs_emu(const Case *c, const uint16_t *kc, const uint16_t *vc, size_t *kdiff, size_t *vdiff, int *maxulp) { - *kdiff = *vdiff = 0; *maxulp = 0; - uint16_t kr[512], vr[512]; - for (uint32_t t = 0; t < c->m; t++) { - emu_rows(c->qkv + (size_t)t * QKVW, c->kn, EPS, c->pos0 + t, THETA, kr, vr); - for (unsigned gk = 0; gk < 4; gk++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)gk * c->max_pos + c->pos0 + t) * 128 + i; - if (kc[o] != kr[gk * 128 + i]) { (*kdiff)++; int d = abs((int)kc[o] - (int)kr[gk * 128 + i]); if (d > *maxulp) *maxulp = d; } - if (vc[o] != vr[gk * 128 + i]) (*vdiff)++; - } - } -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - char msg[200]; - CHECK(omega_tc_patch_selftest(msg, sizeof msg) == 0, "placeholder self-test: %s", msg); - for (uint32_t w = 4; w <= 8; w += 4) for (uint32_t md = 0; md <= 2; md++) for (int m = 0; m <= 4; m++) { - OmegaPrefillAttnSpec s = { w, m, md, 0 }; uint32_t n = 0, gp = 0, ph = 0; - int rc = omega_prefill_attn_prog_stats(&s, &n, &gp, &ph); - CHECK(rc == 0 && n <= 1024 && omega_bw_gpr_declared(gp) <= 128, "codegen warps %u mode %u mutant %d: rc %d insns %u gprs %u", w, md, m, rc, n, gp); - static uint8_t code[1024 * 16]; uint32_t kg = 0; int np = -1; - size_t sz = omega_gpu_prefill_attn_encode(&s, code, sizeof code, &kg, &np); - CHECK(sz > 0 && np == (int)ph, "encode+patch warps %u mode %u mutant %d: size %zu patched %d of %u", w, md, m, sz, np, ph); - if (rc == 0 && m == 0) printf("codegen warps %u mode %u: %u instructions, %u registers (declared %u, %u threads -> %u of 65536), %u placeholders patched\n", - w, md, n, gp, omega_bw_gpr_declared(gp), 32 * w, 32 * w * omega_bw_gpr_declared(gp), ph); - } - { OmegaPrefillAttnSpec s = { 2, 0, 0, 0 }; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "warps 2 refused"); - s.warps = 8; s.mutant = 5; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mutant 5 refused"); - s.mutant = 0; s.mode = 3; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mode 3 refused"); - s.mode = OMEGA_PATTN_MODE_ATTEND; s.mirror = 1; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mirror outside APPEND refused"); - s.mode = OMEGA_PATTN_MODE_APPEND; uint32_t n = 0, gp = 0, ph = 0; - CHECK(omega_prefill_attn_prog_stats(&s, &n, &gp, &ph) == 0 && n <= 1024 && omega_bw_gpr_declared(gp) <= 128, "APPEND + mirror in budget: %u insns %u gprs", n, gp); - printf("codegen warps 8 APPEND + mirror: %u instructions, %u registers\n", n, gp); } - CHECK(omega_gpu_prefill_attn(NULL, 0, 0, 1, NULL, EPS, 1.0f, NULL, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL cache refused"); - CHECK(OMEGA_PATTN_SHARED_BYTES <= 16384u, "shared memory within the QMD cap"); - /* reference sanity: a single token at position 0 returns its own v row (rounded) */ - { Case c; case_make(&c, 256, 0, 1, 5, 1.0f); uint16_t kr[512], vr[512]; - emu_rows(c.qkv, c.kn, EPS, 0, THETA, kr, vr); - for (unsigned gk = 0; gk < 4; gk++) { memcpy(c.kc + (size_t)gk * 256 * 128, kr + gk * 128, 256); memcpy(c.vc + (size_t)gk * 256 * 128, vr + gk * 128, 256); } - double *ref = malloc(OUTW * sizeof(double)); reference(&c, c.kc, c.vc, 1.0f, ref); - int good = 1; for (unsigned h = 0; h < 32 && good; h++) for (unsigned i = 0; i < 128; i++) if (ref[h * 128 + i] != (double)omega_dattn_bf16_f32(vr[(h / 8) * 128 + i])) { good = 0; break; } - CHECK(good, "reference: one token at position 0 returns the rounded v row of its KV group"); - free(ref); case_free(&c); } -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -/* mirror planes for the simulated APPEND (write) / ATTEND (read) launches */ -static struct { uint8_t *k, *v; uint32_t kvs; size_t plane; int write, read; } g_sm; -/* one simulated launch of prog over tokens p0 .. p0+mc-1 whose rows are qbuf / obuf (host memory) */ -static int sim_launch(const BlackwellIRProgram *prog, uint32_t W, const Case *c, uint8_t *kv, size_t plane, const float *rope, const float *norms, - float out_scale, float *qbuf, float *obuf, uint32_t p0, uint32_t mc, int order, char *msg, size_t n) { - static uint8_t smem[OMEGA_PATTN_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = 32 * W; s.order = order; s.smem = smem; s.smem_bytes = sizeof smem; - uint64_t A[7] = { (uintptr_t)qbuf, (uintptr_t)kv, (uintptr_t)(kv + plane), (uintptr_t)rope, (uintptr_t)norms, (uintptr_t)(norms + 128), (uintptr_t)obuf }; - for (unsigned i = 0; i < 7; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = out_scale, fq = (float)((1.0 / sqrt(128.0)) * 1.4426950408889634); - s.cbank[OMEGA_PATTN_ARG_POS0 / 4] = p0; s.cbank[OMEGA_PATTN_ARG_MC / 4] = mc; s.cbank[OMEGA_PATTN_ARG_KV_STRIDE / 4] = c->max_pos * 256; - memcpy(&s.cbank[OMEGA_PATTN_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_PATTN_ARG_OUT_SCALE / 4], &fo, 4); memcpy(&s.cbank[OMEGA_PATTN_ARG_QK_SCALE / 4], &fq, 4); - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)qbuf; s.ranges[0].hi = (uintptr_t)qbuf + (size_t)mc * QKVW * 4; - s.ranges[1].lo = (uintptr_t)kv; s.ranges[1].hi = (uintptr_t)kv + 2 * plane; - s.ranges[2].lo = (uintptr_t)rope; s.ranges[2].hi = (uintptr_t)rope + (size_t)c->max_pos * 512; - s.ranges[3].lo = (uintptr_t)norms; s.ranges[3].hi = (uintptr_t)norms + 1024; - s.ranges[4].lo = (uintptr_t)obuf; s.ranges[4].hi = (uintptr_t)obuf + (size_t)mc * OUTW * 4; - if (g_sm.write) { - uint64_t k2 = (uintptr_t)g_sm.k, v2 = (uintptr_t)g_sm.v; - s.cbank[OMEGA_PATTN_ARG_KC2 / 4] = (uint32_t)k2; s.cbank[OMEGA_PATTN_ARG_KC2 / 4 + 1] = (uint32_t)(k2 >> 32); - s.cbank[OMEGA_PATTN_ARG_VC2 / 4] = (uint32_t)v2; s.cbank[OMEGA_PATTN_ARG_VC2 / 4 + 1] = (uint32_t)(v2 >> 32); - s.cbank[OMEGA_PATTN_ARG_KV_STRIDE2 / 4] = g_sm.kvs; - s.ranges[5].lo = (uintptr_t)g_sm.k; s.ranges[5].hi = (uintptr_t)g_sm.k + 2 * g_sm.plane; s.nranges = 6; - } - if (g_sm.read) { /* ATTEND reads only the mirror: the cache range is replaced, so a stray cache read faults */ - uint64_t k2 = (uintptr_t)g_sm.k, v2 = (uintptr_t)g_sm.v; - s.cbank[OMEGA_PATTN_ARG_KC / 4] = (uint32_t)k2; s.cbank[OMEGA_PATTN_ARG_KC / 4 + 1] = (uint32_t)(k2 >> 32); - s.cbank[OMEGA_PATTN_ARG_VC / 4] = (uint32_t)v2; s.cbank[OMEGA_PATTN_ARG_VC / 4 + 1] = (uint32_t)(v2 >> 32); - s.cbank[OMEGA_PATTN_ARG_KV_STRIDE / 4] = g_sm.kvs; - s.ranges[1].lo = (uintptr_t)g_sm.k; s.ranges[1].hi = (uintptr_t)g_sm.k + 2 * g_sm.plane; - } - int err = ws_run(&s, (mc + W - 1) / W, 4); - if (err) { snprintf(msg, n, "launch at %u: %s (pc %d)", p0, s.msg, s.err_pc); return -1; } - g_sim_issues += s.warp_issues; - return 0; -} -/* runs the API's launch plan through the simulator on host buffers; kv: [K plane | V plane] holding the history. - * progs[mode]; split: one APPEND + one ATTEND launch over all m tokens, else fused 64-token chunks */ -static int sim_call(BlackwellIRProgram *const progs[4], int split, uint32_t W, const Case *c, uint8_t *kv, size_t plane, const float *rope, const float *norms, - float out_scale, float *out, int order, char *msg, size_t n) { - float *qbuf = aligned_alloc(16, (size_t)c->m * QKVW * 4), *obuf = aligned_alloc(16, (size_t)c->m * OUTW * 4); - memcpy(qbuf, c->qkv, (size_t)c->m * QKVW * 4); - for (size_t i = 0; i < (size_t)c->m * OUTW; i++) obuf[i] = -999.0f; - int err = 0; - if (split) { - uint8_t *mir = NULL; - if (split == 2) { /* the API's mirror plan: history rows copied in, APPEND writes both, ATTEND reads the mirror */ - const uint32_t P = c->pos0 + c->m, Pr = (P + 31) & ~31u; - g_sm.kvs = Pr * 256; g_sm.plane = (size_t)4 * g_sm.kvs; - mir = aligned_alloc(16, 2 * g_sm.plane); memset(mir, 0, 2 * g_sm.plane); - g_sm.k = mir; g_sm.v = mir + g_sm.plane; - for (unsigned h = 0; h < 4; h++) { - memcpy(g_sm.k + (size_t)h * g_sm.kvs, kv + (size_t)h * c->max_pos * 256, (size_t)c->pos0 * 256); - memcpy(g_sm.v + (size_t)h * g_sm.kvs, kv + plane + (size_t)h * c->max_pos * 256, (size_t)c->pos0 * 256); - } - g_sm.write = 1; - } - err = sim_launch(progs[split == 2 ? 3 : OMEGA_PATTN_MODE_APPEND], W, c, kv, plane, rope, norms, out_scale, qbuf, obuf, c->pos0, c->m, order, msg, n); - /* APPEND writes no output */ - for (size_t i = 0; i < (size_t)c->m * OUTW && !err; i++) if (obuf[i] != -999.0f) { err = -1; snprintf(msg, n, "APPEND launch wrote output word %zu", i); } - if (split == 2 && !err) for (unsigned h = 0; h < 4 && !err; h++) { /* the mirror holds exactly the cache rows 0 .. P-1 */ - const size_t P = (size_t)c->pos0 + c->m; - if (memcmp(g_sm.k + (size_t)h * g_sm.kvs, kv + (size_t)h * c->max_pos * 256, P * 256) || - memcmp(g_sm.v + (size_t)h * g_sm.kvs, kv + plane + (size_t)h * c->max_pos * 256, P * 256)) { err = -1; snprintf(msg, n, "mirror rows of head %u differ from the cache", h); } - } - g_sm.write = 0; g_sm.read = split == 2; - if (!err) err = sim_launch(progs[OMEGA_PATTN_MODE_ATTEND], W, c, kv, plane, rope, norms, out_scale, qbuf, obuf, c->pos0, c->m, order, msg, n); - g_sm.read = 0; free(mir); - } else { - for (uint32_t done = 0; done < c->m && !err; done += 64) { - const uint32_t mc = c->m - done < 64 ? c->m - done : 64; - err = sim_launch(progs[OMEGA_PATTN_MODE_FUSED], W, c, kv, plane, rope, norms, out_scale, qbuf + (size_t)done * QKVW, obuf + (size_t)done * OUTW, - c->pos0 + done, mc, order, msg, n); - } - } - if (!err) { - size_t unwritten = 0; for (size_t i = 0; i < (size_t)c->m * OUTW; i++) if (obuf[i] == -999.0f) unwritten++; - if (unwritten) { snprintf(msg, n, "%zu output words never written", unwritten); err = -1; } - else memcpy(out, obuf, (size_t)c->m * OUTW * 4); - } - free(qbuf); free(obuf); - return err; -} -static int sim_point(uint32_t W, int mutant, int split, uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int orders, - char *msg, size_t n, double *worst, size_t *bad) { - static BlackwellIRProgram p0, p1, p2, p3; - BlackwellIRProgram *const progs[4] = { &p0, &p1, &p2, &p3 }; - for (uint32_t md = 0; md < 4; md++) { - OmegaPrefillAttnSpec spec = { W, mutant, md == 3 ? OMEGA_PATTN_MODE_APPEND : md, md == 3 }; - if (omega_blackwell_codegen_prefill_attn_prog(&spec, progs[md]) != 0) { snprintf(msg, n, "codegen refused (mode %u)", md); return -1; } - } - Case c; case_make(&c, max_pos, pos0, m, seed, qscale); - size_t plane = (size_t)4 * max_pos * 256 + OMEGA_DATTN_PLANE_SLACK; - uint8_t *kv = aligned_alloc(16, 2 * plane); - float *rope = aligned_alloc(16, (size_t)max_pos * 512); for (uint32_t p = 0; p < max_pos; p++) omega_dattn_rope_row(p, THETA, rope + (size_t)p * 128); - float *norms = aligned_alloc(16, 1024); memcpy(norms, c.qn, 512); memcpy(norms + 128, c.kn, 512); - float *out = malloc((size_t)m * OUTW * 4), *copy = malloc((size_t)m * OUTW * 4); - int err = 0; - for (int order = 0; order < orders && !err; order++) { - memset(kv, 0, 2 * plane); - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); - err = sim_call(progs, split, W, &c, kv, plane, rope, norms, 1.0f, out, order, msg, n); - if (!err && order == 0) memcpy(copy, out, (size_t)m * OUTW * 4); - else if (!err && memcmp(copy, out, (size_t)m * OUTW * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - size_t kd, vd; int mu; - rows_vs_emu(&c, (const uint16_t *)kv, (const uint16_t *)(kv + plane), &kd, &vd, &mu); - *bad = parity(&c, (const uint16_t *)kv, (const uint16_t *)(kv + plane), out, 1.0f, worst); - if (kd || vd) *bad += 1000000; - snprintf(msg, n, "bad=%zu worst=%.3f rows: k %zu v %zu words differ from the emulation (max %d ulp)", *bad, *worst, kd, vd, mu); - } - free(kv); free(rope); free(norms); free(out); free(copy); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[300]; double worst; size_t bad; - struct { uint32_t w, max_pos, pos0, m; float qs; int orders, split; const char *name; } pts[] = { - { 8, 256, 0, 1, 1.0f, 2, 0, "one token at position 0" }, - { 8, 256, 0, 5, 1.0f, 2, 0, "5 tokens from 0 (partial CTA)" }, - { 4, 256, 37, 19, 1.0f, 2, 0, "19 tokens from 37, warps 4" }, - { 8, 256, 37, 19, 4.0f, 1, 0, "19 tokens from 37, sharp q (x4)" }, - { 8, 256, 100, 64, 1.0f, 1, 0, "64 tokens from 100 (full chunk)" }, - { 8, 512, 0, 70, 1.0f, 1, 0, "70 tokens from 0 (two chunks)" }, - { 4, 512, 200, 33, 1.0f, 1, 0, "33 tokens from 200, warps 4" }, - { 8, 256, 0, 1, 1.0f, 2, 1, "split: one token at position 0" }, - { 8, 256, 0, 5, 1.0f, 2, 1, "split: 5 tokens from 0" }, - { 4, 256, 37, 19, 1.0f, 2, 1, "split: 19 tokens from 37, warps 4" }, - { 8, 512, 0, 70, 1.0f, 1, 1, "split: 70 tokens from 0" }, - { 8, 512, 37, 141, 4.0f, 1, 1, "split: 141 tokens from 37, sharp q" }, - { 8, 256, 0, 5, 1.0f, 2, 2, "mirror: 5 tokens from 0" }, - { 4, 256, 37, 19, 1.0f, 2, 2, "mirror: 19 tokens from 37, warps 4" }, - { 8, 512, 37, 141, 4.0f, 1, 2, "mirror: 141 tokens from 37, sharp q" }, - { 8, 512, 300, 45, 1.0f, 1, 2, "mirror: 45 tokens from 300" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - int err = sim_point(pts[i].w, 0, pts[i].split, pts[i].max_pos, pts[i].pos0, pts[i].m, pts[i].qs, 100 + (uint32_t)i, pts[i].orders, msg, sizeof msg, &worst, &bad); - CHECK(err == 0 && bad == 0, "sim %s: %s", pts[i].name, msg); - printf("sim %-40s W=%u: %s %s\n", pts[i].name, pts[i].w, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - fflush(stdout); - } - for (int split = 0; split <= 2; split++) for (int m = 1; m <= 4; m++) { - int err = sim_point(8, m, split, 256, 40, 24, 1.0f, 200, 1, msg, sizeof msg, &worst, &bad); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim %s mutant %d NOT caught (%s)", split == 2 ? "mirror" : split ? "split" : "fused", m, msg); - printf("sim %s mutant %d at 24 tokens from 40: %s (%s)\n", split == 2 ? "mirror" : split ? "split" : "fused", m, caught ? "caught" : "MISSED", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static FILE *g_json; -static int g_warm; /* untimed calls before each timing series (--warm N) */ -static int g_cached; /* --cached: device-entry checks use omega_gpu_pf_alloc_dev buffers (needs PATTN_HAVE_PF) */ -static int g_mirror_on = 1; -static int g_fused; /* --fused: the cut-1 fused path, which never builds a K/V mirror */ -/* the mirror contract: forget the cache's K/V mirrors before freeing it */ -static void cache_free(OmegaGpuDecodeAttnCache *c) { omega_gpu_prefill_attn_kv_mirror_forget(c); omega_gpu_decode_attn_cache_free(c); } -static int cache_with_history(const Case *c, OmegaGpuDecodeAttnCache **out) { - int rc = omega_gpu_decode_attn_cache_alloc(1, c->max_pos, THETA, out); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - rc = omega_gpu_decode_attn_set_norms(*out, 0, c->qn, c->kn); - for (unsigned g = 0; g < 4 && rc == OMEGA_GPU_DATTN_OK && c->pos0; g++) - rc = omega_gpu_decode_attn_cache_write(*out, 0, g, 0, c->pos0, c->kc + (size_t)g * c->max_pos * 128, c->vc + (size_t)g * c->max_pos * 128); - return rc; -} -/* reads rows pos0 .. pos0+m-1 of every KV head into the case-shaped arrays kc/vc (history copied from the case) */ -static int read_rows(OmegaGpuDecodeAttnCache *cc, const Case *c, uint16_t *kc, uint16_t *vc) { - memcpy(kc, c->kc, (size_t)4 * c->max_pos * 256); memcpy(vc, c->vc, (size_t)4 * c->max_pos * 256); - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < c->m; t++) { - size_t o = ((size_t)g * c->max_pos + c->pos0 + t) * 128; - if (omega_gpu_decode_attn_cache_read(cc, 0, g, c->pos0 + t, kc + o, vc + o) != OMEGA_GPU_DATTN_OK) return -1; - } - return 0; -} -static int chip_point(uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int with_decode, float out_scale, int reps) { - Case c; case_make(&c, max_pos, pos0, m, seed, qscale); - OmegaGpuDecodeAttnCache *pc = NULL, *dc = NULL; - float *out = malloc((size_t)m * OUTW * 4), *out2 = malloc((size_t)m * OUTW * 4), *dout = malloc((size_t)m * OUTW * 4); - uint16_t *kc = malloc((size_t)4 * max_pos * 256), *vc = malloc((size_t)4 * max_pos * 256); - uint16_t *dk = malloc((size_t)4 * max_pos * 256), *dv = malloc((size_t)4 * max_pos * 256); - int ok = 1; - OmegaGpuPrefillAttnInfo info; - int rc = cache_with_history(&c, &pc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK, "chip prefill pos0 %u m %u: rc %s (%s)", pos0, m, omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - CHECK(read_rows(pc, &c, kc, vc) == 0, "read rows"); - double worst; size_t bad = parity(&c, kc, vc, out, out_scale, &worst); - size_t kd, vd; int mu; rows_vs_emu(&c, kc, vc, &kd, &vd, &mu); - CHECK(bad == 0, "chip pos0 %u m %u: %zu outputs outside the tolerance (worst %.3f)", pos0, m, bad, worst); - CHECK(vd == 0 && mu <= 1, "chip pos0 %u m %u: rows vs host emulation: k %zu differ (max %d ulp), v %zu differ", pos0, m, kd, mu, vd); - printf("chip pos0 %5u m %5u: parity bad=%zu worst=%.3f; rows vs emulation k %zu (max %d ulp) v %zu; chunks %u grid %ux%u x%u thr; chip %.3f ms call %.3f ms\n", - pos0, m, bad, worst, kd, mu, vd, info.chunks, info.grid_x, info.grid_y, info.threads, info.elapsed_ns / 1e6, info.call_ns / 1e6); - ok &= bad == 0 && vd == 0 && mu <= 1; - /* second call: same rows rewritten, output bit-identical */ - rc = omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, NULL); - int same = rc == OMEGA_GPU_DATTN_OK && memcmp(out, out2, (size_t)m * OUTW * 4) == 0; - CHECK(same, "chip pos0 %u m %u: second call not bit-identical", pos0, m); - ok &= same; - double pre_med = 0, dec_ms = 0; - if (reps > 0) { - uint64_t *t = malloc(sizeof(uint64_t) * reps), *tc = malloc(sizeof(uint64_t) * reps); - static uint64_t lns[256], worst_l[256]; uint32_t worst_n = 0; uint64_t worst_t = 0; - for (int r = 0; r < g_warm; r++) omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, NULL); - printf(" reps chip ms (in order, %d untimed warm calls first):", g_warm); - for (int r = 0; r < reps; r++) { - omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, &info); t[r] = info.elapsed_ns; tc[r] = info.call_ns; - uint32_t nl = omega_gpu_prefill_attn_test_launch_ns(lns, 256); - printf(" %.3f", t[r] / 1e6); - if (t[r] > worst_t) { worst_t = t[r]; worst_n = nl < 256 ? nl : 256; memcpy(worst_l, lns, worst_n * sizeof *lns); } - } - printf("\n slowest rep, per launch ms (%u launches):", worst_n); - for (uint32_t i = 0; i < worst_n; i++) printf(" %.3f", worst_l[i] / 1e6); - printf("\n"); - qsort(t, reps, sizeof *t, cmp_u64); qsort(tc, reps, sizeof *tc, cmp_u64); - pre_med = t[reps / 2] / 1e6; - double flops = 0; for (uint32_t i = 0; i < m; i++) flops += 4.0 * 32 * 128 * (pos0 + i + 1.0); - printf(" timing prefill pos0 %u m %u: chip median %.3f ms (min %.3f) call median %.3f ms; %.2f useful TFLOPS on chip time\n", - pos0, m, pre_med, t[0] / 1e6, tc[reps / 2] / 1e6, flops / (pre_med * 1e-3) / 1e12); - if (g_json) fprintf(g_json, " {\"pos0\": %u, \"m\": %u, \"prefill_chip_ms_median\": %.4f, \"prefill_call_ms_median\": %.4f, \"useful_tflops\": %.3f},\n", pos0, m, pre_med, tc[reps / 2] / 1e6, flops / (pre_med * 1e-3) / 1e12); - free(t); free(tc); - } - if (with_decode) { - /* gate 2: m decode steps on a twin cache: rows bit-identical, outputs within the tolerance of each other */ - rc = cache_with_history(&c, &dc); - uint64_t chip = 0, call = 0; OmegaGpuDecodeAttnInfo di; - for (uint32_t i = 0; i < m && rc == OMEGA_GPU_DATTN_OK; i++) { rc = omega_gpu_decode_attn(dc, 0, pos0 + i, c.qkv + (size_t)i * QKVW, EPS, out_scale, dout + (size_t)i * OUTW, &di); chip += di.elapsed_ns; call += di.call_ns; } - CHECK(rc == OMEGA_GPU_DATTN_OK, "decode twin: rc %s (%s)", omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc == OMEGA_GPU_DATTN_OK && read_rows(dc, &c, dk, dv) == 0) { - size_t rk = 0, rv = 0; - for (unsigned g = 0; g < 4; g++) for (uint32_t t2 = 0; t2 < m; t2++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + pos0 + t2) * 128 + i; rk += kc[o] != dk[o]; rv += vc[o] != dv[o]; } - double dw = 0; size_t dbad = 0, tol_n = 0; - for (size_t i = 0; i < (size_t)m * OUTW; i++) { double d = fabs((double)out[i] - (double)dout[i]) / (1e-2 * out_scale); if (d > dw) dw = d; if (d > 1.0) dbad++; tol_n++; } - CHECK(rk == 0 && rv == 0, "gate 2: prefill rows differ from the decode kernel's rows: k %zu v %zu", rk, rv); - CHECK(dbad == 0, "gate 2: prefill vs decode outputs: %zu outside the tolerance (worst %.3f)", dbad, dw); - dec_ms = chip / 1e6; - printf(" gate 2 vs %u decode steps: rows k %zu v %zu differ; outputs worst %.3f of tol; decode loop chip %.3f ms call %.3f ms%s\n", - m, rk, rv, dw, chip / 1e6, call / 1e6, pre_med > 0 ? "" : ""); - if (pre_med > 0) printf(" speed: prefill %.3f ms vs decode loop %.3f ms chip time: %.1fx\n", pre_med, dec_ms, dec_ms / pre_med); - if (g_json) fprintf(g_json, " {\"pos0\": %u, \"m\": %u, \"gate2_rows_k_diff\": %zu, \"gate2_rows_v_diff\": %zu, \"gate2_out_worst\": %.4f, \"decode_loop_chip_ms\": %.4f, \"decode_loop_call_ms\": %.4f},\n", pos0, m, rk, rv, dw, chip / 1e6, call / 1e6); - ok &= rk == 0 && rv == 0 && dbad == 0; - } else ok = 0; - } -done: - if (pc) cache_free(pc); - if (dc) cache_free(dc); - free(out); free(out2); free(dout); free(kc); free(vc); free(dk); free(dv); case_free(&c); - return ok; -} -/* device-resident entry: qkv and out in session buffers (GPU VAs); output and rows must equal the host entry's bit for bit */ -static int dev_buf(size_t bytes, OmegaGpuMem *m) { - omega_gpu_session_lock(); - int rc = omega_gpu_session_open() ? omega_gpu_session_alloc(bytes, m) : -1; - omega_gpu_session_unlock(); - return rc; -} -static int chip_dev(uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t seed, int reps) { - Case c; case_make(&c, max_pos, pos0, m, seed, 1.0f); - OmegaGpuDecodeAttnCache *hc = NULL, *dc = NULL; - float *hout = malloc((size_t)m * OUTW * 4); - uint16_t *hk = malloc((size_t)4 * max_pos * 256), *hv = malloc((size_t)4 * max_pos * 256); - uint16_t *dk = malloc((size_t)4 * max_pos * 256), *dv = malloc((size_t)4 * max_pos * 256); - OmegaGpuMem q, o; memset(&q, 0, sizeof q); memset(&o, 0, sizeof o); - float *odh = NULL; - int ok = 1; - OmegaGpuPrefillAttnInfo info, dinfo; - int rc = cache_with_history(&c, &hc); - if (rc == OMEGA_GPU_DATTN_OK) rc = cache_with_history(&c, &dc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(hc, 0, pos0, m, c.qkv, EPS, 1.0f, hout, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK, "dev point %u+%u: host entry rc %s", pos0, m, omega_gpu_decode_attn_rc_name(rc)); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } -#if PATTN_HAVE_PF - if (g_cached) { /* W-L1G's GPU-cached device-private buffers, filled and read only through GPU copies */ - CHECK(omega_gpu_pf_alloc_dev((size_t)m * QKVW * 4, &q) == OMEGA_GPU_PF_OK && omega_gpu_pf_alloc_dev((size_t)m * OUTW * 4, &o) == OMEGA_GPU_PF_OK, "dev point: cached device buffers"); - if (!q.va || !o.va) { ok = 0; goto done; } - odh = malloc((size_t)m * OUTW * 4); - for (size_t i = 0; i < (size_t)m * OUTW; i++) odh[i] = -999.0f; - CHECK(omega_gpu_pf_upload(&q, 0, c.qkv, (size_t)m * QKVW * 4) == OMEGA_GPU_PF_OK && omega_gpu_pf_upload(&o, 0, odh, (size_t)m * OUTW * 4) == OMEGA_GPU_PF_OK, "dev point: upload through the copy kernel"); - } else -#endif - { - CHECK(dev_buf((size_t)m * QKVW * 4, &q) == 0 && dev_buf((size_t)m * OUTW * 4, &o) == 0, "dev point: session buffers"); - if (!q.cpu || !o.cpu) { ok = 0; goto done; } - memcpy(q.cpu, c.qkv, (size_t)m * QKVW * 4); - float *op = o.cpu; for (size_t i = 0; i < (size_t)m * OUTW; i++) op[i] = -999.0f; - omega_gpu_session_lock(); omega_gpu_session_sync_to_gpu(&q); omega_gpu_session_sync_to_gpu(&o); omega_gpu_session_unlock(); - } - /* negative control: misaligned and zero VAs are refused before any launch */ - CHECK(omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va + 4, EPS, 1.0f, o.va, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "dev: misaligned qkv VA refused"); - CHECK(omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, 0, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "dev: zero out VA refused"); - rc = omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, &dinfo); - CHECK(rc == OMEGA_GPU_DATTN_OK, "dev point %u+%u: rc %s (%s)", pos0, m, omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - float *od; -#if PATTN_HAVE_PF - if (g_cached) { CHECK(omega_gpu_pf_download(&o, 0, odh, (size_t)m * OUTW * 4) == OMEGA_GPU_PF_OK, "dev point: download through the copy kernel"); od = odh; } - else -#endif - { omega_gpu_session_lock(); omega_gpu_session_sync_to_cpu(&o); omega_gpu_session_unlock(); od = o.cpu; } - size_t unw = 0, diff = 0; - for (size_t i = 0; i < (size_t)m * OUTW; i++) { if (od[i] == -999.0f) unw++; else if (memcmp(&od[i], &hout[i], 4)) diff++; } - CHECK(read_rows(hc, &c, hk, hv) == 0 && read_rows(dc, &c, dk, dv) == 0, "dev point: read rows"); - size_t rk = 0, rv = 0; - for (size_t i = 0; i < (size_t)4 * max_pos * 128; i++) { rk += hk[i] != dk[i]; rv += hv[i] != dv[i]; } - CHECK(unw == 0 && diff == 0, "dev point %u+%u: %zu outputs unwritten, %zu differ from the host entry", pos0, m, unw, diff); - CHECK(rk == 0 && rv == 0, "dev point %u+%u: cache rows differ from the host entry: k %zu v %zu", pos0, m, rk, rv); - ok &= unw == 0 && diff == 0 && rk == 0 && rv == 0; - printf("chip dev%s pos0 %5u m %5u: outputs vs host entry: %zu unwritten, %zu differ; rows k %zu v %zu differ; launches %u grid %ux%u; chip %.3f ms call %.3f ms\n", - g_cached ? " (cached buffers)" : "", pos0, m, unw, diff, rk, rv, dinfo.chunks, dinfo.grid_x, dinfo.grid_y, dinfo.elapsed_ns / 1e6, dinfo.call_ns / 1e6); - if (reps > 0) { - uint64_t *t = malloc(sizeof(uint64_t) * reps), *tc = malloc(sizeof(uint64_t) * reps); - for (int r = 0; r < g_warm; r++) omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, NULL); - printf(" dev reps chip ms:"); - for (int r = 0; r < reps; r++) { omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, &dinfo); t[r] = dinfo.elapsed_ns; tc[r] = dinfo.call_ns; printf(" %.3f", t[r] / 1e6); } - qsort(t, reps, sizeof *t, cmp_u64); qsort(tc, reps, sizeof *tc, cmp_u64); - double flops = 0; for (uint32_t i = 0; i < m; i++) flops += 4.0 * 32 * 128 * (pos0 + i + 1.0); - printf("\n timing dev pos0 %u m %u: chip median %.3f ms (min %.3f) call median %.3f ms; %.2f useful TFLOPS on chip time\n", - pos0, m, t[reps / 2] / 1e6, t[0] / 1e6, tc[reps / 2] / 1e6, flops / (t[reps / 2] * 1e-9) / 1e12); - if (g_json) fprintf(g_json, " {\"dev\": 1, \"pos0\": %u, \"m\": %u, \"chip_ms_median\": %.4f, \"chip_ms_min\": %.4f, \"call_ms_median\": %.4f, \"out_diff\": %zu, \"rows_diff\": %zu},\n", - pos0, m, t[reps / 2] / 1e6, t[0] / 1e6, tc[reps / 2] / 1e6, diff, rk + rv); - free(t); free(tc); - } -done: -#if PATTN_HAVE_PF - if (g_cached) { if (q.va) omega_gpu_pf_free(&q); if (o.va) omega_gpu_pf_free(&o); } else -#endif - { omega_gpu_session_lock(); if (q.cpu) omega_gpu_session_free(&q); if (o.cpu) omega_gpu_session_free(&o); omega_gpu_session_unlock(); } - free(odh); - if (hc) cache_free(hc); - if (dc) cache_free(dc); - free(hout); free(hk); free(hv); free(dk); free(dv); case_free(&c); - return ok; -} -/* persistent mirror (cut 5): prefill 300, decode 5, prefill 64, then a foreign rewrite of rows 0..99 and prefill 32. - * Cache X runs with the mirror, cache Y without (cut 3 path, the reference). Outputs must be bit-identical, except - * the negative control: the rewrite WITHOUT invalidate must make X differ (the stale mirror is visible), and after - * invalidate X must match again. */ -static int chip_continuation(void) { - if (!omega_gpu_prefill_attn_kv_mirror_available() || !g_mirror_on) { printf("chip continuation: skipped (no mirror in this build or --no-mirror)\n"); return 1; } - /* the mirror lives on the split path (APPEND + ATTEND): the API calls mirror_get only when not fused, so the fused - * path never builds one and the check has nothing to compare there. The default (split) run covers it. */ - if (g_fused) { printf("chip continuation: skipped (--fused: the fused path builds no K/V mirror; the split run covers it)\n"); return 1; } - const uint32_t MP = 1024, NA = 300, ND = 5, NB = 64, NC = 32, N = NA + ND + NB + NC; - Case c, junk; case_make(&c, MP, 0, N, 21, 1.0f); case_make(&junk, MP, 100, 1, 22, 1.0f); - OmegaGpuDecodeAttnCache *x = NULL, *y = NULL; - float *ox = malloc((size_t)N * OUTW * 4), *oy = malloc((size_t)N * OUTW * 4), *ox2 = malloc((size_t)NC * OUTW * 4); - int ok = 1, rc = cache_with_history(&c, &x); - if (rc == OMEGA_GPU_DATTN_OK) rc = cache_with_history(&c, &y); - OmegaGpuDecodeAttnInfo di; - OmegaGpuDecodeAttnCache *cs[2] = { x, y }; - float *os[2] = { ox, oy }; - for (int k = 0; k < 2 && rc == OMEGA_GPU_DATTN_OK; k++) { - omega_gpu_prefill_attn_set_kv_mirror(k == 0); - const float *q = c.qkv; float *o = os[k]; - rc = omega_gpu_prefill_attn(cs[k], 0, 0, NA, q, EPS, 1.0f, o, NULL); - for (uint32_t i = 0; i < ND && rc == OMEGA_GPU_DATTN_OK; i++) - rc = omega_gpu_decode_attn(cs[k], 0, NA + i, q + (size_t)(NA + i) * QKVW, EPS, 1.0f, o + (size_t)(NA + i) * OUTW, &di); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(cs[k], 0, NA + ND, NB, q + (size_t)(NA + ND) * QKVW, EPS, 1.0f, o + (size_t)(NA + ND) * OUTW, NULL); - } - CHECK(rc == OMEGA_GPU_DATTN_OK, "continuation: rc %s (%s)", omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - OmegaGpuPrefillAttnMirrorView mv; - int vrc = omega_gpu_prefill_attn_kv_mirror_view(x, 0, &mv); - CHECK(vrc == OMEGA_GPU_DATTN_OK && mv.valid == NA + ND + NB && mv.kv_stride == MP * 256u, "continuation: mirror view valid %u (want %u) stride %u", mv.valid, NA + ND + NB, mv.kv_stride); - size_t d1 = 0; for (size_t i = 0; i < (size_t)(NA + ND + NB) * OUTW; i++) d1 += memcmp(&ox[i], &oy[i], 4) != 0; - CHECK(d1 == 0, "continuation: %zu outputs differ, mirror vs no mirror", d1); - /* foreign writer: rows 0..99 of head 0 rewritten in both caches */ - for (int k = 0; k < 2; k++) omega_gpu_decode_attn_cache_write(cs[k], 0, 0, 0, 100, junk.kc, junk.vc); - const size_t offC = (size_t)(NA + ND + NB); - omega_gpu_prefill_attn_set_kv_mirror(0); - rc = omega_gpu_prefill_attn(y, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, oy + offC * OUTW, NULL); - omega_gpu_prefill_attn_set_kv_mirror(1); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(x, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, ox2, NULL); /* no invalidate */ - size_t stale = 0; for (size_t i = 0; i < (size_t)NC * OUTW; i++) stale += memcmp(&ox2[i], &oy[offC * OUTW + i], 4) != 0; - omega_gpu_prefill_attn_kv_mirror_invalidate(x, UINT32_MAX, 0); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(x, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, ox + offC * OUTW, NULL); - size_t d2 = 0; for (size_t i = 0; i < (size_t)NC * OUTW; i++) d2 += memcmp(&ox[offC * OUTW + i], &oy[offC * OUTW + i], 4) != 0; - CHECK(rc == OMEGA_GPU_DATTN_OK, "continuation C: rc %s", omega_gpu_decode_attn_rc_name(rc)); - CHECK(stale > 0, "negative control: a foreign rewrite without invalidate must show (stale mirror), %zu outputs differ", stale); - CHECK(d2 == 0, "after invalidate: %zu outputs differ, mirror vs no mirror", d2); - printf("chip continuation (prefill %u, decode %u, prefill %u, rewrite, prefill %u): mirror valid %u; outputs differ mirror vs none: %zu; " - "stale control %zu differ (must be > 0); after invalidate %zu differ\n", NA, ND, NB, NC, mv.valid, d1, stale, d2); - ok &= d1 == 0 && stale > 0 && d2 == 0 && vrc == OMEGA_GPU_DATTN_OK; -done: - omega_gpu_prefill_attn_set_kv_mirror(1); - if (x) cache_free(x); - if (y) cache_free(y); - free(ox); free(oy); free(ox2); case_free(&c); case_free(&junk); - return ok; -} -static void chip_mutants(void) { - for (int mu = 1; mu <= 4; mu++) { - omega_gpu_prefill_attn_test_set_mutant(mu); - Case c; case_make(&c, 256, 40, 24, 200, 1.0f); - OmegaGpuDecodeAttnCache *pc = NULL; - float *out = malloc((size_t)24 * OUTW * 4); - uint16_t *kc = malloc((size_t)4 * 256 * 256), *vc = malloc((size_t)4 * 256 * 256); - int rc = cache_with_history(&c, &pc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(pc, 0, 40, 24, c.qkv, EPS, 1.0f, out, NULL); - int caught = rc != OMEGA_GPU_DATTN_OK; - double worst = 0; size_t bad = 0, kd = 0, vd = 0; int mx = 0; - if (!caught && read_rows(pc, &c, kc, vc) == 0) { - bad = parity(&c, kc, vc, out, 1.0f, &worst); - rows_vs_emu(&c, kc, vc, &kd, &vd, &mx); - caught = bad > 0 || vd > 0 || mx > 1; - } - CHECK(caught, "chip mutant %d NOT caught", mu); - printf("chip mutant %d: %s (rc %s, bad %zu, worst %.2f, rows k %zu v %zu)\n", mu, caught ? "caught" : "MISSED", omega_gpu_decode_attn_rc_name(rc), bad, worst, kd, vd); - if (pc) cache_free(pc); - free(out); free(kc); free(vc); case_free(&c); - } - omega_gpu_prefill_attn_test_set_mutant(0); -} - -int main(int argc, char **argv) { - int host = 0, sim = 0, reps = 9, quick = 0, fused = 0, timing_only = 0; const char *json = NULL; uint32_t warps = 0; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--sim")) sim = 1; - else if (!strcmp(argv[i], "--quick")) quick = 1; - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--warps") && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) json = argv[++i]; - else if (!strcmp(argv[i], "--fused")) fused = g_fused = 1; - else if (!strcmp(argv[i], "--no-mirror")) { omega_gpu_prefill_attn_set_kv_mirror(0); g_mirror_on = 0; } - else if (!strcmp(argv[i], "--cached") && PATTN_HAVE_PF) g_cached = 1; - else if (!strcmp(argv[i], "--mirror-per-call")) omega_gpu_prefill_attn_test_set_mirror_per_call(1); - else if (!strcmp(argv[i], "--timing-only")) timing_only = 1; - else if (!strcmp(argv[i], "--warm") && i + 1 < argc) g_warm = atoi(argv[++i]); - else { fprintf(stderr, "usage: %s [--host-only | --sim | [--quick] [--reps N] [--warps 4|8] [--fused] [--no-mirror] [--mirror-per-call] [--cached] [--warm N] [--timing-only] [--out receipt.json]]\n", argv[0]); return 2; } - } - host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (json) { g_json = fopen(json, "w"); if (g_json) fprintf(g_json, "{\"test\": \"gpu_prefill_attn\", \"points\": [\n"); } - if (warps) omega_gpu_prefill_attn_set_warps(warps); - int ok = 1; - if (fused) omega_gpu_prefill_attn_set_fused(1); - printf("path: %s, warps %u, warm %d, dev buffers %s\n", fused ? "fused 64-token chunks" : g_mirror_on && omega_gpu_prefill_attn_kv_mirror_available() ? "split APPEND + ATTEND, ATTEND reads the GPU-cached K/V mirror" : "split APPEND + ATTEND, ATTEND reads the uncached cache", warps ? warps : OMEGA_GPU_PATTN_WARPS, g_warm, g_cached ? "GPU-cached (pf_alloc_dev)" : "session (uncached)"); - if (timing_only) { - ok &= chip_point(4096, 0, 2048, 1.0f, 8, 0, 1.0f, reps); - ok &= chip_dev(4096, 0, 2048, 8, reps); - ok &= chip_dev(8192, 4096, 1500, 12, reps); - ok &= chip_point(4096, 4032, 64, 1.0f, 7, 0, 1.0f, reps); - ok &= chip_dev(8192, 4096, 64, 13, reps); - } else { - ok &= chip_point(256, 0, 1, 1.0f, 1, 1, 1.0f, 0); - ok &= chip_point(256, 37, 19, 1.0f, 2, 1, 1.0f, 0); - ok &= chip_point(256, 0, 64, 1.0f, 3, 1, 1.0f, reps); - ok &= chip_point(512, 100, 70, 4.0f, 4, 1, 1.0f, 0); - ok &= chip_point(512, 200, 64, 1.0f, 5, 1, 18446744073709551616.0f, 0); - if (!quick) { - ok &= chip_point(1024, 0, 512, 1.0f, 6, 1, 1.0f, reps); - ok &= chip_point(4096, 4032, 64, 1.0f, 7, 1, 1.0f, reps); - ok &= chip_point(4096, 0, 2048, 1.0f, 8, 0, 1.0f, reps); - } - ok &= chip_dev(512, 100, 70, 11, 0); - if (!quick) { ok &= chip_dev(4096, 0, 2048, 8, reps); ok &= chip_dev(8192, 4096, 1500, 12, reps); } - ok &= chip_continuation(); - chip_mutants(); - } - (void)ok; - if (g_json) { fprintf(g_json, " {}\n], \"checks\": %d, \"failed\": %d}\n", g_checks, g_failed); fclose(g_json); } - } - printf("gpu_prefill_attn_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_qgemm_test.c b/tests/gpu_qgemm_test.c deleted file mode 100644 index 5e209a733..000000000 --- a/tests/gpu_qgemm_test.c +++ /dev/null @@ -1,438 +0,0 @@ -/* gpu_qgemm_test.c (OWN-30B L1 GEMM, W-L1G, 2026-10-14): the native FP8 prefill path (omega_blackwell_codegen_qg.h). - * --host-only reference self-checks - * --sim kernels in the warp simulator bit-identical to the C reference; mutants caught (a simulator error is a FAIL) - * --chip (under flock /tmp/aien-gb10.lock) through the device API: bit-identical to the reference, mutants caught, - * medians at --tokens - * Verdict line last: "GPU_QGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_qg.h" -#include "omega_gpu_prefill.h" -#include "omega_gpu_fp8_api.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* ---------------- quantiser reference (header semantics) ---------------- */ -static void pq_ref(const float *x, uint32_t k, uint8_t *q, float *s, int mutant) { - for (uint32_t b = 0; b < k / 128; b++) { - float m = ldexpf(1.0f, -100); - if (mutant == 1) { /* lane-local amax: lane l sees elements 4l..4l+3 only (scale per lane; the reference keeps lane 31's) */ - for (uint32_t l = 0; l < 32; l++) { float ml = ldexpf(1.0f, -100); for (int j = 0; j < 4; j++) ml = fmaxf(ml, fabsf(x[128 * b + 4 * l + j])); if (l == 31) m = ml; } - } else for (uint32_t j = 0; j < 128; j++) m = fmaxf(m, fabsf(x[128 * b + j])); - uint32_t mb = f2u(m), E = mb >> 23, M = mb & 0x7fffff, c = mutant == 2 ? 0 : (M + 0x1fffff) >> 23; - float scale = u2f((E + c - 8) << 23), inv = u2f((262 - E - c) << 23); - s[b] = scale; - for (uint32_t j = 0; j < 128; j++) q[128 * b + j] = qm_e4m3_rne_sat(x[128 * b + j] * inv); - } -} -static float rand_act(void) { - float v = ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; - int r = rnd() % 32; if (r == 0) v *= 300.0f; else if (r == 1) v *= 1e-3f; else if (r == 2) v = 0.0f; - return v; -} -static uint16_t bf16_rn(float f) { uint32_t u = f2u(f); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -/* rows x k activations; row 3 all zero, row 5 one huge outlier; bf16 copy when in_type is BF16 */ -static void make_x(uint32_t rows, uint32_t k, uint32_t in_type, float *x, uint16_t *xb) { - for (size_t i = 0; i < (size_t)rows * k; i++) x[i] = rand_act(); - if (rows > 3) memset(x + 3 * (size_t)k, 0, k * 4); - if (rows > 5) x[5 * (size_t)k + 77] = 3.0e4f; - if (in_type == OMEGA_QG_IN_BF16) for (size_t i = 0; i < (size_t)rows * k; i++) { xb[i] = bf16_rn(x[i]); x[i] = u2f((uint32_t)xb[i] << 16); } -} -static size_t pq_compare(const float *x, uint32_t rows, uint32_t k, const uint8_t *q, const float *s, int mutant) { - size_t bad = 0; uint8_t *rq = malloc(k); float *rs = malloc(k / 128 * 4); - for (uint32_t r = 0; r < rows; r++) { - pq_ref(x + (size_t)r * k, k, rq, rs, mutant); - for (uint32_t j = 0; j < k; j++) if (rq[j] != q[(size_t)r * k + j]) bad++; - for (uint32_t b = 0; b < k / 128; b++) if (f2u(rs[b]) != f2u(s[(size_t)r * (k / 128) + b])) bad++; - } - free(rq); free(rs); return bad; -} - -static int pq_host(void) { - int fail = 0; - /* scale choice: amax / scale in (224, 448] for normal amax */ - for (int i = 0; i < 100000; i++) { - float x[128]; for (int j = 0; j < 128; j++) x[j] = rand_act() * ldexpf(1.0f, (int)(rnd() % 40) - 20); - uint8_t q[128]; float s[1]; pq_ref(x, 128, q, s, 0); - float m = 0; for (int j = 0; j < 128; j++) m = fmaxf(m, fabsf(x[j])); - if (m > 0 && !(m / s[0] <= 448.0f && m / s[0] > 224.0f)) { if (fail < 3) printf("scale out of range: amax %g scale %g\n", m, s[0]); fail++; } - double err = 0; for (int j = 0; j < 128; j++) { double d = fabs((double)qm_e4m3(q[j]) * s[0] - x[j]); if (d > err) err = d; } - if (m > 0 && err > m * (1.0 / 16 + 1e-6)) { if (fail < 3) printf("quantisation error %g vs amax %g\n", err, m); fail++; } - } - printf("quantiser reference: %s\n", fail ? "FAIL" : "PASS (amax/scale in (224, 448], error within half an e4m3 ulp)"); - return fail; -} - -static int pq_sim_one(uint32_t k, uint32_t in_type, uint32_t rows, int mutant, size_t *bad_out, char *msg, size_t msgn) { - OmegaPqSpec sp = { k, in_type, mutant }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_pq_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - float *x = malloc((size_t)rows * k * 4); uint16_t *xb = malloc((size_t)rows * k * 2); - uint8_t *q = malloc((size_t)rows * k); float *s = malloc((size_t)rows * (k / 128) * 4); - make_x(rows, k, in_type, x, xb); - memset(q, 0xee, (size_t)rows * k); memset(s, 0xee, (size_t)rows * (k / 128) * 4); - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = 32u * (k / 128); - const void *xin = in_type == OMEGA_QG_IN_F32 ? (const void *)x : (const void *)xb; - uint64_t a[3] = { (uintptr_t)xin, (uintptr_t)q, (uintptr_t)s }; - for (int i = 0; i < 3; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)xin; ws.ranges[0].hi = (uintptr_t)xin + (size_t)rows * k * (in_type == OMEGA_QG_IN_F32 ? 4 : 2); - ws.ranges[1].lo = (uintptr_t)q; ws.ranges[1].hi = (uintptr_t)q + (size_t)rows * k; - ws.ranges[2].lo = (uintptr_t)s; ws.ranges[2].hi = (uintptr_t)s + (size_t)rows * (k / 128) * 4; - ws.nranges = 3; - int err = ws_run(&ws, rows, 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - *bad_out = err ? 0 : pq_compare(x, rows, k, q, s, 0); - free(x); free(xb); free(q); free(s); - return err ? -1 : 0; -} -static int pq_sim(void) { - int fail = 0; char msg[200]; - static const struct { uint32_t k, in_type; } cs[] = { { 2048, OMEGA_QG_IN_F32 }, { 768, OMEGA_QG_IN_BF16 }, { 4096, OMEGA_QG_IN_F32 }, { 128, OMEGA_QG_IN_BF16 } }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - size_t bad = 0; int rc = pq_sim_one(cs[c].k, cs[c].in_type, 9, 0, &bad, msg, sizeof msg); - printf("sim quantiser k %u %s: %s, %zu differ\n", cs[c].k, cs[c].in_type ? "bf16" : "f32", rc ? msg : "ran", bad); - if (rc || bad) fail++; - } - for (int m = 1; m <= 2; m++) { - size_t bad = 0; int rc = pq_sim_one(2048, OMEGA_QG_IN_F32, 9, m, &bad, msg, sizeof msg); - printf("sim quantiser mutant %d: %s\n", m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - return fail; -} - -static int pq_chip(uint32_t tokens, int reps) { - int fail = 0; - static const struct { uint32_t k, in_type, rows_mul; } cs[] = { { 2048, OMEGA_QG_IN_F32, 1 }, { 768, OMEGA_QG_IN_BF16, 8 } }; - for (size_t c = 0; c < 2; c++) { - const uint32_t k = cs[c].k, rows = tokens * cs[c].rows_mul, eb = cs[c].in_type == OMEGA_QG_IN_F32 ? 4 : 2; - float *x = malloc((size_t)rows * k * 4); uint16_t *xb = malloc((size_t)rows * k * 2); - uint8_t *q = malloc((size_t)rows * k); float *s = malloc((size_t)rows * (k / 128) * 4); - make_x(rows, k, cs[c].in_type, x, xb); - OmegaGpuMem xd = { 0 }, qd = { 0 }, sd = { 0 }; - const size_t xbytes = (size_t)rows * k * eb, qbytes = (size_t)rows * k, sbytes = ((size_t)rows * (k / 128) * 4 + 15) & ~(size_t)15; - int rc = omega_gpu_pf_alloc_dev(xbytes, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(qbytes, &qd); - if (!rc) rc = omega_gpu_pf_alloc_dev(sbytes, &sd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, cs[c].in_type == OMEGA_QG_IN_F32 ? (const void *)x : (const void *)xb, xbytes); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_quant(k, cs[c].in_type, rows, xd.va, qd.va, sd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&qd, 0, q, qbytes); - if (!rc) { float *st = malloc(sbytes); rc = omega_gpu_pf_download(&sd, 0, st, sbytes); memcpy(s, st, (size_t)rows * (k / 128) * 4); free(st); } - if (rc) { printf("quantiser chip k %u: %s (%s)\n", k, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - size_t bad = pq_compare(x, rows, k, q, s, 0); - qsort(ns, reps, 8, cmp_u64); - printf("QUANT chip k %u %s rows %u: %zu differ from the reference; median %.3f ms (%.0f GB/s moved)\n", k, cs[c].in_type ? "bf16" : "f32", rows, bad, - ns[reps / 2] / 1e6, (double)(xbytes + qbytes + sbytes) / ns[reps / 2]); - if (bad) fail++; - omega_gpu_pf_quant_test_set_mutant(1); - int mrc = omega_gpu_pf_quant(k, cs[c].in_type, rows, xd.va, qd.va, sd.va, NULL); - omega_gpu_pf_quant_test_set_mutant(0); - if (!mrc) mrc = omega_gpu_pf_download(&qd, 0, q, qbytes); - size_t mb = mrc ? 0 : pq_compare(x, rows > 64 ? 64 : rows, k, q, s, 0); - printf("QUANT chip k %u mutant 1: %s\n", k, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - omega_gpu_pf_free(&xd); omega_gpu_pf_free(&qd); omega_gpu_pf_free(&sd); - free(x); free(xb); free(q); free(s); - } - return fail; -} - -/* ---------------- grouped GEMM on QMMA ---------------- */ -static const QmmaModel GB10Q = { 32, 26, 0, 2, 0 }; /* chip-exact, evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13 */ -typedef struct { - uint32_t E, n, k, M, xr, layout, direct, pad; - uint8_t *w, *xq; /* weights [E][n][k] (checkpoint order, read in place), quantised activations (xr + pad rows) */ - uint16_t *sbf; /* scale_inv bf16 */ - float *swf, *xs, *x; /* GEMV-tensor scale table [E][n/128][KB] f32 * 2^56, activation scales (xr + pad rows), true activations */ - uint32_t *eid, *src, *counts; -} QProb; -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static void qprob_make(QProb *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, uint32_t layout, uint32_t direct, uint32_t pad) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = direct ? M : xr; p->layout = layout; p->direct = direct; p->pad = pad; - const uint32_t KB = k / 128, XR = p->xr + pad; - const size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * KB; - p->w = malloc(wn); p->sbf = malloc(sn * 2); p->swf = malloc(sn * 4); - p->x = calloc((size_t)XR * k, 4); p->xq = calloc((size_t)XR * k, 1); p->xs = malloc((size_t)XR * KB * 4); - p->eid = malloc(M * 4); p->src = malloc(M * 4); p->counts = calloc(E, 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) { float s = ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4); p->sbf[i] = (uint16_t)(f2u(s) >> 16); } - if (omega_fp8_pack_scales(p->sbf, sn, p->swf, 0) != 0) { printf("scale pack refused\n"); exit(2); } - for (size_t i = 0; i < (size_t)p->xr * k; i++) p->x[i] = rand_act(); - if (p->xr > 3) memset(p->x + 3 * (size_t)k, 0, k * 4); - for (uint32_t r = 0; r < XR; r++) pq_ref(p->x + (size_t)r * k, k, p->xq + (size_t)r * k, p->xs + (size_t)r * KB, 0); - uint32_t i = 0; - for (uint32_t e = 0; e < E && i < M; e++) { uint32_t c = e + 1 == E ? M - i : (uint32_t)((uint64_t)(rnd() % 2000) * 2 * M / (2000ull * E)); if (c > M - i) c = M - i; for (uint32_t q = 0; q < c; q++) p->eid[i + q] = e; p->counts[e] = c; i += c; } - for (uint32_t q = 0; q < M; q++) p->src[q] = direct ? q : rnd() % p->xr; -} -static void qprob_free(QProb *p) { free(p->w); free(p->xq); free(p->sbf); free(p->swf); free(p->xs); free(p->x); free(p->eid); free(p->src); free(p->counts); } - -/* the kernel's arithmetic for output row i, physical column c */ -static float qemu_phys(const QProb *p, uint32_t i, uint32_t c) { - const uint32_t k = p->k, KB = k / 128, e = p->eid[i], s = p->src[i]; - /* physical column c -> weight row: F32 c; SWIGLU gate 8G + h % 8 (h < 8) or up I + 8G + h % 8, G = c / 16, h = c % 16 */ - const uint32_t wrow = p->layout == OMEGA_GPU_PF_PLAIN ? c : 8 * (c / 16) + c % 8 + (c % 16 >= 8 ? p->n / 2 : 0); - const uint8_t *xr = p->xq + (size_t)s * k, *wr = p->w + ((size_t)e * p->n + wrow) * k; - const float *swt = p->swf + ((size_t)e * (p->n / 128) + wrow / 128) * KB; - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - const float sc = p->xs[(size_t)s * KB + kb] * (swt[kb] * 0x1p-56f); - for (uint32_t h = 0; h < 2; h++) { - float T = 0.0f; - for (uint32_t v = 0; v < 2; v++) { - float av[32], bv[32]; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - const uint32_t o = 128 * kb + 64 * h + 16 * t + 8 * v + j; - av[4 * t + j] = qm_e4m3(xr[o]); bv[4 * t + j] = qm_e4m3(wr[o]); - av[16 + 4 * t + j] = qm_e4m3(xr[o + 4]); bv[16 + 4 * t + j] = qm_e4m3(wr[o + 4]); - } - T = qm_dot32(&GB10Q, av, bv, T); - } - acc = fmaf(T, sc, acc); - } - } - return acc; -} -static uint16_t qswiglu_bits(float g, float u) { - float t = fminf(g * u2f(0xbfb8aa3bu), 125.0f), ex = exp2f(t), d = ex + 1.0f, r = 1.0f / d, o = g * r; - o = o * u; - return bf16_rn(o); -} -static void qemu_row(const QProb *p, uint32_t i, float *yf, uint16_t *ya) { - if (p->layout == OMEGA_GPU_PF_PLAIN) { for (uint32_t c = 0; c < p->n; c++) yf[c] = qemu_phys(p, i, c); return; } - for (uint32_t a = 0; a < p->n / 2; a++) { uint32_t G = a / 8, m = a % 8; ya[a] = qswiglu_bits(qemu_phys(p, i, 16 * G + m), qemu_phys(p, i, 16 * G + 8 + m)); } -} -/* double oracle on the ORIGINAL weights and the dequantised activations: logical output col (PLAIN) or gate/up of index a */ -static double qoracle(const QProb *p, uint32_t i, uint32_t col, double *mag) { - const uint32_t k = p->k, KB = k / 128, e = p->eid[i], s = p->src[i]; - double acc = 0, m = 0; - for (uint32_t j = 0; j < k; j++) { - const double sw = u2f((uint32_t)p->sbf[((size_t)e * (p->n / 128) + col / 128) * KB + j / 128] << 16); - const double t = (double)qm_e4m3(p->w[((size_t)e * p->n + col) * k + j]) * sw * qm_e4m3(p->xq[(size_t)s * k + j]) * p->xs[(size_t)s * KB + j / 128]; - acc += t; m += fabs(t); - } - *mag = m; return acc; -} - -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt; uint64_t pad; } QTile; -static uint32_t qmake_tiles(const QProb *p, uint32_t bm, QTile *t) { - uint32_t nt = 0, row = 0; const uint32_t KB = p->k / 128; - for (uint32_t e = 0; e < p->E; e++) { for (uint32_t r = 0; r < p->counts[e]; r += bm) { - t[nt].w_va = (uintptr_t)(p->w + (size_t)e * p->n * p->k); t[nt].s_va = (uintptr_t)(p->swf + (size_t)e * (p->n / 128) * KB); - t[nt].row0 = row + r; t[nt].cnt = p->counts[e] - r < bm ? p->counts[e] - r : bm; t[nt].pad = 0; nt++; } row += p->counts[e]; } - return nt; -} -static size_t qcompare(const QProb *p, const void *y, const uint32_t *rows, uint32_t nrows, int tol_ulp, size_t *ulp1) { - size_t bad = 0; if (ulp1) *ulp1 = 0; - float *yf = malloc(p->n * 4); uint16_t *ya = malloc(p->n); - for (uint32_t q = 0; q < nrows; q++) { - const uint32_t i = rows[q]; qemu_row(p, i, yf, ya); - if (p->layout == OMEGA_GPU_PF_PLAIN) { const uint32_t *g = (const uint32_t *)y + (size_t)i * p->n; for (uint32_t c = 0; c < p->n; c++) if (g[c] != f2u(yf[c])) { if (getenv("PFDBG") && bad < 6) printf(" row %u col %u got %.9g want %.9g\n", i, c, u2f(g[c]), yf[c]); bad++; } } - else { const uint16_t *g = (const uint16_t *)y + (size_t)i * (p->n / 2); - for (uint32_t c = 0; c < p->n / 2; c++) if (g[c] != ya[c]) { int d = abs((int)g[c] - (int)ya[c]); if (d <= tol_ulp && ((g[c] ^ ya[c]) & 0x8000) == 0) { if (ulp1) (*ulp1)++; } else { if (getenv("PFDBG") && bad < 12) { const uint32_t G = c / 8, mm = c % 8; printf(" row %u act %u got %04x want %04x (g %.9g u %.9g)\n", i, c, g[c], ya[c], qemu_phys(p, i, 16 * G + mm), qemu_phys(p, i, 16 * G + 8 + mm)); } bad++; } } } - } - free(yf); free(ya); - return bad; -} - -static int qg_host(void) { - int fail = 0; - for (uint32_t layout = 0; layout < 3; layout += 2) { - QProb p; qprob_make(&p, 3, 256, 384, 40, 17, layout, 0, 0); - double worst = 0; - for (uint32_t i = 0; i < p.M; i += 3) { - if (layout == OMEGA_GPU_PF_PLAIN) for (uint32_t c = 0; c < p.n; c++) { double m, o = qoracle(&p, i, c, &m); double d = fabs(qemu_phys(&p, i, c) - o) / (m + 1e-30); if (d > worst) worst = d; } - else for (uint32_t a = 0; a < p.n / 2; a++) { uint32_t G = a / 8, mm = a % 8; double m1, m2; - double og = qoracle(&p, i, a, &m1), ou = qoracle(&p, i, p.n / 2 + a, &m2); - double dg = fabs(qemu_phys(&p, i, 16 * G + mm) - og) / (m1 + 1e-30), du = fabs(qemu_phys(&p, i, 16 * G + 8 + mm) - ou) / (m2 + 1e-30); - if (dg > worst) worst = dg; - if (du > worst) worst = du; } - } - const int ok = worst < 1e-6; - printf("qgemm emulation vs double oracle (%s): worst error %.3g of the sum of |terms| %s\n", layout ? "swiglu_nat" : "plain", worst, ok ? "PASS" : "FAIL"); - if (!ok) fail++; - qprob_free(&p); - } - return fail; -} - -static int qg_sim_run(const QProb *p, const OmegaQgSpec *sp, int order, void *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_qgemm_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused (spec_ok %d, insns %zu)", omega_qg_spec_ok(sp), prog.count); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_qg_span(sp), KB = p->k / 128; - QTile *tiles = calloc(p->M + 1, sizeof *tiles); - const uint32_t nt = qmake_tiles(p, bm, tiles); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - const size_t ob = p->layout == OMEGA_GPU_PF_PLAIN ? 4 : 1, yb = (size_t)(p->M + bm) * p->n * ob; - memset(y, 0xee, yb); - uint8_t *smem = malloc(omega_qg_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_qg_shared_bytes(sp); s.order = order; - const uint64_t a[5] = { (uintptr_t)tiles, sp->direct ? 0 : (uintptr_t)ridx, (uintptr_t)p->xq, (uintptr_t)y, (uintptr_t)p->xs }; - for (int i = 0; i < 5; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a8 / 4] = p->n; - const size_t XR = p->xr + p->pad; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xq; s.ranges[2].hi = (uintptr_t)(p->xq + XR * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)y + (size_t)p->M * p->n * ob; - s.ranges[4].lo = (uintptr_t)p->w; s.ranges[4].hi = (uintptr_t)(p->w + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->swf; s.ranges[5].hi = (uintptr_t)(p->swf + (size_t)p->E * (p->n / 128) * KB); - s.ranges[6].lo = (uintptr_t)p->xs; s.ranges[6].hi = (uintptr_t)(p->xs + XR * KB); - s.nranges = 7; - const int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %.150s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} -static int qg_sim(void) { - int fail = 0; char msg[200]; - static const struct { uint32_t E, n, k, M, xr, layout, direct, rt, warps; } cs[] = { - { 3, 256, 384, 300, 120, OMEGA_GPU_PF_SWIGLU_NAT, 0, 4, 8 }, - { 3, 256, 256, 200, 0, OMEGA_GPU_PF_PLAIN, 1, 4, 8 }, - { 2, 256, 128, 150, 64, OMEGA_GPU_PF_PLAIN, 0, 4, 8 }, - { 2, 512, 1024, 140, 0, OMEGA_GPU_PF_SWIGLU_NAT, 1, 4, 8 }, - }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - const uint32_t bm = 16 * cs[c].rt; - QProb p; qprob_make(&p, cs[c].E, cs[c].n, cs[c].k, cs[c].M, cs[c].xr, cs[c].layout, cs[c].direct, bm); - OmegaQgSpec sp = { cs[c].k, cs[c].rt, cs[c].warps, cs[c].layout == OMEGA_GPU_PF_PLAIN ? OMEGA_QG_EPI_F32 : OMEGA_QG_EPI_SWIGLU, cs[c].direct, cs[c].n, 45, 0 }; - uint32_t *rows = malloc(p.M * 4); for (uint32_t i = 0; i < p.M; i++) rows[i] = i; - void *y = malloc((size_t)(p.M + bm) * p.n * 4); - for (int order = 0; order < 2; order++) { - const int rc = qg_sim_run(&p, &sp, order, y, msg, sizeof msg); - size_t ulp1 = 0, bad = rc ? 0 : qcompare(&p, y, rows, p.M, 0, &ulp1); - printf("sim qgemm case %zu (n %u k %u M %u %s %s rt %u warps %u) order %d: %s, %zu differ\n", c, p.n, p.k, p.M, cs[c].layout ? "swiglu" : "f32", - cs[c].direct ? "direct" : "indexed", cs[c].rt, cs[c].warps, order, rc ? msg : "ran", bad); - if (rc || bad) fail++; - } - if (c == 0 || c == 1) for (int m = 1; m <= 4; m++) { - OmegaQgSpec ms = sp; ms.mutant = m; - const int rc = qg_sim_run(&p, &ms, 0, y, msg, sizeof msg); - const size_t bad = rc ? 0 : qcompare(&p, y, rows, p.M, 0, NULL); - printf("sim qgemm case %zu mutant %d: %s\n", c, m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - free(rows); free(y); qprob_free(&p); - } - return fail; -} - -static int g_cached; /* 1: weights in a GPU-cached device copy (GEMV layout), 0: read in place from the GEMV tensor */ -static int qg_chip_shape(const char *name, uint32_t tokens, int reps, int check_rows, int mutants) { - uint32_t E, n, k, M, xr, layout, direct; - if (!strcmp(name, "gateup")) { E = 128; n = 1536; k = 2048; M = tokens * 8; xr = tokens; layout = OMEGA_GPU_PF_SWIGLU_NAT; direct = 0; } - else if (!strcmp(name, "down")) { E = 128; n = 2048; k = 768; M = tokens * 8; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "qkv")) { E = 1; n = 5120; k = 2048; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else if (!strcmp(name, "o")) { E = 1; n = 2048; k = 4096; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else { printf("unknown shape %s\n", name); return 1; } - const uint32_t bm = omega_gpu_pf_qgemm_bm(), KB = k / 128; - QProb p; qprob_make(&p, E, n, k, M, xr, layout, direct, bm); - int fail = 0, rc; - OmegaGpuFp8Tensor *wt = NULL; OmegaGpuMem xd = { 0 }, sd = { 0 }, yd = { 0 }, tab = { 0 }, ridx = { 0 }, wc = { 0 }, sc = { 0 }; - const size_t XR = p.xr + bm, ob = layout == OMEGA_GPU_PF_PLAIN ? 4 : 1; - rc = omega_gpu_fp8_tensor_upload(E, n, k, p.w, p.sbf, &wt) == 0 ? 0 : OMEGA_GPU_PF_CHIP_FAIL; /* the GEMV tensor, read in place */ - const size_t xb = (XR * k + 15) & ~(size_t)15, sb = (XR * KB * 4 + 15) & ~(size_t)15, yb = (size_t)(M + bm) * n * ob; - if (!rc) rc = omega_gpu_pf_alloc_dev(xb, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(sb, &sd); - if (!rc) rc = omega_gpu_pf_alloc_dev(yb, &yd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, p.xq, XR * k & ~(size_t)15); - if (!rc) rc = omega_gpu_pf_upload(&sd, 0, p.xs, XR * KB * 4 & ~(size_t)15); - const uint32_t maxt = M / bm + E + 1; - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)maxt * 32, &tab); - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(M + bm) * 4, &ridx); - if (rc) { printf("%s setup: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); qprob_free(&p); return 1; } - uint32_t nt = 0; - if (!g_cached) nt = omega_gpu_pf_qgemm_tiles(wt, p.counts, tab.cpu, maxt); - else { - const size_t wbytes = (size_t)E * n * k, sbytes = ((size_t)E * (n / 128) * KB * 4 + 15) & ~(size_t)15; - float *sst = calloc(1, sbytes); memcpy(sst, p.swf, (size_t)E * (n / 128) * KB * 4); - if (omega_gpu_pf_alloc_dev(wbytes, &wc) || omega_gpu_pf_alloc_dev(sbytes, &sc) || omega_gpu_pf_upload(&wc, 0, p.w, wbytes) || omega_gpu_pf_upload(&sc, 0, sst, sbytes)) { printf("%s cached copy failed\n", name); free(sst); return 1; } - free(sst); - uint64_t *wv = malloc(E * 8), *sv = malloc(E * 8); - for (uint32_t e = 0; e < E; e++) { wv[e] = wc.va + (uint64_t)e * n * k; sv[e] = sc.va + (uint64_t)e * (n / 128) * KB * 4; } - nt = omega_gpu_pf_qgemm_tiles_va(E, wv, sv, p.counts, tab.cpu, maxt); free(wv); free(sv); - } - if (!nt) { printf("%s tile table failed\n", name); return 1; } - { uint32_t *ri = ridx.cpu; for (uint32_t i = 0; i < M + bm; i++) ri[i] = i < M ? p.src[i] : 0; } - omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&tab); (void)omega_gpu_session_sync_to_gpu(&ridx); omega_gpu_session_unlock(); - const uint64_t rva = direct ? 0 : ridx.va; - uint8_t *y1 = malloc(yb), *y2 = calloc(1, yb); - uint64_t ns[32] = { 0 }; - if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y1, yb & ~(size_t)15); - if (!rc) rc = omega_gpu_pf_upload(&yd, 0, y2, yb & ~(size_t)15); /* zero the output, run once more: identical result required */ - uint64_t ns2 = 0; - if (!rc) rc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, &ns2); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - if (rc) { printf("%s run: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - const size_t outb = (size_t)M * n * ob; - printf("%s second launch identical: %s\n", name, memcmp(y1, y2, outb) ? "NO" : "yes"); - if (memcmp(y1, y2, outb)) fail++; - uint32_t *rows = malloc(check_rows * 4); for (int q = 0; q < check_rows; q++) rows[q] = q == 0 ? 0 : q == 1 ? M - 1 : rnd() % M; - size_t ulp1 = 0; const size_t bad = qcompare(&p, y1, rows, check_rows, layout == OMEGA_GPU_PF_PLAIN ? 0 : 1, &ulp1); - printf("%s bit-identity on %d sampled rows: %zu differ", name, check_rows, bad); - if (layout != OMEGA_GPU_PF_PLAIN) printf(" (beyond 1 bf16 ulp; %zu within 1 ulp of %zu)", ulp1, (size_t)check_rows * n / 2); - printf("\n"); - if (bad) fail++; - qsort(ns, reps, 8, cmp_u64); - const double fl = 2.0 * M * n * k, med = (double)ns[reps / 2]; - printf("QGEMM%s %s tokens %u M %u n %u k %u tiles %u: median %.3f ms (min %.3f), %.1f TFLOPS, weights %.0f MB -> %.0f GB/s of distinct weights\n", g_cached ? "-cached" : "-inplace", name, tokens, M, n, k, nt, - med / 1e6, ns[0] / 1e6, fl / med / 1e3, (double)E * n * k / 1e6, (double)E * n * k / med); - if (mutants) for (int m = 1; m <= 4; m++) { - omega_gpu_pf_qgemm_test_set_mutant(m); - int mrc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, NULL); - omega_gpu_pf_qgemm_test_set_mutant(0); - if (!mrc) mrc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - const size_t mb = mrc ? 0 : qcompare(&p, y2, rows, check_rows > 8 ? 8 : check_rows, layout == OMEGA_GPU_PF_PLAIN ? 0 : 1, NULL); - printf("%s mutant %d: %s\n", name, m, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - free(rows); - } - free(y1); free(y2); - omega_gpu_fp8_tensor_free(wt); omega_gpu_pf_free(&wc); omega_gpu_pf_free(&sc); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&sd); omega_gpu_pf_free(&yd); omega_gpu_pf_free(&tab); omega_gpu_pf_free(&ridx); - qprob_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7, rows = 64; uint32_t tokens = 3600, rt = 0, warps = 0, wait = 0, waitset = 0; const char *only = NULL; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--rows") && i + 1 < argc) rows = atoi(argv[++i]); - else if (!strcmp(argv[i], "--shape") && i + 1 < argc) only = argv[++i]; - else if (!strcmp(argv[i], "--cached")) g_cached = 1; - else if (!strcmp(argv[i], "--rt") && i + 1 < argc) rt = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--warps") && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--wait") && i + 1 < argc) { wait = (uint32_t)atoi(argv[++i]); waitset = 1; } - } - int fail = 0; - if (host) { fail += pq_host(); fail += qg_host(); } - if (sim) { fail += pq_sim(); fail += qg_sim(); } - if (chip) { - if (rt || warps || waitset) omega_gpu_pf_qgemm_set_shape(rt ? rt : 4, warps ? warps : 8, waitset ? wait : 45); - if (!only) fail += pq_chip(tokens, reps); - static const char *shapes[] = { "gateup", "down", "qkv", "o" }; - for (int s = 0; s < 4; s++) if (!only || !strcmp(only, shapes[s])) fail += qg_chip_shape(shapes[s], tokens, reps, rows, !only || s < 2); - } - printf("GPU_QGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_qmma_probe_test.c b/tests/gpu_qmma_probe_test.c deleted file mode 100644 index 413a80ce6..000000000 --- a/tests/gpu_qmma_probe_test.c +++ /dev/null @@ -1,287 +0,0 @@ -/* gpu_qmma_probe_test.c (OWN-30B L1 GEMM, W-L1G, 2026-10-14): characterise the GB10's QMMA.16832.F32.E4M3.E4M3. - * --host-only patch self-test against the nvcc oracle bits; model self-checks - * (default) chip (caller holds flock /tmp/aien-gb10.lock): - * 1 arithmetic: CASES single-QMMA cases; class "exact" (sparse power-of-two operands, every sum exact) checks the INFERRED - * fragment layout (any miss there = layout wrong); per model of tests/bw_qmma_model.h the bit-exact match count; - * negative control: mutant 1 (C dropped) must differ wherever C matters; a second run with fewer wait NOPs must match - * 2 peak: QMMA chains x issue stall sweep; every stored value must be 32 * iters; TFLOPS = 8192 flop per QMMA / time - * Env QMMA_PROBE_SEED: fresh data (confirmation). --save F / --replay F: chip words to / from a file (offline model search). - * Verdict last: "QMMA_PROBE: model=... exact N/N" or "QMMA_PROBE: NO EXACT MODEL", then "GPU_QMMA_PROBE: PASS|FAIL". */ -#include "omega_blackwell_codegen_qmma.h" -#include "omega_gpu_session.h" -#include "bw_qmma_model.h" -#include -#include -#include - -#define CASES 2048u -#define NCLS 7 -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -/* random e4m3 code with unbiased exponent field in [lo, hi] (1..15; 0 = subnormal), never NaN */ -static uint8_t re4(int lo, int hi) { - for (;;) { uint8_t e = (uint8_t)(lo + (int)(rnd() % (uint32_t)(hi - lo + 1))), c = (uint8_t)((rnd() & 0x80) | e << 3 | (rnd() & 7)); if ((c & 0x7f) != 0x7f) return c; } -} -static float rf(int lo, int hi) { float m = 1.0f + (float)(rnd() & 127) / 128.0f; int e = lo + (int)(rnd() % (uint32_t)(hi - lo + 1)); float v = ldexpf(m, e); return (rnd() & 1) ? -v : v; } - -typedef struct { uint8_t A[16][32], B[32][8]; float C[16][8]; } Case; -static const char *clsname[NCLS] = { "narrow", "wide", "mixed+cancel", "bigC", "subnormal", "medium", "exact" }; -static void gen_case(Case *c, unsigned idx) { - unsigned cls = idx % NCLS; - for (int r = 0; r < 16; r++) for (int k = 0; k < 32; k++) { - uint8_t v; - switch (cls) { - case 0: v = re4(6, 8); break; - case 1: v = re4(1, 15); break; - case 2: v = (k & 1) ? re4(6, 8) : re4(1, 7); break; - case 3: v = re4(5, 9); break; - case 4: v = (rnd() & 3) ? re4(0, 0) : re4(1, 2); break; - case 5: v = re4(3, 11); break; - default: v = (rnd() % 6 == 0) ? (uint8_t)((rnd() & 0x80) | (uint8_t)((5 + rnd() % 5) << 3)) : 0; break; /* sparse +-2^(-2..2) */ - } - c->A[r][k] = v; - } - for (int k = 0; k < 32; k++) for (int n = 0; n < 8; n++) - c->B[k][n] = cls == 6 ? ((rnd() % 4 == 0) ? (uint8_t)((rnd() & 0x80) | (uint8_t)((5 + rnd() % 5) << 3)) : 0) : cls == 1 ? re4(1, 15) : re4(4, 10); - for (int r = 0; r < 16; r++) for (int n = 0; n < 8; n++) { - float v = idx % 11 == 10 ? 0.0f : rf(-6, 6); - if (cls == 3) v = rf(12, 16); - if (cls == 6) v = (float)((int)(rnd() % 9) - 4); - if (cls == 2 && (rnd() & 1)) { double s = 0; for (int k = 0; k < 32; k++) s += (double)qm_e4m3(c->A[r][k]) * qm_e4m3(c->B[k][n]); v = (float)-s; } - c->C[r][n] = v; - } -} -static uint32_t pack4(uint8_t a, uint8_t b, uint8_t cc, uint8_t d) { return (uint32_t)a | (uint32_t)b << 8 | (uint32_t)cc << 16 | (uint32_t)d << 24; } -/* the INFERRED m16n8k32 8-bit fragment layout (header) */ -static void to_frag(const Case *c, uint32_t *in) { - uint32_t *A = in, *B = in + 128; float *C = (float *)(in + 192); - for (int L = 0; L < 32; L++) { - int g = L / 4, t = L % 4; - for (int q = 0; q < 4; q++) { int r = g + (q & 1 ? 8 : 0), k0 = 4 * t + (q & 2 ? 16 : 0); A[L * 4 + q] = pack4(c->A[r][k0], c->A[r][k0 + 1], c->A[r][k0 + 2], c->A[r][k0 + 3]); } - for (int q = 0; q < 2; q++) { int k0 = 4 * t + 16 * q; B[L * 2 + q] = pack4(c->B[k0][g], c->B[k0 + 1][g], c->B[k0 + 2][g], c->B[k0 + 3][g]); } - C[L * 4 + 0] = c->C[g][2 * t]; C[L * 4 + 1] = c->C[g][2 * t + 1]; C[L * 4 + 2] = c->C[g + 8][2 * t]; C[L * 4 + 3] = c->C[g + 8][2 * t + 1]; - } -} -static void out_rc(int L, int q, int *r, int *n) { int g = L / 4, t = L % 4; *r = g + (q >= 2 ? 8 : 0); *n = 2 * t + (q & 1); } -static float model_out(const QmmaModel *m, const Case *c, int r, int n) { - float a[32], b[32]; for (int k = 0; k < 32; k++) { a[k] = qm_e4m3(c->A[r][k]); b[k] = qm_e4m3(c->B[k][n]); } - return qm_dot32(m, a, b, c->C[r][n]); -} -static double exact_out(const Case *c, int r, int n, double *mag) { - double s = c->C[r][n]; *mag = fabs(s); for (int k = 0; k < 32; k++) { double p = (double)qm_e4m3(c->A[r][k]) * qm_e4m3(c->B[k][n]); s += p; *mag += fabs(p); } return s; -} - -static int host_only(void) { - int fail = 0; char msg[160]; - int rc = omega_qmma_patch_selftest(msg, sizeof msg); - printf("QMMA patch self-test: %s (%s)\n", rc ? "FAIL" : "PASS", msg); if (rc) fail++; - if (qm_e4m3(0x38) != 1.0f || qm_e4m3(0x7e) != 448.0f || qm_e4m3(0x01) != ldexpf(1.0f, -9) || qm_e4m3(0xb8) != -1.0f) { printf("e4m3 decode FAIL\n"); fail++; } - for (int i = 0; i < 1000; i++) { - float a[32], b[32]; for (int k = 0; k < 32; k++) { a[k] = (float)((int)(rnd() % 17) - 8); b[k] = (float)((int)(rnd() % 9) - 4); } - float c = (float)((int)(rnd() % 33) - 16); double ex = c; for (int k = 0; k < 32; k++) ex += (double)a[k] * b[k]; - int groups[] = { 0, 1, 2, 4, 8, 16, 32 }; - for (int gi = 0; gi < 7; gi++) for (int rn = 0; rn < 2; rn++) { QmmaModel m = { groups[gi], 24, rn, 0, 0 }; if (qm_dot32(&m, a, b, c) != (float)ex) fail++; } - } - for (int c = 0; c < 256; c++) if ((c & 0x7f) != 0x7f && qm_e4m3_rne_sat(qm_e4m3((uint8_t)c)) != c) { printf("e4m3 round trip FAIL at %02x\n", c); fail++; } - if (qm_e4m3_rne_sat(500.0f) != 0x7e || qm_e4m3_rne_sat(ldexpf(1.0f, -10)) != 0 || qm_e4m3_rne_sat(ldexpf(3.0f, -10)) != 2 || qm_e4m3_rne_sat(1.0625f) != 0x38) { printf("e4m3 rounding FAIL\n"); fail++; } - { static Case c; gen_case(&c, 6); uint32_t in[320]; to_frag(&c, in); if ((in[0] & 0xff) != c.A[0][0] || ((in[1] >> 8) & 0xff) != c.A[8][1] || ((in[128 + 5 * 2 + 1] >> 24) & 0xff) != c.B[16 + 4 + 3][1]) fail++; } - static BlackwellIRProgram p; - if (omega_blackwell_codegen_qmma_probe_prog(0, 4, &p) != 0 || omega_blackwell_codegen_qmma_peak_prog(64, 16, 2, 128, &p) != 0) { printf("codegen refused\n"); fail++; } - printf("host-only checks: %s (%d failures)\n", fail ? "FAIL" : "PASS", fail); - return fail; -} - -static int load_code(BlackwellIRProgram *prog, OmegaGpuMem *code) { - size_t need = omega_bw_program_code_bytes(prog); OmegaBlackwellKernel k; - if (omega_gpu_session_alloc_code(need, code) != 0 || omega_blackwell_kernel_encode_into(prog, code->cpu, need, &k) != 0) return -1; - if (omega_qmma_patch_code(prog, code->cpu, need) < 1) { printf("QMMA patch failed\n"); return -1; } - return omega_gpu_session_sync_to_gpu(code); -} -static int run_probe(int mutant, uint32_t nops, uint32_t *out_words, const uint32_t *in_words) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog || omega_blackwell_codegen_qmma_probe_prog(mutant, nops, prog) != 0) { printf("codegen failed\n"); free(prog); return -1; } - int rc = -1; - omega_gpu_session_lock(); - OmegaGpuMem code = { 0 }, in = { 0 }, out = { 0 }; - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (load_code(prog, &code) != 0) { printf("code upload failed\n"); goto done; } - if (omega_gpu_session_alloc((size_t)CASES * 1280u, &in) != 0 || omega_gpu_session_alloc((size_t)CASES * 512u, &out) != 0) { printf("alloc failed\n"); goto done; } - memcpy(in.cpu, in_words, (size_t)CASES * 1280u); - { float *o = out.cpu; for (size_t i = 0; i < (size_t)CASES * 128u; i++) o[i] = -999.0f; } - if (omega_gpu_session_sync_to_gpu(&in) != 0 || omega_gpu_session_sync_to_gpu(&out) != 0) goto done; - { - uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - uint32_t decl = omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage); - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl < 64 ? 64 : decl, .threads_x = 32, .threads_y = 1, .grid_x = CASES, .grid_y = 1, - .num_elements = (size_t)CASES * 128u, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_sync_to_cpu(&out) != 0) goto done; - printf("chip probe mutant %d nops %u: declared %u, %llu ns\n", mutant, nops, L.gpr_count, (unsigned long long)ns); - } - memcpy(out_words, out.cpu, (size_t)CASES * 512u); - rc = 0; -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(prog); - return rc; -} - - -/* convert probe: NP pairs through F2FP.SATFINITE.E4M3; byte order and rounding against qm_e4m3_rne_sat */ -#define NP (1u << 20) -static float cvt_input(uint32_t i) { - switch (i % 8) { - case 0: return u2f((rnd() & 0x80000000u) | (uint32_t)(127 - 14 + (int)(rnd() % 25)) << 23 | (rnd() & 0x7fffff)); /* 2^-14 .. 2^10, full mantissa */ - case 1: { uint8_t c = (uint8_t)(rnd() & 0xff); if ((c & 0x7f) >= 0x7e) c = 0x10; float a = qm_e4m3(c), b = qm_e4m3((uint8_t)(c + 1)); return (a + b) * 0.5f; } /* exact ties */ - case 2: return u2f((rnd() & 0x80000000u) | (rnd() & 0x7fffff) | (uint32_t)(127 - 12 + (int)(rnd() % 4)) << 23); /* subnormal e4m3 range */ - case 3: { static const uint32_t sp[] = { 0, 0x80000000u, 0x43e00000u, 0x43e80000u, 0x43e7ffffu, 0x7f800000u, 0xff800000u, 0x3a800000u, 0x3a000000u, 0x00000001u, 0x447a0000u, 0xc3e10000u }; return u2f(sp[rnd() % 12]); } - default: return u2f((rnd() & 0x80000000u) | (uint32_t)(127 - 8 + (int)(rnd() % 17)) << 23 | (rnd() & 0x7fffff)); - } -} -static int cvt_probe(void) { - static BlackwellIRProgram p; int fail = 0; - if (omega_blackwell_codegen_f2e4_probe_prog(&p) != 0) { printf("cvt codegen refused\n"); return 1; } - float *x = malloc((size_t)NP * 8); for (uint32_t i = 0; i < 2 * NP; i++) x[i] = cvt_input(i); - omega_gpu_session_lock(); - OmegaGpuMem code = { 0 }, in = { 0 }, out = { 0 }; - if (!omega_gpu_session_open() || load_code(&p, &code) != 0 || omega_gpu_session_alloc((size_t)NP * 8, &in) != 0 || omega_gpu_session_alloc((size_t)NP * 4, &out) != 0) { printf("cvt setup failed: %s\n", omega_gpu_session_last_error()); fail = 1; goto done; } - memcpy(in.cpu, x, (size_t)NP * 8); memset(out.cpu, 0xa5, (size_t)NP * 4); - { uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = 64, .threads_x = 128, .threads_y = 1, .grid_x = NP / 128u, .grid_y = 1, .num_elements = NP, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_sync_to_gpu(&in) || omega_gpu_session_sync_to_gpu(&out) || omega_gpu_session_launch(&L, &ns, NULL) || omega_gpu_session_sync_to_cpu(&out)) { printf("cvt launch failed: %s\n", omega_gpu_session_last_error()); fail = 1; goto done; } } - { const uint32_t *o = out.cpu; size_t hi_ab = 0, hi_ba = 0, upper = 0, nan_n = 0, n = 0, tie_ab = 0, ties = 0; uint32_t first_bad = 0xffffffffu; - for (uint32_t i = 0; i < NP; i++) { - float a = x[2 * i], b = x[2 * i + 1]; - if (isnan(a) || isnan(b)) { nan_n++; continue; } - n++; if (o[i] >> 16) upper++; - uint32_t ab = (uint32_t)qm_e4m3_rne_sat(a) << 8 | qm_e4m3_rne_sat(b), ba = (uint32_t)qm_e4m3_rne_sat(b) << 8 | qm_e4m3_rne_sat(a); - if ((o[i] & 0xffff) == ab) hi_ab++; else if (first_bad == 0xffffffffu) first_bad = i; - if ((o[i] & 0xffff) == ba) hi_ba++; - if (i % 4 == 1 || (2 * i + 1) % 8 == 1) { ties++; if ((o[i] & 0xffff) == ab) tie_ab++; } - } - printf("cvt probe: %zu pairs; Ra->high byte matches %zu, Ra->low byte matches %zu; upper 16 bits nonzero %zu; ties %zu of %zu exact\n", n, hi_ab, hi_ba, upper, tie_ab, ties); - if (first_bad != 0xffffffffu) printf(" first miss pair %u: %a %a -> chip %04x want %04x\n", first_bad, x[2 * first_bad], x[2 * first_bad + 1], o[first_bad] & 0xffff, (uint32_t)qm_e4m3_rne_sat(x[2 * first_bad]) << 8 | qm_e4m3_rne_sat(x[2 * first_bad + 1])); - printf("CVT_PROBE: %s\n", hi_ab == n && upper == 0 ? "e4m3(Ra) << 8 | e4m3(Rb), RNE satfinite, exact on every pair" : "MISMATCH"); - if (hi_ab != n || upper) fail = 1; - (void)nan_n; - } -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(x); - return fail; -} - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static int peak(void) { - static const struct { uint32_t stall, chains, threads, ctas; } pts[] = { - { 8, 16, 128, 192 }, { 4, 16, 128, 192 }, { 2, 16, 128, 192 }, { 1, 16, 128, 192 }, { 2, 8, 128, 192 }, { 2, 4, 128, 192 }, - { 2, 16, 256, 192 }, { 2, 16, 256, 384 }, { 1, 16, 512, 96 }, { 4, 8, 256, 384 }, - }; - const uint32_t iters = 4096; int fail = 0; - omega_gpu_session_lock(); - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return 1; } - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, out = { 0 }; - if (omega_blackwell_codegen_qmma_peak_prog(iters, pts[i].chains, pts[i].stall, pts[i].threads, &p) != 0) { printf("codegen refused\n"); fail++; continue; } - size_t ob = (size_t)pts[i].ctas * pts[i].threads * 16u * pts[i].chains; - uint32_t decl = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage); - if (load_code(&p, &code) != 0 || omega_gpu_session_alloc(ob, &out) != 0) { printf("upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint64_t ns[5]; int ok = 1; size_t bad = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; - float *o = out.cpu; for (size_t q = 0; q < ob / 4; q++) o[q] = -1.0f; - uint32_t args[2] = { (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl, .threads_x = pts[i].threads, .threads_y = 1, .grid_x = pts[i].ctas, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 2, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < ob / 4; q++) if (o[q] != 32.0f * iters) bad++; - } - if (!ok) { fail++; omega_gpu_session_free(&code); omega_gpu_session_free(&out); break; } - qsort(ns, 5, 8, cmp_u64); - double qm = (double)pts[i].ctas * (pts[i].threads / 32u) * iters * pts[i].chains; - printf("QMMA peak stall %u chains %u threads %u ctas %u (declared %u): median %.1f us, %.2f TFLOPS, %zu wrong values\n", pts[i].stall, pts[i].chains, pts[i].threads, pts[i].ctas, decl, - ns[2] / 1e3, qm * 8192.0 / ns[2] / 1e3, bad); - if (bad) fail++; - omega_gpu_session_free(&code); omega_gpu_session_free(&out); - } - omega_gpu_session_unlock(); - return fail; -} - -int main(int argc, char **argv) { - const char *replay = NULL, *save = NULL; int host = 0, do_peak = 1; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--no-peak")) do_peak = 0; - else if (!strcmp(argv[i], "--replay") && i + 1 < argc) replay = argv[++i]; - else if (!strcmp(argv[i], "--save") && i + 1 < argc) save = argv[++i]; - } - if (getenv("QMMA_PROBE_SEED")) rng = strtoull(getenv("QMMA_PROBE_SEED"), NULL, 0) | 1u; - int fail = host_only(); - if (host || fail) { printf("GPU_QMMA_PROBE: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - static Case cases[CASES]; - const size_t ow = (size_t)CASES * 128u; - uint32_t *in = calloc((size_t)CASES, 1280u), *out = calloc(ow, 4), *outm = calloc(ow, 4), *out2 = calloc(ow, 4); - for (unsigned i = 0; i < CASES; i++) { gen_case(&cases[i], i); to_frag(&cases[i], in + (size_t)i * 320u); } - if (replay) { - FILE *rf = fopen(replay, "rb"); if (!rf) return 1; - size_t got = fread(out, 4, ow, rf) + fread(outm, 4, ow, rf) + fread(out2, 4, ow, rf); fclose(rf); - if (got != 3 * ow) { printf("short replay file\n"); return 1; } - printf("replaying chip words from %s\n", replay); do_peak = 0; - } else { - if (run_probe(0, 8, out, in) || run_probe(1, 8, outm, in) || run_probe(0, 2, out2, in)) { printf("GPU_QMMA_PROBE: FAIL chip\n"); return 1; } - if (save) { FILE *sf = fopen(save, "wb"); if (sf) { fwrite(out, 4, ow, sf); fwrite(outm, 4, ow, sf); fwrite(out2, 4, ow, sf); fclose(sf); } } - } - size_t poison = 0, far = 0, exact_miss = 0, exact_n = 0, waitdiff = 0; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - size_t w = (size_t)i * 128 + L * 4 + q; float v = u2f(out[w]); - if (v == -999.0f) poison++; - if (out[w] != out2[w]) waitdiff++; - int r, n; out_rc(L, q, &r, &n); double mag, ex = exact_out(&cases[i], r, n, &mag); - if (fabs(v - ex) > 1e-2 * mag + 1e-30) far++; - if (i % NCLS == 6) { exact_n++; if ((double)v != ex) exact_miss++; } - } - printf("plausibility: %zu poison, %zu of %zu outputs farther than 1e-2 of the term magnitude from the exact sum\n", poison, far, ow); - printf("layout check (class exact, every sum representable): %zu of %zu differ from the exact sum (%s)\n", exact_miss, exact_n, exact_miss ? "LAYOUT OR ARITHMETIC WRONG" : "layout confirmed"); - printf("wait check: 2-NOP run vs 8-NOP run: %zu of %zu words differ\n", waitdiff, ow); - size_t mdiff = 0, mcand = 0; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - size_t w = (size_t)i * 128 + L * 4 + q; int r, n; out_rc(L, q, &r, &n); float dv = u2f(out[w]); - if (cases[i].C[r][n] == 0.0f || fabsf(cases[i].C[r][n]) < ldexpf(fabsf(dv), -8)) continue; - mcand++; if (out[w] != outm[w]) mdiff++; - } - printf("negative control (C dropped): %zu of %zu outputs with significant C differ (%s)\n", mdiff, mcand, mcand && mdiff == mcand ? "caught" : "NOT CAUGHT"); - int groups[] = { 0, 1, 2, 4, 8, 16, 32 }; size_t best = 0; QmmaModel bm = { 0, 0, 0, 0, 0 }; - for (int gi = 0; gi < 7; gi++) for (int keep = 10; keep <= 32; keep++) for (int rn = 0; rn < 2; rn++) for (int nom = 0; nom < 3; nom++) for (int cs = 0; cs < 2; cs++) { - if (groups[gi] == 0 && (keep != 10 || rn || nom || cs)) continue; - QmmaModel m = { groups[gi], keep, rn, nom, cs }; - size_t match = 0, miss[NCLS] = { 0 }; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); - if (f2u(model_out(&m, &cases[i], r, n)) == out[(size_t)i * 128 + L * 4 + q]) match++; else miss[i % NCLS]++; - } - if (match * 100 >= ow * 95) - printf("model group %2d keep %d %s nominal %d csep %d: %zu of %zu (misses: %s %zu %s %zu %s %zu %s %zu %s %zu %s %zu %s %zu)\n", m.group, m.keep, m.rn ? "RN" : "RZ", m.nominal, m.csep, match, ow, - clsname[0], miss[0], clsname[1], miss[1], clsname[2], miss[2], clsname[3], miss[3], clsname[4], miss[4], clsname[5], miss[5], clsname[6], miss[6]); - if (match > best) { best = match; bm = m; } - } - int ok = poison == 0 && far == 0 && exact_miss == 0 && waitdiff == 0 && mcand && mdiff == mcand; - if (ok && best == ow) printf("QMMA_PROBE: model=group %d keep %d %s nominal %d csep %d exact %zu/%zu\n", bm.group, bm.keep, bm.rn ? "RN" : "RZ", bm.nominal, bm.csep, best, ow); - else printf("QMMA_PROBE: NO EXACT MODEL (best group %d keep %d %s nominal %d csep %d: %zu/%zu)%s\n", bm.group, bm.keep, bm.rn ? "RN" : "RZ", bm.nominal, bm.csep, best, ow, ok ? "" : " and plausibility/layout/control FAILED"); - int pf = do_peak ? peak() : 0; - int cf = replay ? 0 : cvt_probe(); - fail = !ok || best != ow || pf || cf; - printf("GPU_QMMA_PROBE: %s\n", fail ? "FAIL" : "PASS"); - free(in); free(out); free(outm); free(out2); - return fail; -} diff --git a/tests/gpu_reconv_test.c b/tests/gpu_reconv_test.c deleted file mode 100644 index 1711e60c5..000000000 --- a/tests/gpu_reconv_test.c +++ /dev/null @@ -1,472 +0,0 @@ -/* gpu_reconv_test: structured warp reconvergence (omega #308) on Omega's own Blackwell codegen. - * - * ./gpu_reconv_test --host-only encoder golden words, region bookkeeping, codegen refusals, - * nvdisasm listing (when /usr/local/cuda/bin/nvdisasm exists), - * every probe kernel through the SIMT warp simulator against - * the host oracle under both fragment orders, the mutation - * controls, scoreboard and control-edge walks. No device. - * ./gpu_reconv_test --out receipt.json chip gate: host part first (a kernel the simulator rejects - * never gets chip time), then every probe on the chip against - * the oracle, bit-exact, then each math mutant must be caught. - * --observe-dropped-join chip only, optional: also launch the dropped-BSYNC mutant of - * one probe and record what the chip did (an observation, not - * a gate; the simulator rejects that kernel first). - * - * Probes (src/omega_gpu_elementwise_api.c, gen_rc_*): R3 diamond, R4 loop break, R5 nested, - * R6 lanes past the end with STS/BAR/LDS + SHFL, and the 16-deep barrier-register bound. - * Oracle: rc_oracle below; every comparison is exact (u32). Launcher chunking (64 CTAs x 128 - * threads per launch, P0 = words in the chunk) is part of the oracle, so a clamp to the wrong - * chunk end shows up. */ -#include "omega_gpu_elementwise_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_bw_reconv.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim.h" -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } - -typedef struct { OmegaGpuEwOp op; const char *name; const char *reg; } Probe; -static const Probe PROBES[] = { - { OMEGA_GPU_EW_RC_DIAMOND, "rc_diamond", "R3" }, - { OMEGA_GPU_EW_RC_LOOPBREAK, "rc_loopbreak", "R4" }, - { OMEGA_GPU_EW_RC_NESTED, "rc_nested", "R5" }, - { OMEGA_GPU_EW_RC_EXIT_BAR, "rc_exit_bar", "R6" }, - { OMEGA_GPU_EW_RC_DEPTH16, "rc_depth16", "B0..B15" }, -}; -#define NPROBES (sizeof PROBES / sizeof PROBES[0]) -/* 8191..8193 straddled the 64-CTA chunk, 131071..131073 the 1024-CTA chunk (cut L, 2026-10-12) */ -static const uint32_t NS[] = { 1, 5, 31, 32, 33, 63, 64, 65, 96, 127, 128, 129, 200, 1000, 4096, 8191, 8192, 8193, 20000, 131071, 131072, 131073 }; -#define MAXN 131073u -#define NNS (sizeof NS / sizeof NS[0]) -#define CHUNK (OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS) - -/* ----------------------------------------------------------------- oracle */ -static uint32_t count_loop(uint32_t x, uint32_t y, int math, uint32_t *v_out) { - uint32_t v = x & 255u, st = (y & 15u) + 1u, cnt = 0, bound = math ? 255u : 256u; - while (v < bound) { v += st; cnt++; } - *v_out = v; return cnt; -} -static uint32_t rc_r(OmegaGpuEwOp op, int math, uint32_t x, uint32_t y, uint32_t partner_x) { - uint32_t v, cnt; - switch (op) { - case OMEGA_GPU_EW_RC_DIAMOND: - if (x >= y) { uint32_t t = 3u * x + y, u = t ^ x, r = 5u * u + 1u; r += r >> 3; return math ? r + 1u : r; } - return x + 1u; - case OMEGA_GPU_EW_RC_LOOPBREAK: cnt = count_loop(x, y, math, &v); return cnt * 256u + v; - case OMEGA_GPU_EW_RC_NESTED: if (x & 1u) return 7u; cnt = count_loop(x, y, math, &v); return cnt * 256u + v + 100u; - case OMEGA_GPU_EW_RC_EXIT_BAR: return 3u * x + (partner_x | 1u); - case OMEGA_GPU_EW_RC_DEPTH16: return x + (x < y ? (uint32_t)BW_RECONV_MAX_BAR : 0u); - default: return 0xdeadbeefu; - } -} -static void rc_oracle(OmegaGpuEwOp op, int math, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out) { - for (uint32_t i0 = 0; i0 < n; i0 += CHUNK) { - uint32_t ni = n - i0 < CHUNK ? n - i0 : CHUNK; - uint32_t threads = ((ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS) * OMEGA_GPU_EW_THREADS; - uint32_t *r = malloc((size_t)threads * 4); - for (uint32_t t = 0; t < threads; t++) { - uint32_t idx = t < ni ? t : ni - 1, pt = t ^ 1u, pidx = pt < ni ? pt : ni - 1; - r[t] = rc_r(op, math, a[i0 + idx], b[i0 + idx], a[i0 + pidx]); - } - for (uint32_t i = 0; i < ni; i++) { uint32_t nb = (i & 31u) == 31u ? i : i + 1u; out[i0 + i] = r[i] + 4099u * r[nb]; } - free(r); - } -} -/* An LCG's low bits cycle quickly (bit 0 has period 2), and the probes key on low bits - * (x & 255, y & 15, x & 1), so each draw goes through a mixing step. */ -static uint32_t mix(uint32_t r) { r ^= r >> 16; r *= 0x45d9f3bu; r ^= r >> 16; r *= 0x45d9f3bu; r ^= r >> 16; return r; } -static void fill(uint32_t *a, uint32_t *b, uint32_t n, uint32_t seed) { - for (uint32_t i = 0; i < n; i++) { a[i] = mix(lcg(&seed)); b[i] = mix(lcg(&seed)); } -} -static size_t diff_count(const uint32_t *got, const uint32_t *want, uint32_t n, uint32_t *first) { - size_t bad = 0; *first = n; - for (uint32_t i = 0; i < n; i++) if (got[i] != want[i]) { if (!bad) *first = i; bad++; } - return bad; -} - -/* --------------------------------------------------------- simulator driver */ -static uint8_t g_smem[1024]; -/* Mirrors run_1d: 64 CTAs x 128 threads per launch, P0 = words in the chunk. Returns the - * simulator's error code (0 clean); the output words are written to out. */ -static int ws_probe(const BlackwellIRProgram *p, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out, int order, WsSim *stats) { - for (uint32_t i = 0; i < n; i++) out[i] = 0xffbadbadu; - uint64_t wi = 0, li = 0, sp = 0; int mf = 0, pb = 0; - for (uint32_t i0 = 0; i0 < n; i0 += CHUNK) { - uint32_t ni = n - i0 < CHUNK ? n - i0 : CHUNK; - WsSim s; memset(&s, 0, sizeof s); - s.p = p; s.threads = OMEGA_GPU_EW_THREADS; s.smem = g_smem; s.smem_bytes = sizeof g_smem; s.order = order; - uint64_t aa = (uintptr_t)(a + i0), ba = (uintptr_t)(b + i0), ca = (uintptr_t)(out + i0); - s.cbank[0x380 / 4] = (uint32_t)aa; s.cbank[0x380 / 4 + 1] = (uint32_t)(aa >> 32); - s.cbank[0x388 / 4] = (uint32_t)ba; s.cbank[0x388 / 4 + 1] = (uint32_t)(ba >> 32); - s.cbank[0x390 / 4] = (uint32_t)ca; s.cbank[0x390 / 4 + 1] = (uint32_t)(ca >> 32); - s.cbank[0x398 / 4] = ni; - s.ranges[0] = (WsRange){ (uintptr_t)aa, (uintptr_t)aa + (size_t)ni * 4 }; - s.ranges[1] = (WsRange){ (uintptr_t)ba, (uintptr_t)ba + (size_t)ni * 4 }; - s.ranges[2] = (WsRange){ (uintptr_t)ca, (uintptr_t)ca + (size_t)ni * 4 }; - s.nranges = 3; - int err = ws_run(&s, (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS, 1); - wi += s.warp_issues; li += s.lane_issues; sp += s.splits; - if (s.max_frags > mf) mf = s.max_frags; - if (s.peak_bars > pb) pb = s.peak_bars; - if (err) { if (stats) *stats = s; return err; } - } - if (stats) { memset(stats, 0, sizeof *stats); stats->warp_issues = wi; stats->lane_issues = li; stats->splits = sp; stats->max_frags = mf; stats->peak_bars = pb; } - return 0; -} -static int codegen(OmegaGpuEwOp op, int mutant, BlackwellIRProgram *p, OmegaBlackwellKernel *k) { - memset(k, 0, sizeof *k); - return omega_gpu_elementwise_codegen_ir(op, mutant, p, k); -} -static int is_reconv_err(int e) { - return e == WS_E_SHFL_SPLIT || e == WS_E_BAR_SPLIT || e == WS_E_STUCK || e == WS_E_NEVER_JOINED || e == WS_E_JOIN_MISMATCH || - e == WS_E_BSYNC_UNARMED || e == WS_E_BSSY_REARM || e == WS_E_NONMEMBER || e == WS_E_SHFL_EXITED; -} - -/* --------------------------------------------------------- static walks */ -/* Scoreboard walk (as bench/prime_race/tests/gb10_sieve_host_test.c sb_hazards): a destination - * written under write scoreboard 0 is in flight until a wait mask that includes it. */ -static int sb_hazards(const BlackwellIRProgram *p) { - int inflight[64], n = 0, bad = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - uint32_t c = in->control; - if ((c >> 20) & 1u) n = 0; - const int src[3] = { in->src1_vreg, in->src2_vreg, in->src3_vreg }; - for (int s = 0; s < 3; s++) for (int k = 0; src[s] >= 0 && k < n; k++) if (inflight[k] == src[s]) bad++; - if (c != 0 && ((c >> 14) & 7u) == 0 && in->dst_vreg >= 0 && n < 64) inflight[n++] = in->dst_vreg; - } - return bad; -} -/* Control-edge walk: the straight-line scoreboard reasoning above holds only if nothing is in - * flight across a branch, barrier op or exit. Every BRA / EXIT / BSSY / BSYNC must wait on every - * scoreboard set since the last wait. Returns the number of control ops that do not. */ -static int edge_waits(const BlackwellIRProgram *p) { - uint32_t pending = 0; int bad = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - uint32_t c = in->control, wait = (c >> 20) & 63u, wb = (c >> 14) & 7u, rb = (c >> 17) & 7u; - pending &= ~wait; - if (in->op == BW_IR_BRA || in->op == BW_IR_EXIT || in->op == BW_IR_BSSY || in->op == BW_IR_BSYNC) { if (pending) bad++; } - if (wb != 7u) pending |= 1u << wb; - if (rb != 7u) pending |= 1u << rb; - } - return bad; -} -static int count_op(const BlackwellIRProgram *p, BlackwellIROpcode op, int bar) { - int n = 0; - for (size_t i = 0; i < p->count; i++) if (p->insns[i].op == op && (bar < 0 || p->insns[i].bar_reg == bar)) n++; - return n; -} -static int find_op(const BlackwellIRProgram *p, BlackwellIROpcode op, int nth) { - for (size_t i = 0; i < p->count; i++) if (p->insns[i].op == op && nth-- == 0) return (int)i; - return -1; -} - -/* --------------------------------------------------------- nvdisasm listing */ -static int nvdisasm_bytes(const uint8_t *code, size_t bytes, const char *name, const char *const *must, int n_must) { - const char *nv = "/usr/local/cuda/bin/nvdisasm"; - if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check skipped for %s\n", name); return 0; } - char bin[96], lst[96], cmd[320]; - snprintf(bin, sizeof bin, "/tmp/omega_rc_%s_%d.bin", name, (int)getpid()); - snprintf(lst, sizeof lst, "/tmp/omega_rc_%s_%d.sass", name, (int)getpid()); - FILE *f = fopen(bin, "wb"); if (!f) return -1; - fwrite(code, 1, bytes, f); fclose(f); - snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); - int rc = system(cmd); - FILE *l = fopen(lst, "r"); if (!l) return -1; - char line[512]; int seen[16] = {0}, bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*0")) continue; - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - for (int i = 0; i < n_must && i < 16; i++) if (strstr(line, must[i])) seen[i] = 1; - } - fclose(l); - int miss = 0; - for (int i = 0; i < n_must && i < 16; i++) if (!seen[i]) { printf(" %s: nvdisasm listing lacks %s\n", name, must[i]); miss++; } - printf("nvdisasm %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - unlink(bin); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} -static int nvdisasm_kernel(OmegaGpuEwOp op, int mutant, const char *name, const char *const *must, int n_must) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - if (!p || codegen(op, mutant, p, &k) != OMEGA_GPU_EW_OK) { free(p); return -1; } - int rc = nvdisasm_bytes(k.code, k.code_size, name, must, n_must); - free(k.code); free(p); - return rc; -} - -/* --------------------------------------------------------- host part */ -typedef struct { const char *name; uint64_t warp_issues, lane_issues, splits; int max_frags, peak_bars; } Model; -static Model g_model[NPROBES * 2]; static int g_nmodel; - -static int host_part(void) { - int before = g_failed; - /* 1. encoder golden words (nvcc 13.0.88 -arch=sm_121 oracle, docs/gpu-reconvergence-308.md) */ - int fx = omega_blackwell_verify_codegen_fixtures_reconv(); - CHECK(fx == 0, "encoder golden words BSSY / BSYNC and refusals (rc %d)", fx); - - /* 2. region bookkeeping on a hand-built program */ - { - BlackwellIRProgram *p = calloc(1, sizeof *p); BwRegions r; memset(&r, 0, sizeof r); - omega_bw_ir_init(p); - BlackwellIRInsn in; memset(&in, 0, sizeof in); in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = -1; - in.op = BW_IR_BSSY; in.bar_reg = 0; in.imm = 2; omega_bw_ir_append(p, &in); /* 0 */ - CHECK(bw_regions_next_bar(&r) == 0 && bw_regions_begin(&r, 0) == 0, "region begin returns B0"); - in.op = BW_IR_BRA; in.imm = 1; in.predicate_p0 = true; omega_bw_ir_append(p, &in); /* 1 */ - CHECK(bw_regions_exit(&r, 1) == 0, "region exit recorded"); - in.op = BW_IR_NOP; in.predicate_p0 = false; omega_bw_ir_append(p, &in); /* 2 */ - in.op = BW_IR_BSYNC; in.bar_reg = 0; omega_bw_ir_append(p, &in); /* 3 */ - CHECK(bw_regions_join(&r, p, 3) == 0, "region join returns B0"); - CHECK(p->insns[0].imm == 4 && p->insns[1].imm == 2, "join patched BSSY to the insn after BSYNC (%u) and the exit to the BSYNC (%u)", p->insns[0].imm, p->insns[1].imm); - CHECK(bw_regions_join(&r, p, 3) == -1, "join with no open region refused"); - CHECK(bw_regions_exit(&r, 1) == -1, "exit with no open region refused"); - /* exits table full */ - memset(&r, 0, sizeof r); bw_regions_begin(&r, 0); - int ok = 1; for (int i = 0; i < BW_RECONV_MAX_EXITS; i++) ok &= bw_regions_exit(&r, 1) == 0; - CHECK(ok && bw_regions_exit(&r, 1) == -1, "exit table bound (%d) fails closed", BW_RECONV_MAX_EXITS); - /* join index inconsistent: BSYNC before BSSY, wrong barrier */ - memset(&r, 0, sizeof r); bw_regions_begin(&r, 3); - CHECK(bw_regions_join(&r, p, 0) == -1, "join with BSSY after BSYNC refused"); - memset(&r, 0, sizeof r); bw_regions_begin(&r, 0); p->insns[3].bar_reg = 1; - CHECK(bw_regions_join(&r, p, 3) == -1, "join with the wrong barrier register refused"); - p->insns[3].bar_reg = 0; - /* depth bound */ - memset(&r, 0, sizeof r); ok = 1; - for (int d = 0; d < BW_RECONV_MAX_DEPTH; d++) ok &= bw_regions_next_bar(&r) == d && bw_regions_begin(&r, d) == d; - CHECK(ok && bw_regions_next_bar(&r) == -1 && bw_regions_begin(&r, 99) == -1, "nesting bound %d: the next begin fails closed", BW_RECONV_MAX_DEPTH); - free(p); - } - - /* 3. codegen: production probes build, refusals refuse, mutants differ */ - static const struct { OmegaGpuEwOp op; const char *name; } refuse[] = { - { OMEGA_GPU_EW_RC_REFUSE_DEPTH17, "17 nested regions" }, { OMEGA_GPU_EW_RC_REFUSE_EXIT_SHFL, "EXIT then BAR/SHFL" }, - { OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION, "EXIT inside a region" }, { OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION, "BAR.SYNC inside a region" }, - { OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION, "SHFL inside a region" }, { OMEGA_GPU_EW_RC_REFUSE_UNCLOSED, "region never joined" }, - { OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY, "BSYNC with no BSSY" }, - }; - for (size_t i = 0; i < sizeof refuse / sizeof refuse[0]; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen(refuse[i].op, 0, p, &k); - CHECK(rc == OMEGA_GPU_EW_CODEGEN_FAIL, "%s refused at codegen (rc %s)", refuse[i].name, omega_gpu_elementwise_rc_name(rc)); - if (rc == OMEGA_GPU_EW_OK) free(k.code); - free(p); - } - for (size_t i = 0; i < NPROBES; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen(PROBES[i].op, 0, p, &k); - CHECK(rc == OMEGA_GPU_EW_OK && k.gpr_count <= 64, "%s builds (rc %s, %zu insns, %u gprs)", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count); - if (rc != OMEGA_GPU_EW_OK) { free(p); continue; } - int nb = count_op(p, BW_IR_BSSY, -1), ns = count_op(p, BW_IR_BSYNC, -1); - int want = PROBES[i].op == OMEGA_GPU_EW_RC_NESTED ? 2 : PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16 ? BW_RECONV_MAX_BAR : 1; - CHECK(nb == want && ns == want, "%s has %d BSSY and %d BSYNC (want %d)", PROBES[i].name, nb, ns, want); - if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) { - int each = 1; for (int b = 0; b < BW_RECONV_MAX_BAR; b++) each &= count_op(p, BW_IR_BSSY, b) == 1 && count_op(p, BW_IR_BSYNC, b) == 1; - CHECK(each, "depth16 uses every barrier register B0..B15 exactly once"); - } - CHECK(sb_hazards(p) == 0, "%s scoreboard walk clean", PROBES[i].name); - CHECK(edge_waits(p) == 0, "%s every control op waits on everything in flight", PROBES[i].name); - printf("codegen %s: %zu insns, %u gprs, %d regions\n", PROBES[i].name, p->count, k.gpr_count, nb); - uint8_t d0[32]; memcpy(d0, k.code_digest, 32); free(k.code); - for (int m = 1; m <= 3; m++) { - BlackwellIRProgram *mp = calloc(1, sizeof *mp); OmegaBlackwellKernel mk; - int mrc = codegen(PROBES[i].op, m, mp, &mk); - int same_ok = m == 1 && PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16; /* depth16 has no math mutant */ - CHECK(mrc == OMEGA_GPU_EW_OK && ((memcmp(d0, mk.code_digest, 32) != 0) != same_ok), "%s mutant %d builds and %s (rc %s)", PROBES[i].name, m, same_ok ? "equals production" : "differs", omega_gpu_elementwise_rc_name(mrc)); - if (mrc == OMEGA_GPU_EW_OK) { - if (m == 2) CHECK(count_op(mp, BW_IR_BSYNC, -1) == 0 && count_op(mp, BW_IR_BSSY, -1) == nb, "%s mutant 2 has no BSYNC", PROBES[i].name); - if (m == 3) CHECK(count_op(mp, BW_IR_BSYNC, -1) == ns, "%s mutant 3 keeps its BSYNCs", PROBES[i].name); - free(mk.code); - } - free(mp); - } - free(p); - } - /* the four regioned sieves build too (their sweep runs in gb10_sieve_host_test) */ - for (int op = OMEGA_GPU_EW_PRIME_SIEVE_DIV1; op <= OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2; op++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen((OmegaGpuEwOp)op, 0, p, &k); - int staged = op == OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV1 || op == OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2; - int nb = rc == OMEGA_GPU_EW_OK ? count_op(p, BW_IR_BSSY, -1) : -1, want = (op >= OMEGA_GPU_EW_PRIME_SIEVE_DIV2 ? 2 : 1) + staged; - CHECK(rc == OMEGA_GPU_EW_OK && k.gpr_count <= 64 && nb == want && edge_waits(p) == 0, "sieve op %d builds with %d regions (rc %s, %u gprs)", op, nb, omega_gpu_elementwise_rc_name(rc), k.gpr_count); - if (rc == OMEGA_GPU_EW_OK) free(k.code); - free(p); - } - - /* 4. nvdisasm: the words decode as BSSY/BSYNC on the real barrier registers, and the predicated - * and B15 forms the encoder can produce decode too (built by hand: encode_one) */ - { - static const char *const m0[] = { "BSSY", "BSYNC", "B0", "SHFL.DOWN", "@P0 BRA" }; - CHECK(nvdisasm_kernel(OMEGA_GPU_EW_RC_DIAMOND, 0, "diamond", m0, 5) == 0, "diamond listing decodes with BSSY/BSYNC B0"); - static const char *const m1[] = { "BSSY", "BSYNC", "B15", "B7" }; - CHECK(nvdisasm_kernel(OMEGA_GPU_EW_RC_DEPTH16, 0, "depth16", m1, 4) == 0, "depth16 listing decodes with B15"); - static const char *const m2[] = { "BSSY", "B1", "BSYNC" }; - CHECK(nvdisasm_kernel(OMEGA_GPU_EW_PRIME_SIEVE_DIV2, 0, "sieve_div2", m2, 3) == 0, "nested sieve listing decodes with B1"); - uint8_t code[64]; uint32_t w[4]; BlackwellIRInsn in; memset(&in, 0, sizeof in); in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = -1; - in.op = BW_IR_BSSY; in.bar_reg = 3; in.imm = 2; in.predicate_p0 = true; omega_blackwell_encode_one(&in, w); memcpy(code, w, 16); - in.op = BW_IR_BSYNC; in.bar_reg = 3; in.predicate_p0 = true; in.predicate_not = true; omega_blackwell_encode_one(&in, w); memcpy(code + 16, w, 16); - in.op = BW_IR_BSYNC; in.bar_reg = 15; in.predicate_p0 = false; in.predicate_not = false; omega_blackwell_encode_one(&in, w); memcpy(code + 32, w, 16); - in.op = BW_IR_EXIT; omega_blackwell_encode_one(&in, w); memcpy(code + 48, w, 16); - static const char *const m3[] = { "@P0 BSSY", "B3", "@!P0 BSYNC", "BSYNC.RECONVERGENT B15" }; - CHECK(nvdisasm_bytes(code, 64, "forms", m3, 4) == 0, "predicated BSSY/BSYNC and B15 decode"); - } - - /* 5. simulator: every probe, every n, both fragment orders, exact against the oracle */ - uint32_t *a = malloc(MAXN * 4), *b = malloc(MAXN * 4), *got = malloc(MAXN * 4), *want = malloc(MAXN * 4); - for (size_t i = 0; i < NPROBES; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - if (codegen(PROBES[i].op, 0, p, &k) != OMEGA_GPU_EW_OK) { free(p); continue; } - int fails = 0; uint64_t cases = 0; - for (size_t j = 0; j < NNS; j++) for (int order = 0; order < 2; order++) { - uint32_t n = NS[j]; fill(a, b, n, 0x308u + n * 7u + (uint32_t)order); - rc_oracle(PROBES[i].op, 0, n, a, b, want); - WsSim st; int err = ws_probe(p, n, a, b, got, order, &st); - uint32_t first; size_t bad = diff_count(got, want, n, &first); - cases++; - if (err || bad) { fails++; printf(" %s n=%u order=%d: sim %s, %zu words differ (first %u: got %08x want %08x)\n", PROBES[i].name, n, order, err ? st.msg : "clean", bad, first, first < n ? got[first] : 0, first < n ? want[first] : 0); } - if (n == 4096) { Model *m = &g_model[g_nmodel++]; m->name = PROBES[i].name; m->warp_issues = st.warp_issues; m->lane_issues = st.lane_issues; m->splits = st.splits; m->max_frags = st.max_frags; m->peak_bars = st.peak_bars; } - } - CHECK(fails == 0, "%s simulator vs oracle: %d of %" PRIu64 " cases differ", PROBES[i].name, fails, cases); - /* math mutant: simulator clean, result wrong (the oracle sees it) */ - BlackwellIRProgram *mp = calloc(1, sizeof *mp); OmegaBlackwellKernel mk; - if (codegen(PROBES[i].op, 1, mp, &mk) == OMEGA_GPU_EW_OK) { - uint32_t n = 1000; fill(a, b, n, 0x1001u); rc_oracle(PROBES[i].op, 0, n, a, b, want); - WsSim st; int err = ws_probe(mp, n, a, b, got, 0, &st); uint32_t first; size_t bad = diff_count(got, want, n, &first); - if (PROBES[i].op == OMEGA_GPU_EW_RC_EXIT_BAR) CHECK(err == WS_E_SHFL_EXITED || err == WS_E_BAR_SPLIT, "R6 early-exit kernel: simulator reports SHFL_EXITED (got %s)", st.msg); - else if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) CHECK(err == 0 && bad == 0, "depth16 'mutant 1' is the production kernel: clean and exact (err %d bad %zu)", err, bad); - else CHECK(err == 0 && bad > 0, "%s math mutant: simulator clean, %zu words differ (err %d)", PROBES[i].name, bad, err); - free(mk.code); - } - free(mp); - /* dropped join and corrupted target: the simulator must reject both, in both orders */ - for (int m = 2; m <= 3; m++) for (int order = 0; order < 2; order++) { - BlackwellIRProgram *xp = calloc(1, sizeof *xp); OmegaBlackwellKernel xk; - if (codegen(PROBES[i].op, m, xp, &xk) == OMEGA_GPU_EW_OK) { - uint32_t n = 1000; fill(a, b, n, 0x2002u + (uint32_t)m); - WsSim st; int err = ws_probe(xp, n, a, b, got, order, &st); - CHECK(is_reconv_err(err), "%s mutant %d (%s) order %d rejected by the simulator: %s", PROBES[i].name, m, m == 2 ? "BSYNC dropped" : "BSSY target corrupted", order, err ? st.msg : "NOT CAUGHT"); - if (m == 3) CHECK(err == WS_E_JOIN_MISMATCH || err == WS_E_STUCK, "%s corrupted target shows as JOIN_MISMATCH or STUCK (%s)", PROBES[i].name, ws_err_name(err)); - free(xk.code); - } - free(xp); - } - free(k.code); free(p); - } - /* 6. hand mutations of the production diamond (controls on the simulator itself, independent of - * the emitter's mutant hooks): exit jumping past the BSYNC, BSYNC on the wrong barrier, a BSSY - * on an armed barrier. And the unmodified program as the positive control. */ - { - BlackwellIRProgram *p = calloc(1, sizeof *p), *q = calloc(1, sizeof *q); OmegaBlackwellKernel k; - if (codegen(OMEGA_GPU_EW_RC_DIAMOND, 0, p, &k) == OMEGA_GPU_EW_OK) { - uint32_t n = 500; fill(a, b, n, 0x3003u); WsSim st; - int bssy = find_op(p, BW_IR_BSSY, 0), bsync = find_op(p, BW_IR_BSYNC, 0), ex = -1; - for (int i = bssy + 1; i < bsync; i++) if (p->insns[i].op == BW_IR_BRA && !p->insns[i].predicate_p0) ex = i; - CHECK(bssy >= 0 && bsync > bssy && ex > bssy, "diamond shape: BSSY %d, exit %d, BSYNC %d", bssy, ex, bsync); - CHECK(ws_probe(p, n, a, b, got, 0, &st) == 0, "positive control: untouched diamond runs clean"); - *q = *p; q->insns[ex].imm += 1; /* exit lands after the BSYNC */ - int e1 = ws_probe(q, n, a, b, got, 0, &st); CHECK(is_reconv_err(e1), "exit past the BSYNC rejected: %s", st.msg); - *q = *p; q->insns[bsync].bar_reg = 1; /* BSYNC on a barrier nobody armed */ - int e2 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e2 == WS_E_BSYNC_UNARMED, "BSYNC on an unarmed barrier rejected: %s", st.msg); - *q = *p; q->insns[bsync].op = BW_IR_NOP; /* join dropped by hand */ - int e3 = ws_probe(q, n, a, b, got, 0, &st); CHECK(is_reconv_err(e3), "join replaced by NOP rejected: %s", st.msg); - *q = *p; q->insns[bssy].imm += 1; /* names the wrong join */ - int e4 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e4 == WS_E_JOIN_MISMATCH, "wrong join target rejected: %s", st.msg); - *q = *p; q->insns[bssy + 1] = p->insns[bssy]; /* second BSSY on the armed barrier (overwrites the ISETP) */ - int e5 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e5 == WS_E_BSSY_REARM, "BSSY on an armed barrier rejected: %s", st.msg); - free(k.code); - } - free(p); free(q); - } - free(a); free(b); free(got); free(want); - for (int i = 0; i < g_nmodel; i++) printf("model %s n=4096: warp_issues=%" PRIu64 " lane_util=%.3f splits=%" PRIu64 " max_frags=%d peak_bars=%d\n", g_model[i].name, g_model[i].warp_issues, g_model[i].warp_issues ? (double)g_model[i].lane_issues / (32.0 * (double)g_model[i].warp_issues) : 0.0, g_model[i].splits, g_model[i].max_frags, g_model[i].peak_bars); - return g_failed == before ? 0 : -1; -} - -/* --------------------------------------------------------- chip part */ -static int chip(const char *out_path, int observe) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_RECONV_V1\",\"issue\":308,\"comparison\":\"exact u32\",\"cases\":["); - int first = 1; - uint32_t *a = malloc(MAXN * 4), *b = malloc(MAXN * 4), *got = malloc(MAXN * 4), *want = malloc(MAXN * 4); - for (size_t i = 0; i < NPROBES; i++) { - for (size_t j = 0; j < NNS; j++) { - uint32_t n = NS[j]; fill(a, b, n, 0x5050u + n); - rc_oracle(PROBES[i].op, 0, n, a, b, want); - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(PROBES[i].op, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - int pass = rc == OMEGA_GPU_EW_OK && bad == 0; - CHECK(pass, "%s n=%u chip rc=%s violations=%zu err=\"%s\"", PROBES[i].name, n, omega_gpu_elementwise_rc_name(rc), bad, omega_gpu_elementwise_last_error()); - if (out) fprintf(out, "%s{\"op\":\"%s\",\"regression\":\"%s\",\"n\":%u,\"rc\":\"%s\",\"violations\":%zu,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"cache_hit\":%s}", - first ? "" : ",", PROBES[i].name, PROBES[i].reg, n, omega_gpu_elementwise_rc_name(rc), bad, pass ? "true" : "false", info.elapsed_ns, info.chip_calls, info.unwritten_words, info.kernel_cache_hit ? "true" : "false"); - first = 0; - if (!pass) { printf("STOP: %s failed on the chip at n=%u; no further launches of this probe\n", PROBES[i].name, n); break; } - } - } - if (out) fprintf(out, "],\"mutants\":["); - first = 1; - for (size_t i = 0; i < NPROBES; i++) { - if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) continue; /* no math mutant */ - uint32_t n = 1000; fill(a, b, n, 0x6060u); rc_oracle(PROBES[i].op, 0, n, a, b, want); - omega_gpu_elementwise_test_set_mutant((int)PROBES[i].op); - /* R6's math mutant is the early-exit kernel: the emitter refuses it on the launch path - * (the bypass exists only for codegen_ir), so the catch is CODEGEN_FAIL: no undefined - * SHFL ever reaches the chip. */ - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(PROBES[i].op, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - int caught = rc != OMEGA_GPU_EW_OK || bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - CHECK(caught, "%s math mutant caught (rc %s, violations %zu)", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), bad); - if (PROBES[i].op == OMEGA_GPU_EW_RC_EXIT_BAR) CHECK(rc == OMEGA_GPU_EW_CODEGEN_FAIL, "R6 early-exit form refused at codegen on the launch path (rc %s)", omega_gpu_elementwise_rc_name(rc)); - if (out) fprintf(out, "%s{\"op\":\"%s\",\"mutant\":1,\"rc\":\"%s\",\"violations\":%zu,\"caught\":%s}", first ? "" : ",", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), bad, caught ? "true" : "false"); - first = 0; - } - if (out) fprintf(out, "],\"observations\":["); - if (observe) { - /* The dropped-join kernel (rejected by the simulator above) on the chip once, small n: - * recorded as an observation of what the hardware does without the BSYNC. Not a gate. */ - uint32_t n = 1000; fill(a, b, n, 0x7070u); rc_oracle(OMEGA_GPU_EW_RC_DIAMOND, 0, n, a, b, want); - omega_gpu_elementwise_test_set_mutant_level(OMEGA_GPU_EW_RC_DIAMOND, 2); - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(OMEGA_GPU_EW_RC_DIAMOND, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - omega_gpu_elementwise_test_set_mutant(0); - printf("observation: diamond with the BSYNC dropped, n=%u: rc=%s, %zu of %u words differ from the oracle (first %u)\n", n, omega_gpu_elementwise_rc_name(rc), bad, n, fi); - if (out) fprintf(out, "{\"op\":\"rc_diamond\",\"mutant\":2,\"what\":\"BSYNC dropped\",\"n\":%u,\"rc\":\"%s\",\"violations\":%zu,\"first_bad\":%u,\"gate\":false}", n, omega_gpu_elementwise_rc_name(rc), bad, fi); - } - CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count()); - if (out) { - fprintf(out, "],\"sim_model_n4096\":["); - for (int i = 0; i < g_nmodel; i++) fprintf(out, "%s{\"op\":\"%s\",\"order\":%d,\"warp_issues\":%" PRIu64 ",\"lane_issues\":%" PRIu64 ",\"splits\":%" PRIu64 ",\"max_frags\":%d,\"peak_bars\":%d}", i ? "," : "", g_model[i].name, i & 1, g_model[i].warp_issues, g_model[i].lane_issues, g_model[i].splits, g_model[i].max_frags, g_model[i].peak_bars); - fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_RECONV_PASS" : "OMEGA_GPU_RECONV_FAIL"); - fclose(out); - } - free(a); free(b); free(got); free(want); - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, observe = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--observe-dropped-join") == 0) observe = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - int hrc = host_part(); - if (!host) { - if (hrc != 0) { printf("host part failed: no chip launches\nFAIL: %d checks, %d failed\n", g_checks, g_failed); return 1; } - if (chip(out_path, observe) != 0) return 2; - } - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_router_test.c b/tests/gpu_router_test.c deleted file mode 100644 index 1c274e79a..000000000 --- a/tests/gpu_router_test.c +++ /dev/null @@ -1,360 +0,0 @@ -/* - * gpu_router_test: the one-launch MoE router (omega_gpu_router_api.h), OWN-30B cut 8 item 2. - * --host-only oracle sanity, codegen budgets and refusals, the libm-free pieces (no device) - * --sim warp-simulator parity at 8 warps (both fragment orders), norm_topk on and off, mutants 1-4 caught - * (default) the chip: parity against the double oracle on random hidden states (two layers, norm_topk on and - * off), second call bit-identical, mutants 1-4 caught, the end-to-end: the grouped FP8 gate+up GEMV - * reading the router-written group table and x' row equals the host-table call bit for bit, chip - * medians (--reps N, --warps W, --depth D, --no-evict, --spin-us, --out receipt.json) - * Verdict line last: "gpu_router_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_router_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static const float EPS = 1e-6f; -#define H OMEGA_ROUTER_HIDDEN -#define NE OMEGA_ROUTER_EXPERTS -#define TK OMEGA_ROUTER_TOPK -#define MARGIN_FLOOR 1e-4 /* an id mismatch at an oracle margin (8th - 9th logit) below this is recorded, not failed */ - -typedef struct { - float x[H], nw[H]; - uint16_t *gate; /* [128][2048] bf16 */ - double xn[H], logits[NE], w[TK], margin; - uint32_t ids[TK]; -} Case; - -/* the double oracle from c->x, c->nw, c->gate: xn, logits, ids (descending, lowest index on ties), weights, margin */ -static void oracle_fill(Case *c, int norm_topk) { - double ss = 0; for (unsigned i = 0; i < H; i++) ss += (double)c->x[i] * c->x[i]; - double r = 1.0 / sqrt(ss / (double)H + (double)EPS); - for (unsigned i = 0; i < H; i++) c->xn[i] = (double)c->x[i] * r * (double)c->nw[i]; - double mx = -1e300; - for (unsigned e = 0; e < NE; e++) { double l = 0; for (unsigned k = 0; k < H; k++) l += (double)bf16_f32(c->gate[(size_t)e * H + k]) * c->xn[k]; c->logits[e] = l; if (l > mx) mx = l; } - double p[NE], sum = 0; for (unsigned e = 0; e < NE; e++) { p[e] = exp(c->logits[e] - mx); sum += p[e]; } - for (unsigned e = 0; e < NE; e++) p[e] /= sum; - int taken[NE]; memset(taken, 0, sizeof taken); - double s8 = 0; - for (unsigned r8 = 0; r8 <= TK; r8++) { /* 9 rounds: the 9th gives the margin */ - int best = -1; for (unsigned e = 0; e < NE; e++) if (!taken[e] && (best < 0 || c->logits[e] > c->logits[best])) best = (int)e; - if (r8 < TK) { c->ids[r8] = (uint32_t)best; taken[best] = 1; s8 += p[best]; c->w[r8] = p[best]; } - else c->margin = c->logits[c->ids[TK - 1]] - c->logits[best]; - } - if (norm_topk) for (unsigned i = 0; i < TK; i++) c->w[i] /= s8; -} -static void case_make(Case *c, uint32_t seed, float xscale, int norm_topk) { - uint32_t s = seed; - c->gate = malloc((size_t)NE * H * 2); - for (unsigned i = 0; i < H; i++) { c->x[i] = frand(&s, -2.0f, 2.0f) * xscale; c->nw[i] = frand(&s, 0.8f, 1.2f); } - for (size_t i = 0; i < (size_t)NE * H; i++) c->gate[i] = bf16_rne(frand(&s, -0.05f, 0.05f)); - oracle_fill(c, norm_topk); -} -static void case_free(Case *c) { free(c->gate); } - -/* outputs of one run (chip or simulator) */ -typedef struct { uint32_t ids[TK]; float w[TK], xout[H]; uint64_t tgu[TK * 2], tdn[TK * 2]; } Out; - -/* compares an Out against the oracle; returns a bitmask of what differed (1 ids, 2 weights, 4 x', 8 tables); fills msg */ -static int compare(const Case *c, const Out *o, float out_scale, const uint64_t *dgu, const uint64_t *ddn, char *msg, size_t n, int *margin_case) { - int bad = 0; *margin_case = 0; - int ids_eq = memcmp(c->ids, o->ids, sizeof c->ids) == 0; - if (!ids_eq) { if (c->margin < MARGIN_FLOOR) *margin_case = 1; else bad |= 1; } - double ww = 0, wx = 0; - if (ids_eq) for (unsigned i = 0; i < TK; i++) { double d = fabs((double)o->w[i] - c->w[i]); if (d > ww) ww = d; } - if (ww > 1e-5) bad |= 2; - double xmax = 0; for (unsigned i = 0; i < H; i++) if (fabs(c->xn[i]) > xmax) xmax = fabs(c->xn[i]); - for (unsigned i = 0; i < H; i++) { double d = fabs((double)o->xout[i] / (double)out_scale - c->xn[i]); if (d > wx) wx = d; } - if (wx > 1e-5 * xmax) bad |= 4; - if (ids_eq) for (unsigned g = 0; g < TK; g++) { - uint32_t id = o->ids[g]; - if (o->tgu[2 * g] != dgu[2 * id] || o->tgu[2 * g + 1] != dgu[2 * id + 1] || o->tdn[2 * g] != ddn[2 * id] || o->tdn[2 * g + 1] != ddn[2 * id + 1]) bad |= 8; - } - snprintf(msg, n, "ids %s%s, w max abs %.2e, x' max abs %.2e (of %.2f), tables %s, margin %.2e", ids_eq ? "equal" : "DIFFER", *margin_case ? " (margin case)" : "", ww, wx, xmax, (bad & 8) ? "WRONG" : "ok", c->margin); - return bad; -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - { Case c; case_make(&c, 1, 1.0f, 1); - double s = 0; for (unsigned i = 0; i < TK; i++) s += c.w[i]; - CHECK(fabs(s - 1.0) < 1e-12, "oracle: normalised weights sum to 1 (%.15f)", s); - int desc = 1; for (unsigned i = 1; i < TK; i++) desc &= c.logits[c.ids[i - 1]] >= c.logits[c.ids[i]]; - CHECK(desc, "oracle: ids are in descending logit order"); - CHECK(c.margin > 0, "oracle: margin positive (%.3e)", c.margin); - double rms = 0; for (unsigned i = 0; i < H; i++) rms += c.xn[i] * c.xn[i] / (c.nw[i] * c.nw[i]); rms = sqrt(rms / H); - CHECK(fabs(rms - 1.0) < 1e-3, "oracle: RMSNorm output has unit rms before the weight (%.6f)", rms); - case_free(&c); } - { Case c; case_make(&c, 2, 1.0f, 0); - double s = 0; for (unsigned i = 0; i < TK; i++) s += c.w[i]; - CHECK(s < 1.0 && s > 0.0, "oracle: unnormalised weights sum below 1 (%.4f)", s); - case_free(&c); } - /* codegen budgets: every production shape fits the register file (32 * warps * declared <= 65536) and the IR limit */ - uint32_t ws[] = { 8, 16, 32 }, ds[] = { 1, 2, 4, 8 }; - for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 4; j++) for (int m = 0; m <= 4; m++) { - OmegaRouterSpec s = { ws[i], ds[j], m }; uint32_t n = 0, g = 0; - int rc = omega_router_prog_stats(&s, &n, &g); - uint32_t decl = ((g + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024 && 32u * ws[i] * decl <= 65536u, "codegen warps %u depth %u mutant %d: rc %d insns %u gprs %u declared %u", ws[i], ds[j], m, rc, n, g, decl); - if (m == 0 && rc == 0) printf("codegen warps %2u depth %u: %u instructions, %u registers (declared %u, register file %u of 65536)\n", ws[i], ds[j], n, g, decl, 32u * ws[i] * decl); - } - { OmegaRouterSpec s = { 4, 8, 0 }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "warps 4 refused"); } - { OmegaRouterSpec s = { 8, 3, 0 }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "depth 3 refused"); } - { OmegaRouterSpec s = { 8, 8, 5 }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "mutant 5 refused"); } - CHECK(OMEGA_ROUTER_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -/* one "device" block: x | xout | ids | wts | tab_gu | tab_dn | dir_gu | dir_dn | norm; the gate row block apart */ -enum { B_X = 0, B_XOUT = 8192, B_IDS = 16384, B_WTS = 16448, B_TGU = 16512, B_TDN = 16640, B_DGU = 16768, B_DDN = 16768 + 2048, B_NORM = 16768 + 4096, B_BYTES = 16768 + 4096 + 8192 }; -static void fake_dirs(uint64_t *dgu, uint64_t *ddn) { for (unsigned e = 0; e < NE; e++) { dgu[2 * e] = 0x100000000ull + e * 16; dgu[2 * e + 1] = 0x200000000ull + e * 16 + 8; ddn[2 * e] = 0x300000000ull + e * 32; ddn[2 * e + 1] = 0x400000000ull + e * 32 + 16; } } -static int sim_point(uint32_t depth, int mutant, int norm_topk, float out_scale, uint32_t seed, char *msg, size_t n, int *bad, int *margin_case) { - static BlackwellIRProgram prog; - OmegaRouterSpec spec = { 8, depth, mutant }; - if (omega_blackwell_codegen_router_prog(&spec, &prog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make(&c, seed, 1.0f, norm_topk); - uint8_t *blk = aligned_alloc(16, B_BYTES); memset(blk, 0, B_BYTES); - uint16_t *gate = aligned_alloc(16, (size_t)NE * H * 2); memcpy(gate, c.gate, (size_t)NE * H * 2); - memcpy(blk + B_X, c.x, sizeof c.x); memcpy(blk + B_NORM, c.nw, sizeof c.nw); - uint64_t dgu[NE * 2], ddn[NE * 2]; fake_dirs(dgu, ddn); - memcpy(blk + B_DGU, dgu, sizeof dgu); memcpy(blk + B_DDN, ddn, sizeof ddn); - Out o, copy; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 256; s.order = order; - static uint8_t smem[OMEGA_ROUTER_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_ROUTER_SHARED_BYTES; - float *xo = (float *)(blk + B_XOUT), *wd = (float *)(blk + B_WTS); uint32_t *idd = (uint32_t *)(blk + B_IDS); - for (unsigned i = 0; i < H; i++) xo[i] = -999.0f; - for (unsigned i = 0; i < TK; i++) { wd[i] = -999.0f; idd[i] = 0xffffffffu; } - memset(blk + B_TGU, 0, 256); - uint64_t A[10] = { (uintptr_t)(blk + B_X), (uintptr_t)gate, (uintptr_t)(blk + B_NORM), (uintptr_t)(blk + B_XOUT), (uintptr_t)(blk + B_IDS), - (uintptr_t)(blk + B_WTS), (uintptr_t)(blk + B_DGU), (uintptr_t)(blk + B_DDN), (uintptr_t)(blk + B_TGU), (uintptr_t)(blk + B_TDN) }; - for (unsigned i = 0; i < 10; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = out_scale; - memcpy(&s.cbank[OMEGA_ROUTER_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_ROUTER_ARG_OUT_SCALE / 4], &fo, 4); - s.cbank[OMEGA_ROUTER_ARG_NORM_TOPK / 4] = norm_topk ? 1u : 0u; - s.nranges = 2; - s.ranges[0].lo = (uintptr_t)blk; s.ranges[0].hi = (uintptr_t)blk + B_BYTES; - s.ranges[1].lo = (uintptr_t)gate; s.ranges[1].hi = (uintptr_t)gate + (size_t)NE * H * 2; - err = ws_run(&s, 1, 1); - if (err) { snprintf(msg, n, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < H; i++) if (xo[i] == -999.0f) unwritten++; - for (unsigned i = 0; i < TK; i++) if (wd[i] == -999.0f || idd[i] == 0xffffffffu) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - memcpy(o.ids, idd, sizeof o.ids); memcpy(o.w, wd, sizeof o.w); memcpy(o.xout, xo, sizeof o.xout); memcpy(o.tgu, blk + B_TGU, 128); memcpy(o.tdn, blk + B_TDN, 128); - if (order == 0) copy = o; - else if (memcmp(©, &o, sizeof o) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) *bad = compare(&c, &o, out_scale, dgu, ddn, msg, n, margin_case); - free(blk); free(gate); case_free(&c); - return err; -} -static void sim_battery(void) { - struct { uint32_t depth; int norm_topk; float oscale; uint32_t seed; const char *name; } pts[] = { - { 8, 1, 1.0f, 11, "depth 8 norm" }, { 8, 1, 1.0f, 12, "depth 8 norm seed 12" }, { 8, 0, 1.0f, 13, "depth 8 no-norm" }, - { 4, 1, 1.0f, 14, "depth 4 norm" }, { 1, 1, 1.0f, 15, "depth 1 norm" }, { 2, 1, 18446744073709551616.0f, 16, "depth 2 norm out_scale 2^64" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; int bad = 0, mc = 0; - int err = sim_point(pts[i].depth, 0, pts[i].norm_topk, pts[i].oscale, pts[i].seed, msg, sizeof msg, &bad, &mc); - CHECK(!err && bad == 0, "sim %s: %s", pts[i].name, msg); - printf("sim %s: %s %s\n", pts[i].name, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 4; m++) { - char msg[300]; int bad = 0, mc = 0; - int err = sim_point(8, m, 1, 1.0f, 21, msg, sizeof msg, &bad, &mc); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s (bad mask %d) %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", bad, msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static int chip_call(OmegaGpuRouter *r, uint32_t layer, const Case *c, int norm_topk, float out_scale, Out *o, OmegaGpuRouterInfo *info) { - int rc = omega_gpu_router(r, layer, c->x, EPS, norm_topk, out_scale, o->ids, o->w, info); - if (rc != OMEGA_GPU_ROUTER_OK) return rc; - return omega_gpu_router_read_back(r, o->xout, o->tgu, o->tdn); -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_ROUTER_V1\",\"reps\":%u,\"evict\":%d,\"spin_us\":%u,\"points\":[", reps, g_evict, omega_gpu_session_spin_us()); - OmegaGpuRouter *r = NULL; - double t0 = now_ms(); - int rc = omega_gpu_router_alloc(2, &r); - printf("router alloc (2 layers): rc=%s %.1f ms (%s)\n", omega_gpu_router_rc_name(rc), now_ms() - t0, rc ? omega_gpu_router_last_error() : ""); - CHECK(rc == OMEGA_GPU_ROUTER_OK, "router alloc"); - if (rc) { if (out) fprintf(out, "],\"verdict\":\"FAIL\"}\n"); return 1; } - uint64_t dgu[NE * 2], ddn[NE * 2]; fake_dirs(dgu, ddn); - CHECK(omega_gpu_router_set_directory(r, 0, dgu, ddn) == OMEGA_GPU_ROUTER_OK, "set directory layer 0"); - int first = 1, parity_fail = 0, margin_cases = 0; - /* parity: layer 0, 24 cases norm on, 8 off, 4 with out_scale 2^64; then the same gate on layer 1 (addressing) */ - Case fixed; case_make(&fixed, 1000, 1.0f, 1); - CHECK(omega_gpu_router_set_layer(r, 0, fixed.gate, fixed.nw) == OMEGA_GPU_ROUTER_OK, "set layer 0"); - for (unsigned i = 0; i < 36; i++) { - int norm = i < 24 || i >= 32; float os = i >= 32 ? 18446744073709551616.0f : 1.0f; - /* layer 0 holds `fixed`'s router weights and norm: a fresh x per case, the oracle on fixed.gate / fixed.nw */ - Case c; uint32_t s = 2000 + i; const float xs = i % 3 == 0 ? 0.01f : i % 3 == 1 ? 1.0f : 40.0f; - for (unsigned k = 0; k < H; k++) c.x[k] = frand(&s, -2.0f, 2.0f) * xs; - memcpy(c.nw, fixed.nw, sizeof c.nw); c.gate = fixed.gate; - oracle_fill(&c, norm); - Out o; OmegaGpuRouterInfo info; - rc = chip_call(r, 0, &c, norm, os, &o, &info); - char msg[300]; int bad = -1, mc = 0; - if (rc == OMEGA_GPU_ROUTER_OK) bad = compare(&c, &o, os, dgu, ddn, msg, sizeof msg, &mc); - else snprintf(msg, sizeof msg, "rc %s: %s", omega_gpu_router_rc_name(rc), omega_gpu_router_last_error()); - if (bad) parity_fail++; - if (mc) margin_cases++; - if (bad || i < 3 || i >= 24) printf("parity %u (norm %d, out_scale %s, x scale %s): %s%s\n", i, norm, os > 2.0f ? "2^64" : "1", i % 3 == 0 ? "0.01" : i % 3 == 1 ? "1" : "40", bad ? "MISMATCH " : "ok ", msg); - if (out) { fprintf(out, "%s{\"point\":\"parity %u\",\"norm_topk\":%d,\"bad_mask\":%d,\"margin_case\":%d,\"chip_ns\":%" PRIu64 "}", first ? "" : ",", i, norm, bad, mc, info.elapsed_ns); first = 0; } - if (i == 0 && rc == OMEGA_GPU_ROUTER_OK) { - Out o2; rc = chip_call(r, 0, &c, norm, os, &o2, NULL); - CHECK(rc == OMEGA_GPU_ROUTER_OK && memcmp(&o, &o2, sizeof o) == 0, "second call bit-identical (ids, weights, x', tables)"); - printf("second call: %s\n", rc == OMEGA_GPU_ROUTER_OK && memcmp(&o, &o2, sizeof o) == 0 ? "bit-identical" : "DIFFERS"); - } - } - CHECK(parity_fail == 0, "chip parity: %d of 36 cases mismatch", parity_fail); - printf("chip parity: %d of 36 mismatches, %d margin cases (recorded, oracle margin below %.0e)\n", parity_fail, margin_cases, MARGIN_FLOOR); - /* mutants on a fixed case, layer 0 */ - for (int m = 1; m <= 4; m++) { - omega_gpu_router_test_set_mutant(m); - Out o; char msg[300]; int bad = -1, mc = 0; - rc = chip_call(r, 0, &fixed, 1, 1.0f, &o, NULL); - if (rc == OMEGA_GPU_ROUTER_OK) bad = compare(&fixed, &o, 1.0f, dgu, ddn, msg, sizeof msg, &mc); - else snprintf(msg, sizeof msg, "rc %s: %s", omega_gpu_router_rc_name(rc), omega_gpu_router_last_error()); - CHECK(bad != 0, "chip mutant %d must be caught: %s", m, msg); - printf("chip mutant %d: %s (bad mask %d) %s\n", m, bad ? "caught" : "NOT CAUGHT", bad, msg); - if (out) fprintf(out, ",{\"point\":\"mutant %d\",\"caught\":%d,\"bad_mask\":%d}", m, bad != 0, bad); - } - omega_gpu_router_test_set_mutant(0); - /* end to end on layer 1: real FP8 gate+up shape (128 x 1536 x 2048) and a small down tensor; the router's device - * table + x' feed omega_gpu_fp8_gemv_grouped_dev; the host-table call with the chip's ids and x'/2^64 must match bit for bit */ - { - const uint32_t GN = 1536, GK = 2048, DN = 256, DK = 768; - size_t gw = (size_t)NE * GN * GK, dw = (size_t)NE * DN * DK; - uint8_t *w1 = malloc(gw), *w2 = malloc(dw); - uint16_t *s1 = malloc((size_t)NE * (GN / 128) * (GK / 128) * 2), *s2 = malloc((size_t)NE * (DN / 128) * (DK / 128) * 2); - uint32_t s = 4242; - for (size_t i = 0; i < gw; i++) { uint8_t b = (uint8_t)(lcg(&s) >> 24); if ((b & 0x7f) == 0x7f) b ^= 1; w1[i] = b; } - for (size_t i = 0; i < dw; i++) { uint8_t b = (uint8_t)(lcg(&s) >> 24); if ((b & 0x7f) == 0x7f) b ^= 1; w2[i] = b; } - for (size_t i = 0; i < (size_t)NE * (GN / 128) * (GK / 128); i++) s1[i] = bf16_rne(frand(&s, 0.5f, 2.0f)); - for (size_t i = 0; i < (size_t)NE * (DN / 128) * (DK / 128); i++) s2[i] = bf16_rne(frand(&s, 0.5f, 2.0f)); - OmegaGpuFp8Tensor *tg = NULL, *td = NULL; - t0 = now_ms(); - int r1 = omega_gpu_fp8_tensor_upload(NE, GN, GK, w1, s1, &tg), r2 = omega_gpu_fp8_tensor_upload(NE, DN, DK, w2, s2, &td); - printf("fp8 upload gate+up %zu MB + down %zu MB: rc %s / %s, %.0f ms\n", gw >> 20, dw >> 20, omega_gpu_fp8_rc_name(r1), omega_gpu_fp8_rc_name(r2), now_ms() - t0); - CHECK(r1 == 0 && r2 == 0, "fp8 uploads for the end-to-end"); - if (r1 == 0 && r2 == 0) { - Case c; case_make(&c, 3000, 1.0f, 1); - CHECK(omega_gpu_router_set_layer(r, 1, c.gate, c.nw) == OMEGA_GPU_ROUTER_OK, "set layer 1"); - CHECK(omega_gpu_router_set_directory_fp8(r, 1, tg, td) == OMEGA_GPU_ROUTER_OK, "set directory layer 1 from the fp8 tensors"); - uint64_t rgu[NE * 2], rdn[NE * 2]; - for (unsigned e = 0; e < NE; e++) { omega_gpu_fp8_tensor_entry(tg, e, &rgu[2 * e], &rgu[2 * e + 1]); omega_gpu_fp8_tensor_entry(td, e, &rdn[2 * e], &rdn[2 * e + 1]); } - Out o; OmegaGpuRouterInfo info; char msg[300]; int mc = 0; - const float OS = 18446744073709551616.0f; - rc = chip_call(r, 1, &c, 1, OS, &o, &info); - int bad = rc == 0 ? compare(&c, &o, OS, rgu, rdn, msg, sizeof msg, &mc) : -1; - CHECK(bad == 0, "e2e router on layer 1 with real directories: %s", rc ? omega_gpu_router_last_error() : msg); - printf("e2e router layer 1: %s %s\n", bad ? "MISMATCH" : "ok", rc ? omega_gpu_router_last_error() : msg); - uint64_t xva, tgva, tdva; omega_gpu_router_device_outputs(r, &xva, &tgva, &tdva); - float *ydev = malloc((size_t)TK * GN * 4), *yhost = malloc((size_t)TK * GN * 4), *xh = malloc(H * 4); - for (unsigned k = 0; k < H; k++) xh[k] = o.xout[k] / OS; /* exact: a power of two */ - OmegaGpuFp8Info fi, fh; - int rd = omega_gpu_fp8_gemv_grouped_dev(tg, TK, tgva, xva, ydev, &fi); - int rh = omega_gpu_fp8_gemv_grouped_f32(tg, TK, o.ids, xh, 1, yhost, &fh); - CHECK(rd == 0 && rh == 0, "grouped gate+up launches: dev %s host %s", omega_gpu_fp8_rc_name(rd), omega_gpu_fp8_rc_name(rh)); - int same = rd == 0 && rh == 0 && memcmp(ydev, yhost, (size_t)TK * GN * 4) == 0; - CHECK(same, "grouped gate+up from the router-written table and x' equals the host-table call bit for bit"); - printf("e2e grouped gate+up (8 experts, %u x %u): device table/x' vs host table: %s; chip %.1f us vs %.1f us, call %.1f us vs %.1f us\n", GN, GK, same ? "bit-identical" : "DIFFER", - fi.elapsed_ns / 1e3, fh.elapsed_ns / 1e3, fi.call_ns / 1e3, fh.call_ns / 1e3); - /* one group against the FP8 host oracle (the grouped kernel is proven elsewhere; this pins the plumbing) */ - if (rd == 0) { - double *yo = malloc(GN * sizeof(double)), *ys = malloc(GN * sizeof(double)); - uint32_t id = o.ids[3]; - omega_fp8_gemv_oracle(w1 + (size_t)id * GN * GK, s1 + (size_t)id * (GN / 128) * (GK / 128), GN, GK, xh, yo, ys); - double worst = 0; for (unsigned i = 0; i < GN; i++) { double d = fabs((double)ydev[3 * GN + i] - yo[i]) / (ys[i] + 1e-30); if (d > worst) worst = d; } - CHECK(worst < 1e-5, "e2e group 3 (expert %u) vs the FP8 host oracle: worst rel %.2e", id, worst); - printf("e2e group 3 vs fp8 oracle: worst rel %.2e\n", worst); - free(yo); free(ys); - } - /* sequence timing: router then grouped gate+up (dev), medians */ - uint64_t *er = malloc(reps * 8), *ec = malloc(reps * 8), *eg = malloc(reps * 8), *es = malloc(reps * 8); - uint32_t done = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - double a = now_ms(); - if (omega_gpu_router(r, 1, c.x, EPS, 1, OS, o.ids, o.w, &info) != 0) break; - if (omega_gpu_fp8_gemv_grouped_dev(tg, TK, tgva, xva, ydev, &fi) != 0) break; - es[done] = (uint64_t)((now_ms() - a) * 1e6); - er[done] = info.elapsed_ns; ec[done] = info.call_ns; eg[done] = fi.elapsed_ns; done++; - } - CHECK(done == reps, "timing loop completed %u of %u", done, reps); - if (done) { - qsort(er, done, 8, cmp_u64); qsort(ec, done, 8, cmp_u64); qsort(eg, done, 8, cmp_u64); qsort(es, done, 8, cmp_u64); - printf("timing (medians of %u, evict %d, warps %u depth %u): router chip %.1f us, router call %.1f us, grouped gate+up dev chip %.1f us, router+gate+up sequence %.1f us\n", - done, g_evict, info.warps, info.depth, er[done / 2] / 1e3, ec[done / 2] / 1e3, eg[done / 2] / 1e3, es[done / 2] / 1e3); - if (out) fprintf(out, ",{\"point\":\"timing\",\"warps\":%u,\"depth\":%u,\"reps\":%u,\"router_chip_median_ns\":%" PRIu64 ",\"router_call_median_ns\":%" PRIu64 ",\"gateup_dev_chip_median_ns\":%" PRIu64 ",\"sequence_median_ns\":%" PRIu64 ",\"router_bytes\":%" PRIu64 ",\"marker\":%u}", - info.warps, info.depth, done, er[done / 2], ec[done / 2], eg[done / 2], es[done / 2], info.weight_bytes, info.completion_marker); - } - free(er); free(ec); free(eg); free(es); free(ydev); free(yhost); free(xh); - case_free(&c); - } - if (tg) omega_gpu_fp8_tensor_free(tg); - if (td) omega_gpu_fp8_tensor_free(td); - free(w1); free(w2); free(s1); free(s2); - } - case_free(&fixed); - omega_gpu_router_free(r); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 0, warps = 0, depth = 0, spin = 2000; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (warps || depth) omega_gpu_router_set_shape(warps, depth); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_router_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_serving_alloc_count_test.c b/tests/gpu_serving_alloc_count_test.c deleted file mode 100644 index c981434e5..000000000 --- a/tests/gpu_serving_alloc_count_test.c +++ /dev/null @@ -1,672 +0,0 @@ -/* - * gpu_serving_alloc_count_test: MEASUREMENT of driver (RM) allocations and frees made by the real - * native GPU stack (session + matmul API + attention API) while it "serves" a Qwen3-4B-shaped - * sequence, on the simulated driver of tests/fake_m16_native.c. Host only, opens no device. - * - * Why: sovereign-core design note docs/design/gb10-weight-ownership.md (sc#277, sc PR #292) argues - * that omega still asks the driver for memory while serving, and that one refused request faults - * the GPU session for the rest of the process. This test counts those requests. - * - * What it asserts: only bookkeeping that is true today (the session opens once, the fake saw every - * request, no double free, nothing latched, the call mix is what the report says it is). It does - * NOT assert the allocation counts: they are printed as MEASURE lines. A later change that reserves - * serving memory up front would lower them and this test would still pass; the numbers in the PR - * that made it are the record of today's behaviour. - * - * What it does not model: the kernels. The fake runs in FK_KERNEL_SKIP mode, so launches are - * counted and complete, but no matmul or attention result is computed. The matmul API therefore - * reports its own poison check (CHIP_FAIL) and the attention API reports UNWRITTEN; those return - * codes are expected here and are not errors of the allocation path. Elementwise kernels (rmsnorm, - * rope, swiglu) are not exercised; the design note's audit says they stop allocating after the - * first full-size call. - * - * Shapes (Qwen3-4B): hidden 2560, 32 q heads, 8 kv heads, head_dim 128, intermediate 9728, - * vocab 151936, 36 layers. One resident tensor per distinct weight shape stands in for the 36 - * layers (resident-weight allocations are a load-time cost, counted in phase LOAD only). - * Call pattern per layer follows crates/aien-inference-abi/src/transformer_backend.rs: - * decode (m = 1): q, k, v, attention(seq), o, gate, up, down ; after the layers lm_head (m = 1) - * prefill chunk: the same with m = chunk rows (<= 128), attention once per token at seq = - * offset + t + 1, lm_head with m = 1 after the chunk - * CTA budget 256 (the daemon value in the audit). - */ -#include -#include -#include - -#include "fake_m16_native.h" -#include "nvrm.h" /* the session reaches the fake driver through the Linux reference platform (P07 cut C) */ -#include "omega_blackwell_codegen.h" /* omega_matmul_frag_block_shape: the kernel cache key */ -#include "omega_blackwell_matmul.h" /* omega_fp32_to_bf16 (update mode) */ -#include "omega_gpu_attention_api.h" -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_serving.h" -#include "omega_gpu_session.h" - -/* The two driver symbols the session needs that the fake (written for the vector engine) lacks. */ -int nvrm_open(Nvrm *rm) { (void)rm; fk.device_open = 1; return 0; } -int nvrm_close(Nvrm *rm) { (void)rm; return 0; } -void nvrm_retire(Nvrm *rm, uint32_t upto) { (void)rm; (void)upto; } - -#define HID 2560u -#define QDIM 4096u -#define KVDIM 1024u -#define INTER 9728u -#define VOCAB 151936u -#define LAYERS 36u -#define QH 32u -#define KVH 8u -#define HD 128u -#define CHUNK 128u - -static int g_fail; -#define CHECK(c, ...) do { if (!(c)) { g_fail++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) - -/* ---- the weights: one tensor per distinct shape ---- */ -static OmegaGpuTensor *W_Q, *W_K, *W_O, *W_G, *W_D, *W_LM; - -static OmegaGpuTensor *upload(uint32_t k, uint32_t n) { - uint16_t *z = calloc((size_t)k * n, sizeof *z); - OmegaGpuTensor *t = NULL; - CHECK(z != NULL, "calloc %ux%u", k, n); - int rc = z ? omega_gpu_tensor_upload_bf16(k, n, z, &t) : -1; - CHECK(rc == OMEGA_GPU_MATMUL_OK, "upload %ux%u rc=%d %s", k, n, rc, omega_gpu_matmul_last_error()); - free(z); - return t; -} - -/* ---- per-phase counters ---- */ -typedef struct { - const char *name; - int allocs, frees; - uint64_t alloc_bytes, free_bytes; - int mm_calls, mm_miss, mm_remiss, mm_other_allocs; /* code-cache misses; misses on an already-seen shape; scratch growth */ - int at_calls, at_allocs; - int a0, f0; /* log positions at phase start */ -} Phase; - -/* The matmul API's kernel cache key: (kp, np, grid_x, rt, ct). rt and ct follow from the call's padded shape - * (omega_matmul_frag_block_shape, the rule the API's launch_shape uses); since the blocked prefill kernel (#407) - * two calls with the same grid_x can need different kernels. */ -typedef struct { uint32_t kp, np, gx, rt, ct; } Key; -static Key g_seen[128]; -static int g_nseen; -static int seen(const OmegaGpuMatmulInfo *in) { - Key k = { in->padded_k, in->padded_n, in->grid_x, 0, 0 }; - omega_matmul_frag_block_shape(in->padded_m / 16u, in->padded_n / 8u, &k.rt, &k.ct); - for (int i = 0; i < g_nseen; i++) - if (g_seen[i].kp == k.kp && g_seen[i].np == k.np && g_seen[i].gx == k.gx && g_seen[i].rt == k.rt && g_seen[i].ct == k.ct) return 1; - if (g_nseen < 128) g_seen[g_nseen++] = k; - return 0; -} - -static Phase *P; /* current phase */ -static int g_rc_mm_ok, g_rc_mm_chipfail, g_rc_at_ok, g_rc_at_unwritten, g_rc_bad; - -static float *g_x, *g_y; /* activation in / result out, sized for CHUNK x INTER and CHUNK x VOCAB-free */ -static float *g_logits; /* 1 x VOCAB */ -static float *g_k, *g_v; /* host KV for the attention call, 4096 x 1024 f32 each */ -static float g_q[QDIM], g_attn[QDIM]; - -static void mm(uint32_t m, const OmegaGpuTensor *w, float *out) { - uint32_t k, n; - omega_gpu_tensor_shape(w, &k, &n); - int a_before = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(m, g_x, w, out, &info); - int made = fk.alloc_calls - a_before; - P->mm_calls++; - if (rc == OMEGA_GPU_MATMUL_OK) g_rc_mm_ok++; - else if (rc == OMEGA_GPU_MATMUL_CHIP_FAIL) g_rc_mm_chipfail++; - else { g_rc_bad++; printf("unexpected matmul rc=%d (%s)\n", rc, omega_gpu_matmul_rc_name(rc)); } - int miss = info.kernel_cache_hit ? 0 : 1; /* at most one miss per launch; m <= 128 rows is one launch here */ - if (miss) { - P->mm_miss++; - if (seen(&info)) P->mm_remiss++; - } else { - (void)seen(&info); - } - P->mm_other_allocs += made - miss; -} - -static void attn(uint32_t seq) { - int a_before = fk.alloc_calls; - OmegaGpuAttnInfo info; - int rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, seq, QH, KVH, HD, g_attn, &info); - P->at_calls++; - P->at_allocs += fk.alloc_calls - a_before; - if (rc == OMEGA_GPU_ATTN_OK) g_rc_at_ok++; - else if (rc == OMEGA_GPU_ATTN_UNWRITTEN) g_rc_at_unwritten++; - else { g_rc_bad++; printf("unexpected attention rc=%d (%s)\n", rc, omega_gpu_attention_rc_name(rc)); } -} - -/* One transformer step over `rows` rows of a sequence that already holds `offset` tokens. */ -static void step(uint32_t rows, uint32_t offset) { - for (uint32_t l = 0; l < LAYERS; l++) { - mm(rows, W_Q, g_y); mm(rows, W_K, g_y); mm(rows, W_K, g_y); - for (uint32_t t = 0; t < rows; t++) attn(offset + t + 1); - mm(rows, W_O, g_y); mm(rows, W_G, g_y); mm(rows, W_G, g_y); mm(rows, W_D, g_y); - } - mm(1, W_LM, g_logits); -} - -static void begin(Phase *p, const char *name) { - memset(p, 0, sizeof *p); - p->name = name; - p->a0 = fk.alloc_size_n; - p->f0 = fk.free_size_n; - p->allocs = fk.alloc_calls; /* start values, turned into deltas by end() */ - p->frees = fk.free_calls; - P = p; -} - -static void sizes(const char *kind, const uint64_t *log, int from, int to) { - /* distinct sizes with counts, in order of first appearance, at most 6 shown */ - uint64_t seen_sz[256]; int cnt[256]; int ns = 0; - for (int i = from; i < to && i < FK_SIZE_LOG; i++) { - int j; - for (j = 0; j < ns; j++) if (seen_sz[j] == log[i]) break; - if (j == ns && ns < 256) { seen_sz[ns] = log[i]; cnt[ns] = 0; ns++; } - if (j < 256) cnt[j]++; - } - printf("MEASURE %s sizes (%d distinct):", kind, ns); - for (int j = 0; j < ns && j < 6; j++) printf(" %llux%d", (unsigned long long)seen_sz[j], cnt[j]); - if (ns > 6) printf(" ... last %llux%d", (unsigned long long)seen_sz[ns - 1], cnt[ns - 1]); - printf("\n"); -} - -static void end(Phase *p, int sized) { - int a1 = fk.alloc_size_n, f1 = fk.free_size_n; - p->allocs = fk.alloc_calls - p->allocs; - p->frees = fk.free_calls - p->frees; - for (int i = p->a0; i < a1 && i < FK_SIZE_LOG; i++) p->alloc_bytes += fk.alloc_size_log[i]; - for (int i = p->f0; i < f1 && i < FK_SIZE_LOG; i++) p->free_bytes += fk.free_size_log[i]; - printf("MEASURE phase %-22s allocs %4d frees %4d alloc_bytes %12llu matmul_calls %5d (code-cache misses %d, of which on a shape seen before %d, other scratch growth %d) attention_calls %5d (allocs %d)\n", - p->name, p->allocs, p->frees, (unsigned long long)p->alloc_bytes, p->mm_calls, p->mm_miss, p->mm_remiss, p->mm_other_allocs, - p->at_calls, p->at_allocs); - if (sized && p->allocs) { sizes("alloc", fk.alloc_size_log, p->a0, a1); sizes("free ", fk.free_size_log, p->f0, f1); } - CHECK(a1 <= FK_SIZE_LOG && f1 <= FK_SIZE_LOG, "size log overflow (%d allocs, %d frees)", a1, f1); -} - -static const OmegaGpuServingBounds QWEN3_4B_BOUNDS = { - .max_context = 4096, .max_seqs = 1, .num_q_heads = QH, .num_kv_heads = KVH, .head_dim = HD, .kv_block_size = 16, - .max_rows = CHUNK, .max_k = INTER, .max_n = INTER, .max_n_one_row = VOCAB, .kernel_slots = 32, -}; - -/* Bounds mode: a tiny reservation, then calls inside it (no driver traffic) and past it (refused loudly). */ -static int paged_call(uint32_t bs, uint32_t ctx); -static int attn_ran(int rc); - -static int bounds_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 256; b.max_rows = 32; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; - Phase ph; begin(&ph, "BOUNDS"); /* sets P for mm()/attn() */ - W_Q = upload(HID, QDIM); - attn(1); mm(1, W_Q, g_y); /* warm kernels at small size */ - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - mm(1, W_Q, g_y); mm(17, W_Q, g_y); mm(32, W_Q, g_y); attn(256); /* warm each shape once (reserving a deeper kernel cache restarts it empty) */ - const int a0 = fk.alloc_calls, f0 = fk.free_calls; - mm(1, W_Q, g_y); mm(17, W_Q, g_y); mm(32, W_Q, g_y); attn(1); attn(100); attn(256); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "calls inside the bounds touched the driver (%d allocs, %d frees)", fk.alloc_calls - a0, fk.free_calls - f0); - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(33, g_x, W_Q, g_y, &info); /* 33 rows -> 48 padded: past 32 */ - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE, "33 rows past a 32-row reservation: rc=%d (%s)", rc, omega_gpu_matmul_rc_name(rc)); - CHECK(strstr(omega_gpu_matmul_last_error(), "serving reservation exceeded") != NULL, "matmul error text: \"%s\"", omega_gpu_matmul_last_error()); - rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, 257, QH, KVH, HD, g_attn, NULL); - CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "context 257 past a 256 reservation: rc=%d (%s)", rc, omega_gpu_attention_rc_name(rc)); - CHECK(strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL, "attention error text: \"%s\"", omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "a refused call touched the driver (%d allocs, %d frees)", fk.alloc_calls - a0, fk.free_calls - f0); - CHECK(!omega_gpu_matmul_is_blocked() && !omega_gpu_session_is_blocked(), "a refusal latched the session"); - mm(32, W_Q, g_y); attn(256); /* still serves after a refusal */ - CHECK(fk.alloc_calls == a0, "serving after a refusal allocated"); - /* paged bf16 attention (the sovereign-core path): 512 tokens = 32 blocks of 16 = exactly the reserved bytes */ - /* build each paged kernel the checked calls use: the split count is part of the kernel (cut F/J, own_log2split), - * 16 tokens run split 0 and 512 tokens split 2, and the attention kernel cache is outside the reservation - * (omega_gpu_serving.h, "Not covered") */ - (void)paged_call(16, 16); (void)paged_call(16, 512); - const int p0 = fk.alloc_calls, pf0 = fk.free_calls; - rc = paged_call(16, 16); CHECK(attn_ran(rc), "paged 16 tokens in bounds: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - rc = paged_call(16, 512); CHECK(attn_ran(rc), "paged 512 tokens (exactly the bound) refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == p0 && fk.free_calls == pf0, "in-bounds paged calls touched the driver (%d allocs, %d frees)", fk.alloc_calls - p0, fk.free_calls - pf0); - rc = paged_call(16, 513); CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "paged 513 tokens (bound+1): rc=%d", rc); - CHECK(strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL, "paged error text: \"%s\"", omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == p0 && fk.free_calls == pf0, "a refused paged call touched the driver"); - omega_gpu_serving_release(); /* lifted: growth is allowed again */ - rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, 257, QH, KVH, HD, g_attn, NULL); - CHECK(rc == OMEGA_GPU_ATTN_OK || rc == OMEGA_GPU_ATTN_UNWRITTEN, "after release, context 257 rc=%d", rc); - CHECK(fk.alloc_calls > a0, "after release, growth did not allocate"); - printf("MEASURE bounds: refused calls made 0 driver allocations; 33 rows -> TOO_LARGE, ctx 257 -> TOO_LARGE; error \"%s\"\n", "serving reservation exceeded: ..."); - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("gpu_serving_alloc_count_test bounds: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* Paged bf16 attention call over `ctx` tokens of a one-layer pool of `bs`-token blocks (the path sovereign-core uses). */ -static int paged_call(uint32_t bs, uint32_t ctx) { - const uint32_t nb = (ctx + bs - 1) / bs; - OmegaGpuKvLayout ly; - ly.head_stride_bytes = (uint64_t)HD * 2; ly.token_stride_bytes = ly.head_stride_bytes * KVH; - ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes; - ly.block_stride_bytes = ly.layer_stride_bytes; ly.pool_bytes = ly.block_stride_bytes * nb; - ly.num_blocks = nb; ly.num_layers = 1; ly.block_size = bs; - uint8_t *pool = calloc(1, (size_t)ly.pool_bytes); - uint32_t *ids = calloc(nb, sizeof *ids); - CHECK(pool && ids, "paged host buffers"); - int rc = OMEGA_GPU_ATTN_BAD_ARGS; - if (pool && ids) { - for (uint32_t i = 0; i < nb; i++) ids[i] = i; - rc = omega_gpu_paged_attention_bf16(g_q, pool, &ly, ids, nb, ctx, 0, QH, KVH, HD, g_attn, NULL); - } - free(pool); free(ids); - return rc; -} -static int attn_ran(int rc) { return rc == OMEGA_GPU_ATTN_OK || rc == OMEGA_GPU_ATTN_UNWRITTEN; } - -/* Under half a block of context: the paged path stages a whole block, more than the f32 formula (review item 1). */ -static int bounds_block_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 16; b.kv_block_size = 64; b.max_rows = 16; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; - Phase ph; begin(&ph, "BOUNDS-BLOCK"); - W_Q = upload(HID, QDIM); - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - int rc = paged_call(64, 16); /* first paged call builds the kernel (one code buffer); no pre-reserve call, it would raise the pool high-water mark */ - CHECK(attn_ran(rc), "paged call of 16 tokens in one 64-token block refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - const int a0 = fk.alloc_calls, f0 = fk.free_calls; - rc = paged_call(64, 64); - CHECK(attn_ran(rc), "paged call of exactly one block (the byte bound) refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "in-bounds paged calls touched the driver"); - rc = paged_call(64, 65); - CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "two blocks past a one-block reservation: rc=%d", rc); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "refused paged call touched the driver"); - printf("MEASURE bounds-block: 16 and 64 tokens (one 64-token block) served with 0 driver traffic; 65 tokens -> TOO_LARGE\n"); - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("gpu_serving_alloc_count_test bounds-block: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* A reserve that fails part way must leave nothing flagged (review item 2). Sweep the failing driver request over every - * allocation the reserve makes (pool, q, out, table, activation, result), on a freshly opened device each time; the - * control (no injected failure) must leave the reservation active. */ -static int rollback_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 256; b.kv_block_size = 16; b.max_rows = 32; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; b.kernel_slots = 0; - Phase ph; begin(&ph, "ROLLBACK"); - int failed_reserves = 0; - /* n = 100 first: the un-injected control, before the probes of the failing runs raise the buffers' high-water marks */ - const int sweep[] = { 100, 1, 2, 3, 4, 5, 6 }; - for (unsigned si = 0; si < sizeof sweep / sizeof sweep[0]; si++) { - const int n = sweep[si]; - W_Q = upload(HID, QDIM); /* opens the session (its own allocations come first) */ - fk.alloc_mode = FK_ALLOC_FAIL; - fk.alloc_fail_nth = fk.alloc_calls + n; - int rc = omega_gpu_reserve_serving(&b); - fk.alloc_fail_nth = 0; - /* probes that need more than the reservation: refused only if something is still flagged */ - /* each probe is larger than every earlier one, so a buffer that is still flagged is refused even though the high-water mark carries over */ - int ra = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, si ? 300 + 500 * si : 257, QH, KVH, HD, g_attn, NULL); - int refused_attn = ra == OMEGA_GPU_ATTN_TOO_LARGE && strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL; - OmegaGpuMatmulInfo info; - int rm = omega_gpu_matmul_resident_f32(si ? 32 + 16 * si : 48, g_x, W_Q, g_y, &info); - int refused_mm = rm == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "serving reservation exceeded") != NULL; - if (rc != 0) { - failed_reserves++; - CHECK(!refused_attn && !refused_mm, "failed reserve (injected fail on its request %d, rc=%d) left a reservation flagged: attention %d matmul %d", n, rc, refused_attn, refused_mm); - } else { - CHECK(refused_attn && refused_mm, "control (request %d never failed, reserve ok): the reservation should be active, attention %d matmul %d", n, refused_attn, refused_mm); - } - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - } - CHECK(failed_reserves >= 6, "only %d of the sweep's reserves failed (expected the 6 buffer requests)", failed_reserves); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("MEASURE rollback: %d injected failures during reserve, none left anything flagged; the un-injected control stayed reserved\n", failed_reserves); - printf("gpu_serving_alloc_count_test rollback: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* mode: "plain" (default) = today's measurement, no reservation; "reserve" = reserve after warm-up and - * ASSERT zero driver traffic while serving; "reserve-skip" = the same asserts without the call (must FAIL: the red run); - * "bounds" = refusal behaviour. */ -/* ---- sweep: the sovereign-core daemon's bounds (sc#311, sc#277). Every row count 1..256 over every weight - * shape is a distinct (kp, np, grid_x) for some rows, because grid_x is baked into the kernel and depends on - * the row tiles. prepare = 1: prepare each (rows, shape) and seal, then serving must make no driver call and an - * unprepared shape is refused. prepare = 0 (control, kernel_slots 32 as before): the cache wraps and serving - * allocates, which this mode must report as a failure. */ -#define SWEEP_ROWS 256u -static int sweep_mode(int prepare) { - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); W_O = upload(QDIM, HID); - W_G = upload(HID, INTER); W_D = upload(INTER, HID); W_LM = upload(HID, VOCAB); - OmegaGpuTensor *odd = upload(HID, 512); /* a shape the server never prepares */ - OmegaGpuTensor *w[6] = {W_Q, W_K, W_O, W_G, W_D, W_LM}; - float *x = calloc((size_t)SWEEP_ROWS * INTER, sizeof *x), *y = calloc((size_t)SWEEP_ROWS * VOCAB, sizeof *y); - CHECK(x && y, "sweep buffers"); - if (g_fail) return 1; - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_rows = SWEEP_ROWS; b.max_n = VOCAB; b.max_n_one_row = VOCAB; b.kernel_slots = prepare ? 128 : 32; - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - int prepared = -1; /* code buffers the prepare pass made: one per distinct kernel */ - if (prepare) { - int a0 = fk.alloc_calls; - for (unsigned i = 0; i < 6; i++) { - uint32_t k, n; - omega_gpu_tensor_shape(w[i], &k, &n); - for (uint32_t m = 1; m <= SWEEP_ROWS; m++) { - int rc = omega_gpu_matmul_prepare(m, k, n); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=%u %ux%u rc=%d %s", m, k, n, rc, omega_gpu_matmul_last_error()); - } - } - prepared = fk.alloc_calls - a0; - printf("MEASURE sweep prepare: %d driver allocations (one code buffer per distinct kernel)\n", prepared); - omega_gpu_serving_seal(); - } - g_nseen = 0; - OmegaGpuAllocStats st0, st1; - omega_gpu_session_alloc_stats(&st0); - int a0 = fk.alloc_calls, too_large = 0, other = 0; - for (unsigned pass = 0; pass < 2; pass++) - for (uint32_t m = 1; m <= SWEEP_ROWS; m++) - for (unsigned i = 0; i < 6; i++) { - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(m, x, w[i], y, &info); - if (rc == OMEGA_GPU_MATMUL_TOO_LARGE) too_large++; - else if (rc != OMEGA_GPU_MATMUL_OK && rc != OMEGA_GPU_MATMUL_CHIP_FAIL) other++; /* CHIP_FAIL = fake kernel skips writes */ - if (rc != OMEGA_GPU_MATMUL_TOO_LARGE) (void)seen(&info); - } - int made = fk.alloc_calls - a0; - omega_gpu_session_alloc_stats(&st1); - CHECK((int)(st1.allocs - st0.allocs) == made, "session alloc stats %llu != driver %d", - (unsigned long long)(st1.allocs - st0.allocs), made); - printf("MEASURE sweep serving (rows 1..%u x 6 shapes, twice): %d driver allocations, %d distinct kernels, %d refused, %d other\n", - SWEEP_ROWS, made, g_nseen, too_large, other); - CHECK(made == 0, "serving made %d driver allocations", made); - CHECK(too_large == 0 && other == 0, "serving refused %d, other rc %d", too_large, other); - /* measured: 95 before the blocked prefill kernel (#407), 83 with it (keyed with rt, ct; lm_head stays - * on the single-tile kernel, its rt > 1 store offset does not fit the 24-bit immediate) */ - CHECK(g_nseen == 83, "distinct kernels %d, expected 83 for Qwen3-4B at CTA budget 256", g_nseen); - CHECK(prepared < 0 || prepared == g_nseen, "prepare built %d kernels, serving used %d distinct", prepared, g_nseen); - if (prepare) { - int a1 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(1, x, odd, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "not prepared"), - "unprepared shape rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a1, "unprepared shape asked the driver for memory"); - omega_gpu_serving_release(); - rc = omega_gpu_matmul_resident_f32(1, x, odd, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE, "release did not lift the seal: %s", omega_gpu_matmul_last_error()); - } - free(x); free(y); - printf("gpu_serving_alloc_count_test sweep%s: %s (%d failed checks)\n", prepare ? "" : "-skip", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* ---- pin: a full cache of prepared kernels is never evicted. 8 slots, 8 prepared kernels (W_Q at 16..144 rows: - * 9 row counts; since the blocked prefill kernel (#407) 64 and 128 rows share one kernel, rt 4 x ct 4 at grid_x 128), - * then an unprepared call BEFORE any seal must be refused with no driver call, and every prepared kernel must still hit. */ -static int pin_mode(void) { - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); - float *x = calloc((size_t)144 * HID, sizeof *x), *y = calloc((size_t)144 * QDIM, sizeof *y); - CHECK(x && y, "pin buffers"); - if (g_fail) return 1; - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_rows = 144; b.kernel_slots = 8; - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - const int ap = fk.alloc_calls; - for (uint32_t m = 16; m <= 144; m += 16) { - int rc = omega_gpu_matmul_prepare(m, HID, QDIM); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=%u rc=%d %s", m, rc, omega_gpu_matmul_last_error()); - } - CHECK(fk.alloc_calls - ap == 8, "premise: prepare built %d kernels, the cache holds 8", fk.alloc_calls - ap); - int a0 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(1, x, W_K, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "prepared kernel"), - "unprepared call with a full pinned cache: rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a0, "refused call asked the driver for memory"); - for (uint32_t m = 16; m <= 144; m += 16) { - rc = omega_gpu_matmul_resident_f32(m, x, W_Q, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE && info.kernel_cache_hit, "prepared m=%u evicted (rc=%d hit=%d)", m, rc, info.kernel_cache_hit); - } - CHECK(fk.alloc_calls == a0, "prepared kernels rebuilt: %d driver allocations", fk.alloc_calls - a0); - free(x); free(y); - printf("gpu_serving_alloc_count_test pin: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - - -/* Sealed without a serving reservation: the scratch buffers could still grow, so every matmul call - * must be refused by name before any driver allocation (review of omega#338). */ -static int seal_bare_mode(void) { - W_Q = upload(HID, QDIM); - float *x = calloc((size_t)144 * HID, sizeof *x), *y = calloc((size_t)144 * QDIM, sizeof *y); - CHECK(x && y, "seal-bare buffers"); - if (g_fail) return 1; - int rc = omega_gpu_matmul_prepare(16, HID, QDIM); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=16 rc=%d %s", rc, omega_gpu_matmul_last_error()); - omega_gpu_matmul_seal(1); - int a0 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - rc = omega_gpu_matmul_resident_f32(144, x, W_Q, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "without a scratch reservation"), - "sealed, unreserved, larger call: rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a0, "sealed call without a reservation asked the driver for memory (%d)", fk.alloc_calls - a0); - omega_gpu_matmul_seal(0); - rc = omega_gpu_matmul_resident_f32(16, x, W_Q, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE, "unsealed call still refused: rc=%d %s", rc, omega_gpu_matmul_last_error()); - free(x); free(y); - printf("gpu_serving_alloc_count_test seal-bare: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} -/* update: omega_gpu_tensor_update_* re-packs new values into the tensor's own device buffer. The fake's device - * memory is host memory with GPU address = CPU address (fk.alloc_va), so the buffer is compared word for word - * with omega_matmul_frag_pack_b of the new values. Two shapes: 72 x 1100 (k pads to 80; n is not a multiple of - * 8 and spans three 64-tile chunks) and 4096 x 200 (the f32 staging holds 8 tiles at this k: four chunks, the - * last ragged). Per shape: the upload's one driver allocation is the GPU-uncached one, update_f32, update_bf16 - * back, update while sealed, no driver allocation or free, shape-mismatch refusals write nothing. Then NULL - * refusals and stale handles (closed device, then a reopened one). */ -static int upd_same(const uint16_t *d, const uint16_t *want, size_t cnt, const char *what) { - size_t diff = 0; - for (size_t i = 0; i < cnt; i++) diff += d[i] != want[i]; - CHECK(diff == 0, "%s: %zu of %zu packed words differ from omega_matmul_frag_pack_b", what, diff, cnt); - return diff == 0; -} -static OmegaGpuTensor *update_shape(uint32_t K, uint32_t N, uint16_t **b1_out, float **b2_out) { - const uint32_t KP = (K + 15u) / 16u * 16u, NT = (N + 7u) / 8u; - const size_t cnt = (size_t)K * N, packed = (size_t)KP * NT * 8u; - uint16_t *b1 = malloc(cnt * sizeof *b1), *b2h = malloc(cnt * sizeof *b2h), *want = malloc(packed * sizeof *want); - float *b2 = malloc(cnt * sizeof *b2); - CHECK(b1 && b2 && b2h && want, "update buffers %ux%u", K, N); - if (!b1 || !b2 || !b2h || !want) return NULL; - uint32_t s = 0x5eedu ^ K ^ (N << 16); - for (size_t i = 0; i < cnt; i++) { - s = s * 1664525u + 1013904223u; - b1[i] = omega_fp32_to_bf16(((float)(s >> 8) / 16777216.0f) - 0.5f); - b2[i] = ((float)(s % 2000003u) / 1000001.0f) - 1.0f + 1e-7f * (float)(i % 7u); /* low bits that rounding must drop */ - } - /* edge values for the update path's rounding: NaNs with payloads and sign, infinities, zeros, subnormals, - * exact ties (odd and even), the largest finite value (rounds to infinity) */ - static const uint32_t EDGE[] = {0x7fc00001u, 0xff800001u, 0x7fbfffffu, 0x7f800000u, 0xff800000u, 0x00000000u, 0x80000000u, - 0x00000001u, 0x807fffffu, 0x00018000u, 0x3f808000u, 0x3f818000u, 0xbf808000u, 0x7f7fffffu, 0xff7fffffu}; - for (size_t e = 0; e < sizeof EDGE / sizeof EDGE[0]; e++) for (size_t r = 0; r < 3; r++) { - const size_t i = r * (K / 3u) * N + (e * 73u + r) % N; /* rows 0, k/3, 2k/3; columns across the chunks */ - memcpy(&b2[i], &EDGE[e], 4); - } - for (size_t i = 0; i < cnt; i++) b2h[i] = omega_fp32_to_bf16(b2[i]); - - OmegaGpuTensor *t = NULL; - const int a0 = fk.alloc_calls, u0 = fk.uncached_calls; - int rc = omega_gpu_tensor_upload_bf16(K, N, b1, &t); - CHECK(rc == OMEGA_GPU_MATMUL_OK && fk.alloc_calls == a0 + 1 && a0 < 16, "premise %ux%u: upload rc=%d made %d allocations (index %d)", K, N, rc, fk.alloc_calls - a0, a0); - CHECK(fk.uncached_calls == u0 + 1, "%ux%u: the tensor's driver allocation was not the GPU-uncached one", K, N); - if (rc != OMEGA_GPU_MATMUL_OK || fk.alloc_calls != a0 + 1 || a0 >= 16) return NULL; - const uint16_t *d = (const uint16_t *)(uintptr_t)fk.alloc_va[a0]; - omega_matmul_frag_pack_b(b1, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "premise: upload"); - - const int a1 = fk.alloc_calls, f1 = fk.free_calls; - CHECK(omega_gpu_tensor_update_f32(t, K + 1u, N, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 with k + 1 not refused"); - CHECK(omega_gpu_tensor_update_bf16(t, K, N - 1u, b1) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 with n - 1 not refused"); - CHECK(omega_gpu_tensor_update_f32(t, N, K, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 with k and n swapped not refused"); - upd_same(d, want, packed, "shape-mismatch refusals left the buffer"); - rc = omega_gpu_tensor_update_f32(t, K, N, b2); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_f32 %ux%u rc=%d %s", K, N, rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b2h, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_f32"); - rc = omega_gpu_tensor_update_bf16(t, K, N, b1); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_bf16 %ux%u rc=%d %s", K, N, rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b1, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_bf16 back"); - omega_gpu_matmul_seal(1); - rc = omega_gpu_tensor_update_f32(t, K, N, b2); - omega_gpu_matmul_seal(0); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update while sealed rc=%d %s", rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b2h, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_f32 while sealed"); - CHECK(fk.alloc_calls == a1 && fk.free_calls == f1, "updates touched the driver (%d allocs, %d frees)", fk.alloc_calls - a1, fk.free_calls - f1); - uint32_t k2 = 0, n2 = 0; - omega_gpu_tensor_shape(t, &k2, &n2); - CHECK(k2 == K && n2 == N, "shape changed by update: %ux%u", k2, n2); - free(b2h); free(want); - *b1_out = b1; *b2_out = b2; - return t; -} -static int update_mode(void) { - OmegaGpuTensor *warm = upload(16, 8); /* opens the session, so each next upload is exactly one driver allocation */ - uint16_t *b1 = NULL, *b1b = NULL; float *b2 = NULL, *b2b = NULL; - OmegaGpuTensor *t = update_shape(72, 1100, &b1, &b2); - OmegaGpuTensor *t2 = update_shape(4096, 200, &b1b, &b2b); - if (!t || !t2) return 1; - - CHECK(omega_gpu_tensor_update_f32(NULL, 72, 1100, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL tensor not refused"); - CHECK(omega_gpu_tensor_update_bf16(NULL, 72, 1100, b1) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL tensor not refused"); - CHECK(omega_gpu_tensor_update_f32(t, 72, 1100, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL values not refused"); - CHECK(omega_gpu_tensor_update_bf16(t, 72, 1100, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL values not refused"); - - /* a handle whose device was closed is stale: refused before anything is written (its memory is gone) */ - omega_gpu_device_close(); - const int a2 = fk.alloc_calls; - int rc = omega_gpu_tensor_update_f32(t, 72, 1100, b2); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_f32 of a stale handle rc=%d (want CHIP_FAIL)", rc); - rc = omega_gpu_tensor_update_bf16(t, 72, 1100, b1); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_bf16 of a stale handle rc=%d (want CHIP_FAIL)", rc); - CHECK(fk.alloc_calls == a2, "stale update asked the driver for memory"); - OmegaGpuTensor *reopen = upload(16, 8); /* a new device: the old handle stays stale */ - rc = omega_gpu_tensor_update_f32(t, 72, 1100, b2); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_f32 of a handle from a previous device rc=%d (want CHIP_FAIL)", rc); - omega_gpu_tensor_free(reopen); - omega_gpu_tensor_free(t); - omega_gpu_tensor_free(t2); - omega_gpu_tensor_free(warm); - omega_gpu_device_close(); - free(b1); free(b2); free(b1b); free(b2b); - printf("gpu_serving_alloc_count_test update: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -int main(int argc, char **argv) { - const char *mode = argc > 1 ? argv[1] : "plain"; - const int do_reserve = strcmp(mode, "reserve") == 0, assert_zero = do_reserve || strcmp(mode, "reserve-skip") == 0; - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.alloc_max = 1ull << 31; - omega_gpu_matmul_set_cta_budget(256); - - g_x = calloc((size_t)CHUNK * INTER, sizeof *g_x); - g_y = calloc((size_t)CHUNK * INTER, sizeof *g_y); - g_logits = calloc(VOCAB, sizeof *g_logits); - g_k = calloc((size_t)4096 * KVDIM, sizeof *g_k); - g_v = calloc((size_t)4096 * KVDIM, sizeof *g_v); - CHECK(g_x && g_y && g_logits && g_k && g_v, "host buffers"); - if (g_fail) return 1; - - Phase ph[9]; - int np = 0; - if (strcmp(mode, "bounds") == 0) return bounds_mode(); - if (strcmp(mode, "bounds-block") == 0) return bounds_block_mode(); - if (strcmp(mode, "rollback") == 0) return rollback_mode(); - if (strcmp(mode, "sweep") == 0) return sweep_mode(1); - if (strcmp(mode, "pin") == 0) return pin_mode(); - if (strcmp(mode, "seal-bare") == 0) return seal_bare_mode(); - if (strcmp(mode, "update") == 0) return update_mode(); - if (strcmp(mode, "sweep-skip") == 0) return sweep_mode(0); - - begin(&ph[np], "LOAD (session+6 weights)"); - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); W_O = upload(QDIM, HID); - W_G = upload(HID, INTER); W_D = upload(INTER, HID); W_LM = upload(HID, VOCAB); - end(&ph[np], 1); np++; - CHECK(omega_gpu_session_open_count() == 1, "session opened %u times", omega_gpu_session_open_count()); - - /* WARM-UP: one decode step at context 1. Everything after this phase is "serving". */ - begin(&ph[np], "WARMUP decode ctx=1"); - step(1, 0); - end(&ph[np], 1); np++; - if (assert_zero) { - /* a daemon's startup: reserve once after loading and a first request, then cover each row-count class - * (1 decode row, a full chunk, the 100 and 72 row remainders) so every matmul shape has been built once */ - if (do_reserve) CHECK(omega_gpu_reserve_serving(&QWEN3_4B_BOUNDS) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - begin(&ph[np], "WARMUP row classes"); - step(128, 0); step(100, 0); step(72, 0); step(1, 0); - end(&ph[np], 0); np++; - } - const int after_warm_allocs = fk.alloc_calls, after_warm_frees = fk.free_calls; - - uint32_t ctx = 0; - const uint32_t N1 = 100, D1 = 64, N2 = 200, D2 = 64; - - begin(&ph[np], "PREFILL-A 100 tokens"); - for (uint32_t off = 0; off < N1; off += CHUNK) { uint32_t r = N1 - off < CHUNK ? N1 - off : CHUNK; step(r, ctx + off); } - ctx += N1; - end(&ph[np], 1); np++; - - begin(&ph[np], "DECODE-A 64 tokens"); - for (uint32_t i = 0; i < D1; i++) { step(1, ctx); ctx++; } - end(&ph[np], 1); np++; - - begin(&ph[np], "PREFILL-B 200 tokens"); - for (uint32_t off = 0; off < N2; off += CHUNK) { uint32_t r = N2 - off < CHUNK ? N2 - off : CHUNK; step(r, ctx + off); } - ctx += N2; - end(&ph[np], 1); np++; - - begin(&ph[np], "DECODE-B 64 tokens"); - for (uint32_t i = 0; i < D2; i++) { step(1, ctx); ctx++; } - end(&ph[np], 1); np++; - - const int serve_allocs = fk.alloc_calls - after_warm_allocs, serve_frees = fk.free_calls - after_warm_frees; - printf("MEASURE AFTER WARM-UP: %d driver allocations, %d driver frees over %u tokens of context (final ctx %u)\n", - serve_allocs, serve_frees, ctx, ctx); - printf("MEASURE distinct matmul kernel shapes seen (kp,np,grid_x): %d (cache slots: %d)\n", g_nseen, do_reserve ? 32 : 8); - printf("MEASURE live driver buffers at end: %d ; session opens: %u ; launches reaching the fake: %d\n", - fk.live, omega_gpu_session_open_count(), fk.kernel_ran); - printf("MEASURE return codes: matmul ok %d, matmul poison-check CHIP_FAIL %d, attention ok %d, attention UNWRITTEN %d, other %d\n", - g_rc_mm_ok, g_rc_mm_chipfail, g_rc_at_ok, g_rc_at_unwritten, g_rc_bad); - - /* ---- what is true today and stays true ---- */ - CHECK(g_rc_bad == 0, "%d calls returned a code other than the expected poison-check ones", g_rc_bad); - CHECK(!omega_gpu_matmul_is_blocked() && !omega_gpu_session_is_blocked(), "session latched"); - CHECK(fk.double_free == 0, "double free %d", fk.double_free); - CHECK(fk.pb_parse_error == 0, "pushbuffer parse error"); - int calls_made = 0; - for (int i = 1; i < np; i++) calls_made += ph[i].mm_calls + ph[i].at_calls; - CHECK(fk.kernel_ran == calls_made, "launches %d != calls made %d", fk.kernel_ran, calls_made); - if (assert_zero) { - /* the point of the reservation: nothing reached the driver while serving inside the bounds */ - CHECK(serve_allocs == 0 && serve_frees == 0, "serving made %d driver allocations and %d frees after warm-up; the reservation promises none", serve_allocs, serve_frees); - for (int i = np - 4; i < np; i++) CHECK(ph[i].allocs == 0 && ph[i].frees == 0, "phase %s: %d allocs, %d frees", ph[i].name, ph[i].allocs, ph[i].frees); - } - CHECK(fk.live < FK_LIVE_MAX, "fake live table full (%d)", fk.live); - /* every real allocation is either live or was freed */ - CHECK(fk.alloc_calls - fk.free_calls >= fk.live, "alloc/free/live inconsistent: %d - %d < %d", fk.alloc_calls, fk.free_calls, fk.live); - - /* teardown: tensors first, then the device (the on-close hooks free the API scratch) */ - omega_gpu_tensor_free(W_Q); omega_gpu_tensor_free(W_K); omega_gpu_tensor_free(W_O); - omega_gpu_tensor_free(W_G); omega_gpu_tensor_free(W_D); omega_gpu_tensor_free(W_LM); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d driver buffers live at close", fk.live_at_close); - printf("MEASURE leaked at close: %d\n", fk.live_at_close); - - printf("gpu_serving_alloc_count_test %s: %s (%d failed checks)\n", mode, g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} diff --git a/tests/gpu_session_probe.c b/tests/gpu_session_probe.c deleted file mode 100644 index dee34588b..000000000 --- a/tests/gpu_session_probe.c +++ /dev/null @@ -1,56 +0,0 @@ -/* gpu_session_probe: FB-1 cut 4b flake investigation (first-call device-open failure). - * - * One fresh process = one sample: open the shared device through the API's own - * path (omega_gpu_ex2_f32 on 128 values is the smallest launch there is), report - * the stage that failed (with the driver's own text) or the open time, exit 0/1. - * - * ./gpu_session_probe [--label L] [--calls N] [--hold-ms M] - * --calls N launches after the first (default 1); keeps the device busy for an overlap test - * --hold-ms M sleep M ms with the device open before exit (overlap window for a second probe) - * - * Output (one line, Astra's SNAP shape; every unknown says so): - * PROBE label=L pid=P rc=OK|CHIP_FAIL|... stage="..." first_call_ms=F open_ms=O calls_ok=K/N opens=1 - * Never run outside the heavy queue (tools/probe_gpu_open.sh). - */ -#include "omega_gpu_elementwise_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include - -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } - -int main(int argc, char **argv) { - const char *label = "probe"; int calls = 1, hold_ms = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--label") == 0 && i + 1 < argc) label = argv[++i]; - else if (strcmp(argv[i], "--calls") == 0 && i + 1 < argc) calls = atoi(argv[++i]); - else if (strcmp(argv[i], "--hold-ms") == 0 && i + 1 < argc) hold_ms = atoi(argv[++i]); - else { fprintf(stderr, "unknown flag %s\n", argv[i]); return 2; } - } - float x[128], y[128]; - for (int i = 0; i < 128; i++) { x[i] = (float)i / 16.0f - 4.0f; y[i] = 0.0f; } - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - double t0 = now_ms(); - int rc = omega_gpu_ex2_f32(128, x, y, &info); - double first_ms = now_ms() - t0; - int ok = 0; - if (rc == OMEGA_GPU_EW_OK) { - /* negative control on the result itself: 2^0 must be 1 (x[64] = 0) */ - if (y[64] < 0.999f || y[64] > 1.001f) { rc = OMEGA_GPU_EW_UNWRITTEN; omega_gpu_session_set_error("probe: 2^0 != 1"); } - else ok = 1; - } - int more_ok = 0; - for (int i = 1; i < calls && ok; i++) if (omega_gpu_ex2_f32(128, x, y, &info) == OMEGA_GPU_EW_OK) more_ok++; - if (hold_ms > 0) usleep((useconds_t)hold_ms * 1000u); - const char *stage = omega_gpu_elementwise_last_error(); - printf("PROBE label=%s pid=%d rc=%s stage=\"%s\" first_call_ms=%.1f chip_us=%.1f calls_ok=%d/%d opens=%u%s\n", - label, (int)getpid(), omega_gpu_elementwise_rc_name(rc), stage[0] ? stage : "-", first_ms, - info.elapsed_ns / 1e3, ok + more_ok, calls, omega_gpu_session_open_count(), - rc == OMEGA_GPU_EW_OK && !stage[0] ? "" : (rc == OMEGA_GPU_EW_OK ? " note=stage_text_from_earlier_failure" : "")); - fflush(stdout); - omega_gpu_session_close(); /* the explicit close is part of what the next process sees */ - return ok ? 0 : 1; -} diff --git a/tests/gpu_tc_peak_test.c b/tests/gpu_tc_peak_test.c deleted file mode 100644 index b19b8ef98..000000000 --- a/tests/gpu_tc_peak_test.c +++ /dev/null @@ -1,99 +0,0 @@ -/* gpu_tc_peak_test.c (OWN-30B T3, 2026-10-13): tensor-core throughput ceiling on GB10 (HMMA.16816.F32.BF16). - * --host-only the generator in the warp simulator: every accumulator 16 * iters - * (default) the chip (caller holds flock /tmp/aien-gb10.lock): a sweep of issue stall x accumulator chains x warps x CTAs; - * each point checks every stored value (16 * iters) and reports TFLOPS = 4096 flop per HMMA / chip time - * (median of 5). Halving the chains must roughly halve the time when the tensor pipe is the limit. - * Verdict line last: "GPU_TC_PEAK: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int host_only(void) { - static BlackwellIRProgram p; int fail = 0; - for (uint32_t chains = 8; chains <= 16; chains += 8) { - if (omega_blackwell_codegen_tc_peak_prog(5, chains, 2, 64, &p) != 0) { printf("codegen refused chains %u\n", chains); return 1; } - static float out[2 * 64 * 64]; for (size_t i = 0; i < sizeof out / 4; i++) out[i] = -1; - static WsSim s; memset(&s, 0, sizeof s); s.p = &p; s.threads = 64; - uint64_t va = (uintptr_t)out; s.cbank[0x380 / 4] = (uint32_t)va; s.cbank[0x384 / 4] = (uint32_t)(va >> 32); - s.ranges[0].lo = va; s.ranges[0].hi = va + 2u * 64u * 16u * chains; s.nranges = 1; - int err = ws_run(&s, 2, 1); size_t bad = 0; - for (size_t i = 0; i < 2u * 64u * 4u * chains; i++) if (out[i] != 80.0f) bad++; - printf("sim chains %u: %s, peak %u registers, %zu instructions, %zu wrong\n", chains, err ? s.msg : "ran", p.regalloc.peak_gpr_usage, p.count, bad); - if (err || bad) fail++; - } - return fail; -} - -int main(int argc, char **argv) { - int fail = host_only(); - if (argc > 1 && !strcmp(argv[1], "--host-only")) { printf("GPU_TC_PEAK: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - if (fail) { printf("GPU_TC_PEAK: FAIL\n"); return 1; } - static const struct { uint32_t stall, chains, threads, ctas; } pts[] = { - { 8, 16, 128, 192 }, { 4, 16, 128, 192 }, { 2, 16, 128, 192 }, { 2, 8, 128, 192 }, - { 2, 16, 256, 192 }, { 2, 16, 128, 384 }, { 2, 16, 512, 96 }, { 4, 8, 256, 384 }, { 1, 16, 256, 384 }, - }; - const uint32_t iters = 4096; - omega_gpu_session_lock(); - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return 1; } - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, out = { 0 }; OmegaBlackwellKernel k; - if (omega_blackwell_codegen_tc_peak_prog(iters, pts[i].chains, pts[i].stall, pts[i].threads, &p) != 0) { printf("codegen refused\n"); fail++; continue; } - size_t need = omega_bw_program_code_bytes(&p), ob = (size_t)pts[i].ctas * pts[i].threads * 16u * pts[i].chains; - uint32_t decl = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage); - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(&p, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0 || - omega_gpu_session_alloc(ob, &out) != 0) { printf("upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint64_t ns[5]; int ok = 1; size_t bad = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; /* omega_gpu_session_launch adds the elapsed time */ - float *o = out.cpu; for (size_t q = 0; q < ob / 4; q++) o[q] = -1.0f; - uint32_t args[2] = { (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl, .threads_x = pts[i].threads, .threads_y = 1, .grid_x = pts[i].ctas, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 2, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < ob / 4; q++) if (o[q] != 16.0f * iters) bad++; - } - if (!ok) { fail++; omega_gpu_session_free(&code); omega_gpu_session_free(&out); break; } - qsort(ns, 5, 8, cmp_u64); - double hm = (double)pts[i].ctas * (pts[i].threads / 32u) * iters * pts[i].chains; - printf("peak stall %u chains %u threads %u ctas %u (declared %u): median %.1f us, %.2f TFLOPS, %zu wrong values\n", pts[i].stall, pts[i].chains, pts[i].threads, pts[i].ctas, decl, - ns[2] / 1e3, hm * 4096.0 / ns[2] / 1e3, bad); - if (bad) fail++; - omega_gpu_session_free(&code); omega_gpu_session_free(&out); - } - /* read bandwidth: every CTA distinct vs every CTA the same bytes (any cache reuse of these GPU-uncached buffers) */ - for (int mode = 0; mode < 4 && !fail; mode++) { - const uint32_t T = 256, grid = 384, iters = mode < 2 ? 32u : 8u, groups = (mode & 1) ? 1u : grid; - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, src = { 0 }, out = { 0 }; OmegaBlackwellKernel k; - if (omega_blackwell_codegen_tc_bw_prog(iters, groups, T, &p) != 0) { printf("bw codegen refused\n"); fail++; break; } - size_t need = omega_bw_program_code_bytes(&p), region = (size_t)iters * T * 128u, sb = region * groups, ob = (size_t)grid * T * 4u; - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(&p, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0 || - omega_gpu_session_alloc(sb, &src) != 0 || omega_gpu_session_alloc(ob, &out) != 0) { printf("bw upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint32_t *sw = src.cpu; for (size_t q = 0; q < sb / 4; q++) sw[q] = (uint32_t)(q * 2654435761u); - uint32_t *want = calloc((size_t)grid * T, 4); - for (uint32_t c = 0; c < grid; c++) for (uint32_t t = 0; t < T; t++) { uint32_t a = 0; const uint32_t *r = sw + (size_t)(groups == 1 ? 0 : c) * region / 4; - for (uint32_t it = 0; it < iters; it++) for (uint32_t q = 0; q < 8; q++) for (uint32_t s = 0; s < 4; s++) a ^= r[((size_t)it * T * 128u + (size_t)q * T * 16u + t * 16u) / 4 + s]; - want[(size_t)c * T + t] = a; } - uint64_t ns[5]; size_t bad = 0; int ok = 1; - if (omega_gpu_session_sync_to_gpu(&src) != 0) ok = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; uint32_t *o = out.cpu; memset(o, 0xee, ob); - uint32_t args[4] = { (uint32_t)src.va, (uint32_t)(src.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage), .threads_x = T, .threads_y = 1, .grid_x = grid, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 4, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("bw launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < (size_t)grid * T; q++) if (o[q] != want[q]) bad++; - } - if (ok) { qsort(ns, 5, 8, cmp_u64); double bytes = (double)grid * region; - printf("bw %s, %zu KB per CTA, %u CTAs: median %.1f us, %.1f GB/s delivered (%zu MB distinct), %zu wrong\n", groups == 1 ? "SAME bytes for every CTA" : "distinct bytes per CTA", region >> 10, grid, ns[2] / 1e3, bytes / ns[2], sb >> 20, bad); - if (bad) fail++; } else fail++; - free(want); omega_gpu_session_free(&code); omega_gpu_session_free(&src); omega_gpu_session_free(&out); - } - omega_gpu_session_unlock(); - printf("GPU_TC_PEAK: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_tc_probe_test.c b/tests/gpu_tc_probe_test.c deleted file mode 100644 index 945d57e1d..000000000 --- a/tests/gpu_tc_probe_test.c +++ /dev/null @@ -1,200 +0,0 @@ -/* gpu_tc_probe_test.c (OWN-30B T3, 2026-10-13): characterise the chip's HMMA.16816.F32.BF16 arithmetic. - * --host-only model self-checks (the model family reproduces exact sums on exactly representable cases) - * (default) chip: CASES single-HMMA cases (one warp each) with operand classes chosen to separate the models - * (wide exponent spread, cancellation, accumulator dominance, bf16 subnormals); prints, per model of - * tests/bw_hmma_model.h, how many of the 128 * CASES outputs match the chip bit for bit; negative control: - * mutant 1 (C dropped) must differ on the cases with C != 0. - * Env TC_PROBE_SEED: a different random data set (confirmation runs). Verdict line: "TC_PROBE: model=... exact N/N" when one model matches every output, else "TC_PROBE: NO EXACT MODEL". - * Chip runs only under flock /tmp/aien-gb10.lock. */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "bw_hmma_model.h" -#include -#include -#include - -#define CASES 2048u - -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static uint16_t bf16_of(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)(u >> 16); } /* truncation: the value is then exactly a bf16 */ -static float f_of_bf16(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; memcpy(&f, &u, 4); return f; } -/* a random bf16 with exponent in [lo, hi] */ -static float rbf(int lo, int hi) { - float m = 1.0f + (float)(rnd() & 127) / 128.0f; - int e = lo + (int)(rnd() % (uint32_t)(hi - lo + 1)); - float v = ldexpf(m, e); - if (rnd() & 1) v = -v; - return f_of_bf16(bf16_of(v)); -} - -typedef struct { float A[16][16], B[16][8], C[16][8]; } Case; - -static void gen_case(Case *c, unsigned idx) { - unsigned cls = idx % 6; - for (int r = 0; r < 16; r++) for (int k = 0; k < 16; k++) { - float v; - switch (cls) { - case 0: v = rbf(-2, 2); break; /* narrow range */ - case 1: v = rbf(-20, 20); break; /* wide spread: alignment truncation shows */ - case 2: v = (k & 1) ? rbf(-1, 1) : rbf(-12, 0); break; - case 3: v = rbf(-4, 4); break; /* with a big accumulator (below) */ - case 4: v = rbf(-130, -126); break; /* bf16 near / below the normal limit (subnormal products) */ - default: v = rbf(-8, 8); break; - } - if (cls == 4 && (rnd() & 3) == 0) { uint16_t h = (uint16_t)((rnd() & 0x7f) | (rnd() & 0x8000)); v = f_of_bf16(h); } /* bf16 subnormal */ - c->A[r][k] = v; - } - for (int k = 0; k < 16; k++) for (int n = 0; n < 8; n++) c->B[k][n] = cls == 4 ? rbf(-2, 2) : rbf(cls == 1 ? -20 : -3, cls == 1 ? 20 : 3); - for (int r = 0; r < 16; r++) for (int n = 0; n < 8; n++) { - float v = idx % 7 == 6 ? 0.0f : rbf(-6, 6); - if (cls == 3) v = rbf(10, 14); - if (cls == 2 && (rnd() & 1)) { /* cancellation: C = -(exact sum rounded) */ - double s = 0; for (int k = 0; k < 16; k++) s += (double)c->A[r][k] * c->B[k][n]; - v = (float)-s; - } - c->C[r][n] = v; - } -} -static uint32_t pack2(float lo, float hi) { return (uint32_t)bf16_of(lo) | ((uint32_t)bf16_of(hi) << 16); } -static void to_frag(const Case *c, uint32_t *in) { - uint32_t *A = in, *B = in + 128; float *C = (float *)(in + 192); - for (int L = 0; L < 32; L++) { - int g = L / 4, t = L % 4; - A[L * 4 + 0] = pack2(c->A[g][2 * t], c->A[g][2 * t + 1]); - A[L * 4 + 1] = pack2(c->A[g + 8][2 * t], c->A[g + 8][2 * t + 1]); - A[L * 4 + 2] = pack2(c->A[g][2 * t + 8], c->A[g][2 * t + 9]); - A[L * 4 + 3] = pack2(c->A[g + 8][2 * t + 8], c->A[g + 8][2 * t + 9]); - B[L * 2 + 0] = pack2(c->B[2 * t][g], c->B[2 * t + 1][g]); - B[L * 2 + 1] = pack2(c->B[2 * t + 8][g], c->B[2 * t + 9][g]); - C[L * 4 + 0] = c->C[g][2 * t]; C[L * 4 + 1] = c->C[g][2 * t + 1]; - C[L * 4 + 2] = c->C[g + 8][2 * t]; C[L * 4 + 3] = c->C[g + 8][2 * t + 1]; - } -} -/* output word (lane L, q) -> (row, col) */ -static void out_rc(int L, int q, int *r, int *n) { int g = L / 4, t = L % 4; *r = g + (q >= 2 ? 8 : 0); *n = 2 * t + (q & 1); } - -static float model_out(const HmmaModel *m, const Case *c, int r, int n) { - float a[16], b[16]; for (int k = 0; k < 16; k++) { a[k] = c->A[r][k]; b[k] = c->B[k][n]; } - return hm_dot16(m, a, b, c->C[r][n]); -} - -static int host_only(void) { - int fail = 0; - /* exactly representable sums must come out exact in every model */ - for (int i = 0; i < 1000; i++) { - float a[16], b[16]; for (int k = 0; k < 16; k++) { a[k] = (float)((int)(rnd() % 17) - 8); b[k] = (float)((int)(rnd() % 9) - 4); } - float c = (float)((int)(rnd() % 33) - 16); double ex = c; for (int k = 0; k < 16; k++) ex += (double)a[k] * b[k]; - int groups[] = { 0, 1, 2, 4, 8, 16 }; - for (int gi = 0; gi < 6; gi++) for (int rn = 0; rn < 2; rn++) { HmmaModel m = { groups[gi], 0, rn, 0, 0 }; if (hm_dot16(&m, a, b, c) != (float)ex) fail++; } - } - /* truncation is visible: 1 + 2^-30 (one product) in G=16, extra 0 truncates to 1, extra 6 keeps it only in double, RZ -> 1 */ - { float a[16] = { 1.0f, ldexpf(1.0f, -30) }, b[16] = { 1.0f, 1.0f }; HmmaModel m = { 16, 0, 0, 0, 0 }; if (hm_dot16(&m, a, b, 0.0f) != 1.0f) fail++; } - /* the probe's case generator produces bf16 values and its fragment packing round-trips */ - { static Case c; gen_case(&c, 7); uint32_t in[320]; to_frag(&c, in); if ((in[0] & 0xffff) != bf16_of(c.A[0][0])) fail++; } - printf("host-only model self-checks: %s (%d failures)\n", fail ? "FAIL" : "PASS", fail); - return fail ? 1 : 0; -} - -static int run_chip(int mutant, uint32_t *out_words, const uint32_t *in_words) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog || omega_blackwell_codegen_tc_probe_prog(mutant, prog) != 0) { printf("codegen failed\n"); free(prog); return -1; } - int rc = -1; - omega_gpu_session_lock(); - OmegaGpuMem code = {0}, in = {0}, out = {0}; - size_t need = omega_bw_program_code_bytes(prog); - OmegaBlackwellKernel k; - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(prog, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0) { printf("code upload failed\n"); goto done; } - if (omega_gpu_session_alloc((size_t)CASES * OMEGA_TC_PROBE_IN_BYTES, &in) != 0 || omega_gpu_session_alloc((size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, &out) != 0) { printf("alloc failed\n"); goto done; } - memcpy(in.cpu, in_words, (size_t)CASES * OMEGA_TC_PROBE_IN_BYTES); - { float *o = out.cpu; for (size_t i = 0; i < (size_t)CASES * 128u; i++) o[i] = -999.0f; } - if (omega_gpu_session_sync_to_gpu(&in) != 0 || omega_gpu_session_sync_to_gpu(&out) != 0) goto done; - { - uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - uint32_t peak = prog->regalloc.peak_gpr_usage, decl = omega_bw_gpr_declared(peak); - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl < 64 ? 64 : decl, .threads_x = 32, .threads_y = 1, .grid_x = CASES, .grid_y = 1, - .num_elements = (size_t)CASES * 128u, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_sync_to_cpu(&out) != 0) goto done; - printf("chip launch mutant %d: peak %u declared %u, %llu ns\n", mutant, peak, L.gpr_count, (unsigned long long)ns); - } - memcpy(out_words, out.cpu, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES); - rc = 0; -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(prog); - return rc; -} - -int main(int argc, char **argv) { - if (argc > 2 && strcmp(argv[1], "--dump") == 0) { /* raw code words for nvdisasm -b SM121 (offline check only) */ - static BlackwellIRProgram p; static uint8_t buf[OMEGA_BW_CODE_CAP_MAX]; size_t len = 0; - if (omega_blackwell_codegen_tc_probe_prog(argc > 3 ? atoi(argv[3]) : 0, &p) != 0 || omega_bw_encode_program(&p, buf, sizeof buf, &len) != 0) return 1; - FILE *f = fopen(argv[2], "wb"); if (!f) return 1; fwrite(buf, 1, len, f); fclose(f); printf("peak %u, %zu bytes\n", p.regalloc.peak_gpr_usage, len); return 0; - } - int host = argc > 1 && strcmp(argv[1], "--host-only") == 0; - if (getenv("TC_PROBE_SEED")) rng = strtoull(getenv("TC_PROBE_SEED"), NULL, 0) | 1u; /* fresh data for a confirmation run */ - if (host_only() != 0) return 1; - if (host) return 0; - static Case cases[CASES]; - uint32_t *in = calloc((size_t)CASES, OMEGA_TC_PROBE_IN_BYTES), *out = calloc((size_t)CASES, OMEGA_TC_PROBE_OUT_BYTES), *outm = calloc((size_t)CASES, OMEGA_TC_PROBE_OUT_BYTES); - for (unsigned i = 0; i < CASES; i++) { gen_case(&cases[i], i); to_frag(&cases[i], in + (size_t)i * (OMEGA_TC_PROBE_IN_BYTES / 4)); } - const char *replay = argc > 2 && strcmp(argv[1], "--replay") == 0 ? argv[2] : NULL, *save = argc > 2 && strcmp(argv[1], "--save") == 0 ? argv[2] : NULL; - if (replay) { /* model search over saved chip words (offline; the words came from a sealed chip run) */ - FILE *rf = fopen(replay, "rb"); if (!rf) return 1; - size_t got = fread(out, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, rf) + fread(outm, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, rf); fclose(rf); - if (got != 2u * CASES * OMEGA_TC_PROBE_OUT_BYTES) { printf("short replay file\n"); return 1; } - printf("replaying chip words from %s\n", replay); - } else { - if (run_chip(0, out, in) != 0) { printf("TC_PROBE: FAIL chip\n"); return 1; } - if (run_chip(1, outm, in) != 0) { printf("TC_PROBE: FAIL chip (mutant)\n"); return 1; } - if (save) { FILE *sf = fopen(save, "wb"); if (sf) { fwrite(out, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, sf); fwrite(outm, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, sf); fclose(sf); } } - } - /* poison and plausibility: relative error vs the exact double sum */ - size_t poison = 0, far = 0, total = (size_t)CASES * 128u; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - float v; memcpy(&v, &out[(size_t)i * 128 + L * 4 + q], 4); - if (v == -999.0f) poison++; - int r, n; out_rc(L, q, &r, &n); - double ex = cases[i].C[r][n], mag = fabs(ex); for (int k = 0; k < 16; k++) { double p = (double)cases[i].A[r][k] * cases[i].B[k][n]; ex += p; mag += fabs(p); } - if (fabs(v - ex) > 1e-5 * mag + 1e-37) far++; - } - printf("plausibility: %zu poison, %zu of %zu outputs farther than 1e-5 of the term magnitude from the exact sum\n", poison, far, total); - /* negative control: mutant 1 drops C; it must differ wherever C is nonzero and large enough to matter */ - size_t mdiff = 0, mcand = 0; - /* counted only where C is clearly significant: |C| >= 2^-8 |D| */ - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); float dv; memcpy(&dv, &out[(size_t)i * 128 + L * 4 + q], 4); - if (fabsf(cases[i].C[r][n]) < ldexpf(fabsf(dv), -8) || cases[i].C[r][n] == 0.0f) continue; - mcand++; if (out[(size_t)i * 128 + L * 4 + q] != outm[(size_t)i * 128 + L * 4 + q]) mdiff++; - } - printf("negative control (C dropped): %zu of %zu outputs with significant C differ (%s)\n", mdiff, mcand, mcand && mdiff == mcand ? "caught" : "NOT CAUGHT"); - /* model search */ - int groups[] = { 0, 1, 2, 4, 8, 16 }, best_i = -1; size_t best = 0; HmmaModel bestm = { 0, 0, 0, 0, 0 }; - static const char *clsname[6] = { "narrow", "wide", "mixed+cancel", "bigC", "subnormal", "medium" }; - for (int gi = 0; gi < 6; gi++) for (int ex = -1; ex <= 8; ex++) for (int rn = 0; rn < 2; rn++) for (int nom = 0; nom < 3; nom++) for (int cs = 0; cs < 2; cs++) { - if (groups[gi] == 0 && (ex || rn || nom || cs)) continue; - HmmaModel m = { groups[gi], ex, rn, nom, cs }; - size_t match = 0, cls_miss[6] = {0}; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); - float mv = model_out(&m, &cases[i], r, n); uint32_t mu; memcpy(&mu, &mv, 4); - if (mu == out[(size_t)i * 128 + L * 4 + q]) match++; else cls_miss[i % 6]++; - } - if (match * 100 >= total * 90 || match == total) - printf("model group %2d extra %d %s nominal %d csep %d: %zu of %zu match (misses by class: %s %zu, %s %zu, %s %zu, %s %zu, %s %zu, %s %zu)\n", m.group, m.extra, m.rn ? "RN" : "RZ", m.nominal, m.csep, match, total, - clsname[0], cls_miss[0], clsname[1], cls_miss[1], clsname[2], cls_miss[2], clsname[3], cls_miss[3], clsname[4], cls_miss[4], clsname[5], cls_miss[5]); - if (match > best) { best = match; bestm = m; best_i = 1; } - } - if (best_i > 0) printf("best model: group %d extra %d %s: %zu of %zu\n", bestm.group, bestm.extra, bestm.rn ? "RN" : "RZ", best, total); - int ok = poison == 0 && far == 0 && mcand && mdiff == mcand; - if (ok && best == total) printf("TC_PROBE: model=group %d extra %d %s nominal %d csep %d exact %zu/%zu\n", bestm.group, bestm.extra, bestm.rn ? "RN" : "RZ", bestm.nominal, bestm.csep, best, total); - else printf("TC_PROBE: NO EXACT MODEL (best %zu/%zu)%s\n", best, total, ok ? "" : " and plausibility/control FAILED"); - free(in); free(out); free(outm); - return ok ? 0 : 1; -} diff --git a/tests/gpu_tcgemm_test.c b/tests/gpu_tcgemm_test.c deleted file mode 100644 index aaddd094d..000000000 --- a/tests/gpu_tcgemm_test.c +++ /dev/null @@ -1,323 +0,0 @@ -/* gpu_tcgemm_test.c (OWN-30B T3, 2026-10-13): tensor-core grouped FP8 GEMM (omega_blackwell_codegen_tc.h). - * --host-only program statistics and register budgets for the production shapes; the C emulation (exact HMMA model, - * tests/bw_hmma_model.h) against a double oracle; permutation and decode checks - * --sim the generated kernel in the warp simulator (both fragment orders) bit-identical to the C emulation; - * mutants 1-4 caught (a simulator error counts as a FAIL, never as caught) - * --chip (under flock /tmp/aien-gb10.lock) through omega_gpu_tcgemm_api: bit-identity to the emulation, second call - * identical, mutants caught on the chip, timing medians (TFLOPS, GB/s) at large M - * Verdict line last: "GPU_TCGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_tcgemm_api.h" -#include -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include -#include - -static const HmmaModel GB10 = { 16, 2, 0, 2, 0 }; -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float frnd(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } - -/* a problem: E experts of n x k e4m3, M sorted rows (expert ids non-decreasing), X source rows */ -typedef struct { - uint32_t E, n, k, M, xr; - uint8_t *w; /* E * n * k */ - uint16_t *sbf; /* E * (n/128) * (k/128) bf16 scale_inv */ - float *sf; /* folded f32 * 2^56 */ - float *x; /* xr * k */ - uint16_t *xp; /* xr * k stored (permuted bf16 * 2^64) */ - uint32_t *eid, *src; /* M */ -} Prob; - -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static uint16_t bf16_trunc(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)(u >> 16); } - -static void prob_make(Prob *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, int skewed) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = xr; - size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * (k / 128); - p->w = malloc(wn); p->sbf = malloc(sn * 2); p->sf = malloc(sn * 4); p->x = malloc((size_t)xr * k * 4); p->xp = malloc((size_t)xr * k * 2); - p->eid = malloc(M * 4); p->src = malloc(M * 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) p->sbf[i] = bf16_trunc(ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4)); - if (omega_fp8_pack_scales(p->sbf, sn, p->sf, 0) != 0) { printf("scale pack failed\n"); exit(2); } - for (size_t i = 0; i < (size_t)xr * k; i++) p->x[i] = frnd() * (rnd() % 16 == 0 ? 8.0f : 1.0f); - for (uint32_t r = 0; r < xr; r++) omega_tcgemm_permute_x(p->x + (size_t)r * k, k, p->xp + (size_t)r * k); - /* expert ids: sorted; skewed puts many rows on a few experts (multi-tile segments) */ - for (uint32_t i = 0; i < M; i++) { uint32_t e = skewed ? (uint32_t)((uint64_t)i * i / ((uint64_t)M * M / E + 1)) : (uint32_t)((uint64_t)i * E / M); if (e >= E) e = E - 1; p->eid[i] = e; p->src[i] = rnd() % xr; } -} -static void prob_free(Prob *p) { free(p->w); free(p->sbf); free(p->sf); free(p->x); free(p->xp); free(p->eid); free(p->src); } - -/* stored index of element p in a permuted row: group (0,2,1,3) */ -static uint32_t stored_ix(uint32_t p) { static const uint32_t inv[4] = { 0, 2, 1, 3 }; return (p & ~3u) | inv[p & 3u]; } - -/* C emulation: exactly the kernel's arithmetic (8 HMMA steps per 128 block from a zero temporary, then fma with S') */ -static void emulate(const Prob *p, float *y) { - const uint32_t n = p->n, k = p->k, KB = k / 128; - for (uint32_t i = 0; i < p->M; i++) { - const uint16_t *xs = p->xp + (size_t)p->src[i] * k; - for (uint32_t c = 0; c < n; c++) { - const uint8_t *wr = p->w + ((size_t)p->eid[i] * n + c) * k; - const float *sr = p->sf + ((size_t)p->eid[i] * (n / 128) + c / 128) * KB; - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - float tmp = 0.0f; - for (uint32_t ch = 0; ch < 2; ch++) for (uint32_t s = 0; s < 4; s++) { - float a[16], b[16]; int m = 0; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - uint32_t e = kb * 128 + ch * 64 + 16 * t + 4 * s + j; - a[m] = u2f((uint32_t)xs[stored_ix(e)] << 16); b[m] = u2f((uint32_t)omega_tcgemm_w_bf16(wr[e]) << 16); m++; - } - tmp = hm_dot16(&GB10, a, b, tmp); - } - acc = fmaf(tmp, sr[kb], acc); - } - y[(size_t)i * n + c] = acc; - } - } -} - -/* tiles: split every expert segment into runs of at most bm rows; rowidx padded by bm entries */ -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt, pad[2]; } Tile; -static uint32_t make_tiles(const Prob *p, uint32_t bm, Tile *t, const uint8_t *wbase, const float *sbase) { - uint32_t nt = 0; - for (uint32_t i = 0; i < p->M;) { - uint32_t j = i; while (j < p->M && p->eid[j] == p->eid[i]) j++; - for (uint32_t r = i; r < j; r += bm) { - memset(&t[nt], 0, sizeof t[nt]); - t[nt].w_va = (uint64_t)(uintptr_t)(wbase + (size_t)p->eid[i] * p->n * p->k); - t[nt].s_va = (uint64_t)(uintptr_t)(sbase + (size_t)p->eid[i] * (p->n / 128) * (p->k / 128)); - t[nt].row0 = r; t[nt].cnt = j - r < bm ? j - r : bm; nt++; - } - i = j; - } - return nt; -} - -static int host_only(void) { - int fail = 0; - /* decode: every non-NaN code, the bf16 bits are the value * 2^-120 exactly */ - for (unsigned c = 0; c < 256; c++) { - if ((c & 0x7f) == 0x7f) continue; - unsigned e = (c >> 3) & 15, m = c & 7; double v = e ? ldexp(1.0 + m / 8.0, (int)e - 7) : ldexp(m / 8.0, -6); if (c & 0x80) v = -v; - if ((double)u2f((uint32_t)omega_tcgemm_w_bf16((uint8_t)c) << 16) != ldexp(v, -120)) { printf("decode code %02x wrong\n", c); fail++; } - } - { char pm[200]; int pr = omega_tc_patch_selftest(pm, sizeof pm); printf("placeholder patch self-test: %s (%s)\n", pr ? "FAIL" : "ok", pm); if (pr) fail++; } - /* production shapes: instructions and registers (declared = peak + 2 rounded to 8 <= 128; 32 * warps * declared <= 65536) */ - static const OmegaTcGemmSpec shapes[] = { - { 2048, 4, 2, 8, 0 }, { 768, 4, 2, 8, 0 }, { 4096, 4, 2, 8, 0 }, { 2048, 4, 1, 8, 0 }, { 2048, 2, 2, 4, 0 }, { 2048, 4, 2, 4, 0 }, { 768, 4, 2, 4, 0 }, - }; - static BlackwellIRProgram prog; - for (size_t i = 0; i < sizeof shapes / sizeof shapes[0]; i++) { - int rc = omega_blackwell_codegen_tcgemm_prog(&shapes[i], &prog); - uint32_t peak = rc == 0 ? prog.regalloc.peak_gpr_usage : 0, decl = omega_bw_gpr_declared(peak); - int ok = rc == 0 && decl <= 128u && 32u * shapes[i].warps * decl <= 65536u; - printf("shape k %u rt %u ct %u warps %u: rc %d, %zu instructions, peak %u, declared %u, shared %u, span %u: %s\n", shapes[i].k, shapes[i].rt, shapes[i].ct, shapes[i].warps, - rc, rc == 0 ? prog.count : 0, peak, decl, omega_tcgemm_shared_bytes(&shapes[i]), omega_tcgemm_span(&shapes[i]), ok ? "ok" : "REFUSED"); - if (i < 2 && !ok) fail++; - } - /* emulation vs double oracle (x as stored bf16, true e4m3 and bf16 scale): relative to the sum of |terms| */ - Prob p; prob_make(&p, 3, 256, 512, 40, 17, 0); - float *y = malloc((size_t)p.M * p.n * 4); emulate(&p, y); - double worst = 0; - for (uint32_t i = 0; i < p.M; i++) for (uint32_t c = 0; c < p.n; c++) { - double s = 0, mag = 0; - for (uint32_t e = 0; e < p.k; e++) { - double wv = (double)u2f((uint32_t)omega_tcgemm_w_bf16(p.w[((size_t)p.eid[i] * p.n + c) * p.k + e]) << 16) * ldexp(1.0, 120); - double xv = (double)u2f((uint32_t)p.xp[(size_t)p.src[i] * p.k + stored_ix(e)] << 16) * ldexp(1.0, -64); - double sv = (double)u2f((uint32_t)p.sbf[((size_t)p.eid[i] * (p.n / 128) + c / 128) * (p.k / 128) + e / 128] << 16); - s += wv * xv * sv; mag += fabs(wv * xv * sv); - } - double rel = fabs(y[(size_t)i * p.n + c] - s) / (mag + 1e-30); if (rel > worst) worst = rel; - } - printf("emulation vs double oracle: worst |err| / sum|terms| = %.3g (%s, bound 1e-6)\n", worst, worst < 1e-6 ? "ok" : "FAIL"); - if (worst >= 1e-6) fail++; - free(y); prob_free(&p); - printf("host-only: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} - -/* run the kernel in the simulator on p; returns 0 and fills y, or -1 with msg */ -static int sim_run(const Prob *p, const OmegaTcGemmSpec *sp, int order, float *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_tcgemm_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_tcgemm_span(sp); - if (p->n % span) { snprintf(msg, msgn, "n %% span"); return -1; } - Tile *tiles = calloc(p->M + 1, sizeof *tiles); - uint32_t nt = make_tiles(p, bm, tiles, p->w, p->sf); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - for (size_t i = 0; i < (size_t)p->M * p->n; i++) y[i] = -999.0f; - uint8_t *smem = malloc(omega_tcgemm_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_tcgemm_shared_bytes(sp); s.order = order; - uint64_t a[5] = { (uintptr_t)tiles, (uintptr_t)ridx, (uintptr_t)p->xp, (uintptr_t)y, p->n }; - for (int i = 0; i < 4; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a0 / 4] = p->n; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xp; s.ranges[2].hi = (uintptr_t)(p->xp + (size_t)p->xr * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)(y + (size_t)p->M * p->n); - s.ranges[4].lo = (uintptr_t)p->w; s.ranges[4].hi = (uintptr_t)(p->w + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->sf; s.ranges[5].hi = (uintptr_t)(p->sf + (size_t)p->E * (p->n / 128) * (p->k / 128)); - s.nranges = 6; - int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} - -static int sim_tests(void) { - int fail = 0; - static const struct { uint32_t E, n, k, M, xr; int skew; OmegaTcGemmSpec sp; } pts[] = { - { 3, 256, 256, 40, 13, 0, { 256, 4, 2, 8, 0 } }, - { 2, 128, 384, 70, 9, 1, { 384, 4, 2, 8, 0 } }, /* three blocks, a multi-tile segment */ - { 4, 128, 128, 37, 11, 0, { 128, 2, 2, 4, 0 } }, - { 2, 256, 256, 20, 7, 0, { 256, 4, 1, 8, 0 } }, - { 2, 128, 256, 33, 5, 1, { 256, 1, 4, 4, 0 } }, - { 1, 512, 256, 64, 64, 0, { 256, 4, 2, 8, 0 } }, /* dense: one expert, four CTAs across n */ - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - Prob p; prob_make(&p, pts[i].E, pts[i].n, pts[i].k, pts[i].M, pts[i].xr, pts[i].skew); - float *ye = malloc((size_t)p.M * p.n * 4), *ys = malloc((size_t)p.M * p.n * 4), *y0 = malloc((size_t)p.M * p.n * 4); - emulate(&p, ye); - for (int order = 0; order < 2; order++) { - char msg[240] = ""; int rc = sim_run(&p, &pts[i].sp, order, ys, msg, sizeof msg); - size_t bad = 0, poison = 0; - if (rc == 0) for (size_t q = 0; q < (size_t)p.M * p.n; q++) { if (ys[q] == -999.0f) poison++; if (memcmp(&ys[q], &ye[q], 4)) bad++; } - if (order == 0 && rc == 0) memcpy(y0, ys, (size_t)p.M * p.n * 4); - int same = order == 0 || (rc == 0 && memcmp(y0, ys, (size_t)p.M * p.n * 4) == 0); - printf("sim E %u n %u k %u M %u rt %u ct %u warps %u order %d: %s %s%zu of %zu differ from the emulation, %zu unwritten%s\n", p.E, p.n, p.k, p.M, pts[i].sp.rt, pts[i].sp.ct, pts[i].sp.warps, order, - rc ? "ERROR" : (bad || poison || !same) ? "MISMATCH" : "ok", msg, bad, (size_t)p.M * p.n, poison, bad || poison ? "" : " (bit-identical)"); - if (rc || bad || poison || !same) fail++; - } - free(ye); free(ys); free(y0); prob_free(&p); - } - /* mutants: each must run cleanly in the simulator and differ from the emulation */ - for (int m = 1; m <= 4; m++) { - Prob p; prob_make(&p, 2, 128, 384, 50, 9, 1); - float *ye = malloc((size_t)p.M * p.n * 4), *ys = malloc((size_t)p.M * p.n * 4); - emulate(&p, ye); - OmegaTcGemmSpec sp = { 384, 4, 2, 8, m }; - char msg[240] = ""; int rc = sim_run(&p, &sp, 0, ys, msg, sizeof msg); - size_t bad = 0; if (rc == 0) for (size_t q = 0; q < (size_t)p.M * p.n; q++) if (memcmp(&ys[q], &ye[q], 4)) bad++; - printf("sim mutant %d: %s %s(%zu of %zu differ)\n", m, rc ? "ERROR (counts as FAIL)" : bad ? "caught" : "NOT CAUGHT", msg, bad, (size_t)p.M * p.n); - if (rc || !bad) fail++; - free(ye); free(ys); prob_free(&p); - } - printf("sim: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} - -int chip_tests(int argc, char **argv); - -int main(int argc, char **argv) { - if (argc > 2 && strcmp(argv[1], "--dump") == 0) { /* raw code words for nvdisasm -b SM121 (offline check only): --dump file [k rt ct warps mutant] */ - static BlackwellIRProgram dp; static uint8_t buf[OMEGA_BW_CODE_CAP_MAX]; size_t len = 0; - OmegaTcGemmSpec sp = { argc > 3 ? (uint32_t)atoi(argv[3]) : 2048u, argc > 4 ? (uint32_t)atoi(argv[4]) : 4u, argc > 5 ? (uint32_t)atoi(argv[5]) : 2u, argc > 6 ? (uint32_t)atoi(argv[6]) : 8u, argc > 7 ? atoi(argv[7]) : 0 }; - if (omega_blackwell_codegen_tcgemm_prog(&sp, &dp) != 0 || omega_bw_encode_program(&dp, buf, sizeof buf, &len) != 0) return 1; - FILE *f = fopen(argv[2], "wb"); if (!f) return 1; fwrite(buf, 1, len, f); fclose(f); printf("peak %u, %zu bytes\n", dp.regalloc.peak_gpr_usage, len); return 0; - } - int host = 0, sim = 0, chip = 0; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--sim")) sim = 1; - else if (!strcmp(argv[i], "--chip")) chip = 1; - } - if (!host && !sim && !chip) host = sim = 1; - int fail = 0; - if (host) fail += host_only(); - if (sim && !fail) fail += sim_tests(); - if (chip && !fail) fail += chip_tests(argc, argv); - printf("GPU_TCGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} - - -/* ------------------------------------------------------------- chip */ -/* route `tokens` tokens to top-8 of E experts (distinct, uniform), sorted by expert; dense (E == 1): one row per token */ -static void route(Prob *p, uint32_t tokens) { - if (p->E == 1) { for (uint32_t i = 0; i < p->M; i++) { p->eid[i] = 0; p->src[i] = i; } return; } - uint32_t *cnt = calloc(p->E, 4), *pe = malloc((size_t)tokens * 8 * 4); - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < 8; j++) { - uint32_t e; int dup; do { e = rnd() % p->E; dup = 0; for (uint32_t q = 0; q < j; q++) if (pe[t * 8 + q] == e) dup = 1; } while (dup); - pe[t * 8 + j] = e; cnt[e]++; - } - uint32_t *off = calloc(p->E + 1, 4); for (uint32_t e = 0; e < p->E; e++) off[e + 1] = off[e] + cnt[e]; - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < 8; j++) { uint32_t e = pe[t * 8 + j], at = off[e]++; p->eid[at] = e; p->src[at] = t; } - free(cnt); free(pe); free(off); -} -static void emulate_rows(const Prob *p, const uint32_t *rows, uint32_t nr, float *out) { /* emulate only the listed rows */ - Prob q = *p; q.M = 1; - for (uint32_t i = 0; i < nr; i++) { q.eid = p->eid + rows[i]; q.src = p->src + rows[i]; emulate(&q, out + (size_t)i * p->n); } -} -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -int chip_tests(int argc, char **argv) { - const char *shape = "gateup", *outp = NULL; uint32_t tokens = 128, reps = 9, check = 384; int mut = 1; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--shape") && i + 1 < argc) shape = argv[++i]; - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--check-rows") && i + 1 < argc) check = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) outp = argv[++i]; - else if (!strcmp(argv[i], "--no-mutants")) mut = 0; - } - uint32_t E, n, k; - if (!strcmp(shape, "gateup")) { E = 128; n = 1536; k = 2048; } else if (!strcmp(shape, "down")) { E = 128; n = 2048; k = 768; } - else if (!strcmp(shape, "qkv")) { E = 1; n = 5120; k = 2048; } else if (!strcmp(shape, "o")) { E = 1; n = 2048; k = 4096; } - else { printf("unknown shape %s\n", shape); return 1; } - const uint32_t M = E == 1 ? tokens : tokens * 8u; - if (reps > 64) reps = 64; - int fail = 0; - Prob p; prob_make(&p, E, n, k, M, tokens, 0); route(&p, tokens); - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(E, n, k, p.w, p.sbf, &t); - if (rc != 0) { printf("chip: upload failed %d: %s\n", rc, omega_gpu_tcgemm_last_error()); prob_free(&p); return 1; } - float *y = malloc((size_t)M * n * 4), *y2 = malloc((size_t)M * n * 4); - OmegaGpuTcGemmInfo info; - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y, &info); - if (rc) { printf("chip: call failed %s: %s\n", omega_gpu_tcgemm_rc_name(rc), omega_gpu_tcgemm_last_error()); fail++; goto done; } - printf("chip %s: %u tokens, M %u rows, %u segments, %u tiles, grid %u x %u, rt %u ct %u warps %u, declared %u registers\n", shape, tokens, M, info.segments, info.tiles, info.grid_x, info.grid_y, info.rt, info.ct, info.warps, info.gpr_declared); - { /* bit-identity on sampled rows: the first and last rows of the table and a stride across it */ - uint32_t nr = check < M ? check : M, *rows = malloc(nr * 4); float *ye = malloc((size_t)nr * n * 4); size_t bad = 0; - for (uint32_t i = 0; i < nr; i++) rows[i] = nr == M ? i : i < 8 ? i : i >= nr - 8 ? M - (nr - i) : (uint32_t)((uint64_t)i * M / nr); - emulate_rows(&p, rows, nr, ye); - for (uint32_t i = 0; i < nr; i++) for (uint32_t c = 0; c < n; c++) if (memcmp(&y[(size_t)rows[i] * n + c], &ye[(size_t)i * n + c], 4)) bad++; - printf("chip bit-identity: %zu of %zu sampled outputs (%u rows) differ from the emulation%s\n", bad, (size_t)nr * n, nr, bad ? "" : " (bit-identical)"); - if (bad) fail++; - free(rows); free(ye); - } - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, &info); - { int same = rc == 0 && memcmp(y, y2, (size_t)M * n * 4) == 0; printf("chip second call: %s\n", same ? "identical" : "DIFFERS"); if (!same) fail++; } - if (mut) for (int m = 1; m <= 4; m++) { - omega_gpu_tcgemm_test_set_mutant(m); - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, NULL); - size_t b = 0; if (rc == 0) for (size_t q = 0; q < (size_t)M * n; q++) if (memcmp(&y[q], &y2[q], 4)) b++; - printf("chip mutant %d: %s (%zu of %zu differ)%s%s\n", m, rc ? "ERROR (counts as FAIL)" : b ? "caught" : "NOT CAUGHT", b, (size_t)M * n, rc ? " " : "", rc ? omega_gpu_tcgemm_last_error() : ""); - if (rc || !b) fail++; - } - omega_gpu_tcgemm_test_set_mutant(0); - { - uint64_t ce[64], cc[64]; uint32_t done = 0; - for (uint32_t r = 0; r < reps; r++) { if (omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, &info) == 0) { ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; } } - if (done != reps) { printf("chip timing: %u of %u calls failed\n", reps - done, reps); fail++; } - if (done) { - qsort(ce, done, 8, cmp_u64); qsort(cc, done, 8, cmp_u64); - double ns = (double)ce[done / 2], flops = 2.0 * M * n * k; - printf("TCGEMM %s (medians of %u): chip %.1f us, call %.1f us; %.2f TFLOPS; weights streamed %.0f MB (%.1f GB/s), activations gathered %.0f MB, output %.0f MB; total %.1f GB/s\n", shape, done, ns / 1e3, cc[done / 2] / 1e3, - flops / ns / 1e3, info.streamed_bytes / 1e6, info.streamed_bytes / ns, info.act_bytes / 1e6, (double)M * n * 4 / 1e6, (info.streamed_bytes + info.act_bytes + (double)M * n * 4) / ns); - if (outp) { FILE *f = fopen(outp, "w"); if (f) { fprintf(f, "{\"shape\":\"%s\",\"tokens\":%u,\"rows\":%u,\"tiles\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%" PRIu64 ",\"tflops\":%.3f,\"streamed_bytes\":%" PRIu64 ",\"act_bytes\":%" PRIu64 ",\"fail\":%d}\n", - shape, tokens, M, info.tiles, done, ns, cc[done / 2], flops / ns / 1e3, info.streamed_bytes, info.act_bytes, fail); fclose(f); } } - } - } -done: - free(y); free(y2); omega_gpu_fp8_tensor_free(t); prob_free(&p); - printf("chip: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} diff --git a/tests/test_omega_blackwell_engine.c b/tests/test_omega_blackwell_engine.c deleted file mode 100644 index a4397d823..000000000 --- a/tests/test_omega_blackwell_engine.c +++ /dev/null @@ -1,995 +0,0 @@ -/* - * Host test of the REAL Blackwell backend (src/omega_blackwell_engine.c), the - * REAL engine core (src/omega_gpu_engine.c) and the REAL vector wrapper - * omega_blackwell_execute_vector (src/omega_blackwell_submit.c), driven through - * a SIMULATED driver (tests/fake_m16_native.c). Cut A3b2. NOT_RUN: this file has - * never been compiled or executed by its author (Phase A rule). - * - * No GPU, no device node, no physics C sources: the seven driver symbols the - * backend calls are replaced by the fake. Every check prints "[PASS] id" or - * "[FAIL] id"; the last line is "SUMMARY passed=N failed=M"; the exit status is - * nonzero on any failure. docs/numeric/OMEGA_GPU_ENGINE.md section 14.1 lists - * every id and the mutants that need it. - * - * Techniques: - * - A tracing copy of the real backend table logs every callback (so the call - * order the core and the backend produce together can be asserted) and - * forwards to the original. The real table is never edited. - * - The fake parses and executes the pushbuffer, so the descriptors, the - * release packets and the L2 flush are checked as the device would see them. - * - A retained run (uncertain completion) leaves the backend busy by design. - * The test asserts that, then drains the backend through its own table - * (free every role, close), exactly what a process exit would do. - * - * Failure names that no driver fault can reach through the real backend, and so - * are covered by the fake-backend test (tests/test_omega_gpu_engine.c) only: - * PREPARE (copy-in and build refuse only on arguments the core already - * validated, and alloc_checked catches bad buffers first as ALLOC), - * VISIBILITY_WAIT (the barrier always returns 0, copy_out refuses only on bad - * arguments), - * INTERNAL_INVARIANT (the table is complete). - * The CPU barrier (dsb sy) has no effect a host can observe; it is chip only. - */ -#include "omega_gpu_engine.h" -#include "omega_blackwell_engine.h" -#include "omega_blackwell_submit.h" -#include "omega_blackwell_encoder.h" -#include "omega_vector.h" -#include "fake_m16_native.h" - -#include -#include -#include -#include -#include - -#define N 100u /* not a multiple of 64: a grid rounded down leaves words unwritten */ -#define TMO_MARKER 111u -#define TMO_MARKER2 222u -#define TMO_RELEASE 333u -#define TMO_VISIBILITY 444u - -#define MARKER1_PAYLOAD 0x44444444u -#define MARKER2_PAYLOAD 0x46464646u -#define SEM_INIT 5u -#define SEM_DONE 6u -#define RELEASE_FLAGS 0x00100001u /* RELEASE | WFI */ -#define FLUSH_OP (0x10u << 27) /* L2_FLUSH_DIRTY */ - -static int n_pass; -static int n_fail; - -static void check(const char *id, int ok) -{ - if (ok) { - n_pass++; - printf("[PASS] %s\n", id); - } else { - n_fail++; - printf("[FAIL] %s\n", id); - } -} - -/* ---- test data -------------------------------------------------------------- */ - -static uint32_t ina[N]; -static uint32_t inb[N]; -static uint32_t expect_out[N]; -static uint32_t poison[N]; -static uint32_t outbuf[N]; -static uint8_t prog[512]; -static uint8_t prog_other[512]; -static uint8_t vec_code[0x1000]; -static size_t vec_len; -static uint8_t bigbytes[0x2000]; -static uint32_t bigwords[2048]; - -static void init_data(void) -{ - uint32_t i; - for (i = 0; i < N; i++) { - uint32_t s; - ina[i] = i * 0x01000193u + 0x01234567u; - inb[i] = i * 0x9e3779b1u + 7u; - s = ina[i] + inb[i]; - /* a wrong-by-one result must never look like the poison word */ - if (s == 0x7fffffffu || s == 0xffffffffu) inb[i] += 0x10u; - } - /* the old fixed poison value as a legitimate sum */ - ina[7] = 0xdeadbeefu - 5u; - inb[7] = 5u; - for (i = 0; i < N; i++) { - expect_out[i] = ina[i] + inb[i]; - poison[i] = ~expect_out[i]; - } - for (i = 0; i < sizeof prog; i++) { - prog[i] = (uint8_t)(i * 7u + 3u); - prog_other[i] = (uint8_t)(i * 11u + 5u); - } -} - -static int output_correct(const uint32_t *o) -{ - uint32_t i; - for (i = 0; i < N; i++) - if (o[i] != expect_out[i]) return 0; - return 1; -} - -/* ---- tracing copy of the real backend table ---------------------------------- */ - -enum { - T_OPEN = 1, T_CHANNEL, T_ALLOC, T_COPY_IN, T_POISON, T_BUILD, T_SUBMIT, T_WAIT1, - T_WAIT2, T_WAITSEM, T_BARRIER, T_COPY_OUT, T_FREE, T_CLOSE -}; -#define TLOG_MAX 128 - -static const OmegaGpuBackend *g_real; -static OmegaGpuBackend g_wrap; -static int g_tlog[TLOG_MAX]; -static int g_targ[TLOG_MAX]; -static int g_tn; - -static void tlog(int kind, int arg) -{ - if (g_tn < TLOG_MAX) { - g_tlog[g_tn] = kind; - g_targ[g_tn] = arg; - g_tn++; - } -} - -static int w_open(void *ctx) { tlog(T_OPEN, 0); return g_real->open_device(ctx); } -static int w_channel(void *ctx) { tlog(T_CHANNEL, 0); return g_real->create_channel(ctx); } -static int w_alloc(void *ctx, int role, size_t bytes) { tlog(T_ALLOC, role); return g_real->alloc(ctx, role, bytes); } -static int w_copy_in(void *ctx, int role, const void *src, size_t bytes) { tlog(T_COPY_IN, role); return g_real->copy_in(ctx, role, src, bytes); } -static int w_poison(void *ctx, const uint32_t *words, size_t count) { tlog(T_POISON, 0); return g_real->fill_poison(ctx, words, count); } -static int w_build(void *ctx, const OmegaGpuJob *job) { tlog(T_BUILD, 0); return g_real->build(ctx, job); } -static int w_submit(void *ctx) { tlog(T_SUBMIT, 0); return g_real->submit(ctx); } -static int w_wait1(void *ctx, uint64_t ms) { tlog(T_WAIT1, 0); return g_real->wait_marker(ctx, ms); } -static int w_wait2(void *ctx, uint64_t ms) { tlog(T_WAIT2, 0); return g_real->wait_marker2(ctx, ms); } -static int w_waitsem(void *ctx, uint64_t ms) { tlog(T_WAITSEM, 0); return g_real->wait_release_semaphore(ctx, ms); } -static int w_barrier(void *ctx, uint64_t ms) { tlog(T_BARRIER, 0); return g_real->barrier(ctx, ms); } -static int w_copy_out(void *ctx, void *dst, size_t bytes) { tlog(T_COPY_OUT, 0); return g_real->copy_out(ctx, dst, bytes); } -static void w_diag(void *ctx, OmegaGpuBackendDiag *d) { g_real->diagnostics(ctx, d); } -static int w_free(void *ctx, int role) { tlog(T_FREE, role); return g_real->free_buf(ctx, role); } -static int w_close(void *ctx) { tlog(T_CLOSE, 0); return g_real->close(ctx); } - -static void wrap_init(void) -{ - g_real = omega_blackwell_engine_backend(); - g_wrap = *g_real; - g_wrap.open_device = w_open; - g_wrap.create_channel = w_channel; - g_wrap.alloc = w_alloc; - g_wrap.copy_in = w_copy_in; - g_wrap.fill_poison = w_poison; - g_wrap.build = w_build; - g_wrap.submit = w_submit; - g_wrap.wait_marker = w_wait1; - g_wrap.wait_marker2 = w_wait2; - g_wrap.wait_release_semaphore = w_waitsem; - g_wrap.barrier = w_barrier; - g_wrap.copy_out = w_copy_out; - g_wrap.diagnostics = w_diag; - g_wrap.free_buf = w_free; - g_wrap.close = w_close; -} - -static int tcount(int kind) -{ - int i; - int n = 0; - for (i = 0; i < g_tn; i++) - if (g_tlog[i] == kind) n++; - return n; -} - -/* ---- case plumbing ---------------------------------------------------------- */ - -static OmegaGpuJob job; -static OmegaGpuResult res; - -static void make_job(OmegaGpuJob *j) -{ - memset(j, 0, sizeof *j); - j->program = prog; - j->program_len = sizeof prog; - j->layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j->element_count = N; - j->input_a = ina; - j->input_a_len = N * 4u; - j->input_b = inb; - j->input_b_len = N * 4u; - j->output = outbuf; - j->output_len = N * 4u; - j->poison = poison; - j->poison_count = N; - j->timeouts.marker_ms = TMO_MARKER; - j->timeouts.marker2_ms = TMO_MARKER2; - j->timeouts.release_semaphore_ms = TMO_RELEASE; - j->timeouts.visibility_ms = TMO_VISIBILITY; - j->flags = 0; -} - -static void begin_case(void) -{ - fake_reset(); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_set_backend(&g_wrap); - g_tn = 0; - memset(outbuf, 0, sizeof outbuf); - fk.prog_expect = prog; - fk.prog_len = sizeof prog; - make_job(&job); -} - -static int run(void) -{ - return omega_gpu_execute(&job, &res); -} - -static int res_is(int failure, int step, int state) -{ - return res.failure == failure && res.failed_step == step && res.last_state == state; -} - -/* Everything the backend allocated was returned, the device was closed once, and - * the number of real driver frees is as expected. */ -static int balanced(int frees) -{ - return fk.live_at_close == 0 && fk.double_free == 0 && fk.close_calls == 1 && - fk.free_calls == frees && fk.device_open == 0; -} - -static int has(const char *hay, const char *needle) -{ - return strstr(hay, needle) != NULL; -} - -/* Drains a retained backend through its own table, the way process exit would: - * free every role (all of them are held), then close. Returns 0 if all went well. */ -static int drain(void) -{ - int bad = 0; - int role; - for (role = (int)OMEGA_GPU_BUF_ROLE_COUNT - 1; role >= 0; role--) - if (g_real->free_buf(g_real->ctx, role) != 0) bad = 1; - if (g_real->close(g_real->ctx) != 0) bad = 1; - return bad; -} - -static void idf(char *buf, size_t cap, const char *tag, const char *what) -{ - (void)snprintf(buf, cap, "sim_%s_%s", tag, what); -} - -/* ---- cases ------------------------------------------------------------------ */ - -static void case_success(void) -{ - static const int k_order[24] = { - T_OPEN, T_CHANNEL, T_ALLOC, T_ALLOC, T_ALLOC, T_ALLOC, T_ALLOC, T_COPY_IN, T_COPY_IN, - T_COPY_IN, T_POISON, T_BUILD, T_SUBMIT, T_WAIT1, T_WAIT2, T_WAITSEM, T_BARRIER, - T_COPY_OUT, T_FREE, T_FREE, T_FREE, T_FREE, T_FREE, T_CLOSE - }; - static const int k_args[24] = { - 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 2, 1, 0, 0 - }; - static const uint64_t k_sizes[8] = { - 0x10000u, 0x1000u, 0x1000u, 0x10000u, 0x1000u, 0x1000u, 0x1000u, 0x1000u - }; - OmegaBlackwellEngineRunInfo info; - int i; - int ok; - int i_cb, i_ar, i_q0, i_si, i_q1, i_k, i_r1, i_fl, i_r2; - - begin_case(); - check("sim_success_returns_ok", run() == OMEGA_GPU_ENGINE_OK); - check("sim_success_state", res.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS && - res.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - check("sim_success_result_flags_clear", - res.retained == 0 && res.cleanup_failed == 0 && res.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - check("sim_success_not_blocked", omega_gpu_engine_is_blocked() == 0); - check("sim_success_output_values", output_correct(outbuf)); - check("sim_success_unchanged_zero", res.n_outputs == 1u && res.output_unchanged_words[0] == 0u); - - ok = g_tn == 24; - for (i = 0; ok && i < 24; i++) - if (g_tlog[i] != k_order[i] || g_targ[i] != k_args[i]) ok = 0; - check("sim_success_call_order", ok); - - check("sim_success_driver_counts", - fk.open_calls == 1 && fk.channel_calls == 1 && fk.alloc_calls == 8 && - fk.submit_calls == 1 && fk.close_calls == 1 && fk.wait_calls == 3); - check("sim_success_all_allocs_gpu_uncached", fk.uncached_calls == fk.alloc_calls && fk.uncached_calls == 8); - ok = fake_count(FK_EV_ALLOC) == 8; - for (i = 0; ok && i < 8; i++) - if (fk.ev[fake_nth(FK_EV_ALLOC, i + 1)].a != k_sizes[i]) ok = 0; - check("sim_success_alloc_sizes", ok); - check("sim_success_balanced", balanced(8)); - check("sim_success_large_pushbuffer_ring", fk.pb_mem_size == 0x10000u); - check("sim_success_pushbuffer_parses", fk.pb_parse_error == 0 && fk.ev_overflow == 0); - - /* The state the GPU sees at the doorbell: the sync words were zeroed first. */ - check("sim_success_doorbell_state_captured", fk.pre_valid == 1); - check("sim_success_marker1_zeroed_before_doorbell", fk.pre_marker1 == 0u); - check("sim_success_marker2_zeroed_before_doorbell", fk.pre_marker2 == 0u); - check("sim_success_semaphore_zeroed_before_doorbell", fk.pre_sem == 0u); - check("sim_success_semaphore_init_value", fk.sem_init_value == SEM_INIT); - - /* The pushbuffer, as the device executes it. */ - i_cb = fake_nth(FK_EV_PB_CBANK, 1); - i_ar = fake_nth(FK_EV_PB_ARGS, 1); - i_q0 = fake_nth(FK_EV_PB_QMD, 1); - i_si = fake_nth(FK_EV_PB_SEM_INIT, 1); - i_q1 = fake_nth(FK_EV_PB_QMD, 2); - i_k = fake_nth(FK_EV_KERNEL, 1); - i_r1 = fake_nth(FK_EV_PB_RELEASE, 1); - i_fl = fake_nth(FK_EV_PB_FLUSH, 1); - i_r2 = fake_nth(FK_EV_PB_RELEASE, 2); - check("sim_success_pushbuffer_order", - i_cb >= 0 && i_cb < i_ar && i_ar < i_q0 && i_q0 < i_si && i_si < i_q1 && i_q1 < i_k && - i_k < i_r1 && i_r1 < i_fl && i_fl < i_r2); - check("sim_success_one_flush_two_releases", - fake_count(FK_EV_PB_FLUSH) == 1 && fake_count(FK_EV_PB_RELEASE) == 2); - if (i_cb >= 0 && i_ar >= 0 && i_q0 >= 0 && i_q1 >= 0 && i_fl >= 0 && i_r1 >= 0 && i_r2 >= 0) { - check("sim_success_cbank_upload_words_and_place", - fk.ev[i_cb].b == 224u && fk.ev[i_cb].a == fk.alloc_va[1]); - check("sim_success_args_upload_words_and_place", - fk.ev[i_ar].b == 7u && fk.ev[i_ar].a == fk.ev[i_cb].a + 0x380u); - check("sim_success_qmd0_is_not_the_kernel_and_place", - fk.ev[i_q0].b == 0u && fk.ev[i_q0].a == fk.alloc_va[3]); - check("sim_success_qmd1_is_the_kernel_and_place", - fk.ev[i_q1].b == 1u && fk.ev[i_q1].a == fk.alloc_va[3] + 0x1000u); - check("sim_success_flush_operation", fk.ev[i_fl].a == (uint64_t)FLUSH_OP); - check("sim_success_release1_address_payload_flags", - fk.ev[i_r1].a == fk.marker1_va && fk.ev[i_r1].b == MARKER1_PAYLOAD && - fk.ev[i_r1].c == RELEASE_FLAGS); - check("sim_success_release2_is_marker_page_plus_0x10", - fk.ev[i_r2].a == fk.ev[i_r1].a + 0x10u); - check("sim_success_release2_payload_and_flags", - fk.ev[i_r2].b == MARKER2_PAYLOAD && fk.ev[i_r2].c == RELEASE_FLAGS); - } else { - check("sim_success_cbank_upload_words_and_place", 0); - check("sim_success_args_upload_words_and_place", 0); - check("sim_success_qmd0_is_not_the_kernel_and_place", 0); - check("sim_success_qmd1_is_the_kernel_and_place", 0); - check("sim_success_flush_operation", 0); - check("sim_success_release1_address_payload_flags", 0); - check("sim_success_release2_is_marker_page_plus_0x10", 0); - check("sim_success_release2_payload_and_flags", 0); - } - - /* The kernel launch the device saw. */ - check("sim_success_kernel_ran_once_with_right_program", fk.kernel_ran == 1 && fk.prog_matched == 1); - check("sim_success_kernel_threads_and_count", fk.kernel_threads == 128u && fk.kernel_n == N); - check("sim_success_kernel_arguments_are_a_b_output", - fk.arg_a == fk.alloc_va[5] && fk.arg_b == fk.alloc_va[6] && fk.arg_c == fk.alloc_va[7]); - check("sim_success_kernel_program_and_cbank_addresses", - fk.prog_va_seen == fk.alloc_va[4] && fk.cbank_va_seen == fk.alloc_va[1]); - check("sim_success_marker_and_semaphore_places", - fk.marker1_va == fk.alloc_va[2] && fk.sem_va == fk.alloc_va[3] + 0x2000u); - ok = fk.snap_n == N; - for (i = 0; ok && i < (int)N; i++) - if (fk.out_before[i] != poison[i]) ok = 0; - check("sim_success_poison_reached_device_output", ok); - check("sim_success_poison_never_equals_a_sum", fk.poison_collisions == 0); - - /* The waits, by word, expected value and timeout. */ - check("sim_success_wait_counts", - fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_MARKER2] == 1 && - fk.wait_n[FK_W_SEM] == 1 && fk.wait_n[FK_W_UNKNOWN] == 0); - check("sim_success_wait_expected_values", - fk.wait_expected[FK_W_MARKER1] == MARKER1_PAYLOAD && - fk.wait_expected[FK_W_MARKER2] == MARKER2_PAYLOAD && - fk.wait_expected[FK_W_SEM] == SEM_DONE); - check("sim_success_wait_timeouts_come_from_the_job", - fk.wait_ms[FK_W_MARKER1] == TMO_MARKER && fk.wait_ms[FK_W_MARKER2] == TMO_MARKER2 && - fk.wait_ms[FK_W_SEM] == TMO_RELEASE); - i = fake_nth(FK_EV_WAIT, 1); - ok = i >= 0 && fk.ev[i].a == (uint64_t)FK_W_MARKER1; - i = fake_nth(FK_EV_WAIT, 2); - ok = ok && i >= 0 && fk.ev[i].a == (uint64_t)FK_W_MARKER2; - i = fake_nth(FK_EV_WAIT, 3); - ok = ok && i >= 0 && fk.ev[i].a == (uint64_t)FK_W_SEM; - check("sim_success_wait_order_marker_marker2_semaphore", ok); - - /* What the backend observed, for the vector wrapper. */ - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_success_run_info_words", - info.marker == MARKER1_PAYLOAD && info.marker2 == MARKER2_PAYLOAD && info.semaphore == SEM_DONE); - check("sim_success_run_info_launch_time_set", info.launch_ns != 0u); - check("sim_success_run_info_done_time_after_launch", - info.marker_done_ns != 0u && info.marker_done_ns >= info.launch_ns); -} - -static void case_no_c3(void) -{ - OmegaBlackwellEngineRunInfo info; - begin_case(); - job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; - check("sim_noc3_returns_ok", run() == OMEGA_GPU_ENGINE_OK); - check("sim_noc3_output_values", output_correct(outbuf)); - check("sim_noc3_no_flush_in_pushbuffer", fake_count(FK_EV_PB_FLUSH) == 0); - check("sim_noc3_one_release_only", fake_count(FK_EV_PB_RELEASE) == 1 && fk.marker2_va == 0u); - check("sim_noc3_marker2_never_waited", - fk.wait_n[FK_W_MARKER2] == 0 && tcount(T_WAIT2) == 0 && fk.wait_calls == 2); - check("sim_noc3_marker1_and_semaphore_waited", - fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_SEM] == 1); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_noc3_run_info_marker2_not_reported", info.marker2 == 0u && info.marker == MARKER1_PAYLOAD); - check("sim_noc3_balanced", balanced(8)); -} - -static void case_back_to_back(void) -{ - int rc1; - int rc2; - int ok; - begin_case(); - rc1 = run(); - ok = output_correct(outbuf); - memset(outbuf, 0, sizeof outbuf); - rc2 = run(); - check("sim_twice_first_ok", rc1 == OMEGA_GPU_ENGINE_OK && ok); - check("sim_twice_second_ok_busy_flag_released", rc2 == OMEGA_GPU_ENGINE_OK && output_correct(outbuf)); - check("sim_twice_driver_opened_and_closed_twice", fk.open_calls == 2 && fk.close_calls == 2); -} - -static void case_open_fail(void) -{ - OmegaBlackwellEngineRunInfo info; - int rc; - begin_case(); - (void)run(); /* leave a dirty run snapshot behind */ - begin_case(); - fk.open_fail = 1; - rc = run(); - check("sim_open_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_DEVICE_OPEN && - res_is(OMEGA_GPU_ENGINE_DEVICE_OPEN, OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - check("sim_open_fail_errno_and_driver_code", res.err_no == EIO && res.drv_rc == -1); - check("sim_open_fail_driver_text_reported", strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_open_fail_nothing_else_touched", - fk.channel_calls == 0 && fk.alloc_calls == 0 && fk.close_calls == 0 && fk.free_calls == 0); - check("sim_open_fail_not_retained_not_blocked", - res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_open_fail_run_info_reset_at_open", - info.marker == 0u && info.semaphore == 0u && info.launch_ns == 0u && info.marker_done_ns == 0u); - begin_case(); - check("sim_open_fail_then_next_run_ok", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_channel_fail(void) -{ - int rc; - begin_case(); - fk.channel_fail = 1; - rc = run(); - check("sim_channel_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_CHANNEL_CREATE && - res_is(OMEGA_GPU_ENGINE_CHANNEL_CREATE, OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - check("sim_channel_fail_errno_text_code", - res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_channel_fail_closed_nothing_allocated", fk.alloc_calls == 0 && balanced(0)); - begin_case(); - check("sim_channel_fail_then_next_run_ok", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_alloc_faults(void) -{ - int nth; - char id[64]; - for (nth = 1; nth <= 8; nth++) { - int rc; - begin_case(); - fk.alloc_fail_nth = nth; - fk.alloc_mode = FK_ALLOC_FAIL; - rc = run(); - (void)snprintf(id, sizeof id, "sim_alloc%d_name_step_state", nth); - check(id, rc == OMEGA_GPU_ENGINE_ALLOC && - res_is(OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STEP_ALLOC, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - (void)snprintf(id, sizeof id, "sim_alloc%d_errno_code_text", nth); - check(id, res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - (void)snprintf(id, sizeof id, "sim_alloc%d_stops_at_the_failure", nth); - check(id, fk.alloc_calls == nth); - /* nothing is leaked: every part that was allocated is freed (nth - 1 of them) */ - (void)snprintf(id, sizeof id, "sim_alloc%d_balanced", nth); - check(id, balanced(nth - 1)); - } -} - -static void case_alloc_own_checks(void) -{ - static const struct { int mode; int nth; int frees; const char *tag; } t[] = { - { FK_ALLOC_SHORT, 1, 1, "short_pb" }, - { FK_ALLOC_NO_CPU, 3, 3, "nocpu_marker" }, - { FK_ALLOC_MISALIGNED, 4, 4, "misaligned_qmd" }, - { FK_ALLOC_SHORT, 6, 6, "short_input_a" }, - { FK_ALLOC_NO_CPU, 6, 6, "nocpu_input_a" }, - { FK_ALLOC_MISALIGNED, 6, 6, "misaligned_input_a" }, - { FK_ALLOC_NO_CPU, 8, 8, "nocpu_output" } - }; - size_t k; - char id[64]; - for (k = 0; k < sizeof t / sizeof t[0]; k++) { - int rc; - begin_case(); - fk.alloc_fail_nth = t[k].nth; - fk.alloc_mode = t[k].mode; - rc = run(); - idf(id, sizeof id, t[k].tag, "refused_as_alloc"); - check(id, rc == OMEGA_GPU_ENGINE_ALLOC && - res_is(OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STEP_ALLOC, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - idf(id, sizeof id, t[k].tag, "own_check_text"); - check(id, has(res.drv_text, "own checks")); - idf(id, sizeof id, t[k].tag, "balanced"); - check(id, balanced(t[k].frees)); - } -} - -static void case_submit_fail(void) -{ - int rc; - begin_case(); - fk.submit_fail = 1; - rc = run(); - check("sim_submit_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_SUBMIT && - res_is(OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED)); - check("sim_submit_fail_errno_code_text", - res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_submit_fail_is_not_uncertain", - res.retained == 0 && omega_gpu_engine_is_blocked() == 0 && fk.kernel_ran == 0); - check("sim_submit_fail_cleaned_up", balanced(8)); -} - -/* One uncertain completion: the engine keeps everything and blocks the process. - * Asserts that, asserts the next job is refused without touching the driver, asserts - * a second open of the backend is refused, drains, and proves the backend works again. */ -static void uncertain_case(const char *tag, int mk, int mk2, int sem, uint32_t flags, - int failure, int step, int wait, uint64_t limit, uint64_t waited, - uint32_t want_marker, uint32_t want_marker2, uint32_t want_sem, - uint32_t want_sync, const char *want_text, int want_drv_rc) -{ - char id[96]; - int rc; - int bad; - int open_before; - OmegaBlackwellEngineRunInfo info; - - begin_case(); - fk.marker_mode = mk; - fk.marker2_mode = mk2; - fk.sem_mode = sem; - job.flags = flags; - rc = run(); - - idf(id, sizeof id, tag, "name_step_wait"); - check(id, rc == failure && res.failure == failure && res.failed_step == step && res.wait == wait); - idf(id, sizeof id, tag, "last_state_submitted"); - check(id, res.last_state == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - idf(id, sizeof id, tag, "limit_and_waited_ms"); - check(id, res.wait_timeout_ms == limit && res.waited_ms == waited); - idf(id, sizeof id, tag, "observed_words"); - check(id, res.marker == want_marker && res.marker2 == want_marker2 && - res.semaphore[0] == want_sem); - idf(id, sizeof id, tag, "sync_valid_mask"); - check(id, res.sync_valid == want_sync); - if (want_text != NULL) { - idf(id, sizeof id, tag, "driver_text"); - check(id, has(res.drv_text, want_text)); - } - idf(id, sizeof id, tag, "retained_and_blocked"); - check(id, res.retained == 1 && omega_gpu_engine_is_blocked() == 1); - idf(id, sizeof id, tag, "nothing_freed_nothing_closed"); - check(id, fk.free_calls == 0 && fk.close_calls == 0 && fk.live == 8 && fk.device_open == 1 && - tcount(T_FREE) == 0 && tcount(T_CLOSE) == 0); - - idf(id, sizeof id, tag, "driver_code"); - check(id, res.drv_rc == want_drv_rc); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - idf(id, sizeof id, tag, "run_info_marker"); - check(id, info.marker == want_marker && info.launch_ns != 0u); - idf(id, sizeof id, tag, "run_info_done_time_only_if_marker_succeeded"); - check(id, (step == OMEGA_GPU_ENGINE_STEP_WAIT_MARKER) == (info.marker_done_ns == 0u)); - idf(id, sizeof id, tag, "run_info_marker2_when_it_was_the_failed_wait"); - check(id, step != OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2 || info.marker2 == want_marker2); - idf(id, sizeof id, tag, "run_info_semaphore_when_it_was_the_failed_wait"); - check(id, step != OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE || info.semaphore == want_sem); - idf(id, sizeof id, tag, "no_marker2_wait_with_noc3"); - check(id, (flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0u || (fk.wait_n[FK_W_MARKER2] == 0 && tcount(T_WAIT2) == 0)); - open_before = fk.open_calls; - rc = run(); - idf(id, sizeof id, tag, "next_job_blocked"); - check(id, rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED && - res.failed_step == OMEGA_GPU_ENGINE_STEP_BLOCKED && fk.open_calls == open_before); - idf(id, sizeof id, tag, "second_open_refused_by_backend"); - check(id, g_real->open_device(g_real->ctx) != 0 && fk.open_calls == open_before); - idf(id, sizeof id, tag, "still_retained_after_refusals"); - check(id, fk.live == 8 && fk.device_open == 1 && fk.close_calls == 0); - - bad = drain(); - idf(id, sizeof id, tag, "drained_through_the_table"); - check(id, bad == 0 && fk.close_calls == 1 && fk.live_at_close == 0 && fk.double_free == 0 && - fk.free_calls == 8); - omega_gpu_engine_test_reset_block(); - make_job(&job); - /* The simulated driver still has the hang or overshoot of this case armed: restore a healthy chip. */ - fk.marker_mode = FK_SYNC_NORMAL; - fk.marker2_mode = FK_SYNC_NORMAL; - fk.sem_mode = FK_SYNC_NORMAL; - idf(id, sizeof id, tag, "backend_works_again_after_drain"); - check(id, run() == OMEGA_GPU_ENGINE_OK && output_correct(outbuf)); -} - -static void case_uncertain(void) -{ - const uint32_t all = OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE; - - uncertain_case("unc_marker_hang", FK_SYNC_NEVER, FK_SYNC_NORMAL, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, - OMEGA_GPU_ENGINE_WAIT_MARKER, TMO_MARKER, TMO_MARKER, - 0u, MARKER2_PAYLOAD, SEM_DONE, all, NULL, -1); - uncertain_case("unc_marker2_hang", FK_SYNC_NORMAL, FK_SYNC_NEVER, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, - OMEGA_GPU_ENGINE_WAIT_MARKER2, TMO_MARKER2, TMO_MARKER2, - MARKER1_PAYLOAD, 0u, SEM_DONE, all, NULL, -1); - uncertain_case("unc_semaphore_hang", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_NEVER, 0u, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, TMO_RELEASE, - MARKER1_PAYLOAD, MARKER2_PAYLOAD, SEM_INIT, all, NULL, -1); - uncertain_case("unc_marker_overshoot", FK_SYNC_OVERSHOOT, FK_SYNC_NORMAL, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, - OMEGA_GPU_ENGINE_WAIT_MARKER, TMO_MARKER, 0u, - MARKER1_PAYLOAD + 1u, MARKER2_PAYLOAD, SEM_DONE, all, "observed 0x44444445", 0); - uncertain_case("unc_marker2_overshoot", FK_SYNC_NORMAL, FK_SYNC_OVERSHOOT, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, - OMEGA_GPU_ENGINE_WAIT_MARKER2, TMO_MARKER2, 0u, - MARKER1_PAYLOAD, MARKER2_PAYLOAD + 1u, SEM_DONE, all, "observed 0x46464647", 0); - uncertain_case("unc_semaphore_overshoot", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_OVERSHOOT, 0u, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, 0u, - MARKER1_PAYLOAD, MARKER2_PAYLOAD, SEM_DONE + 1u, all, "observed 0x00000007", 0); - /* NO_C3: the second marker does not exist, so it is never reported either. */ - uncertain_case("unc_noc3_semaphore_hang", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_NEVER, - OMEGA_GPU_ENGINE_FLAG_NO_C3, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, TMO_RELEASE, - MARKER1_PAYLOAD, 0u, SEM_INIT, OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_SEMAPHORE, NULL, -1); -} - -static void case_cleanup_faults(void) -{ - int rc; - - /* a free of an ordinary buffer fails: every other free still runs */ - begin_case(); - fk.free_fail_nth = 1; - rc = run(); - check("sim_cleanup_free_role_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_FREE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_free_role_flag_errno_text", - res.cleanup_failed == 1 && res.err_no == EIO && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_free_role_every_free_attempted_and_closed", - fk.free_calls == 8 && fk.close_calls == 1 && fk.live_at_close == 1); - check("sim_cleanup_free_role_words_still_mapped_at_capture", - res.sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE) && - res.marker == MARKER1_PAYLOAD && res.marker2 == MARKER2_PAYLOAD && res.semaphore[0] == SEM_DONE); - check("sim_cleanup_free_role_not_uncertain", res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - - /* a free of one SCRATCH part fails (the marker page, sixth real free): the - * other scratch parts are still freed and the sync words are unmapped first */ - begin_case(); - fk.free_fail_nth = 6; - rc = run(); - check("sim_cleanup_free_scratch_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_FREE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_free_scratch_code_and_text", - res.cleanup_failed == 1 && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_free_scratch_all_four_parts_attempted", - fk.free_calls == 8 && fk.close_calls == 1 && fk.live_at_close == 1); - check("sim_cleanup_free_scratch_sync_words_unmapped_before_free", res.sync_valid == 0u); - - /* close fails */ - begin_case(); - fk.close_fail = 1; - rc = run(); - check("sim_cleanup_close_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_CLOSE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_close_flag_errno_text", - res.cleanup_failed == 1 && res.err_no == EIO && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_close_all_freed_first", fk.free_calls == 8 && fk.live_at_close == 0); - begin_case(); - check("sim_cleanup_close_failure_still_releases_busy_flag", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_unchanged(void) -{ - int rc; - - begin_case(); - fk.kernel_mode = FK_KERNEL_NO_WRITE; - rc = run(); - check("sim_unchanged_nowrite_name_step_state", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && - res_is(OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STEP_SCAN, - OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE)); - check("sim_unchanged_nowrite_counts_every_word", - res.n_outputs == 1u && res.output_unchanged_words[0] == N); - check("sim_unchanged_nowrite_completion_was_seen", - fk.kernel_ran == 1 && fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_SEM] == 1); - check("sim_unchanged_nowrite_cleaned_up_not_retained", - balanced(8) && res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - - begin_case(); - fk.kernel_mode = FK_KERNEL_HALF; - rc = run(); - check("sim_unchanged_half_counts_the_unwritten_half", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && res.output_unchanged_words[0] == N / 2u); - - /* the device runs different program bytes than the job supplied: it writes nothing */ - begin_case(); - fk.prog_expect = prog_other; - rc = run(); - check("sim_unchanged_wrong_program_bytes_detected", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && fk.kernel_ran == 1 && fk.prog_matched == 0 && - res.output_unchanged_words[0] == N); -} - -static void case_table_guards(void) -{ - const OmegaGpuBackend *be = omega_blackwell_engine_backend(); - void *ctx = be->ctx; - OmegaGpuJob j; - int role; - int bad = 0; - - begin_case(); - memset(&j, 0, sizeof j); - j.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j.element_count = N; - - check("sim_guard_open_ok", be->open_device(ctx) == 0); - check("sim_guard_channel_ok", be->create_channel(ctx) == 0); - check("sim_guard_alloc_zero_bytes_refused", be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, 0u) != 0); - check("sim_guard_alloc_unknown_role_refused", be->alloc(ctx, 99, 4096u) != 0); - check("sim_guard_alloc_rounds_up_to_whole_pages", - be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, 5000u) == 0 && fake_count(FK_EV_ALLOC) == 1 && - fk.ev[fake_nth(FK_EV_ALLOC, 1)].a == 0x2000u); - check("sim_guard_free_after_rounding_ok", be->free_buf(ctx, (int)OMEGA_GPU_BUF_OUTPUT) == 0); - check("sim_guard_wait_before_build_refused_without_driver_call", - be->wait_marker(ctx, 5u) != 0 && be->wait_marker2(ctx, 5u) != 0 && - be->wait_release_semaphore(ctx, 5u) != 0 && fk.wait_calls == 0); - check("sim_guard_submit_before_build_refused", be->submit(ctx) != 0); - check("sim_guard_build_without_buffers_refused", be->build(ctx, &j) != 0); - - check("sim_guard_alloc_scratch_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_SCRATCH, 0u) == 0); - check("sim_guard_alloc_program_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_PROGRAM, sizeof prog) == 0); - check("sim_guard_alloc_a_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_A, N * 4u) == 0); - check("sim_guard_alloc_b_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_B, N * 4u) == 0); - check("sim_guard_alloc_output_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, N * 4u) == 0); - check("sim_guard_copy_in_negative_role_refused", be->copy_in(ctx, -1, prog, sizeof prog) != 0); - check("sim_guard_free_negative_role_refused", be->free_buf(ctx, -1) != 0); - check("sim_guard_build_null_job_refused", be->build(ctx, NULL) != 0); - j.layout = 7; - check("sim_guard_build_unknown_layout_refused", be->build(ctx, &j) != 0); - j.layout = (int)OMEGA_GPU_LAYOUT_VECTOR_1D; - j.element_count = 0u; - check("sim_guard_build_zero_count_refused", be->build(ctx, &j) != 0); - j.element_count = 2000u; - check("sim_guard_build_count_beyond_the_buffers_refused", be->build(ctx, &j) != 0); - j.element_count = N; - - check("sim_guard_copy_in_too_long_refused", - be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, bigbytes, 0x1000u + 8u) != 0); - check("sim_guard_copy_in_unknown_role_refused", be->copy_in(ctx, 99, prog, sizeof prog) != 0); - check("sim_guard_copy_in_null_source_refused", - be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, NULL, sizeof prog) != 0); - check("sim_guard_fill_poison_too_long_refused", - be->fill_poison(ctx, bigwords, 0x1000u / 4u + 1u) != 0); - check("sim_guard_fill_poison_null_refused", be->fill_poison(ctx, NULL, N) != 0); - check("sim_guard_copy_out_too_long_refused", - be->copy_out(ctx, bigbytes, 0x1000u + 8u) != 0); - check("sim_guard_copy_out_null_refused", be->copy_out(ctx, NULL, N * 4u) != 0); - check("sim_guard_free_unknown_role_refused", be->free_buf(ctx, 99) != 0); - - check("sim_guard_valid_copy_in_ok", be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, prog, sizeof prog) == 0); - check("sim_guard_valid_fill_poison_ok", be->fill_poison(ctx, poison, N) == 0); - memset(bigbytes, 0, sizeof bigbytes); - check("sim_guard_valid_copy_out_returns_the_poison", - be->copy_out(ctx, bigbytes, N * 4u) == 0 && memcmp(bigbytes, poison, N * 4u) == 0); - - for (role = (int)OMEGA_GPU_BUF_ROLE_COUNT - 1; role >= 0; role--) - if (be->free_buf(ctx, role) != 0) bad = 1; - if (be->close(ctx) != 0) bad = 1; - check("sim_guard_drain_ok", bad == 0); - check("sim_guard_nothing_leaked", fk.live_at_close == 0 && fk.double_free == 0 && fk.close_calls == 1); -} - -/* A close without the SCRATCH free (a backend that is closed with its words still - * mapped) must stop reading the sync words: the memory is gone. */ -static void case_close_unmaps_sync_words(void) -{ - const OmegaGpuBackend *be = omega_blackwell_engine_backend(); - void *ctx = be->ctx; - OmegaGpuBackendDiag d; - OmegaGpuJob j; - int ok; - - begin_case(); - make_job(&j); - ok = be->open_device(ctx) == 0 && be->create_channel(ctx) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_SCRATCH, 0u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_PROGRAM, sizeof prog) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_A, N * 4u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_B, N * 4u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, N * 4u) == 0 && - be->build(ctx, &j) == 0; - check("sim_close_setup_through_the_table", ok); - memset(&d, 0, sizeof d); - be->diagnostics(ctx, &d); - check("sim_close_words_mapped_after_build", - d.sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE)); - check("sim_close_returns_zero", be->close(ctx) == 0); - memset(&d, 0, sizeof d); - be->diagnostics(ctx, &d); - check("sim_close_unmaps_every_sync_word", d.sync_valid == 0u); - check("sim_close_released_everything", fk.close_calls == 1 && fk.live == 0); -} - -/* Like begin_case, for the vector wrapper: the device must see the encoder's real - * program bytes, and no backend is installed, so the wrapper has to install its own. */ -static void begin_vec(void) -{ - begin_case(); - omega_gpu_engine_set_backend(NULL); - fk.prog_expect = vec_code; - fk.prog_len = vec_len; -} - -static void case_vector(void) -{ - OmegaVectorSpec spec; - OmegaBlackwellRealization real; - OmegaBlackwellVectorExecution info; - uint32_t c[N]; - uint32_t i; - int rc; - int ok; - uint64_t want_elapsed; - - memset(&real, 0, sizeof real); - real.sm_architecture = OMEGA_BW_SM_ARCH_121; - check("sim_vec_spec_init", omega_vector_spec_init(&spec, "engine_sim", N) == 0); - - /* success */ - begin_vec(); - memset(c, 0, sizeof c); - memset(&info, 0xff, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_success_returns_zero", rc == 0); - check("sim_vec_success_output_values", output_correct(c)); - check("sim_vec_success_parity_verified", info.parity_verified == true); - check("sim_vec_success_completion_marker_and_semaphore", - info.completion_marker == MARKER1_PAYLOAD && info.intermediate_semaphore == SEM_DONE); - check("sim_vec_success_shape_fields", - info.element_count == N && info.sm_architecture == (uint32_t)OMEGA_BW_SM_ARCH_121 && - info.target_chip[0] != '\0'); - want_elapsed = info.completion_timestamp_ns > info.launch_timestamp_ns ? - info.completion_timestamp_ns - info.launch_timestamp_ns : 0u; - check("sim_vec_success_timestamps", - info.launch_timestamp_ns != 0u && info.completion_timestamp_ns != 0u && - info.elapsed_ns == want_elapsed); - check("sim_vec_success_timeouts_are_5000_each", - fk.wait_ms[FK_W_MARKER1] == 5000u && fk.wait_ms[FK_W_MARKER2] == 5000u && - fk.wait_ms[FK_W_SEM] == 5000u); - check("sim_vec_success_all_protections_on", - fake_count(FK_EV_PB_FLUSH) == 1 && fake_count(FK_EV_PB_RELEASE) == 2 && - fk.wait_n[FK_W_MARKER2] == 1); - check("sim_vec_success_encoded_program_reached_the_device", - fk.kernel_ran == 1 && fk.prog_matched == 1); - ok = fk.snap_n == N; - for (i = 0; ok && i < N; i++) - if (fk.out_before[i] != (uint32_t)~expect_out[i]) ok = 0; - check("sim_vec_success_poison_is_the_complement_of_the_sum", ok); - check("sim_vec_success_poison_never_collides_even_for_0xdeadbeef", fk.poison_collisions == 0); - check("sim_vec_success_balanced", balanced(8)); - - /* wrong math on the device: the engine passes it (it only checks poison), the wrapper must not */ - begin_vec(); - fk.kernel_mode = FK_KERNEL_WRONG; - memset(c, 0, sizeof c); - memset(&info, 0, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_wrong_math_returns_nonzero", rc != 0); - check("sim_vec_wrong_math_parity_not_verified", info.parity_verified == false); - - /* a cleanup fault after a good run is still a failure */ - begin_vec(); - fk.free_fail_nth = 1; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_cleanup_fault_returns_nonzero", rc != 0); - - /* the device wrote nothing */ - begin_vec(); - fk.kernel_mode = FK_KERNEL_NO_WRITE; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_unwritten_output_returns_nonzero", rc != 0); - - /* a hung first marker: failure, process blocked, backend retained */ - begin_vec(); - fk.marker_mode = FK_SYNC_NEVER; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_hang_returns_nonzero", rc != 0); - check("sim_vec_hang_blocks_the_process_and_retains", - omega_gpu_engine_is_blocked() == 1 && fk.free_calls == 0 && fk.close_calls == 0); - check("sim_vec_hang_drains", drain() == 0 && fk.live_at_close == 0); - omega_gpu_engine_test_reset_block(); - - /* refusals before any driver call */ - begin_vec(); - check("sim_vec_null_spec_refused", omega_blackwell_execute_vector(NULL, &real, ina, inb, c, &info) != 0); - check("sim_vec_null_output_refused", omega_blackwell_execute_vector(&spec, &real, ina, inb, NULL, &info) != 0); - check("sim_vec_null_input_refused", omega_blackwell_execute_vector(&spec, &real, NULL, inb, c, &info) != 0); - spec.element_count = 0u; - check("sim_vec_zero_count_refused", omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info) != 0); - check("sim_vec_refusals_never_touch_the_driver", fk.open_calls == 0 && fk.alloc_calls == 0); - spec.element_count = N; - - /* the wrapper can be used again afterwards (busy flag, block, tracing table) */ - begin_vec(); - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_works_again", rc == 0 && output_correct(c)); -} - -int main(void) -{ - init_data(); - wrap_init(); - omega_gpu_engine_test_set_clock(fake_now_ms); - check("sim_setup_encoder_ok", - omega_blackwell_encode_vecadd(vec_code, sizeof vec_code, &vec_len) == 0 && vec_len > 0u); - - case_success(); - case_no_c3(); - case_back_to_back(); - case_open_fail(); - case_channel_fail(); - case_alloc_faults(); - case_alloc_own_checks(); - case_submit_fail(); - case_uncertain(); - case_cleanup_faults(); - case_unchanged(); - case_table_guards(); - case_close_unmaps_sync_words(); - case_vector(); - - omega_gpu_engine_set_backend(NULL); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_test_set_clock(NULL); - fake_reset(); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_codegen_freestanding.c b/tests/test_omega_codegen_freestanding.c deleted file mode 100644 index 47e246cdf..000000000 --- a/tests/test_omega_codegen_freestanding.c +++ /dev/null @@ -1,214 +0,0 @@ -/* test_omega_codegen_freestanding.c -- native v1 P07 cut A.2 (aienos#286, aien-architecture#190). - * - * Built twice by mk/omega-gpu-engine.mk (make test-codegen-freestanding): - * - hosted: linked against the hosted codegen/matmul objects; every fixture goes through the existing - * allocating generators (malloc'd code buffer, omega_blackwell_kernel_free); - * - freestanding (-DOMEGA_GPU_NO_POSIX): linked against the -ffreestanding objects of - * `make gpu-engine-freestanding`; every fixture goes through the *_prog generator and - * omega_blackwell_kernel_encode_into with a caller-supplied buffer, no allocator anywhere. - * `--dump` prints every fixture's instruction stream as hex; the make target requires the two dumps to be - * byte-identical (cmp). Without --dump the freestanding build also checks the bounded buffer contract - * (every short buffer refused before a byte is written, nothing written past the reported size), the - * golden-word fixture verifiers against the freestanding object, and the integer bf16 rounding path - * against the hosted __bf16 cast on all 2^32 inputs. - * Host only: opens no device. */ -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include - -typedef enum { FX_I32, FX_TENSOR, FX_LOOP, FX_FRAG, FX_BLOCK } FxKind; -typedef struct { - const char *name; - FxKind kind; - uint32_t m, k, n; - OmegaMatMulPrecision prec; - uint32_t grid_x, unroll, rt, ct; /* unroll 0 = the API's rule (omega_matmul_frag_unroll / _block_unroll) */ - int mutant; -} Fixture; - -/* The shapes the existing tests and the matmul API generate: the integer and K=16 tensor kernels of the - * gates, the looped kernel, the decode fragment kernel at Qwen3 shapes and the blocked prefill kernel. */ -static const Fixture FX[] = { - {"i32_16x16x16", FX_I32, 16, 16, 16, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"i32_32x16x64", FX_I32, 32, 16, 64, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"i32_16x32x8", FX_I32, 16, 32, 8, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"tensor_f16_16x16x8", FX_TENSOR, 16, 16, 8, OMEGA_MATMUL_PRECISION_FP16, 0, 0, 0, 0, 0}, - {"tensor_bf16_32x16x16", FX_TENSOR, 32, 16, 16, OMEGA_MATMUL_PRECISION_BF16, 0, 0, 0, 0, 0}, - {"loop_bf16_16x64x32_g2", FX_LOOP, 16, 64, 32, OMEGA_MATMUL_PRECISION_BF16, 2, 0, 0, 0, 0}, - {"loop_f16_32x128x64_g4", FX_LOOP, 32, 128, 64, OMEGA_MATMUL_PRECISION_FP16, 4, 0, 0, 0, 0}, - {"frag_k128_n64_g1", FX_FRAG, 16, 128, 64, OMEGA_MATMUL_PRECISION_BF16, 1, 0, 0, 0, 0}, - {"frag_k1024_n3072_g64", FX_FRAG, 16, 1024, 3072, OMEGA_MATMUL_PRECISION_BF16, 64, 0, 0, 0, 0}, - {"frag_k4096_n4096_g48", FX_FRAG, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 48, 0, 0, 0, 0}, - {"frag_k4096_n4096_g48_mutant", FX_FRAG, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 48, 0, 0, 0, 1}, - {"block_k256_n128_r4c2", FX_BLOCK, 16, 256, 128, OMEGA_MATMUL_PRECISION_BF16, 1, 0, 4, 2, 0}, - {"block_k1024_n3072_r2c2", FX_BLOCK, 16, 1024, 3072, OMEGA_MATMUL_PRECISION_BF16, 8, 0, 2, 2, 0}, - {"block_k4096_n4096_r4c4", FX_BLOCK, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 16, 0, 4, 4, 0}, -}; -#define NFX (sizeof FX / sizeof FX[0]) - -static uint32_t fx_unroll(const Fixture *f) { - if (f->unroll) return f->unroll; - if (f->kind == FX_BLOCK) return omega_matmul_frag_block_unroll(f->k, f->rt, f->ct); - uint32_t u = omega_matmul_frag_unroll(f->k); - if (f->mutant) while (u > 1 && f->k / 16u / u < 2) u /= 2; /* the API's mutant rule */ - return u; -} - -static int fails; -#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -#ifdef OMEGA_GPU_NO_POSIX -static BlackwellIRProgram g_prog; /* one program at a time; static keeps the stack small */ -static uint8_t g_code[OMEGA_BW_CODE_CAP_MAX + 64]; - -static int fx_prog(const Fixture *f, BlackwellIRProgram *prog) { - OmegaMatMulSpec spec; - if (omega_matmul_spec_init(&spec, f->m, f->k, f->n, f->prec) != 0) return -1; - switch (f->kind) { - case FX_I32: return omega_blackwell_codegen_matmul_i32_prog(&spec, prog); - case FX_TENSOR: return omega_blackwell_codegen_matmul_tensor_prog(&spec, prog); - case FX_LOOP: return omega_blackwell_codegen_matmul_tensor_loop_prog(&spec, f->grid_x, f->mutant, prog); - case FX_FRAG: return omega_blackwell_codegen_matmul_frag_prog(&spec, f->grid_x, fx_unroll(f), f->mutant, prog); - case FX_BLOCK: - return omega_blackwell_codegen_matmul_frag_block_prog(&spec, f->grid_x, fx_unroll(f), f->rt, f->ct, f->mutant, prog); - } - return -1; -} - -/* The cap each hosted generator always had: the i32 buffer is exactly the program, frag_block the IR maximum, - * the others 4096 bytes. The freestanding build passes the same cap so a program the hosted build refuses is - * refused here too. */ -static size_t fx_cap(const Fixture *f, const BlackwellIRProgram *prog) { - if (f->kind == FX_I32) return omega_bw_program_code_bytes(prog); - if (f->kind == FX_BLOCK) return OMEGA_BW_CODE_CAP_MAX; - return OMEGA_BW_CODE_CAP_SMALL; -} - -static int fx_kernel(const Fixture *f, OmegaBlackwellKernel *k) { - if (fx_prog(f, &g_prog) != 0) { memset(k, 0, sizeof *k); return -1; } - return omega_blackwell_kernel_encode_into(&g_prog, g_code, fx_cap(f, &g_prog), k); -} -static void fx_release(OmegaBlackwellKernel *k) { memset(k, 0, sizeof *k); } /* caller-owned buffer: nothing to free */ -#else -static int fx_kernel(const Fixture *f, OmegaBlackwellKernel *k) { - OmegaMatMulSpec spec; - memset(k, 0, sizeof *k); - if (omega_matmul_spec_init(&spec, f->m, f->k, f->n, f->prec) != 0) return -1; - switch (f->kind) { - case FX_I32: return omega_blackwell_codegen_matmul_i32(&spec, k); - case FX_TENSOR: return omega_blackwell_codegen_matmul_tensor(&spec, k); - case FX_LOOP: return omega_blackwell_codegen_matmul_tensor_loop(&spec, f->grid_x, f->mutant, k); - case FX_FRAG: return omega_blackwell_codegen_matmul_frag(&spec, f->grid_x, fx_unroll(f), f->mutant, k); - case FX_BLOCK: return omega_blackwell_codegen_matmul_frag_block(&spec, f->grid_x, fx_unroll(f), f->rt, f->ct, f->mutant, k); - } - return -1; -} -static void fx_release(OmegaBlackwellKernel *k) { omega_blackwell_kernel_free(k); } -#endif - -static int dump(void) { - for (size_t i = 0; i < NFX; i++) { - OmegaBlackwellKernel k; - int rc = fx_kernel(&FX[i], &k); - printf("fixture %s rc %d bytes %zu insns %zu gpr %u ugpr %u\n", FX[i].name, rc, k.code_size, k.insn_count, - k.gpr_count, k.uniform_gpr_count); - if (rc != 0 || !k.code || k.code_size == 0) { fails++; printf("FAIL fixture %s did not generate\n", FX[i].name); continue; } - printf("digest "); - for (int j = 0; j < 32; j++) printf("%02x", k.code_digest[j]); - printf("\n"); - for (size_t j = 0; j < k.code_size; j++) printf("%02x%s", k.code[j], (j % 32u == 31u) ? "\n" : ""); - if (k.code_size % 32u) printf("\n"); - fx_release(&k); - } - return fails ? 1 : 0; -} - -#ifdef OMEGA_GPU_NO_POSIX -static int all_bytes(const uint8_t *p, size_t n, uint8_t v) { - for (size_t i = 0; i < n; i++) if (p[i] != v) return 0; - return 1; -} - -/* The bounded-buffer contract, on every fixture's program. */ -static void buffer_contract(void) { - for (size_t i = 0; i < NFX; i++) { - const Fixture *f = &FX[i]; - OmegaBlackwellKernel k; - if (fx_prog(f, &g_prog) != 0) { CHECK(0, "%s: program", f->name); continue; } - const size_t need = omega_bw_program_code_bytes(&g_prog); - CHECK(need >= 32u * 16u && need % 128u == 0, "%s: code bytes %zu (padded to 8 instructions, at least 32)", f->name, need); - CHECK(need <= OMEGA_BW_CODE_CAP_MAX, "%s: code bytes %zu above the IR maximum", f->name, need); - - /* one byte short: refused, not a byte written, kernel zeroed */ - memset(g_code, 0xa5, sizeof g_code); - memset(&k, 0x5a, sizeof k); - int rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need - 1u, &k); - CHECK(rc == OMEGA_BW_CODE_BUFFER_TOO_SMALL, "%s: need-1 rc %d", f->name, rc); - CHECK(all_bytes(g_code, sizeof g_code, 0xa5), "%s: refused encode wrote into the buffer", f->name); - CHECK(k.code == NULL && k.code_size == 0 && k.insn_count == 0, "%s: refused encode left a kernel", f->name); - - /* zero capacity and NULL buffer refused */ - CHECK(omega_blackwell_kernel_encode_into(&g_prog, g_code, 0, &k) == OMEGA_BW_CODE_BUFFER_TOO_SMALL, "%s: cap 0", f->name); - CHECK(omega_blackwell_kernel_encode_into(&g_prog, NULL, need, &k) == -1 && k.code == NULL, "%s: NULL buffer", f->name); - CHECK(omega_blackwell_kernel_encode_into(NULL, g_code, need, &k) == -1, "%s: NULL program", f->name); - CHECK(omega_blackwell_kernel_encode_into(&g_prog, g_code, need, NULL) == -1, "%s: NULL kernel", f->name); - - /* exactly enough, and a larger buffer: same bytes, nothing written past the reported size */ - memset(g_code, 0xa5, sizeof g_code); - rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need + 64u, &k); - CHECK(rc == 0 && k.code == g_code && k.code_size == need && k.insn_count == need / 16u, - "%s: roomy encode rc %d size %zu", f->name, rc, k.code_size); - CHECK(all_bytes(g_code + need, 64u, 0xa5), "%s: encode wrote past code_size", f->name); - static uint8_t first[OMEGA_BW_CODE_CAP_MAX]; - memcpy(first, g_code, need); - uint8_t d1[32]; - memcpy(d1, k.code_digest, 32); - memset(g_code, 0, sizeof g_code); - rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need, &k); - CHECK(rc == 0 && memcmp(first, g_code, need) == 0 && memcmp(d1, k.code_digest, 32) == 0, - "%s: exact-size encode differs (rc %d)", f->name, rc); - } -} - -static void golden_fixtures(void) { - CHECK(omega_blackwell_verify_codegen_fixtures() == 0, "golden words (rc %d)", omega_blackwell_verify_codegen_fixtures()); - CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "fb1cut4 golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_intops() == 0, "intops golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_fragmm() == 0, "fragmm golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_reconv() == 0, "reconv golden words"); - CHECK(omega_blackwell_test_regalloc_bounds() == 0, "regalloc bounds"); -} - -/* The freestanding omega_fp32_to_bf16 (integer rounding) against the hosted __bf16 cast, every input. */ -static void bf16_sweep(void) { - uint64_t bad = 0; - uint32_t first_bad = 0; - for (uint64_t x = 0; x <= 0xffffffffull; x++) { - uint32_t u = (uint32_t)x; - float f; - memcpy(&f, &u, 4); - __bf16 b = (__bf16)f; - uint16_t want; - memcpy(&want, &b, 2); - if (omega_fp32_to_bf16(f) != want) { if (!bad) first_bad = u; bad++; } - } - CHECK(bad == 0, "bf16: %llu of 2^32 inputs differ from the __bf16 cast (first 0x%08x)", (unsigned long long)bad, first_bad); - if (!bad) printf("bf16 sweep: all 2^32 inputs equal the hosted __bf16 cast\n"); -} -#endif - -int main(int argc, char **argv) { - if (argc > 1 && strcmp(argv[1], "--dump") == 0) return dump(); -#ifdef OMEGA_GPU_NO_POSIX - buffer_contract(); - golden_fixtures(); - if (!(argc > 1 && strcmp(argv[1], "--no-sweep") == 0)) bf16_sweep(); - printf("%s: freestanding codegen contract (%zu fixtures, %d failing checks)\n", fails ? "FAIL" : "PASS", (size_t)NFX, fails); - return fails ? 1 : 0; -#else - fprintf(stderr, "hosted build: only --dump\n"); - return 2; -#endif -} diff --git a/tests/test_omega_gpu_code_alloc.c b/tests/test_omega_gpu_code_alloc.c deleted file mode 100644 index 00c78e9c8..000000000 --- a/tests/test_omega_gpu_code_alloc.c +++ /dev/null @@ -1,31 +0,0 @@ -/* GPU code buffer sizing (src/omega_gpu_code_alloc.h): code + 2 KB instruction prefetch tail, page rounded. - * Host only. The NO_TAIL mutant (the page-rounded size used before omega#323) must fail. */ -#include "omega_gpu_code_alloc.h" -#include -#include - -static int fails; -#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -int main(void) { - /* the two attention kernels of omega#323: 2560 B (head_dim 64) and 2688 B (head_dim 128) */ - CHECK(omega_gpu_code_alloc_bytes(2560) == 8192, "2560 B of code -> 8192 (got %zu)", omega_gpu_code_alloc_bytes(2560)); - CHECK(omega_gpu_code_alloc_bytes(2688) == 8192, "2688 B of code -> 8192 (got %zu)", omega_gpu_code_alloc_bytes(2688)); - CHECK(omega_gpu_code_alloc_bytes(2048) == 4096, "2048 B of code fits one page with the tail (got %zu)", omega_gpu_code_alloc_bytes(2048)); - CHECK(omega_gpu_code_alloc_bytes(2049) == 8192, "2049 B of code needs a second page (got %zu)", omega_gpu_code_alloc_bytes(2049)); - CHECK(omega_gpu_code_alloc_bytes(0) == 4096, "empty code -> one page (got %zu)", omega_gpu_code_alloc_bytes(0)); - CHECK(omega_gpu_code_alloc_bytes(0x4000) == 0x5000, "16 KB capacity -> 20 KB (got %zu)", omega_gpu_code_alloc_bytes(0x4000)); - CHECK(omega_gpu_code_alloc_bytes(SIZE_MAX) == 0, "overflow refused"); - CHECK(omega_gpu_code_alloc_bytes(SIZE_MAX - 2048) == 0, "overflow near the limit refused"); - /* every size: at least 2 KB mapped after the code, page multiple, no more than one extra page */ - for (size_t n = 1; n <= 64 * 1024; n += 16) { - size_t b = omega_gpu_code_alloc_bytes(n); - if (b < n + OMEGA_GPU_CODE_PREFETCH_TAIL || b % OMEGA_GPU_CODE_PAGE != 0 || b > n + OMEGA_GPU_CODE_PREFETCH_TAIL + OMEGA_GPU_CODE_PAGE) { - CHECK(0, "%zu B of code -> %zu B (needs >= code + 2048, page multiple)", n, b); - break; - } - } - if (fails) { printf("OMEGA_GPU_CODE_ALLOC FAIL (%d)\n", fails); return 1; } - printf("OMEGA_GPU_CODE_ALLOC PASS\n"); - return 0; -} diff --git a/tests/test_omega_gpu_engine.c b/tests/test_omega_gpu_engine.c deleted file mode 100644 index 254c7ee04..000000000 --- a/tests/test_omega_gpu_engine.c +++ /dev/null @@ -1,1155 +0,0 @@ -/* - * Host test of the Omega GPU Engine core (A3a) against a FAKE backend. - * No device, no physics headers. Every case prints "[PASS] id" or "[FAIL] id"; - * the last line is "SUMMARY passed=N failed=M"; exit status is nonzero on any - * failure. docs/numeric/OMEGA_GPU_ENGINE.md section 13 lists every case id. - * - * The fake records every backend call in order, can fail the n-th call of any - * kind with a chosen return code (and advance a fake clock), simulates device - * memory (poison fill, a kernel that writes a chosen word range, copy-in and - * copy-out) and flags protocol violations (free of a buffer that is not - * allocated, copy-in to an unallocated buffer, and so on). - */ -#include "omega_gpu_engine.h" - -#include -#include -#include - -#define N 16u -#define INJ_ERRNO EIO -#ifdef OMEGA_GPU_NO_POSIX -#define EXPECT_ERRNO 0 /* the freestanding engine (make test-gpu-engine-freestanding) records no errno */ -#else -#define EXPECT_ERRNO INJ_ERRNO -#endif -#define DIAG_RC (-1234) -#define DIAG_TEXT "fake driver text" -#define LOGMAX 64 -#define TMO_MARKER 111u -#define TMO_MARKER2 222u -#define TMO_RELEASE 333u -#define TMO_VISIBILITY 444u - -enum { - C_OPEN = 0, C_CHANNEL, C_ALLOC, C_COPY_IN, C_POISON, C_BUILD, C_SUBMIT, C_MARKER, - C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, C_FREE, C_CLOSE, C_DIAG, C_COUNT -}; - -typedef struct { - int call; /* which kind of call to fail */ - int nth; /* 1-based occurrence of that kind */ - int rc; /* value the call returns */ - int advance; /* fake milliseconds the call takes */ -} Inj; - -typedef struct { - int log[LOGMAX]; /* every call except diagnostics, in order */ - int nlog; - int count[C_COUNT]; - int state_at[C_COUNT]; /* result->last_state at the first call of each kind, -1 if never */ - uint64_t tmo[C_COUNT]; /* timeout last passed to a timed call */ - Inj inj[2]; - int ninj; - int violations; - int dev_open; - int channel; - int live[OMEGA_GPU_BUF_ROLE_COUNT]; - int alloc_roles[8]; - size_t alloc_bytes[8]; - int nalloc; - int copy_roles[8]; - size_t copy_bytes[8]; - int ncopy; - int free_roles[8]; - int nfree; - uint32_t dev_prog[16]; - uint32_t dev_a[N]; - uint32_t dev_b[N]; - uint32_t dev_out[N]; - uint32_t seen_at_submit[N]; - int submit_seen; - const OmegaGpuJob *build_job; - size_t klo; /* the fake kernel writes output words [klo, khi) */ - size_t khi; -} Fake; - -static Fake F; -static OmegaGpuResult *g_res; /* result being filled, to snapshot last_state at each call */ -static uint64_t g_time; /* fake clock, milliseconds */ -static OmegaGpuBackend BE; - -static const unsigned char code[8] = {1, 2, 3, 4, 5, 6, 7, 8}; -static uint32_t ina[N]; -static uint32_t inb[N]; -static uint32_t poison[N]; -static uint32_t host_out[N + 4u]; /* four spare words so a stray write is visible, not fatal */ - -static int case_ok; -static int n_pass; -static int n_fail; - -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -static void case_begin(void) { case_ok = 1; } - -static void case_end(const char *id) -{ - if (case_ok) { n_pass++; printf("[PASS] %s\n", id); } - else { n_fail++; printf("[FAIL] %s\n", id); } -} - -static uint64_t fake_now(void) { return g_time; } - -static uint32_t exp_out(size_t i) { return ina[i] + inb[i] + 0x100u; } - -/* ---- the fake backend ---------------------------------------------------- */ - -static int hit(int call) -{ - int i; - int n; - if (F.nlog < LOGMAX) F.log[F.nlog] = call; - F.nlog++; - n = ++F.count[call]; - if (F.state_at[call] < 0 && g_res) F.state_at[call] = g_res->last_state; - for (i = 0; i < F.ninj; i++) { - if (F.inj[i].call == call && F.inj[i].nth == n) { - g_time += (uint64_t)F.inj[i].advance; - errno = INJ_ERRNO; - return F.inj[i].rc; - } - } - return 0; -} - -static int f_open(void *c) -{ - int rc; - (void)c; - rc = hit(C_OPEN); - if (rc == 0) F.dev_open = 1; - return rc; -} - -static int f_channel(void *c) -{ - int rc; - (void)c; - rc = hit(C_CHANNEL); - if (rc != 0) return rc; - if (!F.dev_open) F.violations++; - F.channel = 1; - return 0; -} - -static int role_ok(int role) -{ - return role >= 0 && role < (int)OMEGA_GPU_BUF_ROLE_COUNT; -} - -static int f_alloc(void *c, int role, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_ALLOC); - if (rc != 0) return rc; - if (!role_ok(role) || F.live[role] || !F.channel) { F.violations++; return 0; } - F.live[role] = 1; - if (F.nalloc < 8) { F.alloc_roles[F.nalloc] = role; F.alloc_bytes[F.nalloc] = bytes; } - F.nalloc++; - return 0; -} - -static int f_copy_in(void *c, int role, const void *src, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_COPY_IN); - if (rc != 0) return rc; - if (!role_ok(role) || !F.live[role]) { F.violations++; return 0; } - if (F.ncopy < 8) { F.copy_roles[F.ncopy] = role; F.copy_bytes[F.ncopy] = bytes; } - F.ncopy++; - switch (role) { - case OMEGA_GPU_BUF_PROGRAM: - if (bytes > sizeof F.dev_prog) { F.violations++; break; } - memcpy(F.dev_prog, src, bytes); - break; - case OMEGA_GPU_BUF_INPUT_A: - if (bytes > sizeof F.dev_a) { F.violations++; break; } - memcpy(F.dev_a, src, bytes); - break; - case OMEGA_GPU_BUF_INPUT_B: - if (bytes > sizeof F.dev_b) { F.violations++; break; } - memcpy(F.dev_b, src, bytes); - break; - default: - F.violations++; - break; - } - return 0; -} - -static int f_poison(void *c, const uint32_t *words, size_t count) -{ - int rc; - (void)c; - rc = hit(C_POISON); - if (rc != 0) return rc; - if (!F.live[OMEGA_GPU_BUF_OUTPUT] || count != N) { F.violations++; return 0; } - memcpy(F.dev_out, words, count * sizeof(uint32_t)); - return 0; -} - -static int f_build(void *c, const OmegaGpuJob *job) -{ - int rc; - (void)c; - rc = hit(C_BUILD); - if (rc != 0) return rc; - F.build_job = job; - return 0; -} - -static int f_submit(void *c) -{ - int rc; - size_t i; - (void)c; - rc = hit(C_SUBMIT); - if (rc != 0) return rc; - memcpy(F.seen_at_submit, F.dev_out, sizeof F.dev_out); - F.submit_seen = 1; - for (i = F.klo; i < F.khi && i < N; i++) F.dev_out[i] = F.dev_a[i] + F.dev_b[i] + 0x100u; - return 0; -} - -static int f_wait_marker(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_MARKER] = ms; - return hit(C_MARKER); -} - -static int f_wait_marker2(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_MARKER2] = ms; - return hit(C_MARKER2); -} - -static int f_wait_release(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_RELEASE] = ms; - return hit(C_RELEASE); -} - -static int f_barrier(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_BARRIER] = ms; - return hit(C_BARRIER); -} - -static int f_copy_out(void *c, void *dst, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_COPY_OUT); - if (rc != 0) return rc; - if (bytes != sizeof F.dev_out) { F.violations++; return 0; } - memcpy(dst, F.dev_out, bytes); - return 0; -} - -static void f_diag(void *c, OmegaGpuBackendDiag *d) -{ - (void)c; - F.count[C_DIAG]++; - d->drv_rc = DIAG_RC; - memcpy(d->drv_text, DIAG_TEXT, sizeof DIAG_TEXT); - d->sync_valid = OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE; - d->marker = 0x11111111u; - d->marker2 = 0x22222222u; - d->semaphore[0] = 0x33333333u; - errno = 0; /* a diagnostics call that clobbers errno must not matter */ -} - -static int f_free(void *c, int role) -{ - int rc; - (void)c; - rc = hit(C_FREE); - if (F.nfree < 8) F.free_roles[F.nfree] = role; - F.nfree++; - if (rc != 0) return rc; - if (!role_ok(role) || !F.live[role]) { F.violations++; return 0; } - F.live[role] = 0; - return 0; -} - -static int f_close(void *c) -{ - int rc; - (void)c; - rc = hit(C_CLOSE); - if (rc != 0) return rc; - if (!F.dev_open) F.violations++; - F.dev_open = 0; - F.channel = 0; - return 0; -} - -static void backend_init(OmegaGpuBackend *b) -{ - memset(b, 0, sizeof *b); - b->ctx = NULL; - b->open_device = f_open; - b->create_channel = f_channel; - b->alloc = f_alloc; - b->copy_in = f_copy_in; - b->fill_poison = f_poison; - b->build = f_build; - b->submit = f_submit; - b->wait_marker = f_wait_marker; - b->wait_marker2 = f_wait_marker2; - b->wait_release_semaphore = f_wait_release; - b->barrier = f_barrier; - b->copy_out = f_copy_out; - b->diagnostics = f_diag; - b->free_buf = f_free; - b->close = f_close; -} - -/* ---- case helpers ------------------------------------------------------- */ - -static void reset_all(void) -{ - size_t i; - int k; - memset(&F, 0, sizeof F); - for (k = 0; k < C_COUNT; k++) F.state_at[k] = -1; - for (i = 0; i < N; i++) F.dev_out[i] = 0xA5A5A5A5u; /* garbage, never a poison word */ - F.klo = 0; - F.khi = N; - g_time = 1000u; - memset(host_out, 0xCC, sizeof host_out); - g_res = NULL; - backend_init(&BE); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_set_backend(&BE); -} - -static void make_job(OmegaGpuJob *j) -{ - size_t i; - for (i = 0; i < N; i++) { - ina[i] = (uint32_t)(i + 1u); - inb[i] = (uint32_t)(2u * i + 3u); - poison[i] = 0xDEAD0000u + (uint32_t)(i * 7u); /* distinct per word, never an expected output */ - } - memset(j, 0, sizeof *j); - j->program = code; - j->program_len = sizeof code; - j->layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j->element_count = N; - j->input_a = ina; - j->input_a_len = sizeof ina; - j->input_b = inb; - j->input_b_len = sizeof inb; - j->output = host_out; - j->output_len = N * sizeof(uint32_t); - j->poison = poison; - j->poison_count = N; - j->timeouts.marker_ms = TMO_MARKER; - j->timeouts.marker2_ms = TMO_MARKER2; - j->timeouts.release_semaphore_ms = TMO_RELEASE; - j->timeouts.visibility_ms = TMO_VISIBILITY; - j->flags = 0; -} - -static void inject(int call, int nth, int rc, int advance) -{ - F.inj[F.ninj].call = call; - F.inj[F.ninj].nth = nth; - F.inj[F.ninj].rc = rc; - F.inj[F.ninj].advance = advance; - F.ninj++; -} - -static int run(const OmegaGpuJob *job, OmegaGpuResult *r) -{ - int rc; - memset(r, 0x7f, sizeof *r); /* stale garbage the engine must fully overwrite */ - g_res = r; - rc = omega_gpu_execute(job, r); - g_res = NULL; - return rc; -} - -static void expect_log(const int *want, int n) -{ - int i; - EXPECT(F.nlog == n); - for (i = 0; i < n && i < F.nlog && i < LOGMAX; i++) EXPECT(F.log[i] == want[i]); -} - -static void expect_failure(int rc, const OmegaGpuResult *r, int failure, int last, int step, int wait) -{ - EXPECT(rc == failure); - EXPECT(r->failure == failure); - EXPECT(r->last_state == last); - EXPECT(r->failed_step == step); - EXPECT(r->wait == wait); -} - -static void expect_passthrough(const OmegaGpuResult *r, int err) -{ - EXPECT(r->drv_rc == DIAG_RC); - EXPECT(r->err_no == err); - EXPECT(strcmp(r->drv_text, DIAG_TEXT) == 0); - EXPECT(r->sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE)); - EXPECT(r->marker == 0x11111111u); - EXPECT(r->marker2 == 0x22222222u); - EXPECT(r->semaphore[0] == 0x33333333u); - EXPECT(F.count[C_DIAG] == 1); -} - -/* Device closed, every buffer freed, nothing broke the fake's protocol, no block. */ -static void expect_released(const OmegaGpuResult *r) -{ - int role; - EXPECT(F.dev_open == 0); - for (role = 0; role < (int)OMEGA_GPU_BUF_ROLE_COUNT; role++) EXPECT(F.live[role] == 0); - EXPECT(F.violations == 0); - EXPECT(omega_gpu_engine_is_blocked() == 0); - EXPECT(r->retained == 0); -} - -/* Uncertain completion: nothing freed or closed, everything retained, process blocked. */ -static void expect_retained(const OmegaGpuResult *r) -{ - int role; - EXPECT(r->retained == 1); - EXPECT(r->cleanup_failed == 0); - EXPECT(F.count[C_FREE] == 0); - EXPECT(F.count[C_CLOSE] == 0); - EXPECT(F.dev_open == 1); - for (role = 0; role < (int)OMEGA_GPU_BUF_ROLE_COUNT; role++) EXPECT(F.live[role] == 1); - EXPECT(F.violations == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); -} - -static void expect_no_host_output(void) -{ - size_t i; - for (i = 0; i < N; i++) EXPECT(host_out[i] == 0xCCCCCCCCu); -} - -#define PRE_SUBMIT C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, \ - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, C_BUILD, C_SUBMIT -#define FREE5 C_FREE, C_FREE, C_FREE, C_FREE, C_FREE -#define LOGLEN(a) ((int)(sizeof (a) / sizeof (a)[0])) - -/* ---- cases -------------------------------------------------------------- */ - -static void case_success(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - - reset_all(); - make_job(&job); - rc = run(&job, &r); - - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.failure == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(r.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - EXPECT(r.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.wait_timeout_ms == 0 && r.waited_ms == 0); - EXPECT(r.drv_rc == 0 && r.err_no == 0 && r.drv_text[0] == '\0'); - EXPECT(r.sync_valid == 0 && r.marker == 0 && r.marker2 == 0 && r.semaphore[0] == 0); - EXPECT(r.retained == 0 && r.cleanup_failed == 0); - EXPECT(r.n_outputs == 1u); - EXPECT(r.output_unchanged_words[0] == 0); - for (i = 0; i < N; i++) EXPECT(host_out[i] == exp_out(i)); - for (i = N; i < N + 4u; i++) EXPECT(host_out[i] == 0xCCCCCCCCu); - EXPECT(F.count[C_DIAG] == 0); - expect_released(&r); - case_end("SUCCESS_FULL_RUN"); - - case_begin(); - expect_log(want, LOGLEN(want)); - case_end("CALL_ORDER_FULL_RUN"); - - case_begin(); - EXPECT(F.state_at[C_OPEN] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_POISON] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_BUILD] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_SUBMIT] == OMEGA_GPU_ENGINE_STATE_PREPARED); - EXPECT(F.state_at[C_MARKER] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_MARKER2] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_RELEASE] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_BARRIER] == OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE); - EXPECT(F.state_at[C_COPY_OUT] == OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE); - EXPECT(F.state_at[C_FREE] == OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED); - EXPECT(F.state_at[C_CLOSE] == OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED); - case_end("STATE_ADVANCES_STEP_BY_STEP"); - - case_begin(); - EXPECT(F.nalloc == 5); - for (i = 0; i < 5u; i++) EXPECT(F.alloc_roles[i] == (int)i); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_SCRATCH] == 0u); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_PROGRAM] == sizeof code); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_INPUT_A] == sizeof ina); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_INPUT_B] == sizeof inb); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_OUTPUT] == N * sizeof(uint32_t)); - EXPECT(F.ncopy == 3); - EXPECT(F.copy_roles[0] == OMEGA_GPU_BUF_PROGRAM && F.copy_bytes[0] == sizeof code); - EXPECT(F.copy_roles[1] == OMEGA_GPU_BUF_INPUT_A && F.copy_bytes[1] == sizeof ina); - EXPECT(F.copy_roles[2] == OMEGA_GPU_BUF_INPUT_B && F.copy_bytes[2] == sizeof inb); - EXPECT(memcmp(F.dev_prog, code, sizeof code) == 0); - EXPECT(F.build_job == &job); - EXPECT(F.nfree == 5); - EXPECT(F.free_roles[0] == OMEGA_GPU_BUF_OUTPUT); - EXPECT(F.free_roles[1] == OMEGA_GPU_BUF_INPUT_B); - EXPECT(F.free_roles[2] == OMEGA_GPU_BUF_INPUT_A); - EXPECT(F.free_roles[3] == OMEGA_GPU_BUF_PROGRAM); - EXPECT(F.free_roles[4] == OMEGA_GPU_BUF_SCRATCH); - case_end("ROLES_BYTES_AND_REVERSE_FREE_ORDER"); - - case_begin(); - EXPECT(F.tmo[C_MARKER] == TMO_MARKER); - EXPECT(F.tmo[C_MARKER2] == TMO_MARKER2); - EXPECT(F.tmo[C_RELEASE] == TMO_RELEASE); - EXPECT(F.tmo[C_BARRIER] == TMO_VISIBILITY); - case_end("PER_STEP_TIMEOUTS_FROM_JOB"); - - case_begin(); - EXPECT(F.submit_seen == 1); - EXPECT(memcmp(F.seen_at_submit, poison, sizeof poison) == 0); - case_end("POISON_WRITTEN_BEFORE_SUBMIT"); -} - -static void case_no_c3(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - static const int want[] = { PRE_SUBMIT, C_MARKER, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - - reset_all(); - make_job(&job); - job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; - job.timeouts.marker2_ms = 0; /* ignored with NO_C3 */ - rc = run(&job, &r); - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(F.count[C_MARKER2] == 0); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("NO_C3_SKIPS_MARKER2_ONLY"); -} - -static void case_open_channel_alloc_prepare(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - { - static const int want[] = { C_OPEN }; - reset_all(); make_job(&job); - inject(C_OPEN, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_DEVICE_OPEN, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_DEVICE_OPEN"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_CHANNEL, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CHANNEL_CREATE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_CHANNEL_CREATE"); - } - { - /* the third allocation (input A) fails: scratch and program are freed, newest first */ - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_FREE, C_FREE, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_ALLOC, 3, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_ALLOC, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - EXPECT(F.nfree == 2); - EXPECT(F.free_roles[0] == OMEGA_GPU_BUF_PROGRAM && F.free_roles[1] == OMEGA_GPU_BUF_SCRATCH); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_ALLOC"); - } - { - /* the second copy-in (input A) fails */ - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_COPY_IN, 2, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_COPY_IN, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_COPY_IN"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_POISON, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_FILL_POISON, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_FILL_POISON"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, C_BUILD, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_BUILD, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_BUILD, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_BUILD"); - } -} - -static void case_submit_and_visibility(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - { - static const int want[] = { PRE_SUBMIT, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_SUBMIT, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED, - OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - EXPECT(F.submit_seen == 0); - expect_released(&r); /* SUBMIT is a known failure: cleaned up, not blocked */ - expect_no_host_output(); - case_end("FAIL_SUBMIT_IS_NOT_UNCERTAIN"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_BARRIER, 1, OMEGA_GPU_BACKEND_TIMEOUT, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE, - OMEGA_GPU_ENGINE_STEP_BARRIER, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); /* completion is known: cleaned up, not blocked */ - expect_no_host_output(); - case_end("FAIL_VISIBILITY_BARRIER"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_COPY_OUT, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE, - OMEGA_GPU_ENGINE_STEP_COPY_OUT, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_VISIBILITY_COPY_OUT"); - } -} - -static void case_uncertain(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - OmegaGpuResult r2; - int rc; - int nlog_before; - int k; - - { - static const int want[] = { PRE_SUBMIT, C_MARKER }; - reset_all(); make_job(&job); - inject(C_MARKER, 1, OMEGA_GPU_BACKEND_TIMEOUT, 4321); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, OMEGA_GPU_ENGINE_WAIT_MARKER); - EXPECT(r.wait_timeout_ms == TMO_MARKER); - EXPECT(r.waited_ms == 4321u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - expect_no_host_output(); - case_end("UNCERTAIN_MARKER_TIMEOUT"); - - /* the next job in this process is refused with no backend call */ - nlog_before = F.nlog; - k = F.count[C_DIAG]; - rc = run(&job, &r2); - case_begin(); - expect_failure(rc, &r2, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, - OMEGA_GPU_ENGINE_STATE_INITIAL, OMEGA_GPU_ENGINE_STEP_BLOCKED, - OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == nlog_before); - EXPECT(F.count[C_DIAG] == k); - EXPECT(r2.retained == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); - case_end("UNCERTAIN_BLOCKS_NEXT_JOB_NO_BACKEND_CALL"); - - /* test reset clears it; a fresh fake then runs a good job */ - omega_gpu_engine_test_reset_block(); - case_begin(); - EXPECT(omega_gpu_engine_is_blocked() == 0); - reset_all(); - rc = run(&job, &r2); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r2.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - case_end("UNCERTAIN_TEST_RESET_CLEARS_BLOCK"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2 }; - reset_all(); make_job(&job); - inject(C_MARKER2, 1, OMEGA_GPU_BACKEND_UNKNOWN_STATE, 2500); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, OMEGA_GPU_ENGINE_WAIT_MARKER2); - EXPECT(r.wait_timeout_ms == TMO_MARKER2); - EXPECT(r.waited_ms == 2500u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - case_end("UNCERTAIN_MARKER2_UNKNOWN_STATE"); - omega_gpu_engine_test_reset_block(); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE }; - reset_all(); make_job(&job); - inject(C_RELEASE, 1, -5, 777); /* a driver fault, not a timeout */ - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE); - EXPECT(r.wait_timeout_ms == TMO_RELEASE); - EXPECT(r.waited_ms == 777u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - case_end("UNCERTAIN_RELEASE_DRIVER_FAULT"); - omega_gpu_engine_test_reset_block(); - } -} - -static void case_unchanged(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - - /* the fake kernel writes nothing: all 16 words are still poison */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.n_outputs == 1u); - EXPECT(r.output_unchanged_words[0] == 16u); - EXPECT(r.err_no == 0); - EXPECT(r.drv_rc == DIAG_RC); /* observed words are kept on every failure */ - EXPECT(F.count[C_DIAG] == 1); - for (i = 0; i < N; i++) EXPECT(host_out[i] == poison[i]); - expect_released(&r); - case_end("UNCHANGED_NOTHING_WRITTEN"); - - /* only words 4..9 are written: 10 words are still poison */ - reset_all(); make_job(&job); - F.klo = 4; F.khi = 10; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 10u); - for (i = 0; i < N; i++) EXPECT(host_out[i] == ((i >= 4u && i < 10u) ? exp_out(i) : poison[i])); - expect_released(&r); - case_end("UNCHANGED_PARTIAL_EXACT_COUNT"); - - /* all but the last word written: exactly 1 */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = N - 1u; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 1u); - EXPECT(host_out[N - 1u] == poison[N - 1u]); - expect_released(&r); - case_end("UNCHANGED_LAST_WORD_ONLY"); - - /* only the first word is unwritten: exactly 1 */ - reset_all(); make_job(&job); - F.klo = 1; F.khi = N; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 1u); - EXPECT(host_out[0] == poison[0]); - expect_released(&r); - case_end("UNCHANGED_FIRST_WORD_ONLY"); - - /* the fake kernel writes everything: SUCCESS and a zero count */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = N; - rc = run(&job, &r); - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(r.n_outputs == 1u && r.output_unchanged_words[0] == 0u); - case_end("UNCHANGED_ALL_WRITTEN_IS_SUCCESS"); - - /* a silent kernel is only caught because the engine wrote the poison to the - * device output before submit (the fake device starts with other garbage). */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - rc = run(&job, &r); - case_begin(); - EXPECT(memcmp(F.seen_at_submit, poison, sizeof poison) == 0); - EXPECT(rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED); - case_end("UNCHANGED_NEEDS_POISON_FILL"); -} - -static void case_cleanup_faults(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - - /* free fails on the 2nd free after an otherwise good run: the rest still run */ - reset_all(); make_job(&job); - inject(C_FREE, 2, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_FREE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(r.retained == 0); - expect_passthrough(&r, EXPECT_ERRNO); - EXPECT(F.count[C_FREE] == 5); - EXPECT(F.count[C_CLOSE] == 1); - for (i = 0; i < N; i++) EXPECT(host_out[i] == exp_out(i)); - EXPECT(omega_gpu_engine_is_blocked() == 0); - case_end("CLEANUP_FREE_FAILS_AFTER_GOOD_RUN"); - - reset_all(); make_job(&job); - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_CLOSE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - expect_passthrough(&r, EXPECT_ERRNO); - EXPECT(F.count[C_FREE] == 5); - EXPECT(omega_gpu_engine_is_blocked() == 0); - case_end("CLEANUP_CLOSE_FAILS_AFTER_GOOD_RUN"); - - /* a free fault and then a close fault: the first (FREE) is kept */ - reset_all(); make_job(&job); - inject(C_FREE, 1, -9, 0); - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_FREE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(F.count[C_DIAG] == 1); - case_end("CLEANUP_FIRST_CLEANUP_FAULT_KEPT"); - - /* an earlier failure (submit) then a free fault: the first failure is kept */ - reset_all(); make_job(&job); - inject(C_SUBMIT, 1, -3, 0); - inject(C_FREE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED, - OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(F.count[C_FREE] == 5); - EXPECT(F.count[C_CLOSE] == 1); - EXPECT(F.count[C_DIAG] == 1); - expect_passthrough(&r, EXPECT_ERRNO); - case_end("CLEANUP_FAULT_NEVER_OVERWRITES_FIRST_FAILURE"); - - /* unchanged output plus a close fault: still OUTPUT_UNCHANGED */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(r.output_unchanged_words[0] == 16u); - case_end("CLEANUP_FAULT_AFTER_UNCHANGED_KEEPS_UNCHANGED"); -} - -#define EXPECT_INVALID(edit) do { \ - OmegaGpuJob bj; \ - OmegaGpuResult br; \ - int brc; \ - reset_all(); make_job(&bj); \ - edit; \ - brc = run(&bj, &br); \ - expect_failure(brc, &br, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STATE_INITIAL, \ - OMEGA_GPU_ENGINE_STEP_VALIDATE, OMEGA_GPU_ENGINE_WAIT_NONE); \ - EXPECT(F.nlog == 0 && F.count[C_DIAG] == 0); \ - EXPECT(br.drv_rc == 0 && br.err_no == 0 && br.retained == 0 && br.n_outputs == 0u); \ - EXPECT(omega_gpu_engine_is_blocked() == 0); \ - } while (0) - -static void case_invalid_args(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - case_begin(); - EXPECT_INVALID(bj.program = NULL); - EXPECT_INVALID(bj.program_len = 0); - case_end("INVALID_ARGS_PROGRAM"); - - case_begin(); - EXPECT_INVALID(bj.layout = OMEGA_GPU_LAYOUT_COUNT); - case_end("INVALID_ARGS_LAYOUT"); - - case_begin(); - /* zero elements with every length zeroed too: only the zero-count check rejects this */ - EXPECT_INVALID(bj.element_count = 0; bj.input_a_len = 0; bj.input_b_len = 0; bj.output_len = 0; bj.poison_count = 0); - EXPECT_INVALID(bj.element_count = 0); - case_end("INVALID_ARGS_ZERO_ELEMENTS"); - - case_begin(); - EXPECT_INVALID(bj.input_a = NULL); - EXPECT_INVALID(bj.input_a_len = sizeof ina - 4u); - EXPECT_INVALID(bj.input_b = NULL); - EXPECT_INVALID(bj.input_b_len = sizeof inb + 4u); - EXPECT_INVALID(bj.output = NULL); - EXPECT_INVALID(bj.output_len = N * sizeof(uint32_t) - 4u); - case_end("INVALID_ARGS_BUFFERS"); - - case_begin(); - EXPECT_INVALID(bj.output = (unsigned char *)host_out + 1); - case_end("INVALID_ARGS_OUTPUT_ALIGNMENT"); - - case_begin(); - EXPECT_INVALID(bj.poison = NULL); - EXPECT_INVALID(bj.poison_count = N - 1u); - EXPECT_INVALID(bj.poison_count = N + 1u); - case_end("INVALID_ARGS_POISON"); - - case_begin(); - EXPECT_INVALID(bj.flags = 0x2u); - case_end("INVALID_ARGS_UNKNOWN_FLAG"); - - case_begin(); - EXPECT_INVALID(bj.timeouts.marker_ms = 0); - case_end("INVALID_ARGS_ZERO_MARKER_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.release_semaphore_ms = 0); - case_end("INVALID_ARGS_ZERO_RELEASE_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.visibility_ms = 0); - case_end("INVALID_ARGS_ZERO_VISIBILITY_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.marker2_ms = 0); /* C3 on: marker2 needs a timeout */ - case_end("INVALID_ARGS_ZERO_MARKER2_TIMEOUT_WITH_C3"); - - case_begin(); - reset_all(); - memset(&r, 0x7f, sizeof r); - rc = omega_gpu_execute(NULL, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_INVALID_ARGS); - EXPECT(r.failure == OMEGA_GPU_ENGINE_INVALID_ARGS && r.failed_step == OMEGA_GPU_ENGINE_STEP_VALIDATE); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.nlog == 0); - case_end("INVALID_ARGS_NULL_JOB"); - - case_begin(); - reset_all(); make_job(&job); - rc = omega_gpu_execute(&job, NULL); - EXPECT(rc == OMEGA_GPU_ENGINE_INVALID_ARGS); - EXPECT(F.nlog == 0); - case_end("INVALID_ARGS_NULL_RESULT"); -} - -static void case_block_and_backend(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - static OmegaGpuBackend be2; /* static: it stays the default backend until main clears it */ - int rc; - - /* forced block refuses even a malformed or NULL job, with no backend call */ - reset_all(); make_job(&job); - omega_gpu_engine_test_force_block(); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, - OMEGA_GPU_ENGINE_STATE_INITIAL, OMEGA_GPU_ENGINE_STEP_BLOCKED, - OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - job.element_count = 0; - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - memset(&r, 0x7f, sizeof r); - rc = omega_gpu_execute(NULL, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - EXPECT(F.nlog == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); - case_end("BLOCKED_REFUSES_BEFORE_ANY_CHECK_OR_CALL"); - - omega_gpu_engine_test_reset_block(); - case_begin(); - EXPECT(omega_gpu_engine_is_blocked() == 0); - make_job(&job); - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - case_end("BLOCK_RESET_ALLOWS_JOBS_AGAIN"); - - /* no backend set: the defined stub result */ - reset_all(); make_job(&job); - omega_gpu_engine_set_backend(NULL); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - case_end("NO_BACKEND_NOT_IMPLEMENTED"); - - /* an incomplete backend table is refused before any call: each callback in turn */ - case_begin(); -#define EXPECT_INCOMPLETE(field) do { \ - reset_all(); make_job(&job); \ - be2 = BE; be2.field = NULL; \ - omega_gpu_engine_set_backend(&be2); \ - rc = run(&job, &r); \ - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, \ - OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK, OMEGA_GPU_ENGINE_WAIT_NONE); \ - EXPECT(F.nlog == 0); \ - } while (0) - EXPECT_INCOMPLETE(open_device); - EXPECT_INCOMPLETE(create_channel); - EXPECT_INCOMPLETE(alloc); - EXPECT_INCOMPLETE(copy_in); - EXPECT_INCOMPLETE(fill_poison); - EXPECT_INCOMPLETE(build); - EXPECT_INCOMPLETE(submit); - EXPECT_INCOMPLETE(wait_marker); - EXPECT_INCOMPLETE(wait_marker2); - EXPECT_INCOMPLETE(wait_release_semaphore); - EXPECT_INCOMPLETE(barrier); - EXPECT_INCOMPLETE(copy_out); - EXPECT_INCOMPLETE(diagnostics); - EXPECT_INCOMPLETE(free_buf); - EXPECT_INCOMPLETE(close); - case_end("BACKEND_TABLE_INCOMPLETE_REFUSED"); -} - -#ifdef OMEGA_GPU_NO_POSIX -/* Freestanding engine only: with no platform clock installed every job is - * refused before any backend call; installing one through the production - * setter makes the same job run. */ -static void case_platform_clock(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - reset_all(); make_job(&job); - omega_gpu_engine_set_clock(NULL); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_CLOCK_CHECK, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - EXPECT(strcmp(omega_gpu_engine_step_name(r.failed_step), "CLOCK_CHECK") == 0); - omega_gpu_engine_set_clock(fake_now); - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(F.nlog > 0); - case_end("FREESTANDING_NO_CLOCK_REFUSED_BEFORE_ANY_CALL"); -} -#endif - -int main(void) -{ - omega_gpu_engine_test_set_clock(fake_now); - - case_success(); - case_no_c3(); - case_open_channel_alloc_prepare(); - case_submit_and_visibility(); - case_uncertain(); - case_unchanged(); - case_cleanup_faults(); - case_invalid_args(); - case_block_and_backend(); -#ifdef OMEGA_GPU_NO_POSIX - case_platform_clock(); -#endif - - omega_gpu_engine_set_backend(NULL); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_test_set_clock(NULL); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_engine_compile.c b/tests/test_omega_gpu_engine_compile.c deleted file mode 100644 index 70245c3e2..000000000 --- a/tests/test_omega_gpu_engine_compile.c +++ /dev/null @@ -1,166 +0,0 @@ -/* Omega GPU Engine compile check: the header and the A3a core compile, every enum name - * is distinct, argument and backend-table refusals return their defined results, the - * uncertain-completion block functions behave as specified, and a no-op backend reaches - * SUCCESS. */ -#include "omega_gpu_engine.h" -#include -#include - -static int bad; -#define CHECK(c) do { if (!(c)) { printf("[FAIL] line %d: %s\n", __LINE__, #c); bad++; } } while (0) - -static int f_ctx(void *c) { (void)c; return 0; } -static int f_alloc(void *c, int r, size_t n) { (void)c; (void)r; (void)n; return 0; } -static int f_in(void *c, int r, const void *s, size_t n) { (void)c; (void)r; (void)s; (void)n; return 0; } -static int f_poison(void *c, const uint32_t *w, size_t n) { (void)c; (void)w; (void)n; return 0; } -static int f_build(void *c, const OmegaGpuJob *j) { (void)c; (void)j; return 0; } -static int f_wait(void *c, uint64_t ms) { (void)c; (void)ms; return 0; } -static int f_out(void *c, void *d, size_t n) { (void)c; (void)d; (void)n; return 0; } -static void f_diag(void *c, OmegaGpuBackendDiag *d) { (void)c; (void)d; } -static int f_free(void *c, int r) { (void)c; (void)r; return 0; } - -static int all_distinct(const char *(*name)(int), int count) -{ - for (int i = 0; i < count; i++) { - CHECK(name(i) != NULL && strcmp(name(i), "UNKNOWN") != 0); - for (int j = i + 1; j < count; j++) CHECK(strcmp(name(i), name(j)) != 0); - } - return strcmp(name(-1), "UNKNOWN") == 0 && strcmp(name(count), "UNKNOWN") == 0; -} - -/* Expects the stub's full defined result for a job refused at `step` with `failure`. */ -static void expect_result(const OmegaGpuResult *r, int failure, int step) -{ - CHECK(r->failure == failure); - CHECK(r->failed_step == step); - CHECK(r->last_state == OMEGA_GPU_ENGINE_STATE_INITIAL); - CHECK(r->wait == OMEGA_GPU_ENGINE_WAIT_NONE); - CHECK(r->wait_timeout_ms == 0 && r->waited_ms == 0); - CHECK(r->drv_rc == 0 && r->err_no == 0 && r->drv_text[0] == '\0'); - CHECK(r->sync_valid == 0 && r->marker == 0 && r->marker2 == 0 && r->semaphore[0] == 0); - CHECK(r->retained == 0 && r->cleanup_failed == 0); - CHECK(r->n_outputs == 0 && r->output_unchanged_words[0] == 0); -} - -int main(void) -{ - CHECK(all_distinct(omega_gpu_engine_failure_name, OMEGA_GPU_ENGINE_FAILURE_COUNT)); - CHECK(all_distinct(omega_gpu_engine_state_name, OMEGA_GPU_ENGINE_STATE_COUNT)); - CHECK(all_distinct(omega_gpu_engine_wait_name, OMEGA_GPU_ENGINE_WAIT_COUNT)); - CHECK(all_distinct(omega_gpu_engine_step_name, OMEGA_GPU_ENGINE_STEP_COUNT)); - CHECK(OMEGA_GPU_ENGINE_OK == 0 && strcmp(omega_gpu_engine_failure_name(0), "OK") == 0); - CHECK(strcmp(omega_gpu_engine_failure_name(OMEGA_GPU_ENGINE_COMPLETION_WAIT), "COMPLETION_WAIT") == 0); - CHECK(strcmp(omega_gpu_engine_failure_name(OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED), - "UNCERTAIN_COMPLETION_BLOCKED") == 0); - CHECK(strcmp(omega_gpu_engine_state_name(OMEGA_GPU_ENGINE_STATE_INITIAL), "INITIAL") == 0); - CHECK(strcmp(omega_gpu_engine_state_name(OMEGA_GPU_ENGINE_STATE_SUCCESS), "SUCCESS") == 0); - CHECK(OMEGA_GPU_ENGINE_STATE_INITIAL == 0 && OMEGA_GPU_ENGINE_STATE_COUNT == 7); - CHECK(strcmp(omega_gpu_engine_wait_name(OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE), "RELEASE_SEMAPHORE") == 0); - CHECK(strcmp(omega_gpu_engine_step_name(OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED), "NOT_IMPLEMENTED") == 0); - - unsigned char code[4] = {0}; - uint32_t ina[4] = {0}, inb[4] = {0}, outw[4] = {0}, poison[4] = {1, 2, 3, 4}; - OmegaGpuJob job; - memset(&job, 0, sizeof job); - job.program = code; job.program_len = sizeof code; - job.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; job.element_count = 4; - job.input_a = ina; job.input_a_len = sizeof ina; - job.input_b = inb; job.input_b_len = sizeof inb; - job.output = outw; job.output_len = sizeof outw; - job.poison = poison; job.poison_count = 4; - job.timeouts.marker_ms = 1; job.timeouts.release_semaphore_ms = 1; - job.timeouts.marker2_ms = 1; job.timeouts.visibility_ms = 1; - - OmegaGpuResult r; - - /* Not blocked at start; no backend set: the defined stub result. */ - omega_gpu_engine_test_reset_block(); - CHECK(omega_gpu_engine_is_blocked() == 0); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* A missing result pointer is refused and nothing is written. */ - CHECK(omega_gpu_execute(&job, NULL) == OMEGA_GPU_ENGINE_INVALID_ARGS); - - /* Counterexamples: each malformed job is INVALID_ARGS at VALIDATE, never NOT_IMPLEMENTED. */ - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(NULL, &r) == OMEGA_GPU_ENGINE_INVALID_ARGS); - expect_result(&r, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STEP_VALIDATE); - - OmegaGpuJob bad_job; -#define EXPECT_INVALID(edit) do { bad_job = job; edit; memset(&r, 0x7f, sizeof r); \ - CHECK(omega_gpu_execute(&bad_job, &r) == OMEGA_GPU_ENGINE_INVALID_ARGS); \ - expect_result(&r, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STEP_VALIDATE); } while (0) - EXPECT_INVALID(bad_job.program = NULL); - EXPECT_INVALID(bad_job.program_len = 0); - EXPECT_INVALID(bad_job.layout = OMEGA_GPU_LAYOUT_COUNT); - EXPECT_INVALID(bad_job.element_count = 0); - EXPECT_INVALID(bad_job.input_a = NULL); - EXPECT_INVALID(bad_job.input_a_len = sizeof ina - 4); - EXPECT_INVALID(bad_job.input_b = NULL); - EXPECT_INVALID(bad_job.input_b_len = sizeof inb + 4); - EXPECT_INVALID(bad_job.output = NULL); - EXPECT_INVALID(bad_job.output_len = sizeof outw - 4); - EXPECT_INVALID(bad_job.output = (unsigned char *)outw + 1); /* not 4-byte aligned */ - EXPECT_INVALID(bad_job.poison = NULL); - EXPECT_INVALID(bad_job.poison_count = 3); - EXPECT_INVALID(bad_job.flags = 0x2u); /* unknown flag */ - EXPECT_INVALID(bad_job.timeouts.marker_ms = 0); - EXPECT_INVALID(bad_job.timeouts.release_semaphore_ms = 0); - EXPECT_INVALID(bad_job.timeouts.visibility_ms = 0); - EXPECT_INVALID(bad_job.timeouts.marker2_ms = 0); /* C3 on, so marker2 needs a timeout */ - - /* With NO_C3 a zero marker2 timeout is allowed. */ - bad_job = job; bad_job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; bad_job.timeouts.marker2_ms = 0; - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&bad_job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* Backend table: incomplete is refused, complete runs the core to SUCCESS, NULL clears. */ - OmegaGpuBackend be = { - .ctx = NULL, .open_device = f_ctx, .create_channel = f_ctx, .alloc = f_alloc, - .copy_in = f_in, .fill_poison = f_poison, .build = f_build, .submit = f_ctx, - .wait_marker = f_wait, .wait_marker2 = f_wait, .wait_release_semaphore = f_wait, - .barrier = f_wait, .copy_out = f_out, .diagnostics = f_diag, .free_buf = f_free, - .close = f_ctx, - }; - omega_gpu_engine_set_backend(&be); - /* The A3a core now runs the whole state machine: the all-success no-op backend - * (copy-out leaves the output zeros, which differ from the poison words 1..4) - * reaches SUCCESS. The full state machine is tested in tests/test_omega_gpu_engine.c. */ - omega_gpu_engine_test_set_clock(NULL); /* NULL keeps the default clock */ - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_OK); - CHECK(r.failure == OMEGA_GPU_ENGINE_OK && r.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - CHECK(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS && r.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - CHECK(r.retained == 0 && r.cleanup_failed == 0); - CHECK(r.n_outputs == 1u && r.output_unchanged_words[0] == 0); - be.close = NULL; - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK); - omega_gpu_engine_set_backend(NULL); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* Block: forced block refuses every job, even a malformed one, until reset. */ - omega_gpu_engine_test_force_block(); - CHECK(omega_gpu_engine_is_blocked() == 1); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - expect_result(&r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, OMEGA_GPU_ENGINE_STEP_BLOCKED); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(NULL, &r) == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - expect_result(&r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, OMEGA_GPU_ENGINE_STEP_BLOCKED); - CHECK(omega_gpu_engine_is_blocked() == 1); /* a refusal does not clear the block */ - omega_gpu_engine_test_reset_block(); - CHECK(omega_gpu_engine_is_blocked() == 0); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - printf("SUMMARY failed=%d\n", bad); - return bad ? 1 : 0; -} diff --git a/tests/test_omega_gpu_engine_gb10.c b/tests/test_omega_gpu_engine_gb10.c deleted file mode 100644 index 79f6022a3..000000000 --- a/tests/test_omega_gpu_engine_gb10.c +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Phase B only: needs the GB10, queen's go, quiet flag via chip_run; never run in Phase A. - * - * Chip test of the Omega GPU Engine (docs/numeric/OMEGA_GPU_ENGINE.md), cut A3b2. - * Phase A only COMPILES it (make test-gpu-engine-gb10-compile). It was written - * against the real API (src/omega_gpu_engine.h, src/omega_blackwell_submit.h) and - * never compiled or executed by its author. It is a fresh rewrite: the first-cut - * test by GPT-6 Astra (commit 21392ee on fix/omega-gpu-engine-first-cut) used an - * older API, so it served as the outline only. - * - * What it does with --chip on the GB10, through tools/chip_run.sh and - * tools/manifests/gpu_engine.chiprun: - * 1. Runs omega_blackwell_execute_vector (engine core + Blackwell backend + the - * real driver) for element counts 1, 63, 64, 65, 4096 and 65537, ten times - * each. One extra pattern per size uses a[i] = 0xdeadbeef, b[i] = 0 (a sum - * that equals the old constant poison word, which must not fool the engine). - * 2. Negative control: the vector program with its one store instruction - * replaced by the instruction after it (an EXIT), so no lane writes. The - * engine must report OUTPUT_UNCHANGED for all 65 words, after the run - * completed and the output became visible, with nothing retained and no - * cleanup failure. The offsets are the fixture locations in - * src/omega_blackwell_encoder.c (0x120 store, 0x130 exit). - * Verdict lines (the only lines chip_run reads): "GPU_ENGINE: PASS" or - * "GPU_ENGINE: FAIL"; without --chip it prints "GPU_ENGINE: NOT_RUN ..." and - * exits 2. An uncertain completion blocks the process by design: this test then - * parks instead of exiting, because exiting would close the device under a GPU - * that may still be running. - */ -#include "omega_gpu_engine.h" -#include "omega_blackwell_engine.h" -#include "omega_blackwell_submit.h" -#include "omega_blackwell_encoder.h" -#include "omega_blackwell_realize.h" -#include "omega_vector.h" - -#include -#include -#include -#include -#include - -#define REPEATS 10u - -/* An uncertain completion leaves the context and the device memory alive on - * purpose. Never exit in that state. */ -static void park_if_blocked(void) -{ - if (!omega_gpu_engine_is_blocked()) return; - fprintf(stderr, "GPU_ENGINE_BLOCKED uncertain completion, parking (do not close the device)\n"); - puts("GPU_ENGINE: FAIL"); - fflush(stdout); - for (;;) pause(); -} - -static int run_size(uint32_t n, int deadbeef) -{ - OmegaVectorSpec spec; - OmegaBlackwellRealization real; - OmegaBlackwellVectorExecution info; - uint32_t *a = (uint32_t *)malloc((size_t)n * 4u); - uint32_t *b = (uint32_t *)malloc((size_t)n * 4u); - uint32_t *c = (uint32_t *)malloc((size_t)n * 4u); - uint32_t i; - unsigned rep; - int ok = (a && b && c); - - memset(&spec, 0, sizeof spec); - memset(&real, 0, sizeof real); - real.sm_architecture = OMEGA_BW_SM_ARCH_121; - if (ok && omega_vector_spec_init(&spec, "engine_chip", n) != 0) ok = 0; - for (i = 0; ok && i < n; i++) { - a[i] = deadbeef ? 0xdeadbeefu : (uint32_t)(i * 2654435761u + 1u); - b[i] = deadbeef ? 0u : (uint32_t)(i * 40503u + 7u); - } - for (rep = 0; ok && rep < REPEATS; rep++) { - int rc; - memset(c, 0, (size_t)n * 4u); - memset(&info, 0, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, a, b, c, &info); - park_if_blocked(); - if (rc != 0 || !info.parity_verified) { - fprintf(stderr, "vector run failed n=%u deadbeef=%d repeat=%u rc=%d\n", n, deadbeef, rep, rc); - ok = 0; - } - } - free(a); - free(b); - free(c); - return ok; -} - -static int no_store_control(void) -{ - uint8_t code[OMEGA_BW_VECADD_CODE_SIZE]; - size_t code_bytes = 0; - uint32_t a[65], b[65], out[65], poison[65]; - OmegaGpuJob job; - OmegaGpuResult res; - uint32_t i; - int rc; - - if (omega_blackwell_verify_encoder_fixtures() != 0) return 0; - if (omega_blackwell_encode_vecadd(code, sizeof code, &code_bytes) != 0 || code_bytes < 0x140u) return 0; - /* Replace only the store with the exit that follows it. */ - memcpy(code + 0x120, code + 0x130, OMEGA_BW_INSTRUCTION_BYTES); - for (i = 0; i < 65u; i++) { - a[i] = i + 1u; - b[i] = 3u * i; - poison[i] = ~(a[i] + b[i]); - } - memset(out, 0, sizeof out); - memset(&job, 0, sizeof job); - job.program = code; - job.program_len = code_bytes; - job.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - job.element_count = 65u; - job.input_a = a; - job.input_a_len = sizeof a; - job.input_b = b; - job.input_b_len = sizeof b; - job.output = out; - job.output_len = sizeof out; - job.poison = poison; - job.poison_count = 65u; - job.timeouts.marker_ms = 5000; - job.timeouts.release_semaphore_ms = 5000; - job.timeouts.marker2_ms = 5000; - job.timeouts.visibility_ms = 5000; - job.flags = 0; - - omega_gpu_engine_set_backend(omega_blackwell_engine_backend()); - rc = omega_gpu_execute(&job, &res); - park_if_blocked(); - if (rc != OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED || res.last_state != OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE || - res.n_outputs != 1u || res.output_unchanged_words[0] != 65u || res.cleanup_failed != 0 || - res.retained != 0) { - fprintf(stderr, "no-store control failed rc=%d state=%d unchanged=%llu cleanup_failed=%d retained=%d\n", - rc, res.last_state, (unsigned long long)res.output_unchanged_words[0], - res.cleanup_failed, res.retained); - return 0; - } - return 1; -} - -int main(int argc, char **argv) -{ - static const uint32_t sizes[] = {1u, 63u, 64u, 65u, 4096u, 65537u}; - size_t s; - unsigned runs = 0; - int failed = 0; - - if (argc < 2 || strcmp(argv[1], "--chip") != 0) { - puts("GPU_ENGINE: NOT_RUN (pass --chip; needs the GB10, via tools/chip_run.sh)"); - return 2; - } - for (s = 0; !failed && s < sizeof sizes / sizeof sizes[0]; s++) { - if (!run_size(sizes[s], 0) || !run_size(sizes[s], 1)) failed = 1; - else runs += 2u * REPEATS; - } - if (!failed && !no_store_control()) failed = 1; - if (failed) { - puts("GPU_ENGINE: FAIL"); - return 1; - } - printf("GPU_ENGINE_CASES vector_runs=%u no_store_control=detected\n", runs); - puts("GPU_ENGINE: PASS"); - return 0; -} diff --git a/tests/test_omega_gpu_platform.c b/tests/test_omega_gpu_platform.c deleted file mode 100644 index a97b9e3c3..000000000 --- a/tests/test_omega_gpu_platform.c +++ /dev/null @@ -1,317 +0,0 @@ -/* Contract tests for src/omega_gpu_platform.h (native v1 P07 cut A). Host - * program, links the FREESTANDING object of src/omega_gpu_platform.c. Opens - * no device. Every rule in the header comment has a case here, and every - * refusal name is reached at least once. */ -#include "omega_gpu_platform.h" - -#include -#include - -static int n_pass, n_fail, case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) -static void case_begin(void) { case_ok = 1; } -static void case_end(const char *id) -{ - if (case_ok) n_pass++; else n_fail++; - printf("%s %s\n", case_ok ? "PASS" : "FAIL", id); -} - -/* ---- a complete fake platform (no device behind it) ---------------------- */ -static uint64_t f_now(void *c) { (void)c; return 1u; } -static int f_wait(void *c, uint64_t ms) { (void)c; (void)ms; return 0; } -static int f_lock(void *c, uint32_t id) { (void)c; (void)id; return 0; } -static int f_rd(void *c, OmegaGpuDeviceHandle d, uint32_t r, uint64_t o, uint32_t *v) { (void)c; (void)d; (void)r; (void)o; *v = 0; return 0; } -static int f_wr(void *c, OmegaGpuDeviceHandle d, uint32_t r, uint64_t o, uint32_t v) { (void)c; (void)d; (void)r; (void)o; (void)v; return 0; } -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) -{ (void)c; (void)d; (void)desc; (void)o; (void)cpu; (void)g; (void)b; return 0; } -static int f_free(void *c, OmegaGpuBufferHandle b) { (void)c; (void)b; return 0; } -static int f_sync(void *c, OmegaGpuBufferHandle b, uint64_t o, uint64_t l) { (void)c; (void)b; (void)o; (void)l; return 0; } -static int f_word(void *c, OmegaGpuBufferHandle b, uint64_t o, uint32_t e, uint64_t t, uint32_t *v) { (void)c; (void)b; (void)o; (void)e; (void)t; *v = 0; return 0; } -static int f_irq(void *c, OmegaGpuDeviceHandle d, uint64_t t) { (void)c; (void)d; (void)t; return 0; } - -static void full_platform(OmegaGpuPlatform *p) -{ - memset(p, 0, sizeof *p); - p->time_now_ms = f_now; p->wait_ms = f_wait; p->lock = f_lock; p->unlock = f_lock; - p->mmio_read32 = f_rd; p->mmio_write32 = f_wr; p->dma_alloc = f_alloc; p->dma_free = f_free; - p->sync_cpu_to_gpu = f_sync; p->sync_gpu_to_cpu = f_sync; p->poll_word = f_word; -} - -static void caps_v1(OmegaGpuPlatformCaps *c) -{ - memset(c, 0, sizeof *c); - c->abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR; c->abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR; - c->services = OMEGA_GPU_SVC_REQUIRED_V1; - c->max_devices = 1; c->max_buffers = 8; c->max_queues = 2; c->max_inflight = 1; - c->max_buffer_bytes = 1u << 20; c->max_total_bytes = 4u << 20; -} - -static void case_names(void) -{ - int i, j; - case_begin(); - for (i = 0; i < (int)OMEGA_GPU_PLAT_REFUSAL_COUNT; i++) { - EXPECT(strcmp(omega_gpu_platform_refusal_name(i), "UNKNOWN") != 0); - for (j = 0; j < i; j++) EXPECT(strcmp(omega_gpu_platform_refusal_name(i), omega_gpu_platform_refusal_name(j)) != 0); - } - EXPECT(strcmp(omega_gpu_platform_refusal_name(-1), "UNKNOWN") == 0); - EXPECT(strcmp(omega_gpu_platform_refusal_name(OMEGA_GPU_PLAT_REFUSAL_COUNT), "UNKNOWN") == 0); - EXPECT(strcmp(omega_gpu_platform_refusal_name(0), "OK") == 0); - case_end("REFUSAL_NAMES_DISTINCT"); -} - -static void case_negotiate(void) -{ - OmegaGpuPlatformCaps p, r; - case_begin(); - caps_v1(&p); caps_v1(&r); - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_negotiate(NULL, &r) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_negotiate(&p, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* a newer provided minor is fine; an older one or another major is refused */ - p.abi_minor = r.abi_minor + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - caps_v1(&p); r.abi_minor = p.abi_minor + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ABI); - caps_v1(&r); p.abi_major = r.abi_major + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ABI); - /* a required service the platform lacks is refused, never emulated */ - caps_v1(&p); r.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - p.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - /* unknown service bits are malformed */ - p.services |= 1u << 12; /* the first bit past ABI 1.1 */ - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* every limit */ - caps_v1(&p); caps_v1(&r); r.max_devices = 2; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_buffers = 9; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_queues = 3; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_inflight = 2; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_buffer_bytes = (1u << 20) + 1u; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_total_bytes = (4u << 20) + 1u; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* asking for less is fine */ - caps_v1(&r); r.max_buffers = 1; r.max_total_bytes = 1; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - case_end("NEGOTIATE_ABI_SERVICES_LIMITS"); -} - -static void case_check_table(void) -{ - OmegaGpuPlatform p; - OmegaGpuPlatformCaps c; - case_begin(); - full_platform(&p); caps_v1(&c); - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_check(NULL, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_check(&p, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* the v1 required set is mandatory */ - c.services = OMEGA_GPU_SVC_REQUIRED_V1 & ~OMEGA_GPU_SVC_SYNC; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - /* a claimed service with a missing function, one per service */ - caps_v1(&c); - full_platform(&p); p.time_now_ms = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.wait_ms = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.unlock = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.mmio_write32 = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.dma_free = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.sync_gpu_to_cpu = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.poll_word = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - /* IRQ: claimed needs irq_wait; polling-only platforms do not claim it and must not carry one */ - full_platform(&p); c.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - p.irq_wait = f_irq; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_OK); - caps_v1(&c); - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); /* undeclared function = hidden path */ - case_end("SERVICE_TABLE_MATCHES_CLAIMS_NO_HIDDEN_FALLBACK"); -} - - -/* ABI 1.1: the services the persistent GPU session requires (OMEGA_GPU_SVC_REQUIRED_SESSION). */ -static int f_dopen(void *c, uint32_t o, OmegaGpuDeviceHandle *d) { (void)c; (void)o; d->index = 0; d->generation = 1; return 0; } -static int f_dclose(void *c, OmegaGpuDeviceHandle d) { (void)c; (void)d; return 0; } -static const char *f_diag(void *c) { (void)c; return ""; } -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle r, OmegaGpuQueueHandle *q) { (void)c; (void)d; (void)r; q->index = 0; q->generation = 1; return 0; } -static int f_qclose(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static int f_qsubmit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { (void)c; (void)q; (void)w; (void)n; return 0; } -static int f_qretire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static uint64_t f_ns(void *c) { (void)c; return 1u; } -static void *f_halloc(void *c, size_t b) { (void)c; (void)b; return NULL; } -static void f_hfree(void *c, void *p) { (void)c; (void)p; } -static void session_platform(OmegaGpuPlatform *p, OmegaGpuPlatformCaps *c) -{ - full_platform(p); - p->mmio_read32 = NULL; p->mmio_write32 = NULL; /* the session needs no MMIO: a platform without it is fine */ - p->device_open = f_dopen; p->device_close = f_dclose; p->diag_text = f_diag; - p->queue_open = f_qopen; p->queue_close = f_qclose; p->queue_submit = f_qsubmit; p->queue_retire = f_qretire; - p->time_now_ns = f_ns; p->host_alloc = f_halloc; p->host_free = f_hfree; - caps_v1(c); - c->services = OMEGA_GPU_SVC_REQUIRED_SESSION; -} - -static void case_session_services(void) -{ - OmegaGpuPlatform p; - OmegaGpuPlatformCaps c; - case_begin(); - EXPECT(OMEGA_GPU_PLATFORM_ABI_MINOR == 2u); /* 1.2: caps.submit_prefix_words (#459) */ - EXPECT(!(OMEGA_GPU_SVC_REQUIRED_SESSION & (OMEGA_GPU_SVC_IRQ | OMEGA_GPU_SVC_MMIO))); - session_platform(&p, &c); - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); - /* the v1 check still demands MMIO, so a session-only platform is not a v1 device-owner platform */ - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_ALL + 1u) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* each new service: a missing function is refused */ - session_platform(&p, &c); p.device_close = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.diag_text = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.queue_retire = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.time_now_ns = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.host_free = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - /* a required service not claimed is missing; a function of an unclaimed service is a hidden path */ - session_platform(&p, &c); c.services &= ~OMEGA_GPU_SVC_QUEUE; - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - EXPECT(omega_gpu_platform_check_for(&p, &c, c.services) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* polling never claims IRQ: a session platform with an irq_wait it does not claim is refused */ - session_platform(&p, &c); p.irq_wait = f_irq; - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_negotiate(&c, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(OMEGA_GPU_POLL_TIMED_OUT >= (int)OMEGA_GPU_PLAT_REFUSAL_COUNT); - case_end("SESSION_SERVICES_ABI_1_1_POLLING_NOT_IRQ"); -} -static void case_buffers(void) -{ - OmegaGpuBufferDesc d; - OmegaGpuPlatformCaps c; - case_begin(); - caps_v1(&c); - memset(&d, 0, sizeof d); - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; d.rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ; d.bytes = 4096; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_check_buffer(NULL, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_check_buffer(&d, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.kind = OMEGA_GPU_HANDLE_QUEUE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; - d.bytes = 0; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH); - d.bytes = (1u << 20) + 1u; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - d.bytes = 4096; - d.align = 48; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.align = 64; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.gpu_cache = 7; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED; - d.rights = 0; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights = 1u << 7; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - /* exec only on code */ - d.rights = OMEGA_GPU_RIGHT_GPU_EXEC | OMEGA_GPU_RIGHT_CPU_WRITE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.kind = OMEGA_GPU_HANDLE_BUF_CODE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.rights |= OMEGA_GPU_RIGHT_GPU_WRITE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights = OMEGA_GPU_RIGHT_CPU_WRITE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* code without exec */ - d.rights = OMEGA_GPU_RIGHT_GPU_EXEC; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* nobody can fill it */ - /* queue: CPU writes, device reads */ - d.kind = OMEGA_GPU_HANDLE_BUF_QUEUE; d.rights = OMEGA_GPU_RIGHT_CPU_WRITE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights |= OMEGA_GPU_RIGHT_GPU_READ; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - /* host-polled: CPU reads, GPU writes, GPU-uncached (the E1 rule) */ - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; - d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE; - d.gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - d.gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_READ; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.kind = OMEGA_GPU_HANDLE_BUF_CODE; d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_EXEC | OMEGA_GPU_RIGHT_CPU_READ; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - case_end("BUFFER_DESC_KIND_LENGTH_RIGHTS_CACHE"); -} - -static void case_handles(void) -{ - static OmegaGpuHandleTable t; - uint32_t i0, g0, i1, g1, i2, g2, i, g; - uint32_t n; - case_begin(); - omega_gpu_handles_init(&t); - EXPECT(t.nlive == 0 && t.total_bytes == 0); - EXPECT(omega_gpu_handles_open(NULL, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_handles_open(&t, 0, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_KIND_COUNT, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - /* one device allowed */ - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_OK); - EXPECT(g0 != 0u); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i1, &g1) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* buffers account bytes against the total */ - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 3000, 8, 4096, &i1, &g1) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 2000, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 5000, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_CODE, 1096, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_OK); - EXPECT(t.nlive == 3 && t.total_bytes == 4096); - /* checks: kind, index, generation */ - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_CODE) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, OMEGA_GPU_HANDLE_SLOTS, 1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i1, 0, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i1, g1 + 1u, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_check(&t, 40, 1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); /* never opened */ - EXPECT(omega_gpu_handles_check(NULL, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* close: frees bytes, the old handle goes stale, double close refused, slot reuse gets a new generation */ - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_CODE) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(t.nlive == 2 && t.total_bytes == 1096); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 3000, 8, 4096, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == i1 && g == g1 + 1u); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i, g, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - /* per-kind slot limit counts only live handles of that kind */ - for (n = 0; n < 2; n++) EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_close(&t, i2, g2, OMEGA_GPU_HANDLE_QUEUE) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_OK); - /* table capacity */ - omega_gpu_handles_init(&t); - for (n = 0; n < OMEGA_GPU_HANDLE_SLOTS; n++) - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* a wrapped generation retires the slot instead of reissuing generation 0 */ - omega_gpu_handles_init(&t); - t.generation[0] = 0xFFFFFFFFu; - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 8, 8, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == 0 && g == 0xFFFFFFFFu); - EXPECT(omega_gpu_handles_close(&t, 0, g, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 8, 8, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == 1 && g == 1u); - case_end("HANDLES_TYPED_GENERATIONED_LIMITED"); -} - -static void case_sizes(void) -{ - /* No Linux fd, no raw pointer and no physical address can be smuggled - * through a handle: it is two 32-bit fields, and the address types are - * distinct structs that do not convert into each other. */ - case_begin(); - EXPECT(sizeof(OmegaGpuDeviceHandle) == 8u); - EXPECT(sizeof(OmegaGpuBufferHandle) == 8u); - EXPECT(sizeof(OmegaGpuQueueHandle) == 8u); - EXPECT(sizeof(OmegaGpuVa) == 8u && sizeof(OmegaGpuBusAddr) == 8u); - EXPECT(sizeof(OmegaCpuView) == sizeof(void *) + sizeof(size_t)); - EXPECT((OMEGA_GPU_SVC_REQUIRED_V1 | OMEGA_GPU_SVC_IRQ) == 0xFFu); /* the v1 bits; 1.1 adds 8..11 */ - case_end("HANDLE_AND_ADDRESS_SHAPES"); -} - -int main(void) -{ - case_names(); - case_negotiate(); - case_check_table(); - case_session_services(); - case_buffers(); - case_handles(); - case_sizes(); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_platform_linux.c b/tests/test_omega_gpu_platform_linux.c deleted file mode 100644 index e06f53dbf..000000000 --- a/tests/test_omega_gpu_platform_linux.c +++ /dev/null @@ -1,269 +0,0 @@ -/* test_omega_gpu_platform_linux: the Linux REFERENCE platform (src/omega_gpu_platform_linux.c, reference only) on the - * simulated driver (tests/fake_m16_native.c). Host program, hosted build, opens no device. - * - * What it checks: the reference claims exactly the session service set (no MMIO, no IRQ: polling is never claimed as - * an interrupt) and passes the contract check; the hosted session installs it by default; the session makes the same - * driver calls in the same order as before P07 cut C (channel, then the four session buffers through - * nvrm_alloc_gpu_uncached, one submit with the C3 tail, both marker waits, close); the reference refuses a GPU-cached - * buffer, a poll of a buffer that is not HOST_POLLED, freeing the live queue ring, an oversize submit and every handle - * of a closed device; the driver's own failure text survives an open failure; a marker that never lands latches the - * session, which then frees nothing and closes nothing. Each case runs in its own child process. - */ -#include "fake_m16_native.h" -#include "nvrm.h" -#include "omega_blackwell_submit.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_mem_cached.h" -#include "omega_gpu_platform_linux.h" -#include "omega_gpu_session.h" - -#include -#include -#include -#include -#include - -/* The three driver symbols the session path needs that the fake (written for the vector engine) lacks. */ -static int g_open_fail; -int nvrm_open(Nvrm *rm) { - if (g_open_fail) { snprintf(rm->err, sizeof rm->err, "fake RM: open refused"); return -1; } - fk.device_open = 1; return 0; -} -int nvrm_close(Nvrm *rm) { (void)rm; return 0; } -static int g_retires; -void nvrm_retire(Nvrm *rm, uint32_t upto) { (void)rm; (void)upto; g_retires++; } - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -static const uint32_t ARGS[4] = {1, 2, 3, 4}; -static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { - OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; - return L; -} - -static void c_caps(void) { - OmegaGpuPlatformCaps caps; - const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); - EXPECT(p != NULL); - EXPECT(caps.services == OMEGA_GPU_SVC_REQUIRED_SESSION); - EXPECT(!(caps.services & OMEGA_GPU_SVC_IRQ) && !(caps.services & OMEGA_GPU_SVC_MMIO)); - EXPECT(p->irq_wait == NULL && p->mmio_read32 == NULL && p->mmio_write32 == NULL); - EXPECT(omega_gpu_platform_check_for(p, &caps, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); - EXPECT(caps.abi_major == 1 && caps.abi_minor == 2); -} - -static void c_default_install(void) { - fake_reset(); - EXPECT(omega_gpu_session_platform() == omega_gpu_platform_linux(NULL)); /* hosted: the reference by default */ - EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); -} - -static void c_same_driver_calls(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return; } - EXPECT(fk.channel_calls == 1 && fk.uncached_calls == 4 && fk.alloc_calls == 4 && fk.live == 4); - const int ch = fake_nth(FK_EV_CHANNEL, 1), a1 = fake_nth(FK_EV_ALLOC, 1); - EXPECT(ch >= 0 && a1 > ch); /* channel first, then the session buffers */ - EXPECT(fk.ev[fake_nth(FK_EV_ALLOC, 1)].a == 0x10000 && fk.ev[fake_nth(FK_EV_ALLOC, 2)].a == 0x1000 && - fk.ev[fake_nth(FK_EV_ALLOC, 3)].a == 0x1000 && fk.ev[fake_nth(FK_EV_ALLOC, 4)].a == 0x10000); - OmegaGpuLaunch L = launch_desc(1000); - uint32_t mk = 0; - EXPECT(omega_gpu_session_launch(&L, NULL, &mk) == 0); - EXPECT(fk.submit_calls == 1 && fk.pb_mem_size == 0x10000); - EXPECT(fake_count(FK_EV_PB_RELEASE) == 2 && fake_count(FK_EV_PB_FLUSH) == 1); /* the C3 tail */ - EXPECT(fk.marker1_va == s->marker.va && fk.marker2_va == s->marker.va + 0x10); - EXPECT(fk.sem_va == s->qmd.va + 0x2000 && fk.sem_init_value == OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT); - EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && g_retires == 1); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.free_calls == 4 && fk.close_calls == 1 && fk.live_at_close == 0 && fk.double_free == 0); -} - -static void c_reference_refusals(void) { - fake_reset(); - OmegaGpuPlatformCaps caps; - const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); - OmegaGpuDeviceHandle d; - EXPECT(p->device_open(p->ctx, 0, &d) == OMEGA_GPU_PLAT_OK); - OmegaGpuDeviceHandle d2; - EXPECT(p->device_open(p->ctx, 0, &d2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); /* one device context */ - OmegaGpuBufferDesc cached = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, - .gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED, .bytes = 4096}; - OmegaGpuBufferHandle h; OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; - const int allocs0 = fk.alloc_calls; - EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - cached.rights |= OMEGA_GPU_RIGHT_HOST_POLLED; /* polled and cached: the contract refuses it too */ - EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - EXPECT(fk.alloc_calls == allocs0); /* refused before the driver */ - OmegaGpuBufferDesc data = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, - .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; - EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); - EXPECT(cpu.ptr != NULL && cpu.len >= 4096 && bus.iova == 0); - uint32_t seen = 0; - EXPECT(p->poll_word(p->ctx, h, 0, 1, 1, &seen) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* not HOST_POLLED */ - OmegaGpuBufferDesc ring = {.kind = OMEGA_GPU_HANDLE_BUF_QUEUE, .rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ, - .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; - OmegaGpuBufferHandle rh; OmegaGpuQueueHandle q; - EXPECT(p->dma_alloc(p->ctx, d, &ring, &rh, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); - EXPECT(p->queue_open(p->ctx, d, h, &q) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); /* a DATA buffer is not a ring */ - EXPECT(p->queue_open(p->ctx, d, rh, &q) == OMEGA_GPU_PLAT_OK); - EXPECT(p->dma_free(p->ctx, rh) == OMEGA_GPU_PLAT_REFUSED_BUSY); /* the open queue still uses it */ - static uint32_t big[2048]; - EXPECT(p->queue_submit(p->ctx, q, big, 2048) == OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH); /* 8 KiB into a 4 KiB ring */ - EXPECT(fk.submit_calls == 0); - const int frees0 = fk.free_calls; - EXPECT(p->device_close(p->ctx, d) == OMEGA_GPU_PLAT_OK); - /* every handle of the closed device is stale */ - EXPECT(p->dma_free(p->ctx, h) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->sync_cpu_to_gpu(p->ctx, h, 0, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->queue_submit(p->ctx, q, big, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(fk.free_calls == frees0); - EXPECT(strstr(p->diag_text(p->ctx), "STALE") != NULL); -} - -static void c_open_failure_text(void) { - fake_reset(); - fk.channel_fail = 1; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strncmp(omega_gpu_session_last_error(), "m16_native_create_channel: ", 27) == 0); - EXPECT(strstr(omega_gpu_session_last_error(), FK_TEXT) != NULL); /* the driver's own text survives */ - fk.channel_fail = 0; - g_open_fail = 1; - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strcmp(omega_gpu_session_last_error(), "nvrm_open: fake RM: open refused") == 0); - g_open_fail = 0; - EXPECT(omega_gpu_session_open() != NULL && !omega_gpu_session_is_blocked()); - omega_gpu_session_unlock(); - omega_gpu_session_close(); -} - -static void c_marker_never_latches(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.marker_mode = FK_SYNC_NEVER; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - OmegaGpuLaunch L = launch_desc(5); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(omega_gpu_session_is_blocked()); - EXPECT(fk.wait_calls == 5 && fk.clock_ms == 5); /* five 1 ms poll slices, then uncertain */ - EXPECT(g_retires == 0); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.free_calls == 0 && fk.close_calls == 0 && fk.live == 4); /* parked: nothing released, nothing closed */ - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 4); -} - -/* omega #457: the L2_SYSMEM_NCOH_INVALIDATE prefix, MEM_OP_A..D = 0, 0, 0, 0x11 << 27 (clc96f.h:30-73). The fake logs - * every MEM_OP as FK_EV_PB_FLUSH with a = the operation word. */ -#define L2_INVAL_OP (0x11u << 27) -static int count_l2_inval(void) { - int n = 0; - for (int i = 0; i < fk.nev; i++) n += fk.ev[i].kind == FK_EV_PB_FLUSH && fk.ev[i].a == L2_INVAL_OP; - return n; -} - -static void c_l2_inval_prefix_once(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - OmegaGpuPlatformCaps caps; - (void)omega_gpu_platform_linux(&caps); - EXPECT(caps.submit_prefix_words == 5u); /* the cost the platform publishes is the prefix it writes */ - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { omega_gpu_session_unlock(); return; } - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - OmegaGpuMem cached; - EXPECT(omega_gpu_session_alloc_cached(4096, &cached) == 0); - OmegaGpuLaunch L = launch_desc(1000); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 0); /* no host write into a GPU-cached buffer yet: no prefix */ - const size_t plain = fk.pb_len; - EXPECT(p->sync_cpu_to_gpu(p->ctx, s->marker.handle, 0, 4) == OMEGA_GPU_PLAT_OK); /* an uncached buffer: no prefix */ - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 0 && fk.pb_len == plain); - EXPECT(p->sync_cpu_to_gpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1); /* exactly once, at the head of the next submission */ - EXPECT(fk.pb_len == plain + 5u); - EXPECT(fk.pb[0] == ((2u << 28) | (4u << 16) | (0x0028u >> 2)) && fk.pb[1] == 0 && fk.pb[2] == 0 && fk.pb[3] == 0 && - fk.pb[4] == L2_INVAL_OP); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1 && fk.pb_len == plain); /* consumed: the launch after it has none */ - EXPECT(p->sync_gpu_to_cpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); /* GPU to CPU is no host write */ - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1 && fk.pb_len == plain); - EXPECT(fk.pb_parse_error == 0 && fk.ev_overflow == 0); - omega_gpu_session_unlock(); -} - -/* Fable review of omega #459: a stamped standalone list of >= 1167 launches filled one submission to 16381 words; with - * the 5-word prefix pending that is 16386 > 16384 ring words, refused BAD_LENGTH on every retry. The command list must - * budget the prefix the platform publishes (caps.submit_prefix_words). */ -static void c_cmdlist_near_cap_with_l2_inval_pending(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.alloc_max = 4u << 20; /* the 2048-launch bank and QMD buffers are 2 MiB each */ - OmegaGpuCmdList *cl = NULL; - EXPECT(omega_gpu_cmdlist_create(OMEGA_GPU_CMDLIST_MAX_LAUNCHES, &cl) == 0); - if (!cl) { printf(" %s\n", omega_gpu_session_last_error()); return; } - omega_gpu_session_lock(); - OmegaGpuLaunch L = launch_desc(1000); - for (uint32_t i = 0; i < OMEGA_GPU_CMDLIST_MAX_LAUNCHES; i++) EXPECT(omega_gpu_cmdlist_add(cl, &L) == (int)i); - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - OmegaGpuMem cached; - EXPECT(omega_gpu_session_alloc_cached(4096, &cached) == 0); - EXPECT(p->sync_cpu_to_gpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); /* the prefix is now pending */ - const int submits0 = fk.submit_calls; - OmegaGpuCmdListOpts o = { .mode = OMEGA_GPU_CMDLIST_PCAS, .barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI, .timeout_ms = 1000, .stamps = 1 }; - OmegaGpuCmdListStats st; - const int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - if (rc != 0) printf(" cmdlist submit: %s (platform: %s)\n", omega_gpu_session_last_error(), p->diag_text(p->ctx)); - EXPECT(rc == 0); - EXPECT(st.sems_done == OMEGA_GPU_CMDLIST_MAX_LAUNCHES && st.first_missing == -1); - EXPECT(st.submits == 2 && fk.submit_calls - submits0 == 2); - EXPECT(count_l2_inval() == 1); /* the first submission only */ - for (int i = 0; i < fk.nev; i++) - if (fk.ev[i].kind == FK_EV_SUBMIT) EXPECT(fk.ev[i].a * 4u <= fk.pb_mem_size); /* prefix included, inside the ring */ - EXPECT(fk.pb_parse_error == 0 && fk.ev_overflow == 0); - EXPECT(!omega_gpu_session_is_blocked() && !omega_gpu_cmdlist_is_latched()); - omega_gpu_session_unlock(); -} - -typedef struct { const char *id; void (*fn)(void); } Case; -static const Case CASES[] = { - {"LINUX_REF_CAPS_NO_MMIO_NO_IRQ", c_caps}, - {"HOSTED_DEFAULT_IS_LINUX_REFERENCE", c_default_install}, - {"SAME_DRIVER_CALLS_AND_ORDER_AS_BEFORE", c_same_driver_calls}, - {"REFERENCE_REFUSALS_CACHED_POLLED_RING_STALE", c_reference_refusals}, - {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, - {"MARKER_NEVER_LATCHES_AND_PARKS", c_marker_never_latches}, - {"L2_INVAL_PREFIX_ONCE_AFTER_CACHED_HOST_WRITE", c_l2_inval_prefix_once}, - {"CMDLIST_NEAR_CAP_SUBMITS_WITH_L2_INVAL_PENDING", c_cmdlist_near_cap_with_l2_inval_pending}, -}; - -int main(void) { - int pass = 0, fail = 0; - for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int st = 0; - waitpid(pid, &st, 0); - const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; - printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); - if (ok) pass++; else fail++; - } - printf("test_omega_gpu_platform_linux (reference only, simulated driver): %d passed, %d failed\n", pass, fail); - return fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_session_platform.c b/tests/test_omega_gpu_session_platform.c deleted file mode 100644 index 6d00ca8fd..000000000 --- a/tests/test_omega_gpu_session_platform.c +++ /dev/null @@ -1,517 +0,0 @@ -/* test_omega_gpu_session_platform: the portable GPU session (native v1 P07 cut C, session part; aienos#286) on a - * FAKE OmegaGpuPlatform. Host program; links the FREESTANDING partial-link object (build/gpu_fs/ - * omega_gpu_freestanding.o: session, matmul and attention APIs, serving, wait, codegen, platform contract), so what - * runs here is the code the native build would run. Opens no device, touches no GPU. - * - * The fake device "completes" a launch at submit time by writing the intermediate semaphore DONE and both marker - * payloads, or (hang mode) writes nothing. Its clock advances only when asked (plus 1 us per read), so timeouts are - * exact and instant. Each case runs in its own child process because an uncertain completion latches the process - * for good (that is the rule under test). - * - * Cases: platform install refusals; freestanding build has no default platform; open/launch/close with typed - * buffers, explicit rights and GPU-uncached policy (host-polled marker); polling only (irq never called, mode is - * POLLING); cancel before submit (nothing submitted, not latched); cancel after submit (latched, parked); timeout - * (latched, session buffers parked, later frees park, close/reopen/install refused, nothing released); stale handle - * refusal after close and reopen; close/reopen (new device generation, opens 2); serving reservation refusal (no - * platform allocation); matmul API code buffer is a CODE buffer encoded in place; wait helper refuses without a clock; - * the bounded formatter matches snprintf and never writes past its cap. - */ -#include "omega_gpu_session.h" -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_wait.h" -#include "omega_gpu_fmt.h" -#include "omega_blackwell_submit.h" - -#include -#include -#include -#include -#include - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -/* ---- the fake platform ---- */ -#define NB OMEGA_GPU_HANDLE_SLOTS -enum { MODE_COMPLETE = 0, MODE_HANG = 1 }; -static struct { - OmegaGpuHandleTable t; - void *mem[NB]; - OmegaGpuBufferDesc desc[NB]; - uint32_t dev_of[NB]; /* device generation a buffer belongs to */ - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle q; - OmegaGpuBufferHandle ring; - int mode; - int cancel_on_poll; /* poll_word calls omega_gpu_session_cancel() on its first call */ - uint64_t ns; - unsigned allocs, frees, free_refusals, submits, polls, retires, syncs, irq_calls, dev_opens, dev_closes; - unsigned locks_held; - unsigned cached_requests; /* buffers asked GPU-cached (must stay 0) */ - unsigned allocs_unlocked; /* allocations without the session lock (must stay 0) */ - int fail_open; -} fk; - -static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } -static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } -static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } -static int f_lock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held++; return 0; } -static int f_unlock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held--; return 0; } -static const char *f_diag(void *c) { (void)c; return fk.fail_open ? "fake device: no GB10 here" : ""; } - -static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { - (void)c; - if (fk.fail_open) return OMEGA_GPU_PLAT_REFUSED_DEVICE; - if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc == 0) { fk.dev = *out; fk.dev_opens++; } - return rc; -} -static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (rc) return rc; - for (uint32_t i = 0; i < NB; i++) /* every handle of the device goes stale */ - if (fk.t.live[i] && i != d.index) { (void)omega_gpu_handles_close(&fk.t, i, fk.t.generation[i], fk.t.kind[i]); free(fk.mem[i]); fk.mem[i] = NULL; } - (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&fk.dev, 0, sizeof fk.dev); memset(&fk.q, 0, sizeof fk.q); - fk.dev_closes++; - return 0; -} - -static OmegaGpuPlatformCaps g_caps = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, -}; - -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - if (rc) return rc; - if (desc->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED) fk.cached_requests++; - if (!fk.locks_held) fk.allocs_unlocked++; - rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); - if (rc) return rc; - void *m = calloc(1, desc->bytes); - fk.mem[o->index] = m; fk.desc[o->index] = *desc; fk.dev_of[o->index] = d.generation; - cpu->ptr = m; cpu->len = desc->bytes; g->va = 0x100000000ull + (uint64_t)o->index * 0x1000000ull; b->iova = 0; - fk.allocs++; - return 0; -} -static int f_free(void *c, OmegaGpuBufferHandle h) { - (void)c; - if (h.index >= NB) { fk.free_refusals++; return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; } - int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); - if (rc) { fk.free_refusals++; return rc; } - free(fk.mem[h.index]); fk.mem[h.index] = NULL; - fk.frees++; - return 0; -} -static int buf_live(OmegaGpuBufferHandle h) { - return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; -} -static int f_sync(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - fk.syncs++; - return 0; -} -static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - fk.polls++; - if (fk.cancel_on_poll) { fk.cancel_on_poll = 0; omega_gpu_session_cancel(); } - volatile uint32_t *w = (volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); - *seen = *w; - if ((int32_t)(*w - want) >= 0) return 0; - fk.ns += ms * 1000000u; - return OMEGA_GPU_POLL_TIMED_OUT; -} -static int f_irq(void *c, OmegaGpuDeviceHandle d, uint64_t t) { (void)c; (void)d; (void)t; fk.irq_calls++; return 0; } -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); - if (!rc) { fk.q = *o; fk.ring = ring; } - return rc; -} -static int f_qclose(void *c, OmegaGpuQueueHandle q) { - (void)c; - int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (!rc) memset(&fk.q, 0, sizeof fk.q); - return rc; -} -/* The fake device: the launch completes at submit (both markers and the semaphore), or never (hang). The marker and - * semaphore addresses are read back from the method words: the QMD page is the buffer whose VA the QMD0 header - * names, the marker page the one whose VA the first release names. */ -static void *va_to_cpu(uint64_t va) { - for (uint32_t i = 0; i < NB; i++) { - if (!fk.mem[i] || !fk.t.live[i]) continue; - uint64_t base = 0x100000000ull + (uint64_t)i * 0x1000000ull; - if (va >= base && va < base + fk.desc[i].bytes) return (uint8_t *)fk.mem[i] + (va - base); - } - return NULL; -} -static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc) return rc; - if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - memcpy(fk.mem[fk.ring.index], w, (size_t)n * 4u); - fk.submits++; - if (fk.mode != MODE_COMPLETE) return 0; - for (uint32_t i = 0; i + 5 < n; i++) { - if (w[i] == ((2u << 28) | (5u << 16) | (0u << 13) | (0x005cu >> 2))) { /* release: va lo, va hi, payload */ - uint64_t va = (uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32); - uint32_t *m = va_to_cpu(va); - if (m) *m = w[i + 3]; - } - if (w[i] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0188u >> 2)) && w[i + 3] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0180u >> 2)) && - w[i + 4] == 4u) { /* the semaphore init upload: the kernel ran, the semaphore says DONE */ - uint32_t *s = va_to_cpu(((uint64_t)w[i + 1] << 32) | w[i + 2]); - if (s) *s = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; - } - } - return 0; -} -static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; fk.retires++; return 0; } -static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } -static void f_hfree(void *c, void *p) { (void)c; free(p); } - -static OmegaGpuPlatform g_plat = { - .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, - .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_sync, .sync_gpu_to_cpu = f_sync, .poll_word = f_poll, - .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, - .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, - .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, -}; - -static void fk_reset(void) { memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); } - -static int install(void) { return omega_gpu_session_set_platform(&g_plat, &g_caps); } - -static const uint32_t ARGS[4] = {1, 2, 3, 4}; -static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { - OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; - return L; -} - -/* ---- cases ---- */ - -static void c_install_refusals(void) { - fk_reset(); - OmegaGpuPlatform p = g_plat; - OmegaGpuPlatformCaps caps = g_caps; - caps.services &= ~OMEGA_GPU_SVC_CLOCK_NS; p.time_now_ns = NULL; - EXPECT(omega_gpu_session_set_platform(&p, &caps) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - p = g_plat; caps = g_caps; - p.irq_wait = f_irq; /* a function for a service it does not claim: refused, never used */ - const int rc_irq = omega_gpu_session_set_platform(&p, &caps); - EXPECT(rc_irq != OMEGA_GPU_PLAT_OK && omega_gpu_session_platform() == NULL); - caps = g_caps; caps.abi_minor = 1; /* a 1.1 platform predates caps.submit_prefix_words: refused */ - EXPECT(omega_gpu_session_set_platform(&g_plat, &caps) == OMEGA_GPU_PLAT_REFUSED_ABI); - EXPECT(omega_gpu_session_platform() == NULL); /* nothing was installed */ - EXPECT(install() == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_session_platform() == &g_plat); - EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); -} - -static void c_no_default_platform(void) { - fk_reset(); - /* the freestanding build has no Linux fallback: nothing installed means refused, not emulated */ - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strstr(omega_gpu_session_last_error(), "no GPU platform installed") != NULL); - omega_gpu_session_unlock(); - EXPECT(omega_gpu_host_alloc(16) == NULL); - EXPECT(omega_gpu_session_now_ns() == 0); -} - -static void c_open_launch_close(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(fk.locks_held == 1); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { omega_gpu_session_unlock(); return; } - EXPECT(fk.allocs == 4 && fk.dev_opens == 1); - /* typed buffers, explicit rights, all GPU-uncached; the polled marker is HOST_POLLED */ - EXPECT(fk.t.kind[s->pb.handle.index] == OMEGA_GPU_HANDLE_BUF_QUEUE); - EXPECT(fk.desc[s->marker.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED); - EXPECT(!(fk.desc[s->cbank.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)); - EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0); - EXPECT(s->pb.va != s->cbank.va && s->marker.size >= 0x1000 && s->qmd.size >= 0x10000); - OmegaGpuLaunch L = launch_desc(100); - uint64_t el = 0; uint32_t mk = 0; - EXPECT(omega_gpu_session_launch(&L, &el, &mk) == 0); - EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && fk.submits == 1 && fk.retires == 1 && el > 0); - EXPECT(fk.syncs >= 3); /* explicit CPU->GPU and GPU->CPU visibility, never implicit */ - EXPECT(fk.irq_calls == 0); /* polling only */ - EXPECT(!omega_gpu_session_is_blocked()); - /* a CODE buffer: CPU writes, GPU executes, never GPU-written, prefetch tail zeroed */ - OmegaGpuMem code; - EXPECT(omega_gpu_session_alloc_code(100, &code) == 0); - EXPECT(fk.t.kind[code.handle.index] == OMEGA_GPU_HANDLE_BUF_CODE); - EXPECT((fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); - omega_gpu_session_free(&code); - EXPECT(code.cpu == NULL && fk.frees == 1); - omega_gpu_session_unlock(); - EXPECT(fk.locks_held == 0); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 1 && fk.frees == 5 && fk.t.nlive == 0); - EXPECT(!omega_gpu_session_is_open()); -} - -static void c_cancel_before_submit(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - omega_gpu_session_cancel(); - OmegaGpuLaunch L = launch_desc(100); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); - EXPECT(fk.submits == 0); /* nothing went to the device */ - EXPECT(!omega_gpu_session_is_blocked()); /* so nothing is uncertain */ - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 0); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the request was consumed; the session still works */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 1); -} - -static void check_latched(unsigned frees_before) { - EXPECT(omega_gpu_session_is_blocked()); - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 4 && ps.untracked == 0 && ps.bytes >= 0x10000 + 0x1000 + 0x1000 + 0x10000); - /* a buffer the caller frees now is parked too, never released: the device may still be using it */ - OmegaGpuMem m = {0}; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_alloc(64, &m) != 0); /* no new allocation after a latch */ - omega_gpu_session_unlock(); - EXPECT(fk.frees == frees_before); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 0 && fk.frees == frees_before); /* close refused: nothing released */ - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL && strstr(omega_gpu_session_last_error(), "latched") != NULL); - OmegaGpuLaunch L = launch_desc(10); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(strstr(omega_gpu_session_last_error(), "process latched") != NULL); - omega_gpu_session_unlock(); - EXPECT(omega_gpu_session_set_platform(&g_plat, &g_caps) == OMEGA_GPU_PLAT_REFUSED_BUSY); - EXPECT(fk.irq_calls == 0); -} - -static void c_timeout_parks(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - OmegaGpuMem user; - EXPECT(omega_gpu_session_alloc(4096, &user) == 0); - fk.mode = MODE_HANG; - OmegaGpuLaunch L = launch_desc(25); - const uint64_t t0 = fk.ns; - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(strstr(omega_gpu_session_last_error(), "timed out") != NULL); - EXPECT(fk.polls >= 25 && fk.ns - t0 >= 25ull * 1000000u); /* polled in 1 ms slices for the whole timeout */ - EXPECT(fk.retires == 0); /* never retired: the entry may still be in flight */ - OmegaGpuBufferHandle uh = user.handle; - omega_gpu_session_free(&user); - EXPECT(user.cpu == NULL && omega_gpu_session_is_parked(uh)); - EXPECT(omega_gpu_session_is_parked(s->marker.handle) && omega_gpu_session_is_parked(s->pb.handle)); - omega_gpu_session_unlock(); - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 5); - EXPECT(fk.frees == 0 && fk.t.nlive == 1 + 1 + 5); /* device, queue, 5 buffers: all still allocated */ - /* the generic latch checks expect the four session buffers; the user buffer made it five */ - EXPECT(omega_gpu_session_is_blocked()); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 0 && fk.frees == 0); -} - -static void c_cancel_after_submit(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - fk.mode = MODE_HANG; - fk.cancel_on_poll = 1; /* the cancel arrives while the host is polling */ - OmegaGpuLaunch L = launch_desc(60000); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); - EXPECT(fk.submits == 1 && fk.polls <= 2); /* seen within one poll slice, not after the 60 s timeout */ - EXPECT(strstr(omega_gpu_session_last_error(), "cancelled after submit") != NULL); - omega_gpu_session_unlock(); - check_latched(0); -} - -static void c_timeout_latch_rules(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - fk.mode = MODE_HANG; - OmegaGpuLaunch L = launch_desc(3); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - omega_gpu_session_unlock(); - check_latched(0); -} - -static void c_stale_after_reopen(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - const OmegaGpuDeviceHandle d1 = s->dev; - OmegaGpuMem old; - EXPECT(omega_gpu_session_alloc(8192, &old) == 0); - omega_gpu_session_unlock(); - omega_gpu_session_close(); /* the caller kept `old` past the close */ - EXPECT(fk.dev_closes == 1); - omega_gpu_session_lock(); - s = omega_gpu_session_open(); - EXPECT(s != NULL && omega_gpu_session_open_count() == 2); - EXPECT(s->dev.index != d1.index || s->dev.generation != d1.generation); /* a new device generation */ - const unsigned frees = fk.frees; - OmegaGpuAllocStats st0, st1; - omega_gpu_session_alloc_stats(&st0); - omega_gpu_session_free(&old); /* a handle of the closed device: refused, nothing released */ - omega_gpu_session_alloc_stats(&st1); - EXPECT(st1.stale_refusals == st0.stale_refusals + 1 && st1.frees == st0.frees); - EXPECT(fk.frees == frees && fk.free_refusals == 1); - EXPECT(strstr(omega_gpu_session_last_error(), "STALE") != NULL || strstr(omega_gpu_session_last_error(), "stale") != NULL); - EXPECT(old.cpu == NULL); - OmegaGpuLaunch L = launch_desc(100); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the reopened session works */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 2 && fk.t.nlive == 0); -} - -static void c_open_failure_text(void) { - fk_reset(); - EXPECT(install() == 0); - fk.fail_open = 1; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strstr(omega_gpu_session_last_error(), "fake device: no GB10 here") != NULL); /* the driver text survives */ - EXPECT(!omega_gpu_session_is_blocked() && fk.allocs == 0); - fk.fail_open = 0; - EXPECT(omega_gpu_session_open() != NULL); /* a failed open is not a latch */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); -} - -static void c_reservation_refusal(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - OmegaGpuScratch sc; memset(&sc, 0, sizeof sc); - EXPECT(omega_gpu_session_scratch_reserve(&sc, 10000) == 0); - const unsigned allocs = fk.allocs; - EXPECT(omega_gpu_session_scratch(&sc, 9000) == 0); - EXPECT(omega_gpu_session_scratch(&sc, sc.cap + 1) == OMEGA_GPU_SESSION_SCRATCH_RESERVED); - EXPECT(fk.allocs == allocs); /* refused loudly, nothing allocated */ - EXPECT(strstr(omega_gpu_session_last_error(), "serving reservation exceeded") != NULL); - omega_gpu_session_scratch_free(&sc); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.t.nlive == 0); -} - -static void c_matmul_code_buffer(void) { - fk_reset(); - EXPECT(install() == 0); - uint16_t b[32 * 16]; - memset(b, 0, sizeof b); - OmegaGpuTensor *t = NULL; - EXPECT(omega_gpu_tensor_upload_bf16(32, 16, b, &t) == OMEGA_GPU_MATMUL_OK); - uint16_t a[32]; memset(a, 0, sizeof a); - float c[16]; - OmegaGpuMatmulInfo info; - /* the fake device runs no kernel, so the result sentinels survive: CHIP_FAIL is the expected verdict here */ - int rc = omega_gpu_matmul_resident_bf16(1, a, t, c, &info); - EXPECT(rc == OMEGA_GPU_MATMUL_CHIP_FAIL && fk.submits >= 1); - unsigned code_bufs = 0; - for (uint32_t i = 0; i < NB; i++) - if (fk.t.live[i] && fk.t.kind[i] == OMEGA_GPU_HANDLE_BUF_CODE) { - code_bufs++; - const uint8_t *p = fk.mem[i]; - unsigned nz = 0; - for (uint32_t j = 0; j < 64; j++) nz += p[j] != 0; - EXPECT(nz > 0); /* the kernel was encoded in place into the device code buffer */ - EXPECT((fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); - } - EXPECT(code_bufs == 1); - EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0 && fk.irq_calls == 0); - omega_gpu_tensor_free(t); - omega_gpu_session_close(); - EXPECT(fk.t.nlive == 0); -} - -static void c_wait_needs_clock(void) { - volatile uint32_t word = 0; - omega_gpu_wait_report_t r; - EXPECT(!omega_gpu_wait_fixed(&word, 1, &r, NULL)); - EXPECT(r.result == OMEGA_GPU_WAIT_INVALID_STATE); /* no clock in the freestanding build: refused, not unbounded */ -} - -static void c_fmt_matches_snprintf(void) { - char a[96], b[96]; - const long long big = -9223372036854775807LL - 1; - omega_gpu_fmt(a, sizeof a, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, - -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); - snprintf(b, sizeof b, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, - -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); - EXPECT(strcmp(a, b) == 0); - char s[8]; - memset(s, 'Z', sizeof s); - omega_gpu_fmt(s, 6, "%s", "truncate me"); - EXPECT(strcmp(s, "trunc") == 0 && s[6] == 'Z' && s[7] == 'Z'); /* bounded: NUL inside cap, nothing past it */ - omega_gpu_fmt(s, 1, "%d", 123); - EXPECT(s[0] == '\0'); -} - -typedef struct { const char *id; void (*fn)(void); } Case; -static const Case CASES[] = { - {"INSTALL_REFUSALS_ABI_1_1", c_install_refusals}, - {"FREESTANDING_NO_DEFAULT_PLATFORM", c_no_default_platform}, - {"OPEN_LAUNCH_CLOSE_TYPED_UNCACHED_POLLING", c_open_launch_close}, - {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, - {"CANCEL_BEFORE_SUBMIT_NOT_LATCHED", c_cancel_before_submit}, - {"CANCEL_AFTER_SUBMIT_LATCHES_AND_PARKS", c_cancel_after_submit}, - {"TIMEOUT_PARKS_NEVER_RELEASES", c_timeout_parks}, - {"TIMEOUT_LATCH_REFUSES_CLOSE_REOPEN_INSTALL", c_timeout_latch_rules}, - {"STALE_HANDLE_REFUSED_AFTER_CLOSE_REOPEN", c_stale_after_reopen}, - {"SERVING_RESERVATION_REFUSES_WITHOUT_ALLOC", c_reservation_refusal}, - {"MATMUL_CODE_BUFFER_ENCODED_IN_PLACE", c_matmul_code_buffer}, - {"WAIT_REFUSES_WITHOUT_CLOCK", c_wait_needs_clock}, - {"FMT_BOUNDED_MATCHES_SNPRINTF", c_fmt_matches_snprintf}, -}; - -int main(void) { - int pass = 0, fail = 0; - for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int st = 0; - waitpid(pid, &st, 0); - const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; - printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); - if (ok) pass++; else fail++; - } - printf("test_omega_gpu_session_platform: %d passed, %d failed\n", pass, fail); - return fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_wait.c b/tests/test_omega_gpu_wait.c deleted file mode 100644 index 77a1af740..000000000 --- a/tests/test_omega_gpu_wait.c +++ /dev/null @@ -1,303 +0,0 @@ -/* Host test for src/omega_gpu_wait.c: fake memory, fake clock, no GPU. - * Every scenario runs against the real primitive (must behave) and against - * mutants (a naive wall-clock loop, a fixed wait that accepts overshoot, a - * sequence wait with an unsigned compare). Each mutant must be killed by the - * scenarios named for it, otherwise this test fails. */ -#include "omega_gpu_wait.h" - -#include -#include - -typedef struct { - uint64_t t_ns; - uint64_t step_ns; /* clock advance per relax */ - uint64_t relaxes; - uint64_t barriers; - uint64_t at[32]; - volatile uint32_t *target[32]; - uint32_t value[32]; - int nsched; - uint32_t invalid_value; /* valid() rejects this value when nonzero */ - int abort_at; /* abort() true once relaxes >= abort_at when nonzero */ - uint64_t snaps; /* polls seen by the snapshot hook (it runs right after the reads) */ - uint64_t last_snap_barriers; - uint64_t order_violations; /* polls whose reads were not preceded by a fresh barrier */ -} Fake; - -static uint64_t fk_now(void *c) { return ((Fake *)c)->t_ns; } -static void fk_barrier(void *c) { ((Fake *)c)->barriers++; } -static void fk_relax(void *c) { - Fake *f = c; - f->relaxes++; - f->t_ns += f->step_ns; - for (int i = 0; i < f->nsched; i++) - if (f->at[i] == f->relaxes) *f->target[i] = f->value[i]; -} -static void fk_snapshot(void *c, uint32_t out[2]) { - Fake *f = c; - out[0] = out[1] = 0; - f->snaps++; - if (f->barriers <= f->last_snap_barriers) f->order_violations++; - f->last_snap_barriers = f->barriers; -} -static bool fk_valid(void *c, uint32_t v) { return !((Fake *)c)->invalid_value || v != ((Fake *)c)->invalid_value; } -static bool fk_abort(void *c) { Fake *f = c; return f->abort_at && f->relaxes >= (uint64_t)f->abort_at; } - -typedef bool (*WaitFn)(volatile uint32_t *, uint32_t, omega_gpu_wait_report_t *, const omega_gpu_wait_cfg_t *); - -/* Mutants. mode 0: naive wall clock (single deadline, unsigned <, no progress - * tracking, no marker2, no barrier, no report). mode 1: exact for sequence too - * is not needed; mode "fixed_ge": signed >= for a fixed wait. mode "seq_unsigned": - * unsigned >= for a sequence wait. The last two keep everything else correct. */ -static bool naive_wait(volatile uint32_t *word, uint32_t want, omega_gpu_wait_report_t *rpt, - const omega_gpu_wait_cfg_t *cfg) { - uint64_t start = cfg->now_ns(cfg->hook_ctx); - uint64_t lim = 1000000ull * cfg->progress_timeout_ms; - if (rpt) memset(rpt, 0, sizeof(*rpt)); - while (*word < want) { - if (cfg->now_ns(cfg->hook_ctx) - start >= lim) return false; - cfg->relax(cfg->hook_ctx); - } - return true; -} -static bool mut_loop(int cmp, volatile uint32_t *w, uint32_t want, omega_gpu_wait_report_t *rpt, - const omega_gpu_wait_cfg_t *cfg, omega_gpu_wait_kind_t kind) { - /* Correct kind-aware wait with one comparison replaced; delegate the rest - * to the real primitive by wrapping the watched value would be circular, so - * implement the minimal real loop here. */ - uint64_t start = cfg->now_ns(cfg->hook_ctx), last = start; - uint64_t stall = 1000000ull * cfg->progress_timeout_ms; - uint32_t prev = *w; - if (rpt) { memset(rpt, 0, sizeof(*rpt)); rpt->wait_kind = kind; rpt->expected = want; } - for (;;) { - cfg->barrier(cfg->hook_ctx); - uint32_t m = *w, m2 = cfg->marker2 ? *cfg->marker2 : 0; - bool ok = cmp == 0 ? m == want : cmp == 1 ? (int32_t)(m - want) >= 0 : m >= want; - if (rpt) { rpt->last_observed = m; rpt->last_marker2 = m2; } - if (ok && (!cfg->marker2 || m2 == cfg->marker2_want)) { - cfg->barrier(cfg->hook_ctx); - if (rpt) rpt->result = OMEGA_GPU_WAIT_PASS; - return true; - } - uint64_t now = cfg->now_ns(cfg->hook_ctx); - if (m != prev) { prev = m; last = now; if (rpt) rpt->progress_count++; } - if (now - last >= stall) { if (rpt) rpt->result = OMEGA_GPU_WAIT_STALLED; return false; } - cfg->relax(cfg->hook_ctx); - } -} -static bool mut_fixed_ge(volatile uint32_t *w, uint32_t v, omega_gpu_wait_report_t *r, const omega_gpu_wait_cfg_t *c) { - return mut_loop(1, w, v, r, c, OMEGA_GPU_WAIT_FIXED); -} -static bool mut_seq_unsigned(volatile uint32_t *w, uint32_t v, omega_gpu_wait_report_t *r, const omega_gpu_wait_cfg_t *c) { - return mut_loop(2, w, v, r, c, OMEGA_GPU_WAIT_SEQUENCE); -} - -static int g_fail, g_checks, g_quiet; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_fail++; if (!g_quiet) { printf(" FAIL: " __VA_ARGS__); printf("\n"); } } } while (0) - -static void setup(Fake *f, omega_gpu_wait_cfg_t *cfg) { - memset(f, 0, sizeof(*f)); - f->step_ns = 1000000ull; /* 1 ms per poll */ - memset(cfg, 0, sizeof(*cfg)); - cfg->progress_timeout_ms = 100; - cfg->total_timeout_ms = 100000; - cfg->now_ns = fk_now; - cfg->barrier = fk_barrier; - cfg->relax = fk_relax; - cfg->valid = fk_valid; - cfg->abort = fk_abort; - cfg->hook_ctx = f; -} -static void sched(Fake *f, uint64_t at, volatile uint32_t *t, uint32_t v) { - f->at[f->nsched] = at; f->target[f->nsched] = t; f->value[f->nsched] = v; f->nsched++; -} - -enum { S_NEVER, S_LATE, S_MARKER2, S_SEQ_WRAP, S_PROGRESS_RESETS, S_BARRIER, S_HARD_DEADLINE, - S_FIXED_OVERSHOOT, S_INVALID, S_ABORT, S_COUNT }; -static const char *names[S_COUNT] = {"never_written", "written_late", "marker2_gate", "seq_wrap32", - "progress_resets_idle", "barrier_each_read", "hard_deadline_with_progress", - "fixed_overshoot", "invalid_state", "abort"}; - -/* Returns failed checks. fx and sq are the fixed and sequence implementations. */ -static int scenario(const char *name, WaitFn fx, WaitFn sq, int which) { - volatile uint32_t w = 0, w2 = 0; - Fake f; - omega_gpu_wait_cfg_t cfg; - omega_gpu_wait_report_t r; - int before = g_fail; - bool ok; - setup(&f, &cfg); - - switch (which) { - case S_NEVER: - ok = sq(&w, 5, &r, &cfg); - CHECK(!ok, "%s: never-written marker must not pass", name); - CHECK(r.result == OMEGA_GPU_WAIT_STALLED, "%s: result STALLED (got %d)", name, r.result); - CHECK(r.last_observed == 0 && r.expected == 5 && r.wait_kind == OMEGA_GPU_WAIT_SEQUENCE, - "%s: report carries kind/expected/last-seen 0", name); - CHECK(r.elapsed_ns >= 100000000ull && r.progress_count == 0, "%s: elapsed %llu progress %llu", name, - (unsigned long long)r.elapsed_ns, (unsigned long long)r.progress_count); - break; - case S_LATE: - sched(&f, 60, &w, 7); - ok = fx(&w, 7, &r, &cfg); - CHECK(ok && r.result == OMEGA_GPU_WAIT_PASS && r.last_observed == 7, "%s: late fixed marker seen", name); - CHECK(r.progress_count == 1 && r.last_progress_ns > r.start_ns, "%s: progress recorded", name); - break; - case S_MARKER2: - cfg.marker2 = &w2; - cfg.marker2_want = 0x46464646u; - sched(&f, 10, &w, 3); - ok = fx(&w, 3, &r, &cfg); - CHECK(!ok, "%s: marker without marker2 must not pass", name); - CHECK(r.last_observed == 3 && r.last_marker2 == 0, "%s: report shows marker 3, marker2 0", name); - w = 0; w2 = 0; setup(&f, &cfg); - cfg.marker2 = &w2; - cfg.marker2_want = 0x46464646u; - sched(&f, 10, &w, 3); - sched(&f, 20, &w2, 0x46464646u); - ok = fx(&w, 3, &r, &cfg); - CHECK(ok && r.last_marker2 == 0x46464646u, "%s: both markers pass", name); - break; - case S_SEQ_WRAP: { - static const uint32_t tg[4] = {0xfffffffeu, 0xffffffffu, 0u, 1u}; - for (int i = 0; i < 4; i++) { - w = tg[i] - 1u; /* one step behind, wrapping through 0 */ - setup(&f, &cfg); - sched(&f, 10, &w, tg[i]); - ok = sq(&w, tg[i], &r, &cfg); - CHECK(ok, "%s: reaches target %08x from %08x", name, tg[i], tg[i] - 1u); - } - w = 3; setup(&f, &cfg); - ok = sq(&w, 0xffffffffu, &r, &cfg); - CHECK(ok, "%s: 3 is past 0xffffffff", name); - w = 0; setup(&f, &cfg); - ok = sq(&w, 0xfffffffeu, &r, &cfg); - CHECK(ok, "%s: 0 is past 0xfffffffe", name); - w = 0xfffffff0u; setup(&f, &cfg); - ok = sq(&w, 0xffffffffu, &r, &cfg); - CHECK(!ok, "%s: 0xfffffff0 is before 0xffffffff", name); - w = 0xfffffffeu; setup(&f, &cfg); - ok = sq(&w, 1, &r, &cfg); - CHECK(!ok, "%s: 0xfffffffe is before 1", name); - break; - } - case S_PROGRESS_RESETS: - for (int i = 0; i < 4; i++) sched(&f, 60u * (i + 1), &w, (uint32_t)(i + 1)); - ok = sq(&w, 4, &r, &cfg); /* 240 ms total, 60 ms gaps, 100 ms stall bound */ - CHECK(ok, "%s: steady progress must not stall", name); - CHECK(r.progress_count == 4, "%s: progress_count %llu", name, (unsigned long long)r.progress_count); - break; - case S_BARRIER: - sched(&f, 5, &w, 1); - cfg.snapshot = fk_snapshot; /* runs after the reads of each poll: marks where the read happened */ - cfg.snapshot_ctx = &f; - ok = sq(&w, 1, &r, &cfg); - CHECK(ok && r.polls > 0 && f.barriers >= r.polls + 1, "%s: barriers %llu polls %llu", name, - (unsigned long long)f.barriers, (unsigned long long)r.polls); - CHECK(f.snaps == r.polls && f.order_violations == 0, "%s: a barrier must precede every read (%llu of %llu polls unordered)", name, - (unsigned long long)f.order_violations, (unsigned long long)f.snaps); - CHECK(f.barriers > f.last_snap_barriers, "%s: barrier after the PASS observation", name); - break; - case S_HARD_DEADLINE: - cfg.total_timeout_ms = 200; - for (int i = 0; i < 30; i++) sched(&f, (uint64_t)(20 * (i + 1)), &w, (uint32_t)(i + 1)); - ok = sq(&w, 99, &r, &cfg); /* moves every 20 ms, never arrives */ - CHECK(!ok && r.result == OMEGA_GPU_WAIT_TIMEOUT, "%s: hard deadline TIMEOUT (got %d)", name, r.result); - CHECK(r.progress_count > 3, "%s: progress was occurring (%llu)", name, (unsigned long long)r.progress_count); - break; - case S_FIXED_OVERSHOOT: - sched(&f, 10, &w, 5); /* jumps past the fixed value 3 */ - ok = fx(&w, 3, &r, &cfg); - CHECK(!ok, "%s: fixed wait must not accept overshoot 5 for 3", name); - CHECK(r.result == OMEGA_GPU_WAIT_STALLED && r.last_observed == 5, "%s: stalled, saw 5", name); - w = 0; setup(&f, &cfg); - sched(&f, 10, &w, 5); - ok = sq(&w, 3, &r, &cfg); - CHECK(ok, "%s: sequence wait accepts 5 for target 3", name); - break; - case S_INVALID: - f.invalid_value = 9; - sched(&f, 10, &w, 9); - ok = sq(&w, 20, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_INVALID_STATE && r.last_observed == 9, - "%s: invalid value reported (got %d)", name, r.result); - break; - case S_ABORT: - f.abort_at = 7; - ok = sq(&w, 20, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_ABORTED, "%s: abort reported (got %d)", name, r.result); - break; - } - return g_fail - before; -} - -/* CHIPWAIT-1c: QUEUE_WRAP marker2 pattern (src/omega_world_gates.c). Every entry of a - * batch but the last writes its dispatch_id to marker2; the last writes the sentinel - * 0x46464646. A sequence wait for the sentinel must not accept dispatch ids (even a - * high one), and must pass when the sentinel lands. */ -static int sentinel_batch(void) { - volatile uint32_t w2 = 0; - Fake f; - omega_gpu_wait_cfg_t cfg; - omega_gpu_wait_report_t r; - int before = g_fail; - setup(&f, &cfg); - for (uint32_t id = 1; id <= 15; id++) sched(&f, id, &w2, 3000u + id); - bool ok = omega_gpu_wait_sequence(&w2, 0x46464646u, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_STALLED && r.last_observed == 3015u, - "sentinel: dispatch ids alone must not satisfy the sentinel wait (got %d, observed %u)", r.result, r.last_observed); - w2 = 0; - setup(&f, &cfg); - for (uint32_t id = 1; id <= 15; id++) sched(&f, id, &w2, 3000u + id); - sched(&f, 16, &w2, 0x46464646u); - ok = omega_gpu_wait_sequence(&w2, 0x46464646u, &r, &cfg); - CHECK(ok && r.result == OMEGA_GPU_WAIT_PASS && r.last_observed == 0x46464646u, - "sentinel: last entry's sentinel passes (got %d, observed %u)", r.result, r.last_observed); - return g_fail - before; -} - -typedef struct { - const char *label; - WaitFn fx, sq; - unsigned must_kill; /* bitmask of scenarios that must kill this mutant */ -} Mutant; - -int main(void) { - for (int s = 0; s < S_COUNT; s++) { - int bad = scenario(names[s], omega_gpu_wait_fixed, omega_gpu_wait_sequence, s); - printf("real %-28s %s\n", names[s], bad ? "FAIL" : "ok"); - } - { int bad = sentinel_batch(); printf("real %-28s %s\n", "queue_wrap_sentinel", bad ? "FAIL" : "ok"); } - int real_fail = g_fail; - - const Mutant muts[] = { - {"naive_wall_clock", naive_wait, naive_wait, (1u << S_COUNT) - 1u}, - {"fixed_accepts_overshoot", mut_fixed_ge, omega_gpu_wait_sequence, 1u << S_FIXED_OVERSHOOT}, - {"seq_unsigned_compare", omega_gpu_wait_fixed, mut_seq_unsigned, 1u << S_SEQ_WRAP}, - }; - int saved = g_fail, kill_total = 0, kill_need = 0; - g_quiet = 1; - for (unsigned m = 0; m < sizeof(muts) / sizeof(muts[0]); m++) { - unsigned killed = 0; - for (int s = 0; s < S_COUNT; s++) { - if (scenario(names[s], muts[m].fx, muts[m].sq, s) > 0) killed |= 1u << s; - } - g_fail = saved; - g_quiet = 0; - for (int s = 0; s < S_COUNT; s++) { - if (!(muts[m].must_kill & (1u << s))) continue; - kill_need++; - g_checks++; - if (killed & (1u << s)) kill_total++; - else { g_fail++; printf(" FAIL: mutant %s survived scenario %s\n", muts[m].label, names[s]); } - } - printf("mutant %-26s killed mask %03x (required %03x)\n", muts[m].label, killed, muts[m].must_kill); - saved = g_fail; - g_quiet = 1; - } - g_quiet = 0; - printf("gpu_wait: checks=%d real_failures=%d required_kills=%d/%d\n", g_checks, real_fail, kill_total, kill_need); - printf("%s\n", g_fail ? "OMEGA_GPU_WAIT_HOST FAIL" : "OMEGA_GPU_WAIT_HOST PASS"); - return g_fail ? 1 : 0; -} diff --git a/tools/cudapp-link.sh b/tools/cudapp-link.sh new file mode 100755 index 000000000..3d656df8b --- /dev/null +++ b/tools/cudapp-link.sh @@ -0,0 +1,48 @@ +#!/bin/sh +# cudapp-link.sh CUDAPP_DIR: make Omega whole again from the pinned CUDA++ checkout. +# The GPU toolchain, runtime and libraries moved to CUDA++ (aien-dev/CUDAplusplus, MIT) on +# 2026-10-21. Omega keeps building them from the same paths: every path in cudapp.files becomes a +# symbolic link to the same path in CUDAPP_DIR, so every Makefile rule and script works unchanged. +# Checks first (unless CUDAPP_LOCK_CHECK=0): CUDAPP_DIR is a git checkout at the commit in cudapp.lock +# and has no local edits under the linked paths. Make runs this on every invocation (Makefile top). +# +# No CUDA++ (CUDAPP_DIR=/nonexistent, like PHYSICS_DIR=/nonexistent, or offline on first use): a note, +# nothing linked, exit 0; host lanes that need no GPU file still build, the others fail on the +# missing file. Exit non-zero only for a wrong commit, local edits, or a real file in a linked path. +set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +dir=${1:?usage: cudapp-link.sh CUDAPP_DIR} +case $dir in /*) ;; *) dir=$root/$dir ;; esac +want=$(tr -d '[:space:]' < "$root/cudapp.lock") + +if [ ! -d "$dir/src" ] && [ "$dir" = "$root/build/cudapp" ]; then + # first use from a fresh omega checkout: fetch CUDA++ at the pinned commit (https, then ssh while the repo is private) + mkdir -p "$root/build" + if git clone -q "${CUDAPP_URL:-https://github.com/aien-dev/CUDAplusplus}" "$dir" 2>/dev/null || + git clone -q git@github.com:aien-dev/CUDAplusplus.git "$dir" 2>/dev/null; then + git -C "$dir" checkout -q "$want" || { echo "cudapp-link: CUDA++ has no commit $want" >&2; exit 1; } + echo "cudapp-link: fetched CUDA++ $want into $dir" >&2 + else + rm -rf "$dir" + fi +fi +if [ ! -d "$dir/src" ]; then + echo "cudapp-link: note: no CUDA++ at CUDAPP_DIR=$1; GPU files not linked (clone git@github.com:aien-dev/CUDAplusplus.git next to omega for GPU targets)" >&2 + exit 0 +fi + +if [ "${CUDAPP_LOCK_CHECK:-1}" != 0 ]; then + got=$(git -C "$dir" rev-parse HEAD 2>/dev/null) || { echo "cudapp-link: $dir is not a git checkout" >&2; exit 1; } + [ "$got" = "$want" ] || { echo "cudapp-link: CUDAPP_DIR=$dir is at $got but cudapp.lock pins $want (git -C $dir checkout $want, or CUDAPP_LOCK_CHECK=0)" >&2; exit 1; } + dirty=$(git -C "$dir" status --porcelain -- $(grep -v '^#' "$root/cudapp.files") | head -3) + [ -z "$dirty" ] || { echo "cudapp-link: CUDAPP_DIR has local edits in linked files (commit them in CUDA++ and move cudapp.lock):" >&2; echo "$dirty" >&2; exit 1; } +fi + +grep -v '^#' "$root/cudapp.files" | while IFS= read -r p; do + [ -n "$p" ] || continue + [ -e "$dir/$p" ] || { echo "cudapp-link: $p missing in CUDAPP_DIR" >&2; exit 1; } + target=$(realpath -m --relative-to="$root/$(dirname "$p")" "$dir/$p") + if [ -L "$root/$p" ] && [ "$(readlink "$root/$p")" = "$target" ]; then continue; fi + [ ! -e "$root/$p" ] || [ -L "$root/$p" ] || { echo "cudapp-link: $p is a real file in omega; it belongs to CUDA++ (move the change there)" >&2; exit 1; } + ln -sfn "$target" "$root/$p" +done diff --git a/tools/gpu_engine_backend_mutations.sh b/tools/gpu_engine_backend_mutations.sh deleted file mode 100755 index ab7a27efe..000000000 --- a/tools/gpu_engine_backend_mutations.sh +++ /dev/null @@ -1,175 +0,0 @@ -#!/bin/sh -# Omega GPU Engine BACKEND mutation sweep (cut A3b2), a thin adapter over -# tools/mutation_runner.sh, table reader. One mutant per protection in -# src/omega_blackwell_engine.c (the Blackwell backend) and in the vector wrapper -# omega_blackwell_execute_vector (src/omega_blackwell_submit.c). For each row the -# runner copies the needed files to a scratch directory, breaks that one -# protection, rebuilds tests/test_omega_blackwell_engine.c there (against the -# simulated driver tests/fake_m16_native.c) and requires it to FAIL. A mutant that -# does not apply, does not build or is not caught fails the sweep (exit nonzero), -# unless its row carries class "redundant" with a rationale. -# Host only, no device, no GPU, no physics C sources (the driver is the fake). -# The link set is the Makefile RX_COMPOSE_GPU_SRCS list plus the three core files the vector builder needs -# (omega_core.c, omega_canonical.c, sha256.c), with the fake driver in place of physics m16_native.c and nvrm.c. -# Shell only (no Python). The real sources carry no marker comments: the rows -# find their text with exact-once matches (R:) or line ranges (sed), and the -# runner reports "edit did not apply" if a row stops matching. -# Each mutant, what it guards and why a redundant one is redundant are listed in -# docs/numeric/OMEGA_GPU_ENGINE.md section 14.1. Set GPU_ENGINE_BMUT_OUT=path.json -# to also keep the JSON receipt. NOT_RUN in Phase A. -# -# Row format: id~files~edit~guards[~class~rationale]. A row cannot contain a tilde, -# so the one line that contains ~ (the poison complement) is matched with "." in a -# sed row. Edit kinds: "R:from@>@to" (from must match exactly once) or a sed -# expression (a "& " in a replacement is written \&; ranges like -# /^static int be_close/,/^}/ keep an edit inside one function). -set -u -cd "$(dirname "$0")/.." || exit 2 -unset ONLY - -# The scratch copy lives in /tmp, where ../physics does not resolve, so the physics -# path is made absolute here (PHYSICS_DIR, default ../physics). -PHYS=$(cd "${PHYSICS_DIR:-../physics}" 2>/dev/null && pwd -P) || { - echo "gpu_engine_backend_mutations: physics directory not found (set PHYSICS_DIR)" >&2 - exit 2 -} -TP=$PHYS/third_party/nvidia-open-580.173.02 -INC="-I$PHYS/m16 -I$PHYS/nvrm -I$TP/src/common/sdk/nvidia/inc -I$TP/kernel-open/common/inc -I$TP/kernel-open/nvidia-uvm -I$TP/src/nvidia/arch/nvalloc/unix/include" -SRCS="src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c src/omega_blackwell_realize.c src/omega_vector.c src/omega_validate.c src/omega_core.c src/omega_canonical.c src/sha256.c" -BUILD="gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -ffunction-sections -fdata-sections -Isrc -Itests $INC -o .gpu_engine_bt tests/test_omega_blackwell_engine.c tests/fake_m16_native.c $SRCS -Wl,--gc-sections -lm" - -OUT=${GPU_ENGINE_BMUT_OUT:-} -set -- -k table -m - -t ./.gpu_engine_bt -b "$BUILD" \ - -c "src tests/test_omega_blackwell_engine.c tests/fake_m16_native.c tests/fake_m16_native.h" \ - -f '\[FAIL\]' -B -[ -z "$OUT" ] || set -- "$@" -o "$OUT" - -tools/mutation_runner.sh "$@" <<'ROWS' -# ---- allocation checks and frees ------------------------------------------------ -BE_ALLOC_CHECK_CPU~src/omega_blackwell_engine.c~R:if (!m->cpu || m->size < bytes ||@>@if (0 || m->size < bytes ||~a buffer without a CPU mapping is refused (ALLOC) -BE_ALLOC_CHECK_SIZE~src/omega_blackwell_engine.c~R:|| m->size < bytes ||@>@|| 0 ||~a buffer smaller than asked is refused (ALLOC) -BE_ALLOC_CHECK_ALIGN~src/omega_blackwell_engine.c~R:|| (m->va & 255u) != 0) {@>@|| 0) {~a GPU address that is not 256-byte aligned is refused (ALLOC) -BE_ALLOC_OWN_CHECK_NOTE~src/omega_blackwell_engine.c~R:note(c, "allocation failed its own checks (CPU mapping, size or 256-byte alignment)");@>@(void)0;~the backend's own refusal text reaches the result -BE_ALLOC_OWN_CHECK_FREE~src/omega_blackwell_engine.c~R:(void)nvrm_free(&c->m.rm, m);@>@(void)0;~a buffer that fails its own checks is freed, not leaked -BE_ROLE_FREE_SKIPPED~src/omega_blackwell_engine.c~R:rc = nvrm_free(&c->m.rm, m);@>@rc = 0;~free_buf really frees a program, input or output buffer -BE_SCRATCH_FREE_SKIPPED~src/omega_blackwell_engine.c~R:int rc = nvrm_free(&c->m.rm, parts[i]);@>@int rc = (parts[i] == NULL) ? -1 : 0;~release_scratch really frees all four SCRATCH parts -BE_SCRATCH_FREE_ERROR_DROPPED~src/omega_blackwell_engine.c~R:if (rc != 0 && first == 0) first = rc;@>@if (0 && rc != 0 && first == 0) first = rc;~a failed SCRATCH part free is reported -BE_SCRATCH_FREE_STOPS_AT_ERROR~src/omega_blackwell_engine.c~R:if (rc != 0 && first == 0) first = rc;@>@if (rc != 0) { first = rc; break; }~one failed SCRATCH part free does not leave the other parts allocated -BE_SCRATCH_ALLOC_FAIL_NO_RELEASE~src/omega_blackwell_engine.c~R:(void)release_scratch(c);@>@(void)0;~a failed SCRATCH allocation frees the parts that did succeed (the core does not) -BE_ERRNO_NOT_RESTORED~src/omega_blackwell_engine.c~R:errno = saved_errno;@>@(void)saved_errno;~the frees after a failed SCRATCH allocation do not clobber the errno the core reads -BE_ALLOC_FAIL_TEXT_RESTORE~src/omega_blackwell_engine.c~R:copy_text(c->text, sizeof c->text, keep);@>@(void)keep;~the failure text survives the cleanup frees~redundant~release_scratch writes neither c->text nor the driver text on a successful free, in the simulated driver and in nvrm_free (physics nvrm.h: free only zeroes the NvrmMem); the restore is a safety net for a driver that writes text on success, which no model here does -BE_SCRATCH_PB_NOT_INSTALLED~src/omega_blackwell_engine.c~R:c->m.pb_mem = c->pb;@>@(void)0;~the large pushbuffer ring replaces the channel's 4 KiB buffer -BE_PB_REPLACED_RESET~src/omega_blackwell_engine.c~R:c->pb_replaced = 0;@>@(void)0;~the flag that records the replaced ring is cleared after SCRATCH is freed~redundant~the zeroing of m.pb_mem stays (it is a separate line); a stale flag only repeats that harmless zeroing, and open memsets the whole context each run. physics m16_native_close is only nvrm_close(&ctx->rm) and never reads pb_mem -# ---- busy flag and open ---------------------------------------------------------- -BE_BUSY_CHECK_DROPPED~src/omega_blackwell_engine.c~R:if (atomic_flag_test_and_set(&g_busy)) return -1;@>@(void)atomic_flag_test_and_set(&g_busy);~a second open while a run is retained is refused -BE_OPEN_FAIL_KEEPS_BUSY~src/omega_blackwell_engine.c~/^static int be_open_device/,/^}/ s/atomic_flag_clear(&g_busy);/(void)0;/~a failed open releases the busy flag -BE_CLOSE_BUSY_CLEAR_DROPPED~src/omega_blackwell_engine.c~/^static int be_close/,/^}/ s/atomic_flag_clear(&g_busy);/(void)0;/~close releases the busy flag so the next run can open -BE_OPEN_MEMSET_DROPPED~src/omega_blackwell_engine.c~R:memset(c, 0, sizeof *c);@>@(void)0;~open resets the whole context, including the previous run's snapshot -BE_OPEN_NATIVE_FLAG_DROPPED~src/omega_blackwell_engine.c~R:c->native_open = 1;@>@(void)0;~a failed open still reports the driver's own text -BE_OPEN_ERROR_IGNORED~src/omega_blackwell_engine.c~/^static int be_open_device/,/^}/ s/return rc;/return 0;/~a failed driver open is reported (DEVICE_OPEN) -BE_OPEN_LAST_RC_DROPPED~src/omega_blackwell_engine.c~/^static int be_open_device/,/^}/ s/c->last_rc = rc;/(void)0;/~the failed open's driver code reaches the result -BE_CHANNEL_ERROR_IGNORED~src/omega_blackwell_engine.c~/^static int be_create_channel/,/^}/ s/return rc;/return 0;/~a failed channel create is reported (CHANNEL_CREATE) -BE_CHANNEL_LAST_RC_DROPPED~src/omega_blackwell_engine.c~/^static int be_create_channel/,/^}/ s/c->last_rc = rc;/(void)0;/~the failed channel create's driver code reaches the result -BE_ALLOC_LAST_RC_DROPPED~src/omega_blackwell_engine.c~/^static int alloc_checked/,/^}/ s/c->last_rc = rc;/(void)0;/~the failed allocation's driver code reaches the result -# ---- roles, rounding, copies ------------------------------------------------------- -BE_ALLOC_UNKNOWN_ROLE_ACCEPTED~src/omega_blackwell_engine.c~/^static int be_alloc/,/^}/ s/if (!m) {/if (0) {/~alloc refuses an unknown role -BE_ROLE_MEM_UPPER_BOUND~src/omega_blackwell_engine.c~R:|| role >= (int)OMEGA_GPU_BUF_ROLE_COUNT) return NULL;@>@|| 0) return NULL;~a role above the last one has no buffer slot -BE_ROLE_MEM_LOWER_BOUND~src/omega_blackwell_engine.c~R:if (role < (int)OMEGA_GPU_BUF_PROGRAM ||@>@if (0 ||~a negative role has no buffer slot -BE_ROUND_PAGES_ZERO_ACCEPTED~src/omega_blackwell_engine.c~R:if (bytes == 0 ||@>@if (0 ||~a zero-byte allocation is refused -BE_ROUND_PAGES_NO_ROUNDING~src/omega_blackwell_engine.c~s/v = ((uint64_t)bytes + (BE_PAGE - 1u)) & .(uint64_t)(BE_PAGE - 1u);/v = (uint64_t)bytes;/~allocation sizes round up to whole pages -BE_ROUND_PAGES_MINIMUM~src/omega_blackwell_engine.c~R:if (v < BE_PAGE) v = BE_PAGE;@>@(void)0;~one-page minimum~redundant~after the zero check, rounding any nonzero byte count up to a page multiple already gives at least one page, so the minimum can never apply -BE_COPY_IN_NO_MEMCPY~src/omega_blackwell_engine.c~R:memcpy(m->cpu, src, bytes);@>@(void)0;~copy_in really copies the program and the inputs -BE_COPY_IN_BOUNDS~src/omega_blackwell_engine.c~R:!src || (uint64_t)bytes > m->size@>@!src~copy_in refuses a length beyond the buffer -BE_COPY_IN_NULL_SOURCE~src/omega_blackwell_engine.c~R:!m->cpu || !src ||@>@!m->cpu ||~copy_in refuses a NULL source -BE_FILL_POISON_DROPPED~src/omega_blackwell_engine.c~R:memcpy(out->cpu, words, count * 4u);@>@(void)0;~the device output is pre-filled with the poison words -BE_FILL_POISON_SHORT~src/omega_blackwell_engine.c~R:memcpy(out->cpu, words, count * 4u);@>@memcpy(out->cpu, words, (count - 1u) * 4u);~every output word is pre-filled, including the last -BE_FILL_POISON_BOUNDS~src/omega_blackwell_engine.c~R:!words || (uint64_t)count * 4u > out->size@>@!words~fill_poison refuses a length beyond the output buffer -BE_COPY_OUT_NO_MEMCPY~src/omega_blackwell_engine.c~R:memcpy(dst, out->cpu, bytes);@>@(void)0;~copy_out really reads the device output back -BE_COPY_OUT_BOUNDS~src/omega_blackwell_engine.c~R:!dst || (uint64_t)bytes > out->size@>@!dst~copy_out refuses a length beyond the output buffer -# ---- build: arguments, descriptors, sync words, pushbuffer --------------------------- -BE_BUILD_LAYOUT_CHECK~src/omega_blackwell_engine.c~R:if (!job || job->layout != (int)OMEGA_GPU_LAYOUT_VECTOR_1D) {@>@if (0) {~build refuses a missing job and an unsupported layout -BE_BUILD_COUNT_OVERFLOW~src/omega_blackwell_engine.c~R:n == 0 || n > UINT32_MAX - 63u@>@n == 0~grid arithmetic overflow guard~redundant~an element count above UINT32_MAX - 63 needs at least 16 GiB of input, output and input buffers, so the buffer-size check in the same condition chain refuses it first; only the grid rounding (n + 63) could overflow, and it is never reached -BE_BUILD_BUFFERS_SIZE~src/omega_blackwell_engine.c~R:|| a->size < need || b->size < need || out->size < need) {@>@|| need == 1) {~build refuses buffers smaller than the element count needs -BE_C3_FLAG_IGNORED~src/omega_blackwell_engine.c~R:c->c3 = (job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0;@>@c->c3 = 1;~the NO_C3 flag removes the L2 flush and the second marker -BE_C3_NEVER~src/omega_blackwell_engine.c~R:c->c3 = (job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0;@>@c->c3 = 0;~with flags 0 the L2 flush and the second marker are in the pushbuffer -BE_THREADS_WRONG~src/omega_blackwell_engine.c~R:cfg.threads_per_block = 64;@>@cfg.threads_per_block = 32;~the launch covers every element -BE_GRID_ROUNDS_DOWN~src/omega_blackwell_engine.c~R:cfg.grid_width = (n + 63u) / 64u;@>@cfg.grid_width = n / 64u;~the grid rounds up so a partial last block still runs -BE_ARGS_C_SWAPPED~src/omega_blackwell_engine.c~R:a->va, b->va, out->va, n)@>@a->va, out->va, b->va, n)~the kernel writes the OUTPUT buffer -BE_ARGS_A_B_SWAPPED~src/omega_blackwell_engine.c~R:a->va, b->va, out->va, n)@>@b->va, a->va, out->va, n)~the kernel gets input A and input B in the right argument slots -BE_PROGRAM_VA~src/omega_blackwell_engine.c~R:cfg.code_va = code->va;@>@cfg.code_va = c->qmd.va;~the QMD points at the program buffer -BE_CBANK_VA~src/omega_blackwell_engine.c~R:cfg.cbank_va = c->cbank.va;@>@cfg.cbank_va = c->marker.va;~the QMD points at the constant bank buffer -BE_SEM_VA~src/omega_blackwell_engine.c~R:sem_va = c->qmd.va + BE_SEM_OFFSET;@>@sem_va = c->qmd.va + BE_SEM_OFFSET + 0x100u;~the QMD release semaphore address is the word the host waits on -BE_MARKER_VA~src/omega_blackwell_engine.c~R:marker_va = c->marker.va;@>@marker_va = c->marker.va + 0x20u;~the first release lands on the word the host waits on -BE_SEM_ZERO_DROPPED~src/omega_blackwell_engine.c~R:*c->hsem = 0;@>@(void)0;~the semaphore word is zeroed before the doorbell (no stale DONE) -BE_MARKER_ZERO_DROPPED~src/omega_blackwell_engine.c~R:*c->hmarker = 0;@>@(void)0;~the first marker word is zeroed before the doorbell (no stale payload) -BE_MARKER2_ZERO_DROPPED~src/omega_blackwell_engine.c~R:*c->hmarker2 = 0;@>@(void)0;~the second marker word is zeroed before the doorbell -BE_NOC3_MARKER2_REPORTED~src/omega_blackwell_engine.c~R:if (!c->c3) c->hmarker2 = NULL;@>@(void)0;~with NO_C3 the second marker is neither waited for nor reported -BE_MARKER2_OFFSET_CHANGED~src/omega_blackwell_engine.c~R:#define BE_MARKER2_OFFSET 0x10u@>@#define BE_MARKER2_OFFSET 0x20u~the second marker is 0x10 bytes after the first -BE_MARKER2_PAYLOAD_CHANGED~src/omega_blackwell_engine.c~R:#define BE_MARKER2_PAYLOAD 0x46464646u@>@#define BE_MARKER2_PAYLOAD 0x46464647u~the second marker payload is 0x46464646 -BE_RELEASE1_PAYLOAD_ZERO~src/omega_blackwell_engine.c~R:pb_put(c, OMEGA_BW_MARKER_COMPLETION_PAYLOAD);@>@pb_put(c, 0);~the first release writes the completion payload -BE_RELEASE2_PAYLOAD_ZERO~src/omega_blackwell_engine.c~R:pb_put(c, BE_MARKER2_PAYLOAD);@>@pb_put(c, 0);~the second release writes its payload -BE_FLUSH_OP_DROPPED~src/omega_blackwell_engine.c~R:pb_put(c, 0x10u << 27);@>@pb_put(c, 0);~the L2 flush operation word is L2_FLUSH_DIRTY -BE_FLUSH_METHOD_CHANGED~src/omega_blackwell_engine.c~R:pb_put(c, nvrm_mthd(0, 0x0028, 4));@>@pb_put(c, nvrm_mthd(0, 0x002c, 4));~the flush uses the memory-operation method -BE_WFI_FLAG_RELEASE1~src/omega_blackwell_engine.c~/pb_put(c, OMEGA_BW_MARKER_COMPLETION_PAYLOAD);/,+2 s/0x1u | (1u << 20)/0x1u/~the first release waits for idle (WFI) -BE_WFI_FLAG_RELEASE2~src/omega_blackwell_engine.c~/pb_put(c, BE_MARKER2_PAYLOAD);/,+2 s/0x1u | (1u << 20)/0x1u/~the second release waits for idle (WFI) -BE_BARRIER_IN_BUILD~src/omega_blackwell_engine.c~/^static int be_build/,/^}/ s/__asm__ volatile("dsb sy" ::: "memory");/(void)0;/~dsb sy after zeroing the sync words~redundant~a CPU barrier instruction has no effect a host test can observe (the fake driver runs on the same core); it is verified on the chip only (Phase B) -BE_QMD_RELEASE_CHECK~src/omega_blackwell_engine.c~R:if (qmd1_words[9] != 3u ||@>@if (0 ||~extra QMD1 release-word checks~redundant~the real descriptor builder always produces these words (src/omega_blackwell_qmd.c), so no input makes the check fire; it guards a future change of the builder, which tests/test_omega_blackwell_qmd.c style checks cover -BE_PB_OVERFLOW~src/omega_blackwell_engine.c~R:if (c->pb_overflow) {@>@if (0) {~pushbuffer word-capacity guard~redundant~the vector pushbuffer is a fixed 492 words against a 1024-word capacity, so it cannot overflow for any job -# ---- submit, waits, diagnostics ------------------------------------------------------ -BE_SUBMIT_NOTHING_BUILT~src/omega_blackwell_engine.c~R:if (c->pb_len == 0) {@>@if (0) {~submit before build is refused~redundant~the driver refuses an empty submission too (physics m16_native.c m16_native_enqueue_methods: count == 0 returns -1), so the result is the same refusal -BE_LAUNCH_NS_DROPPED~src/omega_blackwell_engine.c~R:c->info.launch_ns = now_ns();@>@(void)0;~the launch time is recorded before the doorbell -BE_SUBMIT_ERROR_IGNORED~src/omega_blackwell_engine.c~/^static int be_submit/,/^}/ s/return rc;/return 0;/~a failed submit is reported (SUBMIT), not treated as launched -BE_WAIT_UNMAPPED_ACCEPTED~src/omega_blackwell_engine.c~R:if (!w) {@>@if (0) {~a wait before build or after free is refused without a driver call -BE_WAIT_DRIVER_RC_DROPPED~src/omega_blackwell_engine.c~/^static int wait_word/,/^}/ s/if (rc != 0) {/if (0) {/~the driver's wait code reaches the result -BE_WAIT_RC_MAPPING~src/omega_blackwell_engine.c~R:return rc == -1 ? OMEGA_GPU_BACKEND_TIMEOUT : -2;@>@return rc;~timeout versus driver fault classification~redundant~the engine core treats every nonzero wait result the same (uncertain completion), and the real m16_native_wait_marker returns only 0 or -1 (m16_native.c) -BE_WAIT_EQUALITY_RECHECK~src/omega_blackwell_engine.c~R:if (*snap != want) {@>@if (0) {~an overshoot of the ">=" compare is refused (UNKNOWN_STATE) -BE_WAIT_SNAPSHOT_DROPPED~src/omega_blackwell_engine.c~R:*snap = *w;@>@(void)0;~the observed word is recorded after every wait -BE_MARKER_DONE_NS_ALWAYS~src/omega_blackwell_engine.c~R:if (rc == 0) c->info.marker_done_ns = now_ns();@>@c->info.marker_done_ns = now_ns();~the completion time is recorded only when the first marker wait succeeded -BE_WAIT_MARKER_WRONG_WORD~src/omega_blackwell_engine.c~R:wait_word(c, c->hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD@>@wait_word(c, c->hmarker2, OMEGA_BW_MARKER_COMPLETION_PAYLOAD~wait_marker waits on the first marker word -BE_WAIT_SEMAPHORE_WRONG_VALUE~src/omega_blackwell_engine.c~R:c->hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE,@>@c->hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT,~the release semaphore wait is for DONE (6), not the initial value (5) -BE_DIAG_DRV_RC_DROPPED~src/omega_blackwell_engine.c~R:d->drv_rc = c->last_rc;@>@d->drv_rc = 0;~diagnostics report the raw driver code -BE_DIAG_TEXT_OWN_DROPPED~src/omega_blackwell_engine.c~R:if (c->text[0] != '\0') copy_text(@>@if (0) copy_text(~diagnostics report the backend's own text -BE_DIAG_TEXT_DRIVER_DROPPED~src/omega_blackwell_engine.c~R:else if (c->native_open) copy_text(@>@else if (0) copy_text(~diagnostics fall back to the driver's text -BE_DIAG_MARKER_DROPPED~src/omega_blackwell_engine.c~R:d->marker = *c->hmarker;@>@d->marker = 0;~diagnostics report the first marker word -BE_DIAG_MARKER2_DROPPED~src/omega_blackwell_engine.c~R:d->marker2 = *c->hmarker2;@>@d->marker2 = 0;~diagnostics report the second marker word -BE_DIAG_SEMAPHORE_DROPPED~src/omega_blackwell_engine.c~R:d->semaphore[0] = *c->hsem;@>@d->semaphore[0] = 0;~diagnostics report the semaphore word -BE_DIAG_VALID_MARKER_DROPPED~src/omega_blackwell_engine.c~R:d->sync_valid |= OMEGA_GPU_SYNC_MARKER;@>@(void)0;~the first marker is flagged valid only when mapped -BE_DIAG_VALID_MARKER2_DROPPED~src/omega_blackwell_engine.c~R:d->sync_valid |= OMEGA_GPU_SYNC_MARKER2;@>@(void)0;~the second marker is flagged valid only when mapped -BE_DIAG_VALID_SEMAPHORE_DROPPED~src/omega_blackwell_engine.c~R:d->sync_valid |= OMEGA_GPU_SYNC_SEMAPHORE;@>@(void)0;~the semaphore is flagged valid only when mapped -# ---- free_buf and close --------------------------------------------------------------- -BE_FREE_SCRATCH_ROLE_DROPPED~src/omega_blackwell_engine.c~/^static int be_free_buf/,/^}/ s/if (role == (int)OMEGA_GPU_BUF_SCRATCH) {/if (0) {/~free_buf of SCRATCH frees the four SCRATCH parts -BE_FREE_UNKNOWN_ROLE_ACCEPTED~src/omega_blackwell_engine.c~/^static int be_free_buf/,/^}/ s/if (!m) {/if (0) {/~free_buf refuses an unknown role -BE_FREE_ERROR_DROPPED~src/omega_blackwell_engine.c~/^static int be_free_buf/,/^}/ s/return rc;/return 0;/~a failed free is reported (CLEANUP) -BE_RELEASE_KEEPS_MARKER_POINTER~src/omega_blackwell_engine.c~/^static int release_scratch/,/^}/ s/c->hmarker = NULL;/(void)0;/~the first marker word is unmapped before SCRATCH is freed -BE_RELEASE_KEEPS_MARKER2_POINTER~src/omega_blackwell_engine.c~/^static int release_scratch/,/^}/ s/c->hmarker2 = NULL;/(void)0;/~the second marker word is unmapped before SCRATCH is freed -BE_RELEASE_KEEPS_SEM_POINTER~src/omega_blackwell_engine.c~/^static int release_scratch/,/^}/ s/c->hsem = NULL;/(void)0;/~the semaphore word is unmapped before SCRATCH is freed -BE_CLOSE_KEEPS_MARKER_POINTER~src/omega_blackwell_engine.c~/^static int be_close/,/^}/ s/c->hmarker = NULL;/(void)0;/~close unmaps the first marker word -BE_CLOSE_KEEPS_MARKER2_POINTER~src/omega_blackwell_engine.c~/^static int be_close/,/^}/ s/c->hmarker2 = NULL;/(void)0;/~close unmaps the second marker word -BE_CLOSE_KEEPS_SEM_POINTER~src/omega_blackwell_engine.c~/^static int be_close/,/^}/ s/c->hsem = NULL;/(void)0;/~close unmaps the semaphore word -BE_CLOSE_NOT_CALLED~src/omega_blackwell_engine.c~R:rc = m16_native_close(&c->m);@>@rc = 0;~close really closes the driver -BE_CLOSE_ERROR_IGNORED~src/omega_blackwell_engine.c~/^static int be_close/,/^}/ s/return rc;/return 0;/~a failed close is reported (CLEANUP) -# ---- the vector wrapper (src/omega_blackwell_submit.c) ---------------------------------- -WRAP_POISON_NOT_COMPLEMENT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/poison\[i\] = .(uint32_t)(h_a\[i\] + h_b\[i\]);/poison[i] = (uint32_t)(h_a[i] + h_b[i]);/~the poison word is the complement of the expected sum -WRAP_POISON_CONSTANT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/poison\[i\] = .(uint32_t)(h_a\[i\] + h_b\[i\]);/poison[i] = 0xdeadbeefu;/~the poison word never collides with a legitimate sum (0xdeadbeef is one) -WRAP_ENGINE_FAILURE_IGNORED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/if (erc != OMEGA_GPU_ENGINE_OK) {/if ((void)erc, 0) {/~an engine failure (here a cleanup fault) fails the wrapper -WRAP_ORACLE_IGNORED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/return parity_res;/return 0;/~the host oracle decides success, not the engine -WRAP_PARITY_FLAG_FORCED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->parity_verified = (parity_res == 0);/exec_info->parity_verified = 1;/~parity_verified follows the oracle -WRAP_MARKER_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->completion_marker = info.marker;/exec_info->completion_marker = 0;/~the completion marker is reported -WRAP_SEMAPHORE_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->intermediate_semaphore = info.semaphore;/exec_info->intermediate_semaphore = 0;/~the semaphore value is reported -WRAP_LAUNCH_TIME_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->launch_timestamp_ns = info.launch_ns;/exec_info->launch_timestamp_ns = 0;/~the launch time is reported -WRAP_DONE_TIME_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->completion_timestamp_ns = info.marker_done_ns;/exec_info->completion_timestamp_ns = 0;/~the completion time is reported -WRAP_ELAPSED_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->elapsed_ns = .*$/exec_info->elapsed_ns = 0;/~the elapsed time is reported -WRAP_SM_ARCH_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->sm_architecture = real->sm_architecture;/exec_info->sm_architecture = 0;/~the architecture is reported -WRAP_ELEMENT_COUNT_NOT_REPORTED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/exec_info->element_count = n;/exec_info->element_count = 0;/~the element count is reported -WRAP_NULL_GUARD_DROPPED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/if (!spec || !real || !h_a || !h_b || !h_c_out) return -1;/(void)0;/~a NULL argument is refused before any use -WRAP_ZERO_COUNT_GUARD~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/if (n == 0) return -1;/(void)0;/~a zero element count is refused by the wrapper~redundant~the engine refuses element_count 0 as INVALID_ARGS (src/omega_gpu_engine.c job_valid) and the wrapper then returns -1, so the result is the same refusal -WRAP_MARKER_TIMEOUT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.timeouts.marker_ms = 5000;/job.timeouts.marker_ms = 6000;/~the first marker wait limit is 5000 ms -WRAP_SEMAPHORE_TIMEOUT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.timeouts.release_semaphore_ms = 5000;/job.timeouts.release_semaphore_ms = 6000;/~the semaphore wait limit is 5000 ms -WRAP_MARKER2_TIMEOUT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.timeouts.marker2_ms = 5000;/job.timeouts.marker2_ms = 6000;/~the second marker wait limit is 5000 ms -WRAP_VISIBILITY_TIMEOUT~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.timeouts.visibility_ms = 5000;/job.timeouts.visibility_ms = 6000;/~the visibility limit is 5000 ms~redundant~the Blackwell barrier callback ignores its timeout argument (it is a CPU dsb sy that cannot wait), so no host observation depends on the value -WRAP_FLAGS_ALL_PROTECTIONS~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.flags = 0;/job.flags = 1;/~the wrapper runs with every protection on (flags 0) -WRAP_BACKEND_NOT_INSTALLED~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/omega_gpu_engine_set_backend(omega_blackwell_engine_backend());/(void)0;/~the wrapper installs the Blackwell backend itself -WRAP_PROGRAM_LENGTH~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/job.program_len = encoded_len;/job.program_len = 16;/~the whole encoded program is handed to the engine -WRAP_MARKER_CHECK~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/if (info.marker != OMEGA_BW_MARKER_COMPLETION_PAYLOAD) return -1;/(void)0;/~second check of the marker payload~redundant~the backend wait_word already refuses any first-marker value other than 0x44444444 (UNKNOWN_STATE), so the engine fails before this line is reached -WRAP_SEMAPHORE_CHECK~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_vector/,/^}/ s/if (info.semaphore != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) return -1;/(void)0;/~second check of the semaphore value~redundant~the backend wait_word already refuses any semaphore value other than DONE (6), so the engine fails before this line is reached -ROWS diff --git a/tools/gpu_engine_mutations.sh b/tools/gpu_engine_mutations.sh deleted file mode 100755 index 17b9f582e..000000000 --- a/tools/gpu_engine_mutations.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/sh -# Omega GPU Engine mutation sweep, a thin adapter over tools/mutation_runner.sh. -# For each rule marked MUT: in src/omega_gpu_engine.c the runner copies the -# needed files to a scratch directory, breaks that one protection, rebuilds -# tests/test_omega_gpu_engine.c there and requires it to FAIL. A mutant that does -# not apply, does not build or is not caught fails the sweep (exit nonzero). -# Host only, no device, no physics headers. Shell only (no Python). -# Each mutant and what it guards is listed in docs/numeric/OMEGA_GPU_ENGINE.md -# section 13. Set GPU_ENGINE_MUT_OUT=path.json to also keep the JSON receipt. -set -u -cd "$(dirname "$0")/.." || exit 2 -unset ONLY - -FILE=src/omega_gpu_engine.c -BUILD='gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o .gpu_engine_t tests/test_omega_gpu_engine.c src/omega_gpu_engine.c' - -# name|file|sed expression (applied only to the line carrying MUT:). -# In an expression, & in the replacement is written \& . -ROWS="VALIDATE_SKIPPED|$FILE|s/if (!job || !job_valid(job))/if (0 \\&\\& (!job || !job_valid(job)))/ -VALID_PROGRAM|$FILE|s/return 0;/(void)0;/ -VALID_LAYOUT|$FILE|s/return 0;/(void)0;/ -VALID_COUNT_ZERO|$FILE|s/return 0;/(void)0;/ -VALID_ALIGN|$FILE|s/return 0;/(void)0;/ -VALID_POISON_COUNT|$FILE|s/return 0;/(void)0;/ -VALID_FLAGS|$FILE|s/return 0;/(void)0;/ -VALID_TIMEOUT_MARKER1|$FILE|s/return 0;/(void)0;/ -VALID_TIMEOUT_MARKER2|$FILE|s/return 0;/(void)0;/ -BLOCK_CHECK_SKIPPED|$FILE|s/if (omega_gpu_engine_is_blocked())/if (0)/ -BACKEND_CHECK_SKIPPED|$FILE|s/if (!backend_complete(b))/if (0 \\&\\& !backend_complete(b))/ -OPEN_NOT_TRACKED|$FILE|s/run.opened = 1;/(void)0;/ -ALLOC_NOT_TRACKED|$FILE|s/run.allocated\\[role\\] = 1;/(void)0;/ -CLEANUP_SKIPPED_CHANNEL|$FILE|s/return leave(b, &run, result);/return result->failure;/ -CLEANUP_SKIPPED_ALLOC|$FILE|s/return leave(b, &run, result);/return result->failure;/ -CLEANUP_SKIPPED_COPY_IN|$FILE|s/return leave(b, &run, result);/return result->failure;/ -CLEANUP_SKIPPED_SUBMIT|$FILE|s/return leave(b, &run, result);/return result->failure;/ -FREE_UNALLOCATED|$FILE|s/if (!run->allocated\\[role\\]) continue;/(void)0;/ -FREE_SKIPPED|$FILE|s/rc = b->free_buf(b->ctx, role);/rc = 0;/ -CLOSE_SKIPPED|$FILE|s/rc = b->close(b->ctx);/rc = 0;/ -CLEANUP_OVERWRITES_FIRST|$FILE|s/if (result->failure == OMEGA_GPU_ENGINE_OK)/if (1)/ -CLEANUP_FLAG_NOT_SET|$FILE|s/result->cleanup_failed = 1;/(void)0;/ -POISON_FILL_SKIPPED|$FILE|s/ERRNO_CLEAR(); rc = b->fill_poison.*/rc = 0; e = 0;/ -STATE_PREPARED_SKIPPED|$FILE|s/result->last_state = OMEGA_GPU_ENGINE_STATE_PREPARED;/(void)0;/ -STATE_SUBMITTED_SKIPPED|$FILE|s/result->last_state = OMEGA_GPU_ENGINE_STATE_SUBMITTED;/(void)0;/ -STATE_GPU_COMPLETE_SKIPPED|$FILE|s/result->last_state = OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE;/(void)0;/ -STATE_OUTPUT_VISIBLE_SKIPPED|$FILE|s/result->last_state = OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE;/(void)0;/ -STATE_OUTPUT_PRODUCED_SKIPPED|$FILE|s/result->last_state = OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED;/(void)0;/ -STATE_SUCCESS_SKIPPED|$FILE|s/if (rc == OMEGA_GPU_ENGINE_OK) result->last_state = OMEGA_GPU_ENGINE_STATE_SUCCESS;/(void)0;/ -SUCCESS_AFTER_CLEANUP_FAIL|$FILE|s/if (rc == OMEGA_GPU_ENGINE_OK) result/if (1) result/ -MARKER1_WAIT_SKIPPED|$FILE|s/rc = timed_call(.*\$/rc = 0;/ -MARKER1_TIMEOUT_WRONG|$FILE|s/job->timeouts.marker_ms, &waited/job->timeouts.release_semaphore_ms, \\&waited/ -MARKER1_RESULT_IGNORED|$FILE|s/if (rc != 0) return uncertain/if (0 \\&\\& rc != 0) return uncertain/ -UNCERTAIN_FREES_MARKER1|$FILE|s/return uncertain(\\(.*\\));/{ (void)uncertain(\\1); return leave(b, \\&run, result); }/ -MARKER2_WAIT_SKIPPED|$FILE|s/if (!(job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3)) {/if (0) {/ -C3_FLAG_IGNORED|$FILE|s/if (!(job->flags & OMEGA_GPU_ENGINE_FLAG_NO_C3)) {/if (1) {/ -MARKER2_RESULT_IGNORED|$FILE|s/if (rc != 0) return uncertain/if (0 \\&\\& rc != 0) return uncertain/ -UNCERTAIN_FREES_MARKER2|$FILE|s/return uncertain(\\(.*\\));/{ (void)uncertain(\\1); return leave(b, \\&run, result); }/ -RELEASE_WAIT_SKIPPED|$FILE|s/rc = timed_call(.*\$/rc = 0;/ -RELEASE_RESULT_IGNORED|$FILE|s/if (rc != 0) return uncertain/if (0 \\&\\& rc != 0) return uncertain/ -UNCERTAIN_FREES_RELEASE|$FILE|s/return uncertain(\\(.*\\));/{ (void)uncertain(\\1); return leave(b, \\&run, result); }/ -BARRIER_SKIPPED|$FILE|s/rc = timed_call(.*\$/rc = 0;/ -BARRIER_RESULT_IGNORED|$FILE|s/if (rc != 0) {/if (0 \\&\\& rc != 0) {/ -RETAINED_FLAG_NOT_SET|$FILE|s/result->retained = 1;/(void)0;/ -NO_BLOCK|$FILE|s/atomic_store(&g_blocked, 1);/(void)0;/ -WAITED_NOT_A_DIFFERENCE|$FILE|s/t1 >= t0 ? t1 - t0 : 0u;/t1 >= t0 ? t1 : 0u;/ -POISON_INDEX_FIXED|$FILE|s/w == job->poison\\[i\\]/w == job->poison[0]/ -UNCHANGED_COUNT_SATURATES|$FILE|s/unchanged++;/unchanged = 1u;/ -UNCHANGED_CHECK_SKIPPED|$FILE|s/if (unchanged != 0u) {/if (0) {/" - -OUT=${GPU_ENGINE_MUT_OUT:-} -set -- -k marker -m - -t ./.gpu_engine_t -b "$BUILD" \ - -c "src/omega_gpu_engine.c src/omega_gpu_engine.h tests/test_omega_gpu_engine.c" \ - -f '\[FAIL\]' -B -[ -z "$OUT" ] || set -- "$@" -o "$OUT" -printf '%s\n' "$ROWS" | tools/mutation_runner.sh "$@"